|
import torch |
|
from transformers import T5Tokenizer, T5ForConditionalGeneration, Trainer, TrainingArguments |
|
from datasets import Dataset |
|
|
|
|
|
model_name = "google-t5/t5-small" |
|
tokenizer = T5Tokenizer.from_pretrained(model_name) |
|
model = T5ForConditionalGeneration.from_pretrained(model_name) |
|
|
|
|
|
with open('data.txt', 'r') as file: |
|
text = file.read() |
|
|
|
|
|
def preprocess_function(examples): |
|
|
|
inputs = tokenizer(examples['text'], truncation=True, padding='max_length', max_length=512) |
|
labels = tokenizer(examples['text'], truncation=True, padding='max_length', max_length=512) |
|
inputs['labels'] = labels['input_ids'] |
|
return inputs |
|
|
|
|
|
|
|
def create_dataset(text): |
|
return Dataset.from_dict({ |
|
'text': [text[i:i+512] for i in range(0, len(text), 512)] |
|
}) |
|
|
|
dataset = create_dataset(text) |
|
tokenized_dataset = dataset.map(preprocess_function, batched=True) |
|
|
|
|
|
train_dataset = tokenized_dataset.shuffle(seed=42).select([i for i in list(range(len(tokenized_dataset)))]) |
|
eval_dataset = train_dataset |
|
|
|
|
|
training_args = TrainingArguments( |
|
output_dir="./results", |
|
evaluation_strategy="epoch", |
|
learning_rate=5e-5, |
|
per_device_train_batch_size=2, |
|
per_device_eval_batch_size=2, |
|
num_train_epochs=3, |
|
weight_decay=0.01, |
|
logging_dir="./logs", |
|
logging_steps=10, |
|
) |
|
|
|
|
|
trainer = Trainer( |
|
model=model, |
|
args=training_args, |
|
train_dataset=train_dataset, |
|
eval_dataset=eval_dataset, |
|
) |
|
|
|
|
|
trainer.train() |
|
trainer.evaluate() |
|
|
|
|
|
model.save_pretrained("./t5-small-finetuned") |
|
tokenizer.save_pretrained("./t5-small-finetuned") |
|
|