Text Generation
Transformers
Safetensors
PyTorch
English
mobilemoe
facebook
meta
mixture-of-experts
MoE
on-device
custom_code
Instructions to use ml-resources/MobileMoE-S-Base with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use ml-resources/MobileMoE-S-Base with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="ml-resources/MobileMoE-S-Base", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("ml-resources/MobileMoE-S-Base", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use ml-resources/MobileMoE-S-Base with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "ml-resources/MobileMoE-S-Base" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "ml-resources/MobileMoE-S-Base", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/ml-resources/MobileMoE-S-Base
- SGLang
How to use ml-resources/MobileMoE-S-Base with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "ml-resources/MobileMoE-S-Base" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "ml-resources/MobileMoE-S-Base", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "ml-resources/MobileMoE-S-Base" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "ml-resources/MobileMoE-S-Base", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use ml-resources/MobileMoE-S-Base with Docker Model Runner:
docker model run hf.co/ml-resources/MobileMoE-S-Base
Mirror facebook/MobileMoE-S-Base
Browse files- .gitattributes +1 -0
- LICENSE +124 -0
- README.md +184 -0
- config.json +87 -0
- configuration_mobilemoe.py +110 -0
- generation_config.json +9 -0
- mobilemoe_pareto.png +3 -0
- mobilemoe_recipe.png +0 -0
- model.safetensors +3 -0
- modeling_mobilemoe.py +721 -0
- special_tokens_map.json +4 -0
- tokenizer.json +0 -0
- tokenizer_config.json +13 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
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,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
---
|
| 14 |
+
> Mirror of [facebook/MobileMoE-S-Base](https://huggingface.co/facebook/MobileMoE-S-Base). All credit to the original authors. Not an official release from them. License unchanged (FAIR Noncommercial Research License, non-commercial use only); see `LICENSE`.
|
| 15 |
+
|
| 16 |
+
# MobileMoE-S (Base) Model Card
|
| 17 |
+
|
| 18 |
+
**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-S-Base** repository — the pre-trained 0.3B-active base model.
|
| 19 |
+
|
| 20 |
+
| | **S** | **M** | **L** |
|
| 21 |
+
|:---|:---:|:---:|:---:|
|
| 22 |
+
| Active / total params | 272M / 1.3B | 528M / 2.8B | 922M / 5.3B |
|
| 23 |
+
| Layers | 20 | 26 | 32 |
|
| 24 |
+
| Model dimension | 768 | 1024 | 1280 |
|
| 25 |
+
| Heads (Q / KV) | 12 / 4 | 16 / 4 | 20 / 4 |
|
| 26 |
+
| Routed experts | 60 | 60 | 60 |
|
| 27 |
+
| Top-k | 4 | 4 | 4 |
|
| 28 |
+
| INT4 weight memory | 0.68 GB | 1.48 GB | 2.75 GB |
|
| 29 |
+
| Base | **MobileMoE-S-Base** | [MobileMoE-M-Base](https://huggingface.co/facebook/MobileMoE-M-Base) | [MobileMoE-L-Base](https://huggingface.co/facebook/MobileMoE-L-Base) |
|
| 30 |
+
| 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) |
|
| 31 |
+
| QAT (INT4) | [MobileMoE-S-QAT](https://huggingface.co/facebook/MobileMoE-S-QAT) | [MobileMoE-M-QAT](https://huggingface.co/facebook/MobileMoE-M-QAT) | [MobileMoE-L-QAT](https://huggingface.co/facebook/MobileMoE-L-QAT) |
|
| 32 |
+
|
| 33 |
+
For the detailed technical report: 📝 [MobileMoE: Scaling On-Device Mixture of Experts](https://arxiv.org/abs/2605.27358)
|
| 34 |
+
|
| 35 |
+
For more versions, check out the 🤗 [MobileMoE Collection](https://huggingface.co/collections/facebook/mobilemoe)
|
| 36 |
+
|
| 37 |
+

|
| 38 |
+
|
| 39 |
+
**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).
|
| 40 |
+
|
| 41 |
+
## Key Features
|
| 42 |
+
|
| 43 |
+
- **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.
|
| 44 |
+
- **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.
|
| 45 |
+
- **Four-stage recipe.** Pre-training → mid-training → instruction fine-tuning → INT4 quantization-aware training, all on open-source datasets.
|
| 46 |
+
|
| 47 |
+
## Model Information
|
| 48 |
+
|
| 49 |
+
**Model:** MobileMoE-S-Base (pre-trained + mid-trained)<br>
|
| 50 |
+
**Active Parameters:** 272M<br>
|
| 51 |
+
**Total Parameters:** 1.3B<br>
|
| 52 |
+
**Layers:** 20<br>
|
| 53 |
+
**Model Dimension:** 768<br>
|
| 54 |
+
**Attention Heads:** 12<br>
|
| 55 |
+
**KV Heads:** 4 (GQA)<br>
|
| 56 |
+
**Head Dimension:** 64<br>
|
| 57 |
+
**Routed Experts:** 60 (fine-grained, FFN hidden dim 384 each)<br>
|
| 58 |
+
**Active Experts per Token:** 4 (top-k sigmoid routing, with normalization)<br>
|
| 59 |
+
**Shared Expert:** 1, always on (FFN hidden dim 1536)<br>
|
| 60 |
+
**Vocabulary Size:** 128,256<br>
|
| 61 |
+
**Other Features:** QK-Norm, tied input/output embeddings, RoPE (θ = 500,000)<br>
|
| 62 |
+
**Input Modality:** Text<br>
|
| 63 |
+
**Output Modality:** Text<br>
|
| 64 |
+
**Languages:** English<br>
|
| 65 |
+
**Training Stages:** Pre-training → mid-training<br>
|
| 66 |
+
**Context Length:** 8,192 tokens<br>
|
| 67 |
+
**Precision:** BF16<br>
|
| 68 |
+
**Model Developer:** Meta<br>
|
| 69 |
+
**Model Release Date:** Aug 2026<br>
|
| 70 |
+
**License:** MobileMoE is FAIR NC licensed
|
| 71 |
+
|
| 72 |
+
## Results
|
| 73 |
+
|
| 74 |
+
All numbers below are for the **base (pre-trained)** 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.
|
| 75 |
+
|
| 76 |
+
### Foundational benchmarks
|
| 77 |
+
|
| 78 |
+
| Capability | Benchmark | Gemma 3 270M | SmolLM2 360M | **MobileMoE-S** |
|
| 79 |
+
|:---|:---|:---:|:---:|:---:|
|
| 80 |
+
| *Active / total params* | | 270M | 362M | **272M / 1.3B** |
|
| 81 |
+
| Commonsense Reasoning | HellaSwag | 41.4 | 56.5 | **58.9** |
|
| 82 |
+
| | PIQA | 68.3 | 71.7 | **75.4** |
|
| 83 |
+
| | SIQA | 40.2 | 40.7 | **46.8** |
|
| 84 |
+
| | WinoGrande | 53.7 | **59.0** | 58.6 |
|
| 85 |
+
| Knowledge | MMLU (5-shot) | 26.7 | 25.2 | **43.7** |
|
| 86 |
+
| | NaturalQuestions (5-shot) | 4.1 | 7.4 | **12.6** |
|
| 87 |
+
| | TriviaQA (5-shot) | 14.3 | 26.8 | **33.2** |
|
| 88 |
+
| Science | ARC-Challenge (25-shot) | 29.4 | 40.5 | **46.5** |
|
| 89 |
+
| | ARC-Easy | 56.8 | 68.1 | **73.9** |
|
| 90 |
+
| | OpenBookQA | 30.4 | **37.6** | 34.6 |
|
| 91 |
+
| Reading | BoolQ | 58.3 | **61.8** | 60.2 |
|
| 92 |
+
| | DROP (3-shot) | 14.2 | 17.9 | **39.0** |
|
| 93 |
+
| Reasoning | BIG-Bench Hard (3-shot) | 29.5 | 31.7 | **31.8** |
|
| 94 |
+
| | GSM8K (8-shot) | 1.8 | 5.3 | **36.2** |
|
| 95 |
+
| **Average** | | 33.5 | 39.3 | **46.5** |
|
| 96 |
+
|
| 97 |
+
## Training
|
| 98 |
+
|
| 99 |
+
MobileMoE uses a four-stage recipe. This checkpoint is the output of stage 2 (mid-training).
|
| 100 |
+
|
| 101 |
+

|
| 102 |
+
|
| 103 |
+
**MobileMoE four-stage training recipe:** pre-training (PT) → mid-training (MT) → instruct supervised fine-tuning (SFT) → quantization-aware training (QAT) with INT4 precision.
|
| 104 |
+
|
| 105 |
+
| | **Pre-training** | **Mid-training** | SFT | QAT |
|
| 106 |
+
|---|---|---|---|---|
|
| 107 |
+
| Context length | **2,048** | **8,192** | 8,192 | 8,192 |
|
| 108 |
+
| Total tokens | **~6T** | **~500B** | ~126B | ~21B |
|
| 109 |
+
| Peak learning rate | **4×10<sup>-4</sup>** | **4×10<sup>-5</sup>** | 4×10<sup>-6</sup> | 4×10<sup>-6</sup> |
|
| 110 |
+
| LR schedule | **Cosine** | **Linear** | Cosine | Cosine |
|
| 111 |
+
| Token dispatch | **drop-and-pad** | **drop-and-pad** | dropless | dropless |
|
| 112 |
+
|
| 113 |
+
## How to use
|
| 114 |
+
|
| 115 |
+
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`).
|
| 116 |
+
|
| 117 |
+
### Requirements
|
| 118 |
+
|
| 119 |
+
```bash
|
| 120 |
+
pip install "torch>=2.1" "transformers>=4.57" "safetensors>=0.4" "accelerate>=1.0"
|
| 121 |
+
```
|
| 122 |
+
|
| 123 |
+
Verified with the following versions:
|
| 124 |
+
|
| 125 |
+
| Package | Version |
|
| 126 |
+
|---|---|
|
| 127 |
+
| `torch` | 2.8.0 (cu128) |
|
| 128 |
+
| `transformers` | 4.57.6 |
|
| 129 |
+
| `tokenizers` | 0.22.2 |
|
| 130 |
+
| `safetensors` | 0.7.0 |
|
| 131 |
+
| `accelerate` | 1.13.0 |
|
| 132 |
+
|
| 133 |
+
For batch evaluation we recommend vLLM (≥ 0.10.2) with `enforce_eager=True`.
|
| 134 |
+
|
| 135 |
+
### Text generation
|
| 136 |
+
|
| 137 |
+
This is a **base model** — it has no chat template and is not instruction-tuned. Prompt it with plain text continuation:
|
| 138 |
+
|
| 139 |
+
```python
|
| 140 |
+
import torch
|
| 141 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 142 |
+
|
| 143 |
+
MODEL_ID = "facebook/MobileMoE-S-Base"
|
| 144 |
+
|
| 145 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 146 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 147 |
+
MODEL_ID,
|
| 148 |
+
trust_remote_code=True,
|
| 149 |
+
dtype=torch.bfloat16,
|
| 150 |
+
)
|
| 151 |
+
model.to("cuda" if torch.cuda.is_available() else "cpu")
|
| 152 |
+
model.eval()
|
| 153 |
+
|
| 154 |
+
prompt = "Why are open-source on-device language models great?"
|
| 155 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 156 |
+
|
| 157 |
+
outputs = model.generate(
|
| 158 |
+
input_ids=inputs["input_ids"],
|
| 159 |
+
attention_mask=inputs["attention_mask"],
|
| 160 |
+
max_new_tokens=64,
|
| 161 |
+
do_sample=False,
|
| 162 |
+
temperature=None,
|
| 163 |
+
top_p=None,
|
| 164 |
+
pad_token_id=tokenizer.eos_token_id,
|
| 165 |
+
)
|
| 166 |
+
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
|
| 167 |
+
```
|
| 168 |
+
|
| 169 |
+
**Known issues.** 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.
|
| 170 |
+
|
| 171 |
+
## Citation
|
| 172 |
+
|
| 173 |
+
```bibtex
|
| 174 |
+
@article{chen2026mobilemoe,
|
| 175 |
+
title={MobileMoE: Scaling On-Device Mixture of Experts},
|
| 176 |
+
author={Chen, Yanbei and Huang, Hanxian and Chang, Ernie and Szwejbka, Jacob and Desai, Digant and Liu, Zechun and Chandra, Vikas and Krishnamoorthi, Raghuraman},
|
| 177 |
+
journal={arXiv preprint arXiv:2605.27358},
|
| 178 |
+
year={2026}
|
| 179 |
+
}
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
## License
|
| 183 |
+
|
| 184 |
+
MobileMoE is distributed under the [FAIR Noncommercial Research License](https://huggingface.co/facebook/MobileMoE-S-Base/blob/main/LICENSE).
|
config.json
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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": 128001,
|
| 14 |
+
"hidden_size": 768,
|
| 15 |
+
"intermediate_size": 384,
|
| 16 |
+
"intermediate_size_mlp": 1536,
|
| 17 |
+
"num_hidden_layers": 20,
|
| 18 |
+
"num_attention_heads": 12,
|
| 19 |
+
"num_key_value_heads": 4,
|
| 20 |
+
"head_dim": 64,
|
| 21 |
+
"hidden_act": "silu",
|
| 22 |
+
"max_position_embeddings": 8192,
|
| 23 |
+
"rms_norm_eps": 1e-05,
|
| 24 |
+
"rope_theta": 500000.0,
|
| 25 |
+
"rope_scaling": {
|
| 26 |
+
"rope_type": "llama3",
|
| 27 |
+
"factor": 16,
|
| 28 |
+
"original_max_position_embeddings": 8192,
|
| 29 |
+
"low_freq_factor": 1.0,
|
| 30 |
+
"high_freq_factor": 1.0
|
| 31 |
+
},
|
| 32 |
+
"num_local_experts": 60,
|
| 33 |
+
"num_experts_per_tok": 4,
|
| 34 |
+
"interleave_moe_layer_step": 1,
|
| 35 |
+
"no_rope_layers": [
|
| 36 |
+
1,
|
| 37 |
+
1,
|
| 38 |
+
1,
|
| 39 |
+
1,
|
| 40 |
+
1,
|
| 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 |
+
],
|
| 57 |
+
"layer_types": [
|
| 58 |
+
"full_attention",
|
| 59 |
+
"full_attention",
|
| 60 |
+
"full_attention",
|
| 61 |
+
"full_attention",
|
| 62 |
+
"full_attention",
|
| 63 |
+
"full_attention",
|
| 64 |
+
"full_attention",
|
| 65 |
+
"full_attention",
|
| 66 |
+
"full_attention",
|
| 67 |
+
"full_attention",
|
| 68 |
+
"full_attention",
|
| 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 |
+
],
|
| 79 |
+
"use_qk_norm": true,
|
| 80 |
+
"attn_temperature_tuning": false,
|
| 81 |
+
"tie_word_embeddings": true,
|
| 82 |
+
"torch_dtype": "bfloat16",
|
| 83 |
+
"attention_bias": false,
|
| 84 |
+
"attention_dropout": 0.0,
|
| 85 |
+
"routed_scaling_factor": 2.5,
|
| 86 |
+
"norm_topk_prob": true
|
| 87 |
+
}
|
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,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 128000,
|
| 4 |
+
"eos_token_id": 128001,
|
| 5 |
+
"do_sample": true,
|
| 6 |
+
"temperature": 0.6,
|
| 7 |
+
"top_p": 0.9,
|
| 8 |
+
"transformers_version": "4.57.6"
|
| 9 |
+
}
|
mobilemoe_pareto.png
ADDED
|
Git LFS Details
|
mobilemoe_recipe.png
ADDED
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:69d09b2b3e4845f7e44831799c74df45752189921021c039752ced2c53d319ac
|
| 3 |
+
size 2526780232
|
modeling_mobilemoe.py
ADDED
|
@@ -0,0 +1,721 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
class MobileMoEMLP(nn.Module):
|
| 188 |
+
"""SwiGLU feed-forward network."""
|
| 189 |
+
|
| 190 |
+
def __init__(self, config, intermediate_size=None):
|
| 191 |
+
super().__init__()
|
| 192 |
+
if intermediate_size is None:
|
| 193 |
+
intermediate_size = config.intermediate_size
|
| 194 |
+
self.gate_proj = nn.Linear(config.hidden_size, intermediate_size, bias=False)
|
| 195 |
+
self.up_proj = nn.Linear(config.hidden_size, intermediate_size, bias=False)
|
| 196 |
+
self.down_proj = nn.Linear(intermediate_size, config.hidden_size, bias=False)
|
| 197 |
+
self.act_fn = nn.SiLU()
|
| 198 |
+
|
| 199 |
+
def forward(self, x):
|
| 200 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class MobileMoEExperts(nn.Module):
|
| 204 |
+
"""Parameter container for routed experts (fused gate+up projection)."""
|
| 205 |
+
|
| 206 |
+
def __init__(self, config):
|
| 207 |
+
super().__init__()
|
| 208 |
+
self.num_experts = config.num_local_experts
|
| 209 |
+
self.hidden_size = config.hidden_size
|
| 210 |
+
self.expert_dim = config.intermediate_size
|
| 211 |
+
self.gate_up_proj = nn.Parameter(
|
| 212 |
+
torch.empty(self.num_experts, self.hidden_size, 2 * self.expert_dim)
|
| 213 |
+
)
|
| 214 |
+
self.down_proj = nn.Parameter(
|
| 215 |
+
torch.empty(self.num_experts, self.expert_dim, self.hidden_size)
|
| 216 |
+
)
|
| 217 |
+
self.act_fn = nn.SiLU()
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class MobileMoERouter(nn.Linear):
|
| 221 |
+
"""Router for expert selection."""
|
| 222 |
+
|
| 223 |
+
def __init__(self, config):
|
| 224 |
+
super().__init__(config.hidden_size, config.num_local_experts, bias=False)
|
| 225 |
+
self.num_experts = config.num_local_experts
|
| 226 |
+
self.top_k = config.num_experts_per_tok
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
# ---------------------------------------------------------------------------
|
| 230 |
+
# MoE layer (custom MobileMoE routing)
|
| 231 |
+
# ---------------------------------------------------------------------------
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
class MobileMoETextMoe(nn.Module):
|
| 235 |
+
"""MobileMoE Mixture-of-Experts layer.
|
| 236 |
+
|
| 237 |
+
Routing: sigmoid -> topk -> normalize -> scale
|
| 238 |
+
Gating: postgate — routing scores applied to expert OUTPUT
|
| 239 |
+
Shared expert: always-active dense FFN with independent intermediate dimension
|
| 240 |
+
"""
|
| 241 |
+
|
| 242 |
+
def __init__(self, config):
|
| 243 |
+
super().__init__()
|
| 244 |
+
self.top_k = config.num_experts_per_tok
|
| 245 |
+
self.hidden_dim = config.hidden_size
|
| 246 |
+
self.num_experts = config.num_local_experts
|
| 247 |
+
self.routed_scaling_factor = getattr(config, "routed_scaling_factor", 2.5)
|
| 248 |
+
self.norm_topk_prob = getattr(config, "norm_topk_prob", True)
|
| 249 |
+
|
| 250 |
+
self.experts = MobileMoEExperts(config)
|
| 251 |
+
self.router = MobileMoERouter(config)
|
| 252 |
+
|
| 253 |
+
# Expert bias for load-balancing-free routing
|
| 254 |
+
# Added post-sigmoid, pre-topk: affects expert SELECTION only, not weights
|
| 255 |
+
self.expert_bias = nn.Parameter(
|
| 256 |
+
torch.zeros(config.num_local_experts),
|
| 257 |
+
requires_grad=False,
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
shared_size = getattr(config, "intermediate_size_mlp", config.intermediate_size)
|
| 261 |
+
self.shared_expert = MobileMoEMLP(config, intermediate_size=shared_size)
|
| 262 |
+
|
| 263 |
+
def forward(self, hidden_states):
|
| 264 |
+
hidden_states = hidden_states.reshape(-1, self.hidden_dim)
|
| 265 |
+
|
| 266 |
+
# Custom routing order (bypass default router forward)
|
| 267 |
+
# Compute router matmul in fp32 for numerical stability
|
| 268 |
+
router_logits = F.linear(hidden_states.float(), self.router.weight.float())
|
| 269 |
+
|
| 270 |
+
# MobileMoE routing: sigmoid FIRST, then topk
|
| 271 |
+
scores = torch.sigmoid(router_logits.float())
|
| 272 |
+
|
| 273 |
+
# Add expert bias for topk selection (load-balancing-free routing)
|
| 274 |
+
# Bias only affects which experts are SELECTED, not the routing weights
|
| 275 |
+
scores_for_topk = scores + self.expert_bias
|
| 276 |
+
_, topk_indices = torch.topk(scores_for_topk, self.top_k, dim=-1)
|
| 277 |
+
# Gather UNBIASED scores at selected indices
|
| 278 |
+
topk_scores = scores.gather(1, topk_indices)
|
| 279 |
+
|
| 280 |
+
# Normalize per-token and scale
|
| 281 |
+
if self.norm_topk_prob:
|
| 282 |
+
topk_scores = topk_scores / (topk_scores.sum(dim=-1, keepdim=True) + 1e-20)
|
| 283 |
+
topk_scores = topk_scores * self.routed_scaling_factor
|
| 284 |
+
|
| 285 |
+
# Sparse per-expert loop with postgate scoring (reference implementation).
|
| 286 |
+
# Processes only the top-k selected tokens per expert.
|
| 287 |
+
out = torch.zeros_like(hidden_states)
|
| 288 |
+
for e in range(self.num_experts):
|
| 289 |
+
mask = (topk_indices == e).any(dim=-1)
|
| 290 |
+
if not mask.any():
|
| 291 |
+
continue
|
| 292 |
+
idx = mask.nonzero(as_tuple=True)[0]
|
| 293 |
+
x_sel = hidden_states[idx]
|
| 294 |
+
|
| 295 |
+
# Expert FFN: gate_up_proj[e] is [D, 2F], down_proj[e] is [F, D]
|
| 296 |
+
gate_up = x_sel @ self.experts.gate_up_proj[e]
|
| 297 |
+
gate, up = gate_up.chunk(2, dim=-1)
|
| 298 |
+
expert_out = (self.experts.act_fn(gate) * up) @ self.experts.down_proj[e]
|
| 299 |
+
|
| 300 |
+
# Postgate: score applied to expert OUTPUT
|
| 301 |
+
pos = (topk_indices[idx] == e).nonzero(as_tuple=True)
|
| 302 |
+
weights = topk_scores[idx][pos[0], pos[1]]
|
| 303 |
+
out[idx] += expert_out * weights.unsqueeze(-1)
|
| 304 |
+
|
| 305 |
+
# Shared expert (additive, applied to all tokens)
|
| 306 |
+
out = out + self.shared_expert(hidden_states)
|
| 307 |
+
|
| 308 |
+
return out, router_logits
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
# ---------------------------------------------------------------------------
|
| 312 |
+
# Attention
|
| 313 |
+
# ---------------------------------------------------------------------------
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class MobileMoEAttention(nn.Module):
|
| 317 |
+
"""Multi-head grouped-query attention with RoPE and optional QK L2 norm."""
|
| 318 |
+
|
| 319 |
+
def __init__(self, config, layer_idx):
|
| 320 |
+
super().__init__()
|
| 321 |
+
self.config = config
|
| 322 |
+
self.layer_idx = layer_idx
|
| 323 |
+
self.head_dim = getattr(
|
| 324 |
+
config, "head_dim", config.hidden_size // config.num_attention_heads
|
| 325 |
+
)
|
| 326 |
+
self.num_attention_heads = config.num_attention_heads
|
| 327 |
+
self.num_key_value_groups = (
|
| 328 |
+
config.num_attention_heads // config.num_key_value_heads
|
| 329 |
+
)
|
| 330 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 331 |
+
self.scaling = self.head_dim**-0.5
|
| 332 |
+
self.attn_scale = config.attn_scale
|
| 333 |
+
self.floor_scale = config.floor_scale
|
| 334 |
+
self.attn_temperature_tuning = config.attn_temperature_tuning
|
| 335 |
+
self.attention_dropout = config.attention_dropout
|
| 336 |
+
self.is_causal = True
|
| 337 |
+
self.use_rope = config.no_rope_layers[layer_idx]
|
| 338 |
+
|
| 339 |
+
self.q_proj = nn.Linear(
|
| 340 |
+
config.hidden_size,
|
| 341 |
+
config.num_attention_heads * self.head_dim,
|
| 342 |
+
bias=config.attention_bias,
|
| 343 |
+
)
|
| 344 |
+
self.k_proj = nn.Linear(
|
| 345 |
+
config.hidden_size,
|
| 346 |
+
config.num_key_value_heads * self.head_dim,
|
| 347 |
+
bias=config.attention_bias,
|
| 348 |
+
)
|
| 349 |
+
self.v_proj = nn.Linear(
|
| 350 |
+
config.hidden_size,
|
| 351 |
+
config.num_key_value_heads * self.head_dim,
|
| 352 |
+
bias=config.attention_bias,
|
| 353 |
+
)
|
| 354 |
+
self.o_proj = nn.Linear(
|
| 355 |
+
config.num_attention_heads * self.head_dim,
|
| 356 |
+
config.hidden_size,
|
| 357 |
+
bias=config.attention_bias,
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
if config.use_qk_norm and self.use_rope:
|
| 361 |
+
self.qk_norm = MobileMoEL2Norm(config.rms_norm_eps)
|
| 362 |
+
|
| 363 |
+
def forward(
|
| 364 |
+
self,
|
| 365 |
+
hidden_states,
|
| 366 |
+
position_embeddings,
|
| 367 |
+
attention_mask=None,
|
| 368 |
+
past_key_values=None,
|
| 369 |
+
cache_position=None,
|
| 370 |
+
**kwargs,
|
| 371 |
+
):
|
| 372 |
+
input_shape = hidden_states.shape[:-1]
|
| 373 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 374 |
+
|
| 375 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape)
|
| 376 |
+
key_states = self.k_proj(hidden_states).view(*input_shape, -1, self.head_dim)
|
| 377 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 378 |
+
|
| 379 |
+
if self.use_rope:
|
| 380 |
+
query_states, key_states = _apply_rotary_emb(
|
| 381 |
+
query_states, key_states, position_embeddings.to(query_states.device)
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
if hasattr(self, "qk_norm"):
|
| 385 |
+
query_states = self.qk_norm(query_states)
|
| 386 |
+
key_states = self.qk_norm(key_states)
|
| 387 |
+
|
| 388 |
+
if self.attn_temperature_tuning and not self.use_rope:
|
| 389 |
+
attn_scales = (
|
| 390 |
+
torch.log1p(
|
| 391 |
+
torch.floor((cache_position.float() + 1.0) / self.floor_scale)
|
| 392 |
+
)
|
| 393 |
+
* self.attn_scale
|
| 394 |
+
+ 1.0
|
| 395 |
+
)
|
| 396 |
+
attn_scales = attn_scales.view((1, input_shape[-1], 1, 1)).expand(
|
| 397 |
+
(*input_shape, 1, 1)
|
| 398 |
+
)
|
| 399 |
+
query_states = (query_states * attn_scales).to(query_states.dtype)
|
| 400 |
+
|
| 401 |
+
query_states = query_states.transpose(1, 2)
|
| 402 |
+
key_states = key_states.transpose(1, 2)
|
| 403 |
+
|
| 404 |
+
if past_key_values is not None:
|
| 405 |
+
cache_kwargs = {"cache_position": cache_position}
|
| 406 |
+
key_states, value_states = past_key_values.update(
|
| 407 |
+
key_states, value_states, self.layer_idx, cache_kwargs
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
attention_interface: Callable = _eager_attention_forward
|
| 411 |
+
if self.config._attn_implementation != "eager":
|
| 412 |
+
if self.config._attn_implementation in ALL_ATTENTION_FUNCTIONS:
|
| 413 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[
|
| 414 |
+
self.config._attn_implementation
|
| 415 |
+
]
|
| 416 |
+
attn_output, attn_weights = attention_interface(
|
| 417 |
+
self,
|
| 418 |
+
query_states,
|
| 419 |
+
key_states,
|
| 420 |
+
value_states,
|
| 421 |
+
attention_mask,
|
| 422 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 423 |
+
scaling=self.scaling,
|
| 424 |
+
**kwargs,
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 428 |
+
attn_output = self.o_proj(attn_output)
|
| 429 |
+
return attn_output, attn_weights
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
# ---------------------------------------------------------------------------
|
| 433 |
+
# Decoder layer
|
| 434 |
+
# ---------------------------------------------------------------------------
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
class MobileMoEDecoderLayer(nn.Module):
|
| 438 |
+
"""MobileMoE decoder layer with custom MoE routing."""
|
| 439 |
+
|
| 440 |
+
def __init__(self, config, layer_idx):
|
| 441 |
+
super().__init__()
|
| 442 |
+
self.hidden_size = config.hidden_size
|
| 443 |
+
self.layer_idx = layer_idx
|
| 444 |
+
self.attention_type = config.layer_types[layer_idx]
|
| 445 |
+
self.self_attn = MobileMoEAttention(config, layer_idx)
|
| 446 |
+
self.is_moe_layer = layer_idx in config.moe_layers
|
| 447 |
+
if self.is_moe_layer:
|
| 448 |
+
self.feed_forward = MobileMoETextMoe(config)
|
| 449 |
+
else:
|
| 450 |
+
self.feed_forward = MobileMoEMLP(
|
| 451 |
+
config, intermediate_size=config.intermediate_size_mlp
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
self.input_layernorm = MobileMoERMSNorm(
|
| 455 |
+
config.hidden_size, eps=config.rms_norm_eps
|
| 456 |
+
)
|
| 457 |
+
self.post_attention_layernorm = MobileMoERMSNorm(
|
| 458 |
+
config.hidden_size, eps=config.rms_norm_eps
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
def forward(
|
| 462 |
+
self,
|
| 463 |
+
hidden_states,
|
| 464 |
+
attention_mask=None,
|
| 465 |
+
position_ids=None,
|
| 466 |
+
past_key_values=None,
|
| 467 |
+
use_cache=False,
|
| 468 |
+
cache_position=None,
|
| 469 |
+
position_embeddings=None,
|
| 470 |
+
**kwargs,
|
| 471 |
+
):
|
| 472 |
+
residual = hidden_states
|
| 473 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 474 |
+
|
| 475 |
+
# Self Attention
|
| 476 |
+
attn_output, _ = self.self_attn(
|
| 477 |
+
hidden_states=hidden_states,
|
| 478 |
+
position_embeddings=position_embeddings,
|
| 479 |
+
attention_mask=attention_mask,
|
| 480 |
+
past_key_values=past_key_values,
|
| 481 |
+
cache_position=cache_position,
|
| 482 |
+
**kwargs,
|
| 483 |
+
)
|
| 484 |
+
hidden_states = residual + attn_output
|
| 485 |
+
|
| 486 |
+
# Feed-Forward
|
| 487 |
+
residual = hidden_states
|
| 488 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 489 |
+
hidden_states = self.feed_forward(hidden_states)
|
| 490 |
+
if self.is_moe_layer:
|
| 491 |
+
hidden_states, _ = hidden_states
|
| 492 |
+
hidden_states = residual + hidden_states.view(residual.shape)
|
| 493 |
+
|
| 494 |
+
return hidden_states
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
# ---------------------------------------------------------------------------
|
| 498 |
+
# Full model
|
| 499 |
+
# ---------------------------------------------------------------------------
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
class MobileMoEPreTrainedModel(PreTrainedModel):
|
| 503 |
+
"""Base class for MobileMoE models."""
|
| 504 |
+
|
| 505 |
+
config_class = MobileMoEConfig
|
| 506 |
+
base_model_prefix = "model"
|
| 507 |
+
supports_gradient_checkpointing = True
|
| 508 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 509 |
+
_supports_flash_attn = False
|
| 510 |
+
_supports_sdpa = True
|
| 511 |
+
_supports_attention_backend = True
|
| 512 |
+
|
| 513 |
+
def _init_weights(self, module):
|
| 514 |
+
std = self.config.initializer_range
|
| 515 |
+
if isinstance(module, nn.Linear):
|
| 516 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 517 |
+
if module.bias is not None:
|
| 518 |
+
module.bias.data.zero_()
|
| 519 |
+
elif isinstance(module, nn.Embedding):
|
| 520 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 521 |
+
if module.padding_idx is not None:
|
| 522 |
+
module.weight.data[module.padding_idx].zero_()
|
| 523 |
+
elif isinstance(module, MobileMoERMSNorm):
|
| 524 |
+
module.weight.data.fill_(1.0)
|
| 525 |
+
elif isinstance(module, MobileMoEExperts):
|
| 526 |
+
module.gate_up_proj.data.normal_(mean=0.0, std=std)
|
| 527 |
+
module.down_proj.data.normal_(mean=0.0, std=std)
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
class MobileMoETextModel(MobileMoEPreTrainedModel):
|
| 531 |
+
"""MobileMoE text model."""
|
| 532 |
+
|
| 533 |
+
_no_split_modules = ["MobileMoEDecoderLayer"]
|
| 534 |
+
|
| 535 |
+
def __init__(self, config):
|
| 536 |
+
super().__init__(config)
|
| 537 |
+
self.padding_idx = config.pad_token_id
|
| 538 |
+
self.vocab_size = config.vocab_size
|
| 539 |
+
self.embed_tokens = nn.Embedding(
|
| 540 |
+
config.vocab_size, config.hidden_size, self.padding_idx
|
| 541 |
+
)
|
| 542 |
+
self.layers = nn.ModuleList(
|
| 543 |
+
[MobileMoEDecoderLayer(config, i) for i in range(config.num_hidden_layers)]
|
| 544 |
+
)
|
| 545 |
+
self.norm = MobileMoERMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 546 |
+
self.rotary_emb = MobileMoERotaryEmbedding(config)
|
| 547 |
+
self.gradient_checkpointing = False
|
| 548 |
+
self.post_init()
|
| 549 |
+
|
| 550 |
+
def forward(
|
| 551 |
+
self,
|
| 552 |
+
input_ids=None,
|
| 553 |
+
attention_mask=None,
|
| 554 |
+
position_ids=None,
|
| 555 |
+
past_key_values=None,
|
| 556 |
+
inputs_embeds=None,
|
| 557 |
+
use_cache=None,
|
| 558 |
+
cache_position=None,
|
| 559 |
+
**kwargs,
|
| 560 |
+
):
|
| 561 |
+
if inputs_embeds is None:
|
| 562 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 563 |
+
|
| 564 |
+
if use_cache and past_key_values is None:
|
| 565 |
+
past_key_values = DynamicCache(config=self.config)
|
| 566 |
+
|
| 567 |
+
if cache_position is None:
|
| 568 |
+
past_seen_tokens = (
|
| 569 |
+
past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 570 |
+
)
|
| 571 |
+
cache_position = torch.arange(
|
| 572 |
+
past_seen_tokens,
|
| 573 |
+
past_seen_tokens + inputs_embeds.shape[1],
|
| 574 |
+
device=inputs_embeds.device,
|
| 575 |
+
)
|
| 576 |
+
|
| 577 |
+
if position_ids is None:
|
| 578 |
+
position_ids = cache_position.unsqueeze(0)
|
| 579 |
+
|
| 580 |
+
# Build causal mask
|
| 581 |
+
causal_mask = create_causal_mask(
|
| 582 |
+
config=self.config,
|
| 583 |
+
input_embeds=inputs_embeds,
|
| 584 |
+
attention_mask=attention_mask,
|
| 585 |
+
cache_position=cache_position,
|
| 586 |
+
past_key_values=past_key_values,
|
| 587 |
+
position_ids=position_ids,
|
| 588 |
+
)
|
| 589 |
+
|
| 590 |
+
hidden_states = inputs_embeds
|
| 591 |
+
freq_cis = self.rotary_emb(hidden_states, position_ids)
|
| 592 |
+
|
| 593 |
+
for decoder_layer in self.layers:
|
| 594 |
+
hidden_states = decoder_layer(
|
| 595 |
+
hidden_states,
|
| 596 |
+
attention_mask=causal_mask,
|
| 597 |
+
position_ids=position_ids,
|
| 598 |
+
past_key_values=past_key_values,
|
| 599 |
+
use_cache=use_cache,
|
| 600 |
+
cache_position=cache_position,
|
| 601 |
+
position_embeddings=freq_cis,
|
| 602 |
+
**kwargs,
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
hidden_states = self.norm(hidden_states)
|
| 606 |
+
|
| 607 |
+
return BaseModelOutputWithPast(
|
| 608 |
+
last_hidden_state=hidden_states,
|
| 609 |
+
past_key_values=past_key_values if use_cache else None,
|
| 610 |
+
)
|
| 611 |
+
|
| 612 |
+
def _build_causal_mask(
|
| 613 |
+
self, attention_mask, inputs_embeds, cache_position, past_key_values
|
| 614 |
+
):
|
| 615 |
+
"""Build 4D causal attention mask."""
|
| 616 |
+
dtype, device = inputs_embeds.dtype, inputs_embeds.device
|
| 617 |
+
min_dtype = torch.finfo(dtype).min
|
| 618 |
+
seq_length = inputs_embeds.shape[1]
|
| 619 |
+
target_length = (
|
| 620 |
+
cache_position[-1].item() + 1 if cache_position is not None else seq_length
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
# Create causal mask [1, 1, Q, K]
|
| 624 |
+
causal_mask = torch.full(
|
| 625 |
+
(seq_length, target_length),
|
| 626 |
+
fill_value=min_dtype,
|
| 627 |
+
dtype=dtype,
|
| 628 |
+
device=device,
|
| 629 |
+
)
|
| 630 |
+
if seq_length != 1:
|
| 631 |
+
causal_mask = torch.triu(
|
| 632 |
+
causal_mask, diagonal=target_length - seq_length + 1
|
| 633 |
+
)
|
| 634 |
+
causal_mask = (
|
| 635 |
+
causal_mask[None, None, :, :]
|
| 636 |
+
.expand(inputs_embeds.shape[0], 1, -1, -1)
|
| 637 |
+
.clone()
|
| 638 |
+
)
|
| 639 |
+
|
| 640 |
+
# Apply padding mask
|
| 641 |
+
if attention_mask is not None and attention_mask.dim() == 2:
|
| 642 |
+
mask_length = attention_mask.shape[-1]
|
| 643 |
+
padding_mask = attention_mask[:, None, None, :mask_length].eq(0)
|
| 644 |
+
causal_mask[:, :, :, :mask_length].masked_fill_(padding_mask, min_dtype)
|
| 645 |
+
|
| 646 |
+
return causal_mask
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
class MobileMoEForCausalLM(MobileMoEPreTrainedModel, GenerationMixin):
|
| 650 |
+
"""MobileMoE causal language model for text generation."""
|
| 651 |
+
|
| 652 |
+
_no_split_modules = ["MobileMoEDecoderLayer"]
|
| 653 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 654 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
| 655 |
+
|
| 656 |
+
def __init__(self, config):
|
| 657 |
+
super().__init__(config)
|
| 658 |
+
self.model = MobileMoETextModel(config)
|
| 659 |
+
self.vocab_size = config.vocab_size
|
| 660 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 661 |
+
self.post_init()
|
| 662 |
+
|
| 663 |
+
def get_input_embeddings(self):
|
| 664 |
+
return self.model.embed_tokens
|
| 665 |
+
|
| 666 |
+
def set_input_embeddings(self, value):
|
| 667 |
+
self.model.embed_tokens = value
|
| 668 |
+
|
| 669 |
+
def get_output_embeddings(self):
|
| 670 |
+
return self.lm_head
|
| 671 |
+
|
| 672 |
+
def set_output_embeddings(self, new_embeddings):
|
| 673 |
+
self.lm_head = new_embeddings
|
| 674 |
+
|
| 675 |
+
def forward(
|
| 676 |
+
self,
|
| 677 |
+
input_ids=None,
|
| 678 |
+
attention_mask=None,
|
| 679 |
+
position_ids=None,
|
| 680 |
+
past_key_values=None,
|
| 681 |
+
inputs_embeds=None,
|
| 682 |
+
labels=None,
|
| 683 |
+
use_cache=None,
|
| 684 |
+
cache_position=None,
|
| 685 |
+
logits_to_keep=0,
|
| 686 |
+
**kwargs,
|
| 687 |
+
):
|
| 688 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 689 |
+
|
| 690 |
+
outputs = self.model(
|
| 691 |
+
input_ids=input_ids,
|
| 692 |
+
attention_mask=attention_mask,
|
| 693 |
+
position_ids=position_ids,
|
| 694 |
+
past_key_values=past_key_values,
|
| 695 |
+
inputs_embeds=inputs_embeds,
|
| 696 |
+
use_cache=use_cache,
|
| 697 |
+
cache_position=cache_position,
|
| 698 |
+
)
|
| 699 |
+
|
| 700 |
+
hidden_states = outputs[0]
|
| 701 |
+
slice_indices = (
|
| 702 |
+
slice(-logits_to_keep, None)
|
| 703 |
+
if isinstance(logits_to_keep, int)
|
| 704 |
+
else logits_to_keep
|
| 705 |
+
)
|
| 706 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 707 |
+
|
| 708 |
+
loss = None
|
| 709 |
+
if labels is not None:
|
| 710 |
+
loss = self.loss_function(
|
| 711 |
+
logits=logits,
|
| 712 |
+
labels=labels,
|
| 713 |
+
vocab_size=self.config.vocab_size,
|
| 714 |
+
**kwargs,
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
return CausalLMOutputWithPast(
|
| 718 |
+
loss=loss,
|
| 719 |
+
logits=logits,
|
| 720 |
+
past_key_values=outputs.past_key_values,
|
| 721 |
+
)
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token": "<|begin_of_text|>",
|
| 3 |
+
"eos_token": "<|end_of_text|>"
|
| 4 |
+
}
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": true,
|
| 3 |
+
"add_eos_token": false,
|
| 4 |
+
"bos_token": "<|begin_of_text|>",
|
| 5 |
+
"eos_token": "<|end_of_text|>",
|
| 6 |
+
"model_max_length": 8192,
|
| 7 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
| 8 |
+
"clean_up_tokenization_spaces": true,
|
| 9 |
+
"model_input_names": [
|
| 10 |
+
"input_ids",
|
| 11 |
+
"attention_mask"
|
| 12 |
+
]
|
| 13 |
+
}
|