JingzeShi commited on
Commit
6d75748
·
verified ·
1 Parent(s): bdeac71

Upload DogeForCausalLM

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