JingzeShi commited on
Commit
4a241da
·
verified ·
1 Parent(s): bbf2d03

Upload PEERForCausalLM

Browse files
Files changed (6) hide show
  1. README.md +199 -0
  2. config.json +39 -0
  3. configuration_peer.py +243 -0
  4. generation_config.json +4 -0
  5. model.safetensors +3 -0
  6. modeling_peer.py +897 -0
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,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "PEERForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_peer.PEERConfig",
9
+ "AutoModelForCausalLM": "modeling_peer.PEERForCausalLM"
10
+ },
11
+ "hidden_act": "silu",
12
+ "hidden_dropout": 0.0,
13
+ "hidden_size": 256,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 768,
16
+ "is_moe": true,
17
+ "keep_window_size": 2048,
18
+ "max_position_embeddings": 2048,
19
+ "mlp_bias": false,
20
+ "model_type": "peer",
21
+ "norm_topk_prob": false,
22
+ "num_attention_heads": 2,
23
+ "num_experts": 1024,
24
+ "num_experts_per_tok": 8,
25
+ "num_hidden_layers": 8,
26
+ "num_key_value_heads": 1,
27
+ "num_peer_heads": 2,
28
+ "output_router_logits": false,
29
+ "rms_norm_eps": 1e-06,
30
+ "rope_scaling": null,
31
+ "rope_theta": 10000.0,
32
+ "router_aux_loss_coef": 0.001,
33
+ "sliding_window": null,
34
+ "tie_word_embeddings": true,
35
+ "torch_dtype": "bfloat16",
36
+ "transformers_version": "4.54.0.dev0",
37
+ "use_cache": true,
38
+ "vocab_size": 128256
39
+ }
configuration_peer.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/peer/modular_peer.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_peer.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 Jingze Shi and the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # The PEER family of small language models is trained by SmallPEER Team.
11
+ #
12
+ # Licensed under the Apache License, Version 2.0 (the "License");
13
+ # you may not use this file except in compliance with the License.
14
+ # You may obtain a copy of the License at
15
+ #
16
+ # http://www.apache.org/licenses/LICENSE-2.0
17
+ #
18
+ # Unless required by applicable law or agreed to in writing, software
19
+ # distributed under the License is distributed on an "AS IS" BASIS,
20
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
+ # See the License for the specific language governing permissions and
22
+ # limitations under the License.
23
+ from transformers.configuration_utils import PretrainedConfig
24
+ from transformers.modeling_rope_utils import rope_config_validation
25
+
26
+
27
+ class PEERConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`PEERModel`]. It is used to instantiate an PEER
30
+ model according to the specified arguments, defining the model architecture like [SmallPEER/PEER-320M](https://huggingface.co/SmallPEER/PEER-320M).
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 32768):
37
+ Vocabulary size of the PEER2 model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`PEERModel`]
38
+ hidden_size (`int`, *optional*, defaults to 1024):
39
+ Dimension of the hidden representations.
40
+ intermediate_size (`int`, *optional*, defaults to 2048):
41
+ Dimension of the MLP representations.
42
+ num_hidden_layers (`int`, *optional*, defaults to 32):
43
+ Number of hidden layers in the Transformer decoder.
44
+ hidden_dropout (`float`, *optional*, defaults to 0.0):
45
+ Dropout probability for each sequence transformation and state transformation module.
46
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
47
+ The non-linear activation function (function or string) in the decoder.
48
+ initializer_range (`float`, *optional*, defaults to 0.02):
49
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
50
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
51
+ The epsilon used by the rms normalization layers.
52
+ use_cache (`bool`, *optional*, defaults to `True`):
53
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
54
+ relevant if `config.is_decoder=True`.
55
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
56
+ Whether the model's input and output word embeddings should be tied.
57
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
58
+ The maximum sequence length that this model might ever be used with.
59
+ rope_theta (`float`, *optional*, defaults to 10000.0):
60
+ The base period of the RoPE embeddings.
61
+ rope_scaling (`Dict`, *optional*):
62
+ Dictionary containing the scaling configuration for the RoPE embeddings.
63
+ NOTE: if you apply new rope type and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value accordingly.
64
+ PEER family of small models use `{ 'rope_type': 'dynamic', 'factor': 4.0, 'original_max_position_embeddings': 2048 }` as the default value.
65
+ Expected contents:
66
+ `rope_type` (`str`):
67
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope', 'llama3'], with 'default' being the original RoPE implementation.
68
+ `factor` (`float`, *optional*):
69
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings.
70
+ In most scaling types, a `factor` of x will enable the model to handle sequences of length x * original maximum pre-trained length.
71
+ `original_max_position_embeddings` (`int`, *optional*):
72
+ Used with 'dynamic', 'longrope' and 'llama3'.
73
+ The original max position embeddings used during pretraining.
74
+ `attention_factor` (`float`, *optional*):
75
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
76
+ computation.
77
+ If unspecified, it defaults to value recommended by the implementation, using the `factor` field to infer the suggested value.
78
+ `beta_fast` (`float`, *optional*):
79
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
80
+ ramp function. If unspecified, it defaults to 32.
81
+ `beta_slow` (`float`, *optional*):
82
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
83
+ ramp function. If unspecified, it defaults to 1.
84
+ `short_factor` (`List[float]`, *optional*):
85
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<`original_max_position_embeddings`).
86
+ Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2
87
+ `long_factor` (`List[float]`, *optional*):
88
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<`original_max_position_embeddings`).
89
+ Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2
90
+ `low_freq_factor` (`float`, *optional*):
91
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
92
+ `high_freq_factor` (`float`, *optional*):
93
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
94
+ num_attention_heads (`int`, *optional*, defaults to 8):
95
+ Number of attention heads for each attention layer in the Transformer decoder.
96
+ num_key_value_heads (`int`, *optional*):
97
+ This is the number of key_value heads that should be used to implement Grouped Query Attention.
98
+ If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
99
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used.
100
+ When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group.
101
+ For more details checkout [this paper](https://arxiv.org/pdf/2305.13245.pdf).
102
+ If it is not specified, will default to `num_attention_heads`.
103
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
104
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
105
+ attention_dropout (`float`, *optional*, defaults to 0.0):
106
+ The dropout ratio for the attention probabilities.
107
+ mlp_bias (`bool`, *optional*, defaults to `False`):
108
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
109
+ sliding_window (`int`, *optional*):
110
+ Sliding window attention window size. If not specified, will default to `None`.
111
+ keep_window_size (`int`, *optional*, defaults to 2048):
112
+ The window size of tokens that are not dynamically masked, and dynamic masking is only performed when the sequence length exceeds this value.
113
+ is_moe (`bool`, *optional*, defaults to `False`):
114
+ Whether to use the Cross Domain Mixture of Experts, if `True`, the MoE will inherit the MLP to initialize.
115
+ num_experts (`int`, *optional*, defaults to 16384):
116
+ Number of routed experts in the model. This is only used when `is_moe=True`.
117
+ num_experts_per_tok (`int`, *optional*, defaults to 64):
118
+ Number of selected experts to route per-token.
119
+ norm_topk_prob (`bool`, *optional*, defaults to `False`):
120
+ Whether to normalize the topk probabilities.
121
+ output_router_logits (`bool`, *optional*, defaults to `False`):
122
+ Whether or not the router logits should be returned by the model. Enabling this will also
123
+ allow the model to output the auxiliary loss, including load balancing loss and router z-loss.
124
+ router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
125
+ The aux loss factor for the total loss.
126
+
127
+ ```python
128
+ >>> from transformers import PEERConfig, PEERModel
129
+
130
+ >>> # Initializing a PEER-320M style configuration
131
+ >>> configuration = PEERConfig()
132
+
133
+ >>> # Initializing a model from the PEER-320M style configuration
134
+ >>> model = PEERModel(configuration)
135
+
136
+ >>> # Accessing the model configuration
137
+ >>> configuration = model.config
138
+ ```"""
139
+
140
+ model_type = "peer"
141
+ keys_to_ignore_at_inference = ["past_key_values"]
142
+ # Default tensor parallel plan for base model `PEERModel`
143
+ base_model_tp_plan = {
144
+ "layers.*.self_attn.q_proj": "colwise",
145
+ "layers.*.self_attn.k_proj": "colwise",
146
+ "layers.*.self_attn.v_proj": "colwise",
147
+ "layers.*.self_attn.dt_proj": "rowwise",
148
+ "layers.*.self_attn.o_proj": "rowwise",
149
+ "layers.*.input_layernorm.weight": "sequence_parallel",
150
+ "layers.*.input_residual.weight": "sequence_parallel",
151
+ "layers.*.post_attention_layernorm.weight": "sequence_parallel",
152
+ "layers.*.post_attention_residual.weight": "sequence_parallel",
153
+ "norm.weight": "sequence_parallel",
154
+ "layers.*.mlp.gate_proj": "colwise",
155
+ "layers.*.mlp.up_proj": "colwise",
156
+ "layers.*.mlp.down_proj": "rowwise",
157
+ "layers.*.mlp.router_gate": "colwise_rep",
158
+ "layers.*.mlp.down_embed": "rowwise_rep",
159
+ "layers.*.mlp.up_embed": "rowwise_rep",
160
+ }
161
+ base_model_pp_plan = {
162
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
163
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
164
+ "norm": (["hidden_states"], ["hidden_states"]),
165
+ }
166
+
167
+ def __init__(
168
+ self,
169
+ vocab_size=32768,
170
+ hidden_size=1024,
171
+ intermediate_size=2048,
172
+ num_hidden_layers=32,
173
+ hidden_dropout=0.0,
174
+ hidden_act="silu",
175
+ initializer_range=0.02,
176
+ rms_norm_eps=1e-06,
177
+ use_cache=True,
178
+ tie_word_embeddings=False,
179
+ max_position_embeddings=2048,
180
+ rope_theta=10000.0,
181
+ rope_scaling=None,
182
+ num_attention_heads=8,
183
+ num_key_value_heads=None,
184
+ attention_bias=False,
185
+ attention_dropout=0.0,
186
+ mlp_bias=False,
187
+ sliding_window=None,
188
+ keep_window_size=2048,
189
+ is_moe=False,
190
+ num_experts=16384,
191
+ num_experts_per_tok=64,
192
+ num_peer_heads=16,
193
+ norm_topk_prob=False,
194
+ output_router_logits=False,
195
+ router_aux_loss_coef=0.001,
196
+ **kwargs,
197
+ ):
198
+ self.vocab_size = vocab_size
199
+ self.hidden_size = hidden_size
200
+ self.intermediate_size = intermediate_size
201
+ self.num_hidden_layers = num_hidden_layers
202
+
203
+ self.hidden_dropout = hidden_dropout
204
+ self.hidden_act = hidden_act
205
+ self.initializer_range = initializer_range
206
+ self.rms_norm_eps = rms_norm_eps
207
+ self.use_cache = use_cache
208
+
209
+ self.max_position_embeddings = max_position_embeddings
210
+ self.rope_theta = rope_theta
211
+ self.rope_scaling = rope_scaling
212
+ self.num_attention_heads = num_attention_heads
213
+ self.num_key_value_heads = num_key_value_heads
214
+ self.attention_bias = attention_bias
215
+ self.attention_dropout = attention_dropout
216
+ self.mlp_bias = mlp_bias
217
+ self.sliding_window = sliding_window
218
+ self.keep_window_size = keep_window_size
219
+ self.is_moe = is_moe
220
+ self.num_experts = num_experts
221
+ self.num_experts_per_tok = num_experts_per_tok
222
+ self.num_peer_heads = num_peer_heads
223
+ self.norm_topk_prob = norm_topk_prob
224
+ self.output_router_logits = output_router_logits
225
+ self.router_aux_loss_coef = router_aux_loss_coef
226
+
227
+ # Validate the correctness of rotary position embeddings parameters
228
+ # BC: if there is a 'type' field, copy it it to 'rope_type'.
229
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
230
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
231
+ rope_config_validation(self)
232
+
233
+ # for backward compatibility
234
+ if num_key_value_heads is None:
235
+ self.num_key_value_heads = num_attention_heads
236
+
237
+ super().__init__(
238
+ tie_word_embeddings=tie_word_embeddings,
239
+ **kwargs,
240
+ )
241
+
242
+
243
+ __all__ = ["PEERConfig"]
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.54.0.dev0"
4
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b83baf3d099a2d2cecd0945231334ebc80088b80e2da570d240c6b4e9c82942
3
+ size 87982624
modeling_peer.py ADDED
@@ -0,0 +1,897 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/peer/modular_peer.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_peer.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 Jingze Shi and the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # The PEER family of small language models is trained by SmallPEER Team.
11
+ #
12
+ # Licensed under the Apache License, Version 2.0 (the "License");
13
+ # you may not use this file except in compliance with the License.
14
+ # You may obtain a copy of the License at
15
+ #
16
+ # http://www.apache.org/licenses/LICENSE-2.0
17
+ #
18
+ # Unless required by applicable law or agreed to in writing, software
19
+ # distributed under the License is distributed on an "AS IS" BASIS,
20
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
+ # See the License for the specific language governing permissions and
22
+ # limitations under the License.
23
+
24
+ import math
25
+ from typing import Callable, Optional, Union
26
+
27
+ import torch
28
+ import torch.nn.functional as F
29
+ from torch import nn
30
+ from einops.layers.torch import Rearrange
31
+ from einops import einsum
32
+ import einx
33
+
34
+ from transformers.activations import ACT2FN
35
+ from transformers.cache_utils import Cache, DynamicCache
36
+ from transformers.generation import GenerationMixin
37
+ from transformers.integrations import use_kernel_forward_from_hub
38
+ from transformers.integrations.flex_attention import compile_friendly_flex_attention
39
+ from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
40
+ from transformers.modeling_layers import GradientCheckpointingLayer
41
+ from transformers.modeling_outputs import (
42
+ BaseModelOutputWithPast,
43
+ MoeCausalLMOutputWithPast,
44
+ MoeModelOutputWithPast,
45
+ SequenceClassifierOutputWithPast,
46
+ )
47
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
48
+ from transformers.modeling_utils import AttentionInterface, PreTrainedModel
49
+ from transformers.processing_utils import Unpack
50
+ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torch_flex_attn_available, logging
51
+ from transformers.utils.generic import OutputRecorder, check_model_inputs
52
+ from .configuration_peer import PEERConfig
53
+
54
+
55
+ if is_torch_flex_attn_available():
56
+ from torch.nn.attention.flex_attention import BlockMask
57
+
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+
62
+ @use_kernel_forward_from_hub("RMSNorm")
63
+ class PEERRMSNorm(nn.Module):
64
+ def __init__(self, hidden_size, eps=1e-6):
65
+ """
66
+ PEERRMSNorm is equivalent to T5LayerNorm
67
+ """
68
+ super().__init__()
69
+ self.weight = nn.Parameter(torch.ones(hidden_size))
70
+ self.variance_epsilon = eps
71
+
72
+ def forward(self, hidden_states):
73
+ input_dtype = hidden_states.dtype
74
+ hidden_states = hidden_states.to(torch.float32)
75
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
76
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
77
+ return self.weight * hidden_states.to(input_dtype)
78
+
79
+ def extra_repr(self):
80
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
81
+
82
+
83
+ class PEERRotaryEmbedding(nn.Module):
84
+ def __init__(self, config: PEERConfig, device=None):
85
+ super().__init__()
86
+ # BC: "rope_type" was originally "type"
87
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
88
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
89
+ else:
90
+ self.rope_type = "default"
91
+ self.max_seq_len_cached = config.max_position_embeddings
92
+ self.original_max_seq_len = config.max_position_embeddings
93
+
94
+ self.config = config
95
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
96
+
97
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
98
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
99
+ self.original_inv_freq = self.inv_freq
100
+
101
+ @torch.no_grad()
102
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
103
+ def forward(self, x, position_ids):
104
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
105
+ position_ids_expanded = position_ids[:, None, :].float()
106
+
107
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
108
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
109
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
110
+ emb = torch.cat((freqs, freqs), dim=-1)
111
+ cos = emb.cos() * self.attention_scaling
112
+ sin = emb.sin() * self.attention_scaling
113
+
114
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
115
+
116
+
117
+ def rotate_half(x):
118
+ """Rotates half the hidden dims of the input."""
119
+ x1 = x[..., : x.shape[-1] // 2]
120
+ x2 = x[..., x.shape[-1] // 2 :]
121
+ return torch.cat((-x2, x1), dim=-1)
122
+
123
+
124
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
125
+ """Applies Rotary Position Embedding to the query and key tensors.
126
+
127
+ Args:
128
+ q (`torch.Tensor`): The query tensor.
129
+ k (`torch.Tensor`): The key tensor.
130
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
131
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
132
+ position_ids (`torch.Tensor`, *optional*):
133
+ Deprecated and unused.
134
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
135
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
136
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
137
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
138
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
139
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
140
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
141
+ Returns:
142
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
143
+ """
144
+ cos = cos.unsqueeze(unsqueeze_dim)
145
+ sin = sin.unsqueeze(unsqueeze_dim)
146
+ q_embed = (q * cos) + (rotate_half(q) * sin)
147
+ k_embed = (k * cos) + (rotate_half(k) * sin)
148
+ return q_embed, k_embed
149
+
150
+
151
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
152
+ """
153
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
154
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
155
+ """
156
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
157
+ if n_rep == 1:
158
+ return hidden_states
159
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
160
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
161
+
162
+
163
+ def eager_attention_forward(
164
+ module: nn.Module,
165
+ query: torch.Tensor,
166
+ key: torch.Tensor,
167
+ value: torch.Tensor,
168
+ attention_mask: Optional[torch.Tensor],
169
+ scaling: float,
170
+ dropout: float = 0.0,
171
+ **kwargs: Unpack[TransformersKwargs],
172
+ ):
173
+ key_states = repeat_kv(key, module.num_key_value_groups)
174
+ value_states = repeat_kv(value, module.num_key_value_groups)
175
+
176
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
177
+ if attention_mask is not None:
178
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
179
+ attn_weights = attn_weights + causal_mask
180
+
181
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
182
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
183
+ attn_output = torch.matmul(attn_weights, value_states)
184
+ attn_output = attn_output.transpose(1, 2).contiguous()
185
+
186
+ return attn_output, attn_weights
187
+
188
+
189
+ def flex_attention_forward(
190
+ module: nn.Module,
191
+ query: torch.Tensor,
192
+ key: torch.Tensor,
193
+ value: torch.Tensor,
194
+ attention_mask: Union[torch.Tensor, "BlockMask"],
195
+ scaling: Optional[float] = None,
196
+ softcap: Optional[float] = None,
197
+ head_mask: Optional[torch.Tensor] = None,
198
+ **kwargs,
199
+ ) -> tuple[torch.Tensor, torch.Tensor]:
200
+ block_mask = None
201
+ causal_mask = None
202
+ if isinstance(attention_mask, BlockMask):
203
+ block_mask = attention_mask
204
+ else:
205
+ causal_mask = attention_mask
206
+
207
+ if causal_mask is not None:
208
+ causal_mask = causal_mask[:, :, :, : key.shape[-2]]
209
+
210
+ def score_mod(score, batch_idx, head_idx, q_idx, kv_idx):
211
+ if softcap is not None:
212
+ score = softcap * torch.tanh(score / softcap)
213
+ if causal_mask is not None:
214
+ score = score + causal_mask[batch_idx][head_idx][q_idx][kv_idx]
215
+ if head_mask is not None:
216
+ score = score + head_mask[batch_idx][head_idx][0][0]
217
+ return score
218
+
219
+ attn_output, attention_weights = compile_friendly_flex_attention(
220
+ query,
221
+ key,
222
+ value,
223
+ score_mod=score_mod,
224
+ block_mask=block_mask,
225
+ enable_gqa=True,
226
+ scale=scaling,
227
+ # Last time checked on PyTorch == 2.5.1: Flex Attention always computes the lse regardless.
228
+ # For simplification, we thus always return it as no additional computations are introduced.
229
+ return_lse=True,
230
+ )
231
+ # lse is returned in float32
232
+ attention_weights = attention_weights.to(value.dtype)
233
+ attn_output = attn_output.transpose(1, 2).contiguous()
234
+
235
+ return attn_output, attention_weights
236
+
237
+
238
+ ALL_ATTENTION_FUNCTIONS = AttentionInterface()
239
+ ALL_ATTENTION_FUNCTIONS["peer_flex_attention"] = flex_attention_forward
240
+
241
+
242
+ class PEERAttention(nn.Module):
243
+ def __init__(self, config: PEERConfig, layer_idx: Optional[int] = None):
244
+ super().__init__()
245
+ self.config = config
246
+ self.layer_idx = layer_idx
247
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
248
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
249
+ self.scaling = self.head_dim**-0.5
250
+ self.attention_dropout = config.attention_dropout
251
+ self.keep_window_size = config.keep_window_size
252
+
253
+ self.q_proj = nn.Linear(
254
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
255
+ )
256
+ self.k_proj = nn.Linear(
257
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
258
+ )
259
+ self.v_proj = nn.Linear(
260
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
261
+ )
262
+ self.o_proj = nn.Linear(
263
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
264
+ )
265
+ self.q_norm = PEERRMSNorm(self.head_dim, eps=config.rms_norm_eps)
266
+ self.k_norm = PEERRMSNorm(self.head_dim, eps=config.rms_norm_eps)
267
+
268
+ def forward(
269
+ self,
270
+ hidden_states: torch.Tensor,
271
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
272
+ attention_mask: Optional[torch.Tensor] = None,
273
+ past_key_value: Optional[Cache] = None,
274
+ cache_position: Optional[torch.LongTensor] = None,
275
+ **kwargs,
276
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
277
+ input_shape = hidden_states.shape[:-1]
278
+ hidden_shape = (*input_shape, -1, self.head_dim)
279
+
280
+ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
281
+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
282
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
283
+
284
+ cos, sin = position_embeddings
285
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
286
+
287
+ if past_key_value is not None:
288
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
289
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
290
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
291
+
292
+ attn_mask = attention_mask
293
+ attention_interface: Callable = eager_attention_forward
294
+ if self.config._attn_implementation != "eager":
295
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
296
+
297
+ attn_output, attn_weights = attention_interface(
298
+ self,
299
+ query_states,
300
+ key_states,
301
+ value_states,
302
+ attention_mask=attn_mask,
303
+ dropout=0.0 if not self.training else self.attention_dropout,
304
+ scaling=self.scaling,
305
+ **kwargs,
306
+ )
307
+
308
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
309
+ attn_output = self.o_proj(attn_output)
310
+ return attn_output, attn_weights
311
+
312
+
313
+ class PEERMLP(nn.Module):
314
+ def __init__(self, config):
315
+ super().__init__()
316
+ self.config = config
317
+ self.hidden_size = config.hidden_size
318
+ self.intermediate_size = config.intermediate_size
319
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
320
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
321
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
322
+ self.act_fn = ACT2FN[config.hidden_act]
323
+
324
+ def forward(self, x):
325
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
326
+ return down_proj
327
+
328
+
329
+ class PEERCDMoE(nn.Module):
330
+ def __init__(self, config: PEERConfig):
331
+ super().__init__()
332
+ self.hidden_size = config.hidden_size
333
+ self.intermediate_size = config.intermediate_size
334
+ self.act_fn = ACT2FN[config.hidden_act]
335
+ self.num_heads = config.num_peer_heads
336
+
337
+ self.num_experts = config.num_experts
338
+ self.num_keys = math.floor(math.sqrt(self.num_experts))
339
+ self.top_k = config.num_experts_per_tok
340
+ self.norm_topk_prob = config.norm_topk_prob
341
+
342
+ # router gate for retrieval experts
343
+ self.to_queries = nn.Sequential(
344
+ nn.Linear(self.hidden_size, self.hidden_size * self.num_heads, bias = False),
345
+ Rearrange('b n (p h d) -> p b n h d', p = 2, h = self.num_heads)
346
+ )
347
+ self.keys = nn.Parameter(torch.zeros(self.num_heads, self.num_keys, 2, self.hidden_size // 2))
348
+
349
+ # routed experts
350
+ self.down_embed = nn.Embedding(self.num_experts * self.num_heads, self.hidden_size)
351
+ self.up_embed = nn.Embedding(self.num_experts * self.num_heads, self.hidden_size)
352
+
353
+ def forward(
354
+ self,
355
+ hidden_states: torch.Tensor,
356
+ **kwargs,
357
+ ) -> torch.Tensor:
358
+
359
+ queries = self.to_queries(hidden_states)
360
+ sim = einsum(queries, self.keys, 'p b n h d, h k p d -> p b n h k')
361
+ (scores_x, scores_y), (indices_x, indices_y) = sim.topk(self.num_keys, dim = -1)
362
+ all_scores = einx.add('... i, ... j -> ... (i j)', scores_x, scores_y)
363
+ all_indices = einx.add('... i, ... j -> ... (i j)', indices_x * self.num_keys, indices_y)
364
+ scores, pk_indices = all_scores.topk(self.top_k, dim = -1)
365
+ indices = all_indices.gather(-1, pk_indices)
366
+ weights_down = self.down_embed(indices)
367
+ weights_up = self.up_embed(indices)
368
+ hidden_states = einsum(hidden_states, weights_down, 'b n d, b n h k d -> b n h k')
369
+ hidden_states = self.act_fn(hidden_states) * scores.softmax(dim=-1)
370
+ hidden_states = einsum(hidden_states, weights_up, 'b n h k, b n h k d -> b n d')
371
+
372
+ return hidden_states, None
373
+
374
+
375
+ class PEERDecoderLayer(GradientCheckpointingLayer):
376
+ def __init__(self, config: PEERConfig, layer_idx: Optional[int] = None):
377
+ super().__init__()
378
+ self.hidden_dropout = config.hidden_dropout
379
+
380
+ self.input_layernorm = PEERRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
381
+ self.self_attn = PEERAttention(config=config, layer_idx=layer_idx)
382
+ self.input_residual = nn.Parameter(torch.ones(config.hidden_size))
383
+
384
+ self.post_attention_layernorm = PEERRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
385
+ self.mlp = PEERMLP(config) if not config.is_moe else PEERCDMoE(config)
386
+ self.post_attention_residual = nn.Parameter(torch.ones(config.hidden_size))
387
+
388
+ def forward(
389
+ self,
390
+ hidden_states: torch.Tensor,
391
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
392
+ attention_mask: Optional[torch.Tensor] = None,
393
+ position_ids: Optional[torch.LongTensor] = None,
394
+ past_key_value: Optional[tuple[torch.Tensor]] = None,
395
+ use_cache: Optional[bool] = False,
396
+ cache_position: Optional[torch.LongTensor] = None,
397
+ **kwargs: Unpack[TransformersKwargs],
398
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
399
+ # sequence transformation
400
+ residual = hidden_states
401
+ hidden_states = self.input_layernorm(hidden_states)
402
+ hidden_states, self_attn_weights = self.self_attn(
403
+ hidden_states=hidden_states,
404
+ position_embeddings=position_embeddings,
405
+ attention_mask=attention_mask,
406
+ position_ids=position_ids,
407
+ past_key_value=past_key_value,
408
+ use_cache=use_cache,
409
+ cache_position=cache_position,
410
+ **kwargs,
411
+ )
412
+ hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training)
413
+ hidden_states = self.input_residual * residual + hidden_states
414
+
415
+ # state transformation
416
+ residual = hidden_states
417
+ hidden_states = self.post_attention_layernorm(hidden_states)
418
+ hidden_states = self.mlp(hidden_states)
419
+ if isinstance(hidden_states, tuple):
420
+ hidden_states, router_logits = hidden_states
421
+ else:
422
+ router_logits = None
423
+ hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training)
424
+ hidden_states = self.post_attention_residual * residual + hidden_states
425
+
426
+ return hidden_states, router_logits
427
+
428
+
429
+ @auto_docstring
430
+ class PEERPreTrainedModel(PreTrainedModel):
431
+ config_class = PEERConfig
432
+ base_model_prefix = "model"
433
+ supports_gradient_checkpointing = True
434
+ _no_split_modules = ["PEERDecoderLayer"]
435
+ _skip_keys_device_placement = ["past_key_values"]
436
+ _supports_flash_attn_2 = False
437
+ _supports_flash_attn_3 = False
438
+ _supports_sdpa = True
439
+ _supports_flex_attn = True
440
+ _supports_cache_class = True
441
+ _supports_quantized_cache = True
442
+ _supports_static_cache = False
443
+ _supports_attention_backend = True
444
+ _can_record_outputs = {
445
+ "router_logits": OutputRecorder(PEERCDMoE, index=1),
446
+ "hidden_states": PEERDecoderLayer,
447
+ "attentions": PEERAttention,
448
+ }
449
+
450
+ def _init_weights(self, module):
451
+ """Initialize the weights"""
452
+ std = self.config.initializer_range
453
+ if isinstance(module, nn.Linear):
454
+ module.weight.data.normal_(mean=0.0, std=std)
455
+ if module.bias is not None:
456
+ module.bias.data.zero_()
457
+ elif isinstance(module, nn.Embedding):
458
+ module.weight.data.normal_(mean=0.0, std=std)
459
+ if module.padding_idx is not None:
460
+ module.weight.data[module.padding_idx].zero_()
461
+ elif isinstance(module, PEERRMSNorm):
462
+ module.weight.data.fill_(1.0)
463
+
464
+ if isinstance(module, PEERAttention):
465
+ if hasattr(module, "A"):
466
+ module.A.data.zero_()
467
+ elif isinstance(module, PEERDecoderLayer):
468
+ if hasattr(module, "input_residual"):
469
+ module.input_residual.data.fill_(1.0)
470
+ if hasattr(module, "post_attention_residual"):
471
+ module.post_attention_residual.data.fill_(1.0)
472
+
473
+
474
+ @auto_docstring
475
+ class PEERModel(PEERPreTrainedModel):
476
+ def __init__(self, config: PEERConfig):
477
+ super().__init__(config)
478
+ self.padding_idx = config.pad_token_id
479
+ self.vocab_size = config.vocab_size
480
+
481
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
482
+ self.layers = nn.ModuleList(
483
+ [PEERDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
484
+ )
485
+ self.norm = PEERRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
486
+ self.rotary_emb = PEERRotaryEmbedding(config=config)
487
+ self.gradient_checkpointing = False
488
+
489
+ # Initialize weights and apply final processing
490
+ self.post_init()
491
+
492
+ def get_input_embeddings(self):
493
+ return self.embed_tokens
494
+
495
+ def set_input_embeddings(self, value):
496
+ self.embed_tokens = value
497
+
498
+ @check_model_inputs
499
+ @auto_docstring
500
+ def forward(
501
+ self,
502
+ input_ids: Optional[torch.LongTensor] = None,
503
+ attention_mask: Optional[torch.Tensor] = None,
504
+ position_ids: Optional[torch.LongTensor] = None,
505
+ past_key_values: Optional[Cache] = None,
506
+ inputs_embeds: Optional[torch.FloatTensor] = None,
507
+ use_cache: Optional[bool] = None,
508
+ cache_position: Optional[torch.LongTensor] = None,
509
+ **kwargs: Unpack[TransformersKwargs],
510
+ ) -> MoeModelOutputWithPast:
511
+ if (input_ids is None) ^ (inputs_embeds is not None):
512
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
513
+
514
+ if use_cache and past_key_values is None:
515
+ past_key_values = DynamicCache()
516
+
517
+ if inputs_embeds is None:
518
+ inputs_embeds = self.embed_tokens(input_ids)
519
+
520
+ if cache_position is None:
521
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
522
+ cache_position = torch.arange(
523
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
524
+ )
525
+ if position_ids is None:
526
+ position_ids = cache_position.unsqueeze(0)
527
+
528
+ mask_function = create_causal_mask if self.config.sliding_window is None else create_sliding_window_causal_mask
529
+ causal_mask = mask_function(
530
+ config=self.config,
531
+ input_embeds=inputs_embeds,
532
+ attention_mask=attention_mask,
533
+ cache_position=cache_position,
534
+ past_key_values=past_key_values,
535
+ position_ids=position_ids,
536
+ )
537
+
538
+ hidden_states = inputs_embeds
539
+
540
+ # create position embeddings to be shared across the decoder layers
541
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
542
+
543
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
544
+ hidden_states, router_logits = decoder_layer(
545
+ hidden_states,
546
+ position_embeddings=position_embeddings,
547
+ attention_mask=causal_mask,
548
+ position_ids=position_ids,
549
+ past_key_value=past_key_values,
550
+ use_cache=use_cache,
551
+ cache_position=cache_position,
552
+ **kwargs,
553
+ )
554
+
555
+ hidden_states = self.norm(hidden_states)
556
+
557
+ return MoeModelOutputWithPast( # only diff with Mistral is the output type, we need MoE
558
+ last_hidden_state=hidden_states,
559
+ past_key_values=past_key_values,
560
+ router_logits=router_logits,
561
+ )
562
+
563
+
564
+ def load_balancing_loss_func(
565
+ gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
566
+ num_experts: Optional[int] = None,
567
+ num_keys: Optional[int] = None,
568
+ top_k: int = 2,
569
+ attention_mask: Optional[torch.Tensor] = None,
570
+ ) -> Union[torch.Tensor, int]:
571
+ r"""
572
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
573
+
574
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
575
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
576
+ experts is too unbalanced.
577
+
578
+ Args:
579
+ gate_logits:
580
+ Logits from the `router_gate`, should be a tuple of model.config.num_hidden_layers tensors of
581
+ shape [2, batch_size * sequence_length, num_keys].
582
+ num_experts:
583
+ Number of experts
584
+ num_keys:
585
+ Number of keys
586
+ top_k:
587
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
588
+ parameter.
589
+ attention_mask (`torch.Tensor`, *optional*):
590
+ The attention_mask used in forward function
591
+ shape [batch_size X sequence_length] if not None.
592
+
593
+ Returns:
594
+ The auxiliary loss.
595
+ """
596
+ if gate_logits is None or not isinstance(gate_logits, tuple):
597
+ return 0
598
+
599
+ compute_dtype = gate_logits[0].dtype
600
+ compute_device = gate_logits[0].device
601
+ all_expert_indices = []
602
+ all_routing_weights = []
603
+
604
+ for layer_gate_logits in gate_logits:
605
+ layer_gate_logits = layer_gate_logits.to(compute_device)
606
+
607
+ (scores_x, scores_y), (indices_x, indices_y) = layer_gate_logits.topk(num_keys, dim=-1)
608
+
609
+ all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2)
610
+ all_indices = indices_x.unsqueeze(-1) * num_keys + indices_y.unsqueeze(-2)
611
+ all_scores = all_scores.view(*all_scores.shape[:-2], -1)
612
+ all_indices = all_indices.view(*all_indices.shape[:-2], -1)
613
+
614
+ _, position_indices = all_scores.topk(top_k, dim=-1)
615
+ expert_indices = all_indices.gather(-1, position_indices)
616
+
617
+ routing_weights = F.softmax(all_scores, dim=-1)
618
+
619
+ all_expert_indices.append(expert_indices)
620
+ all_routing_weights.append(routing_weights)
621
+ all_expert_indices = torch.cat(all_expert_indices, dim=0)
622
+ all_routing_weights = torch.cat(all_routing_weights, dim=0)
623
+
624
+ if attention_mask is None:
625
+ # Compute the percentage of tokens routed to each experts
626
+ all_expert_indices = all_expert_indices.view(-1)
627
+ tokens_per_expert = torch.zeros(num_experts, dtype=compute_dtype, device=compute_device)
628
+ pad = torch.ones_like(all_expert_indices, dtype=compute_dtype, device=compute_device)
629
+ tokens_per_expert = tokens_per_expert.scatter_add_(0, all_expert_indices, pad) / all_expert_indices.shape[0]
630
+
631
+ # Compute the average probability of routing to these experts
632
+ router_prob_per_expert = torch.mean(all_routing_weights, dim=0)
633
+ else:
634
+ batch_size, sequence_length = attention_mask.shape
635
+ num_hidden_layers = len(gate_logits)
636
+
637
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
638
+ expert_attention_mask = (
639
+ attention_mask[None, :, :, None]
640
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k))
641
+ .reshape(-1)
642
+ .to(compute_device)
643
+ )
644
+ all_expert_indices = all_expert_indices.view(-1)[expert_attention_mask.bool()]
645
+
646
+ # Compute the percentage of tokens routed to each experts
647
+ tokens_per_expert = torch.zeros(num_experts, dtype=compute_dtype, device=compute_device)
648
+ pad = torch.ones_like(all_expert_indices, dtype=compute_dtype, device=compute_device)
649
+ tokens_per_expert = tokens_per_expert.scatter_add_(0, all_expert_indices, pad) / torch.sum(
650
+ expert_attention_mask
651
+ )
652
+
653
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
654
+ router_per_expert_attention_mask = (
655
+ attention_mask[None, :, :, None]
656
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
657
+ .reshape(-1, num_experts)
658
+ .to(compute_device)
659
+ )
660
+
661
+ # Compute the average probability of routing to these experts
662
+ router_prob_per_expert = torch.sum(all_routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
663
+ router_per_expert_attention_mask, dim=0
664
+ )
665
+
666
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert)
667
+ return overall_loss * num_experts
668
+
669
+
670
+ @auto_docstring
671
+ class PEERForCausalLM(PEERPreTrainedModel, GenerationMixin):
672
+ _tied_weights_keys = ["lm_head.weight"]
673
+ _tp_plan = {"lm_head": "colwise_rep"}
674
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
675
+
676
+ def __init__(self, config):
677
+ super().__init__(config)
678
+ self.model = PEERModel(config)
679
+ self.vocab_size = config.vocab_size
680
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
681
+ self.router_aux_loss_coef = config.router_aux_loss_coef
682
+ self.num_experts = config.num_experts
683
+ self.num_experts_per_tok = config.num_experts_per_tok
684
+
685
+ # Initialize weights and apply final processing
686
+ self.post_init()
687
+
688
+ def get_input_embeddings(self):
689
+ return self.model.embed_tokens
690
+
691
+ def set_input_embeddings(self, value):
692
+ self.model.embed_tokens = value
693
+
694
+ def get_output_embeddings(self):
695
+ return self.lm_head
696
+
697
+ def set_output_embeddings(self, new_embeddings):
698
+ self.lm_head = new_embeddings
699
+
700
+ def set_decoder(self, decoder):
701
+ self.model = decoder
702
+
703
+ def get_decoder(self):
704
+ return self.model
705
+
706
+ @can_return_tuple
707
+ @auto_docstring
708
+ def forward(
709
+ self,
710
+ input_ids: Optional[torch.LongTensor] = None,
711
+ attention_mask: Optional[torch.Tensor] = None,
712
+ position_ids: Optional[torch.LongTensor] = None,
713
+ past_key_values: Optional[list[torch.FloatTensor]] = None,
714
+ inputs_embeds: Optional[torch.FloatTensor] = None,
715
+ labels: Optional[torch.LongTensor] = None,
716
+ use_cache: Optional[bool] = None,
717
+ cache_position: Optional[torch.LongTensor] = None,
718
+ logits_to_keep: Union[int, torch.Tensor] = 0,
719
+ output_router_logits: Optional[bool] = None,
720
+ **kwargs: Unpack[TransformersKwargs],
721
+ ) -> MoeCausalLMOutputWithPast:
722
+ r"""
723
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
724
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
725
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
726
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
727
+
728
+ Example:
729
+
730
+ ```python
731
+ >>> from transformers import AutoTokenizer, PEERForCausalLM
732
+
733
+ >>> model = PEERForCausalLM.from_pretrained("SmallPEER/PEER-320M")
734
+ >>> tokenizer = AutoTokenizer.from_pretrained("SmallPEER/PEER-320M")
735
+
736
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
737
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
738
+
739
+ >>> # Generate
740
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
741
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
742
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
743
+ ```"""
744
+ output_router_logits = (
745
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
746
+ )
747
+
748
+ # if input_ids is not None:
749
+ # input_ids = torch.where(
750
+ # input_ids == torch.tensor([128256], device=input_ids.device, dtype=torch.long),
751
+ # torch.tensor([128001], device=input_ids.device, dtype=torch.long),
752
+ # input_ids
753
+ # )
754
+
755
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
756
+ outputs: MoeModelOutputWithPast = self.model(
757
+ input_ids=input_ids,
758
+ attention_mask=attention_mask,
759
+ position_ids=position_ids,
760
+ past_key_values=past_key_values,
761
+ inputs_embeds=inputs_embeds,
762
+ use_cache=use_cache,
763
+ cache_position=cache_position,
764
+ **kwargs,
765
+ )
766
+
767
+ hidden_states = outputs.last_hidden_state
768
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
769
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
770
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
771
+
772
+ loss = None
773
+ if labels is not None:
774
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
775
+
776
+ aux_loss = None
777
+ if output_router_logits:
778
+ aux_loss = load_balancing_loss_func(
779
+ outputs.router_logits,
780
+ self.num_experts,
781
+ math.floor(math.sqrt(self.num_experts)),
782
+ self.num_experts_per_tok,
783
+ attention_mask,
784
+ )
785
+ if labels is not None:
786
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
787
+
788
+ return MoeCausalLMOutputWithPast(
789
+ loss=loss,
790
+ aux_loss=aux_loss,
791
+ logits=logits,
792
+ past_key_values=outputs.past_key_values,
793
+ hidden_states=outputs.hidden_states,
794
+ attentions=outputs.attentions,
795
+ router_logits=outputs.router_logits,
796
+ )
797
+
798
+
799
+ @auto_docstring(
800
+ custom_intro="""
801
+ The PEER Model transformer with a sequence classification head on top (linear layer).
802
+
803
+ [`PEERForSequenceClassification`] uses the last token in order to do the classification, as other causal models
804
+ (e.g. GPT-2) do.
805
+
806
+ Since it does classification on the last token, it requires to know the position of the last token. If a
807
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
808
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
809
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
810
+ each row of the batch).
811
+ """
812
+ )
813
+ class PEERForSequenceClassification(PEERPreTrainedModel):
814
+ def __init__(self, config):
815
+ super().__init__(config)
816
+ self.num_labels = config.num_labels
817
+ self.model = PEERModel(config)
818
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
819
+
820
+ # Initialize weights and apply final processing
821
+ self.post_init()
822
+
823
+ def get_input_embeddings(self):
824
+ return self.model.embed_tokens
825
+
826
+ def set_input_embeddings(self, value):
827
+ self.model.embed_tokens = value
828
+
829
+ @can_return_tuple
830
+ @auto_docstring
831
+ def forward(
832
+ self,
833
+ input_ids: Optional[torch.LongTensor] = None,
834
+ attention_mask: Optional[torch.Tensor] = None,
835
+ position_ids: Optional[torch.LongTensor] = None,
836
+ past_key_values: Optional[Cache] = None,
837
+ inputs_embeds: Optional[torch.FloatTensor] = None,
838
+ labels: Optional[torch.LongTensor] = None,
839
+ use_cache: Optional[bool] = None,
840
+ **kwargs: Unpack[TransformersKwargs],
841
+ ) -> SequenceClassifierOutputWithPast:
842
+ r"""
843
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
844
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
845
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
846
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
847
+ """
848
+
849
+ transformer_outputs: BaseModelOutputWithPast = self.model(
850
+ input_ids,
851
+ attention_mask=attention_mask,
852
+ position_ids=position_ids,
853
+ past_key_values=past_key_values,
854
+ inputs_embeds=inputs_embeds,
855
+ use_cache=use_cache,
856
+ **kwargs,
857
+ )
858
+ hidden_states = transformer_outputs.last_hidden_state
859
+ logits = self.score(hidden_states)
860
+
861
+ if input_ids is not None:
862
+ batch_size = input_ids.shape[0]
863
+ else:
864
+ batch_size = inputs_embeds.shape[0]
865
+
866
+ if self.config.pad_token_id is None and batch_size != 1:
867
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
868
+ if self.config.pad_token_id is None:
869
+ last_non_pad_token = -1
870
+ elif input_ids is not None:
871
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
872
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
873
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
874
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
875
+ else:
876
+ last_non_pad_token = -1
877
+ logger.warning_once(
878
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
879
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
880
+ )
881
+
882
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
883
+
884
+ loss = None
885
+ if labels is not None:
886
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
887
+
888
+ return SequenceClassifierOutputWithPast(
889
+ loss=loss,
890
+ logits=pooled_logits,
891
+ past_key_values=transformer_outputs.past_key_values,
892
+ hidden_states=transformer_outputs.hidden_states,
893
+ attentions=transformer_outputs.attentions,
894
+ )
895
+
896
+
897
+ __all__ = ["PEERForCausalLM", "PEERModel", "PEERPreTrainedModel", "PEERForSequenceClassification"]