write code for multi task training using T5. input are query and title. output are rationle(why is the pair relevant or not) and the label. for prefix [label] appended to input, output the label. for prefix [rationle] output the rationle.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Sure! Here's an example code using the Hugging Face Transformers library in Python to create a multi-task training pipeline for T5 model that takes query and title as input and outputs rationale (relevance explanation) and label.
python
import torch
from transformers import T5Tokenizer, T5ForConditionalGeneration, T5Config
# Define the prefixes for label and rationale
LABEL_PREFIX = "[label]"
RATIONALE_PREFIX = "[rationale]"
# Load the T5 model and tokenizer
model_name = 't5-base'
model = T5ForConditionalGeneration.from_pretrained(model_name)
tokenizer = T5Tokenizer.from_pretrained(model_name)
# Set the model to train mode
model.train()
# Define the training data examples
training_data = [
{
'query': "What is the capital of France?",
'title': "Paris",
'rationale': "The capital of France is Paris.",
'label': "relevant"
},
{
'query': "Who won the FIFA World Cup in 2018?",
'title': "France",
'rationale': "France won the FIFA World Cup in 2018.",
'label': "relevant"
},
{
'query': "What is the square root of 16?",
'title': "Mathematics",
'rationale': "The square root of 16 is 4.",
'label': "not relevant"
},
]
# Define the training loop
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-5)
for epoch in range(5):
total_loss = 0
for example in training_data:
query = example['query']
title = example['title']
rationale = example['rationale']
label = example['label']
# Prepare the input tensors
input_text = f"{LABEL_PREFIX} {query} {title}"
input_ids = tokenizer.encode(input_text, return_tensors='pt')
input_ids = input_ids.to(model.device)
# Prepare the target tensors
target_rationale = f"{RATIONALE_PREFIX} {rationale}"
target_label = f"{LABEL_PREFIX} {label}"
target_ids = tokenizer.encode(target_rationale, target_label, return_tensors='pt')
target_ids = target_ids.to(model.device)
# Forward pass and calculate loss
outputs = model(input_ids=input_ids, labels=target_ids)
loss = outputs.loss
#