vividsd commited on
Commit
5c29939
·
verified ·
1 Parent(s): a44c2fb

Create notebook

Browse files
Files changed (1) hide show
  1. notebook +125 -0
notebook ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #[My model deployed on Hugging Face](https://huggingface.co/vividsd/gpt2-enrondataset)
2
+ Viviane da Silva Dilly
3
+
4
+ In this notebook, I did part 2 and 3 of fine tuning a LLM (I chose GPT2) on the enron dataset from kaggle.
5
+
6
+ * Fine-tune a Language Model on the Enron dataset
7
+ * Create a Gradio Interface that answers questions related to the case deploying it in a Huggingface Space
8
+
9
+ As I mentioned below on my code, after many many days of trying to use the whole data set and having my code crashing after long hours of waiting, I decided to use a sample.
10
+
11
+ # I'll start by installing and importing all I need
12
+
13
+ !pip install transformers pandas torch
14
+
15
+ import torch
16
+ import pandas as pd
17
+
18
+ from transformers import GPT2LMHeadModel, GPT2Tokenizer, TextDataset, DataCollatorForLanguageModeling, Trainer, TrainingArguments
19
+ from google.colab import drive
20
+ drive.mount('/content/drive')
21
+
22
+ #Reading my data set
23
+ enron_data = pd.read_csv('/content/drive/MyDrive/Mestrado/emails.csv')
24
+
25
+ # I tried to take the whole dataset several times, but due to memory problems, I decided to go for a sample of 10k
26
+ sample_size = 10000
27
+ sample_enron_data = enron_data.sample(sample_size)
28
+ sample_enron_data.to_csv("sample_enron_dataset.csv", index=False)
29
+
30
+ # now that I have a sample of my data set running locally, I'll call it to make sure it's all good
31
+ sample_enron_data.head()
32
+
33
+
34
+ len(sample_enron_data)
35
+
36
+ # Now I'll concatenate all email messages into a single string
37
+ text = "\n".join(sample_enron_data['message'])
38
+
39
+ tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
40
+ tokenizer.add_special_tokens({'pad_token': '[PAD]'})
41
+ input_ids = tokenizer(text, return_tensors='pt', max_length=512, truncation=True, padding=True)['input_ids']
42
+
43
+ from transformers import GPT2LMHeadModel, GPT2Tokenizer, AdamW, get_linear_schedule_with_warmup
44
+ from torch.utils.data import Dataset, DataLoader
45
+ from tqdm import tqdm
46
+
47
+ # Now I'll try to define a custom dataset
48
+ class EmailDataset(Dataset):
49
+ def __init__(self, input_ids):
50
+ self.input_ids = input_ids
51
+
52
+ def __len__(self):
53
+ return len(self.input_ids)
54
+
55
+ def __getitem__(self, idx):
56
+ return self.input_ids[idx]
57
+
58
+ dataset = EmailDataset(input_ids)
59
+
60
+ # I'll define the GPT-2 model
61
+ model = GPT2LMHeadModel.from_pretrained('gpt2')
62
+
63
+ #Since I tried many times and it crashed, following some tutorials I saw that I could try to define this optimizer
64
+ optimizer = AdamW(model.parameters(), lr=5e-5)
65
+ scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=0, num_training_steps=len(dataset))
66
+
67
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
68
+ model.to(device)
69
+
70
+ # Now I'll train it
71
+ model.train()
72
+
73
+ train_dataloader = DataLoader(dataset, batch_size=8, shuffle=True)
74
+
75
+ num_epochs = 3
76
+ for epoch in range(num_epochs):
77
+ epoch_loss = 0
78
+ steps = 0
79
+
80
+ for batch in tqdm(train_dataloader, desc=f"Epoch {epoch + 1}"):
81
+ batch = batch.to(device)
82
+
83
+ outputs = model(input_ids=batch, labels=batch)
84
+ loss = outputs.loss
85
+
86
+ optimizer.zero_grad()
87
+ loss.backward()
88
+ optimizer.step()
89
+ scheduler.step()
90
+
91
+ epoch_loss += loss.item()
92
+ steps += 1
93
+
94
+ print(f"Epoch {epoch + 1} - Average Loss: {epoch_loss / steps}")
95
+
96
+ # and then I'll save the fine-tuned model
97
+ model.save_pretrained("./fine_tuned_model")
98
+
99
+
100
+ ### PART 3: Create a Gradio Interface that answers questions related to the case
101
+ Now, having fine tuned the model, I proceed to creating the gradio interface
102
+
103
+ # In order to make the gradio interface, first I need to install it and then import
104
+ !pip install gradio
105
+ import gradio as gr
106
+
107
+ # First I'll load the fine tuned model
108
+ model_fine_tuned = GPT2LMHeadModel.from_pretrained("./fine_tuned_model")
109
+ tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
110
+
111
+ # Then I'll create the function to generate the response
112
+ def generate_response(question):
113
+ input_ids = tokenizer.encode(question, return_tensors="pt")
114
+ output = model_fine_tuned.generate(input_ids, max_length=200, num_return_sequences=1, temperature=0.7)
115
+ response = tokenizer.decode(output[0], skip_special_tokens=True)
116
+ return response
117
+
118
+ # Finally I'll create Gradio interface
119
+ gr.Interface(generate_response, "textbox", "textbox", title="Ask Enron Dataset", description="Enter a question about the case").launch()
120
+
121
+
122
+ ### Part 4: Deploy the Gradio Interface in a HuggingFace Space
123
+ (you find the link also on the top of this notebook)
124
+
125
+ #[My model deployed on Hugging Face](https://huggingface.co/vividsd/gpt2-enrondataset)