Upload 22 files
Browse files- data/test.csv +3 -0
- data/test_generated.csv +3 -0
- demo/.gitignore +2 -0
- demo/Build Ingredients Vocab.ipynb +213 -0
- demo/README.md +10 -0
- demo/beam_search.py +63 -0
- demo/config.json +1 -0
- demo/images/chef-transformer.png +0 -0
- demo/images/logo.png +0 -0
- demo/server.py +80 -0
- demo/top_sampling.py +63 -0
- notes/.keep +0 -0
- src/create_dataset.py +164 -0
- src/data_utils.py +71 -0
- src/evaluation.py +124 -0
- src/flax_to_pytorch.py +35 -0
- src/flax_to_tf.py +35 -0
- src/generation.py +196 -0
- src/prediction.py +106 -0
- src/requirements.txt +7 -0
- src/run.sh +58 -0
- src/run_recipe_nlg_flax.py +881 -0
data/test.csv
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:18fbc124237d0f6236d31fcfc5e7705562731445b1b1efc7b538e1538f5d08b6
|
3 |
+
size 95840821
|
data/test_generated.csv
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:479d8789478d92caafa5f31c7c6dbe0fbe55deb34fb0bda72fe410b77a914427
|
3 |
+
size 145654259
|
demo/.gitignore
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
*.pyc
|
2 |
+
.ipynb_checkpoints/
|
demo/Build Ingredients Vocab.ipynb
ADDED
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 3,
|
6 |
+
"metadata": {
|
7 |
+
"ExecuteTime": {
|
8 |
+
"end_time": "2021-07-14T12:54:01.369853Z",
|
9 |
+
"start_time": "2021-07-14T12:49:27.961404Z"
|
10 |
+
}
|
11 |
+
},
|
12 |
+
"outputs": [
|
13 |
+
{
|
14 |
+
"name": "stderr",
|
15 |
+
"output_type": "stream",
|
16 |
+
"text": [
|
17 |
+
"Using custom data configuration default-fdc6acb780b42528\n"
|
18 |
+
]
|
19 |
+
},
|
20 |
+
{
|
21 |
+
"name": "stdout",
|
22 |
+
"output_type": "stream",
|
23 |
+
"text": [
|
24 |
+
"Downloading and preparing dataset recipe_nlg/default (download: Unknown size, generated: 2.04 GiB, post-processed: Unknown size, total: 2.04 GiB) to /home/rtx/.cache/huggingface/datasets/recipe_nlg/default-fdc6acb780b42528/1.0.0/20c969e1192265af03a7186457bdb4a9109d5d68b92cad04c3ec894d6e5aee61...\n"
|
25 |
+
]
|
26 |
+
},
|
27 |
+
{
|
28 |
+
"data": {
|
29 |
+
"application/vnd.jupyter.widget-view+json": {
|
30 |
+
"model_id": "",
|
31 |
+
"version_major": 2,
|
32 |
+
"version_minor": 0
|
33 |
+
},
|
34 |
+
"text/plain": [
|
35 |
+
"HBox(children=(IntProgress(value=1, bar_style='info', max=1), HTML(value='')))"
|
36 |
+
]
|
37 |
+
},
|
38 |
+
"metadata": {},
|
39 |
+
"output_type": "display_data"
|
40 |
+
},
|
41 |
+
{
|
42 |
+
"name": "stdout",
|
43 |
+
"output_type": "stream",
|
44 |
+
"text": [
|
45 |
+
"\r",
|
46 |
+
"Dataset recipe_nlg downloaded and prepared to /home/rtx/.cache/huggingface/datasets/recipe_nlg/default-fdc6acb780b42528/1.0.0/20c969e1192265af03a7186457bdb4a9109d5d68b92cad04c3ec894d6e5aee61. Subsequent calls will reuse this data.\n"
|
47 |
+
]
|
48 |
+
}
|
49 |
+
],
|
50 |
+
"source": [
|
51 |
+
"from datasets import load_dataset\n",
|
52 |
+
"DATA_DIR = \"~/Downloads/dataset/\"\n",
|
53 |
+
"dataset = load_dataset(\"recipe_nlg\", data_dir=DATA_DIR)"
|
54 |
+
]
|
55 |
+
},
|
56 |
+
{
|
57 |
+
"cell_type": "code",
|
58 |
+
"execution_count": 10,
|
59 |
+
"metadata": {
|
60 |
+
"ExecuteTime": {
|
61 |
+
"end_time": "2021-07-14T12:58:25.150105Z",
|
62 |
+
"start_time": "2021-07-14T12:55:27.486385Z"
|
63 |
+
}
|
64 |
+
},
|
65 |
+
"outputs": [
|
66 |
+
{
|
67 |
+
"name": "stderr",
|
68 |
+
"output_type": "stream",
|
69 |
+
"text": [
|
70 |
+
"100%|██████████| 2231142/2231142 [02:57<00:00, 12558.59it/s]\n"
|
71 |
+
]
|
72 |
+
}
|
73 |
+
],
|
74 |
+
"source": [
|
75 |
+
"from collections import Counter\n",
|
76 |
+
"from tqdm import tqdm\n",
|
77 |
+
"ctr = Counter()\n",
|
78 |
+
"\n",
|
79 |
+
"for row in tqdm(dataset[\"train\"]):\n",
|
80 |
+
" for item in row[\"ner\"]:\n",
|
81 |
+
" ctr[item] += 1"
|
82 |
+
]
|
83 |
+
},
|
84 |
+
{
|
85 |
+
"cell_type": "code",
|
86 |
+
"execution_count": 23,
|
87 |
+
"metadata": {
|
88 |
+
"ExecuteTime": {
|
89 |
+
"end_time": "2021-07-14T13:02:09.315817Z",
|
90 |
+
"start_time": "2021-07-14T13:02:09.259046Z"
|
91 |
+
}
|
92 |
+
},
|
93 |
+
"outputs": [],
|
94 |
+
"source": [
|
95 |
+
"first_500 = list(set([x[0].lower() for x in ctr.most_common()[0:500]]))"
|
96 |
+
]
|
97 |
+
},
|
98 |
+
{
|
99 |
+
"cell_type": "code",
|
100 |
+
"execution_count": 25,
|
101 |
+
"metadata": {
|
102 |
+
"ExecuteTime": {
|
103 |
+
"end_time": "2021-07-14T13:02:28.864546Z",
|
104 |
+
"start_time": "2021-07-14T13:02:28.856279Z"
|
105 |
+
}
|
106 |
+
},
|
107 |
+
"outputs": [
|
108 |
+
{
|
109 |
+
"data": {
|
110 |
+
"text/plain": [
|
111 |
+
"443"
|
112 |
+
]
|
113 |
+
},
|
114 |
+
"execution_count": 25,
|
115 |
+
"metadata": {},
|
116 |
+
"output_type": "execute_result"
|
117 |
+
}
|
118 |
+
],
|
119 |
+
"source": [
|
120 |
+
"len(first_500)"
|
121 |
+
]
|
122 |
+
},
|
123 |
+
{
|
124 |
+
"cell_type": "code",
|
125 |
+
"execution_count": 26,
|
126 |
+
"metadata": {
|
127 |
+
"ExecuteTime": {
|
128 |
+
"end_time": "2021-07-14T13:02:53.656711Z",
|
129 |
+
"start_time": "2021-07-14T13:02:53.653868Z"
|
130 |
+
}
|
131 |
+
},
|
132 |
+
"outputs": [],
|
133 |
+
"source": [
|
134 |
+
"first_100 = sorted(first_500[:100])\n",
|
135 |
+
"next_100 = sorted(first_500[100:200])"
|
136 |
+
]
|
137 |
+
},
|
138 |
+
{
|
139 |
+
"cell_type": "code",
|
140 |
+
"execution_count": 29,
|
141 |
+
"metadata": {
|
142 |
+
"ExecuteTime": {
|
143 |
+
"end_time": "2021-07-14T13:03:35.640538Z",
|
144 |
+
"start_time": "2021-07-14T13:03:35.634368Z"
|
145 |
+
}
|
146 |
+
},
|
147 |
+
"outputs": [],
|
148 |
+
"source": [
|
149 |
+
"d = {\n",
|
150 |
+
" \"first_100\": first_100,\n",
|
151 |
+
" \"next_100\": next_100\n",
|
152 |
+
"}"
|
153 |
+
]
|
154 |
+
},
|
155 |
+
{
|
156 |
+
"cell_type": "code",
|
157 |
+
"execution_count": 31,
|
158 |
+
"metadata": {
|
159 |
+
"ExecuteTime": {
|
160 |
+
"end_time": "2021-07-14T13:03:52.682190Z",
|
161 |
+
"start_time": "2021-07-14T13:03:52.679624Z"
|
162 |
+
}
|
163 |
+
},
|
164 |
+
"outputs": [],
|
165 |
+
"source": [
|
166 |
+
"import json\n",
|
167 |
+
"with open(\"config.json\", \"w\") as f:\n",
|
168 |
+
" f.write(json.dumps(d))"
|
169 |
+
]
|
170 |
+
},
|
171 |
+
{
|
172 |
+
"cell_type": "code",
|
173 |
+
"execution_count": null,
|
174 |
+
"metadata": {},
|
175 |
+
"outputs": [],
|
176 |
+
"source": []
|
177 |
+
}
|
178 |
+
],
|
179 |
+
"metadata": {
|
180 |
+
"kernelspec": {
|
181 |
+
"display_name": "Python 3",
|
182 |
+
"language": "python",
|
183 |
+
"name": "python3"
|
184 |
+
},
|
185 |
+
"language_info": {
|
186 |
+
"codemirror_mode": {
|
187 |
+
"name": "ipython",
|
188 |
+
"version": 3
|
189 |
+
},
|
190 |
+
"file_extension": ".py",
|
191 |
+
"mimetype": "text/x-python",
|
192 |
+
"name": "python",
|
193 |
+
"nbconvert_exporter": "python",
|
194 |
+
"pygments_lexer": "ipython3",
|
195 |
+
"version": "3.7.1"
|
196 |
+
},
|
197 |
+
"toc": {
|
198 |
+
"base_numbering": 1,
|
199 |
+
"nav_menu": {},
|
200 |
+
"number_sections": true,
|
201 |
+
"sideBar": true,
|
202 |
+
"skip_h1_title": false,
|
203 |
+
"title_cell": "Table of Contents",
|
204 |
+
"title_sidebar": "Contents",
|
205 |
+
"toc_cell": false,
|
206 |
+
"toc_position": {},
|
207 |
+
"toc_section_display": true,
|
208 |
+
"toc_window_display": false
|
209 |
+
}
|
210 |
+
},
|
211 |
+
"nbformat": 4,
|
212 |
+
"nbformat_minor": 2
|
213 |
+
}
|
demo/README.md
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Streamlit demo for Chef Transformers
|
2 |
+
|
3 |
+
|
4 |
+
### Launch demo:
|
5 |
+
```
|
6 |
+
streamlit run server.py
|
7 |
+
```
|
8 |
+
|
9 |
+
### Modify config
|
10 |
+
Add any custom ingredient to display in `config.json` with key `first_100` to be displayed in multi-select. `next_100` are for custom ingredient adding section (to provide autocomplete assist as we type)
|
demo/beam_search.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from transformers import AutoModelForSeq2SeqLM
|
3 |
+
from transformers import AutoTokenizer
|
4 |
+
from transformers import pipeline
|
5 |
+
|
6 |
+
from pprint import pprint
|
7 |
+
import re
|
8 |
+
|
9 |
+
|
10 |
+
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
11 |
+
# MODEL_NAME_OR_PATH = "flax-community/t5-recipe-generation"
|
12 |
+
# tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME_OR_PATH, use_fast=True)
|
13 |
+
# model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME_OR_PATH)
|
14 |
+
|
15 |
+
|
16 |
+
def skip_special_tokens_and_prettify(text, tokenizer):
|
17 |
+
recipe_maps = {"<sep>": "--", "<section>": "\n"}
|
18 |
+
recipe_map_pattern = "|".join(map(re.escape, recipe_maps.keys()))
|
19 |
+
|
20 |
+
text = re.sub(
|
21 |
+
recipe_map_pattern,
|
22 |
+
lambda m: recipe_maps[m.group()],
|
23 |
+
re.sub("|".join(tokenizer.all_special_tokens), "", text)
|
24 |
+
)
|
25 |
+
|
26 |
+
data = {"title": "", "ingredients": [], "directions": []}
|
27 |
+
for section in text.split("\n"):
|
28 |
+
section = section.strip()
|
29 |
+
section = section.strip()
|
30 |
+
if section.startswith("title:"):
|
31 |
+
data["title"] = section.replace("title:", "").strip()
|
32 |
+
elif section.startswith("ingredients:"):
|
33 |
+
data["ingredients"] = [s.strip() for s in section.replace("ingredients:", "").split('--')]
|
34 |
+
elif section.startswith("directions:"):
|
35 |
+
data["directions"] = [s.strip() for s in section.replace("directions:", "").split('--')]
|
36 |
+
else:
|
37 |
+
pass
|
38 |
+
|
39 |
+
return data
|
40 |
+
|
41 |
+
|
42 |
+
def post_generator(output_tensors, tokenizer):
|
43 |
+
output_tensors = [output_tensors[i]["generated_token_ids"] for i in range(len(output_tensors))]
|
44 |
+
texts = tokenizer.batch_decode(output_tensors, skip_special_tokens=False)
|
45 |
+
texts = [skip_special_tokens_and_prettify(text, tokenizer) for text in texts]
|
46 |
+
return texts
|
47 |
+
|
48 |
+
|
49 |
+
# Example
|
50 |
+
generate_kwargs = {
|
51 |
+
"max_length": 512,
|
52 |
+
"min_length": 64,
|
53 |
+
"no_repeat_ngram_size": 3,
|
54 |
+
"early_stopping": True,
|
55 |
+
"num_beams": 5,
|
56 |
+
"length_penalty": 1.5,
|
57 |
+
"num_return_sequences": 2
|
58 |
+
}
|
59 |
+
items = "potato, cheese"
|
60 |
+
# generator = pipeline("text2text-generation", model=model, tokenizer=tokenizer)
|
61 |
+
# generated = generator(items, return_tensors=True, return_text=False, **generate_kwargs)
|
62 |
+
# outputs = post_generator(generated, tokenizer)
|
63 |
+
# pprint(outputs)
|
demo/config.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"first_100": ["allspice", "almond extract", "applesauce", "avocado", "balsamic vinegar", "basil", "bay leaf", "beets", "bread crumbs", "bread flour", "buns", "catsup", "cayenne", "cherry tomatoes", "chicken breasts", "chives", "chocolate cake", "coconut milk", "cold butter", "cold milk", "cooking oil", "cornstarch", "crab meat", "crackers", "cream of chicken soup", "cream of tartar", "cumin", "cumin seeds", "curry powder", "egg yolk", "extra-virgin olive oil", "feta cheese", "flaked coconut", "flat leaf parsley", "flour tortillas", "fresh chives", "fresh cilantro", "fresh mint", "fresh oregano", "fresh rosemary", "frozen strawberries", "gingerroot", "green olives", "ground allspice", "ground chuck", "ground coriander", "ground cumin", "ground pork", "ground red pepper", "hamburger", "hazelnuts", "heavy cream", "heavy whipping cream", "hot pepper", "italian dressing", "lean ground beef", "lemon juice", "lemon pepper", "marjoram", "miracle", "noodles", "nuts", "oatmeal", "oats", "oleo", "olive oil", "onion salt", "onions", "orange", "paprika", "parmesan cheese", "parsley", "pasta", "peaches", "pecans", "pork sausage", "pork tenderloin", "poultry seasoning", "powdered sugar", "pumpkin", "red potatoes", "red wine vinegar", "rosemary", "salmon", "scallion", "sesame oil", "shell", "stalks celery", "tabasco sauce", "tarragon", "tomatoes", "unsalted butter", "vanilla wafers", "vegetables", "warm water", "whipping cream", "white wine vinegar", "whole wheat flour", "yellow squash", "yogurt"], "next_100": ["active dry yeast", "almonds", "apple", "apple cider", "apple cider vinegar", "avocados", "baby spinach", "bay leaves", "bean sprouts", "beef", "beef broth", "broccoli", "cabbage", "capers", "cashews", "celery", "celery salt", "cherries", "cherry pie filling", "chicken", "chicken broth", "chicken stock", "chickpeas", "chili sauce", "chocolate", "cinnamon", "cloves", "corn", "cottage cheese", "cranberry sauce", "egg noodles", "egg yolks", "extra virgin olive oil", "freshly ground pepper", "garlic powder", "golden raisins", "graham cracker crust", "graham crackers", "green peppers", "ground black pepper", "ground nutmeg", "ground pepper", "ground turmeric", "kosher salt", "lemon rind", "mango", "mint", "mustard", "nutmeg", "orange juice", "orange zest", "oregano", "peanut butter", "peas", "pecan halves", "pepperoni", "pine nuts", "pinto beans", "pizza sauce", "plain yogurt", "potatoes", "raisins", "red", "red bell peppers", "red pepper", "red peppers", "rhubarb", "ricotta cheese", "salad oil", "sauce", "scallions", "sesame seeds", "sherry", "shredded cheese", "skinless", "soda", "soy sauce", "spinach", "strawberries", "sugar", "sweet onion", "sweet potatoes", "swiss cheese", "t", "tomato", "tomato paste", "tomato soup", "tuna", "vanilla bean", "vanilla ice cream", "vanilla pudding", "vegetable broth", "vegetable oil", "vegetable shortening", "whipped cream", "white onion", "white sugar", "yellow cake", "yellow cornmeal", "zucchini"]}
|
demo/images/chef-transformer.png
ADDED
demo/images/logo.png
ADDED
demo/server.py
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
|
2 |
+
from datetime import datetime as dt
|
3 |
+
import streamlit as st
|
4 |
+
from streamlit_tags import st_tags
|
5 |
+
import beam_search
|
6 |
+
import top_sampling
|
7 |
+
from pprint import pprint
|
8 |
+
import json
|
9 |
+
|
10 |
+
with open("config.json") as f:
|
11 |
+
cfg = json.loads(f.read())
|
12 |
+
|
13 |
+
st.set_page_config(layout="wide")
|
14 |
+
|
15 |
+
@st.cache(allow_output_mutation=True)
|
16 |
+
def load_model():
|
17 |
+
tokenizer = AutoTokenizer.from_pretrained("flax-community/t5-recipe-generation")
|
18 |
+
model = AutoModelForSeq2SeqLM.from_pretrained("flax-community/t5-recipe-generation")
|
19 |
+
generator = pipeline("text2text-generation", model=model, tokenizer=tokenizer)
|
20 |
+
return generator, tokenizer
|
21 |
+
|
22 |
+
def sampling_changed(obj):
|
23 |
+
print(obj)
|
24 |
+
|
25 |
+
|
26 |
+
with st.spinner('Loading model...'):
|
27 |
+
generator, tokenizer = load_model()
|
28 |
+
# st.image("images/chef-transformer.png", width=400)
|
29 |
+
st.header("Chef transformers (flax-community)")
|
30 |
+
st.markdown("This demo uses [t5 trained on recipe-nlg](https://huggingface.co/flax-community/t5-recipe-generation) to generate recipe from a given set of ingredients")
|
31 |
+
img = st.sidebar.image("images/chef-transformer.png", width=200)
|
32 |
+
add_text_sidebar = st.sidebar.title("Popular recipes:")
|
33 |
+
add_text_sidebar = st.sidebar.text("Recipe preset(example#1)")
|
34 |
+
add_text_sidebar = st.sidebar.text("Recipe preset(example#2)")
|
35 |
+
|
36 |
+
add_text_sidebar = st.sidebar.title("Mode:")
|
37 |
+
sampling_mode = st.sidebar.selectbox("select a Mode", index=0, options=["Beam Search", "Top-k Sampling"])
|
38 |
+
|
39 |
+
|
40 |
+
original_keywords = st.multiselect("Choose ingredients",
|
41 |
+
cfg["first_100"],
|
42 |
+
["parmesan cheese", "fresh oregano", "basil", "whole wheat flour"]
|
43 |
+
)
|
44 |
+
|
45 |
+
st.write("Add custom ingredients here:")
|
46 |
+
custom_keywords = st_tags(
|
47 |
+
label="",
|
48 |
+
text='Press enter to add more',
|
49 |
+
value=['salt'],
|
50 |
+
suggestions=cfg["next_100"],
|
51 |
+
maxtags = 15,
|
52 |
+
key='1')
|
53 |
+
all_ingredients = []
|
54 |
+
all_ingredients.extend(original_keywords)
|
55 |
+
all_ingredients.extend(custom_keywords)
|
56 |
+
all_ingredients = ", ".join(all_ingredients)
|
57 |
+
st.markdown("**Generate recipe for:** "+all_ingredients)
|
58 |
+
|
59 |
+
|
60 |
+
submit = st.button('Get Recipe!')
|
61 |
+
if submit:
|
62 |
+
with st.spinner('Generating recipe...'):
|
63 |
+
if sampling_mode == "Beam Search":
|
64 |
+
generated = generator(all_ingredients, return_tensors=True, return_text=False, **beam_search.generate_kwargs)
|
65 |
+
outputs = beam_search.post_generator(generated, tokenizer)
|
66 |
+
elif sampling_mode == "Top-k Sampling":
|
67 |
+
generated = generator(all_ingredients, return_tensors=True, return_text=False, **top_sampling.generate_kwargs)
|
68 |
+
outputs = top_sampling.post_generator(generated, tokenizer)
|
69 |
+
output = outputs[0]
|
70 |
+
markdown_output = ""
|
71 |
+
markdown_output += f"## {output['title'].capitalize()}\n"
|
72 |
+
markdown_output += f"#### Ingredients:\n"
|
73 |
+
for o in output["ingredients"]:
|
74 |
+
markdown_output += f"- {o}\n"
|
75 |
+
markdown_output += f"#### Directions:\n"
|
76 |
+
for o in output["directions"]:
|
77 |
+
markdown_output += f"- {o}\n"
|
78 |
+
st.markdown(markdown_output)
|
79 |
+
st.balloons()
|
80 |
+
|
demo/top_sampling.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from transformers import AutoModelForSeq2SeqLM
|
3 |
+
from transformers import AutoTokenizer
|
4 |
+
from transformers import pipeline
|
5 |
+
|
6 |
+
from pprint import pprint
|
7 |
+
import re
|
8 |
+
|
9 |
+
|
10 |
+
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
11 |
+
# MODEL_NAME_OR_PATH = "flax-community/t5-recipe-generation"
|
12 |
+
# tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME_OR_PATH, use_fast=True)
|
13 |
+
# model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME_OR_PATH)
|
14 |
+
|
15 |
+
|
16 |
+
def skip_special_tokens_and_prettify(text, tokenizer):
|
17 |
+
recipe_maps = {"<sep>": "--", "<section>": "\n"}
|
18 |
+
recipe_map_pattern = "|".join(map(re.escape, recipe_maps.keys()))
|
19 |
+
|
20 |
+
text = re.sub(
|
21 |
+
recipe_map_pattern,
|
22 |
+
lambda m: recipe_maps[m.group()],
|
23 |
+
re.sub("|".join(tokenizer.all_special_tokens), "", text)
|
24 |
+
)
|
25 |
+
|
26 |
+
data = {"title": "", "ingredients": [], "directions": []}
|
27 |
+
for section in text.split("\n"):
|
28 |
+
section = section.strip()
|
29 |
+
section = section.strip()
|
30 |
+
if section.startswith("title:"):
|
31 |
+
data["title"] = section.replace("title:", "").strip()
|
32 |
+
elif section.startswith("ingredients:"):
|
33 |
+
data["ingredients"] = [s.strip() for s in section.replace("ingredients:", "").split('--')]
|
34 |
+
elif section.startswith("directions:"):
|
35 |
+
data["directions"] = [s.strip() for s in section.replace("directions:", "").split('--')]
|
36 |
+
else:
|
37 |
+
pass
|
38 |
+
|
39 |
+
return data
|
40 |
+
|
41 |
+
|
42 |
+
def post_generator(output_tensors, tokenizer):
|
43 |
+
output_tensors = [output_tensors[i]["generated_token_ids"] for i in range(len(output_tensors))]
|
44 |
+
texts = tokenizer.batch_decode(output_tensors, skip_special_tokens=False)
|
45 |
+
texts = [skip_special_tokens_and_prettify(text, tokenizer) for text in texts]
|
46 |
+
return texts
|
47 |
+
|
48 |
+
|
49 |
+
# Example
|
50 |
+
generate_kwargs = {
|
51 |
+
"max_length": 512,
|
52 |
+
"min_length": 64,
|
53 |
+
"no_repeat_ngram_size": 3,
|
54 |
+
"do_sample": True,
|
55 |
+
"top_k": 60,
|
56 |
+
"top_p": 0.95,
|
57 |
+
"num_return_sequences": 3
|
58 |
+
}
|
59 |
+
# items = "potato, cheese"
|
60 |
+
# generator = pipeline("text2text-generation", model=model, tokenizer=tokenizer)
|
61 |
+
# generated = generator(items, return_tensors=True, return_text=False, **generate_kwargs)
|
62 |
+
# outputs = post_generator(generated, tokenizer)
|
63 |
+
# pprint(outputs)
|
notes/.keep
ADDED
File without changes
|
src/create_dataset.py
ADDED
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import ast
|
2 |
+
import logging
|
3 |
+
import os
|
4 |
+
import sys
|
5 |
+
from dataclasses import dataclass, field
|
6 |
+
|
7 |
+
import pandas as pd
|
8 |
+
from sklearn.model_selection import train_test_split
|
9 |
+
from tqdm import tqdm
|
10 |
+
from typing import Dict, List, Optional, Tuple
|
11 |
+
|
12 |
+
from datasets import load_dataset
|
13 |
+
from transformers import (
|
14 |
+
HfArgumentParser,
|
15 |
+
)
|
16 |
+
|
17 |
+
from data_utils import (
|
18 |
+
filter_by_lang_regex,
|
19 |
+
filter_by_steps,
|
20 |
+
filter_by_length,
|
21 |
+
filter_by_item,
|
22 |
+
filter_by_num_sents,
|
23 |
+
filter_by_num_tokens,
|
24 |
+
normalizer
|
25 |
+
)
|
26 |
+
|
27 |
+
logger = logging.getLogger(__name__)
|
28 |
+
|
29 |
+
|
30 |
+
@dataclass
|
31 |
+
class DataArguments:
|
32 |
+
"""
|
33 |
+
Arguments to which dataset we are going to set up.
|
34 |
+
"""
|
35 |
+
|
36 |
+
output_dir: str = field(
|
37 |
+
default=".",
|
38 |
+
metadata={"help": "The output directory where the config will be written."},
|
39 |
+
)
|
40 |
+
dataset_name: str = field(
|
41 |
+
default=None,
|
42 |
+
metadata={"help": "The name of the dataset to use (via the datasets library)."}
|
43 |
+
)
|
44 |
+
dataset_data_dir: Optional[str] = field(
|
45 |
+
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
|
46 |
+
)
|
47 |
+
cache_dir: Optional[str] = field(
|
48 |
+
default=None,
|
49 |
+
metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
|
50 |
+
)
|
51 |
+
|
52 |
+
|
53 |
+
def main():
|
54 |
+
parser = HfArgumentParser([DataArguments])
|
55 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
56 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
57 |
+
# let's parse it to get our arguments.
|
58 |
+
data_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))[0]
|
59 |
+
else:
|
60 |
+
data_args = parser.parse_args_into_dataclasses()[0]
|
61 |
+
|
62 |
+
# Setup logging
|
63 |
+
logging.basicConfig(
|
64 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
65 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
66 |
+
handlers=[logging.StreamHandler(sys.stdout)],
|
67 |
+
)
|
68 |
+
logger.setLevel(logging.INFO)
|
69 |
+
|
70 |
+
logger.info(f"Preparing the dataset")
|
71 |
+
|
72 |
+
if data_args.dataset_name is not None:
|
73 |
+
dataset = load_dataset(
|
74 |
+
data_args.dataset_name,
|
75 |
+
data_dir=data_args.dataset_data_dir,
|
76 |
+
cache_dir=data_args.cache_dir
|
77 |
+
)
|
78 |
+
else:
|
79 |
+
dataset = load_dataset(
|
80 |
+
data_args.dataset_name,
|
81 |
+
cache_dir=data_args.cache_dir
|
82 |
+
)
|
83 |
+
|
84 |
+
def cleaning(text, item_type="ner"):
|
85 |
+
# NOTE: DO THE CLEANING LATER
|
86 |
+
text = normalizer(text, do_lowercase=True)
|
87 |
+
return text
|
88 |
+
|
89 |
+
def recipe_preparation(item_dict):
|
90 |
+
ner = item_dict["ner"]
|
91 |
+
title = item_dict["title"]
|
92 |
+
ingredients = item_dict["ingredients"]
|
93 |
+
steps = item_dict["directions"]
|
94 |
+
|
95 |
+
conditions = []
|
96 |
+
conditions += [filter_by_item(ner, 2)]
|
97 |
+
conditions += [filter_by_length(title, 4)]
|
98 |
+
conditions += [filter_by_item(ingredients, 2)]
|
99 |
+
conditions += [filter_by_item(steps, 2)]
|
100 |
+
# conditions += filter_by_steps(" ".join(steps))
|
101 |
+
|
102 |
+
if not all(conditions):
|
103 |
+
return None
|
104 |
+
|
105 |
+
ner = ", ".join(ner)
|
106 |
+
ingredients = " <sep> ".join(ingredients)
|
107 |
+
steps = " <sep> ".join(steps)
|
108 |
+
|
109 |
+
# Cleaning
|
110 |
+
ner = cleaning(ner, "ner")
|
111 |
+
title = cleaning(title, "title")
|
112 |
+
ingredients = cleaning(ingredients, "ingredients")
|
113 |
+
steps = cleaning(steps, "steps")
|
114 |
+
|
115 |
+
return {
|
116 |
+
"inputs": ner,
|
117 |
+
# "targets": f"title: {title} <section> ingredients: {ingredients} <section> directions: {steps}"
|
118 |
+
"targets": f"title: {title} <section> ingredients: {ingredients} <section> directions: {steps}"
|
119 |
+
}
|
120 |
+
|
121 |
+
if len(dataset.keys()) > 1:
|
122 |
+
for subset in dataset.keys():
|
123 |
+
data_dict = []
|
124 |
+
for item in tqdm(dataset[subset], position=0, total=len(dataset[subset])):
|
125 |
+
item = recipe_preparation(item)
|
126 |
+
if item:
|
127 |
+
data_dict.append(item)
|
128 |
+
|
129 |
+
data_df = pd.DataFrame(data_dict)
|
130 |
+
logger.info(f"Preparation of [{subset}] set consists of {len(data_df)} records!")
|
131 |
+
|
132 |
+
output_path = os.path.join(data_args.output_dir, f"{subset}.csv")
|
133 |
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
134 |
+
data_df.to_csv(output_path, sep="\t", encoding="utf-8", index=False)
|
135 |
+
logger.info(f"Data saved here {output_path}")
|
136 |
+
else:
|
137 |
+
data_dict = []
|
138 |
+
subset = list(dataset.keys())[0]
|
139 |
+
for item in tqdm(dataset[subset], position=0, total=len(dataset[subset])):
|
140 |
+
item = recipe_preparation(item)
|
141 |
+
if item:
|
142 |
+
data_dict.append(item)
|
143 |
+
|
144 |
+
data_df = pd.DataFrame(data_dict)
|
145 |
+
|
146 |
+
logger.info(f"Preparation - [before] consists of {len(dataset[subset])} records!")
|
147 |
+
logger.info(f"Preparation - [after] consists of {len(data_df)} records!")
|
148 |
+
|
149 |
+
train, test = train_test_split(data_df, test_size=0.05, random_state=101)
|
150 |
+
|
151 |
+
train = train.reset_index(drop=True)
|
152 |
+
test = test.reset_index(drop=True)
|
153 |
+
|
154 |
+
logger.info(f"Preparation of [train] set consists of {len(train)} records!")
|
155 |
+
logger.info(f"Preparation of [test] set consists of {len(test)} records!")
|
156 |
+
|
157 |
+
os.makedirs(data_args.output_dir, exist_ok=True)
|
158 |
+
train.to_csv(os.path.join(data_args.output_dir, "train.csv"), sep="\t", encoding="utf-8", index=False)
|
159 |
+
test.to_csv(os.path.join(data_args.output_dir, "test.csv"), sep="\t", encoding="utf-8", index=False)
|
160 |
+
logger.info(f"Data saved here {data_args.output_dir}")
|
161 |
+
|
162 |
+
|
163 |
+
if __name__ == '__main__':
|
164 |
+
main()
|
src/data_utils.py
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from nltk.tokenize import wordpunct_tokenize as word_tokenize
|
2 |
+
from nltk.tokenize import sent_tokenize
|
3 |
+
|
4 |
+
import re
|
5 |
+
import six
|
6 |
+
import textwrap
|
7 |
+
|
8 |
+
_whitelist = r"[0-9a-z\,\.\/\<\>]+"
|
9 |
+
_regex = "0-9a-z\,\.\/\<\>"
|
10 |
+
|
11 |
+
|
12 |
+
def filter_by_lang_regex(text, ratio=0.7, regex="0-9a-z\,\.\/\<\>"):
|
13 |
+
candidate_text = re.sub(r"[^" + regex + "]+", " ", six.ensure_str(text), flags=re.IGNORECASE).replace(" ", "")
|
14 |
+
text = text.replace(" ", "")
|
15 |
+
|
16 |
+
return (len(candidate_text) / len(text)) > ratio
|
17 |
+
|
18 |
+
|
19 |
+
def filter_by_num_tokens(text, gt=64):
|
20 |
+
return len(word_tokenize(text)) > gt
|
21 |
+
|
22 |
+
|
23 |
+
def filter_by_num_sents(text, gt=2):
|
24 |
+
return len(sent_tokenize(text)) > gt
|
25 |
+
|
26 |
+
|
27 |
+
def filter_by_steps(text):
|
28 |
+
return re.search('(step|mix all)', text, re.IGNORECASE) is not None
|
29 |
+
|
30 |
+
|
31 |
+
def filter_by_length(text, gt=40):
|
32 |
+
return len(text) > gt
|
33 |
+
|
34 |
+
|
35 |
+
def filter_by_item(item_list, gt=4):
|
36 |
+
return len(item_list) > gt
|
37 |
+
|
38 |
+
|
39 |
+
def chars_to_preserve(sentence, whitelist):
|
40 |
+
try:
|
41 |
+
tokenized = re.findall(whitelist, sentence, re.IGNORECASE)
|
42 |
+
return " ".join(tokenized)
|
43 |
+
except Exception as error:
|
44 |
+
print(
|
45 |
+
textwrap.dedent(
|
46 |
+
f"""
|
47 |
+
Bad characters range {whitelist},
|
48 |
+
{error}
|
49 |
+
"""
|
50 |
+
)
|
51 |
+
)
|
52 |
+
raise
|
53 |
+
|
54 |
+
|
55 |
+
def normalizer(text, whitelist=r"[0-9a-z\,\.\/\<\>]+", do_lowercase=False):
|
56 |
+
if do_lowercase:
|
57 |
+
text = text.lower()
|
58 |
+
|
59 |
+
text = chars_to_preserve(text, whitelist=whitelist)
|
60 |
+
text = " ".join([word.strip() for word in text.split() if word.strip()])
|
61 |
+
text = text.strip()
|
62 |
+
|
63 |
+
return text
|
64 |
+
|
65 |
+
# _text = "Crust, Peanut Butter}Melt <sep> 1/2Butter, 2 c. Eggs, Filling, Semi- Sweet Chocolate Chips, Milk, Butter, " \
|
66 |
+
# "Frosting"
|
67 |
+
# out = normalizer(_text)
|
68 |
+
# print(out)
|
69 |
+
#
|
70 |
+
# _text = "step ... "
|
71 |
+
# print(re.search('(step|mix all)', _text, re.IGNORECASE) != None)
|
src/evaluation.py
ADDED
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pandas as pd
|
3 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
4 |
+
from sklearn.feature_extraction.text import CountVectorizer
|
5 |
+
|
6 |
+
from datasets import load_metric
|
7 |
+
|
8 |
+
import nltk
|
9 |
+
from nltk.tokenize import wordpunct_tokenize
|
10 |
+
from nltk.corpus import stopwords
|
11 |
+
import nltk.translate.bleu_score as bleu
|
12 |
+
from nltk.translate.bleu_score import SmoothingFunction
|
13 |
+
import nltk.translate.gleu_score as gleu
|
14 |
+
import nltk.translate.meteor_score as meteor
|
15 |
+
|
16 |
+
from jiwer import wer, mer
|
17 |
+
|
18 |
+
import re
|
19 |
+
import math
|
20 |
+
from collections import Counter
|
21 |
+
import string
|
22 |
+
from tqdm import tqdm
|
23 |
+
|
24 |
+
|
25 |
+
nltk.download('stopwords')
|
26 |
+
stopwords = stopwords.words("english")
|
27 |
+
|
28 |
+
|
29 |
+
df = pd.read_csv("./test_generated.csv", sep="\t")
|
30 |
+
true_recipes = df["true_recipe"].values.tolist()
|
31 |
+
generated_recipes = df["generated_recipe"].values.tolist()
|
32 |
+
|
33 |
+
def cleaning(text, rm_sep=True, rm_nl=True, rm_punk_stopwords=True):
|
34 |
+
if rm_sep:
|
35 |
+
text = text.replace("--", " ")
|
36 |
+
|
37 |
+
if rm_nl:
|
38 |
+
text = text.replace("\n", " ")
|
39 |
+
|
40 |
+
if rm_punk_stopwords:
|
41 |
+
text = " ".join([word.strip() for word in wordpunct_tokenize(text) if word not in string.punctuation and word not in stopwords and word])
|
42 |
+
else:
|
43 |
+
text = " ".join([word.strip() for word in wordpunct_tokenize(text) if word.strip()])
|
44 |
+
|
45 |
+
text = text.lower()
|
46 |
+
return text
|
47 |
+
|
48 |
+
X, Y = [], []
|
49 |
+
for x, y in tqdm(zip(true_recipes, generated_recipes), total=len(df)):
|
50 |
+
x, y = cleaning(x, True, True, True), cleaning(y, True, True, True)
|
51 |
+
|
52 |
+
if len(x) > 16 and len(y) > 16:
|
53 |
+
X.append(x)
|
54 |
+
Y.append(y)
|
55 |
+
|
56 |
+
|
57 |
+
print(f"Sample X: {X[0]}")
|
58 |
+
print(f"Sample Y: {Y[0]}")
|
59 |
+
|
60 |
+
def get_cosine(vec1, vec2):
|
61 |
+
intersection = set(vec1.keys()) & set(vec2.keys())
|
62 |
+
numerator = sum([vec1[x] * vec2[x] for x in intersection])
|
63 |
+
|
64 |
+
sum1 = sum([vec1[x]**2 for x in vec1.keys()])
|
65 |
+
sum2 = sum([vec2[x]**2 for x in vec2.keys()])
|
66 |
+
denominator = math.sqrt(sum1) * math.sqrt(sum2)
|
67 |
+
|
68 |
+
if not denominator:
|
69 |
+
return 0.0
|
70 |
+
else:
|
71 |
+
return float(numerator) / denominator
|
72 |
+
|
73 |
+
def text_to_vector(text):
|
74 |
+
word = re.compile(r'\w+')
|
75 |
+
words = word.findall(text)
|
76 |
+
return Counter(words)
|
77 |
+
|
78 |
+
def get_result(content_a, content_b):
|
79 |
+
text1 = content_a
|
80 |
+
text2 = content_b
|
81 |
+
|
82 |
+
vector1 = text_to_vector(text1)
|
83 |
+
vector2 = text_to_vector(text2)
|
84 |
+
|
85 |
+
cosine_result = get_cosine(vector1, vector2)
|
86 |
+
return cosine_result
|
87 |
+
|
88 |
+
|
89 |
+
cosim_scores = []
|
90 |
+
for i in tqdm(range(len(X))):
|
91 |
+
cosim_scores.append(get_result(X[i], Y[i]))
|
92 |
+
|
93 |
+
cosim_score = np.array(cosim_scores).mean()
|
94 |
+
print(f"Cosine similarity score: {cosim_score}") # 0.714542
|
95 |
+
|
96 |
+
X, Y = [], []
|
97 |
+
for x, y in tqdm(zip(true_recipes, generated_recipes), total=len(df)):
|
98 |
+
x, y = cleaning(x, True, True, False), cleaning(y, True, True, False)
|
99 |
+
|
100 |
+
if len(x) > 16 and len(y) > 16:
|
101 |
+
X.append(x)
|
102 |
+
Y.append(y)
|
103 |
+
|
104 |
+
|
105 |
+
wer = load_metric("wer")
|
106 |
+
wer_score = wer.compute(predictions=Y, references=X)
|
107 |
+
print(f"WER score: {wer_score}") # 0.70938
|
108 |
+
|
109 |
+
|
110 |
+
rouge = load_metric("rouge")
|
111 |
+
rouge_score = rouge.compute(predictions=Y, references=X, use_stemmer=True)
|
112 |
+
rouge_score = {key: value.mid.fmeasure * 100 for key, value in rouge_score.items()}
|
113 |
+
print(f"Rouge score: {rouge_score}") # {'rouge1': 56.30779082900833, 'rouge2': 29.07704230163075, 'rougeL': 45.812165960365924, 'rougeLsum': 45.813971137090654}
|
114 |
+
|
115 |
+
bleu = load_metric("bleu")
|
116 |
+
def postprocess_text(preds, labels):
|
117 |
+
preds = [wordpunct_tokenize(pred) for pred in preds]
|
118 |
+
labels = [[wordpunct_tokenize(label)] for label in labels]
|
119 |
+
|
120 |
+
return preds, labels
|
121 |
+
|
122 |
+
Y, X = postprocess_text(Y, X)
|
123 |
+
bleu_score = bleu.compute(predictions=Y, references=X)["bleu"]
|
124 |
+
print(f"BLEU score: {bleu_score}") # 0.203867
|
src/flax_to_pytorch.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import numpy as np
|
3 |
+
import jax.numpy as jnp
|
4 |
+
|
5 |
+
from transformers import AutoTokenizer
|
6 |
+
from transformers import FlaxT5ForConditionalGeneration
|
7 |
+
from transformers import T5ForConditionalGeneration
|
8 |
+
|
9 |
+
tokenizer = AutoTokenizer.from_pretrained("../")
|
10 |
+
model_fx = FlaxT5ForConditionalGeneration.from_pretrained("../")
|
11 |
+
model_pt = T5ForConditionalGeneration.from_pretrained("../", from_flax=True)
|
12 |
+
model_pt.save_pretrained("./")
|
13 |
+
|
14 |
+
text = "Hello To You"
|
15 |
+
e_input_ids_fx = tokenizer(text, return_tensors="np", padding=True, max_length=128, truncation=True)
|
16 |
+
d_input_ids_fx = jnp.ones((e_input_ids_fx.input_ids.shape[0], 1), dtype="i4") * model_fx.config.decoder_start_token_id
|
17 |
+
|
18 |
+
e_input_ids_pt = tokenizer(text, return_tensors="pt", padding=True, max_length=128, truncation=True)
|
19 |
+
d_input_ids_pt = np.ones((e_input_ids_pt.input_ids.shape[0], 1), dtype="i4") * model_pt.config.decoder_start_token_id
|
20 |
+
|
21 |
+
|
22 |
+
print(e_input_ids_fx)
|
23 |
+
print(d_input_ids_fx)
|
24 |
+
|
25 |
+
print()
|
26 |
+
|
27 |
+
encoder_pt = model_fx.encode(**e_input_ids_pt)
|
28 |
+
decoder_pt = model_fx.decode(d_input_ids_pt, encoder_pt)
|
29 |
+
logits_pt = decoder_pt.logits
|
30 |
+
print(logits_pt)
|
31 |
+
|
32 |
+
encoder_fx = model_fx.encode(**e_input_ids_fx)
|
33 |
+
decoder_fx = model_fx.decode(d_input_ids_fx, encoder_fx)
|
34 |
+
logits_fx = decoder_fx.logits
|
35 |
+
print(logits_fx)
|
src/flax_to_tf.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import numpy as np
|
3 |
+
import jax.numpy as jnp
|
4 |
+
|
5 |
+
from transformers import AutoTokenizer
|
6 |
+
from transformers import FlaxT5ForConditionalGeneration
|
7 |
+
from transformers import TFT5ForConditionalGeneration
|
8 |
+
|
9 |
+
tokenizer = AutoTokenizer.from_pretrained("../")
|
10 |
+
model_fx = FlaxT5ForConditionalGeneration.from_pretrained("../")
|
11 |
+
model_tf = TFT5ForConditionalGeneration.from_pretrained("./", from_pt=True)
|
12 |
+
model_tf.save_pretrained("./")
|
13 |
+
|
14 |
+
text = "Hello To You"
|
15 |
+
e_input_ids_fx = tokenizer(text, return_tensors="np", padding=True, max_length=128, truncation=True)
|
16 |
+
d_input_ids_fx = jnp.ones((e_input_ids_fx.input_ids.shape[0], 1), dtype="i4") * model_fx.config.decoder_start_token_id
|
17 |
+
|
18 |
+
e_input_ids_tf = tokenizer(text, return_tensors="tf", padding=True, max_length=128, truncation=True)
|
19 |
+
d_input_ids_tf = np.ones((e_input_ids_tf.input_ids.shape[0], 1), dtype="i4") * model_tf.config.decoder_start_token_id
|
20 |
+
|
21 |
+
|
22 |
+
print(e_input_ids_fx)
|
23 |
+
print(d_input_ids_fx)
|
24 |
+
|
25 |
+
print()
|
26 |
+
|
27 |
+
encoder_tf = model_fx.encode(**e_input_ids_tf)
|
28 |
+
decoder_tf = model_fx.decode(d_input_ids_tf, encoder_tf)
|
29 |
+
logits_tf = decoder_tf.logits
|
30 |
+
print(logits_tf)
|
31 |
+
|
32 |
+
encoder_fx = model_fx.encode(**e_input_ids_fx)
|
33 |
+
decoder_fx = model_fx.decode(d_input_ids_fx, encoder_fx)
|
34 |
+
logits_fx = decoder_fx.logits
|
35 |
+
print(logits_fx)
|
src/generation.py
ADDED
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
import os
|
3 |
+
import pandas as pd
|
4 |
+
import random
|
5 |
+
import re
|
6 |
+
import sys
|
7 |
+
import time
|
8 |
+
from dataclasses import dataclass, field
|
9 |
+
from functools import partial
|
10 |
+
from pathlib import Path
|
11 |
+
from typing import Callable, Optional
|
12 |
+
|
13 |
+
import jax
|
14 |
+
import jax.numpy as jnp
|
15 |
+
|
16 |
+
from filelock import FileLock
|
17 |
+
from flax import jax_utils, traverse_util
|
18 |
+
from flax.jax_utils import unreplicate
|
19 |
+
from flax.training import train_state
|
20 |
+
from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key
|
21 |
+
|
22 |
+
from transformers import FlaxAutoModelForSeq2SeqLM
|
23 |
+
from transformers import AutoTokenizer
|
24 |
+
|
25 |
+
from datasets import Dataset, load_dataset, load_metric
|
26 |
+
from tqdm import tqdm
|
27 |
+
import pandas as pd
|
28 |
+
|
29 |
+
|
30 |
+
print(jax.devices())
|
31 |
+
|
32 |
+
MODEL_NAME_OR_PATH = "../"
|
33 |
+
|
34 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME_OR_PATH, use_fast=True)
|
35 |
+
model = FlaxAutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME_OR_PATH)
|
36 |
+
|
37 |
+
prefix = "items: "
|
38 |
+
text_column = "inputs"
|
39 |
+
target_column = "targets"
|
40 |
+
max_source_length = 256
|
41 |
+
max_target_length = 1024
|
42 |
+
seed = 42
|
43 |
+
eval_batch_size = 64
|
44 |
+
# generation_kwargs = {
|
45 |
+
# "max_length": 1024,
|
46 |
+
# "min_length": 128,
|
47 |
+
# "no_repeat_ngram_size": 3,
|
48 |
+
# "do_sample": True,
|
49 |
+
# "top_k": 60,
|
50 |
+
# "top_p": 0.95
|
51 |
+
# }
|
52 |
+
generation_kwargs = {
|
53 |
+
"max_length": 1024,
|
54 |
+
"min_length": 64,
|
55 |
+
"no_repeat_ngram_size": 3,
|
56 |
+
"early_stopping": True,
|
57 |
+
"num_beams": 4,
|
58 |
+
"length_penalty": 1.5,
|
59 |
+
}
|
60 |
+
|
61 |
+
special_tokens = tokenizer.all_special_tokens
|
62 |
+
tokens_map = {
|
63 |
+
"<sep>": "--",
|
64 |
+
"<section>": "\n"
|
65 |
+
}
|
66 |
+
def skip_special_tokens(text, special_tokens):
|
67 |
+
for token in special_tokens:
|
68 |
+
text = text.replace(token, '')
|
69 |
+
|
70 |
+
return text
|
71 |
+
|
72 |
+
def target_postprocessing(texts, special_tokens):
|
73 |
+
if not isinstance(texts, list):
|
74 |
+
texts = [texts]
|
75 |
+
|
76 |
+
new_texts = []
|
77 |
+
for text in texts:
|
78 |
+
text = skip_special_tokens(text, special_tokens)
|
79 |
+
|
80 |
+
for k, v in tokens_map.items():
|
81 |
+
text = text.replace(k, v)
|
82 |
+
|
83 |
+
new_texts.append(text)
|
84 |
+
|
85 |
+
return new_texts
|
86 |
+
|
87 |
+
|
88 |
+
predict_dataset = load_dataset("csv", data_files={"test": "/home/m3hrdadfi/code/data/test.csv"}, delimiter="\t")["test"]
|
89 |
+
print(predict_dataset)
|
90 |
+
# predict_dataset = predict_dataset.select(range(10))
|
91 |
+
# print(predict_dataset)
|
92 |
+
column_names = predict_dataset.column_names
|
93 |
+
print(column_names)
|
94 |
+
|
95 |
+
|
96 |
+
# Setting padding="max_length" as we need fixed length inputs for jitted functions
|
97 |
+
def preprocess_function(examples):
|
98 |
+
inputs = examples[text_column]
|
99 |
+
targets = examples[target_column]
|
100 |
+
inputs = [prefix + inp for inp in inputs]
|
101 |
+
model_inputs = tokenizer(
|
102 |
+
inputs,
|
103 |
+
max_length=max_source_length,
|
104 |
+
padding="max_length",
|
105 |
+
truncation=True,
|
106 |
+
return_tensors="np"
|
107 |
+
)
|
108 |
+
|
109 |
+
# Setup the tokenizer for targets
|
110 |
+
with tokenizer.as_target_tokenizer():
|
111 |
+
labels = tokenizer(
|
112 |
+
targets,
|
113 |
+
max_length=max_target_length,
|
114 |
+
padding="max_length",
|
115 |
+
truncation=True,
|
116 |
+
return_tensors="np"
|
117 |
+
)
|
118 |
+
|
119 |
+
model_inputs["labels"] = labels["input_ids"]
|
120 |
+
|
121 |
+
return model_inputs
|
122 |
+
|
123 |
+
predict_dataset = predict_dataset.map(
|
124 |
+
preprocess_function,
|
125 |
+
batched=True,
|
126 |
+
num_proc=None,
|
127 |
+
remove_columns=column_names,
|
128 |
+
desc="Running tokenizer on prediction dataset",
|
129 |
+
)
|
130 |
+
|
131 |
+
def data_loader(rng: jax.random.PRNGKey, dataset: Dataset, batch_size: int, shuffle: bool = False):
|
132 |
+
"""
|
133 |
+
Returns batches of size `batch_size` from truncated `dataset`, sharded over all local devices.
|
134 |
+
Shuffle batches if `shuffle` is `True`.
|
135 |
+
"""
|
136 |
+
steps_per_epoch = len(dataset) // batch_size
|
137 |
+
|
138 |
+
if shuffle:
|
139 |
+
batch_idx = jax.random.permutation(rng, len(dataset))
|
140 |
+
else:
|
141 |
+
batch_idx = jnp.arange(len(dataset))
|
142 |
+
|
143 |
+
batch_idx = batch_idx[: steps_per_epoch * batch_size] # Skip incomplete batch.
|
144 |
+
batch_idx = batch_idx.reshape((steps_per_epoch, batch_size))
|
145 |
+
|
146 |
+
for idx in batch_idx:
|
147 |
+
batch = dataset[idx]
|
148 |
+
batch = {k: jnp.array(v) for k, v in batch.items()}
|
149 |
+
|
150 |
+
batch = shard(batch)
|
151 |
+
|
152 |
+
yield batch
|
153 |
+
|
154 |
+
rng = jax.random.PRNGKey(seed)
|
155 |
+
rng, dropout_rng = jax.random.split(rng)
|
156 |
+
rng, input_rng = jax.random.split(rng)
|
157 |
+
|
158 |
+
def generate_step(batch):
|
159 |
+
output_ids = model.generate(batch["input_ids"], attention_mask=batch["attention_mask"], **generation_kwargs)
|
160 |
+
return output_ids.sequences
|
161 |
+
|
162 |
+
p_generate_step = jax.pmap(generate_step, "batch")
|
163 |
+
|
164 |
+
pred_generations = []
|
165 |
+
pred_labels = []
|
166 |
+
pred_inputs = []
|
167 |
+
pred_loader = data_loader(input_rng, predict_dataset, eval_batch_size)
|
168 |
+
pred_steps = len(predict_dataset) // eval_batch_size
|
169 |
+
|
170 |
+
for _ in tqdm(range(pred_steps), desc="Predicting...", position=2, leave=False):
|
171 |
+
# Model forward
|
172 |
+
batch = next(pred_loader)
|
173 |
+
inputs = batch["input_ids"]
|
174 |
+
labels = batch["labels"]
|
175 |
+
|
176 |
+
generated_ids = p_generate_step(batch)
|
177 |
+
pred_generations.extend(jax.device_get(generated_ids.reshape(-1, generation_kwargs["max_length"])))
|
178 |
+
pred_labels.extend(jax.device_get(labels.reshape(-1, labels.shape[-1])))
|
179 |
+
pred_inputs.extend(jax.device_get(inputs.reshape(-1, inputs.shape[-1])))
|
180 |
+
|
181 |
+
inputs = tokenizer.batch_decode(pred_inputs, skip_special_tokens=True)
|
182 |
+
true_recipe = target_postprocessing(
|
183 |
+
tokenizer.batch_decode(pred_labels, skip_special_tokens=False),
|
184 |
+
special_tokens
|
185 |
+
)
|
186 |
+
generated_recipe = target_postprocessing(
|
187 |
+
tokenizer.batch_decode(pred_generations, skip_special_tokens=False),
|
188 |
+
special_tokens
|
189 |
+
)
|
190 |
+
test_output = {
|
191 |
+
"inputs": inputs,
|
192 |
+
"true_recipe": true_recipe,
|
193 |
+
"generated_recipe": generated_recipe
|
194 |
+
}
|
195 |
+
test_output = pd.DataFrame.from_dict(test_output)
|
196 |
+
test_output.to_csv("./generated_recipes_b.csv", sep="\t", index=False, encoding="utf-8")
|
src/prediction.py
ADDED
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import FlaxAutoModelForSeq2SeqLM
|
2 |
+
from transformers import AutoTokenizer
|
3 |
+
import textwrap
|
4 |
+
|
5 |
+
MODEL_NAME_OR_PATH = "flax-community/t5-recipe-generation"
|
6 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME_OR_PATH, use_fast=True)
|
7 |
+
model = FlaxAutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME_OR_PATH)
|
8 |
+
|
9 |
+
prefix = "items: "
|
10 |
+
# generation_kwargs = {
|
11 |
+
# "max_length": 1024,
|
12 |
+
# "min_length": 128,
|
13 |
+
# "no_repeat_ngram_size": 3,
|
14 |
+
# "do_sample": True,
|
15 |
+
# "top_k": 60,
|
16 |
+
# "top_p": 0.95
|
17 |
+
# }
|
18 |
+
generation_kwargs = {
|
19 |
+
"max_length": 512,
|
20 |
+
"min_length": 64,
|
21 |
+
"no_repeat_ngram_size": 3,
|
22 |
+
"early_stopping": True,
|
23 |
+
"num_beams": 5,
|
24 |
+
"length_penalty": 1.5,
|
25 |
+
}
|
26 |
+
|
27 |
+
special_tokens = tokenizer.all_special_tokens
|
28 |
+
tokens_map = {
|
29 |
+
"<sep>": "--",
|
30 |
+
"<section>": "\n"
|
31 |
+
}
|
32 |
+
def skip_special_tokens(text, special_tokens):
|
33 |
+
for token in special_tokens:
|
34 |
+
text = text.replace(token, '')
|
35 |
+
|
36 |
+
return text
|
37 |
+
|
38 |
+
def target_postprocessing(texts, special_tokens):
|
39 |
+
if not isinstance(texts, list):
|
40 |
+
texts = [texts]
|
41 |
+
|
42 |
+
new_texts = []
|
43 |
+
for text in texts:
|
44 |
+
text = skip_special_tokens(text, special_tokens)
|
45 |
+
|
46 |
+
for k, v in tokens_map.items():
|
47 |
+
text = text.replace(k, v)
|
48 |
+
|
49 |
+
new_texts.append(text)
|
50 |
+
|
51 |
+
return new_texts
|
52 |
+
|
53 |
+
def generation_function(texts):
|
54 |
+
_inputs = texts if isinstance(texts, list) else [texts]
|
55 |
+
inputs = [prefix + inp for inp in _inputs]
|
56 |
+
inputs = tokenizer(
|
57 |
+
inputs,
|
58 |
+
max_length=256,
|
59 |
+
padding="max_length",
|
60 |
+
truncation=True,
|
61 |
+
return_tensors='jax'
|
62 |
+
)
|
63 |
+
|
64 |
+
input_ids = inputs.input_ids
|
65 |
+
attention_mask = inputs.attention_mask
|
66 |
+
|
67 |
+
output_ids = model.generate(
|
68 |
+
input_ids=input_ids,
|
69 |
+
attention_mask=attention_mask,
|
70 |
+
**generation_kwargs
|
71 |
+
)
|
72 |
+
generated = output_ids.sequences
|
73 |
+
generated_recipe = target_postprocessing(
|
74 |
+
tokenizer.batch_decode(generated, skip_special_tokens=False),
|
75 |
+
special_tokens
|
76 |
+
)
|
77 |
+
return generated_recipe
|
78 |
+
|
79 |
+
|
80 |
+
items = [
|
81 |
+
"macaroni, butter, salt, bacon, milk, flour, pepper, cream corn",
|
82 |
+
"provolone cheese, bacon, bread, ginger"
|
83 |
+
]
|
84 |
+
generated = generation_function(items)
|
85 |
+
for text in generated:
|
86 |
+
sections = text.split("\n")
|
87 |
+
for section in sections:
|
88 |
+
section = section.strip()
|
89 |
+
if section.startswith("title:"):
|
90 |
+
section = section.replace("title:", "")
|
91 |
+
headline = "TITLE"
|
92 |
+
elif section.startswith("ingredients:"):
|
93 |
+
section = section.replace("ingredients:", "")
|
94 |
+
headline = "INGREDIENTS"
|
95 |
+
elif section.startswith("directions:"):
|
96 |
+
section = section.replace("directions:", "")
|
97 |
+
headline = "DIRECTIONS"
|
98 |
+
|
99 |
+
if headline == "TITLE":
|
100 |
+
print(f"[{headline}]: {section.strip().capitalize()}")
|
101 |
+
else:
|
102 |
+
section_info = [f" - {i+1}: {info.strip().capitalize()}" for i, info in enumerate(section.split("--"))]
|
103 |
+
print(f"[{headline}]:")
|
104 |
+
print("\n".join(section_info))
|
105 |
+
|
106 |
+
print("-" * 130)
|
src/requirements.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
datasets >= 1.1.3
|
2 |
+
jax>=0.2.8
|
3 |
+
jaxlib>=0.1.59
|
4 |
+
flax>=0.3.4
|
5 |
+
optax>=0.0.8
|
6 |
+
sacrebleu
|
7 |
+
jiwer
|
src/run.sh
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
export LC_ALL=C.UTF-8
|
4 |
+
export LANG=C.UTF-8
|
5 |
+
|
6 |
+
export OUTPUT_DIR=/home/m3hrdadfi/code/t5-recipe-generation
|
7 |
+
export MODEL_NAME_OR_PATH=t5-base
|
8 |
+
# export MODEL_NAME_OR_PATH=flax-community/t5-recipe-generation
|
9 |
+
export NUM_BEAMS=3
|
10 |
+
|
11 |
+
export TRAIN_FILE=/home/m3hrdadfi/code/data/train.csv
|
12 |
+
export VALIDATION_FILE=/home/m3hrdadfi/code/data/test.csv
|
13 |
+
export TEST_FILE=/home/m3hrdadfi/code/data/test.csv
|
14 |
+
export TEXT_COLUMN=inputs
|
15 |
+
export TARGET_COLUMN=targets
|
16 |
+
export MAX_SOURCE_LENGTH=256
|
17 |
+
export MAX_TARGET_LENGTH=1024
|
18 |
+
export SOURCE_PREFIX=items
|
19 |
+
export MAX_EVAL_SAMPLES=5000
|
20 |
+
|
21 |
+
export PER_DEVICE_TRAIN_BATCH_SIZE=8
|
22 |
+
export PER_DEVICE_EVAL_BATCH_SIZE=8
|
23 |
+
export GRADIENT_ACCUMULATION_STEPS=2
|
24 |
+
export NUM_TRAIN_EPOCHS=5.0
|
25 |
+
export LEARNING_RATE=5e-4
|
26 |
+
export WARMUP_STEPS=5000
|
27 |
+
export LOGGING_STEPS=500
|
28 |
+
export EVAL_STEPS=2500
|
29 |
+
export SAVE_STEPS=2500
|
30 |
+
|
31 |
+
python src/run_recipe_nlg_flax.py \
|
32 |
+
--output_dir="$OUTPUT_DIR" \
|
33 |
+
--train_file="$TRAIN_FILE" \
|
34 |
+
--validation_file="$VALIDATION_FILE" \
|
35 |
+
--max_eval_samples=$MAX_EVAL_SAMPLES \
|
36 |
+
--text_column="$TEXT_COLUMN" \
|
37 |
+
--target_column="$TARGET_COLUMN" \
|
38 |
+
--source_prefix="$SOURCE_PREFIX: " \
|
39 |
+
--max_source_length="$MAX_SOURCE_LENGTH" \
|
40 |
+
--max_target_length="$MAX_TARGET_LENGTH" \
|
41 |
+
--model_name_or_path="$MODEL_NAME_OR_PATH" \
|
42 |
+
--extra_tokens="" \
|
43 |
+
--special_tokens="<sep>,<section>" \
|
44 |
+
--per_device_train_batch_size=$PER_DEVICE_TRAIN_BATCH_SIZE \
|
45 |
+
--per_device_eval_batch_size=$PER_DEVICE_EVAL_BATCH_SIZE \
|
46 |
+
--gradient_accumulation_steps=$GRADIENT_ACCUMULATION_STEPS \
|
47 |
+
--num_train_epochs=$NUM_TRAIN_EPOCHS \
|
48 |
+
--learning_rate=$LEARNING_RATE \
|
49 |
+
--warmup_steps=$WARMUP_STEPS \
|
50 |
+
--logging_step=$LOGGING_STEPS \
|
51 |
+
--eval_steps=$EVAL_STEPS \
|
52 |
+
--save_steps=$SAVE_STEPS \
|
53 |
+
--prediction_debug \
|
54 |
+
--do_train \
|
55 |
+
--do_eval \
|
56 |
+
--overwrite_output_dir \
|
57 |
+
--predict_with_generate \
|
58 |
+
--push_to_hub
|
src/run_recipe_nlg_flax.py
ADDED
@@ -0,0 +1,881 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# coding=utf-8
|
3 |
+
# Copyright 2021 The HuggingFace Team All rights reserved.
|
4 |
+
#
|
5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
+
# you may not use this file except in compliance with the License.
|
7 |
+
# You may obtain a copy of the License at
|
8 |
+
#
|
9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
+
#
|
11 |
+
# Unless required by applicable law or agreed to in writing, software
|
12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
+
# See the License for the specific language governing permissions and
|
15 |
+
# limitations under the License.
|
16 |
+
"""
|
17 |
+
Fine-tuning the library models for recipe-generation.
|
18 |
+
"""
|
19 |
+
# You can also adapt this script on your own sequence to sequence task. Pointers for this are left as comments.
|
20 |
+
|
21 |
+
import logging
|
22 |
+
import os
|
23 |
+
import random
|
24 |
+
import re
|
25 |
+
import sys
|
26 |
+
import time
|
27 |
+
from dataclasses import dataclass, field
|
28 |
+
from functools import partial
|
29 |
+
from pathlib import Path
|
30 |
+
from typing import Callable, Optional
|
31 |
+
|
32 |
+
import datasets
|
33 |
+
import nltk # Here to have a nice missing dependency error message early on
|
34 |
+
import numpy as np
|
35 |
+
from datasets import Dataset, load_dataset, load_metric
|
36 |
+
from tqdm import tqdm
|
37 |
+
|
38 |
+
import jax
|
39 |
+
import jax.numpy as jnp
|
40 |
+
import optax
|
41 |
+
import transformers
|
42 |
+
from filelock import FileLock
|
43 |
+
from flax import jax_utils, traverse_util
|
44 |
+
from flax.jax_utils import unreplicate
|
45 |
+
from flax.training import train_state
|
46 |
+
from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key
|
47 |
+
from transformers import (
|
48 |
+
CONFIG_MAPPING,
|
49 |
+
FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
|
50 |
+
AutoConfig,
|
51 |
+
AutoTokenizer,
|
52 |
+
FlaxAutoModelForSeq2SeqLM,
|
53 |
+
HfArgumentParser,
|
54 |
+
TrainingArguments,
|
55 |
+
is_tensorboard_available,
|
56 |
+
)
|
57 |
+
from transformers.file_utils import is_offline_mode
|
58 |
+
|
59 |
+
logger = logging.getLogger(__name__)
|
60 |
+
|
61 |
+
try:
|
62 |
+
nltk.data.find("tokenizers/punkt")
|
63 |
+
except (LookupError, OSError):
|
64 |
+
if is_offline_mode():
|
65 |
+
raise LookupError(
|
66 |
+
"Offline mode: run this script without TRANSFORMERS_OFFLINE first to download nltk data files"
|
67 |
+
)
|
68 |
+
with FileLock(".lock") as lock:
|
69 |
+
nltk.download("punkt", quiet=True)
|
70 |
+
|
71 |
+
MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.keys())
|
72 |
+
MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
|
73 |
+
|
74 |
+
|
75 |
+
@dataclass
|
76 |
+
class ModelArguments:
|
77 |
+
"""
|
78 |
+
Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
|
79 |
+
"""
|
80 |
+
|
81 |
+
model_name_or_path: Optional[str] = field(
|
82 |
+
default=None,
|
83 |
+
metadata={
|
84 |
+
"help": "The model checkpoint for weights initialization."
|
85 |
+
"Don't set if you want to train a model from scratch."
|
86 |
+
},
|
87 |
+
)
|
88 |
+
model_type: Optional[str] = field(
|
89 |
+
default=None,
|
90 |
+
metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
|
91 |
+
)
|
92 |
+
config_name: Optional[str] = field(
|
93 |
+
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
|
94 |
+
)
|
95 |
+
tokenizer_name: Optional[str] = field(
|
96 |
+
default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
|
97 |
+
)
|
98 |
+
cache_dir: Optional[str] = field(
|
99 |
+
default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
|
100 |
+
)
|
101 |
+
use_fast_tokenizer: bool = field(
|
102 |
+
default=True,
|
103 |
+
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
|
104 |
+
)
|
105 |
+
dtype: Optional[str] = field(
|
106 |
+
default="float32",
|
107 |
+
metadata={
|
108 |
+
"help": "Floating-point format in which the model weights should be initialized and trained. Choose one of `[float32, float16, bfloat16]`."
|
109 |
+
},
|
110 |
+
)
|
111 |
+
|
112 |
+
|
113 |
+
@dataclass
|
114 |
+
class DataTrainingArguments:
|
115 |
+
"""
|
116 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
117 |
+
"""
|
118 |
+
|
119 |
+
dataset_name: Optional[str] = field(
|
120 |
+
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
|
121 |
+
)
|
122 |
+
dataset_config_name: Optional[str] = field(
|
123 |
+
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
|
124 |
+
)
|
125 |
+
text_column: Optional[str] = field(
|
126 |
+
default=None,
|
127 |
+
metadata={"help": "The name of the column in the datasets containing the inputs (for generation)."},
|
128 |
+
)
|
129 |
+
target_column: Optional[str] = field(
|
130 |
+
default=None,
|
131 |
+
metadata={"help": "The name of the column in the datasets containing the targets (for generation)."},
|
132 |
+
)
|
133 |
+
train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
|
134 |
+
validation_file: Optional[str] = field(
|
135 |
+
default=None,
|
136 |
+
metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
|
137 |
+
)
|
138 |
+
test_file: Optional[str] = field(
|
139 |
+
default=None,
|
140 |
+
metadata={"help": "An optional input evaluation data file to predict the perplexity on (a text file)."},
|
141 |
+
)
|
142 |
+
max_source_length: Optional[int] = field(
|
143 |
+
default=128,
|
144 |
+
metadata={
|
145 |
+
"help": "The maximum total input sequence length after tokenization. Sequences longer "
|
146 |
+
"than this will be truncated, sequences shorter will be padded."
|
147 |
+
},
|
148 |
+
)
|
149 |
+
max_target_length: Optional[int] = field(
|
150 |
+
default=1024,
|
151 |
+
metadata={
|
152 |
+
"help": "The maximum total sequence length for target text after tokenization. Sequences longer "
|
153 |
+
"than this will be truncated, sequences shorter will be padded."
|
154 |
+
},
|
155 |
+
)
|
156 |
+
val_max_target_length: Optional[int] = field(
|
157 |
+
default=None,
|
158 |
+
metadata={
|
159 |
+
"help": "The maximum total sequence length for validation target text after tokenization. Sequences longer "
|
160 |
+
"than this will be truncated, sequences shorter will be padded. Will default to `max_target_length`."
|
161 |
+
"This argument is also used to override the `max_length` param of `model.generate`, which is used "
|
162 |
+
"during evaluation."
|
163 |
+
},
|
164 |
+
)
|
165 |
+
max_train_samples: Optional[int] = field(
|
166 |
+
default=None,
|
167 |
+
metadata={
|
168 |
+
"help": "For debugging purposes or quicker training, truncate the number of training examples to this "
|
169 |
+
"value if set."
|
170 |
+
},
|
171 |
+
)
|
172 |
+
max_eval_samples: Optional[int] = field(
|
173 |
+
default=None,
|
174 |
+
metadata={
|
175 |
+
"help": "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
|
176 |
+
"value if set."
|
177 |
+
},
|
178 |
+
)
|
179 |
+
max_predict_samples: Optional[int] = field(
|
180 |
+
default=None,
|
181 |
+
metadata={
|
182 |
+
"help": "For debugging purposes or quicker training, truncate the number of prediction examples to this "
|
183 |
+
"value if set."
|
184 |
+
},
|
185 |
+
)
|
186 |
+
preprocessing_num_workers: Optional[int] = field(
|
187 |
+
default=None,
|
188 |
+
metadata={"help": "The number of processes to use for the preprocessing."},
|
189 |
+
)
|
190 |
+
source_prefix: Optional[str] = field(
|
191 |
+
default=None, metadata={"help": "A prefix to add before every source text (useful for T5 models)."}
|
192 |
+
)
|
193 |
+
predict_with_generate: bool = field(
|
194 |
+
default=False, metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."}
|
195 |
+
)
|
196 |
+
num_beams: Optional[int] = field(
|
197 |
+
default=None,
|
198 |
+
metadata={
|
199 |
+
"help": "Number of beams to use for evaluation. This argument will be passed to `model.generate`, "
|
200 |
+
"which is used during evaluation."
|
201 |
+
},
|
202 |
+
)
|
203 |
+
overwrite_cache: bool = field(
|
204 |
+
default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
|
205 |
+
)
|
206 |
+
extra_tokens: str = field(
|
207 |
+
default=None,
|
208 |
+
metadata={"help": "A text list of extra tokens separated by `,` that you want to add to the vocab."},
|
209 |
+
)
|
210 |
+
special_tokens: str = field(
|
211 |
+
default=None,
|
212 |
+
metadata={"help": "A list of special tokens separated by `,` that you want to add to the vocab."},
|
213 |
+
)
|
214 |
+
prediction_debug: bool = field(
|
215 |
+
default=False,
|
216 |
+
metadata={
|
217 |
+
"help": "Whether to show some examples of the model prediction"
|
218 |
+
},
|
219 |
+
)
|
220 |
+
|
221 |
+
def __post_init__(self):
|
222 |
+
if self.dataset_name is None and self.train_file is None and self.validation_file is None:
|
223 |
+
raise ValueError("Need either a dataset name or a training/validation file.")
|
224 |
+
else:
|
225 |
+
if self.train_file is not None:
|
226 |
+
extension = self.train_file.split(".")[-1]
|
227 |
+
assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
|
228 |
+
if self.validation_file is not None:
|
229 |
+
extension = self.validation_file.split(".")[-1]
|
230 |
+
assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."
|
231 |
+
if self.val_max_target_length is None:
|
232 |
+
self.val_max_target_length = self.max_target_length
|
233 |
+
|
234 |
+
|
235 |
+
class TrainState(train_state.TrainState):
|
236 |
+
dropout_rng: jnp.ndarray
|
237 |
+
|
238 |
+
def replicate(self):
|
239 |
+
return jax_utils.replicate(self).replace(dropout_rng=shard_prng_key(self.dropout_rng))
|
240 |
+
|
241 |
+
|
242 |
+
def data_loader(rng: jax.random.PRNGKey, dataset: Dataset, batch_size: int, shuffle: bool = False):
|
243 |
+
"""
|
244 |
+
Returns batches of size `batch_size` from truncated `dataset`, sharded over all local devices.
|
245 |
+
Shuffle batches if `shuffle` is `True`.
|
246 |
+
"""
|
247 |
+
steps_per_epoch = len(dataset) // batch_size
|
248 |
+
|
249 |
+
if shuffle:
|
250 |
+
batch_idx = jax.random.permutation(rng, len(dataset))
|
251 |
+
else:
|
252 |
+
batch_idx = jnp.arange(len(dataset))
|
253 |
+
|
254 |
+
batch_idx = batch_idx[: steps_per_epoch * batch_size] # Skip incomplete batch.
|
255 |
+
batch_idx = batch_idx.reshape((steps_per_epoch, batch_size))
|
256 |
+
|
257 |
+
for idx in batch_idx:
|
258 |
+
batch = dataset[idx]
|
259 |
+
batch = {k: jnp.array(v) for k, v in batch.items()}
|
260 |
+
|
261 |
+
batch = shard(batch)
|
262 |
+
|
263 |
+
yield batch
|
264 |
+
|
265 |
+
|
266 |
+
# def write_metric(summary_writer, train_metrics, eval_metrics, train_time, step):
|
267 |
+
# summary_writer.scalar("train_time", train_time, step)
|
268 |
+
#
|
269 |
+
# train_metrics = get_metrics(train_metrics)
|
270 |
+
# for key, vals in train_metrics.items():
|
271 |
+
# tag = f"train_{key}"
|
272 |
+
# for i, val in enumerate(vals):
|
273 |
+
# summary_writer.scalar(tag, val, step - len(vals) + i + 1)
|
274 |
+
#
|
275 |
+
# for metric_name, value in eval_metrics.items():
|
276 |
+
# summary_writer.scalar(f"eval_{metric_name}", value, step)
|
277 |
+
#
|
278 |
+
|
279 |
+
def write_train_metric(summary_writer, train_metrics, train_time, step):
|
280 |
+
summary_writer.scalar("train_time", train_time, step)
|
281 |
+
|
282 |
+
train_metrics = get_metrics(train_metrics)
|
283 |
+
for key, vals in train_metrics.items():
|
284 |
+
tag = f"train_{key}"
|
285 |
+
for i, val in enumerate(vals):
|
286 |
+
summary_writer.scalar(tag, val, step - len(vals) + i + 1)
|
287 |
+
|
288 |
+
|
289 |
+
def write_eval_metric(summary_writer, eval_metrics, step):
|
290 |
+
for metric_name, value in eval_metrics.items():
|
291 |
+
summary_writer.scalar(f"eval_{metric_name}", value, step)
|
292 |
+
|
293 |
+
|
294 |
+
def create_learning_rate_fn(
|
295 |
+
train_ds_size: int, train_batch_size: int, num_train_epochs: int, num_warmup_steps: int, learning_rate: float
|
296 |
+
) -> Callable[[int], jnp.array]:
|
297 |
+
"""Returns a linear warmup, linear_decay learning rate function."""
|
298 |
+
steps_per_epoch = train_ds_size // train_batch_size
|
299 |
+
num_train_steps = steps_per_epoch * num_train_epochs
|
300 |
+
warmup_fn = optax.linear_schedule(init_value=0.0, end_value=learning_rate, transition_steps=num_warmup_steps)
|
301 |
+
decay_fn = optax.linear_schedule(
|
302 |
+
init_value=learning_rate, end_value=0, transition_steps=num_train_steps - num_warmup_steps
|
303 |
+
)
|
304 |
+
schedule_fn = optax.join_schedules(schedules=[warmup_fn, decay_fn], boundaries=[num_warmup_steps])
|
305 |
+
return schedule_fn
|
306 |
+
|
307 |
+
|
308 |
+
def main():
|
309 |
+
# See all possible arguments in src/transformers/training_args.py
|
310 |
+
# or by passing the --help flag to this script.
|
311 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
312 |
+
|
313 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
|
314 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
315 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
316 |
+
# let's parse it to get our arguments.
|
317 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
318 |
+
else:
|
319 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
320 |
+
|
321 |
+
if (
|
322 |
+
os.path.exists(training_args.output_dir)
|
323 |
+
and os.listdir(training_args.output_dir)
|
324 |
+
and training_args.do_train
|
325 |
+
and not training_args.overwrite_output_dir
|
326 |
+
):
|
327 |
+
raise ValueError(
|
328 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty."
|
329 |
+
"Use --overwrite_output_dir to overcome."
|
330 |
+
)
|
331 |
+
|
332 |
+
# Make one log on every process with the configuration for debugging.
|
333 |
+
logging.basicConfig(
|
334 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
335 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
336 |
+
level=logging.INFO,
|
337 |
+
)
|
338 |
+
# Setup logging, we only want one process per machine to log things on the screen.
|
339 |
+
logger.setLevel(logging.INFO if jax.process_index() == 0 else logging.ERROR)
|
340 |
+
if jax.process_index() == 0:
|
341 |
+
datasets.utils.logging.set_verbosity_warning()
|
342 |
+
transformers.utils.logging.set_verbosity_info()
|
343 |
+
else:
|
344 |
+
datasets.utils.logging.set_verbosity_error()
|
345 |
+
transformers.utils.logging.set_verbosity_error()
|
346 |
+
|
347 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
348 |
+
logger.info(f"Training/evaluation parameters {training_args}")
|
349 |
+
logger.info(f"List of TPUs {jax.devices()}")
|
350 |
+
|
351 |
+
# Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below)
|
352 |
+
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
|
353 |
+
# (the dataset will be downloaded automatically from the datasets Hub).
|
354 |
+
#
|
355 |
+
# For CSV/JSON files this script will use the first column for the full texts and the second column for the
|
356 |
+
# summaries (unless you specify column names for this with the `text_column` and `summary_column` arguments).
|
357 |
+
#
|
358 |
+
if data_args.dataset_name is not None:
|
359 |
+
# Downloading and loading a dataset from the hub.
|
360 |
+
dataset = load_dataset(
|
361 |
+
data_args.dataset_name,
|
362 |
+
data_args.dataset_config_name,
|
363 |
+
cache_dir=model_args.cache_dir,
|
364 |
+
keep_in_memory=False
|
365 |
+
)
|
366 |
+
else:
|
367 |
+
data_files = {}
|
368 |
+
|
369 |
+
if data_args.train_file is not None:
|
370 |
+
data_files["train"] = data_args.train_file
|
371 |
+
extension = data_args.train_file.split(".")[-1]
|
372 |
+
if data_args.validation_file is not None:
|
373 |
+
data_files["validation"] = data_args.validation_file
|
374 |
+
extension = data_args.validation_file.split(".")[-1]
|
375 |
+
if data_args.test_file is not None:
|
376 |
+
data_files["test"] = data_args.test_file
|
377 |
+
extension = data_args.test_file.split(".")[-1]
|
378 |
+
|
379 |
+
logger.info(data_files)
|
380 |
+
dataset = load_dataset(
|
381 |
+
extension,
|
382 |
+
data_files=data_files,
|
383 |
+
delimiter="\t",
|
384 |
+
cache_dir=model_args.cache_dir
|
385 |
+
)
|
386 |
+
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
|
387 |
+
# https://huggingface.co/docs/datasets/loading_datasets.html.
|
388 |
+
|
389 |
+
# Load pretrained model and tokenizer
|
390 |
+
|
391 |
+
if model_args.config_name:
|
392 |
+
config = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir)
|
393 |
+
elif model_args.model_name_or_path:
|
394 |
+
config = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir)
|
395 |
+
else:
|
396 |
+
config = CONFIG_MAPPING[model_args.model_type]()
|
397 |
+
logger.warning("You are instantiating a new config instance from scratch.")
|
398 |
+
|
399 |
+
if model_args.tokenizer_name:
|
400 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
401 |
+
model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
|
402 |
+
)
|
403 |
+
elif model_args.model_name_or_path:
|
404 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
405 |
+
model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
|
406 |
+
)
|
407 |
+
else:
|
408 |
+
raise ValueError(
|
409 |
+
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
|
410 |
+
"You can do it from another script, save it, and load it from here, using --tokenizer_name."
|
411 |
+
)
|
412 |
+
|
413 |
+
if data_args.extra_tokens and isinstance(data_args.extra_tokens, str):
|
414 |
+
extra_tokens = list(data_args.extra_tokens.split(","))
|
415 |
+
if len(extra_tokens) > 0:
|
416 |
+
logger.info(f"*** Adding extra tokens: {extra_tokens} ***")
|
417 |
+
tokenizer.add_tokens(extra_tokens, special_tokens=False)
|
418 |
+
|
419 |
+
if data_args.special_tokens and isinstance(data_args.special_tokens, str):
|
420 |
+
special_tokens = list(data_args.special_tokens.split(","))
|
421 |
+
if len(special_tokens) > 0:
|
422 |
+
logger.info(f"*** Adding special tokens: {special_tokens} ***")
|
423 |
+
tokenizer.add_tokens(special_tokens, special_tokens=True)
|
424 |
+
|
425 |
+
if model_args.model_name_or_path:
|
426 |
+
model = FlaxAutoModelForSeq2SeqLM.from_pretrained(
|
427 |
+
model_args.model_name_or_path, config=config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
|
428 |
+
)
|
429 |
+
else:
|
430 |
+
model = FlaxAutoModelForSeq2SeqLM.from_config(
|
431 |
+
config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
|
432 |
+
)
|
433 |
+
|
434 |
+
if model.config.decoder_start_token_id is None:
|
435 |
+
raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined")
|
436 |
+
|
437 |
+
prefix = data_args.source_prefix if data_args.source_prefix is not None else ""
|
438 |
+
|
439 |
+
# Preprocessing the datasets.
|
440 |
+
# We need to tokenize inputs and targets.
|
441 |
+
if training_args.do_train:
|
442 |
+
column_names = dataset["train"].column_names
|
443 |
+
elif training_args.do_eval:
|
444 |
+
column_names = dataset["validation"].column_names
|
445 |
+
elif training_args.do_predict:
|
446 |
+
column_names = dataset["test"].column_names
|
447 |
+
else:
|
448 |
+
logger.info("There is nothing to do. Please pass `do_train`, `do_eval` and/or `do_predict`.")
|
449 |
+
return
|
450 |
+
|
451 |
+
# Get the column names for input/target.
|
452 |
+
if data_args.text_column is None:
|
453 |
+
text_column = column_names[0]
|
454 |
+
else:
|
455 |
+
text_column = data_args.text_column
|
456 |
+
if text_column not in column_names:
|
457 |
+
raise ValueError(
|
458 |
+
f"--text_column' value '{data_args.text_column}' needs to be one of: {', '.join(column_names)}"
|
459 |
+
)
|
460 |
+
if data_args.target_column is None:
|
461 |
+
target_column = column_names[1]
|
462 |
+
else:
|
463 |
+
target_column = data_args.target_column
|
464 |
+
if target_column not in column_names:
|
465 |
+
raise ValueError(
|
466 |
+
f"--target_column' value '{data_args.target_column}' needs to be one of: {', '.join(column_names)}"
|
467 |
+
)
|
468 |
+
|
469 |
+
# Temporarily set max_target_length for training.
|
470 |
+
max_target_length = data_args.max_target_length
|
471 |
+
|
472 |
+
# In Flax, for seq2seq models we need to pass `decoder_input_ids`
|
473 |
+
# as the Flax models don't accept `labels`, we need to prepare the decoder_input_ids here
|
474 |
+
# for that dynamically import the `shift_tokens_right` function from the model file
|
475 |
+
model_module = __import__(model.__module__, fromlist=["shift_tokens_tight"])
|
476 |
+
shift_tokens_right_fn = getattr(model_module, "shift_tokens_right")
|
477 |
+
|
478 |
+
# Setting padding="max_length" as we need fixed length inputs for jitted functions
|
479 |
+
def preprocess_function(examples):
|
480 |
+
inputs = examples[text_column]
|
481 |
+
targets = examples[target_column]
|
482 |
+
inputs = [prefix + inp for inp in inputs]
|
483 |
+
model_inputs = tokenizer(
|
484 |
+
inputs, max_length=data_args.max_source_length, padding="max_length", truncation=True, return_tensors="np"
|
485 |
+
)
|
486 |
+
|
487 |
+
# Setup the tokenizer for targets
|
488 |
+
with tokenizer.as_target_tokenizer():
|
489 |
+
labels = tokenizer(
|
490 |
+
targets, max_length=max_target_length, padding="max_length", truncation=True, return_tensors="np"
|
491 |
+
)
|
492 |
+
|
493 |
+
model_inputs["labels"] = labels["input_ids"]
|
494 |
+
decoder_input_ids = shift_tokens_right_fn(
|
495 |
+
jnp.array(labels["input_ids"]), config.pad_token_id, config.decoder_start_token_id
|
496 |
+
)
|
497 |
+
model_inputs["decoder_input_ids"] = np.asarray(decoder_input_ids)
|
498 |
+
|
499 |
+
# We need decoder_attention_mask so we can ignore pad tokens from loss
|
500 |
+
model_inputs["decoder_attention_mask"] = labels["attention_mask"]
|
501 |
+
|
502 |
+
return model_inputs
|
503 |
+
|
504 |
+
if training_args.do_train:
|
505 |
+
if "train" not in dataset:
|
506 |
+
raise ValueError("--do_train requires a train dataset")
|
507 |
+
train_dataset = dataset["train"]
|
508 |
+
if data_args.max_train_samples is not None:
|
509 |
+
train_dataset = train_dataset.select(range(data_args.max_train_samples))
|
510 |
+
train_dataset = train_dataset.map(
|
511 |
+
preprocess_function,
|
512 |
+
batched=True,
|
513 |
+
num_proc=data_args.preprocessing_num_workers,
|
514 |
+
remove_columns=column_names,
|
515 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
516 |
+
desc="Running tokenizer on train dataset",
|
517 |
+
)
|
518 |
+
|
519 |
+
if training_args.do_eval:
|
520 |
+
max_target_length = data_args.val_max_target_length
|
521 |
+
if "validation" not in dataset:
|
522 |
+
raise ValueError("--do_eval requires a validation dataset")
|
523 |
+
eval_dataset = dataset["validation"]
|
524 |
+
if data_args.max_eval_samples is not None:
|
525 |
+
eval_dataset = eval_dataset.select(range(data_args.max_eval_samples))
|
526 |
+
eval_dataset = eval_dataset.map(
|
527 |
+
preprocess_function,
|
528 |
+
batched=True,
|
529 |
+
num_proc=data_args.preprocessing_num_workers,
|
530 |
+
remove_columns=column_names,
|
531 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
532 |
+
desc="Running tokenizer on validation dataset",
|
533 |
+
)
|
534 |
+
|
535 |
+
if training_args.do_predict:
|
536 |
+
max_target_length = data_args.val_max_target_length
|
537 |
+
if "test" not in dataset:
|
538 |
+
raise ValueError("--do_predict requires a test dataset")
|
539 |
+
predict_dataset = dataset["test"]
|
540 |
+
if data_args.max_predict_samples is not None:
|
541 |
+
predict_dataset = predict_dataset.select(range(data_args.max_predict_samples))
|
542 |
+
predict_dataset = predict_dataset.map(
|
543 |
+
preprocess_function,
|
544 |
+
batched=True,
|
545 |
+
num_proc=data_args.preprocessing_num_workers,
|
546 |
+
remove_columns=column_names,
|
547 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
548 |
+
desc="Running tokenizer on prediction dataset",
|
549 |
+
)
|
550 |
+
|
551 |
+
# Metrics
|
552 |
+
bleu = load_metric("sacrebleu")
|
553 |
+
wer = load_metric("wer")
|
554 |
+
|
555 |
+
def skip_special_tokens_text(text):
|
556 |
+
new_text = []
|
557 |
+
for word in text.split():
|
558 |
+
word = word.strip()
|
559 |
+
if word:
|
560 |
+
if word not in special_tokens:
|
561 |
+
new_text.append(word)
|
562 |
+
|
563 |
+
return " ".join(new_text)
|
564 |
+
|
565 |
+
def skip_special_tokens_texts(texts):
|
566 |
+
if isinstance(texts, list):
|
567 |
+
new_texts = [skip_special_tokens_text(text) for text in texts]
|
568 |
+
elif isinstance(texts, str):
|
569 |
+
new_texts = skip_special_tokens_text(texts)
|
570 |
+
else:
|
571 |
+
new_texts = []
|
572 |
+
|
573 |
+
return new_texts
|
574 |
+
|
575 |
+
def postprocess_text(preds, labels):
|
576 |
+
preds = [skip_special_tokens_texts(pred.strip()) for pred in preds]
|
577 |
+
labels_bleu = [[skip_special_tokens_texts(label.strip())] for label in labels]
|
578 |
+
labels_wer = [skip_special_tokens_texts(label.strip()) for label in labels]
|
579 |
+
|
580 |
+
return preds, [labels_bleu, labels_wer]
|
581 |
+
|
582 |
+
def compute_metrics(preds, labels):
|
583 |
+
decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)
|
584 |
+
decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
|
585 |
+
|
586 |
+
# Some simple post-processing
|
587 |
+
decoded_preds, [decoded_labels_bleu, decoded_labels_wer] = postprocess_text(decoded_preds, decoded_labels)
|
588 |
+
|
589 |
+
if data_args.prediction_debug:
|
590 |
+
for index in random.sample(range(len(decoded_labels)), 3):
|
591 |
+
logger.info(f'reference: "{decoded_labels[index]}"')
|
592 |
+
logger.info(f'predicted: "{decoded_preds[index]}"')
|
593 |
+
logger.info('---')
|
594 |
+
|
595 |
+
result = {}
|
596 |
+
|
597 |
+
try:
|
598 |
+
result_blue = bleu.compute(predictions=decoded_preds, references=decoded_labels_bleu)
|
599 |
+
result_blue = result_blue["score"]
|
600 |
+
except Exception as e:
|
601 |
+
logger.info(f'Error occurred during bleu {e}')
|
602 |
+
result_blue = 0.0 * 100
|
603 |
+
|
604 |
+
try:
|
605 |
+
result_wer = wer.compute(predictions=decoded_preds, references=decoded_labels_wer)
|
606 |
+
result_wer = result_wer * 100
|
607 |
+
except Exception as e:
|
608 |
+
logger.info(f'Error occurred during wer {e}')
|
609 |
+
result_wer = 1.0 * 100
|
610 |
+
|
611 |
+
result["blue"] = result_blue
|
612 |
+
result["wer"] = result_wer
|
613 |
+
|
614 |
+
prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in preds]
|
615 |
+
result["gen_len"] = np.mean(prediction_lens)
|
616 |
+
result = {k: round(v, 4) for k, v in result.items()}
|
617 |
+
return result
|
618 |
+
|
619 |
+
# Enable tensorboard only on the master node
|
620 |
+
has_tensorboard = is_tensorboard_available()
|
621 |
+
if has_tensorboard and jax.process_index() == 0:
|
622 |
+
try:
|
623 |
+
from flax.metrics.tensorboard import SummaryWriter
|
624 |
+
|
625 |
+
summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir))
|
626 |
+
except ImportError as ie:
|
627 |
+
has_tensorboard = False
|
628 |
+
logger.warning(
|
629 |
+
f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
|
630 |
+
)
|
631 |
+
else:
|
632 |
+
logger.warning(
|
633 |
+
"Unable to display metrics through TensorBoard because the package is not installed: "
|
634 |
+
"Please run pip install tensorboard to enable."
|
635 |
+
)
|
636 |
+
|
637 |
+
# Initialize our training
|
638 |
+
rng = jax.random.PRNGKey(training_args.seed)
|
639 |
+
rng, dropout_rng = jax.random.split(rng)
|
640 |
+
|
641 |
+
# Store some constant
|
642 |
+
num_epochs = int(training_args.num_train_epochs)
|
643 |
+
train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
|
644 |
+
eval_batch_size = int(training_args.per_device_eval_batch_size) * jax.device_count()
|
645 |
+
steps_per_epoch = len(train_dataset) // train_batch_size
|
646 |
+
total_train_steps = steps_per_epoch * num_epochs
|
647 |
+
|
648 |
+
# Create learning rate schedule
|
649 |
+
linear_decay_lr_schedule_fn = create_learning_rate_fn(
|
650 |
+
len(train_dataset),
|
651 |
+
train_batch_size,
|
652 |
+
training_args.num_train_epochs,
|
653 |
+
training_args.warmup_steps,
|
654 |
+
training_args.learning_rate,
|
655 |
+
)
|
656 |
+
|
657 |
+
# We use Optax's "masking" functionality to not apply weight decay
|
658 |
+
# to bias and LayerNorm scale parameters. decay_mask_fn returns a
|
659 |
+
# mask boolean with the same structure as the parameters.
|
660 |
+
# The mask is True for parameters that should be decayed.
|
661 |
+
# Note that this mask is specifically adapted for FlaxBart.
|
662 |
+
# For FlaxT5, one should correct the layer norm parameter naming
|
663 |
+
# accordingly - see `run_t5_mlm_flax.py` e.g.
|
664 |
+
|
665 |
+
if any(x in model_args.model_name_or_path for x in ["t5", "mt5", "byt5"]):
|
666 |
+
def decay_mask_fn(params):
|
667 |
+
flat_params = traverse_util.flatten_dict(params)
|
668 |
+
layer_norm_params = [
|
669 |
+
(name, "scale") for name in ["layer_norm", "final_layer_norm"]
|
670 |
+
]
|
671 |
+
flat_mask = {path: (path[-1] != "bias" and path[-2:] not in layer_norm_params) for path in flat_params}
|
672 |
+
return traverse_util.unflatten_dict(flat_mask)
|
673 |
+
else:
|
674 |
+
def decay_mask_fn(params):
|
675 |
+
flat_params = traverse_util.flatten_dict(params)
|
676 |
+
layer_norm_params = [
|
677 |
+
(name, "scale") for name in ["self_attn_layer_norm", "layernorm_embedding", "final_layer_norm"]
|
678 |
+
]
|
679 |
+
flat_mask = {path: (path[-1] != "bias" and path[-2:] not in layer_norm_params) for path in flat_params}
|
680 |
+
return traverse_util.unflatten_dict(flat_mask)
|
681 |
+
|
682 |
+
# create adam optimizer
|
683 |
+
adamw = optax.adamw(
|
684 |
+
learning_rate=linear_decay_lr_schedule_fn,
|
685 |
+
b1=training_args.adam_beta1,
|
686 |
+
b2=training_args.adam_beta2,
|
687 |
+
eps=training_args.adam_epsilon,
|
688 |
+
weight_decay=training_args.weight_decay,
|
689 |
+
mask=decay_mask_fn,
|
690 |
+
)
|
691 |
+
|
692 |
+
# Setup train state
|
693 |
+
state = TrainState.create(apply_fn=model.__call__, params=model.params, tx=adamw, dropout_rng=dropout_rng)
|
694 |
+
|
695 |
+
# label smoothed cross entropy
|
696 |
+
def loss_fn(logits, labels, padding_mask, label_smoothing_factor=0.0):
|
697 |
+
"""
|
698 |
+
The label smoothing implementation is adapted from Flax's official example:
|
699 |
+
https://github.com/google/flax/blob/87a211135c6a377c8f29048a1cac3840e38b9da4/examples/wmt/train.py#L104
|
700 |
+
"""
|
701 |
+
vocab_size = logits.shape[-1]
|
702 |
+
confidence = 1.0 - label_smoothing_factor
|
703 |
+
low_confidence = (1.0 - confidence) / (vocab_size - 1)
|
704 |
+
normalizing_constant = -(
|
705 |
+
confidence * jnp.log(confidence) + (vocab_size - 1) * low_confidence * jnp.log(low_confidence + 1e-20)
|
706 |
+
)
|
707 |
+
soft_labels = onehot(labels, vocab_size, on_value=confidence, off_value=low_confidence)
|
708 |
+
|
709 |
+
loss = optax.softmax_cross_entropy(logits, soft_labels)
|
710 |
+
loss = loss - normalizing_constant
|
711 |
+
|
712 |
+
# ignore padded tokens from loss
|
713 |
+
loss = loss * padding_mask
|
714 |
+
loss = loss.sum() / padding_mask.sum()
|
715 |
+
return loss
|
716 |
+
|
717 |
+
# Define gradient update step fn
|
718 |
+
def train_step(state, batch, label_smoothing_factor=0.0):
|
719 |
+
dropout_rng, new_dropout_rng = jax.random.split(state.dropout_rng)
|
720 |
+
|
721 |
+
def compute_loss(params):
|
722 |
+
labels = batch.pop("labels")
|
723 |
+
logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
|
724 |
+
loss = loss_fn(logits, labels, batch["decoder_attention_mask"], label_smoothing_factor)
|
725 |
+
return loss
|
726 |
+
|
727 |
+
grad_fn = jax.value_and_grad(compute_loss)
|
728 |
+
loss, grad = grad_fn(state.params)
|
729 |
+
grad = jax.lax.pmean(grad, "batch")
|
730 |
+
|
731 |
+
new_state = state.apply_gradients(grads=grad, dropout_rng=new_dropout_rng)
|
732 |
+
|
733 |
+
metrics = {"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}
|
734 |
+
metrics = jax.lax.pmean(metrics, axis_name="batch")
|
735 |
+
|
736 |
+
return new_state, metrics
|
737 |
+
|
738 |
+
# Define eval fn
|
739 |
+
def eval_step(params, batch, label_smoothing_factor=0.0):
|
740 |
+
labels = batch.pop("labels")
|
741 |
+
logits = model(**batch, params=params, train=False)[0]
|
742 |
+
loss = loss_fn(logits, labels, batch["decoder_attention_mask"], label_smoothing_factor)
|
743 |
+
|
744 |
+
# summarize metrics
|
745 |
+
metrics = {"loss": loss}
|
746 |
+
metrics = jax.lax.pmean(metrics, axis_name="batch")
|
747 |
+
return metrics
|
748 |
+
|
749 |
+
# Define generation function
|
750 |
+
max_length = (
|
751 |
+
data_args.val_max_target_length if data_args.val_max_target_length is not None else model.config.max_length
|
752 |
+
)
|
753 |
+
num_beams = data_args.num_beams if data_args.num_beams is not None else model.config.num_beams
|
754 |
+
gen_kwargs = {"max_length": max_length, "num_beams": num_beams}
|
755 |
+
|
756 |
+
def generate_step(params, batch):
|
757 |
+
model.params = params
|
758 |
+
output_ids = model.generate(batch["input_ids"], attention_mask=batch["attention_mask"], **gen_kwargs)
|
759 |
+
return output_ids.sequences
|
760 |
+
|
761 |
+
# Create parallel version of the train and eval step
|
762 |
+
p_train_step = jax.pmap(
|
763 |
+
partial(train_step, label_smoothing_factor=training_args.label_smoothing_factor), "batch", donate_argnums=(0,)
|
764 |
+
)
|
765 |
+
p_eval_step = jax.pmap(partial(eval_step, label_smoothing_factor=training_args.label_smoothing_factor), "batch")
|
766 |
+
p_generate_step = jax.pmap(generate_step, "batch")
|
767 |
+
|
768 |
+
# Replicate the train state on each device
|
769 |
+
state = state.replicate()
|
770 |
+
|
771 |
+
logger.info("***** Running training *****")
|
772 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
773 |
+
logger.info(f" Num Epochs = {num_epochs}")
|
774 |
+
logger.info(f" Instantaneous batch size per device = {training_args.per_device_train_batch_size}")
|
775 |
+
logger.info(f" Total train batch size (w. parallel & distributed) = {train_batch_size}")
|
776 |
+
logger.info(f" Total optimization steps = {total_train_steps}")
|
777 |
+
|
778 |
+
train_time = 0
|
779 |
+
train_metrics = []
|
780 |
+
epochs = tqdm(range(num_epochs), desc=f"Epoch ... (1/{num_epochs})", position=0)
|
781 |
+
for epoch in epochs:
|
782 |
+
# ======================== Training ================================
|
783 |
+
train_start = time.time()
|
784 |
+
|
785 |
+
# Create sampling rng
|
786 |
+
rng, input_rng = jax.random.split(rng)
|
787 |
+
|
788 |
+
# Generate an epoch by shuffling sampling indices from the train dataset
|
789 |
+
train_loader = data_loader(input_rng, train_dataset, train_batch_size, shuffle=True)
|
790 |
+
steps_per_epoch = len(train_dataset) // train_batch_size
|
791 |
+
# train
|
792 |
+
for step in tqdm(range(steps_per_epoch), desc="Training...", position=1, leave=False):
|
793 |
+
batch = next(train_loader)
|
794 |
+
state, train_metric = p_train_step(state, batch)
|
795 |
+
train_metrics.append(train_metric)
|
796 |
+
|
797 |
+
cur_step = epoch * (len(train_dataset) // train_batch_size) + step
|
798 |
+
|
799 |
+
if cur_step % training_args.logging_steps == 0 and cur_step > 0:
|
800 |
+
# Save metrics
|
801 |
+
train_metric = unreplicate(train_metric)
|
802 |
+
train_time += time.time() - train_start
|
803 |
+
|
804 |
+
if has_tensorboard and jax.process_index() == 0:
|
805 |
+
logger.info(f"*** Writing training summary after {cur_step} steps ***")
|
806 |
+
write_train_metric(summary_writer, train_metrics, train_time, cur_step)
|
807 |
+
|
808 |
+
epochs.write(
|
809 |
+
f"Step... ({cur_step} | Loss: {train_metric['loss'].mean()}, Learning Rate: {train_metric['learning_rate'].mean()})"
|
810 |
+
)
|
811 |
+
|
812 |
+
train_metrics = []
|
813 |
+
|
814 |
+
if cur_step % training_args.eval_steps == 0 and cur_step > 0 and training_args.do_eval:
|
815 |
+
logger.info(f"*** Evaluation after {cur_step} steps ***")
|
816 |
+
eval_metrics = []
|
817 |
+
eval_preds = []
|
818 |
+
eval_labels = []
|
819 |
+
|
820 |
+
eval_loader = data_loader(input_rng, eval_dataset, eval_batch_size)
|
821 |
+
eval_steps = len(eval_dataset) // eval_batch_size
|
822 |
+
for _ in tqdm(range(eval_steps), desc="Evaluating...", position=2, leave=False):
|
823 |
+
# Model forward
|
824 |
+
batch = next(eval_loader)
|
825 |
+
labels = batch["labels"]
|
826 |
+
|
827 |
+
metrics = p_eval_step(state.params, batch)
|
828 |
+
eval_metrics.append(metrics)
|
829 |
+
|
830 |
+
# generation
|
831 |
+
if data_args.predict_with_generate:
|
832 |
+
generated_ids = p_generate_step(state.params, batch)
|
833 |
+
eval_preds.extend(jax.device_get(generated_ids.reshape(-1, gen_kwargs["max_length"])))
|
834 |
+
eval_labels.extend(jax.device_get(labels.reshape(-1, labels.shape[-1])))
|
835 |
+
|
836 |
+
# normalize eval metrics
|
837 |
+
eval_metrics = get_metrics(eval_metrics)
|
838 |
+
eval_metrics = jax.tree_map(jnp.mean, eval_metrics)
|
839 |
+
|
840 |
+
# compute MIX metrics
|
841 |
+
mix_desc = ""
|
842 |
+
if data_args.predict_with_generate:
|
843 |
+
mix_metrics = compute_metrics(eval_preds, eval_labels)
|
844 |
+
eval_metrics.update(mix_metrics)
|
845 |
+
mix_desc = " ".join([f"Eval {key}: {value} |" for key, value in mix_metrics.items()])
|
846 |
+
|
847 |
+
# Print metrics and update progress bar
|
848 |
+
desc = f"Epoch... ({epoch + 1}/{num_epochs} | Eval Loss: {eval_metrics['loss']} | {mix_desc})"
|
849 |
+
epochs.write(desc)
|
850 |
+
epochs.desc = desc
|
851 |
+
|
852 |
+
# Save metrics
|
853 |
+
if has_tensorboard and jax.process_index() == 0:
|
854 |
+
logger.info(f"*** Writing evaluation summary after {cur_step} steps ***")
|
855 |
+
# cur_step = epoch * (len(train_dataset) // train_batch_size)
|
856 |
+
write_eval_metric(summary_writer, eval_metrics, cur_step)
|
857 |
+
|
858 |
+
if cur_step % training_args.save_steps == 0 and cur_step > 0:
|
859 |
+
logger.info(f"*** Saving checkpoints after {cur_step} steps ***")
|
860 |
+
# save checkpoint after each steps and push checkpoint to the hub
|
861 |
+
if jax.process_index() == 0:
|
862 |
+
params = jax.device_get(jax.tree_map(lambda x: x[0], state.params))
|
863 |
+
# params = jax.device_get(unreplicate(state.params))
|
864 |
+
model.save_pretrained(
|
865 |
+
training_args.output_dir,
|
866 |
+
params=params,
|
867 |
+
push_to_hub=training_args.push_to_hub,
|
868 |
+
commit_message=f"Saving weights and logs of step {cur_step}",
|
869 |
+
)
|
870 |
+
|
871 |
+
if not os.path.exists(os.path.join(training_args.output_dir, "tokenizer.json")):
|
872 |
+
logger.info(f"*** Saving tokenizer ***")
|
873 |
+
tokenizer.save_pretrained(
|
874 |
+
training_args.output_dir,
|
875 |
+
push_to_hub=training_args.push_to_hub,
|
876 |
+
commit_message=f"Saving tokenizer",
|
877 |
+
)
|
878 |
+
|
879 |
+
|
880 |
+
if __name__ == "__main__":
|
881 |
+
main()
|