prompt.py 10.9 KB
Newer Older
Jared Casper's avatar
Jared Casper committed
1
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
zihanl's avatar
zihanl committed
2

zihanl's avatar
zihanl committed
3
4
"""Prompting the pretrained language model to generate knowledge/response"""

zihanl's avatar
zihanl committed
5
6
import json
import torch
zihanl's avatar
zihanl committed
7
import requests
zihanl's avatar
zihanl committed
8
from nltk import word_tokenize
xingjinliang's avatar
xingjinliang committed
9
10
11
from megatron.training import get_args
from megatron.training import print_rank_0
from megatron.training import get_tokenizer
12
from megatron.core import mpu
xingjinliang's avatar
xingjinliang committed
13
from megatron.legacy.model import GPTModel
zihanl's avatar
zihanl committed
14
from megatron.training import get_model
xingjinliang's avatar
xingjinliang committed
15
16
17
from megatron.training.checkpointing import load_checkpoint
from megatron.training.initialize import initialize_megatron
from megatron.inference.text_generation import generate_and_post_process
zihanl's avatar
zihanl committed
18
19


zihanl's avatar
zihanl committed
20
def call_model_api(inputs, tokens_to_generate):
zihanl's avatar
zihanl committed
21
    """Calling the model api to get the output generations"""
zihanl's avatar
zihanl committed
22
23
24
25
26
27
28
29
30
    
    args = get_args()

    # The following is an example of using the Megatron API
    # You can also implement your own API function to place this part
    headers = {'Content-Type': 'application/json; charset=UTF-8'}
    data = {"prompts": [inputs], "tokens_to_generate": tokens_to_generate, "top_k": 1}
    data_json = json.dumps(data)
    outputs = requests.put(args.megatron_api_url, headers=headers, data=data_json).json()["text"][0]
zihanl's avatar
zihanl committed
31

zihanl's avatar
zihanl committed
32
33
34
35
36
    input_len = len(inputs)
    outputs = outputs[input_len:]
    outputs = outputs.split("\n")[0].strip()
    
    return outputs
zihanl's avatar
zihanl committed
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


def read_prompts(prompt_path, prompt_type, n_example):
    """Read prompt data"""

    if prompt_type == "knowledge":
        # prompts for the knowledge generation
        prompt_examples_dict = {}
        # read prompt_path
        with open(prompt_path, "r") as f:
            for i, line in enumerate(f):
                line = line.strip()
                line_dict = json.loads(line)
                key = list(line_dict.keys())[0]
                
                if key not in prompt_examples_dict:
                    prompt_examples = line_dict[key]
                    prompt = ""
                    for instance in prompt_examples:
                        instance = instance.strip()
                        prompt += instance + " \n"
                    prompt_examples_dict[key] = prompt

        return prompt_examples_dict

    else:
        # prompts for the response generation
        # read prompt_path
        prompt = ""
        with open(prompt_path, "r") as f:
            prompt_examples = f.readlines()
            prompt_examples = prompt_examples[:n_example]
            for instance in prompt_examples:
                instance = instance.strip()
                prompt += instance + " \n"

        return prompt


def generate_samples_by_calling_api():
    """ Generate outputs by calling"""
    args = get_args()
    assert args.prompt_type in ["knowledge", "response"], \
                "Please input a correct prompt type!"

    if args.prompt_type == "knowledge":
        # read knowledge generation prompts
        knwl_gen_prompt_dict = read_prompts(
            args.prompt_file, args.prompt_type, args.num_prompt_examples)
        
    else:
        resp_gen_prompt = read_prompts(
            args.prompt_file, args.prompt_type, args.num_prompt_examples)

    # read the test data
    fname = open(args.sample_input_file, "r")
    test_sample_list = fname.readlines()
    # create output file
zihanl's avatar
zihanl committed
95
    fname_out = open(args.sample_output_file, "w")
zihanl's avatar
zihanl committed
96
97
98
99

    # call the api to get the output generations
    for test_sample in test_sample_list:
        test_sample = test_sample.strip()
zihanl's avatar
zihanl committed
100
        splits = test_sample.split("\t")
zihanl's avatar
zihanl committed
101
102
103
104
        topic = splits[0]

        # prepare the inputs for the api
        if args.prompt_type == "knowledge":
zihanl's avatar
zihanl committed
105
            ## inputs = prompt + current test
zihanl's avatar
zihanl committed
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
            # get the prompt
            turns = splits[1].split(" [SEP] ")
            last_turn = turns[-1]
            key = topic + " " + last_turn
            inputs = knwl_gen_prompt_dict[key]

            # add current test
            inputs += "( " + last_turn + " ) " + topic + " =>"

        else:
            # inputs = prompt + current test
            # get the prompt
            inputs = resp_gen_prompt

            # add current test
            turns = splits[1].split(" [SEP] ")
            knowledge = splits[2]
            last_turn = turns[-1]
            last_turn = " ".join(word_tokenize(last_turn))
            knowledge = " ".join(word_tokenize(knowledge))
            knowledge = knowledge.strip()
            last_turn = last_turn.strip()
            inputs += "Topic: " + topic + ". "
            inputs += "User says: " + last_turn + " "
            inputs += "We know that: " + knowledge + " "
            inputs += "System replies:"

        # get the output generations from the api, 
        # and write to the output file
zihanl's avatar
zihanl committed
135
        generations = call_model_api(inputs, args.out_seq_length)
zihanl's avatar
zihanl committed
136
137
138
139
140
141
142
        fname_out.write(generations)
        fname_out.write("\n")

    fname.close()
    fname_out.close()


zihanl's avatar
zihanl committed
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def model_provider(pre_process=True, post_process=True):
    """Build the model."""

    print_rank_0('building GPT model ...')
    model = GPTModel(
        num_tokentypes=0,
        parallel_output=True,
        pre_process=pre_process,
        post_process=post_process
    )
    return model


def generate_samples_by_prompting_input_from_file(model):
zihanl's avatar
zihanl committed
157
158
159
    """Prompt a pretrained language model to generate knowledge/response"""
    
    # get tokenizer
zihanl's avatar
zihanl committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
    args = get_args()
    tokenizer = get_tokenizer()

    # Read the sample file and open the output file.
    assert args.sample_input_file is not None, \
        'sample input file is not provided.'
    if mpu.is_pipeline_first_stage() and mpu.get_tensor_model_parallel_rank() == 0:
        fname = open(args.sample_input_file, "r")
        all_raw_text = fname.readlines()
        input_count = len(all_raw_text)
        if args.sample_output_file is None:
            sample_output_file = args.sample_input_file + ".out"
            print('`sample-output-file` not specified, setting '
                    'it to {}'.format(sample_output_file))
        else:
            sample_output_file = args.sample_output_file

        fname_out = open(sample_output_file, "w")

zihanl's avatar
zihanl committed
179
180
181
182
    # only two prompt types (i.e., knowledge and response) are allowed
    assert args.prompt_type in ["knowledge", "response"], \
                "Please input a correct prompt type!"

zihanl's avatar
zihanl committed
183
    # Read the prompt file
zihanl's avatar
zihanl committed
184
185
    if args.prompt_type == "knowledge":
        # read the prompts for the knowledge generation
zihanl's avatar
zihanl committed
186
187
188
189
190
191
        prompt_examples_dict = {}
        with open(args.prompt_file, "r") as f:
            for i, line in enumerate(f):
                line = line.strip()
                line_dict = json.loads(line)
                key = list(line_dict.keys())[0]
zihanl's avatar
zihanl committed
192
193

                # get the prompt examples based on the key
zihanl's avatar
zihanl committed
194
195
196
197
198
199
200
201
202
                if key not in prompt_examples_dict:
                    prompt_examples = line_dict[key]
                    prompt = ""
                    for instance in prompt_examples:
                        instance = instance.strip()
                        prompt += instance + " \n"
                    prompt_examples_dict[key] = prompt

    else:
zihanl's avatar
zihanl committed
203
        # read the prompts for the response generation
zihanl's avatar
zihanl committed
204
        # prompts are fixed for all test samples
zihanl's avatar
zihanl committed
205
206
207
208
209
210
211
212
213
        with open(args.prompt_file, "r") as f:
            prompt_examples = f.readlines()
            prompt_examples = prompt_examples[:args.num_prompt_examples]

            prompt = ""
            for instance in prompt_examples:
                instance = instance.strip()
                prompt += instance + " \n"

zihanl's avatar
zihanl committed
214
    input_pos = 0
zihanl's avatar
zihanl committed
215
    model.eval()
zihanl's avatar
zihanl committed
216
    # perform prompting
zihanl's avatar
zihanl committed
217
218
219
220
221
222
223
224
    with torch.no_grad():
        while True:
            raw_text_len = 0
            if mpu.is_pipeline_first_stage() \
               and mpu.get_tensor_model_parallel_rank() == 0:
                input_str = all_raw_text[input_pos]
                input_str = input_str.strip()
                splits = input_str.split("\t")
zihanl's avatar
zihanl committed
225
                topic = splits[0]
zihanl's avatar
zihanl committed
226

zihanl's avatar
zihanl committed
227
228
                if args.prompt_type == "knowledge":
                    # first add the prompt into the raw_text
zihanl's avatar
zihanl committed
229
230
231
232
233
                    turns = splits[1].split(" [SEP] ")
                    last_turn = turns[-1]
                    key = topic + " " + last_turn
                    raw_text = prompt_examples_dict[key]

zihanl's avatar
zihanl committed
234
                    # construct inputs for knowledge generation
zihanl's avatar
zihanl committed
235
                    # then add the constructed inputs into the raw_text
zihanl's avatar
zihanl committed
236
                    raw_text += "( " + last_turn + " ) " + topic + " =>"
zihanl's avatar
zihanl committed
237
238
                
                else:
zihanl's avatar
zihanl committed
239
240
241
                    # first add the prompt into the raw_text
                    raw_text = prompt

zihanl's avatar
zihanl committed
242
                    # construct inputs for response generation
zihanl's avatar
zihanl committed
243
                    # then add the constructed inputs into the raw_text
zihanl's avatar
zihanl committed
244
245
246
                    turns = splits[1].split(" [SEP] ")
                    knowledge = splits[2]
                    last_turn = turns[-1]
root's avatar
root committed
247
248
                    last_turn = " ".join(word_tokenize(last_turn))
                    knowledge = " ".join(word_tokenize(knowledge))
zihanl's avatar
zihanl committed
249
250
251
252
253
254
255
256
257
258
259
                    knowledge = knowledge.strip()
                    last_turn = last_turn.strip()
                    raw_text += "Topic: " + topic + ". "
                    raw_text += "User says: " + last_turn + " "
                    raw_text += "We know that: " + knowledge + " "
                    raw_text += "System replies:"

                input_pos += 1
                raw_text_len = len(raw_text)
            
            else:
zihanl's avatar
zihanl committed
260
                raw_text = "EMPTY TEXT"
zihanl's avatar
zihanl committed
261
262
263
264

            if input_pos % 100 == 0:
                print_rank_0("input_pos: %d" % input_pos)

zihanl's avatar
zihanl committed
265
266
267
268
269
270
271
            outputs = generate_and_post_process(
                        model=model, 
                        prompts=[raw_text], 
                        tokens_to_generate=args.out_seq_length,
                        top_k_sampling=1)
            prompts_plus_generations = outputs[0]
            prompts_plus_generations = prompts_plus_generations[0]
zihanl's avatar
zihanl committed
272

zihanl's avatar
zihanl committed
273
            # write the generated output to the output file
zihanl's avatar
zihanl committed
274
275
            if mpu.get_tensor_model_parallel_rank() == 0:
                if mpu.is_pipeline_first_stage():
zihanl's avatar
zihanl committed
276
277
278
279
280

                    generations = prompts_plus_generations[raw_text_len:]
                    generations = generations.split("\n")[0]
                    generations = generations.strip()
                    fname_out.write(generations)
zihanl's avatar
zihanl committed
281
282
283
284
285
286
287
288
289
290
                    fname_out.write("\n")

            raw_text = None
            if input_pos == input_count:
                return


def main():

    args = get_args()
zihanl's avatar
zihanl committed
291
    if args.api_prompt:
zihanl's avatar
zihanl committed
292
293
294
295
        # obtain the generations by calling the api
        generate_samples_by_calling_api()
        return

zihanl's avatar
zihanl committed
296
297
298
299
300
    if args.num_layers_per_virtual_pipeline_stage is not None:
        print("Interleaved pipeline schedule is not yet supported for text generation.")
        exit()

    # Set up model and load checkpoint.
zihanl's avatar
zihanl committed
301
    model = get_model(model_provider, wrap_with_ddp=False)
zihanl's avatar
zihanl committed
302
303
304
305
306
307
    if args.load is not None:
        _ = load_checkpoint(model, None, None)

    assert len(model) == 1, "Above condition should have caught this"
    model = model[0]

zihanl's avatar
zihanl committed
308
    # perform the prompting
zihanl's avatar
zihanl committed
309
    generate_samples_by_prompting_input_from_file(model)