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