<?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 Nabarun Barua on Medium]]></title>
        <description><![CDATA[Stories by Nabarun Barua on Medium]]></description>
        <link>https://medium.com/@nabarun.barua?source=rss-aebcc903ba8b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xw7EYVpDUJI1L4yx3lKx-Q.jpeg</url>
            <title>Stories by Nabarun Barua on Medium</title>
            <link>https://medium.com/@nabarun.barua?source=rss-aebcc903ba8b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:07:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nabarun.barua/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[How AI does Question-Answering!]]></title>
            <link>https://medium.com/@nabarun.barua/how-ai-does-question-answering-aafd05bc4bdc?source=rss-aebcc903ba8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/aafd05bc4bdc</guid>
            <category><![CDATA[questions-answers]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[hugging-face]]></category>
            <dc:creator><![CDATA[Nabarun Barua]]></dc:creator>
            <pubDate>Mon, 27 Feb 2023 19:10:09 GMT</pubDate>
            <atom:updated>2023-02-27T19:10:09.866Z</atom:updated>
            <content:encoded><![CDATA[<h3>Authors</h3><p>Nabarun Barua</p><p><a href="https://github.com/nabarunbaruaAIML">Git</a>/ <a href="https://www.linkedin.com/in/nabarun-barua-aiml-engineer/">LinkedIn</a>/ <a href="https://medium.com/@nabarun.barua">Towardsdatascience</a></p><p>Arjun Kumbakkara</p><p><a href="https://github.com/arjunKumbakkara">Git</a>/ <a href="https://www.linkedin.com/in/arjunkumbakkara/">LinkedIn</a>/ <a href="https://medium.com/@arjunkumbakkara">Towardsdatascience</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*v7QggF0zBNwSLfynWLYOlg.jpeg" /><figcaption>Credits: The 2AI Idiots</figcaption></figure><p>When we think to build a Question and Answer System, we find Huggingface Transformer does an extremely good job but Transformer will only work well when retrieving system retrieving documents works very well.</p><p>So our prime focus of the blog would be how to build an efficient retrieval system. Here we would like to explain Huggingface Dataset Library and Haystack which helps us in building such a system.</p><h3>Dataset Library</h3><p>Dataset Library has a mechanism where we can do similarity search on Dataset based on Embedding/Elastic Search, for Embedding based search we first convert long passages into a single embedding which can be later used as a retrieval system. After Converting passages into embeddings, we would convert Questions into Embeddings. Now with the FAISS Indexing mechanism of Dataset, we can compare the two embeddings and get the most similar passage from the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*r6osUYst3d4qahxJjEMZFg.png" /><figcaption>Credits: <a href="https://huggingface.co/">https://huggingface.co</a></figcaption></figure><p>Elastic Search is pretty much similar to FAISS Search but unlike FAISS, ElasticSearch retrieves documents based on exact matches in the search context.</p><h3>Therefore, Huggingface supports two types of Retrieval Systems which is very useful for NLP Tasks like Question and Answer systems where we would like to retrieve specific documents relevant to the Task.</h3><p><strong>1. FAISS:</strong> FAISS is a Similarity-based search that finds Euclidean distance(by computing the dot-product similarity) or some other similarity metric between two vectors. Here we convert documents into Embedding Vectors which are then saved and when users ask Query that query is first converted into an embedding vector then we do a similarity-based search by taking Euclidean distance(by computing the dot-product similarity) or some other similarity metric between Documents &amp; Query Vector.</p><p>Now to convert Documents &amp; Queries to Embedding Vectors. There are two approaches:</p><ul><li>We can use any Encoder-based transformer and use “pool” or average our token embeddings in some way. One popular approach is to perform CLS pooling</li><li>Another approach is to use Dense Passage Retrieval Transformers/Models which are developed especially for efficient passage retrieval for Question &amp; Answering system</li></ul><p>Let’s see how can we do it technically</p><ul><li>First, we see Encoder based transformer, we can use any transformer for this purpose but a popular Model which is specifically trained for sentence similarity is from sentence transformers which we will use here.</li></ul><p>Load the Check Point <em>“sentence-transformers/multi-qa-mpnet-base-dot-v1”</em> and Dataset</p><pre>from transformers import AutoTokenizer, AutoModel<br>import torch<br>from datasets import load_dataset<br><br>model_ckpt = &quot;sentence-transformers/multi-qa-mpnet-base-dot-v1&quot;<br>tokenizer = AutoTokenizer.from_pretrained(model_ckpt)<br>model = AutoModel.from_pretrained(model_ckpt)<br>device = torch.device(&quot;cuda&quot;) if torch.cuda.is_available() else torch.device(&quot;cpu&quot;) <br>model.to(device)<br>ds = load_dataset(&#39;crime_and_punish&#39;, split=&#39;train[:100]&#39;)<br># Here we are using CLS Pooling<br>ds_with_embeddings = ds.map(CLS_Pooling,batched=True)</pre><p><em>To understand Dataset Library please go through our earlier </em><a href="https://medium.com/mlearning-ai/forget-complex-traditional-approaches-to-handle-nlp-datasets-huggingface-dataset-library-is-your-1f975ce5689f"><em>blog 1</em></a><em> &amp; </em><a href="https://medium.com/mlearning-ai/forget-complex-traditional-approaches-to-handle-nlp-datasets-huggingface-dataset-library-is-your-fe5de16d88c8"><em>blog 2</em></a><em> on Dataset Library</em></p><p>Here our main target is to convert whole sentences, paragraphs, or documents into a single vector instead of Embedding/Vector for each token. This is achieved by pooling token embeddings in some way. Two popular approaches are CLS Pooling and Mean Pooling</p><p><strong>Mean Pooling</strong></p><pre>#Mean Pooling - Take attention mask into account for correct averaging<br>def Mean_Pooling(text_list): <br>    encoded_input = tokenizer(<br>        text_list[&quot;line&quot;], padding=True, truncation=True, return_tensors=&quot;pt&quot;<br>    )<br>    encoded_input = {k: v.to(device) for k, v in encoded_input.items()}<br>    attention_mask = encoded_input[&#39;attention_mask&#39;]<br>    model_output = model(**encoded_input)<br>    last_hidden_state = model_output[0] #First element of model_output contains all token embeddings<br>    input_mask_expanded = attention_mask.unsqueeze(-1).expand(last_hidden_state.size()).float()<br>    mean_pooling = torch.sum(last_hidden_state * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)<br>    return {&#39;embeddings&#39;:mean_pooling }</pre><p><strong>CLS Pooling</strong></p><pre>def CLS_Pooling(text_list):<br>    encoded_input = tokenizer(<br>        text_list[&quot;line&quot;], padding=True, truncation=True, return_tensors=&quot;pt&quot;<br>    )<br>    encoded_input = {k: v.to(device) for k, v in encoded_input.items()}<br>    model_output = model(**encoded_input)<br>    last_hidden_state = model_output[0]<br>    cls_pooling = last_hidden_state[:, 0]<br>    return {&#39;embeddings&#39;:cls_pooling}</pre><p>With any of the above pooling techniques with Transformer, we can convert documents into Embedding/Vectors.</p><ul><li>The second approach is Dense Passage Retrieval (DPR). This transformer model is specially designed for retrieving Passages for Question and Answer system. It first converts the Document into a vector i.e. Context which is later used in the retrieval mechanism. For Detail understanding please go through the <a href="https://towardsdatascience.com/how-to-create-an-answer-from-a-question-with-dpr-d76e29cc5d60">James Briggs Blog</a> and DPR Research <a href="https://arxiv.org/abs/2004.04906">Paper Link</a></li></ul><p>Initialize DPR Context Encoder for converting Documents into Vector/Embedding</p><pre>from transformers import DPRContextEncoder, DPRContextEncoderTokenizer<br>import torch<br>torch.set_grad_enabled(False)<br>ctx_encoder = DPRContextEncoder.from_pretrained(&quot;facebook/dpr-ctx_encoder-single-nq-base&quot;)<br>ctx_tokenizer = DPRContextEncoderTokenizer.from_pretrained(&quot;facebook/dpr-ctx_encoder-single-nq-base&quot;)</pre><p>Load your dataset and compute the vector/embedding representations</p><pre>from datasets import load_dataset<br>ds = load_dataset(&#39;crime_and_punish&#39;, split=&#39;train[:100]&#39;)<br>ds_with_embeddings = ds.map(lambda example: {&#39;embeddings&#39;: ctx_encoder(**ctx_tokenizer(example[&quot;line&quot;], return_tensors=&quot;pt&quot;))[0][0].numpy()})</pre><p><strong><em>To understand Dataset Library please go through our earlier </em></strong><a href="https://medium.com/mlearning-ai/forget-complex-traditional-approaches-to-handle-nlp-datasets-huggingface-dataset-library-is-your-1f975ce5689f"><strong><em>blog 1</em></strong></a><strong><em> &amp; </em></strong><a href="https://medium.com/mlearning-ai/forget-complex-traditional-approaches-to-handle-nlp-datasets-huggingface-dataset-library-is-your-fe5de16d88c8"><strong><em>blog 2</em></strong></a><strong><em> on Dataset Library</em></strong></p><p>With the above two steps, we can convert any document into embedding.</p><p><strong>The Next Step After Converting Documents into Embedding Vectors is to initialize this vector in the add_faiss_index of the Dataset</strong></p><p>To initialize the FAISS Index of the dataset, please follow the below code</p><pre>ds_with_embeddings.add_faiss_index(column=&#39;embeddings&#39;)</pre><p>Wala with the above code we have initialized FAISS Indexing &amp; now the dataset is ready for Query n Search.</p><p>But before we do anything else we need to save this Index first.</p><pre>ds_with_embeddings.save_faiss_index(&#39;embeddings&#39;, &#39;My_FAISS_Index.faiss&#39;)</pre><p>Now similarly if we have to load the same when starting the application.</p><pre>ds_with_embeddings = = load_dataset(&#39;crime_and_punish&#39;, split=&#39;train[:100]&#39;)<br>ds_with_embeddings.load_faiss_index(&#39;embeddings&#39;, &#39;My_FAISS_Index.faiss&#39;)</pre><p>Now we can build Question n Answer Application based on the above knowledge.</p><ul><li>First Fine-Tune a pre-trained model on Question &amp; Answer downstream task for a Dataset</li><li>On the same Dataset do the above steps and create embedding for FAISS Index. The field for the creation of Embedding could be Context or Question or text combining both.</li><li>Now as soon as the user enters a question in the front-end. Get the question from the front end &amp; convert the question into embedding then compare the embedding with FAISS Index and get the top (5 or 10) closest one’s context to be sent to Fine-Tuned Model to get predictions.</li></ul><p>Now point number 3 below development need to be executed.</p><pre>from transformers import DPRQuestionEncoder, DPRQuestionEncoderTokenizer<br>q_encoder = DPRQuestionEncoder.from_pretrained(&quot;facebook/dpr-question_encoder-single-nq-base&quot;)<br>q_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(&quot;facebook/dpr-question_encoder-single-nq-base&quot;)<br><br>question = &quot;Is Crime Rate Increasing ?&quot;<br>question_embedding = q_encoder(**q_tokenizer(question, return_tensors=&quot;pt&quot;))[0][0].numpy()<br>scores, retrieved_examples = ds_with_embeddings.get_nearest_examples(&#39;embeddings&#39;, question_embedding, k=10)<br>retrieved_examples[&quot;line&quot;][0]</pre><p>With this FAISS based searching came to end. Now let’s Understand ElasticSearch</p><p><strong>2. ElasticSearch: </strong>ElasticSearch search is based on exact matches on the designated Field example ‘context’. Elastic Search is pretty much similar to FAISS Search.</p><p>Elastic Search requires installation. Please follow the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/setup.html">Installation Guide</a></p><p><strong>Load the Dataset</strong></p><pre>from datasets import load_dataset<br>squad = load_dataset(&#39;squad&#39;, split=&#39;validation&#39;)</pre><p><strong>Add Elastic Search to Dataset and save the ElasticSearch</strong></p><pre>squad.add_elasticsearch_index(&quot;context&quot;, host=&quot;localhost&quot;, port=&quot;9200&quot;, es_index_name=&quot;hf_squad_val_context&quot;)</pre><p><strong>Execute the query Search</strong></p><pre>query = &quot;machine&quot;<br>scores, retrieved_examples = squad.get_nearest_examples(&quot;context&quot;, query, k=10)<br>retrieved_examples[&quot;title&quot;][0]</pre><p><strong>Load the Elastic Search Index if Name is provided</strong></p><pre>from datasets import load_dataset<br>squad = load_dataset(&#39;squad&#39;, split=&#39;validation&#39;)<br>squad.load_elasticsearch_index(&quot;context&quot;, host=&quot;localhost&quot;, port=&quot;9200&quot;, es_index_name=&quot;hf_squad_val_context&quot;)<br>query = &quot;machine&quot;<br>scores, retrieved_examples = squad.get_nearest_examples(&quot;context&quot;, query, k=10)</pre><p>Like above, now the only thing left is building QnA Application.</p><ul><li>First Fine-Tune a pre-trained model on Question &amp; Answer downstream task for a Dataset</li><li>On the same Dataset do the above steps and Elastic Search.</li><li>Now as soon as the user enters a question in the front-end. Get the question from the front-end &amp; put it in the function get_nearest_examples and get the top (5 or 10) closest one’s context to be sent to Fine-Tuned Model to get predictions.</li></ul><h3>Haystack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1jiq-JNT3Oble3dS.png" /><figcaption>Credits: <a href="https://haystack.deepset.ai/">https://haystack.deepset.ai/</a></figcaption></figure><p>Haystack is an open-source framework for building search systems that work intelligently over large document collections. Recent advances in NLP have enabled the application of question-answering, retrieval, and summarization to real-world settings and Haystack is designed to be the bridge between research and industry.</p><p>Haystack is a system that has both the retriever based on the input and reader function that is tightly coupled with Transformer Library. It can be done using In-memory, Elastic Search, FAISS &amp;, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mKCeQF--eqCBkwtp.png" /><figcaption>Credits: <a href="https://haystack.deepset.ai/">https://haystack.deepset.ai/</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HzHG75Ay7VWrMCAG.png" /><figcaption>Credits: <a href="https://haystack.deepset.ai/">https://haystack.deepset.ai/</a></figcaption></figure><p>First approach which we would see using Elastic Search &amp; BM25</p><ul><li>We first need to install Elastic Search. Please follow <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/setup.html">Installation Guide</a>. The default port used by Elastic Search is 9200</li><li>Next, we need to create Document Store. Here we store our unstructured Data.</li></ul><pre>from haystack.document_stores.elasticsearch import ElasticsearchDocumentStore<br><br># Return the document embedding for later use with dense retriever <br>document_store = ElasticsearchDocumentStore(return_embedding=True)</pre><ul><li>Next, we store our dataset in the document store. In the document store, we store two main components i.e. Content &amp; Label. The below code will show how to prepare Content &amp; Label from Dataset</li></ul><p>Content: Here we store the Context or Passages from where Answer has to be extracted.</p><p>Label: Here we store the question, answer &amp; context. This is useful if training needs to be done.</p><pre>from datasets import load_dataset<br>from haystack import Label, Answer, Document<br>import pandas as pd<br><br>subjqa = load_dataset(&quot;subjqa&quot;, name=&quot;electronics&quot;)<br>dfs = {split: dset.to_pandas() for split, dset in subjqa.flatten().items()}<br><br>#Content<br>for split, df in dfs.items():<br>    # Exclude duplicate reviews<br>    docs = [{&quot;content&quot;: row[&quot;context&quot;], &quot;id&quot;: row[&quot;review_id&quot;],<br>             &quot;meta&quot;:{&quot;item_id&quot;: row[&quot;title&quot;], &quot;question_id&quot;: row[&quot;id&quot;], <br>                     &quot;split&quot;: split}} <br>        for _,row in df.drop_duplicates(subset=&quot;context&quot;).iterrows()]<br>    document_store.write_documents(documents=docs, index=&quot;document&quot;)<br><br>#Label<br>labels = []<br>for i, row in dfs[&quot;test&quot;].iterrows():<br>    # Metadata used for filtering in the Retriever<br>    meta = {&quot;item_id&quot;: row[&quot;title&quot;], &quot;question_id&quot;: row[&quot;id&quot;]}<br>    # Populate labels for questions with answers<br>    if len(row[&quot;answers.text&quot;]):<br>        for answer in row[&quot;answers.text&quot;]:<br>            label = Label(<br>                query=row[&quot;question&quot;], answer=Answer(answer=answer), origin=&quot;gold-label&quot;, document=Document(content=row[&quot;context&quot;], id=row[&quot;review_id&quot;]),<br>                meta=meta, is_correct_answer=True, is_correct_document=True,<br>                no_answer=False, filters={&quot;item_id&quot;: [meta[&quot;item_id&quot;]], &quot;split&quot;:[&quot;test&quot;]})<br>            labels.append(label)<br>    # Populate labels for questions without answers<br>    else:<br>        label = Label(<br>            query=row[&quot;question&quot;], answer=Answer(answer=&quot;&quot;), origin=&quot;gold-label&quot;, document=Document(content=row[&quot;context&quot;], id=row[&quot;review_id&quot;]),<br>            meta=meta, is_correct_answer=True, is_correct_document=True,<br>            no_answer=True, filters={&quot;item_id&quot;: [row[&quot;title&quot;]], &quot;split&quot;:[&quot;test&quot;]})  <br>        labels.append(label)<br>        <br>document_store.write_labels(labels, index=&quot;label&quot;)</pre><p><strong><em>It’s a good idea to flush Elasticsearch when restarting the Application</em></strong></p><pre>if len(document_store.get_all_documents()) or len(document_store.get_all_labels()) &gt; 0:<br>    document_store.delete_documents(index=&quot;document&quot;)<br>    document_store.delete_documents(index=&quot;label&quot;)</pre><ul><li>Next, we declare a retriever that actually retrieves relevant documents for the Reader. In the retriever, we pass Document Store.</li></ul><pre>from haystack.nodes.retriever import BM25Retriever<br><br>bm25_retriever = BM25Retriever(document_store=document_store)</pre><ul><li>Next, we declare the reader which finds Answers from retrieved documents. Here we can pass a model which is already Trained/Fine-Tuned by us or we can also train/fine-tune it here. Please follow the <a href="https://haystack.deepset.ai/tutorials/fine-tuning-a-model">Link</a> on how to fine-tune the reader model.</li></ul><pre>from haystack.nodes import FARMReader<br><br>model_ckpt = &quot;deepset/minilm-uncased-squad2&quot; #alternative larger models: deepset/roberta-base-squad2-distilled or deepset/xlm-roberta-large-squad2 or the tiny distilled model: deepset/tinyroberta-squad2<br>max_seq_length, doc_stride = 384, 128<br>reader = FARMReader(<br>                        model_name_or_path=model_ckpt, <br>                        progress_bar=False,<br>                        max_seq_len=max_seq_length, <br>                        doc_stride=doc_stride, <br>                        return_no_answer=True<br>                       )</pre><ul><li>Now putting everything together</li></ul><pre>from haystack.pipelines import ExtractiveQAPipeline<br><br>pipe = ExtractiveQAPipeline(reader=reader, retriever=bm25_retriever)<br><br>n_answers = 3<br>preds = pipe.run(query=query, params={&quot;Retriever&quot;: {&quot;top_k&quot;: 3, &quot;filters&quot;:{&quot;item_id&quot;: [item_id], &quot;split&quot;:[&quot;train&quot;]}}, <br>                                      &quot;Reader&quot;: {&quot;top_k&quot;: n_answers}})<br><br>print(f&quot;Question: {preds[&#39;query&#39;]} \n&quot;)<br><br>for idx in range(n_answers):<br>    print(f&quot;Answer {idx+1}: {preds[&#39;answers&#39;][idx].answer}&quot;)<br>    print(f&quot;Review snippet: ...{preds[&#39;answers&#39;][idx].context}...&quot;)<br>    print(&quot;\n\n&quot;)</pre><p><strong>The second</strong> approach is with Dense Passage Retriever. Here everything will be the same as above except for the Retriever part. The rest others will be similar to the above.</p><pre>from haystack.nodes import DensePassageRetriever<br><br>dpr_retriever = DensePassageRetriever(document_store=document_store,<br>    query_embedding_model=&quot;facebook/dpr-question_encoder-single-nq-base&quot;,<br>    passage_embedding_model=&quot;facebook/dpr-ctx_encoder-single-nq-base&quot;,<br>    embed_title=False)<br><br>document_store.update_embeddings(retriever=dpr_retriever)</pre><p>With this, we have touched base with the major points for document retrieval systems i.e. Haystack and Datasets Library. Hope this document adds value to your knowledge and with this, we have come to the end of the Blog.</p><p>If you like this Blog please show your love and give us a thumbs up, star us, and if not please do give us feedback in the comment section. Here’s hoping that you will have fun with the Blog!</p><p>For Collaboration, Help, and Learning things together -</p><h4>Join our Discord Server: <a href="https://discord.gg/Z7Kx96CYGJ">https://discord.gg/Z7Kx96CYGJ</a></h4><p>GodSpeed!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aafd05bc4bdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Transformer and making it Uncool Again]]></title>
            <link>https://medium.com/@nabarun.barua/understanding-transformer-and-making-it-uncool-again-92cc210de2f4?source=rss-aebcc903ba8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/92cc210de2f4</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <dc:creator><![CDATA[Nabarun Barua]]></dc:creator>
            <pubDate>Thu, 29 Sep 2022 18:23:37 GMT</pubDate>
            <atom:updated>2022-10-15T13:29:39.903Z</atom:updated>
            <content:encoded><![CDATA[<h3>Authors</h3><p>Nabarun Barua</p><p><a href="https://github.com/nabarunbaruaAIML">Git</a>/ <a href="https://www.linkedin.com/in/nabarun-barua-aiml-engineer/">LinkedIn</a>/ <a href="https://medium.com/@nabarun.barua">Towardsdatascience</a></p><p>Arjun Kumbakkara</p><p><a href="https://github.com/arjunKumbakkara">Git</a>/ <a href="https://www.linkedin.com/in/arjunkumbakkara/">LinkedIn</a>/ <a href="https://medium.com/@arjunkumbakkara">Towardsdatascience</a></p><blockquote>Inspiration of this work has come from Jay Alammar’s Blogs and Lewis Tunstall’s book. These have been a great source of inspiration both technically and empirically.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*2lIky3ANT61DZ5aPi12Zdg.jpeg" /></figure><p>The original <a href="https://arxiv.org/pdf/1706.03762.pdf">Transformer Paper</a> published earlier had Encoder &amp; Decoder Architecture that was used for Translation, since then Transformers have come a long way and there are multiple Transfomer Architectures that have been published recently. Transformers which have been published till now can be broadly classified into 3 categories <strong>Encoder, Decoder &amp; Encoder — Decoder.</strong></p><p><strong>Encoder:</strong> In Encoder architecture, there are multiple Encoders in a stacked fashion. Each Encoder has multi-head self-attention layers followed by Fully — Connected Feed-Forward networks and in between self-attention &amp; Fully Connected layers, there is a mechanism that skips connections &amp; performs layer normalization. Since Neural Networks only understand integer (rather numerical representations.), we convert sentences into tokens after adding special tokens (CLS &amp; SEP in case of BERT), tokens to Word Embeddings and lastly adding positional embedding (this is true in case of BERT based Transformers). These word embeddings are fed to the encoder and it is important to note that the output from the encoder is also of the same size as the input. The main responsibility of the encoder is to add contextual information to the input sequences which means at the end, after passing through the encoder, for instance, let’s say the word ‘Apple’ will have different embeddings when it’s taken with the context of the phone brand than with that of a fruit.</p><p>Now that we understood the basics, let’s dive deeper into the encoder. <strong>Self-Attention</strong> as a mechanism, allows neural networks to assign a different amount of weight or “attention” to each element in a particular sequence. Put simply, the prime purpose of it is to make sure that each token does not end up with the same fixed embedding. Instead, we can use the whole sequence to compute a weighted average of each embedding.</p><p>Another way to formulate this is to say that given a sequence of token embeddings x₁….,xₙ self-attention produces a sequence of new embeddings x’₁….,x’ₙ where each xᵢ is a linear combination of all the xⱼ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*NdZAXbu9MPvfsiLKbSVTzA.png" /></figure><p>The coefficients wⱼᵢ are called <strong><em>attention weights</em></strong> and are normalized so that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*Pl-9cdVdkxdHVIiEIgQB1A.png" /></figure><p>So let us understand this with an example</p><p>Sentence 1: “I love Apple iphone”</p><p>Sentence 2: “I love to eat Apple”</p><p>In sentence 1, the word ‘Apple’ signifies a phone company whereas in sentence 2 Apple signifies a fruit . Hence, the fixed embedding for apple will not work here so it’s a good idea if we can create a representation for “Apple” that incorporates the accompanying context by combining all the token embeddings in different proportions, perhaps by assigning weightsⱼᵢ to the token embeddings for “iphone”. Embeddings that are generated in this manner are called contextualized embeddings.</p><p>Now, we have understood theoretically what the self-attention mechanism does in the encoder, let us see what happens under the hood in a much deeper way:</p><ul><li>We first project Word Embeddings into three vectors which are (1)Query, (2)Key &amp; (3)Value vectors. Now to get these vectors, we have to multiply word Embeddings with three matrices named query, key &amp; value matrix.</li><li>Here we calculate the Attention Score. We take the dot product (multiply) of Query &amp; Key Vector of the respective tokens we’re scoring for i.e.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*HOSBRnrzUa4jB2lEZANvsQ.png" /></figure><p>Attention Scores i.e. Queries and keys that are similar will have a large dot product. The main objective here is to find combinations that are similar and Dot Product is a similarity function in this case.</p><ul><li>Since the Dot Product can produce a very large numerical value. Therefore, we have to normalize it, otherwise, it can destabilize the training process. So we divide the Attention scores with the Square Root of the dimension of the Key matrix then normalize it with a softmax to ensure all the column values sum to 1. The resulting <em>n</em> × <em>n</em> matrix now contains all the attention weights, wⱼᵢ.</li><li>Now that we have got the attention weight, it’s time to update the token embeddings by multiplying Value Vector with the attention weight.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*66Lq3pzdrQUl_o9E4bimMg.png" /></figure><p>Now, Initially, we have read multi-head self-attention and the aforementioned process is just single self—attention. In reality, there are multiple such self—attention in a layer which help us to focus on different semantic aspects of the sequence. But, if you still have a question as to why do we need more than one attention head? The simple answer is that the softmax of one head tends to focus on mostly one aspect of similarity. Having several heads allow the model to focus on several aspects at once. This is similar to CNN, where, in a single CNN layer, we will have multiple Filters learning different things at once.</p><p>Now that we have understood Multi-head Attention, It is time to understand the Feed Forward Network. Every encoder stack has multi-head attention followed by the feed-forward network. The Feed Forward Network is a two-layer fully connected neural network. This network doesn’t process the complete sequence of Embedding as a single vector instead it processes each embedding separately. As a thumb rule, the first layer output size will be four times the input size and GELU is the most common Activation Function used in these layers. This is the place where most parameters are added to the network.</p><p>Transformer architecture also has layer normalization and skip connections. Normalization Layer normalizes each input in the batch to have zero mean and unity variance. Now positioning of Layer Normalization can be done in two ways i.e. Post layer normalization &amp; Pre layer normalization</p><ul><li><strong>Post-layer normalization:</strong> This type of arrangement was there in the Transformer research paper which places layer normalization in between the skip connections. This arrangement is difficult to train from scratch as the gradients can diverge. This was controlled by using the learning rate warm-up where the learning rate is gradually increased from a small value to some maximum value during training.</li><li><strong>Pre-layer normalization: </strong>In this type of arrangement, layer normalization is performed within the span of the skip connections. This results in stable training and you might not require any learning rate warm-up.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zsRzFVjWixyciWebF-jeww.png" /></figure><p>Skip connections, on the other hand, work exactly the same as in ‘Resnet’ Architecture. It passes a tensor to the next layer of the model without processing and adds it to the processed tensor.</p><p>The position and order of the words are essential parts of any language. They define the grammar and thus the actual semantics of a sentence. As a last thing in the <strong>Encoder Topic</strong>, we will discuss Positional Embeddings which is applied to the Embedding generated from Tokens. The simple idea is to add positional information in token Embeddings since the whole sentence is processed parallelly therefore model will not have any sense as to which token came first.</p><p>Approaches that are available for Positional Embeddings.</p><ul><li>The most popular approach is Learnable Positional Embedding. It works similar to token embeddings but uses the position index instead of the token ID as input. This approach is an efficient way of encoding the positions of tokens which is learned during pretraining. Both Embeddings are finally summed so that positional information is added to the token embeddings. Learnable position embeddings are easy to implement and widely used.</li><li>Another approach is Absolute positional Embedding, here transformer model uses static patterns consisting of modulated sine and cosine signals to encode the positions of the tokens.</li></ul><p>Examples: BERT, DistilBERT, RoBERTa, XLM, XLM-RoBERTa, ALBERT, ELECTRA, DeBERTa and etc.</p><p><strong>Decoder:</strong> On the decoder side, the overall mechanism is the same as the Encoder, the only difference is that Decoder has two Attention sublayers in the decoder stack.</p><ul><li>Masked multi-head self-attention layer: The task of this layer is to ensure that the current predicted token is always generated based on past output.</li><li>Encoder-Decoder Attention Layer: This layer in the decoder stack gets Output from the top encoder i.e. Key and Value vector, and at each decoder stack this layer gets this key &amp; value vector from the top encoder. Here the intermediate representations of the decoder(Value from Masked multi-head self-attention layer) acts as the queries. Just like encoder, Query, Key and Value vectors are used for calculations to get contextual embeddings and like in the case of Encoder, the Feed Forward network is used for further processing to give final embedding.</li></ul><p>Example: GPT, GPT-2, CTRL, GPT-3, GPT-Neo/GPT-J-6B and etc.</p><p><strong>Encoder-Decoder:</strong> This type of Transformer Model is being used where we need tasks like sequence to sequence generation. For instance, text generation, translation, summarization &amp; etc. Above knowledge learnt in Encoder &amp; Decoder sections are being used here in combination.</p><p>Example: T5, BART, BigBird, Pegasus &amp; etc.</p><p>If you like this blog post, please show your love and give us a thumbs up, star us and if not please do give us feedback in the comment section. Here’s hoping that you had fun understanding the Transformer!</p><p>For Collaboration, Help and Learning things together -</p><h4>Join our Discord Server : <a href="https://discord.gg/Z7Kx96CYGJ">https://discord.gg/Z7Kx96CYGJ</a></h4><p>GodSpeed!</p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92cc210de2f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Meta-Learning the Huggingface Way]]></title>
            <link>https://medium.com/@nabarun.barua/meta-learning-the-huggingface-way-9422a08188ce?source=rss-aebcc903ba8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9422a08188ce</guid>
            <category><![CDATA[meta-learning]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Nabarun Barua]]></dc:creator>
            <pubDate>Mon, 09 May 2022 17:35:18 GMT</pubDate>
            <atom:updated>2022-05-09T20:48:59.123Z</atom:updated>
            <content:encoded><![CDATA[<h3>Authors</h3><p>Nabarun Barua</p><p><a href="https://github.com/nabarunbaruaAIML">Git</a>/ <a href="https://www.linkedin.com/in/nabarun-barua-aiml-engineer/">LinkedIn</a>/ <a href="https://medium.com/@nabarun.barua">Towardsdatascience</a></p><p>Arjun Kumbakkara</p><p><a href="https://github.com/arjunKumbakkara">Git</a>/ <a href="https://www.linkedin.com/in/arjunkumbakkara/">LinkedIn</a>/ <a href="https://medium.com/@arjunkumbakkara">Towardsdatascience</a></p><p>Meta-Learning is an exciting trend in Research and before we jump into Project implementation, we think that we should first understand Meta — Learning basics.</p><p>In the Traditional ML/DL approach, what we follow is we get a huge dataset and we start training on that dataset, and eventually, we get a good accuracy score.</p><p>Now, the Meta-Learning approach is like the way human learns, first it Learns in one domain &amp; after getting sufficient knowledge then it tries to learn in the next domain with a handful of examples based on the knowledge acquired in the past. In this way, by repeating this step multiple times, we can improve the accuracy of the model with limited training data. Now Meta-Learning works better than the traditional approach of Fine-Tuning on a huge Dataset where the dataset has many domains. However, in the traditional approach, a model at a time tries to learn on different random domains which increases the overall training time whereas in Meta-Learning Model learn a domain with k sample training data, and whatever learning is being learned is passed to the main model after every Epoch(Here for Every Main/Meta Epoch there are multiple Leaner Epoch termed as Inner Epoch)</p><p>There are multiple types of Meta-Learning:</p><ol><li>Metric-based meta-learning</li></ol><ul><li>Siamese Network</li><li>Matching Network</li><li>Prototypical Network</li><li>Relation Network</li></ul><p>2. Optimization-based meta-learning</p><ul><li>MAML (model-agnostic meta-learning)</li><li>FOMAML — First-Order MAML</li><li>Reptile</li></ul><p>Details for the above meta-learning techniques will be available in this <a href="https://arxiv.org/pdf/2007.09604.pdf">Paper</a></p><p>In our Project, we used Reptile a variant of MAML (model-agnostic meta-learning) from optimization-based meta-learning. In the root Meta_Learning.py we get a complete meta-learning training process.</p><p>Now in Our Project in Meta_Learning.py we have two Functions that are important</p><ul><li>Meta Task: This function creates n random Task i.e. n Domains for training with given K Samples for the Training set &amp; L samples for the Test set.</li><li>Leaner: This function trains for i epoch for each task given by Meta Task and updates the gradients to the main model at the end of the train for all the Tasks.</li></ul><p>For detailed process flow, please follow the flow chart below for overall Meta-Learning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*7XQln1ekmjIWpWkQU8A1UA.jpeg" /><figcaption>Meta-Flow Diagram</figcaption></figure><p>Now the Technical Stack:</p><ul><li>Huggingface Transformers</li><li>Huggingface Datasets</li><li>Huggingface Accelerate</li><li>Pytorch</li></ul><p>For the above Technical stack, a basic understanding is needed. We are using Huggingface Datasets instead of Pytorch Datasets because Huggingface Datasets works on apache arrow format and Data processing is fast &amp; quick. For a better understanding, please go through our previous blogs <a href="https://medium.com/mlearning-ai/forget-complex-traditional-approaches-to-handle-nlp-datasets-huggingface-dataset-library-is-your-1f975ce5689f">Part 1</a> &amp; <a href="https://medium.com/mlearning-ai/forget-complex-traditional-approaches-to-handle-nlp-datasets-huggingface-dataset-library-is-your-fe5de16d88c8">Part 2</a>. We are using Huggingface <a href="https://huggingface.co/docs/accelerate/index">Accelerate</a> Library because we wanted a production-ready multi-GPU/CPU code that can be deployed without much effort. Simple configuration takes care of a single GPU/CPU or Multi-GPU approach without changing the code.</p><p>Now let’s discuss the project (<a href="https://github.com/nabarunbaruaAIML/Meta_Learning">Github Link</a>)</p><p>First step Start with setup the environment, we have different bash files that will create the local environment. Please select the bash file as per your need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*B92DgW2jyF8zKy3_fZeTEg.jpeg" /><figcaption>Bash Files Images</figcaption></figure><p>After setuping the local enviorment we are good to go for meta-learning but before we move to Meta-Learning python file. We should understand the dataset which we are using, below is the number of records per domain:</p><p>‘apparel’: 1717,</p><p>‘baby’: 1107,</p><p>‘beauty’: 993,</p><p>‘books’: 921,</p><p>‘camera_&amp;_photo’: 1086,</p><p>‘cell_phones_&amp;_service’: 698,</p><p>‘dvd’: 893,</p><p>‘electronics’: 1277,</p><p>‘grocery’: 1100,</p><p>‘health_&amp;_personal_care’: 1429,</p><p>‘jewelry_&amp;_watches’: 1086,</p><p>‘kitchen_&amp;_housewares’: 1390,</p><p>‘magazines’: 1133,</p><p>‘music’: 1007,</p><p>‘outdoor_living’: 980,</p><p>‘software’: 1029,</p><p>‘sports_&amp;_outdoors’: 1336,</p><p>‘toys_&amp;_games’: 1363,</p><p>‘video’: 1010,</p><p>‘automotive’: 100,</p><p>‘computer_&amp;_video_games’: 100,</p><p>‘office_products’: 100</p><p>We can see the last three domains, namely Automotive, Computer &amp; Video Games and Office Products have only 100 records, therefore, we take them for the Test set whereas the remaining others are in the Training set.</p><p>All the Configuration and Parameters to the Meta — Training is centrally given in the Config.yaml file &amp; Params.yaml file which can be changed to impact the training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*0pR-RqNGYD8MzRqec83BYw.jpeg" /><figcaption>Config &amp; Params Yaml File</figcaption></figure><p>Now to execute training in multi-GPU or single GPU or CPU, we need to configure Accelerate to do that we just need to execute a command</p><pre>accelerate config</pre><p>Once the above command executes then answer the simple questionnaire and it will generate a config file for Accelerate Library which will be picked automatically during training(This execution is done once to create a config file). This process is optional, if we want to execute our python file in the traditional way then Accelerate Library will execute with default parameters that fit well for a single GPU Training.</p><p>The traditional way of executing the python file</p><pre>python my_script.py</pre><p>Now if we have a multi GPU Setup and we want to train, after completion of Configuration. Just need to execute the following command.</p><pre>accelerate launch my_script.py</pre><p>In our example, my_script.py is Meta_Learning.py file. Once executing the above command training will start.</p><p>And you can see the result in the Folder named Logs in running_logs.log file. With this, we come to the end of our blog post.</p><p>Inspiration for our work came from this <a href="https://github.com/mailong25/meta-learning-bert">Github</a> (Long Mai)which is implemented completely in PyTorch, kindly visit and check if you want to implement your implementation completely PyTorch way.</p><p>If you like this Blog please show your love and give us a thumbs up, star us and if not please do give us a feedback in the comment section. Here’s hoping that you will have fun with the implementation!</p><p>For Collaboration, Help and Learning things together -</p><h4>Join our Discord Server: <a href="https://discord.gg/Z7Kx96CYGJ">https://discord.gg/Z7Kx96CYGJ</a></h4><p>GodSpeed!</p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9422a08188ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forget Complex Traditional Approaches to handle NLP Datasets, HuggingFace Dataset Library is your…]]></title>
            <link>https://medium.com/@nabarun.barua/forget-complex-traditional-approaches-to-handle-nlp-datasets-huggingface-dataset-library-is-your-fe5de16d88c8?source=rss-aebcc903ba8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe5de16d88c8</guid>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Nabarun Barua]]></dc:creator>
            <pubDate>Sun, 20 Feb 2022 18:32:58 GMT</pubDate>
            <atom:updated>2022-02-21T07:00:31.543Z</atom:updated>
            <content:encoded><![CDATA[<h3>Forget Complex Traditional Approaches to handle NLP Datasets, HuggingFace Dataset Library is your saviour! Part-2</h3><h3>Authors</h3><p><strong>Nabarun Barua</strong></p><p><a href="https://github.com/nabarunbaruaAIML">Git</a>/ <a href="https://www.linkedin.com/in/nabarun-barua-aiml-engineer/">LinkedIn</a>/ <a href="https://medium.com/@nabarun.barua">Towardsdatascience</a></p><p><strong>Arjun Kumbakkara</strong></p><p><a href="https://github.com/arjunKumbakkara">Git</a>/ <a href="https://www.linkedin.com/in/arjunkumbakkara/">LinkedIn</a>/ <a href="https://medium.com/@arjunkumbakkara">Towardsdatascience</a></p><p>This is the continuation of earlier Part, here we will discuss some more advance thing if you want to read our <a href="https://medium.com/mlearning-ai/forget-complex-traditional-approaches-to-handle-nlp-datasets-huggingface-dataset-library-is-your-1f975ce5689f">Earlier Publised document</a>.</p><p>In this document we will focus on:</p><ul><li>Merging Dataset</li><li>Caching Dataset</li><li>And Cloud Storage</li><li>How to create Document Retrieval System</li></ul><h3>Merging Dataset</h3><p>There may be situations where a Data Scientist may have to Merge multiple Datasets together to form a single dataset. There are two ways by which we can merge datasets:</p><h4><strong>Concatenate</strong></h4><p>In this we can merge different Dataset who have same number of columns and share the same column types if axis is zero.</p><p>If axis is one then we can concatenate the two dataset if the number of rows are same in the Dataset.</p><p>Let see with an example (Example taken from huggingface.co)</p><pre>from datasets import concatenate_datasets, load_dataset  <br>bookcorpus = load_dataset(&quot;bookcorpus&quot;, split=&quot;train&quot;)     <br>wiki = load_dataset(&quot;wikipedia&quot;, &quot;20200501.en&quot;, split=&quot;train&quot;)     wiki = wiki.remove_columns(&quot;title&quot;)  # only keep the text      assert bookcorpus.features.type == wiki.features.type     bert_dataset = concatenate_datasets([bookcorpus, wiki])</pre><h4>Interleave Dataset</h4><p>Here we can merge several dataset togather by taking alternate examples from each one to create new dataset. This is called Interleaving.</p><p>This can be used in both in regular Dataset as well as streaming datasets</p><p>In the below Example we are doing for Streaming Dataset(same can be done for Regular Dataset) and giving probabilities in the example which is optional. If probabilities are given then final Dataset is formed based on the same probability.(Example taken from huggingface.co)</p><pre>from datasets import interleave_datasets<br>from itertools import islice<br>en_dataset = load_dataset(&#39;oscar&#39;, &quot;unshuffled_deduplicated_en&quot;, split=&#39;train&#39;, streaming=True)<br>fr_dataset = load_dataset(&#39;oscar&#39;, &quot;unshuffled_deduplicated_fr&quot;, split=&#39;train&#39;, streaming=True)</pre><pre>multilingual_dataset_with_oversampling = interleave_datasets([en_dataset, fr_dataset], probabilities=[0.8, 0.2], seed=42)</pre><p>Around 80% of the final dataset is made of the en_dataset, and 20% of the fr_dataset.</p><h3>Caching Dataset</h3><p>When you download a dataset, the processing scripts and data are stored locally on your computer. The cache allows 🤗 Datasets to avoid re-downloading or processing the entire dataset every time you use it.</p><h4>Caching Directory</h4><p>We can change the default cache directory from current directory i.e. ~/.cache/huggingface/datasets. By simply setting the enviorment variable.</p><pre>$ export HF_DATASETS_CACHE=”/path/to/another/directory”</pre><p>Similarly we can do the same by passing parameter <em>cache_dir</em> in different keywords like load_dataset,load_metric &amp; etc.</p><p>Example</p><pre>from datasets import concatenate_datasets, load_dataset</pre><pre>bookcorpus = load_dataset(&quot;bookcorpus&quot;, split=&quot;train&quot;)<br>wiki = load_dataset(&quot;wikipedia&quot;, &quot;20200501.en&quot;, split=&quot;train&quot;,cache_dir=&quot;/path/to/another/directory&quot;)</pre><h4>Download Mode</h4><p>Once Dataset is downloaded it’s been cahced therefore again when we load the Dataset it doesn’t download from source rather it loads from cache.</p><p>Now in case there is any change in Dataset and if we want to load Dataset unchanged dataset from the source then we need to use parameter download_mode.</p><p>Example</p><pre>from datasets import concatenate_datasets, load_dataset</pre><pre>bookcorpus = load_dataset(&quot;bookcorpus&quot;, split=&quot;train&quot;)<br>wiki = load_dataset(&quot;wikipedia&quot;, &quot;20200501.en&quot;, split=&quot;train&quot;,download_mode=&#39;force_redownload&#39;)</pre><h4>Clean the Cached Files</h4><p>If there is a need to clean up thecached files then we can do it simply by executing the following command</p><pre># Below function just clears the cache of Dataset<br>ds.cleanup_cache_files()</pre><h4>Enable or disable caching</h4><p>There may be a situation when we don’t want to cache. In that situation, we can do disable caching locally or globally.</p><p><strong>Locally:</strong> If we’re using a cached file locally, it will automatically reload the dataset with any previous transforms you applied to the dataset. We can disable caching using Parameter load_from_cache=False, in datasets.Dataset.map().</p><p>Example:</p><pre>updated_dataset = small_dataset.map(tokenizer_function, load_from_cache=False)</pre><p>In the example above, 🤗 Datasets will execute the function tokenizer_function over the entire dataset again instead of loading the dataset from its previous state.</p><p><strong>Globally:</strong> If we want to disable the Caching Globally then below parameter need to be set for Disable caching on a global scale with datasets.set_caching_enabled():</p><pre>from datasets import set_caching_enabled<br>set_caching_enabled(False)</pre><p>When you disable caching, 🤗 Datasets will no longer reload cached files when applying transforms to datasets. Any transform you apply on your dataset will be need to be reapplied.</p><h3>Cloud Storages</h3><p>Huggingface Dataset can be stored to popular Cloud Storage. Hugginface Dataset has in-built feature to cater this need.</p><p>List of cloud which it supports and filesystem need to be installed to be directly used in Loading Dataset(Table taken from Huggingface.co):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*3xAbsnCqsrnxcE86RlqLJw.jpeg" /><figcaption>Cloud Table</figcaption></figure><p>Here we will try to show how to load and save Dataset with s3fs to a S3 bucket. For other clouds please see the documentation. Though other cloud filesystem implementations can be used similarly.</p><p>First to install the S3 Dependency with Dataset.</p><pre>pip install datasets[s3]</pre><p><strong>Load Dataset:</strong> Now to access the dataset from private S3 bucket by entering your aws_access_key_id and aws_secret_access_key</p><pre>import datasets<br>s3 = datasets.filesystems.S3FileSystem(key=aws_access_key_id, secret=aws_secret_access_key)</pre><pre># load encoded_dataset to from s3 bucket<br>dataset = load_from_disk(&#39;s3://a-public-datasets/imdb/train&#39;,fs=s3)</pre><p><strong>Save Dataset:</strong> After you have processed your dataset, you can save it to S3 with datasets.Dataset.save_to_disk():</p><pre>import datasets<br>s3 = datasets.filesystems.S3FileSystem(key=aws_access_key_id, secret=aws_secret_access_key)</pre><pre># saves encoded_dataset to your s3 bucket<br>encoded_dataset.save_to_disk(&#39;s3://my-private-datasets/imdb/train&#39;, fs=s3)</pre><h3>How to create Document Retrieval System</h3><p>Document Retrieval System is a specific example from dataset which is used in NLP Task such as Question &amp; Answer System. This document will show you how to build an index search for your dataset that will allow you to search items from your Dataset.</p><h4>FAISS(Facebook AI Similarity Search)</h4><p>Dataset has a mechanism where we can do similarity search on Dataset based on Embedding, here first convert long passages into a single a embeddings which can be later used as a retrieval system. After Converting passages into embeddings, we would convert Question into Embedding. Now with the FAISS Indexing mechanism of Dataset, we can compare the two embeddings and get the most similar passage from the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*qIpq1BYSJCus-TcSUmGNpA.png" /><figcaption>Credits: <a href="https://huggingface.co/">https://huggingface.co</a></figcaption></figure><p>To do that we have One such Model named DPR (Dense Passage Retrieval). Example taken from Huggingface Dataset Documentation. Feel free to use any other model like from sentence-transformers,etc.</p><p><strong>Step 1:</strong> Load the Context Encoder Model &amp; Tokenizer.</p><pre>from transformers import DPRContextEncoder, DPRContextEncoderTokenizer<br>import torch<br>torch.set_grad_enabled(False)<br>ctx_encoder = DPRContextEncoder.from_pretrained(&quot;facebook/dpr-ctx_encoder-single-nq-base&quot;)<br>ctx_tokenizer = DPRContextEncoderTokenizer.from_pretrained(&quot;facebook/dpr-ctx_encoder-single-nq-base&quot;)</pre><p><strong>Step 2:</strong> Load the Dataset and get embedding</p><p>As we mentioned earlier, we’d like to represent each entry as a single vector.</p><pre>from datasets import load_dataset<br>ds = load_dataset(&#39;crime_and_punish&#39;, split=&#39;train[:100]&#39;)<br>ds_with_embeddings = ds.map(lambda example: {&#39;embeddings&#39;: ctx_encoder(**ctx_tokenizer(example[&quot;line&quot;], return_tensors=&quot;pt&quot;))[0][0].numpy()})</pre><p><strong>Step 3:</strong> Add embedding to FAISS Search Index.</p><p>Now Using FAISS for efficient similarity search we will Create the index with datasets.Dataset.add_faiss_index()</p><pre>ds_with_embeddings.add_faiss_index(column=&#39;embeddings&#39;)</pre><p><strong>Step 4:</strong> Search Query using the FAISS Search Index</p><p>Now you can query your dataset with the embeddings index. Load the DPR Question Encoder, and search for a question with datasets.Dataset.get_nearest_examples()</p><pre>from transformers import DPRQuestionEncoder, DPRQuestionEncoderTokenizer<br>q_encoder = DPRQuestionEncoder.from_pretrained(&quot;facebook/dpr-question_encoder-single-nq-base&quot;)<br>q_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(&quot;facebook/dpr-question_encoder-single-nq-base&quot;)</pre><pre>question = &quot;Is it serious ?&quot;<br>question_embedding = q_encoder(**q_tokenizer(question, return_tensors=&quot;pt&quot;))[0][0].numpy()<br>scores, retrieved_examples = ds_with_embeddings.get_nearest_examples(&#39;embeddings&#39;, question_embedding, k=10)<br>retrieved_examples[&quot;line&quot;][0]</pre><p><strong>Step 5:</strong> Save FAISS Index</p><p>We can save the index on disk with datasets.Dataset.save_faiss_index()</p><pre>ds_with_embeddings.save_faiss_index(&#39;embeddings&#39;, &#39;my_index.faiss&#39;)</pre><p><strong>Step 6:</strong> Load the FAISS Index</p><p>Now to load the Index from disk can be done datasets.Dataset.load_faiss_index()</p><pre>ds = load_dataset(&#39;crime_and_punish&#39;, split=&#39;train[:100]&#39;)<br>ds.load_faiss_index(&#39;embeddings&#39;, &#39;my_index.faiss&#39;)</pre><h4>Elastic Search</h4><p>Unlike FAISS, ElasticSearch retrieves documents based on exact matches in the search context.</p><p>Please see the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/setup.html">Installation &amp; Configuration Guide for more information</a></p><p>Elastic Search is pretty much similar to the FAISS Search. Example taken from Standard Huggingface Dataset Documentation.</p><p><strong>Step 1:</strong> Load the the Dataset</p><pre>from datasets import load_dataset<br>squad = load_dataset(&#39;squad&#39;, split=&#39;validation&#39;)</pre><p><strong>Step 2:</strong> Add Elastic Search to Dataset</p><pre>squad.add_elasticsearch_index(&quot;context&quot;, host=&quot;localhost&quot;, port=&quot;9200&quot;, es_index_name=&quot;hf_squad_val_context&quot;)</pre><p><strong>Step 3:</strong> Execute the query Search</p><pre>query = &quot;machine&quot;<br>scores, retrieved_examples = squad.get_nearest_examples(&quot;context&quot;, query, k=10)<br>retrieved_examples[&quot;title&quot;][0]</pre><p><strong>Step 4:</strong> Load the Elastic Search Index if Name is provided</p><pre>from datasets import load_dataset<br>squad = load_dataset(&#39;squad&#39;, split=&#39;validation&#39;)<br>squad.load_elasticsearch_index(&quot;context&quot;, host=&quot;localhost&quot;, port=&quot;9200&quot;, es_index_name=&quot;hf_squad_val_context&quot;)<br>query = &quot;machine&quot;<br>scores, retrieved_examples = squad.get_nearest_examples(&quot;context&quot;, query, k=10)</pre><p>As promised , Here we are with the extension of our previous <a href="https://medium.com/mlearning-ai/forget-complex-traditional-approaches-to-handle-nlp-datasets-huggingface-dataset-library-is-your-1f975ce5689f">one stop guide to using HugginFace Datasets Library</a></p><p>If you like this Blog please show your love and give us a thumbs up , star us and if not please do give us a feedback in the comment section. Here’s hoping that you wil have fun with the library!</p><p>For Collaboration, Help and Learning things together -</p><p>Join our Discord Server: <a href="https://discord.gg/Z7Kx96CYGJ">https://discord.gg/Z7Kx96CYGJ</a></p><p>GodSpeed!</p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><p>🔵 <a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb"><strong>Become a Writer</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe5de16d88c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convert your bulky Transformer models into lightweight high performance ONNX models!]]></title>
            <link>https://medium.com/@nabarun.barua/convert-your-bulky-transformer-models-into-lightweight-high-performance-onnx-models-5b18bc25ee06?source=rss-aebcc903ba8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b18bc25ee06</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <dc:creator><![CDATA[Nabarun Barua]]></dc:creator>
            <pubDate>Mon, 07 Feb 2022 18:40:33 GMT</pubDate>
            <atom:updated>2022-02-08T04:39:50.891Z</atom:updated>
            <content:encoded><![CDATA[<h3>Authors</h3><p>Nabarun Barua</p><p><a href="https://github.com/nabarunbaruaAIML">Git</a>/ <a href="https://www.linkedin.com/in/nabarun-barua-aiml-engineer/">LinkedIn</a>/ <a href="https://medium.com/@nabarun.barua">Towardsdatascience</a></p><p>Arjun Kumbakkara</p><p><a href="https://github.com/arjunKumbakkara">Git</a>/ <a href="https://www.linkedin.com/in/arjunkumbakkara/">LinkedIn</a>/ <a href="https://medium.com/@arjunkumbakkara">Towardsdatascience</a></p><blockquote><strong>Synopsis:</strong> How we converted our ALBERT model trained for text classification to ONNX runtime and how it suddenly increased to 358.3 mb from 46.8 mb of size( .bin weights file).</blockquote><p>After we performed our extensive trials with optimizations on python before the conversion stage, we realized that we are focusing on the wrong area. Hence, we figures that the way out was to convert the .onnx converted weights to a compressed, quantized version. Details of which are laid out below:</p><h3>Why ONNX?</h3><ul><li>ONNX Runtime: cross-platform Since ONNX serves as a common format for all the prevalent machine learning, ai models. It becomes more of a defacto standard to convert your trained models(weights) into ONNX compliant ONNX models.For instance, to convert any model built in Tensorflow or Pytorch intially to another format is a painful task.There arises a lot of unprecedented issues and exceptions, resolving which could eat up your development/Experiment time .Hence, Its the best way of making sure that your model does not get into a framework lock. Cross-platform compliance makes it easy for deployment which we will discuss in the coming sections</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*tVrJyZpdH4UyaCQJnCfxEg.png" /><figcaption>ONNX interoperability | Image by <a href="https://towardsdatascience.com/onnx-preventing-framework-lock-in-9a798fb34c92#:~:text=ONNX%20is%20the%20acronym%20that,giants%20Microsoft%2C%20Facebook%20and%20Amazon.">Fernando López</a> | Logos taken from the original source</figcaption></figure><ul><li>Faster Inference: The inference is faster in the ONNX runtime as the runtime itself is built in C and as its the closest we can get to the machine.Its really fast in execution.</li><li>Env agnostic deployment : Although , your training stage would be in python , ONNX now gives the flexibility to deploy your trained weights into multiple other stacks or enviroments such as C#/C++/Java etc.</li></ul><p>In essence, ONNX helps achieve a high degree of Interoperability between architectures and hardwares.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*iaE86nXUprJqKWm3diCvyw.png" /><figcaption>Credit: opendatascience.com</figcaption></figure><h3>Conversion to ONNX:</h3><p>As can be seen below, conversion to ONNX runtime is a matter of calling an API (Pytorch)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/0*8scawoSbG_2WKjxl.jpeg" /></figure><p>For further understanding, feel free to sail over to this training pipeline built by us and check out the ONNX stage from it. Click <a href="https://github.com/nabarunbaruaAIML/CML_with_DVC_on_Transformer_NLP/blob/main/src/stage_04_onnx.py">ONNX</a> <a href="https://medium.com/mlearning-ai/continuous-machine-learning-on-huggingface-transformer-with-dvc-including-weights-biases-6a909983e48e">Note:If you want to understand the entire flow, then head over to this post </a>, which explains the entire training pipeline<a href="https://medium.com/mlearning-ai/continuous-machine-learning-on-huggingface-transformer-with-dvc-including-weights-biases-6a909983e48e">ith code and architecture.</a></p><h4>The Catch:</h4><p>The catch here could however be that a straight up conversion might spike the overall size of your model as can be seen in the images attached below (We have used ALBERT Transformer as an example) Post training of the model , the size obtained was 46.8 mb , But after a straight conversion to ONNX runtime as described in the above section the size increased 40x which is way too much for any inferencing activity. Thus , we had to undertake few work arounds which are explained below for your easier transition into ONNX runtimes and its effective use.</p><h3>Ways to optimize the conversion without the loss of any mettle!</h3><h4>First COMPRESSION: ONNX model size compression using removal of shared layers that can be considered a duplicate.</h4><p>Just a simple pythonic way of reducing the onnx converted model. This implementation is based on a tip by the Team ONNX .</p><p>Original weights size:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VNa965Ugk5VKWxBI.png" /></figure><p>However the size upon conversion spiked to 358.3 mb.</p><p>Onnx weights size:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_GdtIyVD-mVyqI2P.png" /></figure><h4>Excerpt from ONNX Team on the Correctness of the solution:</h4><p>“ ALBERT model has shared weights among layers as part of the optimization from BERT . The export torch.onnx.export outputs the weights to different tensors as so model size becomes larger. Using the below python Script we can remove duplication of weights, and reduce model size ie, Compare each pair of initializers, when they are the same, just remove one initializer, and update all reference of it to the other initializer.”</p><p><strong>“””ONNX Team @tianleiwu”””</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/0*LqbFQ1mj1QKaPJHj.png" /></figure><p>Post implementation :</p><p>Compressed Onnx weights size:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pNdg43ymbBOwxOlp.png" /></figure><p>Dependencies for your Reference:</p><pre>pip install --upgrade transformers sentencepiece<br>pip install --upgrade onnxruntime<br>pip install --upgrade onnxruntime-tools</pre><h4>Second Dynamic Quantization: Via performing quantization on a converted ONNX model.</h4><p>Up on Dynamic Quantization</p><pre>.....<br> quantize_dynamic(onnx_model_path,<br>                     quantized_model_path,<br>                     weight_type=QuantType.QInt8)......</pre><p>Here, onnxruntime.quantization.quantize to apply quantization on the HuggingFace BERT model. It supports dynamic quantization with IntegerOps and static quantization with QLinearOps. For activation ONNXRuntime supports only uint8 format for now, and for weight ONNXRuntime supports both int8 and uint8 format.Here we are using dynamic quantization for BERT model (Albert…etc too) and use int8 for weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OzXu2Wde0-oElkl4.png" /></figure><h4>Third: by Optimizer from ONNX Runtime .</h4><p><strong>However this is not recommended because , the num_heads,hidden_size if not chosen correctly can hamper the trained model.However , its straight forward to use .</strong></p><pre>.....<br># optimize transformer-based models with onnxruntime-tools<br>from onnxruntime_tools import optimizer<br>from onnxruntime_tools.transformers.onnx_model_bert import BertOptimizationOptions<br># disable embedding layer norm optimization for better model size reduction<br>opt_options = BertOptimizationOptions(&#39;bert&#39;)<br>opt_options.enable_embed_layer_norm = False<br>opt_model = optimizer.optimize_model(<br>    &#39;bert.onnx&#39;,<br>    &#39;bert&#39;, <br>    num_heads=12,<br>    hidden_size=768,<br>    optimization_options=opt_options)<br>opt_model.save_model_to_file(&#39;bert.opt.onnx&#39;)</pre><p>This could give you a lot of warnings as ‘onnxruntime_tools ‘ is deprecated now. Thus we recommend that you use the First method which is the best easiest and works like a charm! P.S: We tested these for any unwanted deviations. Turns out there’s none and it works perfectly.</p><p>Each way has its pros and cons please choose the approach based on your inference metrics.</p><p>If you like this Blog please show your love and give us a thumbs up, star us and if not please do give us a feedback in the comment section. Here’s hoping that this helped you understand the importance of Accelerated inferencing.</p><p>For Collaboration, Help and Learning things together — Join our Discord Server: <a href="https://discord.gg/Z7Kx96CYGJ">https://discord.gg/Z7Kx96CYGJ</a></p><p>Github Repo: <a href="https://github.com/nabarunbaruaAIML/onnx_model_size_compression">https://github.com/nabarunbaruaAIML/onnx_model_size_compression</a></p><p>GodSpeed!</p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b18bc25ee06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forget Complex Traditional Approaches to handle NLP Datasets, HuggingFace Dataset Library is your…]]></title>
            <link>https://medium.com/@nabarun.barua/forget-complex-traditional-approaches-to-handle-nlp-datasets-huggingface-dataset-library-is-your-1f975ce5689f?source=rss-aebcc903ba8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f975ce5689f</guid>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Nabarun Barua]]></dc:creator>
            <pubDate>Wed, 02 Feb 2022 18:18:25 GMT</pubDate>
            <atom:updated>2022-02-10T17:29:10.058Z</atom:updated>
            <content:encoded><![CDATA[<h3>Forget Complex Traditional Approaches to handle NLP Datasets, HuggingFace Dataset Library is your saviour!</h3><h3>Authors</h3><p>Nabarun Barua</p><p><a href="https://github.com/nabarunbaruaAIML">Git</a>/ <a href="https://www.linkedin.com/in/nabarun-barua-aiml-engineer/">LinkedIn</a>/ <a href="https://medium.com/@nabarun.barua">Towardsdatascience</a></p><p>Arjun Kumbakkara</p><p><a href="https://github.com/arjunKumbakkara">Git</a>/ <a href="https://www.linkedin.com/in/arjunkumbakkara/">LinkedIn</a>/ <a href="https://medium.com/@arjunkumbakkara">Towardsdatascience</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ruXh6n5COF88eGDC.jpg" /><figcaption>Credit: HuggingFace.co</figcaption></figure><blockquote>Synopsis: This is to demonstrate and articulate how easy it is to deal with your NLP datasets using the Hugginfaces Datasets Library than the old traditional complex ways such as that of reductions , lambdas mapping and above all the to and fro conversion from csv to Dicts to Dfs to Json to whatnot !</blockquote><p>In the world of Data Science and Artificial Intelligence, Data plays an important role which is used either in training or to get insights. Anyone who has use either Tensorflow or Pytorch knows about Tensorflow/Pytorch Dataset Library or knows Pandas for Insights.</p><p>Now the important question to ask why do we need HuggingFace Dataset Library at all?</p><p>The answer to it is in four parts.</p><ol><li>Under the hood HuggingFace Dataset Library runs on <a href="https://arrow.apache.org/">Apache Arrow</a> memory format and <a href="https://arrow.apache.org/docs/python/index.html">pyarrow library</a> because of which Data Loading &amp; Processing is Lighting Fast. Dataset Library Treat each dataset as a memory-mapped file that helps mapping between RAM &amp; File Storage which allows library to access and process the dataset without needing load dataset fully into the memory. For more information on memory-mapped file read this <a href="https://en.wikipedia.org/wiki/Memory-mapped_file">link</a>. This also means less amount of RAM need to process the dataset.</li><li>HuggingFace Dataset Library also support different types of Data format to be loaded into memory. Example CSV, TSV, Text Files, JSON &amp; Pickled DataFrame.</li><li>And if need arise to work in DataFrame then simple property change in the Dataset makes it work as a DataFrame and all the function of DataFrame works here. When work of DataFrame is finished then we can simply reset the property back to Dataset. Under the hood, Memory-mapped is working which makes overall memory consumption much more efficient.</li><li>It also supports the Streaming Data or if Dataset is very Huge then in that condition we can load the data in the form of Streaming Dataset which is little different from normal Dataset i.e. Iteratorable Dataset.</li></ol><p>Now that we know why would like to use HuggingFace Dataset Library. We would study about the library in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*How3GkX1UnsaIA6o.png" /><figcaption>Credit: HuggingFace.co</figcaption></figure><h3>Loading Dataset</h3><p>First step starts from loading the dataset. We can load Dataset in Multiple ways which are as follows:</p><h4>Offline Dataset File:</h4><p>We can load the Dataset simply using a Function named load_dataset. As mentioned above we can load different format.</p><p>Example CSV</p><pre>from datasets import load_dataset</pre><pre>dataset1 =  load_dataset(&#39;csv&#39;, data_files= &#39;location/file1.csv&#39;)</pre><p>Example JSON</p><p>Simple JSON</p><p>{“a”: 1, “b”: 2.0, “c”: “foo”, “d”: false}</p><pre>from datasets import load_dataset</pre><pre>dataset2 =  load_dataset(&#39;json&#39;, data_files= &#39;location/file2.json&#39;)</pre><p>In case of nested JSON</p><p>{“version”: “0.1.0”, “data”: [{“a”: 1, “b”: 2.0, “c”: “foo”, “d”: false}, {“a”: 4, “b”: -5.5, “c”: null, “d”: true}] }</p><pre>from datasets import load_dataset</pre><pre>dataset3 =  load_dataset(&#39;json&#39;, data_files= &#39;location/file3.json&#39;, field= &#39;data&#39;)</pre><p>Example Text File</p><pre>from datasets import load_dataset</pre><pre>dataset4 =  load_dataset(&#39;text&#39;, data_files= &#39;location/file4.txt&#39;)</pre><p>Example Parquet</p><pre>from datasets import load_dataset</pre><pre>dataset5 =  load_dataset(&#39;parquet&#39;, data_files= &#39;location/file5.parquet&#39;)</pre><p>Note:Parquet is just another file storage format .An open source file format built to handle flat columnar storage data formats.</p><p>Example Loading Zip/TAR or common compressed file for JSON or anyother format</p><pre>from datasets import load_dataset</pre><pre>dataset6 =  load_dataset(&#39;json&#39;, data_files= &#39;location/file6.json.gz&#39;, field= &#39;data&#39;)</pre><p>Now if we don’t give split in above example then data will be loaded by default in Train split. To have train-test split while loading the Dataset we can do with following changes:</p><pre>from datasets import load_dataset</pre><pre>DataFile = {&#39;train&#39;:[&#39;location/file7.csv&#39;,&#39;location/file8.csv&#39;,&#39;location/file9.csv&#39;],&#39;test&#39;:&#39;location/file10.csv&#39;}</pre><pre>dataset7 =  load_dataset(&#39;csv&#39;, data_files= DataFile )</pre><p>Simialarly for other file format we can use above technique. Now if by chance we don’t have dataset file with train &amp; test then we can still split dataset by following ways</p><pre>from datasets import load_dataset</pre><pre>dataset8 =  load_dataset(&#39;csv&#39;, data_files= &#39;location/file8.csv&#39;)<br>dataset8 = dataset8[&#39;train&#39;]<br>dataset8 = dataset8.train_test_split(test_size=0.1)</pre><h4>Remote Dataset or Loading Dataset from URL</h4><p>In HuggingFace Dataset Library, we can also load remote dataset stored in a server as a local dataset. As a Data Scientists in real-world scenario most of the time we would be loading data from a remote server. We simpily have to give URL instead local path.</p><p>Example</p><pre>url = &quot;https://https://github.com/crux82/squad-it/raw/master/&quot;</pre><pre>data_files = {<br>    &quot;train&quot;: url + &quot;SQuAD_it-train.json.gz&quot;,<br>    &quot;test&quot;: url + &quot;SQuAD_it-test.json.gz&quot;,<br>}</pre><pre>dataset = load_dataset(&quot;json&quot;, data_files=data_files, field=&quot;data&quot;)</pre><p>Similarly approach can be taken for other data type.</p><h4>Loading Streaming Data</h4><p>Now a days Data are available in GB’s and TB’s because of that it’s not possible to load the complete dataset in the system. For such scenario’s we load dataset in stream format which is bit different. Normally load_dataset returns a data type of Dataset but in Streaming format it returns a data type of IterableDataset. We learn more about streaming Data later in detail.</p><p>We can load any dataset in streaming format by simply passing property streaming=True</p><p>Example</p><pre>url = &quot;https://https://github.com/crux82/squad-it/raw/master/&quot;</pre><pre>data_files = url + &quot;SQuAD_it-train.json.gz&quot;</pre><pre>dataset = load_dataset(&quot;json&quot;, data_files=data_files, field=&quot;data&quot;,split=&quot;train&quot;,streaming=True)</pre><h4>In-Memory Data</h4><p>HuggingFace Dataset Library also allows to create a dataset from a Dictionary &amp; DataFrame.</p><p>Example Dataset from Dictionary</p><pre>from datasets import Dataset</pre><pre>my_dict = {&#39;title&#39;:[&#39;Macbeth&#39;,&#39;Tempest&#39;,&#39;Julius Caesar&#39;],&#39;character&#39;:[&#39;King Duncan of Scotland&#39;,&#39;Prospero&#39;,&#39;Brutus&#39;]}</pre><pre>dataset = Dataset.from_dict(my_dict)</pre><p>Example Dataset from DataFrame</p><pre>from datasets import Dataset<br>import pandas as pd</pre><pre>my_dict = {&#39;title&#39;:[&#39;Macbeth&#39;,&#39;Tempest&#39;,&#39;Julius Caesar&#39;],&#39;character&#39;:[&#39;King Duncan of Scotland&#39;,&#39;Prospero&#39;,&#39;Brutus&#39;]}</pre><pre>df = pd.DataFrame(my_dict)</pre><pre>dataset = Dataset.from_pandas(df)</pre><h3>Preprocessing Dataset</h3><p>Now we know how to load the Dataset, it’s time to learn how to process the raw dataset. In general we may not get a clean Dataset and we have to process the dataset by cleaning and bring it to a level where we can sent it to model.</p><h4>Select Record in Dataset</h4><p>In the below example we’re taking first 1000 entries from the Dataset and returning data type is Dataset</p><p>We can select the record by following example</p><pre>sample = dataset[&#39;train&#39;].select(range(1000))</pre><p>Now similarly if we want to see the actual data then we can do the same by simple change which will return data type Dictionary.</p><pre>sample = dataset[&#39;train&#39;][0:1000]</pre><h4>Shuffle Dataset</h4><p>Now let’s say we want to select dataset but want data point to be shuffled before selecting Dataset or you want to shuffle complete dataset.</p><pre>sample = dataset[&#39;train&#39;].shuffle(seed=34).select(range(1000))</pre><h4>To get unique entries from the dataset column</h4><p>Requirement may araise where a Data Scientist may want to know what are the unique entries available in the column of a dataset.</p><p>with the below example we will get a list of unique entries</p><pre>list = dataset[&#39;train&#39;].unique(&quot;Title&quot;)</pre><h4>Sort Dataset</h4><p>Here Column must have Numerical values i.e. Column must be Numpy compatible, as columns values will be sorted according to their numerical values.</p><pre># It will sort the column in descending Order<br>sorted_dataset = dataset.sort(&#39;label&#39;,reverse=True)</pre><h4>Filter Dataset</h4><p>There may be a condition when a Data Scientist may want to get a specific type of Data from Dataset. So HuggingFace Dataset Library has a Function named Filter which extract data points which matches it’s filter condition.</p><p>In the below example if there is a Data point in Dataset for Column “Character_Name” having value none, in that condition that Data point will be skipped.</p><pre>dataset = dataset.filter(lambda x: x[&#39;Character_Name&#39;] is not None)</pre><h4>Renaming the Column</h4><p>HuggingFace Dataset Library allows you to rename the column of the Dataset. We can understand by the following example, here pass the Actual Column Name i.e. ‘Title’ and the Column Name to be renamed i.e. ‘Novel’.</p><pre>dataset = dataset.rename_column(&quot;Title&quot;, &quot;Novel&quot;)</pre><h4>Removing the Column</h4><p>Similar to Rename, their could be a scenario where Data Scientist need to remove columns from the Dataset. We can understand by the following example, here we pass the list of Columns which we want to remove from the Dataset.</p><pre>dataset = dataset.remove_columns([&#39;ID&#39;, &#39;Texts&#39;])</pre><h4>Cast Data Type for the Column</h4><p>Their could be a scenario where Data Scientist may have to change the Feature type of a column then in that scenario we can cast the column.</p><pre>dataset.features</pre><p>Output</p><pre>{&#39;sentence1&#39;: Value(dtype=&#39;string&#39;, id=None),<br>&#39;sentence2&#39;: Value(dtype=&#39;string&#39;, id=None),<br>&#39;label&#39;: ClassLabel(num_classes=2, names=[&#39;not_equivalent&#39;, &#39;equivalent&#39;], names_file=None, id=None),<br>&#39;idx&#39;: Value(dtype=&#39;int32&#39;, id=None)}</pre><p>As seen , we cast Data Type for the Column labels to text binaris such as ‘positive ‘ and ‘negative’</p><pre>from datasets import ClassLabel, Value<br>new_features = dataset.features.copy()<br>new_features[&quot;label&quot;] = ClassLabel(names=[&#39;negative&#39;, &#39;positive&#39;])<br>new_features[&quot;idx&quot;] = Value(&#39;int64&#39;)<br>dataset = dataset.cast(new_features)<br>dataset.features</pre><p>Output</p><pre>{&#39;sentence1&#39;: Value(dtype=&#39;string&#39;, id=None),<br>&#39;sentence2&#39;: Value(dtype=&#39;string&#39;, id=None),<br>&#39;label&#39;: ClassLabel(num_classes=2, names=[&#39;negative&#39;, &#39;positive&#39;], names_file=None, id=None),<br>&#39;idx&#39;: Value(dtype=&#39;int64&#39;, id=None)}</pre><h4>Flatten</h4><p>Sometimes a column can be a nested structure of several types and need is to extract the subfields into their own separate columns which can be done with Function Flatten.</p><pre>from datasets import load_dataset<br>dataset = load_dataset(&#39;squad&#39;, split=&#39;train&#39;)<br>dataset.features</pre><p>Output</p><pre>{&#39;answers&#39;: Sequence(feature={&#39;text&#39;: Value(dtype=&#39;string&#39;, id=None), &#39;answer_start&#39;: Value(dtype=&#39;int32&#39;, id=None)}, length=-1, id=None),<br>&#39;context&#39;: Value(dtype=&#39;string&#39;, id=None),<br>&#39;id&#39;: Value(dtype=&#39;string&#39;, id=None),<br>&#39;question&#39;: Value(dtype=&#39;string&#39;, id=None),<br>&#39;title&#39;: Value(dtype=&#39;string&#39;, id=None)}</pre><p>The answers field contains two subfields: text and answer_start. Flatten them with datasets.Dataset.flatten():</p><pre>flat_dataset = dataset.flatten()<br>flat_dataset</pre><p>Output</p><pre>Dataset({<br>    features: [&#39;id&#39;, &#39;title&#39;, &#39;context&#39;, &#39;question&#39;, &#39;answers.text&#39;, &#39;answers.answer_start&#39;],<br> num_rows: 87599<br>})</pre><h4>Map() method</h4><p>This is a special method that allows to update a Column/Columns or create a new Column/Columns in Dataset.</p><p>example of updating a column. Below we are lowering the title and updating the column.</p><pre>dataset = dataset.map(lambda x: x[&#39;Title&#39;].lower())</pre><p>example of creating a New Column. Below we are counting word in Column Title and saving in new Column.</p><pre>def compute_length(example):<br>    return {&quot;length&quot;: len(example[&quot;Title&quot;].split())}<br>dataset = dataset.map(compute_length)</pre><p>Now in the above example, we are processing the values one at a time which we are not using full potential of the Library. Here we can do the same stuff in Batches by simiply adding a property batched=True (the batch size is configurable but defaults to 1,000).</p><pre>def compute_length(example):<br>    return {&quot;length&quot;: [len(i.split()) for i in example[&quot;Title&quot;]]}<br>dataset = dataset.map(compute_length,batched=True)</pre><p>Use of this Function can be best seen when using with Fast Tokenizer.</p><p>Below example taken from <a href="http://huggingface.co/"><em>HuggingFace.co</em></a> which shows the relative comparison for Fast &amp; slow tokenizers with batch &amp; without batch on a dataset.</p><pre>Options	            Fast tokenizer	Slow tokenizer<br>batched=True	    10.8s	        4min41s<br>batched=False	    59.2s	        5min3s</pre><p>By above example we can see that if batched is true then it’s 30 times faster in executing the function.</p><p>This Fucntion also support parallelism i.e. property num_proc. But do remember using num_proc to speed up your processing is usually a great idea, as long as the function you are using is not already doing some kind of multiprocessing of its own. In Below example we have used multiprocessing with Fast tokenizer but that is not advisable since Fast tokenizer already works internally on parallelism. For better understanding please go through the <a href="http://huggingface.co/"><em>HuggingFace.co</em></a>. Below example taken from HuggingFace which shows relative comparison for Fast &amp; slow tokenizer with num_proc,batch &amp; without batch,num_proc on a dataset.</p><pre>Options	                      Fast tokenizer	 Slow tokenizer<br>batched=True	              10.8s	         4min41s<br>batched=False	              59.2s	         5min3s<br>batched=True, num_proc=8      6.52s	         41.3s<br>batched=False, num_proc=8     9.49s	         45.2s</pre><p>Above are the major functions which are mostly used for day to day work.</p><h3>Dataset to DataFrame</h3><p>There could be a time when a Data Scientist would wish to see data in DataFrame and do some EDA on it. If Data Scientist is using HuggingFace Dataset Library then he/she can simply do it by setting this Function set_format to Pandas. Example</p><pre>dataset.set_format(&#39;pandas&#39;)</pre><p>This function only changes the output format of the dataset, so you can easily switch to another format without affecting the underlying data format, which is Apache Arrow. The formatting is done in place.</p><p>Now when we access elements of the dataset we get a pandas.DataFrame instead of a dictionary:</p><pre>DF = dataset[&#39;train&#39;][:3]</pre><p>Here all the Pandas functions will work as expected. And when work on the dataset is complete then we can reset it to arrow format. Example</p><pre>dataset.reset_format()</pre><h3>Streaming Dataset</h3><p>Above we have spoken about Streaming Dataset. Since Streaming Dataset are iteratorable Dataset therefore some processing functions are different here than normal datasets which will be explained.</p><h4>Map() method</h4><p>First change is how mapping function works if it’s used without batched = True then in Stream Dataset outputs are returned one by one whereas Normal Dataset complete Dataset is returned. Therefore for optimal use of streaming dataset, use Batched=True which will take batch data from streaming dataset. By default batch size is 1000 but configurable.</p><h4>Shuffle() method</h4><p>Unlike Shuffle in Normal Dataset which shuffles the entire dataset, here shuffle only shuffle the element of the batch that is predefined buffer_size.</p><h4>Take() &amp; Skip() method</h4><p>In Streaming Dataset select() method doesn’t work, instead we have two method take() &amp; skip() method which is similar to select() method.</p><p>Let’s say Buffer size is 1000 and we accessed one value from dataset then buffer is filled or replaced with 1001 place value.</p><p>For example if we want to take first 10 records:</p><pre>dataset = streamed_dataset.take(10)</pre><p>Similarly if we want to create training and validation splits from a streamed dataset</p><pre># Skip the first 1,000 examples and include the rest in the training set<br>train_dataset = streamed_dataset.skip(1000)<br># Take the first 1,000 examples for the validation set<br>validation_dataset = streamed_dataset.take(1000)</pre><p>There are lot’s of things to be told for this Library. Hence we have decided to make this a series based on usage level such as intermediate and advanced. Please watch out for the Advanced version of the same repo. You can click on ‘Watch’ and stay upto date using notifications.</p><h3>Advanced Concepts on Level Advanced</h3><ol><li>More on Parallelized File Systems</li><li>Cloud-based Storages, Retrieval and all pertinent operations.</li><li>Data Collation: Collate large chunks of data into processable units</li></ol><p>If you like this Blog please show your love and give us a thumbs up, star us and if not please do give us feedback in the comment section. Here’s hoping that you will have fun with the library!</p><p>For Collaboration, Help and Learning things together -</p><h4>Join our Discord Server: <a href="https://discord.gg/Z7Kx96CYGJ">https://discord.gg/Z7Kx96CYGJ</a></h4><p>GodSpeed!</p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f975ce5689f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Continuous Machine Learning on Huggingface Transformer with DVC including Weights & Biases…]]></title>
            <link>https://medium.com/@nabarun.barua/continuous-machine-learning-on-huggingface-transformer-with-dvc-including-weights-biases-6a909983e48e?source=rss-aebcc903ba8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a909983e48e</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[hugging-face]]></category>
            <dc:creator><![CDATA[Nabarun Barua]]></dc:creator>
            <pubDate>Wed, 26 Jan 2022 18:14:43 GMT</pubDate>
            <atom:updated>2022-02-03T12:33:55.189Z</atom:updated>
            <content:encoded><![CDATA[<h3>Continuous Machine Learning on Huggingface Transformer with DVC including Weights &amp; Biases implementation and Converting weights to ONNX.</h3><h3>Authors</h3><p><strong>Nabarun Barua</strong></p><p><a href="https://github.com/nabarunbaruaAIML">Git</a>/<a href="https://www.linkedin.com/in/nabarun-barua-aiml-engineer/">LinkedIn</a>/<a href="https://medium.com/@nabarun.barua">Towardsdatascience</a></p><p><strong>Arjun Kumbakkara</strong></p><p><a href="https://github.com/arjunKumbakkara">Git</a>/<a href="https://www.linkedin.com/in/arjunkumbakkara/">LinkedIn</a>/<a href="https://medium.com/@arjunkumbakkara">Towardsdatascience</a></p><h3>Synopsis:</h3><blockquote>Main idea of this project is to explain how CML can be implemented in an NLP Project therefore main focus of this Project is to explain how CML can be implemented. We assume that user is well verse in 🤗 Transformers , DVC, ONNX &amp; Weights&amp;Biases (Wandb) Implementations.</blockquote><p>Below are the online resource used for building this Project.</p><p>Below are the online resource used for building this Project.</p><ul><li><a href="https://www.youtube.com/playlist?list=PL7WG7YrwYcnDBDuCkFbcyjnZQrdskFsBz">DVC Youtube Playlist</a> and <a href="https://cml.dev/doc/self-hosted-runners?tab=AWS">DVC CML Official Doc</a></li><li><a href="https://huggingface.co/docs">Official Huggingface Website</a></li><li><a href="https://docs.wandb.ai/guides/integrations/huggingface">Weights &amp; Biases Official Doc</a></li></ul><p>Before we begin with the session few things that which need to be setup are as follows:</p><ul><li>One AWS IAM user with EC2 &amp; S3 Developer Access</li><li>S3 Bucket to store the Dataset</li><li>Second EC2 Spot Instance need to be requested in advance if not done earlier.</li></ul><p>Please follow these online Resource AWS related information</p><ul><li><a href="https://www.youtube.com/watch?v=rYHt0gtRKFg&amp;t=180s">Youtube Resource 1</a></li><li><a href="https://www.youtube.com/watch?v=GCt-cymgdvo">Youtube Resource 2</a></li><li><a href="https://towardsdatascience.com/choosing-the-right-gpu-for-deep-learning-on-aws-d69c157d8c86">For right GPU Selection</a> and for the same <a href="https://www.youtube.com/watch?v=4bVrIbgGWEA">Youtube Link</a></li></ul><p>In this project we want to implement Transformer Classification for <a href="https://www.kaggle.com/hassanamin/atis-airlinetravelinformationsystem">Kaggle Dataset</a>, idea is to implement DVC so that from DVC studio we can do the experiments, whereas in Transformers Weights &amp; Biases have an inbuilt implementation which allows saving Best Model’s weights &amp; Matrices.</p><p>We can use DVC for Metric tracking but for that further changes &amp; implementation need to be implemented. On the other hand, Weights &amp; Biases just need minimalist changes in any transformer code to start tracking. <strong>One major advantage which I see in using Weights &amp; Biases i.e. it saves the best model which otherwise we had to do after every experiment.</strong></p><p>Now I believe that we’re through with the goal and clear vision as in what we want to do in this project.</p><p>Lets begin by click and going into this <a href="https://github.com/nabarunbaruaAIML/project-template-with-DVC">Template Repository</a></p><p>Once into Template Repository Please click Button <strong>Use this Template</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*enMjJ0ZooH8txpac.jpg" /></figure><p>then fill Details and create repository from the template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hJecGYUHGvSS-DED.jpg" /></figure><h3>Overview:</h3><p><strong>Why DVC ?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/0*Od_0wyypEfGbV0yD.png" /></figure><p>Data processing or ML pipelines typically start a with large raw datasets for most usecases , inclusive of intermediate featurization and training stages .This then finally produces a final tuned model along with the needed accuracy metrics. Versioning of these large data files and directories alone is not sufficient.We also need to understand How the data is filtered, transformed , enriched (if the case be) , or used to finally train the ML models? DVC introduces a mechanism to capture and monitor those data pipelines — series of data processes that produce a final result (A final state as that of a graph). DVC pipelines and their data can also be easily versioned (using Git). This allows you to better organize your project, and reproduce your workflow when and where required and the results can totally ace it!</p><p><strong>Why S3?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OD8dMJS-H7vneGZX.jpg" /></figure><p>Amazon S3 is what we have used as a remote storage for Data .Firstly, starting with the platform github, we have restrictions storing data at scale in github (limit being as little as 100mb) .Secondly, as part of best practices , it is never considered safe to store data on Code repositories (be is privately hostel Github,Gitlab,Bitbucket etc) As the enterprise softwares thes days have a prerequisite to be GDPR compliant. The secrecy of data is of high importance. Now, Amazon S3 being one of the most reliable and secure storage , we chose it for our use case too. S3 is also highly agile and has the all-time availability trait.We may for the most part find it difficult to sometimes store and manage data, however, with S3 its such a breeze to manage data at such low costs. (You can also refer the Boto-core section above for integration information) So head over to amazon S3 setup the account and create a bucket with a decent storage. This bucker can then be connected to for file transferring using tools like Putty,MobaXterm,FileZilla etc. This way you can place the files and get the location .</p><p><strong>Why EC2?</strong></p><p>EC2 is a cost efficient virtual server in Amazon’s Elastic Compute Cloud for Amazon Web Services . Its highly elastic, scalable and reliable when it comes to Failover management and information security.There are out of the box features such as Elastic Load balancing which automatically distributes the traffic to the active instances and recovers the unhealthy instances. However , we would be using these features only during out deployment pipeline. So, to perform the model training, you would have to have an instance of the below kind at the least:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VJlYt8EqpXSbuqbf.png" /></figure><p>Because, as we know, Transformers are resource-intensive .</p><p><strong>Is there a Rigid File Structure for DVC?</strong></p><p>Yes, More than rigidity it means a standard which way it becomes very easy for organization and continuous iterations of change</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/0*_VBSiZZU_B5dLfRl.png" /></figure><p>As seen above, stage_01_load_save.py , stage_02_prepare_dataset.py , stage_03_train.py, stage_04_onnx.py &amp; stage_05_Model_Evalution.py are the stages of the DAG or the DVC pipeline. yaml files such as dvc.yaml( <strong>This File controls the Pipeline</strong>) , params.yaml ( <strong>This file Contains all the Parameters which are needed to perform experiments on Training Pipeline via DVC Studio</strong>) and config.yaml( <strong>This file contains all the configurations for the training pipeline</strong>) carries the major mandatory configurations. dvc.yaml being the control file here with all the Stage details like follows :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/0*6NVkRBqT7CS0hUDg.png" /></figure><p>The all_utils.py can be seen as a collection of operational python functions which is such that it is modular and reusable which constitutes File operations etc</p><p><strong>Architecture:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*TZea4ksJvW76EqlHiAME_Q.jpeg" /></figure><p>The architecture of this entire project is broadly divided into three</p><ol><li>Training</li><li>Deployment and</li><li>Retraining However the architecture pertinent to this repository can be seen in the below sections.</li></ol><h3>Stages and standard Files in DVC:</h3><p><strong>Stages:</strong></p><p>In this Training Pipeline , We have three major Stages linearly arranged.</p><ol><li>Load and Save Data (stage_01_load_save.py) : Here the data is loaded from the S3 bucket and tockenization is done.</li><li>Preparation of Dataset (stage_02_prepare_dataset.py) Here the train test splitting , pre-processing of data for model training.</li><li>Training the Model (stage_03_train.py) Here the model is training with the needed hyperparameters and Callbacks Finally, the model weights will be saved in the wandb (weight and Biases).Which is can fetched using wandb api. (please refer the respective documentation for more details)</li><li>Converting Model to Onnx (Stage_04_Onnx.py) Here we are converting our weights to Onnx runtime framework. Standard Transformer Onnx convertion is available but we feel that it’s not available for Sequence-Classification therefore we used our own logic to convert weights to Onnx runtime framework. Apart from converting we are also quantizing Onnx Model and pushing both to Weights &amp; Biases and S3 Bucket, reason being if weights &amp; Biases are not used by organization then person can still get the weights in S3 Bucket, also considering Information Security Compliance which is the need of the hour. It is recommended that the weights be stored in secure storages for instance S3 etc. We took reference for our development from this <a href="https://colab.research.google.com/github/neuml/txtai/blob/master/examples/18_Export_and_run_models_with_ONNX.ipynb#scrollTo=XMQuuun2R06J">Notebook by txtai</a>. If you’re new to Onnx then please refer Video from <a href="https://www.youtube.com/watch?v=7nutT3Aacyw">Abhishek Thakur</a> for understanding the basics of Onnx. He has explained it in easiest possible manner. One Issue we faced while implementing that was Albert Transformer model which was having size 46 MB when converted to Onnx was 341 MB which was strange for us, solution to it was given by Onnx Team which we implemented. Please refer this repository for the <a href="https://github.com/arjunKumbakkara/onnx_model_size_compression">Explanation</a>. <strong>Excerpt from ONNX Team on the Correctness of the solution:</strong> ALBERT model has shared weights among layers as part of the optimization from BERT . The export torch.onnx.export outputs the weights to different tensors as so model size becomes larger. Using the python Script of the <a href="https://github.com/arjunKumbakkara/onnx_model_size_compression/blob/main/weight_onnx_runtime_compression.py">Repo</a> we can remove duplication of weights, and reduce model size ie, Compare each pair of initializers, when they are the same, just remove one initializer, and update all reference of it to the other initializer.</li><li>In stage_05_Model_Evalution.py we are doing Onnx Model Evalution and Transfering Weights &amp; logs to S3 Bucket &amp; Weights &amp; Biases.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*uXPWXsT28WMwzXGYS3jh5A.jpeg" /></figure><p><strong>Standard Files:</strong></p><ol><li>dvc.yaml — This acts as the fulcrum file which organizes the stages defined into it linearly or otherwise . tags ‘deps’(These are the dependent files to that stage),’params’(All params from params.yaml pertinent to this stage),’outs’(The output files after the stage runs.) dvc.yaml basically houses the DAG relationship of the constituent stages.</li><li>params.yaml — This file is where all the configurable parameters are housed which needs to be changed on the go.This helps extensively in experiment management.ie, If you login via DVC studio , the params on this file alone can be changed and the pipeline can be run as experiments.</li><li>config.yaml — Configurations such as directories,filenames etc are housed here for on the fly changes.</li><li>ci-cd.yml — This is where the github action workflow is defined. Here we define the hook event(push, rebase,deploy etc) and the following chain of events .The highlight being its capability to register a cloud runner instance from all major cloud service providers (AWS,Azure,GCP,Digital Ocean or any custom cloud instance) only with API access keys configured as environment variables. Custom string of commands can also be configured to be run under the run section of the file for each job.</li><li>all_utils.py — This is a collection of all utility methods such as high level file operations using Shutil , loading, parsing , dumping of json, yaml etc.</li></ol><h3>Now follow the below steps for kickstarting the project:</h3><p><strong>STEP 01- Create a local repository after cloning the repository Newly created after using the Template Repo. We can use git bash for cloning if using the windows system. If Linux/Mac OS then Terminal will work.</strong></p><p><strong>STEP 02- Create a conda environment after opening the repository invscode</strong></p><pre>conda create --prefix ./env python=3.7 -y</pre><p>Activate the environment in the VSCode by executing the following command:</p><pre>conda activate ./env</pre><p>OR</p><pre>source activate ./env</pre><p><strong>STEP 03- install the requirements</strong></p><p>Here uncomment <strong>DVC</strong> before executing below command</p><pre>pip install -r requirements.txt</pre><p>After Executing the above command please <strong>comment the DVC</strong> in the requirements.txt file</p><p><strong>STEP 04- initialize the dvc project</strong></p><pre>dvc init</pre><p>Local Testing:</p><pre>dvc repro</pre><p>This can be used to run the pipeline with out the CML enabled github action.This will also fulfill the entire pipeline. However, in that case, the code command needs to be run from inside the code base on an instance say Ec2 or a local linux/win system with an appropriate GPU. If this needs to be done on CPU, make sure to update the transformer dependency in the requirements.txt to a cpu version.(please refer to the official document)</p><p><strong>STEP 05- Start EC2 Instance</strong></p><p>Since we are not using aws EC2 Spot instance therefore we are not creating instance in ci-cd.yml file. Therefore we need to have a GPU enabled EC2 Instance and in the terminal of EC2 execute following command.</p><pre>docker run --gpus all dvcorg/cml-py3 nvidia-smi</pre><p>then</p><pre>docker run --name myrunner -d --gpus all \<br>    -e RUNNER_IDLE_TIMEOUT=1800 \<br>    -e RUNNER_LABELS=cml,gpu \<br>    -e RUNNER_REPO=&quot;https://github.com/USER_ID/REPO_NAME&quot; \<br>    -e repo_token=REPO_Token \<br>    dvcorg/cml-py3</pre><p>Keep the EC2 Instance Running so that we can use it in GitHub Action. Once Workflow is finished, you can either shutdown or terminate the EC2 Instance. Also, the same instance which is latched with the github repository can be found listed as a runner in the cloud runner section of Github.</p><p><strong>STEP 06- commit and push the changes to the remote repository</strong></p><pre>git add .<br>git commit -m &quot;Detailed Commit for further reference&quot;<br>git push origin master    # Branch of choice</pre><p><strong>STEP 07- Push operation triggers for the Pipeline</strong></p><p>The push operation triggers the entire training pipeline as explained on top provided all required API keys and configurations are in place with the same sequence.</p><p><strong>STEP 08- Push as the Github Event:</strong></p><p>Github listens to Push as an Event by the github workflow .This then starts the pipeline defined in the workflow as can be seen below in the Actions tab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D-a6l9T8MZ-lP-bb.png" /></figure><p>The configured DVC stages are executed now one after the other in a EC2( Ubuntu 18 OS) configured instance (our case) else if the instance is not configured then github runs these on a spot instance internally and after the completion of the entire pipeline ,it also cleans up the resources utilized leaving us with only the Metrics and Best model saved.</p><p>As mentioned before, the order of execution of stages can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yAEyjsnX5RS-YbkV.png" /></figure><p>Detailed logs of the same can also be found by clicking the step: Now as seen below, the training starts and finishes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qT9G-nFtyQEYurJY.png" /></figure><p>Logs of custom level (info,debug,error) can also be customized and accessed from the EC2 instance as well if we are using a dedicated instance and not the spot instance of Github.</p><p><strong>STEP 09- Experiment Management:</strong></p><p>DVC Studio — <a href="https://studio.iterative.ai/">DVC Studio</a> This helps us in ML experiment tracking, visualization, and collaboration(While a team of developers work with different sets of experiments).DVC Studio does bookkeeping automatically too. See below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nPyQayN5xZKvAM_L.jpeg" /></figure><p>Since DVC Studio integrates with github smoothly, we can review and cherry pick each commit related to the experiments and this gives a whole lot of flexibility.</p><p><strong>STEP 10- Evaluation Metrics Management :</strong></p><p>wandb -Weights and Biases <a href="https://wandb.ai/site">Wandb</a> Although, DVC Studio This helps us in ML experiment tracking, visualization, and collaboration and best models if used , Weights and Biases(wandb) makes it even more easier by recording evaluation metrices and providing insights with plots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*caoC4GZH19Zv0x_t.jpeg" /></figure><p><strong>STEP 11- Best Model Selection :</strong></p><p>wandb -Weights and Biases <a href="https://wandb.ai/site">Wandb</a> As can be seen below are the best weights we have managed obtain on the different experiments .This is a very useful feature as finding the best weights can sometimes be a hassle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/0*F_iHKlF4hKdR4Mrr.png" /></figure><p><strong>STEP 12- Ending note :</strong></p><p>When all the steps are finished, the last event in the cml workflow is executed which is to comment on the thread.</p><pre>cml-send-comment report.md</pre><p>When this happens, the message notification will pop on the user banner as you can see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s1iivwm1Um41GSy4.jpeg" /></figure><p>The complete Training logs can also be found in report.md as we have configured the below steps in the cml workflow file (ci-cd.yaml)</p><p>See below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M0nJPDgqp-EbwYRG.jpeg" /></figure><h3>W.I.P : Deployment Pipeline will shortly follow this repository</h3><p><strong>Dockerized Container Application clusters with Kubernetes orchestration</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*-nqm36cdF49hU1xqpwTtwA.jpeg" /></figure><p>The Architecture will be as above for the repository that follows</p><p>Follow this Repository for updates: <a href="https://github.com/arjunKumbakkara/NLP_CML_Deployment_Pipeline_On_Kubernetes">Dockerized_CML_Application_On_KubernetesCluster</a></p><p>@misc{Transformer, wandb, DVC &amp; ONNX,title = {Continuous Machine Learning on Huggingface Transformer with DVC including Weights &amp; Biases implementation and Converting weights to ONNX},year = {2022},author = {Nabarun Barua, Arjun Kumbakkara},}</p><p><em>Originally published at </em><a href="https://github.com/nabarunbaruaAIML/CML_with_DVC_on_Transformer_NLP">https://github.com/nabarunbaruaAIML/CML_with_DVC_on_Transformer_NLP</a><em>.</em></p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a909983e48e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>