-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrunTest.py
75 lines (54 loc) · 2.41 KB
/
runTest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from sentence_transformers import SentenceTransformer, models, InputExample, losses, util, LoggingHandler
from torch.utils.data import DataLoader
from transformers import AutoTokenizer, AutoModel
import torch
import sys,os
import torch.nn.functional as F
import json
from sentence_transformers import evaluation
from tqdm import tqdm
import logging
import pandas as pd
DEVICE='cuda'
logging.basicConfig(format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.INFO,
handlers=[LoggingHandler()])
def test(test_data):
# Mean Pooling - Take attention mask into account for correct averaging
def mean_pooling(model_output, attention_mask):
# First element of model_output contains all token embeddings
token_embeddings = model_output[0]
input_mask_expanded = attention_mask.unsqueeze(
-1).expand(token_embeddings.size()).float()
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
checkPointFolder = "models/triplet-loss/..." #specify the path to the best-performing checkpoint
tokenizer = AutoTokenizer.from_pretrained(checkPointFolder)
model = AutoModel.from_pretrained(checkPointFolder).to(DEVICE)
similarities = []
for idx,item in tqdm(test_data.iterrows()):
################## NEGATIVE ##################
sentences = []
sentences.append(item['codeFunctions'])
sentences.append(item['codeComment'])
# Tokenize sentences
encoded_input = tokenizer(
sentences, padding=True, truncation=True, return_tensors='pt').to(DEVICE)
# Compute token embeddings
with torch.no_grad():
model_output = model(**encoded_input)
# Perform pooling
sentence_embeddings = mean_pooling(
model_output, encoded_input['attention_mask'])
# Normalize embeddings
sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)
sim = util.pytorch_cos_sim(
sentence_embeddings[0], sentence_embeddings[1]).item()
similarities.append(sim)
test_data['SIDE'] = similarities
test_data.to_csv('human-annotated-dataset-all-metrics.csv')
def main():
df_response = pd.read_csv('human-annotated-dataset-all-metrics.csv')
test(df_response)
if __name__ == "__main__":
main()