ValueError: too many dimensions 'str'

Traceback:

Traceback (most recent call last):
  File "c:\Users\Philip Chen\Documents\AICrowd\amazon-kdd-cup-2024-starter-kit\models\QnAModel.py", line 83, in <module>
    trainer.train()
  File "C:\Users\Philip Chen\AppData\Local\Programs\Python\Python310\lib\site-packages\transformers\trainer.py", line 1859, in train
    return inner_training_loop(
  File "C:\Users\Philip Chen\AppData\Local\Programs\Python\Python310\lib\site-packages\transformers\trainer.py", line 2165, in _inner_training_loop
    for step, inputs in enumerate(epoch_iterator):
  File "C:\Users\Philip Chen\AppData\Local\Programs\Python\Python310\lib\site-packages\accelerate\data_loader.py", line 454, in __iter__
    current_batch = next(dataloader_iter)
  File "C:\Users\Philip Chen\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\utils\data\dataloader.py", line 631, in __next__
    data = self._next_data()
  File "C:\Users\Philip Chen\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\utils\data\dataloader.py", line 675, in _next_data
    data = self._dataset_fetcher.fetch(index)  # may raise StopIteration
  File "C:\Users\Philip Chen\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\utils\data\_utils\fetch.py", line 54, in fetch
    return self.collate_fn(data)
  File "C:\Users\Philip Chen\AppData\Local\Programs\Python\Python310\lib\site-packages\transformers\data\data_collator.py", line 92, in default_data_collator
    return torch_default_data_collator(features)
  File "C:\Users\Philip Chen\AppData\Local\Programs\Python\Python310\lib\site-packages\transformers\data\data_collator.py", line 141, in torch_default_data_collator
    batch["labels"] = torch.tensor([f["label"] for f in features], dtype=dtype)
ValueError: too many dimensions 'str'

Offending line:

trainer.train()

Code:

import datasets as ds
import pandas as pd
import transformers as tf
import evaluate
import numpy as np


myData=pd.read_json("labels.json", lines=True)

inputField=myData["input_field"]
taskType=myData["task_type"]
outputField=myData["output_field"]
isMCQ=myData["is_multiple_choice"]

qArr=[]
aArr=[]

for i in range (len(myData)):
    if isMCQ[i]==False:
        if taskType[i] == "generation":
            qArr.append(inputField[i])
            aArr.append(outputField[i])

trainDF = pd.DataFrame({
     "label" : aArr,
     "text" : qArr,
})

testDF = pd.DataFrame({
    
     "label" : aArr,
     "text" : qArr,
})

trainDS = ds.Dataset.from_dict(trainDF)
testDS = ds.Dataset.from_dict(testDF)
myDataSetDict=ds.DatasetDict({"train": trainDS, "test":testDS})
print(myDataSetDict)

tokenizer = tf.AutoTokenizer.from_pretrained("google-bert/bert-base-cased")

def tokenize_function(examples):
    return tokenizer(examples["text"], padding="max_length", truncation=True)

tokenizedDatasets = myDataSetDict.map(tokenize_function, batched=True)
print(type(tokenizedDatasets))
small_train_dataset = tokenizedDatasets["train"].shuffle(seed=42).select(range(10))
small_eval_dataset = tokenizedDatasets["test"].shuffle(seed=42).select(range(10))

model = tf.AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased", num_labels=5)

metric = evaluate.load("accuracy")

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

training_args = tf.TrainingArguments(
        output_dir='./',          # output directory
        num_train_epochs=10,                     # total number of training epochs
        warmup_steps=500,                       # number of warmup steps for learning rate scheduler
        weight_decay=0.01,                      # strength of weight decay
        logging_dir='./logs',                   # directory for storing logs
        logging_steps=10,
    )


print(f"TokenizedDataset Type: {type(tokenizedDatasets)}")
trainer = tf.Trainer(
    model=model,
    args=training_args,
    train_dataset=small_train_dataset,
    eval_dataset=small_eval_dataset,
    compute_metrics=compute_metrics,
)


trainer.train()

Did I miss something?

SUggestions anyone?

Where are you getting this code from? Clearly you dont understand it based on the number of threads you’ve created on it, so I assume you’ve got a source you’re emulating. What’s the difference between their data source and yours?

I am totally new to this LLM thing, so I wrote this code for my own practice. However, I am hitting these road blocks and there’s not much help elsewhere on the internet that is helpful.

The data sources that they used is clearly from hugging face, and when I use the squad model, I have no errors when running it. However, when I tried using my data file, I get one error after another, even if it meant readjusting my code etc, so I can never get my program to train model using my json file. And there is almost little to no useful information on how to train models using a custom dataset, as most of the information is only applied to online HF datasets. If you see my recent post, I get a new error mentioned in the latest comment:

so yea, quite frustrating for me.

Here are some of the sources for this code and the latest code.

https://www.mlexpert.io/blog/alpaca-fine-tuning
https://huggingface.co/docs/transformers/training

So clearly, that tells you that the problem is that your data is not in the format that theirs is, and that is causing the problems. You should put the training code aside for a moment, and look at what it will take to reformat your data to conform to the format that the trainer is expecting.

Put some sample of labels.json data here, and I maybe able to help

Here you go:

{"text": "Who wrote Charlie and the Chocolate Factory?", "labels": "Roald Dahl"}
{"text": "Name a few ways to treat constipation naturally.", "labels": "Exercise regularly, eat more fibers, and drink more water."}
{"text": "Where is the longest roller coaster located?", "labels": "Nagashima, Japan. The name of the coaster is Steel Dragon 2000."}
{"text": "Who murdered JFK?", "labels": "It is said to be Harvey Oswald."}
{"text": "What are the 11 herbs and spices that Colonel Sanders used in KFC?", "labels": "Nobody knows, as it's a secret."}
{"text": "Who wrote Les Miserables?", "labels": "Victor Hugo"}
{"text": "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."}
{"text": "What is Obama's most famous quote?", "labels": "'Yes we can!'"}
{"text": "Where did the 2008 Olympic take place?", "labels": "Beijing"}
{"text": "Lentils and Chickpeas are what kind of food?", "labels": "Beans"}
{"text": "Who was the disciple that Jesus loved?", "labels": "John"}
{"text": "Why did the Boston Tea Party happen?", "labels": "The colonists were unhappy with the tax and restrictions imposed by the British colonists."}
{"text": "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."}
{"text": "Who conquered the Aztec Empire?", "labels": "Hernan Cortes"}
{"text": "What is the longest flight as of 2024?", "labels": "Singapore to New York, operated by Singapore Airlines."}
{"text": "Name a few infamous Roman dictators.", "labels": "Caligula, Nero, and Tiberius."}
{"text": "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."}
{"text": "Where is the fastest roller coaster located?", "labels": "Abu Dhabi, and the coaster is known as F1."}
{"text": "What are some popular painting in Uffizi Gallery?", "labels": "The Birth of Venus, Madonna of the Goldfinch, and Judith and Holofernes."}
{"text": "Who wrote A Christmas Carol and Oliver Twist?", "labels": "Charles Dickens"}

That data does not seems to correspond with the below fields or columns

Apologies. I wrote a new code with different dataset. Here goes.

# 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["text"], truncation=True, padding='max_length', max_length=512), batched=True)
sampleDS2.set_format("torch", columns=["input_ids", "attention_mask", "text"])

############## 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()

with this traceback:

Traceback (most recent call last):
  File "C:\Users\chenp\Documents\ML\machineLearning.py", line 52, in <module>
    trainer.train()
  File "C:\Users\chenp\AppData\Local\Programs\Python\Python310\lib\site-packages\transformers\trainer.py", line 1859, in train
    return inner_training_loop(
  File "C:\Users\chenp\AppData\Local\Programs\Python\Python310\lib\site-packages\transformers\trainer.py", line 2203, in _inner_training_loop
    tr_loss_step = self.training_step(model, inputs)
  File "C:\Users\chenp\AppData\Local\Programs\Python\Python310\lib\site-packages\transformers\trainer.py", line 3138, in training_step
    loss = self.compute_loss(model, inputs)
  File "C:\Users\chenp\AppData\Local\Programs\Python\Python310\lib\site-packages\transformers\trainer.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]

and JSON file:

{"text": "Who wrote Charlie and the Chocolate Factory?", "label": "Roald Dahl"}
{"text": "Name a few ways to treat constipation naturally.", "label": "Exercise regularly, eat more fibers, and drink more water."}
{"text": "Where is the longest roller coaster located?", "label": "Nagashima, Japan. The name of the coaster is Steel Dragon 2000."}
{"text": "What are the 11 herbs and spices that Colonel Sanders used in KFC?", "label": "Nobody knows, as it's a secret."}
{"text": "Who wrote Les Miserables?", "label": "Victor Hugo"}
{"text": "What is the Watergate Scandal?", "label": "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."}
{"text": "What is Obama's most famous quote?", "label": "'Yes we can!'"}
1 Like

Your data file does not correspond to the format required by the model Question answering.

The HuggingFace model for Question answering, required the data to be in a format as following:

Where there is answers, context and question.

The answers contains where to pick the start of the answer from the context and what the text should be.

For example:

{'answers': {'answer_start': [515], 'text': ['Saint Bernadette Soubirous']},
 'context': 'Architecturally, the school has a Catholic character. Atop the Main Building\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend "Venite Ad Me Omnes". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.',
 'id': '5733be284776f41900661182',
 'question': 'To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?',
 'title': 'University_of_Notre_Dame'
}
1 Like

You can use vector embedding. Is more of a search than question and answer but is similar. Most search engines if not all have change from index search to vector embedding search.

Sentence Transformers

Here is an example using your data.

Make sure to import install the model:

pip install -U sentence-transformers


from sentence_transformers import SentenceTransformer, util
import datasets as ds
import torch

fileName = "qna.json"
ds = ds.load_dataset("json", data_files=fileName, split="train")

embedder = SentenceTransformer("all-MiniLM-L6-v2")

corpus = []

for i, label in enumerate(ds['label']):
    corpus.append(ds['text'][i] + ". " + label)

print(corpus)
corpus_embeddings = embedder.encode(corpus, convert_to_tensor=True)

# Query sentences:
queries = [
    "Obama's quote",
    "Nixon Scandal",
]


# Find the closest 5 sentences of the corpus for each query sentence based on cosine similarity
# Change the value to 1 if you want to see just the closest ...
top_k = min(5, len(corpus))

for query in queries:
    query_embedding = embedder.encode(query, convert_to_tensor=True)

    # We use cosine-similarity and torch.topk to find the highest 5 scores
    cos_scores = util.cos_sim(query_embedding, corpus_embeddings)[0]
    top_results = torch.topk(cos_scores, k=top_k)

    print("\n\n======================\n\n")
    print("Query:", query)
    print("\nTop 5 most similar sentences in corpus:")

    for score, idx in zip(top_results[0], top_results[1]):
        print(corpus[idx], "(Score: {:.4f})".format(score))

2 Likes

I understood. Thank you so much :D, you really saved me here. Really appreciate it man.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.