ubermensch1218 commited on
Commit
5df558f
·
verified ·
1 Parent(s): 479741c

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "UnlimitedOCRForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "modeling_unlimitedocr.UnlimitedOCRConfig",
9
+ "AutoModel": "modeling_unlimitedocr.UnlimitedOCRForCausalLM"
10
+ },
11
+ "aux_loss_alpha": 0.001,
12
+ "bos_token_id": 0,
13
+ "candidate_resolutions": [
14
+ [
15
+ 1024,
16
+ 1024
17
+ ]
18
+ ],
19
+ "dtype": "bfloat16",
20
+ "eos_token_id": 1,
21
+ "ep_size": 1,
22
+ "first_k_dense_replace": 1,
23
+ "global_view_pos": "head",
24
+ "hidden_act": "silu",
25
+ "hidden_size": 1280,
26
+ "initializer_range": 0.02,
27
+ "intermediate_size": 6848,
28
+ "kv_lora_rank": null,
29
+ "language_config": {
30
+ "architectures": [
31
+ "DeepseekOCRForCausalLM"
32
+ ],
33
+ "auto_map": {
34
+ "AutoConfig": "configuration_deepseekv2.DeepseekV2Config",
35
+ "AutoModel": "modeling_deepseek.DeepseekV2Model",
36
+ "AutoModelForCausalLM": "modeling_deepseek.DeepseekV2ForCausalLM"
37
+ },
38
+ "bos_token_id": 0,
39
+ "eos_token_id": 1,
40
+ "first_k_dense_replace": 1,
41
+ "hidden_size": 1280,
42
+ "intermediate_size": 6848,
43
+ "kv_lora_rank": null,
44
+ "lm_head": true,
45
+ "max_position_embeddings": 32768,
46
+ "moe_intermediate_size": 896,
47
+ "n_group": 1,
48
+ "n_routed_experts": 72,
49
+ "n_shared_experts": 2,
50
+ "num_attention_heads": 10,
51
+ "num_experts_per_tok": 6,
52
+ "num_hidden_layers": 12,
53
+ "num_key_value_heads": 10,
54
+ "q_lora_rank": null,
55
+ "qk_nope_head_dim": 0,
56
+ "qk_rope_head_dim": 0,
57
+ "rm_head": false,
58
+ "sliding_window_size": 128,
59
+ "topk_group": 1,
60
+ "topk_method": "greedy",
61
+ "torch_dtype": "bfloat16",
62
+ "use_mla": false,
63
+ "v_head_dim": 128,
64
+ "vocab_size": 129280
65
+ },
66
+ "lm_head": true,
67
+ "max_position_embeddings": 32768,
68
+ "model_type": "unlimited-ocr",
69
+ "moe_intermediate_size": 896,
70
+ "moe_layer_freq": 1,
71
+ "n_group": 1,
72
+ "n_routed_experts": 72,
73
+ "n_shared_experts": 2,
74
+ "norm_topk_prob": false,
75
+ "num_attention_heads": 10,
76
+ "num_experts_per_tok": 6,
77
+ "num_hidden_layers": 12,
78
+ "num_key_value_heads": 10,
79
+ "pretraining_tp": 1,
80
+ "projector_config": {
81
+ "input_dim": 2048,
82
+ "model_type": "mlp_projector",
83
+ "n_embed": 1280,
84
+ "projector_type": "linear"
85
+ },
86
+ "q_lora_rank": null,
87
+ "qk_nope_head_dim": 0,
88
+ "qk_rope_head_dim": 0,
89
+ "rm_head": false,
90
+ "rms_norm_eps": 1e-06,
91
+ "rope_scaling": null,
92
+ "rope_theta": 10000.0,
93
+ "routed_scaling_factor": 1.0,
94
+ "rswa_window": 128,
95
+ "scoring_func": "softmax",
96
+ "seq_aux": true,
97
+ "sliding_window": 128,
98
+ "sliding_window_size": 128,
99
+ "tie_word_embeddings": false,
100
+ "tile_tag": "2D",
101
+ "topk_group": 1,
102
+ "topk_method": "greedy",
103
+ "transformers_version": "4.57.1",
104
+ "use_cache": false,
105
+ "use_mla": false,
106
+ "v_head_dim": 128,
107
+ "vision_config": {
108
+ "image_size": 1024,
109
+ "mlp_ratio": 3.7362,
110
+ "model_name": "deeplip_b_l",
111
+ "model_type": "vision",
112
+ "width": {
113
+ "clip-l-14-224": {
114
+ "heads": 16,
115
+ "image_size": 224,
116
+ "layers": 24,
117
+ "patch_size": 14,
118
+ "width": 1024
119
+ },
120
+ "sam_vit_b": {
121
+ "downsample_channels": [
122
+ 512,
123
+ 1024
124
+ ],
125
+ "global_attn_indexes": [
126
+ 2,
127
+ 5,
128
+ 8,
129
+ 11
130
+ ],
131
+ "heads": 12,
132
+ "layers": 12,
133
+ "width": 768
134
+ }
135
+ }
136
+ },
137
+ "vocab_size": 129280
138
+ }
configuration_deepseek_v2.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ sliding_window=None,
161
+ **kwargs,
162
+ ):
163
+ self.vocab_size = vocab_size
164
+ self.max_position_embeddings = max_position_embeddings
165
+ self.hidden_size = hidden_size
166
+ self.intermediate_size = intermediate_size
167
+ self.moe_intermediate_size = moe_intermediate_size
168
+ self.num_hidden_layers = num_hidden_layers
169
+ self.num_attention_heads = num_attention_heads
170
+ self.n_shared_experts = n_shared_experts
171
+ self.n_routed_experts = n_routed_experts
172
+ self.ep_size = ep_size
173
+ self.routed_scaling_factor = routed_scaling_factor
174
+ self.kv_lora_rank = kv_lora_rank
175
+ self.q_lora_rank = q_lora_rank
176
+ self.qk_rope_head_dim = qk_rope_head_dim
177
+ self.v_head_dim = v_head_dim
178
+ self.qk_nope_head_dim = qk_nope_head_dim
179
+ self.topk_method = topk_method
180
+ self.n_group = n_group
181
+ self.topk_group = topk_group
182
+ self.num_experts_per_tok = num_experts_per_tok
183
+ self.moe_layer_freq = moe_layer_freq
184
+ self.first_k_dense_replace = first_k_dense_replace
185
+ self.norm_topk_prob = norm_topk_prob
186
+ self.scoring_func = scoring_func
187
+ self.aux_loss_alpha = aux_loss_alpha
188
+ self.seq_aux = seq_aux
189
+ # for backward compatibility
190
+ if num_key_value_heads is None:
191
+ num_key_value_heads = num_attention_heads
192
+
193
+ self.num_key_value_heads = num_key_value_heads
194
+ self.hidden_act = hidden_act
195
+ self.initializer_range = initializer_range
196
+ self.rms_norm_eps = float(rms_norm_eps)
197
+ self.pretraining_tp = pretraining_tp
198
+ self.use_cache = use_cache
199
+ self.rope_theta = rope_theta
200
+ self.rope_scaling = rope_scaling
201
+ self.attention_bias = attention_bias
202
+ self.attention_dropout = attention_dropout
203
+ self.use_mla = use_mla
204
+ self.sliding_window = sliding_window
205
+
206
+ super().__init__(
207
+ pad_token_id=pad_token_id,
208
+ bos_token_id=bos_token_id,
209
+ eos_token_id=eos_token_id,
210
+ tie_word_embeddings=tie_word_embeddings,
211
+ **kwargs,
212
+ )
conversation.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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="deepseekv2",
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="",
220
+ sep2="<|end▁of▁sentence|>",
221
+ stop_token_ids=[100001],
222
+ stop_str=["User:", "<|end▁of▁sentence|>"]
223
+ )
224
+ )
225
+
226
+
227
+ register_conv_template(
228
+ Conversation(
229
+ name="plain",
230
+ system_template="",
231
+ system_message="",
232
+ roles=("", ""),
233
+ messages=(),
234
+ offset=0,
235
+ sep_style=SeparatorStyle.PLAIN,
236
+ sep="",
237
+ sep2="",
238
+ stop_token_ids=[100001],
239
+ stop_str=['</s>'],
240
+ )
241
+ )
242
+
243
+
244
+ register_conv_template(
245
+ Conversation(
246
+ name="alignment",
247
+ system_template="",
248
+ system_message="",
249
+ roles=("", ""),
250
+ messages=(),
251
+ offset=0,
252
+ sep_style=SeparatorStyle.ALIGNMENT,
253
+ sep="",
254
+ sep2="",
255
+ stop_token_ids=[100001],
256
+ stop_str=['</s>'],
257
+ )
258
+ )
259
+
260
+
261
+ if __name__ == "__main__":
262
+ print("deepseek template:")
263
+ conv = get_conv_template("deepseek")
264
+ conv.append_message(conv.roles[0], "Hello!")
265
+ conv.append_message(conv.roles[1], "Hi! This is Tony.")
266
+ conv.append_message(conv.roles[0], "Who are you?")
267
+ conv.append_message(conv.roles[1], "I am a helpful assistant.")
268
+ conv.append_message(conv.roles[0], "How are you?")
269
+ conv.append_message(conv.roles[1], None)
270
+ print(conv.get_prompt())
271
+
272
+ print("deepseekv2 template:")
273
+ conv = get_conv_template("deepseekv2")
274
+ conv.append_message(conv.roles[0], "Hello!")
275
+ conv.append_message(conv.roles[1], "Hi! This is Tony.")
276
+ conv.append_message(conv.roles[0], "Who are you?")
277
+ conv.append_message(conv.roles[1], "I am a helpful assistant.")
278
+ conv.append_message(conv.roles[0], "How are you?")
279
+ conv.append_message(conv.roles[1], None)
280
+ print(conv.get_prompt())
deepencoder.py ADDED
@@ -0,0 +1,1058 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import torch
3
+ import torch.nn.functional as F
4
+ import copy
5
+
6
+ from contextlib import nullcontext
7
+ import math
8
+ from typing import Optional, Tuple
9
+ # from megatron.model import LayerNorm
10
+
11
+ from einops import rearrange
12
+ from easydict import EasyDict as adict
13
+
14
+
15
+ from typing import Optional, Tuple, Type
16
+ from functools import partial
17
+
18
+
19
+
20
+ class MlpProjector(nn.Module):
21
+
22
+ def __init__(self, cfg):
23
+
24
+ super().__init__()
25
+
26
+ self.cfg = cfg
27
+
28
+ if cfg.projector_type == "identity":
29
+ modules = nn.Identity()
30
+
31
+ elif cfg.projector_type == "linear":
32
+ modules = nn.Linear(cfg.input_dim, cfg.n_embed)
33
+
34
+ elif cfg.projector_type == "mlp_gelu":
35
+ mlp_depth = cfg.get("depth", 1)
36
+ modules = [nn.Linear(cfg.input_dim, cfg.n_embed)]
37
+ for _ in range(1, mlp_depth):
38
+ modules.append(nn.GELU())
39
+ modules.append(nn.Linear(cfg.n_embed, cfg.n_embed))
40
+ modules = nn.Sequential(*modules)
41
+
42
+ elif cfg.projector_type == "normlayer_downsample_mlp_gelu":
43
+ mlp_depth = cfg.get("depth", 1)
44
+ mlp_ratio = cfg.get("mlp_ratio", 1)
45
+ modules = [
46
+ nn.LayerNorm(cfg.input_dim * cfg.downsample_ratio * cfg.downsample_ratio),
47
+ nn.Linear(cfg.input_dim * cfg.downsample_ratio * cfg.downsample_ratio, cfg.n_embed * mlp_ratio)
48
+ ]
49
+ for _ in range(1, mlp_depth - 1):
50
+ modules.append(nn.GELU())
51
+ modules.append(nn.Linear(cfg.n_embed * mlp_ratio, cfg.n_embed * mlp_ratio))
52
+ modules.append(nn.GELU())
53
+ modules.append(nn.Linear(cfg.n_embed * mlp_ratio, cfg.n_embed))
54
+ modules = nn.Sequential(*modules)
55
+
56
+ elif cfg.projector_type == "downsample_mlp_gelu":
57
+ mlp_depth = cfg.get("depth", 1)
58
+ mlp_ratio = cfg.get("mlp_ratio", 1)
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
+ elif cfg.projector_type == "low_high_hybrid_split_mlp_gelu":
68
+ mlp_depth = cfg.get("depth", 1)
69
+ self.high_up_proj = nn.Linear(cfg.input_dim, cfg.n_embed // 2)
70
+ self.low_up_proj = nn.Linear(cfg.input_dim, cfg.n_embed // 2)
71
+
72
+ modules = []
73
+ for _ in range(1, mlp_depth):
74
+ modules.append(nn.GELU())
75
+ modules.append(nn.Linear(cfg.n_embed, cfg.n_embed))
76
+ modules = nn.Sequential(*modules)
77
+
78
+ elif cfg.projector_type == "hybrid_split_feature_mlp_gelu":
79
+ mlp_depth = cfg.get("depth", 1)
80
+ channel_div = cfg.get("channel_div", 0.5)
81
+ self.high_up_proj = nn.Linear(cfg.input_dim[0], int(cfg.n_embed * channel_div))
82
+ self.low_up_proj = nn.Linear(cfg.input_dim[1], cfg.n_embed - int(cfg.n_embed * channel_div))
83
+
84
+ modules = []
85
+ for _ in range(1, mlp_depth):
86
+ modules.append(nn.GELU())
87
+ modules.append(nn.Linear(cfg.n_embed, cfg.n_embed))
88
+ modules = nn.Sequential(*modules)
89
+
90
+ elif cfg.projector_type == "low_high_split_mlp_gelu":
91
+ mlp_depth = cfg.get("depth", 1)
92
+ modules = []
93
+ for _ in range(1, mlp_depth):
94
+ modules.append(nn.GELU())
95
+ modules.append(nn.Linear(cfg.n_embed // 2, cfg.n_embed // 2))
96
+ modules = nn.Sequential(*modules)
97
+ self.high_layers = nn.Sequential(*modules)
98
+ self.low_layers = copy.deepcopy(modules)
99
+
100
+ else:
101
+ raise ValueError(f"Unknown projector type: {cfg.projector_type}")
102
+
103
+ if cfg.get("token_pooling", False):
104
+ self.token_pooling_layer = nn.Linear(cfg.input_dim * 4, cfg.input_dim)
105
+
106
+ if cfg.get("conv_fusion_high_low_features", False):
107
+ self.fusion_layer = nn.Linear(cfg.input_dim, cfg.input_dim)
108
+ self.layers = modules
109
+
110
+ def forward(self, x):
111
+ if self.cfg.get("token_pooling", False):
112
+ batch_size, wxh, channels = x.shape
113
+ w = h = int(wxh**0.5)
114
+ x = x.view(batch_size, w, h, channels)
115
+ x = x.permute(0, 3, 1, 2)
116
+ # import ipdb; ipdb.set_trace()
117
+ patches = x.unfold(2, 2, 2).unfold(3, 2, 2)
118
+ batch_size, channels, h_patches, w_patches, _, _ = patches.size()
119
+ # 在通道维度上拼接
120
+ patches = patches.contiguous().view(batch_size, channels, h_patches * w_patches, -1)
121
+
122
+ # 通过线性层
123
+ patches = patches.permute(0, 2, 1, 3).contiguous()
124
+ patches = patches.view(batch_size, h_patches * w_patches, channels * 4)
125
+
126
+ x = self.token_pooling_layer(patches)
127
+
128
+ if self.cfg.get("conv_fusion_high_low_features", False):
129
+ x = self.fusion_layer(x[:, 0]) + x[:, 1]
130
+
131
+ if self.cfg.projector_type == 'low_high_hybrid_split_mlp_gelu':
132
+ high_x, low_x = x[0], x[1]
133
+ high_x = self.high_up_proj(high_x)
134
+ low_x = self.low_up_proj(low_x)
135
+ x = torch.concat([high_x, low_x], dim=-1)
136
+
137
+ if self.cfg.projector_type == 'hybrid_split_feature_mlp_gelu':
138
+ high_x = x[...,:self.cfg.input_dim[0]]
139
+ low_x = x[...,self.cfg.input_dim[0]:]
140
+ high_x = self.high_up_proj(high_x)
141
+ low_x = self.low_up_proj(low_x)
142
+ x = torch.concat([high_x, low_x], dim=-1)
143
+
144
+ if self.cfg.projector_type == 'low_high_split_mlp_gelu':
145
+ high_x, low_x = x[0], x[1]
146
+ high_x = self.high_layers(high_x)
147
+ low_x = self.low_layers(low_x)
148
+ x = torch.concat([high_x, low_x], dim=-1)
149
+ return x
150
+
151
+ if self.cfg.projector_type == 'downsample_mlp_gelu' or self.cfg.projector_type == 'normlayer_downsample_mlp_gelu':
152
+ bs, hw, input_dim = x.shape
153
+ h = w = int((hw) ** 0.5)
154
+
155
+ """compute padding"""
156
+ if h % self.cfg.downsample_ratio:
157
+ pad = self.cfg.downsample_ratio - h % self.cfg.downsample_ratio
158
+ else:
159
+ pad = 0
160
+ x = x.reshape(bs, h, w, input_dim)
161
+ if pad > 0:
162
+ x = F.pad(x, (0, 0, 0, pad, 0, pad), "constant", 0)
163
+
164
+ """4 to 1 concat"""
165
+ x = x.permute(0, 3, 1, 2) # B, C, H, W
166
+ x = F.unfold(x, kernel_size=self.cfg.downsample_ratio, stride=self.cfg.downsample_ratio, padding=0) # B, C*4, HW // 4
167
+ x = x.permute(0, 2, 1)
168
+
169
+ return self.layers(x)
170
+
171
+ @staticmethod
172
+ def get_flops_per_sample(cfg):
173
+ if cfg.projector_type == "linear":
174
+ fwd = 2 * cfg.input_dim * cfg.n_embed
175
+
176
+ elif "mlp_gelu" in cfg.projector_type :
177
+ mlp_depth = cfg.get("depth", 1)
178
+ downsample_ratio = cfg.get("downsample_ratio", 1)
179
+ input_dim = sum(cfg.input_dim) if isinstance(cfg.input_dim, list) else cfg.input_dim
180
+ input_dim = input_dim * downsample_ratio * downsample_ratio
181
+ fwd = 2 * input_dim * cfg.n_embed + (mlp_depth - 1) * 2 * cfg.n_embed * cfg.n_embed
182
+ else:
183
+ fwd = 0
184
+
185
+ return fwd * 3
186
+
187
+
188
+ #===================clip============================================================
189
+
190
+ class LayerNormfp32(torch.nn.LayerNorm):
191
+ """Subclass torch's LayerNorm to handle fp16."""
192
+
193
+ def forward(self, x: torch.Tensor):
194
+ orig_type = x.dtype
195
+ ret = super().forward(x.type(torch.float32))
196
+ return ret.type(orig_type)
197
+
198
+
199
+ def get_abs_pos(abs_pos, tgt_size):
200
+ # abs_pos: L, C
201
+ # tgt_size: M
202
+ # return: M, C
203
+
204
+ # print(tgt_size)
205
+ # print(abs_pos.shape)
206
+ # exit()
207
+ dim = abs_pos.size(-1)
208
+ # print(dim)
209
+ abs_pos_new = abs_pos.squeeze(0)
210
+ cls_token, old_pos_embed = abs_pos_new[:1], abs_pos_new[1:]
211
+
212
+
213
+
214
+ src_size = int(math.sqrt(abs_pos_new.shape[0] - 1))
215
+ tgt_size = int(math.sqrt(tgt_size))
216
+ dtype = abs_pos.dtype
217
+
218
+ if src_size != tgt_size:
219
+ old_pos_embed = old_pos_embed.view(1, src_size, src_size, dim).permute(0, 3, 1,
220
+ 2).contiguous()
221
+ old_pos_embed = old_pos_embed.to(torch.float32)
222
+ new_pos_embed = F.interpolate(
223
+ old_pos_embed,
224
+ size=(tgt_size, tgt_size),
225
+ mode='bicubic',
226
+ antialias=True,
227
+ align_corners=False,
228
+ ).to(dtype)
229
+ new_pos_embed = new_pos_embed.permute(0, 2, 3, 1)
230
+ new_pos_embed = new_pos_embed.view(tgt_size * tgt_size, dim)
231
+ vision_pos_embed = torch.cat([cls_token, new_pos_embed], dim=0)
232
+ vision_pos_embed = vision_pos_embed.view(1, tgt_size * tgt_size + 1, dim)
233
+ return vision_pos_embed
234
+ else:
235
+ return abs_pos
236
+
237
+ @torch.jit.script
238
+ def quick_gelu(x):
239
+ return x * torch.sigmoid(1.702 * x)
240
+
241
+
242
+
243
+ class CLIPVisionEmbeddings(nn.Module):
244
+ def __init__(self, hidden_size=1024, image_size=224, patch_size=14, num_channels=3):
245
+ super().__init__()
246
+ self.embed_dim = hidden_size
247
+ self.image_size = image_size
248
+ self.patch_size = patch_size
249
+
250
+ self.class_embedding = torch.nn.Parameter(torch.randn(self.embed_dim))
251
+
252
+ self.patch_embedding = torch.nn.Conv2d(
253
+ in_channels=num_channels,
254
+ out_channels=self.embed_dim,
255
+ kernel_size=self.patch_size,
256
+ stride=self.patch_size,
257
+ bias=False,
258
+ )
259
+
260
+ self.num_patches = (self.image_size // self.patch_size) ** 2
261
+ self.num_positions = self.num_patches + 1
262
+ self.position_embedding = torch.nn.Embedding(self.num_positions, self.embed_dim)
263
+ self.register_buffer(
264
+ "position_ids", torch.arange(self.num_positions).expand((1, -1))
265
+ )
266
+
267
+ def forward(self, pixel_values, patch_embeds):
268
+ batch_size = pixel_values.shape[0]
269
+ # patch_embeds = self.patch_embedding(
270
+ # pixel_values
271
+ # ) # shape = [*, width, grid, grid]
272
+
273
+
274
+ if patch_embeds is not None:
275
+ patch_embeds = patch_embeds
276
+ # print(patch_embeds.shape)
277
+ else:
278
+ patch_embeds = self.patch_embedding(pixel_values)
279
+ # print(111111)
280
+ # shape = [*, width, grid, grid]
281
+ # patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
282
+
283
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
284
+
285
+
286
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1)
287
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
288
+
289
+ # x = torch.cat([cls_token, x], dim=1)
290
+ embeddings = embeddings + get_abs_pos(self.position_embedding(self.position_ids), embeddings.size(1))
291
+ # embeddings = embeddings + self.position_embedding(self.position_ids)
292
+ return embeddings
293
+
294
+
295
+ class NoTPFeedForward(nn.Module):
296
+ def __init__(
297
+ self,
298
+ cfg,
299
+ dim: int,
300
+ hidden_dim: int,
301
+ ):
302
+ super().__init__()
303
+
304
+ self.fc1 = torch.nn.Linear(dim, hidden_dim, bias=True)
305
+ self.fc2 = torch.nn.Linear(hidden_dim, dim, bias=True)
306
+
307
+ def forward(self, x):
308
+ output = self.fc2(quick_gelu(self.fc1(x)))
309
+ return output
310
+
311
+
312
+
313
+
314
+ class NoTPAttention(torch.nn.Module):
315
+ def __init__(self, cfg):
316
+ super().__init__()
317
+ self.num_heads = cfg.num_attention_heads
318
+ self.n_local_heads = cfg.num_attention_heads
319
+ self.head_dim = cfg.hidden_size // cfg.num_attention_heads
320
+ self.max_seq_len = cfg.seq_length
321
+ self.use_flash_attention = cfg.use_flash_attn
322
+
323
+ self.qkv_proj = torch.nn.Linear(cfg.hidden_size, cfg.hidden_size * 3, bias=True)
324
+ self.out_proj = torch.nn.Linear(cfg.hidden_size, cfg.hidden_size, bias=True)
325
+
326
+ # self.core_attention = CoreAttention(cfg, AttnType.self_attn)
327
+
328
+ self.attn_drop = cfg.attention_dropout
329
+
330
+ def forward(
331
+ self,
332
+ x: torch.Tensor,
333
+ ):
334
+ bsz, seqlen, _ = x.shape
335
+ xqkv = self.qkv_proj(x)
336
+ xqkv = xqkv.view(bsz, seqlen, 3, self.num_heads, self.head_dim)
337
+
338
+ if self.use_flash_attention:
339
+
340
+ xq, xk, xv = torch.split(xqkv, 1, dim=2)
341
+ xq = xq.squeeze(2)
342
+ xk = xk.squeeze(2)
343
+ xv = xv.squeeze(2)
344
+ # xq, xk, xv = xqkv[:, :, 0, ...], xqkv[:, :, 1, ...], xqkv[:, :, 2, ...]
345
+
346
+ # (B, num_head, S, head_size)
347
+ xq = xq.permute(0, 2, 1, 3)
348
+ xk = xk.permute(0, 2, 1, 3)
349
+ xv = xv.permute(0, 2, 1, 3)
350
+ # with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False):
351
+ output = torch.nn.functional.scaled_dot_product_attention(xq, xk, xv, attn_mask=None)
352
+ output = output.permute(0, 2, 1, 3).reshape(bsz, seqlen, -1)
353
+ # output = output.permute(0, 2, 1, 3).contiguous().view(bsz, seqlen, -1)
354
+ else:
355
+ # print(22222)
356
+ xq, xk, xv = torch.split(xqkv, 1, dim=2)
357
+ xq = xq.squeeze(2)
358
+ xk = xk.squeeze(2)
359
+ xv = xv.squeeze(2)
360
+ # xq, xk, xv = xqkv[:, :, 0, ...], xqkv[:, :, 1, ...], xqkv[:, :, 2, ...]
361
+
362
+ # (B, num_head, S, head_size)
363
+ xq = xq.permute(0, 2, 1, 3)
364
+ xk = xk.permute(0, 2, 1, 3)
365
+ xv = xv.permute(0, 2, 1, 3)
366
+ # with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False):
367
+ output = torch.nn.functional.scaled_dot_product_attention(xq, xk, xv, attn_mask=None)
368
+ output = output.permute(0, 2, 1, 3).reshape(bsz, seqlen, -1)
369
+ # output = output.permute(0, 2, 1, 3).contiguous().view(bsz, seqlen, -1)
370
+ output = self.out_proj(output)
371
+ return output
372
+
373
+ class NoTPTransformerBlock(nn.Module):
374
+ def __init__(self, cfg, layer_id: int, multiple_of=256):
375
+ super().__init__()
376
+
377
+ self.n_heads = cfg.num_attention_heads
378
+ self.dim = cfg.hidden_size
379
+ self.head_dim = cfg.hidden_size // cfg.num_attention_heads
380
+ self.self_attn = NoTPAttention(cfg)
381
+ self.mlp = NoTPFeedForward(
382
+ cfg, dim=cfg.hidden_size, hidden_dim=cfg.ffn_hidden_size
383
+ )
384
+ self.layer_id = layer_id
385
+ self.layer_norm1 = torch.nn.LayerNorm(
386
+ cfg.hidden_size, eps=cfg.layernorm_epsilon
387
+ )
388
+ self.layer_norm2 = torch.nn.LayerNorm(
389
+ cfg.hidden_size, eps=cfg.layernorm_epsilon
390
+ )
391
+
392
+ def forward(self, x: torch.Tensor):
393
+ residual = self.self_attn.forward(self.layer_norm1(x))
394
+ h = x + residual
395
+ out = h + self.mlp.forward(self.layer_norm2(h))
396
+ return out
397
+
398
+
399
+ class NoTPTransformer(nn.Module):
400
+ def __init__(self, cfg):
401
+ super().__init__()
402
+
403
+ self.cfg = cfg
404
+ # self.recompute_list = self.cfg.get("recompute_list", [])
405
+ self.num_layers = cfg.num_layers # _get_num_layers(cfg)
406
+
407
+ self.layers = torch.nn.ModuleList()
408
+ for layer_id in range(self.num_layers):
409
+ self.layers.append(
410
+ NoTPTransformerBlock(
411
+ cfg,
412
+ layer_id + 1,
413
+ )
414
+ )
415
+
416
+ def forward(
417
+ self,
418
+ hidden_states,
419
+ ):
420
+
421
+ for lid, layer in enumerate(self.layers):
422
+ # if lid in self.recompute_list:
423
+ # def custom(layer_id):
424
+ # def custom_forward(*args, **kwargs):
425
+ # x_ = self.layers[layer_id](*args, **kwargs)
426
+ # return x_
427
+
428
+ # return custom_forward
429
+
430
+ # assert hidden_states.requires_grad == True, logger.warning(
431
+ # "When using recalculation, the input must have grad fn"
432
+ # )
433
+ # hidden_states = tensor_parallel.checkpoint(
434
+ # custom(lid),
435
+ # False,
436
+ # hidden_states.contiguous()
437
+ # )
438
+ # else:
439
+ hidden_states = layer(hidden_states)
440
+
441
+ return hidden_states
442
+
443
+
444
+ # from megatron.core.tensor_parallel.layers import non_tensor_paralleled, local_dp_reduce, local_dp_scatter
445
+
446
+ class VitModel(nn.Module):
447
+ def __init__(
448
+ self,
449
+ cfg,
450
+ freeze_embed=False,
451
+ freeze_pre_norm=False
452
+ ) -> None:
453
+ super().__init__()
454
+
455
+ self.embeddings = CLIPVisionEmbeddings(hidden_size=cfg.hidden_size, image_size=cfg.image_size, patch_size=cfg.patch_size)
456
+
457
+ if freeze_embed:
458
+ for name, param in self.embeddings.named_parameters():
459
+ param.requires_grad = False
460
+
461
+ self.transformer = NoTPTransformer(cfg=cfg)
462
+
463
+ if cfg.get("fp32norm", False):
464
+ logger.info("Load fp32 layernorm for ViT.")
465
+ self.pre_layrnorm = LayerNormfp32(
466
+ cfg.hidden_size,
467
+ eps=cfg.get("pre_layernorm_epsilon", 1e-5),
468
+ )
469
+ else:
470
+ self.pre_layrnorm = torch.nn.LayerNorm(
471
+ cfg.hidden_size,
472
+ eps=cfg.get("pre_layernorm_epsilon", 1e-5),
473
+ )
474
+
475
+ # self.pre_layrnorm = RMSNorm(
476
+ # cfg.hidden_size,
477
+ # eps=cfg.get("pre_layernorm_epsilon", 1e-5),
478
+ # sequence_parallel=False,
479
+ # use_fp32=True,
480
+ # use_optimus=True,
481
+ # )
482
+
483
+ if freeze_pre_norm:
484
+ for name, param in self.pre_layrnorm.named_parameters():
485
+ param.requires_grad = False
486
+
487
+ for p in self.parameters():
488
+ p.micro_dp = True
489
+
490
+ def set_input_tensor(self, input_tensor):
491
+ if not isinstance(input_tensor, list):
492
+ input_tensor = [input_tensor]
493
+ self.transformer.set_input_tensor(input_tensor[0])
494
+
495
+ def __str__(self) -> str:
496
+ return "open_clip"
497
+
498
+ def forward(
499
+ self,
500
+ x,
501
+ patch_embeds
502
+ ):
503
+ x = self.embeddings(x, patch_embeds)
504
+ hidden_states = self.pre_layrnorm(x)
505
+
506
+ # hidden_states, dis = local_dp_scatter(hidden_states)
507
+ output = self.transformer(hidden_states)
508
+
509
+ # output = local_dp_reduce(output, dis)
510
+
511
+ return output
512
+
513
+
514
+ vit_model_cfg = adict(
515
+ num_layers=24,
516
+ hidden_size=1024,
517
+ num_heads = 16,
518
+ num_attention_heads=16,
519
+ ffn_hidden_size=4096,
520
+ seq_length=256,
521
+ max_position_embeddings=256,
522
+ use_flash_attn=False,
523
+ understand_projector_stride=2,
524
+ hidden_dropout = 0.0,
525
+ attention_dropout = 0.0,
526
+ no_persist_layer_norm = False,
527
+ layernorm_epsilon = 1e-5,
528
+ pre_layernorm_epsilon = 1e-5,
529
+ image_size = 224,
530
+ patch_size = 14,
531
+ recompute_list = []
532
+ )
533
+
534
+ def build_clip_l():
535
+ return VitModel(
536
+ cfg=vit_model_cfg,
537
+ freeze_embed=False,
538
+ freeze_pre_norm=False,
539
+ )
540
+
541
+
542
+
543
+
544
+
545
+ #=========================Sam-Vary=================================
546
+
547
+
548
+ def get_abs_pos_sam(abs_pos, tgt_size):
549
+
550
+ dtype = abs_pos.dtype
551
+
552
+ src_size = abs_pos.size(1)
553
+
554
+ if src_size != tgt_size:
555
+ old_pos_embed = abs_pos.permute(0, 3, 1, 2)
556
+ old_pos_embed = old_pos_embed.to(torch.float32)
557
+ new_pos_embed = F.interpolate(
558
+ old_pos_embed,
559
+ size=(tgt_size, tgt_size),
560
+ mode='bicubic',
561
+ antialias=True,
562
+ align_corners=False,
563
+ ).to(dtype)
564
+ new_pos_embed = new_pos_embed.permute(0, 2, 3, 1)
565
+ return new_pos_embed
566
+ else:
567
+ return abs_pos
568
+
569
+
570
+
571
+
572
+ class MLPBlock(nn.Module):
573
+ def __init__(
574
+ self,
575
+ embedding_dim: int,
576
+ mlp_dim: int,
577
+ act: Type[nn.Module] = nn.GELU,
578
+ ) -> None:
579
+ super().__init__()
580
+ self.lin1 = nn.Linear(embedding_dim, mlp_dim)
581
+ self.lin2 = nn.Linear(mlp_dim, embedding_dim)
582
+ self.act = act()
583
+
584
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
585
+ return self.lin2(self.act(self.lin1(x)))
586
+
587
+
588
+ # From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa
589
+ # Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa
590
+ class LayerNorm2d(nn.Module):
591
+ def __init__(self, num_channels: int, eps: float = 1e-6) -> None:
592
+ super().__init__()
593
+ self.weight = nn.Parameter(torch.ones(num_channels))
594
+ self.bias = nn.Parameter(torch.zeros(num_channels))
595
+ self.eps = eps
596
+
597
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
598
+ u = x.mean(1, keepdim=True)
599
+ s = (x - u).pow(2).mean(1, keepdim=True)
600
+ x = (x - u) / torch.sqrt(s + self.eps)
601
+ x = self.weight[:, None, None] * x + self.bias[:, None, None]
602
+ return x
603
+
604
+
605
+ # This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa
606
+ class ImageEncoderViT(nn.Module):
607
+ def __init__(
608
+ self,
609
+ img_size: int = 1024,
610
+ patch_size: int = 16,
611
+ in_chans: int = 3,
612
+ embed_dim: int = 768,
613
+ depth: int = 12,
614
+ num_heads: int = 12,
615
+ mlp_ratio: float = 4.0,
616
+ out_chans: int = 256,
617
+ qkv_bias: bool = True,
618
+ norm_layer: Type[nn.Module] = nn.LayerNorm,
619
+ act_layer: Type[nn.Module] = nn.GELU,
620
+ use_abs_pos: bool = True,
621
+ use_rel_pos: bool = False,
622
+ rel_pos_zero_init: bool = True,
623
+ window_size: int = 0,
624
+ global_attn_indexes: Tuple[int, ...] = (),
625
+ ) -> None:
626
+ """
627
+ Args:
628
+ img_size (int): Input image size.
629
+ patch_size (int): Patch size.
630
+ in_chans (int): Number of input image channels.
631
+ embed_dim (int): Patch embedding dimension.
632
+ depth (int): Depth of ViT.
633
+ num_heads (int): Number of attention heads in each ViT block.
634
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
635
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
636
+ norm_layer (nn.Module): Normalization layer.
637
+ act_layer (nn.Module): Activation layer.
638
+ use_abs_pos (bool): If True, use absolute positional embeddings.
639
+ use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
640
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
641
+ window_size (int): Window size for window attention blocks.
642
+ global_attn_indexes (list): Indexes for blocks using global attention.
643
+ """
644
+ super().__init__()
645
+ self.img_size = img_size
646
+
647
+ self.patch_embed = PatchEmbed(
648
+ kernel_size=(patch_size, patch_size),
649
+ stride=(patch_size, patch_size),
650
+ in_chans=in_chans,
651
+ embed_dim=embed_dim,
652
+ )
653
+
654
+ self.pos_embed: Optional[nn.Parameter] = None
655
+ if use_abs_pos:
656
+ # Initialize absolute positional embedding with pretrain image size.
657
+ self.pos_embed = nn.Parameter(
658
+ torch.zeros(1, img_size // patch_size, img_size // patch_size, embed_dim)
659
+ )
660
+
661
+ self.blocks = nn.ModuleList()
662
+ for i in range(depth):
663
+ block = Block(
664
+ dim=embed_dim,
665
+ num_heads=num_heads,
666
+ mlp_ratio=mlp_ratio,
667
+ qkv_bias=qkv_bias,
668
+ norm_layer=norm_layer,
669
+ act_layer=act_layer,
670
+ use_rel_pos=use_rel_pos,
671
+ rel_pos_zero_init=rel_pos_zero_init,
672
+ window_size=window_size if i not in global_attn_indexes else 0,
673
+ input_size=(img_size // patch_size, img_size // patch_size),
674
+ )
675
+ self.blocks.append(block)
676
+
677
+ self.neck = nn.Sequential(
678
+ nn.Conv2d(
679
+ embed_dim,
680
+ out_chans,
681
+ kernel_size=1,
682
+ bias=False,
683
+ ),
684
+ LayerNorm2d(out_chans),
685
+ nn.Conv2d(
686
+ out_chans,
687
+ out_chans,
688
+ kernel_size=3,
689
+ padding=1,
690
+ bias=False,
691
+ ),
692
+ LayerNorm2d(out_chans),
693
+ )
694
+
695
+ self.net_2 = nn.Conv2d(256, 512, kernel_size=3, stride=2, padding=1, bias=False)
696
+ self.net_3 = nn.Conv2d(512, 1024, kernel_size=3, stride=2, padding=1, bias=False)
697
+
698
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
699
+ x = self.patch_embed(x)
700
+ if self.pos_embed is not None:
701
+ # x = x + self.pos_embed
702
+ x = x + get_abs_pos_sam(self.pos_embed, x.size(1))
703
+
704
+ for blk in self.blocks:
705
+ x = blk(x)
706
+
707
+ x = self.neck(x.permute(0, 3, 1, 2))
708
+ x2 = self.net_2(x)
709
+ x3 = self.net_3(x2.clone())
710
+
711
+ return x3
712
+
713
+
714
+ class Block(nn.Module):
715
+ """Transformer blocks with support of window attention and residual propagation blocks"""
716
+
717
+ def __init__(
718
+ self,
719
+ dim: int,
720
+ num_heads: int,
721
+ mlp_ratio: float = 4.0,
722
+ qkv_bias: bool = True,
723
+ norm_layer: Type[nn.Module] = nn.LayerNorm,
724
+ act_layer: Type[nn.Module] = nn.GELU,
725
+ use_rel_pos: bool = False,
726
+ rel_pos_zero_init: bool = True,
727
+ window_size: int = 0,
728
+ input_size: Optional[Tuple[int, int]] = None,
729
+ ) -> None:
730
+ """
731
+ Args:
732
+ dim (int): Number of input channels.
733
+ num_heads (int): Number of attention heads in each ViT block.
734
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
735
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
736
+ norm_layer (nn.Module): Normalization layer.
737
+ act_layer (nn.Module): Activation layer.
738
+ use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
739
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
740
+ window_size (int): Window size for window attention blocks. If it equals 0, then
741
+ use global attention.
742
+ input_size (tuple(int, int) or None): Input resolution for calculating the relative
743
+ positional parameter size.
744
+ """
745
+ super().__init__()
746
+ self.norm1 = norm_layer(dim)
747
+ self.attn = Attention(
748
+ dim,
749
+ num_heads=num_heads,
750
+ qkv_bias=qkv_bias,
751
+ use_rel_pos=use_rel_pos,
752
+ rel_pos_zero_init=rel_pos_zero_init,
753
+ input_size=input_size if window_size == 0 else (window_size, window_size),
754
+ )
755
+
756
+ self.norm2 = norm_layer(dim)
757
+ self.mlp = MLPBlock(embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer)
758
+
759
+ self.window_size = window_size
760
+
761
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
762
+ shortcut = x
763
+ x = self.norm1(x)
764
+ # Window partition
765
+ if self.window_size > 0:
766
+ H, W = x.shape[1], x.shape[2]
767
+ x, pad_hw = window_partition(x, self.window_size)
768
+
769
+ x = self.attn(x)
770
+ # Reverse window partition
771
+ if self.window_size > 0:
772
+ x = window_unpartition(x, self.window_size, pad_hw, (H, W))
773
+
774
+ x = shortcut + x
775
+ x = x + self.mlp(self.norm2(x))
776
+
777
+ return x
778
+
779
+
780
+ class Attention(nn.Module):
781
+ """Multi-head Attention block with relative position embeddings."""
782
+
783
+ def __init__(
784
+ self,
785
+ dim: int,
786
+ num_heads: int = 8,
787
+ qkv_bias: bool = True,
788
+ use_rel_pos: bool = False,
789
+ rel_pos_zero_init: bool = True,
790
+ input_size: Optional[Tuple[int, int]] = None,
791
+ ) -> None:
792
+ """
793
+ Args:
794
+ dim (int): Number of input channels.
795
+ num_heads (int): Number of attention heads.
796
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
797
+ rel_pos (bool): If True, add relative positional embeddings to the attention map.
798
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
799
+ input_size (tuple(int, int) or None): Input resolution for calculating the relative
800
+ positional parameter size.
801
+ """
802
+ super().__init__()
803
+ self.num_heads = num_heads
804
+ head_dim = dim // num_heads
805
+ self.scale = head_dim**-0.5
806
+
807
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
808
+ self.proj = nn.Linear(dim, dim)
809
+
810
+ self.use_rel_pos = use_rel_pos
811
+ if self.use_rel_pos:
812
+ assert (
813
+ input_size is not None
814
+ ), "Input size must be provided if using relative positional encoding."
815
+ # initialize relative positional embeddings
816
+ self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
817
+ self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
818
+
819
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
820
+ B, H, W, _ = x.shape
821
+ # qkv with shape (3, B, nHead, H * W, C)
822
+ qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
823
+ # q, k, v with shape (B * nHead, H * W, C)
824
+ q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0)
825
+
826
+ rel_h, rel_w = None, None
827
+ if self.use_rel_pos:
828
+ rel_h, rel_w = add_decomposed_rel_pos(q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W))
829
+
830
+ q = q.view(B, self.num_heads, H * W, -1)
831
+ k = k.view(B, self.num_heads, H * W, -1)
832
+ v = v.view(B, self.num_heads, H * W, -1)
833
+
834
+ if self.use_rel_pos:
835
+ rel_h = rel_h.view(B, self.num_heads, rel_h.size(1), rel_h.size(2), rel_h.size(3))
836
+ rel_w = rel_w.view(B, self.num_heads, rel_w.size(1), rel_w.size(2), rel_w.size(3))
837
+ attn_bias = (rel_h + rel_w).view(B, self.num_heads, rel_h.size(2), rel_h.size(3) * rel_w.size(4))
838
+ x = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=attn_bias)
839
+ # x = _attention_rel_h_rel_w(q, k, v, rel_h, rel_w)
840
+ else:
841
+ x = torch.nn.functional.scaled_dot_product_attention(q, k, v)
842
+
843
+ x = x.view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1)
844
+
845
+ x = self.proj(x)
846
+
847
+ return x
848
+
849
+
850
+ def window_partition(x: torch.Tensor, window_size: int) -> Tuple[torch.Tensor, Tuple[int, int]]:
851
+ """
852
+ Partition into non-overlapping windows with padding if needed.
853
+ Args:
854
+ x (tensor): input tokens with [B, H, W, C].
855
+ window_size (int): window size.
856
+
857
+ Returns:
858
+ windows: windows after partition with [B * num_windows, window_size, window_size, C].
859
+ (Hp, Wp): padded height and width before partition
860
+ """
861
+ B, H, W, C = x.shape
862
+
863
+ pad_h = (window_size - H % window_size) % window_size
864
+ pad_w = (window_size - W % window_size) % window_size
865
+ if pad_h > 0 or pad_w > 0:
866
+ x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h))
867
+ Hp, Wp = H + pad_h, W + pad_w
868
+
869
+ x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C)
870
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
871
+ return windows, (Hp, Wp)
872
+
873
+
874
+ def window_unpartition(
875
+ windows: torch.Tensor, window_size: int, pad_hw: Tuple[int, int], hw: Tuple[int, int]
876
+ ) -> torch.Tensor:
877
+ """
878
+ Window unpartition into original sequences and removing padding.
879
+ Args:
880
+ windows (tensor): input tokens with [B * num_windows, window_size, window_size, C].
881
+ window_size (int): window size.
882
+ pad_hw (Tuple): padded height and width (Hp, Wp).
883
+ hw (Tuple): original height and width (H, W) before padding.
884
+
885
+ Returns:
886
+ x: unpartitioned sequences with [B, H, W, C].
887
+ """
888
+ Hp, Wp = pad_hw
889
+ H, W = hw
890
+ B = windows.shape[0] // (Hp * Wp // window_size // window_size)
891
+ x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1)
892
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1)
893
+
894
+ if Hp > H or Wp > W:
895
+ x = x[:, :H, :W, :].contiguous()
896
+ return x
897
+
898
+
899
+ def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
900
+ """
901
+ Get relative positional embeddings according to the relative positions of
902
+ query and key sizes.
903
+ Args:
904
+ q_size (int): size of query q.
905
+ k_size (int): size of key k.
906
+ rel_pos (Tensor): relative position embeddings (L, C).
907
+
908
+ Returns:
909
+ Extracted positional embeddings according to relative positions.
910
+ """
911
+ max_rel_dist = int(2 * max(q_size, k_size) - 1)
912
+ # Interpolate rel pos if needed.
913
+ if rel_pos.shape[0] != max_rel_dist:
914
+ # Interpolate rel pos.
915
+ dtype = rel_pos.dtype
916
+ rel_pos = rel_pos.to(torch.float32)
917
+ rel_pos_resized = F.interpolate(
918
+ rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1),
919
+ size=max_rel_dist,
920
+ mode="linear",
921
+ ).to(dtype)
922
+ rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
923
+ else:
924
+ rel_pos_resized = rel_pos
925
+
926
+ # Scale the coords with short length if shapes for q and k are different.
927
+ q_coords = torch.arange(q_size, device=rel_pos.device)[:, None] * max(k_size / q_size, 1.0)
928
+ k_coords = torch.arange(k_size, device=rel_pos.device)[None, :] * max(q_size / k_size, 1.0)
929
+ relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
930
+
931
+ return rel_pos_resized[relative_coords.long()]
932
+
933
+
934
+ def add_decomposed_rel_pos(
935
+ q: torch.Tensor,
936
+ rel_pos_h: torch.Tensor,
937
+ rel_pos_w: torch.Tensor,
938
+ q_size: Tuple[int, int],
939
+ k_size: Tuple[int, int],
940
+ ) -> torch.Tensor:
941
+ """
942
+ Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
943
+ https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950
944
+ Args:
945
+ q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C).
946
+ rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis.
947
+ rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis.
948
+ q_size (Tuple): spatial sequence size of query q with (q_h, q_w).
949
+ k_size (Tuple): spatial sequence size of key k with (k_h, k_w).
950
+
951
+ Returns:
952
+ attn (Tensor): attention map with added relative positional embeddings.
953
+ """
954
+ q_h, q_w = q_size
955
+ k_h, k_w = k_size
956
+ Rh = get_rel_pos(q_h, k_h, rel_pos_h)
957
+ Rw = get_rel_pos(q_w, k_w, rel_pos_w)
958
+
959
+ B, _, dim = q.shape
960
+ r_q = q.reshape(B, q_h, q_w, dim)
961
+ rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh)
962
+ rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw)
963
+ rel_h = rel_h.unsqueeze(-1)
964
+ rel_w = rel_w.unsqueeze(-2)
965
+ rel_h = rel_h.reshape(B, q_h * q_w, k_h, 1)
966
+ rel_w = rel_w.reshape(B, q_h * q_w, 1, k_w)
967
+
968
+ return rel_h, rel_w
969
+
970
+
971
+ class PatchEmbed(nn.Module):
972
+ """
973
+ Image to Patch Embedding.
974
+ """
975
+
976
+ def __init__(
977
+ self,
978
+ kernel_size: Tuple[int, int] = (16, 16),
979
+ stride: Tuple[int, int] = (16, 16),
980
+ padding: Tuple[int, int] = (0, 0),
981
+ in_chans: int = 3,
982
+ embed_dim: int = 768,
983
+ ) -> None:
984
+ """
985
+ Args:
986
+ kernel_size (Tuple): kernel size of the projection layer.
987
+ stride (Tuple): stride of the projection layer.
988
+ padding (Tuple): padding size of the projection layer.
989
+ in_chans (int): Number of input image channels.
990
+ embed_dim (int): Patch embedding dimension.
991
+ """
992
+ super().__init__()
993
+
994
+ self.proj = nn.Conv2d(
995
+ in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding
996
+ )
997
+
998
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
999
+ x = self.proj(x)
1000
+ # B C H W -> B H W C
1001
+ x = x.permute(0, 2, 3, 1)
1002
+ return x
1003
+
1004
+
1005
+ def build_sam_vit_b(checkpoint=None):
1006
+ return _build_sam(
1007
+ encoder_embed_dim=768,
1008
+ encoder_depth=12,
1009
+ encoder_num_heads=12,
1010
+ encoder_global_attn_indexes=[2, 5, 8, 11],
1011
+ checkpoint=checkpoint,
1012
+ )
1013
+
1014
+ def build_sam_fast_vit_b(checkpoint=None, compile_mode='max-autotune', dtype=torch.bfloat16):
1015
+ image_encoder = build_sam_vit_b(checkpoint).eval().to(dtype)
1016
+ # sam = _apply_eval_dtype_sam(sam, dtype)
1017
+ image_encoder = torch.compile(image_encoder, mode=compile_mode)
1018
+ return image_encoder
1019
+
1020
+
1021
+ def _build_sam(
1022
+ encoder_embed_dim,
1023
+ encoder_depth,
1024
+ encoder_num_heads,
1025
+ encoder_global_attn_indexes,
1026
+ checkpoint=None,
1027
+ ):
1028
+ prompt_embed_dim = 256
1029
+ image_size = 1024
1030
+ vit_patch_size = 16
1031
+ image_embedding_size = image_size // vit_patch_size
1032
+ image_encoder=ImageEncoderViT(
1033
+ depth=encoder_depth,
1034
+ embed_dim=encoder_embed_dim,
1035
+ img_size=image_size,
1036
+ mlp_ratio=4,
1037
+ norm_layer=partial(torch.nn.LayerNorm, eps=1e-6),
1038
+ num_heads=encoder_num_heads,
1039
+ patch_size=vit_patch_size,
1040
+ qkv_bias=True,
1041
+ use_rel_pos=True,
1042
+ global_attn_indexes=encoder_global_attn_indexes,
1043
+ window_size=14,
1044
+ out_chans=prompt_embed_dim,
1045
+ )
1046
+ image_encoder.eval()
1047
+ if checkpoint is not None:
1048
+ # with open(checkpoint, "rb") as f:
1049
+ state_dict = torch.load(checkpoint)
1050
+ # print(state_dict.keys())
1051
+ # for key in state_dict:
1052
+ # image_encoder.load_state_dict({k[14:]: v for k, v in state_dict.items() if 'image_encoder' in k}, strict=False)
1053
+ # ocr-anyting
1054
+ # image_encoder.load_state_dict(state_dict, strict=True)
1055
+ # tob
1056
+ image_encoder.load_state_dict({k[30:]: v for k, v in state_dict.items() if 'vision_tower_high' in k}, strict=True)
1057
+ print(checkpoint)
1058
+ return image_encoder
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 1,
5
+ "transformers_version": "4.57.1"
6
+ }
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aab00c8b930b4d7987b0422ceb79068cf027fd3dd2625c330c108eb9244e484c
3
+ size 4998399864
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fdc71a7dabe1673271a46a8f1f5a62cd88cdbc75240807d0644a7c565e43d4f6
3
+ size 2279959112
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_deepseekv2.py ADDED
@@ -0,0 +1,2169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=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
+ apply_rotary_pos_emb as _llama_apply_rotary_pos_emb,
40
+ repeat_kv as _llama_repeat_kv,
41
+ # LlamaFlashAttention2
42
+ )
43
+ from transformers.modeling_outputs import (
44
+ BaseModelOutputWithPast,
45
+ CausalLMOutputWithPast,
46
+ SequenceClassifierOutputWithPast,
47
+ )
48
+ from transformers.modeling_utils import PreTrainedModel
49
+ from transformers.pytorch_utils import (
50
+ ALL_LAYERNORM_LAYERS,
51
+ is_torch_greater_or_equal_than_1_13,
52
+ )
53
+ from transformers.utils import (
54
+ add_start_docstrings,
55
+ add_start_docstrings_to_model_forward,
56
+ is_flash_attn_2_available,
57
+ is_flash_attn_greater_or_equal_2_10,
58
+ logging,
59
+ replace_return_docstrings,
60
+ )
61
+ try:
62
+ from transformers.utils.import_utils import is_torch_fx_available
63
+ except Exception:
64
+ def is_torch_fx_available():
65
+ return False
66
+
67
+ from .configuration_deepseek_v2 import DeepseekV2Config
68
+
69
+ if is_flash_attn_2_available():
70
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
71
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
72
+
73
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
74
+ # It means that the function will not be traced through and simply appear as a node in the graph.
75
+ if is_torch_fx_available():
76
+ if not is_torch_greater_or_equal_than_1_13:
77
+ import torch.fx
78
+
79
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
80
+
81
+ logger = logging.get_logger(__name__)
82
+
83
+ _CONFIG_FOR_DOC = "DeepseekV2Config"
84
+
85
+
86
+ def _get_unpad_data(attention_mask):
87
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
88
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
89
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
90
+ cu_seqlens = F.pad(
91
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
92
+ )
93
+ return (
94
+ indices,
95
+ cu_seqlens,
96
+ max_seqlen_in_batch,
97
+ )
98
+
99
+
100
+ class DeepseekV2RMSNorm(nn.Module):
101
+ def __init__(self, hidden_size, eps=1e-6):
102
+ """
103
+ DeepseekV2RMSNorm is equivalent to T5LayerNorm
104
+ """
105
+ super().__init__()
106
+ self.weight = nn.Parameter(torch.ones(hidden_size))
107
+ self.variance_epsilon = eps
108
+
109
+ def forward(self, hidden_states):
110
+ input_dtype = hidden_states.dtype
111
+ hidden_states = hidden_states.to(torch.float32)
112
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
113
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
114
+ return self.weight * hidden_states.to(input_dtype)
115
+
116
+
117
+ ALL_LAYERNORM_LAYERS.append(DeepseekV2RMSNorm)
118
+
119
+
120
+
121
+
122
+ class DeepseekV2RotaryEmbedding(nn.Module):
123
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
124
+ super().__init__()
125
+
126
+ self.dim = dim
127
+ self.max_position_embeddings = max_position_embeddings
128
+ self.base = base
129
+ inv_freq = 1.0 / (
130
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
131
+ )
132
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
133
+
134
+ # Build here to make `torch.jit.trace` work.
135
+ self._set_cos_sin_cache(
136
+ seq_len=max_position_embeddings,
137
+ device=self.inv_freq.device,
138
+ dtype=torch.get_default_dtype(),
139
+ )
140
+ self.max_seq_len_cached = None
141
+
142
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
143
+ self.max_seq_len_cached = seq_len
144
+ t = torch.arange(
145
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
146
+ )
147
+
148
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
149
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
150
+ emb = torch.cat((freqs, freqs), dim=-1)
151
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
152
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
153
+
154
+ def forward(self, x, seq_len=None):
155
+ # x: [bs, num_attention_heads, seq_len, head_size]
156
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
157
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
158
+
159
+ return (
160
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
161
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
162
+ )
163
+
164
+
165
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV2
166
+ class DeepseekV2LinearScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
167
+ """DeepseekV2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
168
+
169
+ def __init__(
170
+ self,
171
+ dim,
172
+ max_position_embeddings=2048,
173
+ base=10000,
174
+ device=None,
175
+ scaling_factor=1.0,
176
+ ):
177
+ self.scaling_factor = scaling_factor
178
+ super().__init__(dim, max_position_embeddings, base, device)
179
+
180
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
181
+ self.max_seq_len_cached = seq_len
182
+ t = torch.arange(
183
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
184
+ )
185
+ t = t / self.scaling_factor
186
+
187
+ freqs = torch.outer(t, self.inv_freq)
188
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
189
+ emb = torch.cat((freqs, freqs), dim=-1)
190
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
191
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
192
+
193
+
194
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV2
195
+ class DeepseekV2DynamicNTKScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
196
+ """DeepseekV2RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
197
+
198
+ def __init__(
199
+ self,
200
+ dim,
201
+ max_position_embeddings=2048,
202
+ base=10000,
203
+ device=None,
204
+ scaling_factor=1.0,
205
+ ):
206
+ self.scaling_factor = scaling_factor
207
+ super().__init__(dim, max_position_embeddings, base, device)
208
+
209
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
210
+ self.max_seq_len_cached = seq_len
211
+
212
+ if seq_len > self.max_position_embeddings:
213
+ base = self.base * (
214
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
215
+ - (self.scaling_factor - 1)
216
+ ) ** (self.dim / (self.dim - 2))
217
+ inv_freq = 1.0 / (
218
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
219
+ )
220
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
221
+
222
+ t = torch.arange(
223
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
224
+ )
225
+
226
+ freqs = torch.outer(t, self.inv_freq)
227
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
228
+ emb = torch.cat((freqs, freqs), dim=-1)
229
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
230
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
231
+
232
+
233
+ # Inverse dim formula to find dim based on number of rotations
234
+ def yarn_find_correction_dim(
235
+ num_rotations, dim, base=10000, max_position_embeddings=2048
236
+ ):
237
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
238
+ 2 * math.log(base)
239
+ )
240
+
241
+
242
+ # Find dim range bounds based on rotations
243
+ def yarn_find_correction_range(
244
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
245
+ ):
246
+ low = math.floor(
247
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
248
+ )
249
+ high = math.ceil(
250
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
251
+ )
252
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
253
+
254
+
255
+ def yarn_get_mscale(scale=1, mscale=1):
256
+ if scale <= 1:
257
+ return 1.0
258
+ return 0.1 * mscale * math.log(scale) + 1.0
259
+
260
+
261
+ def yarn_linear_ramp_mask(min, max, dim):
262
+ if min == max:
263
+ max += 0.001 # Prevent singularity
264
+
265
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
266
+ ramp_func = torch.clamp(linear_func, 0, 1)
267
+ return ramp_func
268
+
269
+
270
+ class DeepseekV2YarnRotaryEmbedding(DeepseekV2RotaryEmbedding):
271
+
272
+ def __init__(
273
+ self,
274
+ dim,
275
+ max_position_embeddings=2048,
276
+ base=10000,
277
+ device=None,
278
+ scaling_factor=1.0,
279
+ original_max_position_embeddings=4096,
280
+ beta_fast=32,
281
+ beta_slow=1,
282
+ mscale=1,
283
+ mscale_all_dim=0,
284
+ ):
285
+ self.scaling_factor = scaling_factor
286
+ self.original_max_position_embeddings = original_max_position_embeddings
287
+ self.beta_fast = beta_fast
288
+ self.beta_slow = beta_slow
289
+ self.mscale = mscale
290
+ self.mscale_all_dim = mscale_all_dim
291
+ super().__init__(dim, max_position_embeddings, base, device)
292
+
293
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
294
+ self.max_seq_len_cached = seq_len
295
+ dim = self.dim
296
+
297
+ freq_extra = 1.0 / (
298
+ self.base
299
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
300
+ )
301
+ freq_inter = 1.0 / (
302
+ self.scaling_factor
303
+ * self.base
304
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
305
+ )
306
+
307
+ low, high = yarn_find_correction_range(
308
+ self.beta_fast,
309
+ self.beta_slow,
310
+ dim,
311
+ self.base,
312
+ self.original_max_position_embeddings,
313
+ )
314
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
315
+ device=device, dtype=torch.float32
316
+ )
317
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
318
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
319
+
320
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
321
+
322
+ freqs = torch.outer(t, inv_freq)
323
+
324
+ _mscale = float(
325
+ yarn_get_mscale(self.scaling_factor, self.mscale)
326
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
327
+ )
328
+
329
+ emb = torch.cat((freqs, freqs), dim=-1)
330
+ self.register_buffer(
331
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
332
+ )
333
+ self.register_buffer(
334
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
335
+ )
336
+
337
+
338
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
339
+ def rotate_half(x):
340
+ """Rotates half the hidden dims of the input."""
341
+ x1 = x[..., : x.shape[-1] // 2]
342
+ x2 = x[..., x.shape[-1] // 2 :]
343
+ return torch.cat((-x2, x1), dim=-1)
344
+
345
+
346
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
347
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
348
+ """Applies Rotary Position Embedding to the query and key tensors.
349
+
350
+ Args:
351
+ q (`torch.Tensor`): The query tensor.
352
+ k (`torch.Tensor`): The key tensor.
353
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
354
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
355
+ position_ids (`torch.Tensor`):
356
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
357
+ used to pass offsetted position ids when working with a KV-cache.
358
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
359
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
360
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
361
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
362
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
363
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
364
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
365
+ Returns:
366
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
367
+ """
368
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
369
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
370
+
371
+
372
+ # print()
373
+
374
+ b, h, s, d = q.shape
375
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
376
+
377
+ b, h, s, d = k.shape
378
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
379
+
380
+ q_embed = (q * cos) + (rotate_half(q) * sin)
381
+ k_embed = (k * cos) + (rotate_half(k) * sin)
382
+
383
+
384
+ return q_embed, k_embed
385
+
386
+
387
+ class DeepseekV2MLP(nn.Module):
388
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
389
+ super().__init__()
390
+ self.config = config
391
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
392
+ self.intermediate_size = (
393
+ config.intermediate_size if intermediate_size is None else intermediate_size
394
+ )
395
+
396
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
397
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
398
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
399
+ self.act_fn = ACT2FN[config.hidden_act]
400
+
401
+ def forward(self, x):
402
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
403
+ return down_proj
404
+
405
+
406
+ class MoEGate(nn.Module):
407
+ def __init__(self, config):
408
+ super().__init__()
409
+ self.config = config
410
+ self.top_k = config.num_experts_per_tok
411
+ self.n_routed_experts = config.n_routed_experts
412
+ self.routed_scaling_factor = config.routed_scaling_factor
413
+ self.scoring_func = config.scoring_func
414
+ self.alpha = config.aux_loss_alpha
415
+ self.seq_aux = config.seq_aux
416
+ self.topk_method = config.topk_method
417
+ self.n_group = config.n_group
418
+ self.topk_group = config.topk_group
419
+
420
+ # topk selection algorithm
421
+ self.norm_topk_prob = config.norm_topk_prob
422
+ self.gating_dim = config.hidden_size
423
+ self.weight = nn.Parameter(
424
+ torch.empty((self.n_routed_experts, self.gating_dim))
425
+ )
426
+ if self.topk_method == "noaux_tc":
427
+ self.e_score_correction_bias = nn.Parameter(
428
+ torch.empty((self.n_routed_experts))
429
+ )
430
+ self.reset_parameters()
431
+
432
+ def reset_parameters(self) -> None:
433
+ import torch.nn.init as init
434
+
435
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
436
+
437
+ def forward(self, hidden_states):
438
+ bsz, seq_len, h = hidden_states.shape
439
+ ### compute gating score
440
+ hidden_states = hidden_states.view(-1, h)
441
+ logits = F.linear(
442
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
443
+ )
444
+ if self.scoring_func == "softmax":
445
+ scores = logits.softmax(dim=-1, dtype=torch.float32)
446
+ elif self.scoring_func == "sigmoid":
447
+ scores = logits.sigmoid()
448
+ else:
449
+ raise NotImplementedError(
450
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
451
+ )
452
+
453
+ ### select top-k experts
454
+ if self.topk_method == "greedy":
455
+ topk_weight, topk_idx = torch.topk(
456
+ scores, k=self.top_k, dim=-1, sorted=False
457
+ )
458
+ elif self.topk_method == "group_limited_greedy":
459
+ group_scores = (
460
+ scores.view(bsz * seq_len, self.n_group, -1).max(dim=-1).values
461
+ ) # [n, n_group]
462
+ group_idx = torch.topk(
463
+ group_scores, k=self.topk_group, dim=-1, sorted=False
464
+ )[
465
+ 1
466
+ ] # [n, top_k_group]
467
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
468
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
469
+ score_mask = (
470
+ group_mask.unsqueeze(-1)
471
+ .expand(
472
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
473
+ )
474
+ .reshape(bsz * seq_len, -1)
475
+ ) # [n, e]
476
+ tmp_scores = scores.masked_fill(~score_mask.bool(), 0.0) # [n, e]
477
+ topk_weight, topk_idx = torch.topk(
478
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
479
+ )
480
+ elif self.topk_method == "noaux_tc":
481
+ assert not self.training
482
+ scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
483
+ group_scores = (
484
+ scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
485
+ ) # [n, n_group]
486
+ group_idx = torch.topk(
487
+ group_scores, k=self.topk_group, dim=-1, sorted=False
488
+ )[
489
+ 1
490
+ ] # [n, top_k_group]
491
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
492
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
493
+ score_mask = (
494
+ group_mask.unsqueeze(-1)
495
+ .expand(
496
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
497
+ )
498
+ .reshape(bsz * seq_len, -1)
499
+ ) # [n, e]
500
+ tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), 0.0) # [n, e]
501
+ _, topk_idx = torch.topk(
502
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
503
+ )
504
+ topk_weight = scores.gather(1, topk_idx)
505
+
506
+ ### norm gate to sum 1
507
+ if self.top_k > 1 and self.norm_topk_prob:
508
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
509
+ topk_weight = topk_weight / denominator * self.routed_scaling_factor
510
+ else:
511
+ topk_weight = topk_weight * self.routed_scaling_factor
512
+ ### expert-level computation auxiliary loss
513
+ if self.training and self.alpha > 0.0:
514
+ scores_for_aux = scores
515
+ aux_topk = self.top_k
516
+ # always compute aux loss based on the naive greedy topk method
517
+ topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
518
+ if self.seq_aux:
519
+ scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
520
+ ce = torch.zeros(
521
+ bsz, self.n_routed_experts, device=hidden_states.device
522
+ )
523
+ ce.scatter_add_(
524
+ 1,
525
+ topk_idx_for_aux_loss,
526
+ torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device),
527
+ ).div_(seq_len * aux_topk / self.n_routed_experts)
528
+ aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(
529
+ dim=1
530
+ ).mean() * self.alpha
531
+ else:
532
+ mask_ce = F.one_hot(
533
+ topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts
534
+ )
535
+ ce = mask_ce.float().mean(0)
536
+ Pi = scores_for_aux.mean(0)
537
+ fi = ce * self.n_routed_experts
538
+ aux_loss = (Pi * fi).sum() * self.alpha
539
+ else:
540
+ aux_loss = None
541
+ return topk_idx, topk_weight, aux_loss
542
+
543
+
544
+ class AddAuxiliaryLoss(torch.autograd.Function):
545
+ """
546
+ The trick function of adding auxiliary (aux) loss,
547
+ which includes the gradient of the aux loss during backpropagation.
548
+ """
549
+
550
+ @staticmethod
551
+ def forward(ctx, x, loss):
552
+ assert loss.numel() == 1
553
+ ctx.dtype = loss.dtype
554
+ ctx.required_aux_loss = loss.requires_grad
555
+ return x
556
+
557
+ @staticmethod
558
+ def backward(ctx, grad_output):
559
+ grad_loss = None
560
+ if ctx.required_aux_loss:
561
+ grad_loss = torch.ones(1, dtype=ctx.dtype, device=grad_output.device)
562
+ return grad_output, grad_loss
563
+
564
+
565
+ class DeepseekV2MoE(nn.Module):
566
+ """
567
+ A mixed expert module containing shared experts.
568
+ """
569
+
570
+ def __init__(self, config):
571
+ super().__init__()
572
+ self.config = config
573
+ self.num_experts_per_tok = config.num_experts_per_tok
574
+
575
+ if hasattr(config, "ep_size") and config.ep_size > 1:
576
+ assert config.ep_size == dist.get_world_size()
577
+ self.ep_size = config.ep_size
578
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
579
+ self.ep_rank = dist.get_rank()
580
+ self.experts = nn.ModuleList(
581
+ [
582
+ (
583
+ DeepseekV2MLP(
584
+ config, intermediate_size=config.moe_intermediate_size
585
+ )
586
+ if i >= self.ep_rank * self.experts_per_rank
587
+ and i < (self.ep_rank + 1) * self.experts_per_rank
588
+ else None
589
+ )
590
+ for i in range(config.n_routed_experts)
591
+ ]
592
+ )
593
+ else:
594
+ self.ep_size = 1
595
+ self.experts_per_rank = config.n_routed_experts
596
+ self.ep_rank = 0
597
+ self.experts = nn.ModuleList(
598
+ [
599
+ DeepseekV2MLP(
600
+ config, intermediate_size=config.moe_intermediate_size
601
+ )
602
+ for i in range(config.n_routed_experts)
603
+ ]
604
+ )
605
+ self.gate = MoEGate(config)
606
+ if config.n_shared_experts is not None:
607
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
608
+ self.shared_experts = DeepseekV2MLP(
609
+ config=config, intermediate_size=intermediate_size
610
+ )
611
+
612
+ def forward(self, hidden_states):
613
+ identity = hidden_states
614
+ orig_shape = hidden_states.shape
615
+ topk_idx, topk_weight, aux_loss = self.gate(hidden_states)
616
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
617
+ flat_topk_idx = topk_idx.view(-1)
618
+ if self.training:
619
+ hidden_states = hidden_states.repeat_interleave(
620
+ self.num_experts_per_tok, dim=0
621
+ )
622
+ y = torch.empty_like(hidden_states)
623
+ for i, expert in enumerate(self.experts):
624
+ y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
625
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
626
+ y = y.to(hidden_states.dtype).view(*orig_shape)
627
+ y = AddAuxiliaryLoss.apply(y, aux_loss)
628
+ else:
629
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
630
+ if self.config.n_shared_experts is not None:
631
+ y = y + self.shared_experts(identity)
632
+ return y
633
+
634
+ @torch.no_grad()
635
+ def moe_infer(self, x, topk_ids, topk_weight):
636
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
637
+ cnts.scatter_(1, topk_ids, 1)
638
+ tokens_per_expert = cnts.sum(dim=0)
639
+ idxs = topk_ids.view(-1).argsort()
640
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
641
+ sorted_tokens_shape = sorted_tokens.shape
642
+ if self.ep_size > 1:
643
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
644
+ tokens_per_expert_group = tokens_per_expert.new_empty(
645
+ tokens_per_expert.shape[0]
646
+ )
647
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
648
+ output_splits = (
649
+ tokens_per_expert_group.view(self.ep_size, -1)
650
+ .sum(1)
651
+ .cpu()
652
+ .numpy()
653
+ .tolist()
654
+ )
655
+ gathered_tokens = sorted_tokens.new_empty(
656
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
657
+ )
658
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
659
+ dist.all_to_all(
660
+ list(gathered_tokens.split(output_splits)),
661
+ list(sorted_tokens.split(input_split_sizes)),
662
+ )
663
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(
664
+ self.ep_size, self.experts_per_rank
665
+ ).sum(dim=0)
666
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
667
+ s = 0
668
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
669
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
670
+ s += k
671
+ gatherd_idxs = gatherd_idxs.argsort()
672
+ sorted_tokens = gathered_tokens[gatherd_idxs]
673
+ tokens_per_expert = tokens_per_expert_post_gather
674
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
675
+
676
+ outputs = []
677
+ start_idx = 0
678
+ for i, num_tokens in enumerate(tokens_per_expert):
679
+ end_idx = start_idx + num_tokens
680
+ if num_tokens == 0:
681
+ continue
682
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
683
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
684
+ expert_out = expert(tokens_for_this_expert)
685
+ outputs.append(expert_out)
686
+ start_idx = end_idx
687
+
688
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
689
+ if self.ep_size > 1:
690
+ new_x = torch.empty_like(outs)
691
+ new_x[gatherd_idxs] = outs
692
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
693
+ dist.all_to_all(
694
+ list(gathered_tokens.split(input_split_sizes)),
695
+ list(new_x.split(output_splits)),
696
+ )
697
+ outs = gathered_tokens
698
+
699
+ new_x = torch.empty_like(outs)
700
+ new_x[idxs] = outs
701
+ final_out = (
702
+ new_x.view(*topk_ids.shape, -1)
703
+ .type(topk_weight.dtype)
704
+ .mul_(topk_weight.unsqueeze(dim=-1))
705
+ .sum(dim=1)
706
+ .type(new_x.dtype)
707
+ )
708
+ return final_out
709
+
710
+
711
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
712
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
713
+ """
714
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
715
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
716
+ """
717
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
718
+ if n_rep == 1:
719
+ return hidden_states
720
+ hidden_states = hidden_states[:, :, None, :, :].expand(
721
+ batch, num_key_value_heads, n_rep, slen, head_dim
722
+ )
723
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
724
+
725
+
726
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV2
727
+ class DeepseekV2Attention(nn.Module):
728
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
729
+
730
+ def __init__(self, config: DeepseekV2Config, layer_idx: Optional[int] = None):
731
+ super().__init__()
732
+ self.config = config
733
+ self.layer_idx = layer_idx
734
+ if layer_idx is None:
735
+ logger.warning_once(
736
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
737
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
738
+ "when creating this class."
739
+ )
740
+
741
+ self.attention_dropout = config.attention_dropout
742
+ self.hidden_size = config.hidden_size
743
+ self.num_heads = config.num_attention_heads
744
+
745
+ self.max_position_embeddings = config.max_position_embeddings
746
+ self.rope_theta = config.rope_theta
747
+ self.q_lora_rank = config.q_lora_rank
748
+ self.qk_rope_head_dim = config.qk_rope_head_dim
749
+ self.kv_lora_rank = config.kv_lora_rank
750
+ self.v_head_dim = config.v_head_dim
751
+ self.qk_nope_head_dim = config.qk_nope_head_dim
752
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
753
+
754
+ self.is_causal = True
755
+
756
+ if self.q_lora_rank is None:
757
+ self.q_proj = nn.Linear(
758
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
759
+ )
760
+ else:
761
+ self.q_a_proj = nn.Linear(
762
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
763
+ )
764
+ self.q_a_layernorm = DeepseekV2RMSNorm(config.q_lora_rank)
765
+ self.q_b_proj = nn.Linear(
766
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
767
+ )
768
+ # config.kv_lora_rank + config.qk_rope_head_dim,
769
+ self.kv_a_proj_with_mqa = nn.Linear(
770
+ self.hidden_size,
771
+ config.kv_lora_rank + config.qk_rope_head_dim,
772
+ bias=config.attention_bias,
773
+ )
774
+ self.kv_a_layernorm = DeepseekV2RMSNorm(config.kv_lora_rank)
775
+ self.kv_b_proj = nn.Linear(
776
+ config.kv_lora_rank,
777
+ self.num_heads
778
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
779
+ bias=False,
780
+ )
781
+
782
+ self.o_proj = nn.Linear(
783
+ self.num_heads * self.v_head_dim,
784
+ self.hidden_size,
785
+ bias=config.attention_bias,
786
+ )
787
+ self._init_rope()
788
+
789
+ self.softmax_scale = self.q_head_dim ** (-0.5)
790
+ if self.config.rope_scaling is not None:
791
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
792
+ scaling_factor = self.config.rope_scaling["factor"]
793
+ if mscale_all_dim:
794
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
795
+ self.softmax_scale = self.softmax_scale * mscale * mscale
796
+
797
+ def _init_rope(self):
798
+ if self.config.rope_scaling is None:
799
+ self.rotary_emb = DeepseekV2RotaryEmbedding(
800
+ self.qk_rope_head_dim,
801
+ max_position_embeddings=self.max_position_embeddings,
802
+ base=self.rope_theta,
803
+ )
804
+ # self.rotary_emb = DeepseekV2LinearScalingRotaryEmbedding(
805
+ # self.qk_rope_head_dim,
806
+ # max_position_embeddings=self.max_position_embeddings,
807
+ # scaling_factor=scaling_factor,
808
+ # base=self.rope_theta,
809
+ # )
810
+ else:
811
+ scaling_type = self.config.rope_scaling["type"]
812
+ scaling_factor = self.config.rope_scaling["factor"]
813
+ if scaling_type == "linear":
814
+ self.rotary_emb = DeepseekV2LinearScalingRotaryEmbedding(
815
+ self.qk_rope_head_dim,
816
+ max_position_embeddings=self.max_position_embeddings,
817
+ scaling_factor=scaling_factor,
818
+ base=self.rope_theta,
819
+ )
820
+ elif scaling_type == "dynamic":
821
+ self.rotary_emb = DeepseekV2DynamicNTKScalingRotaryEmbedding(
822
+ self.qk_rope_head_dim,
823
+ max_position_embeddings=self.max_position_embeddings,
824
+ scaling_factor=scaling_factor,
825
+ base=self.rope_theta,
826
+ )
827
+ elif scaling_type == "yarn":
828
+ kwargs = {
829
+ key: self.config.rope_scaling[key]
830
+ for key in [
831
+ "original_max_position_embeddings",
832
+ "beta_fast",
833
+ "beta_slow",
834
+ "mscale",
835
+ "mscale_all_dim",
836
+ ]
837
+ if key in self.config.rope_scaling
838
+ }
839
+ self.rotary_emb = DeepseekV2YarnRotaryEmbedding(
840
+ self.qk_rope_head_dim,
841
+ max_position_embeddings=self.max_position_embeddings,
842
+ scaling_factor=scaling_factor,
843
+ base=self.rope_theta,
844
+ **kwargs,
845
+ )
846
+ else:
847
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
848
+
849
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
850
+ return (
851
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
852
+ .transpose(1, 2)
853
+ .contiguous()
854
+ )
855
+
856
+ def forward(
857
+ self,
858
+ hidden_states: torch.Tensor,
859
+ attention_mask: Optional[torch.Tensor] = None,
860
+ position_ids: Optional[torch.LongTensor] = None,
861
+ past_key_value: Optional[Cache] = None,
862
+ output_attentions: bool = False,
863
+ use_cache: bool = False,
864
+ **kwargs,
865
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
866
+ if "padding_mask" in kwargs:
867
+ warnings.warn(
868
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
869
+ )
870
+ bsz, q_len, _ = hidden_states.size()
871
+
872
+ if self.q_lora_rank is None:
873
+ q = self.q_proj(hidden_states)
874
+ else:
875
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
876
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
877
+
878
+
879
+ q_nope, q_pe = torch.split(
880
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
881
+ )
882
+
883
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
884
+ compressed_kv, k_pe = torch.split(
885
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
886
+ )
887
+ compressed_kv = self.kv_a_layernorm(compressed_kv)
888
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
889
+
890
+ kv_seq_len = k_pe.shape[-2]
891
+ if past_key_value is not None:
892
+ if self.layer_idx is None:
893
+ raise ValueError(
894
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
895
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
896
+ "with a layer index."
897
+ )
898
+ kv_seq_len += past_key_value.get_seq_length(self.layer_idx)
899
+
900
+ cos, sin = self.rotary_emb(q_pe, seq_len=kv_seq_len)
901
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
902
+
903
+ if past_key_value is not None:
904
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
905
+ compressed_kv = compressed_kv.unsqueeze(1)
906
+ k_pe, compressed_kv = past_key_value.update(k_pe, compressed_kv, self.layer_idx, cache_kwargs)
907
+ compressed_kv = compressed_kv.squeeze(1)
908
+
909
+ kv_b_proj = self.kv_b_proj.weight.view(self.num_heads, -1, self.kv_lora_rank)
910
+ q_absorb = kv_b_proj[:, :self.qk_nope_head_dim, :]
911
+ out_absorb = kv_b_proj[:, self.qk_nope_head_dim:, :]
912
+
913
+ q_nope = torch.matmul(q_nope, q_absorb)
914
+ attn_weights = (torch.matmul(q_pe, k_pe.mT) +
915
+ torch.matmul(q_nope, compressed_kv.unsqueeze(-3).mT)) * self.softmax_scale
916
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
917
+ raise ValueError(
918
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
919
+ f" {attn_weights.size()}"
920
+ )
921
+ assert attention_mask is not None
922
+ if attention_mask is not None:
923
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
924
+ raise ValueError(
925
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
926
+ )
927
+ attn_weights = attn_weights + attention_mask
928
+
929
+ # upcast attention to fp32
930
+ attn_weights = nn.functional.softmax(
931
+ attn_weights, dim=-1, dtype=torch.float32
932
+ ).to(q_pe.dtype)
933
+ attn_weights = nn.functional.dropout(
934
+ attn_weights, p=self.attention_dropout, training=self.training
935
+ )
936
+ attn_output = torch.einsum('bhql,blc->bhqc', attn_weights, compressed_kv)
937
+
938
+ attn_output = torch.matmul(attn_output, out_absorb.mT)
939
+
940
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
941
+ raise ValueError(
942
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
943
+ f" {attn_output.size()}"
944
+ )
945
+
946
+ attn_output = attn_output.transpose(1, 2).contiguous()
947
+
948
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
949
+
950
+ attn_output = self.o_proj(attn_output)
951
+
952
+ if not output_attentions:
953
+ attn_weights = None
954
+
955
+ return attn_output, attn_weights, past_key_value
956
+
957
+
958
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV2
959
+ class DeepseekV2FlashAttention2(DeepseekV2Attention):
960
+ """
961
+ DeepseekV2 flash attention module. This module inherits from `DeepseekV2Attention` as the weights of the module stays
962
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
963
+ flash attention and deal with padding tokens in case the input contains any of them.
964
+ """
965
+
966
+ def __init__(self, *args, **kwargs):
967
+ super().__init__(*args, **kwargs)
968
+
969
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
970
+ # 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.
971
+ # 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).
972
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
973
+
974
+ def forward(
975
+ self,
976
+ hidden_states: torch.Tensor,
977
+ attention_mask: Optional[torch.LongTensor] = None,
978
+ position_ids: Optional[torch.LongTensor] = None,
979
+ past_key_value: Optional[Cache] = None,
980
+ output_attentions: bool = False,
981
+ use_cache: bool = False,
982
+ **kwargs,
983
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
984
+ # DeepseekV2FlashAttention2 attention does not support output_attentions
985
+ if "padding_mask" in kwargs:
986
+ warnings.warn(
987
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
988
+ )
989
+
990
+ # overwrite attention_mask with padding_mask
991
+ attention_mask = kwargs.pop("padding_mask")
992
+
993
+ output_attentions = False
994
+
995
+ bsz, q_len, _ = hidden_states.size()
996
+
997
+ if self.q_lora_rank is None:
998
+ q = self.q_proj(hidden_states)
999
+ else:
1000
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
1001
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
1002
+ q_nope, q_pe = torch.split(
1003
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
1004
+ )
1005
+
1006
+ # Flash attention requires the input to have the shape
1007
+ # batch_size x seq_length x head_dim x hidden_dim
1008
+ # therefore we just need to keep the original shape
1009
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
1010
+ compressed_kv, k_pe = torch.split(
1011
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
1012
+ )
1013
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
1014
+ kv = (
1015
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
1016
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
1017
+ .transpose(1, 2)
1018
+ )
1019
+
1020
+ k_nope, value_states = torch.split(
1021
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
1022
+ )
1023
+ kv_seq_len = value_states.shape[-2]
1024
+
1025
+ kv_seq_len = value_states.shape[-2]
1026
+ if past_key_value is not None:
1027
+ kv_seq_len += past_key_value.get_seq_length(self.layer_idx)
1028
+
1029
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1030
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1031
+
1032
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1033
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1034
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1035
+
1036
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1037
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1038
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1039
+
1040
+ if self.q_head_dim != self.v_head_dim:
1041
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
1042
+
1043
+ # TODO: support compressed_kv for kv_cache (instead of key_states, value_states) in flash_attention version
1044
+ if past_key_value is not None:
1045
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1046
+ key_states, value_states = past_key_value.update(
1047
+ key_states, value_states, self.layer_idx, cache_kwargs
1048
+ )
1049
+
1050
+ # 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
1051
+ # to be able to avoid many of these transpose/reshape/view.
1052
+ query_states = query_states.transpose(1, 2)
1053
+ key_states = key_states.transpose(1, 2)
1054
+ value_states = value_states.transpose(1, 2)
1055
+
1056
+ dropout_rate = self.attention_dropout if self.training else 0.0
1057
+
1058
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
1059
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
1060
+ # cast them back in the correct dtype just to be sure everything works as expected.
1061
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
1062
+ # in fp32. (DeepseekV2RMSNorm handles it correctly)
1063
+
1064
+ input_dtype = query_states.dtype
1065
+ if input_dtype == torch.float32:
1066
+ # Handle the case where the model is quantized
1067
+ if hasattr(self.config, "_pre_quantization_dtype"):
1068
+ target_dtype = self.config._pre_quantization_dtype
1069
+ elif torch.is_autocast_enabled():
1070
+ target_dtype = torch.get_autocast_gpu_dtype()
1071
+ else:
1072
+ target_dtype = (
1073
+ self.q_proj.weight.dtype
1074
+ if self.q_lora_rank is None
1075
+ else self.q_a_proj.weight.dtype
1076
+ )
1077
+
1078
+ logger.warning_once(
1079
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
1080
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
1081
+ f" {target_dtype}."
1082
+ )
1083
+
1084
+ query_states = query_states.to(target_dtype)
1085
+ key_states = key_states.to(target_dtype)
1086
+ value_states = value_states.to(target_dtype)
1087
+
1088
+ attn_output = self._flash_attention_forward(
1089
+ query_states,
1090
+ key_states,
1091
+ value_states,
1092
+ attention_mask,
1093
+ q_len,
1094
+ dropout=dropout_rate,
1095
+ softmax_scale=self.softmax_scale,
1096
+ )
1097
+ if self.q_head_dim != self.v_head_dim:
1098
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
1099
+
1100
+ attn_output = attn_output.reshape(
1101
+ bsz, q_len, self.num_heads * self.v_head_dim
1102
+ ).contiguous()
1103
+ attn_output = self.o_proj(attn_output)
1104
+
1105
+ if not output_attentions:
1106
+ attn_weights = None
1107
+
1108
+ return attn_output, attn_weights, past_key_value
1109
+
1110
+ def _flash_attention_forward(
1111
+ self,
1112
+ query_states,
1113
+ key_states,
1114
+ value_states,
1115
+ attention_mask,
1116
+ query_length,
1117
+ dropout=0.0,
1118
+ softmax_scale=None,
1119
+ ):
1120
+ """
1121
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1122
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1123
+
1124
+ Args:
1125
+ query_states (`torch.Tensor`):
1126
+ Input query states to be passed to Flash Attention API
1127
+ key_states (`torch.Tensor`):
1128
+ Input key states to be passed to Flash Attention API
1129
+ value_states (`torch.Tensor`):
1130
+ Input value states to be passed to Flash Attention API
1131
+ attention_mask (`torch.Tensor`):
1132
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1133
+ position of padding tokens and 1 for the position of non-padding tokens.
1134
+ dropout (`int`, *optional*):
1135
+ Attention dropout
1136
+ softmax_scale (`float`, *optional*):
1137
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1138
+ """
1139
+ if not self._flash_attn_uses_top_left_mask:
1140
+ causal = self.is_causal
1141
+ else:
1142
+ # 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__.
1143
+ causal = self.is_causal and query_length != 1
1144
+
1145
+ # Contains at least one padding token in the sequence
1146
+ if attention_mask is not None:
1147
+ batch_size = query_states.shape[0]
1148
+ (
1149
+ query_states,
1150
+ key_states,
1151
+ value_states,
1152
+ indices_q,
1153
+ cu_seq_lens,
1154
+ max_seq_lens,
1155
+ ) = self._upad_input(
1156
+ query_states, key_states, value_states, attention_mask, query_length
1157
+ )
1158
+
1159
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1160
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1161
+
1162
+ attn_output_unpad = flash_attn_varlen_func(
1163
+ query_states,
1164
+ key_states,
1165
+ value_states,
1166
+ cu_seqlens_q=cu_seqlens_q,
1167
+ cu_seqlens_k=cu_seqlens_k,
1168
+ max_seqlen_q=max_seqlen_in_batch_q,
1169
+ max_seqlen_k=max_seqlen_in_batch_k,
1170
+ dropout_p=dropout,
1171
+ softmax_scale=softmax_scale,
1172
+ causal=causal,
1173
+ )
1174
+
1175
+ attn_output = pad_input(
1176
+ attn_output_unpad, indices_q, batch_size, query_length
1177
+ )
1178
+ else:
1179
+ attn_output = flash_attn_func(
1180
+ query_states,
1181
+ key_states,
1182
+ value_states,
1183
+ dropout,
1184
+ softmax_scale=softmax_scale,
1185
+ causal=causal,
1186
+ )
1187
+
1188
+ return attn_output
1189
+
1190
+ def _upad_input(
1191
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
1192
+ ):
1193
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1194
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1195
+
1196
+ key_layer = index_first_axis(
1197
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1198
+ indices_k,
1199
+ )
1200
+ value_layer = index_first_axis(
1201
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1202
+ indices_k,
1203
+ )
1204
+ if query_length == kv_seq_len:
1205
+ query_layer = index_first_axis(
1206
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1207
+ indices_k,
1208
+ )
1209
+ cu_seqlens_q = cu_seqlens_k
1210
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1211
+ indices_q = indices_k
1212
+ elif query_length == 1:
1213
+ max_seqlen_in_batch_q = 1
1214
+ cu_seqlens_q = torch.arange(
1215
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1216
+ ) # There is a memcpy here, that is very bad.
1217
+ indices_q = cu_seqlens_q[:-1]
1218
+ query_layer = query_layer.squeeze(1)
1219
+ else:
1220
+ # The -q_len: slice assumes left padding.
1221
+ attention_mask = attention_mask[:, -query_length:]
1222
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1223
+ query_layer, attention_mask
1224
+ )
1225
+
1226
+ return (
1227
+ query_layer,
1228
+ key_layer,
1229
+ value_layer,
1230
+ indices_q,
1231
+ (cu_seqlens_q, cu_seqlens_k),
1232
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1233
+ )
1234
+
1235
+
1236
+ # ★ FLASH_MHA (2026-07-17): 학습 프리필 attention을 flash-attn2로. env FLASH_MHA=1.
1237
+ import os as _os_fm
1238
+ _FLASH_MHA_OK = False
1239
+ _flash_attn_func = None
1240
+ if _os_fm.environ.get("FLASH_MHA") == "1":
1241
+ try:
1242
+ from flash_attn import flash_attn_func as _flash_attn_func
1243
+ _FLASH_MHA_OK = True
1244
+ print("FLASH_MHA=1: 학습 프리필 attention -> flash_attn2", flush=True)
1245
+ except Exception as _e:
1246
+ print(f"FLASH_MHA 요청됐으나 import 실패({_e}) — eager 유지", flush=True)
1247
+
1248
+
1249
+ class SlidingWindowLlamaAttention(LlamaAttention):
1250
+ """LlamaAttention with sliding window KV cache using a ring buffer during decode."""
1251
+
1252
+ def __init__(self, config, layer_idx):
1253
+ super().__init__(config, layer_idx)
1254
+ # New transformers moved rotary_emb to model level; create our own
1255
+ if not hasattr(self, 'rotary_emb'):
1256
+ from transformers.models.llama.modeling_llama import LlamaRotaryEmbedding
1257
+ self.rotary_emb = LlamaRotaryEmbedding(config=config)
1258
+ # Save sliding_window separately so we can disable it in config to prevent
1259
+ # DynamicCache from truncating prefill tokens
1260
+ self._sliding_window = getattr(config, 'sliding_window', None)
1261
+
1262
+ def forward(self, *args, **kwargs):
1263
+ import math
1264
+
1265
+ # Compatibility: new DynamicCache uses .layers[i].keys/.values instead of .key_cache[i]/.value_cache[i]
1266
+ def _get_kcache(cache, layer_idx):
1267
+ if hasattr(cache, 'key_cache'):
1268
+ return cache.key_cache[layer_idx]
1269
+ return cache.layers[layer_idx].keys
1270
+
1271
+ def _get_vcache(cache, layer_idx):
1272
+ if hasattr(cache, 'value_cache'):
1273
+ return cache.value_cache[layer_idx]
1274
+ return cache.layers[layer_idx].values
1275
+
1276
+ # Extract args
1277
+ def _get(name, idx, default=None):
1278
+ if name in kwargs:
1279
+ return kwargs[name]
1280
+ if len(args) > idx:
1281
+ return args[idx]
1282
+ return default
1283
+
1284
+ hidden_states = _get('hidden_states', 0)
1285
+ attention_mask = _get('attention_mask', 1)
1286
+ position_ids = _get('position_ids', 2)
1287
+ past_kv = _get('past_key_value', 3)
1288
+ if past_kv is None:
1289
+ past_kv = kwargs.get('past_key_values', None)
1290
+ output_attentions = _get('output_attentions', 4, False)
1291
+
1292
+ # Dimensions from config (new transformers removed self.num_heads)
1293
+ num_heads = self.config.num_attention_heads
1294
+ num_kv_heads = self.config.num_key_value_heads
1295
+ head_dim = self.head_dim
1296
+ num_kv_groups = self.num_key_value_groups
1297
+
1298
+ bsz, q_len, _ = hidden_states.size()
1299
+ W = getattr(self.config, '_ring_window', None) # Read from config (set before generate)
1300
+
1301
+ # --- Helper: standard QKV attention ---
1302
+ def _attn_forward(use_cache_update=True):
1303
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, num_heads, head_dim).transpose(1, 2)
1304
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, num_kv_heads, head_dim).transpose(1, 2)
1305
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, num_kv_heads, head_dim).transpose(1, 2)
1306
+
1307
+ cos, sin = self.rotary_emb(value_states, position_ids)
1308
+ query_states, key_states = _llama_apply_rotary_pos_emb(query_states, key_states, cos, sin)
1309
+
1310
+ if past_kv is not None and use_cache_update:
1311
+ key_states, value_states = past_kv.update(key_states, value_states, self.layer_idx)
1312
+
1313
+ # ★ FLASH_MHA: 학습 프리필(=full causal, 오른쪽패딩이라 causal이 패딩을 자동 차단) 경로만 flash로.
1314
+ # 디코드(ring buffer)·generate 경로는 건드리지 않음. env FLASH_MHA=1에서만 활성.
1315
+ if _FLASH_MHA_OK and self.training and past_kv is None and q_len > 1:
1316
+ _q = query_states.transpose(1, 2) # (b, s, h, d)
1317
+ _k = key_states.transpose(1, 2)
1318
+ _v = value_states.transpose(1, 2)
1319
+ _o = _flash_attn_func(_q, _k, _v, dropout_p=(self.attention_dropout if self.training else 0.0),
1320
+ softmax_scale=1.0 / math.sqrt(head_dim), causal=True)
1321
+ attn_output = _o.reshape(bsz, q_len, -1)
1322
+ return self.o_proj(attn_output), None, past_kv
1323
+
1324
+ k = _llama_repeat_kv(key_states, num_kv_groups)
1325
+ v = _llama_repeat_kv(value_states, num_kv_groups)
1326
+
1327
+ attn_weights = torch.matmul(query_states, k.transpose(2, 3)) / math.sqrt(head_dim)
1328
+ if attention_mask is not None:
1329
+ causal_mask = attention_mask[:, :, :, :k.shape[-2]]
1330
+ attn_weights = attn_weights + causal_mask
1331
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
1332
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
1333
+ attn_output = torch.matmul(attn_weights, v)
1334
+ attn_output = attn_output.transpose(1, 2).contiguous().reshape(bsz, q_len, -1)
1335
+ attn_output = self.o_proj(attn_output)
1336
+ return attn_output, None, past_kv
1337
+
1338
+ # Prefill or no sliding window
1339
+ # True prefill: W disabled, no cache, or first forward (prefill_length not yet recorded)
1340
+ _is_true_prefill = (W is None or past_kv is None or
1341
+ (q_len > 1 and (not hasattr(past_kv, '_prefill_length') or
1342
+ self.layer_idx not in past_kv._prefill_length)))
1343
+ if _is_true_prefill:
1344
+ result = _attn_forward()
1345
+ if W is not None and past_kv is not None and q_len > 1:
1346
+ # Only record prefill_length the FIRST time (don't overwrite on subsequent q_len>1 calls)
1347
+ if not hasattr(past_kv, '_prefill_length'):
1348
+ past_kv._prefill_length = {}
1349
+ if self.layer_idx not in past_kv._prefill_length:
1350
+ past_kv._prefill_length[self.layer_idx] = _get_kcache(past_kv, self.layer_idx).shape[-2]
1351
+ return result
1352
+
1353
+ # Decode path: first decode step -> record prefill_length (only once!)
1354
+ if not hasattr(past_kv, '_prefill_length') or self.layer_idx not in past_kv._prefill_length:
1355
+ if not hasattr(past_kv, '_prefill_length'):
1356
+ past_kv._prefill_length = {}
1357
+ past_kv._prefill_length[self.layer_idx] = _get_kcache(past_kv, self.layer_idx).shape[-2]
1358
+
1359
+ prefill_len = past_kv._prefill_length[self.layer_idx]
1360
+ cur_len = _get_kcache(past_kv, self.layer_idx).shape[-2]
1361
+
1362
+ # Warmup: cat-append until ring region is full
1363
+ if cur_len < prefill_len + W:
1364
+ result = _attn_forward()
1365
+ new_len = _get_kcache(past_kv, self.layer_idx).shape[-2]
1366
+ if new_len >= prefill_len + W:
1367
+ if not hasattr(past_kv, '_ring_pos'):
1368
+ past_kv._ring_pos = {}
1369
+ past_kv._ring_pos[self.layer_idx] = 0
1370
+ return result
1371
+
1372
+ # Steady state: ring in-place overwrite
1373
+ if not hasattr(past_kv, '_ring_pos') or self.layer_idx not in past_kv._ring_pos:
1374
+ past_kv._ring_pos = getattr(past_kv, '_ring_pos', {}) or {}
1375
+ past_kv._ring_pos[self.layer_idx] = 0
1376
+
1377
+ # Ring decode: overwrite ring slots, then attention over full cache
1378
+ ring_pos = past_kv._ring_pos[self.layer_idx]
1379
+ kcache = _get_kcache(past_kv, self.layer_idx)
1380
+ vcache = _get_vcache(past_kv, self.layer_idx)
1381
+
1382
+ # Compute new K, V and apply RoPE, then overwrite ring slots
1383
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, num_heads, head_dim).transpose(1, 2)
1384
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, num_kv_heads, head_dim).transpose(1, 2)
1385
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, num_kv_heads, head_dim).transpose(1, 2)
1386
+ cos, sin = self.rotary_emb(value_states, position_ids)
1387
+ query_states, key_states = _llama_apply_rotary_pos_emb(query_states, key_states, cos, sin)
1388
+
1389
+ # Overwrite ring slots in-place
1390
+ for t in range(q_len):
1391
+ slot = prefill_len + ring_pos
1392
+ kcache[:, :, slot:slot + 1, :] = key_states[:, :, t:t + 1, :]
1393
+ vcache[:, :, slot:slot + 1, :] = value_states[:, :, t:t + 1, :]
1394
+ ring_pos = (ring_pos + 1) % W
1395
+ past_kv._ring_pos[self.layer_idx] = ring_pos
1396
+
1397
+ # Attention over full cache (no causal mask needed for decode q_len=1)
1398
+ k = _llama_repeat_kv(kcache, num_kv_groups)
1399
+ v = _llama_repeat_kv(vcache, num_kv_groups)
1400
+ attn_weights = torch.matmul(query_states, k.transpose(2, 3)) / math.sqrt(head_dim)
1401
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
1402
+ attn_output = torch.matmul(attn_weights, v)
1403
+ attn_output = attn_output.transpose(1, 2).contiguous().reshape(bsz, q_len, -1)
1404
+ attn_output = self.o_proj(attn_output)
1405
+ return attn_output, None, past_kv
1406
+
1407
+
1408
+ ATTENTION_CLASSES = {
1409
+ "eager": DeepseekV2Attention,
1410
+ "flash_attention_2": DeepseekV2FlashAttention2,
1411
+
1412
+ "mla_eager": DeepseekV2Attention,
1413
+ "mla_flash_attention_2": DeepseekV2FlashAttention2,
1414
+
1415
+ "mha_eager": SlidingWindowLlamaAttention,
1416
+ # "mha_flash_attention_2": LlamaFlashAttention2
1417
+ }
1418
+
1419
+
1420
+ class DeepseekV2DecoderLayer(nn.Module):
1421
+ def __init__(self, config: DeepseekV2Config, layer_idx: int):
1422
+ super().__init__()
1423
+ self.hidden_size = config.hidden_size
1424
+
1425
+
1426
+ if config.use_mla:
1427
+ attn_implementation = "mla_" + config._attn_implementation
1428
+ else:
1429
+ attn_implementation = "mha_" + config._attn_implementation
1430
+
1431
+ self.self_attn = ATTENTION_CLASSES[attn_implementation](
1432
+ config=config, layer_idx=layer_idx
1433
+ )
1434
+
1435
+ self.mlp = (
1436
+ DeepseekV2MoE(config)
1437
+ if (
1438
+ config.n_routed_experts is not None
1439
+ and layer_idx >= config.first_k_dense_replace
1440
+ and layer_idx % config.moe_layer_freq == 0
1441
+ )
1442
+ else DeepseekV2MLP(config)
1443
+ )
1444
+ self.input_layernorm = DeepseekV2RMSNorm(
1445
+ config.hidden_size, eps=config.rms_norm_eps
1446
+ )
1447
+ self.post_attention_layernorm = DeepseekV2RMSNorm(
1448
+ config.hidden_size, eps=config.rms_norm_eps
1449
+ )
1450
+
1451
+ def forward(
1452
+ self,
1453
+ hidden_states: torch.Tensor,
1454
+ attention_mask: Optional[torch.Tensor] = None,
1455
+ position_ids: Optional[torch.LongTensor] = None,
1456
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1457
+ output_attentions: Optional[bool] = False,
1458
+ use_cache: Optional[bool] = False,
1459
+ **kwargs,
1460
+ ) -> Tuple[
1461
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1462
+ ]:
1463
+ """
1464
+ Args:
1465
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1466
+ attention_mask (`torch.FloatTensor`, *optional*):
1467
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1468
+ query_sequence_length, key_sequence_length)` if default attention is used.
1469
+ output_attentions (`bool`, *optional*):
1470
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1471
+ returned tensors for more detail.
1472
+ use_cache (`bool`, *optional*):
1473
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1474
+ (see `past_key_values`).
1475
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1476
+ """
1477
+ if "padding_mask" in kwargs:
1478
+ warnings.warn(
1479
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1480
+ )
1481
+ residual = hidden_states
1482
+
1483
+ hidden_states = self.input_layernorm(hidden_states)
1484
+
1485
+ # Self Attention
1486
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1487
+ hidden_states=hidden_states,
1488
+ attention_mask=attention_mask,
1489
+ position_ids=position_ids,
1490
+ past_key_value=past_key_value,
1491
+ output_attentions=output_attentions,
1492
+ use_cache=use_cache,
1493
+ **kwargs,
1494
+ )
1495
+ hidden_states = residual + hidden_states
1496
+
1497
+ # Fully Connected
1498
+ residual = hidden_states
1499
+ hidden_states = self.post_attention_layernorm(hidden_states)
1500
+ hidden_states = self.mlp(hidden_states)
1501
+ hidden_states = residual + hidden_states
1502
+
1503
+ outputs = (hidden_states,)
1504
+
1505
+ if output_attentions:
1506
+ outputs += (self_attn_weights,)
1507
+
1508
+ if use_cache:
1509
+ outputs += (present_key_value,)
1510
+
1511
+ return outputs
1512
+
1513
+
1514
+ DeepseekV2_START_DOCSTRING = r"""
1515
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1516
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1517
+ etc.)
1518
+
1519
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1520
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1521
+ and behavior.
1522
+
1523
+ Parameters:
1524
+ config ([`DeepseekV2Config`]):
1525
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1526
+ load the weights associated with the model, only the configuration. Check out the
1527
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1528
+ """
1529
+
1530
+
1531
+ @add_start_docstrings(
1532
+ "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
1533
+ DeepseekV2_START_DOCSTRING,
1534
+ )
1535
+ class DeepseekV2PreTrainedModel(PreTrainedModel):
1536
+ config_class = DeepseekV2Config
1537
+ base_model_prefix = "model"
1538
+ supports_gradient_checkpointing = True
1539
+ _no_split_modules = ["DeepseekV2DecoderLayer"]
1540
+ _skip_keys_device_placement = "past_key_values"
1541
+ _supports_flash_attn_2 = True
1542
+ _supports_cache_class = True
1543
+
1544
+ def _init_weights(self, module):
1545
+ std = self.config.initializer_range
1546
+ if isinstance(module, nn.Linear):
1547
+ module.weight.data.normal_(mean=0.0, std=std)
1548
+ if module.bias is not None:
1549
+ module.bias.data.zero_()
1550
+ elif isinstance(module, nn.Embedding):
1551
+ module.weight.data.normal_(mean=0.0, std=std)
1552
+ if module.padding_idx is not None:
1553
+ module.weight.data[module.padding_idx].zero_()
1554
+
1555
+
1556
+ DeepseekV2_INPUTS_DOCSTRING = r"""
1557
+ Args:
1558
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1559
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1560
+ it.
1561
+
1562
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1563
+ [`PreTrainedTokenizer.__call__`] for details.
1564
+
1565
+ [What are input IDs?](../glossary#input-ids)
1566
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1567
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1568
+
1569
+ - 1 for tokens that are **not masked**,
1570
+ - 0 for tokens that are **masked**.
1571
+
1572
+ [What are attention masks?](../glossary#attention-mask)
1573
+
1574
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1575
+ [`PreTrainedTokenizer.__call__`] for details.
1576
+
1577
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1578
+ `past_key_values`).
1579
+
1580
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1581
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1582
+ information on the default strategy.
1583
+
1584
+ - 1 indicates the head is **not masked**,
1585
+ - 0 indicates the head is **masked**.
1586
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1587
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1588
+ config.n_positions - 1]`.
1589
+
1590
+ [What are position IDs?](../glossary#position-ids)
1591
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1592
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1593
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1594
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1595
+
1596
+ Two formats are allowed:
1597
+ - a [`~cache_utils.Cache`] instance;
1598
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1599
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1600
+ cache format.
1601
+
1602
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1603
+ legacy cache format will be returned.
1604
+
1605
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1606
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1607
+ of shape `(batch_size, sequence_length)`.
1608
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1609
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1610
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1611
+ model's internal embedding lookup matrix.
1612
+ use_cache (`bool`, *optional*):
1613
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1614
+ `past_key_values`).
1615
+ output_attentions (`bool`, *optional*):
1616
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1617
+ tensors for more detail.
1618
+ output_hidden_states (`bool`, *optional*):
1619
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1620
+ more detail.
1621
+ return_dict (`bool`, *optional*):
1622
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1623
+ """
1624
+
1625
+
1626
+ @add_start_docstrings(
1627
+ "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
1628
+ DeepseekV2_START_DOCSTRING,
1629
+ )
1630
+ class DeepseekV2Model(DeepseekV2PreTrainedModel):
1631
+ """
1632
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV2DecoderLayer`]
1633
+
1634
+ Args:
1635
+ config: DeepseekV2Config
1636
+ """
1637
+
1638
+ def __init__(self, config: DeepseekV2Config):
1639
+ super().__init__(config)
1640
+ self.padding_idx = config.pad_token_id
1641
+ self.vocab_size = config.vocab_size
1642
+
1643
+ self.embed_tokens = nn.Embedding(
1644
+ config.vocab_size, config.hidden_size, self.padding_idx
1645
+ )
1646
+ self.layers = nn.ModuleList(
1647
+ [
1648
+ DeepseekV2DecoderLayer(config, layer_idx)
1649
+ for layer_idx in range(config.num_hidden_layers)
1650
+ ]
1651
+ )
1652
+ # print(config._attn_implementation)
1653
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1654
+ self.norm = DeepseekV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1655
+
1656
+ self.gradient_checkpointing = False
1657
+ # Initialize weights and apply final processing
1658
+ self.post_init()
1659
+
1660
+ def get_input_embeddings(self):
1661
+ return self.embed_tokens
1662
+
1663
+ def set_input_embeddings(self, value):
1664
+ self.embed_tokens = value
1665
+
1666
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1667
+ def forward(
1668
+ self,
1669
+ input_ids: torch.LongTensor = None,
1670
+ attention_mask: Optional[torch.Tensor] = None,
1671
+ position_ids: Optional[torch.LongTensor] = None,
1672
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1673
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1674
+ use_cache: Optional[bool] = None,
1675
+ output_attentions: Optional[bool] = None,
1676
+ output_hidden_states: Optional[bool] = None,
1677
+ return_dict: Optional[bool] = None,
1678
+ cache_position: Optional[torch.LongTensor] = None
1679
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1680
+ output_attentions = (
1681
+ output_attentions
1682
+ if output_attentions is not None
1683
+ else self.config.output_attentions
1684
+ )
1685
+ output_hidden_states = (
1686
+ output_hidden_states
1687
+ if output_hidden_states is not None
1688
+ else self.config.output_hidden_states
1689
+ )
1690
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1691
+
1692
+ return_dict = (
1693
+ return_dict if return_dict is not None else self.config.use_return_dict
1694
+ )
1695
+
1696
+ # retrieve input_ids and inputs_embeds
1697
+ if input_ids is not None and inputs_embeds is not None:
1698
+ raise ValueError(
1699
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1700
+ )
1701
+ elif input_ids is not None:
1702
+ batch_size, seq_length = input_ids.shape[:2]
1703
+ elif inputs_embeds is not None:
1704
+ batch_size, seq_length = inputs_embeds.shape[:2]
1705
+ else:
1706
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1707
+
1708
+ if self.gradient_checkpointing and self.training:
1709
+ if use_cache:
1710
+ logger.warning_once(
1711
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
1712
+ )
1713
+ use_cache = False
1714
+
1715
+ past_key_values_length = 0
1716
+ if use_cache:
1717
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1718
+ if use_legacy_cache:
1719
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1720
+ past_key_values_length = past_key_values.get_seq_length()
1721
+
1722
+ if position_ids is None:
1723
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1724
+ position_ids = torch.arange(
1725
+ past_key_values_length,
1726
+ seq_length + past_key_values_length,
1727
+ dtype=torch.long,
1728
+ device=device,
1729
+ )
1730
+ position_ids = position_ids.unsqueeze(0)
1731
+
1732
+ if inputs_embeds is None:
1733
+ inputs_embeds = self.embed_tokens(input_ids)
1734
+
1735
+ # Skip 4D causal mask for decode (q_len=1 with KV cache doesn't need it)
1736
+ if seq_length == 1 and past_key_values_length > 0:
1737
+ attention_mask = None
1738
+ elif self._use_flash_attention_2:
1739
+ # 2d mask is passed through the layers
1740
+ attention_mask = (
1741
+ attention_mask
1742
+ if (attention_mask is not None and 0 in attention_mask)
1743
+ else None
1744
+ )
1745
+ else:
1746
+ # 4d mask is passed through the layers
1747
+ attention_mask = _prepare_4d_causal_attention_mask(
1748
+ attention_mask,
1749
+ (batch_size, seq_length),
1750
+ inputs_embeds,
1751
+ past_key_values_length,
1752
+ )
1753
+
1754
+ # embed positions
1755
+ hidden_states = inputs_embeds
1756
+
1757
+ # decoder layers
1758
+ all_hidden_states = () if output_hidden_states else None
1759
+ all_self_attns = () if output_attentions else None
1760
+ next_decoder_cache = None
1761
+
1762
+ for decoder_layer in self.layers:
1763
+ if output_hidden_states:
1764
+ all_hidden_states += (hidden_states,)
1765
+
1766
+ if self.gradient_checkpointing and self.training:
1767
+ layer_outputs = self._gradient_checkpointing_func(
1768
+ decoder_layer.__call__,
1769
+ hidden_states,
1770
+ attention_mask,
1771
+ position_ids,
1772
+ past_key_values,
1773
+ output_attentions,
1774
+ use_cache,
1775
+ )
1776
+ else:
1777
+ layer_outputs = decoder_layer(
1778
+ hidden_states,
1779
+ attention_mask=attention_mask,
1780
+ position_ids=position_ids,
1781
+ past_key_value=past_key_values,
1782
+ output_attentions=output_attentions,
1783
+ use_cache=use_cache,
1784
+ )
1785
+
1786
+ hidden_states = layer_outputs[0]
1787
+
1788
+ if use_cache:
1789
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1790
+
1791
+ if output_attentions:
1792
+ all_self_attns += (layer_outputs[1],)
1793
+
1794
+ hidden_states = self.norm(hidden_states)
1795
+
1796
+ # add hidden states from the last decoder layer
1797
+ if output_hidden_states:
1798
+ all_hidden_states += (hidden_states,)
1799
+
1800
+ next_cache = None
1801
+ if use_cache:
1802
+ next_cache = next_decoder_cache # Always return DynamicCache to preserve custom attributes
1803
+ if not return_dict:
1804
+ return tuple(
1805
+ v
1806
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1807
+ if v is not None
1808
+ )
1809
+ return BaseModelOutputWithPast(
1810
+ last_hidden_state=hidden_states,
1811
+ past_key_values=next_cache,
1812
+ hidden_states=all_hidden_states,
1813
+ attentions=all_self_attns,
1814
+ )
1815
+
1816
+
1817
+ class DeepseekV2ForCausalLM(DeepseekV2PreTrainedModel):
1818
+ _tied_weights_keys = ["lm_head.weight"]
1819
+
1820
+ def __init__(self, config):
1821
+ super().__init__(config)
1822
+ self.model = DeepseekV2Model(config)
1823
+ self.vocab_size = config.vocab_size
1824
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1825
+
1826
+ # Initialize weights and apply final processing
1827
+ self.post_init()
1828
+
1829
+ def get_input_embeddings(self):
1830
+ return self.model.embed_tokens
1831
+
1832
+ def set_input_embeddings(self, value):
1833
+ self.model.embed_tokens = value
1834
+
1835
+ def get_output_embeddings(self):
1836
+ return self.lm_head
1837
+
1838
+ def set_output_embeddings(self, new_embeddings):
1839
+ self.lm_head = new_embeddings
1840
+
1841
+ def set_decoder(self, decoder):
1842
+ self.model = decoder
1843
+
1844
+ def get_decoder(self):
1845
+ return self.model
1846
+
1847
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1848
+ @replace_return_docstrings(
1849
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1850
+ )
1851
+ def forward(
1852
+ self,
1853
+ input_ids: torch.LongTensor = None,
1854
+ attention_mask: Optional[torch.Tensor] = None,
1855
+ position_ids: Optional[torch.LongTensor] = None,
1856
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1857
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1858
+ labels: Optional[torch.LongTensor] = None,
1859
+ use_cache: Optional[bool] = None,
1860
+ output_attentions: Optional[bool] = None,
1861
+ output_hidden_states: Optional[bool] = None,
1862
+ return_dict: Optional[bool] = None,
1863
+ cache_position: Optional[torch.LongTensor] = None
1864
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1865
+ r"""
1866
+ Args:
1867
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1868
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1869
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1870
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1871
+
1872
+ Returns:
1873
+
1874
+ Example:
1875
+
1876
+ ```python
1877
+ >>> from transformers import AutoTokenizer, DeepseekV2ForCausalLM
1878
+
1879
+ >>> model = DeepseekV2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1880
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1881
+
1882
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1883
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1884
+
1885
+ >>> # Generate
1886
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1887
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1888
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1889
+ ```"""
1890
+ output_attentions = (
1891
+ output_attentions
1892
+ if output_attentions is not None
1893
+ else self.config.output_attentions
1894
+ )
1895
+ output_hidden_states = (
1896
+ output_hidden_states
1897
+ if output_hidden_states is not None
1898
+ else self.config.output_hidden_states
1899
+ )
1900
+ return_dict = (
1901
+ return_dict if return_dict is not None else self.config.use_return_dict
1902
+ )
1903
+
1904
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1905
+ outputs = self.model(
1906
+ input_ids=input_ids,
1907
+ attention_mask=attention_mask,
1908
+ position_ids=position_ids,
1909
+ past_key_values=past_key_values,
1910
+ inputs_embeds=inputs_embeds,
1911
+ use_cache=use_cache,
1912
+ output_attentions=output_attentions,
1913
+ output_hidden_states=output_hidden_states,
1914
+ return_dict=return_dict,
1915
+ cache_position=cache_position
1916
+ )
1917
+
1918
+ hidden_states = outputs[0]
1919
+ logits = self.lm_head(hidden_states)
1920
+ logits = logits.float()
1921
+
1922
+ loss = None
1923
+ if labels is not None:
1924
+ # Shift so that tokens < n predict n
1925
+ shift_logits = logits[..., :-1, :].contiguous()
1926
+ shift_labels = labels[..., 1:].contiguous()
1927
+ # Flatten the tokens
1928
+ loss_fct = CrossEntropyLoss()
1929
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1930
+ shift_labels = shift_labels.view(-1)
1931
+ # Enable model parallelism
1932
+ shift_labels = shift_labels.to(shift_logits.device)
1933
+ loss = loss_fct(shift_logits, shift_labels)
1934
+
1935
+ if not return_dict:
1936
+ output = (logits,) + outputs[1:]
1937
+ return (loss,) + output if loss is not None else output
1938
+
1939
+ return CausalLMOutputWithPast(
1940
+ loss=loss,
1941
+ logits=logits,
1942
+ past_key_values=outputs.past_key_values,
1943
+ hidden_states=outputs.hidden_states,
1944
+ attentions=outputs.attentions,
1945
+ )
1946
+
1947
+ def prepare_inputs_for_generation(
1948
+ self,
1949
+ input_ids,
1950
+ past_key_values=None,
1951
+ attention_mask=None,
1952
+ inputs_embeds=None,
1953
+ **kwargs,
1954
+ ):
1955
+ past_length = 0
1956
+ if past_key_values is not None:
1957
+ if isinstance(past_key_values, Cache):
1958
+ cache_length = past_key_values.get_seq_length()
1959
+ past_length = past_key_values.get_seq_length()
1960
+ max_cache_length = getattr(past_key_values, 'get_max_length', lambda: None)()
1961
+ else:
1962
+ cache_length = past_length = past_key_values[0][0].shape[2]
1963
+ max_cache_length = None
1964
+
1965
+ # Keep only the unprocessed tokens:
1966
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1967
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1968
+ # input)
1969
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1970
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
1971
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1972
+ # input_ids based on the past_length.
1973
+ elif past_length < input_ids.shape[1]:
1974
+ input_ids = input_ids[:, past_length:]
1975
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1976
+
1977
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1978
+ if (
1979
+ max_cache_length is not None
1980
+ and attention_mask is not None
1981
+ and cache_length + input_ids.shape[1] > max_cache_length
1982
+ ):
1983
+ attention_mask = attention_mask[:, -max_cache_length:]
1984
+
1985
+ position_ids = kwargs.get("position_ids", None)
1986
+ if attention_mask is not None and position_ids is None:
1987
+ # create position_ids on the fly for batch generation
1988
+ position_ids = attention_mask.long().cumsum(-1) - 1
1989
+ position_ids.masked_fill_(attention_mask == 0, 1)
1990
+ if past_key_values:
1991
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1992
+
1993
+ if self.generation_config.cache_implementation == "static":
1994
+ # generation with static cache
1995
+ cache_position = kwargs.get("cache_position", None)
1996
+ if cache_position is None:
1997
+ past_length = 0
1998
+ else:
1999
+ past_length = cache_position[-1] + 1
2000
+ input_ids = input_ids[:, past_length:]
2001
+ position_ids = position_ids[:, past_length:]
2002
+
2003
+ # TODO @gante we should only keep a `cache_position` in generate, and do +=1.
2004
+ # same goes for position ids. Could also help with continued generation.
2005
+ cache_position = torch.arange(past_length, past_length + position_ids.shape[-1], device=position_ids.device)
2006
+
2007
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
2008
+ if inputs_embeds is not None and past_key_values is None:
2009
+ model_inputs = {"inputs_embeds": inputs_embeds}
2010
+ else:
2011
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
2012
+ # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
2013
+ # TODO: use `next_tokens` directly instead.
2014
+ model_inputs = {"input_ids": input_ids.contiguous()}
2015
+
2016
+ model_inputs.update(
2017
+ {
2018
+ "position_ids": position_ids.contiguous(),
2019
+ "cache_position": cache_position,
2020
+ "past_key_values": past_key_values,
2021
+ "use_cache": kwargs.get("use_cache"),
2022
+ "attention_mask": attention_mask,
2023
+ }
2024
+ )
2025
+ return model_inputs
2026
+
2027
+ @staticmethod
2028
+ def _reorder_cache(past_key_values, beam_idx):
2029
+ reordered_past = ()
2030
+ for layer_past in past_key_values:
2031
+ reordered_past += (
2032
+ tuple(
2033
+ past_state.index_select(0, beam_idx.to(past_state.device))
2034
+ for past_state in layer_past
2035
+ ),
2036
+ )
2037
+ return reordered_past
2038
+
2039
+
2040
+ @add_start_docstrings(
2041
+ """
2042
+ The DeepseekV2 Model transformer with a sequence classification head on top (linear layer).
2043
+
2044
+ [`DeepseekV2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
2045
+ (e.g. GPT-2) do.
2046
+
2047
+ Since it does classification on the last token, it requires to know the position of the last token. If a
2048
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
2049
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
2050
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
2051
+ each row of the batch).
2052
+ """,
2053
+ DeepseekV2_START_DOCSTRING,
2054
+ )
2055
+ class DeepseekV2ForSequenceClassification(DeepseekV2PreTrainedModel):
2056
+ def __init__(self, config):
2057
+ super().__init__(config)
2058
+ self.num_labels = config.num_labels
2059
+ self.model = DeepseekV2Model(config)
2060
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
2061
+
2062
+ # Initialize weights and apply final processing
2063
+ self.post_init()
2064
+
2065
+ def get_input_embeddings(self):
2066
+ return self.model.embed_tokens
2067
+
2068
+ def set_input_embeddings(self, value):
2069
+ self.model.embed_tokens = value
2070
+
2071
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
2072
+ def forward(
2073
+ self,
2074
+ input_ids: torch.LongTensor = None,
2075
+ attention_mask: Optional[torch.Tensor] = None,
2076
+ position_ids: Optional[torch.LongTensor] = None,
2077
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
2078
+ inputs_embeds: Optional[torch.FloatTensor] = None,
2079
+ labels: Optional[torch.LongTensor] = None,
2080
+ use_cache: Optional[bool] = None,
2081
+ output_attentions: Optional[bool] = None,
2082
+ output_hidden_states: Optional[bool] = None,
2083
+ return_dict: Optional[bool] = None,
2084
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
2085
+ r"""
2086
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
2087
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
2088
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
2089
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
2090
+ """
2091
+ return_dict = (
2092
+ return_dict if return_dict is not None else self.config.use_return_dict
2093
+ )
2094
+
2095
+ transformer_outputs = self.model(
2096
+ input_ids,
2097
+ attention_mask=attention_mask,
2098
+ position_ids=position_ids,
2099
+ past_key_values=past_key_values,
2100
+ inputs_embeds=inputs_embeds,
2101
+ use_cache=use_cache,
2102
+ output_attentions=output_attentions,
2103
+ output_hidden_states=output_hidden_states,
2104
+ return_dict=return_dict,
2105
+ )
2106
+ hidden_states = transformer_outputs[0]
2107
+ logits = self.score(hidden_states)
2108
+
2109
+ if input_ids is not None:
2110
+ batch_size = input_ids.shape[0]
2111
+ else:
2112
+ batch_size = inputs_embeds.shape[0]
2113
+
2114
+ if self.config.pad_token_id is None and batch_size != 1:
2115
+ raise ValueError(
2116
+ "Cannot handle batch sizes > 1 if no padding token is defined."
2117
+ )
2118
+ if self.config.pad_token_id is None:
2119
+ sequence_lengths = -1
2120
+ else:
2121
+ if input_ids is not None:
2122
+ sequence_lengths = (
2123
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
2124
+ ).to(logits.device)
2125
+ else:
2126
+ sequence_lengths = -1
2127
+
2128
+ pooled_logits = logits[
2129
+ torch.arange(batch_size, device=logits.device), sequence_lengths
2130
+ ]
2131
+
2132
+ loss = None
2133
+ if labels is not None:
2134
+ labels = labels.to(logits.device)
2135
+ if self.config.problem_type is None:
2136
+ if self.num_labels == 1:
2137
+ self.config.problem_type = "regression"
2138
+ elif self.num_labels > 1 and (
2139
+ labels.dtype == torch.long or labels.dtype == torch.int
2140
+ ):
2141
+ self.config.problem_type = "single_label_classification"
2142
+ else:
2143
+ self.config.problem_type = "multi_label_classification"
2144
+
2145
+ if self.config.problem_type == "regression":
2146
+ loss_fct = MSELoss()
2147
+ if self.num_labels == 1:
2148
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
2149
+ else:
2150
+ loss = loss_fct(pooled_logits, labels)
2151
+ elif self.config.problem_type == "single_label_classification":
2152
+ loss_fct = CrossEntropyLoss()
2153
+ loss = loss_fct(
2154
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
2155
+ )
2156
+ elif self.config.problem_type == "multi_label_classification":
2157
+ loss_fct = BCEWithLogitsLoss()
2158
+ loss = loss_fct(pooled_logits, labels)
2159
+ if not return_dict:
2160
+ output = (pooled_logits,) + transformer_outputs[1:]
2161
+ return ((loss,) + output) if loss is not None else output
2162
+
2163
+ return SequenceClassifierOutputWithPast(
2164
+ loss=loss,
2165
+ logits=pooled_logits,
2166
+ past_key_values=transformer_outputs.past_key_values,
2167
+ hidden_states=transformer_outputs.hidden_states,
2168
+ attentions=transformer_outputs.attentions,
2169
+ )
modeling_unlimitedocr.py ADDED
@@ -0,0 +1,1334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .modeling_deepseekv2 import DeepseekV2Model, DeepseekV2ForCausalLM
2
+ from .configuration_deepseek_v2 import DeepseekV2Config
3
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
4
+ from typing import List, Optional, Tuple, Union
5
+ from transformers.cache_utils import Cache
6
+ import requests
7
+ from PIL import Image, ImageOps, ImageDraw, ImageFont
8
+ from io import BytesIO
9
+ import torch
10
+ import torch.nn as nn
11
+ from torch.nn import CrossEntropyLoss
12
+ from torchvision import transforms
13
+ from torchvision.transforms.functional import InterpolationMode
14
+ import os
15
+ from .deepencoder import build_sam_vit_b, build_clip_l, MlpProjector
16
+ from addict import Dict
17
+ from transformers import TextStreamer
18
+ from .conversation import get_conv_template
19
+ from abc import ABC
20
+ import math
21
+ import re
22
+ from tqdm import tqdm
23
+ import numpy as np
24
+ import time
25
+
26
+
27
+ def load_image(image_path):
28
+
29
+ try:
30
+ image = Image.open(image_path)
31
+
32
+ corrected_image = ImageOps.exif_transpose(image)
33
+
34
+ return corrected_image
35
+
36
+ except Exception as e:
37
+ print(f"error: {e}")
38
+ try:
39
+ return Image.open(image_path)
40
+ except:
41
+ return None
42
+
43
+
44
+ def re_match(text):
45
+ ref_pattern = r'(<\|ref\|>(.*?)<\|/ref\|><\|det\|>(.*?)<\|/det\|>)'
46
+ matches = re.findall(ref_pattern, text, re.DOTALL)
47
+
48
+ det_pattern = r'(<\|det\|>\s*([A-Za-z_][\w-]*)\s*(\[[^\]]+\])\s*<\|/det\|>)'
49
+ for full_match, label, box in re.findall(det_pattern, text, re.DOTALL):
50
+ matches.append((full_match, label, box))
51
+
52
+ mathes_image = []
53
+ mathes_other = []
54
+ for a_match in matches:
55
+ if a_match[1].strip() == 'image' or '<|ref|>image<|/ref|>' in a_match[0]:
56
+ mathes_image.append(a_match[0])
57
+ else:
58
+ mathes_other.append(a_match[0])
59
+ return matches, mathes_image, mathes_other
60
+
61
+
62
+ def extract_coordinates_and_label(ref_text, image_width, image_height):
63
+
64
+ try:
65
+ label_type = ref_text[1]
66
+ cor_list = eval(ref_text[2])
67
+ if cor_list and isinstance(cor_list[0], (int, float)):
68
+ cor_list = [cor_list]
69
+ except Exception as e:
70
+ print(e)
71
+ return None
72
+
73
+ return (label_type, cor_list)
74
+
75
+
76
+ def draw_bounding_boxes(image, refs, ouput_path, image_prefix=''):
77
+
78
+ image_width, image_height = image.size
79
+
80
+ img_draw = image.copy()
81
+ draw = ImageDraw.Draw(img_draw)
82
+
83
+ overlay = Image.new('RGBA', img_draw.size, (0, 0, 0, 0))
84
+ draw2 = ImageDraw.Draw(overlay)
85
+
86
+ # try:
87
+ # except IOError:
88
+ # try:
89
+ # font = ImageFont.truetype("DejaVuSans.ttf", 20)
90
+ # except IOError:
91
+ font = ImageFont.load_default()
92
+
93
+ img_idx = 0
94
+
95
+ for i, ref in enumerate(refs):
96
+ try:
97
+ result = extract_coordinates_and_label(ref, image_width, image_height)
98
+ if result:
99
+ label_type, points_list = result
100
+
101
+ color = (np.random.randint(0, 200), np.random.randint(0, 200), np.random.randint(0, 255))
102
+
103
+ color_a = color + (20, )
104
+ for points in points_list:
105
+ x1, y1, x2, y2 = points
106
+
107
+ x1 = int(x1 / 999 * image_width)
108
+ y1 = int(y1 / 999 * image_height)
109
+
110
+ x2 = int(x2 / 999 * image_width)
111
+ y2 = int(y2 / 999 * image_height)
112
+
113
+ if label_type == 'image':
114
+ try:
115
+ cropped = image.crop((x1, y1, x2, y2))
116
+ cropped.save(f"{ouput_path}/images/{image_prefix}{img_idx}.jpg")
117
+ except Exception as e:
118
+ print(e)
119
+ pass
120
+ img_idx += 1
121
+
122
+ try:
123
+ if label_type == 'title':
124
+ draw.rectangle([x1, y1, x2, y2], outline=color, width=4)
125
+ draw2.rectangle([x1, y1, x2, y2], fill=color_a, outline=(0, 0, 0, 0), width=1)
126
+ else:
127
+ draw.rectangle([x1, y1, x2, y2], outline=color, width=2)
128
+ draw2.rectangle([x1, y1, x2, y2], fill=color_a, outline=(0, 0, 0, 0), width=1)
129
+ text_x = x1
130
+ text_y = max(0, y1 - 15)
131
+
132
+
133
+ text_bbox = draw.textbbox((0, 0), label_type, font=font)
134
+ text_width = text_bbox[2] - text_bbox[0]
135
+ text_height = text_bbox[3] - text_bbox[1]
136
+ draw.rectangle([text_x, text_y, text_x + text_width, text_y + text_height],
137
+ fill=(255, 255, 255, 30))
138
+
139
+ draw.text((text_x, text_y), label_type, font=font, fill=color)
140
+ except:
141
+ pass
142
+ except:
143
+ continue
144
+ img_draw.paste(overlay, (0, 0), overlay)
145
+ return img_draw
146
+
147
+
148
+ def process_image_with_refs(image, ref_texts, output_path, image_prefix=''):
149
+
150
+ result_image = draw_bounding_boxes(image, ref_texts, output_path, image_prefix=image_prefix)
151
+
152
+ return result_image
153
+
154
+
155
+
156
+
157
+
158
+ _VIS_BATCH = os.environ.get("VIS_BATCH", "1") == "1"
159
+
160
+
161
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
162
+ best_ratio_diff = float('inf')
163
+ best_ratio = (1, 1)
164
+ area = width * height
165
+ for ratio in target_ratios:
166
+ target_aspect_ratio = ratio[0] / ratio[1]
167
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
168
+ if ratio_diff < best_ratio_diff:
169
+ best_ratio_diff = ratio_diff
170
+ best_ratio = ratio
171
+ elif ratio_diff == best_ratio_diff:
172
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
173
+ best_ratio = ratio
174
+ # print(f'width: {width}, height: {height}, best_ratio: {best_ratio}')
175
+ return best_ratio
176
+
177
+
178
+ def dynamic_preprocess(image, min_num=2, max_num=32, image_size=640, use_thumbnail=False):
179
+ orig_width, orig_height = image.size
180
+ aspect_ratio = orig_width / orig_height
181
+
182
+ # calculate the existing image aspect ratio
183
+ target_ratios = set(
184
+ (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
185
+ i * j <= max_num and i * j >= min_num)
186
+ # print(target_ratios)
187
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
188
+
189
+ # find the closest aspect ratio to the target
190
+ target_aspect_ratio = find_closest_aspect_ratio(
191
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
192
+
193
+ # print(target_aspect_ratio)
194
+ # calculate the target width and height
195
+ target_width = image_size * target_aspect_ratio[0]
196
+ target_height = image_size * target_aspect_ratio[1]
197
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
198
+
199
+ # resize the image
200
+ resized_img = image.resize((target_width, target_height))
201
+ processed_images = []
202
+ for i in range(blocks):
203
+ box = (
204
+ (i % (target_width // image_size)) * image_size,
205
+ (i // (target_width // image_size)) * image_size,
206
+ ((i % (target_width // image_size)) + 1) * image_size,
207
+ ((i // (target_width // image_size)) + 1) * image_size
208
+ )
209
+ # split the image
210
+ split_img = resized_img.crop(box)
211
+ processed_images.append(split_img)
212
+ assert len(processed_images) == blocks
213
+ if use_thumbnail and len(processed_images) != 1:
214
+ thumbnail_img = image.resize((image_size, image_size))
215
+ processed_images.append(thumbnail_img)
216
+ return processed_images, target_aspect_ratio
217
+
218
+
219
+
220
+ def normalize_transform(mean, std):
221
+ if mean is None and std is None:
222
+ transform = None
223
+ elif mean is None and std is not None:
224
+ mean = [0.] * len(std)
225
+ transform = transforms.Normalize(mean=mean, std=std)
226
+ elif mean is not None and std is None:
227
+ std = [1.] * len(mean)
228
+ transform = transforms.Normalize(mean=mean, std=std)
229
+ else:
230
+ transform = transforms.Normalize(mean=mean, std=std)
231
+
232
+ return transform
233
+
234
+
235
+
236
+ def format_messages(
237
+ conversations: List[Dict[str, str]],
238
+ sft_format: str = "deepseek",
239
+ system_prompt: str = "",
240
+ ):
241
+ """
242
+ Applies the SFT template to conversation.
243
+
244
+ Args:
245
+ conversations (List[Dict]): A List of messages.
246
+ sft_format (str, optional): The format of the SFT template to use. Defaults to "deepseek".
247
+ system_prompt (str, optional): The system prompt to use in the SFT template. Defaults to "".
248
+
249
+ Returns:
250
+ sft_prompt (str): The formatted text.
251
+ """
252
+
253
+ conv = get_conv_template(sft_format)
254
+ conv.set_system_message(system_prompt)
255
+ for message in conversations:
256
+ conv.append_message(message["role"], message["content"].strip())
257
+ sft_prompt = conv.get_prompt().strip()
258
+
259
+ return sft_prompt
260
+
261
+
262
+ def text_encode(tokenizer, text: str, bos: bool = True, eos: bool = False):
263
+ t = tokenizer.encode(text, add_special_tokens=False)
264
+ bos_id = 0
265
+ eos_id = 1
266
+ if bos:
267
+ t = [bos_id] + t
268
+ if eos:
269
+ t = t + [eos_id]
270
+
271
+ return t
272
+
273
+ def load_pil_images(conversations: List[Dict[str, str]]) -> List[Image.Image]:
274
+ """
275
+
276
+ Args:
277
+ conversations (List[Dict[str, str]]): the conversations with a list of messages. An example is :
278
+ [
279
+ {
280
+ "role": "User",
281
+ "content": "<image_placeholder>\nExtract all information from this image and convert them into markdown format.",
282
+ "images": ["./examples/table_datasets.png"]
283
+ },
284
+ {"role": "Assistant", "content": ""},
285
+ ]
286
+
287
+ Returns:
288
+ pil_images (List[PIL.Image.Image]): the list of PIL images.
289
+
290
+ """
291
+
292
+ pil_images = []
293
+
294
+ for message in conversations:
295
+ if "images" not in message:
296
+ continue
297
+
298
+ for image_path in message["images"]:
299
+ # print('----------------')
300
+ # print(image_path)
301
+ # print('----------------')
302
+ # exit()
303
+
304
+ # pil_img = Image.open(image_path)
305
+ pil_img = load_image(image_path)
306
+ pil_img = pil_img.convert("RGB")
307
+ pil_images.append(pil_img)
308
+
309
+ return pil_images
310
+
311
+
312
+ class BaseTransform(ABC):
313
+
314
+ def set_rng(self, *args, **kwargs):
315
+ pass
316
+
317
+ def __call__(self, *args, **kwargs) -> torch.Tensor:
318
+ pass
319
+
320
+ @property
321
+ def default_shape(self):
322
+ raise NotImplementedError
323
+
324
+
325
+ class BasicImageTransform(BaseTransform):
326
+ def __init__(
327
+ self,
328
+ mean: Optional[Tuple[float, float, float]] = (0.5, 0.5, 0.5),
329
+ std: Optional[Tuple[float, float, float]] = (0.5, 0.5, 0.5),
330
+ normalize: bool = True
331
+ ):
332
+ self.mean = mean
333
+ self.std = std
334
+
335
+ transform_pipelines = [
336
+ transforms.ToTensor()
337
+ ]
338
+
339
+ normalize = normalize_transform(mean, std) if normalize else nn.Identity()
340
+ if normalize is not None:
341
+ transform_pipelines.append(normalize)
342
+
343
+ self.transform = transforms.Compose(transform_pipelines)
344
+
345
+ def __call__(self, x):
346
+ x = self.transform(x)
347
+ return x
348
+
349
+ class NoEOSTextStreamer(TextStreamer):
350
+ def on_finalized_text(self, text: str, stream_end: bool = False):
351
+
352
+ eos_text = self.tokenizer.decode([self.tokenizer.eos_token_id], skip_special_tokens=False)
353
+ text = text.replace(eos_text, "\n")
354
+ print(text, flush=True, end="")
355
+
356
+
357
+ class SlidingWindowNoRepeatNgramProcessor:
358
+ """Block n-gram repetitions within a sliding window.
359
+ Aligned with SGLang DeepseekOCRNoRepeatNGramLogitProcessor."""
360
+ def __init__(self, ngram_size, window, whitelist_token_ids=None):
361
+ self.ngram_size = ngram_size
362
+ self.window = window
363
+ self.whitelist = set(whitelist_token_ids) if whitelist_token_ids else set()
364
+
365
+ def __call__(self, input_ids, scores):
366
+ for batch_idx in range(input_ids.shape[0]):
367
+ sequence = input_ids[batch_idx].tolist()
368
+ if len(sequence) < self.ngram_size:
369
+ continue
370
+ search_start = max(0, len(sequence) - self.window)
371
+ search_end = len(sequence) - self.ngram_size + 1
372
+ if search_end <= search_start:
373
+ continue
374
+ if self.ngram_size > 1:
375
+ current_prefix = tuple(sequence[-(self.ngram_size - 1):])
376
+ else:
377
+ current_prefix = tuple()
378
+ banned = set()
379
+ for idx in range(search_start, search_end):
380
+ ngram = sequence[idx:idx + self.ngram_size]
381
+ if self.ngram_size == 1 or tuple(ngram[:-1]) == current_prefix:
382
+ banned.add(ngram[-1])
383
+ banned.difference_update(self.whitelist)
384
+ for token_id in banned:
385
+ scores[batch_idx, token_id] = float('-inf')
386
+ return scores
387
+
388
+
389
+ class TPSTextStreamer(TextStreamer):
390
+ """Streamer that prints TPS every `interval` tokens. Set interval=0 to disable."""
391
+ def __init__(self, tokenizer, interval=100, **kwargs):
392
+ super().__init__(tokenizer, **kwargs)
393
+ self.interval = interval
394
+ self.token_count = 0
395
+ self.start_time = None
396
+ self.start_token_count = 0
397
+ self.last_report_count = 0
398
+ self.last_report_time = None
399
+
400
+ def put(self, value):
401
+ import time
402
+ if hasattr(value, 'numel'):
403
+ self.token_count += value.numel()
404
+ else:
405
+ self.token_count += 1
406
+ # 第一次 put 时开始计时(跳过 prefill)
407
+ if self.start_time is None:
408
+ self.start_time = time.time()
409
+ self.last_report_time = self.start_time
410
+ self.last_report_count = self.token_count
411
+ self.start_token_count = self.token_count
412
+ super().put(value)
413
+ return
414
+ if self.interval > 0 and self.token_count - self.last_report_count >= self.interval:
415
+ now = time.time()
416
+ delta_tokens = self.token_count - self.last_report_count
417
+ delta_time = now - self.last_report_time
418
+ recent_tps = delta_tokens / delta_time if delta_time > 0 else 0
419
+ avg_tps = (self.token_count - self.start_token_count) / (now - self.start_time) if (now - self.start_time) > 0 else 0
420
+ print(f"\n[TPS] tokens={self.token_count}, recent={recent_tps:.1f} t/s, avg={avg_tps:.1f} t/s", flush=True)
421
+ self.last_report_count = self.token_count
422
+ self.last_report_time = now
423
+ super().put(value)
424
+
425
+ def on_finalized_text(self, text: str, stream_end: bool = False):
426
+ eos_text = self.tokenizer.decode([self.tokenizer.eos_token_id], skip_special_tokens=False)
427
+ text = text.replace(eos_text, "\n")
428
+ print(text, flush=True, end="")
429
+
430
+
431
+ class UnlimitedOCRConfig(DeepseekV2Config):
432
+ model_type = "unlimited-ocr"
433
+
434
+ class UnlimitedOCRModel(DeepseekV2Model):
435
+ config_class = UnlimitedOCRConfig
436
+
437
+ def __init__(self, config: DeepseekV2Config):
438
+ super(UnlimitedOCRModel, self).__init__(config)
439
+
440
+ self.sam_model = build_sam_vit_b()
441
+ self.vision_model = build_clip_l()
442
+ # self.conv_2 = nn.Conv2d(in_channels=1024, out_channels=2048, kernel_size=2, stride=2)
443
+ n_embed = 1280
444
+ self.projector = MlpProjector(Dict(projector_type="linear", input_dim=2048, n_embed=n_embed))
445
+ embed_std = 1 / torch.sqrt(torch.tensor(n_embed, dtype=torch.float32))
446
+ self.image_newline = nn.Parameter(torch.randn(n_embed) * embed_std)
447
+ self.view_seperator = nn.Parameter(torch.randn(n_embed) * embed_std)
448
+
449
+
450
+
451
+
452
+ def forward(
453
+ self,
454
+ input_ids: torch.LongTensor = None,
455
+ attention_mask: Optional[torch.Tensor] = None,
456
+ position_ids: Optional[torch.LongTensor] = None,
457
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
458
+ inputs_embeds: Optional[torch.FloatTensor] = None,
459
+ use_cache: Optional[bool] = None,
460
+ output_attentions: Optional[bool] = None,
461
+ output_hidden_states: Optional[bool] = None,
462
+ images: Optional[torch.FloatTensor] = None,
463
+ images_seq_mask: Optional[torch.FloatTensor] = None,
464
+ images_spatial_crop: Optional[torch.FloatTensor] = None,
465
+ return_dict: Optional[bool] = None,
466
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
467
+
468
+
469
+
470
+
471
+ if inputs_embeds is None:
472
+ # inputs_embeds = self.embed_tokens(input_ids)
473
+ inputs_embeds = self.get_input_embeddings()(input_ids)
474
+
475
+
476
+
477
+ sam_model = getattr(self, 'sam_model', None)
478
+ # sam_model = self.sam_model
479
+ vision_model = getattr(self, 'vision_model', None)
480
+
481
+
482
+
483
+ if sam_model is not None and images is not None and (input_ids.shape[1] != 1 or self.training) and torch.sum(images[0][1]).item() != 0:
484
+
485
+ idx = 0
486
+
487
+ # sam_model = torch.jit.script(sam_model)
488
+
489
+ # start_time = time.time()
490
+ # ── VIS_BATCH: 샘플별 루프(SAM/CLIP 8콜)를 전 배치 2콜로 묶는다.
491
+ # SAM/CLIP은 이미지 내부에서만 attention → batch축 독립 → 수치 동일.
492
+ # crop(640)/global(1024)은 해상도가 달라 두 콜로 분리. VIS_BATCH=0 → 원경로.
493
+ _pre_local, _pre_global = {}, {}
494
+ if _VIS_BATCH:
495
+ _cs = images_spatial_crop.tolist() if torch.is_tensor(images_spatial_crop) else list(images_spatial_crop)
496
+ _has = [int(_c[0]) > 1 or int(_c[1]) > 1 for _c in _cs]
497
+ with torch.no_grad():
498
+ _G = torch.cat([_im[1] for _im in images], dim=0)
499
+ _g1 = sam_model(_G); _g2 = vision_model(_G, _g1)
500
+ _gf = self.projector(torch.cat((_g2[:, 1:], _g1.flatten(2).permute(0, 2, 1)), dim=-1))
501
+ _off = 0
502
+ for _i, _im in enumerate(images):
503
+ _n = _im[1].shape[0]
504
+ _pre_global[_i] = _gf[_off:_off + _n]; _off += _n
505
+ _ci = [_i for _i, _b in enumerate(_has) if _b]
506
+ if _ci:
507
+ _P = torch.cat([images[_i][0] for _i in _ci], dim=0)
508
+ _l1 = sam_model(_P); _l2 = vision_model(_P, _l1)
509
+ _lf = self.projector(torch.cat((_l2[:, 1:], _l1.flatten(2).permute(0, 2, 1)), dim=-1))
510
+ _sz = [images[_i][0].shape[0] for _i in _ci]
511
+ for _i, _part in zip(_ci, torch.split(_lf, _sz, dim=0)):
512
+ _pre_local[_i] = _part
513
+ for image, crop_shape in zip(images, images_spatial_crop):
514
+ images_in_this_batch = []
515
+
516
+ patches = image[0]
517
+ image_ori = image[1]
518
+
519
+ with torch.no_grad():
520
+ # with torch.inference_mode():
521
+
522
+ _cached = idx in _pre_global
523
+ _crop_here = (idx in _pre_local) if _cached else (torch.sum(patches).item() != 0)
524
+ if _crop_here:
525
+ # P, C, H, W = patches.shape
526
+ crop_flag = 1
527
+ if _cached:
528
+ local_features = _pre_local[idx]
529
+ global_features = _pre_global[idx]
530
+ else:
531
+ local_features_1 = sam_model(patches)
532
+
533
+ local_features_2 = vision_model(patches, local_features_1)
534
+ # vit_time = time.time()
535
+ local_features = torch.cat((local_features_2[:, 1:], local_features_1.flatten(2).permute(0, 2, 1)), dim=-1)
536
+ local_features = self.projector(local_features)
537
+
538
+
539
+ global_features_1 = sam_model(image_ori)
540
+ global_features_2 = vision_model(image_ori, global_features_1)
541
+ global_features = torch.cat((global_features_2[:, 1:], global_features_1.flatten(2).permute(0, 2, 1)), dim=-1)
542
+ global_features = self.projector(global_features)
543
+
544
+ # print('=====================')
545
+ # print('BASE: ', global_features.shape)
546
+ # print('PATCHES: ', local_features.shape)
547
+ # print('=====================')
548
+
549
+ _, hw, n_dim = global_features.shape
550
+ h = w = int(hw ** 0.5)
551
+
552
+ _2, hw2, n_dim2 = local_features.shape
553
+ h2 = w2 = int(hw2 ** 0.5)
554
+
555
+ width_crop_num, height_crop_num = crop_shape[0], crop_shape[1]
556
+
557
+ global_features = global_features.view(h, w, n_dim)
558
+
559
+ global_features = torch.cat(
560
+ [global_features, self.image_newline[None, None, :].expand(h, 1, n_dim)], dim=1
561
+ )
562
+
563
+ global_features = global_features.view(-1, n_dim)
564
+
565
+
566
+ local_features = local_features.view(height_crop_num, width_crop_num, h2, w2, n_dim2).permute(0, 2, 1, 3, 4).reshape(height_crop_num*h2, width_crop_num*w2, n_dim2)
567
+ local_features = torch.cat(
568
+ [local_features, self.image_newline[None, None, :].expand(height_crop_num * h2, 1, n_dim2)], dim=1
569
+ )
570
+ local_features = local_features.view(-1, n_dim2)
571
+
572
+ global_local_features = torch.cat([local_features, global_features, self.view_seperator[None, :]], dim=0)
573
+ images_in_this_batch.append(global_local_features)
574
+
575
+ # end_time = time.time()
576
+
577
+ # print('sam: ', sam_time - start_time)
578
+ # print('vit: ', vit_time - sam_time)
579
+ # print('all: ', end_time - start_time)
580
+
581
+ # exit()
582
+
583
+ else:
584
+ # Handle single or multiple images in image_ori
585
+ num_imgs = image_ori.shape[0]
586
+ for img_idx in range(num_imgs):
587
+ single_img = image_ori[img_idx:img_idx+1] # [1, 3, H, W]
588
+ if _cached:
589
+ global_features = _pre_global[idx][img_idx:img_idx+1]
590
+ else:
591
+ global_features_1 = sam_model(single_img)
592
+ global_features_2 = vision_model(single_img, global_features_1)
593
+ global_features = torch.cat((global_features_2[:, 1:], global_features_1.flatten(2).permute(0, 2, 1)), dim=-1)
594
+ global_features = self.projector(global_features)
595
+
596
+ _, hw, n_dim = global_features.shape
597
+ h = w = int(hw ** 0.5)
598
+
599
+ global_features = global_features.view(h, w, n_dim)
600
+
601
+ global_features = torch.cat(
602
+ [global_features, self.image_newline[None, None, :].expand(h, 1, n_dim)], dim=1
603
+ )
604
+
605
+ global_features = global_features.view(-1, n_dim)
606
+
607
+ global_local_features = torch.cat([global_features, self.view_seperator[None, :]], dim=0)
608
+ images_in_this_batch.append(global_local_features)
609
+
610
+
611
+ # print(inputs_embeds.shape)
612
+
613
+ if images_in_this_batch:
614
+ images_in_this_batch = torch.cat(images_in_this_batch, dim=0)
615
+ # exit()
616
+
617
+ inputs_embeds[idx].masked_scatter_(images_seq_mask[idx].unsqueeze(-1).cuda(), images_in_this_batch)
618
+
619
+ idx += 1
620
+
621
+
622
+ return super(UnlimitedOCRModel, self).forward(
623
+ input_ids=None, attention_mask=attention_mask, past_key_values=past_key_values,
624
+ inputs_embeds=inputs_embeds, use_cache=use_cache, position_ids = position_ids,
625
+ output_attentions=output_attentions, output_hidden_states=output_hidden_states,
626
+ return_dict=return_dict
627
+ )
628
+
629
+
630
+ class UnlimitedOCRForCausalLM(DeepseekV2ForCausalLM):
631
+
632
+ config_class = UnlimitedOCRConfig
633
+ # supports_gradient_checkpointing = True
634
+
635
+ def __init__(self, config):
636
+ super(DeepseekV2ForCausalLM, self).__init__(config)
637
+ self.model = UnlimitedOCRModel(config)
638
+
639
+ self.vocab_size = config.vocab_size
640
+
641
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
642
+
643
+ # self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
644
+
645
+ # Initialize weights and apply final processing
646
+ self.post_init()
647
+
648
+ def get_model(self):
649
+ return self.model
650
+
651
+
652
+ def forward(
653
+ self,
654
+ input_ids: torch.LongTensor = None,
655
+ attention_mask: Optional[torch.Tensor] = None,
656
+ position_ids: Optional[torch.LongTensor] = None,
657
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
658
+ inputs_embeds: Optional[torch.FloatTensor] = None,
659
+ labels: Optional[torch.LongTensor] = None,
660
+ use_cache: Optional[bool] = None,
661
+ output_attentions: Optional[bool] = None,
662
+ output_hidden_states: Optional[bool] = None,
663
+ images: Optional[torch.FloatTensor] = None,
664
+ images_seq_mask: Optional[torch.FloatTensor] = None,
665
+ images_spatial_crop: Optional[torch.FloatTensor] = None,
666
+ return_dict: Optional[bool] = None,
667
+
668
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
669
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
670
+ output_hidden_states = (
671
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
672
+ )
673
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
674
+
675
+
676
+
677
+ outputs = self.model(
678
+ input_ids=input_ids,
679
+ past_key_values=past_key_values,
680
+ attention_mask=attention_mask,
681
+ position_ids=position_ids,
682
+ inputs_embeds=inputs_embeds,
683
+ use_cache=use_cache,
684
+ output_attentions=output_attentions,
685
+ output_hidden_states=output_hidden_states,
686
+ images=images,
687
+ images_seq_mask = images_seq_mask,
688
+ images_spatial_crop = images_spatial_crop,
689
+ return_dict=return_dict
690
+
691
+ )
692
+
693
+
694
+
695
+ # print(transformer_outputs)
696
+
697
+ hidden_states = outputs[0]
698
+ logits = self.lm_head(hidden_states)
699
+ logits = logits.float()
700
+
701
+ # logits
702
+
703
+ loss = None
704
+ if labels is not None:
705
+ # Shift so that tokens < n predict n
706
+ shift_logits = logits[..., :-1, :].contiguous()
707
+ shift_labels = labels[..., 1:].contiguous()
708
+ # Flatten the tokens
709
+ loss_fct = CrossEntropyLoss()
710
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
711
+ shift_labels = shift_labels.view(-1)
712
+ # Enable model parallelism
713
+ shift_labels = shift_labels.to(shift_logits.device)
714
+ loss = loss_fct(shift_logits, shift_labels)
715
+
716
+ if not return_dict:
717
+ output = (logits,) + outputs[1:]
718
+ return (loss,) + output if loss is not None else output
719
+
720
+ return CausalLMOutputWithPast(
721
+ loss=loss,
722
+ logits=logits,
723
+ past_key_values=outputs.past_key_values,
724
+ hidden_states=outputs.hidden_states,
725
+ attentions=outputs.attentions,
726
+ )
727
+
728
+
729
+ def prepare_inputs_for_generation(
730
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
731
+ ):
732
+ # Omit tokens covered by past_key_values
733
+ past_length = 0
734
+ if past_key_values is not None:
735
+ if isinstance(past_key_values, Cache):
736
+ cache_length = past_key_values.get_seq_length()
737
+ past_length = past_key_values.get_seq_length()
738
+ max_cache_length = getattr(past_key_values, 'get_max_length', lambda: None)()
739
+ else:
740
+ cache_length = past_length = past_key_values[0][0].shape[2]
741
+ max_cache_length = None
742
+
743
+ # Ring buffer: cache size is fixed, but we've processed more tokens.
744
+ # Always just take the last token for decode.
745
+ if hasattr(past_key_values, '_prefill_length') and past_length > 0:
746
+ input_ids = input_ids[:, -1:]
747
+ # Keep only the unprocessed tokens:
748
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
749
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
750
+ # input)
751
+ elif attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
752
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
753
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
754
+ # input_ids based on the past_length.
755
+ elif past_length < input_ids.shape[1]:
756
+ input_ids = input_ids[:, past_length:]
757
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
758
+
759
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
760
+ if (
761
+ max_cache_length is not None
762
+ and attention_mask is not None
763
+ and cache_length + input_ids.shape[1] > max_cache_length
764
+ ):
765
+ attention_mask = attention_mask[:, -max_cache_length:]
766
+
767
+ position_ids = kwargs.get("position_ids", None)
768
+ if attention_mask is not None and position_ids is None:
769
+ # create position_ids on the fly for batch generation
770
+ position_ids = attention_mask.long().cumsum(-1) - 1
771
+ position_ids.masked_fill_(attention_mask == 0, 1)
772
+ if past_key_values:
773
+ position_ids = position_ids[:, -input_ids.shape[1] :]
774
+
775
+ # if self.generation_config.cache_implementation == "static":
776
+ # # generation with static cache
777
+ # cache_position = kwargs.get("cache_position", None)
778
+ # if cache_position is None:
779
+ # past_length = 0
780
+ # else:
781
+ # past_length = cache_position[-1] + 1
782
+ # input_ids = input_ids[:, past_length:]
783
+ # position_ids = position_ids[:, past_length:]
784
+
785
+ # TODO @gante we should only keep a `cache_position` in generate, and do +=1.
786
+ # same goes for position ids. Could also help with continued generation.
787
+ cache_position = torch.arange(past_length, past_length + position_ids.shape[-1], device=position_ids.device)
788
+
789
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
790
+ if inputs_embeds is not None and past_key_values is None:
791
+ model_inputs = {"inputs_embeds": inputs_embeds}
792
+ else:
793
+ model_inputs = {"input_ids": input_ids}
794
+
795
+ # Pass images only on prefill (cache empty or None)
796
+ _is_prefill = (past_key_values is None or
797
+ (isinstance(past_key_values, Cache) and past_key_values.get_seq_length() == 0))
798
+ model_inputs.update(
799
+ {
800
+ "position_ids": position_ids,
801
+ "past_key_values": past_key_values,
802
+ "use_cache": kwargs.get("use_cache"),
803
+ "attention_mask": attention_mask,
804
+ "images": kwargs.get("images", None) if _is_prefill else None,
805
+ "images_seq_mask": kwargs.get("images_seq_mask", None) if _is_prefill else None,
806
+ "images_spatial_crop": kwargs.get("images_spatial_crop", None) if _is_prefill else None,
807
+ }
808
+ )
809
+ return model_inputs
810
+
811
+
812
+ def disable_torch_init(self):
813
+ """
814
+ Disable the redundant torch default initialization to accelerate model creation.
815
+ """
816
+ import torch
817
+ setattr(torch.nn.Linear, "reset_parameters", lambda self: None)
818
+ setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
819
+
820
+
821
+
822
+ def infer(self, tokenizer, prompt='', image_file='', output_path = '', base_size=1024, image_size=640, crop_mode=True, test_compress=False, save_results=False, eval_mode=False, max_length=32768, tps_interval=0, no_repeat_ngram_size=0, ngram_window=0, temperature=0.0):
823
+ self.disable_torch_init()
824
+
825
+ os.makedirs(output_path, exist_ok=True)
826
+ os.makedirs(f'{output_path}/images', exist_ok=True)
827
+
828
+ if prompt and image_file:
829
+ conversation = [
830
+ {
831
+ "role": "<|User|>",
832
+ # "content": "<image>\n<|grounding|>Given the layout of the image. ",
833
+ "content": f'{prompt}',
834
+ # "content": "君不见黄河之水天上来的下一句是什么?",
835
+ # "content": "<image>\nFree OCR. ",
836
+ # "content": "<image>\nParse the figure. ",
837
+ # "content": "<image>\nExtract the text in the image. ",
838
+ "images": [f'{image_file}'],
839
+ },
840
+ {"role": "<|Assistant|>", "content": ""},
841
+ ]
842
+
843
+ elif prompt:
844
+ conversation = [
845
+ {
846
+ "role": "<|User|>",
847
+ # "content": "<image>\n<|grounding|>Given the layout of the image. ",
848
+ "content": f'{prompt}',
849
+ # "content": "君不见黄河之水天上来的下一句是什么?",
850
+ # "content": "<image>\nFree OCR. ",
851
+ # "content": "<image>\nParse the figure. ",
852
+ # "content": "<image>\nExtract the text in the image. ",
853
+ # "images": [f'{image_file}'],
854
+ },
855
+ {"role": "<|Assistant|>", "content": ""},
856
+ ]
857
+ else:
858
+ assert False, f'prompt is none!'
859
+
860
+ prompt = format_messages(conversations=conversation, sft_format='plain', system_prompt='')
861
+
862
+ patch_size = 16
863
+ downsample_ratio = 4
864
+ images = load_pil_images(conversation)
865
+
866
+ valid_img_tokens = 0
867
+ ratio = 1
868
+
869
+ image_draw = images[0].copy()
870
+
871
+ w,h = image_draw.size
872
+ # print(w, h)
873
+ ratio = 1 - ((max(w, h) - min(w, h)) / (max(w, h)))
874
+
875
+
876
+ image_transform=BasicImageTransform(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), normalize=True)
877
+ images_seq_mask = []
878
+
879
+ image_token = '<image>'
880
+ image_token_id = 128815
881
+ text_splits = prompt.split(image_token)
882
+
883
+ images_list, images_crop_list, images_seq_mask = [], [], []
884
+ tokenized_str = []
885
+ images_spatial_crop = []
886
+ for text_sep, image in zip(text_splits, images):
887
+
888
+ tokenized_sep = text_encode(tokenizer, text_sep, bos=False, eos=False)
889
+ tokenized_str += tokenized_sep
890
+ images_seq_mask += [False] * len(tokenized_sep)
891
+
892
+ if crop_mode:
893
+
894
+ if image.size[0] <= 640 and image.size[1] <= 640:
895
+ crop_ratio = [1, 1]
896
+
897
+ else:
898
+ if crop_mode:
899
+ # best_width, best_height = select_best_resolution(image.size, self.candidate_resolutions)
900
+ images_crop_raw, crop_ratio = dynamic_preprocess(image)
901
+ else:
902
+ # best_width, best_height = self.image_size, self.image_size
903
+ crop_ratio = [1, 1]
904
+
905
+ """process the global view"""
906
+ # image = image.resize((base_size, base_size))
907
+ global_view = ImageOps.pad(image, (base_size, base_size),
908
+ color=tuple(int(x * 255) for x in image_transform.mean))
909
+
910
+ if base_size == 1024:
911
+ valid_img_tokens += int(256 * ratio)
912
+ elif base_size == 1280:
913
+ valid_img_tokens += int(400 * ratio)
914
+ # elif base_size == 640:
915
+ # valid_img_tokens += int(100 * ratio)
916
+
917
+
918
+
919
+
920
+
921
+ images_list.append(image_transform(global_view).to(torch.bfloat16))
922
+
923
+ # global_view_tensor = image_transform(global_view).to(torch.bfloat16)
924
+
925
+ width_crop_num, height_crop_num = crop_ratio
926
+
927
+ images_spatial_crop.append([width_crop_num, height_crop_num])
928
+
929
+
930
+ if width_crop_num > 1 or height_crop_num > 1:
931
+ """process the local views"""
932
+
933
+ for i in range(len(images_crop_raw)):
934
+ images_crop_list.append(image_transform(images_crop_raw[i]).to(torch.bfloat16))
935
+
936
+ if image_size == 640:
937
+ valid_img_tokens += len(images_crop_list) * 100
938
+
939
+ num_queries = math.ceil((image_size // patch_size) / downsample_ratio)
940
+ num_queries_base = math.ceil((base_size // patch_size) / downsample_ratio)
941
+
942
+
943
+
944
+ """add image tokens"""
945
+
946
+
947
+
948
+ tokenized_image = ([image_token_id] * num_queries_base + [image_token_id]) * num_queries_base
949
+ tokenized_image += [image_token_id]
950
+ if width_crop_num > 1 or height_crop_num > 1:
951
+ tokenized_image += ([image_token_id] * (num_queries * width_crop_num) + [image_token_id]) * (
952
+ num_queries * height_crop_num)
953
+ tokenized_str += tokenized_image
954
+ images_seq_mask += [True] * len(tokenized_image)
955
+ # num_image_tokens.append(len(tokenized_image))
956
+
957
+ else:
958
+ # best_width, best_height = self.image_size, self.image_size
959
+ # print(image.size, (best_width, best_height)) # check the select_best_resolutions func
960
+
961
+ """process the global view"""
962
+ if image_size <= 640:
963
+ print('directly resize')
964
+ image = image.resize((image_size, image_size))
965
+ # else:
966
+ global_view = ImageOps.pad(image, (image_size, image_size),
967
+ color=tuple(int(x * 255) for x in image_transform.mean))
968
+ images_list.append(image_transform(global_view).to(torch.bfloat16))
969
+
970
+ if base_size == 1024:
971
+ valid_img_tokens += int(256 * ratio)
972
+ elif base_size == 1280:
973
+ valid_img_tokens += int(400 * ratio)
974
+ elif base_size == 640:
975
+ valid_img_tokens += int(100 * 1)
976
+ elif base_size == 512:
977
+ valid_img_tokens += int(64 * 1)
978
+
979
+ width_crop_num, height_crop_num = 1, 1
980
+
981
+ images_spatial_crop.append([width_crop_num, height_crop_num])
982
+
983
+
984
+ """add image tokens"""
985
+ num_queries = math.ceil((image_size // patch_size) / downsample_ratio)
986
+
987
+ tokenized_image = ([image_token_id] * num_queries + [image_token_id]) * num_queries
988
+ tokenized_image += [image_token_id]
989
+ # tokenized_image += ([self.image_token_id] * (num_queries * width_crop_num) + [self.image_token_id]) * (
990
+ # num_queries * height_crop_num)
991
+ tokenized_str += tokenized_image
992
+ images_seq_mask += [True] * len(tokenized_image)
993
+ # num_image_tokens.append(len(tokenized_image))
994
+
995
+
996
+ """process the last text split"""
997
+ tokenized_sep = text_encode(tokenizer, text_splits[-1], bos=False, eos=False)
998
+ tokenized_str += tokenized_sep
999
+ images_seq_mask += [False] * len(tokenized_sep)
1000
+
1001
+ """add the bos tokens"""
1002
+ bos_id = 0
1003
+ tokenized_str = [bos_id] + tokenized_str
1004
+ images_seq_mask = [False] + images_seq_mask
1005
+
1006
+
1007
+
1008
+ input_ids = torch.LongTensor(tokenized_str)
1009
+
1010
+
1011
+
1012
+
1013
+ images_seq_mask = torch.tensor(images_seq_mask, dtype=torch.bool)
1014
+
1015
+
1016
+ if len(images_list) == 0:
1017
+ images_ori = torch.zeros((1, 3, image_size, image_size))
1018
+ images_spatial_crop = torch.zeros((1, 2), dtype=torch.long)
1019
+ images_crop = torch.zeros((1, 3, base_size, base_size))
1020
+
1021
+ else:
1022
+ images_ori = torch.stack(images_list, dim=0)
1023
+ images_spatial_crop = torch.tensor(images_spatial_crop, dtype=torch.long)
1024
+ if images_crop_list:
1025
+ images_crop = torch.stack(images_crop_list, dim=0)
1026
+ else:
1027
+ images_crop = torch.zeros((1, 3, base_size, base_size))
1028
+
1029
+
1030
+
1031
+ if not eval_mode:
1032
+ streamer = TPSTextStreamer(tokenizer, interval=tps_interval, skip_prompt=True, skip_special_tokens=False)
1033
+ _orig_sw = getattr(self.config, 'sliding_window_size', None) or getattr(self.config, 'sliding_window', None)
1034
+ self.config._ring_window = _orig_sw
1035
+ self.config.sliding_window = None
1036
+ # Build logits processors for ngram
1037
+ gen_kwargs = dict(
1038
+ input_ids=input_ids.unsqueeze(0).cuda(),
1039
+ images=[(images_crop.cuda(), images_ori.cuda())],
1040
+ images_seq_mask=images_seq_mask.unsqueeze(0).cuda(),
1041
+ images_spatial_crop=images_spatial_crop,
1042
+ do_sample=temperature > 0,
1043
+ temperature=temperature if temperature > 0 else None,
1044
+ eos_token_id=tokenizer.eos_token_id,
1045
+ streamer=streamer,
1046
+ max_length=max_length,
1047
+ use_cache=True
1048
+ )
1049
+ if no_repeat_ngram_size > 0 and ngram_window > 0:
1050
+ gen_kwargs['logits_processor'] = [SlidingWindowNoRepeatNgramProcessor(no_repeat_ngram_size, ngram_window)]
1051
+ elif no_repeat_ngram_size > 0:
1052
+ gen_kwargs['no_repeat_ngram_size'] = no_repeat_ngram_size
1053
+ with torch.autocast("cuda", dtype=torch.bfloat16):
1054
+ with torch.no_grad():
1055
+ output_ids = self.generate(**gen_kwargs)
1056
+ self.config.sliding_window = _orig_sw
1057
+
1058
+ else:
1059
+ _orig_sw = getattr(self.config, 'sliding_window_size', None) or getattr(self.config, 'sliding_window', None)
1060
+ self.config._ring_window = _orig_sw
1061
+ self.config.sliding_window = None
1062
+ gen_kwargs = dict(
1063
+ input_ids=input_ids.unsqueeze(0).cuda(),
1064
+ images=[(images_crop.cuda(), images_ori.cuda())],
1065
+ images_seq_mask=images_seq_mask.unsqueeze(0).cuda(),
1066
+ images_spatial_crop=images_spatial_crop,
1067
+ do_sample=temperature > 0,
1068
+ temperature=temperature if temperature > 0 else None,
1069
+ eos_token_id=tokenizer.eos_token_id,
1070
+ max_length=max_length,
1071
+ use_cache=True
1072
+ )
1073
+ if no_repeat_ngram_size > 0 and ngram_window > 0:
1074
+ gen_kwargs['logits_processor'] = [SlidingWindowNoRepeatNgramProcessor(no_repeat_ngram_size, ngram_window)]
1075
+ elif no_repeat_ngram_size > 0:
1076
+ gen_kwargs['no_repeat_ngram_size'] = no_repeat_ngram_size
1077
+ with torch.autocast("cuda", dtype=torch.bfloat16):
1078
+ with torch.no_grad():
1079
+ output_ids = self.generate(**gen_kwargs)
1080
+ self.config.sliding_window = _orig_sw
1081
+
1082
+
1083
+ if '<image>' in conversation[0]['content'] and eval_mode:
1084
+ outputs = tokenizer.decode(output_ids[0, input_ids.unsqueeze(0).cuda().shape[1]:])
1085
+ stop_str = '<|end▁of▁sentence|>'
1086
+ if outputs.endswith(stop_str):
1087
+ outputs = outputs[:-len(stop_str)]
1088
+ # re_match
1089
+ outputs = outputs.strip()
1090
+
1091
+ return outputs
1092
+
1093
+ if '<image>' in conversation[0]['content'] and test_compress:
1094
+ outputs = tokenizer.decode(output_ids[0, input_ids.unsqueeze(0).cuda().shape[1]:])
1095
+ pure_texts_outputs_token_length = len(text_encode(tokenizer, outputs, bos=False, eos=False))
1096
+ print('='*50)
1097
+ print('image size: ', (w, h))
1098
+ print('valid image tokens: ', int(valid_img_tokens))
1099
+ print('output texts tokens (valid): ', pure_texts_outputs_token_length)
1100
+ print('compression ratio: ', round(pure_texts_outputs_token_length/valid_img_tokens, 2))
1101
+ print('='*50)
1102
+
1103
+
1104
+ if '<image>' in conversation[0]['content'] and save_results:
1105
+ outputs = tokenizer.decode(output_ids[0, input_ids.unsqueeze(0).cuda().shape[1]:])
1106
+ stop_str = '<|end▁of▁sentence|>'
1107
+
1108
+ print('='*15 + 'save results:' + '='*15)
1109
+
1110
+ # # # # conv.messages[-1][-1] = outputs
1111
+ if outputs.endswith(stop_str):
1112
+ outputs = outputs[:-len(stop_str)]
1113
+ outputs = outputs.strip()
1114
+
1115
+ matches_ref, matches_images, mathes_other = re_match(outputs)
1116
+ # print(matches_ref)
1117
+ result = process_image_with_refs(image_draw, matches_ref, output_path)
1118
+
1119
+
1120
+ for idx, a_match_image in enumerate(tqdm(matches_images, desc="image")):
1121
+ outputs = outputs.replace(a_match_image, '![](images/' + str(idx) + '.jpg)\n')
1122
+
1123
+ for idx, a_match_other in enumerate(tqdm(mathes_other, desc="other")):
1124
+ outputs = outputs.replace(a_match_other, '').replace('\\coloneqq', ':=').replace('\\eqqcolon', '=:')
1125
+
1126
+
1127
+ # if 'structural formula' in conversation[0]['content']:
1128
+ # outputs = '<smiles>' + outputs + '</smiles>'
1129
+ with open(f'{output_path}/result.md', 'w', encoding = 'utf-8') as afile:
1130
+ afile.write(outputs)
1131
+
1132
+ if 'line_type' in outputs:
1133
+ import matplotlib.pyplot as plt
1134
+ lines = eval(outputs)['Line']['line']
1135
+
1136
+ line_type = eval(outputs)['Line']['line_type']
1137
+ # print(lines)
1138
+
1139
+ endpoints = eval(outputs)['Line']['line_endpoint']
1140
+
1141
+ fig, ax = plt.subplots(figsize=(3,3), dpi=200)
1142
+ ax.set_xlim(-15, 15)
1143
+ ax.set_ylim(-15, 15)
1144
+
1145
+ for idx, line in enumerate(lines):
1146
+ try:
1147
+ p0 = eval(line.split(' -- ')[0])
1148
+ p1 = eval(line.split(' -- ')[-1])
1149
+
1150
+ if line_type[idx] == '--':
1151
+ ax.plot([p0[0], p1[0]], [p0[1], p1[1]], linewidth=0.8, color='k')
1152
+ else:
1153
+ ax.plot([p0[0], p1[0]], [p0[1], p1[1]], linewidth = 0.8, color = 'k')
1154
+
1155
+ ax.scatter(p0[0], p0[1], s=5, color = 'k')
1156
+ ax.scatter(p1[0], p1[1], s=5, color = 'k')
1157
+ except:
1158
+ pass
1159
+
1160
+ for endpoint in endpoints:
1161
+
1162
+ label = endpoint.split(': ')[0]
1163
+ (x, y) = eval(endpoint.split(': ')[1])
1164
+ ax.annotate(label, (x, y), xytext=(1, 1), textcoords='offset points',
1165
+ fontsize=5, fontweight='light')
1166
+
1167
+
1168
+ plt.savefig(f'{output_path}/geo.jpg')
1169
+ plt.close()
1170
+
1171
+ result.save(f"{output_path}/result_with_boxes.jpg")
1172
+
1173
+
1174
+ def infer_multi(self, tokenizer, prompt='', image_files=None, output_path='', image_size=640, save_results=False, max_length=32768, tps_interval=0, no_repeat_ngram_size=0, ngram_window=0, temperature=0.0):
1175
+ """
1176
+ Multi-image inference. Does NOT support crop mode.
1177
+ Prompt uses a single <image> token (e.g. "<image>Multi page parsing.").
1178
+ All images' token sequences are concatenated at that single <image> position,
1179
+ separated by a single image_token_id between each image (same as crop mode separator).
1180
+
1181
+ Args:
1182
+ prompt: text prompt with one <image> token, e.g. "<image>Multi page parsing."
1183
+ image_files: list of image file paths
1184
+ image_size: size to resize each image to
1185
+ save_results: whether to save output to file
1186
+ """
1187
+ self.disable_torch_init()
1188
+
1189
+ if image_files is None or len(image_files) == 0:
1190
+ assert False, 'image_files must be a non-empty list for multi-image inference!'
1191
+
1192
+ os.makedirs(output_path, exist_ok=True)
1193
+ os.makedirs(f'{output_path}/images', exist_ok=True)
1194
+
1195
+ # Prompt contains a single <image>, all image files go into "images" list
1196
+ conversation = [
1197
+ {
1198
+ "role": "<|User|>",
1199
+ "content": f'{prompt}',
1200
+ "images": image_files,
1201
+ },
1202
+ {"role": "<|Assistant|>", "content": ""},
1203
+ ]
1204
+
1205
+ formatted_prompt = format_messages(conversations=conversation, sft_format='plain', system_prompt='')
1206
+
1207
+ patch_size = 16
1208
+ downsample_ratio = 4
1209
+
1210
+ # Load all images
1211
+ images = load_pil_images(conversation)
1212
+
1213
+ image_transform = BasicImageTransform(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), normalize=True)
1214
+
1215
+ image_token = '<image>'
1216
+ image_token_id = 128815
1217
+
1218
+ # Split on the single <image> token -> 2 parts: before and after
1219
+ text_splits = formatted_prompt.split(image_token)
1220
+
1221
+ images_list, images_seq_mask = [], []
1222
+ tokenized_str = []
1223
+ images_spatial_crop = []
1224
+
1225
+ num_queries = math.ceil((image_size // patch_size) / downsample_ratio)
1226
+
1227
+ # Tokenize text before <image>
1228
+ tokenized_sep = text_encode(tokenizer, text_splits[0], bos=False, eos=False)
1229
+ tokenized_str += tokenized_sep
1230
+ images_seq_mask += [False] * len(tokenized_sep)
1231
+
1232
+ # Process all images at the single <image> position
1233
+ for idx, image in enumerate(images):
1234
+ # Match single-image logic: if image_size <= 640, resize all images
1235
+ if image_size <= 640:
1236
+ image = image.resize((image_size, image_size))
1237
+ global_view = ImageOps.pad(image, (image_size, image_size),
1238
+ color=tuple(int(x * 255) for x in image_transform.mean))
1239
+
1240
+ images_list.append(image_transform(global_view).to(torch.bfloat16))
1241
+ images_spatial_crop.append([1, 1])
1242
+
1243
+ # Image tokens for this image (same structure as single-image non-crop mode)
1244
+ tokenized_image = ([image_token_id] * num_queries + [image_token_id]) * num_queries
1245
+ tokenized_image += [image_token_id] # separator token between images
1246
+ tokenized_str += tokenized_image
1247
+ images_seq_mask += [True] * len(tokenized_image)
1248
+
1249
+ # Tokenize text after <image>
1250
+ tokenized_sep = text_encode(tokenizer, text_splits[1], bos=False, eos=False)
1251
+ tokenized_str += tokenized_sep
1252
+ images_seq_mask += [False] * len(tokenized_sep)
1253
+
1254
+ # Add bos token
1255
+ bos_id = 0
1256
+ tokenized_str = [bos_id] + tokenized_str
1257
+ images_seq_mask = [False] + images_seq_mask
1258
+
1259
+ input_ids = torch.LongTensor(tokenized_str)
1260
+ images_seq_mask = torch.tensor(images_seq_mask, dtype=torch.bool)
1261
+
1262
+ # Stack all images as image_ori; dummy_crop is zeros (triggers no-crop branch)
1263
+ images_ori = torch.stack(images_list, dim=0) # [N, 3, H, W]
1264
+ images_spatial_crop = torch.tensor(images_spatial_crop, dtype=torch.long)
1265
+ dummy_crop = torch.zeros((1, 3, image_size, image_size))
1266
+
1267
+ streamer = TPSTextStreamer(tokenizer, interval=tps_interval, skip_prompt=True, skip_special_tokens=False)
1268
+ # Disable config.sliding_window to prevent DynamicCache from truncating prefill tokens.
1269
+ # The ring buffer in SlidingWindowLlamaAttention handles sliding window manually.
1270
+ _orig_sw = getattr(self.config, 'sliding_window_size', None) or getattr(self.config, 'sliding_window', None)
1271
+ self.config._ring_window = _orig_sw # Save for ring buffer to read
1272
+ self.config.sliding_window = None
1273
+ with torch.autocast("cuda", dtype=torch.bfloat16):
1274
+ with torch.no_grad():
1275
+ gen_kwargs = dict(
1276
+ input_ids=input_ids.unsqueeze(0).cuda(),
1277
+ images=[(dummy_crop.cuda(), images_ori.cuda())],
1278
+ images_seq_mask=images_seq_mask.unsqueeze(0).cuda(),
1279
+ images_spatial_crop=images_spatial_crop,
1280
+ do_sample=temperature > 0,
1281
+ temperature=temperature if temperature > 0 else None,
1282
+ eos_token_id=tokenizer.eos_token_id,
1283
+ streamer=streamer,
1284
+ max_length=max_length,
1285
+ use_cache=True
1286
+ )
1287
+ if no_repeat_ngram_size > 0 and ngram_window > 0:
1288
+ gen_kwargs['logits_processor'] = [SlidingWindowNoRepeatNgramProcessor(no_repeat_ngram_size, ngram_window)]
1289
+ elif no_repeat_ngram_size > 0:
1290
+ gen_kwargs['no_repeat_ngram_size'] = no_repeat_ngram_size
1291
+ output_ids = self.generate(**gen_kwargs)
1292
+ self.config.sliding_window = _orig_sw # Restore
1293
+
1294
+ outputs = tokenizer.decode(output_ids[0, input_ids.unsqueeze(0).cuda().shape[1]:])
1295
+ stop_str = '<|end▁of▁sentence|>'
1296
+ if outputs.endswith(stop_str):
1297
+ outputs = outputs[:-len(stop_str)]
1298
+ outputs = outputs.strip()
1299
+
1300
+ output_tokens = len(text_encode(tokenizer, outputs, bos=False, eos=False))
1301
+
1302
+ if save_results:
1303
+ print('=' * 15 + 'save results:' + '=' * 15)
1304
+ pages = outputs.split('<PAGE>')[1:]
1305
+ processed_pages = []
1306
+ for page_idx, page_output in enumerate(pages):
1307
+ page_output = page_output.strip()
1308
+ if page_idx >= len(images):
1309
+ processed_pages.append(page_output)
1310
+ continue
1311
+
1312
+ matches_ref, matches_images, mathes_other = re_match(page_output)
1313
+ image_prefix = f'page_{page_idx}_'
1314
+ result = process_image_with_refs(
1315
+ images[page_idx].copy(),
1316
+ matches_ref,
1317
+ output_path,
1318
+ image_prefix=image_prefix,
1319
+ )
1320
+ result.save(f"{output_path}/result_with_boxes_{page_idx}.jpg")
1321
+
1322
+ for idx, a_match_image in enumerate(tqdm(matches_images, desc=f"image_page_{page_idx}")):
1323
+ page_output = page_output.replace(a_match_image, f'![](images/{image_prefix}{idx}.jpg)\n')
1324
+
1325
+ for idx, a_match_other in enumerate(tqdm(mathes_other, desc=f"other_page_{page_idx}")):
1326
+ page_output = page_output.replace(a_match_other, '').replace('\\coloneqq', ':=').replace('\\eqqcolon', '=:')
1327
+
1328
+ processed_pages.append(page_output)
1329
+
1330
+ outputs = '<PAGE>\n' + '\n<PAGE>\n'.join(processed_pages)
1331
+ with open(f'{output_path}/result.md', 'w', encoding='utf-8') as afile:
1332
+ afile.write(outputs)
1333
+
1334
+ return outputs, output_tokens
special_tokens_map.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|User|>",
4
+ "<|Assistant|>"
5
+ ],
6
+ "bos_token": {
7
+ "content": "<|begin▁of▁sentence|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false
12
+ },
13
+ "eos_token": {
14
+ "content": "<|end▁of▁sentence|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ },
20
+ "pad_token": {
21
+ "content": "<|▁pad▁|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false
26
+ }
27
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
The diff for this file is too large to render. See raw diff