aapot
commited on
Commit
·
58ed682
1
Parent(s):
f71d1c2
Add toxicity calculation script
Browse files- calculate_toxicity_labels.py +61 -0
calculate_toxicity_labels.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import AutoTokenizer, FlaxBertForSequenceClassification
|
| 2 |
+
import datasets
|
| 3 |
+
import jax
|
| 4 |
+
import jax.numpy as jnp
|
| 5 |
+
import time
|
| 6 |
+
from flax.training.common_utils import shard
|
| 7 |
+
from jax import pmap
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def pred_fn(inputs):
|
| 11 |
+
outputs = model(**inputs)
|
| 12 |
+
return jax.nn.sigmoid(outputs.logits)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def get_toxicity(batch, batch_size):
|
| 16 |
+
num_examples = len(batch["text"])
|
| 17 |
+
inputs = tokenizer(
|
| 18 |
+
batch["text"],
|
| 19 |
+
return_tensors="np",
|
| 20 |
+
truncation=True,
|
| 21 |
+
padding="max_length",
|
| 22 |
+
max_length=512,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
inputs = shard(
|
| 26 |
+
{
|
| 27 |
+
k: jnp.pad(jnp.array(v), ((0, batch_size - num_examples), (0, 0)))
|
| 28 |
+
for k, v in inputs.items()
|
| 29 |
+
}
|
| 30 |
+
)
|
| 31 |
+
preds = p_pred(inputs)
|
| 32 |
+
preds = preds.reshape(-1, preds.shape[-1])[:num_examples]
|
| 33 |
+
for k, v in model.config.id2label.items():
|
| 34 |
+
batch[v] = preds[:, k].tolist()
|
| 35 |
+
return batch
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
p_pred = pmap(pred_fn, "inputs")
|
| 39 |
+
|
| 40 |
+
tokenizer = AutoTokenizer.from_pretrained("TurkuNLP/bert-large-finnish-cased-toxicity")
|
| 41 |
+
model = FlaxBertForSequenceClassification.from_pretrained(
|
| 42 |
+
"TurkuNLP/bert-large-finnish-cased-toxicity", from_pt=True, dtype=jnp.bfloat16
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
dataset = datasets.load_from_disk("/researchdisk/mc4_3.1.0_fi_cleaned")
|
| 47 |
+
|
| 48 |
+
BATCH_SIZE = 8192
|
| 49 |
+
dataset = dataset.map(
|
| 50 |
+
get_toxicity,
|
| 51 |
+
num_proc=1,
|
| 52 |
+
batched=True,
|
| 53 |
+
batch_size=BATCH_SIZE,
|
| 54 |
+
fn_kwargs={"batch_size": BATCH_SIZE},
|
| 55 |
+
)
|
| 56 |
+
print(dataset)
|
| 57 |
+
|
| 58 |
+
# SAVE DATASET
|
| 59 |
+
dataset.save_to_disk(
|
| 60 |
+
"/researchdisk/mc4_3.1.0_fi_cleaned_dataset_toxicity_labels", num_proc=32
|
| 61 |
+
)
|