feather820 commited on
Commit
6eb61b1
·
verified ·
1 Parent(s): f11b451

Upload 3 files

Browse files
Files changed (3) hide show
  1. config.json +40 -0
  2. configuration_d2coder.py +149 -0
  3. modeling_d2coder.py +638 -0
config.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Mymodel"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "bos_token_id": 2,
7
+ "embedding_dim": 4096,
8
+ "embedding_method": "pma",
9
+ "encoder_mode": "post_normal",
10
+ "eos_token_id": 2,
11
+ "hidden_act": "silu",
12
+ "hidden_size": 4096,
13
+ "inf_seq_length": 1024,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 13440,
16
+ "keep_max_layer": 32,
17
+ "max_position_embeddings": 65536,
18
+ "max_window_layers": 28,
19
+ "model_type": "qwen2",
20
+ "num_attention_heads": 32,
21
+ "num_encoder_layers": 0,
22
+ "num_hidden_layers": 32,
23
+ "num_key_value_heads": 4,
24
+ "padding_side": "right",
25
+ "pma_ln": true,
26
+ "pma_norm": false,
27
+ "pma_norm_mode": "post_normal",
28
+ "pma_num_heads": 32,
29
+ "rms_norm_eps": 1e-05,
30
+ "rope_theta": 1000000,
31
+ "rotary_emb_base": 1000000,
32
+ "seq_length": 65536,
33
+ "sliding_window": null,
34
+ "tie_word_embeddings": false,
35
+ "torch_dtype": "bfloat16",
36
+ "transformers_version": "4.39.2",
37
+ "use_cache": true,
38
+ "use_sliding_window": false,
39
+ "vocab_size": 92416
40
+ }
configuration_d2coder.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+ from transformers.utils import logging
3
+
4
+
5
+ logger = logging.get_logger(__name__)
6
+
7
+
8
+ class D2CoderConfig(PretrainedConfig):
9
+ r"""
10
+ This is the configuration class to store the configuration of a [`D2LLM`]. It is used to instantiate a
11
+ Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
12
+ with the defaults will yield a similar configuration to that of
13
+ Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
14
+
15
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
16
+ documentation from [`PretrainedConfig`] for more information.
17
+
18
+
19
+ Args:
20
+ vocab_size (`int`, *optional*, defaults to 151936):
21
+ Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
22
+ `inputs_ids` passed when calling [`D2LLM`]
23
+ hidden_size (`int`, *optional*, defaults to 4096):
24
+ Dimension of the hidden representations.
25
+ intermediate_size (`int`, *optional*, defaults to 22016):
26
+ Dimension of the MLP representations.
27
+ num_hidden_layers (`int`, *optional*, defaults to 32):
28
+ Number of hidden layers in the Transformer encoder.
29
+ num_attention_heads (`int`, *optional*, defaults to 32):
30
+ Number of attention heads for each attention layer in the Transformer encoder.
31
+ num_key_value_heads (`int`, *optional*, defaults to 32):
32
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
33
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
34
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
35
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
36
+ by meanpooling all the original heads within that group. For more details checkout [this
37
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
38
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
39
+ The non-linear activation function (function or string) in the decoder.
40
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
41
+ The maximum sequence length that this model might ever be used with.
42
+ initializer_range (`float`, *optional*, defaults to 0.02):
43
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
44
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
45
+ The epsilon used by the rms normalization layers.
46
+ use_cache (`bool`, *optional*, defaults to `True`):
47
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
48
+ relevant if `config.is_decoder=True`.
49
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
50
+ Whether the model's input and output word embeddings should be tied.
51
+ rope_theta (`float`, *optional*, defaults to 10000.0):
52
+ The base period of the RoPE embeddings.
53
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
54
+ Whether to use sliding window attention.
55
+ sliding_window (`int`, *optional*, defaults to 4096):
56
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
57
+ max_window_layers (`int`, *optional*, defaults to 28):
58
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
59
+ attention_dropout (`float`, *optional*, defaults to 0.0):
60
+ The dropout ratio for the attention probabilities.
61
+
62
+ ```python
63
+ >>> from transformers import Qwen2Model, Qwen2Config
64
+
65
+ >>> # Initializing a Qwen2 style configuration
66
+ >>> configuration = Qwen2Config()
67
+
68
+ >>> # Initializing a model from the Qwen2-7B style configuration
69
+ >>> model = Qwen2Model(configuration)
70
+
71
+ >>> # Accessing the model configuration
72
+ >>> configuration = model.config
73
+ ```"""
74
+
75
+ model_type = "qwen2"
76
+ keys_to_ignore_at_inference = ["past_key_values"]
77
+
78
+ def __init__(
79
+ self,
80
+ vocab_size=151936,
81
+ hidden_size=4096,
82
+ intermediate_size=22016,
83
+ num_hidden_layers=32,
84
+ num_attention_heads=32,
85
+ num_key_value_heads=32,
86
+ hidden_act="silu",
87
+ max_position_embeddings=32768,
88
+ initializer_range=0.02,
89
+ rms_norm_eps=1e-6,
90
+ use_cache=True,
91
+ tie_word_embeddings=False,
92
+ rope_theta=10000.0,
93
+ use_sliding_window=False,
94
+ sliding_window=4096,
95
+ max_window_layers=28,
96
+ attention_dropout=0.0,
97
+
98
+ embedding_method="pma",
99
+ inf_seq_length=1024,
100
+ encoder_mode ="post_normal",
101
+ num_encoder_layers =0,
102
+ padding_side ="right",
103
+
104
+ keep_max_layer=32,
105
+ pma_num_heads=32,
106
+ pma_ln=True,
107
+ pma_norm=False,
108
+ pma_norm_mode="post_normal",
109
+
110
+ **kwargs,
111
+ ):
112
+ self.vocab_size = vocab_size
113
+ self.max_position_embeddings = max_position_embeddings
114
+ self.hidden_size = hidden_size
115
+ self.intermediate_size = intermediate_size
116
+ self.num_hidden_layers = num_hidden_layers
117
+ self.num_attention_heads = num_attention_heads
118
+ self.use_sliding_window = use_sliding_window
119
+ self.sliding_window = sliding_window if use_sliding_window else None
120
+ self.max_window_layers = max_window_layers
121
+
122
+ # for backward compatibility
123
+ if num_key_value_heads is None:
124
+ num_key_value_heads = num_attention_heads
125
+
126
+ self.num_key_value_heads = num_key_value_heads
127
+ self.hidden_act = hidden_act
128
+ self.initializer_range = initializer_range
129
+ self.rms_norm_eps = rms_norm_eps
130
+ self.use_cache = use_cache
131
+ self.rope_theta = rope_theta
132
+ self.attention_dropout = attention_dropout
133
+
134
+ self.embedding_method = config.embedding_method
135
+ self.inf_seq_length = config.inf_seq_length
136
+ self.encoder_mode = config.encoder_mode
137
+ self.num_encoder_layers = config.num_encoder_layers
138
+ self.padding_side = config.padding_side
139
+
140
+ self.keep_max_layer = config.keep_max_layer
141
+ self.pma_num_heads = config.pma_num_heads
142
+ self.pma_ln = config.pma_ln
143
+ self.pma_norm = config.pma_norm
144
+ self.pma_norm_mode = config.pma_norm_mode
145
+
146
+ super().__init__(
147
+ tie_word_embeddings=tie_word_embeddings,
148
+ **kwargs,
149
+ )
modeling_d2coder.py ADDED
@@ -0,0 +1,638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import Qwen2Config
2
+ import inspect
3
+ import math
4
+ import os
5
+ import warnings
6
+ from typing import List, Optional, Tuple, Union
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+ import torch.utils.checkpoint
11
+ from torch import nn
12
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
13
+ from transformers import PretrainedConfig
14
+
15
+ from transformers.activations import ACT2FN
16
+ from transformers.cache_utils import Cache, DynamicCache
17
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa, _prepare_4d_attention_mask, _prepare_4d_attention_mask_for_sdpa
18
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
19
+ from transformers.modeling_utils import PreTrainedModel
20
+ from transformers.utils import (
21
+ add_start_docstrings,
22
+ add_start_docstrings_to_model_forward,
23
+ is_flash_attn_2_available,
24
+ is_flash_attn_greater_or_equal_2_10,
25
+ logging,
26
+ replace_return_docstrings,
27
+ )
28
+ import numpy as np
29
+ from transformers import Qwen2Config
30
+ from transformers import Qwen2ForCausalLM
31
+ import inspect
32
+ import math
33
+ import os
34
+ import warnings
35
+ from typing import List, Optional, Tuple, Union
36
+ from tqdm import tqdm, trange
37
+ import torch
38
+ import torch.nn.functional as F
39
+ import torch.utils.checkpoint
40
+ from torch import nn
41
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
42
+
43
+ from transformers.activations import ACT2FN
44
+ from transformers.cache_utils import Cache, DynamicCache
45
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa, _prepare_4d_attention_mask, _prepare_4d_attention_mask_for_sdpa
46
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
47
+ from transformers.modeling_utils import PreTrainedModel
48
+ from transformers.utils import (
49
+ add_start_docstrings,
50
+ add_start_docstrings_to_model_forward,
51
+ is_flash_attn_2_available,
52
+ is_flash_attn_greater_or_equal_2_10,
53
+ logging,
54
+ replace_return_docstrings,
55
+ )
56
+ import numpy as np
57
+ import torch
58
+ import os
59
+ import argparse
60
+ import json
61
+ from tqdm import tqdm
62
+ from typing import cast, List, Union, Tuple
63
+ from transformers import AutoTokenizer, AutoModel # pylint: disable=C0413
64
+ from peft import LoraConfig, get_peft_model, TaskType
65
+ import time
66
+ import torch.nn.functional as F
67
+ import sys
68
+ import time
69
+ import torch
70
+ import torch.nn as nn
71
+ import torch.nn.functional as F
72
+ import numpy as np
73
+ from tqdm import tqdm, trange
74
+ from collections import defaultdict
75
+ from transformers import AutoTokenizer, AutoModel, AutoModelForCausalLM, AutoConfig
76
+ import torch.distributed as dist
77
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
78
+ import sys
79
+ import torch
80
+ import torch.nn as nn
81
+ import torch.nn.functional as F
82
+ import math
83
+ import re
84
+
85
+
86
+ # PMA部分 post_normal
87
+ class MAB_POST(nn.Module):
88
+ def __init__(self, dim_Q, dim_K, dim_V, num_heads, ln=False):
89
+ super(MAB_POST, self).__init__()
90
+ self.dim_V = dim_V
91
+ self.num_heads = num_heads
92
+ self.fc_q = nn.Linear(dim_Q, dim_V)
93
+ self.fc_k = nn.Linear(dim_K, dim_V)
94
+ self.fc_v = nn.Linear(dim_K, dim_V)
95
+
96
+ if ln:
97
+ self.ln0 = nn.LayerNorm(dim_V)
98
+ self.ln1 = nn.LayerNorm(dim_V)
99
+ self.fc_o = nn.Linear(dim_V, dim_V)
100
+ nn.init.xavier_uniform_(self.fc_q.weight)
101
+ nn.init.xavier_uniform_(self.fc_k.weight)
102
+ nn.init.xavier_uniform_(self.fc_v.weight)
103
+ nn.init.xavier_uniform_(self.fc_o.weight)
104
+
105
+
106
+
107
+ # Q(bs, 1, emb), pad_mask (bs, seq) Post-LN
108
+ def forward(self, Q, K, pad_mask=None):
109
+
110
+ Q_ = self.fc_q(Q)
111
+ K_, V_ = self.fc_k(K), self.fc_v(K)
112
+
113
+ dim_split = self.dim_V // self.num_heads
114
+ Q_ = torch.cat(Q_.split(dim_split, 2), 0) # (bs* num_head, 1, emb)
115
+ K_ = torch.cat(K_.split(dim_split, 2), 0) # (bs* num_head, seq, emb)
116
+ V_ = torch.cat(V_.split(dim_split, 2), 0)
117
+
118
+ pad_mask = pad_mask.unsqueeze(1).repeat(self.num_heads, Q.size(1), 1) # (bs*num_head, 1, seq)
119
+ score = Q_.bmm(K_.transpose(1,2))/math.sqrt(self.dim_V)
120
+ score = score.masked_fill(pad_mask == 0, -1e12)
121
+ A = torch.softmax(score, 2) # (bs*num_head, 1, seq)
122
+ A = A * pad_mask
123
+ O = torch.cat(A.bmm(V_).split(Q.size(0), 0), 2) # (bs, 1, emb)
124
+ O = Q + O
125
+ # O = torch.cat((Q_ + A.bmm(V_)).split(Q.size(0), 0), 2)
126
+ O = O if getattr(self, 'ln0', None) is None else self.ln0(O)
127
+ O = O + F.relu(self.fc_o(O))
128
+ O = O if getattr(self, 'ln1', None) is None else self.ln1(O)
129
+ return O
130
+
131
+
132
+ # PMA部分 pre_normal
133
+ class MAB_PRE_NORMAL(nn.Module):
134
+ def __init__(self, dim_Q, dim_K, dim_V, num_heads, ln=False):
135
+ super(MAB_PRE_NORMAL, self).__init__()
136
+ self.dim_V = dim_V
137
+ self.num_heads = num_heads
138
+ self.fc_q = nn.Linear(dim_Q, dim_V)
139
+ self.fc_k = nn.Linear(dim_K, dim_V)
140
+ self.fc_v = nn.Linear(dim_K, dim_V)
141
+
142
+ if ln:
143
+ self.ln_q = nn.LayerNorm(dim_V)
144
+ self.ln_kv = nn.LayerNorm(dim_V)
145
+ self.ln_o = nn.LayerNorm(dim_V)
146
+ self.ln_final = nn.LayerNorm(dim_V)
147
+
148
+ self.fc_o = nn.Linear(dim_V, dim_V)
149
+ nn.init.xavier_uniform_(self.fc_q.weight)
150
+ nn.init.xavier_uniform_(self.fc_k.weight)
151
+ nn.init.xavier_uniform_(self.fc_v.weight)
152
+ nn.init.xavier_uniform_(self.fc_o.weight)
153
+
154
+
155
+
156
+
157
+ # pad_mask (bs, seq) Pre-LN 正常架构
158
+ def forward(self, Q, K, pad_mask=None):
159
+
160
+ Q_ = Q if getattr(self, 'ln_q', None) is None else self.ln_q(Q)
161
+ K_ = K if getattr(self, 'ln_kv', None) is None else self.ln_kv(K)
162
+
163
+ Q_ = self.fc_q(Q_)
164
+ K_, V_ = self.fc_k(K_), self.fc_v(K_)
165
+
166
+ dim_split = self.dim_V // self.num_heads
167
+
168
+
169
+ Q_ = torch.cat(Q_.split(dim_split, 2), 0) # (bs* num_head, 1, emb)
170
+ K_ = torch.cat(K_.split(dim_split, 2), 0) # (bs* num_head, seq, emb)
171
+ V_ = torch.cat(V_.split(dim_split, 2), 0) # (bs* num_head, seq, emb)
172
+ pad_mask = pad_mask.unsqueeze(1).repeat(self.num_heads, Q.size(1), 1) # (bs*num_head, 1, seq)
173
+ score = Q_.bmm(K_.transpose(1,2))/math.sqrt(self.dim_V)
174
+ score = score.masked_fill(pad_mask == 0, -1e12)
175
+ A = torch.softmax(score, 2) # (bs*num_head, 1, seq)
176
+ A = A * pad_mask
177
+
178
+
179
+ O = torch.cat(A.bmm(V_).split(Q.size(0), 0), 2)
180
+ O = Q + O
181
+
182
+ O_ = O if getattr(self, 'ln_o', None) is None else self.ln_o(O) # O的layernorm分支
183
+ O_ = O + F.relu(self.fc_o(O_))
184
+ return O_ if getattr(self, 'ln_final', None) is None else self.ln_final(O_)
185
+
186
+ # PMA部分 pre_gptj
187
+ class MAB_PRE_GPTJ(nn.Module):
188
+ def __init__(self, dim_Q, dim_K, dim_V, num_heads, ln=False):
189
+ super(MAB_PRE_GPTJ, self).__init__()
190
+ self.dim_V = dim_V
191
+ self.num_heads = num_heads
192
+ self.fc_q = nn.Linear(dim_Q, dim_V)
193
+ self.fc_k = nn.Linear(dim_K, dim_V)
194
+ self.fc_v = nn.Linear(dim_K, dim_V)
195
+ self.fc_o = nn.Linear(dim_V, dim_V)
196
+
197
+ nn.init.xavier_uniform_(self.fc_q.weight)
198
+ nn.init.xavier_uniform_(self.fc_k.weight)
199
+ nn.init.xavier_uniform_(self.fc_v.weight)
200
+ nn.init.xavier_uniform_(self.fc_o.weight)
201
+ if ln:
202
+ self.ln_q = nn.LayerNorm(dim_V)
203
+ self.ln_kv = nn.LayerNorm(dim_V)
204
+ self.ln_final = nn.LayerNorm(dim_V)
205
+
206
+ # pad_mask (bs, seq)
207
+ def forward(self, Q, K, pad_mask=None):
208
+
209
+ # layernorm
210
+ Q_ = Q if getattr(self, 'ln_q', None) is None else self.ln_q(Q)
211
+ K_ = K if getattr(self, 'ln_kv', None) is None else self.ln_kv(K)
212
+
213
+
214
+ Q1 = self.fc_q(Q_)
215
+ K1, V1 = self.fc_k(K_), self.fc_v(K_)
216
+ dim_split = self.dim_V // self.num_heads
217
+
218
+
219
+ Q1 = torch.cat(Q1.split(dim_split, 2), 0) # (bs* num_head, 1, emb)
220
+ K1 = torch.cat(K1.split(dim_split, 2), 0) # (bs* num_head, seq, emb)
221
+ V1 = torch.cat(V1.split(dim_split, 2), 0) # (bs* num_head, seq, emb)
222
+
223
+
224
+ pad_mask = pad_mask.unsqueeze(1).repeat(self.num_heads, Q.size(1), 1) # (bs*num_head, 1, seq)
225
+ score = Q1.bmm(K1.transpose(1,2))/math.sqrt(self.dim_V)
226
+ score = score.masked_fill(pad_mask == 0, -1e12)
227
+ A = torch.softmax(score, 2) # (bs*num_head, 1, seq)
228
+ A = A * pad_mask
229
+ O1 = torch.cat(A.bmm(V1).split(Q.size(0), 0), 2) # (bs, 1, emb)
230
+
231
+ O2 = F.relu(self.fc_o(Q_)) # (bs, 1, emb)
232
+
233
+ O_final = Q + O1 + O2
234
+
235
+ return O_final if getattr(self, 'ln_final', None) is None else self.ln_final(O_final)
236
+
237
+
238
+
239
+
240
+ class PMA(nn.Module):
241
+ def __init__(self, dim, num_heads, num_seeds, ln=False, pma_mode=None):
242
+ super(PMA, self).__init__()
243
+ self.S = nn.Parameter(torch.Tensor(1, num_seeds, dim))
244
+ nn.init.xavier_uniform_(self.S)
245
+ if pma_mode == 'post_normal':
246
+ self.mab = MAB_POST(dim, dim, dim, num_heads, ln=ln)
247
+ elif pma_mode == 'pre_normal':
248
+ self.mab = MAB_PRE_NORMAL(dim, dim, dim, num_heads, ln=ln)
249
+ elif pma_mode == 'pre_gptj':
250
+ self.mab = MAB_PRE_GPTJ(dim, dim, dim, num_heads, ln=ln)
251
+ else:
252
+ raise ValueError(f"Error, the pma_mode {pma_mode} is not implemented !")
253
+ # X: (bs, seq, emb), pad_mask: (bs, seq)
254
+ def forward(self, X, pad_mask):
255
+ if self.S.dtype != torch.bfloat16:
256
+ X = X.float()
257
+ return self.mab(self.S.repeat(X.size(0), 1, 1), X, pad_mask)
258
+
259
+
260
+ # 普通双向transformer encoder, post_normal
261
+ class EncoderLayer_POST(nn.Module):
262
+ def __init__(self, dim_V, num_heads, ln=False):
263
+ super(EncoderLayer_POST, self).__init__()
264
+ self.dim_V = dim_V
265
+ self.num_heads = num_heads
266
+ self.fc_q = nn.Linear(dim_V, dim_V)
267
+ self.fc_k = nn.Linear(dim_V, dim_V)
268
+ self.fc_v = nn.Linear(dim_V, dim_V)
269
+ self.fc_o = nn.Linear(dim_V, dim_V)
270
+
271
+
272
+ nn.init.xavier_uniform_(self.fc_q.weight)
273
+ nn.init.xavier_uniform_(self.fc_k.weight)
274
+ nn.init.xavier_uniform_(self.fc_v.weight)
275
+ nn.init.xavier_uniform_(self.fc_o.weight)
276
+
277
+ if ln:
278
+ self.ln0 = nn.LayerNorm(dim_V)
279
+ self.ln1 = nn.LayerNorm(dim_V)
280
+
281
+ # Q:(bs, seq, emb), pad_mask:(bs, seq)
282
+ def forward(self, Q, pad_mask=None):
283
+
284
+ Q_, K_, V_ = self.fc_q(Q), self.fc_k(Q), self.fc_v(Q)
285
+
286
+ dim_split = self.dim_V // self.num_heads
287
+ Q_ = torch.cat(Q_.split(dim_split, 2), 0) # (bs* num_head, seq, emb)
288
+ K_ = torch.cat(K_.split(dim_split, 2), 0) # (bs* num_head, seq, emb)
289
+ V_ = torch.cat(V_.split(dim_split, 2), 0) # (bs* num_head, seq, emb)
290
+
291
+ pad_mask = pad_mask.unsqueeze(1).repeat(self.num_heads, Q.size(1), 1) # (bs*num_head, seq, seq)
292
+
293
+ score = Q_.bmm(K_.transpose(1,2))/math.sqrt(self.dim_V)
294
+ score = score.masked_fill(pad_mask == 0, -1e12)
295
+ A = torch.softmax(score, 2) # (bs*num_head, seq, seq)
296
+ A = A * pad_mask # (bs*num_head, seq, seq)
297
+
298
+ O = torch.cat(A.bmm(V_).split(Q.size(0), 0), 2) # (bs, seq, emb)
299
+ O = Q + O
300
+
301
+ O = O if getattr(self, 'ln0', None) is None else self.ln0(O)
302
+ O = O + F.relu(self.fc_o(O))
303
+ O = O if getattr(self, 'ln1', None) is None else self.ln1(O)
304
+ return O
305
+
306
+
307
+ # 普通双向transformer encoder, pre LN norm
308
+ class EncoderLayer_PRE_NORMAL(nn.Module):
309
+ def __init__(self, dim_V, num_heads, ln=False):
310
+ super(EncoderLayer_PRE_NORMAL, self).__init__()
311
+ self.dim_V = dim_V
312
+ self.num_heads = num_heads
313
+ self.fc_q = nn.Linear(dim_V, dim_V)
314
+ self.fc_k = nn.Linear(dim_V, dim_V)
315
+ self.fc_v = nn.Linear(dim_V, dim_V)
316
+ self.fc_o = nn.Linear(dim_V, dim_V)
317
+
318
+
319
+ nn.init.xavier_uniform_(self.fc_q.weight)
320
+ nn.init.xavier_uniform_(self.fc_k.weight)
321
+ nn.init.xavier_uniform_(self.fc_v.weight)
322
+ nn.init.xavier_uniform_(self.fc_o.weight)
323
+
324
+ if ln:
325
+ self.ln_qkv = nn.LayerNorm(dim_V)
326
+ self.ln_o = nn.LayerNorm(dim_V)
327
+
328
+ # Q:(bs, seq, emb), pad_mask:(bs, seq)
329
+ def forward(self, Q, pad_mask=None):
330
+
331
+ Q_ = Q if getattr(self, 'ln_qkv', None) is None else self.ln_qkv(Q) # layernorm
332
+
333
+ Q_, K_, V_ = self.fc_q(Q_), self.fc_k(Q_), self.fc_v(Q_)
334
+ dim_split = self.dim_V // self.num_heads
335
+ Q_ = torch.cat(Q_.split(dim_split, 2), 0) # (bs* num_head, seq, emb)
336
+ K_ = torch.cat(K_.split(dim_split, 2), 0) # (bs* num_head, seq, emb)
337
+ V_ = torch.cat(V_.split(dim_split, 2), 0) # (bs* num_head, seq, emb)
338
+ pad_mask = pad_mask.unsqueeze(1).repeat(self.num_heads, Q.size(1), 1) # (bs*num_head, seq, seq)
339
+ score = Q_.bmm(K_.transpose(1,2))/math.sqrt(self.dim_V)
340
+ score = score.masked_fill(pad_mask == 0, -1e12)
341
+ A = torch.softmax(score, 2) # (bs*num_head, seq, seq)
342
+ A = A * pad_mask
343
+
344
+ O = torch.cat(A.bmm(V_).split(Q.size(0), 0), 2)
345
+ O = Q + O
346
+
347
+ O_ = O if getattr(self, 'ln_o', None) is None else self.ln_o(O) # O的layernorm分支
348
+
349
+ O_ = O + F.relu(self.fc_o(O_))
350
+
351
+ return O_
352
+
353
+ # 普通双向transformer encoder, pre LN gptj
354
+ class EncoderLayer_PRE_GPTJ(nn.Module):
355
+ def __init__(self, dim_V, num_heads, ln=False):
356
+ super(EncoderLayer_PRE_GPTJ, self).__init__()
357
+ self.dim_V = dim_V
358
+ self.num_heads = num_heads
359
+ self.fc_q = nn.Linear(dim_V, dim_V)
360
+ self.fc_k = nn.Linear(dim_V, dim_V)
361
+ self.fc_v = nn.Linear(dim_V, dim_V)
362
+ self.fc_o = nn.Linear(dim_V, dim_V)
363
+
364
+
365
+ nn.init.xavier_uniform_(self.fc_q.weight)
366
+ nn.init.xavier_uniform_(self.fc_k.weight)
367
+ nn.init.xavier_uniform_(self.fc_v.weight)
368
+ nn.init.xavier_uniform_(self.fc_o.weight)
369
+
370
+ if ln:
371
+ self.ln_qkv = nn.LayerNorm(dim_V)
372
+
373
+ # Q:(bs, seq, emb), pad_mask:(bs, seq)
374
+ def forward(self, Q, pad_mask=None):
375
+
376
+ Q_ = Q if getattr(self, 'ln_qkv', None) is None else self.ln_qkv(Q) # layernorm
377
+
378
+
379
+ Q1, K1, V1 = self.fc_q(Q_), self.fc_k(Q_), self.fc_v(Q_)
380
+ dim_split = self.dim_V // self.num_heads
381
+ Q1 = torch.cat(Q1.split(dim_split, 2), 0) # (bs* num_head, seq, emb)
382
+ K1 = torch.cat(K1.split(dim_split, 2), 0) # (bs* num_head, seq, emb)
383
+ V1 = torch.cat(V1.split(dim_split, 2), 0) # (bs* num_head, seq, emb)
384
+ pad_mask = pad_mask.unsqueeze(1).repeat(self.num_heads, Q.size(1), 1) # (bs*num_head, seq, seq)
385
+ score = Q1.bmm(K1.transpose(1,2))/math.sqrt(self.dim_V)
386
+ score = score.masked_fill(pad_mask == 0, -1e12)
387
+ A = torch.softmax(score, 2) # (bs*num_head, seq, seq)
388
+ A = A * pad_mask
389
+ O1 = torch.cat(A.bmm(V1).split(Q.size(0), 0), 2) # (bs, seq, emb)
390
+
391
+ O2 = F.relu(self.fc_o(Q_))
392
+
393
+ O_final = Q + O1 + O2
394
+
395
+ return O_final
396
+
397
+
398
+ class Encoder(nn.Module):
399
+ def __init__(self, emb_dim, num_heads, ln, encoder_mode, num_encoder_layers):
400
+ super(Encoder, self).__init__()
401
+ self.num_encoder_layers = num_encoder_layers
402
+ if encoder_mode == 'post_normal':
403
+ self.layers = nn.ModuleList([EncoderLayer_POST(dim_V=emb_dim, num_heads=num_heads, ln=ln)
404
+ for _ in range(num_encoder_layers)])
405
+ elif encoder_mode == 'pre_normal':
406
+ self.layers = nn.ModuleList([EncoderLayer_PRE_NORMAL(dim_V=emb_dim, num_heads=num_heads, ln=ln)
407
+ for _ in range(num_encoder_layers)])
408
+ elif encoder_mode == 'pre_gptj':
409
+ self.layers = nn.ModuleList([EncoderLayer_PRE_GPTJ(dim_V=emb_dim, num_heads=num_heads, ln=ln)
410
+ for _ in range(num_encoder_layers)])
411
+ else:
412
+ raise ValueError(f"Error, the encoder_mode {encoder_mode} is not implemented !")
413
+
414
+ # X:(bs, seq, emb), mask: (bs, seq)
415
+ def forward(self, X, mask):
416
+ if self.num_encoder_layers == 0:
417
+ return X
418
+ if self.layers[0].fc_q.weight.dtype != torch.bfloat16:
419
+ X = X.float()
420
+ for layer in self.layers:
421
+ X = layer(X, mask)
422
+
423
+ return X
424
+
425
+ class D2LLMConfig(PretrainedConfig):
426
+ model_type = "qwen2"
427
+ keys_to_ignore_at_inference = ["past_key_values"]
428
+
429
+ def __init__(
430
+ self,
431
+ vocab_size=151936,
432
+ hidden_size=4096,
433
+ intermediate_size=22016,
434
+ num_hidden_layers=32,
435
+ num_attention_heads=32,
436
+ num_key_value_heads=32,
437
+ hidden_act="silu",
438
+ max_position_embeddings=32768,
439
+ initializer_range=0.02,
440
+ rms_norm_eps=1e-6,
441
+ use_cache=True,
442
+ tie_word_embeddings=False,
443
+ rope_theta=10000.0,
444
+ use_sliding_window=False,
445
+ sliding_window=4096,
446
+ max_window_layers=28,
447
+ attention_dropout=0.0,
448
+ **kwargs,
449
+ ):
450
+ self.vocab_size = vocab_size
451
+ self.max_position_embeddings = max_position_embeddings
452
+ self.hidden_size = hidden_size
453
+ self.intermediate_size = intermediate_size
454
+ self.num_hidden_layers = num_hidden_layers
455
+ self.num_attention_heads = num_attention_heads
456
+ self.use_sliding_window = use_sliding_window
457
+ self.sliding_window = sliding_window if use_sliding_window else None
458
+ self.max_window_layers = max_window_layers
459
+
460
+ # for backward compatibility
461
+ if num_key_value_heads is None:
462
+ num_key_value_heads = num_attention_heads
463
+
464
+ self.num_key_value_heads = num_key_value_heads
465
+ self.hidden_act = hidden_act
466
+ self.initializer_range = initializer_range
467
+ self.rms_norm_eps = rms_norm_eps
468
+ self.use_cache = use_cache
469
+ self.rope_theta = rope_theta
470
+ self.attention_dropout = attention_dropout
471
+
472
+ super().__init__(
473
+ tie_word_embeddings=tie_word_embeddings,
474
+ **kwargs,
475
+ )
476
+
477
+
478
+ class D2Coder(PreTrainedModel):
479
+
480
+ def __init__(self, config):
481
+ super().__init__(config)
482
+ self.plm_model = Qwen2ForCausalLM(config)
483
+
484
+ self.embedding_method = config.embedding_method
485
+ self.inf_seq_length = config.inf_seq_length
486
+ self.encoder_mode = config.encoder_mode
487
+ self.num_encoder_layers = config.num_encoder_layers
488
+ self.padding_side = config.padding_side
489
+
490
+ self.keep_max_layer = config.keep_max_layer
491
+ self.emb_dim = self.plm_model.model.embed_tokens.weight.size(1)
492
+ self.num_heads = config.pma_num_heads
493
+ self.ln = config.pma_ln
494
+ self.norm = config.pma_norm
495
+ self.pma_mode = config.pma_norm_mode
496
+ self.encoder = Encoder(self.emb_dim, self.num_heads, self.ln, self.encoder_mode, self.num_encoder_layers)
497
+ self.mha_pma = PMA(self.emb_dim, self.num_heads, 1, ln=self.ln, pma_mode=self.pma_mode)
498
+
499
+ def forward(self, inputs_all, mode, args):
500
+ # output_embeddings_a = self.get_sentence_embedding(self.embedding_method, **inputs_a)
501
+
502
+ # output_embeddings_b = self.get_sentence_embedding(self.embedding_method, **inputs_b) # (bs, emb_size)
503
+ bs = self.args.batch_size
504
+ if mode == 'train':
505
+ output_embeddings_all = self.get_sentence_embedding(self.embedding_method, **inputs_all).reshape(2+self.args.neg_K, bs, -1) # (2+K, bs, emb_size)
506
+ # if self.to_compress:
507
+ # output_embeddings_all = self.projector(output_embeddings_all)
508
+
509
+ output_embeddings_hardneg = output_embeddings_all[2:] # (neg_K, bs, emb)
510
+ hn_norm = torch.nn.functional.normalize(output_embeddings_hardneg, p=2, dim=-1)
511
+ elif mode == 'eval':
512
+ output_embeddings_all = self.get_sentence_embedding(self.embedding_method, **inputs_all).reshape(2, bs, -1) # (2, bs, emb_size)
513
+ # if self.to_compress:
514
+ # output_embeddings_all = self.projector(output_embeddings_all)
515
+ else:
516
+ raise ValueError('Error of mode value')
517
+
518
+ output_embeddings_a = output_embeddings_all[0] # (bs, emb)
519
+ output_embeddings_b = output_embeddings_all[1] # (bs, emb)
520
+ a_norm = torch.nn.functional.normalize(output_embeddings_a, p=2, dim=-1)
521
+ b_norm = torch.nn.functional.normalize(output_embeddings_b, p=2, dim=-1)
522
+
523
+
524
+
525
+ b_cross_gpus = gather_across_devices(output_embeddings_b, args.global_rank, self.world_size)
526
+ b_norm_cross_gpus = torch.nn.functional.normalize(b_cross_gpus, p=2, dim=-1) # ()
527
+
528
+
529
+ assert a_norm.size(0) == b_norm.size(0)
530
+ bs = output_embeddings_a.size(0)
531
+ # in-batch计算部分
532
+ output_in_batch_local_gpu = torch.matmul(a_norm, b_norm.t())
533
+ output_in_batch_global_gpu = torch.matmul(a_norm, b_norm_cross_gpus.t())
534
+
535
+ if mode == 'train':
536
+ # hard neg计算部分
537
+ pos_neg_emb = torch.cat([b_norm.unsqueeze(0), hn_norm], dim=0) # (1+neg_K, bs, emb)
538
+ output_hardneg_specific_task = torch.matmul(a_norm.unsqueeze(1), pos_neg_emb.permute(1,2,0)).squeeze() # (bs, 1+neg_K)
539
+ # output_pos_hardneg_rep_specific_task = torch.cat([output_embeddings_a.unsqueeze(0).expand(pos_neg_emb.size(0),-1,-1), pos_neg_emb],dim=-1)
540
+
541
+ elif mode == 'eval':
542
+ output_hardneg_specific_task = None
543
+ output_pos_hardneg_rep_specific_task = None
544
+
545
+ return output_in_batch_local_gpu, output_in_batch_global_gpu, output_hardneg_specific_task # (bs, bs) (bs, world_size*bs), (bs, 1+neg_K)
546
+ # return output_in_batch_specific_task, output_hardneg_specific_task, output_pos_hardneg_rep_specific_task
547
+
548
+ def last_embedding(self, A, index):
549
+ bs, seq, emb = A.size()
550
+ res = A[torch.arange(bs), index, :]
551
+ return res
552
+
553
+ def mean_embedding(self, A, mask):
554
+ bs, seq, emb = A.size()
555
+ res = (A * (mask.unsqueeze(-1))).sum(1) / (mask.sum(1).unsqueeze(-1))
556
+ return res
557
+
558
+ # A (bs, seq, emb_size), mask (bs, 1, seq)
559
+ def weighted_embedding(self, A, mask):
560
+ weights = (torch.arange(start=1, end=A.size(1) + 1).unsqueeze(0).unsqueeze(-1).expand(A.size()).float()).to(A.device)
561
+ input_mask_expanded = (mask.squeeze(1).unsqueeze(-1).expand(A.size()).float()).to(A.device)
562
+ sum_embedding = torch.sum(A * input_mask_expanded * weights, dim=1)
563
+ sum_mask = torch.sum(input_mask_expanded * weights, dim=1)
564
+ weighted_embedding = sum_embedding / sum_mask
565
+
566
+ return weighted_embedding
567
+
568
+ def pma_embedding(self, A, mask):
569
+ res = self.mha_pma(A, mask).squeeze(1)
570
+ return res
571
+
572
+
573
+ def get_sentence_embedding(self, embedding_method, **inputs):
574
+ outputs = self.plm_model(inputs['input_ids'], inputs['attention_mask'], output_hidden_states=True)
575
+ if embedding_method == 'last':
576
+ embedding = outputs.hidden_states[self.keep_max_layer]
577
+ index = inputs['attention_mask'].sum(-1).long() - 1
578
+ res_embedding = self.last_embedding(embedding, index)
579
+ elif embedding_method == 'mean':
580
+ embedding = outputs.hidden_states[self.keep_max_layer]
581
+ res_embedding = self.mean_embedding(embedding, inputs['attention_mask'])
582
+ elif embedding_method == 'weighted':
583
+ embedding = outputs.hidden_states[self.keep_max_layer]
584
+ res_embedding = self.weighted_embedding(embedding, inputs['attention_mask'])
585
+ elif embedding_method == 'pma':
586
+ embedding = outputs.hidden_states[self.keep_max_layer] # Qwen.hidden_state: (33, bs, seq, emb)
587
+ attention_mask = inputs['attention_mask']
588
+ embedding = self.encoder(embedding, attention_mask)
589
+ res_embedding = self.pma_embedding(embedding, attention_mask) # embedding: (bs, seq, emb), inputs['attention_mask']: (bs, seq)
590
+ else:
591
+ logger.debug('Error, no {} way to obtain embbedings'.format(embedding_method))
592
+
593
+ if not self.norm:
594
+ res_embedding = torch.nn.functional.normalize(res_embedding, p=2.0, dim=-1, eps=1e-12, out=None)
595
+ return res_embedding
596
+
597
+
598
+
599
+ def encode(self, tokenizer, sentences, batch_size=32, convert_to_numpy=True,
600
+ convert_to_tensor=False, show_progress_bar=True, max_seq_length=None, **kwargs):
601
+
602
+ if max_seq_length is None:
603
+ max_seq_length = self.inf_seq_length
604
+
605
+ input_is_string = False
606
+ if isinstance(sentences, str) or not hasattr(sentences, "__len__"):
607
+ sentences = [sentences]
608
+ input_is_string = True
609
+
610
+
611
+ all_embeddings = []
612
+ length_sorted_idx = np.argsort([-len(s) for s in sentences])
613
+ sentences_sorted = [sentences[idx] for idx in length_sorted_idx] # 大到小重排
614
+ with torch.no_grad():
615
+ for start_index in trange(0, len(sentences), batch_size, desc="Batches", disable=not show_progress_bar):
616
+ sentences_batch = sentences_sorted[start_index: start_index + batch_size]
617
+ # Compute sentences embeddingsz
618
+ with torch.no_grad():
619
+ inputs = tokenizer(sentences_batch, padding=True, truncation=True, max_length=max_seq_length, add_special_tokens=False, return_tensors='pt').to(self.plm_model.device)
620
+ embeddings = self.get_sentence_embedding(self.embedding_method, **inputs)
621
+ # if self.to_compress:
622
+ # embeddings = self.projector(embeddings)
623
+ embeddings = embeddings.detach()
624
+ if convert_to_numpy:
625
+ if embeddings.dtype == torch.bfloat16:
626
+ embeddings = embeddings.cpu().to(torch.float32)
627
+ else:
628
+ embeddings = embeddings.cpu()
629
+ all_embeddings.extend(embeddings)
630
+ all_embeddings = [all_embeddings[idx] for idx in np.argsort(length_sorted_idx)]
631
+ if convert_to_tensor:
632
+ all_embeddings = torch.stack(all_embeddings)
633
+ elif convert_to_numpy:
634
+ all_embeddings = np.asarray([emb.numpy() for emb in all_embeddings])
635
+
636
+ if input_is_string:
637
+ all_embeddings = all_embeddings[0]
638
+ return all_embeddings