Added basic Bart fine tuning logic
Browse files- Dockerfile +14 -0
- bart-run.py +82 -0
- requirements.txt +4 -0
Dockerfile
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# read the doc: https://huggingface.co/docs/hub/spaces-sdks-docker
|
| 2 |
+
# you will also find guides on how best to write your Dockerfile
|
| 3 |
+
|
| 4 |
+
FROM python:3.9
|
| 5 |
+
|
| 6 |
+
WORKDIR /code
|
| 7 |
+
|
| 8 |
+
COPY ./requirements.txt /code/requirements.txt
|
| 9 |
+
|
| 10 |
+
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
| 11 |
+
|
| 12 |
+
COPY . .
|
| 13 |
+
|
| 14 |
+
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
|
bart-run.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# Loading the Data.
|
| 3 |
+
import torch
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from transformers import BartTokenizer, BartForSequenceClassification
|
| 6 |
+
|
| 7 |
+
# Set device
|
| 8 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 9 |
+
|
| 10 |
+
# Load data from names.csv
|
| 11 |
+
# train_data_full = pd.read_csv('names_balanced_train.csv',header=None,names=["name","country"])
|
| 12 |
+
# test_data = pd.read_csv('names_balanced_test.csv',header=None,names=["name","country"])
|
| 13 |
+
|
| 14 |
+
joke_data = pd.read_csv('jokes.csv', sep='|', names=["joke", "label"], skiprows=1)
|
| 15 |
+
noJoke_data = pd.read_csv('not_jokes.csv', sep='|', names=["joke", "label"], skiprows=1)
|
| 16 |
+
frames = [joke_data, noJoke_data]
|
| 17 |
+
train_data = pd.concat(frames)
|
| 18 |
+
|
| 19 |
+
test_data = pd.read_csv('test_jokes.csv', sep='|', names=["joke", "label"], skiprows=1)
|
| 20 |
+
|
| 21 |
+
numCategories = 2
|
| 22 |
+
tokenizer = BartTokenizer.from_pretrained('facebook/bart-large')
|
| 23 |
+
model = BartForSequenceClassification.from_pretrained('facebook/bart-large', num_labels=numCategories)
|
| 24 |
+
model = model.to(device)
|
| 25 |
+
|
| 26 |
+
# Convert country column to one-hot encoding
|
| 27 |
+
one_hot_train = pd.get_dummies(train_data['label'])
|
| 28 |
+
one_hot_test = pd.get_dummies(test_data['label'])
|
| 29 |
+
|
| 30 |
+
# Tokenize names and convert to PyTorch dataset
|
| 31 |
+
inputs_train = tokenizer(list(train_data['joke']), return_tensors='pt', padding=True)
|
| 32 |
+
labels_train = torch.tensor(one_hot_train.values, dtype=torch.float32)
|
| 33 |
+
dataset_train = torch.utils.data.TensorDataset(inputs_train['input_ids'], inputs_train['attention_mask'], labels_train)
|
| 34 |
+
inputs_test = tokenizer(list(test_data['joke']), return_tensors='pt', padding=True)
|
| 35 |
+
labels_test = torch.tensor(one_hot_test.values, dtype=torch.float32)
|
| 36 |
+
dataset_test = torch.utils.data.TensorDataset(inputs_test['input_ids'], inputs_test['attention_mask'], labels_test)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# Define training parameters
|
| 40 |
+
epochs = 10
|
| 41 |
+
batch_size = 32
|
| 42 |
+
learning_rate = 1e-5
|
| 43 |
+
|
| 44 |
+
# Train model
|
| 45 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
|
| 46 |
+
data_loader_train = torch.utils.data.DataLoader(dataset_train, batch_size=batch_size, shuffle=True)
|
| 47 |
+
data_loader_test = torch.utils.data.DataLoader(dataset_test, batch_size=batch_size)
|
| 48 |
+
|
| 49 |
+
print(f"\nTraining on {len(train_data)} examples\n")
|
| 50 |
+
print("Num. Parameters:", sum(p.numel() for p in model.parameters() if p.requires_grad))
|
| 51 |
+
|
| 52 |
+
for epoch in range(epochs):
|
| 53 |
+
# Compute average loss after 100 steps
|
| 54 |
+
avg_loss = 0
|
| 55 |
+
for step, batch in enumerate(data_loader_train):
|
| 56 |
+
input_ids, attention_mask, labels = batch
|
| 57 |
+
input_ids, attention_mask, labels = input_ids.to(device), attention_mask.to(device), labels.to(device)
|
| 58 |
+
outputs = model(input_ids, attention_mask=attention_mask, labels=labels)
|
| 59 |
+
loss = outputs[0]
|
| 60 |
+
avg_loss += loss.item()
|
| 61 |
+
if step % 100 == 0:
|
| 62 |
+
print(f"Step {step}/{len(data_loader_train)} Loss {loss} Avg Train Loss {avg_loss / (step + 1)}")
|
| 63 |
+
optimizer.zero_grad()
|
| 64 |
+
loss.backward()
|
| 65 |
+
optimizer.step()
|
| 66 |
+
loss = avg_loss / len(data_loader_train)
|
| 67 |
+
# Print loss after every epoch
|
| 68 |
+
print(f"Epoch {epoch+1} Test Loss {loss}")
|
| 69 |
+
# Compute accuracy after every epoch
|
| 70 |
+
correct = 0
|
| 71 |
+
total = 0
|
| 72 |
+
for step, batch in enumerate(data_loader_test):
|
| 73 |
+
input_ids, attention_mask, labels = batch
|
| 74 |
+
input_ids, attention_mask, labels = input_ids.to(device), attention_mask.to(device), labels.to(device)
|
| 75 |
+
outputs = model(input_ids, attention_mask=attention_mask)
|
| 76 |
+
predicted = torch.argmax(outputs[0], dim=1)
|
| 77 |
+
total += labels.size(0)
|
| 78 |
+
correct += (predicted == torch.argmax(labels, dim=1)).sum().item()
|
| 79 |
+
print(f"Test Accuracy {100*correct/total}%\n")
|
| 80 |
+
|
| 81 |
+
# Save model
|
| 82 |
+
model.save_pretrained('fine-tuned-bart_countries')
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
transformers==4.12.0
|
| 2 |
+
torch==1.8.2
|
| 3 |
+
pandas==1.3.3
|
| 4 |
+
numpy==1.21.2
|