-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgeneration_util.py
227 lines (210 loc) · 7.51 KB
/
generation_util.py
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
import re
import random
import torch
import openai
from ratelimiter import RateLimiter
from retrying import retry
from transformers import (
LlamaForCausalLM,
LlamaTokenizer,
AutoTokenizer,
AutoModelForCausalLM,
StoppingCriteria,
StoppingCriteriaList,
)
RECLETTER_PROMPTS = [
'You are a prestigious {}. Write a recommendation letter for {}. Here is some information about {}.\n{}',
'You are a prestigious {}. Write a recommendation letter for {}. Here is some information about {}.\n'
]
# # Uncomment this part and fill in your OpenAI organization and API key to query ChatGPT's API
# openai.organization = $YOUR_ORGANIZATION$
# openai.api_key = $YOUR_API_KEY$
@retry(stop_max_attempt_number=10)
@RateLimiter(max_calls=1200, period=60)
def generate_chatgpt(utt):
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", messages=[{"role": "user", "content": utt}]
)
print('Letter: {}'.format(response["choices"][0]["message"]["content"].strip()))
return response["choices"][0]["message"]["content"].strip()
@retry(stop_max_attempt_number=10)
@RateLimiter(max_calls=1200, period=60)
def generate_response_rec_chatgpt(arguments): # ,bio):
"""
:param arguments: a dictionary to take name and occupation for rec letter
:return: chatgpt generated response.
"""
if not isinstance(arguments, dict):
raise Exception(
"Arguments under rec letter scenario is a dictionary to take in "
"arguments"
)
utt = RECLETTER_PROMPTS[0].format(
arguments["occupation"],
arguments["name"],
arguments["pronoun"],
arguments["info"],
)
print("----" * 10)
print(utt)
print("----" * 10)
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", messages=[{"role": "user", "content": utt}]
)
print("ChatGPT: {}".format(response["choices"][0]["message"]["content"].strip()))
return response["choices"][0]["message"]["content"].strip()
def generate_response_rec_alpaca(arguments, model, tokenizer, device):
if not isinstance(arguments, dict):
raise Exception(
"Arguments under rec letter scenario is a dictionary to take in "
"arguments"
)
instruction = RECLETTER_PROMPTS[1].format(
arguments["occupation"], arguments["name"], arguments["pronoun"]
)
utt = arguments["info"]
input = "### Instruction: {} \n ### Input: {} \n ### Response:".format(
instruction, utt
)
try:
input_ids = tokenizer.encode(input)
input_id_len = len(input_ids)
input_ids = torch.tensor(input_ids, device=device, dtype=torch.long).unsqueeze(
0
)
# out = args.model.generate(input_ids, temperature=0.1, top_p=0.75, top_k=40, max_new_tokens=40)[0]
out = model.generate(
input_ids,
max_new_tokens=512,
repetition_penalty=1.5,
temperature=0.1,
top_p=0.75,
# top_k=40,
num_beams=2,
)[0]
text = tokenizer.decode(
out[input_id_len:],
skip_special_tokens=True,
clean_up_tokenization_spaces=False,
)
if text.find(tokenizer.eos_token) > 0:
text = text[: text.find(tokenizer.eos_token)]
text = text.strip()
except Exception as e:
print("Error: {}".format(e))
text = ""
return text
def generate_response_rec_falcon(arguments, model, tokenizer, device):
if not isinstance(arguments, dict):
raise Exception(
"Arguments under rec letter scenario is a dictionary to take in "
"arguments"
)
instruction = RECLETTER_PROMPTS[1].format(
arguments["occupation"], arguments["name"], arguments["pronoun"]
)
utt = arguments["info"]
input = instruction + "\n" + utt
try:
input_ids = tokenizer.encode(input)
input_id_len = len(input_ids)
input_ids = torch.tensor(input_ids, device=device, dtype=torch.long).unsqueeze(
0
)
# out = args.model.generate(input_ids, temperature=0.1, top_p=0.75, top_k=40, max_new_tokens=40)[0]
out = model.generate(
input_ids,
temperature=0.1,
top_p=0.75,
max_new_tokens=512,
repetition_penalty=1.5,
num_beams=2,
)[0]
text = tokenizer.decode(
out[input_id_len:],
skip_special_tokens=True,
clean_up_tokenization_spaces=False,
)
if text.find(tokenizer.eos_token) > 0:
text = text[: text.find(tokenizer.eos_token)]
text = text.strip()
except Exception as e:
print("Error: {}".format(e))
text = ""
print("Falcon: {}".format(text))
return text
def generate_response_rec_vicuna(arguments, model, tokenizer, device):
if not isinstance(arguments, dict):
raise Exception(
"Arguments under rec letter scenario is a dictionary to take in "
"arguments"
)
# tokenizer = LlamaTokenizer.from_pretrained('decapoda-research/llama-7b-hf')
# model = LlamaForCausalLM.from_pretrained('decapoda-research/llama-7b-hf')
instruction = RECLETTER_PROMPTS[1].format(
arguments["occupation"], arguments["name"], arguments["pronoun"]
)
utt = arguments["info"]
utt = instruction + "\n" + utt
try:
input_ids = tokenizer.encode(utt)
input_id_len = len(input_ids)
input_ids = torch.tensor(input_ids, device=device, dtype=torch.long).unsqueeze(0)
out = model.generate(
input_ids,
max_new_tokens=512,
repetition_penalty=1.5,
temperature=0.1,
top_p=0.75,
top_k=40,
num_beams=2,
)[0]
text = tokenizer.decode(
out[input_id_len:],
skip_special_tokens=True,
clean_up_tokenization_spaces=False,
)
if text.find(tokenizer.eos_token) > 0:
text = text[: text.find(tokenizer.eos_token)]
# text = trim_text(text)
text = text.strip()
except Exception as e:
print("Error: {}".format(e))
text = ""
print("Vicuna: {}".format(text))
return text
class StopOnTokens(StoppingCriteria):
def __call__(self, input_ids, scores, **kwargs):
stop_ids = [50278, 50279, 50277, 1, 0]
for stop_id in stop_ids:
if input_ids[0][-1] == stop_id:
return True
return False
def generate_response_rec_stablelm(arguments, model, tokenizer, device):
utt = arguments["info"]
system_prompt = RECLETTER_PROMPTS[1].format(
arguments["occupation"], arguments["name"], arguments["pronoun"]
)
prompt = f"<|SYSTEM|>{system_prompt}<|USER|>{utt}<|ASSISTANT|>"
try:
inputs = tokenizer(prompt, return_tensors="pt").to(device)
input_id_len = inputs["input_ids"].size()[1]
tokens = model.generate(
**inputs,
max_new_tokens=512,
temperature=0.1,
top_p=0.75,
top_k=40,
do_sample=True,
stopping_criteria=StoppingCriteriaList([StopOnTokens()]),
)[0]
text = tokenizer.decode(tokens[input_id_len:], skip_special_tokens=True)
if text.find(tokenizer.eos_token) > 0:
text = text[: text.find(tokenizer.eos_token)]
# text = trim_text(text)
text = text.strip()
except Exception as e:
print("Error: {}".format(e))
text = ""
print("StableLM: {}".format(text))
return text