# Error in fine tuning T5 model for Seq2Seq translation task

**URL:** <https://discuss.huggingface.co/t/error-in-fine-tuning-t5-model-for-seq2seq-translation-task/18184>\
**Category:** 🤗Transformers\
**Created:** [May 20, 2022, 9:06am UTC](https://discuss.huggingface.co/t/error-in-fine-tuning-t5-model-for-seq2seq-translation-task/18184 "2022-05-20T09:06:31Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![aidev](https://avatars.discourse-cdn.com/v4/letter/a/ebca7d/32.png) [@aidev](https://discuss.huggingface.co/u/aidev)\
**Post date:** [May 20, 2022, 9:06am UTC](https://discuss.huggingface.co/t/error-in-fine-tuning-t5-model-for-seq2seq-translation-task/18184/1 "2022-05-20T09:06:31Z")

</div>

compute\_metrics function throwing error at np.argmax

Hi,

I am trying to translate text from 1 semantic to another semantic language. I am using `transformers` version 4.19.2 and `datasets` version 2.2.1

The dataset(s) are .csv files with two columns: “ _src\_db\_sql_ ” and “ _tgt\_db\_sql_ ”. The following is the code that led to the error - if anyone can help identify my error, please let me know 😀

```auto
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
import datasets
from datasets import Dataset
from transformers import AutoTokenizer
from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer
from transformers import DataCollatorForSeq2Seq
from datasets import load_metric

data_path = "./../../datasets/dir_parse_data.xlsx"
conversion_df = pd.read_excel(data_path, sheet_name='Sheet1', dtype=str)
conversion_df.astype(str)
conversion_df.rename(columns={'Semantic1':'semantic1','Semantic2 Syntax':'semantic2'}, inplace=True)
conversion_df[['semantic1', 'semantic2']] = conversion_df[['semantic1', 'semantic2']].astype(str)

train_df, test_df = train_test_split(conversion_df, test_size=0.2)

train_df.head()

train_dataset = Dataset.from_dict(train_df)
test_dataset = Dataset.from_dict(test_df)
conversion_dataset_dict = datasets.DatasetDict({"train":train_dataset,"test":test_dataset})

tokenizer = AutoTokenizer.from_pretrained("t5-base")
source_sql_key = "semantic1"
target_sql_key = "semantic2"
prefix = "translate semantic1 to semantic2: "

def preprocess_function(conv_dataset):
    inputs = [prefix + conv_data for conv_data in conv_dataset[source_sql_key]]
    targets = [conv_data for conv_data in conv_dataset[target_sql_key]]
    model_inputs = tokenizer(inputs, max_length=500, truncation=True, padding=True)

    with tokenizer.as_target_tokenizer():
        labels = tokenizer(targets, max_length=500, truncation=True, padding=True)

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

tokenized_conv_data = conversion_dataset_dict.map(preprocess_function, batched=True)

model = AutoModelForSeq2SeqLM.from_pretrained("t5-base", return_dict=True)
data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=model)

metric = load_metric("accuracy")

def compute_metrics(eval_pred):
    logits, labels = eval_pred
    print("logits - ", type(logits))
    print("labels - ", type(labels))
    predictions = np.argmax(logits, axis=-1)
    print("predictions - ", predictions)
    return metric.compute(predictions=predictions, references=labels)
	

training_args = Seq2SeqTrainingArguments(
    output_dir="./results",
    evaluation_strategy="epoch",
    learning_rate=2e-5,
    per_device_train_batch_size=16,
    per_device_eval_batch_size=16,
    weight_decay=0.01,
    save_total_limit=3,
    num_train_epochs=3,
    fp16=False,
    no_cuda=True,
    report_to=None
)

trainer = Seq2SeqTrainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_conv_data["train"],
    eval_dataset=tokenized_conv_data["test"],
    tokenizer=tokenizer,
    data_collator=data_collator,
    compute_metrics=compute_metrics,
)

trainer.train()

```

Pls someone help for below issue. I get below error only after completing one epoch and at the time trainer.evaluate()

“Could not broadcast input array from shape (240, 500, 32128) into shape (240, 500)”.

Following is stack:

===========================================Stack Start===================================================================  
logits - \<class ‘tuple’\>  
labels - \<class ‘numpy.ndarray’\>

AttributeError Traceback (most recent call last)  
C:\Users\D00365~1\AppData\Local\Temp/ipykernel\_14552/4032920361.py in   
----\> 1 trainer.train()

D:\Anaconda3\lib\site-packages\transformers\trainer.py in train(self, resume\_from\_checkpoint, trial, ignore\_keys\_for\_eval, \*\*kwargs)  
1315 self.\_inner\_training\_loop, self.\_train\_batch\_size, args.auto\_find\_batch\_size  
1316 )  
 → 1317 return inner\_training\_loop(  
1318 args=args,  
1319 resume\_from\_checkpoint=resume\_from\_checkpoint,

D:\Anaconda3\lib\site-packages\transformers\trainer.py in \_inner\_training\_loop(self, batch\_size, args, resume\_from\_checkpoint, trial, ignore\_keys\_for\_eval)  
1642  
1643 self.control = self.callback\_handler.on\_epoch\_end(args, self.state, self.control)  
 → 1644 self.\_maybe\_log\_save\_evaluate(tr\_loss, model, trial, epoch, ignore\_keys\_for\_eval)  
1645  
1646 if DebugOption.TPU\_METRICS\_DEBUG in self.args.debug:

D:\Anaconda3\lib\site-packages\transformers\trainer.py in \_maybe\_log\_save\_evaluate(self, tr\_loss, model, trial, epoch, ignore\_keys\_for\_eval)  
1794 metrics = None  
1795 if self.control.should\_evaluate:  
 → 1796 metrics = self.evaluate(ignore\_keys=ignore\_keys\_for\_eval)  
1797 self.\_report\_to\_hp\_search(trial, epoch, metrics)  
1798

D:\Anaconda3\lib\site-packages\transformers\trainer\_seq2seq.py in evaluate(self, eval\_dataset, ignore\_keys, metric\_key\_prefix, max\_length, num\_beams)  
68 self.\_max\_length = max\_length if max\_length is not None else self.args.generation\_max\_length  
69 self.\_num\_beams = num\_beams if num\_beams is not None else self.args.generation\_num\_beams  
—\> 70 return super().evaluate(eval\_dataset, ignore\_keys=ignore\_keys, metric\_key\_prefix=metric\_key\_prefix)  
71  
72 def predict(

D:\Anaconda3\lib\site-packages\transformers\trainer.py in evaluate(self, eval\_dataset, ignore\_keys, metric\_key\_prefix)  
2456  
2457 eval\_loop = self.prediction\_loop if self.args.use\_legacy\_prediction\_loop else self.evaluation\_loop  
 → 2458 output = eval\_loop(  
2459 eval\_dataloader,  
2460 description=“Evaluation”,

D:\Anaconda3\lib\site-packages\transformers\trainer.py in evaluation\_loop(self, dataloader, description, prediction\_loss\_only, ignore\_keys, metric\_key\_prefix)  
2738 )  
2739 else:  
 → 2740 metrics = self.compute\_metrics(EvalPrediction(predictions=all\_preds, label\_ids=all\_labels))  
2741 else:  
2742 metrics = {}

C:\Users\D00365~1\AppData\Local\Temp/ipykernel\_14552/588117875.py in compute\_metrics(eval\_pred)  
3 print("logits - ", type(logits))  
4 print("labels - ", type(labels))  
----\> 5 predictions = np.argmax(logits, axis=-1)  
6 print("predictions - ", predictions)  
7 return metric.compute(predictions=predictions, references=labels)

ValueError: could not broadcast input array from shape (240, 500, 32128) into shape (240, 500)

==========================================Stack End================================================================================

============================================================Code========================================

Here is my “compute\_metrics” function and trainer:

=============================================================================================================

logits is coming as \<class ‘tuple’\> when I printed type of logits and labels coming as \<class ‘numpy.ndarray’\>

logits - \<class ‘tuple’\>  
labels - \<class ‘numpy.ndarray’\>

---

<div class="post-metadata">

**Author:** ![ZeroMaster28](https://avatars.discourse-cdn.com/v4/letter/z/f475e1/32.png) [@ZeroMaster28](https://discuss.huggingface.co/u/ZeroMaster28)\
**Post date:** [May 30, 2022, 2:44pm UTC](https://discuss.huggingface.co/t/error-in-fine-tuning-t5-model-for-seq2seq-translation-task/18184/2 "2022-05-30T14:44:15Z")

</div>

Hi,

Recently I’ve struggled with similar issue for the exact same implementation of compute\_metrics. I believe it’s related to [this issue](https://github.com/numpy/numpy/issues/17224) which in my case was caused by logits containing two numpy.ndarrays of different shapes.

---

<div class="post-metadata">

**Author:** ![aidev](https://avatars.discourse-cdn.com/v4/letter/a/ebca7d/32.png) [@aidev](https://discuss.huggingface.co/u/aidev)\
**Post date:** [May 31, 2022, 3:50am UTC](https://discuss.huggingface.co/t/error-in-fine-tuning-t5-model-for-seq2seq-translation-task/18184/3 "2022-05-31T03:50:44Z")

</div>

Thank you @ZeroMaster28 . I have got it corrected.

---

<div class="post-metadata">

**Author:** ![ani0075saha](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/ani0075saha/32/42866_2.png) [@ani0075saha](https://discuss.huggingface.co/u/ani0075saha)\
**Post date:** [November 25, 2023, 2:18am UTC](https://discuss.huggingface.co/t/error-in-fine-tuning-t5-model-for-seq2seq-translation-task/18184/4 "2023-11-25T02:18:40Z")

</div>

Hi @aidev,

What’s the fix for this issue?
