wubingheng commited on
Commit
cc8ba98
1 Parent(s): db7503c

Upload DogeForCausalLM

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