Trace2333 commited on
Commit
0032d0a
1 Parent(s): 48efb18

add app.py and transform generate to app_form

Browse files
Files changed (5) hide show
  1. app.py +97 -0
  2. app_test.py +18 -0
  3. forbidden.py +256 -0
  4. gpt2-sentiment.ipynb +505 -0
  5. requirements.txt +15 -0
app.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import spacy
3
+ from accelerate import PartialState
4
+ from accelerate.utils import set_seed
5
+ from flask import Flask, request, jsonify
6
+
7
+ from gpt2_generation import Translator
8
+ from gpt2_generation import generate_prompt, MODEL_CLASSES
9
+
10
+ os.environ["http_proxy"] = "http://127.0.0.1:7890"
11
+ os.environ["https_proxy"] = "http://127.0.0.1:7890"
12
+
13
+ app = Flask(__name__)
14
+
15
+ path_for_model = "./output/checkpoint-101500"
16
+
17
+ args = {
18
+ "model_type": "gpt2",
19
+ "model_name_or_path": path_for_model,
20
+ "length": 80,
21
+ "stop_token": None,
22
+ "temperature": 1.0,
23
+ "repetition_penalty": 1.2,
24
+ "k": 3,
25
+ "p": 0.9,
26
+ "prefix": "",
27
+ "padding_text": "",
28
+ "xlm_language": "",
29
+ "seed": 42,
30
+ "use_cpu": False,
31
+ "num_return_sequences": 1,
32
+ "fp16": False,
33
+ "jit": False,
34
+ }
35
+
36
+ distributed_state = PartialState(cpu=args["use_cpu"])
37
+
38
+ if args["seed"] is not None:
39
+ set_seed(args["seed"])
40
+
41
+ tokenizer = None
42
+ model = None
43
+ zh_en_translator = None
44
+ nlp = None
45
+
46
+ def load_model_and_components():
47
+ global tokenizer, model, zh_en_translator, nlp
48
+
49
+ # Initialize the model and tokenizer
50
+ try:
51
+ args["model_type"] = args["model_type"].lower()
52
+ model_class, tokenizer_class = MODEL_CLASSES[args["model_type"]]
53
+ except KeyError:
54
+ raise KeyError("the model {} you specified is not supported. You are welcome to add it and open a PR :)")
55
+
56
+ tokenizer = tokenizer_class.from_pretrained(args["model_name_or_path"], padding_side='left')
57
+ tokenizer.pad_token = tokenizer.eos_token
58
+ tokenizer.mask_token = tokenizer.eos_token
59
+ model = model_class.from_pretrained(args["model_name_or_path"])
60
+ print("Model loaded!")
61
+
62
+ # translator
63
+ zh_en_translator = Translator("Helsinki-NLP/opus-mt-zh-en")
64
+ print("Translator loaded!")
65
+
66
+ # filter
67
+ nlp = spacy.load('en_core_web_sm')
68
+ print("Filter loaded!")
69
+
70
+ # Set the model to the right device
71
+ model.to(distributed_state.device)
72
+
73
+ if args["fp16"]:
74
+ model.half()
75
+
76
+ @app.route('/chat', methods=['POST'])
77
+ def chat():
78
+ phrase = request.json.get('phrase')
79
+
80
+ if tokenizer is None or model is None or zh_en_translator is None or nlp is None:
81
+ load_model_and_components()
82
+
83
+ messages = generate_prompt(
84
+ prompt_text=phrase,
85
+ args=args,
86
+ zh_en_translator=zh_en_translator,
87
+ nlp=nlp,
88
+ model=model,
89
+ tokenizer=tokenizer,
90
+ distributed_state=distributed_state,
91
+ )
92
+
93
+ return jsonify(messages)
94
+
95
+ if __name__ == '__main__':
96
+ load_model_and_components()
97
+ app.run(host='0.0.0.0', port=10006, debug=False)
app_test.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import json
3
+
4
+ url = 'http://localhost:10006/chat' # 根据实际的主机和端口进行修改
5
+
6
+ # 构造请求数据
7
+ data = {
8
+ 'phrase': 'a spiece 和一只狼' # 根据需要进行修改
9
+ }
10
+
11
+ # 发送 POST 请求
12
+ response = requests.post(url, json=data)
13
+
14
+ # 解析响应
15
+ response_data = response.json()
16
+
17
+ # 打印响应结果
18
+ print(json.dumps(response_data, indent=4))
forbidden.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FORBIDDEN_NOUN = [
2
+ "woman",
3
+ "women",
4
+ "female",
5
+ "man",
6
+ "men",
7
+ "girl",
8
+ "boy",
9
+ "person",
10
+ "people",
11
+ "individual",
12
+ "lady",
13
+ "gentleman",
14
+ "child",
15
+ "children",
16
+ "adult",
17
+ "elderly",
18
+ "elder",
19
+ "youth",
20
+ "teenager",
21
+ "toddler",
22
+ "infant",
23
+ "baby",
24
+ "parent",
25
+ "mother",
26
+ "father",
27
+ "grandparent",
28
+ "grandmother",
29
+ "grandfather",
30
+ "sister",
31
+ "brother",
32
+ "aunt",
33
+ "uncle",
34
+ "cousin",
35
+ "niece",
36
+ "nephew",
37
+ "friend",
38
+ "neighbor",
39
+ "colleague",
40
+ "teacher",
41
+ "student",
42
+ "doctor",
43
+ "nurse",
44
+ "police",
45
+ "firefighter",
46
+ "soldier",
47
+ "veteran",
48
+ "citizen",
49
+ "resident",
50
+ "immigrant",
51
+ "refugee",
52
+ "homeless",
53
+ "disabled",
54
+ "blind",
55
+ "deaf",
56
+ "mute",
57
+ "gay",
58
+ "lesbian",
59
+ "bisexual",
60
+ "transgender",
61
+ "queer",
62
+ "nonbinary",
63
+ "heterosexual",
64
+ "homosexual",
65
+ "marriage",
66
+ "family",
67
+ "relationship",
68
+ "love",
69
+ "diversity",
70
+ "equality",
71
+ "inclusion",
72
+ "discrimination",
73
+ "stereotype",
74
+ "prejudice",
75
+ "bias",
76
+ "harassment",
77
+ "abuse",
78
+ "violence",
79
+ "oppression",
80
+ "racism",
81
+ "sexism",
82
+ "ageism",
83
+ "ableism",
84
+ "homophobia",
85
+ "transphobia",
86
+ "xenophobia",
87
+ "bigotry",
88
+ "hate",
89
+ "offensive",
90
+ "slur",
91
+ "taboo",
92
+ "profanity",
93
+ "obscenity",
94
+ "eyes",
95
+ "ear",
96
+ "nose",
97
+ "mouth",
98
+ "tongue",
99
+ "teeth",
100
+ "lips",
101
+ "face",
102
+ "cheek",
103
+ "chin",
104
+ "neck",
105
+ "shoulder",
106
+ "arm",
107
+ "elbow",
108
+ "wrist",
109
+ "hand",
110
+ "finger",
111
+ "thumb",
112
+ "chest",
113
+ "breast",
114
+ "heart",
115
+ "stomach",
116
+ "belly",
117
+ "back",
118
+ "waist",
119
+ "hip",
120
+ "leg",
121
+ "thigh",
122
+ "knee",
123
+ "ankle",
124
+ "foot",
125
+ "toe",
126
+ "hair",
127
+ "head",
128
+ "brain",
129
+ "skin",
130
+ "bone",
131
+ "muscle",
132
+ "nail",
133
+ "cyberpunk",
134
+ "robot",
135
+ "android",
136
+ "cyborg",
137
+ "AI",
138
+ "artificial intelligence",
139
+ "virtual reality",
140
+ "augmentation",
141
+ "implant",
142
+ "nanotechnology",
143
+ "hacker",
144
+ "data",
145
+ "cyberspace",
146
+ "netrunner",
147
+ "neural",
148
+ "circuit",
149
+ "chip",
150
+ "droid",
151
+ "mecha",
152
+ "synthetic",
153
+ "cyberware",
154
+ "cybersuit",
155
+ "biomechanical",
156
+ "exoskeleton",
157
+ "cybernetics",
158
+ "brain-computer interface",
159
+ "genetic engineering",
160
+ "bionic",
161
+ "hovercar",
162
+ "megacorporation",
163
+ "dystopia",
164
+ "cybercrime",
165
+ "virtual world",
166
+ "neon",
167
+ "hologram",
168
+ "future",
169
+ "tech",
170
+ "cyber",
171
+ "machine",
172
+ "computer",
173
+ "data",
174
+ "code",
175
+ "interface",
176
+ "hack",
177
+ "mod",
178
+ "upgrade",
179
+ "jacking in",
180
+ "cyberdeck",
181
+ "cybersuit",
182
+ "implant",
183
+ "augment",
184
+ "cybersurgery",
185
+ "bone",
186
+ "throne",
187
+ "crown",
188
+ "magic",
189
+ "wizard",
190
+ "witch",
191
+ "sorcerer",
192
+ "dragon",
193
+ "elf",
194
+ "dwarf",
195
+ "goblin",
196
+ "fairy",
197
+ "spell",
198
+ "enchantment",
199
+ "myth",
200
+ "legend",
201
+ "quest",
202
+ "adventure",
203
+ "sword",
204
+ "shield",
205
+ "armor",
206
+ "wand",
207
+ "staff",
208
+ "amulet",
209
+ "scroll",
210
+ "talisman",
211
+ "beast",
212
+ "creature",
213
+ "monster",
214
+ "vampire",
215
+ "werewolf",
216
+ "giant",
217
+ "gargoyle",
218
+ "phoenix",
219
+ "unicorn",
220
+ "mermaid",
221
+ "witchcraft",
222
+ "alchemy",
223
+ "mystic",
224
+ "divination",
225
+ "fantasy",
226
+ "realm",
227
+ "magician",
228
+ "sorcery",
229
+ "enchanted",
230
+ "fabled",
231
+ "lore",
232
+ "mythical",
233
+ "epic",
234
+ "fate",
235
+ "destiny",
236
+ "astronomy",
237
+ "geology",
238
+ "orchestra",
239
+ "zoology",
240
+ "philosophy",
241
+ "archaeology",
242
+ "anthropology",
243
+ "meteorology",
244
+ "botany",
245
+ "sociology",
246
+ "psychology",
247
+ "linguistics",
248
+ "ethics",
249
+ "mythology",
250
+ "astronautics",
251
+ "entomology",
252
+ "ecology",
253
+ "nuclear physics",
254
+ "oceanography",
255
+ "literature"
256
+ ]
gpt2-sentiment.ipynb ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Tune GPT2 to generate positive reviews\n",
8
+ "> Optimise GPT2 to produce positive IMDB movie reviews using a BERT sentiment classifier as a reward function."
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "markdown",
13
+ "metadata": {},
14
+ "source": [
15
+ "<div style=\"text-align: center\">\n",
16
+ "<img src='https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/gpt2_bert_training.png' width='600'>\n",
17
+ "<p style=\"text-align: center;\"> <b>Figure:</b> Experiment setup to tune GPT2. The yellow arrows are outside the scope of this notebook, but the trained models are available through Hugging Face. </p>\n",
18
+ "</div>\n",
19
+ "\n",
20
+ "\n",
21
+ "In this notebook we fine-tune GPT2 (small) to generate positive movie reviews based on the IMDB dataset. The model gets the start of a real review and is tasked to produce positive continuations. To reward positive continuations we use a BERT classifier to analyse the sentiment of the produced sentences and use the classifier's outputs as rewards signals for PPO training."
22
+ ]
23
+ },
24
+ {
25
+ "cell_type": "markdown",
26
+ "metadata": {},
27
+ "source": [
28
+ "## Setup experiment"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "markdown",
33
+ "metadata": {},
34
+ "source": [
35
+ "### Import dependencies"
36
+ ]
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "execution_count": null,
41
+ "metadata": {},
42
+ "outputs": [],
43
+ "source": [
44
+ "%load_ext autoreload\n",
45
+ "%autoreload 2"
46
+ ]
47
+ },
48
+ {
49
+ "cell_type": "code",
50
+ "execution_count": null,
51
+ "metadata": {},
52
+ "outputs": [],
53
+ "source": [
54
+ "%pip install transformers trl wandb"
55
+ ]
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "execution_count": null,
60
+ "metadata": {},
61
+ "outputs": [],
62
+ "source": [
63
+ "import torch\n",
64
+ "from tqdm import tqdm\n",
65
+ "import pandas as pd\n",
66
+ "\n",
67
+ "tqdm.pandas()\n",
68
+ "\n",
69
+ "from transformers import pipeline, AutoTokenizer\n",
70
+ "from datasets import load_dataset\n",
71
+ "\n",
72
+ "from trl import PPOTrainer, PPOConfig, AutoModelForCausalLMWithValueHead\n",
73
+ "from trl.core import LengthSampler"
74
+ ]
75
+ },
76
+ {
77
+ "cell_type": "markdown",
78
+ "metadata": {},
79
+ "source": [
80
+ "### Configuration"
81
+ ]
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "execution_count": null,
86
+ "metadata": {},
87
+ "outputs": [],
88
+ "source": [
89
+ "config = PPOConfig(\n",
90
+ " model_name=\"lvwerra/gpt2-imdb\",\n",
91
+ " learning_rate=1.41e-5,\n",
92
+ " log_with=\"wandb\",\n",
93
+ ")\n",
94
+ "\n",
95
+ "sent_kwargs = {\"return_all_scores\": True, \"function_to_apply\": \"none\", \"batch_size\": 16}"
96
+ ]
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "execution_count": null,
101
+ "metadata": {},
102
+ "outputs": [],
103
+ "source": [
104
+ "import wandb\n",
105
+ "\n",
106
+ "wandb.init()"
107
+ ]
108
+ },
109
+ {
110
+ "cell_type": "markdown",
111
+ "metadata": {},
112
+ "source": [
113
+ "You can see that we load a GPT2 model called `gpt2_imdb`. This model was additionally fine-tuned on the IMDB dataset for 1 epoch with the huggingface [script](https://github.com/huggingface/transformers/blob/master/examples/run_language_modeling.py) (no special settings). The other parameters are mostly taken from the original paper [\"Fine-Tuning Language Models from Human Preferences\"](\n",
114
+ "https://arxiv.org/pdf/1909.08593.pdf). This model as well as the BERT model is available in the Huggingface model zoo [here](https://huggingface.co/models). The following code should automatically download the models."
115
+ ]
116
+ },
117
+ {
118
+ "cell_type": "markdown",
119
+ "metadata": {},
120
+ "source": [
121
+ "## Load data and models"
122
+ ]
123
+ },
124
+ {
125
+ "attachments": {},
126
+ "cell_type": "markdown",
127
+ "metadata": {},
128
+ "source": [
129
+ "### Load IMDB dataset\n",
130
+ "The IMDB dataset contains 50k movie review annotated with \"positive\"/\"negative\" feedback indicating the sentiment. We load the IMDB dataset into a DataFrame and filter for comments that are at least 200 characters. Then we tokenize each text and cut it to random size with the `LengthSampler`."
131
+ ]
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "execution_count": null,
136
+ "metadata": {},
137
+ "outputs": [],
138
+ "source": [
139
+ "def build_dataset(config, dataset_name=\"imdb\", input_min_text_length=2, input_max_text_length=8):\n",
140
+ " \"\"\"\n",
141
+ " Build dataset for training. This builds the dataset from `load_dataset`, one should\n",
142
+ " customize this function to train the model on its own dataset.\n",
143
+ "\n",
144
+ " Args:\n",
145
+ " dataset_name (`str`):\n",
146
+ " The name of the dataset to be loaded.\n",
147
+ "\n",
148
+ " Returns:\n",
149
+ " dataloader (`torch.utils.data.DataLoader`):\n",
150
+ " The dataloader for the dataset.\n",
151
+ " \"\"\"\n",
152
+ " tokenizer = AutoTokenizer.from_pretrained(config.model_name)\n",
153
+ " tokenizer.pad_token = tokenizer.eos_token\n",
154
+ " # load imdb with datasets\n",
155
+ " ds = load_dataset(dataset_name, split=\"train\")\n",
156
+ " ds = ds.rename_columns({\"text\": \"review\"})\n",
157
+ " ds = ds.filter(lambda x: len(x[\"review\"]) > 200, batched=False)\n",
158
+ "\n",
159
+ " input_size = LengthSampler(input_min_text_length, input_max_text_length)\n",
160
+ "\n",
161
+ " def tokenize(sample):\n",
162
+ " sample[\"input_ids\"] = tokenizer.encode(sample[\"review\"])[: input_size()]\n",
163
+ " sample[\"query\"] = tokenizer.decode(sample[\"input_ids\"])\n",
164
+ " return sample\n",
165
+ "\n",
166
+ " ds = ds.map(tokenize, batched=False)\n",
167
+ " ds.set_format(type=\"torch\")\n",
168
+ " return ds"
169
+ ]
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "execution_count": null,
174
+ "metadata": {},
175
+ "outputs": [],
176
+ "source": [
177
+ "dataset = build_dataset(config)\n",
178
+ "\n",
179
+ "\n",
180
+ "def collator(data):\n",
181
+ " return dict((key, [d[key] for d in data]) for key in data[0])"
182
+ ]
183
+ },
184
+ {
185
+ "cell_type": "markdown",
186
+ "metadata": {},
187
+ "source": [
188
+ "### Load pre-trained GPT2 language models"
189
+ ]
190
+ },
191
+ {
192
+ "cell_type": "markdown",
193
+ "metadata": {},
194
+ "source": [
195
+ "We load the GPT2 model with a value head and the tokenizer. We load the model twice; the first model is optimized while the second model serves as a reference to calculate the KL-divergence from the starting point. This serves as an additional reward signal in the PPO training to make sure the optimized model does not deviate too much from the original language model."
196
+ ]
197
+ },
198
+ {
199
+ "cell_type": "code",
200
+ "execution_count": null,
201
+ "metadata": {},
202
+ "outputs": [],
203
+ "source": [
204
+ "model = AutoModelForCausalLMWithValueHead.from_pretrained(config.model_name)\n",
205
+ "ref_model = AutoModelForCausalLMWithValueHead.from_pretrained(config.model_name)\n",
206
+ "tokenizer = AutoTokenizer.from_pretrained(config.model_name)\n",
207
+ "\n",
208
+ "tokenizer.pad_token = tokenizer.eos_token"
209
+ ]
210
+ },
211
+ {
212
+ "attachments": {},
213
+ "cell_type": "markdown",
214
+ "metadata": {},
215
+ "source": [
216
+ "### Initialize PPOTrainer\n",
217
+ "The `PPOTrainer` takes care of device placement and optimization later on:"
218
+ ]
219
+ },
220
+ {
221
+ "cell_type": "code",
222
+ "execution_count": null,
223
+ "metadata": {},
224
+ "outputs": [],
225
+ "source": [
226
+ "ppo_trainer = PPOTrainer(config, model, ref_model, tokenizer, dataset=dataset, data_collator=collator)"
227
+ ]
228
+ },
229
+ {
230
+ "cell_type": "markdown",
231
+ "metadata": {},
232
+ "source": [
233
+ "### Load BERT classifier\n",
234
+ "We load a BERT classifier fine-tuned on the IMDB dataset."
235
+ ]
236
+ },
237
+ {
238
+ "cell_type": "code",
239
+ "execution_count": null,
240
+ "metadata": {},
241
+ "outputs": [],
242
+ "source": [
243
+ "device = ppo_trainer.accelerator.device\n",
244
+ "if ppo_trainer.accelerator.num_processes == 1:\n",
245
+ " device = 0 if torch.cuda.is_available() else \"cpu\" # to avoid a `pipeline` bug\n",
246
+ "sentiment_pipe = pipeline(\"sentiment-analysis\", model=\"lvwerra/distilbert-imdb\", device=device)"
247
+ ]
248
+ },
249
+ {
250
+ "cell_type": "markdown",
251
+ "metadata": {},
252
+ "source": [
253
+ "The model outputs are the logits for the negative and positive class. We will use the logits for positive class as a reward signal for the language model."
254
+ ]
255
+ },
256
+ {
257
+ "cell_type": "code",
258
+ "execution_count": null,
259
+ "metadata": {},
260
+ "outputs": [],
261
+ "source": [
262
+ "text = \"this movie was really bad!!\"\n",
263
+ "sentiment_pipe(text, **sent_kwargs)"
264
+ ]
265
+ },
266
+ {
267
+ "cell_type": "code",
268
+ "execution_count": null,
269
+ "metadata": {},
270
+ "outputs": [],
271
+ "source": [
272
+ "text = \"this movie was really good!!\"\n",
273
+ "sentiment_pipe(text, **sent_kwargs)"
274
+ ]
275
+ },
276
+ {
277
+ "cell_type": "markdown",
278
+ "metadata": {},
279
+ "source": [
280
+ "### Generation settings\n",
281
+ "For the response generation we just use sampling and make sure top-k and nucleus sampling are turned off as well as a minimal length."
282
+ ]
283
+ },
284
+ {
285
+ "cell_type": "code",
286
+ "execution_count": null,
287
+ "metadata": {},
288
+ "outputs": [],
289
+ "source": [
290
+ "gen_kwargs = {\"min_length\": -1, \"top_k\": 0.0, \"top_p\": 1.0, \"do_sample\": True, \"pad_token_id\": tokenizer.eos_token_id}"
291
+ ]
292
+ },
293
+ {
294
+ "cell_type": "markdown",
295
+ "metadata": {},
296
+ "source": [
297
+ "## Optimize model"
298
+ ]
299
+ },
300
+ {
301
+ "cell_type": "markdown",
302
+ "metadata": {},
303
+ "source": [
304
+ "### Training loop"
305
+ ]
306
+ },
307
+ {
308
+ "cell_type": "markdown",
309
+ "metadata": {},
310
+ "source": [
311
+ "The training loop consists of the following main steps:\n",
312
+ "1. Get the query responses from the policy network (GPT-2)\n",
313
+ "2. Get sentiments for query/responses from BERT\n",
314
+ "3. Optimize policy with PPO using the (query, response, reward) triplet\n",
315
+ "\n",
316
+ "**Training time**\n",
317
+ "\n",
318
+ "This step takes **~2h** on a V100 GPU with the above specified settings."
319
+ ]
320
+ },
321
+ {
322
+ "cell_type": "code",
323
+ "execution_count": null,
324
+ "metadata": {},
325
+ "outputs": [],
326
+ "source": [
327
+ "output_min_length = 4\n",
328
+ "output_max_length = 16\n",
329
+ "output_length_sampler = LengthSampler(output_min_length, output_max_length)\n",
330
+ "\n",
331
+ "\n",
332
+ "generation_kwargs = {\n",
333
+ " \"min_length\": -1,\n",
334
+ " \"top_k\": 0.0,\n",
335
+ " \"top_p\": 1.0,\n",
336
+ " \"do_sample\": True,\n",
337
+ " \"pad_token_id\": tokenizer.eos_token_id,\n",
338
+ "}\n",
339
+ "\n",
340
+ "\n",
341
+ "for epoch, batch in tqdm(enumerate(ppo_trainer.dataloader)):\n",
342
+ " query_tensors = batch[\"input_ids\"]\n",
343
+ "\n",
344
+ " #### Get response from gpt2\n",
345
+ " response_tensors = []\n",
346
+ " for query in query_tensors:\n",
347
+ " gen_len = output_length_sampler()\n",
348
+ " generation_kwargs[\"max_new_tokens\"] = gen_len\n",
349
+ " response = ppo_trainer.generate(query, **generation_kwargs)\n",
350
+ " response_tensors.append(response.squeeze()[-gen_len:])\n",
351
+ " batch[\"response\"] = [tokenizer.decode(r.squeeze()) for r in response_tensors]\n",
352
+ "\n",
353
+ " #### Compute sentiment score\n",
354
+ " texts = [q + r for q, r in zip(batch[\"query\"], batch[\"response\"])]\n",
355
+ " pipe_outputs = sentiment_pipe(texts, **sent_kwargs)\n",
356
+ " rewards = [torch.tensor(output[1][\"score\"]) for output in pipe_outputs]\n",
357
+ "\n",
358
+ " #### Run PPO step\n",
359
+ " stats = ppo_trainer.step(query_tensors, response_tensors, rewards)\n",
360
+ " ppo_trainer.log_stats(stats, batch, rewards)"
361
+ ]
362
+ },
363
+ {
364
+ "cell_type": "markdown",
365
+ "metadata": {},
366
+ "source": [
367
+ "### Training progress\n",
368
+ "If you are tracking the training progress with Weights&Biases you should see a plot similar to the one below. Check out the interactive sample report on wandb.ai: [link](https://app.wandb.ai/huggingface/trl-showcase/runs/1jtvxb1m/).\n",
369
+ "\n",
370
+ "<div style=\"text-align: center\">\n",
371
+ "<img src='https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/gpt2_tuning_progress.png' width='800'>\n",
372
+ "<p style=\"text-align: center;\"> <b>Figure:</b> Reward mean and distribution evolution during training. </p>\n",
373
+ "</div>\n",
374
+ "\n",
375
+ "One can observe how the model starts to generate more positive outputs after a few optimisation steps.\n",
376
+ "\n",
377
+ "> Note: Investigating the KL-divergence will probably show that at this point the model has not converged to the target KL-divergence, yet. To get there would require longer training or starting with a higher initial coefficient."
378
+ ]
379
+ },
380
+ {
381
+ "attachments": {},
382
+ "cell_type": "markdown",
383
+ "metadata": {},
384
+ "source": [
385
+ "## Model inspection\n",
386
+ "Let's inspect some examples from the IMDB dataset. We can use `model_ref` to compare the tuned model `model` against the model before optimisation."
387
+ ]
388
+ },
389
+ {
390
+ "cell_type": "code",
391
+ "execution_count": null,
392
+ "metadata": {},
393
+ "outputs": [],
394
+ "source": [
395
+ "#### get a batch from the dataset\n",
396
+ "bs = 16\n",
397
+ "game_data = dict()\n",
398
+ "dataset.set_format(\"pandas\")\n",
399
+ "df_batch = dataset[:].sample(bs)\n",
400
+ "game_data[\"query\"] = df_batch[\"query\"].tolist()\n",
401
+ "query_tensors = df_batch[\"input_ids\"].tolist()\n",
402
+ "\n",
403
+ "response_tensors_ref, response_tensors = [], []\n",
404
+ "\n",
405
+ "#### get response from gpt2 and gpt2_ref\n",
406
+ "for i in range(bs):\n",
407
+ " gen_len = output_length_sampler()\n",
408
+ " output = ref_model.generate(\n",
409
+ " torch.tensor(query_tensors[i]).unsqueeze(dim=0).to(device), max_new_tokens=gen_len, **gen_kwargs\n",
410
+ " ).squeeze()[-gen_len:]\n",
411
+ " response_tensors_ref.append(output)\n",
412
+ " output = model.generate(\n",
413
+ " torch.tensor(query_tensors[i]).unsqueeze(dim=0).to(device), max_new_tokens=gen_len, **gen_kwargs\n",
414
+ " ).squeeze()[-gen_len:]\n",
415
+ " response_tensors.append(output)\n",
416
+ "\n",
417
+ "#### decode responses\n",
418
+ "game_data[\"response (before)\"] = [tokenizer.decode(response_tensors_ref[i]) for i in range(bs)]\n",
419
+ "game_data[\"response (after)\"] = [tokenizer.decode(response_tensors[i]) for i in range(bs)]\n",
420
+ "\n",
421
+ "#### sentiment analysis of query/response pairs before/after\n",
422
+ "texts = [q + r for q, r in zip(game_data[\"query\"], game_data[\"response (before)\"])]\n",
423
+ "game_data[\"rewards (before)\"] = [output[1][\"score\"] for output in sentiment_pipe(texts, **sent_kwargs)]\n",
424
+ "\n",
425
+ "texts = [q + r for q, r in zip(game_data[\"query\"], game_data[\"response (after)\"])]\n",
426
+ "game_data[\"rewards (after)\"] = [output[1][\"score\"] for output in sentiment_pipe(texts, **sent_kwargs)]\n",
427
+ "\n",
428
+ "# store results in a dataframe\n",
429
+ "df_results = pd.DataFrame(game_data)\n",
430
+ "df_results"
431
+ ]
432
+ },
433
+ {
434
+ "cell_type": "markdown",
435
+ "metadata": {},
436
+ "source": [
437
+ "Looking at the reward mean/median of the generated sequences we observe a significant difference."
438
+ ]
439
+ },
440
+ {
441
+ "cell_type": "code",
442
+ "execution_count": null,
443
+ "metadata": {},
444
+ "outputs": [],
445
+ "source": [
446
+ "print(\"mean:\")\n",
447
+ "display(df_results[[\"rewards (before)\", \"rewards (after)\"]].mean())\n",
448
+ "print()\n",
449
+ "print(\"median:\")\n",
450
+ "display(df_results[[\"rewards (before)\", \"rewards (after)\"]].median())"
451
+ ]
452
+ },
453
+ {
454
+ "cell_type": "markdown",
455
+ "metadata": {},
456
+ "source": [
457
+ "## Save model\n",
458
+ "Finally, we save the model and push it to the Hugging Face for later usage."
459
+ ]
460
+ },
461
+ {
462
+ "cell_type": "code",
463
+ "execution_count": null,
464
+ "metadata": {},
465
+ "outputs": [],
466
+ "source": [
467
+ "model.save_pretrained(\"gpt2-imdb-pos-v2\", push_to_hub=True)\n",
468
+ "tokenizer.save_pretrained(\"gpt2-imdb-pos-v2\", push_to_hub=True)"
469
+ ]
470
+ },
471
+ {
472
+ "cell_type": "code",
473
+ "execution_count": null,
474
+ "metadata": {},
475
+ "outputs": [],
476
+ "source": []
477
+ }
478
+ ],
479
+ "metadata": {
480
+ "kernelspec": {
481
+ "display_name": "env",
482
+ "language": "python",
483
+ "name": "python3"
484
+ },
485
+ "language_info": {
486
+ "codemirror_mode": {
487
+ "name": "ipython",
488
+ "version": 3
489
+ },
490
+ "file_extension": ".py",
491
+ "mimetype": "text/x-python",
492
+ "name": "python",
493
+ "nbconvert_exporter": "python",
494
+ "pygments_lexer": "ipython3",
495
+ "version": "3.10.13"
496
+ },
497
+ "vscode": {
498
+ "interpreter": {
499
+ "hash": "4c8ff454cd947027f86954d72bf940c689a97dcc494eb53cfe4813862c6065fe"
500
+ }
501
+ }
502
+ },
503
+ "nbformat": 4,
504
+ "nbformat_minor": 4
505
+ }
requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl_py==2.0.0
2
+ accelerate==0.24.1
3
+ datasets==2.12.0
4
+ evaluate==0.4.1
5
+ Flask==3.0.0
6
+ nltk==3.8.1
7
+ numpy==1.24.4
8
+ pandas==1.5.3
9
+ Requests==2.31.0
10
+ rouge_score==0.1.2
11
+ six==1.16.0
12
+ spacy==3.7.2
13
+ torch==2.1.0
14
+ tqdm==4.65.0
15
+ transformers==4.36.1