<?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 Kalpesh Mulye on Medium]]></title>
        <description><![CDATA[Stories by Kalpesh Mulye on Medium]]></description>
        <link>https://medium.com/@kalpeshmulye?source=rss-423f21e6eb3d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yVq7Yv0AKSF67UDg3_uOYA.jpeg</url>
            <title>Stories by Kalpesh Mulye on Medium</title>
            <link>https://medium.com/@kalpeshmulye?source=rss-423f21e6eb3d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:21:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kalpeshmulye/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[Image Captioning Using Hugging Face Vision Encoder Decoder — Step 2 Step Guide (Part 2)]]></title>
            <link>https://medium.com/@kalpeshmulye/image-captioning-using-hugging-face-vision-encoder-decoder-step-2-step-guide-part-2-95f64f6b73b9?source=rss-423f21e6eb3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/95f64f6b73b9</guid>
            <category><![CDATA[vision-transformer]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[image-captioning]]></category>
            <dc:creator><![CDATA[Kalpesh Mulye]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 18:15:08 GMT</pubDate>
            <atom:updated>2022-07-18T18:15:08.501Z</atom:updated>
            <content:encoded><![CDATA[<h3>Image Captioning Using Hugging Face Vision Encoder Decoder — Step 2 Step Guide (Part 2)</h3><p>In the p<a href="https://medium.com/@kalpeshmulye/image-captioning-using-hugging-face-vision-encoder-decoder-step-2-step-guide-part-1-495ecb05f0d5">revious article</a>, we discussed in brief about <strong>encoder decoders</strong> and our approach towards solving the task of captioning. We fine-tuned a language model, this allowed the decoder to learn new words, generate brief captions and save training time.</p><blockquote>This can be referred as priming our decoder before actual training on the captioning task.</blockquote><p>Before we dirty our hands with the code, let us understand how the Vision Encoder Decoder module connects the two models (Image Encoder and Text Sequence generator) and how it deciphers what is present in the image.</p><blockquote>To understand this, you need a basic understanding of how transformer attention works and terminologies like KEY, QUERY &amp; VALUE. You can learn in detail about transformers in this informative 3-part <a href="https://towardsdatascience.com/transformers-explained-visually-part-1-overview-of-functionality-95a6dd460452">blogpost</a> by <a href="https://medium.com/u/54f9ca55ed47">Ketan Doshi</a> also in this <a href="https://lena-voita.github.io/nlp_course/seq2seq_and_attention.html">Seq2Seq course</a>.</blockquote><h3>VISION ENCODER DECODER (VED)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X1EzTTEMv14ETR-uJQzLcQ.png" /><figcaption>2.1 Vision Encoder Decoder Architecture</figcaption></figure><p>When we initialize the vision encoder decoder with our pretrained models (Vision transformer &amp; Roberta in above example), it creates an image encoder &amp; language decoder instance and <strong>ties their embeddings together using a cross attention layer</strong>.</p><blockquote><strong>The encoder embeddings are used as KEY &amp; VALUE and the decoder embeddings are used as QUERY in the cross-attention head.</strong></blockquote><p>During training, both Image and desired caption are passed as inputs to the model. This is an example of <strong>TEACHER FORCING</strong> training.</p><blockquote>In above example, the image and caption “<strong>&lt;start&gt; Dog is running in grass with ball in its mouth &lt;end&gt;</strong>” are the inputs to our model.</blockquote><p>Using these inputs, the model is forced to generate same caption, this leads to understanding the correlation between words in captions and objects in the input images.</p><p>Final output from the linear layer (LM head), is a vector of size <strong>Length of sequence X Vocabulary size </strong>(refer 2.1).<strong> </strong>The elements of vector matrix (after SoftMax) are <strong>probabilities </strong>(green boxes below signifies highest probability)<strong> </strong>of the word occurring at a given position in the sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*MQBTl0cUpNVLwZKOdjJAwA.png" /><figcaption>2.2 Output Vector to Text Sequence</figcaption></figure><p>This generated sequence “&lt;start&gt; Dog is running &lt;end&gt;” is compared with input caption and loss is calculated for every incorrect word in the generated sequence.</p><blockquote>At every training step, the model predicts sequence of words which is compared with the actual caption and the loss is propagated back to learn.</blockquote><p>After training, GIF below explains how we generate text sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*tDDNgU9P3pza8mDpBduPhA.gif" /><figcaption>2.3 Caption generation</figcaption></figure><ol><li>We start with image and start token “&lt;start&gt;” as input to the model.</li><li>Using inputs model generates <strong>Length of sequence X Vocabulary length </strong>vector again, but unlike in training (where all the tokens are used) only the second token (immediately succeeding to start token) is considered and all the other words are masked. <em>Above GIF shows, after start token, “Dog” was the first word, and all the other words were masked.</em></li><li>Once we get the first word, we repeat the process in first step except this time we will use “&lt;start&gt; Dog” as our input and generate next word (3rd token).</li><li>This loop continues until the model outputs an end token or reaches a maximum set length of output.</li></ol><h3>Translation &amp; <strong>Captioning Analogy</strong></h3><p>Now that we know how model generates caption, we will have a brief discussion on how it interprets objects in the input image using an analogy with machine translation.</p><p>In Sentence translation (ex. converting Spanish to English), words from input sentence are used to select words and structure them to form a meaningful translated sentence. Thus every translated word has some association with words in input sentence. This association (also known as attention weights) signify what input word or set of input words led to the selection of a specific translated word.</p><p>As shown below the word “try” have higher attention weight with “tratar” signifies “try ”was selected predominantly because of “tratar”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*-l23R3Wp9La47ITzWk7P9g.png" /><figcaption>2.4 Translation Attention Matrix</figcaption></figure><p>“descubro” have attention weights with the “find” (which is discover in Spanish) also with “to” and “out” indicating the focus of the model on Spanish tokens while generating the corresponding English token.</p><p><strong>Similarly</strong> in Image captioning task, the words will have attentions to regions, objects or actions in the image. Each word or sequence of words will have association or attention weights with different regions signifying which region contributed towards selection of the word the most.</p><p>As we see the word ‘dog ’ is associated to region of the image containing a dog. ‘Running’ and ‘grass’ has high attention with the 3rd region where we can see the grass and legs of the dog. ‘Running’ has small attention to the first image as we can clearly see that the dog is running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v_AxUA7_lgtMnbZ2rMoqCA.png" /><figcaption>2.5 Captioning Attention Matrix</figcaption></figure><p>After sufficient training, the model is able to interpret nuances in image and generate captions by understanding various objects and their actions in the image.</p><h3>TASK 2</h3><p>In the second task we will start with pre-processing data &amp; initialize VED with pre trained Vision Transformer (from hugging face) &amp; our fine-tuned Roberta model (from Task 1).</p><p><strong>-&gt; Libraries</strong></p><pre><strong>import</strong> datasets<br><strong>import</strong> transformers<br><strong>import</strong> pandas <strong>as</strong> pd<br><strong>import</strong> numpy <strong>as</strong> np<br><strong>import</strong> torch<br><strong>from</strong> torch.utils.data.dataset <strong>import</strong> Dataset<br><strong>from</strong> pathlib <strong>import</strong> Path<br><br><br><br><em>#Tokenizer from scratch on vocabulary of corpus</em><br><strong>from</strong> tokenizers <strong>import</strong> ByteLevelBPETokenizer<br><br><em># Decoder</em><br><strong>from</strong> transformers <strong>import</strong> RobertaConfig<br><strong>from</strong> transformers <strong>import</strong> RobertaForMaskedLM <em># RobertaLM for learning</em><br><strong>from</strong> transformers <strong>import</strong> RobertaTokenizerFast <em># After training tokenizer we will wrap it so it can be used by Roberta model</em><br><br><br><br><em>#Encoder-Decoder Model</em><br><strong>from</strong> transformers <strong>import</strong> VisionEncoderDecoderModel<br><br><em>#Training</em><br><em># When using previous version of the library you need the following two lines</em><br><strong>from</strong> transformers <strong>import</strong> Seq2SeqTrainer<br><strong>from</strong> transformers <strong>import</strong> Seq2SeqTrainingArguments</pre><pre># Latest version imports<strong><br>from</strong> transformers <strong>import</strong> Trainer, TrainingArguments</pre><pre><br>import torch<br><br><em># If there&#39;s a GPU available...</em><br>if torch.cuda.is_available():    <br><br>    <em># Tell PyTorch to use the GPU.    </em><br>    device = torch.device(&quot;cuda&quot;)<br><br>    print(&#39;There are <strong>%d</strong> GPU(s) available.&#39; % torch.cuda.device_count())<br><br>    print(&#39;We will use the GPU:&#39;, torch.cuda.get_device_name(0))<br><br><em># If not...</em><br>else:<br>    print(&#39;No GPU available, using the CPU instead.&#39;)<br>    device = torch.device(&quot;cpu&quot;)</pre><ul><li><strong>&gt; Train Test Split &amp; Pre-processing</strong></li></ul><pre><strong>import</strong> random <br><strong>def</strong> train_test_split(dictionary):<br>    images <strong>=</strong> dictionary<strong>.</strong>keys()<br>    images_test <strong>=</strong> random<strong>.</strong>sample(images,int(0.3<strong>*</strong>len(images)))<br>    images_train <strong>=</strong> [img <strong>for</strong> img <strong>in</strong> images <strong>if</strong> img <strong>not</strong> <strong>in</strong> images_test]<br><br>    train_dict <strong>=</strong> {<br>      img: dictionary[img] <strong>for</strong> img <strong>in</strong> images_train<br>    }<br><br>    test_dict <strong>=</strong> {<br>      img: dictionary[img] <strong>for</strong> img <strong>in</strong> images_test<br>    }<br>    <strong>return</strong>(train_dict,test_dict)<br><br>train,test <strong>=</strong> train_test_split(images_caption_dict)</pre><blockquote><em>The dataset used in this guide has 5 distinct captions associated to a single image. Due to compute constraints, I created 5 distinct image caption pairs to have smaller input sequence, but you can use all 5 captions concatenated together by a separator token by just passing</em><strong><em> use_all = True </em></strong><em>in the function below</em></blockquote><pre><strong>import</strong> pandas <strong>as</strong> pd<br><br><strong>def</strong> get_df(dictionary):<br>    df <strong>=</strong> pd<strong>.</strong>DataFrame([])<br><br>    captions <strong>=</strong> []<br>    images <strong>=</strong> []<br>    <strong>for</strong> image <strong>in</strong> list(images_caption_dict<strong>.</strong>keys()):<br>        caption<strong>=</strong> images_caption_dict[image]<br>        if use_all == True:<br>            captions.append(tokenizer.sep_token.join([&#39; &#39;<strong>.</strong>join(capt<strong>.</strong>replace(&#39;&lt;s&gt; &#39;,&#39;&#39;)<strong>.</strong>replace(&#39;  &lt;e&gt;&#39;,&#39;&#39;)<strong>.</strong>strip()<strong>.</strong>split(&#39; &#39;) for capt in caption])<br>        else:</pre><pre>            <strong>for</strong> capt <strong>in</strong> caption:<br>                captions<strong>.</strong>append(&#39; &#39;<strong>.</strong>join(capt<strong>.</strong>replace(&#39;&lt;s&gt; &#39;,&#39;&#39;)<strong>.</strong>replace(&#39;  &lt;e&gt;&#39;,&#39;&#39;)<strong>.</strong>strip()<strong>.</strong>split(&#39; &#39;)[:30]))<br>                images<strong>.</strong>append(image)<br><br>    df[&#39;images&#39;] <strong>=</strong> images<br>    df[&#39;captions&#39;] <strong>=</strong> captions<br>    <strong>return</strong>(df)<br><br>train_df <strong>=</strong> get_df(train)<br>test_df <strong>=</strong> get_df(test)</pre><ul><li><strong>&gt; Initialize Encoder Feature Extractor &amp; Decoder Tokenizer</strong></li></ul><p>Feature Extractor in Vision transformer is analogous to a tokenizer, because it slices the 3d image in to sequence of 3d cropped images as tokens and ready for input, just like a tokenizer.</p><pre><strong>from</strong> transformers <strong>import</strong> ViTFeatureExtractor<br><strong>from</strong> transformers <strong>import</strong> RobertaTokenizerFast</pre><pre>feature_extractor <strong>=</strong> ViTFeatureExtractor<strong>.</strong>from_pretrained(&quot;google/vit-base-patch16-224-in21k&quot;)<br>tokenizer <strong>=</strong> RobertaTokenizerFast<strong>.</strong>from_pretrained(&#39;Byte_tokenizer&#39;)</pre><ul><li><strong>&gt; Initialize Vision Encoder Decoder (VED)</strong></li></ul><p>We will initialize VED model and provide “Vision Transformer” as an encoder (from hugging face) and our pre-trained “Roberta” model as decoder (as shown above 2.1)</p><blockquote>REMEMBER to put “tie_encoder_decoder = True” this is crucial (it does it by default but make sure it is still included in your code).</blockquote><p>Tie_encoder_decoder method generates a cross attention layer as we discussed in detail above.</p><pre><em># set encoder decoder tying to True</em><br>model <strong>=</strong> VisionEncoderDecoderModel<strong>.</strong>from_encoder_decoder_pretrained\<br>                    (&quot;google/vit-base-patch16-224-in21k&quot;, &#39;RobertaMLM&#39;, tie_encoder_decoder<strong>=True</strong>)<br>model.to(device)</pre><p>Since tokenizer is initialized parallelly, the parameter settings below are necessary for the model to interpret input from the tokenizer.</p><pre><em># set special tokens used for creating the decoder_input_ids from the labels</em><br>model<strong>.</strong>config<strong>.</strong>decoder_start_token_id <strong>=</strong> tokenizer<strong>.</strong>cls_token_id<br>model<strong>.</strong>config<strong>.</strong>pad_token_id <strong>=</strong> tokenizer<strong>.</strong>pad_token_id<br><em># make sure vocab size is set correctly</em><br>model<strong>.</strong>config<strong>.</strong>vocab_size <strong>=</strong> model<strong>.</strong>config<strong>.</strong>decoder<strong>.</strong>vocab_size<br><br><em># set beam search parameters</em><br>model<strong>.</strong>config<strong>.</strong>eos_token_id <strong>=</strong> tokenizer<strong>.</strong>sep_token_id<br>model<strong>.</strong>config<strong>.</strong>max_length <strong>=</strong> 20<br>model<strong>.</strong>config<strong>.</strong>early_stopping <strong>=</strong> <strong>True</strong><br>model<strong>.</strong>config<strong>.</strong>no_repeat_ngram_size <strong>=</strong> 3<br>model<strong>.</strong>config<strong>.</strong>length_penalty <strong>=</strong> 2.0<br>model<strong>.</strong>config<strong>.</strong>num_beams <strong>=</strong> 4</pre><p>The VED model requires only 2 inputs</p><ol><li>pixel_values : 3d image chunk sequence output from feature extractor.</li><li>labels : Token sequence output from tokenizer of desired captions.</li></ol><ul><li><strong>&gt; Create Dataset for training &amp; evaluation</strong></li></ul><pre><strong>from</strong> torch.utils.data <strong>import</strong> Dataset<br><strong>from</strong> PIL <strong>import</strong> Image</pre><pre>batch_size<strong>=</strong>TRAIN_BATCH_SIZE  <em># change to 16 for full training</em></pre><pre>max_length = max(np.max(train_df[&#39;captions&#39;].apply(lambda x : len(x.split(&#39; &#39;))),np.max(test_df[&#39;captions&#39;].apply(lambda x : len(x.split(&#39; &#39;))))</pre><pre><strong>class</strong> IAMDataset(Dataset):<br>    <strong>def</strong> __init__(self, df, tokenizer,feature_extractor, decoder_max_length<strong>=</strong>max_length):<br>        self<strong>.</strong>df <strong>=</strong> df<br>        self<strong>.</strong>tokenizer <strong>=</strong> tokenizer<br>        self<strong>.</strong>feature_extractor <strong>=</strong> feature_extractor<br>        self<strong>.</strong>decoder_max_length <strong>=</strong> decoder_max_length<br><br>    <strong>def</strong> __len__(self):<br>        <strong>return</strong> len(self<strong>.</strong>df)<br><br>    <strong>def</strong> __getitem__(self, idx):<br>        <em># get file name + text </em><br>        img_path <strong>=</strong> self<strong>.</strong>df[&#39;images&#39;][idx]<br>        caption <strong>=</strong> self<strong>.</strong>df[&#39;captions&#39;][idx]<br>        <em># prepare image (i.e. resize + normalize)</em><br>        image <strong>=</strong> Image<strong>.</strong>open(img_path)<strong>.</strong>convert(&quot;RGB&quot;)<br>        pixel_values <strong>=</strong> self<strong>.</strong>feature_extractor(image, return_tensors<strong>=</strong>&quot;pt&quot;)<strong>.</strong>pixel_values<br>        <em># add labels (input_ids) by encoding the text</em><br>        labels <strong>=</strong> self<strong>.</strong>tokenizer(caption, truncation <strong>=</strong> <strong>True</strong>,<br>                                          padding<strong>=</strong>&quot;max_length&quot;, <br>                                          max_length<strong>=</strong>self<strong>.</strong>decoder_max_length)<strong>.</strong>input_ids<br>        <em># important: make sure that PAD tokens are ignored by the loss function</em><br>        labels <strong>=</strong> [label <strong>if</strong> label <strong>!=</strong> self<strong>.</strong>tokenizer<strong>.</strong>pad_token_id <strong>else</strong> <strong>-</strong>100 <strong>for</strong> label <strong>in</strong> labels]<br><br>        encoding <strong>=</strong> {&quot;pixel_values&quot;: pixel_values<strong>.</strong>squeeze(), &quot;labels&quot;: torch<strong>.</strong>tensor(labels)}<br>        <strong>return</strong> encoding<br>    <br>train_dataset <strong>=</strong> IAMDataset(train_df,<br>                           tokenizer<strong>=</strong>tokenizer,<br>                          feature_extractor<strong>=</strong> feature_extractor)<br>eval_dataset <strong>=</strong> IAMDataset(test_df),<br>                           tokenizer<strong>=</strong>tokenizer,feature_extractor<strong>=</strong> feature_extractor)</pre><ul><li><strong>&gt; Rouge Metrics to evaluate performance</strong></li></ul><p><a href="https://aclanthology.org/W04-1013.pdf"><strong>ROUGE</strong> (Recall-Oriented Understudy for Gisting Evaluation)</a>, it measures number of matching n-grams between the sequence generated by the model and desired sequence. Learn more about ROGUE in this <a href="https://medium.com/nlplanet/two-minutes-nlp-learn-the-rouge-metric-by-examples-f179cc285499">article</a>.</p><pre><em># load rouge for validation</em><br>rouge <strong>=</strong> datasets<strong>.</strong>load_metric(&quot;rouge&quot;)<br><br><strong>def</strong> compute_metrics(pred):<br>    labels_ids <strong>=</strong> pred<strong>.</strong>label_ids<br>    pred_ids <strong>=</strong> pred<strong>.</strong>predictions<br><br>    <em># all unnecessary tokens are removed</em><br>    pred_str <strong>=</strong> tokenizer<strong>.</strong>batch_decode(pred_ids, skip_special_tokens<strong>=True</strong>)<br>    labels_ids[labels_ids <strong>==</strong> <strong>-</strong>100] <strong>=</strong> tokenizer<strong>.</strong>pad_token_id<br>    label_str <strong>=</strong> tokenizer<strong>.</strong>batch_decode(labels_ids, skip_special_tokens<strong>=True</strong>)<br><br>    rouge_output <strong>=</strong> rouge<strong>.</strong>compute(predictions<strong>=</strong>pred_str, references<strong>=</strong>label_str, rouge_types<strong>=</strong>[&quot;rouge2&quot;])[&quot;rouge2&quot;]<strong>.</strong>mid<br><br>    <strong>return</strong> {<br>        &quot;rouge2_precision&quot;: round(rouge_output<strong>.</strong>precision, 4),<br>        &quot;rouge2_recall&quot;: round(rouge_output<strong>.</strong>recall, 4),<br>        &quot;rouge2_fmeasure&quot;: round(rouge_output<strong>.</strong>fmeasure, 4),<br>    }</pre><pre>captioning_model <strong>=</strong> &#39;VIT_Captioning&#39;<br><br>training_args <strong>=</strong> Seq2SeqTrainingArguments(<br>    output_dir<strong>=</strong>captioning_model,<br>    per_device_train_batch_size<strong>=</strong>batch_size,<br>    per_device_eval_batch_size<strong>=</strong>batch_size,<br>    predict_with_generate<strong>=True</strong>,<br>    fp16=True,<br>    evaluation_strategy<strong>=</strong>&quot;epoch&quot;,<br>    do_train<strong>=True</strong>,<br>    do_eval<strong>=True</strong>,<br>    logging_steps<strong>=</strong>1024,  <br>    save_steps<strong>=</strong>2048, <br>    warmup_steps<strong>=</strong>1024,  <br>    <em>#max_steps=1500, # delete for full training</em><br>    num_train_epochs <strong>=</strong> TRAIN_EPOCHS, <em>#TRAIN_EPOCHS</em><br>    overwrite_output_dir<strong>=True</strong>,<br>    save_total_limit<strong>=</strong>1,<br>)<br><br><strong>from</strong> transformers <strong>import</strong> default_data_collator<br><br><em># instantiate trainer</em><br>trainer <strong>=</strong> Seq2SeqTrainer(<br>    tokenizer<strong>=</strong>feature_extractor,<br>    model<strong>=</strong>model,<br>    args<strong>=</strong>training_args,<br>    compute_metrics<strong>=</strong>compute_metrics,<br>    train_dataset<strong>=</strong>train_dataset,<br>    eval_dataset<strong>=</strong>eval_dataset,<br>    data_collator<strong>=</strong>default_data_collator,<br>)</pre><pre><em># Fine-tune the model, training and evaluating on the train dataset</em> trainer<strong>.</strong>train()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*txmU4e_7vuTYNVmZGx1f6g.png" /></figure><pre>trainer<strong>.</strong>save_model(&#39;Image_Cationing_VIT_Roberta_iter2&#39;)</pre><h3><strong>Results</strong></h3><p>Let&#39;s see how our model is performing,</p><pre>t <strong>=</strong> VisionEncoderDecoderModel<strong>.</strong>from_pretrained(&#39;Image_Cationing_VIT_Roberta_iter2&#39;)</pre><pre>temp <strong>=</strong> test_df<strong>.</strong>sample(1)<strong>.</strong>images<strong>.</strong>iloc[0]<br>Image<strong>.</strong>open(temp)<strong>.</strong>convert(&quot;RGB&quot;)</pre><pre>print(tokenizer<strong>.</strong>decode(t<strong>.</strong>generate(feature_extractor(Image<strong>.</strong>open(temp)<strong>.</strong>convert(&quot;RGB&quot;), return_tensors<strong>=</strong>&quot;pt&quot;)<strong>.</strong>pixel_values)[0]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*FH5wl1H5YDnFeWwc8DffaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*gfizM5IKvM7cBKFFSZxSGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*OhW4XsyOMuIB9dm_BAjKzA.png" /></figure><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95f64f6b73b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Captioning Using Hugging Face Vision Encoder Decoder — Step 2 Step Guide (Part 1)]]></title>
            <link>https://medium.com/@kalpeshmulye/image-captioning-using-hugging-face-vision-encoder-decoder-step-2-step-guide-part-1-495ecb05f0d5?source=rss-423f21e6eb3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/495ecb05f0d5</guid>
            <category><![CDATA[training-transformer]]></category>
            <category><![CDATA[vision-encoder-decoder]]></category>
            <category><![CDATA[fine-tuning-transformer]]></category>
            <category><![CDATA[image-captioning-pytorch]]></category>
            <category><![CDATA[masked-language-model]]></category>
            <dc:creator><![CDATA[Kalpesh Mulye]]></dc:creator>
            <pubDate>Thu, 07 Jul 2022 20:41:36 GMT</pubDate>
            <atom:updated>2022-07-18T18:16:35.705Z</atom:updated>
            <content:encoded><![CDATA[<h3>Image Captioning Using Hugging Face Vision Encoder Decoder — A Step 2 Step Guide (Part 1)</h3><p>In this tutorial we will learn to create our very own image captioning model using Hugging face library.</p><p>Along with the code walkthrough, we will discuss key concepts in brief to get an intuitive idea of how transformer architecture works with few examples. This guide is divided in 2 main tasks</p><ol><li>Train &amp; fine tune Language model on captions (any transformer BERT, Roberta etc.) — Part 1</li><li>Initialize &amp; train captioning model using Vision Encoder Decoder module of hugging face library — <a href="https://medium.com/@kalpeshmulye/image-captioning-using-hugging-face-vision-encoder-decoder-step-2-step-guide-part-2-95f64f6b73b9">Part 2</a></li></ol><p><a href="https://www.kaggle.com/datasets/adityajn105/flickr8k">Flikr8K</a> dataset was used to train both models.</p><p>You can download the images from <a href="https://www.kaggle.com/datasets/adityajn105/flickr8k">here</a>. All the training captions and Image file names are stored in <a href="https://github.com/kalpesh22-21/Image_Captioning_using_Hugging_Face/blob/main/data.json">data.json</a>.</p><blockquote>For complete code of the tutorial use my <a href="https://github.com/kalpesh22-21/Image_Captioning_using_Hugging_Face">github</a> link</blockquote><h3><strong>What is Image Captioning in a crux?</strong></h3><p>Image captioning is as an End-to-End Sequence to Sequence embedding task where, Image pixels are input sequences and caption describing the image is desired output.</p><p>Due to exclusive nature of both images and text sequences two different model tied together (one dedicated to <strong>ENCODE </strong>from images and other <strong>DECODE </strong>to a text Sequence) are required to solve this task.</p><p>This idea is synonymous to traditional Encoders &amp; Decoders used to resolve processing and propagation of electronic signals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*-Vhqzkq-pWyCnkvnG_A-ug.jpeg" /></figure><p>Encoder-Decoder architecture inspires state of the art Sequence to Sequence learning task like Language translation, Text summarization etc. which harness power of State-of-Art Transformers like BERT, Roberta, GPT2 etc.</p><p>In these above tasks, encoder is essentially a transformer model which coverts information in text into a <strong>mathematical tensor</strong> employing Self-Attention heads which uses Key, Value and Query vectors to encode text and draw the context of entire input into an embedding vector. This solves the problem of traditional NLP techniques like short window of attention and inability of parallel computation. Mathematical-tensor from Encoder is connected with the Decoder using a <strong>cross-attention layer</strong>. This layer helps in mapping decoder tensors to the encoder output and extract the required information and deliver the desired output according to the task at hand.</p><p>Image captioning is analogous to other Seq2 Seq tasks except the only difference is instead of translating from a <strong>language to language</strong> we are translating from an <strong>Image to a language</strong>. Which mathematically is an identical task as both are nothing but 3 dimensional vectors.</p><blockquote><em>You can learn in detail about transformer architecture in this informative 3-part </em><a href="https://towardsdatascience.com/transformers-explained-visually-part-1-overview-of-functionality-95a6dd460452"><em>blogpost</em></a><em> by </em><a href="https://medium.com/u/54f9ca55ed47"><em>Ketan Doshi</em></a><em> also this </em><a href="https://lena-voita.github.io/nlp_course/seq2seq_and_attention.html"><em>Seq2Seq guide course</em></a></blockquote><h3>Before ATTENTION from Transformers</h3><p>Before advent of transformers, encoders chosen for captioning task were CNN architectures trained on image classification or segmentation. Last hidden states from pretrained CNN serve as an input cell state for recurrent networks like LSTM, GRU decoders which generates the desired captions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*wBjQbXoyZKZAeHMT8E_jHQ.png" /><figcaption>Image Captioning Using CNN and RNN networks</figcaption></figure><h3>After ATTENTION from Transformers</h3><p>Due to advances in transformers in computer vision and NLP they replaced both encoder and decoder architectures.</p><p>Encoder for image is a Vision Transformer (explained below) and the LSTMs or GRUs are replaced by transformers which can generate better captions due to its capability to understand context better.</p><blockquote>Note: New Efficient Net V2 outperforms ViT so there is still tussle for best architecture in computer vision</blockquote><p>The output embeddings from ViT encoder are connected with the decoder transformer which can be any transformer architecture like Roberta, BERT or GPT2 etc. with a cross attention layer to generate the text describing the Image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*6mAcga0j1YbKS4HInc0wPg.png" /><figcaption>Image captioning using transformers (Reference: <a href="https://paperswithcode.com/method/vision-transformer">1</a>)</figcaption></figure><h4>What is a Vision Transformer?</h4><p>Recently a paper on Vision Transformers “An Image is worth 16x16 words” which flashes an idea that every Image can be interpreted as chunk of images analogous to tokens or words in a sentence. This 3d Image tensor tokens can be used as an input to a transformer for any CV tasks. This solves the challenge of CNN of limited association as the basic idea of CNN’s are tying only regional pixels using a kernel which convolutes all over the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*AoE_mecs9_prJ2mIc9TDqQ.png" /><figcaption>Vision Transformer (Reference: <a href="https://paperswithcode.com/method/vision-transformer">1</a>)</figcaption></figure><p>Now that we have a brief idea of the models that are used in upcoming guide lets us begin creating our very own image captioning model….</p><h3>TASK1</h3><p>We will be fine tuning a language model on our corpus of text which will allow the decoder to learn new words (if any) and generate brief captions. This will fine tune the self-attention weights of the transformer to build a better context of sentences.</p><p>This will also save us training time and complexity on the actual task of captioning because while training the captioning model the optimizer can focus on fine tuning the cross-attention layers, as the self-attention layers would be already primed to have better sentence (caption) representation.</p><h4>-&gt; Model Parameters</h4><p>Defining hyper parameters like learning rate, batch size, maximum length of text sequence to be generated by the decoder.]</p><pre>TRAIN_BATCH_SIZE <strong>=</strong> 20   <em># input batch size for training (default: 64)</em><br>VALID_BATCH_SIZE <strong>=</strong> 5   <em># input batch size for testing (default: 1000)</em><br>VAL_EPOCHS <strong>=</strong> 1 <br>LEARNING_RATE <strong>=</strong> 1e-4    <em># learning rate (default: 0.01)</em><br>SEED <strong>=</strong> 42               <em># random seed (default: 42)</em><br>MAX_LEN <strong>=</strong> 128           <em># Max length for Input description</em><br><br>TRAIN_EPOCHS <strong>=</strong> 2       <em># number of epochs to train (default: 5)</em><br>WEIGHT_DECAY <strong>=</strong> 0.01<br>SEED <strong>=</strong> 42               <em># random seed (default: 42)</em><br>SUMMARY_LEN <strong>=</strong> 20   <em># Maximum length of caption generated </em></pre><pre>import torch<br><br><em># If there&#39;s a GPU available...</em><br>if torch.cuda.is_available():    <br><br>    <em># Tell PyTorch to use the GPU.    </em><br>    device = torch.device(&quot;cuda&quot;)<br><br>    print(&#39;There are <strong>%d</strong> GPU(s) available.&#39; % torch.cuda.device_count())<br><br>    print(&#39;We will use the GPU:&#39;, torch.cuda.get_device_name(0))<br><br><em># If not...</em><br>else:<br>    print(&#39;No GPU available, using the CPU instead.&#39;)<br>    device = torch.device(&quot;cpu&quot;)</pre><p>Loading the json file with Image file name and captions associated to the image.</p><p>Preprocessing the captions with start and end token (this is not a necessary step most of the tokenizers append the Start and End tokens by default when you tokenize the sentence).</p><pre><strong>import</strong> os<br><strong>import</strong> json<br><strong>import</strong> pandas <strong>as</strong> pd</pre><pre># LOCATION OF JSON AND IMAGES<br>os<strong>.</strong>chdir(r&#39;C:\Users\kalpe\Great lakes\ML project&#39;) </pre><pre># CONVERTING TO DICTIONARY<br><strong>with</strong> open(&#39;data.json&#39;, &#39;r&#39;) <strong>as</strong> openfile:<br><br>    json_object <strong>=</strong> json<strong>.</strong>load(openfile)<br><br>images_caption_dict <strong>=</strong> dict(json_object)</pre><pre><br>images_path <strong>=</strong> &#39;C:/Users/kalpe/Documents/Great lakes/ML project/Flickr8k_Dataset/Flicker8k_Dataset/&#39;</pre><pre>images <strong>=</strong> list(images_caption_dict<strong>.</strong>keys())</pre><pre># PREPENDING IMAGE PATHS TO THE IMAGE FILE NAMES<br><strong>for</strong> image_path <strong>in</strong> images:<br>    <strong>if</strong> image_path<strong>.</strong>endswith(&#39;jpg&#39;):<br>        new <strong>=</strong> images_path <strong>+</strong> image_path<strong>.</strong>split(&#39;/&#39;)[<strong>-</strong>1]<br>        images_caption_dict[new] <strong>=</strong> images_caption_dict<strong>.</strong>pop(image_path)<br>    <strong>else</strong>:<br>        images_caption_dict<strong>.</strong>pop(image_path)</pre><pre># PREPROCESSING CAPTIONS BEFORE TOKENIZING<br>df <strong>=</strong> pd<strong>.</strong>DataFrame([])<br><br>captions <strong>=</strong> []<br>images <strong>=</strong> []<br><strong>for</strong> image <strong>in</strong> list(images_caption_dict<strong>.</strong>keys()):<br>    caption <strong>=</strong> images_caption_dict[image]<br>    <strong>for</strong> capt <strong>in</strong> caption:<br>        captions<strong>.</strong>append(capt<strong>.</strong>replace(&#39;&lt;s&gt; &#39;,&#39;&#39;)<strong>.</strong>replace(&#39;  &lt;e&gt;&#39;,&#39;&#39;)<strong>.</strong>strip())<br>        images<strong>.</strong>append(image)<br>        <br>df[&#39;images&#39;] <strong>=</strong> images<br>df[&#39;captions&#39;] <strong>=</strong> captions</pre><h4>-&gt; Train a Custom Tokenizer</h4><p>It is always better to train a tokenizer on your corpus of text so that it doesn&#39;t miss out on words important for your specific task. If the word in our corpus is not present in the tokenizer vocabulary it may be assigned an unknown “&lt;UNK&gt;” token which will be loss of information.</p><p><em>The captions are needed to be converted into text files, for the tokenizer to learn on the corpus of captions we have.</em></p><pre><em># Store values in a dataframe column (Series object) to files, one file per record</em><br>os<strong>.</strong>mkdir(&quot;./text_split&quot;)</pre><pre><strong>def</strong> column_to_files(column, prefix, txt_files_dir <strong>=</strong> &quot;./text_split&quot;):<br>    <em># The prefix is a unique ID to avoid to overwrite a text file</em><br>    i<strong>=</strong>prefix<br>    <em>#For every value in the df, with just one column</em><br>    <strong>for</strong> row <strong>in</strong> column<strong>.</strong>to_list():<br>      <em># Create the filename using the prefix ID</em><br>        file_name <strong>=</strong> os<strong>.</strong>path<strong>.</strong>join(txt_files_dir, str(i)<strong>+</strong>&#39;.txt&#39;)<br>        <strong>try</strong>:<br>            <em># Create the file and write the column text to it</em><br>            f <strong>=</strong> open(file_name, &#39;wb&#39;)<br>            f<strong>.</strong>write(row<strong>.</strong>encode(&#39;utf-8&#39;))<br>            f<strong>.</strong>close()<br>        <strong>except</strong> Exception <strong>as</strong> e:  <em>#catch exceptions(for eg. empty rows)</em><br>            print(row, e) <br>        i<strong>+=</strong>1<br>    <em># Return the last ID</em><br>    <strong>return</strong> i<br><br>data <strong>=</strong> df[&quot;captions&quot;]</pre><pre><em># Removing the end of line character \n</em><br>data <strong>=</strong> data<strong>.</strong>replace(&quot;\n&quot;,&quot; &quot;)</pre><pre><em># Set the ID to 0</em><br>prefix<strong>=</strong>0</pre><pre><em># Create a file for every description value</em><br>prefix <strong>=</strong> column_to_files(data, prefix)</pre><p>In this example we will train a Byte Level BPE Tokenizer which starts constructing tokens at byte level rather than word level.</p><blockquote><strong><em>Ex. “Higher the throw higher the scoring ability”</em></strong></blockquote><p><em>For above sentence the tokenizer will first start with all letters in the sentence and after chunking words together the final tokens might look like</em></p><p><em>[ “&lt;/s&gt;” ,“High”, “er&lt;/w&gt;”, “the&lt;/w&gt;”, “throw&lt;/w&gt;”, “high”, “er&lt;/w&gt;”, “the&lt;/w&gt;”, “scor”, “ing&lt;/w&gt;”, “ability&lt;/w&gt;”, “&lt;/e&gt;”]</em></p><blockquote>To learn more about different types of tokenizers <a href="https://towardsdatascience.com/byte-pair-encoding-subword-based-tokenization-algorithm-77828a70bee0">Refer this</a> awesome blog post.</blockquote><pre><strong>%%time</strong> <br>paths <strong>=</strong> [str(x) <strong>for</strong> x <strong>in</strong> Path(&quot;.&quot;)<strong>.</strong>glob(&quot;text_split/*.txt&quot;)]<br><br><em># Initialize a tokenizer</em><br>tokenizer <strong>=</strong> ByteLevelBPETokenizer(lowercase<strong>=True</strong>)<br><br><em># Customize training</em><br>tokenizer<strong>.</strong>train(files<strong>=</strong>paths, vocab_size<strong>=</strong>10000, min_frequency<strong>=</strong>2,<br>                show_progress<strong>=True</strong>,<br>                special_tokens<strong>=</strong>[<br>                                &quot;&lt;s&gt;&quot;,<br>                                &quot;&lt;pad&gt;&quot;,<br>                                &quot;&lt;e&gt;&quot;,<br>                                &quot;&lt;unk&gt;&quot;,<br>                                &quot;&lt;mask&gt;&quot;])</pre><p>After training save the tokenizer and then call it using the decoder model&#39;s tokenizer wrapper function which will wrap our trained tokenizer.</p><pre>os<strong>.</strong>mkdir(&#39;Byte_tokenizer&#39;)<br>tokenizer<strong>.</strong>save_model(&#39;Byte_tokenizer&#39;)</pre><h4>-&gt; Training Decoder</h4><p>I have used Roberta as a Text decoder model in this demonstration you can choose any Transformer model like Deberta, BERT, Alberta etc. (The tokenizing and initializing steps might differ for different models).</p><p>We are training decoder on the captions to fine tune it on the language structure and create better and brief description of Images.</p><p>For training the Language model we used masked LM method to initialize. In this method a random word in the sentence is masked while training, and the model tries to predict the word which will possibly be the right choice. The model keeps on learning till it starts predicting right words.</p><p><em>Initialize the model with the config and also use Roberta tokenizer wrapper as shown below. To learn more about Masked LM (Language Modelling) training checkout </em><a href="https://towardsdatascience.com/masked-language-modelling-with-bert-7d49793e5d2c"><em>this blogpost</em></a><em>.</em></p><pre>config <strong>=</strong> RobertaConfig(<br>    vocab_size<strong>=</strong>10000,<br>    max_position_embeddings<strong>=</strong>514,<br>    num_attention_heads<strong>=</strong>12,<br>    num_hidden_layers<strong>=</strong>6,<br>    type_vocab_size<strong>=</strong>1,<br>)<br><br>model <strong>=</strong> RobertaForMaskedLM(config<strong>=</strong>config)<br>model.to(device)</pre><pre>print(&#39;Num parameters: &#39;,model<strong>.</strong>num_parameters())<br><br><em># Create the tokenizer from a trained one</em><br>tokenizer <strong>=</strong> RobertaTokenizerFast<strong>.</strong>from_pretrained(&#39;Byte_tokenizer&#39;, max_len<strong>=</strong>MAX_LEN)</pre><p>Before training the model, we need to process the data by creating a data loader.</p><pre><strong>class</strong> CustomDataset(Dataset):<br>    <strong>def</strong> __init__(self, df, tokenizer):<br>        <em># or use the RobertaTokenizer from `transformers` directly.</em><br><br>        self<strong>.</strong>examples <strong>=</strong> []<br>        <br>        <strong>for</strong> example <strong>in</strong> df<strong>.</strong>values:<br>           x<strong>=</strong>tokenizer<strong>.</strong>encode_plus(example, max_length <strong>=</strong> MAX_LEN, truncation<strong>=True</strong>, padding<strong>=True</strong>)<br>            self<strong>.</strong>examples <strong>+=</strong> [x<strong>.</strong>input_ids]<br><br>    <strong>def</strong> __len__(self):<br>        <strong>return</strong> len(self<strong>.</strong>examples)<br><br>    <strong>def</strong> __getitem__(self, i):<br>        <em># We’ll pad at the batch level.</em><br>        <strong>return</strong> torch<strong>.</strong>tensor(self<strong>.</strong>examples[i])<br></pre><pre><em># Create the train and evaluation dataset</em> <br>train_dataset <strong>=</strong> CustomDataset(df[&#39;captions&#39;][:38000], tokenizer) eval_dataset <strong>=</strong> CustomDataset(df[&#39;captions&#39;][38000:], tokenizer)</pre><p>Also, we use a handy tool, Data collator for Language Modelling which will randomly mask words while training.</p><pre><strong>from</strong> transformers <strong>import</strong> DataCollatorForLanguageModeling<br><br><em># Define the Data Collator</em><br>collator <strong>=</strong> DataCollatorForLanguageModeling(<br>    tokenizer<strong>=</strong>tokenizer, mlm<strong>=True</strong>, mlm_probability<strong>=</strong>0.1<br>)</pre><p>Now using the previously defined hyper parameters we will allocate the training arguments for training and start training the model.</p><pre>model_folder <strong>=</strong> &quot;RobertaMLM&quot;<br><em># Define the training arguments</em><br>training_args <strong>=</strong> TrainingArguments(<br>    output_dir<strong>=</strong>model_folder,<br>    fp16=True,<br>    overwrite_output_dir<strong>=True</strong>,<br>    evaluation_strategy <strong>=</strong> &#39;epoch&#39;,<br>    num_train_epochs<strong>=</strong>TRAIN_EPOCHS,<br>    learning_rate<strong>=</strong>LEARNING_RATE,<br>    weight_decay<strong>=</strong>WEIGHT_DECAY,<br>    per_device_train_batch_size<strong>=</strong>TRAIN_BATCH_SIZE,<br>    per_device_eval_batch_size<strong>=</strong>VALID_BATCH_SIZE,<br>    save_steps<strong>=</strong>8192,<br>    <em>#eval_steps=4096,</em><br>    save_total_limit<strong>=</strong>1,<br>)<br><em># Create the trainer for our model</em><br>trainer <strong>=</strong> Trainer(<br>    model<strong>=</strong>model,<br>    args<strong>=</strong>training_args,<br>    data_collator<strong>=</strong>collator,<br>    train_dataset<strong>=</strong>train_dataset,<br>    eval_dataset<strong>=</strong>eval_dataset,<br>    <em>#prediction_loss_only=True,</em><br>)</pre><pre><em># Train the model</em><br>trainer<strong>.</strong>train()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*JfaDayc2Ssl90i76IHA-FQ.png" /></figure><p>Time to check how the model is performing!!</p><pre><strong>from</strong> transformers <strong>import</strong> pipeline<br><br>fill <strong>=</strong> pipeline(<br>    &quot;fill-mask&quot;,<br>    model<strong>=</strong> r&#39;RobertaMLM&#39;,<br>    tokenizer<strong>=</strong> &#39;Byte_tokenizer&#39;<br>)</pre><pre>fill(&quot;a girl going into a &lt;mask&gt; building&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*dTTiiWO3-EMqrUB9ss61OA.png" /></figure><p>Finally save the decoder and tokenizer for further use in the second step.</p><pre>tokenizer<strong>.</strong>save_pretrained(&#39;Byte_tokenizer&#39;)<br>trainer<strong>.</strong>save_model(model_folder)</pre><p>This fine-tuned Language transformer will serve as a decoder in our final model.</p><p>Please refer my <a href="https://medium.com/@kalpeshmulye/image-captioning-using-hugging-face-vision-encoder-decoder-step-2-step-guide-part-2-95f64f6b73b9">next blog</a> for Task 2 where we will train our Vision Encoder Decoder model to generate the Image captions.</p><p>References:</p><p><a href="https://github.com/google-research/vision_transformer">GitHub - google-research/vision_transformer</a></p><p><a href="https://github.com/edumunozsala/RoBERTa_Encoder_Decoder_Product_Names">https://github.com/edumunozsala/RoBERTa_Encoder_Decoder_Product_Names</a></p><p><a href="https://huggingface.co/docs/transformers/model_doc/encoder-decoder">Encoder Decoder Models</a></p><p><a href="https://arxiv.org/abs/2109.10282">https://arxiv.org/abs/2109.10282</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=495ecb05f0d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>