LongT5 fine-tunning

I’m trying to fine tune the google/long-t5-tglobal-base model using a similar approach as with t5-base.
The code runs but the metric returns all zenos and loss=nan.

This is the preprocessing and training code I’m using.

Pre-processing

max_input_length = 4096
max_target_length = 200

def preprocess_function(examples):
    inputs = [doc for doc in examples["Input"]]
    model_inputs = tokenizer(inputs, max_length=max_input_length, truncation=True)

    # Setup the tokenizer for targets
    with tokenizer.as_target_tokenizer():
        labels = tokenizer(examples["Answer"], max_length=max_target_length, truncation=True)

    model_inputs["labels"] = labels["input_ids"]
    return model_inputs


def compute_metrics(eval_pred):
    predictions, labels = eval_pred
    decoded_preds = tokenizer.batch_decode(predictions, skip_special_tokens=True)
    # Replace -100 in the labels as we can't decode them.
    labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
    decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
    
    # Rouge expects a newline after each sentence
    decoded_preds = ["\n".join(nltk.sent_tokenize(pred.strip())) for pred in decoded_preds]
    decoded_labels = ["\n".join(nltk.sent_tokenize(label.strip())) for label in decoded_labels]
    
    result = metric.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True)
    # Extract a few results
    result = {key: value.mid.fmeasure * 100 for key, value in result.items()}
    
    # Add mean generated length
    prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in predictions]
    result["gen_len"] = np.mean(prediction_lens)
    
    return {k: round(v, 4) for k, v in result.items()}

Training code

from transformers import AutoTokenizer, LongT5ForConditionalGeneration

### Fine-tunning
model_name = 'long-t5'
model = LongT5ForConditionalGeneration.from_pretrained(model_checkpoint)

# Define Arguments
batch_size = 1
args = Seq2SeqTrainingArguments(
    f"{model_name}-finetuned-gen-QA",
    evaluation_strategy = "epoch",
    learning_rate=2e-5,
    per_device_train_batch_size=batch_size,
    per_device_eval_batch_size=batch_size,
    weight_decay=0.01,
    save_total_limit=3,
    num_train_epochs=3,
    predict_with_generate=True,
    fp16=True,
    push_to_hub=False,
)

# Trainer
data_collator = DataCollatorForSeq2Seq(tokenizer, model=model)

trainer = Seq2SeqTrainer(
    model, args, 
    train_dataset=tokenized_train,
    eval_dataset=tokenized_test,
    data_collator=data_collator,
    tokenizer=tokenizer,
    compute_metrics=compute_metrics
)

trainer.train()

Hi,
I just had the same error and switching fp16 to False solved it.

1 Like

See here for why it failed: Mixed precision for bfloat16-pretrained models

tldr: t5 was trained with bf16 and you fine tuned in fp16. bf16 has a much larger range than fp16 so those large values (bf16) turned into nan (fp16)

I have also resolved it in this way

I’m struggling with CUDA out-of-memory errors while fine-tuning long-t5-tglobal-base on Colab Pro. Any suggestions?

lora_config = LoraConfig(
    r = 8,
    lora_alpha = 8,
    lora_dropout = 0.1,
    target_modules=["q", "k"],
    bias="none",
    task_type="SEQ_2_SEQ_LM"
)
def formatting_prompts_func(example):
    output_texts = []
    for i in range(len(example['meeting'])):
        text = f"### Generate the summary of the following meeting: {example['meeting'][i]}\n ### Summary: {example['summary'][i]}"
        output_texts.append(text)
    return output_texts
from transformers import Seq2SeqTrainingArguments
from trl import SFTTrainer

batch_size = 1
training_args = Seq2SeqTrainingArguments(
    "./LongT5_summary_gen",
    evaluation_strategy = "epoch",
    # learning_rate=2e-5,
    learning_rate=0.001,
    per_device_train_batch_size=batch_size,
    per_device_eval_batch_size=batch_size,
    gradient_accumulation_steps=4,
    weight_decay=0.01,
    save_total_limit=3,
    num_train_epochs=3,
    predict_with_generate=True,
    fp16=False,
    bf16=True,
    push_to_hub=False,
)

trainer = SFTTrainer(
  model=model,
  args=training_args,
  train_dataset=dataset["train"],
  eval_dataset=dataset["test"],
  max_seq_length=8192, 
  formatting_func=formatting_prompts_func,
  peft_config=lora_config,
  compute_metrics=compute_metrics,
  dataset_batch_size=1,
  num_of_sequences=1, 
  packing=False,
)