JingzeShi commited on
Commit
5719a3d
·
verified ·
1 Parent(s): ed14b2a

Upload DogeForCausalLM

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