add code refinement
Browse files- Code-Code/code-refinement/code/bleu.py +134 -0
- Code-Code/code-refinement/code/eval.sh +17 -0
- Code-Code/code-refinement/code/evaluate.sh +3 -0
- Code-Code/code-refinement/code/evaluator.py +35 -0
- Code-Code/code-refinement/code/model.py +223 -0
- Code-Code/code-refinement/code/run.py +575 -0
- Code-Code/code-refinement/code/train.sh +22 -0
- Code-Code/code-refinement/dataset.zip +3 -0
- Code-Code/code-refinement/model/small/epoch_1/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_10/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_11/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_12/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_13/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_14/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_15/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_16/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_17/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_18/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_19/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_2/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_20/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_21/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_22/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_23/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_24/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_25/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_26/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_27/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_28/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_29/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_3/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_30/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_31/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_32/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_33/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_34/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_4/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_5/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_6/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_7/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_8/subject_model.pth +3 -0
- Code-Code/code-refinement/model/small/epoch_9/subject_model.pth +3 -0
Code-Code/code-refinement/code/bleu.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017 Google Inc. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
|
| 16 |
+
"""Python implementation of BLEU and smooth-BLEU.
|
| 17 |
+
|
| 18 |
+
This module provides a Python implementation of BLEU and smooth-BLEU.
|
| 19 |
+
Smooth BLEU is computed following the method outlined in the paper:
|
| 20 |
+
Chin-Yew Lin, Franz Josef Och. ORANGE: a method for evaluating automatic
|
| 21 |
+
evaluation metrics for machine translation. COLING 2004.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
import collections
|
| 25 |
+
import math
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _get_ngrams(segment, max_order):
|
| 29 |
+
"""Extracts all n-grams upto a given maximum order from an input segment.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
segment: text segment from which n-grams will be extracted.
|
| 33 |
+
max_order: maximum length in tokens of the n-grams returned by this
|
| 34 |
+
methods.
|
| 35 |
+
|
| 36 |
+
Returns:
|
| 37 |
+
The Counter containing all n-grams upto max_order in segment
|
| 38 |
+
with a count of how many times each n-gram occurred.
|
| 39 |
+
"""
|
| 40 |
+
ngram_counts = collections.Counter()
|
| 41 |
+
for order in range(1, max_order + 1):
|
| 42 |
+
for i in range(0, len(segment) - order + 1):
|
| 43 |
+
ngram = tuple(segment[i:i+order])
|
| 44 |
+
ngram_counts[ngram] += 1
|
| 45 |
+
return ngram_counts
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def compute_bleu(reference_corpus, translation_corpus, max_order=4,
|
| 49 |
+
smooth=False):
|
| 50 |
+
"""Computes BLEU score of translated segments against one or more references.
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
reference_corpus: list of lists of references for each translation. Each
|
| 54 |
+
reference should be tokenized into a list of tokens.
|
| 55 |
+
translation_corpus: list of translations to score. Each translation
|
| 56 |
+
should be tokenized into a list of tokens.
|
| 57 |
+
max_order: Maximum n-gram order to use when computing BLEU score.
|
| 58 |
+
smooth: Whether or not to apply Lin et al. 2004 smoothing.
|
| 59 |
+
|
| 60 |
+
Returns:
|
| 61 |
+
3-Tuple with the BLEU score, n-gram precisions, geometric mean of n-gram
|
| 62 |
+
precisions and brevity penalty.
|
| 63 |
+
"""
|
| 64 |
+
matches_by_order = [0] * max_order
|
| 65 |
+
possible_matches_by_order = [0] * max_order
|
| 66 |
+
reference_length = 0
|
| 67 |
+
translation_length = 0
|
| 68 |
+
for (references, translation) in zip(reference_corpus,
|
| 69 |
+
translation_corpus):
|
| 70 |
+
reference_length += min(len(r) for r in references)
|
| 71 |
+
translation_length += len(translation)
|
| 72 |
+
|
| 73 |
+
merged_ref_ngram_counts = collections.Counter()
|
| 74 |
+
for reference in references:
|
| 75 |
+
merged_ref_ngram_counts |= _get_ngrams(reference, max_order)
|
| 76 |
+
translation_ngram_counts = _get_ngrams(translation, max_order)
|
| 77 |
+
overlap = translation_ngram_counts & merged_ref_ngram_counts
|
| 78 |
+
for ngram in overlap:
|
| 79 |
+
matches_by_order[len(ngram)-1] += overlap[ngram]
|
| 80 |
+
for order in range(1, max_order+1):
|
| 81 |
+
possible_matches = len(translation) - order + 1
|
| 82 |
+
if possible_matches > 0:
|
| 83 |
+
possible_matches_by_order[order-1] += possible_matches
|
| 84 |
+
|
| 85 |
+
precisions = [0] * max_order
|
| 86 |
+
for i in range(0, max_order):
|
| 87 |
+
if smooth:
|
| 88 |
+
precisions[i] = ((matches_by_order[i] + 1.) /
|
| 89 |
+
(possible_matches_by_order[i] + 1.))
|
| 90 |
+
else:
|
| 91 |
+
if possible_matches_by_order[i] > 0:
|
| 92 |
+
precisions[i] = (float(matches_by_order[i]) /
|
| 93 |
+
possible_matches_by_order[i])
|
| 94 |
+
else:
|
| 95 |
+
precisions[i] = 0.0
|
| 96 |
+
|
| 97 |
+
if min(precisions) > 0:
|
| 98 |
+
p_log_sum = sum((1. / max_order) * math.log(p) for p in precisions)
|
| 99 |
+
geo_mean = math.exp(p_log_sum)
|
| 100 |
+
else:
|
| 101 |
+
geo_mean = 0
|
| 102 |
+
|
| 103 |
+
ratio = float(translation_length) / reference_length
|
| 104 |
+
|
| 105 |
+
if ratio > 1.0:
|
| 106 |
+
bp = 1.
|
| 107 |
+
else:
|
| 108 |
+
bp = math.exp(1 - 1. / ratio)
|
| 109 |
+
|
| 110 |
+
bleu = geo_mean * bp
|
| 111 |
+
|
| 112 |
+
return (bleu, precisions, bp, ratio, translation_length, reference_length)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _bleu(ref_file, trans_file, subword_option=None):
|
| 116 |
+
max_order = 4
|
| 117 |
+
smooth = True
|
| 118 |
+
ref_files = [ref_file]
|
| 119 |
+
reference_text = []
|
| 120 |
+
for reference_filename in ref_files:
|
| 121 |
+
with open(reference_filename) as fh:
|
| 122 |
+
reference_text.append(fh.readlines())
|
| 123 |
+
per_segment_references = []
|
| 124 |
+
for references in zip(*reference_text):
|
| 125 |
+
reference_list = []
|
| 126 |
+
for reference in references:
|
| 127 |
+
reference_list.append(reference.strip().split())
|
| 128 |
+
per_segment_references.append(reference_list)
|
| 129 |
+
translations = []
|
| 130 |
+
with open(trans_file) as fh:
|
| 131 |
+
for line in fh:
|
| 132 |
+
translations.append(line.strip().split())
|
| 133 |
+
bleu_score, _, _, _, _, _ = compute_bleu(per_segment_references, translations, max_order, smooth)
|
| 134 |
+
return round(100 * bleu_score,2)
|
Code-Code/code-refinement/code/eval.sh
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pretrained_model=microsoft/codebert-base
|
| 2 |
+
output_dir=../model
|
| 3 |
+
data_size=small
|
| 4 |
+
|
| 5 |
+
CUDA_VISIBLE_DEVICES=1 python run.py \
|
| 6 |
+
--do_test \
|
| 7 |
+
--model_type roberta \
|
| 8 |
+
--model_name_or_path $pretrained_model \
|
| 9 |
+
--config_name roberta-base \
|
| 10 |
+
--tokenizer_name roberta-base \
|
| 11 |
+
--load_model_path $output_dir/epoch_34/subject_model.pth \
|
| 12 |
+
--dev_filename ../data/$data_size/valid.buggy-fixed.buggy,../data/$data_size/valid.buggy-fixed.fixed \
|
| 13 |
+
--output_dir $output_dir \
|
| 14 |
+
--max_source_length 256 \
|
| 15 |
+
--max_target_length 256 \
|
| 16 |
+
--beam_size 5 \
|
| 17 |
+
--eval_batch_size 16
|
Code-Code/code-refinement/code/evaluate.sh
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
python evaluator.py \
|
| 2 |
+
-ref ../data/small/valid.buggy-fixed.fixed \
|
| 3 |
+
-pre ../model/test_0.output
|
Code-Code/code-refinement/code/evaluator.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT license.
|
| 3 |
+
import logging
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
from bleu import _bleu
|
| 7 |
+
|
| 8 |
+
def main():
|
| 9 |
+
import argparse
|
| 10 |
+
parser = argparse.ArgumentParser(description='Evaluate leaderboard predictions for BigCloneBench dataset.')
|
| 11 |
+
parser.add_argument('--references', '-ref',help="filename of the labels, in txt format.")
|
| 12 |
+
parser.add_argument('--predictions', '-pre',help="filename of the leaderboard predictions, in txt format.")
|
| 13 |
+
|
| 14 |
+
args = parser.parse_args()
|
| 15 |
+
|
| 16 |
+
refs = [x.strip() for x in open(args.references, 'r', encoding='utf-8').readlines()]
|
| 17 |
+
pres = [x.strip() for x in open(args.predictions, 'r', encoding='utf-8').readlines()]
|
| 18 |
+
|
| 19 |
+
assert len(refs) == len(pres)
|
| 20 |
+
|
| 21 |
+
length = len(refs)
|
| 22 |
+
count = 0
|
| 23 |
+
for i in range(length):
|
| 24 |
+
r = refs[i]
|
| 25 |
+
p = pres[i]
|
| 26 |
+
if r == p:
|
| 27 |
+
count += 1
|
| 28 |
+
acc = round(count/length*100, 2)
|
| 29 |
+
|
| 30 |
+
bleu_score = round(_bleu(args.references, args.predictions),2)
|
| 31 |
+
|
| 32 |
+
print('BLEU:', bleu_score, '; Acc:', acc)
|
| 33 |
+
|
| 34 |
+
if __name__ == '__main__':
|
| 35 |
+
main()
|
Code-Code/code-refinement/code/model.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT license.
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch
|
| 7 |
+
from torch.autograd import Variable
|
| 8 |
+
import copy
|
| 9 |
+
class Seq2Seq(nn.Module):
|
| 10 |
+
"""
|
| 11 |
+
Build Seqence-to-Sequence.
|
| 12 |
+
|
| 13 |
+
Parameters:
|
| 14 |
+
|
| 15 |
+
* `encoder`- encoder of seq2seq model. e.g. roberta
|
| 16 |
+
* `decoder`- decoder of seq2seq model. e.g. transformer
|
| 17 |
+
* `config`- configuration of encoder model.
|
| 18 |
+
* `beam_size`- beam size for beam search.
|
| 19 |
+
* `max_length`- max length of target for beam search.
|
| 20 |
+
* `sos_id`- start of symbol ids in target for beam search.
|
| 21 |
+
* `eos_id`- end of symbol ids in target for beam search.
|
| 22 |
+
"""
|
| 23 |
+
def __init__(self, encoder,decoder,config,beam_size=None,max_length=None,sos_id=None,eos_id=None):
|
| 24 |
+
super(Seq2Seq, self).__init__()
|
| 25 |
+
self.encoder = encoder
|
| 26 |
+
self.decoder=decoder
|
| 27 |
+
self.config=config
|
| 28 |
+
self.register_buffer("bias", torch.tril(torch.ones(2048, 2048)))
|
| 29 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 30 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 31 |
+
self.lsm = nn.LogSoftmax(dim=-1)
|
| 32 |
+
self.tie_weights()
|
| 33 |
+
|
| 34 |
+
self.beam_size=beam_size
|
| 35 |
+
self.max_length=max_length
|
| 36 |
+
self.sos_id=sos_id
|
| 37 |
+
self.eos_id=eos_id
|
| 38 |
+
|
| 39 |
+
def _tie_or_clone_weights(self, first_module, second_module):
|
| 40 |
+
""" Tie or clone module weights depending of weither we are using TorchScript or not
|
| 41 |
+
"""
|
| 42 |
+
if self.config.torchscript:
|
| 43 |
+
first_module.weight = nn.Parameter(second_module.weight.clone())
|
| 44 |
+
else:
|
| 45 |
+
first_module.weight = second_module.weight
|
| 46 |
+
|
| 47 |
+
def tie_weights(self):
|
| 48 |
+
""" Make sure we are sharing the input and output embeddings.
|
| 49 |
+
Export to TorchScript can't handle parameter sharing so we are cloning them instead.
|
| 50 |
+
"""
|
| 51 |
+
self._tie_or_clone_weights(self.lm_head,
|
| 52 |
+
self.encoder.embeddings.word_embeddings)
|
| 53 |
+
|
| 54 |
+
def forward(self, source_ids=None,source_mask=None,target_ids=None,target_mask=None,args=None, return_vec=None):
|
| 55 |
+
outputs = self.encoder(source_ids, attention_mask=source_mask)
|
| 56 |
+
if return_vec:
|
| 57 |
+
return outputs.pooler_output
|
| 58 |
+
|
| 59 |
+
encoder_output = outputs[0].permute([1,0,2]).contiguous()
|
| 60 |
+
|
| 61 |
+
if target_ids is not None:
|
| 62 |
+
attn_mask=-1e4 *(1-self.bias[:target_ids.shape[1],:target_ids.shape[1]])
|
| 63 |
+
tgt_embeddings = self.encoder.embeddings(target_ids).permute([1,0,2]).contiguous()
|
| 64 |
+
out = self.decoder(tgt_embeddings,encoder_output,tgt_mask=attn_mask,memory_key_padding_mask=(1-source_mask).bool())
|
| 65 |
+
hidden_states = torch.tanh(self.dense(out)).permute([1,0,2]).contiguous()
|
| 66 |
+
lm_logits = self.lm_head(hidden_states)
|
| 67 |
+
# Shift so that tokens < n predict n
|
| 68 |
+
active_loss = target_mask[..., 1:].ne(0).view(-1) == 1
|
| 69 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
| 70 |
+
shift_labels = target_ids[..., 1:].contiguous()
|
| 71 |
+
# Flatten the tokens
|
| 72 |
+
loss_fct = nn.CrossEntropyLoss(ignore_index=-1)
|
| 73 |
+
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1))[active_loss],
|
| 74 |
+
shift_labels.view(-1)[active_loss])
|
| 75 |
+
|
| 76 |
+
outputs = loss,loss*active_loss.sum(),active_loss.sum()
|
| 77 |
+
return outputs
|
| 78 |
+
else:
|
| 79 |
+
#Predict
|
| 80 |
+
preds=[]
|
| 81 |
+
zero=torch.cuda.LongTensor(1).fill_(0)
|
| 82 |
+
for i in range(source_ids.shape[0]):
|
| 83 |
+
context=encoder_output[:,i:i+1]
|
| 84 |
+
context_mask=source_mask[i:i+1,:]
|
| 85 |
+
beam = Beam(self.beam_size,self.sos_id,self.eos_id)
|
| 86 |
+
input_ids=beam.getCurrentState()
|
| 87 |
+
context=context.repeat(1, self.beam_size,1)
|
| 88 |
+
context_mask=context_mask.repeat(self.beam_size,1)
|
| 89 |
+
for _ in range(self.max_length):
|
| 90 |
+
if beam.done():
|
| 91 |
+
break
|
| 92 |
+
attn_mask=-1e4 *(1-self.bias[:input_ids.shape[1],:input_ids.shape[1]])
|
| 93 |
+
tgt_embeddings = self.encoder.embeddings(input_ids).permute([1,0,2]).contiguous()
|
| 94 |
+
out = self.decoder(tgt_embeddings,context,tgt_mask=attn_mask,memory_key_padding_mask=(1-context_mask).bool())
|
| 95 |
+
out = torch.tanh(self.dense(out))
|
| 96 |
+
hidden_states=out.permute([1,0,2]).contiguous()[:,-1,:]
|
| 97 |
+
out = self.lsm(self.lm_head(hidden_states)).data
|
| 98 |
+
beam.advance(out)
|
| 99 |
+
input_ids.data.copy_(input_ids.data.index_select(0, beam.getCurrentOrigin()))
|
| 100 |
+
input_ids=torch.cat((input_ids,beam.getCurrentState()),-1)
|
| 101 |
+
hyp= beam.getHyp(beam.getFinal())
|
| 102 |
+
pred=beam.buildTargetTokens(hyp)[:self.beam_size]
|
| 103 |
+
pred=[torch.cat([x.view(-1) for x in p]+[zero]*(self.max_length-len(p))).view(1,-1) for p in pred]
|
| 104 |
+
preds.append(torch.cat(pred,0).unsqueeze(0))
|
| 105 |
+
|
| 106 |
+
preds=torch.cat(preds,0)
|
| 107 |
+
return preds
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class Beam(object):
|
| 112 |
+
def __init__(self, size,sos,eos):
|
| 113 |
+
self.size = size
|
| 114 |
+
self.tt = torch.cuda
|
| 115 |
+
# The score for each translation on the beam.
|
| 116 |
+
self.scores = self.tt.FloatTensor(size).zero_()
|
| 117 |
+
# The backpointers at each time-step.
|
| 118 |
+
self.prevKs = []
|
| 119 |
+
# The outputs at each time-step.
|
| 120 |
+
self.nextYs = [self.tt.LongTensor(size)
|
| 121 |
+
.fill_(0)]
|
| 122 |
+
self.nextYs[0][0] = sos
|
| 123 |
+
# Has EOS topped the beam yet.
|
| 124 |
+
self._eos = eos
|
| 125 |
+
self.eosTop = False
|
| 126 |
+
# Time and k pair for finished.
|
| 127 |
+
self.finished = []
|
| 128 |
+
|
| 129 |
+
def getCurrentState(self):
|
| 130 |
+
"Get the outputs for the current timestep."
|
| 131 |
+
batch = self.tt.LongTensor(self.nextYs[-1]).view(-1, 1)
|
| 132 |
+
return batch
|
| 133 |
+
|
| 134 |
+
def getCurrentOrigin(self):
|
| 135 |
+
"Get the backpointers for the current timestep."
|
| 136 |
+
return self.prevKs[-1]
|
| 137 |
+
|
| 138 |
+
def advance(self, wordLk):
|
| 139 |
+
"""
|
| 140 |
+
Given prob over words for every last beam `wordLk` and attention
|
| 141 |
+
`attnOut`: Compute and update the beam search.
|
| 142 |
+
|
| 143 |
+
Parameters:
|
| 144 |
+
|
| 145 |
+
* `wordLk`- probs of advancing from the last step (K x words)
|
| 146 |
+
* `attnOut`- attention at the last step
|
| 147 |
+
|
| 148 |
+
Returns: True if beam search is complete.
|
| 149 |
+
"""
|
| 150 |
+
numWords = wordLk.size(1)
|
| 151 |
+
|
| 152 |
+
# Sum the previous scores.
|
| 153 |
+
if len(self.prevKs) > 0:
|
| 154 |
+
beamLk = wordLk + self.scores.unsqueeze(1).expand_as(wordLk)
|
| 155 |
+
|
| 156 |
+
# Don't let EOS have children.
|
| 157 |
+
for i in range(self.nextYs[-1].size(0)):
|
| 158 |
+
if self.nextYs[-1][i] == self._eos:
|
| 159 |
+
beamLk[i] = -1e20
|
| 160 |
+
else:
|
| 161 |
+
beamLk = wordLk[0]
|
| 162 |
+
flatBeamLk = beamLk.view(-1)
|
| 163 |
+
bestScores, bestScoresId = flatBeamLk.topk(self.size, 0, True, True)
|
| 164 |
+
|
| 165 |
+
self.scores = bestScores
|
| 166 |
+
|
| 167 |
+
# bestScoresId is flattened beam x word array, so calculate which
|
| 168 |
+
# word and beam each score came from
|
| 169 |
+
prevK = bestScoresId // numWords
|
| 170 |
+
self.prevKs.append(prevK)
|
| 171 |
+
self.nextYs.append((bestScoresId - prevK * numWords))
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
for i in range(self.nextYs[-1].size(0)):
|
| 175 |
+
if self.nextYs[-1][i] == self._eos:
|
| 176 |
+
s = self.scores[i]
|
| 177 |
+
self.finished.append((s, len(self.nextYs) - 1, i))
|
| 178 |
+
|
| 179 |
+
# End condition is when top-of-beam is EOS and no global score.
|
| 180 |
+
if self.nextYs[-1][0] == self._eos:
|
| 181 |
+
self.eosTop = True
|
| 182 |
+
|
| 183 |
+
def done(self):
|
| 184 |
+
return self.eosTop and len(self.finished) >=self.size
|
| 185 |
+
|
| 186 |
+
def getFinal(self):
|
| 187 |
+
if len(self.finished) == 0:
|
| 188 |
+
self.finished.append((self.scores[0], len(self.nextYs) - 1, 0))
|
| 189 |
+
self.finished.sort(key=lambda a: -a[0])
|
| 190 |
+
if len(self.finished) != self.size:
|
| 191 |
+
unfinished=[]
|
| 192 |
+
for i in range(self.nextYs[-1].size(0)):
|
| 193 |
+
if self.nextYs[-1][i] != self._eos:
|
| 194 |
+
s = self.scores[i]
|
| 195 |
+
unfinished.append((s, len(self.nextYs) - 1, i))
|
| 196 |
+
unfinished.sort(key=lambda a: -a[0])
|
| 197 |
+
self.finished+=unfinished[:self.size-len(self.finished)]
|
| 198 |
+
return self.finished[:self.size]
|
| 199 |
+
|
| 200 |
+
def getHyp(self, beam_res):
|
| 201 |
+
"""
|
| 202 |
+
Walk back to construct the full hypothesis.
|
| 203 |
+
"""
|
| 204 |
+
hyps=[]
|
| 205 |
+
for _,timestep, k in beam_res:
|
| 206 |
+
hyp = []
|
| 207 |
+
for j in range(len(self.prevKs[:timestep]) - 1, -1, -1):
|
| 208 |
+
hyp.append(self.nextYs[j+1][k])
|
| 209 |
+
k = self.prevKs[j][k]
|
| 210 |
+
hyps.append(hyp[::-1])
|
| 211 |
+
return hyps
|
| 212 |
+
|
| 213 |
+
def buildTargetTokens(self, preds):
|
| 214 |
+
sentence=[]
|
| 215 |
+
for pred in preds:
|
| 216 |
+
tokens = []
|
| 217 |
+
for tok in pred:
|
| 218 |
+
if tok==self._eos:
|
| 219 |
+
break
|
| 220 |
+
tokens.append(tok)
|
| 221 |
+
sentence.append(tokens)
|
| 222 |
+
return sentence
|
| 223 |
+
|
Code-Code/code-refinement/code/run.py
ADDED
|
@@ -0,0 +1,575 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""
|
| 17 |
+
Fine-tuning the library models for language modeling on a text file (GPT, GPT-2, BERT, RoBERTa).
|
| 18 |
+
GPT and GPT-2 are fine-tuned using a causal language modeling (CLM) loss while BERT and RoBERTa are fine-tuned
|
| 19 |
+
using a masked language modeling (MLM) loss.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from __future__ import absolute_import
|
| 23 |
+
import os
|
| 24 |
+
import sys
|
| 25 |
+
import pickle
|
| 26 |
+
import torch
|
| 27 |
+
import json
|
| 28 |
+
import random
|
| 29 |
+
import logging
|
| 30 |
+
import argparse
|
| 31 |
+
import numpy as np
|
| 32 |
+
from io import open
|
| 33 |
+
from itertools import cycle
|
| 34 |
+
import torch.nn as nn
|
| 35 |
+
from model import Seq2Seq
|
| 36 |
+
from tqdm import tqdm, trange
|
| 37 |
+
from bleu import _bleu
|
| 38 |
+
from torch.utils.data import DataLoader, Dataset, SequentialSampler, RandomSampler,TensorDataset
|
| 39 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 40 |
+
from transformers import (WEIGHTS_NAME, AdamW, get_linear_schedule_with_warmup,
|
| 41 |
+
RobertaConfig, RobertaModel, RobertaTokenizer)
|
| 42 |
+
MODEL_CLASSES = {'roberta': (RobertaConfig, RobertaModel, RobertaTokenizer)}
|
| 43 |
+
|
| 44 |
+
logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
|
| 45 |
+
datefmt = '%m/%d/%Y %H:%M:%S',
|
| 46 |
+
level = logging.INFO)
|
| 47 |
+
logger = logging.getLogger(__name__)
|
| 48 |
+
|
| 49 |
+
class Example(object):
|
| 50 |
+
"""A single training/test example."""
|
| 51 |
+
def __init__(self,
|
| 52 |
+
idx,
|
| 53 |
+
source,
|
| 54 |
+
target,
|
| 55 |
+
):
|
| 56 |
+
self.idx = idx
|
| 57 |
+
self.source = source
|
| 58 |
+
self.target = target
|
| 59 |
+
|
| 60 |
+
# def read_examples(filename):
|
| 61 |
+
# """Read examples from filename."""
|
| 62 |
+
# examples=[]
|
| 63 |
+
# with open(filename,encoding="utf-8") as f:
|
| 64 |
+
# for idx,js in enumerate(json.load(f)):
|
| 65 |
+
# source=' '.join(js['old_comment_tokens'])
|
| 66 |
+
# target=' '.join(js['new_comment_tokens'])
|
| 67 |
+
# examples.append(
|
| 68 |
+
# Example(
|
| 69 |
+
# idx = idx,
|
| 70 |
+
# source=source,
|
| 71 |
+
# target=target,
|
| 72 |
+
# )
|
| 73 |
+
# )
|
| 74 |
+
# return examples
|
| 75 |
+
def read_examples(filename):
|
| 76 |
+
"""Read examples from filename."""
|
| 77 |
+
examples=[]
|
| 78 |
+
assert len(filename.split(','))==2
|
| 79 |
+
src_filename = filename.split(',')[0]
|
| 80 |
+
trg_filename = filename.split(',')[1]
|
| 81 |
+
idx = 0
|
| 82 |
+
with open(src_filename) as f1,open(trg_filename) as f2:
|
| 83 |
+
for line1,line2 in zip(f1,f2):
|
| 84 |
+
examples.append(
|
| 85 |
+
Example(
|
| 86 |
+
idx = idx,
|
| 87 |
+
source=line1.strip(),
|
| 88 |
+
target=line2.strip(),
|
| 89 |
+
)
|
| 90 |
+
)
|
| 91 |
+
idx+=1
|
| 92 |
+
return examples
|
| 93 |
+
|
| 94 |
+
class InputFeatures(object):
|
| 95 |
+
"""A single training/test features for a example."""
|
| 96 |
+
def __init__(self,
|
| 97 |
+
example_id,
|
| 98 |
+
source_ids,
|
| 99 |
+
target_ids,
|
| 100 |
+
source_mask,
|
| 101 |
+
target_mask,
|
| 102 |
+
|
| 103 |
+
):
|
| 104 |
+
self.example_id = example_id
|
| 105 |
+
self.source_ids = source_ids
|
| 106 |
+
self.target_ids = target_ids
|
| 107 |
+
self.source_mask = source_mask
|
| 108 |
+
self.target_mask = target_mask
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def convert_examples_to_features(examples, tokenizer, args,stage=None):
|
| 113 |
+
features = []
|
| 114 |
+
for example_index, example in enumerate(examples):
|
| 115 |
+
#source
|
| 116 |
+
source_tokens = tokenizer.tokenize(example.source)[:args.max_source_length-2]
|
| 117 |
+
source_tokens =[tokenizer.cls_token]+source_tokens+[tokenizer.sep_token]
|
| 118 |
+
source_ids = tokenizer.convert_tokens_to_ids(source_tokens)
|
| 119 |
+
source_mask = [1] * (len(source_tokens))
|
| 120 |
+
padding_length = args.max_source_length - len(source_ids)
|
| 121 |
+
source_ids+=[tokenizer.pad_token_id]*padding_length
|
| 122 |
+
source_mask+=[0]*padding_length
|
| 123 |
+
|
| 124 |
+
#target
|
| 125 |
+
if stage=="test":
|
| 126 |
+
target_tokens = tokenizer.tokenize("None")
|
| 127 |
+
else:
|
| 128 |
+
target_tokens = tokenizer.tokenize(example.target)[:args.max_target_length-2]
|
| 129 |
+
target_tokens = [tokenizer.cls_token]+target_tokens+[tokenizer.sep_token]
|
| 130 |
+
target_ids = tokenizer.convert_tokens_to_ids(target_tokens)
|
| 131 |
+
target_mask = [1] *len(target_ids)
|
| 132 |
+
padding_length = args.max_target_length - len(target_ids)
|
| 133 |
+
target_ids+=[tokenizer.pad_token_id]*padding_length
|
| 134 |
+
target_mask+=[0]*padding_length
|
| 135 |
+
|
| 136 |
+
if example_index < 5:
|
| 137 |
+
if stage=='train':
|
| 138 |
+
logger.info("*** Example ***")
|
| 139 |
+
logger.info("idx: {}".format(example.idx))
|
| 140 |
+
|
| 141 |
+
logger.info("source_tokens: {}".format([x.replace('\u0120','_') for x in source_tokens]))
|
| 142 |
+
logger.info("source_ids: {}".format(' '.join(map(str, source_ids))))
|
| 143 |
+
logger.info("source_mask: {}".format(' '.join(map(str, source_mask))))
|
| 144 |
+
|
| 145 |
+
logger.info("target_tokens: {}".format([x.replace('\u0120','_') for x in target_tokens]))
|
| 146 |
+
logger.info("target_ids: {}".format(' '.join(map(str, target_ids))))
|
| 147 |
+
logger.info("target_mask: {}".format(' '.join(map(str, target_mask))))
|
| 148 |
+
|
| 149 |
+
features.append(
|
| 150 |
+
InputFeatures(
|
| 151 |
+
example_index,
|
| 152 |
+
source_ids,
|
| 153 |
+
target_ids,
|
| 154 |
+
source_mask,
|
| 155 |
+
target_mask,
|
| 156 |
+
)
|
| 157 |
+
)
|
| 158 |
+
return features
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _truncate_seq_pair(tokens_a, tokens_b,tokens_c, max_length):
|
| 162 |
+
"""Truncates a sequence pair in place to the maximum length."""
|
| 163 |
+
|
| 164 |
+
# This is a simple heuristic which will always truncate the longer sequence
|
| 165 |
+
# one token at a time. This makes more sense than truncating an equal percent
|
| 166 |
+
# of tokens from each, since if one sequence is very short then each token
|
| 167 |
+
# that's truncated likely contains more information than a longer sequence.
|
| 168 |
+
|
| 169 |
+
while True:
|
| 170 |
+
total_length = len(tokens_a) + len(tokens_b)+len(tokens_c)
|
| 171 |
+
if total_length <= max_length:
|
| 172 |
+
break
|
| 173 |
+
if len(tokens_a) >= len(tokens_b) and len(tokens_a)>=len(tokens_c):
|
| 174 |
+
tokens_a.pop()
|
| 175 |
+
elif len(tokens_b) >= len(tokens_a) and len(tokens_b)>=len(tokens_c):
|
| 176 |
+
tokens_b.pop()
|
| 177 |
+
else:
|
| 178 |
+
tokens_c.pop()
|
| 179 |
+
|
| 180 |
+
def set_seed(args):
|
| 181 |
+
"""set random seed."""
|
| 182 |
+
random.seed(args.seed)
|
| 183 |
+
np.random.seed(args.seed)
|
| 184 |
+
torch.manual_seed(args.seed)
|
| 185 |
+
if args.n_gpu > 0:
|
| 186 |
+
torch.cuda.manual_seed_all(args.seed)
|
| 187 |
+
|
| 188 |
+
def main():
|
| 189 |
+
parser = argparse.ArgumentParser()
|
| 190 |
+
|
| 191 |
+
## Required parameters
|
| 192 |
+
parser.add_argument("--model_type", default=None, type=str, required=True,
|
| 193 |
+
help="Model type: e.g. roberta")
|
| 194 |
+
parser.add_argument("--model_name_or_path", default=None, type=str, required=True,
|
| 195 |
+
help="Path to pre-trained model: e.g. roberta-base" )
|
| 196 |
+
parser.add_argument("--tokenizer_name", default="", required=True,
|
| 197 |
+
help="Pretrained tokenizer name or path if not the same as model_name")
|
| 198 |
+
parser.add_argument("--output_dir", default=None, type=str, required=True,
|
| 199 |
+
help="The output directory where the model predictions and checkpoints will be written.")
|
| 200 |
+
parser.add_argument("--load_model_path", default=None, type=str,
|
| 201 |
+
help="Path to trained model: Should contain the .bin files" )
|
| 202 |
+
## Other parameters
|
| 203 |
+
parser.add_argument("--train_filename", default=None, type=str,
|
| 204 |
+
help="The train filenames (source and target files).")
|
| 205 |
+
parser.add_argument("--dev_filename", default=None, type=str,
|
| 206 |
+
help="The dev filename. (source and target files).")
|
| 207 |
+
parser.add_argument("--test_filename", default=None, type=str,
|
| 208 |
+
help="The test filename. (source and target files).")
|
| 209 |
+
|
| 210 |
+
parser.add_argument("--config_name", default="", type=str,
|
| 211 |
+
help="Pretrained config name or path if not the same as model_name")
|
| 212 |
+
|
| 213 |
+
parser.add_argument("--max_source_length", default=64, type=int,
|
| 214 |
+
help="The maximum total source sequence length after tokenization. Sequences longer "
|
| 215 |
+
"than this will be truncated, sequences shorter will be padded.")
|
| 216 |
+
parser.add_argument("--max_target_length", default=32, type=int,
|
| 217 |
+
help="The maximum total target sequence length after tokenization. Sequences longer "
|
| 218 |
+
"than this will be truncated, sequences shorter will be padded.")
|
| 219 |
+
|
| 220 |
+
parser.add_argument("--do_train", action='store_true',
|
| 221 |
+
help="Whether to run training.")
|
| 222 |
+
parser.add_argument("--do_eval", action='store_true',
|
| 223 |
+
help="Whether to run eval on the dev set.")
|
| 224 |
+
parser.add_argument("--do_test", action='store_true',
|
| 225 |
+
help="Whether to run eval on the dev set.")
|
| 226 |
+
parser.add_argument("--do_lower_case", action='store_true',
|
| 227 |
+
help="Set this flag if you are using an uncased model.")
|
| 228 |
+
parser.add_argument("--no_cuda", action='store_true',
|
| 229 |
+
help="Avoid using CUDA when available")
|
| 230 |
+
|
| 231 |
+
parser.add_argument("--train_batch_size", default=8, type=int,
|
| 232 |
+
help="Batch size per GPU/CPU for training.")
|
| 233 |
+
parser.add_argument("--eval_batch_size", default=8, type=int,
|
| 234 |
+
help="Batch size per GPU/CPU for evaluation.")
|
| 235 |
+
parser.add_argument('--gradient_accumulation_steps', type=int, default=1,
|
| 236 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.")
|
| 237 |
+
parser.add_argument("--learning_rate", default=5e-5, type=float,
|
| 238 |
+
help="The initial learning rate for Adam.")
|
| 239 |
+
parser.add_argument("--beam_size", default=10, type=int,
|
| 240 |
+
help="beam size for beam search")
|
| 241 |
+
parser.add_argument("--weight_decay", default=0.0, type=float,
|
| 242 |
+
help="Weight deay if we apply some.")
|
| 243 |
+
parser.add_argument("--adam_epsilon", default=1e-8, type=float,
|
| 244 |
+
help="Epsilon for Adam optimizer.")
|
| 245 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float,
|
| 246 |
+
help="Max gradient norm.")
|
| 247 |
+
parser.add_argument("--num_train_epochs", default=3.0, type=float,
|
| 248 |
+
help="Total number of training epochs to perform.")
|
| 249 |
+
parser.add_argument("--max_steps", default=-1, type=int,
|
| 250 |
+
help="If > 0: set total number of training steps to perform. Override num_train_epochs.")
|
| 251 |
+
parser.add_argument("--eval_steps", default=-1, type=int,
|
| 252 |
+
help="")
|
| 253 |
+
parser.add_argument("--train_steps", default=-1, type=int,
|
| 254 |
+
help="")
|
| 255 |
+
parser.add_argument("--warmup_steps", default=0, type=int,
|
| 256 |
+
help="Linear warmup over warmup_steps.")
|
| 257 |
+
parser.add_argument("--local_rank", type=int, default=-1,
|
| 258 |
+
help="For distributed training: local_rank")
|
| 259 |
+
parser.add_argument('--seed', type=int, default=42,
|
| 260 |
+
help="random seed for initialization")
|
| 261 |
+
# print arguments
|
| 262 |
+
args = parser.parse_args()
|
| 263 |
+
logger.info(args)
|
| 264 |
+
|
| 265 |
+
# Setup CUDA, GPU & distributed training
|
| 266 |
+
if args.local_rank == -1 or args.no_cuda:
|
| 267 |
+
device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
|
| 268 |
+
args.n_gpu = torch.cuda.device_count()
|
| 269 |
+
else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
|
| 270 |
+
torch.cuda.set_device(args.local_rank)
|
| 271 |
+
device = torch.device("cuda", args.local_rank)
|
| 272 |
+
torch.distributed.init_process_group(backend='nccl')
|
| 273 |
+
args.n_gpu = 1
|
| 274 |
+
logger.warning("Process rank: %s, device: %s, n_gpu: %s, distributed training: %s",
|
| 275 |
+
args.local_rank, device, args.n_gpu, bool(args.local_rank != -1))
|
| 276 |
+
args.device = device
|
| 277 |
+
# Set seed
|
| 278 |
+
set_seed(args)
|
| 279 |
+
# make dir if output_dir not exist
|
| 280 |
+
if os.path.exists(args.output_dir) is False:
|
| 281 |
+
os.makedirs(args.output_dir)
|
| 282 |
+
|
| 283 |
+
config_class, model_class, tokenizer_class = MODEL_CLASSES[args.model_type]
|
| 284 |
+
config = config_class.from_pretrained(args.config_name if args.config_name else args.model_name_or_path)
|
| 285 |
+
tokenizer = tokenizer_class.from_pretrained(args.tokenizer_name,do_lower_case=args.do_lower_case)
|
| 286 |
+
|
| 287 |
+
#budild model
|
| 288 |
+
encoder = model_class.from_pretrained(args.model_name_or_path,config=config)
|
| 289 |
+
decoder_layer = nn.TransformerDecoderLayer(d_model=config.hidden_size, nhead=config.num_attention_heads)
|
| 290 |
+
decoder = nn.TransformerDecoder(decoder_layer, num_layers=6)
|
| 291 |
+
model=Seq2Seq(encoder=encoder,decoder=decoder,config=config,
|
| 292 |
+
beam_size=args.beam_size,max_length=args.max_target_length,
|
| 293 |
+
sos_id=tokenizer.cls_token_id,eos_id=tokenizer.sep_token_id)
|
| 294 |
+
|
| 295 |
+
if args.load_model_path is not None:
|
| 296 |
+
logger.info("reload model from {}".format(args.load_model_path))
|
| 297 |
+
model.load_state_dict(torch.load(args.load_model_path))
|
| 298 |
+
|
| 299 |
+
model.to(device)
|
| 300 |
+
if args.local_rank != -1:
|
| 301 |
+
# Distributed training
|
| 302 |
+
try:
|
| 303 |
+
from apex.parallel import DistributedDataParallel as DDP
|
| 304 |
+
except ImportError:
|
| 305 |
+
raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
|
| 306 |
+
|
| 307 |
+
model = DDP(model)
|
| 308 |
+
elif args.n_gpu > 1:
|
| 309 |
+
# multi-gpu training
|
| 310 |
+
model = torch.nn.DataParallel(model)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
if args.do_train:
|
| 316 |
+
# Prepare training data loader
|
| 317 |
+
train_examples = read_examples(args.train_filename)
|
| 318 |
+
train_features = convert_examples_to_features(train_examples, tokenizer,args,stage='train')
|
| 319 |
+
all_source_ids = torch.tensor([f.source_ids for f in train_features], dtype=torch.long)
|
| 320 |
+
all_source_mask = torch.tensor([f.source_mask for f in train_features], dtype=torch.long)
|
| 321 |
+
all_target_ids = torch.tensor([f.target_ids for f in train_features], dtype=torch.long)
|
| 322 |
+
all_target_mask = torch.tensor([f.target_mask for f in train_features], dtype=torch.long)
|
| 323 |
+
train_data = TensorDataset(all_source_ids,all_source_mask,all_target_ids,all_target_mask)
|
| 324 |
+
|
| 325 |
+
if args.local_rank == -1:
|
| 326 |
+
train_sampler = RandomSampler(train_data)
|
| 327 |
+
else:
|
| 328 |
+
train_sampler = DistributedSampler(train_data)
|
| 329 |
+
train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=args.train_batch_size//args.gradient_accumulation_steps)
|
| 330 |
+
|
| 331 |
+
num_train_optimization_steps = args.train_steps
|
| 332 |
+
|
| 333 |
+
# Prepare optimizer and schedule (linear warmup and decay)
|
| 334 |
+
no_decay = ['bias', 'LayerNorm.weight']
|
| 335 |
+
optimizer_grouped_parameters = [
|
| 336 |
+
{'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
|
| 337 |
+
'weight_decay': args.weight_decay},
|
| 338 |
+
{'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
|
| 339 |
+
]
|
| 340 |
+
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
|
| 341 |
+
scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=args.warmup_steps,
|
| 342 |
+
num_training_steps=num_train_optimization_steps)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
#Start training
|
| 346 |
+
logger.info("***** Running training *****")
|
| 347 |
+
logger.info(" Num examples = %d", len(train_examples))
|
| 348 |
+
logger.info(" Batch size = %d", args.train_batch_size)
|
| 349 |
+
logger.info(" Num epoch = %d", num_train_optimization_steps*args.train_batch_size//len(train_examples))
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
model.train()
|
| 353 |
+
dev_dataset={}
|
| 354 |
+
nb_tr_examples, nb_tr_steps,tr_loss,global_step,best_bleu,best_loss = 0, 0,0,0,0,1e6
|
| 355 |
+
bar = range(num_train_optimization_steps)
|
| 356 |
+
train_dataloader=cycle(train_dataloader)
|
| 357 |
+
eval_flag = True
|
| 358 |
+
idx=0
|
| 359 |
+
for step in bar:
|
| 360 |
+
batch = next(train_dataloader)
|
| 361 |
+
batch = tuple(t.to(device) for t in batch)
|
| 362 |
+
source_ids,source_mask,target_ids,target_mask = batch
|
| 363 |
+
loss,_,_ = model(source_ids=source_ids,source_mask=source_mask,target_ids=target_ids,target_mask=target_mask)
|
| 364 |
+
|
| 365 |
+
if args.n_gpu > 1:
|
| 366 |
+
loss = loss.mean() # mean() to average on multi-gpu.
|
| 367 |
+
if args.gradient_accumulation_steps > 1:
|
| 368 |
+
loss = loss / args.gradient_accumulation_steps
|
| 369 |
+
tr_loss += loss.item()
|
| 370 |
+
train_loss=round(tr_loss*args.gradient_accumulation_steps/(nb_tr_steps+1),4)
|
| 371 |
+
if (global_step + 1)%100==0:
|
| 372 |
+
logger.info(" step {} loss {} batch-{}".format(global_step + 1,train_loss, ((global_step+1)*args.train_batch_size) / len(train_examples)))
|
| 373 |
+
nb_tr_examples += source_ids.size(0)
|
| 374 |
+
nb_tr_steps += 1
|
| 375 |
+
loss.backward()
|
| 376 |
+
|
| 377 |
+
if (nb_tr_steps + 1) % args.gradient_accumulation_steps == 0:
|
| 378 |
+
#Update parameters
|
| 379 |
+
optimizer.step()
|
| 380 |
+
optimizer.zero_grad()
|
| 381 |
+
scheduler.step()
|
| 382 |
+
global_step += 1
|
| 383 |
+
eval_flag = True
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
if args.do_eval and ((global_step + 1) %args.eval_steps == 0) and eval_flag:
|
| 387 |
+
#Eval model with dev dataset
|
| 388 |
+
tr_loss = 0
|
| 389 |
+
nb_tr_examples, nb_tr_steps = 0, 0
|
| 390 |
+
eval_flag=False
|
| 391 |
+
if 'dev_loss' in dev_dataset:
|
| 392 |
+
eval_examples,eval_data=dev_dataset['dev_loss']
|
| 393 |
+
else:
|
| 394 |
+
eval_examples = read_examples(args.dev_filename)
|
| 395 |
+
eval_features = convert_examples_to_features(eval_examples, tokenizer, args,stage='dev')
|
| 396 |
+
all_source_ids = torch.tensor([f.source_ids for f in eval_features], dtype=torch.long)
|
| 397 |
+
all_source_mask = torch.tensor([f.source_mask for f in eval_features], dtype=torch.long)
|
| 398 |
+
all_target_ids = torch.tensor([f.target_ids for f in eval_features], dtype=torch.long)
|
| 399 |
+
all_target_mask = torch.tensor([f.target_mask for f in eval_features], dtype=torch.long)
|
| 400 |
+
eval_data = TensorDataset(all_source_ids,all_source_mask,all_target_ids,all_target_mask)
|
| 401 |
+
dev_dataset['dev_loss']=eval_examples,eval_data
|
| 402 |
+
eval_sampler = SequentialSampler(eval_data)
|
| 403 |
+
eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size)
|
| 404 |
+
|
| 405 |
+
logger.info("\n***** Running evaluation *****")
|
| 406 |
+
logger.info(" Num examples = %d", len(eval_examples))
|
| 407 |
+
logger.info(" Batch size = %d", args.eval_batch_size)
|
| 408 |
+
|
| 409 |
+
#Start Evaling model
|
| 410 |
+
model.eval()
|
| 411 |
+
eval_loss,tokens_num = 0,0
|
| 412 |
+
for batch in eval_dataloader:
|
| 413 |
+
batch = tuple(t.to(device) for t in batch)
|
| 414 |
+
source_ids,source_mask,target_ids,target_mask = batch
|
| 415 |
+
|
| 416 |
+
with torch.no_grad():
|
| 417 |
+
_,loss,num = model(source_ids=source_ids,source_mask=source_mask,
|
| 418 |
+
target_ids=target_ids,target_mask=target_mask)
|
| 419 |
+
eval_loss += loss.sum().item()
|
| 420 |
+
tokens_num += num.sum().item()
|
| 421 |
+
#Pring loss of dev dataset
|
| 422 |
+
model.train()
|
| 423 |
+
eval_loss = eval_loss / tokens_num
|
| 424 |
+
result = {'eval_ppl': round(np.exp(eval_loss),5),
|
| 425 |
+
'global_step': global_step+1,
|
| 426 |
+
'train_loss': round(train_loss,5)}
|
| 427 |
+
for key in sorted(result.keys()):
|
| 428 |
+
logger.info(" %s = %s", key, str(result[key]))
|
| 429 |
+
logger.info(" "+"*"*20)
|
| 430 |
+
|
| 431 |
+
#save last checkpoint
|
| 432 |
+
last_output_dir = os.path.join(args.output_dir, 'checkpoint-last')
|
| 433 |
+
if not os.path.exists(last_output_dir):
|
| 434 |
+
os.makedirs(last_output_dir)
|
| 435 |
+
model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self
|
| 436 |
+
output_model_file = os.path.join(last_output_dir, "pytorch_model.bin")
|
| 437 |
+
torch.save(model_to_save.state_dict(), output_model_file)
|
| 438 |
+
if eval_loss<best_loss:
|
| 439 |
+
logger.info(" Best ppl:%s",round(np.exp(eval_loss),5))
|
| 440 |
+
logger.info(" "+"*"*20)
|
| 441 |
+
best_loss=eval_loss
|
| 442 |
+
# Save best checkpoint for best ppl
|
| 443 |
+
output_dir = os.path.join(args.output_dir, 'checkpoint-best-ppl')
|
| 444 |
+
if not os.path.exists(output_dir):
|
| 445 |
+
os.makedirs(output_dir)
|
| 446 |
+
model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self
|
| 447 |
+
output_model_file = os.path.join(output_dir, "pytorch_model.bin")
|
| 448 |
+
torch.save(model_to_save.state_dict(), output_model_file)
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
#Calculate bleu
|
| 452 |
+
if 'dev_bleu' in dev_dataset:
|
| 453 |
+
eval_examples,eval_data=dev_dataset['dev_bleu']
|
| 454 |
+
else:
|
| 455 |
+
eval_examples = read_examples(args.dev_filename)
|
| 456 |
+
eval_examples = random.sample(eval_examples,min(1000,len(eval_examples)))
|
| 457 |
+
eval_features = convert_examples_to_features(eval_examples, tokenizer, args,stage='test')
|
| 458 |
+
all_source_ids = torch.tensor([f.source_ids for f in eval_features], dtype=torch.long)
|
| 459 |
+
all_source_mask = torch.tensor([f.source_mask for f in eval_features], dtype=torch.long)
|
| 460 |
+
eval_data = TensorDataset(all_source_ids,all_source_mask)
|
| 461 |
+
dev_dataset['dev_bleu']=eval_examples,eval_data
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
eval_sampler = SequentialSampler(eval_data)
|
| 465 |
+
eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size)
|
| 466 |
+
|
| 467 |
+
model.eval()
|
| 468 |
+
p=[]
|
| 469 |
+
for batch in eval_dataloader:
|
| 470 |
+
batch = tuple(t.to(device) for t in batch)
|
| 471 |
+
source_ids,source_mask= batch
|
| 472 |
+
with torch.no_grad():
|
| 473 |
+
preds = model(source_ids=source_ids,source_mask=source_mask)
|
| 474 |
+
for pred in preds:
|
| 475 |
+
t=pred[0].cpu().numpy()
|
| 476 |
+
t=list(t)
|
| 477 |
+
if 0 in t:
|
| 478 |
+
t=t[:t.index(0)]
|
| 479 |
+
text = tokenizer.decode(t,clean_up_tokenization_spaces=False)
|
| 480 |
+
p.append(text)
|
| 481 |
+
model.train()
|
| 482 |
+
predictions=[]
|
| 483 |
+
accs=[]
|
| 484 |
+
with open(os.path.join(args.output_dir,"dev.output"),'w') as f, open(os.path.join(args.output_dir,"dev.gold"),'w') as f1:
|
| 485 |
+
for ref,gold in zip(p,eval_examples):
|
| 486 |
+
predictions.append(str(gold.idx)+'\t'+ref)
|
| 487 |
+
f.write(ref+'\n')
|
| 488 |
+
f1.write(gold.target+'\n')
|
| 489 |
+
accs.append(ref==gold.target)
|
| 490 |
+
|
| 491 |
+
dev_bleu=round(_bleu(os.path.join(args.output_dir, "dev.gold"), os.path.join(args.output_dir, "dev.output")),2)
|
| 492 |
+
logger.info(" %s = %s "%("bleu-4",str(dev_bleu)))
|
| 493 |
+
logger.info(" %s = %s "%("xMatch",str(round(np.mean(accs)*100,4))))
|
| 494 |
+
logger.info(" "+"*"*20)
|
| 495 |
+
if dev_bleu>best_bleu:
|
| 496 |
+
logger.info(" Best bleu:%s",dev_bleu)
|
| 497 |
+
logger.info(" "+"*"*20)
|
| 498 |
+
best_bleu=dev_bleu
|
| 499 |
+
# Save best checkpoint for best bleu
|
| 500 |
+
output_dir = os.path.join(args.output_dir, 'checkpoint-best-bleu')
|
| 501 |
+
if not os.path.exists(output_dir):
|
| 502 |
+
os.makedirs(output_dir)
|
| 503 |
+
model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self
|
| 504 |
+
output_model_file = os.path.join(output_dir, "pytorch_model.bin")
|
| 505 |
+
torch.save(model_to_save.state_dict(), output_model_file)
|
| 506 |
+
|
| 507 |
+
# 每一轮记录checkpoint
|
| 508 |
+
if int((global_step+1)*args.train_batch_size / len(train_examples)) == idx+1:
|
| 509 |
+
logger.info(" batch:%s",idx)
|
| 510 |
+
output_dir = os.path.join(args.output_dir, 'epoch_{}'.format(idx+1))
|
| 511 |
+
if not os.path.exists(output_dir):
|
| 512 |
+
os.makedirs(output_dir)
|
| 513 |
+
model_to_save = model.module if hasattr(model, 'module') else model
|
| 514 |
+
ckpt_output_path = os.path.join(output_dir, 'subject_model.pth')
|
| 515 |
+
logger.info("Saving model checkpoint to %s", ckpt_output_path)
|
| 516 |
+
torch.save(model_to_save.state_dict(), ckpt_output_path)
|
| 517 |
+
idx = idx+1
|
| 518 |
+
|
| 519 |
+
if args.do_test:
|
| 520 |
+
files=[]
|
| 521 |
+
if args.dev_filename is not None:
|
| 522 |
+
files.append(args.dev_filename)
|
| 523 |
+
if args.test_filename is not None:
|
| 524 |
+
files.append(args.test_filename)
|
| 525 |
+
for idx,file in enumerate(files):
|
| 526 |
+
logger.info("Test file: {}".format(file))
|
| 527 |
+
eval_examples = read_examples(file)
|
| 528 |
+
eval_features = convert_examples_to_features(eval_examples, tokenizer, args,stage='test')
|
| 529 |
+
all_source_ids = torch.tensor([f.source_ids for f in eval_features], dtype=torch.long)
|
| 530 |
+
all_source_mask = torch.tensor([f.source_mask for f in eval_features], dtype=torch.long)
|
| 531 |
+
eval_data = TensorDataset(all_source_ids,all_source_mask)
|
| 532 |
+
|
| 533 |
+
# Calculate bleu
|
| 534 |
+
eval_sampler = SequentialSampler(eval_data)
|
| 535 |
+
eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size)
|
| 536 |
+
|
| 537 |
+
model.eval()
|
| 538 |
+
p=[]
|
| 539 |
+
for batch in tqdm(eval_dataloader,total=len(eval_dataloader)):
|
| 540 |
+
batch = tuple(t.to(device) for t in batch)
|
| 541 |
+
source_ids,source_mask= batch
|
| 542 |
+
with torch.no_grad():
|
| 543 |
+
preds = model(source_ids=source_ids,source_mask=source_mask)
|
| 544 |
+
for pred in preds:
|
| 545 |
+
t=pred[0].cpu().numpy()
|
| 546 |
+
t=list(t)
|
| 547 |
+
if 0 in t:
|
| 548 |
+
t=t[:t.index(0)]
|
| 549 |
+
text = tokenizer.decode(t,clean_up_tokenization_spaces=False)
|
| 550 |
+
p.append(text)
|
| 551 |
+
model.train()
|
| 552 |
+
predictions=[]
|
| 553 |
+
accs=[]
|
| 554 |
+
with open(os.path.join(args.output_dir,"test_{}.output".format(str(idx))),'w') as f, open(os.path.join(args.output_dir,"test_{}.gold".format(str(idx))),'w') as f1:
|
| 555 |
+
for ref,gold in zip(p,eval_examples):
|
| 556 |
+
predictions.append(str(gold.idx)+'\t'+ref)
|
| 557 |
+
f.write(ref+'\n')
|
| 558 |
+
f1.write(gold.target+'\n')
|
| 559 |
+
accs.append(ref==gold.target)
|
| 560 |
+
dev_bleu=round(_bleu(os.path.join(args.output_dir, "test_{}.gold".format(str(idx))).format(file),
|
| 561 |
+
os.path.join(args.output_dir, "test_{}.output".format(str(idx))).format(file)),2)
|
| 562 |
+
logger.info(" %s = %s "%("bleu-4",str(dev_bleu)))
|
| 563 |
+
logger.info(" %s = %s "%("xMatch",str(round(np.mean(accs)*100,4))))
|
| 564 |
+
logger.info(" "+"*"*20)
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
if __name__ == "__main__":
|
| 573 |
+
main()
|
| 574 |
+
|
| 575 |
+
|
Code-Code/code-refinement/code/train.sh
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pretrained_model=microsoft/codebert-base
|
| 2 |
+
output_dir=../model
|
| 3 |
+
data_size=small
|
| 4 |
+
|
| 5 |
+
CUDA_VISIBLE_DEVICES=1 python run.py \
|
| 6 |
+
--do_train \
|
| 7 |
+
--do_eval \
|
| 8 |
+
--model_type roberta \
|
| 9 |
+
--model_name_or_path $pretrained_model \
|
| 10 |
+
--config_name roberta-base \
|
| 11 |
+
--tokenizer_name roberta-base \
|
| 12 |
+
--train_filename ../data/$data_size/train.buggy-fixed.buggy,../data/$data_size/train.buggy-fixed.fixed \
|
| 13 |
+
--dev_filename ../data/$data_size/valid.buggy-fixed.buggy,../data/$data_size/valid.buggy-fixed.fixed \
|
| 14 |
+
--output_dir $output_dir \
|
| 15 |
+
--max_source_length 256 \
|
| 16 |
+
--max_target_length 256 \
|
| 17 |
+
--beam_size 5 \
|
| 18 |
+
--train_batch_size 16 \
|
| 19 |
+
--eval_batch_size 16 \
|
| 20 |
+
--learning_rate 5e-5 \
|
| 21 |
+
--train_steps 100000 \
|
| 22 |
+
--eval_steps 5000
|
Code-Code/code-refinement/dataset.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:777c3c2c8db2e206e35336adda286979caea2dd7627f86be63ad9313d6dd5c29
|
| 3 |
+
size 9317188
|
Code-Code/code-refinement/model/small/epoch_1/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e6b05f716a14b3d0a62b4422dc6f18cfa2fdac29301e12cf4e121347729ec8fa
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_10/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d61f16c493c55bb0bd1b84ce36cf4225e64e0c187a7e41994b2d5c4d1f5efb45
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_11/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f3084bd427a8cf7b0a05046af79827883226af6445109de5f6440ee93c7abc2f
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_12/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:aeee8fa65ce756766f4edf0f94ae7805ae1f6bedad447f358d019b83fdf4b513
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_13/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:25e8ca4fbe1853e219c06fa1e362c4751abab57ed3f94a23d63c782ed3c63853
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_14/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:42421558f25f54dc444045333f543047b79d41f5a5109c204871cf1e7e714e34
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_15/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cb6b4b9bd653da1a38777abc33580b16c0ea7737e2e6eebd40c1ee3231dd2525
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_16/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e84db73a34b32c5a34de0a8b654b65c3a7f816d520166417fbfffaf06709761a
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_17/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1940da61b9694d399c0174cabbbe079305fd0c83af9b330d7b7c29a24212ff7e
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_18/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:eb2f87f3b1bdd22cc199e7cd6d2fdeeabed172aba80dc1b5e3e931f00c0db221
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_19/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f435b05862fb483953e8d89cd282b3d2455e66ea185424b064c3a9dea60d44ba
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_2/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d2765a60f55cefb0f81a2ccfe5a3feecff60e4ddd6ec95f926e09bb82b5ea35a
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_20/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dbd7a12d14fdded692014ece0c839271c9550baf566121769bf0155ae45b0dff
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_21/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c6968ca9583229fe1f4a405ffcd5a1755880afeaaddf44d3bf232512f3117b30
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_22/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c92b34a54054d5050a93987c8c86f4709d1d045d67320833d5d77d790de1b92a
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_23/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3ccb0de56f83b838b266aa8d4b70d487165f7890e9516de51781d090fc930110
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_24/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bab03af58d3427465a77c73a14522acae3e1cfad656a73657b66873ef8e78a4c
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_25/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:808738fef09b31ce1a622c39c6768ce8456b9660e5d593d33ffff5b41063e3b4
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_26/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:31a5268731cd469961b76140fc87aca6c5b1bc4970389db067218a1facfb284b
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_27/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5490287d246c88b9a2726719172c6defb08e1aa1262d1cb735868d692e832fe3
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_28/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d93d8c1a8bdf36d86f58a8e681540b0af99a21a0718bbc8439215375eeea78a7
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_29/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8a28193fba39c8e1671f4a4cd5c41d2d2c695776d6fe8095ccab336ea2753c86
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_3/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e2286983e6e43899b2b6685d4ef71f6f26b3f301a50c2b376e94bab0b0f4edcf
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_30/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a4436991d4e786259881a3dd0cbd2076fdb085a25aedf969580891e889946ae9
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_31/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5b133f89fb3ab2d7a549a3cecd4e78eed0307d93f521cf6e98773ac856ce8957
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_32/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4dfd1584e18a19423adb2e996987015213feac913e5a39b87b00d76c46b333cd
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_33/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b1e71a49b62f8e90528fe875a94bfef3e341216667dab643a793d2fb5627caca
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_34/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:169be3c2a9e8d7f8480a905040b71be15b2d8b1f041717ea37b21924dd20e6c9
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_4/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:111f43e21f3b2353d1cd81792c983292aca2e3ac2fc7f4df96a70e61c086c1ae
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_5/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e2d1e6b278a504f5d401296cf78d763fc9115971dfd5a25b5be9a2c4408208d9
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_6/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:45ee133457ba3921a4ed06a666eb0cf4761132393b1173ee4259ccaf5f15609c
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_7/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0f0d67dac12fa48e241b70d89e620b384ee820c191749e605ec931ae8473c44c
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_8/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5b68f6098a2a815fff9cbe53b565c4d907ba3c82985053f7791aa96527772b16
|
| 3 |
+
size 706916066
|
Code-Code/code-refinement/model/small/epoch_9/subject_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:45e29b5f23c8343e59e59193d2e60253728c7f0262c1984866fdfc267c722b75
|
| 3 |
+
size 706916066
|