├── .gitignore ├── LICENSE ├── README.md ├── moduleformer ├── __init__.py ├── configuration_moduleformer.py ├── modeling_moduleformer.py └── utils │ ├── __init__.py │ ├── gate.py │ ├── moe.py │ └── parallel_experts.py ├── setup.py └── test.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.egg-info -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # **ModuleFormer** 2 | 3 | **ModuleFormer** is a MoE-based architecture that includes two different types of experts: stick-breaking attention heads and feedforward experts. 4 | Different experts are sparsely activated conditions on the input token during training and inference. 5 | In our experiment, we found that the sparse architecture enables three important abilities for large pre-trained language models: 6 | 7 | 1) Efficiency, since ModuleFormer only activates a subset of its experts for each input token, thus it could achieve the same performance as dense LLMs with more than two times throughput; 8 | 2) Extendability, ModuleFormer is more immune to catastrophic forgetting than dense LLMs and can be easily extended with new experts to learn new knowledge that is not included in the training data; 9 | 3) Specialisation, finetuning ModuleFormer could specialize a subset of experts to the finetuning task, and the task-unrelated experts could be easily pruned for a lightweight deployment. 10 | 11 | **MoLM** is a collection of ModuleFormer-based language models ranging in scale from 4 billion to 8 billion parameters. 12 | 13 | **Model Usage** 14 | To load the models, you need install this package: 15 | ``` 16 | pip install -e . 17 | ``` 18 | 19 | Then you can load the model with the following code: 20 | ``` 21 | from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig, AutoModelForSequenceClassification 22 | from moduleformer import ModuleFormerForCausalLM, ModuleFormerConfig, ModuleFormerForSequenceClassification 23 | AutoConfig.register("moduleformer", ModuleFormerConfig) 24 | AutoModelForCausalLM.register(ModuleFormerConfig, ModuleFormerForCausalLM) 25 | AutoModelForSequenceClassification.register(ModuleFormerConfig, ModuleFormerForSequenceClassification) 26 | 27 | tokenizer = AutoTokenizer.from_pretrained('ibm/MoLM-350M-4B') 28 | model = AutoModelForCausalLM.from_pretrained('ibm/MoLM-350M-4B') 29 | ``` 30 | 31 | **Model Details** 32 | MoLM-350M-4B is a MoE-based language model. It has 4 billion parameters, but each input token only activates 350M parameters. Thus, it's computationally equivalent to a 350M dense model. 33 | MoLM-700M-4B has 4 billion parameters and is computationally equivalent to a 700M dense model. 34 | MoLM-700M-8B has 8 billion parameters and is computationally equivalent to a 700M dense model. All models are trained on 300 billion tokens from publicly available sources. 35 | All models are trained on 300 billion tokens from publicly available sources, with a learning rate of 3.0 x 10-4 and a global batch-size of 3M tokens. 36 | 37 | **Model Developers** IBM 38 | 39 | **Variations** MoLM comes in two different parameter sizes — 4B and 8B. The 4B models has two variants with different computation cost — 350M and 700M. 40 | 41 | **Input** Models input text only. 42 | 43 | **Output** Models generate text only. 44 | 45 | **Model Architecture** MoLM is an auto-regressive language model that uses the ModuleFormer architecture. It has 16 attention modules in each attention layer and 32 MLP modules in each MLP layer. During inference, in each layer, MoLM-350M-4B and MoLM-700M-8B activate 2 modules for each token, while MoLM-700M-4B activate 4 modules. MoLM-350M-4B and MoLM-700M-4B has 24 blocks and MoLM-700M-8B has 48 blocks. 46 | 47 | **Status** This is a static model trained on an offline dataset. Future versions of the tuned models will be released as we improve model safety with community feedback. 48 | 49 | **Research Paper** ["ModuleFormer: Modularity Emerges from Mixture-of-Experts"](https://arxiv.org/abs/2306.04640) 50 | 51 | ## Training Data 52 | MoLM models are pretrained on 300 billion tokens of data from publicly available sources. 53 | 54 | ## Evaluation Results 55 | 56 | In this section, we report the results for the MoLM models on standard academic benchmarks. For all the evaluations, we use [LM evaluations Harness](https://github.com/EleutherAI/lm-evaluation-harness). 57 | 58 | |Model|Latency|Memory|Throughput|Hellaswag|PIQA|ARC-e|ARC-c|OBQA| 59 | |---|---|---|---|---|---|---|---|---| 60 | ||ms|GB|tokens/sec|acc|acc|acc|acc|acc| 61 | |Pythia 410M|554|25|59594|33.72|66.70|51.89|21.42|18.2| 62 | |GPT-Neo 1.3B|991|23|32857|38.66|71.11|56.19|23.12|21.4| 63 | |Pythia 1.4B|918|42|35559|40.41|70.84|60.52|26.11|22.2| 64 | |MoLM-350M-4B|497|27|71017|39.21|70.13|56.44|23.55|20.8| 65 | |GPT-Neo 2.7B|1737|35|18788|42.71|72.2|61.07|27.47|23.2| 66 | |Pythia 2.8B|2111|70|15522|45.34|73.99|64.35|29.35|23.8| 67 | |MoLM-700M-4B|863|27|39931|42.20|73.01|60.82|25.94|22.6| 68 | |MoLM-700M-8B|939|38|37419|43.33|72.91|62.46|27.90|23.8| 69 | 70 | |Model| |TriviaQA| | | HumanEval| |Wikitext| 71 | |---|---|---|---|---|---|---|---| 72 | ||0-shot |1-shot |5-shot |pass@1 |pass@10 |pass@100 |PPL| 73 | |Pythia 410M |2.32 |5.02 |6.42 |1.20 |3.85 |9.98 |20.09 | 74 | |GPT-Neo 1.3B |5.24 |8.01 |9.74 |3.62 |6.87 |14.50 |16.16 | 75 | |Pythia 1.4B |5.30 |9.87 |12.84 |2.19 |7.31 |14.33 |14.71| 76 | |MoLM-350M-4B |5.40 |11.12 |13.70 |3.04 |6.99 |13.79 |15.15 | 77 | |GPT-Neo 2.7B |4.82 |11.23 |13.67 |4.89 |9.54 |17.90 |13.93 | 78 | |Pythia 2.8B |7.38 |15.58 |18.98 |4.91 |11.76 |21.54 |12.68| 79 | |MoLM-700M-4B|9.07|14.24|16.49|5.50|10.65|20.27|13.20| 80 | |MoLM-700M-8B |11.47 |16.73 |20.75 |5.51 |12.58 |20.40 |12.97 | 81 | 82 | ## Ethical Considerations and Limitations 83 | MoLM is a new technology that carries risks with use. Testing conducted to date has been in English, and has not covered, nor could it cover all scenarios. For these reasons, as with all LLMs, MoLM’s potential outputs cannot be predicted in advance, and the model may in some instances produce inaccurate, biased or other objectionable responses to user prompts. Therefore, before deploying any applications of MoLM, developers should perform safety testing and tuning tailored to their specific applications of the model. 84 | 85 | ## Citation 86 | 87 | Please cite the following paper if you use the data or code in this repo. 88 | 89 | ``` 90 | @article{shen2023moduleformer, 91 | title={ModuleFormer: Learning Modular Large Language Models From Uncurated Data}, 92 | author={Shen, Yikang and Zhang, Zheyu and Cao, Tianyou and Tan, Shawn and Chen, Zhenfang and Gan, Chuang}, 93 | journal={arXiv preprint arXiv:2306.04640}, 94 | year={2023} 95 | } 96 | ``` 97 | 98 | ## MoLM Model Index 99 | |Model|MoLM| 100 | |---|---| 101 | |350M-4B| [Link](https://huggingface.co/ibm/MoLM-350M-4B) | 102 | |700M-4B| [Link](https://huggingface.co/ibm/MoLM-700M-4B) | 103 | |700M-8B| [Link](https://huggingface.co/ibm/MoLM-700M-8B) | 104 | -------------------------------------------------------------------------------- /moduleformer/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Salesforce authors, The EleutherAI, and HuggingFace Teams. All rights reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | from typing import TYPE_CHECKING 15 | 16 | from transformers.utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available 17 | 18 | 19 | _import_structure = { 20 | "configuration_moduleformer": ["SPARSEGPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ModuleFormerConfig", "ModuleFormerOnnxConfig"], 21 | } 22 | 23 | try: 24 | if not is_torch_available(): 25 | raise OptionalDependencyNotAvailable() 26 | except OptionalDependencyNotAvailable: 27 | pass 28 | else: 29 | _import_structure["modeling_moduleformer"] = [ 30 | "SPARSEGPT_PRETRAINED_MODEL_ARCHIVE_LIST", 31 | "ModuleFormerForCausalLM", 32 | "ModuleFormerModel", 33 | "ModuleFormerPreTrainedModel", 34 | "ModuleFormerForSequenceClassification", 35 | ] 36 | 37 | if TYPE_CHECKING: 38 | from .configuration_moduleformer import SPARSEGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ModuleFormerConfig, ModuleFormerOnnxConfig 39 | 40 | try: 41 | if not is_torch_available(): 42 | raise OptionalDependencyNotAvailable() 43 | except OptionalDependencyNotAvailable: 44 | pass 45 | else: 46 | from .modeling_moduleformer import ( 47 | SPARSEGPT_PRETRAINED_MODEL_ARCHIVE_LIST, 48 | ModuleFormerForCausalLM, 49 | ModuleFormerModel, 50 | ModuleFormerPreTrainedModel, 51 | ModuleFormerForSequenceClassification, 52 | ) 53 | 54 | else: 55 | import sys 56 | 57 | sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__) 58 | -------------------------------------------------------------------------------- /moduleformer/configuration_moduleformer.py: -------------------------------------------------------------------------------- 1 | """ ModuleFormer model configuration""" 2 | from collections import OrderedDict 3 | from typing import Any, List, Mapping, Optional 4 | 5 | from transformers import PreTrainedTokenizer, TensorType, is_torch_available 6 | from transformers.configuration_utils import PretrainedConfig 7 | from transformers.onnx import OnnxConfigWithPast, PatchingSpec 8 | from transformers.utils import logging 9 | 10 | 11 | logger = logging.get_logger(__name__) 12 | 13 | 14 | # SPARSEGPT_PRETRAINED_CONFIG_ARCHIVE_MAP = { 15 | # "moduleformer-small": "https://huggingface.co/moduleformer-small/resolve/main/config.json", 16 | # } 17 | 18 | 19 | 20 | class ModuleFormerConfig(PretrainedConfig): 21 | r""" 22 | This is the configuration class to store the configuration of a [`ModuleFormerModel`]. It is used to instantiate a 23 | ModuleFormer model according to the specified arguments, defining the model architecture. Instantiating a configuration 24 | with the defaults will yield a similar configuration to that of the ModuleFormer 25 | [moduleformer-small](https://huggingface.co/moduleformer-small) architecture. Configuration objects 26 | inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from 27 | [`PretrainedConfig`] for more information. 28 | 29 | Args: 30 | vocab_size (`int`, *optional*, defaults to 50400): 31 | Vocabulary size of the ModuleFormer model. Defines the number of different tokens that can be represented by the 32 | `inputs_ids` passed when calling [`ModuleFormerModel`]. 33 | n_positions (`int`, *optional*, defaults to 2048): 34 | The maximum sequence length that this model might ever be used with. Typically set this to something large 35 | just in case (e.g., 512 or 1024 or 2048). 36 | n_embd (`int`, *optional*, defaults to 4096): 37 | Dimensionality of the embeddings and hidden states. 38 | n_layer (`int`, *optional*, defaults to 28): 39 | Number of hidden layers in the Transformer encoder. 40 | n_head (`int`, *optional*, defaults to 16): 41 | Number of attention heads for each attention layer in the Transformer encoder. 42 | rotary_dim (`int`, *optional*, defaults to 64): 43 | Number of dimensions in the embedding that Rotary Position Embedding is applied to. 44 | n_inner (`int`, *optional*, defaults to None): 45 | Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd 46 | activation_function (`str`, *optional*, defaults to `"gelu_new"`): 47 | Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new"]`. 48 | resid_pdrop (`float`, *optional*, defaults to 0.1): 49 | The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. 50 | embd_pdrop (`int`, *optional*, defaults to 0.1): 51 | The dropout ratio for the embeddings. 52 | attn_pdrop (`float`, *optional*, defaults to 0.1): 53 | The dropout ratio for the attention. 54 | layer_norm_epsilon (`float`, *optional*, defaults to 1e-5): 55 | The epsilon to use in the layer normalization layers. 56 | initializer_range (`float`, *optional*, defaults to 0.02): 57 | The standard deviation of the truncated_normal_initializer for initializing all weight matrices. 58 | use_cache (`bool`, *optional*, defaults to `True`): 59 | Whether or not the model should return the last key/values attentions (not used by all models). 60 | 61 | Example: 62 | 63 | ```python 64 | >>> from transformers import ModuleFormerConfig, ModuleFormerModel 65 | 66 | >>> # Initializing a ModuleFormer 6B configuration 67 | >>> configuration = ModuleFormerConfig() 68 | 69 | >>> # Initializing a model (with random weights) from the configuration 70 | >>> model = ModuleFormerModel(configuration) 71 | 72 | >>> # Accessing the model configuration 73 | >>> configuration = model.config 74 | ```""" 75 | model_type = "moduleformer" 76 | attribute_map = { 77 | "max_position_embeddings": "n_positions", 78 | "hidden_size": "n_embd", 79 | "num_attention_heads": "n_head", 80 | "num_hidden_layers": "n_layer", 81 | } 82 | 83 | def __init__( 84 | self, 85 | vocab_size=50295, 86 | block_size=512, 87 | history_length=512, 88 | n_embd=1024, 89 | n_layer=24, 90 | n_head=8, 91 | att_hidden = 512, 92 | ffd_hidden=2048, 93 | activation_function="gelu_new", 94 | resid_pdrop=0.0, 95 | embd_pdrop=0.0, 96 | attn_pdrop=0.0, 97 | moe_pdrop=0.0, 98 | sample_topk = 0, 99 | gating_size = 256, 100 | n_att_experts = 32, 101 | k_att = 2, 102 | n_mlp_experts = 32, 103 | k_mlp = 2, 104 | layer_norm_epsilon=1e-5, 105 | initializer_range=0.02, 106 | use_cache=True, 107 | bos_token_id=50256, 108 | eos_token_id=50256, 109 | tie_word_embeddings=False, 110 | aux_loss_type = 'mi', 111 | aux_loss_weight=0, 112 | gate_type = "mlp", 113 | **kwargs, 114 | ): 115 | self.vocab_size = vocab_size 116 | self.history_length = history_length 117 | self.block_size = block_size 118 | self.n_embd = n_embd 119 | self.n_layer = n_layer 120 | self.n_head = n_head 121 | self.att_hidden = att_hidden 122 | self.ffd_hidden = ffd_hidden 123 | self.activation_function = activation_function 124 | self.resid_pdrop = resid_pdrop 125 | self.embd_pdrop = embd_pdrop 126 | self.attn_pdrop = attn_pdrop 127 | self.moe_pdrop = moe_pdrop 128 | self.layer_norm_epsilon = layer_norm_epsilon 129 | self.initializer_range = initializer_range 130 | self.use_cache = use_cache 131 | self.sample_topk = sample_topk 132 | self.gating_size = gating_size 133 | self.n_att_experts = n_att_experts 134 | self.k_att = k_att 135 | self.n_mlp_experts = n_mlp_experts 136 | self.k_mlp = k_mlp 137 | self.aux_loss_type = aux_loss_type 138 | self.aux_loss_weight = aux_loss_weight 139 | self.gate_type = gate_type 140 | self.n_ctx = history_length * n_layer 141 | 142 | self.bos_token_id = bos_token_id 143 | self.eos_token_id = eos_token_id 144 | 145 | super().__init__( 146 | bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs 147 | ) 148 | 149 | 150 | class ModuleFormerOnnxConfig(OnnxConfigWithPast): 151 | def __init__( 152 | self, 153 | config: PretrainedConfig, 154 | task: str = "default", 155 | patching_specs: List[PatchingSpec] = None, 156 | use_past: bool = False, 157 | ): 158 | """ 159 | Initialize the ModuleFormerOnnxConfig. 160 | 161 | Args: 162 | config (PretrainedConfig): Pretrained model configuration. 163 | task (str): Task description. 164 | patching_specs (List[PatchingSpec]): List of patching specifications. 165 | use_past (bool): Whether to use past tokens in the configuration. 166 | """ 167 | super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past) 168 | if not getattr(self._config, "pad_token_id", None): 169 | # TODO: how to do that better? 170 | self._config.pad_token_id = 0 171 | 172 | @property 173 | def inputs(self) -> Mapping[str, Mapping[int, str]]: 174 | """ 175 | Define the input mappings. 176 | 177 | Returns: 178 | Mapping[str, Mapping[int, str]]: Input mappings. 179 | """ 180 | common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}}) 181 | if self.use_past: 182 | self.fill_with_past_key_values_(common_inputs, direction="inputs") 183 | common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"} 184 | else: 185 | common_inputs["attention_mask"] = {0: "batch", 1: "sequence"} 186 | 187 | return common_inputs 188 | 189 | @property 190 | def num_layers(self) -> int: 191 | """ 192 | Get the number of layers. 193 | 194 | Returns: 195 | int: Number of layers. 196 | """ 197 | return self._config.n_layer 198 | 199 | @property 200 | def num_attention_heads(self) -> int: 201 | """ 202 | Get the number of attention heads. 203 | 204 | Returns: 205 | int: Number of attention heads. 206 | """ 207 | return self._config.n_head 208 | 209 | def generate_dummy_inputs( 210 | self, 211 | tokenizer: PreTrainedTokenizer, 212 | batch_size: int = -1, 213 | seq_length: int = -1, 214 | is_pair: bool = False, 215 | framework: Optional[TensorType] = None, 216 | ) -> Mapping[str, Any]: 217 | """ 218 | Generate dummy inputs for testing. 219 | 220 | Args: 221 | tokenizer (PreTrainedTokenizer): Pretrained tokenizer. 222 | batch_size (int): Batch size. 223 | seq_length (int): Sequence length. 224 | is_pair (bool): Whether the input is a pair. 225 | framework (Optional[TensorType]): Tensor framework. 226 | 227 | Returns: 228 | Mapping[str, Any]: Dummy inputs. 229 | """ 230 | common_inputs = super(OnnxConfigWithPast, self).generate_dummy_inputs( 231 | tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework 232 | ) 233 | 234 | # We need to order the input in the way they appears in the forward() 235 | ordered_inputs = OrderedDict({"input_ids": common_inputs["input_ids"]}) 236 | 237 | # Need to add the past_keys 238 | if self.use_past: 239 | if not is_torch_available(): 240 | raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.") 241 | else: 242 | import torch 243 | 244 | batch, seqlen = common_inputs["input_ids"].shape 245 | # Not using the same length for past_key_values 246 | past_key_values_length = seqlen + 2 247 | past_shape = ( 248 | batch, 249 | self.num_attention_heads, 250 | past_key_values_length, 251 | self._config.hidden_size // self.num_attention_heads, 252 | ) 253 | ordered_inputs["past_key_values"] = [ 254 | (torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(self.num_layers) 255 | ] 256 | 257 | ordered_inputs["attention_mask"] = common_inputs["attention_mask"] 258 | if self.use_past: 259 | mask_dtype = ordered_inputs["attention_mask"].dtype 260 | ordered_inputs["attention_mask"] = torch.cat( 261 | [ordered_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1 262 | ) 263 | 264 | return ordered_inputs 265 | 266 | @property 267 | def default_onnx_opset(self) -> int: 268 | """ 269 | Get the default ONNX opset version. 270 | 271 | Returns: 272 | int: Default ONNX opset version. 273 | """ 274 | return 13 275 | -------------------------------------------------------------------------------- /moduleformer/modeling_moduleformer.py: -------------------------------------------------------------------------------- 1 | """ PyTorch ModuleFormer model.""" 2 | 3 | from typing import Optional, Tuple, Union 4 | import math 5 | 6 | import torch 7 | import torch.utils.checkpoint 8 | from torch import nn 9 | from torch.nn import CrossEntropyLoss, MSELoss, BCEWithLogitsLoss 10 | from torch.nn import functional as F 11 | 12 | from transformers.activations import get_activation 13 | from transformers.modeling_outputs import ( 14 | BaseModelOutputWithPast, 15 | CausalLMOutputWithPast, 16 | SequenceClassifierOutputWithPast 17 | ) 18 | from transformers.modeling_utils import PreTrainedModel 19 | from transformers.utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging 20 | from .configuration_moduleformer import ModuleFormerConfig 21 | from .utils.moe import MoE 22 | 23 | 24 | logger = logging.get_logger(__name__) 25 | 26 | _CHECKPOINT_FOR_DOC = "moduleformer-small" 27 | _CONFIG_FOR_DOC = "ModuleFormerConfig" 28 | 29 | 30 | # SPARSEGPT_PRETRAINED_MODEL_ARCHIVE_LIST = [ 31 | # "moduleformer-small", 32 | # # See all ModuleFormer models at https://huggingface.co/models?filter=moduleformer 33 | # ] 34 | 35 | 36 | @torch.jit.script 37 | def stickbreaking_att( 38 | q: torch.Tensor, 39 | k: torch.Tensor, 40 | v: torch.Tensor, 41 | mask: torch.Tensor, 42 | cum_weight: torch.Tensor, 43 | att_mask: Optional[torch.FloatTensor] = None, 44 | ) -> Tuple[torch.Tensor, torch.Tensor]: 45 | """ 46 | Compute stick-breaking attention weights. 47 | 48 | Args: 49 | q (torch.Tensor): Query tensor. 50 | k (torch.Tensor): Key tensor. 51 | v (torch.Tensor): Value tensor. 52 | mask (torch.Tensor): Mask tensor. 53 | cum_weight (torch.Tensor): Cumulative weight tensor. 54 | att_mask (Optional[torch.FloatTensor]): Attention mask tensor (default: None). 55 | 56 | Returns: 57 | Tuple[torch.Tensor, torch.Tensor]: Tuple containing the output tensor and attention weights. 58 | """ 59 | logits = torch.einsum('bikhd,bjhd->bkhij', q, k) / math.sqrt(k.size(-1)) 60 | mask = (mask[None, None, None, :, :] == 0).expand_as(logits) 61 | logits = logits + att_mask if att_mask is not None else logits 62 | z = F.sigmoid(logits).masked_fill(mask, 0) 63 | log_beta = F.logsigmoid(-logits).masked_fill(mask, 0) 64 | re_cum_log_beta = torch.einsum('bnhij,jk->bnhik', log_beta, cum_weight) 65 | att = z * re_cum_log_beta.exp() 66 | y = torch.einsum('bkhij,bjhd->bikhd', att, v) 67 | return y, att 68 | 69 | 70 | class ModuleFormerAttention(nn.Module): 71 | def __init__(self, config): 72 | """ 73 | Initialize the ModuleFormerAttention module. 74 | 75 | Args: 76 | config: Configuration object with model hyperparameters. 77 | """ 78 | super().__init__() 79 | 80 | self.q_proj = MoE( 81 | input_size=config.n_embd, 82 | head_size=config.att_hidden, 83 | num_experts=config.n_att_experts, 84 | top_k=config.k_att, 85 | acc_aux_loss=False, 86 | bias=False, 87 | gating_dropout=config.moe_pdrop, 88 | sample_topk=config.sample_topk, 89 | gating_size=config.gating_size, 90 | aux_loss=config.aux_loss_type, 91 | gate_type=config.gate_type, 92 | ) 93 | if config.att_hidden == config.n_embd and config.n_head == 1: 94 | self.k_proj = nn.Identity() 95 | self.v_proj = nn.Identity() 96 | else: 97 | self.k_proj = nn.Linear(config.n_embd, config.att_hidden) 98 | self.v_proj = nn.Linear(config.n_embd, config.att_hidden) 99 | 100 | # regularization 101 | self.attn_dropout = nn.Dropout(config.attn_pdrop) 102 | # causal mask to ensure that attention is only applied to the left in the input sequence 103 | 104 | self.context_length = config.history_length + config.block_size 105 | 106 | self.register_buffer( 107 | "mask", 108 | torch.tril(torch.ones(self.context_length, self.context_length, dtype=torch.int8)) 109 | ) 110 | self.register_buffer( 111 | "cum_weight", 112 | torch.tril(torch.ones(self.context_length, self.context_length), -1) 113 | ) 114 | self.n_head = config.n_head 115 | self.top_k = config.k_att 116 | self.n_embd = config.n_embd 117 | self.att_hidden = config.att_hidden 118 | self.head_size = config.att_hidden // config.n_head 119 | 120 | def add_history(self, k, v, hidden, use_cache=False): 121 | """ 122 | Add history to key and value tensors. 123 | 124 | Args: 125 | k (torch.Tensor): Key tensor. 126 | v (torch.Tensor): Value tensor. 127 | hidden: Hidden state. 128 | use_cache (bool): Whether to use cached history. 129 | 130 | Returns: 131 | Tuple[torch.Tensor, torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: Updated key, value, and history. 132 | """ 133 | if hidden is None or not use_cache: 134 | new_k = k 135 | new_v = v 136 | else: 137 | k_history, v_history = hidden 138 | new_k = torch.cat([k_history, k], dim=1) 139 | new_v = torch.cat([v_history, v], dim=1) 140 | k_history = new_k.detach() 141 | v_history = new_v.detach() 142 | 143 | return new_k, new_v, (k_history, v_history) 144 | 145 | def forward( 146 | self, 147 | hidden_states: Optional[torch.FloatTensor], 148 | attention_mask: Optional[torch.FloatTensor] = None, 149 | layer_past: Optional[Tuple[torch.Tensor]] = None, 150 | head_mask: Optional[torch.FloatTensor] = None, 151 | use_cache: Optional[bool] = False, 152 | output_attentions: Optional[bool] = False, 153 | ) -> Union[ 154 | Tuple[torch.Tensor, Tuple[torch.Tensor]], 155 | Optional[Tuple[torch.Tensor, Tuple[torch.Tensor], Tuple[torch.Tensor, ...]]], 156 | ]: 157 | """ 158 | Forward pass of the ModuleFormerAttention module. 159 | 160 | Args: 161 | hidden_states (Optional[torch.FloatTensor]): Input hidden states. 162 | attention_mask (Optional[torch.FloatTensor]): Attention mask. 163 | layer_past (Optional[Tuple[torch.Tensor]]): Past layer state. 164 | head_mask (Optional[torch.FloatTensor]): Head mask. 165 | use_cache (Optional[bool]): Whether to use cached states. 166 | output_attentions (Optional[bool]): Whether to output attention weights. 167 | 168 | Returns: 169 | Union[Tuple[torch.Tensor, Tuple[torch.Tensor]], Optional[Tuple[...]]]: Tuple containing outputs. 170 | """ 171 | B, T, C = hidden_states.size() # batch size, sequence length, embedding dimensionality (n_embd) 172 | 173 | # calculate query, key, values 174 | q, aux_loss = self.q_proj.map(hidden_states) 175 | k = self.k_proj(hidden_states) 176 | v = self.v_proj(hidden_states) 177 | 178 | k, v, hidden = self.add_history(k, v, layer_past, use_cache) 179 | context_length = k.size(1) 180 | 181 | q = q.view(B, T, self.top_k, self.n_head, self.head_size) # (B, T, k, nh, hs) 182 | k = k.view(B, context_length, self.n_head, self.head_size) # (B, T, nh, hs) 183 | v = v.view(B, context_length, self.n_head, self.head_size) # (B, T, nh, hs) 184 | 185 | mask = torch.tril(torch.ones(context_length, context_length, dtype=torch.int8, device=q.device))[context_length - T:, :] 186 | cum_weight=torch.tril(torch.ones(context_length, context_length, device=q.device), -1).type_as(q) 187 | 188 | y, attn_weights = stickbreaking_att(q, k, v, mask=mask, cum_weight=cum_weight, att_mask=attention_mask) 189 | 190 | # output projection 191 | y = self.q_proj.reduce(y.reshape(B, T, self.top_k, self.att_hidden).type_as(hidden_states)) 192 | 193 | y = y.view(B, T, C) # re-assemble all head outputs side by side 194 | 195 | outputs = (y, hidden, aux_loss) 196 | if output_attentions: 197 | outputs += (attn_weights,) 198 | return outputs 199 | 200 | 201 | class ModuleFormerBlock(nn.Module): 202 | def __init__(self, config): 203 | """ 204 | Initialize the ModuleFormerBlock module. 205 | 206 | Args: 207 | config: Configuration object with model hyperparameters. 208 | """ 209 | super().__init__() 210 | self.ln_1 = nn.LayerNorm(config.n_embd) 211 | self.attn = ModuleFormerAttention(config) 212 | self.ln_2 = nn.LayerNorm(config.n_embd) 213 | self.mlpf = MoE( 214 | input_size=config.n_embd, 215 | head_size=config.ffd_hidden, 216 | num_experts=config.n_mlp_experts, 217 | top_k=config.k_mlp, 218 | bias=False, 219 | activation=get_activation(config.activation_function), 220 | acc_aux_loss=False, 221 | gating_dropout=config.moe_pdrop, 222 | sample_topk=config.sample_topk, 223 | gating_size=config.gating_size, 224 | aux_loss=config.aux_loss_type, 225 | gate_type=config.gate_type, 226 | ) 227 | self.resid_dropout = nn.Dropout(config.resid_pdrop) 228 | 229 | def get_aux_loss_and_clear(self): 230 | """ 231 | Get auxiliary loss and clear auxiliary loss accumulators in the attention and MLP layers. 232 | 233 | Returns: 234 | torch.Tensor: Auxiliary loss. 235 | """ 236 | return self.attn.q_proj.get_aux_loss_and_clear() + self.mlpf.get_aux_loss_and_clear() 237 | 238 | 239 | def forward( 240 | self, 241 | hidden_states: Optional[torch.FloatTensor], 242 | layer_past: Optional[Tuple[torch.Tensor]] = None, 243 | attention_mask: Optional[torch.FloatTensor] = None, 244 | head_mask: Optional[torch.FloatTensor] = None, 245 | use_cache: Optional[bool] = False, 246 | output_attentions: Optional[bool] = False, 247 | ) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]: 248 | """ 249 | Forward pass of the ModuleFormerBlock module. 250 | 251 | Args: 252 | hidden_states (Optional[torch.FloatTensor]): Input hidden states. 253 | layer_past (Optional[Tuple[torch.Tensor]]): Past layer state. 254 | attention_mask (Optional[torch.FloatTensor]): Attention mask. 255 | head_mask (Optional[torch.FloatTensor]): Head mask. 256 | use_cache (Optional[bool]): Whether to use cached states. 257 | output_attentions (Optional[bool]): Whether to output attention weights. 258 | 259 | Returns: 260 | Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]: 261 | Tuple containing outputs or optional attention weights. 262 | """ 263 | attn_outputs = self.attn( 264 | self.ln_1(hidden_states), 265 | layer_past=layer_past, 266 | attention_mask=attention_mask, 267 | head_mask=head_mask, 268 | use_cache=use_cache, 269 | output_attentions=output_attentions, 270 | ) 271 | attn_output = attn_outputs[0] # output_attn: a, present, (attentions) 272 | hidden = attn_outputs[1] 273 | att_aux_loss = attn_outputs[2] 274 | 275 | hidden_states = hidden_states + self.resid_dropout(attn_output) 276 | x_mlp, mlp_aux_loss = self.mlpf(self.ln_2(hidden_states)) 277 | hidden_states = hidden_states + self.resid_dropout(x_mlp) 278 | 279 | aux_loss = att_aux_loss + mlp_aux_loss 280 | return (hidden_states, hidden, aux_loss) + attn_outputs[3:] 281 | 282 | 283 | class ModuleFormerPreTrainedModel(PreTrainedModel): 284 | """ 285 | An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained 286 | models. 287 | """ 288 | 289 | config_class = ModuleFormerConfig 290 | base_model_prefix = "transformer" 291 | supports_gradient_checkpointing = True 292 | _no_split_modules = ["ModuleFormerBlock"] 293 | 294 | def __init__(self, *inputs, **kwargs): 295 | """ 296 | Initialize the ModuleFormerPreTrainedModel. 297 | 298 | Args: 299 | *inputs: Variable length input arguments. 300 | **kwargs: Keyword arguments. 301 | """ 302 | super().__init__(*inputs, **kwargs) 303 | 304 | self.gradient_checkpointing = False 305 | 306 | def _init_weights(self, module): 307 | """Initialize the weights.""" 308 | if isinstance(module, (nn.Linear,)): 309 | # Slightly different from Mesh Transformer JAX which uses truncated_normal for initialization 310 | # cf https://github.com/pytorch/pytorch/pull/5617 311 | module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) 312 | if module.bias is not None: 313 | module.bias.data.zero_() 314 | elif isinstance(module, nn.Embedding): 315 | module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) 316 | if module.padding_idx is not None: 317 | module.weight.data[module.padding_idx].zero_() 318 | elif isinstance(module, nn.LayerNorm): 319 | module.bias.data.zero_() 320 | module.weight.data.fill_(1.0) 321 | 322 | def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs={}): 323 | for module in self.modules(): 324 | if hasattr(module, "gradient_checkpointing"): 325 | self._set_gradient_checkpointing( 326 | module, True, gradient_checkpointing_kwargs 327 | ) 328 | 329 | def gradient_checkpointing_disable(self): 330 | for module in self.modules(): 331 | if hasattr(module, "gradient_checkpointing"): 332 | self._set_gradient_checkpointing( 333 | module, False 334 | ) 335 | 336 | def _set_gradient_checkpointing( 337 | self, 338 | module, 339 | value=False, 340 | gradient_checkpointing_kwargs={"use_reentrant": False}, 341 | ): 342 | """ 343 | Set gradient checkpointing for the ModuleFormerModel. 344 | 345 | Args: 346 | module: The module for which gradient checkpointing is set. 347 | value (bool): Whether to enable gradient checkpointing. 348 | """ 349 | if isinstance(module, ModuleFormerModel): 350 | module.gradient_checkpointing = value 351 | module.gradient_checkpointing_kwargs = gradient_checkpointing_kwargs 352 | 353 | 354 | SPARSEGPT_START_DOCSTRING = r""" 355 | This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use 356 | it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and 357 | behavior. 358 | 359 | Parameters: 360 | config ([`ModuleFormerConfig`]): Model configuration class with all the parameters of the model. 361 | Initializing with a config file does not load the weights associated with the model, only the 362 | configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. 363 | """ 364 | 365 | SPARSEGPT_INPUTS_DOCSTRING = r""" 366 | Args: 367 | input_ids (`torch.LongTensor` of shape `({0})`): 368 | Indices of input sequence tokens in the vocabulary. 369 | 370 | Indices can be obtained using [`AutoProcenizer`]. See [`PreTrainedTokenizer.encode`] and 371 | [`PreTrainedTokenizer.__call__`] for details. 372 | 373 | [What are input IDs?](../glossary#input-ids) 374 | attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*): 375 | Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: 376 | 377 | - 1 for tokens that are **not masked**, 378 | - 0 for tokens that are **masked**. 379 | 380 | [What are attention masks?](../glossary#attention-mask) 381 | token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*): 382 | Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 383 | 1]`: 384 | 385 | - 0 corresponds to a *sentence A* token, 386 | - 1 corresponds to a *sentence B* token. 387 | 388 | [What are token type IDs?](../glossary#token-type-ids) 389 | position_ids (`torch.LongTensor` of shape `({0})`, *optional*): 390 | Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, 391 | config.n_positions - 1]`. 392 | 393 | [What are position IDs?](../glossary#position-ids) 394 | head_mask (`torch.FloatTensor` of shape `(num_attention_heads,)` or `(n_layer, num_attention_heads)`, *optional*): 395 | Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`: 396 | 397 | - 1 indicates the head is **not masked**, 398 | - 0 indicates the head is **masked**. 399 | 400 | inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_dim)`, *optional*): 401 | Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This 402 | is useful if you want more control over how to convert *input_ids* indices into associated vectors than the 403 | model's internal embedding lookup matrix. 404 | output_attentions (`bool`, *optional*): 405 | Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned 406 | tensors for more detail. 407 | output_hidden_states (`bool`, *optional*): 408 | Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for 409 | more detail. 410 | return_dict (`bool`, *optional*): 411 | Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. 412 | """ 413 | 414 | 415 | @add_start_docstrings( 416 | "The bare ModuleFormer Model transformer outputting raw hidden-states without any specific head on top.", 417 | SPARSEGPT_START_DOCSTRING, 418 | ) 419 | class ModuleFormerModel(ModuleFormerPreTrainedModel): 420 | def __init__(self, config): 421 | super().__init__(config) 422 | 423 | self.embed_dim = config.n_embd 424 | self.vocab_size = config.vocab_size 425 | self.wte = nn.Embedding(config.vocab_size, config.n_embd) 426 | self.drop = nn.Dropout(config.embd_pdrop) 427 | self.h = nn.ModuleList([ModuleFormerBlock(config) for _ in range(config.n_layer)]) 428 | self.ln_f = nn.LayerNorm(config.n_embd) 429 | 430 | # Initialize weights and apply final processing 431 | self.post_init() 432 | 433 | def get_input_embeddings(self): 434 | return self.wte 435 | 436 | def set_input_embeddings(self, new_embeddings): 437 | self.wte = new_embeddings 438 | 439 | @add_start_docstrings_to_model_forward(SPARSEGPT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) 440 | @add_code_sample_docstrings( 441 | checkpoint=_CHECKPOINT_FOR_DOC, 442 | output_type=BaseModelOutputWithPast, 443 | config_class=_CONFIG_FOR_DOC, 444 | ) 445 | def forward( 446 | self, 447 | input_ids: Optional[torch.LongTensor] = None, 448 | past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, 449 | attention_mask: Optional[torch.FloatTensor] = None, 450 | token_type_ids: Optional[torch.LongTensor] = None, 451 | head_mask: Optional[torch.FloatTensor] = None, 452 | inputs_embeds: Optional[torch.FloatTensor] = None, 453 | use_cache: Optional[bool] = None, 454 | output_attentions: Optional[bool] = None, 455 | output_hidden_states: Optional[bool] = None, 456 | return_dict: Optional[bool] = None, 457 | ) -> Union[Tuple, BaseModelOutputWithPast]: 458 | output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions 459 | output_hidden_states = ( 460 | output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states 461 | ) 462 | use_cache = use_cache if use_cache is not None else self.config.use_cache 463 | return_dict = return_dict if return_dict is not None else self.config.use_return_dict 464 | 465 | if input_ids is not None and inputs_embeds is not None: 466 | raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") 467 | elif input_ids is not None: 468 | input_shape = input_ids.size() 469 | input_ids = input_ids.view(-1, input_shape[-1]) 470 | batch_size = input_ids.shape[0] 471 | elif inputs_embeds is not None: 472 | input_shape = inputs_embeds.size()[:-1] 473 | batch_size = inputs_embeds.shape[0] 474 | else: 475 | raise ValueError("You have to specify either input_ids or inputs_embeds") 476 | 477 | if token_type_ids is not None: 478 | token_type_ids = token_type_ids.view(-1, input_shape[-1]) 479 | 480 | if past_key_values is None: 481 | past_key_values = tuple([None] * len(self.h)) 482 | 483 | # Attention mask. 484 | if attention_mask is not None: 485 | if batch_size <= 0: 486 | raise ValueError("batch_size has to be defined and > 0") 487 | attention_mask = attention_mask.view(batch_size, -1) 488 | # We create a 3D attention mask from a 2D tensor mask. 489 | # Sizes are [batch_size, 1, 1, to_seq_length] 490 | # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length] 491 | # this attention mask is more simple than the triangular masking of causal attention 492 | # used in OpenAI GPT, we just need to prepare the broadcast dimension here. 493 | attention_mask = attention_mask[:, None, None, None, :] 494 | 495 | # Since attention_mask is 1.0 for positions we want to attend and 0.0 for 496 | # masked positions, this operation will create a tensor which is 0.0 for 497 | # positions we want to attend and the dtype's smallest value for masked positions. 498 | # Since we are adding it to the raw scores before the softmax, this is 499 | # effectively the same as removing these entirely. 500 | attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility 501 | attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min 502 | 503 | # Prepare head mask if needed 504 | # 1.0 in head_mask indicate we keep the head 505 | # attention_probs has shape bsz x num_attention_heads x N x N 506 | # head_mask has shape n_layer x batch x num_attention_heads x N x N 507 | head_mask = self.get_head_mask(head_mask, self.config.n_layer) 508 | 509 | if inputs_embeds is None: 510 | inputs_embeds = self.wte(input_ids) 511 | 512 | hidden_states = inputs_embeds 513 | 514 | if token_type_ids is not None: 515 | token_type_embeds = self.wte(token_type_ids) 516 | hidden_states = hidden_states + token_type_embeds 517 | 518 | hidden_states = self.drop(hidden_states) 519 | 520 | output_shape = input_shape + (hidden_states.size(-1),) 521 | 522 | if self.gradient_checkpointing and self.training: 523 | if use_cache: 524 | logger.warning_once( 525 | "`use_cache=True` is incompatible with `config.gradient_checkpointing=True`. Setting " 526 | "`use_cache=False`..." 527 | ) 528 | use_cache = False 529 | 530 | presents = () if use_cache else None 531 | all_self_attentions = () if output_attentions else None 532 | all_hidden_states = () if output_hidden_states else None 533 | self.aux_loss = 0 534 | for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)): 535 | if output_hidden_states: 536 | all_hidden_states = all_hidden_states + (hidden_states,) 537 | 538 | if self.gradient_checkpointing and self.training: 539 | 540 | def create_custom_forward(module): 541 | def custom_forward(*inputs): 542 | # None for past_key_value 543 | return module(*inputs, use_cache, output_attentions) 544 | 545 | return custom_forward 546 | 547 | outputs = torch.utils.checkpoint.checkpoint( 548 | create_custom_forward(block), 549 | hidden_states, 550 | None, 551 | attention_mask, 552 | head_mask[i], 553 | **self.gradient_checkpointing_kwargs, 554 | ) 555 | else: 556 | outputs = block( 557 | hidden_states, 558 | layer_past=layer_past, 559 | attention_mask=attention_mask, 560 | head_mask=head_mask[i], 561 | use_cache=use_cache, 562 | output_attentions=output_attentions, 563 | ) 564 | 565 | hidden_states = outputs[0] 566 | if use_cache is True: 567 | presents = presents + (outputs[1],) 568 | 569 | self.aux_loss = self.aux_loss + outputs[2] 570 | 571 | if output_attentions: 572 | all_self_attentions = all_self_attentions + (outputs[3],) 573 | 574 | hidden_states = self.ln_f(hidden_states) 575 | 576 | hidden_states = hidden_states.view(output_shape) 577 | # Add last hidden state 578 | if output_hidden_states: 579 | all_hidden_states = all_hidden_states + (hidden_states,) 580 | 581 | if not return_dict: 582 | return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None) 583 | 584 | return BaseModelOutputWithPast( 585 | last_hidden_state=hidden_states, 586 | past_key_values=presents, 587 | hidden_states=all_hidden_states, 588 | attentions=all_self_attentions, 589 | ) 590 | 591 | 592 | @add_start_docstrings( 593 | """ 594 | The ModuleFormer Model transformer with a language modeling head on top. 595 | """, 596 | SPARSEGPT_START_DOCSTRING, 597 | ) 598 | class ModuleFormerForCausalLM(ModuleFormerPreTrainedModel): 599 | _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.causal_mask"] 600 | 601 | def __init__(self, config): 602 | super().__init__(config) 603 | self.transformer = ModuleFormerModel(config) 604 | self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) 605 | 606 | self.aux_loss_weight = config.aux_loss_weight 607 | 608 | # Initialize weights and apply final processing 609 | self.post_init() 610 | 611 | def get_output_embeddings(self): 612 | return self.lm_head 613 | 614 | def set_output_embeddings(self, new_embeddings): 615 | self.lm_head = new_embeddings 616 | 617 | def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **kwargs): 618 | token_type_ids = kwargs.get("token_type_ids", None) 619 | # only last token for inputs_ids if past is defined in kwargs 620 | if past_key_values: 621 | input_ids = input_ids[:, -1].unsqueeze(-1) 622 | if token_type_ids is not None: 623 | token_type_ids = token_type_ids[:, -1].unsqueeze(-1) 624 | 625 | attention_mask = kwargs.get("attention_mask", None) 626 | 627 | return { 628 | "input_ids": input_ids, 629 | "past_key_values": past_key_values, 630 | "use_cache": kwargs.get("use_cache"), 631 | "attention_mask": attention_mask, 632 | "token_type_ids": token_type_ids, 633 | } 634 | 635 | @add_start_docstrings_to_model_forward(SPARSEGPT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) 636 | @add_code_sample_docstrings( 637 | checkpoint=_CHECKPOINT_FOR_DOC, 638 | output_type=CausalLMOutputWithPast, 639 | config_class=_CONFIG_FOR_DOC, 640 | ) 641 | def forward( 642 | self, 643 | input_ids: Optional[torch.LongTensor] = None, 644 | past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, 645 | attention_mask: Optional[torch.FloatTensor] = None, 646 | token_type_ids: Optional[torch.LongTensor] = None, 647 | head_mask: Optional[torch.FloatTensor] = None, 648 | inputs_embeds: Optional[torch.FloatTensor] = None, 649 | labels: Optional[torch.LongTensor] = None, 650 | use_cache: Optional[bool] = None, 651 | output_attentions: Optional[bool] = None, 652 | output_hidden_states: Optional[bool] = None, 653 | return_dict: Optional[bool] = None, 654 | ) -> Union[Tuple, CausalLMOutputWithPast]: 655 | r""" 656 | labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): 657 | Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set 658 | `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100` 659 | are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]` 660 | """ 661 | return_dict = return_dict if return_dict is not None else self.config.use_return_dict 662 | 663 | transformer_outputs = self.transformer( 664 | input_ids, 665 | past_key_values=past_key_values, 666 | attention_mask=attention_mask, 667 | token_type_ids=token_type_ids, 668 | head_mask=head_mask, 669 | inputs_embeds=inputs_embeds, 670 | use_cache=use_cache, 671 | output_attentions=output_attentions, 672 | output_hidden_states=output_hidden_states, 673 | return_dict=return_dict, 674 | ) 675 | hidden_states = transformer_outputs[0] 676 | 677 | # make sure sampling in fp16 works correctly and 678 | # compute loss in fp32 to match with mesh-tf version 679 | # https://github.com/EleutherAI/gpt-neo/blob/89ce74164da2fb16179106f54e2269b5da8db333/models/gpt2/gpt2.py#L179 680 | lm_logits = self.lm_head(hidden_states).to(torch.float32) 681 | 682 | loss = None 683 | if labels is not None: 684 | # Shift so that tokens < n predict n 685 | shift_logits = lm_logits[..., :-1, :].contiguous() 686 | shift_labels = labels[..., 1:].contiguous() 687 | # Flatten the tokens 688 | loss_fct = CrossEntropyLoss() 689 | loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)) 690 | 691 | loss = loss.to(hidden_states.dtype) 692 | 693 | if self.aux_loss_weight > 0: 694 | loss = loss + self.transformer.aux_loss * self.aux_loss_weight 695 | 696 | if not return_dict: 697 | output = (lm_logits,) + transformer_outputs[1:] 698 | return ((loss,) + output) if loss is not None else output 699 | 700 | return CausalLMOutputWithPast( 701 | loss=loss, 702 | logits=lm_logits, 703 | past_key_values=transformer_outputs.past_key_values, 704 | hidden_states=transformer_outputs.hidden_states, 705 | attentions=transformer_outputs.attentions, 706 | ) 707 | 708 | @staticmethod 709 | def _reorder_cache( 710 | past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor 711 | ) -> Tuple[Tuple[torch.Tensor]]: 712 | """ 713 | This function is used to re-order the `past_key_values` cache if [`~PretrainedModel.beam_search`] or 714 | [`~PretrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct 715 | beam_idx at every generation step. 716 | """ 717 | return tuple( 718 | tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past) 719 | for layer_past in past_key_values 720 | ) 721 | 722 | @add_start_docstrings( 723 | """ 724 | The ModuleFormer Model with a sequence classification head on top (linear layer). 725 | 726 | [`ModuleFormerForSequenceClassification`] uses the last token in order to do the classification, as other causal models 727 | (e.g. GPT-1) do. 728 | 729 | Since it does classification on the last token, it requires to know the position of the last token. If a 730 | `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If 731 | no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the 732 | padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in 733 | each row of the batch). 734 | """, 735 | SPARSEGPT_START_DOCSTRING, 736 | ) 737 | class ModuleFormerForSequenceClassification(ModuleFormerPreTrainedModel): 738 | _keys_to_ignore_on_load_missing = [ 739 | # r"h\.\d+\.attn\.masked_bias", 740 | r"lm_head.weight" 741 | ] 742 | 743 | def __init__(self, config): 744 | super().__init__(config) 745 | self.num_labels = config.num_labels 746 | self.transformer = ModuleFormerModel(config) 747 | self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False) 748 | 749 | # Initialize weights and apply final processing 750 | self.post_init() 751 | 752 | @add_start_docstrings_to_model_forward(SPARSEGPT_INPUTS_DOCSTRING) 753 | @add_code_sample_docstrings( 754 | checkpoint=_CHECKPOINT_FOR_DOC, 755 | output_type=SequenceClassifierOutputWithPast, 756 | config_class=_CONFIG_FOR_DOC, 757 | ) 758 | def forward( 759 | self, 760 | input_ids: Optional[torch.Tensor] = None, 761 | past_key_values: Optional[Tuple[torch.FloatTensor]] = None, 762 | attention_mask: Optional[torch.Tensor] = None, 763 | token_type_ids: Optional[torch.Tensor] = None, 764 | head_mask: Optional[torch.Tensor] = None, 765 | inputs_embeds: Optional[torch.Tensor] = None, 766 | labels: Optional[torch.Tensor] = None, 767 | use_cache: Optional[bool] = None, 768 | output_attentions: Optional[bool] = None, 769 | output_hidden_states: Optional[bool] = None, 770 | return_dict: Optional[bool] = None, 771 | ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutputWithPast]: 772 | r""" 773 | labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): 774 | Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., 775 | config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If 776 | `config.num_labels > 1` a classification loss is computed (Cross-Entropy). 777 | """ 778 | return_dict = return_dict if return_dict is not None else self.config.use_return_dict 779 | 780 | transformer_outputs = self.transformer( 781 | input_ids, 782 | past_key_values=past_key_values, 783 | attention_mask=attention_mask, 784 | token_type_ids=token_type_ids, 785 | head_mask=head_mask, 786 | inputs_embeds=inputs_embeds, 787 | use_cache=use_cache, 788 | output_attentions=output_attentions, 789 | output_hidden_states=output_hidden_states, 790 | return_dict=return_dict, 791 | ) 792 | hidden_states = transformer_outputs[0] 793 | logits = self.score(hidden_states) 794 | 795 | if input_ids is not None: 796 | batch_size, sequence_length = input_ids.shape[:2] 797 | else: 798 | batch_size, sequence_length = inputs_embeds.shape[:2] 799 | 800 | if self.config.pad_token_id is None and batch_size != 1: 801 | raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") 802 | if self.config.pad_token_id is None: 803 | sequence_lengths = -1 804 | else: 805 | if input_ids is not None: 806 | sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device) 807 | else: 808 | sequence_lengths = -1 809 | logger.warning( 810 | f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be " 811 | "unexpected if using padding tokens in conjunction with `inputs_embeds.`" 812 | ) 813 | 814 | pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths] 815 | 816 | loss = None 817 | if labels is not None: 818 | if self.config.problem_type is None: 819 | if self.num_labels == 1: 820 | self.config.problem_type = "regression" 821 | elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): 822 | self.config.problem_type = "single_label_classification" 823 | else: 824 | self.config.problem_type = "multi_label_classification" 825 | 826 | if self.config.problem_type == "regression": 827 | loss_fct = MSELoss() 828 | if self.num_labels == 1: 829 | loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) 830 | else: 831 | loss = loss_fct(pooled_logits, labels) 832 | elif self.config.problem_type == "single_label_classification": 833 | loss_fct = CrossEntropyLoss() 834 | loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1)) 835 | elif self.config.problem_type == "multi_label_classification": 836 | loss_fct = BCEWithLogitsLoss() 837 | loss = loss_fct(pooled_logits, labels) 838 | if not return_dict: 839 | output = (pooled_logits,) + transformer_outputs[1:] 840 | return ((loss,) + output) if loss is not None else output 841 | 842 | return SequenceClassifierOutputWithPast( 843 | loss=loss, 844 | logits=pooled_logits, 845 | past_key_values=transformer_outputs.past_key_values, 846 | hidden_states=transformer_outputs.hidden_states, 847 | attentions=transformer_outputs.attentions, 848 | ) -------------------------------------------------------------------------------- /moduleformer/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/ModuleFormer/850f1eb7804fbd644ca60437277448c162350a6c/moduleformer/utils/__init__.py -------------------------------------------------------------------------------- /moduleformer/utils/gate.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | from typing import Any, Dict, List, Optional 5 | 6 | # @torch.jit.script 7 | def log_gmm_posterior(z, expert_centroids): 8 | """ 9 | Compute the log posterior probabilities of data points z belonging to Gaussian mixture components defined by centroids. 10 | 11 | Args: 12 | z (torch.Tensor): Data points (batch_size x feature_dim). 13 | expert_centroids (torch.Tensor): Centroids of Gaussian mixture components (num_experts x feature_dim). 14 | 15 | Returns: 16 | torch.Tensor: Log posterior probabilities for each data point (batch_size x num_experts). 17 | """ 18 | return ( 19 | torch.matmul(z, expert_centroids.t()) 20 | # - 0.5 * ( 21 | # torch.einsum('ni,ni->n', z, z)[:, None] + 22 | # torch.einsum('ni,ni->n', expert_centroids, expert_centroids)[None, :] 23 | # ) 24 | ) 25 | 26 | 27 | @torch.jit.script 28 | def compute_gating(k: int, probs: torch.Tensor, top_k_gates: torch.Tensor, top_k_indices: torch.Tensor): 29 | """ 30 | Compute gating values for the mixture of experts based on probabilities and top-k indices. 31 | 32 | Args: 33 | k (int): Number of experts to select. 34 | probs (torch.Tensor): Probability values for each expert (batch_size x num_experts). 35 | top_k_gates (torch.Tensor): Gating values for top-k experts (batch_size x k). 36 | top_k_indices (torch.Tensor): Indices of top-k experts (batch_size x k). 37 | 38 | Returns: 39 | torch.Tensor: Batch-level gating values. 40 | torch.Tensor: Batch-level expert indices. 41 | torch.Tensor: Expert size for each expert. 42 | torch.Tensor: Sorted indices of top-k experts. 43 | """ 44 | zeros = torch.zeros_like(probs) 45 | gates = zeros.scatter(1, top_k_indices, 1) 46 | expert_size = gates.long().sum(0) 47 | top_k_gates = top_k_gates.flatten() 48 | top_k_experts = top_k_indices.flatten() 49 | _, index_sorted_experts = top_k_experts.sort(0) 50 | batch_index = index_sorted_experts.div(k, rounding_mode='trunc') 51 | batch_gates = top_k_gates[index_sorted_experts] 52 | return batch_gates, batch_index, expert_size, index_sorted_experts 53 | 54 | 55 | class top_k_gating(nn.Module): 56 | def __init__( 57 | self, 58 | input_size, 59 | num_experts, 60 | top_k, 61 | acc_aux_loss=False, 62 | dropout=0.1, 63 | hidden_size=256, 64 | sample_topk=0, 65 | aux_loss='mi', 66 | gate_type='mlp', 67 | ): 68 | """ 69 | Initialize the top-k gating mechanism. 70 | 71 | Args: 72 | input_size (int): Size of the input. 73 | num_experts (int): Number of experts. 74 | top_k (int): Number of top experts to select. 75 | acc_aux_loss (bool): Whether to accumulate auxiliary loss statistics. 76 | dropout (float): Dropout rate for gating network. 77 | hidden_size (int): Hidden size of the gating network. 78 | sample_topk (int): Number of top-k experts to sample during training. 79 | aux_loss (str): Type of auxiliary loss ('mi' or 'switch'). 80 | gate_type (str): Type of gating mechanism ('mlp', 'linear', or 'gmm'). 81 | """ 82 | super().__init__() 83 | 84 | self.num_experts = num_experts 85 | self.input_size = input_size 86 | assert top_k <= num_experts 87 | self.top_k = top_k 88 | assert sample_topk <= top_k 89 | self.sample_topk = sample_topk 90 | 91 | self.acc_aux_loss = acc_aux_loss 92 | self.aux_loss = aux_loss 93 | self.init_aux_statistics() 94 | 95 | self.gate_type = gate_type 96 | if gate_type == 'mlp': 97 | self.w_gate = nn.Sequential( 98 | nn.Linear(input_size, hidden_size), 99 | nn.GELU(), 100 | nn.Dropout(dropout), 101 | nn.Linear(hidden_size, num_experts, bias=False) 102 | ) 103 | elif gate_type == 'linear': 104 | self.w_gate = nn.Sequential( 105 | nn.Linear(input_size, num_experts, bias=False) 106 | ) 107 | elif gate_type == 'gmm': 108 | self.w_gate = nn.Linear(input_size, hidden_size, bias=False) 109 | self.expert_centroids = nn.Parameter(torch.empty(num_experts, hidden_size)) 110 | nn.init.normal_(self.expert_centroids) 111 | self.temperature = nn.Parameter(torch.zeros(1)) 112 | else: 113 | print(gate_type) 114 | raise NotImplementedError 115 | 116 | def extra_repr(self): 117 | """ 118 | Return extra representation string for the module. 119 | """ 120 | return 'k={}, num_experts={}, aux_loss={}'.format( 121 | self.top_k, self.num_experts, self.aux_loss) 122 | 123 | def init_aux_statistics(self): 124 | """ 125 | Initialize auxiliary statistics based on the chosen auxiliary loss type. 126 | """ 127 | if self.aux_loss == 'mi': 128 | self.p_e = 0. 129 | self.neg_H_e_given_x = 0. 130 | self.count_layers = 0 131 | else: 132 | self.acc_probs = 0. 133 | self.acc_freq = 0. 134 | self.acc_lsesq = 0. 135 | self.acc_count = 0 136 | 137 | def update_aux_statistics(self, probs, logits, gates, skip_mask=None): 138 | """ 139 | Update auxiliary statistics based on the current batch. 140 | 141 | Args: 142 | probs (torch.Tensor): Probability values for each expert. 143 | logits (torch.Tensor): Logits values for each expert. 144 | gates (torch.Tensor): Gating values for each expert. 145 | skip_mask (torch.Tensor): Skip mask tensor. 146 | 147 | """ 148 | if self.aux_loss == 'mi': 149 | log_prob = torch.log_softmax(logits, dim=-1) 150 | self.p_e = self.p_e + probs.mean(0) 151 | self.neg_H_e_given_x = self.neg_H_e_given_x + (probs * log_prob).sum() / probs.size(0) 152 | self.count_layers += 1 153 | else: 154 | self.acc_count = self.acc_count + logits.size(0) 155 | self.acc_probs = self.acc_probs + probs.sum(0) 156 | self.acc_freq = self.acc_freq + (gates > 0).float().sum(0) 157 | lsesq = torch.log(torch.exp(logits).sum(dim=-1)) ** 2 158 | self.acc_lsesq = self.acc_lsesq + lsesq.sum() 159 | 160 | def get_aux_loss_and_clear(self, eps=1e-8): 161 | """ 162 | Calculate and return the auxiliary loss based on the accumulated statistics. 163 | 164 | Args: 165 | eps (float): Small epsilon value for numerical stability. 166 | 167 | Returns: 168 | torch.Tensor: The calculated auxiliary loss. 169 | """ 170 | if self.aux_loss == 'mi': 171 | denominator = self.count_layers 172 | p_e = self.p_e / denominator 173 | H_e = -(p_e * (p_e + eps).log()).sum() 174 | neg_H_e_given_x = self.neg_H_e_given_x / denominator 175 | miloss = -(neg_H_e_given_x + H_e) 176 | loss = miloss 177 | else: 178 | switchloss = self.num_experts * ( 179 | F.normalize(self.acc_probs, p=1, dim=0) * 180 | F.normalize(self.acc_freq, p=1, dim=0) 181 | ).sum() 182 | zloss = self.acc_lsesq / self.acc_count 183 | loss = switchloss + 0.1 * zloss 184 | 185 | self.init_aux_statistics() 186 | return loss 187 | 188 | def forward(self, x, skip_mask=None): 189 | """ 190 | Compute the top-k gating for the input. 191 | 192 | See paper: https://arxiv.org/abs/1701.06538. 193 | 194 | Args: 195 | x (torch.Tensor): Input tensor with shape [batch_size, input_size]. 196 | skip_mask (torch.Tensor): Skip mask tensor (binary) with the same shape as `x`. 197 | x: input Tensor with shape [batch_size, input_size] 198 | train: a boolean - we only add noise at training time. 199 | noise_epsilon: a float 200 | 201 | Returns: 202 | torch.Tensor: Top-k indices. 203 | torch.Tensor: Top-k gating values. 204 | torch.Tensor: Probability values for each expert. 205 | gates: a Tensor with shape [batch_size, num_experts] 206 | load: a Tensor with shape [num_experts] 207 | """ 208 | 209 | if self.gate_type in ['linear', 'mlp']: 210 | logits = self.w_gate(x) 211 | elif self.gate_type == 'gmm': 212 | z = self.w_gate(x) 213 | logits = log_gmm_posterior(F.normalize(z, p=2, dim=-1), F.normalize(self.expert_centroids, p=2, dim=-1)) * self.temperature.exp() 214 | 215 | probs = torch.softmax(logits, dim=1) 216 | if skip_mask is not None: 217 | probs = torch.masked_fill(probs, (skip_mask == 0), 0) 218 | logits = torch.masked_fill(logits, (skip_mask == 0), 0) 219 | 220 | if self.training and (self.sample_topk > 0): 221 | _, top_km1_indices = probs.topk(self.top_k - self.sample_topk, dim=1) 222 | masked_probs = probs + 1e-6 223 | masked_probs[torch.arange(probs.size(0)).unsqueeze( 224 | 1), top_km1_indices] = 0 225 | k_indices = torch.multinomial(masked_probs, self.sample_topk) 226 | top_k_indices = torch.cat([top_km1_indices, k_indices], dim=-1) 227 | top_k_gates = torch.gather(probs, 1, top_k_indices) 228 | else: 229 | top_k_gates, top_k_indices = probs.topk(self.top_k, dim=1) 230 | 231 | # if self.top_k > 1: 232 | # top_k_gates = top_k_gates / (top_k_gates.sum(dim=1, keepdim=True) + 1e-6) 233 | 234 | # gate = torch.zeros_like(top_k_gates) 235 | # gate[:, 0] = 1 236 | # top_k_gates = (gate - top_k_gates).detach() + top_k_gates 237 | 238 | zeros = torch.zeros_like(probs) 239 | gates = zeros.scatter(1, top_k_indices, top_k_gates) 240 | self.update_aux_statistics(probs, logits, gates, skip_mask) 241 | if not self.acc_aux_loss: 242 | self.loss = self.get_aux_loss_and_clear() 243 | else: 244 | self.loss = 0 245 | 246 | return top_k_indices, top_k_gates, probs 247 | 248 | # batch_gates, batch_index, expert_size, gates, index_sorted_experts = \ 249 | # compute_gating(self.top_k, probs, top_k_gates, top_k_indices) 250 | 251 | # return batch_gates, batch_index, expert_size.tolist(), gates, index_sorted_experts -------------------------------------------------------------------------------- /moduleformer/utils/moe.py: -------------------------------------------------------------------------------- 1 | import math 2 | from typing import List 3 | 4 | import torch 5 | import torch.nn as nn 6 | import torch.nn.functional as F 7 | 8 | from .parallel_experts import ParallelExperts 9 | from .gate import top_k_gating, compute_gating 10 | 11 | 12 | class MoE(nn.Module): 13 | """ 14 | A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts. 15 | 16 | 17 | Args: 18 | input_size: integer - size of the input 19 | head_size: integer - size of the expert's hidden layer 20 | num_experts: an integer - number of experts 21 | top_k: an integer - how many experts to use for each batch element 22 | bias: a boolean - whether to include bias in linear layers 23 | activation: an activation function to apply to expert's outputs 24 | acc_aux_loss: a boolean - whether to accumulate auxiliary loss 25 | hidden_size: an integer - hidden size of the experts 26 | gating_dropout: a float - dropout rate for gating network 27 | sample_topk: an integer - how many experts to sample during training 28 | gating_size: an integer - size of the gating network 29 | aux_loss: a string - type of auxiliary loss ('mi' or 'sparse') 30 | gate_type: a string - type of gating mechanism ('mlp' or 'topk') 31 | """ 32 | 33 | def __init__( 34 | self, 35 | input_size, 36 | head_size, 37 | num_experts, 38 | top_k, 39 | bias=False, 40 | activation=None, 41 | acc_aux_loss=False, 42 | hidden_size=None, 43 | gating_dropout=0.0, 44 | sample_topk=0, 45 | gating_size=256, 46 | aux_loss='mi', 47 | gate_type='mlp', 48 | ): 49 | super(MoE, self).__init__() 50 | 51 | self.num_experts = num_experts 52 | self.input_size = input_size 53 | self.head_size = head_size 54 | self.bias = bias 55 | self.experts = ParallelExperts(num_experts, input_size, head_size, bias) 56 | if hidden_size is None: 57 | hidden_size = head_size 58 | self.output_experts = ParallelExperts(num_experts, hidden_size, input_size, bias) 59 | self.top_k = min(top_k, self.num_experts) 60 | self.activation = activation 61 | 62 | self.gate = top_k_gating( 63 | input_size=input_size, 64 | num_experts=num_experts, 65 | top_k=top_k, 66 | acc_aux_loss=acc_aux_loss, 67 | dropout=gating_dropout, 68 | sample_topk=sample_topk, 69 | hidden_size=gating_size, 70 | aux_loss=aux_loss, 71 | gate_type=gate_type, 72 | ) 73 | 74 | def extra_repr(self): 75 | return 'k={}'.format( 76 | self.top_k) 77 | 78 | def get_aux_loss_and_clear(self): 79 | """ 80 | Get the accumulated auxiliary loss and clear it. 81 | 82 | Returns: 83 | float: Accumulated auxiliary loss. 84 | """ 85 | 86 | return self.gate.get_aux_loss_and_clear() 87 | 88 | def compute_gate(self, moe_inp, skip_mask=None): 89 | """ 90 | Compute gating for the mixture of experts. 91 | 92 | Args: 93 | moe_inp (Tensor): Input tensor. 94 | skip_mask (Tensor): Skip mask tensor. 95 | 96 | Returns: 97 | float: Gating loss. 98 | """ 99 | 100 | top_k_indices, top_k_gates, probs = self.gate(moe_inp, skip_mask=skip_mask) 101 | self.batch_gates, self.batch_index, expert_size, self.index_sorted_experts =\ 102 | compute_gating(self.top_k, probs, top_k_gates, top_k_indices) 103 | self.expert_size = expert_size.tolist() 104 | return self.gate.loss 105 | 106 | def forward(self, x, skip_mask=None, sample_topk=0, multiply_by_gates=True): 107 | """ 108 | Forward pass of the mixture of experts layer. 109 | 110 | Args: 111 | x (Tensor): Input tensor. 112 | skip_mask (Tensor): Skip mask tensor. 113 | sample_topk (int): Number of experts to sample during training. 114 | multiply_by_gates (bool): Whether to multiply outputs by gating values. 115 | 116 | Returns: 117 | Tensor: Output tensor. 118 | float: Gating loss. 119 | """ 120 | bsz, length, emb_size = x.size() 121 | if skip_mask is not None: 122 | assert x.size()[:-1] == skip_mask.size(), \ 123 | "Skip mask should be same shape as `x`" 124 | skip_mask = skip_mask.flatten()[:, None] 125 | x = x.reshape(-1, emb_size) 126 | loss = self.compute_gate(x, skip_mask) 127 | 128 | expert_inputs = x[self.batch_index] 129 | h = self.experts(expert_inputs, self.expert_size) 130 | h = self.activation(h) 131 | expert_outputs = self.output_experts(h, self.expert_size) 132 | 133 | if multiply_by_gates: 134 | expert_outputs = expert_outputs * self.batch_gates[:, None] 135 | 136 | zeros = torch.zeros( 137 | (bsz * length, self.input_size), 138 | dtype=expert_outputs.dtype, device=expert_outputs.device) 139 | y = zeros.index_add(0, self.batch_index, expert_outputs) 140 | y = y.view(bsz, length, self.input_size) 141 | # assert torch.allclose(y, y_) 142 | return y, loss 143 | 144 | def map(self, x, skip_mask=None, sample_topk=0, return_indices=False): 145 | """ 146 | 147 | Args: 148 | x: tensor shape [batch_size, input_size] 149 | train: a boolean scalar. 150 | loss_coef: a scalar - multiplier on load-balancing losses 151 | 152 | Returns: 153 | y: a tensor with shape [batch_size, output_size]. 154 | extra_training_loss: a scalar. This should be added into the overall 155 | training loss of the model. The backpropagation of this loss 156 | encourages all experts to be approximately equally used across a batch. 157 | """ 158 | """ 159 | Map input through the mixture of experts layer. 160 | 161 | Args: 162 | x (Tensor): Input tensor. 163 | skip_mask (Tensor): Skip mask tensor. 164 | sample_topk (int): Number of experts to sample during training. 165 | return_indices (bool): Whether to return expert indices. 166 | 167 | Returns: 168 | Tensor: Output tensor. 169 | float: Gating loss. 170 | """ 171 | if skip_mask is not None: 172 | assert x.size()[:-1] == skip_mask.size(), \ 173 | "Skip mask should be same shape as `x`" 174 | bsz, length, emb_size = x.size() 175 | x = x.reshape(-1, emb_size) 176 | if skip_mask is not None: 177 | skip_mask = skip_mask.view(-1, 1) 178 | loss = self.compute_gate(x, skip_mask) 179 | 180 | expert_inputs = x[self.batch_index] 181 | expert_outputs = self.experts(expert_inputs, self.expert_size) 182 | 183 | zeros = torch.zeros((bsz * length * self.top_k, self.head_size), 184 | dtype=expert_outputs.dtype, device=expert_outputs.device) 185 | y = zeros.index_add(0, self.index_sorted_experts, expert_outputs) 186 | y = y.view(bsz, length, self.top_k, -1) 187 | return y, loss 188 | 189 | def reduce(self, x, multiply_by_gates=True): 190 | """ 191 | Reduce the mapped output. 192 | 193 | Args: 194 | x (Tensor): Mapped output tensor. 195 | multiply_by_gates (bool): Whether to multiply outputs by gating values. 196 | 197 | Returns: 198 | Tensor: Reduced output tensor. 199 | """ 200 | 201 | bsz, length, k, emb_size = x.size() 202 | x = x.reshape(-1, emb_size) 203 | 204 | expert_inputs = x[self.index_sorted_experts] 205 | expert_outputs = self.output_experts(expert_inputs, self.expert_size) 206 | 207 | if multiply_by_gates: 208 | expert_outputs = expert_outputs * self.batch_gates[:, None] 209 | 210 | zeros = torch.zeros((bsz * length, self.input_size), 211 | dtype=expert_outputs.dtype, device=expert_outputs.device) 212 | y = zeros.index_add(0, self.batch_index, expert_outputs) 213 | y = y.view(bsz, length, self.input_size) 214 | return y -------------------------------------------------------------------------------- /moduleformer/utils/parallel_experts.py: -------------------------------------------------------------------------------- 1 | import math 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | from torch.cuda.amp import custom_fwd, custom_bwd 6 | from typing import Any, Dict, List, Optional 7 | from torch import Tensor 8 | 9 | 10 | class ParallelLinear(torch.autograd.Function): 11 | """ 12 | A custom autograd function for Parallel Linear operation. 13 | """ 14 | 15 | @staticmethod 16 | @custom_fwd 17 | def forward(ctx, input, expert_size_list, weight, bias=None): 18 | """ 19 | Forward pass of the ParallelLinear operation. 20 | 21 | Args: 22 | ctx: Context object. 23 | input (Tensor): Input tensor. 24 | expert_size_list (List[int]): List of expert sizes. 25 | weight (Tensor): Weight tensor. 26 | bias (Optional[Tensor]): Bias tensor. 27 | 28 | Returns: 29 | Tensor: Output tensor. 30 | """ 31 | # expert_size_list: List[int] = expert_size.tolist() 32 | output = ParallelLinear.forward_scriptable(input, expert_size_list, weight, bias) 33 | # assert torch.allclose(ParallelLinear._forward_scriptable(input, expert_size, weight, bias), output) 34 | ctx.save_for_backward(input, weight, bias) 35 | ctx.expert_size_list = expert_size_list 36 | return output 37 | 38 | @staticmethod 39 | @torch.jit.script 40 | def forward_scriptable(input: Tensor, expert_size_list: List[int], 41 | weight: Tensor, bias: Optional[Tensor]): 42 | """ 43 | Scriptable forward pass of the ParallelLinear operation. 44 | 45 | Args: 46 | input (Tensor): Input tensor. 47 | expert_size_list (List[int]): List of expert sizes. 48 | weight (Tensor): Weight tensor. 49 | bias (Optional[Tensor]): Bias tensor. 50 | 51 | Returns: 52 | Tensor: Output tensor. 53 | """ 54 | output_buf: Tensor = torch.empty((input.size(0), weight.size(2)), 55 | device=input.device, dtype=input.dtype) 56 | num_linears = weight.size(0) 57 | 58 | input_list = input.split(expert_size_list, dim=0) 59 | output_buf_list = output_buf.split(expert_size_list) 60 | 61 | for i in range(num_linears): 62 | torch.mm(input_list[i], weight[i], out=output_buf_list[i]) 63 | 64 | if bias is not None: 65 | for i in range(num_linears): 66 | output_buf_list[i].add_(bias[i]) 67 | 68 | output = output_buf 69 | return output 70 | 71 | @staticmethod 72 | @custom_bwd 73 | def backward(ctx, grad_out): 74 | """ 75 | Backward pass of the ParallelLinear operation. 76 | 77 | Args: 78 | ctx: Context object. 79 | grad_out (Tensor): Gradient of the output. 80 | 81 | Returns: 82 | Tuple of Tensors: Gradients with respect to input, weight, and bias. 83 | """ 84 | input, weight, bias = ctx.saved_tensors 85 | expert_size_list = ctx.expert_size_list 86 | return ParallelLinear.backward_scriptable( 87 | grad_out, input, expert_size_list, 88 | weight, bias 89 | ) 90 | 91 | @staticmethod 92 | @torch.jit.script 93 | def backward_scriptable(grad_out: Tensor, 94 | input: Tensor, expert_size_list: List[int], 95 | weight: Tensor, bias: Optional[Tensor]): 96 | """ 97 | Scriptable backward pass of the ParallelLinear operation. 98 | 99 | Args: 100 | grad_out (Tensor): Gradient of the output. 101 | input (Tensor): Input tensor. 102 | expert_size_list (List[int]): List of expert sizes. 103 | weight (Tensor): Weight tensor. 104 | bias (Optional[Tensor]): Bias tensor. 105 | 106 | Returns: 107 | Tuple of Tensors: Gradients with respect to input, weight, and bias. 108 | """ 109 | num_linears = weight.size(0) 110 | input_list = input.t().split(expert_size_list, dim=1) 111 | grad_list = grad_out.split(expert_size_list, dim=0) 112 | 113 | d_input_buf = torch.empty_like(input) 114 | d_input_buf_list = d_input_buf.split(expert_size_list, dim=0) 115 | d_weight_buf = torch.empty_like(weight) 116 | 117 | weight_t = weight.permute(0, 2, 1) 118 | 119 | for i in range(num_linears): 120 | torch.mm(grad_list[i], weight_t[i], out=d_input_buf_list[i]) 121 | torch.mm(input_list[i], grad_list[i], out=d_weight_buf[i]) 122 | 123 | d_input = d_input_buf 124 | d_weight = d_weight_buf 125 | 126 | if bias is not None: 127 | d_bias_buf = torch.empty_like(bias) 128 | for i in range(num_linears): 129 | torch.sum(grad_list[i], dim=0, keepdim=False, out=d_bias_buf[i]) 130 | d_bias = d_bias_buf 131 | else: 132 | d_bias = None 133 | 134 | return d_input, None, d_weight, d_bias 135 | 136 | 137 | class ParallelExperts(nn.Module): 138 | def __init__(self, num_experts, input_size, output_size, bias=False) -> None: 139 | """ 140 | Initialize the ParallelExperts module. 141 | 142 | Args: 143 | num_experts (int): Number of experts. 144 | input_size (int): Size of the input. 145 | output_size (int): Size of the output. 146 | bias (bool): Whether to include bias terms. 147 | """ 148 | super().__init__() 149 | # self.input_experts = nn.ModuleList( 150 | # [nn.Linear(input_size, output_size, bias=bias) for _ in range(num_experts)] 151 | # ) 152 | self.weight = nn.Parameter(torch.empty(num_experts, input_size, output_size)) 153 | if bias: 154 | self.bias = nn.Parameter(torch.zeros(num_experts, output_size)) 155 | else: 156 | self.bias = None 157 | self.reset_parameters() 158 | self.num_experts = num_experts 159 | self.input_size = input_size 160 | self.output_size = output_size 161 | 162 | def extra_repr(self): 163 | return 'num_experts={}, input_size={}, output_size={}'.format( 164 | self.num_experts, self.input_size, self.output_size) 165 | 166 | def reset_parameters(self) -> None: 167 | """ 168 | Reset the parameters of the model. 169 | """ 170 | # std = math.sqrt(2.0 / float(self.weight.size(1) + self.weight.size(2))) 171 | # a = math.sqrt(3.0) * std 172 | nn.init.uniform_(self.weight, -1. / self.weight.size(1), 1. / self.weight.size(1)) 173 | if self.bias is not None: 174 | fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight[0]) 175 | bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0 176 | nn.init.uniform_(self.bias, -bound, bound) 177 | 178 | def forward(self, inputs, expert_size): 179 | """ 180 | Forward pass of the ParallelExperts module. 181 | 182 | Args: 183 | inputs (Tensor): Input tensor. 184 | expert_size: Expert size information. 185 | 186 | Returns: 187 | Tensor: Output tensor. 188 | """ 189 | results = ParallelLinear.apply(inputs, expert_size, self.weight, self.bias) 190 | # expert_size_list: List[int] = expert_size.tolist() 191 | # input_list = inputs.split(expert_size_list, dim=0) 192 | # output_list = [] 193 | # for i in range(self.num_experts): 194 | # output_list.append(self.input_experts[i](input_list[i])) 195 | # results = torch.cat(output_list, dim=0) 196 | return results -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup(name='moduleformer', 4 | packages=find_packages(), 5 | install_requires=[ 6 | 'torch', 7 | 'transformers' 8 | ]) -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig, AutoModelForSequenceClassification 3 | from obsidian import SparseGPTForCausalLM, SparseGPTConfig, SparseGPTForSequenceClassification 4 | AutoConfig.register("sparsegpt", SparseGPTConfig) 5 | AutoModelForCausalLM.register(SparseGPTConfig, SparseGPTForCausalLM) 6 | AutoModelForSequenceClassification.register(SparseGPTConfig, SparseGPTForSequenceClassification) 7 | 8 | model_path = "/dccstor/codeai/yikang/pretrained_models/obsidian-8b-dolly" 9 | 10 | model = AutoModelForSequenceClassification.from_pretrained(model_path) 11 | 12 | x = torch.randint(low=10, high=101, size=(5, 7)) 13 | 14 | # 选择模型和tokenizer 15 | tokenizer = AutoTokenizer.from_pretrained(model_path) 16 | 17 | # 输入文本 18 | text = "The quick brown fox jumps over the lazy dog" 19 | 20 | # 对文本进行 tokenization 和 padding 21 | input_ids = tokenizer.encode(text, return_tensors="pt") 22 | 23 | y = model(input_ids) 24 | 25 | print(y) 26 | 27 | # print(input_ids.shape) 28 | # for i, o in enumerate(y): 29 | # print(i, type(o), (o.shape if 'ensor' in str(type(o)) else o)) 30 | 31 | # logits = y.logits 32 | # print(logits.shape) 33 | 34 | # prob = logits.softmax(dim = -1) 35 | 36 | # for i in range(1, input_ids.shape[1]): 37 | # print(input_ids[0,i], prob[0,i-1,input_ids[0,i]]) 38 | 39 | --------------------------------------------------------------------------------