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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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#!/usr/bin/env python
# coding: utf-8

# In[1]:


import pandas as pd
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn import init, MarginRankingLoss
from transformers import BertModel, RobertaModel
from transformers import BertTokenizer, RobertaTokenizer
from torch.optim import Adam
from distutils.version import LooseVersion
from torch.utils.data import Dataset, DataLoader
from torch.utils.tensorboard import SummaryWriter
from datetime import datetime
from torch.autograd import Variable
from transformers import AutoConfig, AutoModel, AutoModelForCausalLM, AutoTokenizer
import torch.optim as optim
from torch.distributions import Categorical
import random
from transformers import AutoModelForMaskedLM, BertForMaskedLM, AdamW
from transformers import BertTokenizer
from tqdm import tqdm
import matplotlib.pyplot as plt
from transformers import XLMRobertaTokenizer
import os
import csv
from sklearn.model_selection import train_test_split
import nltk
from collections import defaultdict
from nltk.tokenize import word_tokenize
from nltk import pos_tag
from nltk.tokenize import word_tokenize
import math
from nltk.corpus import words
from sklearn.model_selection import train_test_split
import random
import re
import random


# In[2]:


class MyDataset(Dataset):
    def __init__(self,file_name):
        df1 = pd.read_csv(file_name)
        df1 = df1[200:300]
        df1 = df1.fillna("")
        res = df1['X'].to_numpy()
        self.X_list = res
        self.y_list = df1['y'].to_numpy()
    def __len__(self):
        return len(self.X_list)
    def __getitem__(self,idx):
        mapi = []
        mapi.append(self.X_list[idx])
        mapi.append(self.y_list[idx])
        return mapi


# In[3]:


class Step1_model(nn.Module):
    def __init__(self, hidden_size=512):
        super(Step1_model, self).__init__()
        self.hidden_size = hidden_size
        self.model = AutoModelForMaskedLM.from_pretrained('microsoft/graphcodebert-base')
        self.tokenizer = AutoTokenizer.from_pretrained("microsoft/graphcodebert-base")
        self.config = AutoConfig.from_pretrained("microsoft/graphcodebert-base")
        self.linear_layer = nn.Linear(self.model.config.vocab_size, self.model.config.vocab_size)
    def foo (self,data):
        result = []
        if type(data) == tuple:
            return data[1]
        if type(data) == list:
            for inner in data:
                result.append(foo(inner))
        res = []
        for a in result[0]:
            res.append(a[:2])
        return res
    def loss_func1(self, word, y):
        if word =='NA':
            return torch.full((1,), fill_value=100)
        try:
            pred_list = re.findall(r'[A-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))|[a-z]+|\d+', word)
            target_list = re.findall(r'[A-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))|[a-z]+|\d+', y)
            pred_tag = self.foo(nltk.pos_tag(pred_list))
            target_tag = self.foo(nltk.pos_tag(target_list))
            str1 = ' '.join(pred_tag)  # Convert lists to strings
            str2 = ' '.join(target_tag)
            distance = Levenshtein.distance(str1, str2)
            dist = torch.Tensor([distance])
        except:
            dist = torch.Tensor([2*len(target_list)])
        return dist
    def loss_func2(self, word, y):
        if word =='NA':
            return  torch.full((1,), fill_value=100)
        nlp = en_core_web_sm.load()
        pred_list = re.findall(r'[A-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))|[a-z]+|\d+', word)
        target_list = re.findall(r'[A-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))|[a-z]+|\d+', y)
        try:
            str1 = ' '.join(pred_list)  # Convert lists to strings
            str2 = ' '.join(target_list)
            tokens1 = nlp(str1)
            tokens2 = nlp(str2)
            embedding1 = sum(token.vector for token in tokens1) / len(tokens1)
            embedding2 = sum(token.vector for token in tokens2) / len(tokens2)
            w1= LA.norm(embedding1)
            w2= LA.norm(embedding2)
            distance = 1 - (embedding1.dot(embedding2) / (w1 * w2))
            dist = torch.Tensor([distance])
        except:
            dist = torch.Tensor([1])
        return dist
    def forward(self, mapi):
        global variable_names
        global base_model
        global tot_pll
        global base_tot_pll
        X_init1 = mapi[0]
        X_init = mapi[0]
        y = mapi[1]
        print(y)
        y_tok = self.tokenizer.encode(y)[1:-1]
        nl = re.findall(r'[A-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))|[a-z]+|\d+', y)
        lb = ' '.join(nl).lower()
        x = self.tokenizer.tokenize(lb)
        num_sub_tokens_label = len(x)
        X_init = X_init.replace("[MASK]", " ".join([self.tokenizer.mask_token] * num_sub_tokens_label))
        sent_pll = 0.0
        base_sent_pll = 0.0
        for m in range(num_sub_tokens_label):
            print(m)
            tokens = self.tokenizer.encode_plus(X_init, add_special_tokens=False,return_tensors='pt')
            input_id_chunki = tokens['input_ids'][0].split(510)
            input_id_chunks = []
            mask_chunks  = []
            mask_chunki = tokens['attention_mask'][0].split(510)
            for tensor in input_id_chunki:
                input_id_chunks.append(tensor)
            for tensor in mask_chunki:
                mask_chunks.append(tensor)
            xi = torch.full((1,), fill_value=101)
            yi = torch.full((1,), fill_value=1)
            zi = torch.full((1,), fill_value=102)
            for r in range(len(input_id_chunks)):
                input_id_chunks[r] = torch.cat([xi, input_id_chunks[r]],dim = -1)
                input_id_chunks[r] = torch.cat([input_id_chunks[r],zi],dim=-1)
                mask_chunks[r] = torch.cat([yi, mask_chunks[r]],dim=-1)
                mask_chunks[r] = torch.cat([mask_chunks[r],yi],dim=-1)
            di = torch.full((1,), fill_value=0)
            for i in range(len(input_id_chunks)):
                pad_len = 512 - input_id_chunks[i].shape[0]
                if pad_len > 0:
                    for p in range(pad_len):
                        input_id_chunks[i] = torch.cat([input_id_chunks[i],di],dim=-1)
                        mask_chunks[i] = torch.cat([mask_chunks[i],di],dim=-1)
            input_ids = torch.stack(input_id_chunks)
            attention_mask = torch.stack(mask_chunks)
            input_dict = {
                'input_ids': input_ids.long(),
                'attention_mask': attention_mask.int()
            }
            maski = []
            u = 0
            ad = 0
            for l in range(len(input_dict['input_ids'])):
                masked_pos = []
                for i in range(len(input_dict['input_ids'][l])):
                    if input_dict['input_ids'][l][i] == 50264: #103
                        u+=1
                        if i != 0 and input_dict['input_ids'][l][i-1] == 50264:
                            continue
                        masked_pos.append(i)
                        ad+=1
                maski.append(masked_pos)
            print('number of mask tok',u)
            print('number of seq', ad)
            with torch.no_grad():
                output = self.model(**input_dict)
                base_output = base_model(**input_dict)
            last_hidden_state = output[0].squeeze()
            base_last_hidden_state = base_output[0].squeeze()
            l_o_l_sa = []
            base_l_o_l_sa = []
            if len(maski) == 1:
                masked_pos = maski[0]
                for k in masked_pos:
                    l_o_l_sa.append(last_hidden_state[k])
                    base_l_o_l_sa.append(base_last_hidden_state[k])
            else:
                for p in range(len(maski)):
                    masked_pos = maski[p]
                    for k in masked_pos:
                        l_o_l_sa.append(last_hidden_state[p][k])
                        base_l_o_l_sa.append(base_last_hidden_state[p][k])
            sum_state = l_o_l_sa[0]
            base_sum_state = base_l_o_l_sa[0]
            for i in range(len(l_o_l_sa)):
                if i == 0:
                    continue
                sum_state += l_o_l_sa[i]
                base_sum_state += base_l_o_l_sa[i]
            yip = len(l_o_l_sa)
            sum_state /= yip
            base_sum_state /= yip
            probs = F.softmax(sum_state, dim=0)
            base_probs = F.softmax(base_sum_state, dim=0)
            a_lab = y_tok[m]
            prob = probs[a_lab]
            base_prob = base_probs[a_lab]
            log_prob = -1*math.log(prob)
            base_log_prob = -1*math.log(base_prob)
            sent_pll+=log_prob
            base_sent_pll+=base_log_prob
            xl = X_init.split()
            xxl = []
            for p in range(len(xl)):
                if xl[p] == self.tokenizer.mask_token:
                    if p != 0 and xl[p-1] == self.tokenizer.mask_token:
                        xxl.append(xl[p])
                        continue
                    xxl.append(self.tokenizer.convert_ids_to_tokens(y_tok[m]))
                    continue
                xxl.append(xl[p])
            X_init = " ".join(xxl)
        sent_pll/=num_sub_tokens_label
        base_sent_pll/=num_sub_tokens_label
        print("Sent PLL:")
        print(sent_pll)
        print("Base Sent PLL:")
        print(base_sent_pll)
        print("Net % difference:")
        diff = (sent_pll-base_sent_pll)*100/base_sent_pll
        print(diff)
        tot_pll += sent_pll
        base_tot_pll+=base_sent_pll
        print()
        print()
        y = random.choice(variable_names)
        print(y)
        X_init = X_init1
        y_tok = self.tokenizer.encode(y)[1:-1]
        nl = re.findall(r'[A-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))|[a-z]+|\d+', y)
        lb = ' '.join(nl).lower()
        x = self.tokenizer.tokenize(lb)
        num_sub_tokens_label = len(x)
        X_init = X_init.replace("[MASK]", " ".join([self.tokenizer.mask_token] * num_sub_tokens_label))
        sent_pll = 0.0
        base_sent_pll = 0.0
        for m in range(num_sub_tokens_label):
            print(m)
            tokens = self.tokenizer.encode_plus(X_init, add_special_tokens=False,return_tensors='pt')
            input_id_chunki = tokens['input_ids'][0].split(510)
            input_id_chunks = []
            mask_chunks  = []
            mask_chunki = tokens['attention_mask'][0].split(510)
            for tensor in input_id_chunki:
                input_id_chunks.append(tensor)
            for tensor in mask_chunki:
                mask_chunks.append(tensor)
            xi = torch.full((1,), fill_value=101)
            yi = torch.full((1,), fill_value=1)
            zi = torch.full((1,), fill_value=102)
            for r in range(len(input_id_chunks)):
                input_id_chunks[r] = torch.cat([xi, input_id_chunks[r]],dim = -1)
                input_id_chunks[r] = torch.cat([input_id_chunks[r],zi],dim=-1)
                mask_chunks[r] = torch.cat([yi, mask_chunks[r]],dim=-1)
                mask_chunks[r] = torch.cat([mask_chunks[r],yi],dim=-1)
            di = torch.full((1,), fill_value=0)
            for i in range(len(input_id_chunks)):
                pad_len = 512 - input_id_chunks[i].shape[0]
                if pad_len > 0:
                    for p in range(pad_len):
                        input_id_chunks[i] = torch.cat([input_id_chunks[i],di],dim=-1)
                        mask_chunks[i] = torch.cat([mask_chunks[i],di],dim=-1)
            input_ids = torch.stack(input_id_chunks)
            attention_mask = torch.stack(mask_chunks)
            input_dict = {
                'input_ids': input_ids.long(),
                'attention_mask': attention_mask.int()
            }
            maski = []
            u = 0
            ad = 0
            for l in range(len(input_dict['input_ids'])):
                masked_pos = []
                for i in range(len(input_dict['input_ids'][l])):
                    if input_dict['input_ids'][l][i] == 50264: #103
                        u+=1
                        if i != 0 and input_dict['input_ids'][l][i-1] == 50264:
                            continue
                        masked_pos.append(i)
                        ad+=1
                maski.append(masked_pos)
            print('number of mask tok',u)
            print('number of seq', ad)
            with torch.no_grad():
                output = self.model(**input_dict)
                base_output = base_model(**input_dict)
            last_hidden_state = output[0].squeeze()
            base_last_hidden_state = base_output[0].squeeze()
            l_o_l_sa = []
            base_l_o_l_sa = []
            if len(maski) == 1:
                masked_pos = maski[0]
                for k in masked_pos:
                    l_o_l_sa.append(last_hidden_state[k])
                    base_l_o_l_sa.append(base_last_hidden_state[k])
            else:
                for p in range(len(maski)):
                    masked_pos = maski[p]
                    for k in masked_pos:
                        l_o_l_sa.append(last_hidden_state[p][k])
                        base_l_o_l_sa.append(base_last_hidden_state[p][k])
            sum_state = l_o_l_sa[0]
            base_sum_state = base_l_o_l_sa[0]
            for i in range(len(l_o_l_sa)):
                if i == 0:
                    continue
                sum_state += l_o_l_sa[i]
                base_sum_state += base_l_o_l_sa[i]
            yip = len(l_o_l_sa)
            sum_state /= yip
            base_sum_state /= yip
            probs = F.softmax(sum_state, dim=0)
            base_probs = F.softmax(base_sum_state, dim=0)
            a_lab = y_tok[m]
            prob = probs[a_lab]
            base_prob = base_probs[a_lab]
            log_prob = -1*math.log(prob)
            base_log_prob = -1*math.log(base_prob)
            sent_pll+=log_prob
            base_sent_pll+=base_log_prob
            xl = X_init.split()
            xxl = []
            for p in range(len(xl)):
                if xl[p] == self.tokenizer.mask_token:
                    if p != 0 and xl[p-1] == self.tokenizer.mask_token:
                        xxl.append(xl[p])
                        continue
                    xxl.append(self.tokenizer.convert_ids_to_tokens(y_tok[m]))
                    continue
                xxl.append(xl[p])
            X_init = " ".join(xxl)
        sent_pll/=num_sub_tokens_label
        base_sent_pll/=num_sub_tokens_label
        print("Sent PLL:")
        print(sent_pll)
        print("Base Sent PLL:")
        print(base_sent_pll)
        print("Net % difference:")
        diff = (sent_pll-base_sent_pll)*100/base_sent_pll
        print(diff)
        print()
        print("******")
        print()
    


# In[4]:


tokenizer = AutoTokenizer.from_pretrained("microsoft/graphcodebert-base")
model = Step1_model()
model.load_state_dict(torch.load('var_runs/model_98_3'))
base_model = AutoModelForMaskedLM.from_pretrained('microsoft/graphcodebert-base')
model.eval()
base_model.eval()


# In[5]:


myDs=MyDataset('dat.csv')
loader=DataLoader(myDs,batch_size=2,shuffle=True)
loop = tqdm(loader, leave=True)


# In[6]:


tot_pll = 0.0
base_tot_pll = 0.0
variable_names = [
    'x', 'y', 'myVariable', 'dataPoint', 'randomNumber', 'userAge', 'resultValue', 'inputValue', 'tempValue', 'indexCounter', 
    'itemPrice', 'userName', 'testScore', 'acceleration', 'productCount', 'errorMargin', 'piValue', 'sensorReading', 
    'currentTemperature', 'velocityVector', 'variable1', 'variable2', 'valueA', 'valueB', 'counter', 'flag', 'total', 
    'average', 'valueX', 'valueY', 'valueZ', 'price', 'quantity', 'name', 'age', 'score', 'weight', 'height', 'distance', 
    'time', 'radius', 'width', 'length', 'temperature', 'pressure', 'humidity', 'voltage', 'current', 'resistance'
]

for batch in loop:
    inputs = batch
    try:
        for i in range(len(inputs[0])):
            l = []
            l.append(inputs[0][i])
            l.append(inputs[1][i])
            model(l)
    except:
        continue

tot_pll/=len(myDs)
print('Total PLL per sentence: ')
print(tot_pll)
base_tot_pll/=len(myDs)
print('Total Base PLL per sentence: ')
print(base_tot_pll)
print("Net % difference average:")
tot_diff = (tot_pll-base_tot_pll)*100/base_tot_pll
print(tot_diff)
  


# In[ ]: