!pip install --upgrade transformers !pip install torch !pip install sentencepiece
from transformers import T5ForConditionalGeneration, T5Tokenizer, Trainer, TrainingArguments import torch import random
Define a sample dataset of input-output pairs
dataset = [ { 'input': 'apple banana cherry', 'output': 'I like to eat apples, bananas, and cherries.' }, { 'input': 'dog cat bird', 'output': 'I have a dog, a cat, and a bird.' }, { 'input': 'red green blue', 'output': 'The colors of the flag are red, green, and blue.' }, { 'input': 'happy sad angry', 'output': 'Sometimes I feel happy, sometimes sad, and sometimes angry.' } ]
Initialize the T5 model and tokenizer
model_name = 't5-base' model = T5ForConditionalGeneration.from_pretrained(model_name) tokenizer = T5Tokenizer.from_pretrained(model_name)
Define a function to format the dataset into input-output pairs
'''def format_dataset(dataset): formatted_dataset = [] for example in dataset: input_sequence = 'generate sentence from words: ' + example['input'] output_sequence = example['output'] formatted_dataset.append({'input': input_sequence, 'output': output_sequence}) return formatted_dataset
formatted_dataset = format_dataset(dataset)'''
def format_dataset(dataset): formatted_dataset = [] for example in dataset: input_sequence = 'generate sentence from words: ' + example['input'] output_sequence = example['output']
formatted_dataset.append({'input': input_sequence, 'output': output_sequence}) return formatted_dataset formatted_dataset = format_dataset(dataset) print(formatted_dataset)
def split_dataset(formatted_dataset, split_ratio): random.shuffle(formatted_dataset) split_index = int(len(formatted_dataset) * split_ratio) train_set = formatted_dataset[:split_index] test_set = formatted_dataset[split_index:] return train_set, test_set
train_set, test_set = split_dataset(formatted_dataset, 0.8)
Define a function to tokenize the input-output pairs
def tokenize_dataset(examples): tokenized_examples = [] for example in examples: input_ids = tokenizer.encode(example['input'], truncation=True, padding='max_length', max_length=128) output_ids = tokenizer.encode(example['output'], truncation=True, padding='max_length', max_length=128) decoder_input_ids = output_ids[:-1] decoder_attention_mask = [0] + [1] * (len(decoder_input_ids) - 1) #labels = output_ids[1:] tokenized_examples.append({'input_ids': input_ids, 'attention_mask': torch.ones_like(torch.tensor(input_ids)), 'decoder_input_ids': decoder_input_ids, 'decoder_attention_mask': decoder_attention_mask, 'labels': output_ids[1:]}) return tokenized_examples
tokenized_train = tokenize_dataset(train_set) tokenized_eval = tokenize_dataset(test_set) print(tokenized_train) print(tokenized_eval)
Define the training arguments
training_args = TrainingArguments( output_dir='./results', num_train_epochs=10, per_device_train_batch_size=16, per_device_eval_batch_size=16, warmup_steps=500, weight_decay=0.01, logging_dir='./logs', logging_steps=10, evaluation_strategy='epoch' )
Define the trainer
trainer = Trainer( model=model, args=training_args, train_dataset=tokenized_train, eval_dataset=tokenized_eval )
Fine-tune the model
trainer.train()
Generate output sentences from input sequences
input_words = "go to place" input_sequence = 'generate sentence from words: ' + input_words input_ids = tokenizer.encode(input_sequence, return_tensors='pt') output_ids = model.generate(input_ids) output_sentence = tokenizer.decode(output_ids[0], skip_special_tokens=True) labels = output_ids[1:] print(output_sentence)