Upload 6 files
Browse files- configuration_deepseek.py +210 -0
- conversation.py +310 -0
- modeling_deepseek.py +1975 -0
- modeling_deepseek_vl_v2.py +697 -0
- processing_deepseek_vl_v2.py +675 -0
- siglip_vit.py +660 -0
configuration_deepseek.py
ADDED
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers.configuration_utils import PretrainedConfig
|
2 |
+
from transformers.utils import logging
|
3 |
+
|
4 |
+
logger = logging.get_logger(__name__)
|
5 |
+
|
6 |
+
DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
7 |
+
class DeepseekV2Config(PretrainedConfig):
|
8 |
+
r"""
|
9 |
+
This is the configuration class to store the configuration of a [`DeepseekV2Model`]. It is used to instantiate an DeepSeek
|
10 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
11 |
+
defaults will yield a similar configuration to that of the DeepSeek-V2 with multi-latent attention.
|
12 |
+
|
13 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
14 |
+
documentation from [`PretrainedConfig`] for more information.
|
15 |
+
|
16 |
+
|
17 |
+
Args:
|
18 |
+
vocab_size (`int`, *optional*, defaults to 102400):
|
19 |
+
Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
|
20 |
+
`inputs_ids` passed when calling [`DeepseekV2Model`]
|
21 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
22 |
+
Dimension of the hidden representations.
|
23 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
24 |
+
Dimension of the MLP representations.
|
25 |
+
moe_intermediate_size (`int`, *optional*, defaults to 1407):
|
26 |
+
Dimension of the MoE representations.
|
27 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
28 |
+
Number of hidden layers in the Transformer decoder.
|
29 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
30 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
31 |
+
n_shared_experts (`int`, *optional*, defaults to None):
|
32 |
+
Number of shared experts, None means dense model.
|
33 |
+
n_routed_experts (`int`, *optional*, defaults to None):
|
34 |
+
Number of routed experts, None means dense model.
|
35 |
+
routed_scaling_factor (`float`, *optional*, defaults to 1.0):
|
36 |
+
Scaling factor or routed experts.
|
37 |
+
topk_method (`str`, *optional*, defaults to `gready`):
|
38 |
+
Topk method used in routed gate.
|
39 |
+
n_group (`int`, *optional*, defaults to None):
|
40 |
+
Number of groups for routed experts.
|
41 |
+
topk_group (`int`, *optional*, defaults to None):
|
42 |
+
Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
|
43 |
+
num_experts_per_tok (`int`, *optional*, defaults to None):
|
44 |
+
Number of selected experts, None means dense model.
|
45 |
+
moe_layer_freq (`int`, *optional*, defaults to 1):
|
46 |
+
The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.
|
47 |
+
first_k_dense_replace (`int`, *optional*, defaults to 0):
|
48 |
+
Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
|
49 |
+
\--k dense layers--/
|
50 |
+
norm_topk_prob (`bool`, *optional*, defaults to False):
|
51 |
+
Whether to normalize the weights of the routed experts.
|
52 |
+
scoring_func (`str`, *optional*, defaults to 'softmax'):
|
53 |
+
Method of computing expert weights.
|
54 |
+
aux_loss_alpha (`float`, *optional*, defaults to 0.001):
|
55 |
+
Auxiliary loss weight coefficient.
|
56 |
+
seq_aux = (`bool`, *optional*, defaults to True):
|
57 |
+
Whether to compute the auxiliary loss for each individual sample.
|
58 |
+
num_key_value_heads (`int`, *optional*):
|
59 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
60 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
61 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
62 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
63 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
64 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
65 |
+
`num_attention_heads`.
|
66 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
67 |
+
The non-linear activation function (function or string) in the decoder.
|
68 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
69 |
+
The maximum sequence length that this model might ever be used with.
|
70 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
71 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
72 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
73 |
+
The epsilon used by the rms normalization layers.
|
74 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
75 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
76 |
+
relevant if `config.is_decoder=True`.
|
77 |
+
pad_token_id (`int`, *optional*):
|
78 |
+
Padding token id.
|
79 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
80 |
+
Beginning of stream token id.
|
81 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
82 |
+
End of stream token id.
|
83 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
84 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
85 |
+
document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
|
86 |
+
necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
|
87 |
+
issue](https://github.com/pytorch/pytorch/issues/76232).
|
88 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
89 |
+
Whether to tie weight embeddings
|
90 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
91 |
+
The base period of the RoPE embeddings.
|
92 |
+
rope_scaling (`Dict`, *optional*):
|
93 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
94 |
+
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
|
95 |
+
`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
96 |
+
`max_position_embeddings` to the expected new maximum.
|
97 |
+
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
98 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
99 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
100 |
+
The dropout ratio for the attention probabilities.
|
101 |
+
use_mla (`bool`, *optional*, defaults to `True`): Use multi-latent attention or multi-head attention. If True,
|
102 |
+
the model will use multi-latent attention, otherwise, it will use multi-head attention.
|
103 |
+
|
104 |
+
```python
|
105 |
+
>>> from transformers import DeepseekV2Model, DeepseekV2Config
|
106 |
+
|
107 |
+
>>> # Initializing a Deepseek-V2 style configuration
|
108 |
+
>>> configuration = DeepseekV2Config()
|
109 |
+
|
110 |
+
>>> # Accessing the model configuration
|
111 |
+
>>> configuration = model.config
|
112 |
+
```"""
|
113 |
+
|
114 |
+
model_type = "deepseek_v2"
|
115 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
116 |
+
|
117 |
+
def __init__(
|
118 |
+
self,
|
119 |
+
vocab_size=102400,
|
120 |
+
hidden_size=4096,
|
121 |
+
intermediate_size=11008,
|
122 |
+
moe_intermediate_size = 1407,
|
123 |
+
num_hidden_layers=30,
|
124 |
+
num_attention_heads=32,
|
125 |
+
num_key_value_heads=32,
|
126 |
+
n_shared_experts = None,
|
127 |
+
n_routed_experts = None,
|
128 |
+
ep_size = 1,
|
129 |
+
routed_scaling_factor = 1.0,
|
130 |
+
kv_lora_rank = 512,
|
131 |
+
q_lora_rank = 1536,
|
132 |
+
qk_rope_head_dim = 64,
|
133 |
+
v_head_dim = 128,
|
134 |
+
qk_nope_head_dim = 128,
|
135 |
+
topk_method = 'gready',
|
136 |
+
n_group = None,
|
137 |
+
topk_group = None,
|
138 |
+
num_experts_per_tok = None,
|
139 |
+
moe_layer_freq = 1,
|
140 |
+
first_k_dense_replace = 0,
|
141 |
+
norm_topk_prob = False,
|
142 |
+
scoring_func = 'softmax',
|
143 |
+
aux_loss_alpha = 0.001,
|
144 |
+
seq_aux = True,
|
145 |
+
hidden_act="silu",
|
146 |
+
max_position_embeddings=2048,
|
147 |
+
initializer_range=0.02,
|
148 |
+
rms_norm_eps=1e-6,
|
149 |
+
use_cache=True,
|
150 |
+
pad_token_id=None,
|
151 |
+
bos_token_id=100000,
|
152 |
+
eos_token_id=100001,
|
153 |
+
pretraining_tp=1,
|
154 |
+
tie_word_embeddings=False,
|
155 |
+
rope_theta=10000.0,
|
156 |
+
rope_scaling=None,
|
157 |
+
attention_bias=False,
|
158 |
+
attention_dropout=0.0,
|
159 |
+
use_mla=True,
|
160 |
+
**kwargs,
|
161 |
+
):
|
162 |
+
self.vocab_size = vocab_size
|
163 |
+
self.max_position_embeddings = max_position_embeddings
|
164 |
+
self.hidden_size = hidden_size
|
165 |
+
self.intermediate_size = intermediate_size
|
166 |
+
self.moe_intermediate_size = moe_intermediate_size
|
167 |
+
self.num_hidden_layers = num_hidden_layers
|
168 |
+
self.num_attention_heads = num_attention_heads
|
169 |
+
self.n_shared_experts = n_shared_experts
|
170 |
+
self.n_routed_experts = n_routed_experts
|
171 |
+
self.ep_size = ep_size
|
172 |
+
self.routed_scaling_factor = routed_scaling_factor
|
173 |
+
self.kv_lora_rank = kv_lora_rank
|
174 |
+
self.q_lora_rank = q_lora_rank
|
175 |
+
self.qk_rope_head_dim = qk_rope_head_dim
|
176 |
+
self.v_head_dim = v_head_dim
|
177 |
+
self.qk_nope_head_dim = qk_nope_head_dim
|
178 |
+
self.topk_method = topk_method
|
179 |
+
self.n_group = n_group
|
180 |
+
self.topk_group = topk_group
|
181 |
+
self.num_experts_per_tok = num_experts_per_tok
|
182 |
+
self.moe_layer_freq = moe_layer_freq
|
183 |
+
self.first_k_dense_replace = first_k_dense_replace
|
184 |
+
self.norm_topk_prob = norm_topk_prob
|
185 |
+
self.scoring_func = scoring_func
|
186 |
+
self.aux_loss_alpha = aux_loss_alpha
|
187 |
+
self.seq_aux = seq_aux
|
188 |
+
# for backward compatibility
|
189 |
+
if num_key_value_heads is None:
|
190 |
+
num_key_value_heads = num_attention_heads
|
191 |
+
|
192 |
+
self.num_key_value_heads = num_key_value_heads
|
193 |
+
self.hidden_act = hidden_act
|
194 |
+
self.initializer_range = initializer_range
|
195 |
+
self.rms_norm_eps = float(rms_norm_eps)
|
196 |
+
self.pretraining_tp = pretraining_tp
|
197 |
+
self.use_cache = use_cache
|
198 |
+
self.rope_theta = rope_theta
|
199 |
+
self.rope_scaling = rope_scaling
|
200 |
+
self.attention_bias = attention_bias
|
201 |
+
self.attention_dropout = attention_dropout
|
202 |
+
self.use_mla = use_mla
|
203 |
+
|
204 |
+
super().__init__(
|
205 |
+
pad_token_id=pad_token_id,
|
206 |
+
bos_token_id=bos_token_id,
|
207 |
+
eos_token_id=eos_token_id,
|
208 |
+
tie_word_embeddings=tie_word_embeddings,
|
209 |
+
**kwargs,
|
210 |
+
)
|
conversation.py
ADDED
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
From https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py
|
3 |
+
"""
|
4 |
+
|
5 |
+
import dataclasses
|
6 |
+
from enum import IntEnum, auto
|
7 |
+
from typing import Any, Dict, List
|
8 |
+
|
9 |
+
|
10 |
+
class SeparatorStyle(IntEnum):
|
11 |
+
"""Separator styles."""
|
12 |
+
|
13 |
+
DeepSeek = auto()
|
14 |
+
DeepSeekV2 = auto()
|
15 |
+
PLAIN = auto()
|
16 |
+
ALIGNMENT = auto()
|
17 |
+
|
18 |
+
|
19 |
+
@dataclasses.dataclass
|
20 |
+
class Conversation:
|
21 |
+
"""A class that manages prompt templates and keeps all conversation history."""
|
22 |
+
|
23 |
+
# The name of this template
|
24 |
+
name: str
|
25 |
+
# The template of the system prompt
|
26 |
+
system_template: str = "{system_message}"
|
27 |
+
# The system message
|
28 |
+
system_message: str = ""
|
29 |
+
# The names of two roles
|
30 |
+
roles: List[str] = (("USER", "ASSISTANT"),)
|
31 |
+
# All messages. Each item is (role, message).
|
32 |
+
messages: List[List[str]] = ()
|
33 |
+
# The number of few shot examples
|
34 |
+
offset: int = 0
|
35 |
+
# The separator style and configurations
|
36 |
+
sep_style: SeparatorStyle = SeparatorStyle.DeepSeek
|
37 |
+
sep: str = "\n"
|
38 |
+
sep2: str = None
|
39 |
+
# Stop criteria (the default one is EOS token)
|
40 |
+
stop_str: str = None
|
41 |
+
# Stops generation if meeting any token in this list
|
42 |
+
stop_token_ids: List[int] = None
|
43 |
+
|
44 |
+
def get_prompt(self) -> str:
|
45 |
+
"""Get the prompt for generation."""
|
46 |
+
system_prompt = self.system_template.format(system_message=self.system_message)
|
47 |
+
if self.sep_style == SeparatorStyle.DeepSeek:
|
48 |
+
seps = [self.sep, self.sep2]
|
49 |
+
if system_prompt == "" or system_prompt is None:
|
50 |
+
ret = ""
|
51 |
+
else:
|
52 |
+
ret = system_prompt + seps[0]
|
53 |
+
for i, (role, message) in enumerate(self.messages):
|
54 |
+
if message:
|
55 |
+
ret += role + ": " + message + seps[i % 2]
|
56 |
+
else:
|
57 |
+
ret += role + ":"
|
58 |
+
return ret
|
59 |
+
elif self.sep_style == SeparatorStyle.DeepSeekV2:
|
60 |
+
seps = [self.sep, self.sep2]
|
61 |
+
if system_prompt == "" or system_prompt is None:
|
62 |
+
ret = ""
|
63 |
+
else:
|
64 |
+
ret = system_prompt + seps[0]
|
65 |
+
for i, (role, message) in enumerate(self.messages):
|
66 |
+
if message:
|
67 |
+
if role == "User":
|
68 |
+
ret += "<|sft▁begin|>\n" + message + self.sep #<|sft▁begin|>User Input<|sft▁end|>\nResponse<|end▁of▁sentence|>
|
69 |
+
else:
|
70 |
+
ret += message + self.sep2
|
71 |
+
else:
|
72 |
+
ret = ret
|
73 |
+
return ret
|
74 |
+
|
75 |
+
elif self.sep_style == SeparatorStyle.PLAIN:
|
76 |
+
seps = [self.sep, self.sep2]
|
77 |
+
ret = ""
|
78 |
+
for i, (role, message) in enumerate(self.messages):
|
79 |
+
if message:
|
80 |
+
if type(message) is tuple:
|
81 |
+
message, _, _ = message
|
82 |
+
if i % 2 == 0:
|
83 |
+
ret += message + seps[i % 2]
|
84 |
+
else:
|
85 |
+
ret += message + seps[i % 2]
|
86 |
+
else:
|
87 |
+
ret += ""
|
88 |
+
return ret
|
89 |
+
elif self.sep_style == SeparatorStyle.ALIGNMENT:
|
90 |
+
seps = [self.sep, self.sep2]
|
91 |
+
ret = ""
|
92 |
+
for i, (role, message) in enumerate(self.messages):
|
93 |
+
if message:
|
94 |
+
if type(message) is tuple:
|
95 |
+
message, _, _ = message
|
96 |
+
if i % 2 == 0:
|
97 |
+
ret += '<image>\n' + seps[i % 2]
|
98 |
+
else:
|
99 |
+
ret += message + seps[i % 2]
|
100 |
+
else:
|
101 |
+
ret += ""
|
102 |
+
return ret
|
103 |
+
else:
|
104 |
+
raise ValueError(f"Invalid style: {self.sep_style}")
|
105 |
+
|
106 |
+
def set_system_message(self, system_message: str):
|
107 |
+
"""Set the system message."""
|
108 |
+
self.system_message = system_message
|
109 |
+
|
110 |
+
def append_message(self, role: str, message: str):
|
111 |
+
"""Append a new message."""
|
112 |
+
self.messages.append([role, message])
|
113 |
+
|
114 |
+
def update_last_message(self, message: str):
|
115 |
+
"""Update the last output.
|
116 |
+
|
117 |
+
The last message is typically set to be None when constructing the prompt,
|
118 |
+
so we need to update it in-place after getting the response from a model.
|
119 |
+
"""
|
120 |
+
self.messages[-1][1] = message
|
121 |
+
|
122 |
+
def reset_message(self):
|
123 |
+
"""Reset a new message."""
|
124 |
+
self.messages = []
|
125 |
+
|
126 |
+
def to_gradio_chatbot(self):
|
127 |
+
"""Convert the conversation to gradio chatbot format."""
|
128 |
+
ret = []
|
129 |
+
for i, (role, msg) in enumerate(self.messages[self.offset :]):
|
130 |
+
if i % 2 == 0:
|
131 |
+
ret.append([msg, None])
|
132 |
+
else:
|
133 |
+
ret[-1][-1] = msg
|
134 |
+
return ret
|
135 |
+
|
136 |
+
def to_openai_api_messages(self):
|
137 |
+
"""Convert the conversation to OpenAI chat completion format."""
|
138 |
+
system_prompt = self.system_template.format(system_message=self.system_message)
|
139 |
+
ret = [{"role": "system", "content": system_prompt}]
|
140 |
+
|
141 |
+
for i, (_, msg) in enumerate(self.messages[self.offset :]):
|
142 |
+
if i % 2 == 0:
|
143 |
+
ret.append({"role": "user", "content": msg})
|
144 |
+
else:
|
145 |
+
if msg is not None:
|
146 |
+
ret.append({"role": "assistant", "content": msg})
|
147 |
+
return ret
|
148 |
+
|
149 |
+
def copy(self):
|
150 |
+
return Conversation(
|
151 |
+
name=self.name,
|
152 |
+
system_template=self.system_template,
|
153 |
+
system_message=self.system_message,
|
154 |
+
roles=self.roles,
|
155 |
+
messages=[[x, y] for x, y in self.messages],
|
156 |
+
offset=self.offset,
|
157 |
+
sep_style=self.sep_style,
|
158 |
+
sep=self.sep,
|
159 |
+
sep2=self.sep2,
|
160 |
+
stop_str=self.stop_str,
|
161 |
+
stop_token_ids=self.stop_token_ids,
|
162 |
+
)
|
163 |
+
|
164 |
+
def dict(self):
|
165 |
+
return {
|
166 |
+
"template_name": self.name,
|
167 |
+
"system_message": self.system_message,
|
168 |
+
"roles": self.roles,
|
169 |
+
"messages": self.messages,
|
170 |
+
"offset": self.offset,
|
171 |
+
}
|
172 |
+
|
173 |
+
|
174 |
+
# A global registry for all conversation templates
|
175 |
+
conv_templates: Dict[str, Conversation] = {}
|
176 |
+
|
177 |
+
|
178 |
+
def register_conv_template(template: Conversation, override: bool = False):
|
179 |
+
"""Register a new conversation template."""
|
180 |
+
if not override:
|
181 |
+
assert template.name not in conv_templates, f"{template.name} has been registered."
|
182 |
+
|
183 |
+
conv_templates[template.name] = template
|
184 |
+
|
185 |
+
|
186 |
+
def get_conv_template(name: str) -> Conversation:
|
187 |
+
"""Get a conversation template."""
|
188 |
+
return conv_templates[name].copy()
|
189 |
+
|
190 |
+
|
191 |
+
# register_conv_template(
|
192 |
+
# Conversation(
|
193 |
+
# name="deepseek",
|
194 |
+
# system_template="{system_message}",
|
195 |
+
# # system_message="You are a helpful assistant. Please answer truthfully and write out your "
|
196 |
+
# # "thinking step by step to be sure you get the right answer.",
|
197 |
+
# system_message="",
|
198 |
+
# roles=("User", "Assistant"),
|
199 |
+
# messages=(),
|
200 |
+
# offset=0,
|
201 |
+
# sep_style=SeparatorStyle.DeepSeek,
|
202 |
+
# sep="\n\n",
|
203 |
+
# sep2="<|end▁of▁sentence|>",
|
204 |
+
# stop_token_ids=[100001],
|
205 |
+
# stop_str=["User:", "<|end▁of▁sentence|>"]
|
206 |
+
# )
|
207 |
+
# )
|
208 |
+
register_conv_template(
|
209 |
+
Conversation(
|
210 |
+
name="deepseek",
|
211 |
+
system_template="{system_message}",
|
212 |
+
# system_message="You are a helpful assistant. Please answer truthfully and write out your "
|
213 |
+
# "thinking step by step to be sure you get the right answer.",
|
214 |
+
system_message="",
|
215 |
+
roles=("<|User|>", "<|Assistant|>"),
|
216 |
+
messages=(),
|
217 |
+
offset=0,
|
218 |
+
sep_style=SeparatorStyle.DeepSeek,
|
219 |
+
sep="\n\n",
|
220 |
+
sep2="<|end▁of▁sentence|>",
|
221 |
+
stop_token_ids=[100001],
|
222 |
+
stop_str=["User:", "<|end▁of▁sentence|>"]
|
223 |
+
)
|
224 |
+
)
|
225 |
+
# register_conv_template(
|
226 |
+
# Conversation(
|
227 |
+
# name="deepseekv2",
|
228 |
+
# system_template="{system_message}",
|
229 |
+
# system_message="",
|
230 |
+
# roles=("User", "Assistant"),
|
231 |
+
# messages=(),
|
232 |
+
# offset=0,
|
233 |
+
# sep_style=SeparatorStyle.DeepSeekV2,
|
234 |
+
# sep="\n<|sft▁end|>",
|
235 |
+
# sep2="<|end▁of▁sentence|>",
|
236 |
+
# stop_token_ids=[100001],
|
237 |
+
# stop_str=["User:", "<|end▁of▁sentence|>"]
|
238 |
+
# )
|
239 |
+
# )
|
240 |
+
register_conv_template(
|
241 |
+
Conversation(
|
242 |
+
name="deepseekv2",
|
243 |
+
system_template="{system_message}",
|
244 |
+
system_message="",
|
245 |
+
roles=("|<User>|", "|<Assistant>|"),
|
246 |
+
messages=(),
|
247 |
+
offset=0,
|
248 |
+
sep_style=SeparatorStyle.DeepSeekV2,
|
249 |
+
sep="\n<|sft▁end|>",
|
250 |
+
sep2="<|end▁of▁sentence|>",
|
251 |
+
stop_token_ids=[100001],
|
252 |
+
stop_str=["User:", "<|end▁of▁sentence|>"]
|
253 |
+
)
|
254 |
+
)
|
255 |
+
|
256 |
+
|
257 |
+
register_conv_template(
|
258 |
+
Conversation(
|
259 |
+
name="plain",
|
260 |
+
system_template="",
|
261 |
+
system_message="",
|
262 |
+
roles=("", ""),
|
263 |
+
messages=(),
|
264 |
+
offset=0,
|
265 |
+
sep_style=SeparatorStyle.PLAIN,
|
266 |
+
sep="",
|
267 |
+
sep2="",
|
268 |
+
stop_token_ids=[100001],
|
269 |
+
stop_str=['</s>'],
|
270 |
+
)
|
271 |
+
)
|
272 |
+
|
273 |
+
|
274 |
+
register_conv_template(
|
275 |
+
Conversation(
|
276 |
+
name="alignment",
|
277 |
+
system_template="",
|
278 |
+
system_message="",
|
279 |
+
roles=("", ""),
|
280 |
+
messages=(),
|
281 |
+
offset=0,
|
282 |
+
sep_style=SeparatorStyle.ALIGNMENT,
|
283 |
+
sep="",
|
284 |
+
sep2="",
|
285 |
+
stop_token_ids=[100001],
|
286 |
+
stop_str=['</s>'],
|
287 |
+
)
|
288 |
+
)
|
289 |
+
|
290 |
+
|
291 |
+
if __name__ == "__main__":
|
292 |
+
print("deepseek template:")
|
293 |
+
conv = get_conv_template("deepseek")
|
294 |
+
conv.append_message(conv.roles[0], "Hello!")
|
295 |
+
conv.append_message(conv.roles[1], "Hi! This is Tony.")
|
296 |
+
conv.append_message(conv.roles[0], "Who are you?")
|
297 |
+
conv.append_message(conv.roles[1], "I am a helpful assistant.")
|
298 |
+
conv.append_message(conv.roles[0], "How are you?")
|
299 |
+
conv.append_message(conv.roles[1], None)
|
300 |
+
print(conv.get_prompt())
|
301 |
+
|
302 |
+
print("deepseekv2 template:")
|
303 |
+
conv = get_conv_template("deepseekv2")
|
304 |
+
conv.append_message(conv.roles[0], "Hello!")
|
305 |
+
conv.append_message(conv.roles[1], "Hi! This is Tony.")
|
306 |
+
conv.append_message(conv.roles[0], "Who are you?")
|
307 |
+
conv.append_message(conv.roles[1], "I am a helpful assistant.")
|
308 |
+
conv.append_message(conv.roles[0], "How are you?")
|
309 |
+
conv.append_message(conv.roles[1], None)
|
310 |
+
print(conv.get_prompt())
|
modeling_deepseek.py
ADDED
@@ -0,0 +1,1975 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ding=utf-8
|
2 |
+
# Copyright 2023 DeepSeek-AI and The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
""" PyTorch DeepSeek model and compatible with both DeepSeekV2 and DeepSeekV3"""
|
21 |
+
import math
|
22 |
+
import warnings
|
23 |
+
from typing import List, Optional, Tuple, Union
|
24 |
+
import numpy as np
|
25 |
+
|
26 |
+
import torch
|
27 |
+
import torch.nn.functional as F
|
28 |
+
import torch.utils.checkpoint
|
29 |
+
import torch.distributed as dist
|
30 |
+
from einops import repeat
|
31 |
+
from torch import nn
|
32 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
33 |
+
|
34 |
+
from transformers.activations import ACT2FN
|
35 |
+
from transformers.cache_utils import Cache, DynamicCache
|
36 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
|
37 |
+
from transformers.models.llama.modeling_llama import (
|
38 |
+
LlamaAttention,
|
39 |
+
LlamaFlashAttention2
|
40 |
+
)
|
41 |
+
from transformers.modeling_outputs import (
|
42 |
+
BaseModelOutputWithPast,
|
43 |
+
CausalLMOutputWithPast,
|
44 |
+
SequenceClassifierOutputWithPast,
|
45 |
+
)
|
46 |
+
from transformers.modeling_utils import PreTrainedModel
|
47 |
+
from transformers.pytorch_utils import (
|
48 |
+
ALL_LAYERNORM_LAYERS,
|
49 |
+
is_torch_greater_or_equal_than_1_13,
|
50 |
+
)
|
51 |
+
from transformers.utils import (
|
52 |
+
add_start_docstrings,
|
53 |
+
add_start_docstrings_to_model_forward,
|
54 |
+
is_flash_attn_2_available,
|
55 |
+
is_flash_attn_greater_or_equal_2_10,
|
56 |
+
logging,
|
57 |
+
replace_return_docstrings,
|
58 |
+
)
|
59 |
+
from transformers.utils.import_utils import is_torch_fx_available
|
60 |
+
|
61 |
+
from .configuration_deepseek import DeepseekV2Config
|
62 |
+
|
63 |
+
if is_flash_attn_2_available():
|
64 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
65 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
66 |
+
|
67 |
+
# This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
|
68 |
+
# It means that the function will not be traced through and simply appear as a node in the graph.
|
69 |
+
if is_torch_fx_available():
|
70 |
+
if not is_torch_greater_or_equal_than_1_13:
|
71 |
+
import torch.fx
|
72 |
+
|
73 |
+
_prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
|
74 |
+
|
75 |
+
logger = logging.get_logger(__name__)
|
76 |
+
|
77 |
+
_CONFIG_FOR_DOC = "DeepseekV2Config"
|
78 |
+
|
79 |
+
|
80 |
+
def _get_unpad_data(attention_mask):
|
81 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
82 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
83 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
84 |
+
cu_seqlens = F.pad(
|
85 |
+
torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
|
86 |
+
)
|
87 |
+
return (
|
88 |
+
indices,
|
89 |
+
cu_seqlens,
|
90 |
+
max_seqlen_in_batch,
|
91 |
+
)
|
92 |
+
|
93 |
+
|
94 |
+
class DeepseekV2RMSNorm(nn.Module):
|
95 |
+
def __init__(self, hidden_size, eps=1e-6):
|
96 |
+
"""
|
97 |
+
DeepseekV2RMSNorm is equivalent to T5LayerNorm
|
98 |
+
"""
|
99 |
+
super().__init__()
|
100 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
101 |
+
self.variance_epsilon = eps
|
102 |
+
|
103 |
+
def forward(self, hidden_states):
|
104 |
+
input_dtype = hidden_states.dtype
|
105 |
+
hidden_states = hidden_states.to(torch.float32)
|
106 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
107 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
108 |
+
return self.weight * hidden_states.to(input_dtype)
|
109 |
+
|
110 |
+
|
111 |
+
ALL_LAYERNORM_LAYERS.append(DeepseekV2RMSNorm)
|
112 |
+
|
113 |
+
|
114 |
+
class DeepseekV2RotaryEmbedding(nn.Module):
|
115 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
116 |
+
super().__init__()
|
117 |
+
|
118 |
+
self.dim = dim
|
119 |
+
self.max_position_embeddings = max_position_embeddings
|
120 |
+
self.base = base
|
121 |
+
inv_freq = 1.0 / (
|
122 |
+
self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
|
123 |
+
)
|
124 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
125 |
+
|
126 |
+
# Build here to make `torch.jit.trace` work.
|
127 |
+
self._set_cos_sin_cache(
|
128 |
+
seq_len=max_position_embeddings,
|
129 |
+
device=self.inv_freq.device,
|
130 |
+
dtype=torch.get_default_dtype(),
|
131 |
+
)
|
132 |
+
self.max_seq_len_cached = None
|
133 |
+
|
134 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
135 |
+
self.max_seq_len_cached = seq_len
|
136 |
+
t = torch.arange(
|
137 |
+
self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
|
138 |
+
)
|
139 |
+
|
140 |
+
freqs = torch.outer(t, self.inv_freq.to(t.device))
|
141 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
142 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
143 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
144 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
145 |
+
|
146 |
+
def forward(self, x, seq_len=None):
|
147 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
148 |
+
if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
|
149 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
150 |
+
|
151 |
+
return (
|
152 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
153 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
154 |
+
)
|
155 |
+
|
156 |
+
|
157 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV2
|
158 |
+
class DeepseekV2LinearScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
|
159 |
+
"""DeepseekV2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
160 |
+
|
161 |
+
def __init__(
|
162 |
+
self,
|
163 |
+
dim,
|
164 |
+
max_position_embeddings=2048,
|
165 |
+
base=10000,
|
166 |
+
device=None,
|
167 |
+
scaling_factor=1.0,
|
168 |
+
):
|
169 |
+
self.scaling_factor = scaling_factor
|
170 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
171 |
+
|
172 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
173 |
+
self.max_seq_len_cached = seq_len
|
174 |
+
t = torch.arange(
|
175 |
+
self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
|
176 |
+
)
|
177 |
+
t = t / self.scaling_factor
|
178 |
+
|
179 |
+
freqs = torch.outer(t, self.inv_freq)
|
180 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
181 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
182 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
183 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
184 |
+
|
185 |
+
|
186 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV2
|
187 |
+
class DeepseekV2DynamicNTKScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
|
188 |
+
"""DeepseekV2RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
189 |
+
|
190 |
+
def __init__(
|
191 |
+
self,
|
192 |
+
dim,
|
193 |
+
max_position_embeddings=2048,
|
194 |
+
base=10000,
|
195 |
+
device=None,
|
196 |
+
scaling_factor=1.0,
|
197 |
+
):
|
198 |
+
self.scaling_factor = scaling_factor
|
199 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
200 |
+
|
201 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
202 |
+
self.max_seq_len_cached = seq_len
|
203 |
+
|
204 |
+
if seq_len > self.max_position_embeddings:
|
205 |
+
base = self.base * (
|
206 |
+
(self.scaling_factor * seq_len / self.max_position_embeddings)
|
207 |
+
- (self.scaling_factor - 1)
|
208 |
+
) ** (self.dim / (self.dim - 2))
|
209 |
+
inv_freq = 1.0 / (
|
210 |
+
base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
|
211 |
+
)
|
212 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
213 |
+
|
214 |
+
t = torch.arange(
|
215 |
+
self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
|
216 |
+
)
|
217 |
+
|
218 |
+
freqs = torch.outer(t, self.inv_freq)
|
219 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
220 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
221 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
222 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
223 |
+
|
224 |
+
|
225 |
+
# Inverse dim formula to find dim based on number of rotations
|
226 |
+
def yarn_find_correction_dim(
|
227 |
+
num_rotations, dim, base=10000, max_position_embeddings=2048
|
228 |
+
):
|
229 |
+
return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
|
230 |
+
2 * math.log(base)
|
231 |
+
)
|
232 |
+
|
233 |
+
|
234 |
+
# Find dim range bounds based on rotations
|
235 |
+
def yarn_find_correction_range(
|
236 |
+
low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
|
237 |
+
):
|
238 |
+
low = math.floor(
|
239 |
+
yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
|
240 |
+
)
|
241 |
+
high = math.ceil(
|
242 |
+
yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
|
243 |
+
)
|
244 |
+
return max(low, 0), min(high, dim - 1) # Clamp values just in case
|
245 |
+
|
246 |
+
|
247 |
+
def yarn_get_mscale(scale=1, mscale=1):
|
248 |
+
if scale <= 1:
|
249 |
+
return 1.0
|
250 |
+
return 0.1 * mscale * math.log(scale) + 1.0
|
251 |
+
|
252 |
+
|
253 |
+
def yarn_linear_ramp_mask(min, max, dim):
|
254 |
+
if min == max:
|
255 |
+
max += 0.001 # Prevent singularity
|
256 |
+
|
257 |
+
linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
|
258 |
+
ramp_func = torch.clamp(linear_func, 0, 1)
|
259 |
+
return ramp_func
|
260 |
+
|
261 |
+
|
262 |
+
class DeepseekV2YarnRotaryEmbedding(DeepseekV2RotaryEmbedding):
|
263 |
+
|
264 |
+
def __init__(
|
265 |
+
self,
|
266 |
+
dim,
|
267 |
+
max_position_embeddings=2048,
|
268 |
+
base=10000,
|
269 |
+
device=None,
|
270 |
+
scaling_factor=1.0,
|
271 |
+
original_max_position_embeddings=4096,
|
272 |
+
beta_fast=32,
|
273 |
+
beta_slow=1,
|
274 |
+
mscale=1,
|
275 |
+
mscale_all_dim=0,
|
276 |
+
):
|
277 |
+
self.scaling_factor = scaling_factor
|
278 |
+
self.original_max_position_embeddings = original_max_position_embeddings
|
279 |
+
self.beta_fast = beta_fast
|
280 |
+
self.beta_slow = beta_slow
|
281 |
+
self.mscale = mscale
|
282 |
+
self.mscale_all_dim = mscale_all_dim
|
283 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
284 |
+
|
285 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
286 |
+
self.max_seq_len_cached = seq_len
|
287 |
+
dim = self.dim
|
288 |
+
|
289 |
+
freq_extra = 1.0 / (
|
290 |
+
self.base
|
291 |
+
** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
|
292 |
+
)
|
293 |
+
freq_inter = 1.0 / (
|
294 |
+
self.scaling_factor
|
295 |
+
* self.base
|
296 |
+
** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
|
297 |
+
)
|
298 |
+
|
299 |
+
low, high = yarn_find_correction_range(
|
300 |
+
self.beta_fast,
|
301 |
+
self.beta_slow,
|
302 |
+
dim,
|
303 |
+
self.base,
|
304 |
+
self.original_max_position_embeddings,
|
305 |
+
)
|
306 |
+
inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
|
307 |
+
device=device, dtype=torch.float32
|
308 |
+
)
|
309 |
+
inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
|
310 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
311 |
+
|
312 |
+
t = torch.arange(seq_len, device=device, dtype=torch.float32)
|
313 |
+
|
314 |
+
freqs = torch.outer(t, inv_freq)
|
315 |
+
|
316 |
+
_mscale = float(
|
317 |
+
yarn_get_mscale(self.scaling_factor, self.mscale)
|
318 |
+
/ yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
|
319 |
+
)
|
320 |
+
|
321 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
322 |
+
self.register_buffer(
|
323 |
+
"cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
|
324 |
+
)
|
325 |
+
self.register_buffer(
|
326 |
+
"sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
|
327 |
+
)
|
328 |
+
|
329 |
+
|
330 |
+
# Copied from transformers.models.llama.modeling_llama.rotate_half
|
331 |
+
def rotate_half(x):
|
332 |
+
"""Rotates half the hidden dims of the input."""
|
333 |
+
x1 = x[..., : x.shape[-1] // 2]
|
334 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
335 |
+
return torch.cat((-x2, x1), dim=-1)
|
336 |
+
|
337 |
+
|
338 |
+
# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
|
339 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
340 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
341 |
+
|
342 |
+
Args:
|
343 |
+
q (`torch.Tensor`): The query tensor.
|
344 |
+
k (`torch.Tensor`): The key tensor.
|
345 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
346 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
347 |
+
position_ids (`torch.Tensor`):
|
348 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
349 |
+
used to pass offsetted position ids when working with a KV-cache.
|
350 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
351 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
352 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
353 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
354 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
355 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
356 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
357 |
+
Returns:
|
358 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
359 |
+
"""
|
360 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
361 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
362 |
+
|
363 |
+
b, h, s, d = q.shape
|
364 |
+
q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
|
365 |
+
|
366 |
+
b, h, s, d = k.shape
|
367 |
+
k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
|
368 |
+
|
369 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
370 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
371 |
+
return q_embed, k_embed
|
372 |
+
|
373 |
+
|
374 |
+
class DeepseekV2MLP(nn.Module):
|
375 |
+
def __init__(self, config, hidden_size=None, intermediate_size=None):
|
376 |
+
super().__init__()
|
377 |
+
self.config = config
|
378 |
+
self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
|
379 |
+
self.intermediate_size = (
|
380 |
+
config.intermediate_size if intermediate_size is None else intermediate_size
|
381 |
+
)
|
382 |
+
|
383 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
384 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
385 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
386 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
387 |
+
|
388 |
+
def forward(self, x):
|
389 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
390 |
+
return down_proj
|
391 |
+
|
392 |
+
|
393 |
+
class MoEGate(nn.Module):
|
394 |
+
def __init__(self, config):
|
395 |
+
super().__init__()
|
396 |
+
self.config = config
|
397 |
+
self.top_k = config.num_experts_per_tok
|
398 |
+
self.n_routed_experts = config.n_routed_experts
|
399 |
+
self.routed_scaling_factor = config.routed_scaling_factor
|
400 |
+
self.scoring_func = config.scoring_func
|
401 |
+
self.alpha = config.aux_loss_alpha
|
402 |
+
self.seq_aux = config.seq_aux
|
403 |
+
self.topk_method = config.topk_method
|
404 |
+
self.n_group = config.n_group
|
405 |
+
self.topk_group = config.topk_group
|
406 |
+
|
407 |
+
# topk selection algorithm
|
408 |
+
self.norm_topk_prob = config.norm_topk_prob
|
409 |
+
self.gating_dim = config.hidden_size
|
410 |
+
self.weight = nn.Parameter(
|
411 |
+
torch.empty((self.n_routed_experts, self.gating_dim))
|
412 |
+
)
|
413 |
+
if self.topk_method == "noaux_tc":
|
414 |
+
self.e_score_correction_bias = nn.Parameter(
|
415 |
+
torch.empty((self.n_routed_experts))
|
416 |
+
)
|
417 |
+
self.reset_parameters()
|
418 |
+
|
419 |
+
def reset_parameters(self) -> None:
|
420 |
+
import torch.nn.init as init
|
421 |
+
|
422 |
+
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
|
423 |
+
|
424 |
+
def forward(self, hidden_states):
|
425 |
+
bsz, seq_len, h = hidden_states.shape
|
426 |
+
### compute gating score
|
427 |
+
hidden_states = hidden_states.view(-1, h)
|
428 |
+
logits = F.linear(
|
429 |
+
hidden_states.type(torch.float32), self.weight.type(torch.float32), None
|
430 |
+
)
|
431 |
+
if self.scoring_func == "softmax":
|
432 |
+
scores = logits.softmax(dim=-1, dtype=torch.float32)
|
433 |
+
elif self.scoring_func == "sigmoid":
|
434 |
+
scores = logits.sigmoid()
|
435 |
+
else:
|
436 |
+
raise NotImplementedError(
|
437 |
+
f"insupportable scoring function for MoE gating: {self.scoring_func}"
|
438 |
+
)
|
439 |
+
|
440 |
+
### select top-k experts
|
441 |
+
if self.topk_method == "greedy":
|
442 |
+
topk_weight, topk_idx = torch.topk(
|
443 |
+
scores, k=self.top_k, dim=-1, sorted=False
|
444 |
+
)
|
445 |
+
elif self.topk_method == "group_limited_greedy":
|
446 |
+
group_scores = (
|
447 |
+
scores.view(bsz * seq_len, self.n_group, -1).max(dim=-1).values
|
448 |
+
) # [n, n_group]
|
449 |
+
group_idx = torch.topk(
|
450 |
+
group_scores, k=self.topk_group, dim=-1, sorted=False
|
451 |
+
)[
|
452 |
+
1
|
453 |
+
] # [n, top_k_group]
|
454 |
+
group_mask = torch.zeros_like(group_scores) # [n, n_group]
|
455 |
+
group_mask.scatter_(1, group_idx, 1) # [n, n_group]
|
456 |
+
score_mask = (
|
457 |
+
group_mask.unsqueeze(-1)
|
458 |
+
.expand(
|
459 |
+
bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
|
460 |
+
)
|
461 |
+
.reshape(bsz * seq_len, -1)
|
462 |
+
) # [n, e]
|
463 |
+
tmp_scores = scores.masked_fill(~score_mask.bool(), 0.0) # [n, e]
|
464 |
+
topk_weight, topk_idx = torch.topk(
|
465 |
+
tmp_scores, k=self.top_k, dim=-1, sorted=False
|
466 |
+
)
|
467 |
+
elif self.topk_method == "noaux_tc":
|
468 |
+
assert not self.training
|
469 |
+
scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
|
470 |
+
group_scores = (
|
471 |
+
scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
|
472 |
+
) # [n, n_group]
|
473 |
+
group_idx = torch.topk(
|
474 |
+
group_scores, k=self.topk_group, dim=-1, sorted=False
|
475 |
+
)[
|
476 |
+
1
|
477 |
+
] # [n, top_k_group]
|
478 |
+
group_mask = torch.zeros_like(group_scores) # [n, n_group]
|
479 |
+
group_mask.scatter_(1, group_idx, 1) # [n, n_group]
|
480 |
+
score_mask = (
|
481 |
+
group_mask.unsqueeze(-1)
|
482 |
+
.expand(
|
483 |
+
bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
|
484 |
+
)
|
485 |
+
.reshape(bsz * seq_len, -1)
|
486 |
+
) # [n, e]
|
487 |
+
tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), 0.0) # [n, e]
|
488 |
+
_, topk_idx = torch.topk(
|
489 |
+
tmp_scores, k=self.top_k, dim=-1, sorted=False
|
490 |
+
)
|
491 |
+
topk_weight = scores.gather(1, topk_idx)
|
492 |
+
|
493 |
+
### norm gate to sum 1
|
494 |
+
if self.top_k > 1 and self.norm_topk_prob:
|
495 |
+
denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
|
496 |
+
topk_weight = topk_weight / denominator * self.routed_scaling_factor
|
497 |
+
else:
|
498 |
+
topk_weight = topk_weight * self.routed_scaling_factor
|
499 |
+
### expert-level computation auxiliary loss
|
500 |
+
if self.training and self.alpha > 0.0:
|
501 |
+
scores_for_aux = scores
|
502 |
+
aux_topk = self.top_k
|
503 |
+
# always compute aux loss based on the naive greedy topk method
|
504 |
+
topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
|
505 |
+
if self.seq_aux:
|
506 |
+
scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
|
507 |
+
ce = torch.zeros(
|
508 |
+
bsz, self.n_routed_experts, device=hidden_states.device
|
509 |
+
)
|
510 |
+
ce.scatter_add_(
|
511 |
+
1,
|
512 |
+
topk_idx_for_aux_loss,
|
513 |
+
torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device),
|
514 |
+
).div_(seq_len * aux_topk / self.n_routed_experts)
|
515 |
+
aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(
|
516 |
+
dim=1
|
517 |
+
).mean() * self.alpha
|
518 |
+
else:
|
519 |
+
mask_ce = F.one_hot(
|
520 |
+
topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts
|
521 |
+
)
|
522 |
+
ce = mask_ce.float().mean(0)
|
523 |
+
Pi = scores_for_aux.mean(0)
|
524 |
+
fi = ce * self.n_routed_experts
|
525 |
+
aux_loss = (Pi * fi).sum() * self.alpha
|
526 |
+
else:
|
527 |
+
aux_loss = None
|
528 |
+
return topk_idx, topk_weight, aux_loss
|
529 |
+
|
530 |
+
|
531 |
+
class AddAuxiliaryLoss(torch.autograd.Function):
|
532 |
+
"""
|
533 |
+
The trick function of adding auxiliary (aux) loss,
|
534 |
+
which includes the gradient of the aux loss during backpropagation.
|
535 |
+
"""
|
536 |
+
|
537 |
+
@staticmethod
|
538 |
+
def forward(ctx, x, loss):
|
539 |
+
assert loss.numel() == 1
|
540 |
+
ctx.dtype = loss.dtype
|
541 |
+
ctx.required_aux_loss = loss.requires_grad
|
542 |
+
return x
|
543 |
+
|
544 |
+
@staticmethod
|
545 |
+
def backward(ctx, grad_output):
|
546 |
+
grad_loss = None
|
547 |
+
if ctx.required_aux_loss:
|
548 |
+
grad_loss = torch.ones(1, dtype=ctx.dtype, device=grad_output.device)
|
549 |
+
return grad_output, grad_loss
|
550 |
+
|
551 |
+
|
552 |
+
class DeepseekV2MoE(nn.Module):
|
553 |
+
"""
|
554 |
+
A mixed expert module containing shared experts.
|
555 |
+
"""
|
556 |
+
|
557 |
+
def __init__(self, config):
|
558 |
+
super().__init__()
|
559 |
+
self.config = config
|
560 |
+
self.num_experts_per_tok = config.num_experts_per_tok
|
561 |
+
|
562 |
+
if hasattr(config, "ep_size") and config.ep_size > 1:
|
563 |
+
assert config.ep_size == dist.get_world_size()
|
564 |
+
self.ep_size = config.ep_size
|
565 |
+
self.experts_per_rank = config.n_routed_experts // config.ep_size
|
566 |
+
self.ep_rank = dist.get_rank()
|
567 |
+
self.experts = nn.ModuleList(
|
568 |
+
[
|
569 |
+
(
|
570 |
+
DeepseekV2MLP(
|
571 |
+
config, intermediate_size=config.moe_intermediate_size
|
572 |
+
)
|
573 |
+
if i >= self.ep_rank * self.experts_per_rank
|
574 |
+
and i < (self.ep_rank + 1) * self.experts_per_rank
|
575 |
+
else None
|
576 |
+
)
|
577 |
+
for i in range(config.n_routed_experts)
|
578 |
+
]
|
579 |
+
)
|
580 |
+
else:
|
581 |
+
self.ep_size = 1
|
582 |
+
self.experts_per_rank = config.n_routed_experts
|
583 |
+
self.ep_rank = 0
|
584 |
+
self.experts = nn.ModuleList(
|
585 |
+
[
|
586 |
+
DeepseekV2MLP(
|
587 |
+
config, intermediate_size=config.moe_intermediate_size
|
588 |
+
)
|
589 |
+
for i in range(config.n_routed_experts)
|
590 |
+
]
|
591 |
+
)
|
592 |
+
self.gate = MoEGate(config)
|
593 |
+
if config.n_shared_experts is not None:
|
594 |
+
intermediate_size = config.moe_intermediate_size * config.n_shared_experts
|
595 |
+
self.shared_experts = DeepseekV2MLP(
|
596 |
+
config=config, intermediate_size=intermediate_size
|
597 |
+
)
|
598 |
+
|
599 |
+
def forward(self, hidden_states):
|
600 |
+
identity = hidden_states
|
601 |
+
orig_shape = hidden_states.shape
|
602 |
+
topk_idx, topk_weight, aux_loss = self.gate(hidden_states)
|
603 |
+
hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
|
604 |
+
flat_topk_idx = topk_idx.view(-1)
|
605 |
+
if self.training:
|
606 |
+
hidden_states = hidden_states.repeat_interleave(
|
607 |
+
self.num_experts_per_tok, dim=0
|
608 |
+
)
|
609 |
+
y = torch.empty_like(hidden_states)
|
610 |
+
for i, expert in enumerate(self.experts):
|
611 |
+
y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
|
612 |
+
y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
|
613 |
+
y = y.to(hidden_states.dtype).view(*orig_shape)
|
614 |
+
y = AddAuxiliaryLoss.apply(y, aux_loss)
|
615 |
+
else:
|
616 |
+
y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
|
617 |
+
if self.config.n_shared_experts is not None:
|
618 |
+
y = y + self.shared_experts(identity)
|
619 |
+
return y
|
620 |
+
|
621 |
+
@torch.no_grad()
|
622 |
+
def moe_infer(self, x, topk_ids, topk_weight):
|
623 |
+
cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
|
624 |
+
cnts.scatter_(1, topk_ids, 1)
|
625 |
+
tokens_per_expert = cnts.sum(dim=0)
|
626 |
+
idxs = topk_ids.view(-1).argsort()
|
627 |
+
sorted_tokens = x[idxs // topk_ids.shape[1]]
|
628 |
+
sorted_tokens_shape = sorted_tokens.shape
|
629 |
+
if self.ep_size > 1:
|
630 |
+
tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
|
631 |
+
tokens_per_expert_group = tokens_per_expert.new_empty(
|
632 |
+
tokens_per_expert.shape[0]
|
633 |
+
)
|
634 |
+
dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
|
635 |
+
output_splits = (
|
636 |
+
tokens_per_expert_group.view(self.ep_size, -1)
|
637 |
+
.sum(1)
|
638 |
+
.cpu()
|
639 |
+
.numpy()
|
640 |
+
.tolist()
|
641 |
+
)
|
642 |
+
gathered_tokens = sorted_tokens.new_empty(
|
643 |
+
tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
|
644 |
+
)
|
645 |
+
input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
|
646 |
+
dist.all_to_all(
|
647 |
+
list(gathered_tokens.split(output_splits)),
|
648 |
+
list(sorted_tokens.split(input_split_sizes)),
|
649 |
+
)
|
650 |
+
tokens_per_expert_post_gather = tokens_per_expert_group.view(
|
651 |
+
self.ep_size, self.experts_per_rank
|
652 |
+
).sum(dim=0)
|
653 |
+
gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
|
654 |
+
s = 0
|
655 |
+
for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
|
656 |
+
gatherd_idxs[s : s + k] = i % self.experts_per_rank
|
657 |
+
s += k
|
658 |
+
gatherd_idxs = gatherd_idxs.argsort()
|
659 |
+
sorted_tokens = gathered_tokens[gatherd_idxs]
|
660 |
+
tokens_per_expert = tokens_per_expert_post_gather
|
661 |
+
tokens_per_expert = tokens_per_expert.cpu().numpy()
|
662 |
+
|
663 |
+
outputs = []
|
664 |
+
start_idx = 0
|
665 |
+
for i, num_tokens in enumerate(tokens_per_expert):
|
666 |
+
end_idx = start_idx + num_tokens
|
667 |
+
if num_tokens == 0:
|
668 |
+
continue
|
669 |
+
expert = self.experts[i + self.ep_rank * self.experts_per_rank]
|
670 |
+
tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
|
671 |
+
expert_out = expert(tokens_for_this_expert)
|
672 |
+
outputs.append(expert_out)
|
673 |
+
start_idx = end_idx
|
674 |
+
|
675 |
+
outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
|
676 |
+
if self.ep_size > 1:
|
677 |
+
new_x = torch.empty_like(outs)
|
678 |
+
new_x[gatherd_idxs] = outs
|
679 |
+
gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
|
680 |
+
dist.all_to_all(
|
681 |
+
list(gathered_tokens.split(input_split_sizes)),
|
682 |
+
list(new_x.split(output_splits)),
|
683 |
+
)
|
684 |
+
outs = gathered_tokens
|
685 |
+
|
686 |
+
new_x = torch.empty_like(outs)
|
687 |
+
new_x[idxs] = outs
|
688 |
+
final_out = (
|
689 |
+
new_x.view(*topk_ids.shape, -1)
|
690 |
+
.type(topk_weight.dtype)
|
691 |
+
.mul_(topk_weight.unsqueeze(dim=-1))
|
692 |
+
.sum(dim=1)
|
693 |
+
.type(new_x.dtype)
|
694 |
+
)
|
695 |
+
return final_out
|
696 |
+
|
697 |
+
|
698 |
+
# Copied from transformers.models.llama.modeling_llama.repeat_kv
|
699 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
700 |
+
"""
|
701 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
702 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
703 |
+
"""
|
704 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
705 |
+
if n_rep == 1:
|
706 |
+
return hidden_states
|
707 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(
|
708 |
+
batch, num_key_value_heads, n_rep, slen, head_dim
|
709 |
+
)
|
710 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
711 |
+
|
712 |
+
|
713 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV2
|
714 |
+
class DeepseekV2Attention(nn.Module):
|
715 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
716 |
+
|
717 |
+
def __init__(self, config: DeepseekV2Config, layer_idx: Optional[int] = None):
|
718 |
+
super().__init__()
|
719 |
+
self.config = config
|
720 |
+
self.layer_idx = layer_idx
|
721 |
+
if layer_idx is None:
|
722 |
+
logger.warning_once(
|
723 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
724 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
725 |
+
"when creating this class."
|
726 |
+
)
|
727 |
+
|
728 |
+
self.attention_dropout = config.attention_dropout
|
729 |
+
self.hidden_size = config.hidden_size
|
730 |
+
self.num_heads = config.num_attention_heads
|
731 |
+
|
732 |
+
self.max_position_embeddings = config.max_position_embeddings
|
733 |
+
self.rope_theta = config.rope_theta
|
734 |
+
self.q_lora_rank = config.q_lora_rank
|
735 |
+
self.qk_rope_head_dim = config.qk_rope_head_dim
|
736 |
+
self.kv_lora_rank = config.kv_lora_rank
|
737 |
+
self.v_head_dim = config.v_head_dim
|
738 |
+
self.qk_nope_head_dim = config.qk_nope_head_dim
|
739 |
+
self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
|
740 |
+
|
741 |
+
self.is_causal = True
|
742 |
+
|
743 |
+
if self.q_lora_rank is None:
|
744 |
+
self.q_proj = nn.Linear(
|
745 |
+
self.hidden_size, self.num_heads * self.q_head_dim, bias=False
|
746 |
+
)
|
747 |
+
else:
|
748 |
+
self.q_a_proj = nn.Linear(
|
749 |
+
self.hidden_size, config.q_lora_rank, bias=config.attention_bias
|
750 |
+
)
|
751 |
+
self.q_a_layernorm = DeepseekV2RMSNorm(config.q_lora_rank)
|
752 |
+
self.q_b_proj = nn.Linear(
|
753 |
+
config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
|
754 |
+
)
|
755 |
+
|
756 |
+
self.kv_a_proj_with_mqa = nn.Linear(
|
757 |
+
self.hidden_size,
|
758 |
+
config.kv_lora_rank + config.qk_rope_head_dim,
|
759 |
+
bias=config.attention_bias,
|
760 |
+
)
|
761 |
+
self.kv_a_layernorm = DeepseekV2RMSNorm(config.kv_lora_rank)
|
762 |
+
self.kv_b_proj = nn.Linear(
|
763 |
+
config.kv_lora_rank,
|
764 |
+
self.num_heads
|
765 |
+
* (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
|
766 |
+
bias=False,
|
767 |
+
)
|
768 |
+
|
769 |
+
self.o_proj = nn.Linear(
|
770 |
+
self.num_heads * self.v_head_dim,
|
771 |
+
self.hidden_size,
|
772 |
+
bias=config.attention_bias,
|
773 |
+
)
|
774 |
+
self._init_rope()
|
775 |
+
|
776 |
+
self.softmax_scale = self.q_head_dim ** (-0.5)
|
777 |
+
if self.config.rope_scaling is not None:
|
778 |
+
mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
|
779 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
780 |
+
if mscale_all_dim:
|
781 |
+
mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
|
782 |
+
self.softmax_scale = self.softmax_scale * mscale * mscale
|
783 |
+
|
784 |
+
def _init_rope(self):
|
785 |
+
if self.config.rope_scaling is None:
|
786 |
+
self.rotary_emb = DeepseekV2RotaryEmbedding(
|
787 |
+
self.qk_rope_head_dim,
|
788 |
+
max_position_embeddings=self.max_position_embeddings,
|
789 |
+
base=self.rope_theta,
|
790 |
+
)
|
791 |
+
else:
|
792 |
+
scaling_type = self.config.rope_scaling["type"]
|
793 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
794 |
+
if scaling_type == "linear":
|
795 |
+
self.rotary_emb = DeepseekV2LinearScalingRotaryEmbedding(
|
796 |
+
self.qk_rope_head_dim,
|
797 |
+
max_position_embeddings=self.max_position_embeddings,
|
798 |
+
scaling_factor=scaling_factor,
|
799 |
+
base=self.rope_theta,
|
800 |
+
)
|
801 |
+
elif scaling_type == "dynamic":
|
802 |
+
self.rotary_emb = DeepseekV2DynamicNTKScalingRotaryEmbedding(
|
803 |
+
self.qk_rope_head_dim,
|
804 |
+
max_position_embeddings=self.max_position_embeddings,
|
805 |
+
scaling_factor=scaling_factor,
|
806 |
+
base=self.rope_theta,
|
807 |
+
)
|
808 |
+
elif scaling_type == "yarn":
|
809 |
+
kwargs = {
|
810 |
+
key: self.config.rope_scaling[key]
|
811 |
+
for key in [
|
812 |
+
"original_max_position_embeddings",
|
813 |
+
"beta_fast",
|
814 |
+
"beta_slow",
|
815 |
+
"mscale",
|
816 |
+
"mscale_all_dim",
|
817 |
+
]
|
818 |
+
if key in self.config.rope_scaling
|
819 |
+
}
|
820 |
+
self.rotary_emb = DeepseekV2YarnRotaryEmbedding(
|
821 |
+
self.qk_rope_head_dim,
|
822 |
+
max_position_embeddings=self.max_position_embeddings,
|
823 |
+
scaling_factor=scaling_factor,
|
824 |
+
base=self.rope_theta,
|
825 |
+
**kwargs,
|
826 |
+
)
|
827 |
+
else:
|
828 |
+
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
829 |
+
|
830 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
831 |
+
return (
|
832 |
+
tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
|
833 |
+
.transpose(1, 2)
|
834 |
+
.contiguous()
|
835 |
+
)
|
836 |
+
|
837 |
+
def forward(
|
838 |
+
self,
|
839 |
+
hidden_states: torch.Tensor,
|
840 |
+
attention_mask: Optional[torch.Tensor] = None,
|
841 |
+
position_ids: Optional[torch.LongTensor] = None,
|
842 |
+
past_key_value: Optional[Cache] = None,
|
843 |
+
output_attentions: bool = False,
|
844 |
+
use_cache: bool = False,
|
845 |
+
**kwargs,
|
846 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
847 |
+
if "padding_mask" in kwargs:
|
848 |
+
warnings.warn(
|
849 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
850 |
+
)
|
851 |
+
bsz, q_len, _ = hidden_states.size()
|
852 |
+
|
853 |
+
if self.q_lora_rank is None:
|
854 |
+
q = self.q_proj(hidden_states)
|
855 |
+
else:
|
856 |
+
q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
|
857 |
+
q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
|
858 |
+
q_nope, q_pe = torch.split(
|
859 |
+
q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
|
860 |
+
)
|
861 |
+
|
862 |
+
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
|
863 |
+
compressed_kv, k_pe = torch.split(
|
864 |
+
compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
|
865 |
+
)
|
866 |
+
compressed_kv = self.kv_a_layernorm(compressed_kv)
|
867 |
+
k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
|
868 |
+
|
869 |
+
kv_seq_len = k_pe.shape[-2]
|
870 |
+
if past_key_value is not None:
|
871 |
+
if self.layer_idx is None:
|
872 |
+
raise ValueError(
|
873 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
874 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
875 |
+
"with a layer index."
|
876 |
+
)
|
877 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
878 |
+
|
879 |
+
cos, sin = self.rotary_emb(q_pe, seq_len=kv_seq_len)
|
880 |
+
q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
|
881 |
+
|
882 |
+
if past_key_value is not None:
|
883 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
884 |
+
compressed_kv = compressed_kv.unsqueeze(1)
|
885 |
+
k_pe, compressed_kv = past_key_value.update(k_pe, compressed_kv, self.layer_idx, cache_kwargs)
|
886 |
+
compressed_kv = compressed_kv.squeeze(1)
|
887 |
+
|
888 |
+
kv_b_proj = self.kv_b_proj.weight.view(self.num_heads, -1, self.kv_lora_rank)
|
889 |
+
q_absorb = kv_b_proj[:, :self.qk_nope_head_dim, :]
|
890 |
+
out_absorb = kv_b_proj[:, self.qk_nope_head_dim:, :]
|
891 |
+
|
892 |
+
q_nope = torch.matmul(q_nope, q_absorb)
|
893 |
+
attn_weights = (torch.matmul(q_pe, k_pe.mT) +
|
894 |
+
torch.matmul(q_nope, compressed_kv.unsqueeze(-3).mT)) * self.softmax_scale
|
895 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
896 |
+
raise ValueError(
|
897 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
898 |
+
f" {attn_weights.size()}"
|
899 |
+
)
|
900 |
+
assert attention_mask is not None
|
901 |
+
if attention_mask is not None:
|
902 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
903 |
+
raise ValueError(
|
904 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
905 |
+
)
|
906 |
+
attn_weights = attn_weights + attention_mask
|
907 |
+
|
908 |
+
# upcast attention to fp32
|
909 |
+
attn_weights = nn.functional.softmax(
|
910 |
+
attn_weights, dim=-1, dtype=torch.float32
|
911 |
+
).to(q_pe.dtype)
|
912 |
+
attn_weights = nn.functional.dropout(
|
913 |
+
attn_weights, p=self.attention_dropout, training=self.training
|
914 |
+
)
|
915 |
+
attn_output = torch.einsum('bhql,blc->bhqc', attn_weights, compressed_kv)
|
916 |
+
|
917 |
+
attn_output = torch.matmul(attn_output, out_absorb.mT)
|
918 |
+
|
919 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
|
920 |
+
raise ValueError(
|
921 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
|
922 |
+
f" {attn_output.size()}"
|
923 |
+
)
|
924 |
+
|
925 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
926 |
+
|
927 |
+
attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
|
928 |
+
|
929 |
+
attn_output = self.o_proj(attn_output)
|
930 |
+
|
931 |
+
if not output_attentions:
|
932 |
+
attn_weights = None
|
933 |
+
|
934 |
+
return attn_output, attn_weights, past_key_value
|
935 |
+
|
936 |
+
|
937 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV2
|
938 |
+
class DeepseekV2FlashAttention2(DeepseekV2Attention):
|
939 |
+
"""
|
940 |
+
DeepseekV2 flash attention module. This module inherits from `DeepseekV2Attention` as the weights of the module stays
|
941 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
942 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
943 |
+
"""
|
944 |
+
|
945 |
+
def __init__(self, *args, **kwargs):
|
946 |
+
super().__init__(*args, **kwargs)
|
947 |
+
|
948 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
949 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
|
950 |
+
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
|
951 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
952 |
+
|
953 |
+
def forward(
|
954 |
+
self,
|
955 |
+
hidden_states: torch.Tensor,
|
956 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
957 |
+
position_ids: Optional[torch.LongTensor] = None,
|
958 |
+
past_key_value: Optional[Cache] = None,
|
959 |
+
output_attentions: bool = False,
|
960 |
+
use_cache: bool = False,
|
961 |
+
**kwargs,
|
962 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
963 |
+
# DeepseekV2FlashAttention2 attention does not support output_attentions
|
964 |
+
if "padding_mask" in kwargs:
|
965 |
+
warnings.warn(
|
966 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
967 |
+
)
|
968 |
+
|
969 |
+
# overwrite attention_mask with padding_mask
|
970 |
+
attention_mask = kwargs.pop("padding_mask")
|
971 |
+
|
972 |
+
output_attentions = False
|
973 |
+
|
974 |
+
bsz, q_len, _ = hidden_states.size()
|
975 |
+
|
976 |
+
if self.q_lora_rank is None:
|
977 |
+
q = self.q_proj(hidden_states)
|
978 |
+
else:
|
979 |
+
q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
|
980 |
+
q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
|
981 |
+
q_nope, q_pe = torch.split(
|
982 |
+
q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
|
983 |
+
)
|
984 |
+
|
985 |
+
# Flash attention requires the input to have the shape
|
986 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
987 |
+
# therefore we just need to keep the original shape
|
988 |
+
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
|
989 |
+
compressed_kv, k_pe = torch.split(
|
990 |
+
compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
|
991 |
+
)
|
992 |
+
k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
|
993 |
+
kv = (
|
994 |
+
self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
|
995 |
+
.view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
|
996 |
+
.transpose(1, 2)
|
997 |
+
)
|
998 |
+
|
999 |
+
k_nope, value_states = torch.split(
|
1000 |
+
kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
|
1001 |
+
)
|
1002 |
+
kv_seq_len = value_states.shape[-2]
|
1003 |
+
|
1004 |
+
kv_seq_len = value_states.shape[-2]
|
1005 |
+
if past_key_value is not None:
|
1006 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
1007 |
+
|
1008 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
1009 |
+
q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
|
1010 |
+
|
1011 |
+
query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
|
1012 |
+
query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
|
1013 |
+
query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
|
1014 |
+
|
1015 |
+
key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
|
1016 |
+
key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
|
1017 |
+
key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
|
1018 |
+
|
1019 |
+
if self.q_head_dim != self.v_head_dim:
|
1020 |
+
value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
|
1021 |
+
|
1022 |
+
# TODO: support compressed_kv for kv_cache (instead of key_states, value_states) in flash_attention version
|
1023 |
+
if past_key_value is not None:
|
1024 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
1025 |
+
key_states, value_states = past_key_value.update(
|
1026 |
+
key_states, value_states, self.layer_idx, cache_kwargs
|
1027 |
+
)
|
1028 |
+
|
1029 |
+
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
|
1030 |
+
# to be able to avoid many of these transpose/reshape/view.
|
1031 |
+
query_states = query_states.transpose(1, 2)
|
1032 |
+
key_states = key_states.transpose(1, 2)
|
1033 |
+
value_states = value_states.transpose(1, 2)
|
1034 |
+
|
1035 |
+
dropout_rate = self.attention_dropout if self.training else 0.0
|
1036 |
+
|
1037 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
1038 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
1039 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
1040 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
1041 |
+
# in fp32. (DeepseekV2RMSNorm handles it correctly)
|
1042 |
+
|
1043 |
+
input_dtype = query_states.dtype
|
1044 |
+
if input_dtype == torch.float32:
|
1045 |
+
# Handle the case where the model is quantized
|
1046 |
+
if hasattr(self.config, "_pre_quantization_dtype"):
|
1047 |
+
target_dtype = self.config._pre_quantization_dtype
|
1048 |
+
elif torch.is_autocast_enabled():
|
1049 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
1050 |
+
else:
|
1051 |
+
target_dtype = (
|
1052 |
+
self.q_proj.weight.dtype
|
1053 |
+
if self.q_lora_rank is None
|
1054 |
+
else self.q_a_proj.weight.dtype
|
1055 |
+
)
|
1056 |
+
|
1057 |
+
logger.warning_once(
|
1058 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
1059 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
1060 |
+
f" {target_dtype}."
|
1061 |
+
)
|
1062 |
+
|
1063 |
+
query_states = query_states.to(target_dtype)
|
1064 |
+
key_states = key_states.to(target_dtype)
|
1065 |
+
value_states = value_states.to(target_dtype)
|
1066 |
+
|
1067 |
+
attn_output = self._flash_attention_forward(
|
1068 |
+
query_states,
|
1069 |
+
key_states,
|
1070 |
+
value_states,
|
1071 |
+
attention_mask,
|
1072 |
+
q_len,
|
1073 |
+
dropout=dropout_rate,
|
1074 |
+
softmax_scale=self.softmax_scale,
|
1075 |
+
)
|
1076 |
+
if self.q_head_dim != self.v_head_dim:
|
1077 |
+
attn_output = attn_output[:, :, :, : self.v_head_dim]
|
1078 |
+
|
1079 |
+
attn_output = attn_output.reshape(
|
1080 |
+
bsz, q_len, self.num_heads * self.v_head_dim
|
1081 |
+
).contiguous()
|
1082 |
+
attn_output = self.o_proj(attn_output)
|
1083 |
+
|
1084 |
+
if not output_attentions:
|
1085 |
+
attn_weights = None
|
1086 |
+
|
1087 |
+
return attn_output, attn_weights, past_key_value
|
1088 |
+
|
1089 |
+
def _flash_attention_forward(
|
1090 |
+
self,
|
1091 |
+
query_states,
|
1092 |
+
key_states,
|
1093 |
+
value_states,
|
1094 |
+
attention_mask,
|
1095 |
+
query_length,
|
1096 |
+
dropout=0.0,
|
1097 |
+
softmax_scale=None,
|
1098 |
+
):
|
1099 |
+
"""
|
1100 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
1101 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
1102 |
+
|
1103 |
+
Args:
|
1104 |
+
query_states (`torch.Tensor`):
|
1105 |
+
Input query states to be passed to Flash Attention API
|
1106 |
+
key_states (`torch.Tensor`):
|
1107 |
+
Input key states to be passed to Flash Attention API
|
1108 |
+
value_states (`torch.Tensor`):
|
1109 |
+
Input value states to be passed to Flash Attention API
|
1110 |
+
attention_mask (`torch.Tensor`):
|
1111 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
1112 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
1113 |
+
dropout (`int`, *optional*):
|
1114 |
+
Attention dropout
|
1115 |
+
softmax_scale (`float`, *optional*):
|
1116 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
1117 |
+
"""
|
1118 |
+
if not self._flash_attn_uses_top_left_mask:
|
1119 |
+
causal = self.is_causal
|
1120 |
+
else:
|
1121 |
+
# TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in DeepseekV2FlashAttention2 __init__.
|
1122 |
+
causal = self.is_causal and query_length != 1
|
1123 |
+
|
1124 |
+
# Contains at least one padding token in the sequence
|
1125 |
+
if attention_mask is not None:
|
1126 |
+
batch_size = query_states.shape[0]
|
1127 |
+
(
|
1128 |
+
query_states,
|
1129 |
+
key_states,
|
1130 |
+
value_states,
|
1131 |
+
indices_q,
|
1132 |
+
cu_seq_lens,
|
1133 |
+
max_seq_lens,
|
1134 |
+
) = self._upad_input(
|
1135 |
+
query_states, key_states, value_states, attention_mask, query_length
|
1136 |
+
)
|
1137 |
+
|
1138 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
1139 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
1140 |
+
|
1141 |
+
attn_output_unpad = flash_attn_varlen_func(
|
1142 |
+
query_states,
|
1143 |
+
key_states,
|
1144 |
+
value_states,
|
1145 |
+
cu_seqlens_q=cu_seqlens_q,
|
1146 |
+
cu_seqlens_k=cu_seqlens_k,
|
1147 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
1148 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
1149 |
+
dropout_p=dropout,
|
1150 |
+
softmax_scale=softmax_scale,
|
1151 |
+
causal=causal,
|
1152 |
+
)
|
1153 |
+
|
1154 |
+
attn_output = pad_input(
|
1155 |
+
attn_output_unpad, indices_q, batch_size, query_length
|
1156 |
+
)
|
1157 |
+
else:
|
1158 |
+
attn_output = flash_attn_func(
|
1159 |
+
query_states,
|
1160 |
+
key_states,
|
1161 |
+
value_states,
|
1162 |
+
dropout,
|
1163 |
+
softmax_scale=softmax_scale,
|
1164 |
+
causal=causal,
|
1165 |
+
)
|
1166 |
+
|
1167 |
+
return attn_output
|
1168 |
+
|
1169 |
+
def _upad_input(
|
1170 |
+
self, query_layer, key_layer, value_layer, attention_mask, query_length
|
1171 |
+
):
|
1172 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
1173 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
1174 |
+
|
1175 |
+
key_layer = index_first_axis(
|
1176 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
|
1177 |
+
indices_k,
|
1178 |
+
)
|
1179 |
+
value_layer = index_first_axis(
|
1180 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
|
1181 |
+
indices_k,
|
1182 |
+
)
|
1183 |
+
if query_length == kv_seq_len:
|
1184 |
+
query_layer = index_first_axis(
|
1185 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
|
1186 |
+
indices_k,
|
1187 |
+
)
|
1188 |
+
cu_seqlens_q = cu_seqlens_k
|
1189 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
1190 |
+
indices_q = indices_k
|
1191 |
+
elif query_length == 1:
|
1192 |
+
max_seqlen_in_batch_q = 1
|
1193 |
+
cu_seqlens_q = torch.arange(
|
1194 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
1195 |
+
) # There is a memcpy here, that is very bad.
|
1196 |
+
indices_q = cu_seqlens_q[:-1]
|
1197 |
+
query_layer = query_layer.squeeze(1)
|
1198 |
+
else:
|
1199 |
+
# The -q_len: slice assumes left padding.
|
1200 |
+
attention_mask = attention_mask[:, -query_length:]
|
1201 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
|
1202 |
+
query_layer, attention_mask
|
1203 |
+
)
|
1204 |
+
|
1205 |
+
return (
|
1206 |
+
query_layer,
|
1207 |
+
key_layer,
|
1208 |
+
value_layer,
|
1209 |
+
indices_q,
|
1210 |
+
(cu_seqlens_q, cu_seqlens_k),
|
1211 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
1212 |
+
)
|
1213 |
+
|
1214 |
+
|
1215 |
+
ATTENTION_CLASSES = {
|
1216 |
+
"eager": DeepseekV2Attention,
|
1217 |
+
"flash_attention_2": DeepseekV2FlashAttention2,
|
1218 |
+
|
1219 |
+
"mla_eager": DeepseekV2Attention,
|
1220 |
+
"mla_flash_attention_2": DeepseekV2FlashAttention2,
|
1221 |
+
|
1222 |
+
"mha_eager": LlamaAttention,
|
1223 |
+
"mha_flash_attention_2": LlamaFlashAttention2
|
1224 |
+
}
|
1225 |
+
|
1226 |
+
|
1227 |
+
class DeepseekV2DecoderLayer(nn.Module):
|
1228 |
+
def __init__(self, config: DeepseekV2Config, layer_idx: int):
|
1229 |
+
super().__init__()
|
1230 |
+
self.hidden_size = config.hidden_size
|
1231 |
+
|
1232 |
+
if config.use_mla:
|
1233 |
+
attn_implementation = "mla_" + config._attn_implementation
|
1234 |
+
else:
|
1235 |
+
attn_implementation = "mha_" + config._attn_implementation
|
1236 |
+
|
1237 |
+
self.self_attn = ATTENTION_CLASSES[attn_implementation](
|
1238 |
+
config=config, layer_idx=layer_idx
|
1239 |
+
)
|
1240 |
+
|
1241 |
+
self.mlp = (
|
1242 |
+
DeepseekV2MoE(config)
|
1243 |
+
if (
|
1244 |
+
config.n_routed_experts is not None
|
1245 |
+
and layer_idx >= config.first_k_dense_replace
|
1246 |
+
and layer_idx % config.moe_layer_freq == 0
|
1247 |
+
)
|
1248 |
+
else DeepseekV2MLP(config)
|
1249 |
+
)
|
1250 |
+
self.input_layernorm = DeepseekV2RMSNorm(
|
1251 |
+
config.hidden_size, eps=config.rms_norm_eps
|
1252 |
+
)
|
1253 |
+
self.post_attention_layernorm = DeepseekV2RMSNorm(
|
1254 |
+
config.hidden_size, eps=config.rms_norm_eps
|
1255 |
+
)
|
1256 |
+
|
1257 |
+
def forward(
|
1258 |
+
self,
|
1259 |
+
hidden_states: torch.Tensor,
|
1260 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1261 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1262 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
1263 |
+
output_attentions: Optional[bool] = False,
|
1264 |
+
use_cache: Optional[bool] = False,
|
1265 |
+
**kwargs,
|
1266 |
+
) -> Tuple[
|
1267 |
+
torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
|
1268 |
+
]:
|
1269 |
+
"""
|
1270 |
+
Args:
|
1271 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
1272 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
1273 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
1274 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
1275 |
+
output_attentions (`bool`, *optional*):
|
1276 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
1277 |
+
returned tensors for more detail.
|
1278 |
+
use_cache (`bool`, *optional*):
|
1279 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
1280 |
+
(see `past_key_values`).
|
1281 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
1282 |
+
"""
|
1283 |
+
if "padding_mask" in kwargs:
|
1284 |
+
warnings.warn(
|
1285 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
1286 |
+
)
|
1287 |
+
residual = hidden_states
|
1288 |
+
|
1289 |
+
hidden_states = self.input_layernorm(hidden_states)
|
1290 |
+
|
1291 |
+
# Self Attention
|
1292 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
1293 |
+
hidden_states=hidden_states,
|
1294 |
+
attention_mask=attention_mask,
|
1295 |
+
position_ids=position_ids,
|
1296 |
+
past_key_value=past_key_value,
|
1297 |
+
output_attentions=output_attentions,
|
1298 |
+
use_cache=use_cache,
|
1299 |
+
**kwargs,
|
1300 |
+
)
|
1301 |
+
hidden_states = residual + hidden_states
|
1302 |
+
|
1303 |
+
# Fully Connected
|
1304 |
+
residual = hidden_states
|
1305 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
1306 |
+
hidden_states = self.mlp(hidden_states)
|
1307 |
+
hidden_states = residual + hidden_states
|
1308 |
+
|
1309 |
+
outputs = (hidden_states,)
|
1310 |
+
|
1311 |
+
if output_attentions:
|
1312 |
+
outputs += (self_attn_weights,)
|
1313 |
+
|
1314 |
+
if use_cache:
|
1315 |
+
outputs += (present_key_value,)
|
1316 |
+
|
1317 |
+
return outputs
|
1318 |
+
|
1319 |
+
|
1320 |
+
DeepseekV2_START_DOCSTRING = r"""
|
1321 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
1322 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
1323 |
+
etc.)
|
1324 |
+
|
1325 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
1326 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
1327 |
+
and behavior.
|
1328 |
+
|
1329 |
+
Parameters:
|
1330 |
+
config ([`DeepseekV2Config`]):
|
1331 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
1332 |
+
load the weights associated with the model, only the configuration. Check out the
|
1333 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
1334 |
+
"""
|
1335 |
+
|
1336 |
+
|
1337 |
+
@add_start_docstrings(
|
1338 |
+
"The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
|
1339 |
+
DeepseekV2_START_DOCSTRING,
|
1340 |
+
)
|
1341 |
+
class DeepseekV2PreTrainedModel(PreTrainedModel):
|
1342 |
+
config_class = DeepseekV2Config
|
1343 |
+
base_model_prefix = "model"
|
1344 |
+
supports_gradient_checkpointing = True
|
1345 |
+
_no_split_modules = ["DeepseekV2DecoderLayer"]
|
1346 |
+
_skip_keys_device_placement = "past_key_values"
|
1347 |
+
_supports_flash_attn_2 = True
|
1348 |
+
_supports_cache_class = True
|
1349 |
+
|
1350 |
+
def _init_weights(self, module):
|
1351 |
+
std = self.config.initializer_range
|
1352 |
+
if isinstance(module, nn.Linear):
|
1353 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
1354 |
+
if module.bias is not None:
|
1355 |
+
module.bias.data.zero_()
|
1356 |
+
elif isinstance(module, nn.Embedding):
|
1357 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
1358 |
+
if module.padding_idx is not None:
|
1359 |
+
module.weight.data[module.padding_idx].zero_()
|
1360 |
+
|
1361 |
+
|
1362 |
+
DeepseekV2_INPUTS_DOCSTRING = r"""
|
1363 |
+
Args:
|
1364 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
1365 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
1366 |
+
it.
|
1367 |
+
|
1368 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
1369 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
1370 |
+
|
1371 |
+
[What are input IDs?](../glossary#input-ids)
|
1372 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1373 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
1374 |
+
|
1375 |
+
- 1 for tokens that are **not masked**,
|
1376 |
+
- 0 for tokens that are **masked**.
|
1377 |
+
|
1378 |
+
[What are attention masks?](../glossary#attention-mask)
|
1379 |
+
|
1380 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
1381 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
1382 |
+
|
1383 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
1384 |
+
`past_key_values`).
|
1385 |
+
|
1386 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
1387 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
1388 |
+
information on the default strategy.
|
1389 |
+
|
1390 |
+
- 1 indicates the head is **not masked**,
|
1391 |
+
- 0 indicates the head is **masked**.
|
1392 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1393 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
1394 |
+
config.n_positions - 1]`.
|
1395 |
+
|
1396 |
+
[What are position IDs?](../glossary#position-ids)
|
1397 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
1398 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
1399 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
1400 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
1401 |
+
|
1402 |
+
Two formats are allowed:
|
1403 |
+
- a [`~cache_utils.Cache`] instance;
|
1404 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
1405 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
1406 |
+
cache format.
|
1407 |
+
|
1408 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
1409 |
+
legacy cache format will be returned.
|
1410 |
+
|
1411 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
1412 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
1413 |
+
of shape `(batch_size, sequence_length)`.
|
1414 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
1415 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
1416 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
1417 |
+
model's internal embedding lookup matrix.
|
1418 |
+
use_cache (`bool`, *optional*):
|
1419 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
1420 |
+
`past_key_values`).
|
1421 |
+
output_attentions (`bool`, *optional*):
|
1422 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
1423 |
+
tensors for more detail.
|
1424 |
+
output_hidden_states (`bool`, *optional*):
|
1425 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
1426 |
+
more detail.
|
1427 |
+
return_dict (`bool`, *optional*):
|
1428 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
1429 |
+
"""
|
1430 |
+
|
1431 |
+
|
1432 |
+
@add_start_docstrings(
|
1433 |
+
"The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
|
1434 |
+
DeepseekV2_START_DOCSTRING,
|
1435 |
+
)
|
1436 |
+
class DeepseekV2Model(DeepseekV2PreTrainedModel):
|
1437 |
+
"""
|
1438 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV2DecoderLayer`]
|
1439 |
+
|
1440 |
+
Args:
|
1441 |
+
config: DeepseekV2Config
|
1442 |
+
"""
|
1443 |
+
|
1444 |
+
def __init__(self, config: DeepseekV2Config):
|
1445 |
+
super().__init__(config)
|
1446 |
+
self.padding_idx = config.pad_token_id
|
1447 |
+
self.vocab_size = config.vocab_size
|
1448 |
+
|
1449 |
+
self.embed_tokens = nn.Embedding(
|
1450 |
+
config.vocab_size, config.hidden_size, self.padding_idx
|
1451 |
+
)
|
1452 |
+
self.layers = nn.ModuleList(
|
1453 |
+
[
|
1454 |
+
DeepseekV2DecoderLayer(config, layer_idx)
|
1455 |
+
for layer_idx in range(config.num_hidden_layers)
|
1456 |
+
]
|
1457 |
+
)
|
1458 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
1459 |
+
self.norm = DeepseekV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
1460 |
+
|
1461 |
+
self.gradient_checkpointing = False
|
1462 |
+
# Initialize weights and apply final processing
|
1463 |
+
self.post_init()
|
1464 |
+
|
1465 |
+
def get_input_embeddings(self):
|
1466 |
+
return self.embed_tokens
|
1467 |
+
|
1468 |
+
def set_input_embeddings(self, value):
|
1469 |
+
self.embed_tokens = value
|
1470 |
+
|
1471 |
+
@add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
|
1472 |
+
def forward(
|
1473 |
+
self,
|
1474 |
+
input_ids: torch.LongTensor = None,
|
1475 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1476 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1477 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1478 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1479 |
+
use_cache: Optional[bool] = None,
|
1480 |
+
output_attentions: Optional[bool] = None,
|
1481 |
+
output_hidden_states: Optional[bool] = None,
|
1482 |
+
return_dict: Optional[bool] = None,
|
1483 |
+
cache_position: Optional[torch.LongTensor] = None
|
1484 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
1485 |
+
output_attentions = (
|
1486 |
+
output_attentions
|
1487 |
+
if output_attentions is not None
|
1488 |
+
else self.config.output_attentions
|
1489 |
+
)
|
1490 |
+
output_hidden_states = (
|
1491 |
+
output_hidden_states
|
1492 |
+
if output_hidden_states is not None
|
1493 |
+
else self.config.output_hidden_states
|
1494 |
+
)
|
1495 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1496 |
+
|
1497 |
+
return_dict = (
|
1498 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1499 |
+
)
|
1500 |
+
|
1501 |
+
# retrieve input_ids and inputs_embeds
|
1502 |
+
if input_ids is not None and inputs_embeds is not None:
|
1503 |
+
raise ValueError(
|
1504 |
+
"You cannot specify both input_ids and inputs_embeds at the same time"
|
1505 |
+
)
|
1506 |
+
elif input_ids is not None:
|
1507 |
+
batch_size, seq_length = input_ids.shape[:2]
|
1508 |
+
elif inputs_embeds is not None:
|
1509 |
+
batch_size, seq_length = inputs_embeds.shape[:2]
|
1510 |
+
else:
|
1511 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
1512 |
+
|
1513 |
+
if self.gradient_checkpointing and self.training:
|
1514 |
+
if use_cache:
|
1515 |
+
logger.warning_once(
|
1516 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
|
1517 |
+
)
|
1518 |
+
use_cache = False
|
1519 |
+
|
1520 |
+
past_key_values_length = 0
|
1521 |
+
if use_cache:
|
1522 |
+
use_legacy_cache = not isinstance(past_key_values, Cache)
|
1523 |
+
if use_legacy_cache:
|
1524 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
1525 |
+
past_key_values_length = past_key_values.get_usable_length(seq_length)
|
1526 |
+
|
1527 |
+
if position_ids is None:
|
1528 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
1529 |
+
position_ids = torch.arange(
|
1530 |
+
past_key_values_length,
|
1531 |
+
seq_length + past_key_values_length,
|
1532 |
+
dtype=torch.long,
|
1533 |
+
device=device,
|
1534 |
+
)
|
1535 |
+
position_ids = position_ids.unsqueeze(0)
|
1536 |
+
|
1537 |
+
if inputs_embeds is None:
|
1538 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
1539 |
+
|
1540 |
+
if self._use_flash_attention_2:
|
1541 |
+
# 2d mask is passed through the layers
|
1542 |
+
attention_mask = (
|
1543 |
+
attention_mask
|
1544 |
+
if (attention_mask is not None and 0 in attention_mask)
|
1545 |
+
else None
|
1546 |
+
)
|
1547 |
+
else:
|
1548 |
+
# 4d mask is passed through the layers
|
1549 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
1550 |
+
attention_mask,
|
1551 |
+
(batch_size, seq_length),
|
1552 |
+
inputs_embeds,
|
1553 |
+
past_key_values_length,
|
1554 |
+
)
|
1555 |
+
|
1556 |
+
# embed positions
|
1557 |
+
hidden_states = inputs_embeds
|
1558 |
+
|
1559 |
+
# decoder layers
|
1560 |
+
all_hidden_states = () if output_hidden_states else None
|
1561 |
+
all_self_attns = () if output_attentions else None
|
1562 |
+
next_decoder_cache = None
|
1563 |
+
|
1564 |
+
for decoder_layer in self.layers:
|
1565 |
+
if output_hidden_states:
|
1566 |
+
all_hidden_states += (hidden_states,)
|
1567 |
+
|
1568 |
+
if self.gradient_checkpointing and self.training:
|
1569 |
+
layer_outputs = self._gradient_checkpointing_func(
|
1570 |
+
decoder_layer.__call__,
|
1571 |
+
hidden_states,
|
1572 |
+
attention_mask,
|
1573 |
+
position_ids,
|
1574 |
+
past_key_values,
|
1575 |
+
output_attentions,
|
1576 |
+
use_cache,
|
1577 |
+
)
|
1578 |
+
else:
|
1579 |
+
layer_outputs = decoder_layer(
|
1580 |
+
hidden_states,
|
1581 |
+
attention_mask=attention_mask,
|
1582 |
+
position_ids=position_ids,
|
1583 |
+
past_key_value=past_key_values,
|
1584 |
+
output_attentions=output_attentions,
|
1585 |
+
use_cache=use_cache,
|
1586 |
+
)
|
1587 |
+
|
1588 |
+
hidden_states = layer_outputs[0]
|
1589 |
+
|
1590 |
+
if use_cache:
|
1591 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
1592 |
+
|
1593 |
+
if output_attentions:
|
1594 |
+
all_self_attns += (layer_outputs[1],)
|
1595 |
+
|
1596 |
+
hidden_states = self.norm(hidden_states)
|
1597 |
+
|
1598 |
+
# add hidden states from the last decoder layer
|
1599 |
+
if output_hidden_states:
|
1600 |
+
all_hidden_states += (hidden_states,)
|
1601 |
+
|
1602 |
+
next_cache = None
|
1603 |
+
if use_cache:
|
1604 |
+
next_cache = (
|
1605 |
+
next_decoder_cache.to_legacy_cache()
|
1606 |
+
if use_legacy_cache
|
1607 |
+
else next_decoder_cache
|
1608 |
+
)
|
1609 |
+
if not return_dict:
|
1610 |
+
return tuple(
|
1611 |
+
v
|
1612 |
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
|
1613 |
+
if v is not None
|
1614 |
+
)
|
1615 |
+
return BaseModelOutputWithPast(
|
1616 |
+
last_hidden_state=hidden_states,
|
1617 |
+
past_key_values=next_cache,
|
1618 |
+
hidden_states=all_hidden_states,
|
1619 |
+
attentions=all_self_attns,
|
1620 |
+
)
|
1621 |
+
|
1622 |
+
|
1623 |
+
class DeepseekV2ForCausalLM(DeepseekV2PreTrainedModel):
|
1624 |
+
_tied_weights_keys = ["lm_head.weight"]
|
1625 |
+
|
1626 |
+
def __init__(self, config):
|
1627 |
+
super().__init__(config)
|
1628 |
+
self.model = DeepseekV2Model(config)
|
1629 |
+
self.vocab_size = config.vocab_size
|
1630 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
1631 |
+
|
1632 |
+
# Initialize weights and apply final processing
|
1633 |
+
self.post_init()
|
1634 |
+
|
1635 |
+
def get_input_embeddings(self):
|
1636 |
+
return self.model.embed_tokens
|
1637 |
+
|
1638 |
+
def set_input_embeddings(self, value):
|
1639 |
+
self.model.embed_tokens = value
|
1640 |
+
|
1641 |
+
def get_output_embeddings(self):
|
1642 |
+
return self.lm_head
|
1643 |
+
|
1644 |
+
def set_output_embeddings(self, new_embeddings):
|
1645 |
+
self.lm_head = new_embeddings
|
1646 |
+
|
1647 |
+
def set_decoder(self, decoder):
|
1648 |
+
self.model = decoder
|
1649 |
+
|
1650 |
+
def get_decoder(self):
|
1651 |
+
return self.model
|
1652 |
+
|
1653 |
+
@add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
|
1654 |
+
@replace_return_docstrings(
|
1655 |
+
output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
|
1656 |
+
)
|
1657 |
+
def forward(
|
1658 |
+
self,
|
1659 |
+
input_ids: torch.LongTensor = None,
|
1660 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1661 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1662 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1663 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1664 |
+
labels: Optional[torch.LongTensor] = None,
|
1665 |
+
use_cache: Optional[bool] = None,
|
1666 |
+
output_attentions: Optional[bool] = None,
|
1667 |
+
output_hidden_states: Optional[bool] = None,
|
1668 |
+
return_dict: Optional[bool] = None,
|
1669 |
+
cache_position: Optional[torch.LongTensor] = None
|
1670 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1671 |
+
r"""
|
1672 |
+
Args:
|
1673 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1674 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
|
1675 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1676 |
+
(masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
|
1677 |
+
|
1678 |
+
Returns:
|
1679 |
+
|
1680 |
+
Example:
|
1681 |
+
|
1682 |
+
```python
|
1683 |
+
>>> from transformers import AutoTokenizer, DeepseekV2ForCausalLM
|
1684 |
+
|
1685 |
+
>>> model = DeepseekV2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
1686 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
1687 |
+
|
1688 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
1689 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1690 |
+
|
1691 |
+
>>> # Generate
|
1692 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1693 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1694 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
1695 |
+
```"""
|
1696 |
+
output_attentions = (
|
1697 |
+
output_attentions
|
1698 |
+
if output_attentions is not None
|
1699 |
+
else self.config.output_attentions
|
1700 |
+
)
|
1701 |
+
output_hidden_states = (
|
1702 |
+
output_hidden_states
|
1703 |
+
if output_hidden_states is not None
|
1704 |
+
else self.config.output_hidden_states
|
1705 |
+
)
|
1706 |
+
return_dict = (
|
1707 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1708 |
+
)
|
1709 |
+
|
1710 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1711 |
+
outputs = self.model(
|
1712 |
+
input_ids=input_ids,
|
1713 |
+
attention_mask=attention_mask,
|
1714 |
+
position_ids=position_ids,
|
1715 |
+
past_key_values=past_key_values,
|
1716 |
+
inputs_embeds=inputs_embeds,
|
1717 |
+
use_cache=use_cache,
|
1718 |
+
output_attentions=output_attentions,
|
1719 |
+
output_hidden_states=output_hidden_states,
|
1720 |
+
return_dict=return_dict,
|
1721 |
+
cache_position=cache_position
|
1722 |
+
)
|
1723 |
+
|
1724 |
+
hidden_states = outputs[0]
|
1725 |
+
logits = self.lm_head(hidden_states)
|
1726 |
+
logits = logits.float()
|
1727 |
+
|
1728 |
+
loss = None
|
1729 |
+
if labels is not None:
|
1730 |
+
# Shift so that tokens < n predict n
|
1731 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1732 |
+
shift_labels = labels[..., 1:].contiguous()
|
1733 |
+
# Flatten the tokens
|
1734 |
+
loss_fct = CrossEntropyLoss()
|
1735 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1736 |
+
shift_labels = shift_labels.view(-1)
|
1737 |
+
# Enable model parallelism
|
1738 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1739 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1740 |
+
|
1741 |
+
if not return_dict:
|
1742 |
+
output = (logits,) + outputs[1:]
|
1743 |
+
return (loss,) + output if loss is not None else output
|
1744 |
+
|
1745 |
+
return CausalLMOutputWithPast(
|
1746 |
+
loss=loss,
|
1747 |
+
logits=logits,
|
1748 |
+
past_key_values=outputs.past_key_values,
|
1749 |
+
hidden_states=outputs.hidden_states,
|
1750 |
+
attentions=outputs.attentions,
|
1751 |
+
)
|
1752 |
+
|
1753 |
+
def prepare_inputs_for_generation(
|
1754 |
+
self,
|
1755 |
+
input_ids,
|
1756 |
+
past_key_values=None,
|
1757 |
+
attention_mask=None,
|
1758 |
+
inputs_embeds=None,
|
1759 |
+
**kwargs,
|
1760 |
+
):
|
1761 |
+
past_length = 0
|
1762 |
+
if past_key_values is not None:
|
1763 |
+
if isinstance(past_key_values, Cache):
|
1764 |
+
cache_length = past_key_values.get_seq_length()
|
1765 |
+
past_length = past_key_values.seen_tokens
|
1766 |
+
max_cache_length = past_key_values.get_max_length()
|
1767 |
+
else:
|
1768 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
1769 |
+
max_cache_length = None
|
1770 |
+
|
1771 |
+
# Keep only the unprocessed tokens:
|
1772 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
1773 |
+
# some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
|
1774 |
+
# input)
|
1775 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
1776 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
|
1777 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
1778 |
+
# input_ids based on the past_length.
|
1779 |
+
elif past_length < input_ids.shape[1]:
|
1780 |
+
input_ids = input_ids[:, past_length:]
|
1781 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
1782 |
+
|
1783 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
1784 |
+
if (
|
1785 |
+
max_cache_length is not None
|
1786 |
+
and attention_mask is not None
|
1787 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
1788 |
+
):
|
1789 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
1790 |
+
|
1791 |
+
position_ids = kwargs.get("position_ids", None)
|
1792 |
+
if attention_mask is not None and position_ids is None:
|
1793 |
+
# create position_ids on the fly for batch generation
|
1794 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1795 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1796 |
+
if past_key_values:
|
1797 |
+
position_ids = position_ids[:, -input_ids.shape[1]:]
|
1798 |
+
|
1799 |
+
if self.generation_config.cache_implementation == "static":
|
1800 |
+
# generation with static cache
|
1801 |
+
cache_position = kwargs.get("cache_position", None)
|
1802 |
+
if cache_position is None:
|
1803 |
+
past_length = 0
|
1804 |
+
else:
|
1805 |
+
past_length = cache_position[-1] + 1
|
1806 |
+
input_ids = input_ids[:, past_length:]
|
1807 |
+
position_ids = position_ids[:, past_length:]
|
1808 |
+
|
1809 |
+
# TODO @gante we should only keep a `cache_position` in generate, and do +=1.
|
1810 |
+
# same goes for position ids. Could also help with continued generation.
|
1811 |
+
cache_position = torch.arange(past_length, past_length + position_ids.shape[-1], device=position_ids.device)
|
1812 |
+
|
1813 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1814 |
+
if inputs_embeds is not None and past_key_values is None:
|
1815 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1816 |
+
else:
|
1817 |
+
# The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
|
1818 |
+
# recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
|
1819 |
+
# TODO: use `next_tokens` directly instead.
|
1820 |
+
model_inputs = {"input_ids": input_ids.contiguous()}
|
1821 |
+
|
1822 |
+
model_inputs.update(
|
1823 |
+
{
|
1824 |
+
"position_ids": position_ids.contiguous(),
|
1825 |
+
"cache_position": cache_position,
|
1826 |
+
"past_key_values": past_key_values,
|
1827 |
+
"use_cache": kwargs.get("use_cache"),
|
1828 |
+
"attention_mask": attention_mask,
|
1829 |
+
}
|
1830 |
+
)
|
1831 |
+
return model_inputs
|
1832 |
+
|
1833 |
+
@staticmethod
|
1834 |
+
def _reorder_cache(past_key_values, beam_idx):
|
1835 |
+
reordered_past = ()
|
1836 |
+
for layer_past in past_key_values:
|
1837 |
+
reordered_past += (
|
1838 |
+
tuple(
|
1839 |
+
past_state.index_select(0, beam_idx.to(past_state.device))
|
1840 |
+
for past_state in layer_past
|
1841 |
+
),
|
1842 |
+
)
|
1843 |
+
return reordered_past
|
1844 |
+
|
1845 |
+
|
1846 |
+
@add_start_docstrings(
|
1847 |
+
"""
|
1848 |
+
The DeepseekV2 Model transformer with a sequence classification head on top (linear layer).
|
1849 |
+
|
1850 |
+
[`DeepseekV2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
1851 |
+
(e.g. GPT-2) do.
|
1852 |
+
|
1853 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
1854 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
1855 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
1856 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
1857 |
+
each row of the batch).
|
1858 |
+
""",
|
1859 |
+
DeepseekV2_START_DOCSTRING,
|
1860 |
+
)
|
1861 |
+
class DeepseekV2ForSequenceClassification(DeepseekV2PreTrainedModel):
|
1862 |
+
def __init__(self, config):
|
1863 |
+
super().__init__(config)
|
1864 |
+
self.num_labels = config.num_labels
|
1865 |
+
self.model = DeepseekV2Model(config)
|
1866 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
1867 |
+
|
1868 |
+
# Initialize weights and apply final processing
|
1869 |
+
self.post_init()
|
1870 |
+
|
1871 |
+
def get_input_embeddings(self):
|
1872 |
+
return self.model.embed_tokens
|
1873 |
+
|
1874 |
+
def set_input_embeddings(self, value):
|
1875 |
+
self.model.embed_tokens = value
|
1876 |
+
|
1877 |
+
@add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
|
1878 |
+
def forward(
|
1879 |
+
self,
|
1880 |
+
input_ids: torch.LongTensor = None,
|
1881 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1882 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1883 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1884 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1885 |
+
labels: Optional[torch.LongTensor] = None,
|
1886 |
+
use_cache: Optional[bool] = None,
|
1887 |
+
output_attentions: Optional[bool] = None,
|
1888 |
+
output_hidden_states: Optional[bool] = None,
|
1889 |
+
return_dict: Optional[bool] = None,
|
1890 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
1891 |
+
r"""
|
1892 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1893 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
|
1894 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1895 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1896 |
+
"""
|
1897 |
+
return_dict = (
|
1898 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1899 |
+
)
|
1900 |
+
|
1901 |
+
transformer_outputs = self.model(
|
1902 |
+
input_ids,
|
1903 |
+
attention_mask=attention_mask,
|
1904 |
+
position_ids=position_ids,
|
1905 |
+
past_key_values=past_key_values,
|
1906 |
+
inputs_embeds=inputs_embeds,
|
1907 |
+
use_cache=use_cache,
|
1908 |
+
output_attentions=output_attentions,
|
1909 |
+
output_hidden_states=output_hidden_states,
|
1910 |
+
return_dict=return_dict,
|
1911 |
+
)
|
1912 |
+
hidden_states = transformer_outputs[0]
|
1913 |
+
logits = self.score(hidden_states)
|
1914 |
+
|
1915 |
+
if input_ids is not None:
|
1916 |
+
batch_size = input_ids.shape[0]
|
1917 |
+
else:
|
1918 |
+
batch_size = inputs_embeds.shape[0]
|
1919 |
+
|
1920 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
1921 |
+
raise ValueError(
|
1922 |
+
"Cannot handle batch sizes > 1 if no padding token is defined."
|
1923 |
+
)
|
1924 |
+
if self.config.pad_token_id is None:
|
1925 |
+
sequence_lengths = -1
|
1926 |
+
else:
|
1927 |
+
if input_ids is not None:
|
1928 |
+
sequence_lengths = (
|
1929 |
+
torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
1930 |
+
).to(logits.device)
|
1931 |
+
else:
|
1932 |
+
sequence_lengths = -1
|
1933 |
+
|
1934 |
+
pooled_logits = logits[
|
1935 |
+
torch.arange(batch_size, device=logits.device), sequence_lengths
|
1936 |
+
]
|
1937 |
+
|
1938 |
+
loss = None
|
1939 |
+
if labels is not None:
|
1940 |
+
labels = labels.to(logits.device)
|
1941 |
+
if self.config.problem_type is None:
|
1942 |
+
if self.num_labels == 1:
|
1943 |
+
self.config.problem_type = "regression"
|
1944 |
+
elif self.num_labels > 1 and (
|
1945 |
+
labels.dtype == torch.long or labels.dtype == torch.int
|
1946 |
+
):
|
1947 |
+
self.config.problem_type = "single_label_classification"
|
1948 |
+
else:
|
1949 |
+
self.config.problem_type = "multi_label_classification"
|
1950 |
+
|
1951 |
+
if self.config.problem_type == "regression":
|
1952 |
+
loss_fct = MSELoss()
|
1953 |
+
if self.num_labels == 1:
|
1954 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
1955 |
+
else:
|
1956 |
+
loss = loss_fct(pooled_logits, labels)
|
1957 |
+
elif self.config.problem_type == "single_label_classification":
|
1958 |
+
loss_fct = CrossEntropyLoss()
|
1959 |
+
loss = loss_fct(
|
1960 |
+
pooled_logits.view(-1, self.num_labels), labels.view(-1)
|
1961 |
+
)
|
1962 |
+
elif self.config.problem_type == "multi_label_classification":
|
1963 |
+
loss_fct = BCEWithLogitsLoss()
|
1964 |
+
loss = loss_fct(pooled_logits, labels)
|
1965 |
+
if not return_dict:
|
1966 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1967 |
+
return ((loss,) + output) if loss is not None else output
|
1968 |
+
|
1969 |
+
return SequenceClassifierOutputWithPast(
|
1970 |
+
loss=loss,
|
1971 |
+
logits=pooled_logits,
|
1972 |
+
past_key_values=transformer_outputs.past_key_values,
|
1973 |
+
hidden_states=transformer_outputs.hidden_states,
|
1974 |
+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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from attrdict import AttrDict
|
2 |
+
from dataclasses import dataclass
|
3 |
+
import logging
|
4 |
+
import gc
|
5 |
+
|
6 |
+
from einops import rearrange, repeat
|
7 |
+
from typing import Optional, List, Tuple, Callable, Union
|
8 |
+
|
9 |
+
import torch
|
10 |
+
import torch.nn as nn
|
11 |
+
import torch.nn.functional as F
|
12 |
+
|
13 |
+
from transformers.utils import (
|
14 |
+
add_start_docstrings,
|
15 |
+
add_start_docstrings_to_model_forward,
|
16 |
+
)
|
17 |
+
from transformers.modeling_outputs import ModelOutput
|
18 |
+
from transformers.configuration_utils import PretrainedConfig
|
19 |
+
from transformers import (
|
20 |
+
AutoConfig,
|
21 |
+
AutoModelForCausalLM,
|
22 |
+
PreTrainedModel
|
23 |
+
)
|
24 |
+
from transformers.utils import logging
|
25 |
+
|
26 |
+
from .siglip_vit import VisionTransformer
|
27 |
+
from .configuration_deepseek import DeepseekV2Config
|
28 |
+
from .modeling_deepseek import DeepseekV2ForCausalLM
|
29 |
+
|
30 |
+
|
31 |
+
logger = logging.get_logger(__name__)
|
32 |
+
|
33 |
+
|
34 |
+
class MlpProjector(nn.Module):
|
35 |
+
|
36 |
+
def __init__(self, cfg):
|
37 |
+
|
38 |
+
super().__init__()
|
39 |
+
|
40 |
+
self.cfg = cfg
|
41 |
+
|
42 |
+
if cfg.projector_type == "identity":
|
43 |
+
modules = nn.Identity()
|
44 |
+
|
45 |
+
elif cfg.projector_type == "linear":
|
46 |
+
modules = nn.Linear(cfg.input_dim, cfg.n_embed)
|
47 |
+
|
48 |
+
elif cfg.projector_type == "mlp_gelu":
|
49 |
+
mlp_depth = cfg.depth
|
50 |
+
modules = [nn.Linear(cfg.input_dim, cfg.n_embed)]
|
51 |
+
for _ in range(1, mlp_depth):
|
52 |
+
modules.append(nn.GELU())
|
53 |
+
modules.append(nn.Linear(cfg.n_embed, cfg.n_embed))
|
54 |
+
modules = nn.Sequential(*modules)
|
55 |
+
|
56 |
+
elif cfg.projector_type == "downsample_mlp_gelu":
|
57 |
+
mlp_depth = cfg.depth
|
58 |
+
mlp_ratio = cfg.mlp_ratio
|
59 |
+
modules = [nn.Linear(cfg.input_dim * cfg.downsample_ratio * cfg.downsample_ratio, cfg.n_embed * mlp_ratio)]
|
60 |
+
for _ in range(1, mlp_depth - 1):
|
61 |
+
modules.append(nn.GELU())
|
62 |
+
modules.append(nn.Linear(cfg.n_embed * mlp_ratio, cfg.n_embed * mlp_ratio))
|
63 |
+
modules.append(nn.GELU())
|
64 |
+
modules.append(nn.Linear(cfg.n_embed * mlp_ratio, cfg.n_embed))
|
65 |
+
modules = nn.Sequential(*modules)
|
66 |
+
|
67 |
+
else:
|
68 |
+
raise ValueError(f"Unknown projector type: {cfg.projector_type}")
|
69 |
+
|
70 |
+
if cfg.token_pooling:
|
71 |
+
self.token_pooling_layer = nn.Linear(cfg.input_dim * 4, cfg.input_dim)
|
72 |
+
|
73 |
+
self.layers = modules
|
74 |
+
|
75 |
+
def forward(self, x):
|
76 |
+
if self.cfg.token_pooling:
|
77 |
+
batch_size, wxh, channels = x.shape
|
78 |
+
w = h = int(wxh ** 0.5)
|
79 |
+
x = x.view(batch_size, w, h, channels)
|
80 |
+
x = x.permute(0, 3, 1, 2)
|
81 |
+
# import ipdb; ipdb.set_trace()
|
82 |
+
patches = x.unfold(2, 2, 2).unfold(3, 2, 2)
|
83 |
+
batch_size, channels, h_patches, w_patches, _, _ = patches.size()
|
84 |
+
# 在通道维度上拼接
|
85 |
+
patches = patches.contiguous().view(batch_size, channels, h_patches * w_patches, -1)
|
86 |
+
|
87 |
+
# 通过线性层
|
88 |
+
patches = patches.permute(0, 2, 1, 3).contiguous()
|
89 |
+
patches = patches.view(batch_size, h_patches * w_patches, channels * 4)
|
90 |
+
|
91 |
+
x = self.token_pooling_layer(patches)
|
92 |
+
|
93 |
+
elif self.cfg.projector_type == 'downsample_mlp_gelu':
|
94 |
+
bs, hw, input_dim = x.shape
|
95 |
+
h = w = int((hw) ** 0.5)
|
96 |
+
|
97 |
+
"""compute padding"""
|
98 |
+
if h % self.cfg.downsample_ratio:
|
99 |
+
pad = self.cfg.downsample_ratio - h % self.cfg.downsample_ratio
|
100 |
+
else:
|
101 |
+
pad = 0
|
102 |
+
x = x.reshape(bs, h, w, input_dim)
|
103 |
+
if pad > 0:
|
104 |
+
x = F.pad(x, (0, 0, 0, pad, 0, pad), "constant", 0)
|
105 |
+
|
106 |
+
"""4 to 1 concat"""
|
107 |
+
x = x.permute(0, 3, 1, 2) # B, C, H, W
|
108 |
+
x = F.unfold(x, kernel_size=self.cfg.downsample_ratio, stride=self.cfg.downsample_ratio,
|
109 |
+
padding=0) # B, C*4, HW // 4
|
110 |
+
x = x.permute(0, 2, 1)
|
111 |
+
|
112 |
+
return self.layers(x)
|
113 |
+
|
114 |
+
|
115 |
+
class VisionEncoderConfig(PretrainedConfig):
|
116 |
+
model_type: str = "vision"
|
117 |
+
|
118 |
+
model_name: str = "siglip_large_patch16_384"
|
119 |
+
image_size: int = 384
|
120 |
+
patch_size: int = 16
|
121 |
+
width: int = 1024
|
122 |
+
layers: int = 24
|
123 |
+
heads: int = 16
|
124 |
+
mlp_ratio: int = 4
|
125 |
+
global_pool: str = "map"
|
126 |
+
ignore_head: bool = True
|
127 |
+
class_token: bool = False
|
128 |
+
num_classes: int = 0
|
129 |
+
use_checkpoint: bool = False
|
130 |
+
weight_init: str = "skip"
|
131 |
+
deterministic: bool = False
|
132 |
+
num_recomputing_layers: int = 0
|
133 |
+
|
134 |
+
def __init__(
|
135 |
+
self,
|
136 |
+
model_name: str = "siglip_large_patch16_384",
|
137 |
+
image_size: int = 384,
|
138 |
+
patch_size: int = 16,
|
139 |
+
width: int = 1024,
|
140 |
+
layers: int = 24,
|
141 |
+
heads: int = 16,
|
142 |
+
mlp_ratio: int = 4,
|
143 |
+
global_pool: str = "map",
|
144 |
+
ignore_head: bool = True,
|
145 |
+
class_token: bool = False,
|
146 |
+
num_classes: int = 0,
|
147 |
+
use_checkpoint: bool = False,
|
148 |
+
**kwargs
|
149 |
+
):
|
150 |
+
self.model_name = model_name
|
151 |
+
self.image_size = image_size
|
152 |
+
self.patch_size = patch_size
|
153 |
+
self.width = width
|
154 |
+
self.layers = layers
|
155 |
+
self.heads = heads
|
156 |
+
self.mlp_ratio = mlp_ratio
|
157 |
+
self.global_pool = global_pool
|
158 |
+
self.ignore_head = ignore_head
|
159 |
+
self.class_token = class_token
|
160 |
+
self.num_classes = num_classes
|
161 |
+
self.use_checkpoint = use_checkpoint
|
162 |
+
|
163 |
+
super().__init__(**kwargs)
|
164 |
+
|
165 |
+
|
166 |
+
class MlpProjectorConfig(PretrainedConfig):
|
167 |
+
model_type = "mlp_projector"
|
168 |
+
projector_type: str = "downsample_mlp_gelu"
|
169 |
+
input_dim: int = 1152
|
170 |
+
n_embed: int = 2048
|
171 |
+
depth: int = 2
|
172 |
+
mlp_ratio: int = 1
|
173 |
+
downsample_ratio: int = 2
|
174 |
+
token_pooling: bool = False
|
175 |
+
|
176 |
+
def __init__(
|
177 |
+
self,
|
178 |
+
projector_type: str = "downsample_mlp_gelu",
|
179 |
+
input_dim: int = 1152,
|
180 |
+
n_embed: int = 2048,
|
181 |
+
depth: int = 2,
|
182 |
+
mlp_ratio: int = 1,
|
183 |
+
downsample_ratio: int = 2,
|
184 |
+
**kwargs
|
185 |
+
):
|
186 |
+
self.projector_type = projector_type
|
187 |
+
self.input_dim = input_dim
|
188 |
+
self.n_embed = n_embed
|
189 |
+
self.depth = depth
|
190 |
+
self.mlp_ratio = mlp_ratio
|
191 |
+
self.downsample_ratio = downsample_ratio
|
192 |
+
|
193 |
+
super().__init__(**kwargs)
|
194 |
+
|
195 |
+
|
196 |
+
@dataclass
|
197 |
+
class DeepSeekVLV2CausalLMOutputWithPast(ModelOutput):
|
198 |
+
"""
|
199 |
+
Base class for DeepSeek-VL2 causal language model (or autoregressive) outputs.
|
200 |
+
|
201 |
+
Args:
|
202 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
203 |
+
Language modeling loss (for next-token prediction).
|
204 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
205 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
206 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
207 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
208 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`)
|
209 |
+
|
210 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
|
211 |
+
`past_key_values` input) to speed up sequential decoding.
|
212 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
213 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
214 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
215 |
+
|
216 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
217 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
218 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
219 |
+
sequence_length)`.
|
220 |
+
|
221 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
222 |
+
heads.
|
223 |
+
rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
|
224 |
+
The rope index difference between sequence length and multimodal rope.
|
225 |
+
"""
|
226 |
+
|
227 |
+
loss: Optional[torch.FloatTensor] = None
|
228 |
+
logits: torch.FloatTensor = None
|
229 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None
|
230 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
231 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
232 |
+
rope_deltas: Optional[torch.LongTensor] = None
|
233 |
+
|
234 |
+
|
235 |
+
class DeepseekVLV2Config(PretrainedConfig):
|
236 |
+
model_type = "deepseek_vl_v2"
|
237 |
+
vision_config: VisionEncoderConfig
|
238 |
+
projector_config: MlpProjectorConfig
|
239 |
+
language_config: DeepseekV2Config
|
240 |
+
|
241 |
+
tile_tag: str = "2D"
|
242 |
+
global_view_pos: str = "head"
|
243 |
+
candidate_resolutions: Tuple[Tuple[int, int]] = ((384, 384),)
|
244 |
+
|
245 |
+
def __init__(
|
246 |
+
self,
|
247 |
+
tile_tag: str = "tile_tag",
|
248 |
+
global_view_pos: str = "head",
|
249 |
+
candidate_resolutions: Tuple[Tuple[int, int]] = ((384, 384),),
|
250 |
+
**kwargs
|
251 |
+
):
|
252 |
+
super().__init__(**kwargs)
|
253 |
+
|
254 |
+
vision_config = kwargs.get("vision_config", {})
|
255 |
+
self.vision_config = VisionEncoderConfig(**vision_config)
|
256 |
+
|
257 |
+
projector_config = kwargs.get("projector_config", {})
|
258 |
+
self.projector_config = MlpProjectorConfig(**projector_config)
|
259 |
+
|
260 |
+
language_config = kwargs.get("language_config", {})
|
261 |
+
if isinstance(language_config, DeepseekV2Config):
|
262 |
+
self.language_config = language_config
|
263 |
+
else:
|
264 |
+
self.language_config = DeepseekV2Config(**language_config)
|
265 |
+
|
266 |
+
self.tile_tag = tile_tag
|
267 |
+
self.global_view_pos = global_view_pos
|
268 |
+
self.candidate_resolutions = candidate_resolutions
|
269 |
+
|
270 |
+
|
271 |
+
class DeepseekVLV2PreTrainedModel(PreTrainedModel):
|
272 |
+
config_class = DeepseekVLV2Config
|
273 |
+
base_model_prefix = "deepseek_vl_v2"
|
274 |
+
_no_split_modules = []
|
275 |
+
_skip_keys_device_placement = "past_key_values"
|
276 |
+
|
277 |
+
|
278 |
+
class DeepseekVLV2ForCausalLM(DeepseekVLV2PreTrainedModel):
|
279 |
+
|
280 |
+
def __init__(self, config: DeepseekVLV2Config):
|
281 |
+
super().__init__(config)
|
282 |
+
|
283 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
284 |
+
|
285 |
+
# ----------- vision encoder ------------
|
286 |
+
vision_config = config.vision_config
|
287 |
+
self.vision = VisionTransformer(
|
288 |
+
img_size=vision_config.image_size,
|
289 |
+
patch_size=vision_config.patch_size,
|
290 |
+
embed_dim=vision_config.width,
|
291 |
+
depth=vision_config.layers,
|
292 |
+
num_heads=vision_config.heads,
|
293 |
+
mlp_ratio=vision_config.mlp_ratio,
|
294 |
+
class_token=vision_config.class_token,
|
295 |
+
global_pool=vision_config.global_pool,
|
296 |
+
ignore_head=vision_config.ignore_head,
|
297 |
+
weight_init=vision_config.weight_init,
|
298 |
+
num_classes=0,
|
299 |
+
deterministic=vision_config.deterministic,
|
300 |
+
num_recomputing_layers=vision_config.num_recomputing_layers
|
301 |
+
)
|
302 |
+
|
303 |
+
# ----------- vl projector ------------
|
304 |
+
projector_config = config.projector_config
|
305 |
+
self.projector = MlpProjector(projector_config)
|
306 |
+
|
307 |
+
# image token format 形式
|
308 |
+
# FIXME 目前tile tag & global_view_pos的默认取值都是之前的实验策略;后续应当去掉默认取值,改为没有取值就raise error
|
309 |
+
self.tile_tag = config.tile_tag
|
310 |
+
self.global_view_pos = config.global_view_pos
|
311 |
+
|
312 |
+
# 用于format image token sequence的特殊token
|
313 |
+
embed_std = 1 / torch.sqrt(torch.tensor(projector_config.n_embed, dtype=torch.float32))
|
314 |
+
if self.tile_tag == "2D":
|
315 |
+
# <|view_separator|>, <|\n|>
|
316 |
+
self.image_newline = nn.Parameter(torch.randn(projector_config.n_embed) * embed_std)
|
317 |
+
# fix the typo: view_seperater
|
318 |
+
self.view_seperator = nn.Parameter(torch.randn(projector_config.n_embed) * embed_std)
|
319 |
+
elif self.tile_tag == "1D":
|
320 |
+
# <|tile_x|>, <|tile_global|>
|
321 |
+
candidate_resolutions = config.candidate_resolutions
|
322 |
+
if len(candidate_resolutions) == 0:
|
323 |
+
raise ValueError(
|
324 |
+
f"len(candidate_resolutions) should be larger than 0, but got {len(candidate_resolutions)}")
|
325 |
+
tile_variants_num = len(candidate_resolutions)
|
326 |
+
self.tile_indicators = nn.Parameter(
|
327 |
+
torch.randn(size=(tile_variants_num + 1, config.aligner.params.n_embed)) * embed_std
|
328 |
+
)
|
329 |
+
else:
|
330 |
+
raise ValueError(f"tile tag should be either 1D or 2D, but got {self.tile_tag}")
|
331 |
+
|
332 |
+
# ----------- language model ------------
|
333 |
+
language_config = config.language_config
|
334 |
+
self.language = DeepseekV2ForCausalLM(language_config)
|
335 |
+
|
336 |
+
def prepare_inputs_embeds(
|
337 |
+
self,
|
338 |
+
input_ids: torch.LongTensor,
|
339 |
+
images: Optional[torch.FloatTensor] = None,
|
340 |
+
images_seq_mask: Optional[torch.LongTensor] = None,
|
341 |
+
images_spatial_crop: Optional[torch.LongTensor] = None,
|
342 |
+
**ignore_kwargs
|
343 |
+
):
|
344 |
+
"""
|
345 |
+
|
346 |
+
Args:
|
347 |
+
input_ids (torch.LongTensor): [b, T]
|
348 |
+
images (torch.FloatTensor): [b, max_n_images, 3, height, width]
|
349 |
+
images_seq_mask (torch.BoolTensor): [b, T]
|
350 |
+
images_spatial_crop (torch.LongTensor): [b, max_n_images, 2]
|
351 |
+
|
352 |
+
Returns:
|
353 |
+
input_embeds (torch.Tensor): [b, T, D]
|
354 |
+
"""
|
355 |
+
|
356 |
+
if images is None or images_spatial_crop.sum() == 0:
|
357 |
+
return self.language.get_input_embeddings()(input_ids)
|
358 |
+
|
359 |
+
bs, max_n_images, _ = images_spatial_crop.shape
|
360 |
+
batch_num_tiles = [0 for _ in range(bs)]
|
361 |
+
total_tiles = []
|
362 |
+
for idx in range(bs):
|
363 |
+
for jdx in range(max_n_images):
|
364 |
+
num_width_tiles, num_height_tiles = images_spatial_crop[idx, jdx]
|
365 |
+
if num_width_tiles == 0 or num_height_tiles == 0:
|
366 |
+
break
|
367 |
+
batch_num_tiles[idx] += (1 + num_width_tiles * num_height_tiles)
|
368 |
+
|
369 |
+
total_tiles.append(images[idx, :batch_num_tiles[idx]])
|
370 |
+
|
371 |
+
# [batch_all_tiles, 3, height, width]
|
372 |
+
total_tiles = torch.cat(total_tiles, dim=0)
|
373 |
+
assert total_tiles.shape[0] == sum(batch_num_tiles)
|
374 |
+
if total_tiles.shape[0] == 0:
|
375 |
+
return self.language.get_input_embeddings()(input_ids)
|
376 |
+
|
377 |
+
# [batch_all_tiles, vit_seq_len, c]
|
378 |
+
images_feature = self.vision(total_tiles)
|
379 |
+
|
380 |
+
# [batch_all_tiles, hw, D]
|
381 |
+
images_embeds = self.projector(images_feature)
|
382 |
+
_, hw, n_dim = images_embeds.shape
|
383 |
+
h = w = int(hw ** 0.5)
|
384 |
+
|
385 |
+
# put image tokens into the input_embeds, [b, T, D]
|
386 |
+
input_embeds = self.language.get_input_embeddings()(input_ids)
|
387 |
+
|
388 |
+
# 根据self.tile_tag & self.global_view_pos填充image token sequence
|
389 |
+
tile_index = 0
|
390 |
+
for idx in range(images_spatial_crop.shape[0]):
|
391 |
+
images_in_this_batch = []
|
392 |
+
for jdx in range(images_spatial_crop.shape[1]):
|
393 |
+
|
394 |
+
# extra global & local features
|
395 |
+
num_width_tiles, num_height_tiles = images_spatial_crop[idx, jdx]
|
396 |
+
if num_width_tiles == 0 or num_height_tiles == 0:
|
397 |
+
break
|
398 |
+
|
399 |
+
num_tiles_in_image = num_width_tiles * num_height_tiles
|
400 |
+
|
401 |
+
# [hw, D]
|
402 |
+
global_features = images_embeds[tile_index]
|
403 |
+
|
404 |
+
# [num_height_tiles * num_width_tiles, hw, D]
|
405 |
+
local_features = images_embeds[tile_index + 1: tile_index + 1 + num_tiles_in_image]
|
406 |
+
|
407 |
+
tile_index += num_tiles_in_image + 1
|
408 |
+
|
409 |
+
# format global and local features
|
410 |
+
if self.tile_tag == "2D":
|
411 |
+
|
412 |
+
# ----------------- global view add newline -----------------
|
413 |
+
# [hw, D] -> [h, w, D]
|
414 |
+
global_features = global_features.view(h, w, n_dim)
|
415 |
+
# [D] -> [h, 1, D]
|
416 |
+
new_lines_in_global = repeat(self.image_newline, "d -> h 1 d", h=h)
|
417 |
+
# cat([h, w, D], [h, 1, D], dim=1) -> [h, w + 1, D]
|
418 |
+
global_features = torch.cat([global_features, new_lines_in_global], dim=1)
|
419 |
+
# [h, w + 1, D] -> [h * (w + 1), D]
|
420 |
+
global_features = global_features.view(-1, n_dim)
|
421 |
+
|
422 |
+
# ----------------- local view add newline -----------------
|
423 |
+
# [num_height_tiles * num_width_tiles, h * w, D] -> [num_height_tiles * h, num_width_tiles * w, D]
|
424 |
+
local_features = rearrange(
|
425 |
+
local_features,
|
426 |
+
"(th tw) (h w) d -> (th h) (tw w) d",
|
427 |
+
th=num_height_tiles,
|
428 |
+
tw=num_width_tiles,
|
429 |
+
h=h,
|
430 |
+
w=w
|
431 |
+
)
|
432 |
+
|
433 |
+
# [D] -> [num_height_tiles * h, 1, D]
|
434 |
+
new_lines_in_local = repeat(
|
435 |
+
self.image_newline,
|
436 |
+
"d -> (th h) 1 d",
|
437 |
+
th=num_height_tiles,
|
438 |
+
h=h
|
439 |
+
)
|
440 |
+
|
441 |
+
# [num_height_tiles * h, num_width_tiles * w + 1, D]
|
442 |
+
local_features = torch.cat([local_features, new_lines_in_local], dim=1)
|
443 |
+
|
444 |
+
# [num_height_tiles * h, num_width_tiles * w + 1, D]
|
445 |
+
# --> [(num_height_tiles * h) * (num_width_tiles * w + 1), D]
|
446 |
+
local_features = local_features.view(-1, n_dim)
|
447 |
+
|
448 |
+
# ----------------- merge global and local tiles -----------------
|
449 |
+
if self.global_view_pos == "head":
|
450 |
+
global_local_features = torch.cat(
|
451 |
+
[global_features, self.view_seperator[None, :], local_features], dim=0)
|
452 |
+
else:
|
453 |
+
global_local_features = torch.cat(
|
454 |
+
[local_features, self.view_seperator[None, :], global_features], dim=0)
|
455 |
+
|
456 |
+
else:
|
457 |
+
# abandoned,实际上不会走这个逻辑
|
458 |
+
global_features = torch.cat(
|
459 |
+
[self.tile_indicators[0:1], global_features], dim=0
|
460 |
+
)
|
461 |
+
local_features = torch.cat(
|
462 |
+
[self.tile_indicators[1:num_tiles_in_image + 1].unsqueeze(1), local_features], dim=1
|
463 |
+
)
|
464 |
+
local_features = rearrange(local_features, 'crop_num hw d -> (crop_num hw) d')
|
465 |
+
|
466 |
+
if self.global_view_pos == "head":
|
467 |
+
global_local_features = torch.cat([global_features, local_features], dim=0)
|
468 |
+
else:
|
469 |
+
global_local_features = torch.cat([local_features, global_features], dim=0)
|
470 |
+
|
471 |
+
images_in_this_batch.append(global_local_features)
|
472 |
+
|
473 |
+
if len(images_in_this_batch) > 0:
|
474 |
+
images_in_this_batch = torch.cat(images_in_this_batch, dim=0)
|
475 |
+
input_embeds[idx].masked_scatter_(images_seq_mask[idx].unsqueeze(-1), images_in_this_batch)
|
476 |
+
|
477 |
+
return input_embeds
|
478 |
+
|
479 |
+
@torch.no_grad()
|
480 |
+
def incremental_prefilling(
|
481 |
+
self,
|
482 |
+
input_ids: Optional[torch.LongTensor] = None,
|
483 |
+
attention_mask: Optional[torch.Tensor] = None,
|
484 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
485 |
+
|
486 |
+
images: Optional[torch.FloatTensor] = None,
|
487 |
+
images_seq_mask: Optional[torch.LongTensor] = None,
|
488 |
+
images_spatial_crop: Optional[torch.LongTensor] = None,
|
489 |
+
chunk_size: int = 1024
|
490 |
+
):
|
491 |
+
if inputs_embeds is None:
|
492 |
+
inputs_embeds = self.prepare_inputs_embeds(
|
493 |
+
input_ids=input_ids,
|
494 |
+
images=images,
|
495 |
+
images_seq_mask=images_seq_mask,
|
496 |
+
images_spatial_crop=images_spatial_crop,
|
497 |
+
)
|
498 |
+
|
499 |
+
del images
|
500 |
+
del images_seq_mask
|
501 |
+
del images_spatial_crop
|
502 |
+
|
503 |
+
if attention_mask is not None:
|
504 |
+
attention_mask = attention_mask.to(inputs_embeds.device)
|
505 |
+
|
506 |
+
self._clear_cuda_cache()
|
507 |
+
|
508 |
+
bzs, seq_len, _ = inputs_embeds.shape
|
509 |
+
past_key_values = None
|
510 |
+
|
511 |
+
# remain the last token for the next forward
|
512 |
+
prefilling_len = seq_len - 1
|
513 |
+
for i in range(0, prefilling_len, chunk_size):
|
514 |
+
chunk_start = i
|
515 |
+
chunk_end = min(i + chunk_size, prefilling_len)
|
516 |
+
chunk_inputs_embeds = inputs_embeds[:, chunk_start: chunk_end]
|
517 |
+
chunk_attention_mask = attention_mask[:, 0: chunk_end]
|
518 |
+
# print(f"start = {chunk_start}, end = {chunk_end}, prefilling_len = {prefilling_len}, seq_len = {seq_len}")
|
519 |
+
|
520 |
+
# compute position_ids
|
521 |
+
if past_key_values is not None:
|
522 |
+
position_ids = torch.arange(
|
523 |
+
chunk_start,
|
524 |
+
chunk_end,
|
525 |
+
dtype=torch.long,
|
526 |
+
device=inputs_embeds.device
|
527 |
+
).unsqueeze(0)
|
528 |
+
past_key_values = self._move_past_key_values_to_gpu(past_key_values, inputs_embeds.device)
|
529 |
+
else:
|
530 |
+
position_ids = None
|
531 |
+
|
532 |
+
# chunk-forward
|
533 |
+
with torch.no_grad():
|
534 |
+
outputs = self.forward(
|
535 |
+
inputs_embeds=chunk_inputs_embeds,
|
536 |
+
attention_mask=chunk_attention_mask,
|
537 |
+
past_key_values=past_key_values,
|
538 |
+
position_ids=position_ids,
|
539 |
+
use_cache=True,
|
540 |
+
)
|
541 |
+
# update past_key_values
|
542 |
+
past_key_values = outputs.past_key_values
|
543 |
+
past_key_values = self._move_past_key_values_to_cpu(past_key_values)
|
544 |
+
|
545 |
+
del outputs, position_ids
|
546 |
+
self._clear_cuda_cache()
|
547 |
+
|
548 |
+
prefilling_key_values = []
|
549 |
+
for layer_past in past_key_values:
|
550 |
+
prefilling_key_values.append(
|
551 |
+
(
|
552 |
+
layer_past[0][:, :, 0: prefilling_len, ...].to(inputs_embeds.device),
|
553 |
+
layer_past[1][:, :, 0: prefilling_len, ...].to(inputs_embeds.device),
|
554 |
+
)
|
555 |
+
)
|
556 |
+
|
557 |
+
return inputs_embeds, prefilling_key_values
|
558 |
+
|
559 |
+
def forward(
|
560 |
+
self,
|
561 |
+
input_ids: Optional[torch.LongTensor] = None,
|
562 |
+
|
563 |
+
attention_mask: Optional[torch.Tensor] = None,
|
564 |
+
position_ids: Optional[torch.LongTensor] = None,
|
565 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
566 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
567 |
+
|
568 |
+
images: Optional[torch.FloatTensor] = None,
|
569 |
+
images_seq_mask: Optional[torch.LongTensor] = None,
|
570 |
+
images_spatial_crop: Optional[torch.LongTensor] = None,
|
571 |
+
|
572 |
+
labels: Optional[torch.LongTensor] = None,
|
573 |
+
use_cache: Optional[bool] = None,
|
574 |
+
output_attentions: Optional[bool] = None,
|
575 |
+
output_hidden_states: Optional[bool] = None,
|
576 |
+
return_dict: Optional[bool] = None,
|
577 |
+
cache_position: Optional[torch.LongTensor] = None,
|
578 |
+
):
|
579 |
+
|
580 |
+
output_attentions = (
|
581 |
+
output_attentions
|
582 |
+
if output_attentions is not None
|
583 |
+
else self.config.output_attentions
|
584 |
+
)
|
585 |
+
output_hidden_states = (
|
586 |
+
output_hidden_states
|
587 |
+
if output_hidden_states is not None
|
588 |
+
else self.config.output_hidden_states
|
589 |
+
)
|
590 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
591 |
+
|
592 |
+
return_dict = (
|
593 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
594 |
+
)
|
595 |
+
if inputs_embeds is None:
|
596 |
+
inputs_embeds = self.prepare_inputs_embeds(
|
597 |
+
input_ids=input_ids,
|
598 |
+
images=images,
|
599 |
+
images_seq_mask=images_seq_mask,
|
600 |
+
images_spatial_crop=images_spatial_crop,
|
601 |
+
)
|
602 |
+
|
603 |
+
if attention_mask is not None:
|
604 |
+
attention_mask = attention_mask.to(inputs_embeds.device)
|
605 |
+
|
606 |
+
# print(inputs_embeds.shape)
|
607 |
+
outputs = self.language.forward(
|
608 |
+
input_ids=None,
|
609 |
+
attention_mask=attention_mask,
|
610 |
+
position_ids=position_ids,
|
611 |
+
past_key_values=past_key_values,
|
612 |
+
inputs_embeds=inputs_embeds,
|
613 |
+
labels=labels,
|
614 |
+
use_cache=use_cache,
|
615 |
+
output_attentions=output_attentions,
|
616 |
+
output_hidden_states=output_hidden_states,
|
617 |
+
return_dict=return_dict,
|
618 |
+
cache_position=cache_position
|
619 |
+
)
|
620 |
+
|
621 |
+
return outputs
|
622 |
+
|
623 |
+
def _clear_cuda_cache(self):
|
624 |
+
"""clear CUDA memory cache"""
|
625 |
+
gc.collect()
|
626 |
+
if torch.cuda.is_available():
|
627 |
+
torch.cuda.empty_cache()
|
628 |
+
torch.cuda.synchronize()
|
629 |
+
|
630 |
+
def _move_past_key_values_to_cpu(self, past_key_values):
|
631 |
+
# print(f"past_key_values -> cpu")
|
632 |
+
if past_key_values is None:
|
633 |
+
return None
|
634 |
+
return tuple(tuple(t.cpu() for t in layer) for layer in past_key_values)
|
635 |
+
|
636 |
+
def _move_past_key_values_to_gpu(self, past_key_values, device="cuda:0"):
|
637 |
+
# print(f"past_key_values -> gpu")
|
638 |
+
if past_key_values is None:
|
639 |
+
return None
|
640 |
+
return tuple(tuple(t.to(device) for t in layer) for layer in past_key_values)
|
641 |
+
|
642 |
+
def prepare_inputs_for_generation(
|
643 |
+
self,
|
644 |
+
input_ids,
|
645 |
+
past_key_values=None,
|
646 |
+
inputs_embeds=None,
|
647 |
+
|
648 |
+
images: Optional[torch.FloatTensor] = None,
|
649 |
+
images_seq_mask: Optional[torch.LongTensor] = None,
|
650 |
+
images_spatial_crop: Optional[torch.LongTensor] = None,
|
651 |
+
|
652 |
+
attention_mask=None,
|
653 |
+
cache_position=None,
|
654 |
+
|
655 |
+
pixel_values=None,
|
656 |
+
image_sizes=None,
|
657 |
+
num_logits_to_keep=None,
|
658 |
+
**kwargs,
|
659 |
+
):
|
660 |
+
# Overwritten -- in specific circumstances we don't want to forward image inputs to the model
|
661 |
+
model_inputs = self.language.prepare_inputs_for_generation(
|
662 |
+
input_ids,
|
663 |
+
past_key_values=past_key_values,
|
664 |
+
inputs_embeds=inputs_embeds,
|
665 |
+
attention_mask=attention_mask,
|
666 |
+
cache_position=cache_position,
|
667 |
+
num_logits_to_keep=num_logits_to_keep,
|
668 |
+
**kwargs,
|
669 |
+
)
|
670 |
+
|
671 |
+
# If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
|
672 |
+
# Otherwise we need pixel values to be passed to model
|
673 |
+
cache_position = model_inputs["cache_position"]
|
674 |
+
if cache_position[0] == 0:
|
675 |
+
model_inputs["images"] = images
|
676 |
+
model_inputs["images_seq_mask"] = images_seq_mask
|
677 |
+
model_inputs["images_spatial_crop"] = images_spatial_crop
|
678 |
+
|
679 |
+
return model_inputs
|
680 |
+
|
681 |
+
@staticmethod
|
682 |
+
def _reorder_cache(past_key_values, beam_idx):
|
683 |
+
reordered_past = ()
|
684 |
+
for layer_past in past_key_values:
|
685 |
+
reordered_past += (
|
686 |
+
tuple(
|
687 |
+
past_state.index_select(0, beam_idx.to(past_state.device))
|
688 |
+
for past_state in layer_past
|
689 |
+
),
|
690 |
+
)
|
691 |
+
return reordered_past
|
692 |
+
|
693 |
+
|
694 |
+
AutoConfig.register("vision", VisionEncoderConfig)
|
695 |
+
AutoConfig.register("mlp_projector", MlpProjectorConfig)
|
696 |
+
AutoConfig.register("deepseek_vl_v2", DeepseekVLV2Config)
|
697 |
+
AutoModelForCausalLM.register(DeepseekVLV2Config, DeepseekVLV2ForCausalLM)
|
processing_deepseek_vl_v2.py
ADDED
@@ -0,0 +1,675 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2023-2024 DeepSeek.
|
2 |
+
#
|
3 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of
|
4 |
+
# this software and associated documentation files (the "Software"), to deal in
|
5 |
+
# the Software without restriction, including without limitation the rights to
|
6 |
+
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
7 |
+
# the Software, and to permit persons to whom the Software is furnished to do so,
|
8 |
+
# subject to the following conditions:
|
9 |
+
#
|
10 |
+
# The above copyright notice and this permission notice shall be included in all
|
11 |
+
# copies or substantial portions of the Software.
|
12 |
+
#
|
13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
15 |
+
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
16 |
+
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
17 |
+
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
18 |
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
19 |
+
|
20 |
+
from dataclasses import dataclass
|
21 |
+
from typing import Dict, Tuple, List, Literal, Optional
|
22 |
+
import math
|
23 |
+
|
24 |
+
import torch
|
25 |
+
from torch.nn.utils.rnn import pad_sequence
|
26 |
+
import torchvision.transforms as T
|
27 |
+
from transformers import LlamaTokenizerFast
|
28 |
+
from transformers.processing_utils import ProcessorMixin
|
29 |
+
from PIL import Image, ImageOps
|
30 |
+
|
31 |
+
from .conversation import get_conv_template
|
32 |
+
|
33 |
+
|
34 |
+
def select_best_resolution(image_size, candidate_resolutions):
|
35 |
+
# used for cropping
|
36 |
+
original_width, original_height = image_size
|
37 |
+
best_fit = None
|
38 |
+
max_effective_resolution = 0
|
39 |
+
min_wasted_resolution = float("inf")
|
40 |
+
|
41 |
+
for width, height in candidate_resolutions:
|
42 |
+
scale = min(width / original_width, height / original_height)
|
43 |
+
downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
|
44 |
+
effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
|
45 |
+
wasted_resolution = (width * height) - effective_resolution
|
46 |
+
|
47 |
+
if effective_resolution > max_effective_resolution or (effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution):
|
48 |
+
max_effective_resolution = effective_resolution
|
49 |
+
min_wasted_resolution = wasted_resolution
|
50 |
+
best_fit = (width, height)
|
51 |
+
|
52 |
+
return best_fit
|
53 |
+
|
54 |
+
|
55 |
+
class DictOutput(object):
|
56 |
+
def keys(self):
|
57 |
+
return self.__dict__.keys()
|
58 |
+
|
59 |
+
def __getitem__(self, item):
|
60 |
+
return self.__dict__[item]
|
61 |
+
|
62 |
+
def __setitem__(self, key, value):
|
63 |
+
self.__dict__[key] = value
|
64 |
+
|
65 |
+
|
66 |
+
# 对于inference sample也可以维护input_ids,反正最后不会用到
|
67 |
+
@dataclass
|
68 |
+
class VLChatProcessorOutput(DictOutput):
|
69 |
+
sft_format: str
|
70 |
+
input_ids: torch.LongTensor
|
71 |
+
target_ids: torch.LongTensor
|
72 |
+
images: torch.Tensor
|
73 |
+
images_seq_mask: torch.BoolTensor
|
74 |
+
images_spatial_crop: torch.LongTensor
|
75 |
+
num_image_tokens: List[int]
|
76 |
+
|
77 |
+
def __len__(self):
|
78 |
+
return len(self.input_ids)
|
79 |
+
|
80 |
+
|
81 |
+
@dataclass
|
82 |
+
class BatchCollateOutput(DictOutput):
|
83 |
+
sft_format: List[str]
|
84 |
+
input_ids: torch.LongTensor
|
85 |
+
labels: torch.LongTensor
|
86 |
+
images: torch.Tensor
|
87 |
+
attention_mask: torch.Tensor
|
88 |
+
images_seq_mask: torch.BoolTensor
|
89 |
+
images_spatial_crop: torch.LongTensor
|
90 |
+
seq_lens: List[int]
|
91 |
+
|
92 |
+
def to(self, device, dtype=torch.bfloat16):
|
93 |
+
self.input_ids = self.input_ids.to(device)
|
94 |
+
self.labels = self.labels.to(device)
|
95 |
+
self.attention_mask = self.attention_mask.to(device)
|
96 |
+
self.images_seq_mask = self.images_seq_mask.to(device)
|
97 |
+
self.images_spatial_crop = self.images_spatial_crop.to(device)
|
98 |
+
self.images = self.images.to(device=device, dtype=dtype)
|
99 |
+
return self
|
100 |
+
|
101 |
+
|
102 |
+
class ImageTransform(object):
|
103 |
+
def __init__(
|
104 |
+
self,
|
105 |
+
mean: Optional[Tuple[float, float, float]] = (0.5, 0.5, 0.5),
|
106 |
+
std: Optional[Tuple[float, float, float]] = (0.5, 0.5, 0.5),
|
107 |
+
normalize: bool = True
|
108 |
+
):
|
109 |
+
self.mean = mean
|
110 |
+
self.std = std
|
111 |
+
self.normalize = normalize
|
112 |
+
|
113 |
+
transform_pipelines = [
|
114 |
+
T.ToTensor()
|
115 |
+
]
|
116 |
+
|
117 |
+
if normalize:
|
118 |
+
transform_pipelines.append(T.Normalize(mean, std))
|
119 |
+
|
120 |
+
self.transform = T.Compose(transform_pipelines)
|
121 |
+
|
122 |
+
def __call__(self, pil_img: Image.Image):
|
123 |
+
x = self.transform(pil_img)
|
124 |
+
return x
|
125 |
+
|
126 |
+
|
127 |
+
|
128 |
+
class DeepseekVLV2Processor(ProcessorMixin):
|
129 |
+
tokenizer_class = ("LlamaTokenizer", "LlamaTokenizerFast")
|
130 |
+
attributes = ["tokenizer"]
|
131 |
+
|
132 |
+
def __init__(
|
133 |
+
self,
|
134 |
+
tokenizer: LlamaTokenizerFast,
|
135 |
+
candidate_resolutions: Tuple[Tuple[int, int]],
|
136 |
+
patch_size: int,
|
137 |
+
downsample_ratio: int,
|
138 |
+
image_mean: Tuple[float, float, float] = (0.5, 0.5, 0.5),
|
139 |
+
image_std: Tuple[float, float, float] = (0.5, 0.5, 0.5),
|
140 |
+
normalize: bool = True,
|
141 |
+
image_token: str = "<image>",
|
142 |
+
pad_token: str = "<|▁pad▁|>",
|
143 |
+
add_special_token: bool = False,
|
144 |
+
sft_format: str = "deepseek",
|
145 |
+
mask_prompt: bool = True,
|
146 |
+
ignore_id: int = -100,
|
147 |
+
**kwargs,
|
148 |
+
):
|
149 |
+
|
150 |
+
self.candidate_resolutions = candidate_resolutions
|
151 |
+
self.image_size = candidate_resolutions[0][0]
|
152 |
+
self.patch_size = patch_size
|
153 |
+
self.image_mean = image_mean
|
154 |
+
self.image_std = image_std
|
155 |
+
self.normalize = normalize
|
156 |
+
self.downsample_ratio = downsample_ratio
|
157 |
+
|
158 |
+
self.image_transform = ImageTransform(mean=image_mean, std=image_std, normalize=normalize)
|
159 |
+
self.tokenizer = tokenizer
|
160 |
+
self.tokenizer.padding_side = 'left' # must set this,padding side with make a difference in batch inference
|
161 |
+
|
162 |
+
# add the pad_token as special token to use 'tokenizer.pad_token' and 'tokenizer.pad_token_id'
|
163 |
+
if tokenizer.pad_token is None:
|
164 |
+
self.tokenizer.add_special_tokens({'pad_token': pad_token})
|
165 |
+
print(f"Add pad token = ['{pad_token}'] to the tokenizer\n"
|
166 |
+
f"{pad_token}:{tokenizer.encode(pad_token, add_special_tokens=False)[0]}")
|
167 |
+
|
168 |
+
# add image token
|
169 |
+
image_token_id = self.tokenizer.vocab.get(image_token)
|
170 |
+
if image_token_id is None:
|
171 |
+
special_tokens = [image_token]
|
172 |
+
special_tokens_dict = {"additional_special_tokens": special_tokens}
|
173 |
+
self.tokenizer.add_special_tokens(special_tokens_dict)
|
174 |
+
self.image_token_id = self.tokenizer.vocab.get(image_token)
|
175 |
+
print(f"Add image token = ['{image_token}'] to the tokenizer\n"
|
176 |
+
f"{image_token}:{tokenizer.encode(image_token, add_special_tokens=False)[0]}")
|
177 |
+
|
178 |
+
# add five special tokens for grounding-related tasks
|
179 |
+
# <|ref|>, <|/ref|>, <|det|>, <|/det|>, <|grounding|>
|
180 |
+
special_tokens = ['<|ref|>', '<|/ref|>', '<|det|>', '<|/det|>', '<|grounding|>']
|
181 |
+
special_tokens_dict = {"additional_special_tokens": special_tokens}
|
182 |
+
self.tokenizer.add_special_tokens(special_tokens_dict)
|
183 |
+
print(f"Add grounding-related tokens = {special_tokens} to the tokenizer with input_ids\n"
|
184 |
+
f"<|ref|>:{tokenizer.encode('<|ref|>', add_special_tokens=False)[0]}\n"
|
185 |
+
f"<|/ref|>:{tokenizer.encode('<|/ref|>', add_special_tokens=False)[0]}\n"
|
186 |
+
f"<|det|>:{tokenizer.encode('<|det|>', add_special_tokens=False)[0]}\n"
|
187 |
+
f"<|/det|>:{tokenizer.encode('<|/det|>', add_special_tokens=False)[0]}\n"
|
188 |
+
f"<|grounding|>:{tokenizer.encode('<|grounding|>', add_special_tokens=False)[0]}")
|
189 |
+
|
190 |
+
# add special tokens for SFT data
|
191 |
+
special_tokens = ["<|User|>", "<|Assistant|>"]
|
192 |
+
special_tokens_dict = {"additional_special_tokens": special_tokens}
|
193 |
+
self.tokenizer.add_special_tokens(special_tokens_dict)
|
194 |
+
print(f"Add chat tokens = {special_tokens} to the tokenizer with input_ids\n"
|
195 |
+
f"<|User|>:{tokenizer.encode('<|User|>', add_special_tokens=False)[0]}\n"
|
196 |
+
f"<|Assistant|>:{tokenizer.encode('<|Assistant|>', add_special_tokens=False)[0]}\n")
|
197 |
+
|
198 |
+
self.image_token = image_token
|
199 |
+
self.pad_token = pad_token
|
200 |
+
self.add_special_token = add_special_token
|
201 |
+
self.sft_format = sft_format
|
202 |
+
self.mask_prompt = mask_prompt
|
203 |
+
self.ignore_id = ignore_id
|
204 |
+
|
205 |
+
super().__init__(
|
206 |
+
tokenizer,
|
207 |
+
**kwargs,
|
208 |
+
)
|
209 |
+
|
210 |
+
def new_chat_template(self):
|
211 |
+
conv = get_conv_template(self.sft_format)
|
212 |
+
return conv
|
213 |
+
|
214 |
+
def format_messages(
|
215 |
+
self,
|
216 |
+
conversations: List[Dict[str, str]],
|
217 |
+
sft_format: str = "deepseek",
|
218 |
+
system_prompt: str = "",
|
219 |
+
):
|
220 |
+
"""
|
221 |
+
Applies the SFT template to conversation.
|
222 |
+
|
223 |
+
Args:
|
224 |
+
conversations (List[Dict]): A List of messages.
|
225 |
+
sft_format (str, optional): The format of the SFT template to use. Defaults to "deepseek".
|
226 |
+
system_prompt (str, optional): The system prompt to use in the SFT template. Defaults to "".
|
227 |
+
|
228 |
+
Returns:
|
229 |
+
sft_prompt (str): The formatted text.
|
230 |
+
"""
|
231 |
+
|
232 |
+
conv = get_conv_template(sft_format)
|
233 |
+
conv.set_system_message(system_prompt)
|
234 |
+
for message in conversations:
|
235 |
+
conv.append_message(message["role"], message["content"].strip())
|
236 |
+
sft_prompt = conv.get_prompt().strip()
|
237 |
+
|
238 |
+
return sft_prompt
|
239 |
+
|
240 |
+
def format_messages_v2(self, messages, pil_images, systems=None):
|
241 |
+
"""play the role of format_messages_v2 and get_images_info in the last version"""
|
242 |
+
tokenized_data = []
|
243 |
+
masked_tokenized_data = [] # labels
|
244 |
+
images_list = []
|
245 |
+
images_seq_mask = []
|
246 |
+
images_spatial_crop = []
|
247 |
+
num_image_tokens = []
|
248 |
+
|
249 |
+
image_index = 0
|
250 |
+
|
251 |
+
conv = get_conv_template(self.sft_format)
|
252 |
+
conv_system_message = conv.system_message
|
253 |
+
|
254 |
+
for idx, message in enumerate(messages):
|
255 |
+
if idx == 0:
|
256 |
+
tokenized_data += [self.bos_id]
|
257 |
+
masked_tokenized_data += [self.bos_id]
|
258 |
+
images_seq_mask += [False]
|
259 |
+
conv.system_message = conv_system_message
|
260 |
+
else:
|
261 |
+
conv.system_message = ''
|
262 |
+
|
263 |
+
if message['role'] == conv.roles[0] or message['role'] == "user":
|
264 |
+
conv.reset_message()
|
265 |
+
conv.append_message(conv.roles[0], str(message['content']).strip())
|
266 |
+
conv.append_message(conv.roles[1], '')
|
267 |
+
formatted_question = conv.get_prompt()
|
268 |
+
tokenized_str, images, seq_mask, spatial_crop, n_image_tokens = self.tokenize_with_images(
|
269 |
+
formatted_question,
|
270 |
+
pil_images[image_index: image_index + formatted_question.count(self.image_token)],
|
271 |
+
bos=False,
|
272 |
+
eos=False,
|
273 |
+
cropping=len(pil_images) <= 2
|
274 |
+
)
|
275 |
+
image_index += formatted_question.count(self.image_token)
|
276 |
+
|
277 |
+
tokenized_data += tokenized_str
|
278 |
+
if self.mask_prompt:
|
279 |
+
masked_tokenized_data += [self.ignore_id] * len(tokenized_str)
|
280 |
+
else:
|
281 |
+
masked_tokenized_data += tokenized_str
|
282 |
+
images_list += images
|
283 |
+
images_seq_mask += seq_mask
|
284 |
+
images_spatial_crop += spatial_crop
|
285 |
+
num_image_tokens += n_image_tokens
|
286 |
+
|
287 |
+
elif message['role'] == conv.roles[1] or message['role'] == "assistant":
|
288 |
+
formatted_answer = message['content'].strip()
|
289 |
+
assert formatted_answer.count(
|
290 |
+
self.image_token) == 0, f"there should be no {self.image_token} in the assistant's reply, but got {messages}"
|
291 |
+
tokenized_str, images, seq_mask, spatial_crop, n_image_tokens = self.tokenize_with_images(
|
292 |
+
formatted_answer,
|
293 |
+
[],
|
294 |
+
bos=False,
|
295 |
+
eos=True,
|
296 |
+
cropping=len(pil_images) <= 2)
|
297 |
+
|
298 |
+
tokenized_data += tokenized_str
|
299 |
+
masked_tokenized_data += tokenized_str
|
300 |
+
images_seq_mask += seq_mask
|
301 |
+
|
302 |
+
elif message['role'] == 'system' or message['role'] == 'deepseekapi-sys':
|
303 |
+
# 如果message里面有system,那就只允许出现在message的第一句,同时conv原本的system就会失效
|
304 |
+
assert idx == 0, 'system information should only exist in the begining of the conversation'
|
305 |
+
formatted_system = message['content'].strip()
|
306 |
+
tokenized_str = self.encode(formatted_system, bos=False, eos=False)
|
307 |
+
tokenized_data += tokenized_str
|
308 |
+
if self.mask_prompt:
|
309 |
+
masked_tokenized_data += [self.ignore_id] * len(tokenized_str)
|
310 |
+
else:
|
311 |
+
masked_tokenized_data += tokenized_str
|
312 |
+
seq_mask = [False] * len(tokenized_str)
|
313 |
+
images_seq_mask += seq_mask
|
314 |
+
|
315 |
+
else:
|
316 |
+
assert False, f"Unknown role: {message['role']}"
|
317 |
+
|
318 |
+
assert len(tokenized_data) == len(
|
319 |
+
images_seq_mask), f"format_messages_v2: tokenized_str's length {len(tokenized_str)} is not equal to imags_seq_mask's length {len(images_seq_mask)}"
|
320 |
+
assert len(images_spatial_crop) == len(num_image_tokens), f"image number should be compatible"
|
321 |
+
|
322 |
+
return tokenized_data, masked_tokenized_data, images_list, images_seq_mask, images_spatial_crop, num_image_tokens
|
323 |
+
|
324 |
+
def format_prompts(
|
325 |
+
self,
|
326 |
+
prompts: str,
|
327 |
+
sft_format: str = "deepseek",
|
328 |
+
system_prompt: str = "",
|
329 |
+
):
|
330 |
+
"""
|
331 |
+
Applies the SFT template to prompts.
|
332 |
+
|
333 |
+
Args:
|
334 |
+
prompts (str): the non-sft formatted prompt;
|
335 |
+
sft_format (str, optional): The format of the SFT template to use. Defaults to "deepseek".
|
336 |
+
system_prompt (str, optional): The system prompt to use in the SFT template. Defaults to "".
|
337 |
+
|
338 |
+
Returns:
|
339 |
+
sft_prompt (str): The formatted text.
|
340 |
+
"""
|
341 |
+
|
342 |
+
conv = get_conv_template(sft_format)
|
343 |
+
conv.set_system_message(system_prompt)
|
344 |
+
conv.append_message(conv.roles[0], prompts.strip())
|
345 |
+
conv.append_message(conv.roles[1], "")
|
346 |
+
|
347 |
+
sft_prompt = conv.get_prompt().strip()
|
348 |
+
|
349 |
+
return sft_prompt
|
350 |
+
|
351 |
+
@property
|
352 |
+
def bos_id(self):
|
353 |
+
return self.tokenizer.bos_token_id
|
354 |
+
|
355 |
+
@property
|
356 |
+
def eos_id(self):
|
357 |
+
return self.tokenizer.eos_token_id
|
358 |
+
|
359 |
+
@property
|
360 |
+
def pad_id(self):
|
361 |
+
return self.tokenizer.pad_token_id
|
362 |
+
|
363 |
+
def encode(self, text: str, bos: bool = True, eos: bool = False):
|
364 |
+
t = self.tokenizer.encode(text, add_special_tokens=False)
|
365 |
+
|
366 |
+
if bos:
|
367 |
+
t = [self.bos_id] + t
|
368 |
+
if eos:
|
369 |
+
t = t + [self.eos_id]
|
370 |
+
|
371 |
+
return t
|
372 |
+
|
373 |
+
def decode(self, t: List[int], **kwargs) -> str:
|
374 |
+
return self.tokenizer.decode(t, **kwargs)
|
375 |
+
|
376 |
+
def process_one(
|
377 |
+
self,
|
378 |
+
prompt: str = None,
|
379 |
+
conversations: List[Dict[str, str]] = None,
|
380 |
+
images: List[Image.Image] = None,
|
381 |
+
apply_sft_format: bool = False,
|
382 |
+
inference_mode: bool = True,
|
383 |
+
system_prompt: str = "",
|
384 |
+
**kwargs,
|
385 |
+
):
|
386 |
+
"""
|
387 |
+
|
388 |
+
Args:
|
389 |
+
prompt (str): the formatted prompt;
|
390 |
+
conversations (List[Dict]): conversations with a list of messages;
|
391 |
+
images (List[ImageType]): the list of images;
|
392 |
+
apply_sft_format (bool): if prompt is not None, then apply the SFT format to prompt;
|
393 |
+
if conversations is not None, then it will always apply the SFT format to conversations;
|
394 |
+
inference_mode (bool): if True, then remove the last eos token;
|
395 |
+
system_prompt (str): the system prompt;
|
396 |
+
**kwargs:
|
397 |
+
|
398 |
+
Returns:
|
399 |
+
outputs (BaseProcessorOutput): the output of the processor,
|
400 |
+
- input_ids (torch.LongTensor): [N + image tokens]
|
401 |
+
- target_ids (torch.LongTensor): [N + image tokens]
|
402 |
+
- images (torch.FloatTensor): [n_images, 3, H, W]
|
403 |
+
- image_id (int): the id of the image token
|
404 |
+
- num_image_tokens (List[int]): the number of image tokens
|
405 |
+
"""
|
406 |
+
|
407 |
+
assert (
|
408 |
+
prompt is None or conversations is None
|
409 |
+
), "prompt and conversations cannot be used at the same time."
|
410 |
+
|
411 |
+
if prompt is None:
|
412 |
+
# apply sft format
|
413 |
+
sft_format = self.format_messages(
|
414 |
+
conversations=conversations,
|
415 |
+
sft_format=self.sft_format,
|
416 |
+
system_prompt=system_prompt,
|
417 |
+
)
|
418 |
+
tokenized_str, masked_tokenized_str, images_list, images_seq_mask, images_spatial_crop, num_image_tokens = self.format_messages_v2(
|
419 |
+
conversations, images)
|
420 |
+
else:
|
421 |
+
if apply_sft_format:
|
422 |
+
sft_format = self.format_prompts(
|
423 |
+
prompts=prompt,
|
424 |
+
sft_format=self.sft_format,
|
425 |
+
system_prompt=system_prompt
|
426 |
+
)
|
427 |
+
else:
|
428 |
+
sft_format = prompt
|
429 |
+
tokenized_str, images_list, images_seq_mask, images_spatial_crop, num_image_tokens = self.tokenize_with_images(
|
430 |
+
sft_format, images, bos=True, eos=True, cropping=len(images) <= 2)
|
431 |
+
masked_tokenized_str = []
|
432 |
+
for token_index in tokenized_str:
|
433 |
+
if token_index != self.image_token_id:
|
434 |
+
masked_tokenized_str.append(token_index)
|
435 |
+
else:
|
436 |
+
masked_tokenized_str.append(self.ignore_id)
|
437 |
+
|
438 |
+
assert len(tokenized_str) == len(images_seq_mask) == len(masked_tokenized_str), \
|
439 |
+
(f"tokenized_str's length {len(tokenized_str)}, input_ids' length {len(masked_tokenized_str)}, "
|
440 |
+
f"imags_seq_mask's length {len(images_seq_mask)}, are not equal")
|
441 |
+
|
442 |
+
input_ids = torch.LongTensor(tokenized_str)
|
443 |
+
target_ids = torch.LongTensor(masked_tokenized_str)
|
444 |
+
images_seq_mask = torch.tensor(images_seq_mask, dtype=torch.bool)
|
445 |
+
|
446 |
+
# set input_ids < 0 | input_ids == self.image_token_id as ignore_id
|
447 |
+
target_ids[(input_ids < 0) | (input_ids == self.image_token_id)] = self.ignore_id
|
448 |
+
input_ids[input_ids < 0] = self.pad_id
|
449 |
+
|
450 |
+
if inference_mode:
|
451 |
+
# 去掉结尾的eos token
|
452 |
+
assert input_ids[-1] == self.eos_id
|
453 |
+
input_ids = input_ids[:-1]
|
454 |
+
target_ids = target_ids[:-1]
|
455 |
+
images_seq_mask = images_seq_mask[:-1]
|
456 |
+
|
457 |
+
if len(images_list) == 0:
|
458 |
+
images = torch.zeros((1, 3, self.image_size, self.image_size))
|
459 |
+
images_spatial_crop = torch.zeros((1, 2), dtype=torch.long)
|
460 |
+
else:
|
461 |
+
images = torch.stack(images_list, dim=0)
|
462 |
+
images_spatial_crop = torch.tensor(images_spatial_crop, dtype=torch.long)
|
463 |
+
|
464 |
+
prepare = VLChatProcessorOutput(
|
465 |
+
sft_format=sft_format,
|
466 |
+
input_ids=input_ids,
|
467 |
+
target_ids=target_ids,
|
468 |
+
images=images,
|
469 |
+
images_seq_mask=images_seq_mask,
|
470 |
+
images_spatial_crop=images_spatial_crop,
|
471 |
+
num_image_tokens=num_image_tokens
|
472 |
+
)
|
473 |
+
|
474 |
+
return prepare
|
475 |
+
|
476 |
+
def __call__(
|
477 |
+
self,
|
478 |
+
*,
|
479 |
+
prompt: str = None,
|
480 |
+
conversations: List[Dict[str, str]] = None,
|
481 |
+
images: List[Image.Image] = None,
|
482 |
+
apply_sft_format: bool = False,
|
483 |
+
force_batchify: bool = True,
|
484 |
+
inference_mode: bool = True,
|
485 |
+
system_prompt: str = "",
|
486 |
+
**kwargs,
|
487 |
+
):
|
488 |
+
"""
|
489 |
+
|
490 |
+
Args:
|
491 |
+
prompt (str): the formatted prompt;
|
492 |
+
conversations (List[Dict]): conversations with a list of messages;
|
493 |
+
images (List[ImageType]): the list of images;
|
494 |
+
apply_sft_format (bool): if prompt is not None, then apply the SFT format to prompt;
|
495 |
+
if conversations is not None, then it will always apply the SFT format to conversations;
|
496 |
+
force_batchify (bool): force batchify the inputs;
|
497 |
+
inference_mode (bool): if True, then remove the last eos token;
|
498 |
+
system_prompt (str): the system prompt;
|
499 |
+
**kwargs:
|
500 |
+
|
501 |
+
Returns:
|
502 |
+
outputs (BaseProcessorOutput): the output of the processor,
|
503 |
+
- input_ids (torch.LongTensor): [N + image tokens]
|
504 |
+
- images (torch.FloatTensor): [n_images, 3, H, W]
|
505 |
+
- image_id (int): the id of the image token
|
506 |
+
- num_image_tokens (List[int]): the number of image tokens
|
507 |
+
"""
|
508 |
+
|
509 |
+
prepare = self.process_one(
|
510 |
+
prompt=prompt,
|
511 |
+
conversations=conversations,
|
512 |
+
images=images,
|
513 |
+
apply_sft_format=apply_sft_format,
|
514 |
+
inference_mode=inference_mode,
|
515 |
+
system_prompt=system_prompt
|
516 |
+
)
|
517 |
+
|
518 |
+
if force_batchify:
|
519 |
+
prepare = self.batchify([prepare])
|
520 |
+
|
521 |
+
return prepare
|
522 |
+
|
523 |
+
def tokenize_with_images(
|
524 |
+
self,
|
525 |
+
conversation: str,
|
526 |
+
images: List[Image.Image],
|
527 |
+
bos: bool = True,
|
528 |
+
eos: bool = True,
|
529 |
+
cropping: bool = True,
|
530 |
+
):
|
531 |
+
"""Tokenize text with <image> tags."""
|
532 |
+
assert conversation.count(self.image_token) == len(images)
|
533 |
+
text_splits = conversation.split(self.image_token)
|
534 |
+
images_list, images_seq_mask, images_spatial_crop = [], [], []
|
535 |
+
num_image_tokens = []
|
536 |
+
tokenized_str = []
|
537 |
+
for text_sep, image in zip(text_splits, images):
|
538 |
+
"""encode text_sep"""
|
539 |
+
tokenized_sep = self.encode(text_sep, bos=False, eos=False)
|
540 |
+
tokenized_str += tokenized_sep
|
541 |
+
images_seq_mask += [False] * len(tokenized_sep)
|
542 |
+
|
543 |
+
"""select best resolution for anyres"""
|
544 |
+
if cropping:
|
545 |
+
best_width, best_height = select_best_resolution(image.size, self.candidate_resolutions)
|
546 |
+
else:
|
547 |
+
best_width, best_height = self.image_size, self.image_size
|
548 |
+
# print(image.size, (best_width, best_height)) # check the select_best_resolutions func
|
549 |
+
|
550 |
+
"""process the global view"""
|
551 |
+
global_view = ImageOps.pad(image, (self.image_size, self.image_size),
|
552 |
+
color=tuple(int(x * 255) for x in self.image_transform.mean))
|
553 |
+
images_list.append(self.image_transform(global_view))
|
554 |
+
|
555 |
+
"""process the local views"""
|
556 |
+
local_view = ImageOps.pad(image, (best_width, best_height),
|
557 |
+
color=tuple(int(x * 255) for x in self.image_transform.mean))
|
558 |
+
for i in range(0, best_height, self.image_size):
|
559 |
+
for j in range(0, best_width, self.image_size):
|
560 |
+
images_list.append(
|
561 |
+
self.image_transform(local_view.crop((j, i, j + self.image_size, i + self.image_size))))
|
562 |
+
|
563 |
+
"""record height / width crop num"""
|
564 |
+
num_width_tiles, num_height_tiles = best_width // self.image_size, best_height // self.image_size
|
565 |
+
images_spatial_crop.append([num_width_tiles, num_height_tiles])
|
566 |
+
|
567 |
+
"""add image tokens"""
|
568 |
+
h = w = math.ceil((self.image_size // self.patch_size) / self.downsample_ratio)
|
569 |
+
# global views tokens h * (w + 1), 1 is for line seperator
|
570 |
+
tokenized_image = [self.image_token_id] * h * (w + 1)
|
571 |
+
# add a seperator between global and local views
|
572 |
+
tokenized_image += [self.image_token_id]
|
573 |
+
# local views tokens, (num_height_tiles * h) * (num_width_tiles * w + 1)
|
574 |
+
tokenized_image += [self.image_token_id] * (num_height_tiles * h) * (num_width_tiles * w + 1)
|
575 |
+
|
576 |
+
tokenized_str += tokenized_image
|
577 |
+
images_seq_mask += [True] * len(tokenized_image)
|
578 |
+
num_image_tokens.append(len(tokenized_image))
|
579 |
+
# print(width_crop_num, height_crop_num, len(tokenized_image)) # test the correctness of the number of image-related tokens
|
580 |
+
|
581 |
+
"""process the last text split"""
|
582 |
+
tokenized_sep = self.encode(text_splits[-1], bos=False, eos=False)
|
583 |
+
tokenized_str += tokenized_sep
|
584 |
+
images_seq_mask += [False] * len(tokenized_sep)
|
585 |
+
|
586 |
+
"""add the bos and eos tokens"""
|
587 |
+
if bos:
|
588 |
+
tokenized_str = [self.bos_id] + tokenized_str
|
589 |
+
images_seq_mask = [False] + images_seq_mask
|
590 |
+
if eos:
|
591 |
+
tokenized_str = tokenized_str + [self.eos_id]
|
592 |
+
images_seq_mask = images_seq_mask + [False]
|
593 |
+
|
594 |
+
assert len(tokenized_str) == len(
|
595 |
+
images_seq_mask), f"tokenize_with_images func: tokenized_str's length {len(tokenized_str)} is not equal to imags_seq_mask's length {len(images_seq_mask)}"
|
596 |
+
|
597 |
+
return tokenized_str, images_list, images_seq_mask, images_spatial_crop, num_image_tokens
|
598 |
+
|
599 |
+
def batchify(
|
600 |
+
self,
|
601 |
+
sample_list: List[VLChatProcessorOutput],
|
602 |
+
padding: Literal["left", "right"] = "left"
|
603 |
+
) -> BatchCollateOutput:
|
604 |
+
"""
|
605 |
+
Preprocesses the inputs for multimodal inference.
|
606 |
+
|
607 |
+
Args:
|
608 |
+
sample_list (List[VLChatProcessorOutput]): A list of VLChatProcessorOutput.
|
609 |
+
padding (str): The padding method. Defaults to "left".
|
610 |
+
|
611 |
+
Returns:
|
612 |
+
BatchCollateOutput: A dictionary of the inputs to use for multimodal inference.
|
613 |
+
"""
|
614 |
+
|
615 |
+
batched_sft_format = [sample.sft_format for sample in sample_list]
|
616 |
+
batched_input_ids = [sample.input_ids for sample in sample_list]
|
617 |
+
batched_labels = [sample.target_ids for sample in sample_list]
|
618 |
+
batched_images_seq_mask = [sample["images_seq_mask"] for sample in sample_list]
|
619 |
+
seq_lens = [len(sample) for sample in sample_list]
|
620 |
+
|
621 |
+
"""padding input_ids and images_seq_mask"""
|
622 |
+
if padding == "left":
|
623 |
+
# the tokenizer is default to pad at left
|
624 |
+
## TODO, You're using a LlamaTokenizerFast tokenizer.
|
625 |
+
# Please note that with a fast tokenizer, using the `__call__` method is faster than
|
626 |
+
# using a method to encode the text followed by a call to the `pad` method to get a padded encoding.
|
627 |
+
padded_input_ids = self.tokenizer.pad({"input_ids": batched_input_ids})
|
628 |
+
batched_input_ids, batched_attention_mask = padded_input_ids["input_ids"], padded_input_ids[
|
629 |
+
"attention_mask"].bool()
|
630 |
+
batched_labels = self.tokenizer.pad({"input_ids": batched_labels})["input_ids"]
|
631 |
+
batched_labels[batched_labels == self.pad_id] = self.ignore_id # labels正常不会出现pad_id,无需额外保护
|
632 |
+
batched_images_seq_mask = self.tokenizer.pad({"input_ids": batched_images_seq_mask})["input_ids"]
|
633 |
+
batched_images_seq_mask[batched_images_seq_mask == self.pad_id] = False
|
634 |
+
else:
|
635 |
+
batched_input_ids = pad_sequence(batched_input_ids, batch_first=True, padding_value=self.pad_id)
|
636 |
+
batched_labels = pad_sequence(batched_labels, batch_first=True, padding_value=self.ignore_id)
|
637 |
+
batched_images_seq_mask = pad_sequence(batched_images_seq_mask, batch_first=True, padding_value=0)
|
638 |
+
batched_attention_mask = batched_input_ids != self.pad_id
|
639 |
+
|
640 |
+
"""padding images to max_patch_num"""
|
641 |
+
max_n_patches = max(sample["images"].shape[0] for sample in sample_list)
|
642 |
+
batched_images = []
|
643 |
+
for sample in sample_list:
|
644 |
+
images = sample["images"]
|
645 |
+
n_pads = max_n_patches - images.shape[0]
|
646 |
+
if n_pads > 0:
|
647 |
+
pad_images = torch.zeros((n_pads, *images.shape[1:]), dtype=images.dtype)
|
648 |
+
images = torch.cat([images, pad_images], dim=0)
|
649 |
+
batched_images.append(images)
|
650 |
+
batched_images = torch.stack(batched_images, dim=0)
|
651 |
+
|
652 |
+
"""padding images_spatial_crop to max_n_images"""
|
653 |
+
max_n_images = max(sample["images_spatial_crop"].shape[0] for sample in sample_list)
|
654 |
+
batched_images_spatial_crop = []
|
655 |
+
for sample in sample_list:
|
656 |
+
images_spatial_crop = sample["images_spatial_crop"]
|
657 |
+
n_pads = max_n_images - sample["images_spatial_crop"].shape[0]
|
658 |
+
if n_pads > 0:
|
659 |
+
pad_images_spatial_crop = torch.full((n_pads, 2), 0, dtype=images_spatial_crop.dtype)
|
660 |
+
images_spatial_crop = torch.cat([images_spatial_crop, pad_images_spatial_crop], dim=0)
|
661 |
+
batched_images_spatial_crop.append(images_spatial_crop)
|
662 |
+
batched_images_spatial_crop = torch.stack(batched_images_spatial_crop, dim=0)
|
663 |
+
|
664 |
+
batched_samples = BatchCollateOutput(
|
665 |
+
input_ids=batched_input_ids,
|
666 |
+
attention_mask=batched_attention_mask,
|
667 |
+
labels=batched_labels,
|
668 |
+
images=batched_images,
|
669 |
+
images_seq_mask=batched_images_seq_mask,
|
670 |
+
images_spatial_crop=batched_images_spatial_crop,
|
671 |
+
sft_format=batched_sft_format,
|
672 |
+
seq_lens=seq_lens
|
673 |
+
)
|
674 |
+
|
675 |
+
return batched_samples
|
siglip_vit.py
ADDED
@@ -0,0 +1,660 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py
|
2 |
+
from dataclasses import dataclass
|
3 |
+
import numpy as np
|
4 |
+
import torch
|
5 |
+
import torch.nn as nn
|
6 |
+
import torch.nn.functional as F
|
7 |
+
from typing import Final, Optional, Callable, Union, Tuple, List, Set, Dict, Type, Literal, Sequence
|
8 |
+
import math
|
9 |
+
import warnings
|
10 |
+
from timm.layers import (
|
11 |
+
PatchEmbed, Mlp, DropPath,
|
12 |
+
AttentionPoolLatent, PatchDropout, resample_abs_pos_embed, LayerType
|
13 |
+
)
|
14 |
+
from timm.models._manipulate import named_apply, checkpoint_seq, adapt_input_conv
|
15 |
+
from transformers.modeling_utils import is_flash_attn_2_available
|
16 |
+
from xformers.ops import memory_efficient_attention
|
17 |
+
from functools import partial
|
18 |
+
|
19 |
+
|
20 |
+
if is_flash_attn_2_available():
|
21 |
+
from flash_attn import flash_attn_qkvpacked_func
|
22 |
+
|
23 |
+
|
24 |
+
def _no_grad_trunc_normal_(tensor, mean, std, a, b):
|
25 |
+
# Cut & paste from PyTorch official master until it's in a few official releases - RW
|
26 |
+
# Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
|
27 |
+
def norm_cdf(x):
|
28 |
+
# Computes standard normal cumulative distribution function
|
29 |
+
return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
|
30 |
+
|
31 |
+
if (mean < a - 2 * std) or (mean > b + 2 * std):
|
32 |
+
warnings.warn(
|
33 |
+
"mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
|
34 |
+
"The distribution of values may be incorrect.",
|
35 |
+
stacklevel=2,
|
36 |
+
)
|
37 |
+
|
38 |
+
with torch.no_grad():
|
39 |
+
# Values are generated by using a truncated uniform distribution and
|
40 |
+
# then using the inverse CDF for the normal distribution.
|
41 |
+
# Get upper and lower cdf values
|
42 |
+
l = norm_cdf((a - mean) / std) # noqa: E741
|
43 |
+
u = norm_cdf((b - mean) / std)
|
44 |
+
|
45 |
+
# Uniformly fill tensor with values from [l, u], then translate to
|
46 |
+
# [2l-1, 2u-1].
|
47 |
+
tensor.uniform_(2 * l - 1, 2 * u - 1)
|
48 |
+
|
49 |
+
# Use inverse cdf transform for normal distribution to get truncated
|
50 |
+
# standard normal
|
51 |
+
tensor.erfinv_()
|
52 |
+
|
53 |
+
# Transform to proper mean, std
|
54 |
+
tensor.mul_(std * math.sqrt(2.0))
|
55 |
+
tensor.add_(mean)
|
56 |
+
|
57 |
+
# Clamp to ensure it's in the proper range
|
58 |
+
tensor.clamp_(min=a, max=b)
|
59 |
+
return tensor
|
60 |
+
|
61 |
+
|
62 |
+
def trunc_normal_(tensor, mean=0.0, std=1.0, a=-2.0, b=2.0):
|
63 |
+
# type: (torch.Tensor, float, float, float, float) -> torch.Tensor
|
64 |
+
r"""The original timm.models.layers.weight_init.trunc_normal_ can not handle bfloat16 yet, here we first
|
65 |
+
convert the tensor to float32, apply the trunc_normal_() in float32, and then convert it back to its orignal dtype.
|
66 |
+
Fills the input Tensor with values drawn from a truncated normal distribution. The values are effectively drawn
|
67 |
+
from the normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
|
68 |
+
with values outside :math:`[a, b]` redrawn until they are within
|
69 |
+
the bounds. The method used for generating the random values works
|
70 |
+
best when :math:`a \leq \text{mean} \leq b`.
|
71 |
+
Args:
|
72 |
+
tensor: an n-dimensional `torch.Tensor`
|
73 |
+
mean: the mean of the normal distribution
|
74 |
+
std: the standard deviation of the normal distribution
|
75 |
+
a: the minimum cutoff value
|
76 |
+
b: the maximum cutoff value
|
77 |
+
Examples:
|
78 |
+
>>> w = torch.empty(3, 5)
|
79 |
+
>>> nn.init.trunc_normal_(w)
|
80 |
+
"""
|
81 |
+
|
82 |
+
with torch.no_grad():
|
83 |
+
dtype = tensor.dtype
|
84 |
+
tensor_fp32 = tensor.float()
|
85 |
+
tensor_fp32 = _no_grad_trunc_normal_(tensor_fp32, mean, std, a, b)
|
86 |
+
tensor_dtype = tensor_fp32.to(dtype=dtype)
|
87 |
+
tensor.copy_(tensor_dtype)
|
88 |
+
|
89 |
+
|
90 |
+
def init_weights(self):
|
91 |
+
if self.pos_embed is not None:
|
92 |
+
trunc_normal_(self.pos_embed, std=self.pos_embed.shape[1] ** -0.5)
|
93 |
+
trunc_normal_(self.latent, std=self.latent_dim ** -0.5)
|
94 |
+
|
95 |
+
|
96 |
+
def init_weights_vit_timm(module: nn.Module, name: str = '') -> None:
|
97 |
+
""" ViT weight initialization, original timm impl (for reproducibility) """
|
98 |
+
if isinstance(module, nn.Linear):
|
99 |
+
trunc_normal_(module.weight, std=.02)
|
100 |
+
if module.bias is not None:
|
101 |
+
nn.init.zeros_(module.bias)
|
102 |
+
elif hasattr(module, 'init_weights'):
|
103 |
+
module.init_weights()
|
104 |
+
|
105 |
+
|
106 |
+
class Attention(nn.Module):
|
107 |
+
fused_attn: Final[bool]
|
108 |
+
|
109 |
+
def __init__(
|
110 |
+
self,
|
111 |
+
dim: int,
|
112 |
+
num_heads: int = 8,
|
113 |
+
qkv_bias: bool = False,
|
114 |
+
qk_norm: bool = False,
|
115 |
+
attn_drop: float = 0.,
|
116 |
+
proj_drop: float = 0.,
|
117 |
+
norm_layer: nn.Module = nn.LayerNorm,
|
118 |
+
deterministic: bool = False,
|
119 |
+
) -> None:
|
120 |
+
super().__init__()
|
121 |
+
assert dim % num_heads == 0, 'dim should be divisible by num_heads'
|
122 |
+
self.num_heads = num_heads
|
123 |
+
self.head_dim = dim // num_heads
|
124 |
+
self.scale = self.head_dim ** -0.5
|
125 |
+
self.qk_norm = qk_norm
|
126 |
+
self.fused_attn = True
|
127 |
+
self.deterministic = deterministic
|
128 |
+
|
129 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
130 |
+
self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
|
131 |
+
self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
|
132 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
133 |
+
self.proj = nn.Linear(dim, dim)
|
134 |
+
self.proj_drop = nn.Dropout(proj_drop) if proj_drop > 0. else nn.Identity()
|
135 |
+
|
136 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
137 |
+
B, N, C = x.shape
|
138 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim)
|
139 |
+
|
140 |
+
if not self.qk_norm:
|
141 |
+
if self.head_dim % 32 == 0 and is_flash_attn_2_available():
|
142 |
+
# flashattn must have head_dim as a multiple of 32
|
143 |
+
x = flash_attn_qkvpacked_func(qkv, dropout_p=self.attn_drop.p if self.training else 0.,
|
144 |
+
deterministic=self.deterministic)
|
145 |
+
else:
|
146 |
+
q, k, v = qkv.unbind(2)
|
147 |
+
x = memory_efficient_attention(q, k, v, p=self.attn_drop.p if self.training else 0.)
|
148 |
+
x = x.reshape(B, N, C)
|
149 |
+
x = self.proj(x)
|
150 |
+
x = self.proj_drop(x)
|
151 |
+
return x
|
152 |
+
|
153 |
+
qkv = qkv.permute(2, 0, 3, 1, 4)
|
154 |
+
q, k, v = qkv.unbind(0)
|
155 |
+
q, k = self.q_norm(q), self.k_norm(k)
|
156 |
+
|
157 |
+
if self.fused_attn:
|
158 |
+
with torch.backends.cuda.sdp_kernel(enable_math=False, enable_mem_efficient=False):
|
159 |
+
# 用上下文的方式强行使用fa
|
160 |
+
x = F.scaled_dot_product_attention(
|
161 |
+
q, k, v,
|
162 |
+
dropout_p=self.attn_drop.p if self.training else 0.,
|
163 |
+
)
|
164 |
+
else:
|
165 |
+
q = q * self.scale
|
166 |
+
attn = q @ k.transpose(-2, -1)
|
167 |
+
attn = attn.softmax(dim=-1)
|
168 |
+
attn = self.attn_drop(attn)
|
169 |
+
x = attn @ v
|
170 |
+
|
171 |
+
x = x.transpose(1, 2).reshape(B, N, C)
|
172 |
+
x = self.proj(x)
|
173 |
+
x = self.proj_drop(x)
|
174 |
+
return x
|
175 |
+
|
176 |
+
|
177 |
+
class LayerScale(nn.Module):
|
178 |
+
def __init__(
|
179 |
+
self,
|
180 |
+
dim: int,
|
181 |
+
init_values: float = 1e-5,
|
182 |
+
inplace: bool = False,
|
183 |
+
) -> None:
|
184 |
+
super().__init__()
|
185 |
+
self.inplace = inplace
|
186 |
+
self.gamma = nn.Parameter(init_values * torch.ones(dim))
|
187 |
+
|
188 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
189 |
+
return x.mul_(self.gamma) if self.inplace else x * self.gamma
|
190 |
+
|
191 |
+
|
192 |
+
class Block(nn.Module):
|
193 |
+
def __init__(
|
194 |
+
self,
|
195 |
+
dim: int,
|
196 |
+
num_heads: int,
|
197 |
+
mlp_ratio: float = 4.,
|
198 |
+
qkv_bias: bool = False,
|
199 |
+
qk_norm: bool = False,
|
200 |
+
proj_drop: float = 0.,
|
201 |
+
attn_drop: float = 0.,
|
202 |
+
init_values: Optional[float] = None,
|
203 |
+
drop_path: float = 0.,
|
204 |
+
act_layer: nn.Module = nn.GELU,
|
205 |
+
norm_layer: nn.Module = nn.LayerNorm,
|
206 |
+
mlp_layer: nn.Module = Mlp,
|
207 |
+
deterministic: bool = False,
|
208 |
+
) -> None:
|
209 |
+
super().__init__()
|
210 |
+
self.norm1 = norm_layer(dim)
|
211 |
+
self.attn = Attention(
|
212 |
+
dim,
|
213 |
+
num_heads=num_heads,
|
214 |
+
qkv_bias=qkv_bias,
|
215 |
+
qk_norm=qk_norm,
|
216 |
+
attn_drop=attn_drop,
|
217 |
+
proj_drop=proj_drop,
|
218 |
+
norm_layer=norm_layer,
|
219 |
+
deterministic=deterministic,
|
220 |
+
)
|
221 |
+
self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
|
222 |
+
self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
223 |
+
|
224 |
+
self.norm2 = norm_layer(dim)
|
225 |
+
self.mlp = mlp_layer(
|
226 |
+
in_features=dim,
|
227 |
+
hidden_features=int(dim * mlp_ratio),
|
228 |
+
act_layer=act_layer,
|
229 |
+
drop=proj_drop,
|
230 |
+
)
|
231 |
+
self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
|
232 |
+
self.drop_path2 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
233 |
+
|
234 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
235 |
+
x = x + self.drop_path1(self.ls1(self.attn(self.norm1(x))))
|
236 |
+
x = x + self.drop_path2(self.ls2(self.mlp(self.norm2(x))))
|
237 |
+
return x
|
238 |
+
|
239 |
+
|
240 |
+
class VisionTransformer(nn.Module):
|
241 |
+
""" Vision Transformer
|
242 |
+
|
243 |
+
A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale`
|
244 |
+
- https://arxiv.org/abs/2010.11929
|
245 |
+
"""
|
246 |
+
dynamic_img_size: Final[bool]
|
247 |
+
|
248 |
+
def __init__(
|
249 |
+
self,
|
250 |
+
img_size: Union[int, Tuple[int, int]] = 224,
|
251 |
+
patch_size: Union[int, Tuple[int, int]] = 16,
|
252 |
+
in_chans: int = 3,
|
253 |
+
num_classes: int = 1000,
|
254 |
+
global_pool: Literal['', 'avg', 'token', 'map'] = 'token',
|
255 |
+
embed_dim: int = 768,
|
256 |
+
depth: int = 12,
|
257 |
+
num_heads: int = 12,
|
258 |
+
mlp_ratio: float = 4.,
|
259 |
+
qkv_bias: bool = True,
|
260 |
+
qk_norm: bool = False,
|
261 |
+
init_values: Optional[float] = None,
|
262 |
+
class_token: bool = True,
|
263 |
+
no_embed_class: bool = False,
|
264 |
+
reg_tokens: int = 0,
|
265 |
+
pre_norm: bool = False,
|
266 |
+
fc_norm: Optional[bool] = None,
|
267 |
+
dynamic_img_size: bool = False,
|
268 |
+
dynamic_img_pad: bool = False,
|
269 |
+
drop_rate: float = 0.,
|
270 |
+
pos_drop_rate: float = 0.,
|
271 |
+
patch_drop_rate: float = 0.,
|
272 |
+
proj_drop_rate: float = 0.,
|
273 |
+
attn_drop_rate: float = 0.,
|
274 |
+
drop_path_rate: float = 0.,
|
275 |
+
weight_init: Literal['skip', 'jax', 'jax_nlhb', 'moco', ''] = '',
|
276 |
+
embed_layer: Callable = PatchEmbed,
|
277 |
+
norm_layer: Optional[LayerType] = None,
|
278 |
+
act_layer: Optional[LayerType] = None,
|
279 |
+
block_fn: Type[nn.Module] = Block,
|
280 |
+
mlp_layer: Type[nn.Module] = Mlp,
|
281 |
+
ignore_head: bool = False,
|
282 |
+
deterministic: bool = False,
|
283 |
+
num_recomputing_layers: int = 0
|
284 |
+
) -> None:
|
285 |
+
"""
|
286 |
+
Args:
|
287 |
+
img_size: Input image size.
|
288 |
+
patch_size: Patch size.
|
289 |
+
in_chans: Number of image input channels.
|
290 |
+
num_classes: Mumber of classes for classification head.
|
291 |
+
global_pool: Type of global pooling for final sequence (default: 'token').
|
292 |
+
embed_dim: Transformer embedding dimension.
|
293 |
+
depth: Depth of transformer.
|
294 |
+
num_heads: Number of attention heads.
|
295 |
+
mlp_ratio: Ratio of mlp hidden dim to embedding dim.
|
296 |
+
qkv_bias: Enable bias for qkv projections if True.
|
297 |
+
init_values: Layer-scale init values (layer-scale enabled if not None).
|
298 |
+
class_token: Use class token.
|
299 |
+
no_embed_class: Don't include position embeddings for class (or reg) tokens.
|
300 |
+
reg_tokens: Number of register tokens.
|
301 |
+
fc_norm: Pre head norm after pool (instead of before), if None, enabled when global_pool == 'avg'.
|
302 |
+
drop_rate: Head dropout rate.
|
303 |
+
pos_drop_rate: Position embedding dropout rate.
|
304 |
+
attn_drop_rate: Attention dropout rate.
|
305 |
+
drop_path_rate: Stochastic depth rate.
|
306 |
+
weight_init: Weight initialization scheme.
|
307 |
+
embed_layer: Patch embedding layer.
|
308 |
+
norm_layer: Normalization layer.
|
309 |
+
act_layer: MLP activation layer.
|
310 |
+
block_fn: Transformer block layer.
|
311 |
+
"""
|
312 |
+
super().__init__()
|
313 |
+
assert global_pool in ('', 'avg', 'token', 'map')
|
314 |
+
assert class_token or global_pool != 'token'
|
315 |
+
use_fc_norm = global_pool == 'avg' if fc_norm is None else fc_norm
|
316 |
+
# norm_layer = get_norm_layer(norm_layer) or partial(nn.LayerNorm, eps=1e-6)
|
317 |
+
# act_layer = get_act_layer(act_layer) or nn.GELU
|
318 |
+
norm_layer = partial(nn.LayerNorm, eps=1e-6)
|
319 |
+
# siglip use PytorchGELUTanh() rather than the vanilla nn.GELU()
|
320 |
+
# https://github.com/huggingface/transformers/blob/78b2929c0554b79e0489b451ce4ece14d265ead2/src/transformers/models/siglip/configuration_siglip.py#L191
|
321 |
+
act_layer = partial(nn.GELU, approximate='tanh')
|
322 |
+
|
323 |
+
self.num_classes = num_classes
|
324 |
+
self.global_pool = global_pool
|
325 |
+
self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
|
326 |
+
self.num_prefix_tokens = 1 if class_token else 0
|
327 |
+
self.num_prefix_tokens += reg_tokens
|
328 |
+
self.num_reg_tokens = reg_tokens
|
329 |
+
self.has_class_token = class_token
|
330 |
+
self.no_embed_class = no_embed_class # don't embed prefix positions (includes reg)
|
331 |
+
self.dynamic_img_size = dynamic_img_size
|
332 |
+
self.grad_checkpointing = False
|
333 |
+
self.ignore_head = ignore_head
|
334 |
+
self.num_recomputing_layers = num_recomputing_layers
|
335 |
+
|
336 |
+
embed_args = {}
|
337 |
+
if dynamic_img_size:
|
338 |
+
# flatten deferred until after pos embed
|
339 |
+
embed_args.update(dict(strict_img_size=False, output_fmt='NHWC'))
|
340 |
+
self.patch_embed = embed_layer(
|
341 |
+
img_size=img_size,
|
342 |
+
patch_size=patch_size,
|
343 |
+
in_chans=in_chans,
|
344 |
+
embed_dim=embed_dim,
|
345 |
+
bias=not pre_norm, # disable bias if pre-norm is used (e.g. CLIP)
|
346 |
+
dynamic_img_pad=dynamic_img_pad,
|
347 |
+
**embed_args,
|
348 |
+
)
|
349 |
+
num_patches = self.patch_embed.num_patches
|
350 |
+
|
351 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) if class_token else None
|
352 |
+
self.reg_token = nn.Parameter(torch.zeros(1, reg_tokens, embed_dim)) if reg_tokens else None
|
353 |
+
embed_len = num_patches if no_embed_class else num_patches + self.num_prefix_tokens
|
354 |
+
self.pos_embed = nn.Parameter(torch.randn(1, embed_len, embed_dim) * .02)
|
355 |
+
self.pos_drop = nn.Dropout(p=pos_drop_rate)
|
356 |
+
if patch_drop_rate > 0:
|
357 |
+
self.patch_drop = PatchDropout(
|
358 |
+
patch_drop_rate,
|
359 |
+
num_prefix_tokens=self.num_prefix_tokens,
|
360 |
+
)
|
361 |
+
else:
|
362 |
+
self.patch_drop = nn.Identity()
|
363 |
+
self.norm_pre = norm_layer(embed_dim) if pre_norm else nn.Identity()
|
364 |
+
|
365 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
|
366 |
+
self.blocks = nn.Sequential(*[
|
367 |
+
block_fn(
|
368 |
+
dim=embed_dim,
|
369 |
+
num_heads=num_heads,
|
370 |
+
mlp_ratio=mlp_ratio,
|
371 |
+
qkv_bias=qkv_bias,
|
372 |
+
qk_norm=qk_norm,
|
373 |
+
init_values=init_values,
|
374 |
+
proj_drop=proj_drop_rate,
|
375 |
+
attn_drop=attn_drop_rate,
|
376 |
+
drop_path=dpr[i],
|
377 |
+
norm_layer=norm_layer,
|
378 |
+
act_layer=act_layer,
|
379 |
+
mlp_layer=mlp_layer,
|
380 |
+
deterministic=deterministic,
|
381 |
+
)
|
382 |
+
for i in range(depth)])
|
383 |
+
self.norm = norm_layer(embed_dim) if not use_fc_norm else nn.Identity()
|
384 |
+
|
385 |
+
# Classifier Head
|
386 |
+
if global_pool == 'map':
|
387 |
+
AttentionPoolLatent.init_weights = init_weights
|
388 |
+
self.attn_pool = AttentionPoolLatent(
|
389 |
+
self.embed_dim,
|
390 |
+
num_heads=num_heads,
|
391 |
+
mlp_ratio=mlp_ratio,
|
392 |
+
norm_layer=norm_layer,
|
393 |
+
)
|
394 |
+
else:
|
395 |
+
self.attn_pool = None
|
396 |
+
self.fc_norm = norm_layer(embed_dim) if use_fc_norm else nn.Identity()
|
397 |
+
self.head_drop = nn.Dropout(drop_rate)
|
398 |
+
self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
|
399 |
+
|
400 |
+
if weight_init != 'skip':
|
401 |
+
self.init_weights(weight_init)
|
402 |
+
|
403 |
+
def init_weights(self, mode: Literal['jax', 'jax_nlhb', 'moco', ''] = '') -> None:
|
404 |
+
assert mode in ('jax', 'jax_nlhb', 'moco', '')
|
405 |
+
head_bias = -math.log(self.num_classes) if 'nlhb' in mode else 0.
|
406 |
+
trunc_normal_(self.pos_embed, std=.02)
|
407 |
+
if self.cls_token is not None:
|
408 |
+
nn.init.normal_(self.cls_token, std=1e-6)
|
409 |
+
named_apply(init_weights_vit_timm, self)
|
410 |
+
|
411 |
+
@torch.jit.ignore
|
412 |
+
def no_weight_decay(self) -> Set:
|
413 |
+
return {'pos_embed', 'cls_token', 'dist_token'}
|
414 |
+
|
415 |
+
@torch.jit.ignore
|
416 |
+
def group_matcher(self, coarse: bool = False) -> Dict:
|
417 |
+
return dict(
|
418 |
+
stem=r'^cls_token|pos_embed|patch_embed', # stem and embed
|
419 |
+
blocks=[(r'^blocks\.(\d+)', None), (r'^norm', (99999,))]
|
420 |
+
)
|
421 |
+
|
422 |
+
@torch.jit.ignore
|
423 |
+
def set_grad_checkpointing(self, enable: bool = True) -> None:
|
424 |
+
self.grad_checkpointing = enable
|
425 |
+
|
426 |
+
@torch.jit.ignore
|
427 |
+
def get_classifier(self) -> nn.Module:
|
428 |
+
return self.head
|
429 |
+
|
430 |
+
def reset_classifier(self, num_classes: int, global_pool=None) -> None:
|
431 |
+
self.num_classes = num_classes
|
432 |
+
if global_pool is not None:
|
433 |
+
assert global_pool in ('', 'avg', 'token', 'map')
|
434 |
+
if global_pool == 'map' and self.attn_pool is None:
|
435 |
+
assert False, "Cannot currently add attention pooling in reset_classifier()."
|
436 |
+
elif global_pool != 'map ' and self.attn_pool is not None:
|
437 |
+
self.attn_pool = None # remove attention pooling
|
438 |
+
self.global_pool = global_pool
|
439 |
+
self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
|
440 |
+
|
441 |
+
def _pos_embed(self, x: torch.Tensor) -> torch.Tensor:
|
442 |
+
if self.dynamic_img_size:
|
443 |
+
B, H, W, C = x.shape
|
444 |
+
pos_embed = resample_abs_pos_embed(
|
445 |
+
self.pos_embed,
|
446 |
+
(H, W),
|
447 |
+
num_prefix_tokens=0 if self.no_embed_class else self.num_prefix_tokens,
|
448 |
+
)
|
449 |
+
x = x.view(B, -1, C)
|
450 |
+
else:
|
451 |
+
pos_embed = self.pos_embed
|
452 |
+
|
453 |
+
to_cat = []
|
454 |
+
if self.cls_token is not None:
|
455 |
+
to_cat.append(self.cls_token.expand(x.shape[0], -1, -1))
|
456 |
+
if self.reg_token is not None:
|
457 |
+
to_cat.append(self.reg_token.expand(x.shape[0], -1, -1))
|
458 |
+
|
459 |
+
if self.no_embed_class:
|
460 |
+
# deit-3, updated JAX (big vision)
|
461 |
+
# position embedding does not overlap with class token, add then concat
|
462 |
+
x = x + pos_embed
|
463 |
+
if to_cat:
|
464 |
+
x = torch.cat(to_cat + [x], dim=1)
|
465 |
+
else:
|
466 |
+
# original timm, JAX, and deit vit impl
|
467 |
+
# pos_embed has entry for class token, concat then add
|
468 |
+
if to_cat:
|
469 |
+
x = torch.cat(to_cat + [x], dim=1)
|
470 |
+
x = x + pos_embed
|
471 |
+
|
472 |
+
return self.pos_drop(x)
|
473 |
+
|
474 |
+
def _intermediate_layers(
|
475 |
+
self,
|
476 |
+
x: torch.Tensor,
|
477 |
+
n: Union[int, Sequence] = 1,
|
478 |
+
) -> List[torch.Tensor]:
|
479 |
+
outputs, num_blocks = [], len(self.blocks)
|
480 |
+
take_indices = set(range(num_blocks - n, num_blocks) if isinstance(n, int) else n)
|
481 |
+
|
482 |
+
# forward pass
|
483 |
+
x = self.patch_embed(x)
|
484 |
+
x = self._pos_embed(x)
|
485 |
+
x = self.patch_drop(x)
|
486 |
+
x = self.norm_pre(x)
|
487 |
+
for i, blk in enumerate(self.blocks):
|
488 |
+
x = blk(x)
|
489 |
+
if i in take_indices:
|
490 |
+
outputs.append(x)
|
491 |
+
|
492 |
+
return outputs
|
493 |
+
|
494 |
+
def get_intermediate_layers(
|
495 |
+
self,
|
496 |
+
x: torch.Tensor,
|
497 |
+
n: Union[int, Sequence] = 1,
|
498 |
+
reshape: bool = False,
|
499 |
+
return_prefix_tokens: bool = False,
|
500 |
+
norm: bool = False,
|
501 |
+
) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]:
|
502 |
+
""" Intermediate layer accessor (NOTE: This is a WIP experiment).
|
503 |
+
Inspired by DINO / DINOv2 interface
|
504 |
+
"""
|
505 |
+
# take last n blocks if n is an int, if in is a sequence, select by matching indices
|
506 |
+
outputs = self._intermediate_layers(x, n)
|
507 |
+
if norm:
|
508 |
+
outputs = [self.norm(out) for out in outputs]
|
509 |
+
prefix_tokens = [out[:, 0:self.num_prefix_tokens] for out in outputs]
|
510 |
+
outputs = [out[:, self.num_prefix_tokens:] for out in outputs]
|
511 |
+
|
512 |
+
if reshape:
|
513 |
+
grid_size = self.patch_embed.grid_size
|
514 |
+
outputs = [
|
515 |
+
out.reshape(x.shape[0], grid_size[0], grid_size[1], -1).permute(0, 3, 1, 2).contiguous()
|
516 |
+
for out in outputs
|
517 |
+
]
|
518 |
+
|
519 |
+
if return_prefix_tokens:
|
520 |
+
return tuple(zip(outputs, prefix_tokens))
|
521 |
+
return tuple(outputs)
|
522 |
+
|
523 |
+
def forward_features(self, x: torch.Tensor) -> torch.Tensor:
|
524 |
+
if getattr(self, "is_first_stage", True):
|
525 |
+
x = self.patch_embed(x)
|
526 |
+
x = self._pos_embed(x)
|
527 |
+
x = self.patch_drop(x)
|
528 |
+
x = self.norm_pre(x)
|
529 |
+
if self.grad_checkpointing and not torch.jit.is_scripting():
|
530 |
+
skip_last = max(1, len(self.blocks) - self.num_recomputing_layers)
|
531 |
+
x = checkpoint_seq(self.blocks, x, skip_last=skip_last)
|
532 |
+
else:
|
533 |
+
x = self.blocks(x)
|
534 |
+
if getattr(self, "is_last_stage", True):
|
535 |
+
x = self.norm(x)
|
536 |
+
return x
|
537 |
+
|
538 |
+
def forward_head(self, x: torch.Tensor, pre_logits: bool = False) -> torch.Tensor:
|
539 |
+
if not getattr(self, "is_last_stage", True):
|
540 |
+
return x
|
541 |
+
if self.attn_pool is not None:
|
542 |
+
x = self.attn_pool(x)
|
543 |
+
elif self.global_pool == 'avg':
|
544 |
+
x = x[:, self.num_prefix_tokens:].mean(dim=1)
|
545 |
+
elif self.global_pool:
|
546 |
+
x = x[:, 0] # class token
|
547 |
+
x = self.fc_norm(x)
|
548 |
+
x = self.head_drop(x)
|
549 |
+
return x if pre_logits else self.head(x)
|
550 |
+
|
551 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
552 |
+
x = self.forward_features(x)
|
553 |
+
if not self.ignore_head:
|
554 |
+
x = self.forward_head(x)
|
555 |
+
return x
|
556 |
+
|
557 |
+
def to_pipeline(self, pp_size, pp_rank, pp_splits: Optional[List[int]] = None):
|
558 |
+
self.is_first_stage = pp_rank == 0
|
559 |
+
self.is_last_stage = pp_rank == pp_size - 1
|
560 |
+
if not self.is_first_stage and hasattr(self, "patch_embed"):
|
561 |
+
del self.patch_embed, self.cls_token, self.reg_token, self.pos_embed, self.pos_drop, self.patch_drop, self.norm_pre
|
562 |
+
if not self.is_last_stage and hasattr(self, "norm"):
|
563 |
+
del self.norm, self.attn_pool, self.fc_norm, self.head_drop, self.head
|
564 |
+
if pp_splits is not None:
|
565 |
+
assert len(self.blocks) == sum(pp_splits)
|
566 |
+
splits = np.cumsum([0] + pp_splits)
|
567 |
+
self.blocks = self.blocks[splits[pp_rank]:splits[pp_rank + 1]]
|
568 |
+
return self
|
569 |
+
|
570 |
+
|
571 |
+
@dataclass
|
572 |
+
class SigLIPVisionCfg:
|
573 |
+
width: int = 1152
|
574 |
+
layers: Union[Tuple[int, int, int, int], int] = 27
|
575 |
+
heads: int = 16
|
576 |
+
patch_size: int = 14
|
577 |
+
image_size: Union[Tuple[int, int], int] = 336
|
578 |
+
global_pool: str = "map"
|
579 |
+
mlp_ratio: float = 3.7362
|
580 |
+
class_token: bool = False
|
581 |
+
num_classes: int = 0
|
582 |
+
use_checkpoint: bool = False
|
583 |
+
|
584 |
+
|
585 |
+
SigLIP_MODEL_CONFIG = {
|
586 |
+
"siglip_so400m_patch14_384": {
|
587 |
+
"image_size": 384,
|
588 |
+
"patch_size": 14,
|
589 |
+
"width": 1152,
|
590 |
+
"layers": 27,
|
591 |
+
"heads": 16,
|
592 |
+
"mlp_ratio": 3.7362,
|
593 |
+
"global_pool": "map",
|
594 |
+
"use_checkpoint": False
|
595 |
+
},
|
596 |
+
|
597 |
+
"siglip_so400m_patch14_224": {
|
598 |
+
"image_size": 224,
|
599 |
+
"patch_size": 14,
|
600 |
+
"width": 1152,
|
601 |
+
"layers": 27,
|
602 |
+
"heads": 16,
|
603 |
+
"mlp_ratio": 3.7362,
|
604 |
+
"global_pool": "map",
|
605 |
+
"use_checkpoint": False
|
606 |
+
},
|
607 |
+
|
608 |
+
"siglip_large_patch16_384": {
|
609 |
+
"image_size": 384,
|
610 |
+
"patch_size": 16,
|
611 |
+
"width": 1024,
|
612 |
+
"layers": 24,
|
613 |
+
"heads": 16,
|
614 |
+
"mlp_ratio": 4,
|
615 |
+
"global_pool": "map",
|
616 |
+
"use_checkpoint": False
|
617 |
+
}
|
618 |
+
}
|
619 |
+
|
620 |
+
|
621 |
+
def create_siglip_vit(
|
622 |
+
model_name: str = "siglip_so400m_patch14_384",
|
623 |
+
image_size: int = 384,
|
624 |
+
select_layer: int = -1,
|
625 |
+
ckpt_path: str = "",
|
626 |
+
**kwargs
|
627 |
+
):
|
628 |
+
assert model_name in SigLIP_MODEL_CONFIG.keys(), f"model name should be in {SigLIP_MODEL_CONFIG.keys()}"
|
629 |
+
|
630 |
+
vision_cfg = SigLIPVisionCfg(**SigLIP_MODEL_CONFIG[model_name])
|
631 |
+
|
632 |
+
if select_layer <= 0:
|
633 |
+
layers = min(vision_cfg.layers, vision_cfg.layers + select_layer + 1)
|
634 |
+
else:
|
635 |
+
layers = min(vision_cfg.layers, select_layer)
|
636 |
+
|
637 |
+
model = VisionTransformer(
|
638 |
+
img_size=image_size,
|
639 |
+
patch_size=vision_cfg.patch_size,
|
640 |
+
embed_dim=vision_cfg.width,
|
641 |
+
depth=layers,
|
642 |
+
num_heads=vision_cfg.heads,
|
643 |
+
mlp_ratio=vision_cfg.mlp_ratio,
|
644 |
+
class_token=vision_cfg.class_token,
|
645 |
+
global_pool=vision_cfg.global_pool,
|
646 |
+
ignore_head=kwargs.get("ignore_head", True),
|
647 |
+
weight_init=kwargs.get("weight_init", "skip"),
|
648 |
+
num_classes=0,
|
649 |
+
deterministic=kwargs.get("deterministic", False),
|
650 |
+
num_recomputing_layers=kwargs.get("num_recomputing_layers", 0)
|
651 |
+
)
|
652 |
+
|
653 |
+
if ckpt_path:
|
654 |
+
state_dict = torch.load(ckpt_path, map_location="cpu")
|
655 |
+
|
656 |
+
incompatible_keys = model.load_state_dict(state_dict, strict=False)
|
657 |
+
print(f"SigLIP-ViT restores from {ckpt_path},\n"
|
658 |
+
f"\tincompatible_keys:', {incompatible_keys}.")
|
659 |
+
|
660 |
+
return model
|