JingzeShi commited on
Commit
6dadfe9
verified
1 Parent(s): 12266e3

Upload DogeForCausalLM

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