Ricardo Rei
commited on
Commit
·
44e6fb6
1
Parent(s):
0f56920
multilingual fine-edu classifier
Browse files
README.md
CHANGED
|
@@ -1,9 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
```python
|
|
|
|
| 4 |
import torch
|
| 5 |
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
| 6 |
-
from
|
|
|
|
| 7 |
|
| 8 |
device = "cuda"
|
| 9 |
path = "Unbabel/mfineweb-edu-classifier"
|
|
@@ -15,19 +31,104 @@ model = AutoModelForSequenceClassification.from_pretrained(
|
|
| 15 |
)
|
| 16 |
tokenizer = AutoTokenizer.from_pretrained(path, use_fast=True)
|
| 17 |
|
| 18 |
-
def
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
]
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
]
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
```
|
|
|
|
| 1 |
+
language:
|
| 2 |
+
- multilingual
|
| 3 |
+
license: apache-2.0
|
| 4 |
+
---
|
| 5 |
|
| 6 |
+
## Running Model:
|
| 7 |
+
To run inference you must install
|
| 8 |
+
```
|
| 9 |
+
pip install transformers[torch]
|
| 10 |
+
pip install datasets
|
| 11 |
+
pip install pandas
|
| 12 |
+
pip install tqdm
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
After installing those libraries you can sun the following code:
|
| 16 |
|
| 17 |
```python
|
| 18 |
+
import pandas as pd
|
| 19 |
import torch
|
| 20 |
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
| 21 |
+
from tqdm import tqdm
|
| 22 |
+
|
| 23 |
|
| 24 |
device = "cuda"
|
| 25 |
path = "Unbabel/mfineweb-edu-classifier"
|
|
|
|
| 31 |
)
|
| 32 |
tokenizer = AutoTokenizer.from_pretrained(path, use_fast=True)
|
| 33 |
|
| 34 |
+
def get_model_outputs(texts):
|
| 35 |
+
inputs = tokenizer(texts, padding=True, truncation=True, return_tensors="pt", max_length=512).to(model.device)
|
| 36 |
+
with torch.no_grad():
|
| 37 |
+
outputs = model(**inputs)
|
| 38 |
+
score = outputs.logits
|
| 39 |
+
prob = torch.nn.functional.sigmoid(outputs.binary_logits)
|
| 40 |
+
return score.cpu(), prob.cpu()
|
| 41 |
+
|
| 42 |
+
def batchify_texts(texts, batch_size):
|
| 43 |
+
for i in range(0, len(texts), batch_size):
|
| 44 |
+
yield texts[i:i + batch_size]
|
| 45 |
+
|
| 46 |
+
# TODO: replace the next line with the texts you want to classify
|
| 47 |
+
texts = LIST_WITH_TEXTS_TO_CLASSIFY
|
| 48 |
+
batch_size = 64 # Adjust based on your available memory and model capacity
|
| 49 |
+
num_batches = (len(texts) + batch_size - 1) // batch_size
|
| 50 |
+
|
| 51 |
+
all_scores = []
|
| 52 |
+
all_probs = []
|
| 53 |
+
with tqdm(total=num_batches, dynamic_ncols=True) as pbar:
|
| 54 |
+
for batch_num, batch in enumerate(batchify_texts(texts, batch_size), 1):
|
| 55 |
+
score, probs = get_model_outputs(batch)
|
| 56 |
+
all_scores.append(score)
|
| 57 |
+
all_probs.append(probs)
|
| 58 |
+
pbar.set_description(f"Processing Batch {batch_num}/{num_batches}")
|
| 59 |
+
pbar.update(1)
|
| 60 |
+
|
| 61 |
+
# SCORES is the output of the regression head and should reflect the
|
| 62 |
+
# educational score of the text!
|
| 63 |
+
scores = torch.cat(all_scores, dim=0).squeeze()
|
| 64 |
+
|
| 65 |
+
## BINARY_PRED is the output of the classification head that tells
|
| 66 |
+
# if a text has an acceptable educational score or not.
|
| 67 |
+
# NOTE: Converting the scores into binary predictions is also possible
|
| 68 |
+
all_probs = torch.cat(all_probs, dim=0).squeeze()
|
| 69 |
+
binary_pred = (all_probs >= 0.5).numpy().astype(int)
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
## English Results:
|
| 73 |
+
|
| 74 |
+
When testing the model on an english partition with 37537 samples the results are comparable to the original FineEdu-classifier.
|
| 75 |
+
|
| 76 |
+
Regression head results:
|
| 77 |
+
```
|
| 78 |
+
precision recall f1-score support
|
| 79 |
+
|
| 80 |
+
0 0.80 0.53 0.64 5130
|
| 81 |
+
1 0.80 0.88 0.83 21602
|
| 82 |
+
2 0.63 0.58 0.61 7849
|
| 83 |
+
3 0.54 0.62 0.58 2310
|
| 84 |
+
4 0.62 0.48 0.54 645
|
| 85 |
+
5 0.00 0.00 0.00 1
|
| 86 |
+
|
| 87 |
+
accuracy 0.74 37537
|
| 88 |
+
macro avg 0.56 0.51 0.53 37537
|
| 89 |
+
weighted avg 0.74 0.74 0.74 37537
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
Binary head results:
|
| 93 |
+
```
|
| 94 |
+
precision recall f1-score support
|
| 95 |
+
|
| 96 |
+
0 0.98 0.97 0.98 34581
|
| 97 |
+
1 0.71 0.74 0.73 2956
|
| 98 |
+
|
| 99 |
+
accuracy 0.96 37537
|
| 100 |
+
macro avg 0.85 0.86 0.85 37537
|
| 101 |
+
weighted avg 0.96 0.96 0.96 37537
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
## Multilingual Results:
|
| 105 |
+
|
| 106 |
+
If we evaluate on the same texts translated into 15 different languages are almost identical!
|
| 107 |
+
|
| 108 |
+
Regression head results:
|
| 109 |
+
```
|
| 110 |
+
precision recall f1-score support
|
| 111 |
+
|
| 112 |
+
0 0.80 0.50 0.61 5130
|
| 113 |
+
1 0.79 0.87 0.83 21602
|
| 114 |
+
2 0.61 0.58 0.59 7849
|
| 115 |
+
3 0.52 0.61 0.56 2310
|
| 116 |
+
4 0.61 0.38 0.47 645
|
| 117 |
+
5 0.00 0.00 0.00 1
|
| 118 |
+
|
| 119 |
+
accuracy 0.73 37537
|
| 120 |
+
macro avg 0.55 0.49 0.51 37537
|
| 121 |
+
weighted avg 0.73 0.73 0.73 37537
|
| 122 |
+
```
|
| 123 |
|
| 124 |
+
Binary head results:
|
| 125 |
+
```
|
| 126 |
+
precision recall f1-score support
|
|
|
|
| 127 |
|
| 128 |
+
0 0.98 0.97 0.97 34581
|
| 129 |
+
1 0.70 0.71 0.71 2956
|
|
|
|
| 130 |
|
| 131 |
+
accuracy 0.95 37537
|
| 132 |
+
macro avg 0.84 0.84 0.84 37537
|
| 133 |
+
weighted avg 0.95 0.95 0.95 37537
|
| 134 |
+
```
|
train.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from classifier import DebertaV2ForSequenceClassification
|
| 4 |
+
from datasets import Dataset
|
| 5 |
+
from scipy.stats import pearsonr
|
| 6 |
+
from sklearn.metrics import accuracy_score, precision_score, recall_score
|
| 7 |
+
from transformers import (AutoTokenizer, DataCollatorWithPadding, Trainer,
|
| 8 |
+
TrainingArguments)
|
| 9 |
+
|
| 10 |
+
tokenizer = AutoTokenizer.from_pretrained("microsoft/mdeberta-v3-base")
|
| 11 |
+
|
| 12 |
+
def sigmoid(x):
|
| 13 |
+
return 1 / (1 + np.exp(-x))
|
| 14 |
+
|
| 15 |
+
def compute_metrics(eval_pred):
|
| 16 |
+
predictions, labels = eval_pred
|
| 17 |
+
scores, binary_logits = predictions
|
| 18 |
+
scores = scores.squeeze()
|
| 19 |
+
probs = sigmoid(binary_logits.squeeze())
|
| 20 |
+
predicted_labels = (probs >= 0.5).astype(int)
|
| 21 |
+
binary_labels = (labels >= 3).astype(int)
|
| 22 |
+
return {
|
| 23 |
+
'pearson': pearsonr(scores, labels)[0],
|
| 24 |
+
'accuracy': accuracy_score(binary_labels, predicted_labels),
|
| 25 |
+
'precision': precision_score(binary_labels, predicted_labels),
|
| 26 |
+
'recall': recall_score(binary_labels, predicted_labels),
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
def tokenize_function(examples):
|
| 30 |
+
return tokenizer(examples["text"], truncation=True, max_length=512)
|
| 31 |
+
|
| 32 |
+
def train_classifier():
|
| 33 |
+
train_csv = pd.read_csv(PATH_TO_TRAINSET)
|
| 34 |
+
train_dataset = Dataset.from_pandas(train_csv)
|
| 35 |
+
|
| 36 |
+
test_csv = pd.read_csv(PATH_TO_TESTSET).sample(n=10_000, random_state=42)
|
| 37 |
+
test_dataset = Dataset.from_pandas(test_csv)
|
| 38 |
+
|
| 39 |
+
train_dataset = train_dataset.map(tokenize_function, batched=True)
|
| 40 |
+
test_dataset = test_dataset.map(tokenize_function, batched=True)
|
| 41 |
+
train_dataset = train_dataset.with_format("torch")
|
| 42 |
+
test_dataset = test_dataset.with_format("torch")
|
| 43 |
+
|
| 44 |
+
data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
|
| 45 |
+
|
| 46 |
+
training_args = TrainingArguments(
|
| 47 |
+
output_dir="./results",
|
| 48 |
+
evaluation_strategy="epoch",
|
| 49 |
+
save_strategy="epoch",
|
| 50 |
+
learning_rate=2e-5,
|
| 51 |
+
per_device_train_batch_size=16,
|
| 52 |
+
per_device_eval_batch_size=16,
|
| 53 |
+
num_train_epochs=3,
|
| 54 |
+
weight_decay=0.01,
|
| 55 |
+
logging_dir="./logs",
|
| 56 |
+
logging_steps=10,
|
| 57 |
+
)
|
| 58 |
+
model = DebertaV2ForSequenceClassification.from_pretrained("microsoft/mdeberta-v3-base")
|
| 59 |
+
print ("Freezing model embeddings!")
|
| 60 |
+
model.freeze_embeddings()
|
| 61 |
+
trainer = Trainer(
|
| 62 |
+
model=model,
|
| 63 |
+
args=training_args,
|
| 64 |
+
train_dataset=train_dataset,
|
| 65 |
+
eval_dataset=test_dataset,
|
| 66 |
+
tokenizer=tokenizer,
|
| 67 |
+
data_collator=data_collator,
|
| 68 |
+
compute_metrics=compute_metrics
|
| 69 |
+
)
|
| 70 |
+
trainer.train()
|
| 71 |
+
# Evaluate the model
|
| 72 |
+
trainer.evaluate()
|
| 73 |
+
#trainer.push_to_hub(private=True, model_name="mFine-Edu-classifier")
|
| 74 |
+
|
| 75 |
+
if __name__ == "__main__":
|
| 76 |
+
train_classifier()
|