ikuyamada commited on
Commit
7d780b3
·
verified ·
1 Parent(s): 69ec906

Upload model

Browse files
Files changed (4) hide show
  1. config.json +44 -0
  2. configuration.py +37 -0
  3. model.safetensors +3 -0
  4. modeling.py +244 -0
config.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "models/qa_multi_4_bge_freeze_diclp0.05pp0.3_min1_epoch20_lrate5e-5",
3
+ "architectures": [
4
+ "KPRModelForBert"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration.KPRConfigForBert",
9
+ "AutoModel": "modeling.KPRModelForBert"
10
+ },
11
+ "classifier_dropout": null,
12
+ "entity_embedding_size": 768,
13
+ "entity_fusion_activation": "sigmoid",
14
+ "entity_fusion_method": "multihead_attention",
15
+ "entity_vocab_size": null,
16
+ "gradient_checkpointing": false,
17
+ "hidden_act": "gelu",
18
+ "hidden_dropout_prob": 0.1,
19
+ "hidden_size": 768,
20
+ "id2label": {
21
+ "0": "LABEL_0"
22
+ },
23
+ "initializer_range": 0.02,
24
+ "intermediate_size": 3072,
25
+ "label2id": {
26
+ "LABEL_0": 0
27
+ },
28
+ "layer_norm_eps": 1e-12,
29
+ "max_position_embeddings": 512,
30
+ "model_type": "kpr-bert",
31
+ "num_attention_heads": 12,
32
+ "num_entity_fusion_attention_heads": 1,
33
+ "num_hidden_layers": 12,
34
+ "pad_token_id": 0,
35
+ "position_embedding_type": "absolute",
36
+ "similarity_function": "cosine",
37
+ "similarity_temperature": 0.02,
38
+ "torch_dtype": "float32",
39
+ "transformers_version": "4.35.2",
40
+ "type_vocab_size": 2,
41
+ "use_cache": true,
42
+ "use_entity_position_embeddings": true,
43
+ "vocab_size": 30522
44
+ }
configuration.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.models.bert import BertConfig
2
+ from transformers.models.xlm_roberta import XLMRobertaConfig
3
+
4
+
5
+ def _init_function(
6
+ self,
7
+ entity_vocab_size: int | None = 10000,
8
+ entity_embedding_size: int = 768,
9
+ entity_fusion_method: str = "multihead_attention",
10
+ use_entity_position_embeddings: bool = True,
11
+ entity_fusion_activation: str = "softmax",
12
+ num_entity_fusion_attention_heads: int = 12,
13
+ similarity_function: str = "dot",
14
+ similarity_temperature: float = 1.0,
15
+ *args,
16
+ **kwargs,
17
+ ):
18
+ self.entity_vocab_size = entity_vocab_size
19
+ self.entity_embedding_size = entity_embedding_size
20
+ self.entity_fusion_method = entity_fusion_method
21
+ self.use_entity_position_embeddings = use_entity_position_embeddings
22
+ self.entity_fusion_activation = entity_fusion_activation
23
+ self.num_entity_fusion_attention_heads = num_entity_fusion_attention_heads
24
+ self.similarity_function = similarity_function
25
+ self.similarity_temperature = similarity_temperature
26
+
27
+ super(self.__class__, self).__init__(*args, **kwargs)
28
+
29
+
30
+ class KPRConfigForBert(BertConfig):
31
+ __init__ = _init_function
32
+ model_type = "kpr-bert"
33
+
34
+
35
+ class KPRConfigForXLMRoberta(XLMRobertaConfig):
36
+ __init__ = _init_function
37
+ model_type = "kpr-xlm-roberta"
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eeb2938c65122bbba652f56f2f77ad285e77f4d5d44aa60e2a3cc16b757801e7
3
+ size 448988504
modeling.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+ import torch.distributed as dist
5
+ import torch.nn.functional as F
6
+ from torch import Tensor, nn
7
+ from transformers import PretrainedConfig
8
+ from transformers.file_utils import ModelOutput
9
+ from transformers.models.bert import BertModel, BertPreTrainedModel
10
+ from transformers.models.xlm_roberta import XLMRobertaModel, XLMRobertaPreTrainedModel
11
+
12
+ from .configuration import KPRConfigForBert, KPRConfigForXLMRoberta
13
+
14
+
15
+ class EntityEmbeddings(nn.Module):
16
+ def __init__(self, config: PretrainedConfig):
17
+ super().__init__()
18
+ self.config = config
19
+
20
+ if config.entity_vocab_size is not None:
21
+ self.embeddings = nn.Embedding(config.entity_vocab_size, config.entity_embedding_size, padding_idx=0)
22
+ self.embeddings.weight.requires_grad = False
23
+
24
+ # The 0-th position corresponds to the [CLS] token which does not correspond to any entity
25
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size, padding_idx=0)
26
+
27
+ self.dense = nn.Linear(config.entity_embedding_size, config.hidden_size, bias=False)
28
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
29
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
30
+
31
+ def forward(self, entity_ids: Tensor | None, entity_embeds: Tensor | None, entity_position_ids: Tensor) -> Tensor:
32
+ if entity_embeds is not None:
33
+ entity_embeddings = entity_embeds
34
+ elif entity_ids is not None:
35
+ if self.config.entity_vocab_size is None:
36
+ raise ValueError("Entity embeddings are not constructed because entity_vocab_size is None.")
37
+ entity_embeddings = self.embeddings(entity_ids)
38
+ else:
39
+ raise ValueError("Either entity_ids or entity_embeds need to be provided.")
40
+
41
+ entity_embeddings = self.dense(entity_embeddings)
42
+
43
+ if self.config.use_entity_position_embeddings:
44
+ entity_position_embeddings = self.position_embeddings(
45
+ entity_position_ids
46
+ ) # batch, entities, positions, hidden
47
+ entity_position_embeddings = torch.sum(entity_position_embeddings, dim=2)
48
+ entity_position_embeddings = entity_position_embeddings / entity_position_ids.ne(0).sum(dim=2).clamp(
49
+ min=1
50
+ ).unsqueeze(-1)
51
+ entity_embeddings = entity_embeddings + entity_position_embeddings
52
+
53
+ entity_embeddings = self.LayerNorm(entity_embeddings)
54
+ entity_embeddings = self.dropout(entity_embeddings)
55
+
56
+ return entity_embeddings
57
+
58
+
59
+ class EntityFusionMultiHeadAttention(nn.Module):
60
+ def __init__(self, config: PretrainedConfig):
61
+ super().__init__()
62
+ self.config = config
63
+
64
+ self.num_attention_heads = config.num_entity_fusion_attention_heads
65
+ self.attention_head_size = int(config.hidden_size / self.num_attention_heads)
66
+
67
+ self.query = nn.Linear(config.hidden_size, config.hidden_size)
68
+ self.key = nn.Linear(config.hidden_size, config.hidden_size)
69
+ self.value = nn.Linear(config.hidden_size, config.hidden_size)
70
+
71
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
72
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
73
+ x = x.view(new_x_shape)
74
+ return x.permute(0, 2, 1, 3)
75
+
76
+ def forward(
77
+ self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, key_padding_mask: torch.Tensor
78
+ ) -> tuple[torch.Tensor, torch.Tensor]:
79
+ query_layer = self.transpose_for_scores(self.query(query))
80
+ key_layer = self.transpose_for_scores(self.key(key))
81
+ value_layer = self.transpose_for_scores(self.value(value))
82
+
83
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
84
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
85
+
86
+ dtype = attention_scores.dtype
87
+ key_padding_mask_scores = key_padding_mask[:, None, None, :]
88
+ key_padding_mask_scores = key_padding_mask_scores.to(dtype=dtype)
89
+ key_padding_mask_scores = key_padding_mask_scores * torch.finfo(dtype).min
90
+ attention_scores = attention_scores + key_padding_mask_scores
91
+ orig_attention_scores = attention_scores.clone()
92
+
93
+ if self.config.entity_fusion_activation == "sigmoid":
94
+ # https://arxiv.org/abs/2409.04431
95
+ entity_fusion_sigmoid_bias = key_padding_mask.eq(0).sum(dim=-1, keepdim=True)[:, :, None, None]
96
+ entity_fusion_sigmoid_bias = entity_fusion_sigmoid_bias.to(dtype)
97
+ entity_fusion_sigmoid_bias = -torch.log(entity_fusion_sigmoid_bias)
98
+
99
+ attention_scores = attention_scores + entity_fusion_sigmoid_bias
100
+ normalized_attention_scores = torch.sigmoid(attention_scores)
101
+ else:
102
+ normalized_attention_scores = nn.functional.softmax(attention_scores, dim=-1)
103
+
104
+ context_layer = torch.matmul(normalized_attention_scores, value_layer)
105
+
106
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
107
+ new_context_layer_shape = context_layer.size()[:-2] + (self.config.hidden_size,)
108
+ context_layer = context_layer.view(new_context_layer_shape)
109
+
110
+ return (context_layer, orig_attention_scores)
111
+
112
+
113
+ class EntityFusionLayer(nn.Module):
114
+ def __init__(self, config: PretrainedConfig):
115
+ super().__init__()
116
+ self.config = config
117
+
118
+ self.entity_embeddings = EntityEmbeddings(config)
119
+ self.entity_fusion_layer = EntityFusionMultiHeadAttention(config)
120
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
121
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
122
+
123
+ self.noop_embeddings = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
124
+
125
+ def forward(
126
+ self,
127
+ entity_ids: Tensor | None,
128
+ entity_embeds: Tensor | None,
129
+ entity_position_ids: Tensor,
130
+ cls_embeddings: Tensor,
131
+ ) -> tuple[torch.Tensor, torch.Tensor]:
132
+ entity_embeddings = self.entity_embeddings(entity_ids, entity_embeds, entity_position_ids)
133
+
134
+ batch_size = entity_ids.size(0)
135
+ kv_embeddings = entity_embeddings
136
+ key_padding_mask = entity_ids.eq(0)
137
+ cls_embeddings = cls_embeddings.unsqueeze(1)
138
+
139
+ noop_embeddings = self.noop_embeddings.expand(batch_size, 1, -1)
140
+
141
+ kv_embeddings = torch.cat([noop_embeddings, kv_embeddings], dim=1)
142
+ noop_padding_mask = torch.zeros(batch_size, 1, device=entity_ids.device, dtype=torch.bool)
143
+ key_padding_mask = torch.cat([noop_padding_mask, key_padding_mask], dim=1)
144
+
145
+ entity_embeddings, attention_scores = self.entity_fusion_layer(
146
+ cls_embeddings, kv_embeddings, kv_embeddings, key_padding_mask=key_padding_mask
147
+ )
148
+ entity_embeddings = self.dropout(entity_embeddings)
149
+ output_embeddings = entity_embeddings + cls_embeddings
150
+ output_embeddings = self.LayerNorm(output_embeddings)
151
+
152
+ output_embeddings = output_embeddings.squeeze(1)
153
+
154
+ return output_embeddings, attention_scores
155
+
156
+
157
+ class KPRMixin:
158
+ def _forward(self, **inputs: Tensor | dict[str, Tensor]) -> Tensor:
159
+ if self.training:
160
+ query_embeddings = self._encode(inputs["queries"])
161
+ passage_embeddings = self._encode(inputs["passages"])
162
+
163
+ query_embeddings = self._dist_gather_tensor(query_embeddings)
164
+ passage_embeddings = self._dist_gather_tensor(passage_embeddings)
165
+
166
+ scores = self._compute_similarity(query_embeddings, passage_embeddings)
167
+ scores = scores / self.config.similarity_temperature
168
+ scores = scores.view(query_embeddings.size(0), -1)
169
+
170
+ ce_target = torch.arange(scores.size(0), device=scores.device, dtype=torch.long)
171
+ ce_target = ce_target * (passage_embeddings.size(0) // query_embeddings.size(0))
172
+ loss = torch.nn.CrossEntropyLoss(reduction="mean")(scores, ce_target)
173
+
174
+ return ModelOutput(loss=loss, scores=scores)
175
+
176
+ else:
177
+ return self._encode(inputs)
178
+
179
+ def _encode(self, inputs: dict[str, Tensor]) -> Tensor:
180
+ entity_ids = inputs.pop("entity_ids", None)
181
+ entity_position_ids = inputs.pop("entity_position_ids", None)
182
+ entity_embeds = inputs.pop("entity_embeds", None)
183
+
184
+ outputs = getattr(self, self.base_model_prefix)(**inputs)
185
+ output_embeddings = outputs.last_hidden_state[:, 0]
186
+
187
+ if self.config.entity_fusion_method != "none":
188
+ output_embeddings, _ = self.entity_fusion_layer(
189
+ entity_ids=entity_ids,
190
+ entity_embeds=entity_embeds,
191
+ entity_position_ids=entity_position_ids,
192
+ cls_embeddings=output_embeddings,
193
+ )
194
+
195
+ return output_embeddings
196
+
197
+ def _dist_gather_tensor(self, t: torch.Tensor) -> torch.Tensor:
198
+ t = t.contiguous()
199
+ tensor_list = [torch.empty_like(t) for _ in range(dist.get_world_size())]
200
+ dist.all_gather(tensor_list, t)
201
+
202
+ tensor_list[dist.get_rank()] = t
203
+ gathered_tensor = torch.cat(tensor_list, dim=0)
204
+
205
+ return gathered_tensor
206
+
207
+ def _compute_similarity(self, query_embeddings: Tensor, passage_embeddings: Tensor) -> Tensor:
208
+ if self.config.similarity_function == "cosine":
209
+ query_embeddings = F.normalize(query_embeddings, p=2, dim=-1)
210
+ passage_embeddings = F.normalize(passage_embeddings, p=2, dim=-1)
211
+
212
+ return torch.matmul(query_embeddings, passage_embeddings.transpose(-2, -1))
213
+
214
+
215
+ class KPRModelForBert(BertPreTrainedModel, KPRMixin):
216
+ config_class = KPRConfigForBert
217
+
218
+ def __init__(self, config: KPRConfigForBert):
219
+ BertPreTrainedModel.__init__(self, config)
220
+
221
+ self.bert = BertModel(config)
222
+ if self.config.entity_fusion_method != "none":
223
+ self.entity_fusion_layer = EntityFusionLayer(config)
224
+
225
+ self.post_init()
226
+
227
+ def forward(self, *args, **kwargs):
228
+ return self._forward(*args, **kwargs)
229
+
230
+
231
+ class KPRModelForXLMRoberta(XLMRobertaPreTrainedModel, KPRMixin):
232
+ config_class = KPRConfigForXLMRoberta
233
+
234
+ def __init__(self, config: KPRConfigForXLMRoberta):
235
+ XLMRobertaPreTrainedModel.__init__(self, config)
236
+
237
+ self.roberta = XLMRobertaModel(config)
238
+ if self.config.entity_fusion_method != "none":
239
+ self.entity_fusion_layer = EntityFusionLayer(config)
240
+
241
+ self.post_init()
242
+
243
+ def forward(self, *args, **kwargs):
244
+ return self._forward(*args, **kwargs)