mrfakename commited on
Commit
2d4e5b0
·
verified ·
1 Parent(s): 1f7bfc1

Mirror facebook/MobileMoE-M-QAT

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ mobilemoe_pareto.png filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FAIR Noncommercial Research License
2
+ v1 Last Updated: August 21, 2026
3
+
4
+ “Acceptable Use Policy” means the FAIR Acceptable Use Policy, applicable to Research Materials, that is incorporated into this Agreement.
5
+
6
+ “Agreement” means the terms and conditions for use, reproduction, distribution and modification of the Research Materials set forth herein.
7
+
8
+
9
+ “Documentation” means the specifications, manuals and documentation accompanying
10
+ Research Materials distributed by Meta.
11
+
12
+
13
+ “Licensee” or “you” means you, or your employer or any other person or entity (if you are entering into this Agreement on such person or entity’s behalf), of the age required under applicable laws, rules or regulations to provide legal consent and that has legal authority to bind your employer or such other person or entity if you are entering in this Agreement on their behalf.
14
+
15
+
16
+ “Meta” or “we” means Meta Platforms Ireland Limited (if you are located in or, if you are an entity, your principal place of business is in the EEA or Switzerland) and Meta Platforms, Inc. (if you are located outside of the EEA or Switzerland).
17
+
18
+ “Noncommercial Research Uses” means noncommercial research use cases related to research, development, education, processing, or analysis and in each case, is not primarily intended for commercial advantage or monetary compensation to you or others.
19
+
20
+ “Research Materials” means, collectively, Documentation and the models, software and algorithms, including machine-learning model code, trained model weights, inference-enabling code, training-enabling code, fine-tuning enabling code, demonstration materials and other elements of the foregoing distributed by Meta and made available under this Agreement.
21
+
22
+ By clicking “I Accept” below or by using or distributing any portion or element of the Research Materials, you agree to be bound by this Agreement.
23
+
24
+
25
+ 1. License Rights and Redistribution.
26
+
27
+
28
+ a. Grant of Rights. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Meta’s intellectual property or other rights owned by Meta embodied in the Research Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the Research Materials.
29
+
30
+ b. Redistribution and Use.
31
+ i. You will not use the Research Materials or any outputs or results of the Research Materials in connection with any commercial uses or for any uses other than Noncommercial Research Uses;
32
+
33
+
34
+ ii. Distribution of Research Materials, and any derivative works thereof, are subject to the terms of this Agreement. If you distribute or make the Research Materials, or any derivative works thereof, available to a third party, you may only do so under the terms of this Agreement. You shall also provide a copy of this Agreement to such third party.
35
+
36
+
37
+ iii. If you submit for publication the results of research you perform on, using, or otherwise in connection with Research Materials, you must acknowledge the use of Research Materials in your publication.
38
+
39
+
40
+ iv. Your use of the Research Materials must comply with applicable laws and regulations (including Trade Control Laws) and adhere to the FAIR Acceptable Use Policy, which is hereby incorporated by reference into this Agreement.
41
+ 2. User Support. Your Noncommercial Research Use of the Research Materials is done at your own discretion; Meta does not process any information nor provide any service in relation to such use. Meta is under no obligation to provide any support services for the Research Materials. Any support provided is “as is”, “with all faults”, and without warranty of any kind.
42
+
43
+
44
+ 3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE RESEARCH MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS ALL WARRANTIES OF ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE RESEARCH MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE RESEARCH MATERIALS AND ANY OUTPUT AND RESULTS.
45
+
46
+ 4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT OR INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
47
+
48
+ 5. Intellectual Property.
49
+
50
+
51
+ a. Subject to Meta’s ownership of Research Materials and derivatives made by or for Meta, with respect to any derivative works and modifications of the Research Materials that are made by you, as between you and Meta, you are and will be the owner of such derivative works and modifications.
52
+
53
+ b. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Research Materials, outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Meta from and against any claim by any third party arising out of or related to your use or distribution of the Research Materials.
54
+
55
+ 6. Term and Termination. The term of this Agreement will commence upon your acceptance of this Agreement or access to the Research Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Meta may terminate this Agreement if you are in breach of any term or condition of this Agreement. Upon termination of this Agreement, you shall delete and cease use of the Research Materials. Sections 3, 4 and 7 shall survive the termination of this Agreement.
56
+
57
+ 7. Governing Law and Jurisdiction. This Agreement will be governed and construed under the laws of the State of California without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The courts of California shall have exclusive jurisdiction of any dispute arising out of this Agreement.
58
+
59
+
60
+ 8. Modifications and Amendments. Meta may modify this Agreement from time to time; provided that they are similar in spirit to the current version of the Agreement, but may differ in detail to address new problems or concerns. All such changes will be effective immediately. Your continued use of the Research Materials after any modification to this Agreement constitutes your agreement to such modification. Except as provided in this Agreement, no modification or addition to any provision of this Agreement will be binding unless it is in writing and signed by an authorized representative of both you and Meta.
61
+
62
+
63
+ FAIR Acceptable Use Policy
64
+
65
+ The Fundamental AI Research (FAIR) team at Meta seeks to further understanding of new and existing research domains with the mission of advancing the state-of-the-art in artificial intelligence through open research for the benefit of all.
66
+
67
+ As part of this mission, Meta makes certain research materials available for noncommercial research use. Meta is committed to promoting the safe and responsible use of such research materials.
68
+
69
+ Prohibited Uses
70
+
71
+ You agree you will not use, or allow others to use, Research Materials to:
72
+
73
+ Violate the law or others’ rights, including to:
74
+ Engage in, promote, generate, contribute to, encourage, plan, incite, or further illegal or unlawful activity or content, such as:
75
+ Violence or terrorism
76
+ Exploitation or harm to children, including the solicitation, creation, acquisition, or dissemination of child exploitative content or failure to report Child Sexual Abuse Material
77
+ Human trafficking, exploitation, and sexual violence
78
+ The illegal distribution of information or materials to minors, including obscene materials, or failure to employ legally required age-gating in connection with such information or materials.
79
+ Sexual solicitation
80
+ Any other criminal activity
81
+
82
+ Engage in, promote, incite, or facilitate the harassment, abuse, threatening, or bullying of individuals or groups of individuals
83
+
84
+ Engage in, promote, incite, or facilitate discrimination or other unlawful or harmful conduct in the provision of employment, employment benefits, credit, housing, other economic benefits, or other essential goods and services
85
+
86
+ Engage in the unauthorized or unlicensed practice of any profession including, but not limited to, financial, legal, medical/health, or related professional practices
87
+
88
+ Collect, process, disclose, generate, or infer health, demographic, or other sensitive personal or private information about individuals without rights and consents required by applicable laws
89
+
90
+ Engage in or facilitate any action or generate any content that infringes, misappropriates, or otherwise violates any third-party rights, including the outputs or results of any technology using FAIR research materials
91
+
92
+ Create, generate, or facilitate the creation of malicious code, malware, computer viruses or do anything else that could disable, overburden, interfere with or impair the proper working, integrity, operation or appearance of a website or computer system
93
+
94
+ 2. Engage in, promote, incite, facilitate, or assist in the planning or development of activities that present a risk of death or bodily harm to individuals, including use of research artifacts related to the following:
95
+
96
+ Military, warfare, nuclear industries or applications, espionage, use for materials or activities that are subject to the International Traffic Arms Regulations (ITAR) maintained by the United States Department of State
97
+
98
+ Guns and illegal weapons (including weapon development)
99
+
100
+ Illegal drugs and regulated/controlled substances
101
+
102
+ Operation of critical infrastructure, transportation technologies, or heavy machinery
103
+
104
+ Self-harm or harm to others, including suicide, cutting, and eating disorders
105
+
106
+ Any content intended to incite or promote violence, abuse, or any infliction of bodily harm to an individual
107
+
108
+ 3. Intentionally deceive or mislead others, including use of FAIR Research Materials related to the following:
109
+
110
+ Generating, promoting, or furthering fraud or the creation or promotion of disinformation
111
+
112
+ Generating, promoting, or furthering defamatory content, including the creation of defamatory statements, images, or other content
113
+
114
+ Generating, promoting, or further distributing spam
115
+
116
+ Impersonating another individual without consent, authorization, or legal right
117
+
118
+ Representing that outputs of FAIR research materials or outputs from technology using FAIR research materials are human-generated
119
+
120
+ Generating or facilitating false online engagement, including fake reviews and other means of fake online engagement
121
+
122
+ 4. Fail to appropriately disclose to end users any known dangers of your Research Materials.
123
+
124
+ Please report any violation of this Policy or other problems that could lead to a violation of this Policy by submitting a report here [https://docs.google.com/forms/d/e/1FAIpQLSeb11cryAopJ7LNrC4nxEUXrHY26hfkXQMf_uH-oFgA3WlYZQ/viewform].
README.md ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: fair-noncommercial-research-license
3
+ language:
4
+ - en
5
+ library_name: transformers
6
+ tags:
7
+ - facebook
8
+ - meta
9
+ - pytorch
10
+ - mixture-of-experts
11
+ - MoE
12
+ - on-device
13
+ - quantization
14
+ - int4
15
+ ---
16
+ > Mirror of [facebook/MobileMoE-M-QAT](https://huggingface.co/facebook/MobileMoE-M-QAT). All credit to the original authors. Not an official release from them. License unchanged (FAIR Noncommercial Research License, non-commercial use only); see `LICENSE`.
17
+
18
+ # MobileMoE-M (QAT) Model Card
19
+
20
+ **MobileMoE** is a family of on-device Mixture-of-Experts (MoE) language models with sub-billion *active* parameters, designed to push the quality–efficiency Pareto frontier for on-device LLMs, including three model scales (S/M/L): 0.3B/0.5B/0.9B active parameters (1.3B/2.8B/5.3B total), with <3 GB INT4 weight footprints to fit in mobile DRAM. Each scale is released in three variants: a **Base** model (pre-training + mid-training), an **SFT** model (supervised fine-tuning), and a **QAT** model (quantization-aware training). You are currently in the **MobileMoE-M-QAT** repository — the **INT4** quantization-aware-trained 0.5B-active model, built on top of MobileMoE-M-SFT and intended for on-device deployment.
21
+
22
+ | | **S** | **M** | **L** |
23
+ |:---|:---:|:---:|:---:|
24
+ | Active / total params | 272M / 1.3B | 528M / 2.8B | 922M / 5.3B |
25
+ | Layers | 20 | 26 | 32 |
26
+ | Model dimension | 768 | 1024 | 1280 |
27
+ | Heads (Q / KV) | 12 / 4 | 16 / 4 | 20 / 4 |
28
+ | Routed experts | 60 | 60 | 60 |
29
+ | Top-k | 4 | 4 | 4 |
30
+ | Projected INT4 weight memory | 0.68 GB | **1.48 GB** | 2.75 GB |
31
+ | Base | [MobileMoE-S-Base](https://huggingface.co/facebook/MobileMoE-S-Base) | [MobileMoE-M-Base](https://huggingface.co/facebook/MobileMoE-M-Base) | [MobileMoE-L-Base](https://huggingface.co/facebook/MobileMoE-L-Base) |
32
+ | SFT | [MobileMoE-S-SFT](https://huggingface.co/facebook/MobileMoE-S-SFT) | [MobileMoE-M-SFT](https://huggingface.co/facebook/MobileMoE-M-SFT) | [MobileMoE-L-SFT](https://huggingface.co/facebook/MobileMoE-L-SFT) |
33
+ | QAT (INT4) | [MobileMoE-S-QAT](https://huggingface.co/facebook/MobileMoE-S-QAT) | **MobileMoE-M-QAT** | [MobileMoE-L-QAT](https://huggingface.co/facebook/MobileMoE-L-QAT) |
34
+
35
+ For the detailed technical report: 📝 [MobileMoE: Scaling On-Device Mixture of Experts](https://arxiv.org/abs/2605.27358)
36
+
37
+ For more versions, check out the 🤗 [MobileMoE Collection](https://huggingface.co/collections/facebook/mobilemoe)
38
+
39
+ ![MobileMoE establishes a new Pareto frontier for on-device LLMs](mobilemoe_pareto.png)
40
+
41
+ **MobileMoE establishes a new Pareto frontier for on-device LLMs.** Average benchmark accuracy, computed over 14 benchmarks spanning commonsense, knowledge, science, comprehension, and reasoning, is plotted against (a) per-token inference compute *F*<sub>inf</sub> = 2*N*<sub>act</sub> (GFLOPs) and (b) total parameters *N*<sub>total</sub> (B); in (b), x-axis tick labels show total params (B) | projected INT4 memory (GB). Accuracy is shown for the instruction-tuned models.
42
+
43
+ ## Key Features
44
+
45
+ - **A new Pareto frontier for on-device LLMs.** Across 14 foundational benchmarks, MobileMoE matches or exceeds leading on-device dense LLMs at 2–4× fewer inference FLOPs, and matches or surpasses the state-of-the-art MoE OLMoE-1B-7B with up to 60% fewer parameters.
46
+ - **Scaling-law-derived architecture.** The architecture is derived from an on-device MoE scaling law that jointly optimizes under mobile *memory* and *compute* constraints, identifying an on-device sweet spot: moderate sparsity, with fine-grained experts and shared expert.
47
+ - **Four-stage recipe.** Pre-training → mid-training → instruction fine-tuning → INT4 quantization-aware training, all on open-source datasets.
48
+
49
+ ## Model Information
50
+
51
+ **Model:** MobileMoE-M-QAT (INT4, quantization-aware trained)<br>
52
+ **Active Parameters:** 528M<br>
53
+ **Total Parameters:** 2.8B<br>
54
+ **Layers:** 26<br>
55
+ **Model Dimension:** 1024<br>
56
+ **Attention Heads:** 16<br>
57
+ **KV Heads:** 4 (GQA)<br>
58
+ **Head Dimension:** 64<br>
59
+ **Routed Experts:** 60 (fine-grained, FFN hidden dim 512 each)<br>
60
+ **Active Experts per Token:** 4 (top-k sigmoid routing, with normalization)<br>
61
+ **Shared Expert:** 1, always on (FFN hidden dim 2048)<br>
62
+ **Vocabulary Size:** 128,256<br>
63
+ **Other Features:** QK-Norm, tied input/output embeddings, RoPE (θ = 500,000)<br>
64
+ **Input Modality:** Text<br>
65
+ **Output Modality:** Text<br>
66
+ **Languages:** English<br>
67
+ **Chat Template:** Yes (end-of-turn token `<|eot|>`)<br>
68
+ **Training Stages:** Pre-training → mid-training → SFT → INT4 QAT<br>
69
+ **Context Length:** 8,192 tokens<br>
70
+ **Precision:** INT4 weights (symmetric, group size 32; FP16 scales); router stored and routing computed in FP32; BF16 norms and dense compute<br>
71
+ **Projected INT4 Weight Memory:** 1.48 GB<br>
72
+ **Model Developer:** Meta<br>
73
+ **Model Release Date:** Aug 2026<br>
74
+ **License:** MobileMoE is FAIR NC licensed
75
+
76
+ ## Quantization
77
+
78
+ INT4 quantization-aware training is applied to the SFT checkpoint. Weights are quantized as
79
+
80
+ ```
81
+ W̃g = sg · clamp(round(Wg / sg), −8, 7), sg = 2·max(|Wg|) / (2^b − 1), b = 4
82
+ ```
83
+
84
+ where `Wg` is a contiguous group of 32 weights sharing one scale `sg`.
85
+
86
+ | component | precision |
87
+ |:---|:---|
88
+ | Attention (q/k/v/o), routed experts, shared expert, embeddings | **INT4**, symmetric, group size 32 |
89
+ | Router | Stored and routing computed in FP32 |
90
+ | RMSNorm weights, expert bias | BF16 |
91
+
92
+ **Note:** Projected INT4 weight memory is a weight-only estimate. Packaged checkpoint files (`model.safetensors`) are 0.71 / 1.59 / 3.00 GB for S / M / L, including FP16 group scales, FP32 router weights, and BF16 norms/biases. Runtime memory is backend-dependent and additionally includes the KV cache, activations, and other overhead.
93
+
94
+ ## Results
95
+
96
+ All numbers below are for **INT4-quantized** models, re-evaluated under identical settings with greedy decoding using [`lm-eval`](https://github.com/EleutherAI/lm-evaluation-harness); few-shot counts are given in parentheses after the benchmark name, and benchmarks shown without one are evaluated 0-shot. All three MobileMoE scales are the exact weights released in their respective QAT repositories, which include brief fine-tuning with self-identity beyond the QAT checkpoints in the [technical report](https://arxiv.org/abs/2605.27358). This produces small differences against the report: averages of 43.9 / 52.7 / 58.1 here versus 44.0 / 52.5 / 57.8 for S / M / L in the report.
97
+
98
+ ### Foundational benchmarks (INT4)
99
+
100
+ <style>
101
+ .mobilemoe-table th{padding:10px 7px;text-align:center;font-weight:500;border-bottom:2px solid #0A2EFE;color:#1E3A8A;font-size:14px;line-height:1.2}
102
+ .mobilemoe-table th:first-child{width:28%;text-align:left}
103
+ .mobilemoe-table th:not(:first-child){width:18%}
104
+ .mobilemoe-table td:not([colspan]){padding:7px;border-bottom:1px solid rgba(128,128,128,0.15);font-size:15px;line-height:1.2;vertical-align:middle}
105
+ .mobilemoe-table td:first-child:not([colspan]){padding-left:20px;text-align:left}
106
+ .mobilemoe-table td:not(:first-child):not([colspan]){text-align:center}
107
+ .mobilemoe-table th:nth-child(4),.mobilemoe-table td:nth-child(4):not([colspan]){background:rgba(10,46,254,0.08)}
108
+ .mobilemoe-table td[colspan]{padding:8px 12px;text-align:left;font-weight:600;color:#1E3A8A;border-bottom:1px solid rgba(10,46,254,0.2);background:#D6DAFC}
109
+ .mobilemoe-table tr.summary-row td{padding:8px 7px;font-weight:600;color:#1E3A8A;border-bottom:1px solid rgba(10,46,254,0.2);background:#D6DAFC!important}
110
+ .mobilemoe-table tr.summary-row td:first-child{padding-left:12px}
111
+ .mobilemoe-table tr.summary-row td:nth-child(4){background:rgba(10,46,254,0.18)!important}
112
+
113
+ @media (prefers-color-scheme: dark){
114
+ .mobilemoe-table th,.mobilemoe-table td[colspan]{color:#8DA2FF!important;border-bottom-color:#8DA2FF!important}
115
+ .mobilemoe-table td[colspan]{background:rgba(10,46,254,0.22)!important}
116
+ .mobilemoe-table th:nth-child(4),.mobilemoe-table td:nth-child(4):not([colspan]){background:rgba(10,46,254,0.16)!important}
117
+ .mobilemoe-table tr.summary-row td{color:#8DA2FF!important;border-bottom-color:#8DA2FF!important;background:rgba(10,46,254,0.22)!important}
118
+ .mobilemoe-table tr.summary-row td:nth-child(4){background:rgba(10,46,254,0.32)!important}
119
+ }
120
+ </style>
121
+
122
+ <div style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;max-width:1200px;margin:0 auto;padding:16px 0">
123
+ <table class="mobilemoe-table" style="width:100%;table-layout:fixed;border-collapse:collapse;font-size:13px">
124
+ <thead><tr><th>Benchmark</th><th>MobileLLM-Pro</th><th>MobileMoE-S</th><th>MobileMoE-M</th><th>MobileMoE-L</th></tr></thead>
125
+ <tbody>
126
+ <tr><td><strong>Active / total params</strong></td><td>1.1B</td><td>272M / 1.3B</td><td>528M / 2.8B</td><td>922M / 5.3B</td></tr>
127
+ <tr><td colspan="5">Commonsense Reasoning</td></tr>
128
+ <tr><td><strong>HellaSwag</strong></td><td>64.7</td><td>53.3</td><td>63.7</td><td>70.7</td></tr>
129
+ <tr><td><strong>PIQA</strong></td><td>75.6</td><td>73.9</td><td>76.4</td><td>78.9</td></tr>
130
+ <tr><td><strong>SIQA</strong></td><td>47.4</td><td>45.3</td><td>48.7</td><td>53.4</td></tr>
131
+ <tr><td><strong>WinoGrande</strong></td><td>62.8</td><td>56.6</td><td>61.6</td><td>65.4</td></tr>
132
+ <tr><td colspan="5">Knowledge</td></tr>
133
+ <tr><td><strong>MMLU (5-shot)</strong></td><td>30.4</td><td>39.0</td><td>52.2</td><td>57.4</td></tr>
134
+ <tr><td><strong>NaturalQuestions (5-shot)</strong></td><td>13.9</td><td>8.6</td><td>4.7</td><td>19.3</td></tr>
135
+ <tr><td><strong>TriviaQA (5-shot)</strong></td><td>39.9</td><td>25.2</td><td>42.7</td><td>52.7</td></tr>
136
+ <tr><td colspan="5">Science</td></tr>
137
+ <tr><td><strong>ARC-Challenge (25-shot)</strong></td><td>51.6</td><td>42.0</td><td>51.5</td><td>55.6</td></tr>
138
+ <tr><td><strong>ARC-Easy</strong></td><td>75.2</td><td>69.3</td><td>79.2</td><td>80.6</td></tr>
139
+ <tr><td><strong>OpenBookQA</strong></td><td>42.8</td><td>30.6</td><td>36.6</td><td>40.4</td></tr>
140
+ <tr><td colspan="5">Reading</td></tr>
141
+ <tr><td><strong>BoolQ</strong></td><td>76.8</td><td>71.2</td><td>77.1</td><td>78.3</td></tr>
142
+ <tr><td><strong>DROP (3-shot)</strong></td><td>20.5</td><td>26.3</td><td>43.5</td><td>47.3</td></tr>
143
+ <tr><td colspan="5">Reasoning</td></tr>
144
+ <tr><td><strong>BIG-Bench Hard (3-shot)</strong></td><td>31.4</td><td>30.8</td><td>37.0</td><td>39.5</td></tr>
145
+ <tr><td><strong>GSM8K (8-shot)</strong></td><td>4.1</td><td>42.9</td><td>63.5</td><td>73.2</td></tr>
146
+ <tr class="summary-row"><td><strong>Average</strong></td><td>45.5</td><td>43.9</td><td>52.7</td><td>58.1</td></tr>
147
+ </tbody>
148
+ </table>
149
+ </div>
150
+
151
+ ## Training
152
+
153
+ MobileMoE uses a four-stage recipe. This checkpoint is the output of stage 4 (INT4 QAT).
154
+
155
+ ![MobileMoE four-stage training recipe](mobilemoe_recipe.png)
156
+
157
+ **MobileMoE four-stage training recipe:** pre-training (PT) → mid-training (MT) → instruct supervised fine-tuning (SFT) → quantization-aware training (QAT) with INT4 precision.
158
+
159
+ | | Pre-training | Mid-training | SFT | **QAT** |
160
+ |---|---|---|---|---|
161
+ | Context length | 2,048 | 8,192 | 8,192 | **8,192** |
162
+ | Total tokens | ~6T | ~500B | ~126B | **~21B** |
163
+ | Peak learning rate | 4×10<sup>-4</sup> | 4×10<sup>-5</sup> | 4×10<sup>-6</sup> | **4×10<sup>-6</sup>** |
164
+ | LR schedule | Cosine | Linear | Cosine | **Cosine** |
165
+ | Token dispatch | drop-and-pad | drop-and-pad | dropless | **dropless** |
166
+
167
+ ## How to use
168
+
169
+ MobileMoE uses a custom architecture (`model_type: mobilemoe`) that is not yet part of upstream `transformers`, so **`trust_remote_code=True` is required**. The modeling code ships in this repo (`configuration_mobilemoe.py`, `modeling_mobilemoe.py`), and it handles INT4 dequantization automatically.
170
+
171
+ ### Requirements
172
+
173
+ ```bash
174
+ pip install "torch>=2.1" "transformers>=4.57" "safetensors>=0.4" "accelerate>=1.0"
175
+ ```
176
+
177
+ Verified with the following versions:
178
+
179
+ | Package | Version |
180
+ |---|---|
181
+ | `torch` | 2.8.0 (cu128) |
182
+ | `transformers` | 4.57.6 |
183
+ | `tokenizers` | 0.22.2 |
184
+ | `safetensors` | 0.7.0 |
185
+ | `accelerate` | 1.13.0 |
186
+
187
+ ### Chat
188
+
189
+ This model is **instruction-tuned** (QAT is applied on top of the SFT checkpoint), so use the chat template:
190
+
191
+ ```python
192
+ import torch
193
+ from transformers import AutoTokenizer, AutoModelForCausalLM
194
+
195
+ MODEL_ID = "facebook/MobileMoE-M-QAT"
196
+
197
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
198
+ model = AutoModelForCausalLM.from_pretrained(
199
+ MODEL_ID,
200
+ trust_remote_code=True,
201
+ dtype=torch.bfloat16,
202
+ )
203
+ model.to("cuda" if torch.cuda.is_available() else "cpu")
204
+ model.eval()
205
+
206
+ messages = [{"role": "user", "content": "Why are open-source on-device language models great?"}]
207
+ text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
208
+ inputs = tokenizer(text, return_tensors="pt").to(model.device)
209
+
210
+ outputs = model.generate(
211
+ input_ids=inputs["input_ids"],
212
+ attention_mask=inputs["attention_mask"],
213
+ max_new_tokens=1024,
214
+ do_sample=False,
215
+ temperature=None,
216
+ top_p=None,
217
+ pad_token_id=tokenizer.eos_token_id,
218
+ )
219
+ print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True))
220
+ ```
221
+
222
+ For multi-turn conversations, append each generated reply to `messages` with the `assistant` role. This ensures that each subsequent prompt includes the complete conversation history:
223
+
224
+ ```python
225
+ messages = []
226
+
227
+ for user_message in ["Who are you?", "Why are open-source on-device language models great?"]:
228
+ messages.append({"role": "user", "content": user_message})
229
+ input_ids = tokenizer.apply_chat_template(
230
+ messages, add_generation_prompt=True, return_tensors="pt"
231
+ ).to(model.device)
232
+ outputs = model.generate(
233
+ input_ids,
234
+ attention_mask=torch.ones_like(input_ids),
235
+ max_new_tokens=1024,
236
+ do_sample=False,
237
+ temperature=None,
238
+ top_p=None,
239
+ pad_token_id=tokenizer.eos_token_id,
240
+ )
241
+ reply = tokenizer.decode(outputs[0][input_ids.shape[-1]:], skip_special_tokens=True).strip()
242
+ messages.append({"role": "assistant", "content": reply})
243
+ print(reply)
244
+ ```
245
+
246
+ **Known issues.**
247
+
248
+ - Loading the tokenizer on `transformers` 4.57.6 prints a `fix_mistral_regex=True` warning. Please ignore it and do not set the flag, as MobileMoE uses the Llama-3 tokenizer whose default tokenization is already correct.
249
+ - The checkpoint stores `qweight` / `weight_scale` and creates dense weights on the first forward pass, so a *"newly initialized"* warning before then is expected.
250
+ - vLLM does not support this repository's INT4 format directly because its Transformers fallback replaces the custom layers and ignores the INT4 tensors. Convert the checkpoint to BF16 as described below, or use [MobileMoE-M-SFT](https://huggingface.co/facebook/MobileMoE-M-SFT) instead.
251
+
252
+ ### Exporting the INT4 Checkpoint to BF16
253
+
254
+ No conversion is needed for general use (e.g., with `transformers`) because the custom modeling code dequantizes the INT4 checkpoint to BF16 on the first forward pass. This section exports a numerically identical BF16 checkpoint to support other runtimes (e.g., vLLM) that bypass the custom loading logic and cannot use `qweight` / `weight_scale` directly.
255
+
256
+ ```python
257
+ import os, shutil, torch
258
+ from transformers import AutoModelForCausalLM, AutoTokenizer
259
+
260
+ SRC, DST = "facebook/MobileMoE-M-QAT", "./MobileMoE-M-QAT-bf16"
261
+
262
+ model = AutoModelForCausalLM.from_pretrained(SRC, trust_remote_code=True, dtype=torch.bfloat16)
263
+ model(torch.tensor([[128000]])) # first forward materializes INT4 -> BF16
264
+
265
+ state = {k: v for k, v in model.state_dict().items()
266
+ if not (k.endswith("qweight") or k.endswith("_scale"))}
267
+ model.config.quantization = None # mark the copy as plain BF16
268
+ model.save_pretrained(DST, state_dict=state, safe_serialization=True)
269
+ AutoTokenizer.from_pretrained(SRC).save_pretrained(DST)
270
+
271
+ # a trust_remote_code architecture needs its modeling files alongside the weights
272
+ for f in ("modeling_mobilemoe.py", "configuration_mobilemoe.py"):
273
+ src_f = os.path.join(SRC, f) if os.path.isdir(SRC) else __import__(
274
+ "huggingface_hub").hf_hub_download(SRC, f)
275
+ shutil.copy2(src_f, os.path.join(DST, f))
276
+ ```
277
+
278
+ ## Citation
279
+
280
+ ```bibtex
281
+ @article{chen2026mobilemoe,
282
+ title={MobileMoE: Scaling On-Device Mixture of Experts},
283
+ author={Chen, Yanbei and Huang, Hanxian and Chang, Ernie and Szwejbka, Jacob and Desai, Digant and Liu, Zechun and Chandra, Vikas and Krishnamoorthi, Raghuraman},
284
+ journal={arXiv preprint arXiv:2605.27358},
285
+ year={2026}
286
+ }
287
+ ```
288
+
289
+ ## License
290
+
291
+ MobileMoE is distributed under the [FAIR Noncommercial Research License](https://huggingface.co/facebook/MobileMoE-M-QAT/blob/main/LICENSE).
config.json ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "mobilemoe",
3
+ "architectures": [
4
+ "MobileMoEForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_mobilemoe.MobileMoEConfig",
8
+ "AutoModel": "modeling_mobilemoe.MobileMoETextModel",
9
+ "AutoModelForCausalLM": "modeling_mobilemoe.MobileMoEForCausalLM"
10
+ },
11
+ "vocab_size": 128256,
12
+ "bos_token_id": 128000,
13
+ "eos_token_id": [
14
+ 128001,
15
+ 128007,
16
+ 128008
17
+ ],
18
+ "pad_token_id": 128001,
19
+ "hidden_size": 1024,
20
+ "intermediate_size": 512,
21
+ "intermediate_size_mlp": 2048,
22
+ "num_hidden_layers": 26,
23
+ "num_attention_heads": 16,
24
+ "num_key_value_heads": 4,
25
+ "head_dim": 64,
26
+ "hidden_act": "silu",
27
+ "max_position_embeddings": 8192,
28
+ "rms_norm_eps": 1e-05,
29
+ "rope_theta": 500000.0,
30
+ "rope_scaling": {
31
+ "rope_type": "llama3",
32
+ "factor": 16,
33
+ "original_max_position_embeddings": 8192,
34
+ "low_freq_factor": 1.0,
35
+ "high_freq_factor": 1.0
36
+ },
37
+ "num_local_experts": 60,
38
+ "num_experts_per_tok": 4,
39
+ "interleave_moe_layer_step": 1,
40
+ "no_rope_layers": [
41
+ 1,
42
+ 1,
43
+ 1,
44
+ 1,
45
+ 1,
46
+ 1,
47
+ 1,
48
+ 1,
49
+ 1,
50
+ 1,
51
+ 1,
52
+ 1,
53
+ 1,
54
+ 1,
55
+ 1,
56
+ 1,
57
+ 1,
58
+ 1,
59
+ 1,
60
+ 1,
61
+ 1,
62
+ 1,
63
+ 1,
64
+ 1,
65
+ 1,
66
+ 1
67
+ ],
68
+ "layer_types": [
69
+ "full_attention",
70
+ "full_attention",
71
+ "full_attention",
72
+ "full_attention",
73
+ "full_attention",
74
+ "full_attention",
75
+ "full_attention",
76
+ "full_attention",
77
+ "full_attention",
78
+ "full_attention",
79
+ "full_attention",
80
+ "full_attention",
81
+ "full_attention",
82
+ "full_attention",
83
+ "full_attention",
84
+ "full_attention",
85
+ "full_attention",
86
+ "full_attention",
87
+ "full_attention",
88
+ "full_attention",
89
+ "full_attention",
90
+ "full_attention",
91
+ "full_attention",
92
+ "full_attention",
93
+ "full_attention",
94
+ "full_attention"
95
+ ],
96
+ "use_qk_norm": true,
97
+ "attn_temperature_tuning": false,
98
+ "tie_word_embeddings": true,
99
+ "torch_dtype": "bfloat16",
100
+ "attention_bias": false,
101
+ "attention_dropout": 0.0,
102
+ "routed_scaling_factor": 2.5,
103
+ "norm_topk_prob": true,
104
+ "quantization": {
105
+ "format": "mobilemoe-int4-g32",
106
+ "group_size": 32,
107
+ "embedding_group_size": 32,
108
+ "qmin": -8,
109
+ "qmax": 7,
110
+ "symmetric": true,
111
+ "half_range": 7.5,
112
+ "storage": "two 4-bit values per uint8 byte (packed)",
113
+ "embedding_precision": "int4 (16 levels, -8..7) stored in an int8 container - QAT trained the embeddings at int4/g32, so this is lossless; it is NOT 8-bit precision",
114
+ "scale_dtype": "float16",
115
+ "quantized": [
116
+ "attention",
117
+ "experts",
118
+ "shared_expert",
119
+ "embeddings"
120
+ ],
121
+ "not_quantized": [
122
+ "router (fp32)",
123
+ "expert_bias",
124
+ "norms"
125
+ ],
126
+ "linear_group_axis": "in (last dim of [out, in])",
127
+ "expert_group_axis": "out (last dim of [E, in, out])",
128
+ "packed": true,
129
+ "bit_exact_vs_bf16_export": "NO - float16 scales differ by <= 1 bf16 ulp of the output on ~5% of weights. Use scale_dtype float32 for strict bit-identity."
130
+ }
131
+ }
configuration_mobilemoe.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # This source code is licensed under the FAIR Noncommercial Research License
3
+
4
+ """Configuration class for MobileMoE.
5
+
6
+ MobileMoE is a Mixture-of-Experts language model with sigmoid-topk routing,
7
+ postgate scoring, and a shared expert. This config extends PretrainedConfig
8
+ with MoE-specific fields (routed_scaling_factor, norm_topk_prob,
9
+ intermediate_size_mlp) as first-class attributes.
10
+ """
11
+
12
+ from transformers.configuration_utils import PretrainedConfig
13
+
14
+
15
+ class MobileMoEConfig(PretrainedConfig):
16
+ model_type = "mobilemoe"
17
+ keys_to_ignore_at_inference = ["past_key_values"]
18
+
19
+ def __init__(
20
+ self,
21
+ vocab_size=128256,
22
+ hidden_size=768,
23
+ intermediate_size=384,
24
+ intermediate_size_mlp=1536,
25
+ num_hidden_layers=20,
26
+ num_attention_heads=12,
27
+ num_key_value_heads=4,
28
+ head_dim=64,
29
+ hidden_act="silu",
30
+ max_position_embeddings=2048,
31
+ initializer_range=0.02,
32
+ rms_norm_eps=1e-5,
33
+ use_cache=True,
34
+ pad_token_id=None,
35
+ bos_token_id=1,
36
+ eos_token_id=2,
37
+ tie_word_embeddings=True,
38
+ rope_theta=500000.0,
39
+ rope_scaling=None,
40
+ attention_bias=False,
41
+ attention_dropout=0.0,
42
+ num_experts_per_tok=4,
43
+ num_local_experts=60,
44
+ interleave_moe_layer_step=1,
45
+ use_qk_norm=True,
46
+ attn_temperature_tuning=False,
47
+ no_rope_layers=None,
48
+ layer_types=None,
49
+ routed_scaling_factor=2.5,
50
+ norm_topk_prob=True,
51
+ output_router_logits=False,
52
+ floor_scale=8192,
53
+ attn_scale=0.1,
54
+ sliding_window=None,
55
+ attention_chunk_size=8192,
56
+ **kwargs,
57
+ ):
58
+ super().__init__(
59
+ pad_token_id=pad_token_id,
60
+ bos_token_id=bos_token_id,
61
+ eos_token_id=eos_token_id,
62
+ tie_word_embeddings=tie_word_embeddings,
63
+ **kwargs,
64
+ )
65
+ self.vocab_size = vocab_size
66
+ self.hidden_size = hidden_size
67
+ self.intermediate_size = intermediate_size
68
+ self.intermediate_size_mlp = intermediate_size_mlp
69
+ self.num_hidden_layers = num_hidden_layers
70
+ self.num_attention_heads = num_attention_heads
71
+ self.num_key_value_heads = num_key_value_heads
72
+ self.head_dim = head_dim
73
+ self.hidden_act = hidden_act
74
+ self.max_position_embeddings = max_position_embeddings
75
+ self.initializer_range = initializer_range
76
+ self.rms_norm_eps = rms_norm_eps
77
+ self.use_cache = use_cache
78
+ self.rope_theta = rope_theta
79
+ self.rope_scaling = rope_scaling
80
+ self.attention_bias = attention_bias
81
+ self.attention_dropout = attention_dropout
82
+ self.num_experts_per_tok = num_experts_per_tok
83
+ self.num_local_experts = num_local_experts
84
+ self.interleave_moe_layer_step = interleave_moe_layer_step
85
+ self.use_qk_norm = use_qk_norm
86
+ self.attn_temperature_tuning = attn_temperature_tuning
87
+ self.routed_scaling_factor = routed_scaling_factor
88
+ self.norm_topk_prob = norm_topk_prob
89
+ self.output_router_logits = output_router_logits
90
+ self.floor_scale = floor_scale
91
+ self.attn_scale = attn_scale
92
+ self.sliding_window = sliding_window
93
+ self.attention_chunk_size = attention_chunk_size
94
+
95
+ if no_rope_layers is None:
96
+ no_rope_layers = [1] * num_hidden_layers
97
+ self.no_rope_layers = no_rope_layers
98
+
99
+ if layer_types is None:
100
+ layer_types = ["full_attention"] * num_hidden_layers
101
+ self.layer_types = layer_types
102
+
103
+ # Compute moe_layers from interleave_moe_layer_step
104
+ self.moe_layers = list(
105
+ range(
106
+ interleave_moe_layer_step - 1,
107
+ num_hidden_layers,
108
+ interleave_moe_layer_step,
109
+ )
110
+ )
generation_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 128000,
4
+ "eos_token_id": [
5
+ 128001,
6
+ 128007,
7
+ 128008
8
+ ],
9
+ "pad_token_id": 128001,
10
+ "do_sample": true,
11
+ "temperature": 0.6,
12
+ "top_p": 0.9,
13
+ "transformers_version": "4.57.6"
14
+ }
mobilemoe_pareto.png ADDED

Git LFS Details

  • SHA256: c6fb41cb7f2f6ee7e33cfd47a903086b5aa3598ecb89e9999dc36df322e7ab41
  • Pointer size: 131 Bytes
  • Size of remote file: 190 kB
mobilemoe_recipe.png ADDED
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f6260f2a009d6c311090947af696f9369da9e4f60a10c7c8b4d25a1e005e24e
3
+ size 1590986088
modeling_mobilemoe.py ADDED
@@ -0,0 +1,943 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # This source code is licensed under the FAIR Noncommercial Research License
3
+
4
+ """MobileMoE model implementation.
5
+
6
+ MobileMoE is a decoder-only Mixture-of-Experts (MoE) language model designed
7
+ for on-device inference. Only the MoE layer is custom; all other components
8
+ (attention, layernorm, embeddings) follow standard transformer design.
9
+
10
+ Usage:
11
+ from transformers import AutoModelForCausalLM
12
+ model = AutoModelForCausalLM.from_pretrained(ckpt_dir, trust_remote_code=True)
13
+ """
14
+
15
+ import math
16
+ from typing import Callable, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+ from transformers import PreTrainedModel
22
+ from transformers.cache_utils import Cache, DynamicCache
23
+ from transformers.generation import GenerationMixin
24
+ from transformers.masking_utils import create_causal_mask
25
+ from transformers.modeling_outputs import (
26
+ BaseModelOutputWithPast,
27
+ CausalLMOutputWithPast,
28
+ )
29
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
30
+
31
+ try:
32
+ from .configuration_mobilemoe import MobileMoEConfig
33
+ except ImportError:
34
+ from configuration_mobilemoe import MobileMoEConfig
35
+
36
+
37
+ # ---------------------------------------------------------------------------
38
+ # Building blocks
39
+ # ---------------------------------------------------------------------------
40
+
41
+
42
+ class MobileMoEL2Norm(nn.Module):
43
+ """L2 normalization for QK norm (no learnable parameters)."""
44
+
45
+ def __init__(self, eps: float = 1e-6):
46
+ super().__init__()
47
+ self.eps = eps
48
+
49
+ def _norm(self, x):
50
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
51
+
52
+ def forward(self, x):
53
+ return self._norm(x.float()).type_as(x)
54
+
55
+
56
+ class MobileMoERMSNorm(nn.Module):
57
+ """RMS normalization with learnable scale."""
58
+
59
+ def __init__(self, hidden_size, eps=1e-5):
60
+ super().__init__()
61
+ self.eps = eps
62
+ self.weight = nn.Parameter(torch.ones(hidden_size))
63
+
64
+ def _norm(self, x):
65
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
66
+
67
+ def forward(self, x):
68
+ output = self._norm(x.float()).type_as(x)
69
+ return output * self.weight
70
+
71
+
72
+ class MobileMoERotaryEmbedding(nn.Module):
73
+ """Rotary Position Embedding (RoPE) with optional Llama3-style scaling."""
74
+
75
+ def __init__(self, config, device=None):
76
+ super().__init__()
77
+ self.rope_type = "llama3" if config.rope_scaling is not None else "default"
78
+ self.max_seq_len_cached = config.max_position_embeddings
79
+ self.config = config
80
+
81
+ dim = config.head_dim
82
+ base = config.rope_theta
83
+ inv_freq = 1.0 / (
84
+ base ** (torch.arange(0, dim, 2, dtype=torch.float, device=device) / dim)
85
+ )
86
+
87
+ # Llama3 rope scaling
88
+ self.attention_scaling = 1.0
89
+ if config.rope_scaling is not None:
90
+ factor = config.rope_scaling.get("factor", 1.0)
91
+ low_freq_factor = config.rope_scaling.get("low_freq_factor", 1.0)
92
+ high_freq_factor = config.rope_scaling.get("high_freq_factor", 4.0)
93
+ old_context_len = config.rope_scaling.get(
94
+ "original_max_position_embeddings", config.max_position_embeddings
95
+ )
96
+
97
+ low_freq_wavelen = old_context_len / low_freq_factor
98
+ high_freq_wavelen = old_context_len / high_freq_factor
99
+
100
+ new_freqs = []
101
+ for freq, wavelen in zip(inv_freq, 2 * math.pi / inv_freq):
102
+ if wavelen < high_freq_wavelen:
103
+ new_freqs.append(freq)
104
+ elif wavelen > low_freq_wavelen:
105
+ new_freqs.append(freq / factor)
106
+ else:
107
+ if high_freq_factor != low_freq_factor:
108
+ smooth = (old_context_len / wavelen - low_freq_factor) / (
109
+ high_freq_factor - low_freq_factor
110
+ )
111
+ new_freqs.append((1 - smooth) * freq / factor + smooth * freq)
112
+ else:
113
+ new_freqs.append(freq)
114
+ inv_freq = torch.tensor(new_freqs, dtype=inv_freq.dtype, device=device)
115
+ # attention_scaling stays 1.0 for llama3 rope type
116
+ # (factor ** 0.5 is only used for dynamic/yarn types)
117
+
118
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
119
+
120
+ @torch.no_grad()
121
+ def forward(self, x, position_ids):
122
+ inv_freq_expanded = (
123
+ self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
124
+ )
125
+ position_ids_expanded = position_ids[:, None, :].float()
126
+
127
+ device_type = (
128
+ x.device.type
129
+ if isinstance(x.device.type, str) and x.device.type != "mps"
130
+ else "cpu"
131
+ )
132
+ with torch.autocast(device_type=device_type, enabled=False):
133
+ freqs = (inv_freq_expanded.to(x.device) @ position_ids_expanded).transpose(
134
+ 1, 2
135
+ )
136
+ freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
137
+ freqs_cis = freqs_cis * self.attention_scaling
138
+
139
+ return freqs_cis
140
+
141
+
142
+ def _apply_rotary_emb(xq, xk, freqs_cis):
143
+ """Apply rotary embeddings using complex multiplication."""
144
+ xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
145
+ xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
146
+ xq_out = torch.view_as_real(xq_ * freqs_cis[:, :, None, :]).flatten(3)
147
+ xk_out = torch.view_as_real(xk_ * freqs_cis[:, :, None, :]).flatten(3)
148
+ return xq_out.type_as(xq), xk_out.type_as(xk)
149
+
150
+
151
+ def _repeat_kv(hidden_states, n_rep):
152
+ """Expand KV heads for grouped-query attention."""
153
+ batch, num_kv_heads, slen, head_dim = hidden_states.shape
154
+ if n_rep == 1:
155
+ return hidden_states
156
+ hidden_states = hidden_states[:, :, None, :, :].expand(
157
+ batch, num_kv_heads, n_rep, slen, head_dim
158
+ )
159
+ return hidden_states.reshape(batch, num_kv_heads * n_rep, slen, head_dim)
160
+
161
+
162
+ def _eager_attention_forward(
163
+ module, query, key, value, attention_mask, scaling, dropout=0.0, **kwargs
164
+ ):
165
+ """Eager attention forward (no FlashAttention dependency)."""
166
+ key_states = _repeat_kv(key, module.num_key_value_groups)
167
+ value_states = _repeat_kv(value, module.num_key_value_groups)
168
+
169
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
170
+ if attention_mask is not None:
171
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
172
+ attn_weights = attn_weights + causal_mask
173
+
174
+ attn_weights = F.softmax(attn_weights, dim=-1)
175
+ attn_weights = F.dropout(attn_weights, p=dropout, training=module.training)
176
+ attn_output = torch.matmul(attn_weights, value_states)
177
+ attn_output = attn_output.transpose(1, 2).contiguous()
178
+
179
+ return attn_output, attn_weights
180
+
181
+
182
+ # ---------------------------------------------------------------------------
183
+ # MLP / Expert layers
184
+ # ---------------------------------------------------------------------------
185
+
186
+
187
+ # ---------------------------------------------------------------------------
188
+ # Optional INT4 checkpoint support
189
+ #
190
+ # Checkpoints written by convert_rlformers_qat_to_hf_int4_quantized.py store
191
+ # <base>.qweight int8, values in [-8, 7]
192
+ # <base>.weight_scale fp32, last dim // group_size
193
+ # in place of a bf16 <base>.weight, and declare a "quantization" block in
194
+ # config.json.
195
+ #
196
+ # BACKWARD COMPATIBILITY: everything below is inert unless config.quantization
197
+ # is present. `_quant_group_size()` returns None for every existing bf16
198
+ # checkpoint, in which case the modules built are exactly nn.Linear /
199
+ # nn.Embedding / nn.Parameter as before -- same classes, same names, same
200
+ # behaviour. Nothing in the bf16 load path is touched.
201
+ #
202
+ # When quantised, the dense `weight` stays a real nn.Parameter (so weight
203
+ # tying, _tp_plan and vLLM's Transformers backend keep working) and is filled
204
+ # from the int8 buffers on first forward, after which the buffers are freed.
205
+ # Runtime memory is therefore bf16; the saving is in the checkpoint.
206
+ # ---------------------------------------------------------------------------
207
+
208
+ DEFAULT_QUANT_GROUP_SIZE = 32
209
+
210
+
211
+ def _quant_group_size(config):
212
+ """Group size if this config describes an INT4 checkpoint, else None."""
213
+ q = getattr(config, "quantization", None)
214
+ if not q:
215
+ return None
216
+ if isinstance(q, dict):
217
+ return int(q.get("group_size", DEFAULT_QUANT_GROUP_SIZE))
218
+ return DEFAULT_QUANT_GROUP_SIZE
219
+
220
+
221
+ def _quant_embedding_group_size(config):
222
+ q = getattr(config, "quantization", None)
223
+ if not q:
224
+ return None
225
+ if isinstance(q, dict):
226
+ return int(q.get("embedding_group_size", _quant_group_size(config)))
227
+ return DEFAULT_QUANT_GROUP_SIZE
228
+
229
+
230
+ def _quant_packed(config):
231
+ """True if qweight tensors hold two 4-bit values per byte."""
232
+ q = getattr(config, "quantization", None)
233
+ return bool(q.get("packed")) if isinstance(q, dict) else False
234
+
235
+
236
+ def _quant_scale_dtype(config):
237
+ q = getattr(config, "quantization", None)
238
+ name = q.get("scale_dtype", "float32") if isinstance(q, dict) else "float32"
239
+ return {"float32": torch.float32, "fp32": torch.float32,
240
+ "float16": torch.float16, "fp16": torch.float16,
241
+ "bfloat16": torch.bfloat16, "bf16": torch.bfloat16}.get(name, torch.float32)
242
+
243
+
244
+ def _unpack_int4(p):
245
+ """uint8/int8 [..., N/2] with two nibbles per byte -> int8 [..., N] in [-8,7].
246
+
247
+ Low nibble is the even index, high nibble the odd index (the order the
248
+ packer writes them).
249
+ """
250
+ b = p.to(torch.uint8)
251
+ lo = b & 0x0F
252
+ hi = (b >> 4) & 0x0F
253
+ out = torch.stack([lo, hi], dim=-1).reshape(*p.shape[:-1], p.shape[-1] * 2)
254
+ out = out.to(torch.int16)
255
+ return torch.where(out > 7, out - 16, out).to(torch.int8)
256
+
257
+
258
+ def _dequant_group(q, scale, group_size, packed=False):
259
+ """q [..., N] (or [..., N/2] if packed), scale [..., N/gs] -> float [..., N]."""
260
+ if packed:
261
+ q = _unpack_int4(q)
262
+ shape = q.shape
263
+ if shape[-1] % group_size:
264
+ raise ValueError(f"last dim {shape[-1]} not divisible by group_size {group_size}")
265
+ x = q.reshape(*shape[:-1], shape[-1] // group_size, group_size).float()
266
+ return (x * scale.unsqueeze(-1).float()).reshape(shape)
267
+
268
+
269
+ class _LazyDequantMixin:
270
+ """Fills dense parameters from int8 buffers on first use, then frees them."""
271
+
272
+ # (dense_attr, qweight_buffer, scale_buffer)
273
+ _quant_slots = (("weight", "qweight", "weight_scale"),)
274
+
275
+ def _materialize_quantized(self):
276
+ if getattr(self, "_quant_done", False):
277
+ return
278
+ gs = self.quant_group_size
279
+ with torch.no_grad():
280
+ for dense, qn, sn in self._quant_slots:
281
+ q, s = getattr(self, qn), getattr(self, sn)
282
+ if q is None or q.numel() == 0:
283
+ continue
284
+ target = getattr(self, dense)
285
+ target.data.copy_(
286
+ _dequant_group(q, s, gs, getattr(self, "quant_packed", False)).to(target.dtype)
287
+ )
288
+ # release the int8/fp32 staging buffers
289
+ setattr(self, qn, nn.Parameter(torch.empty(0, dtype=q.dtype, device=q.device), requires_grad=False))
290
+ setattr(self, sn, nn.Parameter(torch.empty(0, dtype=s.dtype, device=s.device), requires_grad=False))
291
+ self._quant_done = True
292
+
293
+
294
+ class MobileMoEInt4Linear(_LazyDequantMixin, nn.Linear):
295
+ """nn.Linear whose weight arrives as int4 (int8 container) + per-group scale."""
296
+
297
+ def __init__(self, in_features, out_features, bias=False, group_size=DEFAULT_QUANT_GROUP_SIZE,
298
+ packed=False, scale_dtype=torch.float32):
299
+ super().__init__(in_features, out_features, bias=bias)
300
+ self.quant_group_size = group_size
301
+ self.quant_packed = packed
302
+ n = in_features // 2 if packed else in_features
303
+ self.qweight = nn.Parameter(
304
+ torch.zeros(out_features, n, dtype=torch.uint8 if packed else torch.int8),
305
+ requires_grad=False,
306
+ )
307
+ self.weight_scale = nn.Parameter(
308
+ torch.zeros(out_features, in_features // group_size, dtype=scale_dtype),
309
+ requires_grad=False,
310
+ )
311
+ self._quant_done = False
312
+
313
+ def forward(self, x):
314
+ self._materialize_quantized()
315
+ return super().forward(x)
316
+
317
+
318
+ class MobileMoEInt4Embedding(_LazyDequantMixin, nn.Embedding):
319
+ """nn.Embedding whose weight arrives as int4 (int8 container) + per-group scale.
320
+
321
+ `weight` remains an nn.Parameter, so `_tied_weights_keys = ["lm_head.weight"]`
322
+ ties lm_head to the *same* tensor; materialising in place therefore updates
323
+ both. embed_tokens always runs before lm_head in the forward pass.
324
+ """
325
+
326
+ def __init__(self, num_embeddings, embedding_dim, padding_idx=None,
327
+ group_size=DEFAULT_QUANT_GROUP_SIZE, packed=False, scale_dtype=torch.float32):
328
+ super().__init__(num_embeddings, embedding_dim, padding_idx)
329
+ self.quant_group_size = group_size
330
+ self.quant_packed = packed
331
+ n = embedding_dim // 2 if packed else embedding_dim
332
+ self.qweight = nn.Parameter(
333
+ torch.zeros(num_embeddings, n, dtype=torch.uint8 if packed else torch.int8),
334
+ requires_grad=False,
335
+ )
336
+ self.weight_scale = nn.Parameter(
337
+ torch.zeros(num_embeddings, embedding_dim // group_size, dtype=scale_dtype),
338
+ requires_grad=False,
339
+ )
340
+ self._quant_done = False
341
+
342
+ def forward(self, x):
343
+ self._materialize_quantized()
344
+ return super().forward(x)
345
+
346
+
347
+ def _make_linear(config, in_features, out_features, bias=False):
348
+ """nn.Linear for bf16 checkpoints, MobileMoEInt4Linear for INT4 ones."""
349
+ gs = _quant_group_size(config)
350
+ if gs is None or in_features % gs:
351
+ return nn.Linear(in_features, out_features, bias=bias)
352
+ return MobileMoEInt4Linear(in_features, out_features, bias=bias, group_size=gs,
353
+ packed=_quant_packed(config), scale_dtype=_quant_scale_dtype(config))
354
+
355
+
356
+ class MobileMoEMLP(nn.Module):
357
+ """SwiGLU feed-forward network."""
358
+
359
+ def __init__(self, config, intermediate_size=None):
360
+ super().__init__()
361
+ if intermediate_size is None:
362
+ intermediate_size = config.intermediate_size
363
+ self.gate_proj = _make_linear(config, config.hidden_size, intermediate_size)
364
+ self.up_proj = _make_linear(config, config.hidden_size, intermediate_size)
365
+ self.down_proj = _make_linear(config, intermediate_size, config.hidden_size)
366
+ self.act_fn = nn.SiLU()
367
+
368
+ def forward(self, x):
369
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
370
+
371
+
372
+ class MobileMoEExperts(nn.Module):
373
+ """Parameter container for routed experts (fused gate+up projection)."""
374
+
375
+ def __init__(self, config):
376
+ super().__init__()
377
+ self.num_experts = config.num_local_experts
378
+ self.hidden_size = config.hidden_size
379
+ self.expert_dim = config.intermediate_size
380
+ self.gate_up_proj = nn.Parameter(
381
+ torch.empty(self.num_experts, self.hidden_size, 2 * self.expert_dim)
382
+ )
383
+ self.down_proj = nn.Parameter(
384
+ torch.empty(self.num_experts, self.expert_dim, self.hidden_size)
385
+ )
386
+ self.act_fn = nn.SiLU()
387
+
388
+ # INT4 staging buffers (only for quantised checkpoints; see _make_linear).
389
+ # Grouping is over the LAST dim, which for these [E, in, out] tensors is
390
+ # the OUTPUT dim -- inherited from the rlformers layout, where the expert
391
+ # matmul is `x @ W` rather than F.linear.
392
+ gs = _quant_group_size(config)
393
+ if gs is not None and (2 * self.expert_dim) % gs == 0 and self.hidden_size % gs == 0:
394
+ pk = _quant_packed(config); sd = _quant_scale_dtype(config)
395
+ qdt = torch.uint8 if pk else torch.int8
396
+ gu_n = (2 * self.expert_dim) // 2 if pk else 2 * self.expert_dim
397
+ dn_n = self.hidden_size // 2 if pk else self.hidden_size
398
+ self.quant_group_size = gs
399
+ self.quant_packed = pk
400
+ self.gate_up_qweight = nn.Parameter(
401
+ torch.zeros(self.num_experts, self.hidden_size, gu_n, dtype=qdt), requires_grad=False
402
+ )
403
+ self.gate_up_scale = nn.Parameter(
404
+ torch.zeros(self.num_experts, self.hidden_size, (2 * self.expert_dim) // gs, dtype=sd),
405
+ requires_grad=False,
406
+ )
407
+ self.down_qweight = nn.Parameter(
408
+ torch.zeros(self.num_experts, self.expert_dim, dn_n, dtype=qdt), requires_grad=False
409
+ )
410
+ self.down_scale = nn.Parameter(
411
+ torch.zeros(self.num_experts, self.expert_dim, self.hidden_size // gs, dtype=sd), requires_grad=False
412
+ )
413
+ self._quant_done = False
414
+ else:
415
+ self.quant_group_size = None
416
+ self.quant_packed = False
417
+ self._quant_done = True
418
+
419
+ _quant_slots = (
420
+ ("gate_up_proj", "gate_up_qweight", "gate_up_scale"),
421
+ ("down_proj", "down_qweight", "down_scale"),
422
+ )
423
+
424
+ def _materialize_quantized(self):
425
+ if self._quant_done or self.quant_group_size is None:
426
+ return
427
+ _LazyDequantMixin._materialize_quantized(self)
428
+
429
+
430
+ class MobileMoERouter(nn.Linear):
431
+ """Router for expert selection."""
432
+
433
+ def __init__(self, config):
434
+ super().__init__(config.hidden_size, config.num_local_experts, bias=False)
435
+ self.num_experts = config.num_local_experts
436
+ self.top_k = config.num_experts_per_tok
437
+
438
+
439
+ # ---------------------------------------------------------------------------
440
+ # MoE layer (custom MobileMoE routing)
441
+ # ---------------------------------------------------------------------------
442
+
443
+
444
+ class MobileMoETextMoe(nn.Module):
445
+ """MobileMoE Mixture-of-Experts layer.
446
+
447
+ Routing: sigmoid -> topk -> normalize -> scale
448
+ Gating: postgate — routing scores applied to expert OUTPUT
449
+ Shared expert: always-active dense FFN with independent intermediate dimension
450
+ """
451
+
452
+ def __init__(self, config):
453
+ super().__init__()
454
+ self.top_k = config.num_experts_per_tok
455
+ self.hidden_dim = config.hidden_size
456
+ self.num_experts = config.num_local_experts
457
+ self.routed_scaling_factor = getattr(config, "routed_scaling_factor", 2.5)
458
+ self.norm_topk_prob = getattr(config, "norm_topk_prob", True)
459
+
460
+ self.experts = MobileMoEExperts(config)
461
+ self.router = MobileMoERouter(config)
462
+
463
+ # Expert bias for load-balancing-free routing
464
+ # Added post-sigmoid, pre-topk: affects expert SELECTION only, not weights
465
+ self.expert_bias = nn.Parameter(
466
+ torch.zeros(config.num_local_experts),
467
+ requires_grad=False,
468
+ )
469
+
470
+ shared_size = getattr(config, "intermediate_size_mlp", config.intermediate_size)
471
+ self.shared_expert = MobileMoEMLP(config, intermediate_size=shared_size)
472
+
473
+ def forward(self, hidden_states):
474
+ hidden_states = hidden_states.reshape(-1, self.hidden_dim)
475
+ self.experts._materialize_quantized()
476
+
477
+ # Custom routing order (bypass default router forward)
478
+ # Compute router matmul in fp32 for numerical stability
479
+ router_logits = F.linear(hidden_states.float(), self.router.weight.float())
480
+
481
+ # MobileMoE routing: sigmoid FIRST, then topk
482
+ scores = torch.sigmoid(router_logits.float())
483
+
484
+ # Add expert bias for topk selection (load-balancing-free routing)
485
+ # Bias only affects which experts are SELECTED, not the routing weights
486
+ scores_for_topk = scores + self.expert_bias
487
+ _, topk_indices = torch.topk(scores_for_topk, self.top_k, dim=-1)
488
+ # Gather UNBIASED scores at selected indices
489
+ topk_scores = scores.gather(1, topk_indices)
490
+
491
+ # Normalize per-token and scale
492
+ if self.norm_topk_prob:
493
+ topk_scores = topk_scores / (topk_scores.sum(dim=-1, keepdim=True) + 1e-20)
494
+ topk_scores = topk_scores * self.routed_scaling_factor
495
+
496
+ # Sparse per-expert loop with postgate scoring (reference implementation).
497
+ # Processes only the top-k selected tokens per expert.
498
+ out = torch.zeros_like(hidden_states)
499
+ for e in range(self.num_experts):
500
+ mask = (topk_indices == e).any(dim=-1)
501
+ if not mask.any():
502
+ continue
503
+ idx = mask.nonzero(as_tuple=True)[0]
504
+ x_sel = hidden_states[idx]
505
+
506
+ # Expert FFN: gate_up_proj[e] is [D, 2F], down_proj[e] is [F, D]
507
+ gate_up = x_sel @ self.experts.gate_up_proj[e]
508
+ gate, up = gate_up.chunk(2, dim=-1)
509
+ expert_out = (self.experts.act_fn(gate) * up) @ self.experts.down_proj[e]
510
+
511
+ # Postgate: score applied to expert OUTPUT
512
+ pos = (topk_indices[idx] == e).nonzero(as_tuple=True)
513
+ weights = topk_scores[idx][pos[0], pos[1]]
514
+ out[idx] += expert_out * weights.unsqueeze(-1)
515
+
516
+ # Shared expert (additive, applied to all tokens)
517
+ out = out + self.shared_expert(hidden_states)
518
+
519
+ return out, router_logits
520
+
521
+
522
+ # ---------------------------------------------------------------------------
523
+ # Attention
524
+ # ---------------------------------------------------------------------------
525
+
526
+
527
+ class MobileMoEAttention(nn.Module):
528
+ """Multi-head grouped-query attention with RoPE and optional QK L2 norm."""
529
+
530
+ def __init__(self, config, layer_idx):
531
+ super().__init__()
532
+ self.config = config
533
+ self.layer_idx = layer_idx
534
+ self.head_dim = getattr(
535
+ config, "head_dim", config.hidden_size // config.num_attention_heads
536
+ )
537
+ self.num_attention_heads = config.num_attention_heads
538
+ self.num_key_value_groups = (
539
+ config.num_attention_heads // config.num_key_value_heads
540
+ )
541
+ self.num_key_value_heads = config.num_key_value_heads
542
+ self.scaling = self.head_dim**-0.5
543
+ self.attn_scale = config.attn_scale
544
+ self.floor_scale = config.floor_scale
545
+ self.attn_temperature_tuning = config.attn_temperature_tuning
546
+ self.attention_dropout = config.attention_dropout
547
+ self.is_causal = True
548
+ self.use_rope = config.no_rope_layers[layer_idx]
549
+
550
+ self.q_proj = _make_linear(
551
+ config,
552
+ config.hidden_size,
553
+ config.num_attention_heads * self.head_dim,
554
+ bias=config.attention_bias,
555
+ )
556
+ self.k_proj = _make_linear(
557
+ config,
558
+ config.hidden_size,
559
+ config.num_key_value_heads * self.head_dim,
560
+ bias=config.attention_bias,
561
+ )
562
+ self.v_proj = _make_linear(
563
+ config,
564
+ config.hidden_size,
565
+ config.num_key_value_heads * self.head_dim,
566
+ bias=config.attention_bias,
567
+ )
568
+ self.o_proj = _make_linear(
569
+ config,
570
+ config.num_attention_heads * self.head_dim,
571
+ config.hidden_size,
572
+ bias=config.attention_bias,
573
+ )
574
+
575
+ if config.use_qk_norm and self.use_rope:
576
+ self.qk_norm = MobileMoEL2Norm(config.rms_norm_eps)
577
+
578
+ def forward(
579
+ self,
580
+ hidden_states,
581
+ position_embeddings,
582
+ attention_mask=None,
583
+ past_key_values=None,
584
+ cache_position=None,
585
+ **kwargs,
586
+ ):
587
+ input_shape = hidden_states.shape[:-1]
588
+ hidden_shape = (*input_shape, -1, self.head_dim)
589
+
590
+ query_states = self.q_proj(hidden_states).view(hidden_shape)
591
+ key_states = self.k_proj(hidden_states).view(*input_shape, -1, self.head_dim)
592
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
593
+
594
+ if self.use_rope:
595
+ query_states, key_states = _apply_rotary_emb(
596
+ query_states, key_states, position_embeddings.to(query_states.device)
597
+ )
598
+
599
+ if hasattr(self, "qk_norm"):
600
+ query_states = self.qk_norm(query_states)
601
+ key_states = self.qk_norm(key_states)
602
+
603
+ if self.attn_temperature_tuning and not self.use_rope:
604
+ attn_scales = (
605
+ torch.log1p(
606
+ torch.floor((cache_position.float() + 1.0) / self.floor_scale)
607
+ )
608
+ * self.attn_scale
609
+ + 1.0
610
+ )
611
+ attn_scales = attn_scales.view((1, input_shape[-1], 1, 1)).expand(
612
+ (*input_shape, 1, 1)
613
+ )
614
+ query_states = (query_states * attn_scales).to(query_states.dtype)
615
+
616
+ query_states = query_states.transpose(1, 2)
617
+ key_states = key_states.transpose(1, 2)
618
+
619
+ if past_key_values is not None:
620
+ cache_kwargs = {"cache_position": cache_position}
621
+ key_states, value_states = past_key_values.update(
622
+ key_states, value_states, self.layer_idx, cache_kwargs
623
+ )
624
+
625
+ attention_interface: Callable = _eager_attention_forward
626
+ if self.config._attn_implementation != "eager":
627
+ if self.config._attn_implementation in ALL_ATTENTION_FUNCTIONS:
628
+ attention_interface = ALL_ATTENTION_FUNCTIONS[
629
+ self.config._attn_implementation
630
+ ]
631
+ attn_output, attn_weights = attention_interface(
632
+ self,
633
+ query_states,
634
+ key_states,
635
+ value_states,
636
+ attention_mask,
637
+ dropout=0.0 if not self.training else self.attention_dropout,
638
+ scaling=self.scaling,
639
+ **kwargs,
640
+ )
641
+
642
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
643
+ attn_output = self.o_proj(attn_output)
644
+ return attn_output, attn_weights
645
+
646
+
647
+ # ---------------------------------------------------------------------------
648
+ # Decoder layer
649
+ # ---------------------------------------------------------------------------
650
+
651
+
652
+ class MobileMoEDecoderLayer(nn.Module):
653
+ """MobileMoE decoder layer with custom MoE routing."""
654
+
655
+ def __init__(self, config, layer_idx):
656
+ super().__init__()
657
+ self.hidden_size = config.hidden_size
658
+ self.layer_idx = layer_idx
659
+ self.attention_type = config.layer_types[layer_idx]
660
+ self.self_attn = MobileMoEAttention(config, layer_idx)
661
+ self.is_moe_layer = layer_idx in config.moe_layers
662
+ if self.is_moe_layer:
663
+ self.feed_forward = MobileMoETextMoe(config)
664
+ else:
665
+ self.feed_forward = MobileMoEMLP(
666
+ config, intermediate_size=config.intermediate_size_mlp
667
+ )
668
+
669
+ self.input_layernorm = MobileMoERMSNorm(
670
+ config.hidden_size, eps=config.rms_norm_eps
671
+ )
672
+ self.post_attention_layernorm = MobileMoERMSNorm(
673
+ config.hidden_size, eps=config.rms_norm_eps
674
+ )
675
+
676
+ def forward(
677
+ self,
678
+ hidden_states,
679
+ attention_mask=None,
680
+ position_ids=None,
681
+ past_key_values=None,
682
+ use_cache=False,
683
+ cache_position=None,
684
+ position_embeddings=None,
685
+ **kwargs,
686
+ ):
687
+ residual = hidden_states
688
+ hidden_states = self.input_layernorm(hidden_states)
689
+
690
+ # Self Attention
691
+ attn_output, _ = self.self_attn(
692
+ hidden_states=hidden_states,
693
+ position_embeddings=position_embeddings,
694
+ attention_mask=attention_mask,
695
+ past_key_values=past_key_values,
696
+ cache_position=cache_position,
697
+ **kwargs,
698
+ )
699
+ hidden_states = residual + attn_output
700
+
701
+ # Feed-Forward
702
+ residual = hidden_states
703
+ hidden_states = self.post_attention_layernorm(hidden_states)
704
+ hidden_states = self.feed_forward(hidden_states)
705
+ if self.is_moe_layer:
706
+ hidden_states, _ = hidden_states
707
+ hidden_states = residual + hidden_states.view(residual.shape)
708
+
709
+ return hidden_states
710
+
711
+
712
+ # ---------------------------------------------------------------------------
713
+ # Full model
714
+ # ---------------------------------------------------------------------------
715
+
716
+
717
+ class MobileMoEPreTrainedModel(PreTrainedModel):
718
+ """Base class for MobileMoE models."""
719
+
720
+ config_class = MobileMoEConfig
721
+ base_model_prefix = "model"
722
+ supports_gradient_checkpointing = True
723
+ _skip_keys_device_placement = ["past_key_values"]
724
+ _supports_flash_attn = False
725
+ _supports_sdpa = True
726
+ _supports_attention_backend = True
727
+
728
+ def _init_weights(self, module):
729
+ std = self.config.initializer_range
730
+ if isinstance(module, nn.Linear):
731
+ module.weight.data.normal_(mean=0.0, std=std)
732
+ if module.bias is not None:
733
+ module.bias.data.zero_()
734
+ elif isinstance(module, nn.Embedding):
735
+ module.weight.data.normal_(mean=0.0, std=std)
736
+ if module.padding_idx is not None:
737
+ module.weight.data[module.padding_idx].zero_()
738
+ elif isinstance(module, MobileMoERMSNorm):
739
+ module.weight.data.fill_(1.0)
740
+ elif isinstance(module, MobileMoEExperts):
741
+ module.gate_up_proj.data.normal_(mean=0.0, std=std)
742
+ module.down_proj.data.normal_(mean=0.0, std=std)
743
+
744
+
745
+ class MobileMoETextModel(MobileMoEPreTrainedModel):
746
+ """MobileMoE text model."""
747
+
748
+ _no_split_modules = ["MobileMoEDecoderLayer"]
749
+
750
+ def __init__(self, config):
751
+ super().__init__(config)
752
+ self.padding_idx = config.pad_token_id
753
+ self.vocab_size = config.vocab_size
754
+ _egs = _quant_embedding_group_size(config)
755
+ if _egs is None or config.hidden_size % _egs:
756
+ self.embed_tokens = nn.Embedding(
757
+ config.vocab_size, config.hidden_size, self.padding_idx
758
+ )
759
+ else:
760
+ self.embed_tokens = MobileMoEInt4Embedding(
761
+ config.vocab_size, config.hidden_size, self.padding_idx, group_size=_egs,
762
+ packed=_quant_packed(config), scale_dtype=_quant_scale_dtype(config)
763
+ )
764
+ self.layers = nn.ModuleList(
765
+ [MobileMoEDecoderLayer(config, i) for i in range(config.num_hidden_layers)]
766
+ )
767
+ self.norm = MobileMoERMSNorm(config.hidden_size, eps=config.rms_norm_eps)
768
+ self.rotary_emb = MobileMoERotaryEmbedding(config)
769
+ self.gradient_checkpointing = False
770
+ self.post_init()
771
+
772
+ def forward(
773
+ self,
774
+ input_ids=None,
775
+ attention_mask=None,
776
+ position_ids=None,
777
+ past_key_values=None,
778
+ inputs_embeds=None,
779
+ use_cache=None,
780
+ cache_position=None,
781
+ **kwargs,
782
+ ):
783
+ if inputs_embeds is None:
784
+ inputs_embeds = self.embed_tokens(input_ids)
785
+
786
+ if use_cache and past_key_values is None:
787
+ past_key_values = DynamicCache(config=self.config)
788
+
789
+ if cache_position is None:
790
+ past_seen_tokens = (
791
+ past_key_values.get_seq_length() if past_key_values is not None else 0
792
+ )
793
+ cache_position = torch.arange(
794
+ past_seen_tokens,
795
+ past_seen_tokens + inputs_embeds.shape[1],
796
+ device=inputs_embeds.device,
797
+ )
798
+
799
+ if position_ids is None:
800
+ position_ids = cache_position.unsqueeze(0)
801
+
802
+ # Build causal mask
803
+ causal_mask = create_causal_mask(
804
+ config=self.config,
805
+ input_embeds=inputs_embeds,
806
+ attention_mask=attention_mask,
807
+ cache_position=cache_position,
808
+ past_key_values=past_key_values,
809
+ position_ids=position_ids,
810
+ )
811
+
812
+ hidden_states = inputs_embeds
813
+ freq_cis = self.rotary_emb(hidden_states, position_ids)
814
+
815
+ for decoder_layer in self.layers:
816
+ hidden_states = decoder_layer(
817
+ hidden_states,
818
+ attention_mask=causal_mask,
819
+ position_ids=position_ids,
820
+ past_key_values=past_key_values,
821
+ use_cache=use_cache,
822
+ cache_position=cache_position,
823
+ position_embeddings=freq_cis,
824
+ **kwargs,
825
+ )
826
+
827
+ hidden_states = self.norm(hidden_states)
828
+
829
+ return BaseModelOutputWithPast(
830
+ last_hidden_state=hidden_states,
831
+ past_key_values=past_key_values if use_cache else None,
832
+ )
833
+
834
+ def _build_causal_mask(
835
+ self, attention_mask, inputs_embeds, cache_position, past_key_values
836
+ ):
837
+ """Build 4D causal attention mask."""
838
+ dtype, device = inputs_embeds.dtype, inputs_embeds.device
839
+ min_dtype = torch.finfo(dtype).min
840
+ seq_length = inputs_embeds.shape[1]
841
+ target_length = (
842
+ cache_position[-1].item() + 1 if cache_position is not None else seq_length
843
+ )
844
+
845
+ # Create causal mask [1, 1, Q, K]
846
+ causal_mask = torch.full(
847
+ (seq_length, target_length),
848
+ fill_value=min_dtype,
849
+ dtype=dtype,
850
+ device=device,
851
+ )
852
+ if seq_length != 1:
853
+ causal_mask = torch.triu(
854
+ causal_mask, diagonal=target_length - seq_length + 1
855
+ )
856
+ causal_mask = (
857
+ causal_mask[None, None, :, :]
858
+ .expand(inputs_embeds.shape[0], 1, -1, -1)
859
+ .clone()
860
+ )
861
+
862
+ # Apply padding mask
863
+ if attention_mask is not None and attention_mask.dim() == 2:
864
+ mask_length = attention_mask.shape[-1]
865
+ padding_mask = attention_mask[:, None, None, :mask_length].eq(0)
866
+ causal_mask[:, :, :, :mask_length].masked_fill_(padding_mask, min_dtype)
867
+
868
+ return causal_mask
869
+
870
+
871
+ class MobileMoEForCausalLM(MobileMoEPreTrainedModel, GenerationMixin):
872
+ """MobileMoE causal language model for text generation."""
873
+
874
+ _no_split_modules = ["MobileMoEDecoderLayer"]
875
+ _tied_weights_keys = ["lm_head.weight"]
876
+ _tp_plan = {"lm_head": "colwise_rep"}
877
+
878
+ def __init__(self, config):
879
+ super().__init__(config)
880
+ self.model = MobileMoETextModel(config)
881
+ self.vocab_size = config.vocab_size
882
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
883
+ self.post_init()
884
+
885
+ def get_input_embeddings(self):
886
+ return self.model.embed_tokens
887
+
888
+ def set_input_embeddings(self, value):
889
+ self.model.embed_tokens = value
890
+
891
+ def get_output_embeddings(self):
892
+ return self.lm_head
893
+
894
+ def set_output_embeddings(self, new_embeddings):
895
+ self.lm_head = new_embeddings
896
+
897
+ def forward(
898
+ self,
899
+ input_ids=None,
900
+ attention_mask=None,
901
+ position_ids=None,
902
+ past_key_values=None,
903
+ inputs_embeds=None,
904
+ labels=None,
905
+ use_cache=None,
906
+ cache_position=None,
907
+ logits_to_keep=0,
908
+ **kwargs,
909
+ ):
910
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
911
+
912
+ outputs = self.model(
913
+ input_ids=input_ids,
914
+ attention_mask=attention_mask,
915
+ position_ids=position_ids,
916
+ past_key_values=past_key_values,
917
+ inputs_embeds=inputs_embeds,
918
+ use_cache=use_cache,
919
+ cache_position=cache_position,
920
+ )
921
+
922
+ hidden_states = outputs[0]
923
+ slice_indices = (
924
+ slice(-logits_to_keep, None)
925
+ if isinstance(logits_to_keep, int)
926
+ else logits_to_keep
927
+ )
928
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
929
+
930
+ loss = None
931
+ if labels is not None:
932
+ loss = self.loss_function(
933
+ logits=logits,
934
+ labels=labels,
935
+ vocab_size=self.config.vocab_size,
936
+ **kwargs,
937
+ )
938
+
939
+ return CausalLMOutputWithPast(
940
+ loss=loss,
941
+ logits=logits,
942
+ past_key_values=outputs.past_key_values,
943
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|begin_of_text|>",
3
+ "eos_token": "<|eot|>",
4
+ "pad_token": "<|end_of_text|>"
5
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "bos_token": "<|begin_of_text|>",
5
+ "eos_token": "<|eot|>",
6
+ "pad_token": "<|end_of_text|>",
7
+ "model_max_length": 8192,
8
+ "tokenizer_class": "PreTrainedTokenizerFast",
9
+ "clean_up_tokenization_spaces": true,
10
+ "chat_template": "{{ bos_token }}{% set loop_messages = messages %}{% for message in loop_messages %}{% set content = '<|header_start|>' + message['role'] + '<|header_end|>\n\n' %}{% if message['content'] is string %}{% set content = content + message['content'] %}{% else %}{% for item in message['content'] %}{% if item['type'] == 'text' %}{% set content = content + item['text'] %}{% endif %}{% endfor %}{% endif %}{{ content + '<|eot|>' }}{% endfor %}{% if add_generation_prompt %}{{ '<|header_start|>assistant<|header_end|>\n\n' }}{% endif %}",
11
+ "model_input_names": [
12
+ "input_ids",
13
+ "attention_mask"
14
+ ]
15
+ }