eval_humaneval.py 12.5 KB
Newer Older
Rayyyyy's avatar
Rayyyyy committed
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
import argparse
from human_eval.data import write_jsonl, read_problems
import torch, transformers
import math
import pdb
from tqdm import tqdm
import sys, os, pdb, re, json
from abc import ABC
from torch.utils.data import Dataset

sys.path.append('./')
from megatron import get_args
from megatron import print_rank_0
from megatron.core import mpu
from megatron.checkpointing import load_checkpoint
from megatron.initialize import initialize_megatron
from megatron.model import YuanModel
from megatron.training import get_model
from megatron.arguments import core_transformer_config_from_args
from megatron.text_generation import generate_and_post_process
from megatron.text_generation import beam_search_and_post_process
import torch
from transformers import LlamaTokenizer
from megatron import get_tokenizer
import re
from typing import Optional
import json


def parse_code_block(string: str, lang: str) -> Optional[str]:
    code_pattern = fr"```{lang}\n(.*?)\n```"
    match = re.search(code_pattern, string, re.DOTALL)
    if match:
        return match.group(1)
    else:
        return parse_first_func(string, lang)


def parse_first_func(code: str, lang: str) -> Optional[str]:
    assert lang == "python", "Only python is supported for now. TODO: Rust"
    code_lines = code.split("\n")
    def_i = 0
    last_i = 0
    for i, line in enumerate(code_lines):
        if line.startswith("def "):
            if def_i == 0:
                def_i = i
            else:
                break
        if line == "" and def_i != 0:
            last_i = i
            break

    if last_i == 0:
        last_i = len(code_lines) - 1

    if def_i == 0:
        return None

    return "\n".join(code_lines[def_i:last_i+1])


def get_textbookprompt(task_id, prompt_lines):

    prompt = [line['prompt'] for line in prompt_lines if line['task_id'] == task_id][0]

    return prompt


def model_provider(pre_process=True, post_process=True):
    """Build the model."""

    config = core_transformer_config_from_args(get_args())

    print_rank_0('building GPT model ...')
    model = YuanModel(config, num_tokentypes=0, parallel_output=False, pre_process=pre_process, post_process=post_process)
    return model


def add_text_generate_args(parser):
    group = parser.add_argument_group(title='text generation')
    group.add_argument('--max_len', type=int, default=512)
    group.add_argument('--model_config_path', type=str, default='<Specify path>')
    group.add_argument('--human_eval_datapath', type=str, default='./dataset/HUMANEVAL/HumanEval.jsonl.gz')
    group.add_argument('--textprompts_datapath', type=str, default='./dataset/HUMANEVAL/HumanEval-textprompts.jsonl')
    group.add_argument('--output_path', type=str, default='<Specify path>')
    group.add_argument('--num_samples_per_task', type=int, default=1)
    group.add_argument('--top_k', type=int, default=1)
    group.add_argument('--top_p', type=float, default=0)
    group.add_argument('--top_p_decay', type=float, default=0.0)
    group.add_argument('--top_p_bound', type=float, default=0.0)
    group.add_argument('--temp', type=float, default=1)
    group.add_argument('--min_length', type=int, default=0)
    group.add_argument('--random_seed', type=int, default=1234)
    group.add_argument('--beam_width', type=int, default=None)
    group.add_argument('--length_penalty', type=int, default=1)
    group.add_argument('--eos_id', type=int, default=28956)
    group.add_argument('--prevent_newline_after_colon', type=bool, default=False)
    return parser

class HumanEvalDataset(ABC, Dataset):
    def __init__(self, data_path):
        self.problems = read_problems(data_path)
        self.keys = list(self.problems.keys())

    def __len__(self):
        return len(self.problems)

    def __getitem__(self, idx):
        try:
            key = self.keys[idx]
            sample = self.problems[key]
        except Exception as e:
            print(e, idx, len(self.problems))
            exit()
        return {'task_id':key, 'sample':sample}


def main():
    initialize_megatron(extra_args_provider=add_text_generate_args,
                        args_defaults={'tokenizer_type': 'LlamaTokenizer',
                                       'no_load_rng': True,
                                       'no_load_optim': True})

    args = get_args()

    textprompts_path = args.textprompts_datapath
    textprompts_lines = open(textprompts_path,'r',encoding='utf-8').readlines()
    textprompts_lines = [json.loads(line) for line in textprompts_lines]

    dataset = HumanEvalDataset(args.human_eval_datapath)
    sampler = torch.utils.data.distributed.DistributedSampler(dataset,rank=mpu.get_data_parallel_rank(),num_replicas=mpu.get_data_parallel_world_size(),shuffle=False,drop_last=False)

    data_loader = torch.utils.data.DataLoader(dataset,
            batch_size=args.micro_batch_size,
            sampler=sampler,
            num_workers=args.num_workers,
            shuffle=False,
            pin_memory=True,
            drop_last=False,
            prefetch_factor=2)
    model = get_model(model_provider, wrap_with_ddp=False)
    if args.load is not None:
        _ = load_checkpoint(model, None, None)
    assert len(model) == 1, "Above condition should have caught this"
    model = model[0]
    tokenizer = get_tokenizer()
    tokenizer.add_eos_token = False
    tokenizer.add_bos_token = False
    tokenizer.eod = tokenizer.convert_tokens_to_ids(tokenizer.eos_token)
    stop_token = tokenizer.convert_tokens_to_ids(tokenizer.eos_token)
    tokenizer.add_special_tokens({'pad_token': '<pad>'})
    torch.distributed.barrier()
    
    model.eval()
    if args.fp16:
        model = model.half()
    elif args.bf16:
        model = model.bfloat16()
    else:
        model = model.float()
    model.cuda()
    torch.distributed.barrier()
    if torch.distributed.get_rank()==0 and not os.path.exists(args.output_path):
        os.mkdirs(args.output_path)

    samples = []
    with torch.no_grad():
        with open(os.path.join(args.output_path, f'samples_{args.rank}.jsonl'), 'w') as fp:
            data_iter = tqdm(enumerate(data_loader), total=len(data_loader)) if torch.distributed.get_rank()==0 else enumerate(data_loader)
            for i, batch in data_iter:
                sample_iter = tqdm(range(args.num_samples_per_task), total=args.num_samples_per_task) if torch.distributed.get_rank()==0 else  range(args.num_samples_per_task)
                for j in sample_iter:
                    new_prompt = get_textbookprompt(task_id=batch['task_id'][0], prompt_lines=textprompts_lines)
                    if new_prompt is not None:
                        batch['sample']['prompt'] = [new_prompt]
                    tokens = tokenizer(batch['sample']['prompt'], return_tensors='pt', padding=True).input_ids[:,:-1].to(torch.cuda.current_device())
                    if args.beam_width is not None:
                        response, response_seg, response_scores = \
                            beam_search_and_post_process(
                            model,
                            prompts=batch['sample']['prompt'],
                            tokens_to_generate=(args.max_len - len(tokens)),
                            beam_size = args.beam_width,
                            add_BOS=False,
                            stop_token=stop_token,
                            num_return_gen=args.beam_width,  # Returning whole beam
                            length_penalty=args.length_penalty,
                            prevent_newline_after_colon=args.prevent_newline_after_colon
                            )
                    else:
                        response, response_seg, response_logprobs, _ = \
                            generate_and_post_process(
                            model,
                            prompts=batch['sample']['prompt'],
                            tokens_to_generate=(args.max_len - len(tokens)),
                            return_output_log_probs=False,
                            top_k_sampling=args.top_k,
                            top_p_sampling=args.top_p,
                            top_p_decay=args.top_p_decay,
                            top_p_bound=args.top_p_bound,
                            temperature=args.temp,
                            add_BOS=False,
                            stop_on_eol=False,
                            prevent_newline_after_colon=args.prevent_newline_after_colon,
                            random_seed=args.random_seed)
                    if mpu.is_pipeline_first_stage() and mpu.get_tensor_model_parallel_rank() == 0:
                        if response[0][-5:]=='<eod>':
                            if response[0][0]==' ':
                                response = [response[0][1:-5]]
                            else:
                                response = [response[0][0:-5]]

                        if new_prompt is not None:
                            new_sample = [response[0][response[0].rfind("```python")+9:]]
                        else:
                            new_sample = response
                        print('\n\n')
                        print(response[0])
                        print('-----------------------------------------------------------')
                        for k, x in enumerate(new_sample):
                            x = x.replace('\nFIX = """\nAdd more test cases.\n"""','')
                            x = x.replace('\n\n\ndef','\ndef')
                            x = x.replace('\n    \n\n    ','\n    \n    ')
                            x = x.replace('\n\n    ','\n    ')
                            x = x.replace('\n\n\n','\n\n')
                            x = x.replace('"""\n        ','"""\n    ')
                            x = x.replace('\n```python','')
                            if x.count('"""') >= 2:
                                x = x.replace(x[x.find('"""'):x.find('"""',x.find('"""')+1)+3],'')
                            elif x.count("'''") >= 2:
                                x = x.replace(x[x.find("'''"):x.find("'''",x.find("'''")+1)+3],'')
                            x_func = parse_code_block(x, "python")
                            if x_func is not None:
                                x_func = x[0:x.find(x_func[0:10])]+x_func
                            else:
                                x_func = x
                            if x_func.count('\ndef') > 1 and x_func.count('\n```')<1 and x_func.count('\n#')<1 and x_func.count('\nif')<1:
                                x_func = x_func.replace(x_func[x_func.find('\ndef',x_func.find('\ndef')+1):],'\n')
                            if x_func.find('\nprint')>0:
                                x_func = x_func[0:x_func.find('\nprint')]
                            if x_func.find('\n# 示例')>0:
                                x_func = x_func[0:x_func.find('\n# 示例')]
                            if x_func.find('\n```')>0:
                                x_func = x_func[0:x_func.find('\n```')]
                            if x_func.find('\n# 测试')>0:
                                x_func = x_func[0:x_func.find('\n# 测试')]
                            if x_func.find('\n# 单元测试')>0:
                                x_func = x_func[0:x_func.find('\n# 单元测试')]
                            if x_func.find('\n#')>0:
                                x_func = x_func[0:x_func.find('\n#')]
                            if x_func.find('\nif')>0:
                                x_func = x_func[0:x_func.find('\nif')]
                            print(x_func)
                            x = dict(task_id=batch['task_id'][k], completion=x_func)
                            fp.write(json.dumps(x) + "\n")
                            fp.flush()
    torch.distributed.barrier()
    if torch.distributed.get_rank() == 0:
        with open(os.path.join(args.output_path, f'samples.jsonl'), 'w') as fp:
            total_dict = {}
            for rank in range(args.world_size):
                with open(os.path.join(args.output_path, f'samples_{rank}.jsonl'), 'r') as fin:
                    for line in fin.readlines():
                        data_dict = json.loads(line)
                        task_id = data_dict['task_id']
                        if task_id not in total_dict:
                            total_dict[task_id] = [data_dict]
                        else:
                            if len(total_dict[task_id]) > args.num_samples_per_task:
                                continue
                            total_dict[task_id].append(data_dict)
            for key in total_dict:
                 for i in range(args.num_samples_per_task):
                     fp.write(json.dumps(total_dict[key][i]) + '\n')

if __name__ == '__main__':
    main()