brunosan commited on
Commit
bf45cf1
1 Parent(s): 3316819

Upload 2 files

Browse files
Files changed (2) hide show
  1. finetune.ipynb +531 -0
  2. text.txt +0 -0
finetune.ipynb ADDED
@@ -0,0 +1,531 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "metadata": {},
7
+ "outputs": [
8
+ {
9
+ "name": "stdout",
10
+ "output_type": "stream",
11
+ "text": [
12
+ "Requirement already satisfied: transformers in /srv/conda/envs/notebook/lib/python3.9/site-packages (4.26.1)\n",
13
+ "Requirement already satisfied: filelock in /srv/conda/envs/notebook/lib/python3.9/site-packages (from transformers) (3.8.0)\n",
14
+ "Requirement already satisfied: numpy>=1.17 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from transformers) (1.23.3)\n",
15
+ "Requirement already satisfied: requests in /srv/conda/envs/notebook/lib/python3.9/site-packages (from transformers) (2.28.1)\n",
16
+ "Requirement already satisfied: packaging>=20.0 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from transformers) (21.3)\n",
17
+ "Requirement already satisfied: pyyaml>=5.1 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from transformers) (5.4.1)\n",
18
+ "Requirement already satisfied: regex!=2019.12.17 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from transformers) (2022.10.31)\n",
19
+ "Requirement already satisfied: tokenizers!=0.11.3,<0.14,>=0.11.1 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from transformers) (0.13.2)\n",
20
+ "Requirement already satisfied: tqdm>=4.27 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from transformers) (4.64.1)\n",
21
+ "Requirement already satisfied: huggingface-hub<1.0,>=0.11.0 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from transformers) (0.12.1)\n",
22
+ "Requirement already satisfied: typing-extensions>=3.7.4.3 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from huggingface-hub<1.0,>=0.11.0->transformers) (4.3.0)\n",
23
+ "Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from packaging>=20.0->transformers) (3.0.9)\n",
24
+ "Requirement already satisfied: certifi>=2017.4.17 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from requests->transformers) (2022.9.14)\n",
25
+ "Requirement already satisfied: charset-normalizer<3,>=2 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from requests->transformers) (2.1.1)\n",
26
+ "Requirement already satisfied: urllib3<1.27,>=1.21.1 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from requests->transformers) (1.26.11)\n",
27
+ "Requirement already satisfied: idna<4,>=2.5 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from requests->transformers) (3.3)\n"
28
+ ]
29
+ }
30
+ ],
31
+ "source": [
32
+ "!pip install transformers"
33
+ ]
34
+ },
35
+ {
36
+ "cell_type": "code",
37
+ "execution_count": 16,
38
+ "metadata": {},
39
+ "outputs": [
40
+ {
41
+ "data": {
42
+ "text/plain": [
43
+ "('fine_tuned_tokenizer/tokenizer_config.json',\n",
44
+ " 'fine_tuned_tokenizer/special_tokens_map.json',\n",
45
+ " 'fine_tuned_tokenizer/vocab.json',\n",
46
+ " 'fine_tuned_tokenizer/merges.txt',\n",
47
+ " 'fine_tuned_tokenizer/added_tokens.json')"
48
+ ]
49
+ },
50
+ "execution_count": 16,
51
+ "metadata": {},
52
+ "output_type": "execute_result"
53
+ }
54
+ ],
55
+ "source": [
56
+ "import torch\n",
57
+ "from transformers import GPT2LMHeadModel, GPT2Tokenizer\n",
58
+ "from torch.utils.data import Dataset, DataLoader\n",
59
+ "\n",
60
+ "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
61
+ "\n",
62
+ "\n",
63
+ "class TextDataset(Dataset):\n",
64
+ " def __init__(self, file_path, tokenizer, max_seq_length):\n",
65
+ " with open(file_path, 'r', encoding='utf-8') as f:\n",
66
+ " self.text = f.read()\n",
67
+ " self.tokenizer = tokenizer\n",
68
+ " self.max_seq_length = max_seq_length\n",
69
+ " self.segments = []\n",
70
+ "\n",
71
+ " for line in self.text.split('\\n'):\n",
72
+ " if len(line) > 0:\n",
73
+ " if len(line) > self.max_seq_length:\n",
74
+ " # Split long lines into shorter segments\n",
75
+ " segments = [line[i:i+self.max_seq_length] for i in range(0, len(line), self.max_seq_length)]\n",
76
+ " self.segments.extend(segments)\n",
77
+ " else:\n",
78
+ " self.segments.append(line)\n",
79
+ "\n",
80
+ " def __len__(self):\n",
81
+ " return len(self.segments)\n",
82
+ "\n",
83
+ " def __getitem__(self, idx):\n",
84
+ " self.tokenizer.pad_token_id = 0\n",
85
+ " segment = self.segments[idx]\n",
86
+ " input_ids = self.tokenizer.encode(segment, add_special_tokens=True)\n",
87
+ " target_ids = input_ids[1:] + [self.tokenizer.pad_token_id]\n",
88
+ "\n",
89
+ " if not input_ids:\n",
90
+ " return None\n",
91
+ " \n",
92
+ "\n",
93
+ " # Pad the input sequence to the same length\n",
94
+ " if len(input_ids) > self.max_seq_length:\n",
95
+ " input_ids = input_ids[:self.max_seq_length]\n",
96
+ " target_ids = target_ids[:self.max_seq_length]\n",
97
+ " else:\n",
98
+ " padding_length = self.max_seq_length - len(input_ids)\n",
99
+ " input_ids = input_ids + [self.tokenizer.pad_token_id] * padding_length\n",
100
+ " target_ids = target_ids + [self.tokenizer.pad_token_id] * padding_length\n",
101
+ " #print(\"segment:\",segment,\"\\n input:\", input_ids, \"\\n targets\" ,target_ids)\n",
102
+ " #print(\"\\r segment:\",segment, end=\"\")\n",
103
+ " \n",
104
+ " return torch.tensor(input_ids), torch.tensor(target_ids)\n",
105
+ "\n",
106
+ "\n",
107
+ "# Initialize the tokenizer and the pre-trained model\n",
108
+ "tokenizer = GPT2Tokenizer.from_pretrained('gpt2')\n",
109
+ "model = GPT2LMHeadModel.from_pretrained('gpt2').to(device)\n",
110
+ "\n",
111
+ "\n",
112
+ "# Define the path to the training text file\n",
113
+ "train_file = 'text.txt'\n",
114
+ "\n",
115
+ "# Define the training and validation datasets\n",
116
+ "max_seq_length = 512\n",
117
+ "\n",
118
+ "train_dataset = TextDataset(train_file, tokenizer, max_seq_length)\n",
119
+ "valid_dataset = TextDataset(train_file, tokenizer, max_seq_length)\n",
120
+ "\n",
121
+ "# Define the training hyperparameters\n",
122
+ "batch_size = 8\n",
123
+ "num_epochs = 7\n",
124
+ "learning_rate = 5e-4\n",
125
+ "\n",
126
+ "# Define the data loader for the training and validation datasets\n",
127
+ "train_loader = DataLoader(train_dataset,batch_size=batch_size, shuffle=True)\n",
128
+ "valid_loader = DataLoader(valid_dataset,batch_size=batch_size, shuffle=True)\n",
129
+ "\n",
130
+ "# Define the loss function and the optimizer\n",
131
+ "loss_fn = torch.nn.CrossEntropyLoss()\n",
132
+ "optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n",
133
+ "\n",
134
+ "tokenizer.save_pretrained('fine_tuned_tokenizer')\n"
135
+ ]
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "execution_count": 17,
140
+ "metadata": {},
141
+ "outputs": [
142
+ {
143
+ "name": "stdout",
144
+ "output_type": "stream",
145
+ "text": [
146
+ "Epoch 1/7, Train Batch 9/82, Train Loss: 0.071097498259893286"
147
+ ]
148
+ }
149
+ ],
150
+ "source": [
151
+ "# Train the model for a fixed number of epochs\n",
152
+ "for epoch in range(num_epochs):\n",
153
+ " # Training loop\n",
154
+ " model.train()\n",
155
+ " train_loss = 0\n",
156
+ " i=0\n",
157
+ " for batch in train_loader:\n",
158
+ " i+=1\n",
159
+ " input_ids, target_ids = batch\n",
160
+ " input_ids, target_ids = input_ids.to(device), target_ids.to(device)\n",
161
+ " optimizer.zero_grad()\n",
162
+ " outputs = model(input_ids, labels=target_ids)\n",
163
+ " loss = loss_fn(outputs.logits.view(-1, outputs.logits.size(-1)), target_ids.view(-1))\n",
164
+ " loss.backward()\n",
165
+ " optimizer.step()\n",
166
+ " train_loss += loss.item()\n",
167
+ " print(f'\\rEpoch {epoch+1}/{num_epochs}, Train Batch {i}/{len(train_loader)}, Train Loss: {train_loss/len(train_loader)}',end=\"\")\n",
168
+ "\n",
169
+ "\n",
170
+ " # Validation loop\n",
171
+ " model.eval()\n",
172
+ " valid_loss = 0\n",
173
+ " with torch.no_grad():\n",
174
+ " i=0\n",
175
+ " for batch in valid_loader:\n",
176
+ " i+=1\n",
177
+ " input_ids, target_ids = batch\n",
178
+ " input_ids, target_ids = input_ids.to(device), target_ids.to(device)\n",
179
+ " outputs = model(input_ids, labels=target_ids)\n",
180
+ " loss = loss_fn(outputs.logits.view(-1, outputs.logits.size(-1)), target_ids.view(-1))\n",
181
+ " valid_loss += loss.item()\n",
182
+ " print(f'\\rEpoch {epoch+1}/{num_epochs}, Valid Batch {i}/{len(valid_loader)}, Valid Loss: {valid_loss/len(valid_loader)}',end=\"\")\n",
183
+ "\n",
184
+ " print(f'\\rEpoch {epoch+1}/{num_epochs}, Train Loss: {train_loss/len(train_loader)}, Valid Loss: {valid_loss/len(valid_loader)}, lr: {learning_rate}',end=\"\\n\")\n",
185
+ " learning_rate /= 5\n",
186
+ "model.save_pretrained('fine_tuned_model')\n",
187
+ "tokenizer.save_pretrained('fine_tuned_tokenizer')"
188
+ ]
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "execution_count": null,
193
+ "metadata": {},
194
+ "outputs": [
195
+ {
196
+ "name": "stderr",
197
+ "output_type": "stream",
198
+ "text": [
199
+ "Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.\n"
200
+ ]
201
+ },
202
+ {
203
+ "data": {
204
+ "text/plain": [
205
+ "'Antonio, who died in 2015, was a brilliant engineer who was able to master complex networks of increasingly complex projects. He was also very involved on airborne radars, ground planes, and hovercrafts. In the mid-90s, several European nations, some being primary producers of CFC, began considering regulations, or even creating public funds to assist their efforts. While extremely conscious of the environmental impact, at the same time, he also advocated for non-proliferation, peaceful'"
206
+ ]
207
+ },
208
+ "execution_count": 4,
209
+ "metadata": {},
210
+ "output_type": "execute_result"
211
+ }
212
+ ],
213
+ "source": [
214
+ "import torch\n",
215
+ "from transformers import GPT2LMHeadModel, GPT2Tokenizer\n",
216
+ "\n",
217
+ "# Define the device to run the model on\n",
218
+ "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
219
+ "\n",
220
+ "# Load the fine-tuned model\n",
221
+ "model_path = 'fine_tuned_model'\n",
222
+ "tokenizer = GPT2Tokenizer.from_pretrained('fine_tuned_tokenizer')\n",
223
+ "model = GPT2LMHeadModel.from_pretrained('fine_tuned_model').to(device)\n",
224
+ "\n",
225
+ "# Set the pad_token_id to the same value as the unk_token_id\n",
226
+ "#model.config.pad_token_id = tokenizer.unk_token_id\n",
227
+ "\n",
228
+ "# Set the generation parameters\n",
229
+ "max_length = 100\n",
230
+ "num_beams = 5\n",
231
+ "no_repeat_ngram_size = 2\n",
232
+ "temperature = 1.0\n",
233
+ "\n",
234
+ "# Generate text using beam search, n-grams, and other techniques\n",
235
+ "prompt = \"Antonio,\"\n",
236
+ "\n",
237
+ "def generate(prompt):\n",
238
+ " input_ids = tokenizer.encode(prompt, return_tensors='pt').to(device)\n",
239
+ " attention_mask = torch.ones(input_ids.shape, dtype=torch.long, device=device)\n",
240
+ " outputs = model.generate(input_ids=input_ids, attention_mask=attention_mask,\n",
241
+ " max_length=max_length, num_beams=num_beams,\n",
242
+ " no_repeat_ngram_size=no_repeat_ngram_size,\n",
243
+ " temperature=temperature, do_sample=True, top_p=0.95,\n",
244
+ " top_k=50)\n",
245
+ "\n",
246
+ " # Convert the generated output to string format\n",
247
+ " generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
248
+ " return generated_text\n",
249
+ "\n",
250
+ "generate(prompt)"
251
+ ]
252
+ },
253
+ {
254
+ "cell_type": "code",
255
+ "execution_count": null,
256
+ "metadata": {},
257
+ "outputs": [
258
+ {
259
+ "data": {
260
+ "application/vnd.jupyter.widget-view+json": {
261
+ "model_id": "ece98d6d9c9149ca8f4caee4b2ad9e34",
262
+ "version_major": 2,
263
+ "version_minor": 0
264
+ },
265
+ "text/plain": [
266
+ "Upload 1 LFS files: 0%| | 0/1 [00:00<?, ?it/s]"
267
+ ]
268
+ },
269
+ "metadata": {},
270
+ "output_type": "display_data"
271
+ },
272
+ {
273
+ "data": {
274
+ "application/vnd.jupyter.widget-view+json": {
275
+ "model_id": "6a183417e6304bd99a135703d3d88717",
276
+ "version_major": 2,
277
+ "version_minor": 0
278
+ },
279
+ "text/plain": [
280
+ "pytorch_model.bin: 0%| | 0.00/510M [00:00<?, ?B/s]"
281
+ ]
282
+ },
283
+ "metadata": {},
284
+ "output_type": "display_data"
285
+ },
286
+ {
287
+ "data": {
288
+ "text/plain": [
289
+ "CommitInfo(commit_url='https://huggingface.co/brunosan/GPT2-impactscience/commit/3316819787943d7a4693aee44c786ba4c2b4fc7f', commit_message='Upload tokenizer', commit_description='', oid='3316819787943d7a4693aee44c786ba4c2b4fc7f', pr_url=None, pr_revision=None, pr_num=None)"
290
+ ]
291
+ },
292
+ "execution_count": 5,
293
+ "metadata": {},
294
+ "output_type": "execute_result"
295
+ }
296
+ ],
297
+ "source": [
298
+ "model.push_to_hub(\"brunosan/GPT2-impactscience\")\n",
299
+ "tokenizer.push_to_hub(\"brunosan/GPT2-impactscience\")"
300
+ ]
301
+ },
302
+ {
303
+ "cell_type": "code",
304
+ "execution_count": null,
305
+ "metadata": {},
306
+ "outputs": [
307
+ {
308
+ "name": "stdout",
309
+ "output_type": "stream",
310
+ "text": [
311
+ "Collecting gradio\n",
312
+ " Downloading gradio-3.19.1-py3-none-any.whl (14.2 MB)\n",
313
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m14.2/14.2 MB\u001b[0m \u001b[31m36.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m00:01\u001b[0m\n",
314
+ "\u001b[?25hRequirement already satisfied: markupsafe in /srv/conda/envs/notebook/lib/python3.9/site-packages (from gradio) (2.1.1)\n",
315
+ "Requirement already satisfied: pydantic in /srv/conda/envs/notebook/lib/python3.9/site-packages (from gradio) (1.10.2)\n",
316
+ "Collecting python-multipart\n",
317
+ " Downloading python_multipart-0.0.6-py3-none-any.whl (45 kB)\n",
318
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m45.7/45.7 kB\u001b[0m \u001b[31m4.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
319
+ "\u001b[?25hRequirement already satisfied: requests in /srv/conda/envs/notebook/lib/python3.9/site-packages (from gradio) (2.28.1)\n",
320
+ "Requirement already satisfied: typing-extensions in /srv/conda/envs/notebook/lib/python3.9/site-packages (from gradio) (4.3.0)\n",
321
+ "Collecting ffmpy\n",
322
+ " Downloading ffmpy-0.3.0.tar.gz (4.8 kB)\n",
323
+ " Preparing metadata (setup.py) ... \u001b[?25ldone\n",
324
+ "\u001b[?25hRequirement already satisfied: pyyaml in /srv/conda/envs/notebook/lib/python3.9/site-packages (from gradio) (5.4.1)\n",
325
+ "Requirement already satisfied: aiohttp in /srv/conda/envs/notebook/lib/python3.9/site-packages (from gradio) (3.8.1)\n",
326
+ "Requirement already satisfied: websockets>=10.0 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from gradio) (10.3)\n",
327
+ "Requirement already satisfied: numpy in /srv/conda/envs/notebook/lib/python3.9/site-packages (from gradio) (1.23.3)\n",
328
+ "Collecting altair>=4.2.0\n",
329
+ " Downloading altair-4.2.2-py3-none-any.whl (813 kB)\n",
330
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m813.6/813.6 kB\u001b[0m \u001b[31m34.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
331
+ "\u001b[?25hCollecting mdit-py-plugins<=0.3.3\n",
332
+ " Downloading mdit_py_plugins-0.3.3-py3-none-any.whl (50 kB)\n",
333
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m50.5/50.5 kB\u001b[0m \u001b[31m3.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
334
+ "\u001b[?25hRequirement already satisfied: fsspec in /srv/conda/envs/notebook/lib/python3.9/site-packages (from gradio) (2022.8.2)\n",
335
+ "Collecting pydub\n",
336
+ " Downloading pydub-0.25.1-py2.py3-none-any.whl (32 kB)\n",
337
+ "Requirement already satisfied: httpx in /srv/conda/envs/notebook/lib/python3.9/site-packages (from gradio) (0.23.0)\n",
338
+ "Requirement already satisfied: pandas in /srv/conda/envs/notebook/lib/python3.9/site-packages (from gradio) (1.4.4)\n",
339
+ "Requirement already satisfied: aiofiles in /srv/conda/envs/notebook/lib/python3.9/site-packages (from gradio) (0.8.0)\n",
340
+ "Requirement already satisfied: matplotlib in /srv/conda/envs/notebook/lib/python3.9/site-packages (from gradio) (3.5.3)\n",
341
+ "Requirement already satisfied: orjson in /srv/conda/envs/notebook/lib/python3.9/site-packages (from gradio) (3.8.0)\n",
342
+ "Requirement already satisfied: fastapi in /srv/conda/envs/notebook/lib/python3.9/site-packages (from gradio) (0.85.0)\n",
343
+ "Requirement already satisfied: pillow in /srv/conda/envs/notebook/lib/python3.9/site-packages (from gradio) (9.2.0)\n",
344
+ "Collecting pycryptodome\n",
345
+ " Downloading pycryptodome-3.17-cp35-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.1 MB)\n",
346
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.1/2.1 MB\u001b[0m \u001b[31m75.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
347
+ "\u001b[?25hRequirement already satisfied: jinja2 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from gradio) (3.1.2)\n",
348
+ "Collecting markdown-it-py[linkify]>=2.0.0\n",
349
+ " Downloading markdown_it_py-2.2.0-py3-none-any.whl (84 kB)\n",
350
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m84.5/84.5 kB\u001b[0m \u001b[31m7.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
351
+ "\u001b[?25hRequirement already satisfied: uvicorn in /srv/conda/envs/notebook/lib/python3.9/site-packages (from gradio) (0.18.3)\n",
352
+ "Requirement already satisfied: jsonschema>=3.0 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from altair>=4.2.0->gradio) (4.16.0)\n",
353
+ "Requirement already satisfied: toolz in /srv/conda/envs/notebook/lib/python3.9/site-packages (from altair>=4.2.0->gradio) (0.12.0)\n",
354
+ "Requirement already satisfied: entrypoints in /srv/conda/envs/notebook/lib/python3.9/site-packages (from altair>=4.2.0->gradio) (0.4)\n",
355
+ "Collecting mdurl~=0.1\n",
356
+ " Downloading mdurl-0.1.2-py3-none-any.whl (10.0 kB)\n",
357
+ "Collecting linkify-it-py<3,>=1\n",
358
+ " Downloading linkify_it_py-2.0.0-py3-none-any.whl (19 kB)\n",
359
+ "Requirement already satisfied: python-dateutil>=2.8.1 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from pandas->gradio) (2.8.2)\n",
360
+ "Requirement already satisfied: pytz>=2020.1 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from pandas->gradio) (2022.2.1)\n",
361
+ "Requirement already satisfied: yarl<2.0,>=1.0 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from aiohttp->gradio) (1.7.2)\n",
362
+ "Requirement already satisfied: charset-normalizer<3.0,>=2.0 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from aiohttp->gradio) (2.1.1)\n",
363
+ "Requirement already satisfied: attrs>=17.3.0 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from aiohttp->gradio) (22.1.0)\n",
364
+ "Requirement already satisfied: aiosignal>=1.1.2 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from aiohttp->gradio) (1.2.0)\n",
365
+ "Requirement already satisfied: multidict<7.0,>=4.5 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from aiohttp->gradio) (6.0.2)\n",
366
+ "Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from aiohttp->gradio) (4.0.2)\n",
367
+ "Requirement already satisfied: frozenlist>=1.1.1 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from aiohttp->gradio) (1.3.1)\n",
368
+ "Requirement already satisfied: starlette==0.20.4 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from fastapi->gradio) (0.20.4)\n",
369
+ "Requirement already satisfied: anyio<5,>=3.4.0 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from starlette==0.20.4->fastapi->gradio) (3.6.1)\n",
370
+ "Requirement already satisfied: httpcore<0.16.0,>=0.15.0 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from httpx->gradio) (0.15.0)\n",
371
+ "Requirement already satisfied: sniffio in /srv/conda/envs/notebook/lib/python3.9/site-packages (from httpx->gradio) (1.3.0)\n",
372
+ "Requirement already satisfied: certifi in /srv/conda/envs/notebook/lib/python3.9/site-packages (from httpx->gradio) (2022.9.14)\n",
373
+ "Requirement already satisfied: rfc3986[idna2008]<2,>=1.3 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from httpx->gradio) (1.5.0)\n",
374
+ "Requirement already satisfied: fonttools>=4.22.0 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from matplotlib->gradio) (4.37.2)\n",
375
+ "Requirement already satisfied: cycler>=0.10 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from matplotlib->gradio) (0.11.0)\n",
376
+ "Requirement already satisfied: pyparsing>=2.2.1 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from matplotlib->gradio) (3.0.9)\n",
377
+ "Requirement already satisfied: packaging>=20.0 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from matplotlib->gradio) (21.3)\n",
378
+ "Requirement already satisfied: kiwisolver>=1.0.1 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from matplotlib->gradio) (1.4.4)\n",
379
+ "Requirement already satisfied: urllib3<1.27,>=1.21.1 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from requests->gradio) (1.26.11)\n",
380
+ "Requirement already satisfied: idna<4,>=2.5 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from requests->gradio) (3.3)\n",
381
+ "Requirement already satisfied: click>=7.0 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from uvicorn->gradio) (8.0.4)\n",
382
+ "Requirement already satisfied: h11>=0.8 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from uvicorn->gradio) (0.12.0)\n",
383
+ "Requirement already satisfied: pyrsistent!=0.17.0,!=0.17.1,!=0.17.2,>=0.14.0 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from jsonschema>=3.0->altair>=4.2.0->gradio) (0.18.1)\n",
384
+ "Collecting uc-micro-py\n",
385
+ " Downloading uc_micro_py-1.0.1-py3-none-any.whl (6.2 kB)\n",
386
+ "Requirement already satisfied: six>=1.5 in /srv/conda/envs/notebook/lib/python3.9/site-packages (from python-dateutil>=2.8.1->pandas->gradio) (1.16.0)\n",
387
+ "Building wheels for collected packages: ffmpy\n",
388
+ " Building wheel for ffmpy (setup.py) ... \u001b[?25ldone\n",
389
+ "\u001b[?25h Created wheel for ffmpy: filename=ffmpy-0.3.0-py3-none-any.whl size=4693 sha256=46e8ead5afd51fafc1a56d6493e03067d54d956c9883722536d9642763e1d1f4\n",
390
+ " Stored in directory: /home/jovyan/.cache/pip/wheels/91/e2/96/f676aa08bfd789328c6576cd0f1fde4a3d686703bb0c247697\n",
391
+ "Successfully built ffmpy\n",
392
+ "Installing collected packages: pydub, ffmpy, uc-micro-py, python-multipart, pycryptodome, mdurl, markdown-it-py, linkify-it-py, mdit-py-plugins, altair, gradio\n",
393
+ "Successfully installed altair-4.2.2 ffmpy-0.3.0 gradio-3.19.1 linkify-it-py-2.0.0 markdown-it-py-2.2.0 mdit-py-plugins-0.3.3 mdurl-0.1.2 pycryptodome-3.17 pydub-0.25.1 python-multipart-0.0.6 uc-micro-py-1.0.1\n"
394
+ ]
395
+ }
396
+ ],
397
+ "source": [
398
+ "!pip install gradio"
399
+ ]
400
+ },
401
+ {
402
+ "cell_type": "code",
403
+ "execution_count": null,
404
+ "metadata": {},
405
+ "outputs": [
406
+ {
407
+ "name": "stderr",
408
+ "output_type": "stream",
409
+ "text": [
410
+ "/srv/conda/envs/notebook/lib/python3.9/site-packages/gradio/inputs.py:27: UserWarning: Usage of gradio.inputs is deprecated, and will not be supported in the future, please import your component from gradio.components\n",
411
+ " warnings.warn(\n",
412
+ "/srv/conda/envs/notebook/lib/python3.9/site-packages/gradio/deprecation.py:40: UserWarning: `optional` parameter is deprecated, and it has no effect\n",
413
+ " warnings.warn(value)\n",
414
+ "/srv/conda/envs/notebook/lib/python3.9/site-packages/gradio/deprecation.py:40: UserWarning: `numeric` parameter is deprecated, and it has no effect\n",
415
+ " warnings.warn(value)\n",
416
+ "/srv/conda/envs/notebook/lib/python3.9/site-packages/gradio/outputs.py:22: UserWarning: Usage of gradio.outputs is deprecated, and will not be supported in the future, please import your components from gradio.components\n",
417
+ " warnings.warn(\n"
418
+ ]
419
+ },
420
+ {
421
+ "name": "stdout",
422
+ "output_type": "stream",
423
+ "text": [
424
+ "Running on local URL: http://127.0.0.1:7861\n",
425
+ "Running on public URL: https://6989ff3075913a1f9b.gradio.live\n",
426
+ "\n",
427
+ "This share link expires in 72 hours. For free permanent hosting and GPU upgrades (NEW!), check out Spaces: https://huggingface.co/spaces\n"
428
+ ]
429
+ },
430
+ {
431
+ "data": {
432
+ "text/html": [
433
+ "<div><iframe src=\"https://6989ff3075913a1f9b.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
434
+ ],
435
+ "text/plain": [
436
+ "<IPython.core.display.HTML object>"
437
+ ]
438
+ },
439
+ "metadata": {},
440
+ "output_type": "display_data"
441
+ },
442
+ {
443
+ "data": {
444
+ "text/plain": []
445
+ },
446
+ "execution_count": 15,
447
+ "metadata": {},
448
+ "output_type": "execute_result"
449
+ },
450
+ {
451
+ "name": "stderr",
452
+ "output_type": "stream",
453
+ "text": [
454
+ "Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.\n",
455
+ "Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.\n"
456
+ ]
457
+ }
458
+ ],
459
+ "source": [
460
+ "import gradio as gr\n",
461
+ "import torch\n",
462
+ "from transformers import GPT2LMHeadModel, GPT2Tokenizer\n",
463
+ "\n",
464
+ "# Load the fine-tuned model and tokenizer\n",
465
+ "model_path = 'fine_tuned_model'\n",
466
+ "tokenizer_path = 'fine_tuned_tokenizer'\n",
467
+ "\n",
468
+ "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
469
+ "tokenizer = GPT2Tokenizer.from_pretrained(tokenizer_path)\n",
470
+ "model = GPT2LMHeadModel.from_pretrained(model_path).to(device)\n",
471
+ "\n",
472
+ "# Define the generation function\n",
473
+ "def generate_text(prompt):\n",
474
+ " input_ids = tokenizer.encode(prompt, return_tensors='pt').to(device)\n",
475
+ " attention_mask = torch.ones(input_ids.shape, dtype=torch.long, device=device)\n",
476
+ " outputs = model.generate(input_ids=input_ids, attention_mask=attention_mask,\n",
477
+ " max_length=100, num_beams=9,\n",
478
+ " no_repeat_ngram_size=2,\n",
479
+ " temperature=1.0, do_sample=True,\n",
480
+ " top_p=0.95, top_k=50)\n",
481
+ "\n",
482
+ " generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
483
+ " return generated_text\n",
484
+ "\n",
485
+ "# Create a Gradio interface\n",
486
+ "input_text = gr.inputs.Textbox(lines=2, label=\"Enter the starting text\")\n",
487
+ "output_text = gr.outputs.Textbox(label=\"Generated Text\")\n",
488
+ "\n",
489
+ "interface = gr.Interface(fn=generate_text, inputs=input_text, outputs=output_text,\n",
490
+ " title=\"GPT-2 Impact Science Text Generator\", description=\"Generate text using a fine-tuned GPT-2 model onthe Impact Science book.\")\n",
491
+ "\n",
492
+ "# Export the Gradio interface to the Hugging Face Model Hub\n",
493
+ "interface.launch(share=True)\n"
494
+ ]
495
+ },
496
+ {
497
+ "cell_type": "code",
498
+ "execution_count": null,
499
+ "metadata": {},
500
+ "outputs": [],
501
+ "source": []
502
+ }
503
+ ],
504
+ "metadata": {
505
+ "kernelspec": {
506
+ "display_name": "Python [conda env:notebook] *",
507
+ "language": "python",
508
+ "name": "conda-env-notebook-py"
509
+ },
510
+ "language_info": {
511
+ "codemirror_mode": {
512
+ "name": "ipython",
513
+ "version": 3
514
+ },
515
+ "file_extension": ".py",
516
+ "mimetype": "text/x-python",
517
+ "name": "python",
518
+ "nbconvert_exporter": "python",
519
+ "pygments_lexer": "ipython3",
520
+ "version": "3.9.13"
521
+ },
522
+ "orig_nbformat": 4,
523
+ "vscode": {
524
+ "interpreter": {
525
+ "hash": "43343113618a7691a2af3d61372ef21fdddd71fdb8d3292e4208750f8afc007e"
526
+ }
527
+ }
528
+ },
529
+ "nbformat": 4,
530
+ "nbformat_minor": 2
531
+ }
text.txt ADDED
The diff for this file is too large to render. See raw diff