diff --git a/.gitattributes b/.gitattributes
index a6344aac8c09253b3b630fb776ae94478aa0275b..a09db2ea4d1bd1fc1c09f6fca45e8e4054953535 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.zst filter=lfs diff=lfs merge=lfs -text
*tfevents* filter=lfs diff=lfs merge=lfs -text
+tokenizer.json filter=lfs diff=lfs merge=lfs -text
+model.safetensors.index.json filter=lfs diff=lfs merge=lfs -text
diff --git a/__init__.py b/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fef8d30e777e13534cecaa58eb361f6de857247b
--- /dev/null
+++ b/__init__.py
@@ -0,0 +1,4 @@
+from .configuration_afmoe import AfmoeConfig
+from .modeling_afmoe import AfmoeForCausalLM
+
+__all__ = ["AfmoeConfig", "AfmoeForCausalLM"]
diff --git a/chat_template.jinja b/chat_template.jinja
new file mode 100644
index 0000000000000000000000000000000000000000..5b93512b2ca66f53ececeff7a4661df3a4084118
--- /dev/null
+++ b/chat_template.jinja
@@ -0,0 +1,159 @@
+<|begin_of_text|>{%- macro render_extra_keys(json_dict, handled_keys) -%}
+ {%- if json_dict is mapping %}
+ {%- for json_key in json_dict if json_key not in handled_keys %}
+ {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %}
+ {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '' ~ json_key ~ '>' }}
+ {%- else %}
+ {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '' ~ json_key ~ '>' }}
+ {%- endif %}
+ {%- endfor %}
+ {%- endif %}
+{%- endmacro -%}
+
+{%- macro render_tool_call(raw_tool_call) -%}
+ {%- if raw_tool_call.function is defined and raw_tool_call.function is mapping %}
+ {%- set tool_call = raw_tool_call.function %}
+ {%- else %}
+ {%- set tool_call = raw_tool_call %}
+ {%- endif %}
+ {{- '\n\n' }}
+ {%- if tool_call.arguments is defined and tool_call.arguments is mapping %}
+ {%- for args_name, args_value in tool_call.arguments.items() %}
+ {{- '\n' }}
+ {%- if args_value is mapping or (args_value is sequence and args_value is not string) %}
+ {{- args_value | tojson | safe }}
+ {%- else %}
+ {{- args_value | string }}
+ {%- endif %}
+ {{- '\n\n' }}
+ {%- endfor %}
+ {%- endif %}
+ {{- '\n' }}
+{%- endmacro -%}
+
+{%- set system_message = none %}
+{%- if messages and messages[0]["role"] == "system" %}
+ {%- set system_message = messages[0]["content"] %}
+ {%- set loop_messages = messages[1:] %}
+{%- else %}
+ {%- set loop_messages = messages %}
+{%- endif %}
+
+{%- if not tools is defined %}
+ {%- set tools = [] %}
+{%- endif %}
+{%- set has_tools = tools is iterable and tools is not string and tools | length > 0 %}
+
+{%- if system_message is not none or has_tools %}
+ {{- '<|im_start|>system\n' }}
+ {%- if system_message is not none %}
+ {{- system_message }}
+ {%- else %}
+ {{- "You are Trinity Large, a helpful assistant developed by Arcee AI, that can interact with a computer to solve tasks." }}
+ {%- endif %}
+ {%- if has_tools %}
+ {{- "\n\n# Tools\n\nYou have access to the following functions:\n\n" }}
+ {%- for tool in tools %}
+ {%- if tool.function is defined and tool.function is mapping %}
+ {%- set tool = tool.function %}
+ {%- endif %}
+ {{- '\n\n' ~ (tool.name | default('') | string) ~ '' }}
+ {%- if tool.description is defined and tool.description is not none %}
+ {{- '\n' ~ (tool.description | string | trim) ~ '' }}
+ {%- endif %}
+ {{- '\n' }}
+ {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %}
+ {%- for param_name, param_fields in tool.parameters.properties.items() %}
+ {{- '\n\n' ~ (param_name | string) ~ '' }}
+ {%- if param_fields is mapping and param_fields.type is defined and param_fields.type is not none %}
+ {{- '\n' ~ (param_fields.type | string) ~ '' }}
+ {%- endif %}
+ {%- if param_fields is mapping and param_fields.description is defined and param_fields.description is not none %}
+ {{- '\n' ~ (param_fields.description | string | trim) ~ '' }}
+ {%- endif %}
+ {%- if param_fields is mapping %}
+ {%- set handled_keys = ['name', 'type', 'description'] %}
+ {{- render_extra_keys(param_fields, handled_keys) }}
+ {%- endif %}
+ {{- '\n' }}
+ {%- endfor %}
+ {%- endif %}
+ {%- if tool.parameters is defined %}
+ {%- set handled_keys = ['type', 'properties'] %}
+ {{- render_extra_keys(tool.parameters, handled_keys) }}
+ {%- endif %}
+ {{- '\n' }}
+ {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %}
+ {{- render_extra_keys(tool, handled_keys) }}
+ {{- '\n' }}
+ {%- endfor %}
+ {{- "\n" }}
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within 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' }}
+ {%- endif %}
+ {{- '<|im_end|>\n' }}
+{%- endif %}
+
+{%- for message in loop_messages %}
+ {%- set role = message.role | default('') %}
+ {%- if role == "assistant" %}
+ {%- set content_str = '' if message.content is none else (message.content | string) %}
+ {%- set trimmed_content = content_str | trim %}
+
+ {%- set has_reasoning_content = message.reasoning_content is defined %}
+ {%- set has_reasoning = has_reasoning_content or (message.reasoning is defined) %}
+
+ {%- if has_reasoning_content %}
+ {%- set reasoning_value = message.reasoning_content %}
+ {%- elif message.reasoning is defined %}
+ {%- set reasoning_value = message.reasoning %}
+ {%- else %}
+ {%- set reasoning_value = none %}
+ {%- endif %}
+
+ {%- set has_tool_calls = message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls is not string and message.tool_calls | length > 0 %}
+
+ {{- '<|im_start|>assistant\n' }}
+ {%- if has_reasoning %}
+ {%- if reasoning_value %}
+ {{- '' + (reasoning_value | string | trim) + '' }}
+ {%- else %}
+ {{- '' }}
+ {%- endif %}
+ {%- if trimmed_content %}
+ {{- '\n' + trimmed_content }}
+ {%- endif %}
+ {%- elif has_tool_calls %}
+ {%- if trimmed_content %}
+ {{- trimmed_content }}
+ {%- endif %}
+ {%- else %}
+ {{- content_str }}
+ {%- endif %}
+
+ {%- if has_tool_calls %}
+ {%- for tool_call in message.tool_calls %}
+ {%- set separator = '\n' if ((loop.first and (has_reasoning or trimmed_content)) or (not loop.first)) else '' -%}
+ {{- separator + render_tool_call(tool_call) }}
+ {%- endfor %}
+ {%- endif %}
+ {{- '<|im_end|>\n' }}
+ {%- elif role == "tool" or role == "observation" or role == "function" %}
+ {%- if loop.first or loop.previtem.role not in ["tool", "observation", "function"] %}
+ {{- '<|im_start|>user\n' }}
+ {%- endif %}
+ {{- '\n' }}
+ {{- '' if message.content is none else (message.content | string) }}
+ {{- '\n\n' }}
+ {%- if loop.last or loop.nextitem.role not in ["tool", "observation", "function"] %}
+ {{- '<|im_end|>\n' }}
+ {%- endif %}
+ {%- else %}
+ {{- '<|im_start|>' + (role | string) }}
+ {{- '\n' + ('' if message.content is none else (message.content | string)) }}
+ {{- '<|im_end|>\n' }}
+ {%- endif %}
+{%- endfor %}
+
+{%- if add_generation_prompt %}
+ {{- '<|im_start|>assistant\n' }}
+{%- endif %}
\ No newline at end of file
diff --git a/config.json b/config.json
new file mode 100644
index 0000000000000000000000000000000000000000..7c3ed65eebfa7c377a2a53e4147881c0f4b9fe5a
--- /dev/null
+++ b/config.json
@@ -0,0 +1,512 @@
+{
+ "architectures": [
+ "AfmoeForCausalLM"
+ ],
+ "attention_dropout": 0.0,
+ "auto_map": {
+ "AutoConfig": "configuration_afmoe.AfmoeConfig",
+ "AutoModel": "modeling_afmoe.AfmoeModel",
+ "AutoModelForCausalLM": "modeling_afmoe.AfmoeForCausalLM"
+ },
+ "dtype": "bfloat16",
+ "global_attn_every_n_layers": 4,
+ "head_dim": 128,
+ "hidden_act": "silu",
+ "hidden_size": 3072,
+ "initializer_range": 0.02,
+ "intermediate_size": 12288,
+ "layer_types": [
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "sliding_attention",
+ "full_attention"
+ ],
+ "load_balance_coeff": 5e-05,
+ "max_position_embeddings": 262144,
+ "model_type": "afmoe",
+ "moe_intermediate_size": 3072,
+ "mup_enabled": true,
+ "n_group": 1,
+ "num_attention_heads": 48,
+ "num_dense_layers": 6,
+ "num_expert_groups": 1,
+ "num_experts": 256,
+ "num_experts_per_tok": 4,
+ "num_hidden_layers": 60,
+ "num_key_value_heads": 8,
+ "num_limited_groups": 1,
+ "num_shared_experts": 1,
+ "quantization_config": {
+ "config_groups": {
+ "group_0": {
+ "format": "nvfp4-pack-quantized",
+ "input_activations": {
+ "actorder": null,
+ "block_structure": null,
+ "dynamic": "local",
+ "group_size": 16,
+ "num_bits": 4,
+ "observer": "static_minmax",
+ "observer_kwargs": {},
+ "scale_dtype": "torch.float8_e4m3fn",
+ "strategy": "tensor_group",
+ "symmetric": true,
+ "type": "float",
+ "zp_dtype": null
+ },
+ "output_activations": null,
+ "targets": [
+ "Linear"
+ ],
+ "weights": {
+ "actorder": null,
+ "block_structure": null,
+ "dynamic": false,
+ "group_size": 16,
+ "num_bits": 4,
+ "observer": "memoryless_minmax",
+ "observer_kwargs": {},
+ "scale_dtype": "torch.float8_e4m3fn",
+ "strategy": "tensor_group",
+ "symmetric": true,
+ "type": "float",
+ "zp_dtype": null
+ }
+ }
+ },
+ "format": "nvfp4-pack-quantized",
+ "global_compression_ratio": null,
+ "ignore": [
+ "model.layers.0.self_attn.q_proj",
+ "model.layers.0.self_attn.k_proj",
+ "model.layers.0.self_attn.v_proj",
+ "model.layers.0.self_attn.o_proj",
+ "model.layers.0.self_attn.gate_proj",
+ "model.layers.1.self_attn.q_proj",
+ "model.layers.1.self_attn.k_proj",
+ "model.layers.1.self_attn.v_proj",
+ "model.layers.1.self_attn.o_proj",
+ "model.layers.1.self_attn.gate_proj",
+ "model.layers.2.self_attn.q_proj",
+ "model.layers.2.self_attn.k_proj",
+ "model.layers.2.self_attn.v_proj",
+ "model.layers.2.self_attn.o_proj",
+ "model.layers.2.self_attn.gate_proj",
+ "model.layers.3.self_attn.q_proj",
+ "model.layers.3.self_attn.k_proj",
+ "model.layers.3.self_attn.v_proj",
+ "model.layers.3.self_attn.o_proj",
+ "model.layers.3.self_attn.gate_proj",
+ "model.layers.4.self_attn.q_proj",
+ "model.layers.4.self_attn.k_proj",
+ "model.layers.4.self_attn.v_proj",
+ "model.layers.4.self_attn.o_proj",
+ "model.layers.4.self_attn.gate_proj",
+ "model.layers.5.self_attn.q_proj",
+ "model.layers.5.self_attn.k_proj",
+ "model.layers.5.self_attn.v_proj",
+ "model.layers.5.self_attn.o_proj",
+ "model.layers.5.self_attn.gate_proj",
+ "model.layers.6.self_attn.q_proj",
+ "model.layers.6.self_attn.k_proj",
+ "model.layers.6.self_attn.v_proj",
+ "model.layers.6.self_attn.o_proj",
+ "model.layers.6.self_attn.gate_proj",
+ "model.layers.6.mlp.router.gate",
+ "model.layers.7.self_attn.q_proj",
+ "model.layers.7.self_attn.k_proj",
+ "model.layers.7.self_attn.v_proj",
+ "model.layers.7.self_attn.o_proj",
+ "model.layers.7.self_attn.gate_proj",
+ "model.layers.7.mlp.router.gate",
+ "model.layers.8.self_attn.q_proj",
+ "model.layers.8.self_attn.k_proj",
+ "model.layers.8.self_attn.v_proj",
+ "model.layers.8.self_attn.o_proj",
+ "model.layers.8.self_attn.gate_proj",
+ "model.layers.8.mlp.router.gate",
+ "model.layers.9.self_attn.q_proj",
+ "model.layers.9.self_attn.k_proj",
+ "model.layers.9.self_attn.v_proj",
+ "model.layers.9.self_attn.o_proj",
+ "model.layers.9.self_attn.gate_proj",
+ "model.layers.9.mlp.router.gate",
+ "model.layers.10.self_attn.q_proj",
+ "model.layers.10.self_attn.k_proj",
+ "model.layers.10.self_attn.v_proj",
+ "model.layers.10.self_attn.o_proj",
+ "model.layers.10.self_attn.gate_proj",
+ "model.layers.10.mlp.router.gate",
+ "model.layers.11.self_attn.q_proj",
+ "model.layers.11.self_attn.k_proj",
+ "model.layers.11.self_attn.v_proj",
+ "model.layers.11.self_attn.o_proj",
+ "model.layers.11.self_attn.gate_proj",
+ "model.layers.11.mlp.router.gate",
+ "model.layers.12.self_attn.q_proj",
+ "model.layers.12.self_attn.k_proj",
+ "model.layers.12.self_attn.v_proj",
+ "model.layers.12.self_attn.o_proj",
+ "model.layers.12.self_attn.gate_proj",
+ "model.layers.12.mlp.router.gate",
+ "model.layers.13.self_attn.q_proj",
+ "model.layers.13.self_attn.k_proj",
+ "model.layers.13.self_attn.v_proj",
+ "model.layers.13.self_attn.o_proj",
+ "model.layers.13.self_attn.gate_proj",
+ "model.layers.13.mlp.router.gate",
+ "model.layers.14.self_attn.q_proj",
+ "model.layers.14.self_attn.k_proj",
+ "model.layers.14.self_attn.v_proj",
+ "model.layers.14.self_attn.o_proj",
+ "model.layers.14.self_attn.gate_proj",
+ "model.layers.14.mlp.router.gate",
+ "model.layers.15.self_attn.q_proj",
+ "model.layers.15.self_attn.k_proj",
+ "model.layers.15.self_attn.v_proj",
+ "model.layers.15.self_attn.o_proj",
+ "model.layers.15.self_attn.gate_proj",
+ "model.layers.15.mlp.router.gate",
+ "model.layers.16.self_attn.q_proj",
+ "model.layers.16.self_attn.k_proj",
+ "model.layers.16.self_attn.v_proj",
+ "model.layers.16.self_attn.o_proj",
+ "model.layers.16.self_attn.gate_proj",
+ "model.layers.16.mlp.router.gate",
+ "model.layers.17.self_attn.q_proj",
+ "model.layers.17.self_attn.k_proj",
+ "model.layers.17.self_attn.v_proj",
+ "model.layers.17.self_attn.o_proj",
+ "model.layers.17.self_attn.gate_proj",
+ "model.layers.17.mlp.router.gate",
+ "model.layers.18.self_attn.q_proj",
+ "model.layers.18.self_attn.k_proj",
+ "model.layers.18.self_attn.v_proj",
+ "model.layers.18.self_attn.o_proj",
+ "model.layers.18.self_attn.gate_proj",
+ "model.layers.18.mlp.router.gate",
+ "model.layers.19.self_attn.q_proj",
+ "model.layers.19.self_attn.k_proj",
+ "model.layers.19.self_attn.v_proj",
+ "model.layers.19.self_attn.o_proj",
+ "model.layers.19.self_attn.gate_proj",
+ "model.layers.19.mlp.router.gate",
+ "model.layers.20.self_attn.q_proj",
+ "model.layers.20.self_attn.k_proj",
+ "model.layers.20.self_attn.v_proj",
+ "model.layers.20.self_attn.o_proj",
+ "model.layers.20.self_attn.gate_proj",
+ "model.layers.20.mlp.router.gate",
+ "model.layers.21.self_attn.q_proj",
+ "model.layers.21.self_attn.k_proj",
+ "model.layers.21.self_attn.v_proj",
+ "model.layers.21.self_attn.o_proj",
+ "model.layers.21.self_attn.gate_proj",
+ "model.layers.21.mlp.router.gate",
+ "model.layers.22.self_attn.q_proj",
+ "model.layers.22.self_attn.k_proj",
+ "model.layers.22.self_attn.v_proj",
+ "model.layers.22.self_attn.o_proj",
+ "model.layers.22.self_attn.gate_proj",
+ "model.layers.22.mlp.router.gate",
+ "model.layers.23.self_attn.q_proj",
+ "model.layers.23.self_attn.k_proj",
+ "model.layers.23.self_attn.v_proj",
+ "model.layers.23.self_attn.o_proj",
+ "model.layers.23.self_attn.gate_proj",
+ "model.layers.23.mlp.router.gate",
+ "model.layers.24.self_attn.q_proj",
+ "model.layers.24.self_attn.k_proj",
+ "model.layers.24.self_attn.v_proj",
+ "model.layers.24.self_attn.o_proj",
+ "model.layers.24.self_attn.gate_proj",
+ "model.layers.24.mlp.router.gate",
+ "model.layers.25.self_attn.q_proj",
+ "model.layers.25.self_attn.k_proj",
+ "model.layers.25.self_attn.v_proj",
+ "model.layers.25.self_attn.o_proj",
+ "model.layers.25.self_attn.gate_proj",
+ "model.layers.25.mlp.router.gate",
+ "model.layers.26.self_attn.q_proj",
+ "model.layers.26.self_attn.k_proj",
+ "model.layers.26.self_attn.v_proj",
+ "model.layers.26.self_attn.o_proj",
+ "model.layers.26.self_attn.gate_proj",
+ "model.layers.26.mlp.router.gate",
+ "model.layers.27.self_attn.q_proj",
+ "model.layers.27.self_attn.k_proj",
+ "model.layers.27.self_attn.v_proj",
+ "model.layers.27.self_attn.o_proj",
+ "model.layers.27.self_attn.gate_proj",
+ "model.layers.27.mlp.router.gate",
+ "model.layers.28.self_attn.q_proj",
+ "model.layers.28.self_attn.k_proj",
+ "model.layers.28.self_attn.v_proj",
+ "model.layers.28.self_attn.o_proj",
+ "model.layers.28.self_attn.gate_proj",
+ "model.layers.28.mlp.router.gate",
+ "model.layers.29.self_attn.q_proj",
+ "model.layers.29.self_attn.k_proj",
+ "model.layers.29.self_attn.v_proj",
+ "model.layers.29.self_attn.o_proj",
+ "model.layers.29.self_attn.gate_proj",
+ "model.layers.29.mlp.router.gate",
+ "model.layers.30.self_attn.q_proj",
+ "model.layers.30.self_attn.k_proj",
+ "model.layers.30.self_attn.v_proj",
+ "model.layers.30.self_attn.o_proj",
+ "model.layers.30.self_attn.gate_proj",
+ "model.layers.30.mlp.router.gate",
+ "model.layers.31.self_attn.q_proj",
+ "model.layers.31.self_attn.k_proj",
+ "model.layers.31.self_attn.v_proj",
+ "model.layers.31.self_attn.o_proj",
+ "model.layers.31.self_attn.gate_proj",
+ "model.layers.31.mlp.router.gate",
+ "model.layers.32.self_attn.q_proj",
+ "model.layers.32.self_attn.k_proj",
+ "model.layers.32.self_attn.v_proj",
+ "model.layers.32.self_attn.o_proj",
+ "model.layers.32.self_attn.gate_proj",
+ "model.layers.32.mlp.router.gate",
+ "model.layers.33.self_attn.q_proj",
+ "model.layers.33.self_attn.k_proj",
+ "model.layers.33.self_attn.v_proj",
+ "model.layers.33.self_attn.o_proj",
+ "model.layers.33.self_attn.gate_proj",
+ "model.layers.33.mlp.router.gate",
+ "model.layers.34.self_attn.q_proj",
+ "model.layers.34.self_attn.k_proj",
+ "model.layers.34.self_attn.v_proj",
+ "model.layers.34.self_attn.o_proj",
+ "model.layers.34.self_attn.gate_proj",
+ "model.layers.34.mlp.router.gate",
+ "model.layers.35.self_attn.q_proj",
+ "model.layers.35.self_attn.k_proj",
+ "model.layers.35.self_attn.v_proj",
+ "model.layers.35.self_attn.o_proj",
+ "model.layers.35.self_attn.gate_proj",
+ "model.layers.35.mlp.router.gate",
+ "model.layers.36.self_attn.q_proj",
+ "model.layers.36.self_attn.k_proj",
+ "model.layers.36.self_attn.v_proj",
+ "model.layers.36.self_attn.o_proj",
+ "model.layers.36.self_attn.gate_proj",
+ "model.layers.36.mlp.router.gate",
+ "model.layers.37.self_attn.q_proj",
+ "model.layers.37.self_attn.k_proj",
+ "model.layers.37.self_attn.v_proj",
+ "model.layers.37.self_attn.o_proj",
+ "model.layers.37.self_attn.gate_proj",
+ "model.layers.37.mlp.router.gate",
+ "model.layers.38.self_attn.q_proj",
+ "model.layers.38.self_attn.k_proj",
+ "model.layers.38.self_attn.v_proj",
+ "model.layers.38.self_attn.o_proj",
+ "model.layers.38.self_attn.gate_proj",
+ "model.layers.38.mlp.router.gate",
+ "model.layers.39.self_attn.q_proj",
+ "model.layers.39.self_attn.k_proj",
+ "model.layers.39.self_attn.v_proj",
+ "model.layers.39.self_attn.o_proj",
+ "model.layers.39.self_attn.gate_proj",
+ "model.layers.39.mlp.router.gate",
+ "model.layers.40.self_attn.q_proj",
+ "model.layers.40.self_attn.k_proj",
+ "model.layers.40.self_attn.v_proj",
+ "model.layers.40.self_attn.o_proj",
+ "model.layers.40.self_attn.gate_proj",
+ "model.layers.40.mlp.router.gate",
+ "model.layers.41.self_attn.q_proj",
+ "model.layers.41.self_attn.k_proj",
+ "model.layers.41.self_attn.v_proj",
+ "model.layers.41.self_attn.o_proj",
+ "model.layers.41.self_attn.gate_proj",
+ "model.layers.41.mlp.router.gate",
+ "model.layers.42.self_attn.q_proj",
+ "model.layers.42.self_attn.k_proj",
+ "model.layers.42.self_attn.v_proj",
+ "model.layers.42.self_attn.o_proj",
+ "model.layers.42.self_attn.gate_proj",
+ "model.layers.42.mlp.router.gate",
+ "model.layers.43.self_attn.q_proj",
+ "model.layers.43.self_attn.k_proj",
+ "model.layers.43.self_attn.v_proj",
+ "model.layers.43.self_attn.o_proj",
+ "model.layers.43.self_attn.gate_proj",
+ "model.layers.43.mlp.router.gate",
+ "model.layers.44.self_attn.q_proj",
+ "model.layers.44.self_attn.k_proj",
+ "model.layers.44.self_attn.v_proj",
+ "model.layers.44.self_attn.o_proj",
+ "model.layers.44.self_attn.gate_proj",
+ "model.layers.44.mlp.router.gate",
+ "model.layers.45.self_attn.q_proj",
+ "model.layers.45.self_attn.k_proj",
+ "model.layers.45.self_attn.v_proj",
+ "model.layers.45.self_attn.o_proj",
+ "model.layers.45.self_attn.gate_proj",
+ "model.layers.45.mlp.router.gate",
+ "model.layers.46.self_attn.q_proj",
+ "model.layers.46.self_attn.k_proj",
+ "model.layers.46.self_attn.v_proj",
+ "model.layers.46.self_attn.o_proj",
+ "model.layers.46.self_attn.gate_proj",
+ "model.layers.46.mlp.router.gate",
+ "model.layers.47.self_attn.q_proj",
+ "model.layers.47.self_attn.k_proj",
+ "model.layers.47.self_attn.v_proj",
+ "model.layers.47.self_attn.o_proj",
+ "model.layers.47.self_attn.gate_proj",
+ "model.layers.47.mlp.router.gate",
+ "model.layers.48.self_attn.q_proj",
+ "model.layers.48.self_attn.k_proj",
+ "model.layers.48.self_attn.v_proj",
+ "model.layers.48.self_attn.o_proj",
+ "model.layers.48.self_attn.gate_proj",
+ "model.layers.48.mlp.router.gate",
+ "model.layers.49.self_attn.q_proj",
+ "model.layers.49.self_attn.k_proj",
+ "model.layers.49.self_attn.v_proj",
+ "model.layers.49.self_attn.o_proj",
+ "model.layers.49.self_attn.gate_proj",
+ "model.layers.49.mlp.router.gate",
+ "model.layers.50.self_attn.q_proj",
+ "model.layers.50.self_attn.k_proj",
+ "model.layers.50.self_attn.v_proj",
+ "model.layers.50.self_attn.o_proj",
+ "model.layers.50.self_attn.gate_proj",
+ "model.layers.50.mlp.router.gate",
+ "model.layers.51.self_attn.q_proj",
+ "model.layers.51.self_attn.k_proj",
+ "model.layers.51.self_attn.v_proj",
+ "model.layers.51.self_attn.o_proj",
+ "model.layers.51.self_attn.gate_proj",
+ "model.layers.51.mlp.router.gate",
+ "model.layers.52.self_attn.q_proj",
+ "model.layers.52.self_attn.k_proj",
+ "model.layers.52.self_attn.v_proj",
+ "model.layers.52.self_attn.o_proj",
+ "model.layers.52.self_attn.gate_proj",
+ "model.layers.52.mlp.router.gate",
+ "model.layers.53.self_attn.q_proj",
+ "model.layers.53.self_attn.k_proj",
+ "model.layers.53.self_attn.v_proj",
+ "model.layers.53.self_attn.o_proj",
+ "model.layers.53.self_attn.gate_proj",
+ "model.layers.53.mlp.router.gate",
+ "model.layers.54.self_attn.q_proj",
+ "model.layers.54.self_attn.k_proj",
+ "model.layers.54.self_attn.v_proj",
+ "model.layers.54.self_attn.o_proj",
+ "model.layers.54.self_attn.gate_proj",
+ "model.layers.54.mlp.router.gate",
+ "model.layers.55.self_attn.q_proj",
+ "model.layers.55.self_attn.k_proj",
+ "model.layers.55.self_attn.v_proj",
+ "model.layers.55.self_attn.o_proj",
+ "model.layers.55.self_attn.gate_proj",
+ "model.layers.55.mlp.router.gate",
+ "model.layers.56.self_attn.q_proj",
+ "model.layers.56.self_attn.k_proj",
+ "model.layers.56.self_attn.v_proj",
+ "model.layers.56.self_attn.o_proj",
+ "model.layers.56.self_attn.gate_proj",
+ "model.layers.56.mlp.router.gate",
+ "model.layers.57.self_attn.q_proj",
+ "model.layers.57.self_attn.k_proj",
+ "model.layers.57.self_attn.v_proj",
+ "model.layers.57.self_attn.o_proj",
+ "model.layers.57.self_attn.gate_proj",
+ "model.layers.57.mlp.router.gate",
+ "model.layers.58.self_attn.q_proj",
+ "model.layers.58.self_attn.k_proj",
+ "model.layers.58.self_attn.v_proj",
+ "model.layers.58.self_attn.o_proj",
+ "model.layers.58.self_attn.gate_proj",
+ "model.layers.58.mlp.router.gate",
+ "model.layers.59.self_attn.q_proj",
+ "model.layers.59.self_attn.k_proj",
+ "model.layers.59.self_attn.v_proj",
+ "model.layers.59.self_attn.o_proj",
+ "model.layers.59.self_attn.gate_proj",
+ "model.layers.59.mlp.router.gate",
+ "lm_head"
+ ],
+ "kv_cache_scheme": null,
+ "quant_method": "compressed-tensors",
+ "quantization_status": "compressed",
+ "sparsity_config": {},
+ "transform_config": {},
+ "version": "0.14.1.a20260326"
+ },
+ "rms_norm_eps": 1e-05,
+ "rope_scaling": null,
+ "rope_theta": 10000,
+ "route_norm": true,
+ "route_scale": 2.448,
+ "score_func": "sigmoid",
+ "sliding_window": 4096,
+ "tie_word_embeddings": false,
+ "topk_group": 1,
+ "transformers_version": "4.57.6",
+ "use_cache": true,
+ "use_grouped_mm": true,
+ "vocab_size": 200192
+}
\ No newline at end of file
diff --git a/configuration_afmoe.py b/configuration_afmoe.py
new file mode 100644
index 0000000000000000000000000000000000000000..9efecdd517e8e6168f46ebecb3d282bdea34c5dc
--- /dev/null
+++ b/configuration_afmoe.py
@@ -0,0 +1,133 @@
+# coding=utf-8
+# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from transformers.configuration_utils import PretrainedConfig
+from transformers.modeling_rope_utils import rope_config_validation
+from transformers.configuration_utils import layer_type_validation
+from transformers.utils import logging
+
+logger = logging.get_logger(__name__)
+
+class AfmoeConfig(PretrainedConfig):
+ """
+ n_group (`int`, *optional*, defaults to 1):
+ Number of groups for routed experts.
+ topk_group (`int`, *optional*, defaults to 1):
+ Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
+ """
+ model_type = "afmoe"
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+
+ def __init__(
+ self,
+ num_hidden_layers: int = 32,
+ vocab_size: int = 200192,
+ hidden_size: int = 2048,
+ intermediate_size: int = 6144,
+ moe_intermediate_size=1408,
+ num_dense_layers=1,
+ num_attention_heads=16,
+ num_key_value_heads=None,
+ head_dim=128,
+ hidden_act="silu",
+ max_position_embeddings=16384,
+ initializer_range=0.02,
+ rms_norm_eps=1e-5,
+ use_cache=True,
+ tie_word_embeddings=False,
+ rope_theta=10000.0,
+ rope_scaling=None,
+ num_experts=64,
+ num_experts_per_tok=6,
+ num_shared_experts=2,
+ num_expert_groups=1,
+ num_limited_groups=1,
+ score_func="sigmoid",
+ route_norm=True,
+ route_scale=1.0,
+ global_attn_every_n_layers=4,
+ sliding_window=1024,
+ mup_enabled=False,
+ layer_types=None,
+ attention_dropout: float = 0.0,
+ n_group: int = 1,
+ topk_group: int = 1,
+ **kwargs,
+ ):
+ self.vocab_size = vocab_size
+ self.max_position_embeddings = max_position_embeddings
+ self.hidden_size = hidden_size
+ self.intermediate_size = intermediate_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_dense_layers = num_dense_layers
+ self.num_attention_heads = num_attention_heads
+ self.head_dim = head_dim
+ self.hidden_act = hidden_act
+ self.initializer_range = initializer_range
+ self.rms_norm_eps = rms_norm_eps
+ self.use_cache = use_cache
+ self.rope_theta = rope_theta
+ self.rope_scaling = rope_scaling
+
+
+ # MoE specific
+ self.moe_intermediate_size = moe_intermediate_size
+ self.num_experts_per_tok = num_experts_per_tok
+ self.n_group = n_group
+ self.topk_group = topk_group
+ self.num_experts = num_experts
+ self.num_shared_experts = num_shared_experts
+ self.num_expert_groups = num_expert_groups
+ self.num_limited_groups = num_limited_groups
+ self.score_func = score_func
+ self.route_norm = route_norm
+ self.route_scale = route_scale
+
+
+ # Attention specific
+ self.attention_dropout = attention_dropout
+ self.global_attn_every_n_layers = global_attn_every_n_layers
+ self.sliding_window = sliding_window
+ self.layer_types = layer_types
+ if self.layer_types is None:
+ self.layer_types = [
+ "sliding_attention" if bool((i + 1) % global_attn_every_n_layers) else "full_attention" for i in range(self.num_hidden_layers)
+ ]
+ layer_type_validation(self.layer_types)
+
+ # muP specific
+ self.mup_enabled = mup_enabled
+
+ if num_key_value_heads is None:
+ num_key_value_heads = num_attention_heads
+
+ self.num_key_value_heads = num_key_value_heads
+
+
+ # Validate rope configs
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
+ rope_config_validation(self)
+
+ super().__init__(
+ tie_word_embeddings=tie_word_embeddings,
+ **kwargs,
+ )
+
+
+__all__ = ["AfmoeConfig"]
diff --git a/generation_config.json b/generation_config.json
new file mode 100644
index 0000000000000000000000000000000000000000..ec2172d2dddacfba7d50b745ee38f248ad989e0e
--- /dev/null
+++ b/generation_config.json
@@ -0,0 +1,10 @@
+{
+ "_from_model_config": true,
+ "bos_token_id": 0,
+ "do_sample": true,
+ "eos_token_id": 3,
+ "pad_token_id": 12,
+ "temperature": 0.8,
+ "top_p": 0.8,
+ "transformers_version": "4.57.6"
+}
diff --git a/model-00001-of-00047.safetensors b/model-00001-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..fc9671dd62d44a5b2f6da93db549dee4e8a56b3b
--- /dev/null
+++ b/model-00001-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:def18a0497fc8b5c53c4cb7f6d296b084cae4e405d5f3f135ffb8eb640b742ca
+size 4999975928
diff --git a/model-00002-of-00047.safetensors b/model-00002-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..b888e526e22e618c69b9c49c263f58b152d16c1d
--- /dev/null
+++ b/model-00002-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:828ef7979cf7239a4d4e34b037bce3a2b984ae83c8ec4c9b5acd625757b721f5
+size 4996296800
diff --git a/model-00003-of-00047.safetensors b/model-00003-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..7d22c55b09de22c53898ca7f03843ba51c18b6be
--- /dev/null
+++ b/model-00003-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d1b07aeb01d86f6aef0f88ca767f28dfafea70cfce95365d25b8d73e02553558
+size 5000425320
diff --git a/model-00004-of-00047.safetensors b/model-00004-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..d09d627660e821e7f73508b313e766c2658e3052
--- /dev/null
+++ b/model-00004-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:cc41fee8c8a7e98b22b7b00ca54f5a5568d06bc32b53fbe926f6d7a855bed88a
+size 4996312816
diff --git a/model-00005-of-00047.safetensors b/model-00005-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..0e5ca508c6c7c8724a8e1dc321b32c2225837db7
--- /dev/null
+++ b/model-00005-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:070cbccee39c95b518352417d402d1e4156087efbb2abe1d1e1feec2e3d61186
+size 5000428416
diff --git a/model-00006-of-00047.safetensors b/model-00006-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..2c6d300cc054098ea2cf35bd2f3c0af8f315359f
--- /dev/null
+++ b/model-00006-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:1d780213a370f4b5c27c9e5628ff5764a41128b13b57c6ac5c23026fb6dc842b
+size 4996300320
diff --git a/model-00007-of-00047.safetensors b/model-00007-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..efd7ed2b390d18b10e8e148c35882966e15000a9
--- /dev/null
+++ b/model-00007-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:b762f0e6051502b75153e1912fd07533c3fa8b8f84e98c892244b6a1a84f9b15
+size 5000429008
diff --git a/model-00008-of-00047.safetensors b/model-00008-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..240a33949c4b0f7e179dde60d788c51ee9a82b87
--- /dev/null
+++ b/model-00008-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c2eab2e0cee9db17c423735f2c4c3e530fadafae62708f2f86e48d547d5b5f51
+size 4996300480
diff --git a/model-00009-of-00047.safetensors b/model-00009-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..93c5a0301a4c43a217aeb82a8cef8635bca47848
--- /dev/null
+++ b/model-00009-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:1c8e2bc499353e84d58bdef7678aef507dc29748552376f476c34968c7419e2f
+size 5000444384
diff --git a/model-00010-of-00047.safetensors b/model-00010-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..e80411bdaf1d68d8bce056bc8a28d314e7e8c853
--- /dev/null
+++ b/model-00010-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:2a7a904bc2e52d5a3eb034884fa36efa60b55c08af43c8ebd27e2bd2fed2e582
+size 4996299896
diff --git a/model-00013-of-00047.safetensors b/model-00013-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..d676357b8a61de400f48552e84aa74c0f18144ee
--- /dev/null
+++ b/model-00013-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:2727bf031c2c192fa593e86ffc75438acf71e998f6c0b4feb5c760991d2dfed3
+size 5000429008
diff --git a/model-00014-of-00047.safetensors b/model-00014-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..f0aac8edeefa9197541fe200154c9502cef7ad93
--- /dev/null
+++ b/model-00014-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:2809026dfeaf460bcbcdb2748cbcefd7279caf7f28fe049e029b6f7c0fa55544
+size 4966998400
diff --git a/model-00015-of-00047.safetensors b/model-00015-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..af1d9952bc41625d48cefd2e4d539e77f8f85d6c
--- /dev/null
+++ b/model-00015-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:b43f5cbcd46fce8c1678ae3b448f0c5d6d2b9638019f9b64ed8af93a7af890e7
+size 4998483128
diff --git a/model-00016-of-00047.safetensors b/model-00016-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..f8fc7a11ac722ba8b5c5600767d4e638b4504330
--- /dev/null
+++ b/model-00016-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:5fe2a17f0b2bd6375dba268fc9c18c5b6749747ce6059c4f51a2fc8ceceeb1e0
+size 5000428416
diff --git a/model-00017-of-00047.safetensors b/model-00017-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..1acf3ef52b863f70cf04cf4705ac5cd7eb964fbd
--- /dev/null
+++ b/model-00017-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a42f3d035a7733dbd1deb35522da1059076b19776cfbb3fa9c37d51f50b657c0
+size 4996300384
diff --git a/model-00018-of-00047.safetensors b/model-00018-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..732826e81f4098b3a640ecf3eab83ef3510011af
--- /dev/null
+++ b/model-00018-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:77287564a008317747b9eed53909f2941ea88e920d79b85eb35175ddde4ecbcf
+size 5000429008
diff --git a/model-00021-of-00047.safetensors b/model-00021-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..4fd4a347a839fcc939613025b1b8ae8fa733daaa
--- /dev/null
+++ b/model-00021-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:9437db53ed6266d59e31a19d4720645cf1be87613a6ec06d9a570b262a81eb4b
+size 4996299896
diff --git a/model-00022-of-00047.safetensors b/model-00022-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..2013a6dd210f6c4068c2e5bd0fdbcab16a16cb9b
--- /dev/null
+++ b/model-00022-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:474c665953d25b3d0e0528ace6cf5d3169ce24b9e94ba862d909f6e610e5d470
+size 5000428656
diff --git a/model-00024-of-00047.safetensors b/model-00024-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..4d12cab36c198232ccd065a2718df4077ae4351f
--- /dev/null
+++ b/model-00024-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:7195ccbc39fecc2eda62cf0efdd454e5e5852a52f6743936ca9b837b66119dd6
+size 5000429008
diff --git a/model-00025-of-00047.safetensors b/model-00025-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..5988b5334f66a05c305402fe630ae65f835b9d22
--- /dev/null
+++ b/model-00025-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:480810ac10f71f9650ebc77a914dae3879e96c43bb1b6b2794fcf89fd11339ad
+size 4996315968
diff --git a/model-00027-of-00047.safetensors b/model-00027-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..15dcb627d2668be1fec90a812a7fdf4f635f2ec3
--- /dev/null
+++ b/model-00027-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:97cced6c56e7d3247e754d3cd1ead9692ef2506141430bb358e7a9cc231bffd7
+size 4996299896
diff --git a/model-00028-of-00047.safetensors b/model-00028-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..508e9e2935a07f42461b24dbf9ded6ae6ebe65ed
--- /dev/null
+++ b/model-00028-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d13fbb8ae9f724b542ea8a4df8e8ff67bae14ff51cb47687590aec007ec55211
+size 5000428992
diff --git a/model-00029-of-00047.safetensors b/model-00029-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..8f3b52a04db88fd84a048a5519d6835f7c74acf9
--- /dev/null
+++ b/model-00029-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:33f5b9c6130b82f0a35ebf9afadd116eb5e629d9d17b2ad7e853e8d605dd908d
+size 4996300480
diff --git a/model-00030-of-00047.safetensors b/model-00030-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..648eb5a689988d1c3913d3df54b232a11605415c
--- /dev/null
+++ b/model-00030-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:357bc4b98298e30ba38e607d0e9c2379f90727942c762cdd7991ec2dd9105fb4
+size 5000429008
diff --git a/model-00031-of-00047.safetensors b/model-00031-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..cf943dd351b13f41c76ae879786150c4b6d06496
--- /dev/null
+++ b/model-00031-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:9694dfa9ecb50906ff25fe3004277efbb2c77f7d02b41c04bd41c66fcfbac0e2
+size 4996315864
diff --git a/model-00032-of-00047.safetensors b/model-00032-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..b1af7d2bbafe258a80af01179bbd58dd3b4b1a47
--- /dev/null
+++ b/model-00032-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:0a3229a2ea673e5b7edc505a81982a4fff4a955e34a65d3bea6fe0e6835fc67e
+size 5000428424
diff --git a/model-00033-of-00047.safetensors b/model-00033-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..8c82893c179f58bcd83345083d173a8f889eaa40
--- /dev/null
+++ b/model-00033-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:8b9136dfda62670c2aaa3416760ca2ed4a6e52c1850b67b69a42be25adae90a9
+size 4996300216
diff --git a/model-00035-of-00047.safetensors b/model-00035-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..51ca73d22664d4ee82a2ecb69759edfc9529614a
--- /dev/null
+++ b/model-00035-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:655d6363656e8bf513823155ed7f52eda9c8806ab02a96c0c146acc793340bdd
+size 4996300480
diff --git a/model-00036-of-00047.safetensors b/model-00036-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..0c95a4df7b764f8d087f16532969b4c47cfc0742
--- /dev/null
+++ b/model-00036-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:092ea495a451e5143e3abee0367c349ed5219f82a720d46e2c0ea3f844312bf0
+size 5000444408
diff --git a/model-00037-of-00047.safetensors b/model-00037-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..a26456cb899cb7795f0965b7c93062009faf2d00
--- /dev/null
+++ b/model-00037-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6d5a0cf1fc975d2c537f86255e7f46f916dc6d3dfb8a68d963d1542ab6f6a667
+size 4996299880
diff --git a/model-00038-of-00047.safetensors b/model-00038-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..7a29fae66f9cea0abcdf5230b1afffa4c09ec3af
--- /dev/null
+++ b/model-00038-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:32979e95d0ed5711b18776ca5bc389b5690192645c492adef5533803fc097b10
+size 5000428496
diff --git a/model-00039-of-00047.safetensors b/model-00039-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..67cc9e95f62abdfbf3c7fc3820deb192814ccbdc
--- /dev/null
+++ b/model-00039-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:75865fd5969e2b37649055fefe5c0385c6392a8aa552a2223615b5324adfa6b4
+size 4996300480
diff --git a/model-00040-of-00047.safetensors b/model-00040-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..46b3f86de0174e8cbfe921104076f689d6eb35b6
--- /dev/null
+++ b/model-00040-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:09ba6edbf10cbb4f46010d79f67fe9f82cbd70b8c6e6caa5fae9c4263725565d
+size 5000429000
diff --git a/model-00041-of-00047.safetensors b/model-00041-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..b6992c7494dbee20e543771b6314851f04732255
--- /dev/null
+++ b/model-00041-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:91162f377e9489a4c41ac502d7fcc74892583c1b8d33bb4fe226e1c8243768b8
+size 4996300480
diff --git a/model-00042-of-00047.safetensors b/model-00042-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..6a61590f457f7752b414eb6831be952190ee3066
--- /dev/null
+++ b/model-00042-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:283882498cb2b009bcca867eeb54269d859501224fc103bcb31005c06226302a
+size 5000444400
diff --git a/model-00043-of-00047.safetensors b/model-00043-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..cde3c966e44b893e5d9bd0303296fa90076261e6
--- /dev/null
+++ b/model-00043-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:320b965403986144b9a96894b300bea1904a2a194a3be4b7753ebef924f042d8
+size 4996299896
diff --git a/model-00044-of-00047.safetensors b/model-00044-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..df2b1cdfd9f7a166c2076423a5aabed03efedf74
--- /dev/null
+++ b/model-00044-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:7c4116c9bbc64522bbacd6b451332df443cfa5267595bce9b2297a98fe367d7d
+size 5000428832
diff --git a/model-00046-of-00047.safetensors b/model-00046-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..a10aa2db28ebdd6995b443eef8612f4d03e79096
--- /dev/null
+++ b/model-00046-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:356a830b736a374d7870c5a2657d03476946b80a9510d1649ae28e47310b1299
+size 5000429000
diff --git a/model-00047-of-00047.safetensors b/model-00047-of-00047.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..3362fa02777fec00650f4ea7a3b352b44ad53e86
--- /dev/null
+++ b/model-00047-of-00047.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:f6b2daa8cf0c9de03c4bc920149c3ed5da407168c40f3e5a1138ccddbb05e5e3
+size 1612818256
diff --git a/model.safetensors.index.json b/model.safetensors.index.json
new file mode 100644
index 0000000000000000000000000000000000000000..0fdb2f52f3cab121a67351c0ec4cd54365902512
--- /dev/null
+++ b/model.safetensors.index.json
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:584b9855a0b3144a4444d2295f9a4f11d055620a3abd148db062b65b8004b800
+size 16781255
diff --git a/modeling_afmoe.py b/modeling_afmoe.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c22cca909b47329db43092311406bb22dd07c2c
--- /dev/null
+++ b/modeling_afmoe.py
@@ -0,0 +1,680 @@
+from typing import Callable, Optional, Tuple, Union
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from transformers.activations import ACT2FN
+from transformers.generation import GenerationMixin
+from transformers.modeling_outputs import (
+ MoeCausalLMOutputWithPast,
+ MoeModelOutputWithPast,
+)
+from transformers.modeling_utils import PreTrainedModel, ALL_ATTENTION_FUNCTIONS
+from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from transformers.masking_utils import (
+ create_causal_mask,
+ create_sliding_window_causal_mask,
+)
+from transformers.modeling_layers import GradientCheckpointingLayer
+from transformers.processing_utils import Unpack
+from transformers.utils import TransformersKwargs
+from transformers.cache_utils import Cache, DynamicCache
+from transformers.integrations import use_kernel_forward_from_hub
+
+
+try:
+ from .configuration_afmoe import AfmoeConfig
+except:
+ from configuration_afmoe import AfmoeConfig
+
+class AfmoeRotaryEmbedding(nn.Module):
+
+ def __init__(self, config: AfmoeConfig, device=None):
+ super().__init__()
+ # BC: "rope_type" was originally "type"
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
+ else:
+ self.rope_type = "default"
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.original_inv_freq = self.inv_freq
+
+ def _dynamic_frequency_update(self, position_ids, device):
+ """
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
+ 1 - growing beyond the cached sequence length (allow scaling)
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
+ """
+ seq_len = torch.max(position_ids) + 1
+ if seq_len > self.max_seq_len_cached: # growth
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
+ self.max_seq_len_cached = seq_len
+
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
+ # This .to() is needed if the model has been moved to a device after being initialized (because
+ # the buffer is automatically moved, but not the original copy)
+ self.original_inv_freq = self.original_inv_freq.to(device)
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
+ self.max_seq_len_cached = self.original_max_seq_len
+
+ @torch.no_grad()
+ def forward(self, x, position_ids):
+ if "dynamic" in self.rope_type:
+ self._dynamic_frequency_update(position_ids, device=x.device)
+
+ # Core RoPE block
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
+ position_ids_expanded = position_ids[:, None, :].float()
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
+ device_type = x.device.type
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
+ with torch.autocast(device_type=device_type, enabled=False):
+ freqs = (inv_freq_expanded.float().to(x.device) @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos()
+ sin = emb.sin()
+
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
+ cos = cos * self.attention_scaling
+ sin = sin * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ position_ids (`torch.Tensor`, *optional*):
+ Deprecated and unused.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(
+ batch, num_key_value_heads, n_rep, slen, head_dim
+ )
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+@use_kernel_forward_from_hub("RMSNorm")
+class AfmoeRMSNorm(nn.Module):
+ def __init__(self, hidden_size: int, eps: float):
+ """
+ AfmoeRMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states):
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: Optional[torch.Tensor],
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs,
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
+ attn_weights = attn_weights + causal_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
+ query.dtype
+ )
+ attn_weights = nn.functional.dropout(
+ attn_weights, p=dropout, training=module.training
+ )
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class AfmoeMLP(nn.Module):
+ def __init__(self, config, intermediate_size=None):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = intermediate_size or config.intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+
+
+class AfmoeTokenChoiceRouter(nn.Module):
+ """Token-choice top-K router for MoE routing."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.top_k = config.num_experts_per_tok
+ self.num_experts = config.num_experts
+ self.score_func = config.score_func
+ self.route_norm = config.route_norm
+ self.route_scale = config.route_scale
+ self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
+
+ def forward(self, hidden_states, expert_bias: torch.Tensor | None):
+ _, _, hidden_dim = hidden_states.shape
+ hidden_states = hidden_states.view(-1, hidden_dim)
+
+ scores = self.gate(hidden_states)
+
+ # Apply scoring function in float32 for stability
+ if self.score_func == "sigmoid":
+ scores = torch.sigmoid(scores.to(torch.float32))
+ else:
+ scores = F.softmax(scores.to(torch.float32), dim=-1)
+
+ if expert_bias is not None:
+ _, selected_experts = torch.topk(scores + expert_bias, k=self.top_k, dim=1)
+ top_scores = scores.gather(dim=1, index=selected_experts)
+ else:
+ top_scores, selected_experts = torch.topk(scores, k=self.top_k, dim=1)
+
+ # Normalize weights if using sigmoid
+ if self.score_func == "sigmoid" and self.route_norm:
+ denominator = top_scores.sum(dim=-1, keepdim=True) + 1e-20
+ top_scores = top_scores / denominator
+
+ top_scores = top_scores * self.route_scale
+ return top_scores, selected_experts
+
+class AfmoeMoE(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.router = AfmoeTokenChoiceRouter(config)
+
+ self.shared_experts = None
+ if config.num_shared_experts > 0:
+ self.shared_experts = AfmoeMLP(
+ config, config.moe_intermediate_size * config.num_shared_experts
+ )
+ self.experts = nn.ModuleList(
+ [AfmoeMLP(
+ config, intermediate_size=config.moe_intermediate_size
+ ) for _ in range(config.num_experts)]
+ )
+ self.expert_bias = nn.Parameter(torch.zeros(config.num_experts, dtype=torch.float32), requires_grad=False)
+
+
+ def forward(self, hidden_states):
+ batch_size, seq_len, hidden_dim = hidden_states.shape
+ hidden_states_flat = hidden_states.view(-1, hidden_dim)
+
+ # Get routing decisions
+ top_scores, selected_experts = self.router(hidden_states, self.expert_bias)
+
+ # Process through shared experts
+ if self.shared_experts is not None:
+ shared_output = self.shared_experts(hidden_states_flat)
+ else:
+ shared_output = torch.zeros_like(hidden_states_flat)
+
+ # Reorder tokens by expert for efficient processing
+ token_indices_sorted = torch.argsort(selected_experts.view(-1), stable=True)
+ top_scores_sorted = top_scores.view(-1)[token_indices_sorted]
+ token_to_expert = selected_experts.view(-1)[token_indices_sorted]
+ token_indices_sorted = token_indices_sorted // self.config.num_experts_per_tok
+
+ # Gather input tokens
+ token_indices_expanded = token_indices_sorted.unsqueeze(-1).expand(
+ -1, hidden_dim
+ )
+ routed_input = torch.gather(
+ hidden_states_flat, dim=0, index=token_indices_expanded
+ )
+
+ routed_output = torch.zeros_like(routed_input)
+ for expert_id in range(self.config.num_experts):
+ mask = token_to_expert == expert_id
+ if mask.any():
+ expert_input = routed_input[mask]
+ expert_out = self.experts[expert_id](expert_input)
+ routed_output[mask] = expert_out
+
+ routed_output = (
+ routed_output.to(torch.float32) * top_scores_sorted.unsqueeze(-1)
+ ).to(hidden_states.dtype)
+
+ # Scatter back to original positions
+ output = shared_output.scatter_add(
+ dim=0, index=token_indices_expanded, src=routed_output
+ )
+
+ return output.view(batch_size, seq_len, hidden_dim)
+
+
+class AfmoeAttention(nn.Module):
+ """Multi-headed attention with local/global pattern and gating."""
+
+ def __init__(self, config: AfmoeConfig, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_heads = config.num_attention_heads
+ self.num_key_value_heads = config.num_key_value_heads
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
+
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = config.attention_dropout
+ self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"
+ self.sliding_window = config.sliding_window if self.is_local_attention else None
+
+ self.q_proj = nn.Linear(
+ config.hidden_size, self.num_heads * self.head_dim, bias=False
+ )
+ self.k_proj = nn.Linear(
+ config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
+ )
+ self.v_proj = nn.Linear(
+ config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
+ )
+ self.o_proj = nn.Linear(
+ self.num_heads * self.head_dim, config.hidden_size, bias=False
+ )
+
+ self.q_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
+ self.k_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
+
+ self.gate_proj = nn.Linear(
+ config.hidden_size, self.num_heads * self.head_dim, bias=False
+ )
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
+ attention_mask: Optional[torch.Tensor],
+ past_key_value: Optional[Cache] = None,
+ cache_position: Optional[torch.LongTensor] = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape)
+ key_states = self.k_proj(hidden_states).view(hidden_shape)
+ value_states = self.v_proj(hidden_states).view(hidden_shape)
+ gate_states = self.gate_proj(hidden_states)
+
+ query_states = self.q_norm(query_states)
+ key_states = self.k_norm(key_states)
+
+ query_states = query_states.transpose(1, 2)
+ key_states = key_states.transpose(1, 2)
+ value_states = value_states.transpose(1, 2)
+
+ if self.is_local_attention:
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_value is not None:
+ cache_kwargs = {"cache_position": cache_position}
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
+
+ attention_interface: Callable = eager_attention_forward
+ if self.config._attn_implementation != "eager":
+ attention_interface = ALL_ATTENTION_FUNCTIONS[
+ self.config._attn_implementation
+ ]
+
+ output, _ = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask=attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ sliding_window=self.sliding_window,
+ **kwargs,
+ )
+
+ output = output.view(*input_shape, -1).contiguous()
+ output = output * F.sigmoid(gate_states)
+ return self.o_proj(output)
+
+
+class AfmoeDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: AfmoeConfig, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+ self.layer_idx = layer_idx
+
+ self.self_attn = AfmoeAttention(config=config, layer_idx=layer_idx)
+ self.attention_type = config.layer_types[layer_idx]
+
+ # Dual normalization for attention
+ self.input_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ # Dual normalization for FFN
+ self.pre_mlp_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_mlp_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ # MoE or dense FFN
+ self.moe_enabled = layer_idx >= config.num_dense_layers
+ if self.moe_enabled:
+ self.mlp = AfmoeMoE(config)
+ else:
+ self.mlp = AfmoeMLP(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_value: Optional[Cache] = None,
+ use_cache: Optional[bool] = None,
+ cache_position: Optional[torch.LongTensor] = None,
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.FloatTensor:
+ residual = hidden_states
+
+ # Self Attention with dual normalization
+ hidden_states = self.input_layernorm(hidden_states)
+ hidden_states = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_value=past_key_value,
+ use_cache=use_cache,
+ cache_position=cache_position,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = residual + hidden_states
+
+ # FFN with dual normalization
+ residual = hidden_states
+ hidden_states = self.pre_mlp_layernorm(hidden_states)
+
+ if self.moe_enabled:
+ hidden_states = self.mlp(hidden_states)
+ else:
+ hidden_states = self.mlp(hidden_states)
+
+ hidden_states = self.post_mlp_layernorm(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+class AfmoePreTrainedModel(PreTrainedModel):
+ config_class = AfmoeConfig
+ base_model_prefix = "model"
+ _no_split_modules = ["AfmoeDecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _keep_in_fp32_modules = [
+ "input_layernorm",
+ "post_attention_layernorm",
+ "pre_mlp_layernorm",
+ "post_mlp_layernorm",
+ "q_norm",
+ "k_norm",
+ "norm",
+ ]
+ _supports_sdpa = True
+ _supports_attention_backend = True
+ supports_gradient_checkpointing = True
+
+
+class AfmoeModel(AfmoePreTrainedModel):
+ _no_split_modules = ["AfmoeDecoderLayer"]
+
+ def __init__(self, config: AfmoeConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(
+ config.vocab_size, config.hidden_size, self.padding_idx
+ )
+ self.layers = nn.ModuleList(
+ [
+ AfmoeDecoderLayer(config, layer_idx)
+ for layer_idx in range(config.num_hidden_layers)
+ ]
+ )
+ self.norm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = AfmoeRotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.embed_tokens = value
+
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[list[torch.FloatTensor]] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ use_cache: Optional[bool] = None,
+ cache_position: Optional[torch.LongTensor] = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> MoeModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError(
+ "You must specify exactly one of input_ids or inputs_embeds"
+ )
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache()
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ if cache_position is None:
+ past_seen_tokens = (
+ past_key_values.get_seq_length() if past_key_values is not None else 0
+ )
+ cache_position = torch.arange(
+ past_seen_tokens,
+ past_seen_tokens + inputs_embeds.shape[1],
+ device=inputs_embeds.device,
+ )
+ if position_ids is None:
+ position_ids = cache_position.unsqueeze(0)
+
+ # It may already have been prepared by e.g. `generate`
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
+ mask_kwargs = {
+ "config": self.config,
+ "input_embeds": inputs_embeds,
+ "attention_mask": attention_mask,
+ "cache_position": cache_position,
+ "past_key_values": past_key_values,
+ }
+ causal_mask_mapping = {
+ "full_attention": create_causal_mask(**mask_kwargs),
+ "sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
+ }
+
+ hidden_states = inputs_embeds
+
+ # Apply muP input scaling if enabled
+ if self.config.mup_enabled:
+ hidden_states = hidden_states * (self.config.hidden_size**0.5)
+
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
+
+ for decoder_layer in self.layers:
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
+ position_ids=position_ids,
+ past_key_value=past_key_values,
+ use_cache=use_cache,
+ cache_position=cache_position,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+ return MoeModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+class AfmoeForCausalLM(AfmoePreTrainedModel, GenerationMixin):
+ _tied_weights_keys = ["lm_head.weight"]
+ _tp_plan = {"lm_head": "colwise_rep"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = AfmoeModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.model.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.model.embed_tokens = value
+
+ def get_output_embeddings(self):
+ return self.lm_head
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head = new_embeddings
+
+ def set_decoder(self, decoder):
+ self.model = decoder
+
+ def get_decoder(self):
+ return self.model
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[Cache] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ cache_position: Optional[torch.LongTensor] = None,
+ logits_to_keep: Union[int, torch.Tensor] = 0,
+ token_type_ids: Optional[torch.Tensor] = None, # will be ignored
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
+ outputs: MoeModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ cache_position=cache_position,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits
+ slice_indices = (
+ slice(-logits_to_keep, None)
+ if isinstance(logits_to_keep, int)
+ else logits_to_keep
+ )
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
+
+
+ return MoeCausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ router_logits=outputs.router_logits,
+ )
+
+
+__all__ = [
+ "AfmoeForCausalLM",
+ "AfmoeModel",
+ "AfmoePreTrainedModel",
+]
diff --git a/recipe.yaml b/recipe.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..c3887f15dcd9dab723d7c8a9cb7ea29739021857
--- /dev/null
+++ b/recipe.yaml
@@ -0,0 +1,7 @@
+default_stage:
+ default_modifiers:
+ QuantizationModifier:
+ targets: [Linear]
+ ignore: [lm_head, 're:.*self_attn.*', 're:.*mlp.router.*']
+ scheme: NVFP4
+ bypass_divisibility_checks: false
diff --git a/special_tokens_map.json b/special_tokens_map.json
new file mode 100644
index 0000000000000000000000000000000000000000..5fd26c542275c864fff98316bef46b902bc68cce
--- /dev/null
+++ b/special_tokens_map.json
@@ -0,0 +1,23 @@
+{
+ "bos_token": {
+ "content": "<|begin_of_text|>",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false
+ },
+ "eos_token": {
+ "content": "<|im_end|>",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false
+ },
+ "pad_token": {
+ "content": "<|pad|>",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false
+ }
+}
diff --git a/tokenizer.json b/tokenizer.json
new file mode 100644
index 0000000000000000000000000000000000000000..20286e2b0432a2f82d206ea4a2788e51775e376e
--- /dev/null
+++ b/tokenizer.json
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c5a93d847b4d3a1da95e9527c30ec10144f63a823e9feec98570274980754897
+size 14614487
diff --git a/tokenizer_config.json b/tokenizer_config.json
new file mode 100644
index 0000000000000000000000000000000000000000..88320d663cb9cbb25a9f5348166bee5af8209901
--- /dev/null
+++ b/tokenizer_config.json
@@ -0,0 +1,271 @@
+{
+ "add_bos_token": false,
+ "add_eos_token": false,
+ "add_prefix_space": null,
+ "added_tokens_decoder": {
+ "0": {
+ "content": "<|begin_of_text|>",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": true
+ },
+ "1": {
+ "content": "<|end_of_text|>",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": true
+ },
+ "2": {
+ "content": "<|im_start|>",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": true
+ },
+ "3": {
+ "content": "<|im_end|>",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": true
+ },
+ "4": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "5": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "6": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "7": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "8": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "9": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "10": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "11": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "12": {
+ "content": "<|pad|>",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": true
+ },
+ "13": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "14": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "15": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "16": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "17": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "18": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "19": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "20": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "21": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "22": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "23": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "24": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "25": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "26": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "27": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "28": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": false
+ },
+ "29": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false,
+ "special": true
+ }
+ },
+ "bos_token": "<|begin_of_text|>",
+ "clean_up_tokenization_spaces": false,
+ "eos_token": "<|im_end|>",
+ "extra_special_tokens": {},
+ "model_max_length": 65536,
+ "pad_token": "<|pad|>",
+ "tokenizer_class": "PreTrainedTokenizerFast",
+ "use_default_system_prompt": false
+}