<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shiva Rama on Medium]]></title>
        <description><![CDATA[Stories by Shiva Rama on Medium]]></description>
        <link>https://medium.com/@shivarama?source=rss-7f0dfb436607------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NFLyE31pjFT9Ml4X.jpg</url>
            <title>Stories by Shiva Rama on Medium</title>
            <link>https://medium.com/@shivarama?source=rss-7f0dfb436607------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:20:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shivarama/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[LayoutLMv3: from zero to hero — Part 3]]></title>
            <link>https://medium.com/@shivarama/layoutlmv3-from-zero-to-hero-part-3-16ae58291e9d?source=rss-7f0dfb436607------2</link>
            <guid isPermaLink="false">https://medium.com/p/16ae58291e9d</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[document-ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shiva Rama]]></dc:creator>
            <pubDate>Sun, 10 Sep 2023 20:47:50 GMT</pubDate>
            <atom:updated>2023-09-10T20:54:25.804Z</atom:updated>
            <content:encoded><![CDATA[<h3>LayoutLMv3: from zero to hero — Part 3</h3><p>This part is a continuation to the <a href="https://medium.com/@shivarama/layoutlmv3-from-zero-to-hero-part-2-d2659eaa7dee">last article</a> where we discussed how to create the custom dataset for finetuning a LayoutLMv3 model.</p><p>Here we’ll go through the fine-tuning of the model. That’s it.</p><h3>Fine-tuning</h3><p>Fine tuning the model would need access to a good GPU resource, and Google Colab is a good place to start with.</p><p>You can also access the notebook from the <a href="https://github.com/shivarama23/LayoutLMV3/blob/main/finetune_layoutlmv3.ipynb">repo</a>.</p><p>If you have followed the last article, you’d have already created a folder structure which includes layoutlmv3.py script and a layoutlmv3 folder. The folder contains the images and the train.txt, test.txt and the class_list.txt files.</p><p>The first step to start the training process is to load all of this to colab or wherever you plan to train the model.</p><p>In your current working directory, put the training python notebook from above.</p><p>If you wish to use the files that I used for this blog/demo, they are available in the repo too.</p><h4>Install Libraries</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ca3a369aeee1fb3cef2a385f9348069/href">https://medium.com/media/6ca3a369aeee1fb3cef2a385f9348069/href</a></iframe><p><strong>Load Dataset</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61c69a7bf304dec20e9bec545b134c68/href">https://medium.com/media/61c69a7bf304dec20e9bec545b134c68/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cc334601707e5dfcdacd8e7e7e7fb88/href">https://medium.com/media/1cc334601707e5dfcdacd8e7e7e7fb88/href</a></iframe><pre>DatasetDict({<br>    train: Dataset({<br>        features: [&#39;id&#39;, &#39;tokens&#39;, &#39;bboxes&#39;, &#39;ner_tags&#39;, &#39;image_path&#39;, &#39;image&#39;],<br>        num_rows: 10<br>    })<br>    test: Dataset({<br>        features: [&#39;id&#39;, &#39;tokens&#39;, &#39;bboxes&#39;, &#39;ner_tags&#39;, &#39;image_path&#39;, &#39;image&#39;],<br>        num_rows: 2<br>    })<br>})</pre><p><strong>Check an example datapoint</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b9df6193c9a1916d9f1f0c143ab90bc/href">https://medium.com/media/6b9df6193c9a1916d9f1f0c143ab90bc/href</a></iframe><p><strong>Load Tokenizer</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eeb676527a798a13a9e71b70e238b38e/href">https://medium.com/media/eeb676527a798a13a9e71b70e238b38e/href</a></iframe><p><strong>Some helper functions</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42559699ccdbe49b699554f31c7abf51/href">https://medium.com/media/42559699ccdbe49b699554f31c7abf51/href</a></iframe><p><strong>Tokenize train and test dataset</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29d32588ff39fb219c8f3935ab4f5c0c/href">https://medium.com/media/29d32588ff39fb219c8f3935ab4f5c0c/href</a></iframe><p><strong>Load seqeval metric</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c7474edcd1667ff2942dd652a831f60/href">https://medium.com/media/5c7474edcd1667ff2942dd652a831f60/href</a></iframe><p><strong>Load Model</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/482f0a5796ece42ba032b0fd27b8a149/href">https://medium.com/media/482f0a5796ece42ba032b0fd27b8a149/href</a></iframe><p><strong>Define training arguments</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/571f39ed2fdac5cde18a741e60d4ac49/href">https://medium.com/media/571f39ed2fdac5cde18a741e60d4ac49/href</a></iframe><p><strong>Define “Trainer”</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3161ca683dad7f84aaf36b1edc7e920d/href">https://medium.com/media/3161ca683dad7f84aaf36b1edc7e920d/href</a></iframe><p><strong>Start Training</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f65775f4ece0f50cd0ff5c951ce538d/href">https://medium.com/media/4f65775f4ece0f50cd0ff5c951ce538d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNAIa2iHqWye3gIDRu1tOw.png" /></figure><p><strong>Evaluate</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c9459e3f24645851974087c63aa3690/href">https://medium.com/media/9c9459e3f24645851974087c63aa3690/href</a></iframe><pre>{&#39;eval_loss&#39;: 0.45275625586509705,<br> &#39;eval_precision&#39;: 0.4,<br> &#39;eval_recall&#39;: 0.3333333333333333,<br> &#39;eval_f1&#39;: 0.3636363636363636,<br> &#39;eval_accuracy&#39;: 0.75,<br> &#39;eval_runtime&#39;: 0.3588,<br> &#39;eval_samples_per_second&#39;: 5.574,<br> &#39;eval_steps_per_second&#39;: 2.787,<br> &#39;epoch&#39;: 200.0}</pre><p>Post this you can download the checkpoint that gets generated in the folder.</p><p>Post this we can go through some of the inference steps involving loading of the model and running through the pipeline.</p><h3>Inferencing</h3><p><strong>Loading the model</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d91651be5411de881e8456281c7249d/href">https://medium.com/media/5d91651be5411de881e8456281c7249d/href</a></iframe><p><strong>Loading a test image</strong></p><p>Since we set the “apply_ocr=False” in the beginning while training the model, we need to give the OCR output for the text tokens to the model along with the image for inference. For that you need to run the same functions that you ran for a list of images to create dataset, but this time only on a single image, and then pass to the model. Since we already have some images in the test dataset, we’ll directly load that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bac70264f5ae70bf426e35144f8a9953/href">https://medium.com/media/bac70264f5ae70bf426e35144f8a9953/href</a></iframe><p><strong>Run model</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d660fe9cc23bc872eab4bda058bb786/href">https://medium.com/media/9d660fe9cc23bc872eab4bda058bb786/href</a></iframe><p><strong>Show Output</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7d868c2cc25fb177871ada09ce1f16c/href">https://medium.com/media/f7d868c2cc25fb177871ada09ce1f16c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*WFB-j7yMel3Yk9Zm-ZNdog.png" /></figure><p>Of course there are mistakes in the output because for demonstration purposes I took only 4–5 images and replicated the same in the train and the test dataset. A larger dataset will show better performance on the entities that you want to train on.</p><p>This concludes the 3 part series where I try to explain the model, dataset creation and the training procedure for the model that we call LayoutLMv3.</p><p>Link to <a href="https://medium.com/@shivarama/layoutlmv3-from-zero-to-hero-part-1-85d05818eec4">part-1</a> and <a href="https://medium.com/@shivarama/layoutlmv3-from-zero-to-hero-part-2-d2659eaa7dee">part-2</a></p><h3>Cheers!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16ae58291e9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LayoutLMv3: from zero to hero — Part 2]]></title>
            <link>https://medium.com/@shivarama/layoutlmv3-from-zero-to-hero-part-2-d2659eaa7dee?source=rss-7f0dfb436607------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2659eaa7dee</guid>
            <category><![CDATA[document-ai]]></category>
            <category><![CDATA[label-studio]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Shiva Rama]]></dc:creator>
            <pubDate>Sun, 10 Sep 2023 20:46:13 GMT</pubDate>
            <atom:updated>2023-10-12T19:56:49.188Z</atom:updated>
            <content:encoded><![CDATA[<h3>LayoutLMv3: from zero to hero — Part 2</h3><h3>Create custom dataset to train LayoutLMV3 model</h3><p>Extracting entities from documents, especially scanned documents like invoices, lab reports, legal documents etc., that too manually, can be a daunting task. But automating the task by using some state-of-the-art AI is not a cake walk either.</p><p>If you are reading this, you already know that creating a dataset, a proper train-test-validation dataset with proper annotations is a painstaking and a time consuming process. Even though data labelling tools like LabelStudio, Rubrix, Prodigy(and many others) have solved the problem of data labelling to a great extent, but they are still limited to text/image classification, NER, Object Detection problems, and there is no tool except UBIAI (<a href="https://ubiai.tools/">https://ubiai.tools/</a>) which provides an out of the box solution for annotating your scanned documents for consumption in a LayoutLMV2 or LayoutLMV3 models.</p><p>Our challenge primarily with UBIAI was that it’s a paid tool and we didn’t have the option to upload our data to their cloud to even try annotating some examples. So we thought of creating our own custom dataset by doing some <a href="https://en.wikipedia.org/wiki/Jugaad"><em>jugaad</em></a><em>.</em></p><p>Please continue to read and see how you can solve this problem, if you have one.</p><p><strong><em>Note</em></strong><em>: This process of creating training data is not intended for large datasets of the size of 1000–10000 documents. Rather, for someone who wants to do some quick prototyping and PoC to validate the effectiveness of this model for their application, this is a very easy and effective way. For larger dataset, creating gold-standard dataset can be done using the annotate OCR option of label-studio.</em></p><h3><strong>Step 1: Get all the required pre-requisites</strong></h3><p>Please follow the steps below to create a brand new python environment and install the required packages for doing the exercise.</p><p><strong>NOTE:</strong> The primary assumption is that you have <a href="https://docs.anaconda.com/anaconda/install/windows/">Anaconda </a>or <a href="https://docs.conda.io/en/latest/miniconda.html">Miniconda </a>already installed on your system. If not please follow the links. All the codes here are tested on Windows and Linux environments, except labelling, which was done on a Windows environment.</p><p>Create a python-3.9 environment in anaconda using the command below.</p><pre>conda create -n layoutlmv3 python=3.9</pre><p>Install the required <a href="https://github.com/shivarama23/LayoutLMV3/blob/main/requirements.txt">python packages</a> for labelling your data and extracting text as follows.</p><pre>pip install -r requirements.txt</pre><p>Once the above python packages are installed, install Tesseract, which is the OCR tool that we would be using for extracting text from scanned images of documents. Please follow <a href="https://tesseract-ocr.github.io/tessdoc/Installation.html">this</a> link to install tesseract.</p><p>Before you start labelling and creating dataset, verify that all the packages and tesseract are installed properly.</p><h3>Step 2: Start labelling using label-studio (Real hard-work)</h3><ul><li><strong>Convert your data into images</strong></li></ul><p>The first task while creating the data annotation set is to have your documents in an image format. So, if you have a native/scanned pdf, I would suggest first converting them into images using the resource below.</p><p><a href="https://www.geeksforgeeks.org/convert-pdf-to-image-using-python/">Convert PDF to Image using Python - GeeksforGeeks</a></p><ul><li><strong>Start LabelStudio</strong></li></ul><p>Open LabelStudio using the below command in the python environment you just created.</p><pre>label-studio</pre><p>This will open the LabelStudio labelling dashboard as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xv-6sfIFzMrQ5KunTm0LmA.png" /><figcaption>LabelStudio Dashboard</figcaption></figure><ul><li><strong>Finalize Entities to be extracted</strong></li></ul><p>Before we start labelling, we have to decide the entities that we plan to tag in our dataset, and for demonstration purposes let’s assume for this tutorial we’ll tag the <strong>Invoice Number, Date, Amount</strong> in the invoice documents with the tags <strong>invoice_no, date, amount</strong> respectively. I am going to use a very small sample from <a href="https://adamharley.com/rvl-cdip/">RVL-CDIP</a> dataset for this tutorial.</p><ul><li><strong>Start labelling &amp; Export data into a JSON</strong></li></ul><p>Follow this YouTube video to start labelling and export your data into a json format.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKLUeT0pNhVE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKLUeT0pNhVE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKLUeT0pNhVE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d38ad7aae927ea25211ef7843b3936bb/href">https://medium.com/media/d38ad7aae927ea25211ef7843b3936bb/href</a></iframe><p><em>After this step, label-studio has a weird behavior where it appends a unique string for every image uploaded to the tool. To avoid any file name error in the next steps, go to the below path and copy all the uploaded images with changed filename to your current directory inside a folder called “layoutlmv3” or any folder name that you wish. </em><strong><em>Do this only if you see mismatch in original file name vs. the file name in the output annotated json.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XTo2vxlkXZC5vhbLFelfw.png" /></figure><ul><li><strong>Create text+bounding-box dataset</strong></li></ul><p>Now we’ll create the required annotation files for training, using tesseract HOCR and the annotation JSON created in last step.</p><h3><strong>Step 3: Use tesseract and label-studio labels to create training files</strong></h3><p><strong>Import packages</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51abc07c8729266c42e94505b7392b3f/href">https://medium.com/media/51abc07c8729266c42e94505b7392b3f/href</a></iframe><p><strong>Parsing LabelStudio output into DataFrame</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b07b607e2abd33edb2e136b46b55d0a4/href">https://medium.com/media/b07b607e2abd33edb2e136b46b55d0a4/href</a></iframe><p><strong>Define custom functions</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99d3be2b7a21a8003882ccb06d244cc1/href">https://medium.com/media/99d3be2b7a21a8003882ccb06d244cc1/href</a></iframe><p><strong>Loop over LabelStudio JSON to create DataFrame</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/927a7bc3863d7641a5b41047cc3e426c/href">https://medium.com/media/927a7bc3863d7641a5b41047cc3e426c/href</a></iframe><p>After this step check the “custom_dataset” dataframe once to see if the DataFrame is formed correctly.</p><p><strong>Define label2id and id2label</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/949b51c4b8de0bef7a4de4c9bce3b1b8/href">https://medium.com/media/949b51c4b8de0bef7a4de4c9bce3b1b8/href</a></iframe><p><strong>Extract text from images using Tesseract HOCR</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa71fbe262d5244cc7fc8507f452e931/href">https://medium.com/media/aa71fbe262d5244cc7fc8507f452e931/href</a></iframe><p><strong>Split data and write final data to train and test files</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/480465ec27c66e41197429eef15804f5/href">https://medium.com/media/480465ec27c66e41197429eef15804f5/href</a></iframe><p>The train.txt file should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQemYy3__1uKWDvWA_EECQ.png" /></figure><p>NOTE: To save some time, I annotated just 4 images and copy-pasted the same as multiple images for representation.</p><p>Another file that is required is “<strong><em>class_list.txt</em></strong>” file that contains the list of all the labels in a comma separated format. The file would look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/543d6ff2488bb567e18a44a6b6cc4e79/href">https://medium.com/media/543d6ff2488bb567e18a44a6b6cc4e79/href</a></iframe><p><strong>Create proper folder structure for running the next steps</strong></p><p>In the next steps we’ll create the proper folder structure for our code, which can be replicated on google colab and we’ll train the model on a colab notebook.</p><ul><li>Create a folder called “layoutlmv3” in your current working directory</li><li>Copy all the image files as mentioned, created after labelling to the above folder.</li><li>Copy the train.txt, test.txt to the above folder.</li><li>Copy the class_list.txt file created above to the same layoutlmv3 folder.</li></ul><p>The folder should look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lViAnUrGiD6l4s8tkgUugg.png" /><figcaption>layoutlmv3 folder</figcaption></figure><h3>Step 4: <strong>Create dataset loading script(second most important step after labelling):</strong></h3><p>The custom data annotated until now needs to be loaded in a huggingface dataset format so that it is ingestible for the downstream task of fine-tuning LayoutLMv3 model. To do this, I have edited a data loading script with inspiration from <a href="https://huggingface.co/datasets/nielsr/funsd-layoutlmv3/tree/main">here</a>. If you have followed all the steps until now as discussed, you shouldn’t need to edit anything in this file. Just download/copy it and use it in the current working directory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66f1455d457b8867f014cf15e83a0911/href">https://medium.com/media/66f1455d457b8867f014cf15e83a0911/href</a></iframe><p>After doing this the working directory would look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*QvltWhNqe_ZbUsIuXLOa4A.png" /><figcaption>current working directory</figcaption></figure><h3>Step 5: Load dataset as a transformers datasets object:</h3><p>The next step involves loading the annotated data as a transformers <a href="https://huggingface.co/docs/datasets/index">datasets</a> object, which can further be used to fine-tune the model.</p><p>Create a new ipynb notebook called “invoice_dataset_loading.ipynb”. Or you could take it from the <a href="https://github.com/shivarama23/LayoutLMV3/blob/main/invoice_dataset_loading.ipynb">git repo</a>. Open the notebook and follow the steps below:</p><p><strong>Install the required libraries</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d491eed983d999c0fbfd0bd13bba506/href">https://medium.com/media/8d491eed983d999c0fbfd0bd13bba506/href</a></iframe><p><strong>Load Dataset</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfe8434c7c5fbd955a35ccc10f1ea19d/href">https://medium.com/media/dfe8434c7c5fbd955a35ccc10f1ea19d/href</a></iframe><p><strong>Inspect loaded dataset</strong></p><p>The loaded dataset should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-v15jtbmZ-KiYTtbJfG0w.png" /></figure><p><strong>Inspect one of the annotated images</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8988329fef01de7c108372a3b490c204/href">https://medium.com/media/8988329fef01de7c108372a3b490c204/href</a></iframe><p>If there is no error until now, this is what you should see as the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*33xBdfydmRhpWFkZ69xc3g.png" /></figure><h3>Step 6: Conclusion(part-2):</h3><p>This concludes the dataset creation part of the tutorial series. This part of the process is probably the toughest and the most time consuming part of the whole pipeline.</p><p>Once the dataset is created, training and hyperparameter tuning is more of an iterative process. This tutorial in no means explains how to improve the model performance, it is just a guide to setup and train a custom model.</p><p>Checkout <a href="https://medium.com/@shivarama/layoutlmv3-from-zero-to-hero-part-1-85d05818eec4">part-1</a> to know architecture of the model. <br>Checkout <a href="https://medium.com/@shivarama/layoutlmv3-from-zero-to-hero-part-3-16ae58291e9d">part-3</a> to continue and train/fine-tune the LayoutLMV3 model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2659eaa7dee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LayoutLMv3: from zero to hero — Part 1]]></title>
            <link>https://medium.com/@shivarama/layoutlmv3-from-zero-to-hero-part-1-85d05818eec4?source=rss-7f0dfb436607------2</link>
            <guid isPermaLink="false">https://medium.com/p/85d05818eec4</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[document-ai]]></category>
            <category><![CDATA[layoutlm]]></category>
            <category><![CDATA[key-value-pair]]></category>
            <category><![CDATA[hugging-face]]></category>
            <dc:creator><![CDATA[Shiva Rama]]></dc:creator>
            <pubDate>Sun, 10 Sep 2023 20:44:25 GMT</pubDate>
            <atom:updated>2024-01-03T03:18:29.119Z</atom:updated>
            <content:encoded><![CDATA[<h3>LayoutLMv3: from zero to hero — Part 1</h3><p>This article is for anyone who wants a basic understanding of what LayoutLMv3 model is and where and how you can use it in your project.</p><p>This article is followed by 2 articles on how to create custom data for training a LayoutLMv3 model, train a custom model and then inference on test data. So, without much ado let’s get started.</p><p>The whole space of working with documents for different tasks like classification, key-value pair extraction, information retrieval, QnA is broadly termed as <a href="https://github.com/philschmid/document-ai-transformers">DocumentAI</a>. To read more about the evolution of the whole DocumentAI space, <a href="https://github.com/philschmid/document-ai-transformers"><em>this</em></a> is a good blog from HuggingFace.</p><p>Considering just the LayoutLM family, there have been 2 versions of LayoutLMs before the LayoutLMv3(obviously!). Each model improves upon the other either from a model architecture point of view or from the pre-training strategy etc. Let’s go through this in a little more detail, but before that let me list down the original papers for all the 3 models.</p><p><strong>LayoutLM</strong>: <a href="https://arxiv.org/abs/1912.13318">https://arxiv.org/abs/1912.13318</a></p><p><strong>LayoutLMv2</strong>: <a href="https://arxiv.org/abs/2012.14740">https://arxiv.org/abs/2012.14740</a></p><p><strong>LayoutLMv3</strong>: <a href="https://arxiv.org/abs/2204.08387">https://arxiv.org/abs/2204.08387</a></p><p>Understanding BERT: <a href="http://jalammar.github.io/illustrated-bert/">http://jalammar.github.io/illustrated-bert/</a> (read this even if you aren’t interested in LayoutLM, this is gold.)</p><p>For anyone who is interested in the journey of the model, the above links should be a good starting point.</p><h3><strong>What is LayoutLM anyway?</strong></h3><p>The LayoutLM model is a pre-trained language model that jointly models text and layout information for document image understanding tasks.</p><p>Some of the salient features of the LayoutLM model as referred by the author(s) are:</p><ul><li>For the first time, textual and layout information from scanned document images is pre-trained in a single framework. Image features are also leveraged to achieve new state-of-the-art results.(<a href="https://arxiv.org/pdf/1912.13318.pdf">ref</a>)</li><li>LayoutLM uses the masked visual-language model and the multi-label document classification as the training objectives, which significantly outperforms several SOTA pre-trained models in document image understanding tasks.(<a href="https://arxiv.org/pdf/1912.13318.pdf">ref</a>)</li></ul><p>For beginners, the BERT model takes in words(<em>called tokens</em>) as inputs, converts them into meaningful numbers(called embeddings) and then processes them over multiple layers of neural networks with attention mechanism and back-propagation. This updates the weights of the model, which after multiple iterations of training, are good enough for inference on new(unseen) data.</p><p>In LayoutLM, the authors added information about the position(x-y coordinates) of the words as positional embeddings(along with the meaningful word embeddings above). On top of coordinates as positional embeddings, image features of the words are fed to the model as well, which is expected to embed different visual features of the text like <strong>boldness</strong>, <em>italics</em> to name a few. These image features are extracted by using a Faster-RCNN model. One thing to note here is that the pre-training task doesn’t get to see the features of the image from Faster RCNN, only while fine-tuning we give the image features from Faster R-CNN final layer to the model, we’ll see later why that is a problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewLVzFrWjRAUjlpTkmtP3w.png" /><figcaption>Architecture of LayoutLM(<a href="https://arxiv.org/pdf/1912.13318.pdf">ref</a>)</figcaption></figure><p>So, this was a breakthrough where the model performed better than the earlier benchmarks and provided a way to work with both textual and image features at the same time.</p><h3>Now what is LayoutLMv2 then?</h3><p>One disadvantage of the LayoutLM model is that the domain knowledge of one document type cannot be easily transferred into another, so these models often need to be re-trained once the document type is changed. This is primarily because it uses the BERT output embeddings and the FasterRCNN image features are added at the end i.e. the pre-training task of transformer model(BERT) doesn’t really get to see the image features which can be a problem for generalization on new formats of documents.</p><p>To overcome this, author(s) of LayoutLMv2 came up with a multi-modal approach, which embeds both the text and image and layout features together in the pre-training task itself, and hence while pre-training the transformer, model learns the features of text and the image along with the layout of the document. The visual embeddings in LayoutLMV2 are extracted using ResNeXt-FPN, and during pre-training the weights of the model are updated with back-propagation. For the layout embedding, along with the x-y coordinates, the width and the height of the segments of image are also fed to the model. The input documents are also partially masked like text tokens, in fact the word tokens of document which are replaced with [MASK] token, the same part of the document corresponding to the masked word token is redacted(blacked out) in the document image. All these are simplified for easier understanding here, there are mathematical models of how all these embeddings are created and fed to the model for pre-training and fine-tuning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*dkaW7oS9sA6d-_aiR1KzRA.png" /><figcaption>LayoutLMv2 model architecture(<a href="https://arxiv.org/pdf/2012.14740.pdf">ref</a>)</figcaption></figure><h3>Finally LayoutLMv3!!</h3><p>Let’s start with the salient features as described by the author(s).</p><ul><li>LayoutLMv3 is the first multimodal model in Document AI that<strong> does not</strong> rely on a pre-trained CNN or Faster R-CNN backbone to extract visual features, which significantly saves parameters and eliminates region annotations.</li><li>LayoutLMv3 mitigates the discrepancy between text and image multimodal representation learning with unified discrete token reconstructive objectives MLM and MIM. A Word-Patch Alignment (WPA) objective is proposed to facilitate cross-modal alignment learning.</li><li>LayoutLMv3 is a general-purpose model for both text-centric and image-centric Document AI tasks.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*fxKLPYNFE7Nn_VwQMi3urA.png" /><figcaption>Pre-training Architecture of LayoutLMv3(<a href="https://arxiv.org/pdf/2204.08387.pdf">ref</a>)</figcaption></figure><p>The LayoutLMv3 model differs(called improves) drastically when compared to the earlier 2 versions. Here, the image features are also fed to the transformer directly(as patches) rather than using a feature extractor backbone like Faster-RCNN or ResNeXT. In technical terms it is trained on both <strong>Masked Language Modelling</strong> task(predicting the [MASK]ed word) and <strong>Masked Image Modelling</strong> task(predicting the [MASK]ed image patch) along with a Word Patch Alignment objective. MLM and MIM are self explanatory, so let’s talk a little about <strong>Word Patch Alignment.</strong></p><p>As pointed out earlier, we mask some word tokens for MLM task, and corresponding parts of the same masked words in the image are redacted for the MIM task, as this masking is done randomly for the words(tokens) the model doesn’t learn that the masks in the two modalities i.e. the text and the image correspond to each other, which means there needs to be some way to send this information to the model as well so that the model knows about the alignment of these two modalities. This is done by assigning an aligned label to an unmasked text token when its corresponding image tokens are also unmasked. Otherwise, an unaligned label is assigned. A two-layer MLP(multi layer perceptron) head that inputs contextual text and image and outputs the binary aligned/unaligned labels with a binary cross-entropy loss is trained to predict these aligned/unaligned labels. This is how the alignment of masked and unmasked tokens is learnt and withheld in the model.</p><h3>Applications</h3><p>So, based on the above discussion, we can conclude that the LayoutLMv3 and older cousins can be used in Document Understanding, Form Recognition, Visual QnA and similar use-cases, for eg. extracting KV Pairs from IDs, bank forms, receipts, classifying document images based on layout and text and many more similar tasks.</p><h3>Fine-tuning LayoutLMv3 on custom dataset</h3><p>Hop on to:</p><ul><li>the <a href="https://medium.com/@shivarama/layoutlmv3-from-zero-to-hero-part-2-d2659eaa7dee">part-2</a> of the series to understand how to create the custom data.</li><li>the <a href="https://medium.com/@shivarama/layoutlmv3-from-zero-to-hero-part-3-16ae58291e9d">part-3</a> to see the fine-tuning on custom dataset.</li></ul><h3>Thanks!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85d05818eec4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>