JingzeShi commited on
Commit
940f76a
·
verified ·
1 Parent(s): 1444dc9

Upload DogeForCausalLM

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