Running Inference on custom dataset
Model I am using (LayoutLM ):
Fine tuning on Custom annotated data
Steps followed-
Dataset :- we took three images from FUNSD and annotated them using Microsoft Azure tool. After annotation of the three images we got two JSON files for each image, where one of the JSON annotation files contains the information of OCR and the another JSON annotation file contains the information of the labels. We created 8 copies of each image which is further used for pre-processing and model training.
Pre-processing As we saw there was a pre-processing script for FUNSD dataset, so for our Microsoft JSON annotations we need to get our own pre-processing script to get the required txt files for training.
Approach :- we took the same script of the FUNDS pre-processing and made few changes in the code which are required for our custom annotation considering the two JSON files of Microsoft azure namely ocr.JSON and labels.JSON and converted it to one JSON file passing this to pre-proecessing.py which resulted to .txt files which we use for training.This approach generated the required txt and label files used in training.
Fine tuning the model We have fine tuned the pre-trained model on the custom dataset with 2 epochs just to verify whether the training is happening in a proper way and we have saved the trained model for inference. Training has been done successfully.
Inference from the model Now we used the saved model to perform inference on the testing data of FUNDS.
Roadblock - While we are running the inference part of the code for our custom data we got the Following error :-
**IndexError: index out of range in self**
model.to(args.device)
194 result, predictions = evaluate(
--> 195 args, model, tokenizer, labels, pad_token_label_id, mode="test"
196 )
print("\n\n",inputs.keys())
333 print(inputs)
--> 334 outputs = model(**inputs)
335 tmp_eval_loss, logits = outputs[:2]
embedding_output = self.embeddings(
--> 177 input_ids, bbox, position_ids=position_ids, token_type_ids=token_type_ids
178 )
179 encoder_outputs = self.encoder(
The index out of range is occurring over here
w_position_embeddings = self.w_position_embeddings(
---> 88 bbox[:, :, 2] - bbox[:, :, 0]
89 )
We performed a few debugging steps by printing the view size and values of input of the model. The debugging output is given below.
bbox[:,:,2] shape :- torch.Size([8, 512])
bbox[:, :, 0] shape :- torch.Size([8, 512])
printing the w_position_embeddings:- Embedding(1024, 768)
Kindly help me with the same Best Regards Mohit Tuli
Can you provide the commands for do_train and do_predict? For do_predict I had to still point to the same folders as for do_train:
--model_name_or_path path/to/pretrained/model/directory --output_dir path/to/output/directory
while your fine tuned model is in the output_dir
We have changed the code and broken it down cell by cell, by changing it from command line arguments structure to a class structure using main and args for running it
Here sequence_labelling_data is my class and rest are the command line arguments
command for -do_train :
args=sequence_labelling_data_input(data_dir='custom_data',model_type = "layoutlm",model_name_or_path = "bert-base-uncased",do_lower_case = True,max_seq_length = 512,do_train = True,num_train_epochs = 2,overwrite_output_dir = True,logging_steps = 1,save_steps = -1,output_dir = 'output_dir3',labels = '/content/gdrive/My Drive/unilm (1)/layoutlm/examples/seq_labeling/data/labels.txt' ,per_gpu_train_batch_size = 1,per_gpu_eval_batch_size = 1)
command for -do_predict::
args = sequence_labelling_data_input(data_dir = "custom_data",model_type = "layoutlm",output_dir = "output_dir3",model_name_or_path = 'bert-base-uncased',do_lower_case = True,max_seq_length = 512,do_predict = True,labels = "data/labels.txt",fp16 = True)
for running the code we are using -
if __name__ == "__main__":
main(args)
Your model type is layoutlm but your pointing at bert-base-uncased: model_type = "layoutlm", model_name_or_path = "bert-base-uncased"
I'm no expert and haven't looked at the code enough but I got it running with downloading the layoutlm pre-trained model from the readme here on github and point to that directory in model_name_or_path. Hope it helps
@r000bin can you help me understand something, the OP says : " fter annotation of the three images we got two JSON files for each image, where one of the JSON annotation files contains the information of OCR and the another JSON annotation file contains the information of the labels. We created 8 copies of each image which is further used for pre-processing and model training." What I don't understand is, how from the OCR of an image using Azure or any other form of OCR, the label (question, answer) in a Jason annotation file? When running the test example posed by the repo as well, three files are generated, text.txt, test_image, and text_box. Inside text.txt, the annotations of Q,A,O, are provided. I had assumed from the paper that this is what we are trying to infer, so why is it provided in the text.txt file? if for evaluation purposes at test side, how can we over-ride it at --do_predict?
From the OCR extraction you just took the text and the bounding box per word. After that you can do the annotation in any tool for image annotation which mostly generate jsons. From the OCR output and the annotation output you then generate the 3 txt files.
I haven't done any prediction on an unlabeled sample so far.
This is an interesting discussion. I am looking to finetune layoutLM (multilingual if possible) on custom document images to perform sequence labelling (or Named Entity Recognition). I have no direct clue how to get started with this though. I would need some more concise explanations on how to "annotate" the data (all occurrences of just 1?), in what format I should create the training data, and how to run both training and predictions. Any help on the matter is appreciated. In any case, I am willing to look into it jointly to make sure others are helped as well.
@r000bin I understand exactly what you're saying, however the steps you've mentiond includes evaluation - meaning if I were to put the files in the folder and create them for my custom data set, without labels, they would fail. Not because the model lacks the ability to predict without eval, purely because the code is setup to eval and predict in sequence...
@MohitTuli have you been able to run prediction for an input test.txt without evaluation happening? I am trying to run a do_predict without labeling the test set, but the eval throws up errors, although I dont call for eval
This is an interesting discussion. I am looking to finetune layoutLM (multilingual if possible) on custom document images to perform sequence labelling (or Named Entity Recognition). I have no direct clue how to get started with this though. I would need some more concise explanations on how to "annotate" the data (all occurrences of just 1?), in what format I should create the training data, and how to run both training and predictions. Any help on the matter is appreciated. In any case, I am willing to look into it jointly to make sure others are helped as well.
Did u find any resources? I'm looking for the same