How do I fix “ValueError: The model did not return a loss from the inputs”?

I am writing a program in Python. What it does is to train a question-answering model, and it uses a custom-made dataset from a JSON file that I created. However, I ran into the error from the full traceback below:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Traceback (most recent call last):
File "C:UserschenpDocumentsMLmachineLearning.py", line 52, in <module>
trainer.train()
File "C:UserschenpAppDataLocalProgramsPythonPython310libsite-packagestransformerstrainer.py", line 1859, in train
return inner_training_loop(
File "C:UserschenpAppDataLocalProgramsPythonPython310libsite-packagestransformerstrainer.py", line 2203, in _inner_training_loop
tr_loss_step = self.training_step(model, inputs)
File "C:UserschenpAppDataLocalProgramsPythonPython310libsite-packagestransformerstrainer.py", line 3138, in training_step
loss = self.compute_loss(model, inputs)
File "C:UserschenpAppDataLocalProgramsPythonPython310libsite-packagestransformerstrainer.py", line 3179, in compute_loss
raise ValueError(
ValueError: The model did not return a loss from the inputs, only the following keys: start_logits,end_logits. For reference, the inputs it received are input_ids,attention_mask.
0%| | 0/9 [00:00<?, ?it/s]
</code>
<code>Traceback (most recent call last): File "C:UserschenpDocumentsMLmachineLearning.py", line 52, in <module> trainer.train() File "C:UserschenpAppDataLocalProgramsPythonPython310libsite-packagestransformerstrainer.py", line 1859, in train return inner_training_loop( File "C:UserschenpAppDataLocalProgramsPythonPython310libsite-packagestransformerstrainer.py", line 2203, in _inner_training_loop tr_loss_step = self.training_step(model, inputs) File "C:UserschenpAppDataLocalProgramsPythonPython310libsite-packagestransformerstrainer.py", line 3138, in training_step loss = self.compute_loss(model, inputs) File "C:UserschenpAppDataLocalProgramsPythonPython310libsite-packagestransformerstrainer.py", line 3179, in compute_loss raise ValueError( ValueError: The model did not return a loss from the inputs, only the following keys: start_logits,end_logits. For reference, the inputs it received are input_ids,attention_mask. 0%| | 0/9 [00:00<?, ?it/s] </code>
Traceback (most recent call last):
  File "C:UserschenpDocumentsMLmachineLearning.py", line 52, in <module>
    trainer.train()
  File "C:UserschenpAppDataLocalProgramsPythonPython310libsite-packagestransformerstrainer.py", line 1859, in train
    return inner_training_loop(
  File "C:UserschenpAppDataLocalProgramsPythonPython310libsite-packagestransformerstrainer.py", line 2203, in _inner_training_loop
    tr_loss_step = self.training_step(model, inputs)
  File "C:UserschenpAppDataLocalProgramsPythonPython310libsite-packagestransformerstrainer.py", line 3138, in training_step
    loss = self.compute_loss(model, inputs)
  File "C:UserschenpAppDataLocalProgramsPythonPython310libsite-packagestransformerstrainer.py", line 3179, in compute_loss
    raise ValueError(
ValueError: The model did not return a loss from the inputs, only the following keys: start_logits,end_logits. For reference, the inputs it received are input_ids,attention_mask.
  0%|          | 0/9 [00:00<?, ?it/s]

from the offending line:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>trainer.train()
</code>
<code>trainer.train() </code>
trainer.train()

And this is my full code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code># https://www.mlexpert.io/blog/alpaca-fine-tuning
# https://wellsr.com/python/fine-tuning-huggingface-models-in-tensorflow-keras/
# https://learnopencv.com/fine-tuning-bert/
# https://medium.com/@karary/nlp-fine-tune-question-answering-model-%E5%AF%A6%E4%BD%9C-3-model-training-%E5%84%B2%E5%AD%98%E8%88%87-inference-13d2a5bf5c32
# https://medium.com/@anyuanay/fine-tuning-the-pre-trained-bert-model-in-hugging-face-for-question-answering-8edc76890ce0
import transformers as tf
import datasets as ds
import pandas as pd
import numpy as np
import torch
import json
############## Check if CUDA is enabled. ################
hasCUDA=torch.cuda.is_available()
print(f"CUDA Enabled? {hasCUDA}")
device="cuda" if hasCUDA else "cpu"
############## Loading file and populating data ################
fileName="qna.json"
sampleDS2=ds.load_dataset("json", data_files=fileName, split="train")
############## Model ##########################################
modelName="distilbert/distilbert-base-cased" #or replace the model name with whatever you feel like.
# config=tf.AutoConfig.from_pretrained(modelName+"/config.json")
model=tf.AutoModelForQuestionAnswering.from_pretrained(modelName)
tokenizer=tf.AutoTokenizer.from_pretrained(modelName)
############## Encoding and Tokenizing #######################################
sampleDS2=sampleDS2.map(lambda batch: tokenizer(sampleDS2["question"], truncation=True, padding='max_length', max_length=512), batched=True)
sampleDS2.set_format("torch", columns=["input_ids", "attention_mask", "question"])
# sampleDS2.rename_column("answer", "labels")
print(sampleDS2)
############## Training #######################################
trnArgs=tf.TrainingArguments(
output_dir="./",
evaluation_strategy="epoch",
save_strategy="epoch",
learning_rate=2e-5,
num_train_epochs=3,
remove_unused_columns=True,
fp16=True
)
trainer=tf.Trainer(
model=model,
args=trnArgs,
train_dataset=sampleDS2,
eval_dataset=sampleDS2,
tokenizer=tokenizer
)
trainer.train()
</code>
<code># https://www.mlexpert.io/blog/alpaca-fine-tuning # https://wellsr.com/python/fine-tuning-huggingface-models-in-tensorflow-keras/ # https://learnopencv.com/fine-tuning-bert/ # https://medium.com/@karary/nlp-fine-tune-question-answering-model-%E5%AF%A6%E4%BD%9C-3-model-training-%E5%84%B2%E5%AD%98%E8%88%87-inference-13d2a5bf5c32 # https://medium.com/@anyuanay/fine-tuning-the-pre-trained-bert-model-in-hugging-face-for-question-answering-8edc76890ce0 import transformers as tf import datasets as ds import pandas as pd import numpy as np import torch import json ############## Check if CUDA is enabled. ################ hasCUDA=torch.cuda.is_available() print(f"CUDA Enabled? {hasCUDA}") device="cuda" if hasCUDA else "cpu" ############## Loading file and populating data ################ fileName="qna.json" sampleDS2=ds.load_dataset("json", data_files=fileName, split="train") ############## Model ########################################## modelName="distilbert/distilbert-base-cased" #or replace the model name with whatever you feel like. # config=tf.AutoConfig.from_pretrained(modelName+"/config.json") model=tf.AutoModelForQuestionAnswering.from_pretrained(modelName) tokenizer=tf.AutoTokenizer.from_pretrained(modelName) ############## Encoding and Tokenizing ####################################### sampleDS2=sampleDS2.map(lambda batch: tokenizer(sampleDS2["question"], truncation=True, padding='max_length', max_length=512), batched=True) sampleDS2.set_format("torch", columns=["input_ids", "attention_mask", "question"]) # sampleDS2.rename_column("answer", "labels") print(sampleDS2) ############## Training ####################################### trnArgs=tf.TrainingArguments( output_dir="./", evaluation_strategy="epoch", save_strategy="epoch", learning_rate=2e-5, num_train_epochs=3, remove_unused_columns=True, fp16=True ) trainer=tf.Trainer( model=model, args=trnArgs, train_dataset=sampleDS2, eval_dataset=sampleDS2, tokenizer=tokenizer ) trainer.train() </code>
# https://www.mlexpert.io/blog/alpaca-fine-tuning
# https://wellsr.com/python/fine-tuning-huggingface-models-in-tensorflow-keras/
# https://learnopencv.com/fine-tuning-bert/
# https://medium.com/@karary/nlp-fine-tune-question-answering-model-%E5%AF%A6%E4%BD%9C-3-model-training-%E5%84%B2%E5%AD%98%E8%88%87-inference-13d2a5bf5c32
# https://medium.com/@anyuanay/fine-tuning-the-pre-trained-bert-model-in-hugging-face-for-question-answering-8edc76890ce0
import transformers as tf
import datasets as ds
import pandas as pd
import numpy as np
import torch
import json
 
############## Check if CUDA is enabled. ################
hasCUDA=torch.cuda.is_available()
print(f"CUDA Enabled? {hasCUDA}")
device="cuda" if hasCUDA else "cpu"      
 
############## Loading file and populating data ################
fileName="qna.json"
sampleDS2=ds.load_dataset("json", data_files=fileName, split="train")


############## Model ##########################################
modelName="distilbert/distilbert-base-cased"     #or replace the model name with whatever you feel like.
# config=tf.AutoConfig.from_pretrained(modelName+"/config.json")
model=tf.AutoModelForQuestionAnswering.from_pretrained(modelName)
tokenizer=tf.AutoTokenizer.from_pretrained(modelName)

############## Encoding and Tokenizing #######################################
sampleDS2=sampleDS2.map(lambda batch: tokenizer(sampleDS2["question"], truncation=True, padding='max_length', max_length=512), batched=True)
sampleDS2.set_format("torch", columns=["input_ids", "attention_mask", "question"])
# sampleDS2.rename_column("answer", "labels")
print(sampleDS2)
############## Training #######################################
trnArgs=tf.TrainingArguments(
    output_dir="./",
    evaluation_strategy="epoch",
    save_strategy="epoch",
    learning_rate=2e-5,
    num_train_epochs=3,
    remove_unused_columns=True,
    fp16=True
)
 
trainer=tf.Trainer(
    model=model,
    args=trnArgs,
    train_dataset=sampleDS2, 
    eval_dataset=sampleDS2,
    tokenizer=tokenizer
)
trainer.train()

Here is a sample of the JSON file that I made:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{"question": "Who wrote Charlie and the Chocolate Factory?", "labels": "Roald Dahl"}
{"question": "Name a few ways to treat constipation naturally.", "labels": "Exercise regularly, eat more fibers, and drink more water."}
{"question": "Where is the longest roller coaster located?", "labels": "Nagashima, Japan. The name of the coaster is Steel Dragon 2000."}
{"question": "Who murdered JFK?", "labels": "It is said to be Harvey Oswald."}
{"question": "What are the 11 herbs and spices that Colonel Sanders used in KFC?", "labels": "Nobody knows, as it's a secret."}
{"question": "Who wrote Les Miserables?", "labels": "Victor Hugo"}
{"question": "What is the Watergate Scandal?", "labels": "The Watergate scandal was a significant political controversy in the United States during the presidency of Richard Nixon from 1972 to 1974, ultimately resulting in Nixon's resignation. It originated from attempts by the Nixon administration to conceal its involvement in the June 17, 1972, break-in at the Democratic National Committee headquarters located in the Watergate Office Building in Washington, D.C."}
{"question": "What is Obama's most famous quote?", "labels": "'Yes we can!'"}
{"question": "Where did the 2008 Olympic take place?", "labels": "Beijing"}
{"question": "Lentils and Chickpeas are what kind of food?", "labels": "Beans"}
{"question": "Who was the disciple that Jesus loved?", "labels": "John"}
{"question": "Why did the Boston Tea Party happen?", "labels": "The colonists were unhappy with the tax and restrictions imposed by the British colonists."}
{"question": "What was the effect of the Boston Tea Party?", "labels": "The British imposed a new Intolerable Act, and tensions between the colonies and the British escalated."}
{"question": "Who conquered the Aztec Empire?", "labels": "Hernan Cortes"}
{"question": "What is the longest flight as of 2024?", "labels": "Singapore to New York, operated by Singapore Airlines."}
{"question": "Name a few infamous Roman dictators.", "labels": "Caligula, Nero, and Tiberius."}
{"question": "Where did the early Hungarians come from?", "labels": "They originated from the Uralic region as nomads, and then migrated to Central Europe's Carpathian basin."}
{"question": "Where is the fastest roller coaster located?", "labels": "Abu Dhabi, and the coaster is known as F1."}
{"question": "What are some popular painting in Uffizi Gallery?", "labels": "The Birth of Venus, Madonna of the Goldfinch, and Judith and Holofernes."}
{"question": "Who wrote A Christmas Carol and Oliver Twist?", "labels": "Charles Dickens"}
</code>
<code>{"question": "Who wrote Charlie and the Chocolate Factory?", "labels": "Roald Dahl"} {"question": "Name a few ways to treat constipation naturally.", "labels": "Exercise regularly, eat more fibers, and drink more water."} {"question": "Where is the longest roller coaster located?", "labels": "Nagashima, Japan. The name of the coaster is Steel Dragon 2000."} {"question": "Who murdered JFK?", "labels": "It is said to be Harvey Oswald."} {"question": "What are the 11 herbs and spices that Colonel Sanders used in KFC?", "labels": "Nobody knows, as it's a secret."} {"question": "Who wrote Les Miserables?", "labels": "Victor Hugo"} {"question": "What is the Watergate Scandal?", "labels": "The Watergate scandal was a significant political controversy in the United States during the presidency of Richard Nixon from 1972 to 1974, ultimately resulting in Nixon's resignation. It originated from attempts by the Nixon administration to conceal its involvement in the June 17, 1972, break-in at the Democratic National Committee headquarters located in the Watergate Office Building in Washington, D.C."} {"question": "What is Obama's most famous quote?", "labels": "'Yes we can!'"} {"question": "Where did the 2008 Olympic take place?", "labels": "Beijing"} {"question": "Lentils and Chickpeas are what kind of food?", "labels": "Beans"} {"question": "Who was the disciple that Jesus loved?", "labels": "John"} {"question": "Why did the Boston Tea Party happen?", "labels": "The colonists were unhappy with the tax and restrictions imposed by the British colonists."} {"question": "What was the effect of the Boston Tea Party?", "labels": "The British imposed a new Intolerable Act, and tensions between the colonies and the British escalated."} {"question": "Who conquered the Aztec Empire?", "labels": "Hernan Cortes"} {"question": "What is the longest flight as of 2024?", "labels": "Singapore to New York, operated by Singapore Airlines."} {"question": "Name a few infamous Roman dictators.", "labels": "Caligula, Nero, and Tiberius."} {"question": "Where did the early Hungarians come from?", "labels": "They originated from the Uralic region as nomads, and then migrated to Central Europe's Carpathian basin."} {"question": "Where is the fastest roller coaster located?", "labels": "Abu Dhabi, and the coaster is known as F1."} {"question": "What are some popular painting in Uffizi Gallery?", "labels": "The Birth of Venus, Madonna of the Goldfinch, and Judith and Holofernes."} {"question": "Who wrote A Christmas Carol and Oliver Twist?", "labels": "Charles Dickens"} </code>
{"question": "Who wrote Charlie and the Chocolate Factory?", "labels": "Roald Dahl"}
{"question": "Name a few ways to treat constipation naturally.", "labels": "Exercise regularly, eat more fibers, and drink more water."}
{"question": "Where is the longest roller coaster located?", "labels": "Nagashima, Japan. The name of the coaster is Steel Dragon 2000."}
{"question": "Who murdered JFK?", "labels": "It is said to be Harvey Oswald."}
{"question": "What are the 11 herbs and spices that Colonel Sanders used in KFC?", "labels": "Nobody knows, as it's a secret."}
{"question": "Who wrote Les Miserables?", "labels": "Victor Hugo"}
{"question": "What is the Watergate Scandal?", "labels": "The Watergate scandal was a significant political controversy in the United States during the presidency of Richard Nixon from 1972 to 1974, ultimately resulting in Nixon's resignation. It originated from attempts by the Nixon administration to conceal its involvement in the June 17, 1972, break-in at the Democratic National Committee headquarters located in the Watergate Office Building in Washington, D.C."}
{"question": "What is Obama's most famous quote?", "labels": "'Yes we can!'"}
{"question": "Where did the 2008 Olympic take place?", "labels": "Beijing"}
{"question": "Lentils and Chickpeas are what kind of food?", "labels": "Beans"}
{"question": "Who was the disciple that Jesus loved?", "labels": "John"}
{"question": "Why did the Boston Tea Party happen?", "labels": "The colonists were unhappy with the tax and restrictions imposed by the British colonists."}
{"question": "What was the effect of the Boston Tea Party?", "labels": "The British imposed a new Intolerable Act, and tensions between the colonies and the British escalated."}
{"question": "Who conquered the Aztec Empire?", "labels": "Hernan Cortes"}
{"question": "What is the longest flight as of 2024?", "labels": "Singapore to New York, operated by Singapore Airlines."}
{"question": "Name a few infamous Roman dictators.", "labels": "Caligula, Nero, and Tiberius."}
{"question": "Where did the early Hungarians come from?", "labels": "They originated from the Uralic region as nomads, and then migrated to Central Europe's Carpathian basin."}
{"question": "Where is the fastest roller coaster located?", "labels": "Abu Dhabi, and the coaster is known as F1."}
{"question": "What are some popular painting in Uffizi Gallery?", "labels": "The Birth of Venus, Madonna of the Goldfinch, and Judith and Holofernes."}
{"question": "Who wrote A Christmas Carol and Oliver Twist?", "labels": "Charles Dickens"}

Any suggestions for this fix is welcome.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật