- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython code generation copy.py
More file actions
Latest commit
528 lines (428 loc) · 21.6 KB
/
Copy pathpython code generation copy.py
File metadata and controls
528 lines (428 loc) · 21.6 KB
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
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
importsubprocess
importos
# by default setting to kaggle environment
DEVICE_IDS= [0, 1]
ROOT_DIR='/kaggle/working/Python-Code-Generation'
if'KAGGLE_KERNEL_RUN_TYPE'inos.environ:
try:
subprocess.run(['bash', f"{ROOT_DIR}/start.sh", ROOT_DIR], check=True)
print("Shell script executed successfully in kaggle environment.")
exceptsubprocess.CalledProcessErrorase:
print("Error running shell script in kaggle environment:", e)
print("Running in Kaggle environment")
else:
DEVICE_IDS= [0, 1, 2, 4]
ROOT_DIR="/home/coder/Anurag/Python-Code-Generation"
try:
subprocess.run(['bash', f"{ROOT_DIR}/start.sh", ROOT_DIR], check=True)
print("Shell script executed successfully in Nvidia DGX A100 environment.")
exceptsubprocess.CalledProcessErrorase:
print("Error running shell script in Nvidia DGX A100 environemnt:", e)
print("Running in Nvidia DGX A100 environment")
# Loading required library
importnumpyasnp
importpandasaspd
importmatplotlib.pyplotasplt
fromsklearn.model_selectionimporttrain_test_split
importjson
fromtqdm.autonotebookimporttqdm
importtorch
fromtorch.utils.dataimportDataset, DataLoader, random_split
fromtorch.optim.lr_schedulerimportStepLR
importtorch.distributedasdist
fromtorch.nn.parallelimportDistributedDataParallel
fromtransformersimportT5Tokenizer, RobertaTokenizer, T5ForConditionalGeneration, AutoModelForCausalLM, AutoTokenizer
importnltk
nltk.download('punkt')
fromnltk.translate.bleu_scoreimportsentence_bleu, SmoothingFunction
fromnltk.translate.meteor_scoreimportmeteor_score
fromrougeimportRouge
fromcodebleuimportcalc_codebleu
# Code Control
MODEL_NAME="t5-base"
MAX_INPUT_TOKENS=512
MAX_OUTPUT_TOKENS=512
BATCH_SIZE=8
EPOCHS=2
DO_SAMPLE=False
TEMPERATURE=None
DEVICE_IDS= [0, 1]
if'KAGGLE_KERNEL_RUN_TYPE'inos.environ:
print("Running in Kaggle environment")
else:
DEVICE_IDS= [0, 1, 2, 4]
print("Not running in Kaggle environment")
tokenizer=T5Tokenizer.from_pretrained(MODEL_NAME)
model=T5ForConditionalGeneration.from_pretrained(MODEL_NAME)
# helper function
defsave_metrics_to_excel(metrics_dict, file_name):
ifos.path.exists(file_name):
# If file exists, load the existing data
df_old=pd.read_excel(file_name)
# Convert new data to DataFrame
df_new=pd.DataFrame.from_dict(metrics_dict)
# Append new data to old data
df=pd.concat([df_old, df_new], ignore_index=True)
else:
# If file doesn't exist, create a new DataFrame
df=pd.DataFrame.from_dict(metrics_dict)
df.to_excel(file_name, index=False)
# Stage1 : Dataset Preprocessing
data_text_length=0
data_code_length=0
data_file_path=f"{ROOT_DIR}/dataset/pythoncode.jsonl"
withopen(data_file_path, 'r') asf:
forlineinf:
# Load each line as a JSON object
data=json.loads(line)
# Extract text and code
text=data['text']
code=data['code']
# Update lengths if necessary
text_length=len(text)
code_length=len(code)
iftext_length>data_text_length:
data_text_length=text_length
ifcode_length>data_code_length:
data_code_length=code_length
# Count the number of lines in the file
withopen(data_file_path, 'r') asf:
data_length=sum(1for_inf)
print("Length of data:", data_length)
print("Maximum length of text:", data_text_length)
print("Maximum length of code:", data_code_length)
classTaskDataset(Dataset):
def__init__(self, file_path, tokenizer, input_name, output_name, data_text_length, data_code_length):
self.tokenizer=tokenizer
self.data_text_length=data_text_length
self.data_code_length=data_code_length
self.input_name=input_name
self.output_name=output_name
self.data= []
withopen(file_path, 'r') asf:
forlineinf:
self.data.append(json.loads(line))
def__len__(self):
returnlen(self.data)
def__getitem__(self, idx):
row=self.data[idx]
#task = row['text']
#code = row['code']
task=row[self.input_name]
code=row[self.output_name]
inputs=self.tokenizer.encode_plus(
task,
max_length=self.data_text_length,
padding='max_length',
truncation=True,
)
outputs=self.tokenizer.encode_plus(
code,
max_length=self.data_code_length,
padding='max_length',
truncation=True,
)
input_ids=torch.tensor(inputs.input_ids)
output_ids=torch.tensor(outputs.input_ids)
returninput_ids, output_ids
# Stage2 : Setting up Mixed Precision Strategy
globaldevice
defset_strategy(model, tpu, gpu):
iftpu:
importtorch_xla.core.xla_modelasxm
device=xm.xla_device()
model.to(device)
print("TPU strategy setup complete.")
elifgpu:
device=torch.device('cuda') iftorch.cuda.is_available() elsetorch.device('cpu')
gpu_count=torch.cuda.device_count()
ifgpu_count>1:
print(f"GPU strategy setup complete with {gpu_count} GPUs!")
model=torch.nn.DataParallel(model, device_ids=DEVICE_IDS)
model.to(device)
#torch.distributed.init_process_group(backend='nccl')
#model = DistributedDataParallel(model, device_ids=[DEVICE_IDS], output_device=DEVICE_IDS)
elifgpu_count==1:
model.to(device)
print(f"GPU strategy setup complete with {gpu_count} GPU!")
else:
print(f"CPU strategy setup complete.")
model.to(device)
else:
print(f"CPU strategy setup complete.")
model.to(device)
returnmodel, device
model, device=set_strategy(model, tpu=False, gpu=True)
model, device
# Stage3: Split of data
dataset=TaskDataset(data_file_path, tokenizer, "text", "code", data_text_length=MAX_INPUT_TOKENS, data_code_length=MAX_OUTPUT_TOKENS)
TRAIN_SIZE=int(0.8*len(dataset))
VAL_SIZE=int(0.1*len(dataset))
TEST_SIZE=len(dataset) -TRAIN_SIZE-VAL_SIZE
train_dataset, val_dataset, test_dataset=random_split(dataset, [TRAIN_SIZE, VAL_SIZE, TEST_SIZE])
print(f"Total length dataset :{len(dataset)}")
print(f'Train dataset: {len(train_dataset)}\nValidation dataset: {len(val_dataset)}\nTest dataset:{len(test_dataset)}')
train_dataloader=DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)
val_dataloader=DataLoader(val_dataset, batch_size=BATCH_SIZE, shuffle=False)
test_dataloader=DataLoader(test_dataset, batch_size=BATCH_SIZE, shuffle=False)
# Stage4: Performance Metrics
defcalculate_metrics(reference, candidate, tokenizer):
# Tokenize the reference and candidate
reference_tokens=reference.split()
candidate_tokens=candidate.split()
#This method uses the p-norm method mentioned in the BLEU SmoothingFunction paper
smoothie=SmoothingFunction().method4
# Calculate BLEU score
bleu_score=sentence_bleu([reference], candidate, smoothing_function=smoothie)
# Calculate Rouge score
rouge=Rouge()
scores= [{ "rouge-1": {"f": 0., "p": 0.,"r": 0.}, "rouge-2": {"f": 0., "p": 0., "r": 0.}, "rouge-l": {"f": 0., "p": 0.0, "r": 0.}}]
try:
iflen(candidate)>0andlen(reference) >0:
scores=rouge.get_scores(candidate, reference)
except:
print('can:', candidate)
print('ref:', reference)
# Calculate METEOR score
meteor=meteor_score([reference_tokens], candidate_tokens)
# Calculate CodeBLEU score
codebleu=calc_codebleu([reference], [candidate], lang="python",tokenizer=tokenizer)
returnbleu_score, scores[0], meteor, codebleu# scores[0] contains Rouge-1, Rouge-2 and Rouge-L
defcalculate_batch_metrics(references, candidates, tokenizer):
batch_bleu_scores= []
batch_rouge_scores= []
batch_meteor_scores= []
batch_codebleu_scores= []
forreference, candidateinzip(references, candidates):
bleu_score, rouge_score, meteor_score, codebleu_score=calculate_metrics(reference, candidate, tokenizer)
batch_bleu_scores.append(bleu_score)
batch_rouge_scores.append(rouge_score)
batch_meteor_scores.append(meteor_score)
batch_codebleu_scores.append(codebleu_score)
returnbatch_bleu_scores, batch_rouge_scores, batch_meteor_scores, batch_codebleu_scores
# Stage5: Model Training
deftrain_model(model, train_dataloader, validation_dataloader, test_dataloader, tokenizer, epochs):
# OPTIMIZER PARAMETER
learning_rate=3e-4
weight_decay=1e-4
adam_epsilon=1e-8
gpu_count=torch.cuda.device_count()
optimizer=torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay, eps=1e-8)
# Add an LR scheduler and a system to save the best model
scheduler=StepLR(optimizer, step_size=2, gamma=0.1)
best_val_loss=float('inf')
globalmodel_save_path
# METRICS SAVING
metrics_dict= {
'Epoch': [],
'Training Loss': [],
'Validation Loss': [],
'Training BLEU': [],
'Validation BLEU': [],
'Training METEOR': [],
'Validation METEOR': [],
'Training CodeBLEU': [],
'Validation CodeBLEU': [],
'Training ROUGE-1-f': [],
'Validation ROUGE-1-f': [],
'Training ROUGE-1-p': [],
'Validation ROUGE-1-p': [],
'Training ROUGE-1-r': [],
'Validation ROUGE-1-r': [],
'Training ROUGE-2-f': [],
'Validation ROUGE-2-f': [],
'Training ROUGE-2-p': [],
'Validation ROUGE-2-p': [],
'Training ROUGE-2-r': [],
'Validation ROUGE-2-r': [],
'Training ROUGE-L-f': [],
'Validation ROUGE-L-f': [],
'Training ROUGE-L-p': [],
'Validation ROUGE-L-p': [],
'Training ROUGE-L-r': [],
'Validation ROUGE-L-r': [],
}
val_loss=0
model_save_path=f"{ROOT_DIR}/output/{MODEL_NAME}best_model_{epochs}"
loss_history= []
print("Learning Rate Scheduled:", scheduler.get_last_lr())
forepochinrange(epochs):
total_loss=0
model.train()
total_train_bleu_score=0
total_train_meteor_score=0
total_train_codebleu_score=0
total_train_codebleu_score_dict= {'codebleu' : 0., 'ngram_match_score': 0.,'weighted_ngram_match_score': 0., 'syntax_match_score': 0.0, 'dataflow_match_score': 0.0}
total_train_rouge_scores= {'rouge-1': {'f': 0, 'p': 0, 'r': 0}, 'rouge-2': {'f': 0, 'p': 0, 'r': 0}, 'rouge-l': {'f': 0, 'p': 0, 'r': 0}}
forbatchintqdm(train_dataloader):
optimizer.zero_grad()
input_ids, output_ids=batch
input_ids=input_ids.to(device)
output_ids=output_ids.to(device)
outputs=model(input_ids=input_ids, labels=output_ids)
loss=outputs.loss
loss=loss.mean().view(1)
loss.backward()
optimizer.step()
scheduler.step()
total_loss+=loss.item()
ifgpu_count>1:
# Generate sequences for the entire batch
generated=model.module.generate(input_ids, max_length=MAX_OUTPUT_TOKENS, temperature=TEMPERATURE, do_sample=DO_SAMPLE)
else:
generated=model.generate(input_ids, max_length=MAX_OUTPUT_TOKENS, temperature=TEMPERATURE, do_sample=DO_SAMPLE)
# Decode all the generated and reference sequences
candidates=tokenizer.batch_decode(generated, skip_special_tokens=True)
references=tokenizer.batch_decode(output_ids, skip_special_tokens=True)
# Calculate metrics for the entire batch
bleu_scores, rouge_scores, meteors, codebleu_scores=calculate_batch_metrics(references, candidates, tokenizer)
# Calculate average scores for the batch and accumulate
total_train_bleu_score+=np.mean(bleu_scores)
total_train_meteor_score+=np.mean(meteors)
total_train_codebleu_score+=np.mean([score['codebleu'] forscoreincodebleu_scores])
forcodebleu_scoreincodebleu_scores:
forkeyincodebleu_score:
total_train_codebleu_score_dict[key] +=codebleu_score[key]
forrouge_scoreinrouge_scores:
forkeyinrouge_score:
forsub_keyinrouge_score[key]:
total_train_rouge_scores[key][sub_key] +=rouge_score[key][sub_key]
# Normalization of the total scores
forkeyintotal_train_rouge_scores:
forsub_keyintotal_train_rouge_scores[key]:
total_train_rouge_scores[key][sub_key] /=len(validation_dataloader)
forkeyintotal_train_codebleu_score_dict:
total_train_codebleu_score_dict[key] /=len(validation_dataloader)
training_bleu=total_train_bleu_score/len(train_dataloader)
training_rouge= {key: {sub_key: score/len(train_dataloader) forsub_key, scoreinvalue.items()} forkey, valueintotal_train_rouge_scores.items()}
training_meteor=total_train_meteor_score/len(train_dataloader)
training_codebleu= { key : score/len(train_dataloader) forkey, scoreintotal_train_codebleu_score_dict.items()}
print('Training BLEU:', training_bleu)
print('Training ROUGE:', training_rouge)
print('Training METEOR:', training_meteor)
print('Training CodeBLEU:', training_codebleu)
val_loss=0
model.eval()
total_bleu_score=0
total_meteor_score=0
total_codebleu_score=0
total_codebleu_score_dict= {'codebleu' : 0., 'ngram_match_score': 0.,'weighted_ngram_match_score': 0., 'syntax_match_score': 0.0, 'dataflow_match_score': 0.0}
total_rouge_scores= {'rouge-1': {'f': 0, 'p': 0, 'r': 0}, 'rouge-2': {'f': 0, 'p': 0, 'r': 0}, 'rouge-l': {'f': 0, 'p': 0, 'r': 0}}
withtorch.no_grad():
forbatchintqdm(validation_dataloader):
input_ids, output_ids=batch
input_ids=input_ids.to(device)
output_ids=output_ids.to(device)
# Generate sequences for the entire batch
ifgpu_count>1:
generated=model.module.generate(input_ids, max_length=200, temperature=TEMPERATURE, do_sample=DO_SAMPLE)
else:
generated=model.generate(input_ids, max_length=200, temperature=TEMPERATURE, do_sample=DO_SAMPLE)
# Decode all the generated and reference sequences
candidates=tokenizer.batch_decode(generated, skip_special_tokens=True)
references=tokenizer.batch_decode(output_ids, skip_special_tokens=True)
# Calculate metrics for the entire batch
bleu_scores, rouge_scores, meteors, codebleu_scores=calculate_batch_metrics(references, candidates, tokenizer)
# Calculate average scores for the batch and accumulate
total_bleu_score+=np.mean(bleu_scores)
total_meteor_score+=np.mean(meteors)
total_codebleu_score+=np.mean([score['codebleu'] forscoreincodebleu_scores])
forcodebleu_scoreincodebleu_scores:
forkeyincodebleu_score:
total_codebleu_score_dict[key] +=codebleu_score[key]
forrouge_scoreinrouge_scores:
forkeyinrouge_score:
forsub_keyinrouge_score[key]:
total_rouge_scores[key][sub_key] +=rouge_score[key][sub_key]
# Normalization of the total scores
forkeyintotal_rouge_scores:
forsub_keyintotal_rouge_scores[key]:
total_rouge_scores[key][sub_key] /=len(validation_dataloader)
forkeyintotal_codebleu_score_dict:
total_codebleu_score_dict[key] /=len(validation_dataloader)
# Save the best model
ifval_loss<best_val_loss:
best_val_loss=val_loss
# Save the model
ifgpu_count>1:
model.module.save_pretrained(model_save_path)
else:
model.save_pretrained(model_save_path)
# Store loss history for plotting
loss_history.append((total_loss/len(train_dataloader), val_loss/len(val_dataloader)))
validation_bleu=total_bleu_score/len(validation_dataloader)
validation_rouge= {key: {sub_key: score/len(validation_dataloader) forsub_key, scoreinvalue.items()} forkey, valueintotal_rouge_scores.items()}
validation_meteor=total_meteor_score/len(validation_dataloader)
validation_codebleu= { key : score/len(validation_dataloader) forkey, scoreintotal_codebleu_score_dict.items()}
print(f'Epoch: {epoch}, Training Loss: {total_loss/len(train_dataloader)}, Validation Loss: {val_loss/len(val_dataloader)}')
print('Validation BLEU:', validation_bleu)
print('Validation ROUGE:', validation_rouge)
print('Validation METEOR:', validation_meteor)
print('Validation CodeBLEU:', validation_codebleu)
metrics_dict['Epoch'].append(epoch)
metrics_dict['Training Loss'].append(total_loss/len(train_dataloader))
metrics_dict['Validation Loss'].append(val_loss/len(val_dataloader))
metrics_dict['Training BLEU'].append(training_bleu)
metrics_dict['Validation BLEU'].append(validation_bleu)
metrics_dict['Training METEOR'].append(training_meteor)
metrics_dict['Validation METEOR'].append(validation_meteor)
metrics_dict['Training CodeBLEU'].append(training_codebleu['codebleu'])
metrics_dict['Validation CodeBLEU'].append(validation_codebleu['codebleu'])
metrics_dict['Training ROUGE-1-f'].append(training_rouge['rouge-1']['f'])
metrics_dict['Validation ROUGE-1-f'].append(validation_rouge['rouge-1']['f'])
metrics_dict['Training ROUGE-1-p'].append(training_rouge['rouge-1']['p'])
metrics_dict['Validation ROUGE-1-p'].append(validation_rouge['rouge-1']['p'])
metrics_dict['Training ROUGE-1-r'].append(training_rouge['rouge-1']['r'])
metrics_dict['Validation ROUGE-1-r'].append(validation_rouge['rouge-1']['r'])
metrics_dict['Training ROUGE-2-f'].append(training_rouge['rouge-2']['f'])
metrics_dict['Validation ROUGE-2-f'].append(total_rouge_scores['rouge-2']['f'])
metrics_dict['Training ROUGE-2-p'].append(training_rouge['rouge-2']['p'])
metrics_dict['Validation ROUGE-2-p'].append(total_rouge_scores['rouge-2']['p'])
metrics_dict['Training ROUGE-2-r'].append(training_rouge['rouge-2']['r'])
metrics_dict['Validation ROUGE-2-r'].append(total_rouge_scores['rouge-2']['r'])
metrics_dict['Training ROUGE-L-f'].append(training_rouge['rouge-l']['f'])
metrics_dict['Validation ROUGE-L-f'].append(validation_rouge['rouge-l']['f'])
metrics_dict['Training ROUGE-L-p'].append(training_rouge['rouge-l']['p'])
metrics_dict['Validation ROUGE-L-p'].append(validation_rouge['rouge-l']['p'])
metrics_dict['Training ROUGE-L-r'].append(training_rouge['rouge-l']['r'])
metrics_dict['Validation ROUGE-L-r'].append(validation_rouge['rouge-l']['r'])
save_metrics_to_excel(metrics_dict, f"{ROOT_DIR}/output/train_val_metrics.xlsx")
returnloss_history
model_history=train_model(model, train_dataloader, val_dataloader, test_dataloader, tokenizer, EPOCHS)
print(f"Best Model: {model_save_path}")
print(pd.read_excel(f"{ROOT_DIR}/output/train_val_metrics.xlsx"))
defplot_training_val_loss(loss_history):
epochs=range(1, len(loss_history) +1)
plt.plot(epochs, [loss[0] forlossinloss_history], 'g', label='Training loss')
plt.plot(epochs, [loss[1] forlossinloss_history], 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.savefig(f"{ROOT_DIR}/output/train_val_loss.jpeg")
plot_training_val_loss(model_history)
# Stage6: Model Inference
model=T5ForConditionalGeneration.from_pretrained(model_save_path).to(device)
defgenerate_code(task_description):
# Encode the task description
inputs=tokenizer.encode_plus(
task_description,
max_length=MAX_INPUT_TOKENS,
padding='max_length',
truncation=True,
)
input_ids=torch.tensor(inputs.input_ids)
# Move the inputs to the GPU
input_ids=input_ids.to(device)
# Add a batch dimension to the tensor
input_ids=input_ids.unsqueeze(0)
# Generate the code
withtorch.no_grad():
# performing beam search with 5
outputs=model.generate(input_ids, do_sample=DO_SAMPLE, max_length=MAX_OUTPUT_TOKENS, top_p=0.95, top_k=1, repetition_penalty=2., num_return_sequences=1)
# Decode the generated IDs to get the generated text
generated_code=tokenizer.decode(outputs[0], skip_special_tokens=True)
returngenerated_code
# Test the function with a task description
task_description="Write a python function to remove first and last occurrence of a given character from the string."
print(generate_code(task_description))