MCPcopy Create free account
hub / github.com/BeastyZ/ConvSearch-R1 / ANCE

Class ANCE

src/eval/models.py:11–55  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

9
10# ANCE model
11class ANCE(RobertaForSequenceClassification):
12 # class Pooler: # adapt to DPR
13 # def __init__(self, pooler_output):
14 # self.pooler_output = pooler_output
15
16 def __init__(self, config):
17 RobertaForSequenceClassification.__init__(self, config)
18 self.embeddingHead = nn.Linear(config.hidden_size, 768)
19 self.norm = nn.LayerNorm(768)
20 self.apply(self._init_weights)
21 self.use_mean = False
22
23 def _init_weights(self, module):
24 """ Initialize the weights """
25 if isinstance(module, (nn.Linear, nn.Embedding, nn.Conv1d)):
26 # Slightly different from the TF version which uses truncated_normal for initialization
27 # cf https://github.com/pytorch/pytorch/pull/5617
28 module.weight.data.normal_(mean=0.0, std=0.02)
29
30 def query_emb(self, input_ids, attention_mask):
31 outputs1 = self.roberta(input_ids=input_ids,
32 attention_mask=attention_mask)
33 outputs1 = outputs1.last_hidden_state
34 full_emb = self.masked_mean_or_first(outputs1, attention_mask)
35 query1 = self.norm(self.embeddingHead(full_emb))
36 return query1
37
38
39 def doc_emb(self, input_ids, attention_mask):
40 return self.query_emb(input_ids, attention_mask)
41
42
43 def masked_mean_or_first(self, emb_all, mask):
44 if self.use_mean:
45 return self.masked_mean(emb_all, mask)
46 else:
47 return emb_all[:, 0]
48
49 def masked_mean(self, t, mask):
50 s = torch.sum(t * mask.unsqueeze(-1).float(), axis=1)
51 d = mask.sum(axis=1, keepdim=True).float()
52 return s / d
53
54 def forward(self, input_ids, attention_mask, wrap_pooler=False):
55 return self.query_emb(input_ids, attention_mask)
56
57
58def load_model(model_type, model_path):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected