Spaces:
Runtime error
Runtime error
delete some files and retain necesary files.
Browse files- build_openprompt.py +0 -56
- central_finetuning.py +0 -0
- corenlp_openie.py +0 -104
- data/1k.csv +0 -0
- forbidden.py +0 -256
- generation_test.py +0 -101
- gpt2-sentiment.ipynb +0 -505
- gpt2_generation.py +1 -15
- gpt_api.py +0 -27
- monitor.sh +0 -15
- rouge/README.md +0 -161
- rouge/app.py +0 -6
- rouge/requirements.txt +0 -4
- rouge/rouge.py +0 -158
- sft.py +0 -81
- trible.py +0 -56
build_openprompt.py
DELETED
@@ -1,56 +0,0 @@
|
|
1 |
-
import csv
|
2 |
-
import pandas as pd
|
3 |
-
import json
|
4 |
-
import random
|
5 |
-
|
6 |
-
from torch.nn.utils.rnn import pad_sequence
|
7 |
-
|
8 |
-
|
9 |
-
from tqdm import tqdm
|
10 |
-
|
11 |
-
|
12 |
-
samples = {
|
13 |
-
"x": [],
|
14 |
-
"y": [],
|
15 |
-
}
|
16 |
-
little = False
|
17 |
-
all_loaded_sample = 400000
|
18 |
-
normal = True # 全部读取,非采样方式
|
19 |
-
s_pro = all_loaded_sample / 1e+7
|
20 |
-
# 读取概率
|
21 |
-
with open("./data/cleaned_oie_prompts.csv") as f:
|
22 |
-
csv_reader = csv.DictReader(f)
|
23 |
-
process_reader = tqdm(enumerate(csv_reader))
|
24 |
-
for row_number, row in process_reader:
|
25 |
-
num_samples = len(samples['x'])
|
26 |
-
process_reader.set_description(f"got data num: {num_samples}")
|
27 |
-
if not normal:
|
28 |
-
if random.uniform(0, 1) > s_pro:
|
29 |
-
continue
|
30 |
-
if len(samples["x"]) > all_loaded_sample:
|
31 |
-
break
|
32 |
-
else:
|
33 |
-
if row['prompt'] == "":
|
34 |
-
continue
|
35 |
-
if little:
|
36 |
-
if len(samples["x"]) > 100:
|
37 |
-
break
|
38 |
-
|
39 |
-
datum = row
|
40 |
-
# prompt = datum['prompt']
|
41 |
-
prompt = ",".join(eval(datum['raw_data'])['modifiers'])
|
42 |
-
if not normal:
|
43 |
-
modifiers = eval(datum['raw_data'])['modifiers']
|
44 |
-
if len(modifiers) < 4:
|
45 |
-
continue
|
46 |
-
label = prompt
|
47 |
-
x = prompt
|
48 |
-
# 小文本到大文本,因此x更小,同时x按照6:3:1的比例分配
|
49 |
-
|
50 |
-
samples["x"].append(x)
|
51 |
-
samples["y"].append(label)
|
52 |
-
|
53 |
-
|
54 |
-
with open(f"./data/dataset_openprompt.json", "w") as f:
|
55 |
-
json.dump(samples, f, indent=4, ensure_ascii=False)
|
56 |
-
print("*"*40, f"save {num_samples} train samples done.", "with little" if little else "", "*"*40)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
central_finetuning.py
DELETED
File without changes
|
corenlp_openie.py
DELETED
@@ -1,104 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import re
|
3 |
-
import csv
|
4 |
-
import json
|
5 |
-
import jsonlines
|
6 |
-
from tqdm import tqdm
|
7 |
-
from stanfordcorenlp import StanfordCoreNLP
|
8 |
-
|
9 |
-
import concurrent.futures
|
10 |
-
|
11 |
-
|
12 |
-
nlp = StanfordCoreNLP('./stanford-corenlp-4.5.5')
|
13 |
-
|
14 |
-
SOURCE_FILE = "./data/raw_oie_source.jsonl"
|
15 |
-
|
16 |
-
def oie_extract(sentence):
|
17 |
-
output = nlp.annotate(sentence, properties={
|
18 |
-
'annotators': 'tokenize, ssplit, pos, depparse, parse, openie',
|
19 |
-
'outputFormat': 'json'
|
20 |
-
})
|
21 |
-
try:
|
22 |
-
data = json.loads(output)
|
23 |
-
sentences_ie = [i['openie'] for i in data['sentences'] if len(i['openie']) > 0]
|
24 |
-
oie_result = [max([sub["object"] for sub in sen], key=len) for sen in sentences_ie]
|
25 |
-
central_result = [sen[0]["subject"] for sen in sentences_ie][1:]
|
26 |
-
|
27 |
-
result = central_result + oie_result
|
28 |
-
result = ",".join(result)
|
29 |
-
except Exception as e:
|
30 |
-
print(f"An error occurred output: {output}")
|
31 |
-
result = ""
|
32 |
-
return result
|
33 |
-
|
34 |
-
def process_sentence(sentence):
|
35 |
-
row_data = {'raw_data': {'modifiers': sentence.split(".")}, 'prompt': ''}
|
36 |
-
oie_prompt = oie_extract(sentence)
|
37 |
-
row_data['prompt'] = oie_prompt
|
38 |
-
return row_data
|
39 |
-
|
40 |
-
def get_sentences(path):
|
41 |
-
if not os.path.exists(SOURCE_FILE):
|
42 |
-
raise FileNotFoundError(f"{SOURCE_FILE} not found.")
|
43 |
-
|
44 |
-
with jsonlines.open(path) as reader:
|
45 |
-
for obj in reader:
|
46 |
-
yield obj['description']
|
47 |
-
|
48 |
-
def main():
|
49 |
-
file_name = "./data/oie_prompts.csv"
|
50 |
-
fieldnames = ['prompt', 'raw_data']
|
51 |
-
csvfile = open(file_name, 'w', newline='', encoding='utf-8')
|
52 |
-
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
|
53 |
-
writer.writeheader()
|
54 |
-
|
55 |
-
# for sentence in tqdm(get_sentences(SOURCE_FILE), desc="extracting oie prompts"):
|
56 |
-
# row_data = {'raw_data': {'modifiers': sentence.split(".")}, "prompt": ""}
|
57 |
-
# oie_prompt = oie_extract(sentence)
|
58 |
-
# row_data['prompt'] = oie_prompt
|
59 |
-
# writer.writerow(row_data)
|
60 |
-
|
61 |
-
with concurrent.futures.ThreadPoolExecutor() as executor:
|
62 |
-
results = list(tqdm(executor.map(process_sentence, get_sentences(SOURCE_FILE)),
|
63 |
-
total=len(list(get_sentences(SOURCE_FILE))),
|
64 |
-
desc="extracting oie prompts"))
|
65 |
-
|
66 |
-
for result in results:
|
67 |
-
writer.writerow(result)
|
68 |
-
|
69 |
-
def remove_chinese(text):
|
70 |
-
pattern = re.compile(r'[\u4e00-\u9fa5]')
|
71 |
-
result = re.sub(pattern, '', text)
|
72 |
-
return result
|
73 |
-
|
74 |
-
|
75 |
-
def remove_special_chars(text):
|
76 |
-
pattern = re.compile(r'[^\w\s.,]')
|
77 |
-
result = re.sub(pattern, '', text)
|
78 |
-
return result
|
79 |
-
|
80 |
-
def cleaning_dataset():
|
81 |
-
"""只清理oie_prompts.csv,保存在cleaned_oie_prompts.csv中"""
|
82 |
-
file_name = "./data/cleaned_oie_prompts.csv"
|
83 |
-
fieldnames = ['prompt', 'raw_data']
|
84 |
-
csvfile = open(file_name, 'w', newline='', encoding='utf-8')
|
85 |
-
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
|
86 |
-
writer.writeheader()
|
87 |
-
with open("./data/oie_prompts.csv") as f:
|
88 |
-
csv_reader = csv.DictReader(f)
|
89 |
-
process_reader = tqdm(enumerate(csv_reader))
|
90 |
-
for row_number, row in process_reader:
|
91 |
-
datum = row
|
92 |
-
|
93 |
-
cleaned_prompts = remove_special_chars(remove_chinese(datum['prompt']))
|
94 |
-
joined_modifiers = ",".join(eval(datum['raw_data'])['modifiers'])
|
95 |
-
cleaned_modifiers = remove_special_chars(remove_chinese(joined_modifiers))
|
96 |
-
row_data = {'raw_data': {'modifiers': cleaned_modifiers.split(",")}, "prompt": cleaned_prompts}
|
97 |
-
writer.writerow(row_data)
|
98 |
-
|
99 |
-
|
100 |
-
if __name__ == '__main__':
|
101 |
-
# main()
|
102 |
-
cleaning_dataset()
|
103 |
-
|
104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/1k.csv
DELETED
The diff for this file is too large to render.
See raw diff
|
|
forbidden.py
DELETED
@@ -1,256 +0,0 @@
|
|
1 |
-
FORBIDDEN_NOUN = [
|
2 |
-
"woman",
|
3 |
-
"women",
|
4 |
-
"female",
|
5 |
-
"man",
|
6 |
-
"men",
|
7 |
-
"girl",
|
8 |
-
"boy",
|
9 |
-
"person",
|
10 |
-
"people",
|
11 |
-
"individual",
|
12 |
-
"lady",
|
13 |
-
"gentleman",
|
14 |
-
"child",
|
15 |
-
"children",
|
16 |
-
"adult",
|
17 |
-
"elderly",
|
18 |
-
"elder",
|
19 |
-
"youth",
|
20 |
-
"teenager",
|
21 |
-
"toddler",
|
22 |
-
"infant",
|
23 |
-
"baby",
|
24 |
-
"parent",
|
25 |
-
"mother",
|
26 |
-
"father",
|
27 |
-
"grandparent",
|
28 |
-
"grandmother",
|
29 |
-
"grandfather",
|
30 |
-
"sister",
|
31 |
-
"brother",
|
32 |
-
"aunt",
|
33 |
-
"uncle",
|
34 |
-
"cousin",
|
35 |
-
"niece",
|
36 |
-
"nephew",
|
37 |
-
"friend",
|
38 |
-
"neighbor",
|
39 |
-
"colleague",
|
40 |
-
"teacher",
|
41 |
-
"student",
|
42 |
-
"doctor",
|
43 |
-
"nurse",
|
44 |
-
"police",
|
45 |
-
"firefighter",
|
46 |
-
"soldier",
|
47 |
-
"veteran",
|
48 |
-
"citizen",
|
49 |
-
"resident",
|
50 |
-
"immigrant",
|
51 |
-
"refugee",
|
52 |
-
"homeless",
|
53 |
-
"disabled",
|
54 |
-
"blind",
|
55 |
-
"deaf",
|
56 |
-
"mute",
|
57 |
-
"gay",
|
58 |
-
"lesbian",
|
59 |
-
"bisexual",
|
60 |
-
"transgender",
|
61 |
-
"queer",
|
62 |
-
"nonbinary",
|
63 |
-
"heterosexual",
|
64 |
-
"homosexual",
|
65 |
-
"marriage",
|
66 |
-
"family",
|
67 |
-
"relationship",
|
68 |
-
"love",
|
69 |
-
"diversity",
|
70 |
-
"equality",
|
71 |
-
"inclusion",
|
72 |
-
"discrimination",
|
73 |
-
"stereotype",
|
74 |
-
"prejudice",
|
75 |
-
"bias",
|
76 |
-
"harassment",
|
77 |
-
"abuse",
|
78 |
-
"violence",
|
79 |
-
"oppression",
|
80 |
-
"racism",
|
81 |
-
"sexism",
|
82 |
-
"ageism",
|
83 |
-
"ableism",
|
84 |
-
"homophobia",
|
85 |
-
"transphobia",
|
86 |
-
"xenophobia",
|
87 |
-
"bigotry",
|
88 |
-
"hate",
|
89 |
-
"offensive",
|
90 |
-
"slur",
|
91 |
-
"taboo",
|
92 |
-
"profanity",
|
93 |
-
"obscenity",
|
94 |
-
"eyes",
|
95 |
-
"ear",
|
96 |
-
"nose",
|
97 |
-
"mouth",
|
98 |
-
"tongue",
|
99 |
-
"teeth",
|
100 |
-
"lips",
|
101 |
-
"face",
|
102 |
-
"cheek",
|
103 |
-
"chin",
|
104 |
-
"neck",
|
105 |
-
"shoulder",
|
106 |
-
"arm",
|
107 |
-
"elbow",
|
108 |
-
"wrist",
|
109 |
-
"hand",
|
110 |
-
"finger",
|
111 |
-
"thumb",
|
112 |
-
"chest",
|
113 |
-
"breast",
|
114 |
-
"heart",
|
115 |
-
"stomach",
|
116 |
-
"belly",
|
117 |
-
"back",
|
118 |
-
"waist",
|
119 |
-
"hip",
|
120 |
-
"leg",
|
121 |
-
"thigh",
|
122 |
-
"knee",
|
123 |
-
"ankle",
|
124 |
-
"foot",
|
125 |
-
"toe",
|
126 |
-
"hair",
|
127 |
-
"head",
|
128 |
-
"brain",
|
129 |
-
"skin",
|
130 |
-
"bone",
|
131 |
-
"muscle",
|
132 |
-
"nail",
|
133 |
-
"cyberpunk",
|
134 |
-
"robot",
|
135 |
-
"android",
|
136 |
-
"cyborg",
|
137 |
-
"AI",
|
138 |
-
"artificial intelligence",
|
139 |
-
"virtual reality",
|
140 |
-
"augmentation",
|
141 |
-
"implant",
|
142 |
-
"nanotechnology",
|
143 |
-
"hacker",
|
144 |
-
"data",
|
145 |
-
"cyberspace",
|
146 |
-
"netrunner",
|
147 |
-
"neural",
|
148 |
-
"circuit",
|
149 |
-
"chip",
|
150 |
-
"droid",
|
151 |
-
"mecha",
|
152 |
-
"synthetic",
|
153 |
-
"cyberware",
|
154 |
-
"cybersuit",
|
155 |
-
"biomechanical",
|
156 |
-
"exoskeleton",
|
157 |
-
"cybernetics",
|
158 |
-
"brain-computer interface",
|
159 |
-
"genetic engineering",
|
160 |
-
"bionic",
|
161 |
-
"hovercar",
|
162 |
-
"megacorporation",
|
163 |
-
"dystopia",
|
164 |
-
"cybercrime",
|
165 |
-
"virtual world",
|
166 |
-
"neon",
|
167 |
-
"hologram",
|
168 |
-
"future",
|
169 |
-
"tech",
|
170 |
-
"cyber",
|
171 |
-
"machine",
|
172 |
-
"computer",
|
173 |
-
"data",
|
174 |
-
"code",
|
175 |
-
"interface",
|
176 |
-
"hack",
|
177 |
-
"mod",
|
178 |
-
"upgrade",
|
179 |
-
"jacking in",
|
180 |
-
"cyberdeck",
|
181 |
-
"cybersuit",
|
182 |
-
"implant",
|
183 |
-
"augment",
|
184 |
-
"cybersurgery",
|
185 |
-
"bone",
|
186 |
-
"throne",
|
187 |
-
"crown",
|
188 |
-
"magic",
|
189 |
-
"wizard",
|
190 |
-
"witch",
|
191 |
-
"sorcerer",
|
192 |
-
"dragon",
|
193 |
-
"elf",
|
194 |
-
"dwarf",
|
195 |
-
"goblin",
|
196 |
-
"fairy",
|
197 |
-
"spell",
|
198 |
-
"enchantment",
|
199 |
-
"myth",
|
200 |
-
"legend",
|
201 |
-
"quest",
|
202 |
-
"adventure",
|
203 |
-
"sword",
|
204 |
-
"shield",
|
205 |
-
"armor",
|
206 |
-
"wand",
|
207 |
-
"staff",
|
208 |
-
"amulet",
|
209 |
-
"scroll",
|
210 |
-
"talisman",
|
211 |
-
"beast",
|
212 |
-
"creature",
|
213 |
-
"monster",
|
214 |
-
"vampire",
|
215 |
-
"werewolf",
|
216 |
-
"giant",
|
217 |
-
"gargoyle",
|
218 |
-
"phoenix",
|
219 |
-
"unicorn",
|
220 |
-
"mermaid",
|
221 |
-
"witchcraft",
|
222 |
-
"alchemy",
|
223 |
-
"mystic",
|
224 |
-
"divination",
|
225 |
-
"fantasy",
|
226 |
-
"realm",
|
227 |
-
"magician",
|
228 |
-
"sorcery",
|
229 |
-
"enchanted",
|
230 |
-
"fabled",
|
231 |
-
"lore",
|
232 |
-
"mythical",
|
233 |
-
"epic",
|
234 |
-
"fate",
|
235 |
-
"destiny",
|
236 |
-
"astronomy",
|
237 |
-
"geology",
|
238 |
-
"orchestra",
|
239 |
-
"zoology",
|
240 |
-
"philosophy",
|
241 |
-
"archaeology",
|
242 |
-
"anthropology",
|
243 |
-
"meteorology",
|
244 |
-
"botany",
|
245 |
-
"sociology",
|
246 |
-
"psychology",
|
247 |
-
"linguistics",
|
248 |
-
"ethics",
|
249 |
-
"mythology",
|
250 |
-
"astronautics",
|
251 |
-
"entomology",
|
252 |
-
"ecology",
|
253 |
-
"nuclear physics",
|
254 |
-
"oceanography",
|
255 |
-
"literature"
|
256 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
generation_test.py
DELETED
@@ -1,101 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import spacy
|
3 |
-
from accelerate import PartialState
|
4 |
-
from accelerate.utils import set_seed
|
5 |
-
|
6 |
-
from gpt2_generation import Translator
|
7 |
-
from gpt2_generation import generate_prompt, MODEL_CLASSES
|
8 |
-
|
9 |
-
os.environ["http_proxy"] = "http://127.0.0.1:7890"
|
10 |
-
os.environ["https_proxy"] = "http://127.0.0.1:7890"
|
11 |
-
|
12 |
-
|
13 |
-
path_for_model = "./output/gpt2_openprompt/checkpoint-4500"
|
14 |
-
|
15 |
-
args = {
|
16 |
-
"model_type": "gpt2",
|
17 |
-
"model_name_or_path": path_for_model,
|
18 |
-
"length": 80,
|
19 |
-
"length_penalty": 1.2,
|
20 |
-
"stop_token": None,
|
21 |
-
"temperature": 1.0,
|
22 |
-
"repetition_penalty": 1.2,
|
23 |
-
"k": 3,
|
24 |
-
"p": 0.9,
|
25 |
-
"prefix": "",
|
26 |
-
"padding_text": "",
|
27 |
-
"xlm_language": "",
|
28 |
-
"seed": 42,
|
29 |
-
"use_cpu": False,
|
30 |
-
"num_return_sequences": 4,
|
31 |
-
"fp16": False,
|
32 |
-
"jit": False,
|
33 |
-
}
|
34 |
-
|
35 |
-
distributed_state = PartialState(cpu=args["use_cpu"])
|
36 |
-
|
37 |
-
if args["seed"] is not None:
|
38 |
-
set_seed(args["seed"])
|
39 |
-
|
40 |
-
tokenizer = None
|
41 |
-
model = None
|
42 |
-
zh_en_translator = None
|
43 |
-
nlp = None
|
44 |
-
|
45 |
-
def load_model_and_components():
|
46 |
-
global tokenizer, model, zh_en_translator, nlp
|
47 |
-
|
48 |
-
# Initialize the model and tokenizer
|
49 |
-
try:
|
50 |
-
args["model_type"] = args["model_type"].lower()
|
51 |
-
model_class, tokenizer_class = MODEL_CLASSES[args["model_type"]]
|
52 |
-
except KeyError:
|
53 |
-
raise KeyError("the model {} you specified is not supported. You are welcome to add it and open a PR :)")
|
54 |
-
|
55 |
-
tokenizer = tokenizer_class.from_pretrained(args["model_name_or_path"], padding_side='left')
|
56 |
-
tokenizer.pad_token = tokenizer.eos_token
|
57 |
-
tokenizer.mask_token = tokenizer.eos_token
|
58 |
-
model = model_class.from_pretrained(args["model_name_or_path"])
|
59 |
-
print("Model loaded!")
|
60 |
-
|
61 |
-
# translator
|
62 |
-
zh_en_translator = Translator("Helsinki-NLP/opus-mt-zh-en")
|
63 |
-
print("Translator loaded!")
|
64 |
-
|
65 |
-
# filter
|
66 |
-
nlp = spacy.load('en_core_web_sm')
|
67 |
-
print("Filter loaded!")
|
68 |
-
|
69 |
-
# Set the model to the right device
|
70 |
-
model.to(distributed_state.device)
|
71 |
-
|
72 |
-
if args["fp16"]:
|
73 |
-
model.half()
|
74 |
-
|
75 |
-
def chat():
|
76 |
-
phrase = input("Input Prompt >>")
|
77 |
-
|
78 |
-
if tokenizer is None or model is None or zh_en_translator is None or nlp is None:
|
79 |
-
load_model_and_components()
|
80 |
-
|
81 |
-
messages = generate_prompt(
|
82 |
-
prompt_text=phrase,
|
83 |
-
args=args,
|
84 |
-
zh_en_translator=zh_en_translator,
|
85 |
-
nlp=nlp,
|
86 |
-
model=model,
|
87 |
-
tokenizer=tokenizer,
|
88 |
-
distributed_state=distributed_state,
|
89 |
-
)
|
90 |
-
|
91 |
-
for n, m in enumerate(messages):
|
92 |
-
print(f"-----generated sequence {n} -----")
|
93 |
-
print(m)
|
94 |
-
print("*"*60)
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
if __name__ == '__main__':
|
99 |
-
load_model_and_components()
|
100 |
-
while True:
|
101 |
-
chat()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
gpt2-sentiment.ipynb
DELETED
@@ -1,505 +0,0 @@
|
|
1 |
-
{
|
2 |
-
"cells": [
|
3 |
-
{
|
4 |
-
"cell_type": "markdown",
|
5 |
-
"metadata": {},
|
6 |
-
"source": [
|
7 |
-
"# Tune GPT2 to generate positive reviews\n",
|
8 |
-
"> Optimise GPT2 to produce positive IMDB movie reviews using a BERT sentiment classifier as a reward function."
|
9 |
-
]
|
10 |
-
},
|
11 |
-
{
|
12 |
-
"cell_type": "markdown",
|
13 |
-
"metadata": {},
|
14 |
-
"source": [
|
15 |
-
"<div style=\"text-align: center\">\n",
|
16 |
-
"<img src='https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/gpt2_bert_training.png' width='600'>\n",
|
17 |
-
"<p style=\"text-align: center;\"> <b>Figure:</b> Experiment setup to tune GPT2. The yellow arrows are outside the scope of this notebook, but the trained models are available through Hugging Face. </p>\n",
|
18 |
-
"</div>\n",
|
19 |
-
"\n",
|
20 |
-
"\n",
|
21 |
-
"In this notebook we fine-tune GPT2 (small) to generate positive movie reviews based on the IMDB dataset. The model gets the start of a real review and is tasked to produce positive continuations. To reward positive continuations we use a BERT classifier to analyse the sentiment of the produced sentences and use the classifier's outputs as rewards signals for PPO training."
|
22 |
-
]
|
23 |
-
},
|
24 |
-
{
|
25 |
-
"cell_type": "markdown",
|
26 |
-
"metadata": {},
|
27 |
-
"source": [
|
28 |
-
"## Setup experiment"
|
29 |
-
]
|
30 |
-
},
|
31 |
-
{
|
32 |
-
"cell_type": "markdown",
|
33 |
-
"metadata": {},
|
34 |
-
"source": [
|
35 |
-
"### Import dependencies"
|
36 |
-
]
|
37 |
-
},
|
38 |
-
{
|
39 |
-
"cell_type": "code",
|
40 |
-
"execution_count": null,
|
41 |
-
"metadata": {},
|
42 |
-
"outputs": [],
|
43 |
-
"source": [
|
44 |
-
"%load_ext autoreload\n",
|
45 |
-
"%autoreload 2"
|
46 |
-
]
|
47 |
-
},
|
48 |
-
{
|
49 |
-
"cell_type": "code",
|
50 |
-
"execution_count": null,
|
51 |
-
"metadata": {},
|
52 |
-
"outputs": [],
|
53 |
-
"source": [
|
54 |
-
"%pip install transformers trl wandb"
|
55 |
-
]
|
56 |
-
},
|
57 |
-
{
|
58 |
-
"cell_type": "code",
|
59 |
-
"execution_count": null,
|
60 |
-
"metadata": {},
|
61 |
-
"outputs": [],
|
62 |
-
"source": [
|
63 |
-
"import torch\n",
|
64 |
-
"from tqdm import tqdm\n",
|
65 |
-
"import pandas as pd\n",
|
66 |
-
"\n",
|
67 |
-
"tqdm.pandas()\n",
|
68 |
-
"\n",
|
69 |
-
"from transformers import pipeline, AutoTokenizer\n",
|
70 |
-
"from datasets import load_dataset\n",
|
71 |
-
"\n",
|
72 |
-
"from trl import PPOTrainer, PPOConfig, AutoModelForCausalLMWithValueHead\n",
|
73 |
-
"from trl.core import LengthSampler"
|
74 |
-
]
|
75 |
-
},
|
76 |
-
{
|
77 |
-
"cell_type": "markdown",
|
78 |
-
"metadata": {},
|
79 |
-
"source": [
|
80 |
-
"### Configuration"
|
81 |
-
]
|
82 |
-
},
|
83 |
-
{
|
84 |
-
"cell_type": "code",
|
85 |
-
"execution_count": null,
|
86 |
-
"metadata": {},
|
87 |
-
"outputs": [],
|
88 |
-
"source": [
|
89 |
-
"config = PPOConfig(\n",
|
90 |
-
" model_name=\"lvwerra/gpt2-imdb\",\n",
|
91 |
-
" learning_rate=1.41e-5,\n",
|
92 |
-
" log_with=\"wandb\",\n",
|
93 |
-
")\n",
|
94 |
-
"\n",
|
95 |
-
"sent_kwargs = {\"return_all_scores\": True, \"function_to_apply\": \"none\", \"batch_size\": 16}"
|
96 |
-
]
|
97 |
-
},
|
98 |
-
{
|
99 |
-
"cell_type": "code",
|
100 |
-
"execution_count": null,
|
101 |
-
"metadata": {},
|
102 |
-
"outputs": [],
|
103 |
-
"source": [
|
104 |
-
"import wandb\n",
|
105 |
-
"\n",
|
106 |
-
"wandb.init()"
|
107 |
-
]
|
108 |
-
},
|
109 |
-
{
|
110 |
-
"cell_type": "markdown",
|
111 |
-
"metadata": {},
|
112 |
-
"source": [
|
113 |
-
"You can see that we load a GPT2 model called `gpt2_imdb`. This model was additionally fine-tuned on the IMDB dataset for 1 epoch with the huggingface [script](https://github.com/huggingface/transformers/blob/master/examples/run_language_modeling.py) (no special settings). The other parameters are mostly taken from the original paper [\"Fine-Tuning Language Models from Human Preferences\"](\n",
|
114 |
-
"https://arxiv.org/pdf/1909.08593.pdf). This model as well as the BERT model is available in the Huggingface model zoo [here](https://huggingface.co/models). The following code should automatically download the models."
|
115 |
-
]
|
116 |
-
},
|
117 |
-
{
|
118 |
-
"cell_type": "markdown",
|
119 |
-
"metadata": {},
|
120 |
-
"source": [
|
121 |
-
"## Load data and models"
|
122 |
-
]
|
123 |
-
},
|
124 |
-
{
|
125 |
-
"attachments": {},
|
126 |
-
"cell_type": "markdown",
|
127 |
-
"metadata": {},
|
128 |
-
"source": [
|
129 |
-
"### Load IMDB dataset\n",
|
130 |
-
"The IMDB dataset contains 50k movie review annotated with \"positive\"/\"negative\" feedback indicating the sentiment. We load the IMDB dataset into a DataFrame and filter for comments that are at least 200 characters. Then we tokenize each text and cut it to random size with the `LengthSampler`."
|
131 |
-
]
|
132 |
-
},
|
133 |
-
{
|
134 |
-
"cell_type": "code",
|
135 |
-
"execution_count": null,
|
136 |
-
"metadata": {},
|
137 |
-
"outputs": [],
|
138 |
-
"source": [
|
139 |
-
"def build_dataset(config, dataset_name=\"imdb\", input_min_text_length=2, input_max_text_length=8):\n",
|
140 |
-
" \"\"\"\n",
|
141 |
-
" Build dataset for training. This builds the dataset from `load_dataset`, one should\n",
|
142 |
-
" customize this function to train the model on its own dataset.\n",
|
143 |
-
"\n",
|
144 |
-
" Args:\n",
|
145 |
-
" dataset_name (`str`):\n",
|
146 |
-
" The name of the dataset to be loaded.\n",
|
147 |
-
"\n",
|
148 |
-
" Returns:\n",
|
149 |
-
" dataloader (`torch.utils.data.DataLoader`):\n",
|
150 |
-
" The dataloader for the dataset.\n",
|
151 |
-
" \"\"\"\n",
|
152 |
-
" tokenizer = AutoTokenizer.from_pretrained(config.model_name)\n",
|
153 |
-
" tokenizer.pad_token = tokenizer.eos_token\n",
|
154 |
-
" # load imdb with datasets\n",
|
155 |
-
" ds = load_dataset(dataset_name, split=\"train\")\n",
|
156 |
-
" ds = ds.rename_columns({\"text\": \"review\"})\n",
|
157 |
-
" ds = ds.filter(lambda x: len(x[\"review\"]) > 200, batched=False)\n",
|
158 |
-
"\n",
|
159 |
-
" input_size = LengthSampler(input_min_text_length, input_max_text_length)\n",
|
160 |
-
"\n",
|
161 |
-
" def tokenize(sample):\n",
|
162 |
-
" sample[\"input_ids\"] = tokenizer.encode(sample[\"review\"])[: input_size()]\n",
|
163 |
-
" sample[\"query\"] = tokenizer.decode(sample[\"input_ids\"])\n",
|
164 |
-
" return sample\n",
|
165 |
-
"\n",
|
166 |
-
" ds = ds.map(tokenize, batched=False)\n",
|
167 |
-
" ds.set_format(type=\"torch\")\n",
|
168 |
-
" return ds"
|
169 |
-
]
|
170 |
-
},
|
171 |
-
{
|
172 |
-
"cell_type": "code",
|
173 |
-
"execution_count": null,
|
174 |
-
"metadata": {},
|
175 |
-
"outputs": [],
|
176 |
-
"source": [
|
177 |
-
"dataset = build_dataset(config)\n",
|
178 |
-
"\n",
|
179 |
-
"\n",
|
180 |
-
"def collator(data):\n",
|
181 |
-
" return dict((key, [d[key] for d in data]) for key in data[0])"
|
182 |
-
]
|
183 |
-
},
|
184 |
-
{
|
185 |
-
"cell_type": "markdown",
|
186 |
-
"metadata": {},
|
187 |
-
"source": [
|
188 |
-
"### Load pre-trained GPT2 language models"
|
189 |
-
]
|
190 |
-
},
|
191 |
-
{
|
192 |
-
"cell_type": "markdown",
|
193 |
-
"metadata": {},
|
194 |
-
"source": [
|
195 |
-
"We load the GPT2 model with a value head and the tokenizer. We load the model twice; the first model is optimized while the second model serves as a reference to calculate the KL-divergence from the starting point. This serves as an additional reward signal in the PPO training to make sure the optimized model does not deviate too much from the original language model."
|
196 |
-
]
|
197 |
-
},
|
198 |
-
{
|
199 |
-
"cell_type": "code",
|
200 |
-
"execution_count": null,
|
201 |
-
"metadata": {},
|
202 |
-
"outputs": [],
|
203 |
-
"source": [
|
204 |
-
"model = AutoModelForCausalLMWithValueHead.from_pretrained(config.model_name)\n",
|
205 |
-
"ref_model = AutoModelForCausalLMWithValueHead.from_pretrained(config.model_name)\n",
|
206 |
-
"tokenizer = AutoTokenizer.from_pretrained(config.model_name)\n",
|
207 |
-
"\n",
|
208 |
-
"tokenizer.pad_token = tokenizer.eos_token"
|
209 |
-
]
|
210 |
-
},
|
211 |
-
{
|
212 |
-
"attachments": {},
|
213 |
-
"cell_type": "markdown",
|
214 |
-
"metadata": {},
|
215 |
-
"source": [
|
216 |
-
"### Initialize PPOTrainer\n",
|
217 |
-
"The `PPOTrainer` takes care of device placement and optimization later on:"
|
218 |
-
]
|
219 |
-
},
|
220 |
-
{
|
221 |
-
"cell_type": "code",
|
222 |
-
"execution_count": null,
|
223 |
-
"metadata": {},
|
224 |
-
"outputs": [],
|
225 |
-
"source": [
|
226 |
-
"ppo_trainer = PPOTrainer(config, model, ref_model, tokenizer, dataset=dataset, data_collator=collator)"
|
227 |
-
]
|
228 |
-
},
|
229 |
-
{
|
230 |
-
"cell_type": "markdown",
|
231 |
-
"metadata": {},
|
232 |
-
"source": [
|
233 |
-
"### Load BERT classifier\n",
|
234 |
-
"We load a BERT classifier fine-tuned on the IMDB dataset."
|
235 |
-
]
|
236 |
-
},
|
237 |
-
{
|
238 |
-
"cell_type": "code",
|
239 |
-
"execution_count": null,
|
240 |
-
"metadata": {},
|
241 |
-
"outputs": [],
|
242 |
-
"source": [
|
243 |
-
"device = ppo_trainer.accelerator.device\n",
|
244 |
-
"if ppo_trainer.accelerator.num_processes == 1:\n",
|
245 |
-
" device = 0 if torch.cuda.is_available() else \"cpu\" # to avoid a `pipeline` bug\n",
|
246 |
-
"sentiment_pipe = pipeline(\"sentiment-analysis\", model=\"lvwerra/distilbert-imdb\", device=device)"
|
247 |
-
]
|
248 |
-
},
|
249 |
-
{
|
250 |
-
"cell_type": "markdown",
|
251 |
-
"metadata": {},
|
252 |
-
"source": [
|
253 |
-
"The model outputs are the logits for the negative and positive class. We will use the logits for positive class as a reward signal for the language model."
|
254 |
-
]
|
255 |
-
},
|
256 |
-
{
|
257 |
-
"cell_type": "code",
|
258 |
-
"execution_count": null,
|
259 |
-
"metadata": {},
|
260 |
-
"outputs": [],
|
261 |
-
"source": [
|
262 |
-
"text = \"this movie was really bad!!\"\n",
|
263 |
-
"sentiment_pipe(text, **sent_kwargs)"
|
264 |
-
]
|
265 |
-
},
|
266 |
-
{
|
267 |
-
"cell_type": "code",
|
268 |
-
"execution_count": null,
|
269 |
-
"metadata": {},
|
270 |
-
"outputs": [],
|
271 |
-
"source": [
|
272 |
-
"text = \"this movie was really good!!\"\n",
|
273 |
-
"sentiment_pipe(text, **sent_kwargs)"
|
274 |
-
]
|
275 |
-
},
|
276 |
-
{
|
277 |
-
"cell_type": "markdown",
|
278 |
-
"metadata": {},
|
279 |
-
"source": [
|
280 |
-
"### Generation settings\n",
|
281 |
-
"For the response generation we just use sampling and make sure top-k and nucleus sampling are turned off as well as a minimal length."
|
282 |
-
]
|
283 |
-
},
|
284 |
-
{
|
285 |
-
"cell_type": "code",
|
286 |
-
"execution_count": null,
|
287 |
-
"metadata": {},
|
288 |
-
"outputs": [],
|
289 |
-
"source": [
|
290 |
-
"gen_kwargs = {\"min_length\": -1, \"top_k\": 0.0, \"top_p\": 1.0, \"do_sample\": True, \"pad_token_id\": tokenizer.eos_token_id}"
|
291 |
-
]
|
292 |
-
},
|
293 |
-
{
|
294 |
-
"cell_type": "markdown",
|
295 |
-
"metadata": {},
|
296 |
-
"source": [
|
297 |
-
"## Optimize model"
|
298 |
-
]
|
299 |
-
},
|
300 |
-
{
|
301 |
-
"cell_type": "markdown",
|
302 |
-
"metadata": {},
|
303 |
-
"source": [
|
304 |
-
"### Training loop"
|
305 |
-
]
|
306 |
-
},
|
307 |
-
{
|
308 |
-
"cell_type": "markdown",
|
309 |
-
"metadata": {},
|
310 |
-
"source": [
|
311 |
-
"The training loop consists of the following main steps:\n",
|
312 |
-
"1. Get the query responses from the policy network (GPT-2)\n",
|
313 |
-
"2. Get sentiments for query/responses from BERT\n",
|
314 |
-
"3. Optimize policy with PPO using the (query, response, reward) triplet\n",
|
315 |
-
"\n",
|
316 |
-
"**Training time**\n",
|
317 |
-
"\n",
|
318 |
-
"This step takes **~2h** on a V100 GPU with the above specified settings."
|
319 |
-
]
|
320 |
-
},
|
321 |
-
{
|
322 |
-
"cell_type": "code",
|
323 |
-
"execution_count": null,
|
324 |
-
"metadata": {},
|
325 |
-
"outputs": [],
|
326 |
-
"source": [
|
327 |
-
"output_min_length = 4\n",
|
328 |
-
"output_max_length = 16\n",
|
329 |
-
"output_length_sampler = LengthSampler(output_min_length, output_max_length)\n",
|
330 |
-
"\n",
|
331 |
-
"\n",
|
332 |
-
"generation_kwargs = {\n",
|
333 |
-
" \"min_length\": -1,\n",
|
334 |
-
" \"top_k\": 0.0,\n",
|
335 |
-
" \"top_p\": 1.0,\n",
|
336 |
-
" \"do_sample\": True,\n",
|
337 |
-
" \"pad_token_id\": tokenizer.eos_token_id,\n",
|
338 |
-
"}\n",
|
339 |
-
"\n",
|
340 |
-
"\n",
|
341 |
-
"for epoch, batch in tqdm(enumerate(ppo_trainer.dataloader)):\n",
|
342 |
-
" query_tensors = batch[\"input_ids\"]\n",
|
343 |
-
"\n",
|
344 |
-
" #### Get response from gpt2\n",
|
345 |
-
" response_tensors = []\n",
|
346 |
-
" for query in query_tensors:\n",
|
347 |
-
" gen_len = output_length_sampler()\n",
|
348 |
-
" generation_kwargs[\"max_new_tokens\"] = gen_len\n",
|
349 |
-
" response = ppo_trainer.generate(query, **generation_kwargs)\n",
|
350 |
-
" response_tensors.append(response.squeeze()[-gen_len:])\n",
|
351 |
-
" batch[\"response\"] = [tokenizer.decode(r.squeeze()) for r in response_tensors]\n",
|
352 |
-
"\n",
|
353 |
-
" #### Compute sentiment score\n",
|
354 |
-
" texts = [q + r for q, r in zip(batch[\"query\"], batch[\"response\"])]\n",
|
355 |
-
" pipe_outputs = sentiment_pipe(texts, **sent_kwargs)\n",
|
356 |
-
" rewards = [torch.tensor(output[1][\"score\"]) for output in pipe_outputs]\n",
|
357 |
-
"\n",
|
358 |
-
" #### Run PPO step\n",
|
359 |
-
" stats = ppo_trainer.step(query_tensors, response_tensors, rewards)\n",
|
360 |
-
" ppo_trainer.log_stats(stats, batch, rewards)"
|
361 |
-
]
|
362 |
-
},
|
363 |
-
{
|
364 |
-
"cell_type": "markdown",
|
365 |
-
"metadata": {},
|
366 |
-
"source": [
|
367 |
-
"### Training progress\n",
|
368 |
-
"If you are tracking the training progress with Weights&Biases you should see a plot similar to the one below. Check out the interactive sample report on wandb.ai: [link](https://app.wandb.ai/huggingface/trl-showcase/runs/1jtvxb1m/).\n",
|
369 |
-
"\n",
|
370 |
-
"<div style=\"text-align: center\">\n",
|
371 |
-
"<img src='https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/gpt2_tuning_progress.png' width='800'>\n",
|
372 |
-
"<p style=\"text-align: center;\"> <b>Figure:</b> Reward mean and distribution evolution during training. </p>\n",
|
373 |
-
"</div>\n",
|
374 |
-
"\n",
|
375 |
-
"One can observe how the model starts to generate more positive outputs after a few optimisation steps.\n",
|
376 |
-
"\n",
|
377 |
-
"> Note: Investigating the KL-divergence will probably show that at this point the model has not converged to the target KL-divergence, yet. To get there would require longer training or starting with a higher initial coefficient."
|
378 |
-
]
|
379 |
-
},
|
380 |
-
{
|
381 |
-
"attachments": {},
|
382 |
-
"cell_type": "markdown",
|
383 |
-
"metadata": {},
|
384 |
-
"source": [
|
385 |
-
"## Model inspection\n",
|
386 |
-
"Let's inspect some examples from the IMDB dataset. We can use `model_ref` to compare the tuned model `model` against the model before optimisation."
|
387 |
-
]
|
388 |
-
},
|
389 |
-
{
|
390 |
-
"cell_type": "code",
|
391 |
-
"execution_count": null,
|
392 |
-
"metadata": {},
|
393 |
-
"outputs": [],
|
394 |
-
"source": [
|
395 |
-
"#### get a batch from the dataset\n",
|
396 |
-
"bs = 16\n",
|
397 |
-
"game_data = dict()\n",
|
398 |
-
"dataset.set_format(\"pandas\")\n",
|
399 |
-
"df_batch = dataset[:].sample(bs)\n",
|
400 |
-
"game_data[\"query\"] = df_batch[\"query\"].tolist()\n",
|
401 |
-
"query_tensors = df_batch[\"input_ids\"].tolist()\n",
|
402 |
-
"\n",
|
403 |
-
"response_tensors_ref, response_tensors = [], []\n",
|
404 |
-
"\n",
|
405 |
-
"#### get response from gpt2 and gpt2_ref\n",
|
406 |
-
"for i in range(bs):\n",
|
407 |
-
" gen_len = output_length_sampler()\n",
|
408 |
-
" output = ref_model.generate(\n",
|
409 |
-
" torch.tensor(query_tensors[i]).unsqueeze(dim=0).to(device), max_new_tokens=gen_len, **gen_kwargs\n",
|
410 |
-
" ).squeeze()[-gen_len:]\n",
|
411 |
-
" response_tensors_ref.append(output)\n",
|
412 |
-
" output = model.generate(\n",
|
413 |
-
" torch.tensor(query_tensors[i]).unsqueeze(dim=0).to(device), max_new_tokens=gen_len, **gen_kwargs\n",
|
414 |
-
" ).squeeze()[-gen_len:]\n",
|
415 |
-
" response_tensors.append(output)\n",
|
416 |
-
"\n",
|
417 |
-
"#### decode responses\n",
|
418 |
-
"game_data[\"response (before)\"] = [tokenizer.decode(response_tensors_ref[i]) for i in range(bs)]\n",
|
419 |
-
"game_data[\"response (after)\"] = [tokenizer.decode(response_tensors[i]) for i in range(bs)]\n",
|
420 |
-
"\n",
|
421 |
-
"#### sentiment analysis of query/response pairs before/after\n",
|
422 |
-
"texts = [q + r for q, r in zip(game_data[\"query\"], game_data[\"response (before)\"])]\n",
|
423 |
-
"game_data[\"rewards (before)\"] = [output[1][\"score\"] for output in sentiment_pipe(texts, **sent_kwargs)]\n",
|
424 |
-
"\n",
|
425 |
-
"texts = [q + r for q, r in zip(game_data[\"query\"], game_data[\"response (after)\"])]\n",
|
426 |
-
"game_data[\"rewards (after)\"] = [output[1][\"score\"] for output in sentiment_pipe(texts, **sent_kwargs)]\n",
|
427 |
-
"\n",
|
428 |
-
"# store results in a dataframe\n",
|
429 |
-
"df_results = pd.DataFrame(game_data)\n",
|
430 |
-
"df_results"
|
431 |
-
]
|
432 |
-
},
|
433 |
-
{
|
434 |
-
"cell_type": "markdown",
|
435 |
-
"metadata": {},
|
436 |
-
"source": [
|
437 |
-
"Looking at the reward mean/median of the generated sequences we observe a significant difference."
|
438 |
-
]
|
439 |
-
},
|
440 |
-
{
|
441 |
-
"cell_type": "code",
|
442 |
-
"execution_count": null,
|
443 |
-
"metadata": {},
|
444 |
-
"outputs": [],
|
445 |
-
"source": [
|
446 |
-
"print(\"mean:\")\n",
|
447 |
-
"display(df_results[[\"rewards (before)\", \"rewards (after)\"]].mean())\n",
|
448 |
-
"print()\n",
|
449 |
-
"print(\"median:\")\n",
|
450 |
-
"display(df_results[[\"rewards (before)\", \"rewards (after)\"]].median())"
|
451 |
-
]
|
452 |
-
},
|
453 |
-
{
|
454 |
-
"cell_type": "markdown",
|
455 |
-
"metadata": {},
|
456 |
-
"source": [
|
457 |
-
"## Save model\n",
|
458 |
-
"Finally, we save the model and push it to the Hugging Face for later usage."
|
459 |
-
]
|
460 |
-
},
|
461 |
-
{
|
462 |
-
"cell_type": "code",
|
463 |
-
"execution_count": null,
|
464 |
-
"metadata": {},
|
465 |
-
"outputs": [],
|
466 |
-
"source": [
|
467 |
-
"model.save_pretrained(\"gpt2-imdb-pos-v2\", push_to_hub=True)\n",
|
468 |
-
"tokenizer.save_pretrained(\"gpt2-imdb-pos-v2\", push_to_hub=True)"
|
469 |
-
]
|
470 |
-
},
|
471 |
-
{
|
472 |
-
"cell_type": "code",
|
473 |
-
"execution_count": null,
|
474 |
-
"metadata": {},
|
475 |
-
"outputs": [],
|
476 |
-
"source": []
|
477 |
-
}
|
478 |
-
],
|
479 |
-
"metadata": {
|
480 |
-
"kernelspec": {
|
481 |
-
"display_name": "env",
|
482 |
-
"language": "python",
|
483 |
-
"name": "python3"
|
484 |
-
},
|
485 |
-
"language_info": {
|
486 |
-
"codemirror_mode": {
|
487 |
-
"name": "ipython",
|
488 |
-
"version": 3
|
489 |
-
},
|
490 |
-
"file_extension": ".py",
|
491 |
-
"mimetype": "text/x-python",
|
492 |
-
"name": "python",
|
493 |
-
"nbconvert_exporter": "python",
|
494 |
-
"pygments_lexer": "ipython3",
|
495 |
-
"version": "3.10.13"
|
496 |
-
},
|
497 |
-
"vscode": {
|
498 |
-
"interpreter": {
|
499 |
-
"hash": "4c8ff454cd947027f86954d72bf940c689a97dcc494eb53cfe4813862c6065fe"
|
500 |
-
}
|
501 |
-
}
|
502 |
-
},
|
503 |
-
"nbformat": 4,
|
504 |
-
"nbformat_minor": 4
|
505 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
gpt2_generation.py
CHANGED
@@ -100,12 +100,6 @@ def prepare_xlm_input(args, model, tokenizer, prompt_text):
|
|
100 |
model.config.lang_id = model.config.lang2id[language]
|
101 |
# kwargs["language"] = tokenizer.lang2id[language]
|
102 |
|
103 |
-
# TODO fix mask_token_id setup when configurations will be synchronized between models and tokenizers
|
104 |
-
# XLM masked-language modeling (MLM) models need masked token
|
105 |
-
# is_xlm_mlm = "mlm" in args.model_name_or_path
|
106 |
-
# if is_xlm_mlm:
|
107 |
-
# kwargs["mask_token_id"] = tokenizer.mask_token_id
|
108 |
-
|
109 |
return prompt_text
|
110 |
|
111 |
|
@@ -373,15 +367,7 @@ def generate_prompt(
|
|
373 |
total_sequence = (
|
374 |
prompt_text + text[len(tokenizer.decode(encoded_prompt[0], clean_up_tokenization_spaces=True)) :]
|
375 |
)
|
376 |
-
|
377 |
-
# 暂时删去关键词检测
|
378 |
-
# docs = nlp(text)
|
379 |
-
# nouns = [token.text for token in docs if token.pos_ == 'NOUN']
|
380 |
-
# nouns = set(nouns)
|
381 |
-
# if nouns.intersection(FORBIDDEN_NOUN) and repeat_gen_time < 10:
|
382 |
-
# continue
|
383 |
-
# else:
|
384 |
-
# break
|
385 |
break
|
386 |
total_sequence = remove_tokens_before_copula(total_sequence)
|
387 |
generated_sequences.append(total_sequence)
|
|
|
100 |
model.config.lang_id = model.config.lang2id[language]
|
101 |
# kwargs["language"] = tokenizer.lang2id[language]
|
102 |
|
|
|
|
|
|
|
|
|
|
|
|
|
103 |
return prompt_text
|
104 |
|
105 |
|
|
|
367 |
total_sequence = (
|
368 |
prompt_text + text[len(tokenizer.decode(encoded_prompt[0], clean_up_tokenization_spaces=True)) :]
|
369 |
)
|
370 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
371 |
break
|
372 |
total_sequence = remove_tokens_before_copula(total_sequence)
|
373 |
generated_sequences.append(total_sequence)
|
gpt_api.py
DELETED
@@ -1,27 +0,0 @@
|
|
1 |
-
import openai
|
2 |
-
|
3 |
-
|
4 |
-
def get_response_create_data(cn_text):
|
5 |
-
openai.api_type = "azure"
|
6 |
-
openai.api_base = "https://poster-pku-gpt4.openai.azure.com/"
|
7 |
-
openai.api_version = "2023-07-01-preview"
|
8 |
-
openai.api_key = '788c2b57f1954ddc92bb27786fbcdd6e'
|
9 |
-
|
10 |
-
response = openai.ChatCompletion.create(
|
11 |
-
engine="dragon",
|
12 |
-
messages=[{"role": "system", "content": "Now you are a home improvement designer,\
|
13 |
-
I give you some keywords, generate a brief interior design in English, no more than words: "},
|
14 |
-
{"role": "user", "content": cn_text}],
|
15 |
-
temperature=0.7,
|
16 |
-
max_tokens=800,
|
17 |
-
top_p=0.95,
|
18 |
-
frequency_penalty=0,
|
19 |
-
presence_penalty=0,
|
20 |
-
stop=None)
|
21 |
-
return response['choices'][0]["message"]["content"]
|
22 |
-
|
23 |
-
|
24 |
-
if __name__ == '__main__':
|
25 |
-
while (1):
|
26 |
-
input_text = input("输入:")
|
27 |
-
get_response_create_data(input_text)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
monitor.sh
DELETED
@@ -1,15 +0,0 @@
|
|
1 |
-
#!/bin/bash
|
2 |
-
|
3 |
-
while true; do
|
4 |
-
|
5 |
-
seed=$(date +%s)
|
6 |
-
|
7 |
-
python trible.py ${seed}
|
8 |
-
|
9 |
-
if [ $? -eq 0 ]; then
|
10 |
-
echo "program complect, no need to restart..."
|
11 |
-
break
|
12 |
-
else
|
13 |
-
echo "program crash, restarting"
|
14 |
-
fi
|
15 |
-
done
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
rouge/README.md
DELETED
@@ -1,161 +0,0 @@
|
|
1 |
-
---
|
2 |
-
title: ROUGE
|
3 |
-
emoji: 🤗
|
4 |
-
colorFrom: blue
|
5 |
-
colorTo: red
|
6 |
-
sdk: gradio
|
7 |
-
sdk_version: 3.19.1
|
8 |
-
app_file: app.py
|
9 |
-
pinned: false
|
10 |
-
tags:
|
11 |
-
- evaluate
|
12 |
-
- metric
|
13 |
-
description: >-
|
14 |
-
ROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for
|
15 |
-
evaluating automatic summarization and machine translation software in natural language processing.
|
16 |
-
The metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.
|
17 |
-
|
18 |
-
Note that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.
|
19 |
-
|
20 |
-
This metrics is a wrapper around Google Research reimplementation of ROUGE:
|
21 |
-
https://github.com/google-research/google-research/tree/master/rouge
|
22 |
-
---
|
23 |
-
|
24 |
-
# Metric Card for ROUGE
|
25 |
-
|
26 |
-
## Metric Description
|
27 |
-
ROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for evaluating automatic summarization and machine translation software in natural language processing. The metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.
|
28 |
-
|
29 |
-
Note that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.
|
30 |
-
|
31 |
-
This metrics is a wrapper around the [Google Research reimplementation of ROUGE](https://github.com/google-research/google-research/tree/master/rouge)
|
32 |
-
|
33 |
-
## How to Use
|
34 |
-
At minimum, this metric takes as input a list of predictions and a list of references:
|
35 |
-
```python
|
36 |
-
>>> rouge = evaluate.load('rouge')
|
37 |
-
>>> predictions = ["hello there", "general kenobi"]
|
38 |
-
>>> references = ["hello there", "general kenobi"]
|
39 |
-
>>> results = rouge.compute(predictions=predictions,
|
40 |
-
... references=references)
|
41 |
-
>>> print(results)
|
42 |
-
{'rouge1': 1.0, 'rouge2': 1.0, 'rougeL': 1.0, 'rougeLsum': 1.0}
|
43 |
-
```
|
44 |
-
|
45 |
-
One can also pass a custom tokenizer which is especially useful for non-latin languages.
|
46 |
-
```python
|
47 |
-
>>> results = rouge.compute(predictions=predictions,
|
48 |
-
... references=references,
|
49 |
-
tokenizer=lambda x: x.split())
|
50 |
-
>>> print(results)
|
51 |
-
{'rouge1': 1.0, 'rouge2': 1.0, 'rougeL': 1.0, 'rougeLsum': 1.0}
|
52 |
-
```
|
53 |
-
|
54 |
-
It can also deal with lists of references for each predictions:
|
55 |
-
```python
|
56 |
-
>>> rouge = evaluate.load('rouge')
|
57 |
-
>>> predictions = ["hello there", "general kenobi"]
|
58 |
-
>>> references = [["hello", "there"], ["general kenobi", "general yoda"]]
|
59 |
-
>>> results = rouge.compute(predictions=predictions,
|
60 |
-
... references=references)
|
61 |
-
>>> print(results)
|
62 |
-
{'rouge1': 0.8333, 'rouge2': 0.5, 'rougeL': 0.8333, 'rougeLsum': 0.8333}```
|
63 |
-
```
|
64 |
-
|
65 |
-
### Inputs
|
66 |
-
- **predictions** (`list`): list of predictions to score. Each prediction
|
67 |
-
should be a string with tokens separated by spaces.
|
68 |
-
- **references** (`list` or `list[list]`): list of reference for each prediction or a list of several references per prediction. Each
|
69 |
-
reference should be a string with tokens separated by spaces.
|
70 |
-
- **rouge_types** (`list`): A list of rouge types to calculate. Defaults to `['rouge1', 'rouge2', 'rougeL', 'rougeLsum']`.
|
71 |
-
- Valid rouge types:
|
72 |
-
- `"rouge1"`: unigram (1-gram) based scoring
|
73 |
-
- `"rouge2"`: bigram (2-gram) based scoring
|
74 |
-
- `"rougeL"`: Longest common subsequence based scoring.
|
75 |
-
- `"rougeLSum"`: splits text using `"\n"`
|
76 |
-
- See [here](https://github.com/huggingface/datasets/issues/617) for more information
|
77 |
-
- **use_aggregator** (`boolean`): If True, returns aggregates. Defaults to `True`.
|
78 |
-
- **use_stemmer** (`boolean`): If `True`, uses Porter stemmer to strip word suffixes. Defaults to `False`.
|
79 |
-
|
80 |
-
### Output Values
|
81 |
-
The output is a dictionary with one entry for each rouge type in the input list `rouge_types`. If `use_aggregator=False`, each dictionary entry is a list of scores, with one score for each sentence. E.g. if `rouge_types=['rouge1', 'rouge2']` and `use_aggregator=False`, the output is:
|
82 |
-
|
83 |
-
```python
|
84 |
-
{'rouge1': [0.6666666666666666, 1.0], 'rouge2': [0.0, 1.0]}
|
85 |
-
```
|
86 |
-
|
87 |
-
If `rouge_types=['rouge1', 'rouge2']` and `use_aggregator=True`, the output is of the following format:
|
88 |
-
```python
|
89 |
-
{'rouge1': 1.0, 'rouge2': 1.0}
|
90 |
-
```
|
91 |
-
|
92 |
-
The ROUGE values are in the range of 0 to 1.
|
93 |
-
|
94 |
-
|
95 |
-
#### Values from Popular Papers
|
96 |
-
|
97 |
-
|
98 |
-
### Examples
|
99 |
-
An example without aggregation:
|
100 |
-
```python
|
101 |
-
>>> rouge = evaluate.load('rouge')
|
102 |
-
>>> predictions = ["hello goodbye", "ankh morpork"]
|
103 |
-
>>> references = ["goodbye", "general kenobi"]
|
104 |
-
>>> results = rouge.compute(predictions=predictions,
|
105 |
-
... references=references,
|
106 |
-
... use_aggregator=False)
|
107 |
-
>>> print(list(results.keys()))
|
108 |
-
['rouge1', 'rouge2', 'rougeL', 'rougeLsum']
|
109 |
-
>>> print(results["rouge1"])
|
110 |
-
[0.5, 0.0]
|
111 |
-
```
|
112 |
-
|
113 |
-
The same example, but with aggregation:
|
114 |
-
```python
|
115 |
-
>>> rouge = evaluate.load('rouge')
|
116 |
-
>>> predictions = ["hello goodbye", "ankh morpork"]
|
117 |
-
>>> references = ["goodbye", "general kenobi"]
|
118 |
-
>>> results = rouge.compute(predictions=predictions,
|
119 |
-
... references=references,
|
120 |
-
... use_aggregator=True)
|
121 |
-
>>> print(list(results.keys()))
|
122 |
-
['rouge1', 'rouge2', 'rougeL', 'rougeLsum']
|
123 |
-
>>> print(results["rouge1"])
|
124 |
-
0.25
|
125 |
-
```
|
126 |
-
|
127 |
-
The same example, but only calculating `rouge_1`:
|
128 |
-
```python
|
129 |
-
>>> rouge = evaluate.load('rouge')
|
130 |
-
>>> predictions = ["hello goodbye", "ankh morpork"]
|
131 |
-
>>> references = ["goodbye", "general kenobi"]
|
132 |
-
>>> results = rouge.compute(predictions=predictions,
|
133 |
-
... references=references,
|
134 |
-
... rouge_types=['rouge_1'],
|
135 |
-
... use_aggregator=True)
|
136 |
-
>>> print(list(results.keys()))
|
137 |
-
['rouge1']
|
138 |
-
>>> print(results["rouge1"])
|
139 |
-
0.25
|
140 |
-
```
|
141 |
-
|
142 |
-
## Limitations and Bias
|
143 |
-
See [Schluter (2017)](https://aclanthology.org/E17-2007/) for an in-depth discussion of many of ROUGE's limits.
|
144 |
-
|
145 |
-
## Citation
|
146 |
-
```bibtex
|
147 |
-
@inproceedings{lin-2004-rouge,
|
148 |
-
title = "{ROUGE}: A Package for Automatic Evaluation of Summaries",
|
149 |
-
author = "Lin, Chin-Yew",
|
150 |
-
booktitle = "Text Summarization Branches Out",
|
151 |
-
month = jul,
|
152 |
-
year = "2004",
|
153 |
-
address = "Barcelona, Spain",
|
154 |
-
publisher = "Association for Computational Linguistics",
|
155 |
-
url = "https://www.aclweb.org/anthology/W04-1013",
|
156 |
-
pages = "74--81",
|
157 |
-
}
|
158 |
-
```
|
159 |
-
|
160 |
-
## Further References
|
161 |
-
- This metrics is a wrapper around the [Google Research reimplementation of ROUGE](https://github.com/google-research/google-research/tree/master/rouge)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
rouge/app.py
DELETED
@@ -1,6 +0,0 @@
|
|
1 |
-
import evaluate
|
2 |
-
from evaluate.utils import launch_gradio_widget
|
3 |
-
|
4 |
-
|
5 |
-
module = evaluate.load("rouge")
|
6 |
-
launch_gradio_widget(module)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
rouge/requirements.txt
DELETED
@@ -1,4 +0,0 @@
|
|
1 |
-
git+https://github.com/huggingface/evaluate@{COMMIT_PLACEHOLDER}
|
2 |
-
absl-py
|
3 |
-
nltk
|
4 |
-
rouge_score>=0.1.2
|
|
|
|
|
|
|
|
|
|
rouge/rouge.py
DELETED
@@ -1,158 +0,0 @@
|
|
1 |
-
# Copyright 2020 The HuggingFace Evaluate Authors.
|
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 |
-
""" ROUGE metric from Google Research github repo. """
|
15 |
-
|
16 |
-
# The dependencies in https://github.com/google-research/google-research/blob/master/rouge/requirements.txt
|
17 |
-
import absl # Here to have a nice missing dependency error message early on
|
18 |
-
import datasets
|
19 |
-
import nltk # Here to have a nice missing dependency error message early on
|
20 |
-
import numpy # Here to have a nice missing dependency error message early on
|
21 |
-
import six # Here to have a nice missing dependency error message early on
|
22 |
-
from rouge_score import rouge_scorer, scoring
|
23 |
-
|
24 |
-
import evaluate
|
25 |
-
|
26 |
-
|
27 |
-
_CITATION = """\
|
28 |
-
@inproceedings{lin-2004-rouge,
|
29 |
-
title = "{ROUGE}: A Package for Automatic Evaluation of Summaries",
|
30 |
-
author = "Lin, Chin-Yew",
|
31 |
-
booktitle = "Text Summarization Branches Out",
|
32 |
-
month = jul,
|
33 |
-
year = "2004",
|
34 |
-
address = "Barcelona, Spain",
|
35 |
-
publisher = "Association for Computational Linguistics",
|
36 |
-
url = "https://www.aclweb.org/anthology/W04-1013",
|
37 |
-
pages = "74--81",
|
38 |
-
}
|
39 |
-
"""
|
40 |
-
|
41 |
-
_DESCRIPTION = """\
|
42 |
-
ROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for
|
43 |
-
evaluating automatic summarization and machine translation software in natural language processing.
|
44 |
-
The metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.
|
45 |
-
|
46 |
-
Note that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.
|
47 |
-
|
48 |
-
This metrics is a wrapper around Google Research reimplementation of ROUGE:
|
49 |
-
https://github.com/google-research/google-research/tree/master/rouge
|
50 |
-
"""
|
51 |
-
|
52 |
-
_KWARGS_DESCRIPTION = """
|
53 |
-
Calculates average rouge scores for a list of hypotheses and references
|
54 |
-
Args:
|
55 |
-
predictions: list of predictions to score. Each prediction
|
56 |
-
should be a string with tokens separated by spaces.
|
57 |
-
references: list of reference for each prediction. Each
|
58 |
-
reference should be a string with tokens separated by spaces.
|
59 |
-
rouge_types: A list of rouge types to calculate.
|
60 |
-
Valid names:
|
61 |
-
`"rouge{n}"` (e.g. `"rouge1"`, `"rouge2"`) where: {n} is the n-gram based scoring,
|
62 |
-
`"rougeL"`: Longest common subsequence based scoring.
|
63 |
-
`"rougeLsum"`: rougeLsum splits text using `"\n"`.
|
64 |
-
See details in https://github.com/huggingface/datasets/issues/617
|
65 |
-
use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.
|
66 |
-
use_aggregator: Return aggregates if this is set to True
|
67 |
-
Returns:
|
68 |
-
rouge1: rouge_1 (f1),
|
69 |
-
rouge2: rouge_2 (f1),
|
70 |
-
rougeL: rouge_l (f1),
|
71 |
-
rougeLsum: rouge_lsum (f1)
|
72 |
-
Examples:
|
73 |
-
|
74 |
-
>>> rouge = evaluate.load('rouge')
|
75 |
-
>>> predictions = ["hello there", "general kenobi"]
|
76 |
-
>>> references = ["hello there", "general kenobi"]
|
77 |
-
>>> results = rouge.compute(predictions=predictions, references=references)
|
78 |
-
>>> print(results)
|
79 |
-
{'rouge1': 1.0, 'rouge2': 1.0, 'rougeL': 1.0, 'rougeLsum': 1.0}
|
80 |
-
"""
|
81 |
-
|
82 |
-
|
83 |
-
class Tokenizer:
|
84 |
-
"""Helper class to wrap a callable into a class with a `tokenize` method as used by rouge-score."""
|
85 |
-
|
86 |
-
def __init__(self, tokenizer_func):
|
87 |
-
self.tokenizer_func = tokenizer_func
|
88 |
-
|
89 |
-
def tokenize(self, text):
|
90 |
-
return self.tokenizer_func(text)
|
91 |
-
|
92 |
-
|
93 |
-
@evaluate.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
|
94 |
-
class Rouge(evaluate.Metric):
|
95 |
-
def _info(self):
|
96 |
-
return evaluate.MetricInfo(
|
97 |
-
description=_DESCRIPTION,
|
98 |
-
citation=_CITATION,
|
99 |
-
inputs_description=_KWARGS_DESCRIPTION,
|
100 |
-
features=[
|
101 |
-
datasets.Features(
|
102 |
-
{
|
103 |
-
"predictions": datasets.Value("string", id="sequence"),
|
104 |
-
"references": datasets.Sequence(datasets.Value("string", id="sequence")),
|
105 |
-
}
|
106 |
-
),
|
107 |
-
datasets.Features(
|
108 |
-
{
|
109 |
-
"predictions": datasets.Value("string", id="sequence"),
|
110 |
-
"references": datasets.Value("string", id="sequence"),
|
111 |
-
}
|
112 |
-
),
|
113 |
-
],
|
114 |
-
codebase_urls=["https://github.com/google-research/google-research/tree/master/rouge"],
|
115 |
-
reference_urls=[
|
116 |
-
"https://en.wikipedia.org/wiki/ROUGE_(metric)",
|
117 |
-
"https://github.com/google-research/google-research/tree/master/rouge",
|
118 |
-
],
|
119 |
-
)
|
120 |
-
|
121 |
-
def _compute(
|
122 |
-
self, predictions, references, rouge_types=None, use_aggregator=True, use_stemmer=False, tokenizer=None
|
123 |
-
):
|
124 |
-
if rouge_types is None:
|
125 |
-
rouge_types = ["rouge1", "rouge2", "rougeL", "rougeLsum"]
|
126 |
-
|
127 |
-
multi_ref = isinstance(references[0], list)
|
128 |
-
|
129 |
-
if tokenizer is not None:
|
130 |
-
tokenizer = Tokenizer(tokenizer)
|
131 |
-
|
132 |
-
scorer = rouge_scorer.RougeScorer(rouge_types=rouge_types, use_stemmer=use_stemmer, tokenizer=tokenizer)
|
133 |
-
if use_aggregator:
|
134 |
-
aggregator = scoring.BootstrapAggregator()
|
135 |
-
else:
|
136 |
-
scores = []
|
137 |
-
|
138 |
-
for ref, pred in zip(references, predictions):
|
139 |
-
if multi_ref:
|
140 |
-
score = scorer.score_multi(ref, pred)
|
141 |
-
else:
|
142 |
-
score = scorer.score(ref, pred)
|
143 |
-
if use_aggregator:
|
144 |
-
aggregator.add_scores(score)
|
145 |
-
else:
|
146 |
-
scores.append(score)
|
147 |
-
|
148 |
-
if use_aggregator:
|
149 |
-
result = aggregator.aggregate()
|
150 |
-
for key in result:
|
151 |
-
result[key] = result[key].mid.fmeasure
|
152 |
-
|
153 |
-
else:
|
154 |
-
result = {}
|
155 |
-
for key in scores[0]:
|
156 |
-
result[key] = list(score[key].fmeasure for score in scores)
|
157 |
-
|
158 |
-
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
sft.py
DELETED
@@ -1,81 +0,0 @@
|
|
1 |
-
import time
|
2 |
-
import evaluate
|
3 |
-
import numpy as np
|
4 |
-
import math
|
5 |
-
from transformers import DataCollatorForLanguageModeling, DataCollatorForSeq2Seq
|
6 |
-
from transformers import TrainingArguments, Trainer
|
7 |
-
|
8 |
-
from transformers.trainer_callback import TrainerCallback
|
9 |
-
|
10 |
-
from utils import (
|
11 |
-
get_dataset,
|
12 |
-
get_tok_and_model,
|
13 |
-
get_open_prompt_data,
|
14 |
-
get_dict_dataset,
|
15 |
-
get_advance_dataset,)
|
16 |
-
|
17 |
-
base_model = "gpt2"
|
18 |
-
tokenizer, model = get_tok_and_model(f"./models/{base_model}")
|
19 |
-
tokenizer.pad_token = tokenizer.eos_token
|
20 |
-
rouge = evaluate.load("rouge")
|
21 |
-
|
22 |
-
dict_data = get_dict_dataset("./data")
|
23 |
-
dataset = get_advance_dataset(dict_data)
|
24 |
-
dataset = dataset.train_test_split(test_size=0.05)
|
25 |
-
|
26 |
-
def preprocess_function(examples):
|
27 |
-
x_inputs = [x for x in examples["x"]]
|
28 |
-
y_inputs = examples["y"]
|
29 |
-
model_inputs = tokenizer(x_inputs, max_length=256, truncation=True)
|
30 |
-
|
31 |
-
labels = tokenizer(y_inputs, max_length=256, truncation=True)
|
32 |
-
|
33 |
-
model_inputs["labels"] = labels["input_ids"]
|
34 |
-
return model_inputs
|
35 |
-
|
36 |
-
class CustomCallback(TrainerCallback):
|
37 |
-
def on_epoch_end(self, args, state, control, **kwargs):
|
38 |
-
control.should_evaluate=True,
|
39 |
-
|
40 |
-
def on_evaluate(self, args, state, control, **kwargs):
|
41 |
-
eval_results = kwargs["metrics"]
|
42 |
-
print(f"Perplexity: {math.exp(eval_results['eval_loss']):.2f}\n")
|
43 |
-
|
44 |
-
# data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)
|
45 |
-
data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=model)
|
46 |
-
|
47 |
-
|
48 |
-
print("tokenize data...")
|
49 |
-
t1 = time.time()
|
50 |
-
tokenized_dataset = dataset.map(preprocess_function, batched=True, remove_columns=["x", "y"])
|
51 |
-
t2 = time.time()
|
52 |
-
print(f"data tokenize done. process time : {t2 - t1}")
|
53 |
-
|
54 |
-
|
55 |
-
training_args = TrainingArguments(
|
56 |
-
output_dir=f"./output/{base_model}_openprompt",
|
57 |
-
evaluation_strategy="steps",
|
58 |
-
eval_steps=20000,
|
59 |
-
learning_rate=3e-5,
|
60 |
-
lr_scheduler_type="constant",
|
61 |
-
report_to="tensorboard",
|
62 |
-
per_device_train_batch_size=64,
|
63 |
-
per_device_eval_batch_size=32,
|
64 |
-
save_total_limit=1,
|
65 |
-
num_train_epochs=60,
|
66 |
-
fp16=True,
|
67 |
-
push_to_hub=False,
|
68 |
-
)
|
69 |
-
|
70 |
-
trainer = Trainer(
|
71 |
-
model=model,
|
72 |
-
args=training_args,
|
73 |
-
train_dataset=tokenized_dataset["train"],
|
74 |
-
eval_dataset=tokenized_dataset["test"],
|
75 |
-
tokenizer=tokenizer,
|
76 |
-
data_collator=data_collator,
|
77 |
-
callbacks=[CustomCallback]
|
78 |
-
)
|
79 |
-
|
80 |
-
trainer.train()
|
81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
trible.py
DELETED
@@ -1,56 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import click
|
3 |
-
import random
|
4 |
-
import jsonlines
|
5 |
-
|
6 |
-
from tqdm import tqdm
|
7 |
-
from gpt_api import get_response_create_data
|
8 |
-
|
9 |
-
|
10 |
-
KEYWORDS_PATH = "/data/aigc/zw/task2/pg_distilgpt/data/raw_keywords.txt"
|
11 |
-
TARGET_PATH = "/data/aigc/zw/task2/pg_distilgpt/data/raw_discriptions.jsonl"
|
12 |
-
|
13 |
-
if not os.path.exists(TARGET_PATH):
|
14 |
-
with open(TARGET_PATH, "w") as f:
|
15 |
-
pass
|
16 |
-
|
17 |
-
|
18 |
-
def read_keywords(path=KEYWORDS_PATH):
|
19 |
-
|
20 |
-
keywords = []
|
21 |
-
|
22 |
-
with open(path, 'r', encoding='utf-8') as file:
|
23 |
-
for line in tqdm(file, desc="reading keywords"):
|
24 |
-
parts = line.strip().split('\t')
|
25 |
-
result = parts[0]
|
26 |
-
keywords.append(result)
|
27 |
-
|
28 |
-
return keywords
|
29 |
-
|
30 |
-
def keywords_sampler(num, key_words):
|
31 |
-
random.seed()
|
32 |
-
while(1):
|
33 |
-
sampled_words = random.sample(key_words, num)
|
34 |
-
yield sampled_words
|
35 |
-
|
36 |
-
def create_data(keywords, total_num=10000, n=4, seed=42):
|
37 |
-
random.seed(seed)
|
38 |
-
for n, key_words in tqdm(enumerate(keywords_sampler(n, keywords)), desc="generating data"):
|
39 |
-
|
40 |
-
res = get_response_create_data(" ".join(key_words))
|
41 |
-
|
42 |
-
with jsonlines.open(TARGET_PATH, mode='a') as writer:
|
43 |
-
writer.write({"keywrods": key_words, "description": res})
|
44 |
-
|
45 |
-
if n >= total_num:
|
46 |
-
print("generation data done.")
|
47 |
-
break
|
48 |
-
|
49 |
-
@click.command()
|
50 |
-
@click.argument('seed', type=int)
|
51 |
-
def main(seed):
|
52 |
-
keywords = read_keywords()
|
53 |
-
create_data(keywords, seed=seed)
|
54 |
-
|
55 |
-
if __name__ == '__main__':
|
56 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|