JingzeShi commited on
Commit
12b276d
·
verified ·
1 Parent(s): 385a41f

Upload DogeForCausalLM

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