LoserCheems commited on
Commit
b566051
1 Parent(s): 6644523

Upload DogeForCausalLM

Browse files
Files changed (6) hide show
  1. README.md +199 -0
  2. config.json +36 -0
  3. configuration_doge.py +185 -0
  4. generation_config.json +7 -0
  5. model.safetensors +3 -0
  6. modeling_doge.py +1141 -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,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "./results_doge/25M/checkpoint-2000",
3
+ "architectures": [
4
+ "DogeForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_doge.DogeConfig",
8
+ "AutoModelForCausalLM": "modeling_doge.DogeForCausalLM"
9
+ },
10
+ "bos_token_id": 1,
11
+ "cross_domain_intermediate_size": 1024,
12
+ "eos_token_id": 2,
13
+ "hidden_act": "silu",
14
+ "hidden_bias": false,
15
+ "hidden_dropout": 0.0,
16
+ "hidden_size": 256,
17
+ "initializer_range": 0.02,
18
+ "max_position_embeddings": 16384,
19
+ "model_type": "doge",
20
+ "num_attention_heads": 4,
21
+ "num_cdmmoe_experts": 256,
22
+ "num_cdmmoe_experts_per_head": 4,
23
+ "num_cdmmoe_heads": 2,
24
+ "num_hidden_layers": 8,
25
+ "num_inner_values": 2,
26
+ "pad_token_id": 0,
27
+ "private_expert_intermediate_size": 256,
28
+ "rms_norm_eps": 1e-06,
29
+ "rope_scaling": null,
30
+ "rope_theta": 10000.0,
31
+ "tie_word_embeddings": false,
32
+ "torch_dtype": "float32",
33
+ "transformers_version": "4.46.1",
34
+ "use_cache": true,
35
+ "vocab_size": 32768
36
+ }
configuration_doge.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Jingze Shi and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on the Wonderful Matrices paper implementation.
5
+ #
6
+ # https://arxiv.org/abs/2407.16958
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+ """PyTorch Doge model configuration"""
20
+
21
+ from transformers.configuration_utils import PretrainedConfig
22
+ from transformers.modeling_rope_utils import rope_config_validation
23
+
24
+
25
+ class DogeConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`DogeModel`]. It is used to instantiate an Doge
28
+ model according to the specified arguments, defining the model architecture like [LoserCheems/doge-tiny-test](https://huggingface.co/LoserCheems/doge-tiny-test)
29
+
30
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
31
+ documentation from [`PretrainedConfig`] for more information.
32
+
33
+ Args:
34
+ vocab_size (`int`, *optional*, defaults to 32768):
35
+ Vocabulary size of the Doge model. Defines the number of different tokens that can be represented by the
36
+ `inputs_ids` passed when calling [`DogeModel`]
37
+ hidden_size (`int`, *optional*, defaults to 1024):
38
+ Dimension of the hidden representations.
39
+ num_hidden_layers (`int`, *optional*, defaults to 16):
40
+ Number of hidden layers in the Transformer decoder.
41
+ hidden_bias (`bool`, *optional*, defaults to `False`):
42
+ Whether to use bias in the hidden layers.
43
+ hidden_dropout (`float`, *optional*, defaults to 0.0):
44
+ Dropout probability for each sequence transformation and state transformation module.
45
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
46
+ The non-linear activation function (function or string) in the decoder.
47
+ max_position_embeddings (`int`, *optional*, defaults to 16384):
48
+ The maximum sequence length that this model might ever be used with.
49
+ rope_theta (`float`, *optional*, defaults to 10000.0):
50
+ The base period of the RoPE embeddings.
51
+ rope_scaling (`Dict`, *optional*):
52
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
53
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
54
+ accordingly.
55
+ Expected contents:
56
+ `rope_type` (`str`):
57
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
58
+ 'llama3'], with 'default' being the original RoPE implementation.
59
+ `factor` (`float`, *optional*):
60
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
61
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
62
+ original maximum pre-trained length.
63
+ `original_max_position_embeddings` (`int`, *optional*):
64
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
65
+ pretraining.
66
+ `attention_factor` (`float`, *optional*):
67
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
68
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
69
+ `factor` field to infer the suggested value.
70
+ `beta_fast` (`float`, *optional*):
71
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
72
+ ramp function. If unspecified, it defaults to 32.
73
+ `beta_slow` (`float`, *optional*):
74
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
75
+ ramp function. If unspecified, it defaults to 1.
76
+ `short_factor` (`List[float]`, *optional*):
77
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
78
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
79
+ size divided by the number of attention heads divided by 2
80
+ `long_factor` (`List[float]`, *optional*):
81
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
82
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
83
+ size divided by the number of attention heads divided by 2
84
+ `low_freq_factor` (`float`, *optional*):
85
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
86
+ `high_freq_factor` (`float`, *optional*):
87
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
88
+ initializer_range (`float`, *optional*, defaults to 0.02):
89
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
90
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
91
+ The epsilon used by the rms normalization layers.
92
+ use_cache (`bool`, *optional*, defaults to `True`):
93
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
94
+ relevant if `config.is_decoder=True`.
95
+ pad_token_id (`int`, *optional*, defaults to 0):
96
+ Padding token id.
97
+ bos_token_id (`int`, *optional*, defaults to 1):
98
+ Beginning of stream token id.
99
+ eos_token_id (`int`, *optional*, defaults to 2):
100
+ End of stream token id.
101
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
102
+ Whether to tie weight embeddings
103
+ num_attention_heads (`int`, *optional*, defaults to 16):
104
+ Number of attention heads for each attention layer in the Transformer decoder.
105
+ num_inner_values (`int`, *optional*, defaults to 8):
106
+ Number of inner values for each attention layer in the Transformer decoder.
107
+ cross_domain_intermediate_size (`int`, *optional*, defaults to 4096):
108
+ Dimension of the Cross Domain representations for the Cross Domain Mixture of Experts.
109
+ private_expert_intermediate_size (`int`, *optional*, defaults to 1024):
110
+ Dimension of the Private Expert representations for the Cross Domain Mixture of Experts.
111
+ num_cdmmoe_experts (`int`, *optional*, defaults to 4096):
112
+ Number of Private Experts for the Cross Domain Mixture of Experts.
113
+ num_cdmmoe_heads (`int`, *optional*, defaults to 1):
114
+ Number of heads of Private Experts for the Cross Domain Mixture of Experts.
115
+ num_cdmmoe_experts_per_head (`int`, *optional*, defaults to 2):
116
+ Number of Private Experts per head for the Cross Domain Mixture of Experts.
117
+ """
118
+
119
+ model_type = "doge"
120
+ keys_to_ignore_at_inference = ["past_key_values"]
121
+
122
+ def __init__(
123
+ self,
124
+ vocab_size=32768,
125
+ hidden_size=256,
126
+ num_hidden_layers=8,
127
+ hidden_bias=False,
128
+ hidden_dropout=0.0,
129
+ hidden_act="silu",
130
+ max_position_embeddings=16384,
131
+ rope_theta=10000.0,
132
+ rope_scaling=None,
133
+ initializer_range=0.02,
134
+ rms_norm_eps=1e-06,
135
+ use_cache=True,
136
+ pad_token_id=0,
137
+ bos_token_id=1,
138
+ eos_token_id=2,
139
+ tie_word_embeddings=False,
140
+ num_attention_heads=4,
141
+ num_inner_values=2,
142
+ cross_domain_intermediate_size=1024,
143
+ private_expert_intermediate_size=256,
144
+ num_cdmmoe_experts=256,
145
+ num_cdmmoe_heads=2,
146
+ num_cdmmoe_experts_per_head=4,
147
+ **kwargs,
148
+ ):
149
+ self.vocab_size = vocab_size
150
+ self.hidden_size = hidden_size
151
+ self.num_hidden_layers = num_hidden_layers
152
+ self.hidden_bias = hidden_bias
153
+ self.hidden_dropout = hidden_dropout
154
+ self.hidden_act = hidden_act
155
+ self.max_position_embeddings = max_position_embeddings
156
+ self.rope_theta = rope_theta
157
+ self.rope_scaling = rope_scaling
158
+ self.initializer_range = initializer_range
159
+ self.rms_norm_eps = rms_norm_eps
160
+ self.use_cache = use_cache
161
+ self.pad_token_id = pad_token_id
162
+ self.bos_token_id = bos_token_id
163
+ self.eos_token_id = eos_token_id
164
+ self.tie_word_embeddings = tie_word_embeddings
165
+ self.num_attention_heads = num_attention_heads
166
+ self.num_inner_values = num_inner_values
167
+ self.cross_domain_intermediate_size = cross_domain_intermediate_size
168
+ self.private_expert_intermediate_size = private_expert_intermediate_size
169
+ self.num_cdmmoe_experts = num_cdmmoe_experts
170
+ self.num_cdmmoe_heads = num_cdmmoe_heads
171
+ self.num_cdmmoe_experts_per_head = num_cdmmoe_experts_per_head
172
+
173
+ # Validate the correctness of rotary position embeddings parameters
174
+ # BC: if there is a 'type' field, copy it it to 'rope_type'.
175
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
176
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
177
+ rope_config_validation(self)
178
+
179
+ super().__init__(
180
+ pad_token_id=pad_token_id,
181
+ bos_token_id=bos_token_id,
182
+ eos_token_id=eos_token_id,
183
+ tie_word_embeddings=tie_word_embeddings,
184
+ **kwargs,
185
+ )
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "pad_token_id": 0,
6
+ "transformers_version": "4.46.1"
7
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e44e5918909b9a8a65efa448b1996e7e1fb0356fa05fa1cbb8d9fd7bfda3466e
3
+ size 101501024
modeling_doge.py ADDED
@@ -0,0 +1,1141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Jingze Shi and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on the Wonderful Matrices paper implementation.
5
+ #
6
+ # https://arxiv.org/abs/2407.16958
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+ """PyTorch Doge model."""
20
+
21
+ import math
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.nn.functional as F
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
31
+ from transformers.generation import GenerationMixin
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ SequenceClassifierOutputWithPast,
36
+ )
37
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.utils import (
40
+ add_start_docstrings,
41
+ add_start_docstrings_to_model_forward,
42
+ # is_einx_available,
43
+ logging,
44
+ replace_return_docstrings,
45
+ )
46
+ from .configuration_doge import DogeConfig
47
+
48
+
49
+
50
+ from einx import add as einx_add
51
+
52
+
53
+
54
+ logger = logging.get_logger(__name__)
55
+
56
+ _CONFIG_FOR_DOC = "DogeConfig"
57
+
58
+
59
+ class RMSNorm(nn.Module):
60
+ def __init__(self, hidden_size, eps=1e-6):
61
+ """
62
+ RMSNorm is equivalent to T5LayerNorm
63
+ """
64
+ super().__init__()
65
+ self.weight = nn.Parameter(torch.ones(hidden_size))
66
+ self.variance_epsilon = eps
67
+
68
+ def forward(self, hidden_states):
69
+ input_dtype = hidden_states.dtype
70
+ hidden_states = hidden_states.to(torch.float32)
71
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
72
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
73
+ return self.weight * hidden_states.to(input_dtype)
74
+
75
+ def extra_repr(self):
76
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
77
+
78
+
79
+ class RotaryEmbedding(nn.Module):
80
+ def __init__(self, config: Optional[DogeConfig] = None):
81
+ super().__init__()
82
+ self.rope_kwargs = {}
83
+
84
+ if config.rope_scaling is None:
85
+ self.rope_type = "default"
86
+ else:
87
+ self.rope_type = config.rope_scaling
88
+ self.max_seq_len_cached = config.max_position_embeddings
89
+ self.original_max_seq_len = config.max_position_embeddings
90
+ self.base = config.rope_theta
91
+
92
+ self.config = config
93
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
94
+
95
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, **self.rope_kwargs)
96
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
97
+ self.original_inv_freq = self.inv_freq
98
+
99
+ def _dynamic_frequency_update(self, position_ids, device):
100
+ """
101
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
102
+ 1 - growing beyond the cached sequence length (allow scaling)
103
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
104
+ """
105
+ seq_len = torch.max(position_ids) + 1
106
+ if seq_len > self.max_seq_len_cached: # growth
107
+ inv_freq, self.attention_scaling = self.rope_init_fn(
108
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
109
+ )
110
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
111
+ self.max_seq_len_cached = seq_len
112
+
113
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
114
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
115
+ self.max_seq_len_cached = self.original_max_seq_len
116
+
117
+ @torch.no_grad()
118
+ def forward(self, x, position_ids):
119
+ if "dynamic" in self.rope_type:
120
+ self._dynamic_frequency_update(position_ids, device=x.device)
121
+
122
+ # core RoPE block
123
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
124
+ position_ids_expanded = position_ids[:, None, :].float()
125
+ device_type = x.device.type
126
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
127
+ with torch.autocast(device_type=device_type, enabled=False):
128
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
129
+ emb = torch.cat((freqs, freqs), dim=-1)
130
+ cos = emb.cos()
131
+ sin = emb.sin()
132
+
133
+ cos = cos * self.attention_scaling
134
+ sin = sin * self.attention_scaling
135
+
136
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
137
+
138
+
139
+ def rotate_half(x):
140
+ """
141
+ Rotates half the hidden dims of the input.
142
+ """
143
+ x1 = x[..., : x.shape[-1] // 2]
144
+ x2 = x[..., x.shape[-1] // 2 :]
145
+ return torch.cat((-x2, x1), dim=-1)
146
+
147
+
148
+ def apply_QK_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
149
+ """Applies Rotary Position Embedding to the query and key tensors.
150
+
151
+ Args:
152
+ q (`torch.Tensor`): The query tensor.
153
+ k (`torch.Tensor`): The key tensor.
154
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
155
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
156
+ position_ids (`torch.Tensor`, *optional*):
157
+ Deprecated and unused.
158
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
159
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
160
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
161
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
162
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
163
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
164
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
165
+ Returns:
166
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
167
+ """
168
+ cos = cos.unsqueeze(unsqueeze_dim)
169
+ sin = sin.unsqueeze(unsqueeze_dim)
170
+ q_embed = (q * cos) + (rotate_half(q) * sin)
171
+ k_embed = (k * cos) + (rotate_half(k) * sin)
172
+ return q_embed, k_embed
173
+
174
+
175
+ class DogeInnerFuncAttn(nn.Module):
176
+ """Inner Function Attention from 'Wonderful Matrices' paper."""
177
+
178
+ def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None):
179
+ super().__init__()
180
+
181
+ self.config = config
182
+ self.layer_idx = layer_idx
183
+ if layer_idx is None:
184
+ logger.warning_once(
185
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
186
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
187
+ "when creating this class."
188
+ )
189
+
190
+ self.hidden_size = config.hidden_size
191
+ self.num_attention_heads = config.num_attention_heads
192
+
193
+ # for accuracy of attention scores, we do not use GQA
194
+ self.attention_head_dim = self.hidden_size // self.num_attention_heads
195
+ self.num_inner_values = config.num_inner_values
196
+
197
+ self.q_proj = nn.Linear(
198
+ self.hidden_size,
199
+ self.attention_head_dim * self.num_attention_heads,
200
+ bias=config.hidden_bias,
201
+ )
202
+ self.k_proj = nn.Linear(
203
+ self.hidden_size,
204
+ self.attention_head_dim * self.num_attention_heads,
205
+ bias=config.hidden_bias,
206
+ )
207
+ self.dynamic_mask = nn.Parameter(
208
+ torch.round(torch.ones(self.num_attention_heads, config.max_position_embeddings))
209
+ )
210
+ self.v_queries = nn.Linear(
211
+ self.hidden_size,
212
+ self.attention_head_dim,
213
+ bias=config.hidden_bias,
214
+ )
215
+ self.v_keys = nn.Parameter(
216
+ torch.zeros(
217
+ self.num_inner_values,
218
+ self.attention_head_dim,
219
+ )
220
+ )
221
+ self.v_embed = nn.Embedding(
222
+ self.num_inner_values,
223
+ self.attention_head_dim * self.num_attention_heads,
224
+ )
225
+ self.o_proj = nn.Linear(
226
+ self.hidden_size,
227
+ self.hidden_size,
228
+ bias=config.hidden_bias,
229
+ )
230
+
231
+ def _update_causal_mask(
232
+ self,
233
+ attention_mask: torch.Tensor = None,
234
+ input_tensor: torch.Tensor = None,
235
+ cache_position: torch.Tensor = None,
236
+ past_key_values: Cache = None,
237
+ output_attentions: bool = False,
238
+ ):
239
+ # for SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
240
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
241
+ # to infer the attention mask.
242
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
243
+ using_static_cache = isinstance(past_key_values, StaticCache)
244
+
245
+ dtype, device = input_tensor.dtype, input_tensor.device
246
+ sequence_length = input_tensor.shape[1]
247
+ if using_static_cache:
248
+ target_length = past_key_values.get_max_cache_shape()
249
+ else:
250
+ target_length = (
251
+ attention_mask.shape[-1]
252
+ if isinstance(attention_mask, torch.Tensor)
253
+ else past_seen_tokens + sequence_length + 1
254
+ )
255
+
256
+ # in case the provided `attention` mask is 2D, we generate a causal mask here (4D).
257
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position_and_dynamic_mask(
258
+ attention_mask=attention_mask,
259
+ dynamic_mask=self.dynamic_mask,
260
+ sequence_length=sequence_length,
261
+ target_length=target_length,
262
+ dtype=dtype,
263
+ device=device,
264
+ cache_position=cache_position,
265
+ batch_size=input_tensor.shape[0],
266
+ )
267
+
268
+ return causal_mask
269
+
270
+ @staticmethod
271
+ def _prepare_4d_causal_attention_mask_with_cache_position_and_dynamic_mask(
272
+ attention_mask: torch.Tensor = None,
273
+ dynamic_mask: torch.Tensor = None,
274
+ sequence_length: int = None,
275
+ target_length: int = None,
276
+ dtype: torch.dtype = None,
277
+ device: torch.device = None,
278
+ cache_position: torch.Tensor = None,
279
+ batch_size: int = None,
280
+ **kwargs,
281
+ ):
282
+ """
283
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
284
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
285
+
286
+ Args:
287
+ attention_mask (`torch.Tensor`):
288
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
289
+ `(batch_size, 1, query_length, key_value_length)`.
290
+ dynamic_mask (`torch.Tensor`):
291
+ A 2D dynamic mask of shape `(num_heads, max_position_embeddings)`.
292
+ sequence_length (`int`):
293
+ The sequence length being processed.
294
+ target_length (`int`):
295
+ The target length: when generating with static cache, the mask should be as long as the static cache,
296
+ to account for the 0 padding, the part of the cache that is not filled yet.
297
+ dtype (`torch.dtype`):
298
+ The dtype to use for the 4D attention mask.
299
+ device (`torch.device`):
300
+ The device to plcae the 4D attention mask on.
301
+ cache_position (`torch.Tensor`):
302
+ Indices depicting the position of the input sequence tokens in the sequence.
303
+ batch_size (`torch.Tensor`):
304
+ Batch size.
305
+ """
306
+ if attention_mask is not None and attention_mask.dim() == 4:
307
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
308
+ causal_mask = attention_mask
309
+ else:
310
+ num_heads = 1 if dynamic_mask is None else dynamic_mask.size(0)
311
+ min_dtype = torch.finfo(dtype).min
312
+ causal_mask = torch.full(
313
+ (sequence_length, target_length),
314
+ fill_value=min_dtype,
315
+ dtype=dtype,
316
+ device=device,
317
+ )
318
+ if sequence_length != 1:
319
+ causal_mask = torch.triu(causal_mask, diagonal=1)
320
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
321
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, num_heads, -1, -1)
322
+ if attention_mask is not None:
323
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
324
+ mask_length = attention_mask.shape[-1]
325
+ attention_mask = attention_mask[:, None, None, :].expand(-1, num_heads, 1, -1)
326
+ if dynamic_mask is not None:
327
+ dynamic_mask = dynamic_mask[None, :, None, :mask_length].expand(batch_size, -1, 1, -1)
328
+ attention_mask = attention_mask.clone() * dynamic_mask
329
+
330
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask
331
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
332
+ padding_mask == 0, min_dtype
333
+ )
334
+
335
+ return causal_mask
336
+
337
+ def inner_func(
338
+ self,
339
+ hidden_states: torch.Tensor,
340
+ ) -> torch.Tensor:
341
+ """
342
+ Each value can share weights with other values to increase the expressive power
343
+ """
344
+ v_queries = self.v_queries(hidden_states)
345
+ sim = torch.matmul(v_queries, self.v_keys.transpose(-1, -2))
346
+ v_embed = self.v_embed(sim.topk(k=1, dim=-1).indices)
347
+ v = hidden_states * v_embed.sum(dim=-2)
348
+ return v
349
+
350
+ def forward(
351
+ self,
352
+ hidden_states: torch.Tensor,
353
+ attention_mask: Optional[torch.Tensor] = None,
354
+ position_ids: Optional[torch.LongTensor] = None,
355
+ past_key_value: Optional[Cache] = None,
356
+ cache_position: Optional[torch.LongTensor] = None,
357
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
358
+ **kwargs,
359
+ ) -> Tuple[torch.Tensor, Optional[Cache]]:
360
+ bsz, seq_len, _ = hidden_states.shape
361
+
362
+ query_states = self.q_proj(hidden_states)
363
+ key_states = self.k_proj(hidden_states)
364
+ value_states = self.inner_func(hidden_states)
365
+
366
+ query_states = query_states.reshape(bsz, seq_len, self.num_attention_heads, self.attention_head_dim).transpose(
367
+ 1, 2
368
+ )
369
+ key_states = key_states.reshape(bsz, seq_len, self.num_attention_heads, self.attention_head_dim).transpose(
370
+ 1, 2
371
+ )
372
+ value_states = value_states.reshape(bsz, seq_len, self.num_attention_heads, self.attention_head_dim).transpose(
373
+ 1, 2
374
+ )
375
+
376
+ cos, sin = position_embeddings
377
+ query_states, query_states = apply_QK_rotary_pos_emb(query_states, query_states, cos, sin)
378
+
379
+ if past_key_value is not None:
380
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
381
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
382
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
383
+
384
+ attn_weights = torch.matmul(query_states, key_states.transpose(-1, -2)) / math.sqrt(self.attention_head_dim)
385
+
386
+ causal_mask = self._update_causal_mask(attention_mask, hidden_states, cache_position, past_key_value)
387
+ # no matter the length, we just slice it
388
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
389
+ attn_weights = attn_weights + causal_mask
390
+
391
+ # upcast attention to fp32
392
+ attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
393
+ attn_output = torch.matmul(attn_weights, value_states)
394
+
395
+ if attn_output.size() != (
396
+ bsz,
397
+ self.num_attention_heads,
398
+ seq_len,
399
+ self.attention_head_dim,
400
+ ):
401
+ raise ValueError(
402
+ f"`attn_output` should be of size {(bsz, self.num_attention_heads, seq_len, self.attention_head_dim)}, but is"
403
+ f" {attn_output.size()}"
404
+ )
405
+
406
+ attn_output = attn_output.transpose(1, 2).contiguous().reshape(bsz, seq_len, self.hidden_size)
407
+ attn_output = self.o_proj(attn_output)
408
+
409
+ return attn_output, past_key_value
410
+
411
+
412
+ class DogeCDMoE(nn.Module):
413
+ """Cross-Domain Mixture of Experts from 'Wonderful Matrices' paper."""
414
+
415
+ def __init__(self, config: DogeConfig):
416
+ super().__init__()
417
+ self.hidden_dim = config.hidden_size
418
+ self.act_fn = ACT2FN[config.hidden_act]
419
+
420
+ self.cross_domain_intermediate_size = config.cross_domain_intermediate_size
421
+ self.private_expert_intermediate_dim = config.private_expert_intermediate_size
422
+
423
+ self.num_cdmmoe_experts = config.num_cdmmoe_experts
424
+ self.num_cdmmoe_heads = config.num_cdmmoe_heads
425
+ self.num_cdmmoe_experts_per_head = config.num_cdmmoe_experts_per_head
426
+
427
+ # shared parameter up Linear
428
+ self.shared_up_proj = nn.Linear(
429
+ self.hidden_dim,
430
+ self.cross_domain_intermediate_size,
431
+ bias=config.hidden_bias,
432
+ )
433
+ # shared parameter down Linear
434
+ self.shared_down_proj = nn.Linear(
435
+ self.cross_domain_intermediate_size,
436
+ self.private_expert_intermediate_dim,
437
+ bias=config.hidden_bias,
438
+ )
439
+
440
+ # queries and keys for retrieval private experts
441
+ self.queries = nn.Linear(
442
+ self.private_expert_intermediate_dim,
443
+ self.private_expert_intermediate_dim * self.num_cdmmoe_heads,
444
+ bias=False,
445
+ )
446
+ self.num_keys = int(math.sqrt(self.num_cdmmoe_experts))
447
+ self.keys = nn.Parameter(
448
+ torch.zeros(
449
+ self.num_cdmmoe_heads,
450
+ self.num_keys,
451
+ 2,
452
+ self.private_expert_intermediate_dim // 2,
453
+ )
454
+ )
455
+
456
+ # private experts
457
+ self.down_embed = nn.Embedding(
458
+ self.num_cdmmoe_experts,
459
+ self.hidden_dim,
460
+ )
461
+ self.up_embed = nn.Embedding(
462
+ self.num_cdmmoe_experts,
463
+ self.private_expert_intermediate_dim,
464
+ )
465
+
466
+ def forward(
467
+ self,
468
+ hidden_states: torch.Tensor,
469
+ **kwargs,
470
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
471
+ bsz, seq_len, _ = hidden_states.shape
472
+ # cross-domain
473
+ hidden_states = self.shared_down_proj(self.act_fn(self.shared_up_proj(hidden_states)))
474
+
475
+ # queries
476
+ queries = self.queries(hidden_states)
477
+ queries = queries.reshape(bsz, seq_len, 2, self.num_cdmmoe_heads, -1).permute(2, 0, 1, 3, 4)
478
+ # get similarity with keys
479
+ sim = torch.einsum("p b t h d, h k p d -> p b t h k", queries, self.keys)
480
+ # get expert scores and indices with the highest similarity
481
+ (scores_x, scores_y), (indices_x, indices_y) = sim.topk(self.num_cdmmoe_experts_per_head, dim=-1)
482
+
483
+ if einx_add is not None:
484
+ all_scores = einx_add("... i, ... j -> ... (i j)", scores_x, scores_y)
485
+ all_indices = einx_add("... i, ... j -> ... (i j)", indices_x * self.num_keys, indices_y)
486
+ else:
487
+ all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2)
488
+ all_scores = all_scores.view(*scores_x.shape[:-1], -1)
489
+ all_indices = (indices_x.unsqueeze(-1) * self.num_keys) + indices_y.unsqueeze(-2)
490
+ all_indices = all_indices.view(*indices_x.shape[:-1], -1)
491
+
492
+ scores, pk_indices = all_scores.topk(self.num_cdmmoe_experts_per_head, dim=-1)
493
+ indices = all_indices.gather(-1, pk_indices)
494
+
495
+ # get related expert embeddings based on indices
496
+ down_embed = self.down_embed(indices)
497
+ up_embed = self.up_embed(indices)
498
+
499
+ # efficient retrieval of private experts
500
+ hidden_states = torch.einsum("b t d, b t h k d -> b t h k", hidden_states, down_embed)
501
+ hidden_states = self.act_fn(hidden_states * scores.softmax(dim=-1))
502
+ hidden_states = torch.einsum("b t h k, b t h k d -> b t d", hidden_states, up_embed)
503
+ return hidden_states
504
+
505
+
506
+ class DogeDecoderLayer(nn.Module):
507
+ def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None):
508
+ super().__init__()
509
+ self.hidden_dropout = config.hidden_dropout
510
+
511
+ self.in_attn_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
512
+ self.attn = DogeInnerFuncAttn(config, layer_idx)
513
+ self.in_ff_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
514
+ self.feed_forward = DogeCDMoE(config)
515
+
516
+ def forward(
517
+ self,
518
+ hidden_states: torch.Tensor,
519
+ attention_mask: Optional[torch.Tensor] = None,
520
+ position_ids: Optional[torch.LongTensor] = None,
521
+ past_key_value: Optional[Cache] = None,
522
+ output_attentions: Optional[bool] = False,
523
+ use_cache: Optional[bool] = False,
524
+ cache_position: Optional[torch.LongTensor] = None,
525
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
526
+ **kwargs,
527
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
528
+ """
529
+ Args:
530
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
531
+ attention_mask (`torch.FloatTensor`, *optional*):
532
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
533
+ query_sequence_length, key_sequence_length)` if default attention is used.
534
+ output_attentions (`bool`, *optional*):
535
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
536
+ returned tensors for more detail.
537
+ use_cache (`bool`, *optional*):
538
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
539
+ (see `past_key_values`).
540
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
541
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
542
+ Indices depicting the position of the input sequence tokens in the sequence
543
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
544
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
545
+ with `head_dim` being the embedding dimension of each attention head.
546
+ kwargs (`dict`, *optional*):
547
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
548
+ into the model
549
+ """
550
+
551
+ # sequence transformation
552
+ residual = hidden_states
553
+ hidden_states = self.in_attn_layernorm(hidden_states)
554
+ hidden_states, present_key_value = self.attn(
555
+ hidden_states=hidden_states,
556
+ attention_mask=attention_mask,
557
+ position_ids=position_ids,
558
+ past_key_value=past_key_value,
559
+ cache_position=cache_position,
560
+ position_embeddings=position_embeddings,
561
+ **kwargs,
562
+ )
563
+ self_attn_weights = None
564
+ hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training)
565
+ hidden_states = residual + hidden_states
566
+
567
+ # state transformation
568
+ residual = hidden_states
569
+ hidden_states = self.in_ff_layernorm(hidden_states)
570
+ hidden_states = self.feed_forward(hidden_states)
571
+ hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training)
572
+ hidden_states = residual + hidden_states
573
+
574
+ outputs = (hidden_states,)
575
+
576
+ if output_attentions:
577
+ outputs += (self_attn_weights,)
578
+
579
+ if use_cache:
580
+ outputs += (present_key_value,)
581
+
582
+ return outputs
583
+
584
+
585
+ @add_start_docstrings("The bare Doge Model outputting raw hidden-states without any specific head on top.")
586
+ class DogePreTrainedModel(PreTrainedModel):
587
+ config_class = DogeConfig
588
+ base_model_prefix = "model"
589
+ supports_gradient_checkpointing = True
590
+ _no_split_modules = ["DogeDecoderLayer"]
591
+ _skip_keys_device_placement = ["past_key_values"]
592
+ _supports_cache_class = True
593
+ _supports_quantized_cache = True
594
+ _supports_static_cache = True
595
+
596
+ def _init_weights(self, module):
597
+ std = self.config.initializer_range
598
+ if isinstance(module, (nn.Linear)):
599
+ module.weight.data.normal_(mean=0.0, std=std)
600
+ if module.bias is not None:
601
+ module.bias.data.zero_()
602
+ elif isinstance(module, nn.Embedding):
603
+ module.weight.data.normal_(mean=0.0, std=std)
604
+ if module.padding_idx is not None:
605
+ module.weight.data[module.padding_idx].zero_()
606
+
607
+
608
+ DOGE_INPUTS_DOCSTRING = r"""
609
+ Args:
610
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
611
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
612
+ it.
613
+
614
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
615
+ [`PreTrainedTokenizer.__call__`] for details.
616
+
617
+ [What are input IDs?](../glossary#input-ids)
618
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
619
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
620
+
621
+ - 1 for tokens that are **not masked**,
622
+ - 0 for tokens that are **masked**.
623
+
624
+ [What are attention masks?](../glossary#attention-mask)
625
+
626
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
627
+ [`PreTrainedTokenizer.__call__`] for details.
628
+
629
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
630
+ `past_key_values`).
631
+
632
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
633
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
634
+ information on the default strategy.
635
+
636
+ - 1 indicates the head is **not masked**,
637
+ - 0 indicates the head is **masked**.
638
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
639
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
640
+ config.n_positions - 1]`.
641
+
642
+ [What are position IDs?](../glossary#position-ids)
643
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
644
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
645
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
646
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
647
+
648
+ Two formats are allowed:
649
+ - a [`~cache_utils.Cache`] instance, see our
650
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
651
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
652
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
653
+ cache format.
654
+
655
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
656
+ legacy cache format will be returned.
657
+
658
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
659
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
660
+ of shape `(batch_size, sequence_length)`.
661
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
662
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
663
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
664
+ model's internal embedding lookup matrix.
665
+ use_cache (`bool`, *optional*):
666
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
667
+ `past_key_values`).
668
+ output_attentions (`bool`, *optional*):
669
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
670
+ tensors for more detail.
671
+ output_hidden_states (`bool`, *optional*):
672
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
673
+ more detail.
674
+ return_dict (`bool`, *optional*):
675
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
676
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
677
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
678
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
679
+ the complete sequence length.
680
+ """
681
+
682
+
683
+ @add_start_docstrings("The bare Doge Model outputting raw hidden-states without any specific head on top.")
684
+ class DogeModel(DogePreTrainedModel):
685
+ def __init__(self, config: DogeConfig):
686
+ super().__init__(config)
687
+ self.config = config
688
+ self.padding_idx = config.pad_token_id
689
+ self.vocab_size = config.vocab_size
690
+
691
+ self.word_embed = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
692
+ self.rotary_emb = RotaryEmbedding(config)
693
+ self.layers = nn.ModuleList(
694
+ [DogeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
695
+ )
696
+ self.final_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
697
+ self.gradient_checkpointing = False
698
+
699
+ # Initialize weights and apply final processing
700
+ self.post_init()
701
+
702
+ def get_input_embeddings(self):
703
+ return self.word_embed
704
+
705
+ def set_input_embeddings(self, value):
706
+ self.word_embed = value
707
+
708
+ @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING)
709
+ def forward(
710
+ self,
711
+ input_ids: torch.LongTensor = None,
712
+ attention_mask: Optional[torch.Tensor] = None,
713
+ position_ids: Optional[torch.LongTensor] = None,
714
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
715
+ inputs_embeds: Optional[torch.FloatTensor] = None,
716
+ use_cache: Optional[bool] = None,
717
+ output_attentions: Optional[bool] = None,
718
+ output_hidden_states: Optional[bool] = None,
719
+ return_dict: Optional[bool] = None,
720
+ cache_position: Optional[torch.LongTensor] = None,
721
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
722
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
723
+ output_hidden_states = (
724
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
725
+ )
726
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
727
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
728
+
729
+ if (input_ids is None) ^ (inputs_embeds is not None):
730
+ raise ValueError("You cannot specify both input_ids and inputs_embeds")
731
+
732
+ if self.gradient_checkpointing and self.training and use_cache:
733
+ logger.warning_once(
734
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
735
+ )
736
+ use_cache = False
737
+
738
+ if inputs_embeds is None:
739
+ inputs_embeds = self.word_embed(input_ids)
740
+
741
+ # kept for BC (non `Cache` `past_key_values` inputs)
742
+ return_legacy_cache = False
743
+ if use_cache and not isinstance(past_key_values, Cache):
744
+ return_legacy_cache = True
745
+ if past_key_values is None:
746
+ past_key_values = DynamicCache()
747
+ else:
748
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
749
+ logger.warning_once(
750
+ "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
751
+ "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
752
+ "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
753
+ )
754
+
755
+ if cache_position is None:
756
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
757
+ cache_position = torch.arange(
758
+ past_seen_tokens,
759
+ past_seen_tokens + inputs_embeds.shape[1],
760
+ device=inputs_embeds.device,
761
+ )
762
+ if position_ids is None:
763
+ position_ids = cache_position.unsqueeze(0)
764
+
765
+ # causal_mask = self._update_causal_mask(
766
+ # attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
767
+ # )
768
+ hidden_states = inputs_embeds
769
+
770
+ # create position embeddings to be shared across the decoder layers
771
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
772
+
773
+ # decoder layers
774
+ all_hidden_states = () if output_hidden_states else None
775
+ all_self_attns = () if output_attentions else None
776
+
777
+ for decoder_layer in self.layers:
778
+ if output_hidden_states:
779
+ all_hidden_states += (hidden_states,)
780
+
781
+ if self.gradient_checkpointing and self.training:
782
+ layer_outputs = self._gradient_checkpointing_func(
783
+ decoder_layer.__call__,
784
+ hidden_states,
785
+ attention_mask,
786
+ position_ids,
787
+ past_key_values,
788
+ output_attentions,
789
+ use_cache,
790
+ cache_position,
791
+ position_embeddings,
792
+ )
793
+ else:
794
+ layer_outputs = decoder_layer(
795
+ hidden_states,
796
+ attention_mask=attention_mask,
797
+ position_ids=position_ids,
798
+ past_key_value=past_key_values,
799
+ output_attentions=output_attentions,
800
+ use_cache=use_cache,
801
+ cache_position=cache_position,
802
+ position_embeddings=position_embeddings,
803
+ )
804
+
805
+ hidden_states = layer_outputs[0]
806
+
807
+ if use_cache:
808
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
809
+
810
+ if output_attentions:
811
+ all_self_attns += (layer_outputs[1],)
812
+
813
+ hidden_states = self.final_layernorm(hidden_states)
814
+
815
+ # add hidden states from the last decoder layer
816
+ if output_hidden_states:
817
+ all_hidden_states += (hidden_states,)
818
+
819
+ next_cache = next_decoder_cache if use_cache else None
820
+ if return_legacy_cache:
821
+ next_cache = next_cache.to_legacy_cache()
822
+
823
+ if not return_dict:
824
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
825
+
826
+ return BaseModelOutputWithPast(
827
+ last_hidden_state=hidden_states,
828
+ past_key_values=next_cache,
829
+ hidden_states=all_hidden_states,
830
+ attentions=all_self_attns,
831
+ )
832
+
833
+ """Move to DogeInnerFuncAttn"""
834
+ # def _update_causal_mask(
835
+ # self,
836
+ # attention_mask: torch.Tensor,
837
+ # input_tensor: torch.Tensor,
838
+ # cache_position: torch.Tensor,
839
+ # past_key_values: Cache,
840
+ # output_attentions: bool,
841
+ # ):
842
+ # # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
843
+ # # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
844
+ # # to infer the attention mask.
845
+ # past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
846
+ # using_static_cache = isinstance(past_key_values, StaticCache)
847
+
848
+ # dtype, device = input_tensor.dtype, input_tensor.device
849
+ # sequence_length = input_tensor.shape[1]
850
+ # if using_static_cache:
851
+ # target_length = past_key_values.get_max_cache_shape()
852
+ # else:
853
+ # target_length = (
854
+ # attention_mask.shape[-1]
855
+ # if isinstance(attention_mask, torch.Tensor)
856
+ # else past_seen_tokens + sequence_length + 1
857
+ # )
858
+
859
+ # # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
860
+ # causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
861
+ # attention_mask,
862
+ # sequence_length=sequence_length,
863
+ # target_length=target_length,
864
+ # dtype=dtype,
865
+ # device=device,
866
+ # cache_position=cache_position,
867
+ # batch_size=input_tensor.shape[0],
868
+ # )
869
+
870
+ # return causal_mask
871
+
872
+ # @staticmethod
873
+ # def _prepare_4d_causal_attention_mask_with_cache_position(
874
+ # attention_mask: torch.Tensor,
875
+ # sequence_length: int,
876
+ # target_length: int,
877
+ # dtype: torch.dtype,
878
+ # device: torch.device,
879
+ # cache_position: torch.Tensor,
880
+ # batch_size: int,
881
+ # **kwargs,
882
+ # ):
883
+ # """
884
+ # Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
885
+ # `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
886
+
887
+ # Args:
888
+ # attention_mask (`torch.Tensor`):
889
+ # A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
890
+ # `(batch_size, 1, query_length, key_value_length)`.
891
+ # sequence_length (`int`):
892
+ # The sequence length being processed.
893
+ # target_length (`int`):
894
+ # The target length: when generating with static cache, the mask should be as long as the static cache,
895
+ # to account for the 0 padding, the part of the cache that is not filled yet.
896
+ # dtype (`torch.dtype`):
897
+ # The dtype to use for the 4D attention mask.
898
+ # device (`torch.device`):
899
+ # The device to plcae the 4D attention mask on.
900
+ # cache_position (`torch.Tensor`):
901
+ # Indices depicting the position of the input sequence tokens in the sequence.
902
+ # batch_size (`torch.Tensor`):
903
+ # Batch size.
904
+ # """
905
+ # if attention_mask is not None and attention_mask.dim() == 4:
906
+ # # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
907
+ # causal_mask = attention_mask
908
+ # else:
909
+ # min_dtype = torch.finfo(dtype).min
910
+ # causal_mask = torch.full(
911
+ # (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
912
+ # )
913
+ # if sequence_length != 1:
914
+ # causal_mask = torch.triu(causal_mask, diagonal=1)
915
+ # causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
916
+ # causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
917
+ # if attention_mask is not None:
918
+ # causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
919
+ # mask_length = attention_mask.shape[-1]
920
+ # padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
921
+ # padding_mask = padding_mask == 0
922
+ # causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
923
+ # padding_mask, min_dtype
924
+ # )
925
+
926
+ # return causal_mask
927
+
928
+
929
+ class DogeForCausalLM(DogePreTrainedModel, GenerationMixin):
930
+ _tied_weights_keys = ["lm_head.weight"]
931
+
932
+ def __init__(self, config: DogeConfig):
933
+ super().__init__(config)
934
+ self.config = config
935
+ self.model = DogeModel(config)
936
+ self.vocab_size = config.vocab_size
937
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
938
+
939
+ # Initialize weights and apply final processing
940
+ self.post_init()
941
+
942
+ def get_input_embeddings(self):
943
+ return self.model.word_embed
944
+
945
+ def set_input_embeddings(self, value):
946
+ self.model.word_embed = value
947
+
948
+ def get_output_embeddings(self):
949
+ return self.lm_head
950
+
951
+ def set_output_embeddings(self, new_embeddings):
952
+ self.lm_head = new_embeddings
953
+
954
+ def set_decoder(self, decoder):
955
+ self.model = decoder
956
+
957
+ def get_decoder(self):
958
+ return self.model
959
+
960
+ @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING)
961
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
962
+ def forward(
963
+ self,
964
+ input_ids: torch.LongTensor = None,
965
+ attention_mask: Optional[torch.Tensor] = None,
966
+ position_ids: Optional[torch.LongTensor] = None,
967
+ past_key_values: Optional[torch.Tensor] = None,
968
+ inputs_embeds: Optional[torch.FloatTensor] = None,
969
+ labels: Optional[torch.LongTensor] = None,
970
+ use_cache: Optional[bool] = None,
971
+ output_attentions: Optional[bool] = None,
972
+ output_hidden_states: Optional[bool] = None,
973
+ return_dict: Optional[bool] = None,
974
+ cache_position: Optional[torch.LongTensor] = None,
975
+ num_logits_to_keep: int = 0,
976
+ **loss_kwargs,
977
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
978
+ r"""
979
+ Args:
980
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
981
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
982
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
983
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
984
+
985
+ num_logits_to_keep (`int`, *optional*):
986
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
987
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
988
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
989
+
990
+ Returns:
991
+ """
992
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
993
+ output_hidden_states = (
994
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
995
+ )
996
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
997
+
998
+ # decoder output consists of (dec_features, layer_state, dec_hidden, dec_attn)
999
+ outputs = self.model(
1000
+ input_ids=input_ids,
1001
+ attention_mask=attention_mask,
1002
+ position_ids=position_ids,
1003
+ past_key_values=past_key_values,
1004
+ inputs_embeds=inputs_embeds,
1005
+ use_cache=use_cache,
1006
+ output_attentions=output_attentions,
1007
+ output_hidden_states=output_hidden_states,
1008
+ return_dict=return_dict,
1009
+ cache_position=cache_position,
1010
+ )
1011
+
1012
+ hidden_states = outputs[0]
1013
+
1014
+ # only compute necessary logits, and do not upcast them to float if we are not computing the loss
1015
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1016
+
1017
+ loss = None
1018
+ if labels is not None:
1019
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.vocab_size, **loss_kwargs)
1020
+
1021
+ if not return_dict:
1022
+ output = (logits,) + outputs[1:]
1023
+ return (loss,) + output if loss is not None else output
1024
+
1025
+ return CausalLMOutputWithPast(
1026
+ loss=loss,
1027
+ logits=logits,
1028
+ past_key_values=outputs.past_key_values,
1029
+ hidden_states=outputs.hidden_states,
1030
+ attentions=outputs.attentions,
1031
+ )
1032
+
1033
+
1034
+ @add_start_docstrings(
1035
+ """
1036
+ The Doge Model transformer with a sequence classification head on top (linear layer).
1037
+
1038
+ [`DogeForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1039
+ (e.g. GPT-2) do.
1040
+
1041
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1042
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1043
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1044
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1045
+ each row of the batch).
1046
+ """
1047
+ )
1048
+ class DogeForSequenceClassification(DogePreTrainedModel):
1049
+ def __init__(self, config: DogeConfig):
1050
+ super().__init__(config)
1051
+ self.config = config
1052
+ self.num_labels = config.num_labels
1053
+
1054
+ self.model = DogeModel(config)
1055
+ self.classifier = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1056
+
1057
+ # Initialize weights and apply final processing
1058
+ self.init_weights()
1059
+
1060
+ def get_input_embeddings(self):
1061
+ return self.model.word_embed
1062
+
1063
+ def set_input_embeddings(self, value):
1064
+ self.model.word_embed = value
1065
+
1066
+ @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING)
1067
+ def forward(
1068
+ self,
1069
+ input_ids: Optional[torch.LongTensor] = None,
1070
+ attention_mask: Optional[torch.Tensor] = None,
1071
+ position_ids: Optional[torch.LongTensor] = None,
1072
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1073
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1074
+ labels: Optional[torch.LongTensor] = None,
1075
+ use_cache: Optional[bool] = None,
1076
+ output_attentions: Optional[bool] = None,
1077
+ output_hidden_states: Optional[bool] = None,
1078
+ return_dict: Optional[bool] = None,
1079
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1080
+ r"""
1081
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1082
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1083
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1084
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1085
+ """
1086
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1087
+
1088
+ outputs = self.model(
1089
+ input_ids=input_ids,
1090
+ attention_mask=attention_mask,
1091
+ position_ids=position_ids,
1092
+ past_key_values=past_key_values,
1093
+ inputs_embeds=inputs_embeds,
1094
+ use_cache=use_cache,
1095
+ output_attentions=output_attentions,
1096
+ output_hidden_states=output_hidden_states,
1097
+ return_dict=return_dict,
1098
+ )
1099
+ hidden_states = outputs[0]
1100
+ logits = self.classifier(hidden_states)
1101
+
1102
+ if input_ids is not None:
1103
+ batch_size = input_ids.shape[0]
1104
+ else:
1105
+ batch_size = inputs_embeds.shape[0]
1106
+
1107
+ if self.config.pad_token_id is None and batch_size != 1:
1108
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1109
+ if self.config.pad_token_id is None:
1110
+ sequence_lengths = -1
1111
+ else:
1112
+ if input_ids is not None:
1113
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1114
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1115
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1116
+ sequence_lengths = sequence_lengths.to(logits.device)
1117
+ else:
1118
+ sequence_lengths = -1
1119
+
1120
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1121
+
1122
+ loss = None
1123
+ if labels is not None:
1124
+ loss = self.loss_function(
1125
+ logits=logits,
1126
+ labels=labels,
1127
+ pooled_logits=pooled_logits,
1128
+ config=self.config,
1129
+ )
1130
+
1131
+ if not return_dict:
1132
+ output = (pooled_logits,) + outputs[1:]
1133
+ return ((loss,) + output) if loss is not None else output
1134
+
1135
+ return SequenceClassifierOutputWithPast(
1136
+ loss=loss,
1137
+ logits=pooled_logits,
1138
+ past_key_values=outputs.past_key_values,
1139
+ hidden_states=outputs.hidden_states,
1140
+ attentions=outputs.attentions,
1141
+ )