JingzeShi commited on
Commit
424b1fd
verified
1 Parent(s): 98449eb

Upload DogeForCausalLM

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