-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpreprocess_finetuned_variant_7.py
202 lines (157 loc) · 6.54 KB
/
preprocess_finetuned_variant_7.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
from transformers import RobertaTokenizer, RobertaModel
import pandas as pd
import json
import os
import torch
import tqdm
from torch import cuda
from torch import nn as nn
import matplotlib.pyplot as plt
from model import VariantSeventFineTuneOnlyClassifier
directory = os.path.dirname(os.path.abspath(__file__))
EMBEDDING_DIRECTORY = '../finetuned_embeddings/variant_7'
FINE_TUNED_MODEL_PATH = 'model/patch_variant_7_finetuned_model.sav'
dataset_name = 'ase_dataset_sept_19_2021.csv'
# dataset_name = 'huawei_sub_dataset.csv'
CODE_LINE_LENGTH = 256
use_cuda = cuda.is_available()
device = torch.device("cuda:0" if use_cuda else "cpu")
random_seed = 109
torch.manual_seed(random_seed)
torch.cuda.manual_seed(random_seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = True
def get_input_and_mask(tokenizer, code_list):
inputs = tokenizer(code_list, padding='max_length', max_length=CODE_LINE_LENGTH, truncation=True, return_tensors="pt")
return inputs.data['input_ids'], inputs.data['attention_mask']
def get_code_version(diff, added_version):
code = ''
lines = diff.splitlines()
for line in lines:
mark = '+'
if not added_version:
mark = '-'
if line.startswith(mark):
line = line[1:].strip()
if line.startswith(('//', '/**', '/*', '*', '*/', '#')):
continue
code = code + line + '\n'
return code
def get_hunk_embeddings(code_list, tokenizer, code_bert):
# process all hunks in one
if len(code_list) == 0:
return []
input_ids, attention_mask = get_input_and_mask(tokenizer, code_list)
with torch.no_grad():
input_ids = input_ids.to(device)
attention_mask = attention_mask.to(device)
embeddings = code_bert(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state[:, 0, :]
embeddings = embeddings.tolist()
return embeddings
def write_embeddings_to_files(removed_embeddings, added_embeddings, removed_url_list, added_url_list):
url_set = set()
url_to_removed_embeddings = {}
for index, url in enumerate(removed_url_list):
if url not in url_to_removed_embeddings:
url_set.add(url)
url_to_removed_embeddings[url] = []
url_to_removed_embeddings[url].append(removed_embeddings[index])
url_to_added_embeddings = {}
for index, url in enumerate(added_url_list):
if url not in url_to_added_embeddings:
url_set.add(url)
url_to_added_embeddings[url] = []
url_to_added_embeddings[url].append(added_embeddings[index])
url_to_data = {}
for url in url_set:
before_data = []
after_data = []
if url in url_to_removed_embeddings:
before_data = url_to_removed_embeddings[url]
if url in url_to_added_embeddings:
after_data = url_to_added_embeddings[url]
data = {'before': before_data, 'after': after_data}
url_to_data[url] = data
for url, data in url_to_data.items():
file_path = os.path.join(directory, EMBEDDING_DIRECTORY + '/' + url.replace('/', '_') + '.txt')
json.dump(data, open(file_path, 'w'))
def hunk_empty(hunk):
if hunk.strip() == '':
return True
for line in hunk.split('\n'):
if line[1:].strip() != '':
return False
return True
def get_hunk_from_diff(diff):
hunk_list = []
hunk = ''
for line in diff.split('\n'):
if line.startswith(('+', '-')):
hunk = hunk + line + '\n'
else:
if not hunk_empty(hunk): # finish a hunk
hunk = hunk[:-1]
hunk_list.append(hunk)
hunk = ''
if not hunk_empty(hunk):
hunk_list.append(hunk)
return hunk_list
def get_data():
tokenizer = RobertaTokenizer.from_pretrained("microsoft/codebert-base")
model = VariantSeventFineTuneOnlyClassifier()
if torch.cuda.device_count() > 1:
print("Let's use", torch.cuda.device_count(), "GPUs!")
# dim = 0 [30, xxx] -> [10, ...], [10, ...], [10, ...] on 3 GPUs
model = nn.DataParallel(model)
model.load_state_dict(torch.load(FINE_TUNED_MODEL_PATH))
code_bert = model.module.code_bert
if torch.cuda.device_count() > 1:
print("Let's use", torch.cuda.device_count(), "GPUs!")
# dim = 0 [30, xxx] -> [10, ...], [10, ...], [10, ...] on 3 GPUs
code_bert = nn.DataParallel(code_bert)
code_bert = code_bert.to(device)
code_bert.eval()
print("Reading dataset...")
df = pd.read_csv(dataset_name)
df = df[['commit_id', 'repo', 'partition', 'diff', 'label', 'PL', 'LOC_MOD', 'filename']]
items = df.to_numpy().tolist()
url_to_hunk = {}
for item in items:
commit_id = item[0]
repo = item[1]
url = repo + '/commit/' + commit_id
diff = item[3]
if url not in url_to_hunk:
url_to_hunk[url] = []
url_to_hunk[url].extend(get_hunk_from_diff(diff))
removed_code_list = []
added_code_list = []
removed_url_list = []
added_url_list = []
for url, diff_list in tqdm.tqdm(url_to_hunk.items()):
file_path = os.path.join(directory, EMBEDDING_DIRECTORY + '/' + url.replace('/', '_') + '.txt')
if os.path.isfile(file_path):
continue
for i, diff in enumerate(diff_list):
removed_code = get_code_version(diff, False)
if removed_code.strip() != '':
removed_code_list.append(removed_code)
removed_url_list.append(url)
added_code = get_code_version(diff, True)
if added_code.strip() != '':
added_code_list.append(added_code)
added_url_list.append(url)
if len(removed_code_list) >= 50 or len(added_code_list) >= 50:
removed_embeddings = get_hunk_embeddings(removed_code_list, tokenizer, code_bert)
added_embeddings = get_hunk_embeddings(added_code_list, tokenizer, code_bert)
write_embeddings_to_files(removed_embeddings, added_embeddings, removed_url_list, added_url_list)
removed_code_list = []
added_code_list = []
removed_url_list = []
added_url_list = []
if len(removed_code_list) > 0 or len(added_code_list) > 0:
removed_embeddings = get_hunk_embeddings(removed_code_list, tokenizer, code_bert)
added_embeddings = get_hunk_embeddings(added_code_list, tokenizer, code_bert)
write_embeddings_to_files(removed_embeddings, added_embeddings, removed_url_list, added_url_list)
if __name__ == '__main__':
get_data()