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