arunvenkat17 commited on
Commit
a70826c
·
verified ·
1 Parent(s): 0914e72

Upload Param1MoEForCausalLM

Browse files
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation": "silu",
3
+ "architectures": [
4
+ "Param1MoEForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_param1MoE.Param7BMoEConfig",
9
+ "AutoModelForCausalLM": "modeling_param1MoE.Param1MoEForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "eos_token_id": 2,
13
+ "head_dim": 96,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 1536,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 512,
18
+ "max_position_embeddings": 4096,
19
+ "model_type": "param1MoE",
20
+ "num_attention_heads": 16,
21
+ "num_experts_per_tok": 8,
22
+ "num_hidden_layers": 40,
23
+ "num_key_value_heads": 4,
24
+ "num_local_experts": 64,
25
+ "output_router_logits": false,
26
+ "quantization_config": {
27
+ "_load_in_4bit": true,
28
+ "_load_in_8bit": false,
29
+ "bnb_4bit_compute_dtype": "bfloat16",
30
+ "bnb_4bit_quant_storage": "uint8",
31
+ "bnb_4bit_quant_type": "nf4",
32
+ "bnb_4bit_use_double_quant": false,
33
+ "llm_int8_enable_fp32_cpu_offload": false,
34
+ "llm_int8_has_fp16_weight": false,
35
+ "llm_int8_skip_modules": [
36
+ "lm_head",
37
+ "q_proj",
38
+ "k_proj",
39
+ "v_proj",
40
+ "gate",
41
+ "router",
42
+ "o_proj"
43
+ ],
44
+ "llm_int8_threshold": 6.0,
45
+ "load_in_4bit": true,
46
+ "load_in_8bit": false,
47
+ "quant_method": "bitsandbytes"
48
+ },
49
+ "rms_norm_eps": 1e-05,
50
+ "rope_theta": 1000.0,
51
+ "router_aux_loss_coef": 0.02,
52
+ "router_jitter_noise": 0.0,
53
+ "sliding_window": null,
54
+ "tie_word_embeddings": false,
55
+ "torch_dtype": "float16",
56
+ "transformers_version": "4.53.3",
57
+ "use_cache": true,
58
+ "vocab_size": 128000
59
+ }
configuration_param1MoE.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+ class Param7BMoEConfig(PretrainedConfig):
4
+ model_type = "param1MoE"
5
+ keys_to_ignore_at_inference = ["past_key_values"]
6
+ base_model_tp_plan = {
7
+ "layers.*.self_attn.q_proj": "colwise",
8
+ "layers.*.self_attn.k_proj": "colwise",
9
+ "layers.*.self_attn.v_proj": "colwise",
10
+ "layers.*.self_attn.o_proj": "rowwise",
11
+ "layers.*.block_sparse_moe.gate": "colwise_rep", # we need to replicate here to correctly route experts
12
+ "layers.*.block_sparse_moe.experts.*.w1": "colwise",
13
+ "layers.*.block_sparse_moe.experts.*.w2": "rowwise",
14
+ "layers.*.block_sparse_moe.experts.*.w3": "colwise",
15
+ }
16
+ base_model_pp_plan = {
17
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
18
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
19
+ "norm": (["hidden_states"], ["hidden_states"]),
20
+ }
21
+
22
+ def __init__(
23
+ self,
24
+ vocab_size=32000,
25
+ hidden_size=4096,
26
+ intermediate_size=14336,
27
+ num_hidden_layers=32,
28
+ num_attention_heads=32,
29
+ num_key_value_heads=8,
30
+ head_dim=None,
31
+ hidden_act="silu",
32
+ max_position_embeddings=4096 * 32,
33
+ initializer_range=0.02,
34
+ rms_norm_eps=1e-5,
35
+ use_cache=True,
36
+ pad_token_id=None,
37
+ bos_token_id=1,
38
+ eos_token_id=2,
39
+ tie_word_embeddings=False,
40
+ rope_theta=1e6,
41
+ sliding_window=None,
42
+ attention_dropout=0.0,
43
+ num_experts_per_tok=2,
44
+ num_local_experts=8,
45
+ output_router_logits=False,
46
+ router_aux_loss_coef=0.001,
47
+ router_jitter_noise=0.0,
48
+ **kwargs,
49
+ ):
50
+ self.vocab_size = vocab_size
51
+ self.max_position_embeddings = max_position_embeddings
52
+ self.hidden_size = hidden_size
53
+ self.intermediate_size = intermediate_size
54
+ self.num_hidden_layers = num_hidden_layers
55
+ self.num_attention_heads = num_attention_heads
56
+ self.sliding_window = sliding_window
57
+
58
+ # for backward compatibility
59
+ if num_key_value_heads is None:
60
+ num_key_value_heads = num_attention_heads
61
+
62
+ self.num_key_value_heads = num_key_value_heads
63
+ self.hidden_act = hidden_act
64
+ self.initializer_range = initializer_range
65
+ self.rms_norm_eps = rms_norm_eps
66
+ self.use_cache = use_cache
67
+ self.rope_theta = rope_theta
68
+ self.attention_dropout = attention_dropout
69
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
70
+
71
+ self.num_experts_per_tok = num_experts_per_tok
72
+ self.num_local_experts = num_local_experts
73
+ self.output_router_logits = output_router_logits
74
+ self.router_aux_loss_coef = router_aux_loss_coef
75
+ self.router_jitter_noise = router_jitter_noise
76
+ super().__init__(
77
+ pad_token_id=pad_token_id,
78
+ bos_token_id=bos_token_id,
79
+ eos_token_id=eos_token_id,
80
+ tie_word_embeddings=tie_word_embeddings,
81
+ **kwargs,
82
+ )
83
+
84
+ Param7BMoEConfig.register_for_auto_class()
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "transformers_version": "4.53.3"
6
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:51d523eece6456176fc7cc36f11daad02ac63ba10ac370d6cacc8032242c586d
3
+ size 4669101216
modeling_param1MoE.py ADDED
@@ -0,0 +1,1022 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on open-source implementations from:
4
+ # - EleutherAI's GPT-NeoX library
5
+ # - Hugging Face Transformers (including Mistral and Mixtral models)
6
+ #
7
+ # It has been modified from its original forms to support
8
+ # custom architectural and implementation-specific changes
9
+ # developed by BharatGenAI.
10
+ #
11
+ # Licensed under the Apache License, Version 2.0 (the "License");
12
+ # you may not use this file except in compliance with the License.
13
+ # You may obtain a copy of the License at
14
+ #
15
+ # http://www.apache.org/licenses/LICENSE-2.0
16
+ #
17
+ # Unless required by applicable law or agreed to in writing, software
18
+ # distributed under the License is distributed on an "AS IS" BASIS,
19
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ # See the License for the specific language governing permissions and
21
+ # limitations under the License.
22
+
23
+ from collections.abc import Callable
24
+ from functools import partial
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ from .configuration_param1MoE import Param7BMoEConfig
29
+ from torch import nn
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
33
+ from transformers.generation import GenerationMixin
34
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
35
+ from transformers.modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
36
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
37
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
38
+ from transformers.processing_utils import Unpack
39
+ from transformers.utils import (
40
+ LossKwargs,
41
+ add_start_docstrings_to_model_forward,
42
+ can_return_tuple,
43
+ logging,
44
+ replace_return_docstrings,
45
+ )
46
+ from transformers.utils.deprecation import deprecate_kwarg
47
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
48
+
49
+
50
+ logger = logging.get_logger(__name__)
51
+ _CONFIG_FOR_DOC = "Param7BMoEConfig"
52
+
53
+
54
+ class Param1MoEBlockSparseTop2MLP(nn.Module):
55
+ def __init__(self, config: Param7BMoEConfig):
56
+ super().__init__()
57
+ self.ffn_dim = config.intermediate_size
58
+ self.hidden_dim = config.hidden_size
59
+
60
+ self.w1 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
61
+ self.w2 = nn.Linear(self.ffn_dim, self.hidden_dim, bias=False)
62
+ self.w3 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
63
+
64
+ self.act_fn = ACT2FN[config.hidden_act]
65
+
66
+ def forward(self, hidden_states):
67
+ current_hidden_states = self.act_fn(self.w1(hidden_states)) * self.w3(hidden_states)
68
+ current_hidden_states = self.w2(current_hidden_states)
69
+ return current_hidden_states
70
+
71
+
72
+ class Param1MoESparseMoeBlock(nn.Module):
73
+ """
74
+ This implementation is
75
+ strictly equivalent to standard MoE with full capacity (no
76
+ dropped tokens). It's faster since it formulates MoE operations
77
+ in terms of block-sparse operations to accommodate imbalanced
78
+ assignments of tokens to experts, whereas standard MoE either
79
+ (1) drop tokens at the cost of reduced performance or (2) set
80
+ capacity factor to number of experts and thus waste computation
81
+ and memory on padding.
82
+ """
83
+
84
+ def __init__(self, config):
85
+ super().__init__()
86
+ self.hidden_dim = config.hidden_size
87
+ self.ffn_dim = config.intermediate_size
88
+ self.num_experts = config.num_local_experts
89
+ self.top_k = config.num_experts_per_tok
90
+
91
+ # gating
92
+ self.gate = nn.Linear(self.hidden_dim, self.num_experts, bias=False)
93
+
94
+ self.experts = nn.ModuleList([Param1MoEBlockSparseTop2MLP(config) for _ in range(self.num_experts)])
95
+
96
+ # Jitter parameters
97
+ self.jitter_noise = config.router_jitter_noise
98
+
99
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
100
+ """ """
101
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
102
+ if self.training and self.jitter_noise > 0:
103
+ hidden_states *= torch.empty_like(hidden_states).uniform_(1.0 - self.jitter_noise, 1.0 + self.jitter_noise)
104
+ hidden_states = hidden_states.view(-1, hidden_dim)
105
+ # router_logits: (batch * sequence_length, n_experts)
106
+ router_logits = self.gate(hidden_states)
107
+
108
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
109
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
110
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
111
+ # we cast back to the input dtype
112
+ routing_weights = routing_weights.to(hidden_states.dtype)
113
+
114
+ final_hidden_states = torch.zeros(
115
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
116
+ )
117
+
118
+ # One hot encode the selected experts to create an expert mask
119
+ # this will be used to easily index which expert is going to be sollicitated
120
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
121
+
122
+ # Loop over all available experts in the model and perform the computation on each expert
123
+ for expert_idx in range(self.num_experts):
124
+ expert_layer = self.experts[expert_idx]
125
+ idx, top_x = torch.where(expert_mask[expert_idx])
126
+
127
+ # Index the correct hidden states and compute the expert hidden state for
128
+ # the current expert. We need to make sure to multiply the output hidden
129
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
130
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
131
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
132
+
133
+ # However `index_add_` only support torch tensors for indexing so we'll use
134
+ # the `top_x` tensor here.
135
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
136
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
137
+ return final_hidden_states, router_logits
138
+
139
+
140
+ class Param1MoERMSNorm(nn.Module):
141
+ def __init__(self, hidden_size, eps=1e-6):
142
+ """
143
+ Param1MoERMSNorm is equivalent to T5LayerNorm
144
+ """
145
+ super().__init__()
146
+ self.weight = nn.Parameter(torch.ones(hidden_size))
147
+ self.variance_epsilon = eps
148
+
149
+ def forward(self, hidden_states):
150
+ input_dtype = hidden_states.dtype
151
+ hidden_states = hidden_states.to(torch.float32)
152
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
153
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
154
+ return self.weight * hidden_states.to(input_dtype)
155
+
156
+ def extra_repr(self):
157
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
158
+
159
+
160
+ def rotate_half(x):
161
+ """Rotates half the hidden dims of the input."""
162
+ x1 = x[..., : x.shape[-1] // 2]
163
+ x2 = x[..., x.shape[-1] // 2 :]
164
+ return torch.cat((-x2, x1), dim=-1)
165
+
166
+
167
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
168
+ """Applies Rotary Position Embedding to the query and key tensors.
169
+
170
+ Args:
171
+ q (`torch.Tensor`): The query tensor.
172
+ k (`torch.Tensor`): The key tensor.
173
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
174
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
175
+ position_ids (`torch.Tensor`, *optional*):
176
+ Deprecated and unused.
177
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
178
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
179
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
180
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
181
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
182
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
183
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
184
+ Returns:
185
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
186
+ """
187
+ cos = cos.unsqueeze(unsqueeze_dim)
188
+ sin = sin.unsqueeze(unsqueeze_dim)
189
+ q_embed = (q * cos) + (rotate_half(q) * sin)
190
+ k_embed = (k * cos) + (rotate_half(k) * sin)
191
+ return q_embed, k_embed
192
+
193
+
194
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
195
+ """
196
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
197
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
198
+ """
199
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
200
+ if n_rep == 1:
201
+ return hidden_states
202
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
203
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
204
+
205
+
206
+ def eager_attention_forward(
207
+ module: nn.Module,
208
+ query: torch.Tensor,
209
+ key: torch.Tensor,
210
+ value: torch.Tensor,
211
+ attention_mask: torch.Tensor | None,
212
+ scaling: float,
213
+ dropout: float = 0.0,
214
+ **kwargs,
215
+ ):
216
+ key_states = repeat_kv(key, module.num_key_value_groups)
217
+ value_states = repeat_kv(value, module.num_key_value_groups)
218
+
219
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
220
+ if attention_mask is not None:
221
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
222
+ attn_weights = attn_weights + causal_mask
223
+
224
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
225
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
226
+ attn_output = torch.matmul(attn_weights, value_states)
227
+ attn_output = attn_output.transpose(1, 2).contiguous()
228
+
229
+ return attn_output, attn_weights
230
+
231
+
232
+ class Param1MoEAttention(nn.Module):
233
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
234
+
235
+ def __init__(self, config: Param7BMoEConfig, layer_idx: int):
236
+ super().__init__()
237
+ self.config = config
238
+ self.layer_idx = layer_idx
239
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
240
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
241
+ self.scaling = self.head_dim**-0.5
242
+ self.attention_dropout = config.attention_dropout
243
+ self.is_causal = True
244
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
245
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
246
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
247
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
248
+
249
+ def forward(
250
+ self,
251
+ hidden_states: torch.Tensor,
252
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
253
+ attention_mask: torch.Tensor | None,
254
+ past_key_value: Cache | None = None,
255
+ cache_position: torch.LongTensor | None = None,
256
+ **kwargs: Unpack[FlashAttentionKwargs],
257
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
258
+ input_shape = hidden_states.shape[:-1]
259
+ hidden_shape = (*input_shape, -1, self.head_dim)
260
+
261
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
262
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
263
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
264
+
265
+ cos, sin = position_embeddings
266
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
267
+
268
+ if past_key_value is not None:
269
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
270
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
271
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
272
+
273
+ attention_interface: Callable = eager_attention_forward
274
+ if self.config._attn_implementation != "eager":
275
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
276
+ logger.warning_once(
277
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
278
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
279
+ )
280
+ else:
281
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
282
+
283
+ attn_output, attn_weights = attention_interface(
284
+ self,
285
+ query_states,
286
+ key_states,
287
+ value_states,
288
+ attention_mask,
289
+ dropout=0.0 if not self.training else self.attention_dropout,
290
+ scaling=self.scaling,
291
+ sliding_window=getattr(self.config, "sliding_window", None), # main diff with Llama
292
+ **kwargs,
293
+ )
294
+
295
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
296
+ attn_output = self.o_proj(attn_output)
297
+ return attn_output, attn_weights
298
+
299
+
300
+ class Param1MoEDecoderLayer(nn.Module):
301
+ def __init__(self, config: Param7BMoEConfig, layer_idx: int):
302
+ super().__init__()
303
+ self.hidden_size = config.hidden_size
304
+ self.self_attn = Param1MoEAttention(config, layer_idx)
305
+ self.block_sparse_moe = Param1MoESparseMoeBlock(config)
306
+ self.input_layernorm = Param1MoERMSNorm(config.hidden_size, eps=config.rms_norm_eps)
307
+ self.post_attention_layernorm = Param1MoERMSNorm(config.hidden_size, eps=config.rms_norm_eps)
308
+
309
+ def forward(
310
+ self,
311
+ hidden_states: torch.Tensor,
312
+ attention_mask: torch.Tensor | None = None,
313
+ position_ids: torch.LongTensor | None = None,
314
+ past_key_value: tuple[torch.Tensor] | None = None,
315
+ output_attentions: bool | None = False,
316
+ output_router_logits: bool | None = False,
317
+ use_cache: bool | None = False,
318
+ cache_position: torch.LongTensor | None = None,
319
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, # necessary, but kept here for BC
320
+ **kwargs: Unpack[FlashAttentionKwargs],
321
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
322
+ """
323
+ Args:
324
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
325
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
326
+ `(batch, sequence_length)` where padding elements are indicated by 0.
327
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
328
+ output_attentions (`bool`, *optional*):
329
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
330
+ returned tensors for more detail.
331
+ output_router_logits (`bool`, *optional*):
332
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
333
+ should not be returned during inference.
334
+ use_cache (`bool`, *optional*):
335
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
336
+ (see `past_key_values`).
337
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
338
+ Indices depicting the position of the input sequence tokens in the sequence.
339
+ kwargs (`dict`, *optional*):
340
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
341
+ into the model
342
+ """
343
+
344
+ residual = hidden_states
345
+
346
+ hidden_states = self.input_layernorm(hidden_states)
347
+
348
+ # Self Attention
349
+ hidden_states, self_attn_weights = self.self_attn(
350
+ hidden_states=hidden_states,
351
+ position_embeddings=position_embeddings,
352
+ attention_mask=attention_mask,
353
+ position_ids=position_ids,
354
+ past_key_value=past_key_value,
355
+ output_attentions=output_attentions,
356
+ use_cache=use_cache,
357
+ cache_position=cache_position,
358
+ **kwargs,
359
+ )
360
+ hidden_states = residual + hidden_states
361
+
362
+ # Fully Connected
363
+ residual = hidden_states
364
+ hidden_states = self.post_attention_layernorm(hidden_states)
365
+ hidden_states, router_logits = self.block_sparse_moe(hidden_states)
366
+ hidden_states = residual + hidden_states
367
+
368
+ outputs = (hidden_states,)
369
+
370
+ if output_attentions:
371
+ outputs += (self_attn_weights,)
372
+
373
+ if output_router_logits:
374
+ outputs += (router_logits,)
375
+
376
+ return outputs
377
+
378
+
379
+ class Param1MoERotaryEmbedding(nn.Module):
380
+ def __init__(self, config: Param7BMoEConfig, device=None):
381
+ super().__init__()
382
+ # BC: "rope_type" was originally "type"
383
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
384
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
385
+ else:
386
+ self.rope_type = "default"
387
+ self.max_seq_len_cached = config.max_position_embeddings
388
+ self.original_max_seq_len = config.max_position_embeddings
389
+
390
+ self.config = config
391
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
392
+
393
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
394
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
395
+ self.original_inv_freq = self.inv_freq
396
+
397
+ @torch.no_grad()
398
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
399
+ def forward(self, x, position_ids):
400
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
401
+ position_ids_expanded = position_ids[:, None, :].float()
402
+
403
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
404
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
405
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
406
+ emb = torch.cat((freqs, freqs), dim=-1)
407
+ cos = emb.cos() * self.attention_scaling
408
+ sin = emb.sin() * self.attention_scaling
409
+
410
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
411
+
412
+
413
+ class Param1MoEPreTrainedModel(PreTrainedModel):
414
+ config_class = Param7BMoEConfig
415
+ base_model_prefix = "model"
416
+ supports_gradient_checkpointing = True
417
+ _no_split_modules = ["Param1MoEDecoderLayer"]
418
+ _skip_keys_device_placement = ["past_key_values"]
419
+ _supports_flash_attn_2 = True
420
+ _supports_sdpa = True
421
+ _supports_flex_attn = True
422
+ _supports_cache_class = True
423
+ _supports_quantized_cache = True
424
+ _supports_static_cache = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
425
+ _supports_attention_backend = True
426
+
427
+ def _init_weights(self, module):
428
+ std = self.config.initializer_range
429
+ if isinstance(module, nn.Linear):
430
+ module.weight.data.normal_(mean=0.0, std=std)
431
+ if module.bias is not None:
432
+ module.bias.data.zero_()
433
+ elif isinstance(module, nn.Embedding):
434
+ module.weight.data.normal_(mean=0.0, std=std)
435
+ if module.padding_idx is not None:
436
+ module.weight.data[module.padding_idx].zero_()
437
+
438
+
439
+ PARAM1MOE_INPUTS_DOCSTRING = r"""
440
+ Args:
441
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
442
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
443
+ it.
444
+
445
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
446
+ [`PreTrainedTokenizer.__call__`] for details.
447
+
448
+ [What are input IDs?](../glossary#input-ids)
449
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
450
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
451
+
452
+ - 1 for tokens that are **not masked**,
453
+ - 0 for tokens that are **masked**.
454
+
455
+ [What are attention masks?](../glossary#attention-mask)
456
+
457
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
458
+ [`PreTrainedTokenizer.__call__`] for details.
459
+
460
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
461
+ `past_key_values`).
462
+
463
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
464
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
465
+ information on the default strategy.
466
+
467
+ - 1 indicates the head is **not masked**,
468
+ - 0 indicates the head is **masked**.
469
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
470
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
471
+ config.n_positions - 1]`.
472
+
473
+ [What are position IDs?](../glossary#position-ids)
474
+ past_key_values (`Cache`, *optional*):
475
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
476
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
477
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
478
+
479
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
480
+
481
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
482
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
483
+ of shape `(batch_size, sequence_length)`.
484
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
485
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
486
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
487
+ model's internal embedding lookup matrix.
488
+ use_cache (`bool`, *optional*):
489
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
490
+ `past_key_values`).
491
+ output_attentions (`bool`, *optional*):
492
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
493
+ tensors for more detail.
494
+ output_hidden_states (`bool`, *optional*):
495
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
496
+ more detail.
497
+ return_dict (`bool`, *optional*):
498
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
499
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
500
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
501
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
502
+ the complete sequence length.
503
+ """
504
+
505
+
506
+ class Param1MoEModel(Param1MoEPreTrainedModel):
507
+ def __init__(self, config: Param7BMoEConfig):
508
+ super().__init__(config)
509
+ self.padding_idx = config.pad_token_id
510
+ self.vocab_size = config.vocab_size
511
+
512
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
513
+ self.layers = nn.ModuleList(
514
+ [Param1MoEDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
515
+ )
516
+ self.norm = Param1MoERMSNorm(config.hidden_size, eps=config.rms_norm_eps)
517
+ self.rotary_emb = Param1MoERotaryEmbedding(config=config)
518
+ self.gradient_checkpointing = False
519
+
520
+ # Initialize weights and apply final processing
521
+ self.post_init()
522
+
523
+ def get_input_embeddings(self):
524
+ return self.embed_tokens
525
+
526
+ def set_input_embeddings(self, value):
527
+ self.embed_tokens = value
528
+
529
+ @can_return_tuple
530
+ @add_start_docstrings_to_model_forward(PARAM1MOE_INPUTS_DOCSTRING)
531
+ def forward(
532
+ self,
533
+ input_ids: torch.LongTensor | None = None,
534
+ attention_mask: torch.Tensor | None = None,
535
+ position_ids: torch.LongTensor | None = None,
536
+ past_key_values: list[torch.FloatTensor] | None = None,
537
+ inputs_embeds: torch.FloatTensor | None = None,
538
+ use_cache: bool | None = None,
539
+ output_attentions: bool | None = None,
540
+ output_hidden_states: bool | None = None,
541
+ output_router_logits: bool | None = None,
542
+ cache_position: torch.LongTensor | None = None,
543
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
544
+ ) -> MoeModelOutputWithPast:
545
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
546
+ output_router_logits = (
547
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
548
+ )
549
+ output_hidden_states = (
550
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
551
+ )
552
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
553
+
554
+ if (input_ids is None) ^ (inputs_embeds is not None):
555
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
556
+
557
+ if self.gradient_checkpointing and self.training:
558
+ if use_cache:
559
+ logger.warning_once(
560
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
561
+ )
562
+ use_cache = False
563
+
564
+ if use_cache and past_key_values is None:
565
+ past_key_values = DynamicCache()
566
+
567
+ if inputs_embeds is None:
568
+ inputs_embeds = self.embed_tokens(input_ids)
569
+
570
+ if cache_position is None:
571
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
572
+ cache_position = torch.arange(
573
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
574
+ )
575
+ if position_ids is None:
576
+ position_ids = cache_position.unsqueeze(0)
577
+
578
+ causal_mask = self._update_causal_mask(
579
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
580
+ )
581
+
582
+ hidden_states = inputs_embeds
583
+
584
+ # create position embeddings to be shared across the decoder layers
585
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
586
+
587
+ # decoder layers
588
+ all_hidden_states = () if output_hidden_states else None
589
+ all_self_attns = () if output_attentions else None
590
+ all_router_logits = () if output_router_logits else None
591
+
592
+ for decoder_layer in self.layers:
593
+ if output_hidden_states:
594
+ all_hidden_states += (hidden_states,)
595
+
596
+ if self.gradient_checkpointing and self.training:
597
+ layer_outputs = self._gradient_checkpointing_func(
598
+ partial(decoder_layer.__call__, **flash_attn_kwargs),
599
+ hidden_states,
600
+ causal_mask,
601
+ position_ids,
602
+ past_key_values,
603
+ output_attentions,
604
+ output_router_logits,
605
+ use_cache,
606
+ cache_position,
607
+ position_embeddings,
608
+ )
609
+ else:
610
+ layer_outputs = decoder_layer(
611
+ hidden_states,
612
+ attention_mask=causal_mask,
613
+ position_ids=position_ids,
614
+ past_key_value=past_key_values,
615
+ output_attentions=output_attentions,
616
+ output_router_logits=output_router_logits,
617
+ use_cache=use_cache,
618
+ cache_position=cache_position,
619
+ position_embeddings=position_embeddings,
620
+ **flash_attn_kwargs,
621
+ )
622
+
623
+ hidden_states = layer_outputs[0]
624
+
625
+ if output_attentions:
626
+ all_self_attns += (layer_outputs[1],)
627
+
628
+ if output_router_logits:
629
+ all_router_logits += (layer_outputs[-1],)
630
+
631
+ hidden_states = self.norm(hidden_states)
632
+
633
+ # add hidden states from the last decoder layer
634
+ if output_hidden_states:
635
+ all_hidden_states += (hidden_states,)
636
+
637
+ return MoeModelOutputWithPast(
638
+ last_hidden_state=hidden_states,
639
+ past_key_values=past_key_values,
640
+ hidden_states=all_hidden_states,
641
+ attentions=all_self_attns,
642
+ router_logits=all_router_logits,
643
+ )
644
+
645
+ def _update_causal_mask(
646
+ self,
647
+ attention_mask: torch.Tensor,
648
+ input_tensor: torch.Tensor,
649
+ cache_position: torch.Tensor,
650
+ past_key_values: Cache,
651
+ output_attentions: bool = False,
652
+ ):
653
+ if self.config._attn_implementation == "flash_attention_2":
654
+ if attention_mask is not None and past_key_values is not None:
655
+ is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0]
656
+ if is_padding_right:
657
+ raise ValueError(
658
+ "You are attempting to perform batched generation with padding_side='right'"
659
+ " this may lead to unexpected behaviour for Flash Attention version of Param1MoE. Make sure to "
660
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
661
+ )
662
+ if attention_mask is not None and 0.0 in attention_mask:
663
+ return attention_mask
664
+ return None
665
+
666
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
667
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
668
+ # to infer the attention mask.
669
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
670
+ using_static_cache = isinstance(past_key_values, StaticCache)
671
+ using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
672
+
673
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
674
+ if (
675
+ self.config._attn_implementation == "sdpa"
676
+ and not (using_static_cache or using_sliding_window_cache)
677
+ and not output_attentions
678
+ ):
679
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
680
+ attention_mask,
681
+ inputs_embeds=input_tensor,
682
+ past_key_values_length=past_seen_tokens,
683
+ sliding_window=self.config.sliding_window,
684
+ is_training=self.training,
685
+ ):
686
+ return None
687
+
688
+ dtype, device = input_tensor.dtype, input_tensor.device
689
+ min_dtype = torch.finfo(dtype).min
690
+ sequence_length = input_tensor.shape[1]
691
+ # SlidingWindowCache or StaticCache
692
+ if using_sliding_window_cache or using_static_cache:
693
+ target_length = past_key_values.get_max_cache_shape()
694
+ # DynamicCache or no cache
695
+ else:
696
+ target_length = (
697
+ attention_mask.shape[-1]
698
+ if isinstance(attention_mask, torch.Tensor)
699
+ else past_seen_tokens + sequence_length + 1
700
+ )
701
+
702
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
703
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
704
+ attention_mask,
705
+ sequence_length=sequence_length,
706
+ target_length=target_length,
707
+ dtype=dtype,
708
+ device=device,
709
+ cache_position=cache_position,
710
+ batch_size=input_tensor.shape[0],
711
+ config=self.config,
712
+ past_key_values=past_key_values,
713
+ )
714
+
715
+ if (
716
+ self.config._attn_implementation == "sdpa"
717
+ and attention_mask is not None
718
+ and attention_mask.device.type in ["cuda", "xpu"]
719
+ and not output_attentions
720
+ ):
721
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
722
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
723
+ # Details: https://github.com/pytorch/pytorch/issues/110213
724
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
725
+
726
+ return causal_mask
727
+
728
+ @staticmethod
729
+ def _prepare_4d_causal_attention_mask_with_cache_position(
730
+ attention_mask: torch.Tensor,
731
+ sequence_length: int,
732
+ target_length: int,
733
+ dtype: torch.dtype,
734
+ device: torch.device,
735
+ cache_position: torch.Tensor,
736
+ batch_size: int,
737
+ config: Param7BMoEConfig,
738
+ past_key_values: Cache,
739
+ ):
740
+ """
741
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
742
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
743
+
744
+ Args:
745
+ attention_mask (`torch.Tensor`):
746
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
747
+ sequence_length (`int`):
748
+ The sequence length being processed.
749
+ target_length (`int`):
750
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
751
+ dtype (`torch.dtype`):
752
+ The dtype to use for the 4D attention mask.
753
+ device (`torch.device`):
754
+ The device to place the 4D attention mask on.
755
+ cache_position (`torch.Tensor`):
756
+ Indices depicting the position of the input sequence tokens in the sequence.
757
+ batch_size (`torch.Tensor`):
758
+ Batch size.
759
+ config (`Param1MoE`):
760
+ The model's configuration class
761
+ past_key_values (`Cache`):
762
+ The cache class that is being used currently to generate
763
+ """
764
+ if attention_mask is not None and attention_mask.dim() == 4:
765
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
766
+ causal_mask = attention_mask
767
+ else:
768
+ min_dtype = torch.finfo(dtype).min
769
+ causal_mask = torch.full(
770
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
771
+ )
772
+ diagonal_attend_mask = torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
773
+ if config.sliding_window is not None:
774
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
775
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
776
+ if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
777
+ sliding_attend_mask = torch.arange(target_length, device=device) <= (
778
+ cache_position.reshape(-1, 1) - config.sliding_window
779
+ )
780
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
781
+ causal_mask *= diagonal_attend_mask
782
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
783
+ if attention_mask is not None:
784
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
785
+ if attention_mask.shape[-1] > target_length:
786
+ attention_mask = attention_mask[:, :target_length]
787
+ mask_length = attention_mask.shape[-1]
788
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
789
+ causal_mask.device
790
+ )
791
+ padding_mask = padding_mask == 0
792
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
793
+ padding_mask, min_dtype
794
+ )
795
+ return causal_mask
796
+
797
+
798
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
799
+
800
+
801
+ def load_balancing_loss_func(
802
+ gate_logits: torch.Tensor | tuple[torch.Tensor] | None,
803
+ num_experts: int | None = None,
804
+ top_k=2,
805
+ attention_mask: torch.Tensor | None = None,
806
+ ) -> torch.Tensor | int:
807
+ r"""
808
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
809
+
810
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
811
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
812
+ experts is too unbalanced.
813
+
814
+ Args:
815
+ gate_logits:
816
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
817
+ shape [batch_size X sequence_length, num_experts].
818
+ num_experts:
819
+ Number of experts
820
+ top_k:
821
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
822
+ parameter.
823
+ attention_mask (`torch.Tensor`, *optional*):
824
+ The attention_mask used in forward function
825
+ shape [batch_size X sequence_length] if not None.
826
+
827
+ Returns:
828
+ The auxiliary loss.
829
+ """
830
+ if gate_logits is None or not isinstance(gate_logits, tuple):
831
+ return 0
832
+
833
+ if isinstance(gate_logits, tuple):
834
+ compute_device = gate_logits[0].device
835
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
836
+
837
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
838
+
839
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
840
+
841
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
842
+
843
+ if attention_mask is None:
844
+ # Compute the percentage of tokens routed to each experts
845
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
846
+
847
+ # Compute the average probability of routing to these experts
848
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
849
+ else:
850
+ batch_size, sequence_length = attention_mask.shape
851
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
852
+
853
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
854
+ expert_attention_mask = (
855
+ attention_mask[None, :, :, None, None]
856
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
857
+ .reshape(-1, top_k, num_experts)
858
+ .to(compute_device)
859
+ )
860
+
861
+ # Compute the percentage of tokens routed to each experts
862
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
863
+ expert_attention_mask, dim=0
864
+ )
865
+
866
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
867
+ router_per_expert_attention_mask = (
868
+ attention_mask[None, :, :, None]
869
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
870
+ .reshape(-1, num_experts)
871
+ .to(compute_device)
872
+ )
873
+
874
+ # Compute the average probability of routing to these experts
875
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
876
+ router_per_expert_attention_mask, dim=0
877
+ )
878
+
879
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
880
+ return overall_loss * num_experts
881
+
882
+
883
+ class Param1MoEForCausalLM(Param1MoEPreTrainedModel, GenerationMixin):
884
+ _tied_weights_keys = ["lm_head.weight"]
885
+ _tp_plan = {"lm_head": "colwise_rep"}
886
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
887
+
888
+ def __init__(self, config):
889
+ super().__init__(config)
890
+ self.model = Param1MoEModel(config)
891
+ self.vocab_size = config.vocab_size
892
+ self.router_aux_loss_coef = config.router_aux_loss_coef
893
+ self.num_experts = config.num_local_experts
894
+ self.num_experts_per_tok = config.num_experts_per_tok
895
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
896
+
897
+ # Initialize weights and apply final processing
898
+ self.post_init()
899
+
900
+ def get_input_embeddings(self):
901
+ return self.model.embed_tokens
902
+
903
+ def set_input_embeddings(self, value):
904
+ self.model.embed_tokens = value
905
+
906
+ def get_output_embeddings(self):
907
+ return self.lm_head
908
+
909
+ def set_output_embeddings(self, new_embeddings):
910
+ self.lm_head = new_embeddings
911
+
912
+ def set_decoder(self, decoder):
913
+ self.model = decoder
914
+
915
+ def get_decoder(self):
916
+ return self.model
917
+
918
+ @can_return_tuple
919
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
920
+ @add_start_docstrings_to_model_forward(PARAM1MOE_INPUTS_DOCSTRING)
921
+ @replace_return_docstrings(output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
922
+ def forward(
923
+ self,
924
+ input_ids: torch.LongTensor | None = None,
925
+ attention_mask: torch.Tensor | None = None,
926
+ position_ids: torch.LongTensor | None = None,
927
+ past_key_values: list[torch.FloatTensor] | None = None,
928
+ inputs_embeds: torch.FloatTensor | None = None,
929
+ labels: torch.LongTensor | None = None,
930
+ use_cache: bool | None = None,
931
+ output_attentions: bool | None = None,
932
+ output_hidden_states: bool | None = None,
933
+ output_router_logits: bool | None = None,
934
+ cache_position: torch.LongTensor | None = None,
935
+ logits_to_keep: int | torch.Tensor = 0,
936
+ **kwargs: Unpack[KwargsForCausalLM],
937
+ ) -> MoeCausalLMOutputWithPast:
938
+ r"""
939
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
940
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
941
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
942
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
943
+
944
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
945
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
946
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
947
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
948
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
949
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
950
+
951
+ Returns:
952
+
953
+ Example:
954
+
955
+ ```python
956
+ >>> from transformers import AutoTokenizer, Param1MoEForCausalLM
957
+
958
+ >>> model = Param1MoEForCausalLM.from_pretrained("bharatgenai/Param-1-7B")
959
+ >>> tokenizer = AutoTokenizer.from_pretrained("bharatgenai/Param-1-7B")
960
+
961
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
962
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
963
+
964
+ >>> # Generate
965
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
966
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
967
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
968
+ ```"""
969
+
970
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
971
+ output_router_logits = (
972
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
973
+ )
974
+
975
+ output_hidden_states = (
976
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
977
+ )
978
+
979
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
980
+ outputs: MoeModelOutputWithPast = self.model(
981
+ input_ids=input_ids,
982
+ attention_mask=attention_mask,
983
+ position_ids=position_ids,
984
+ past_key_values=past_key_values,
985
+ inputs_embeds=inputs_embeds,
986
+ use_cache=use_cache,
987
+ output_attentions=output_attentions,
988
+ output_hidden_states=output_hidden_states,
989
+ output_router_logits=output_router_logits,
990
+ cache_position=cache_position,
991
+ **kwargs,
992
+ )
993
+
994
+ hidden_states = outputs.last_hidden_state
995
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
996
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
997
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
998
+
999
+ loss = None
1000
+ if labels is not None:
1001
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
1002
+
1003
+ aux_loss = None
1004
+ if output_router_logits:
1005
+ aux_loss = load_balancing_loss_func(
1006
+ outputs.router_logits,
1007
+ self.num_experts,
1008
+ self.num_experts_per_tok,
1009
+ attention_mask,
1010
+ )
1011
+ if labels is not None:
1012
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
1013
+
1014
+ return MoeCausalLMOutputWithPast(
1015
+ loss=loss,
1016
+ aux_loss=aux_loss,
1017
+ logits=logits,
1018
+ past_key_values=outputs.past_key_values,
1019
+ hidden_states=outputs.hidden_states,
1020
+ attentions=outputs.attentions,
1021
+ router_logits=outputs.router_logits,
1022
+ )