<?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 Gaurav Ghati on Medium]]></title>
        <description><![CDATA[Stories by Gaurav Ghati on Medium]]></description>
        <link>https://medium.com/@gghati?source=rss-c2dc95c5f41------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0uXksEQP-oLrrea1dsxEAQ.png</url>
            <title>Stories by Gaurav Ghati on Medium</title>
            <link>https://medium.com/@gghati?source=rss-c2dc95c5f41------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 07:05:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gghati/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[Head Pruning in Transformer models !]]></title>
            <link>https://medium.com/data-science/head-pruning-in-transformer-models-ec222ca9ece7?source=rss-c2dc95c5f41------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec222ca9ece7</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[head-pruning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pruning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Gaurav Ghati]]></dc:creator>
            <pubDate>Mon, 11 May 2020 15:36:19 GMT</pubDate>
            <atom:updated>2020-05-13T23:54:11.952Z</atom:updated>
            <content:encoded><![CDATA[<h3>Head Pruning in Transformer Models!</h3><h4>In this article, we are going to look at pruning attention heads in transformers models like BERT.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BHEDS7vGKgSEUcxIsuwnDg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@tetrakiss?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Arseny Togulev</a> on <a href="https://unsplash.com/s/photos/transformer?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Overview:</p><ul><li><strong>Background work</strong> for this article.</li><li><strong>Importance of attention heads</strong> and <strong>why pruning</strong> is needed.</li><li><strong>Identifying important heads</strong> and their <strong>head</strong> <strong>functions</strong>.</li><li><strong>How to prune heads?</strong></li><li>How pruning affects the <strong>BLEU score</strong>.</li><li><strong>Pruning for Analysis</strong></li></ul><h3>Background Work</h3><p>Just for the recap, here is the basic transformer model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yxKYbi_K2NihsW6Z0Tq-Q.png" /><figcaption>Model Architecture of the transformer, (Image source: Figure 1 and 2 from <a href="http://papers.nips.cc/paper/7181-attention-is-all-you-need.pdf">Attention is all you need</a>)</figcaption></figure><p>As from the above figure you can see that the transformer have <strong>three</strong> types of attention implementations that are:<br>- Multi-head attention(MHA) of <strong>encoder</strong>,<br>- <strong>Masked</strong> multi-head attention of<strong> decoder</strong>,<br>- Multi-head attention <strong>encoder-decoder</strong></p><p>Each MHA consists of the <strong>concatenation</strong> of several <strong>scaled dot-product</strong> attention heads which are running in <strong>parallel</strong> unlike recurrent networks, that’s why attention is better than almost all RNNs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*kenaiakmUzdkF0QTwhRG1A.png" /></figure><p>Each head is attention function of <strong>query, key and value</strong> with trainable parameters <strong>(Wᵢᵩ, Wᵢᵏ, Wᵢᵛ)</strong>.</p><h3>Importance of Attention Heads</h3><p>All <strong>3 types</strong> of <strong>MHA</strong> play a specific and important role in different ways.</p><ul><li><strong>Encoder MHA </strong>contains self-attention layers, here all parameters that are query, key and value come from the same place, in this case, previous encoder or input vector sequence.</li><li>The<strong> decoder Masked MHA </strong>masked out all the words after that particular word, It shows that every position in the decoder is based on the <strong>previous inputs </strong>of the<strong> </strong>sequence, this <strong>mimics</strong> the encoder-decoder mechanism in <strong>sequence to sequence recurrent </strong>models.</li><li>In <strong>encoder-decoder MHA</strong>, <strong>query</strong> vectors come from the masked MHA and then combines it with <strong>key and value</strong> vectors from the top encoder. This whole structure allows producing efficient result based on previous inputs.</li></ul><p>Self-attention in MHA is the key component of the transformer since MHAs depends on attention heads, it’s important for them to be accurate, depending on <strong>multiple heads can improve</strong> the efficiency up to <strong>1 BLEU</strong> scores.</p><h3>Why Pruning?</h3><p>Surprising observations are made in the <a href="https://arxiv.org/pdf/1905.09418.pdf"><strong><em>paper</em></strong></a><strong>,</strong> that even after training models normally(with all heads), many heads can be <strong>removed</strong> at a <strong>test time</strong> and it will<strong> not significantly affect the BLEU</strong> score, in fact, some cases removing few heads led to improving BLEU scores.</p><h3>Identifying Important heads</h3><p>For detecting important heads from the MHA, to remove less important heads, we can use many approaches like <strong>“confidence”</strong> of the heads or <strong>Layer-wise relevance propagation(LRP)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*717_K6vvc1aPe_F0HxFZBQ.png" /><figcaption>Image Source: Figure 1 from <a href="https://arxiv.org/pdf/1905.09418.pdf">Analyzing Multi-Head Self-Attention</a></figcaption></figure><p><strong>Confidence</strong> is a relatively <strong>simple approach</strong> than LRP, and it contains the average of its <strong>maximum attention weights</strong>, where the average is taken over the set of sentences used for evaluation, it is an <strong>important</strong> consideration for translation.</p><p>As you can see in this figure that almost <strong>80%</strong> of the model’s attention is given to the <strong>single token head</strong>.</p><p>LRP is more reliable than “confidence”. It helps to find the <strong>relative contribution</strong> of a head in a <strong>network of heads</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqAEJOlfmE53VGYMjo7b5Q.png" /><figcaption>Image Source: Figure 1 from <a href="https://arxiv.org/pdf/1905.09418.pdf">Analyzing Multi-Head Self-Attention</a></figcaption></figure><p><strong>Both</strong> confidence and LRP is used for <strong>detecting important heads</strong>, as you can see in the above figure both LRP and confidence show almost similar results. So, now we know which heads are important, let’s see their role.</p><h3>Head Functions</h3><p>In the transformer’s MHA, each individual head plays a role in influencing translation produced by the models, these are the functions that head might be performing:</p><ul><li><strong>Positional</strong>: in this, the head point to the <strong>adjacent token</strong>, showed by purple in below figure.</li><li><strong>Syntactic</strong>: this points to the<strong> specific relation</strong> in the sentence, showed in green colour</li><li><strong>Rare word</strong>: this point to the <strong>least frequent or rare</strong> words, showed in orange colour.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*N8EWKyIXtWXvXbljiesnpA.png" /><figcaption>Image Source: Figure 1 from <a href="https://arxiv.org/pdf/1905.09418.pdf">Analyzing Multi-Head Self-Attention</a></figcaption></figure><p>From these head functions, it is clear that <strong>certain heads</strong> detect and learn <strong>syntactic relations</strong> with more accuracy than the others.</p><p>This also supports the hypothesis that the encoder does support some amount of <strong>syntactic disambiguation</strong> in sentences.</p><h3>How to prune heads?</h3><p>In the original transformer, as we saw in our background work, the MHA is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*qP0jzlNyPd-f7bsMVI2YSQ.png" /></figure><p>For removing less important heads, we modify the equation by using a specific gate g<strong>ᵢ</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*3EAVncpLhewuvKTe0GqSPg.png" /></figure><p>Where g<strong>ᵢ </strong>is in between <strong>{0, 1}</strong> if g<strong>ᵢ </strong>is 1 then while concatenating we are considering <strong>all its attention</strong> else if g<strong>ᵢ </strong>is 0 then we are just <strong>pruning</strong> it out.</p><p>So, <strong>gᵢ is a learnable parameter</strong> and is independent of the input sequence, as we want to prune heads for that, we ideally apply <strong>L0 regularization</strong> to scalar gate g<strong>ᵢ</strong>. The <strong>L0 norm</strong> equals the number of non-zero components and forces the models to remove less important heads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*Uu_Fbe6l549HZevc6tVpaQ.gif" /><figcaption>model converging for important heads (Image Sorce: By Lena Voita from <a href="https://lena-voita.github.io/posts/acl19_heads.html">Story of Heads</a>)</figcaption></figure><p>This model gets converge and at the end, heads are <strong>completely removed</strong> or<strong> stay open</strong>, this means that we only use the subset of all attention-heads.</p><h3>BLEU Score</h3><p>After removing heads let’s see how it affects the BLEU score of the model, as from the below image you can see that BLEU score <strong>hardly fall by 0.25</strong> <strong>BLEU</strong> while compressing the model from <strong>48 heads to 10 heads.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZLQgd5iCTFoTW2psX3i1SA.png" /><figcaption>Image Source: Figure 7 from <a href="https://arxiv.org/pdf/1905.09418.pdf">Analyzing Multi-Head Self-Attention</a></figcaption></figure><p>This <a href="https://arxiv.org/pdf/1905.09418.pdf">paper</a> demonstrated head pruning performing on two datasets that are <strong>WMT</strong> and <strong>OpenSubtitle</strong> as shown in the graph above, there BLEU score is noted according to the attention-heads used.</p><p>Surprisingly, in the case of WMT dataset, after removing a few heads we can see the<strong> increment in BLEU score</strong>, and as we decrease our heads from 5 heads to 1 head, BLEU score gets <strong>drastically reduced</strong>. These observations suggest that we only <strong>need a few heads(5–10)</strong> to perform competitive results with BASE models.</p><h3>Pruning for Analysis</h3><p>The transformers consist of three MHAs, as covered in background work. These MHAs are :<br>(a) Multi-head attention(MHA) of the <strong>encoder</strong> <br>(b) <strong>Masked</strong> multi-head attention of<strong> decoder <br></strong>(c) Multi-head attention <strong>encoder-decoder</strong></p><p>All these MHA contains a concatenation of the multiple heads. Head pruning can happen from any of these MHAs. It is observed that the model <strong>prefers to prune encoders</strong> self-attention heads first, while <strong>encoder-decoder MHA</strong> appears to be <strong>important</strong> among both datasets. Obviously, without encoder-decoder MHA translation task is not possible. As you can see below, in both cases less important heads are from the encoder MHA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yCZXddN5fpTK1QaKOrjfkQ.png" /><figcaption>Image Source: Figure 9 from <a href="https://arxiv.org/pdf/1905.09418.pdf">Analyzing Multi-Head Self-Attention</a></figcaption></figure><p>Another observation is that the head functions of the MHA retain even after pruning. When pruning model below 5–6 heads, due to fewer number of heads, only a <strong>few heads</strong> have to perform <strong>several functions</strong> then they are also preserved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hLM6F4siTqDtlm3dzxC-Gg.png" /><figcaption>Image Source: Figure 8 from <a href="https://arxiv.org/pdf/1905.09418.pdf">Analyzing Multi-Head Self-Attention</a></figcaption></figure><p>I hope this article has increased your understanding of MHA and pruning heads for better efficiency.</p><h3>References</h3><ul><li>The Story of Heads: (<a href="https://lena-voita.github.io/posts/acl19_heads.html">Post</a>)</li><li>Analyzing Multi-Head Self-Attention: (<a href="https://arxiv.org/pdf/1905.09418.pdf">Original Paper)</a></li><li>Are Sixteen Heads Really Better than One?: (<a href="https://arxiv.org/pdf/1905.10650.pdf">Original Paper)</a></li><li>Attention is all you need: (<a href="https://arxiv.org/pdf/1706.03762.pdf">Original Paper</a>)</li></ul><blockquote><em>Thanks for reading, You can connect with me on </em><a href="http://linkedin.com/in/gauravghati/"><em>LinkedIn</em></a><em>, </em><a href="https://twitter.com/GauravGhati/"><em>Twitter</em></a><em> or my </em><a href="http://gauravghati.world/"><em>portfolio</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec222ca9ece7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/head-pruning-in-transformer-models-ec222ca9ece7">Head Pruning in Transformer models !</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparison between BERT, GPT-2 and ELMo]]></title>
            <link>https://medium.com/@gghati/comparison-between-bert-gpt-2-and-elmo-9ad140cd1cda?source=rss-c2dc95c5f41------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ad140cd1cda</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Gaurav Ghati]]></dc:creator>
            <pubDate>Sun, 03 May 2020 14:03:32 GMT</pubDate>
            <atom:updated>2020-05-12T10:22:14.296Z</atom:updated>
            <content:encoded><![CDATA[<p>The recent progress in NLP in terms of model architecture had led us to breakthrough ideas like BERT architecture. Among those ideas, the few which changed the way we implement further models are large-scale pre-trained language models like <a href="https://openai.com/blog/language-unsupervised/"><strong>OpenAI GPT</strong></a><strong>, </strong><a href="https://arxiv.org/abs/1810.04805"><strong>BERT</strong></a><strong> </strong>and deep contextualized word representations i.e. <a href="https://arxiv.org/abs/1802.05365"><strong>ELMo</strong></a><strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3aZpXfSHgD9AlnGiUoaPQg.jpeg" /><figcaption>(Image Source: From Unsplash by <a href="https://unsplash.com/@aaronburden">Aaron Burden</a>)</figcaption></figure><p>In this article, we will look at how various model approaches were proposed:</p><ol><li><strong>ELMo <br>- </strong>Bidirectional Language Model<br>- ELMo Representations<br>- ELMo for Downstream Tasks</li><li><strong>OpenAI GPT-2 <br>- </strong>Transformer Decoder as Language Model<br>- Supervised Fine-Tuning</li><li><strong>BERT<br>- </strong>Pre-training<br>- Input Representation<br>- BERT in Downstream Tasks</li></ol><p>4. <strong>Comparison of GPT-2, BERT and ELMo</strong></p><h3>ELMo</h3><p><a href="https://arxiv.org/abs/1802.05365"><strong>ELMo</strong></a> stands for <strong>Embeddings from Language Model</strong>,<strong> </strong>as the name suggests in this models the deeply contextualized word embeddings are created from the Language Models (LM).</p><p>ELMo uses bidirectional language model (biLM) which is pre-trained on a large text corpus, to learn both words (e.g., syntax and semantics) and linguistic context (i.e., to model polysemy). BiLM capture <strong>context-dependent </strong>aspects of word meaning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eFh5yDpdy9nInndCC0V0uw.png" /><figcaption>BiLM based on ELMo, Figure: From <a href="http://colah.github.io/posts/2015-09-NN-Types-FP/"><em>“Neural Networks, Types, and Functional Programming”</em></a><em> by Christopher Olah</em></figcaption></figure><p><strong>Bidirectional Language Model<br></strong>Given a sequence of n tokens, (x₁, x₂, …, xₙ), a forward language model computes the probability of the sequence by modeling the probability of token tₖ given the history (x₁, x₂, …,xk-1):</p><p>In the forward pass, the history contains words before the target token,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*JqWtVgL1PkHIEvUoBrAqHQ.png" /></figure><p>In the backward pass, the history contains words after the target token,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*j4IvRODX3AC0tV1Yf1fGUw.png" /></figure><p>A biLM combines both a forward and backward LM, and train the model to maximize the probability of likelihood i.e. minimize the negative log-likelihood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*NaFU6u7pNf5zfpZKQiwKAw.png" /></figure><p><strong>ELMo Representation<br></strong>each token xₖ, an L-layer biLM computes a set of 2L + 1 representations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*jwi3Xl1PVbQCsF5IBO5WEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/171/1*VLDO-IGJhbD4esLNk3Gfzg.png" /><figcaption>Outputs from both LSTM are concatenated together to form Hi,l</figcaption></figure><p>The weights,<strong> </strong>sᵗᵃˢᵏ,<strong> </strong>in the linear combination, are learned for each end task and normalized by softmax. The scaling factor γᵗᵃˢᵏ is used to correct the misalignment between the distribution of biLM hidden states and the distribution of task-specific representations. Both sᵗᵃˢᵏ and γᵗᵃˢᵏ are learnable parameters in LM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*XBHLs14FVoXdNTGZF1v-BQ.png" /><figcaption>Here, Vi= ELMoᵗᵃˢᵏ = Task-specific weighting</figcaption></figure><p>ELMo is applied on <strong>semantic-intensive</strong> and <strong>syntax-intensive</strong> tasks respectively using representations in different layers of biLM</p><ul><li>For a <strong>semantic-intensive</strong> task, the <strong>top layer</strong> is better than the first layer.</li><li>And for a <strong>syntax-intensive </strong>task,<strong> the first layer</strong> is better than top layers.</li></ul><p><strong>ELMo for Downstream Tasks<br></strong>This representation can be easily added to existing models and significantly improve the state-of-the-art across six challenging NLP problems, including question answering, textual entailment and sentiment analysis.</p><h3>OpenAI GPT-2</h3><p>The <a href="https://openai.com/blog/better-language-models/">OpenAI GPT-2</a> is the successor of the <a href="https://blog.openai.com/language-unsupervised/">GPT</a> model. GPT-2 is a large <a href="https://arxiv.org/abs/1706.03762">transformer</a>-based language model, with <strong>generative pre-training</strong> of a language model on a diverse corpus of <strong>unlabeled text</strong>, followed by discriminative <strong>fine-tuning</strong> on each specific task.</p><p>GPT has two major differences from ELMo:</p><ol><li>The model architecture: ELMo uses the concatenation of forward and backward LSTMs, but GPT uses <strong>multi-layer transformers decoder</strong>.</li><li>Contextualized embedding: ELMo uses unsupervised Feature-based approach, while GPT fine-tunes the same base model for all end tasks.</li></ol><p><strong>Transformer Decoder as Language Model<br></strong>Unlike <a href="https://arxiv.org/abs/1706.03762">original transformer</a> architecture, the <a href="https://arxiv.org/abs/1801.10198">transformer decoder</a> model discards the encoder part, so there is only one single input sentence rather than two separate source and target sequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CUp-WtzkBh_x6aBIIzcdHQ.png" /><figcaption>Figure: From <a href="https://lilianweng.github.io/lil-log/2019/01/31/generalized-language-models.html">Lil’Log</a> by <a href="https://lilianweng.github.io/lil-log/contact.html">Lilian</a>.</figcaption></figure><p>Transformer block contains a masked <strong><em>multi-headed self-attention</em></strong> followed by <strong><em>pointwise feed-forward</em> layer</strong> and normalization layers in between. The final output produces a distribution over target tokens after softmax.</p><p>The likelihood probability of the next word, same as <a href="https://lilianweng.github.io/lil-log/2019/01/31/generalized-language-models.html#elmo">ELMo</a>, but <strong>without backward</strong> computation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*JqWtVgL1PkHIEvUoBrAqHQ.png" /></figure><p><strong>Supervised Fine-Tuning<br></strong>After training the model, we use the parameters for the <strong>supervised task</strong>. We assume a labelled dataset, where each instance consists of a sequence of input tokens(x₁, x₂, …, xₙ), and an output label <em>y</em> for it.</p><p>This transformer model (GPT) can be used for <strong>fine-tuning</strong> on different tasks. First convert all structured inputs into token sequences to be processed by pre-trained model, followed by a linear+softmax layer.</p><p>The basic model architecture of <strong>various NLP tasks </strong>is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zJymmx5uwcqAPqRjHHYETQ.png" /><figcaption><em>(Image source: </em><a href="https://s3-us-west-2.amazonaws.com/openai-assets/research-covers/language-unsupervised/language_understanding_paper.pdf"><em>original paper</em></a><em>)</em></figcaption></figure><p>At the first stage, generative pre-training of a language model can absorb as much free text as possible (<strong>unsupervised </strong>learning). Then at the second stage, the model is fine-tuned on specific tasks with a small labelled dataset and a minimal set of new parameters to learn, This method is <strong>semi-supervised sequence learning</strong> (<a href="https://arxiv.org/abs/1511.01432"><em>original paper</em></a>).</p><p><strong>Drawbacks:</strong> GPT is its <strong>uni-directional</strong> nature — the model is only trained to predict the future <strong>left-to-right context</strong>.</p><h3>BERT</h3><p><a href="https://arxiv.org/pdf/1810.04805.pdf">BERT</a> stands for <strong>B</strong>idirectional <strong>E</strong>ncoder <strong>R</strong>epresentations from <strong>T</strong>ransformers, as the name suggests this model is based on bidirectional representations from the <strong>unlabeled text</strong> by jointly conditioning on both <strong>left and right context</strong> in all layers. As a result, BERT is one of the most breakthroughs ideas in the last few years.</p><p>Compared to GPT, the largest difference and improvement of BERT is to make training <strong>bi-directional</strong>. The paper claim that:</p><blockquote>“bidirectional nature of our model is the single most important new contribution”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTlf55tRT8NbyE6dyKVKQQ.png" /><figcaption><em>(Image source: BERT: </em><a href="https://arxiv.org/abs/1810.04805"><em>original paper</em></a><em>)</em></figcaption></figure><p><strong>Pre-Training BERT<br></strong>Pre-training BERT uses two unsupervised tasks, that are <strong>Masked LM</strong> and <strong>Next Sentence Prediction (NSP) </strong>to train.</p><p>Task 1:<strong> Masked Language Model</strong> (MLM)<br>Learning the context <strong>around a word</strong> rather than learning just after the word makes it able to better capture its meaning, both syntactically and semantically, you can read more about this <strong>cloze</strong> procedure in <a href="https://journals.sagepub.com/doi/abs/10.1177/107769905303000401"><em>this paper</em></a><em>.</em></p><p>The training data generator chooses <strong>15% of the token </strong>positions at <strong>random</strong> for <strong>prediction</strong>. If the iᵗʰ token is chosen, we replace the iᵗʰ token with</p><p>1. The <strong>[MASK]</strong> token <strong>80%</strong> of the time<br>2. A <strong>random</strong> token <strong>10%</strong> of the time<br>3. The <strong>unchanged</strong> iᵗʰ token <strong>10%</strong> of the time<br>Ti will be used to predict the original token with <strong>cross-entropy loss</strong></p><p>Task 2: <strong>Next Sentence Prediction </strong>(NSP)<br>Many important downstream tasks such as Question Answering (QA) are based on the relationship between <strong>two sentences</strong>, which is not directly captured by language modeling.</p><p>Training a <strong><em>binary classifier</em></strong> for telling whether one sentence is the next sentence of the other, this pre-training will <strong>improve efficiency</strong> in tasks like <strong><em>QA</em> and <em>NLI</em></strong>.</p><p><strong>Input Representation<br></strong>BERT input representation. The input embeddings are the sum of the token embeddings, the segmentation embeddings and the position embeddings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8RQ2bSb4VEvlwBx_mui7NA.png" /><figcaption><em>(Image source: BERT: </em><a href="https://arxiv.org/abs/1810.04805"><em>original paper</em></a><em>)</em></figcaption></figure><p><strong>Positional embeddings</strong> help to store position-related information in<strong> whole sequence</strong> and <strong>segment embedding</strong> stores position with respect to sentences.</p><p><strong>BERT in Downstream Tasks<br></strong>This model is trained on huge corpus i.e. English Wikipedia (2,500M words) and BooksCorpus (800M words) which makes it a state-of-the-art model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owff4Qx7aWDWu0cPFqlYGQ.png" /><figcaption>Various Architecture of BERT model for different NLP tasks, <em>(Image source: BERT </em><a href="https://arxiv.org/abs/1810.04805"><em>original paper</em></a><em>)</em></figcaption></figure><p>BERT performs <strong>state-of-the-art results </strong>in many <strong>NLP task</strong> such as :</p><ul><li>Multi-Genre Natural Language Inference (MNLI)</li><li>Quora Question Pairs (QQP)</li><li>Question Natural Language Inference (QNLI)</li><li>The Stanford Sentiment Treebank (SST-2)</li><li>The Corpus of Linguistic Acceptability (CoLA)</li><li>The Semantic Textual Similarity Benchmark (STS-B)</li><li>Microsoft Research Paraphrase Corpus (MRPC)</li><li>Recognizing Textual Entailment (RTE) etc.</li></ul><p>For more info of every task, you can view Appendix section of the <a href="https://arxiv.org/pdf/1810.04805.pdf">original paper</a></p><h3>Comparison of BERT, GPT-2 and ELMo</h3><p>The comparisons between the model architectures are shown visually below. Note that in addition to the architecture differences, <strong>BERT and OpenAI GPT </strong>are <strong>finetuning approaches</strong>, while<strong> ELMo</strong> is a <strong>feature-based approach</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vsHLTyAb3bHeWiQAxM8TTg.png" /><figcaption><em>Comparison of BERT, OpenAI GPT and ELMo, (Image source: BERT </em><a href="https://arxiv.org/abs/1810.04805"><em>original paper</em></a><em>)</em></figcaption></figure><ul><li>BERT and GPT are transformer-based architecture while ELMo is Bi-LSTM Language model.</li><li>BERT is purely <strong>Bi-directional</strong>, GPT is <strong>unidirectional </strong>and ELMo is semi-bidirectional.</li><li>GPT is trained on the <strong>BooksCorpus (800M words)</strong>; BERT is trained on the <strong>BooksCorpus (800M words)</strong> and <strong>Wikipedia (2,500M words)</strong>.</li><li>GPT uses a sentence separator ([SEP]) and classifier token ([CLS]) which are only introduced at fine-tuning time; BERT learns [SEP], [CLS] and sentence A/B embeddings during pre-training.</li><li>GPT was trained for 1M steps with a batch size of 32,000 words; BERT was trained for 1M steps with a batch size of 128,000 words.</li><li>GPT used the same learning rate of 5e-5 for all fine-tuning experiments; BERT chooses a task-specific fine-tuning learning rate which performs the best on the development set.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*Lj56XHrgpIhj-pxnLUqTkg.png" /><figcaption>Summary of various models, Figure: From <a href="https://lilianweng.github.io/lil-log/2019/01/31/generalized-language-models.html">Lil’Log</a> by <a href="https://lilianweng.github.io/lil-log/contact.html">Lilian</a>.</figcaption></figure><p><strong>References:</strong></p><ul><li>BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding: (<a href="https://arxiv.org/pdf/1810.04805.pdf">original paper)</a></li><li>Generalized Language Models: (<a href="https://lilianweng.github.io/lil-log/2019/01/31/generalized-language-models.html">Original post</a>) by Lilian Wang.</li><li>Deep contextualized word representations: ELMo (<a href="https://arxiv.org/pdf/1802.05365.pdf">original paper</a>)</li><li>Improving Language Understanding with Unsupervised Learning: GPT (<a href="https://openai.com/blog/language-unsupervised/">Original Paper</a>)</li><li>Language Models are Unsupervised Multitask Learners: GPT-2 (<a href="https://openai.com/blog/better-language-models/">Original paper</a>)</li></ul><blockquote>Thanks for reading, You can connect with me on <a href="http://linkedin.com/in/gauravghati/">LinkedIn</a>, <a href="https://twitter.com/GauravGhati/">Twitter</a> or my <a href="http://gauravghati.world/">portfolio</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ad140cd1cda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Github Pages for creating global APIs]]></title>
            <link>https://medium.com/data-science/using-github-pages-for-creating-global-api-76b296c4b3b5?source=rss-c2dc95c5f41------2</link>
            <guid isPermaLink="false">https://medium.com/p/76b296c4b3b5</guid>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[global-api]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[github-pages]]></category>
            <dc:creator><![CDATA[Gaurav Ghati]]></dc:creator>
            <pubDate>Wed, 01 Apr 2020 13:17:43 GMT</pubDate>
            <atom:updated>2021-10-06T02:43:19.907Z</atom:updated>
            <content:encoded><![CDATA[<h4>This article is all about creating a globally hosted <strong>static API </strong>and using it for your website’s API.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Euo0Y1oxpa7JOg_OrL9omw.jpeg" /></figure><p>So, I accidentally figured out that we can return <strong>JSON</strong> responses instead of the standard HTML when we access any <strong>GitHub Pages</strong> site. So, I thought instead of creating a static website why not do some dev fun ;) and create a REST API for the data that I need.</p><p>For example, if you type this on terminal</p><pre><strong>curl https://gauravghati.github.io/apis/home.json</strong></pre><p>Gives the following result:</p><pre>{<br>    &quot;name&quot;: &quot;Gaurav Ghati&quot;,<br>    &quot;phone&quot;: &quot;+91 9067365762&quot;,<br>    &quot;mail&quot;: &quot;gauravghati225@gmail.com&quot;,<br><br>    &quot;bio&quot;: &quot;MY BIO&quot;,<br>    &quot;fun&quot;: &quot;FUN STATEMENT&quot;,<br><br>    &quot;github&quot;: &quot;https://github.com/gauravghati/&quot;,<br>    &quot;twitter&quot;: &quot;https://twitter.com/GauravGhati/&quot;,<br>    &quot;linkedin&quot;: &quot;http://linkedin.com/in/gauravghati/&quot;,<br><br>    &quot;aboutme&quot;: {<br>        &quot;para1&quot;: &quot;This is Paragraph 1&quot;,<br>        &quot;para2&quot;: &quot;This is Paragraph 2&quot;<br>    },<br><br>    &quot;volunteer&quot;: {<br>        &quot;tfi&quot;: {<br>            &quot;heading&quot;: &quot;Teach For India&quot;,<br>            &quot;description&quot;: &quot;description of TFI&quot;<br>        },<br>        &quot;pisb&quot;: {<br>            &quot;heading&quot;: &quot;PICT IEEE Student Branch&quot;,<br>            &quot;description&quot;: &quot;description of PISB&quot;<br>        }<br>    }<br>}</pre><p>I used this JSON API for <a href="http://gauravghati.herokuapp.com/">my website</a>, now each time when the website loads it makes a request to the Github pages link and fetch data from that URL and displays the fetched data on the website!</p><p>Now, whenever I want to edit any data on my website, I just have to change the JSON files and push them to my Github pages <a href="http://github.com/gauravghati/gauravghati.github.io/">repo</a>, the changes will automatically get displayed on the main website.</p><p>You can view the code of the website, <a href="https://github.com/gauravghati/dotworld">here</a>. It’s in Django.</p><h3><strong>Now, How to create your own API?</strong></h3><p>By using Github, we can host our JSON files data there, because it is a static site, the only limitation is that it only supports GET requests.</p><h4>Setup Github Pages</h4><p>Create a new repository on Github with the repository name “<strong>github_username.github.io</strong>.” after this your new GitHub pages repository is ready. The URL for this repository will be</p><blockquote><strong>https://github_username.github.io/</strong></blockquote><h4>Preparing JSON files</h4><p>Clone the above repository, or if you already have JSON files saved locally, run <strong><em>git init</em></strong> in that folder and add the above remote repository and then commit and push your .json file. After you push your files there, you can access your JSON response on hitting the URL:</p><blockquote>https://github_username.github.io/json_file.json</blockquote><h4>Accessing data by JSON API</h4><p>The data which we get after hitting the URL is in the form of JSON objects. which we can directly send to the frontend while rendering HTML pages.</p><p>When your backend is in<strong> python</strong> i.e. in <strong>Django or Flask</strong>, you can access the JSON file’s data as shown below:</p><pre>import urllib.request, json</pre><pre>github_link = &quot;https://github_username.github.io/json_file.json&quot;</pre><pre>with urllib.request.urlopen(github_link) as url: <br>   json_data = json.loads(url.read().decode())</pre><pre>print(json_data)</pre><p>this piece of code will print all your JSON data as the output.</p><p>And if you want data in <strong>JavaScript</strong> using <strong>JQuery</strong>, you can access the JSON file’s data as shown below:</p><pre>let github_link = ‘https://github_username.github.io/jsonfile.json&#39;;</pre><pre>$.getJSON(github_link, function(data) {<br>     //data is the JSON string<br>     console.log(data);<br>});</pre><p>So, this is how you can use Github pages for creating global APIs.</p><blockquote>Thanks for reading, You can connect with me on <a href="http://linkedin.com/in/gauravghati/">LinkedIn</a>, <a href="https://twitter.com/GauravGhati/">Twitter</a> or my <a href="http://gauravg.in/">portfolio</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76b296c4b3b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/using-github-pages-for-creating-global-api-76b296c4b3b5">Using Github Pages for creating global APIs</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>