|
import transformers |
|
import numpy as np |
|
from datasets import load_dataset, DatasetDict |
|
from transformers import AutoModelForSeq2SeqLM |
|
from transformers import AutoTokenizer |
|
from transformers import DataCollatorForSeq2Seq |
|
import evaluate |
|
import numpy as np |
|
from transformers import Seq2SeqTrainingArguments |
|
from transformers import Seq2SeqTrainer |
|
from torch.utils.data import DataLoader |
|
from transformers import pipeline |
|
from transformers import AdamW |
|
from accelerate import Accelerator |
|
from transformers import get_scheduler |
|
from huggingface_hub import Repository, get_full_repo_name |
|
from tqdm.auto import tqdm |
|
import torch |
|
from torch import Tensor |
|
import os |
|
|
|
"""CONSTANTS""" |
|
MAX_LENGTH = 128 |
|
RUN_PROCESS_DATA_TOKENIZER = True |
|
DATASET_PATH = "aatherton2024/eng-nah-svo" |
|
MODEL_CHECKPOINT = "eng-nah-svo-translation" |
|
PRETRAINED_MODEL = "t5-small" |
|
METRIC_BLEU = evaluate.load("sacrebleu") |
|
METRIC_CHRF = evaluate.load("chrf") |
|
ARGS = Seq2SeqTrainingArguments( |
|
MODEL_CHECKPOINT, |
|
evaluation_strategy="no", |
|
save_strategy="epoch", |
|
learning_rate=2e-5, |
|
per_device_train_batch_size=32, |
|
per_device_eval_batch_size=64, |
|
weight_decay=0.01, |
|
save_total_limit=3, |
|
num_train_epochs=3, |
|
predict_with_generate=True, |
|
fp16=False, |
|
push_to_hub=True, |
|
use_cpu=False, |
|
no_cuda=False |
|
) |
|
|
|
"""Simple method to either load tokenizer or train new one""" |
|
def get_tokenizer(): |
|
if not RUN_PROCESS_DATA_TOKENIZER: |
|
return AutoTokenizer.from_pretrained(MODEL_CHECKPOINT) |
|
|
|
def get_training_corpus(raw_datasets): |
|
return ( |
|
raw_datasets["train"][ds][i : i + 1000] |
|
for i in range(0, len(raw_datasets["train"]), 1000) |
|
for ds in ["en", "fr"] |
|
) |
|
|
|
training_corpus = get_training_corpus(raw_datasets) |
|
old_tokenizer = AutoTokenizer.from_pretrained(PRETRAINED_MODEL) |
|
tokenizer = old_tokenizer.train_new_from_iterator(training_corpus, 52000) |
|
tokenizer.add_special_tokens({'pad_token': '<pad>', 'eos_token': "</s>"}) |
|
tokenizer.save_pretrained(MODEL_CHECKPOINT) |
|
tokenizer.push_to_hub(MODEL_CHECKPOINT) |
|
return tokenizer |
|
|
|
"""Scan dataset, storing lists of english and french words then returning the tokenization of them""" |
|
def preprocess_function(examples): |
|
prefix = "translate en to fr" |
|
inputs = [prefix + example for example in examples["en"]] |
|
targets = [prefix + example for example in examples["fr"]] |
|
model_inputs = tokenizer( |
|
inputs, text_target=targets, max_length=MAX_LENGTH, truncation=True, padding=True |
|
) |
|
return model_inputs |
|
|
|
"""Apply preprocessing in one go to all splits of the dataset""" |
|
def tokenize_datasets(): |
|
tokenized_datasets = raw_datasets.map( |
|
preprocess_function, |
|
batched=True, |
|
remove_columns=raw_datasets["train"].column_names |
|
) |
|
return tokenized_datasets |
|
|
|
"""Simple method to return test metrics""" |
|
def compute_metrics(eval_preds): |
|
preds, labels = eval_preds |
|
|
|
if isinstance(preds, tuple): |
|
preds = preds[0] |
|
|
|
decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True) |
|
|
|
|
|
labels = np.where(labels != -100, labels, tokenizer.pad_token_id) |
|
decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True) |
|
|
|
|
|
decoded_preds = [pred.strip() for pred in decoded_preds] |
|
decoded_labels = [[label.strip()] for label in decoded_labels] |
|
|
|
result_bleu = METRIC_BLEU.compute(predictions=decoded_preds, references=decoded_labels) |
|
result_chrf = METRIC_CHRF.compute(predictions=decoded_preds, references=decoded_labels) |
|
return {"bleu": result_bleu["score"], "chrf": result_chrf["score"]} |
|
|
|
"""Simple method to evaluate, train, then reevaluate model""" |
|
def evaluate_train_evaluate(): |
|
print(trainer.evaluate(max_length=MAX_LENGTH)) |
|
trainer.train() |
|
print(trainer.evaluate(max_length=MAX_LENGTH)) |
|
|
|
|
|
"""Method to test translation capabilities of model""" |
|
def test_translation(): |
|
sequence = "he bofrimizes us" |
|
inputs = tokenizer(sequence, return_tensors="pt").input_ids.to("cuda") |
|
print(inputs) |
|
print(tokenizer.tokenize(sequence)) |
|
outputs = model.generate(inputs, max_new_tokens=40, do_sample=True, top_k=30, top_p=0.95) |
|
print(outputs) |
|
print(tokenizer.decode(outputs[0], skip_special_tokens=True)) |
|
|
|
translator = pipeline("translation_en_to_fr", model="eng-nah-svo-translation") |
|
print(translator(sequence)) |
|
|
|
"""Main testing script""" |
|
raw_datasets = load_dataset("aatherton2024/eng-nah-svo") |
|
tokenizer = get_tokenizer() |
|
tokenized_datasets = tokenize_datasets() |
|
model = AutoModelForSeq2SeqLM.from_pretrained(PRETRAINED_MODEL) |
|
data_collator = DataCollatorForSeq2Seq(tokenizer, model=model) |
|
trainer = Seq2SeqTrainer( |
|
model, |
|
ARGS, |
|
train_dataset=tokenized_datasets["train"], |
|
eval_dataset=tokenized_datasets["test"], |
|
data_collator=data_collator, |
|
tokenizer=tokenizer, |
|
compute_metrics=compute_metrics, |
|
) |
|
|
|
evaluate_train_evaluate() |
|
|
|
test_translation() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|