<?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 Mohit Pilkhan on Medium]]></title>
        <description><![CDATA[Stories by Mohit Pilkhan on Medium]]></description>
        <link>https://medium.com/@mahakal001?source=rss-3405b7e9c40c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RuSOOZKzWn1Zw4e1EWK3RA.jpeg</url>
            <title>Stories by Mohit Pilkhan on Medium</title>
            <link>https://medium.com/@mahakal001?source=rss-3405b7e9c40c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 02:12:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mahakal001/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[The First Infrastructure Decision That Will Define Your AI Future]]></title>
            <link>https://medium.com/@mahakal001/on-premise-compute-your-first-step-into-the-age-of-ai-902e45f68b92?source=rss-3405b7e9c40c------2</link>
            <guid isPermaLink="false">https://medium.com/p/902e45f68b92</guid>
            <category><![CDATA[on-premise]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Mohit Pilkhan]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 04:52:53 GMT</pubDate>
            <atom:updated>2026-03-20T17:59:39.579Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUI92a-3ehquFdZNPyDe6Q.png" /><figcaption>Own the compute. Own the future</figcaption></figure><p>The discourse surrounding Artificial Intelligence is often dominated by the cloud. However, attending a recent AI impact summit in India crystallized a thought that has been pending for too long: the critical and often overlooked importance of on-premise GPU and hardware accelerators in the modern AI era.</p><p>This article aims to provide a balanced, professional perspective on why organizations and individuals should reconsider the role of on-premise infrastructure.</p><h4>Defining “On-Prem” in the AI Context</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hj4-ljNnnMDgqrI_hJtBvg.png" /></figure><p>Before discussing the merits of on-premise versus cloud computing, it is essential to establish a clear definition of what “on-prem” means for AI workloads. The comparison is not always direct.</p><p>Typically, when we discuss hosting an application, we choose between on-premise infrastructure or a cloud provider. In the AI space, this choice manifests in two primary ways:</p><ol><li>Renting Infrastructure: You rent a cloud instance (e.g., from AWS, RunPod, or DigitalOcean) with a GPU and host your own models or applications. You pay for the compute by the hour.</li><li>Consuming Services: You use AI models via APIs (e.g., ChatGPT, Claude). You pay per token or per API call, with the underlying compute cost included in the price.</li></ol><p>The first model requires a certain level of technical expertise to manage instances and is typically used by development teams. The second model is more accessible and is used by a broader audience, or is necessary when using proprietary models that are only available via API.</p><p>It is important to first identify which category you fall into. For those focused on training or intensive computational tasks, the decision between on-prem and cloud becomes even more strategic, and a clear understanding of both is necessary to find the optimal solution.</p><h3>Cloud Compute is Oversold</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x6D0DGWh5jb689ZHM_-N-Q.png" /></figure><p>The concept of cloud computing is fundamentally sound, offering scalability and flexibility. However, its dominance in the tech narrative has arguably been oversold to the point where considering on-premise infrastructure is often viewed as an outdated practice. This perception can lead to a self-imposed limitation, where professionals hesitate to propose on-prem solutions for fear of being seen as behind the times.</p><p>For anyone who has been working to integrate AI into practical use cases, a few realities quickly become apparent. The initial hurdle is often simply securing access to suitable hardware. This is followed by the uncertainty of whether a given model or workflow will function correctly on that hardware. The subsequent experimentation phase involves a significant amount of discovery, where the primary goal is to establish an effective iteration loop. While online resources like articles and videos offer valuable insights, they cannot replace the confidence gained from hands-on experimentation.</p><p><em>A person with experience is never at the mercy of a person with opinion</em></p><h4><strong>The number One killer of curiousity: </strong>Lack of Access</h4><p>If you do not have a GPU(or GPUs :-) ) lying around, You will always hesitate to rent them on cloud just to play around thing. Even in tradional Software Engineering, people first make things work on local and then move it to cloud for deployment.</p><p>Consider two hypothetical organizations:</p><ul><li><strong>Organization A </strong>invests in on-premise hardware accelerators.</li><li><strong>Organization B </strong>relies on applying for grants and free credits from cloud providers.</li></ul><p>The employees in Organization A can discuss, test, and run new workflows as soon as they are released. This immediate access allows them to move beyond generic online opinions and develop a deep, practical understanding of cutting-edge AI tools. Over time, their internal conversations evolve from basic troubleshooting to strategic discussions about iteration, evaluation, and internal tooling. They are effectively building the competence to use any infrastructure, including the cloud, more effectively.</p><p>In contrast, Organization B remains in a perpetual state of procurement, waiting for access and falling behind in both technical expertise and innovative capacity.</p><h4>Cost Effectiveness:</h4><p>A practical cost analysis further supports the on-premise argument. For example, renting an RTX 5090 on a service like RunPod is approximately $0.89 per hour. If utilized continuously for a year, the total rental cost would be roughly $7,796 (INR 7.07 lakh). This is much more than the one-time purchase price of the same GPU, which can range from approximately $3,800 to $5,300.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49O5VDjZFdKYlrZwtb0U7Q.png" /></figure><p>While an argument against on-premise is that the hardware may not be used 24/7, AI workloads can be unpredictable. An agentic application or a deep research task, once initiated, may consume significant compute resources for an extended period. With on-premise hardware, the marginal cost of running these intensive jobs is limited to electricity.</p><p>Even at 50% utilization, the total cost of cloud rental over a year can approach or equal the acquisition cost of the hardware, making on-premise a financially sound, long-term investment..</p><h4>Data Privacy and Sovereignty</h4><p>The adage, “If you are not paying for the product, you are the product,” is particularly pertinent in the AI era. Many free AI tools log and store user data for various purposes, including model training. Even with paid cloud services, it is imperative to scrutinize the terms and conditions and verify security certifications like GDPR or ISO compliance. However, it is important to recognize that certifications, while valuable, are not absolute guarantees. On-premise infrastructure offers the ultimate level of data control, ensuring that sensitive intellectual property and private information remain within the organization’s physical perimeter.</p><h4>“Opportunity comes to the prepared Mind”</h4><p>This principle is acutely relevant to AI engineering. Without consistent access to on-premise compute, one’s hands-on experience remains limited. The constant pressure of a running meter on cloud instances can create anxiety, leading to rushed experiments and superficial findings. The time needed for thoughtful reflection between iterations is a critical component of genuine learning and is often sacrificed to avoid idle, credit-consuming GPUs. This prevents a true appreciation for the complexities of AI engineering and, more importantly, makes one ill-prepared to recognize and seize the right opportunities when they arise. At an enterprise scale, the cost of this unpreparedness can be substantial.</p><h4>Ensuring Solution Ownership and Optionality</h4><p>The AI landscape is dynamic and, at times, unpredictable. There have been instances where access to proprietary models has been revoked with little notice, or models have been taken down due to unforeseen security concerns. Because AI solutions are typically the result of rigorous iteration, adapting to such disruptions on short notice is nearly impossible.</p><p>If AI is integral to a product or service, maintaining <em>optionality</em> is not just beneficial but a necessity. This means having a fallback solution that you own and control. It may not be as performant as the primary service, but it provides a critical safety net. By running and optimizing this in-house solution on your on-premise hardware, you ensure it is always ready. In a worst-case scenario, this internal solution can provide continuity. Furthermore, this very process of optimization may lead to insights that ultimately allow your on-premise solution to replace the external service entirely.</p><h4>The Reliability of Your Solution</h4><p>There has been speculation, and some evidence, suggesting that some popular LLM providers may switch to less capable model versions during peak hours without informing users, leading to inconsistent output quality. This represents a form of reliability risk that is outside of your control.</p><p>With an on-premise setup, you have a consistent baseline for comparison. You can run daily benchmarks against the outputs of your rented AI services, giving you tangible data on their quality and reliability. This empowers you to make informed decisions about which workflows to use and which providers to trust, preventing lock-in to a single, potentially unreliable service.</p><h3>Practical Guidance and Recommendations</h3><p>A Personal Example: To illustrate the value of on-premise access, I recently acquired a machine with dual RTX 5090s (providing 64GB of VRAM), 256GB of system RAM, and an AMD Threadripper CPU. The speed at which this setup allows for testing and iteration is invaluable. While hardware costs can fluctuate, the principle remains: having dedicated compute is a game-changer.</p><h3>Recommendations for Different Audiences:</h3><h4>For Small to Medium Enterprises ( SMEs):</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UABVDSZkg2v4uwdUJ8otUA.png" /></figure><p>If your organization is struggling to adopt AI, acquiring a GPU-powered server is a straightforward and powerful first step. Do not get paralyzed by calculating the immediate ROI for a single machine; instead, measure its impact after six months of use. Aim for a minimum of 128GB of VRAM, but remember that any dedicated compute is better than none. For inference-focused tasks, consider consumer-grade cards like the RTX 5090 or professional cards like the RTX 6000 pro, as “enterprise” grade cards often come with a significant cost premium for features you may not need. Initial use cases can include:</p><ol><li>Hosting internal AI models as APIs for employees.</li><li>Allocating dedicated resources to specific teams for their projects.</li><li>Hosting internal hackathons to foster a culture of AI innovation</li></ol><h4>For Working Professionals</h4><p>A GPU-powered workstation is a versatile companion. It allows you to explore new ideas, build a robust portfolio, and deepen your expertise. Invest in as much compute as you can reasonably afford and leverage it to stay at the forefront of the field.</p><h4>For Students</h4><p>The current cost of hardware can be prohibitive. Maximize your access to free resources like Google Colab, Kaggle, and introductory credits from cloud GPU providers. Additionally, advocate for your university to invest in shared compute resources that can be made available to students. The goal is to gain hands-on experience through any available means.</p><h4>References</h4><ol><li><a href="https://timdettmers.com/2023/01/30/which-gpu-for-deep-learning/">Which GPU(s) to Get for Deep Learning: My Experience and Advice for Using GPUs in Deep Learning</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=902e45f68b92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a RAG pipeline — Step-By-Step]]></title>
            <link>https://medium.com/@mahakal001/building-a-rag-pipeline-step-by-step-0a5e1ac68562?source=rss-3405b7e9c40c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a5e1ac68562</guid>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[google-palm]]></category>
            <category><![CDATA[llamaindex]]></category>
            <category><![CDATA[natural-language-processi]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Mohit Pilkhan]]></dc:creator>
            <pubDate>Sat, 13 Jan 2024 07:28:30 GMT</pubDate>
            <atom:updated>2024-01-13T07:30:02.981Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a RAG pipeline — Step-By-Step</h3><p>If <em>you have a tough question that you can’t answer, start by tackling a simpler question that you can’t answer.</em><br> — Max Tegmark</p><p>Retrieval-augmented generation, currently making waves in the ML industry, is a straightforward technique that empowers Language Models to enhance their generation capabilities. The concept is rather simple. Through RAG, we help a Language Model to “augment” it’s “generation” by feeding it with information “relevant” to the query.</p><p>Before diving into the implementations, Let’s understand why there is a need of RAG techniques.</p><h3>The WHY</h3><p>Suppose you are talking to ChatGPT — one of the most capable LLMs available to play around. But would you ask questions such as “How many members are in my family” or “do you think my brother was a bit rude last morning” ? Of course, you would not ask such a question because ChatGPT does not have the context in which these questions have been asked. What would you do in such case? of course, You would provide some context in the prompt. Let’s take the second question as an example. You can prompt ChatGPT in the following way —</p><blockquote>“Hi ChatGPT. I want to narrate an incident that happend between me and my brother last morning. &lt; NARRATE THE INCIDENT &gt;. Do you think my brother was a bit rude ?”</blockquote><p>So what we just did? Along with the query, we provided some information that we think can be useful for ChatGPT to give us expected answer. That’s all what we are trying to do with the help of RAG pipelines. Now this is just a toy example. Real world is a complicated place.</p><h3>The HOW</h3><p>Suppose A new book is published and it has one thousand pages. You do not want to read the book but You want to query the book for certain kind of details through ChatGPT. How would you provide the relevant context? If we use the “Brute Force Analogy” of computer science, you can just feed the entire book as a context to ChatGPT but this would be highly inefficient. In an alternative scenario, You are supposed to read the book yourself and extract the relevant information and then provide this to ChatGPT. But isn’t this the exact thing that you wanted to avoid?</p><p>Other than personal choice, sometimes it may be completely impractical or inefficient to use these brute force methods. For example, suppose you are working in a healthcare company. You have millions of data points around feedback from patients. Now every time you want to take help from ChatGPT, you frame a query and then with every query you will have to traverse through millions of data point to decide the relevant section of the data and then feed that relevant information to ChatGPT along with the query. It’s definitely not practical.</p><p>Do we have any technique that can substitute our manual efforts? Of course, we do. That’s where the concept of vector embeddings comes into play. We can use ML model, that take our query and the external information and finds out the relevant sections. In brief, we can convert the raw text into embedding vectors with the help of Embedding models which are trained to generate a signature of the input text in such a way that two similar data points have high similarity score. In the book example we discussed above, we can generate embedding for every page of the book. We can store these embeddings in a simple list. Then we can generate an embedding vector for the query also. Now we can calculate similarity scores between the query embeddings and each of the embedding vector of the pages of the book. We can then choose the pages with the highest similarity score and use it as a “context” in the prompt.</p><h3>The Dive</h3><p>In this blog, We will build a RAG pipeline using following tools:-</p><ol><li>Llama-Index.</li><li>Local Embeddings powered by Huggingface.</li><li>Google PaLM free API.</li><li>numpy.ndarray as “vector database” :-)</li></ol><h4>The Algroithm</h4><p>First get your external information dataset. Since our focus is on building the simplest RAG pipeline, so it would be useful if you can have a text data. If you don’t have anything in mind, then you can follow along by fetching the <a href="https://github.com/amephraim/nlp/blob/master/texts/J.%20K.%20Rowling%20-%20Harry%20Potter%201%20-%20Sorcerer&#39;s%20Stone.txt">this particular text file</a>. Following would be steps in our Algorithm -</p><pre>1. Read the external text file and split it into chunks.<br>2. Initialize an embedding model.<br>3. Generate embeddings for each chunk.<br>4. Generate embedding of the query ( QE).<br>5. Generate a similarity score betweent QE and each of the Chunk embeddings.<br>6. Extract top K chunks based on similarity score.<br>7. Frame a prompt with the query and the top-k chunks.<br>8. Prompt an LLM with the prompt framed in step-7.</pre><h3>The implementation</h3><p>Let’s import the required packages.</p><pre>import numpy as np<br>import llama_index<br>from llama_index.embeddings import HuggingFaceEmbedding<br>import google.generativeai as palm<br>from llama_index.llms.palm import PaLM<br>import math<br><br>palm_api_key = &quot;your-palm-api-key&quot;<br>palm.configure(api_key=palm_api_key)</pre><p>Some utility Functions</p><pre>def read_text_file(file_path):<br>    with open(file_path, &#39;r&#39;, encoding=&#39;utf-8&#39;) as file:<br>        text = file.read()<br>    return text<br><br>def chunk_text(text, chunk_size):<br>    chunks = [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]<br>    return chunks<br><br>def get_embedding_model():<br>    embed_model = HuggingFaceEmbedding(model_name=&quot;BAAI/bge-small-en-v1.5&quot;)<br>    return embed_model<br><br>def get_embeddings(embed_model, text: str):<br>    embeddings = embed_model.get_text_embedding(text)<br>    return embeddings<br><br>def dot_product(vec1, vec2):<br>    return sum(a * b for a, b in zip(vec1, vec2))<br><br>def magnitude(vec):<br>    return math.sqrt(sum(v**2 for v in vec))<br><br>def cosine_similarity(vec1, vec2):<br>    dot_prod = dot_product(vec1, vec2)<br>    mag_vec1 = magnitude(vec1)<br>    mag_vec2 = magnitude(vec2)<br><br>    if mag_vec1 == 0 or mag_vec2 == 0:<br>        return 0  # Handle division by zero<br><br>    return dot_prod / (mag_vec1 * mag_vec2)</pre><h3>Step By Step Algorithm Implementation</h3><ol><li>Read the external text file and split it into chunks.</li></ol><pre>text_file = read_text_file(&quot;Simple-RAG-Application/J. K. Rowling - Harry Potter 1 - Sorcerer&#39;s Stone.txt&quot;)<br>chunks = chunk_text(text_file, chunk_size=250)</pre><p>2. Initialize an embedding Model.</p><pre>embd_model = get_embedding_model()</pre><p>3. Generate Embedding for each chunk.</p><pre>vdb = [] # our sasta vector database :-)<br>for chunk in chunks:<br>    embd = get_embeddings(embd_model, chunk)<br>    vdb.append(embd)</pre><p>4. Generate Embedding for Query.</p><pre>query = &quot;what is greatest fear of Dursleys&quot;<br>q_embd = get_embeddings(embd_model, query)</pre><p>5. Generate a similarity score betweent QE and each of the Chunk embeddings.</p><pre><br>ratings = [cosine_similarity(q_embd, x) for x in vdb]</pre><p>6. Extract top K chunks based on similarity score.</p><pre>k = 5<br>idx = np.argpartition(ratings, -k)[-k:]  # Indices not sorted</pre><p>7. Frame a prompt with the query and the top-k chunks</p><pre>prompt = f&quot;You are a smart agent. A question would be asked to you and relevant information would be provided.\<br>    Your task is to answer the question and use the information provided. Question - {query}. Relevant Information - {[chunks[index] for index in idx]}&quot;</pre><p>8. Prompt an LLM with the prompt framed in step-7.</p><pre>model = PaLM(api_key=palm_api_key)<br>output = model.complete(prompt)<br>print(output.text)<br><br>&#39;The greatest fear of Dursleys was that someone would discover their secret.&#39;</pre><h3>The world of Hyperparameters</h3><p>There is no God’s formulae to give the “best” configuratioin in Deep Learning Systems. The parameters such as how many layers to have in a deep neural network, which activation function to be used, what should be the learning rate etc. etc. does not have any absolute “correct” answers. We have to make educated guesses and experiment to check whether it worked or not. The same is true in RAG pipelines -</p><pre>1. What is the ideal chunk size ? ( for my use case)<br>2. Which Embedding models should I use? ( for my use case)<br>3. What should be an ideal value of K? ( for my use case)<br>4. What is an ideal way to store chunk embeddings? ( for my use case)<br>5. Is this LLM good for my use case? ( for my use case)<br>6. Do I need to reframe my prompt? ( for my use case)</pre><p>These are just some examples. But when we really work in production setting, there can be so many other parameters to tune. As an ML/AI Engineer, We need to invest significant time in gaining clarity over the expectation from the system we are building.</p><p>This is it folks. Hope you have got a better idea about RAG system from this Blog.</p><p><em>To give any feedback please leave a comment.</em></p><p><strong><em>If you notice any discrepancy in this article please leave a comment so that any issue can be addressed at the earliest.</em></strong></p><h3>References</h3><ol><li><a href="https://docs.llamaindex.ai/en/stable/examples/embeddings/huggingface.html">Local Embeddings with HuggingFace.</a></li><li><a href="https://docs.llamaindex.ai/en/stable/examples/llm/palm.html">Setting Up PaLM with LLama-Index.</a></li><li><a href="https://www.youtube.com/watch?v=8OJC21T2SL4">The five Levels of Text Splitting.</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a5e1ac68562" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[nanoCLIP — An illustration of the CLIP framework using MNIST]]></title>
            <link>https://medium.com/@mahakal001/nanoclip-an-illustration-of-the-clip-framework-using-mnist-f281b161c9fa?source=rss-3405b7e9c40c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f281b161c9fa</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[semi-supervised-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <dc:creator><![CDATA[Mohit Pilkhan]]></dc:creator>
            <pubDate>Mon, 03 Apr 2023 19:11:05 GMT</pubDate>
            <atom:updated>2023-12-24T11:39:35.332Z</atom:updated>
            <content:encoded><![CDATA[<h3>nanoCLIP — An illustration of the CLIP framework using MNIST</h3><p><em>If you have a tough question that you can’t answer, start by tackling a simpler question that you can’t answer.</em><br> — Max Tegmark</p><p>“We demonstrate that the simple pre-training task of predicting which caption goes with which image is an efficient and scalable way to learn SOTA image representations from scratch on a dataset of 400 million (image, text) pairs”</p><p>— This is a text from the Abstract section of the paper “<a href="https://arxiv.org/abs/2103.00020">Learning Transferable Visual Models From Natural Language Supervision</a>” by <a href="https://openai.com/">OpenAI</a>.</p><h3>Introduction</h3><p>Most of the ML problems that we see around are predominantly treated in the purely supervised manner (of course the trend is changing now). And the first thing you need for such a learning setting is a very carefully created dataset. Depending on the problem, the effort required to create such data can be huge and may not be scalable. But let’s suppose you can create a large(and clean :-)) dataset and you train a SOTA model for this specific task. The issue that can arise with training just for a specific task is that the model may take a short route and be very selective about which features to learn just to get good performance for this specific task. Thus the model may not have a robust representation of the underlying distribution. And so it may not have good generalization abilities. The CLIP framework proposed solutions to both of this problem. We first train a network to learn better representation. This first step ( Pre-training ) of training happens in an unsupervised manner on a huge corpus of (image, text) pairs. Equipped with its amazing representation capabilities such a model can then be easily adapted to new downstream tasks with a few labeled example or for some tasks, may produce SOTA result even without further fine tuning. Thus not only we got a better representation model but we have also been able to use a large corpus of data.</p><h3>“Hello World”</h3><p>In this blog, we will code a basic CLIP framework using MNIST data. The goal is to understand and illustrate the very basic principles. Take it as a “hello world” example for CLIP. We will build very basic image encoder and Text encoder networks to illustrate the idea. So let’s dive in.</p><p><em>The jupyter notebook corresponding to this blog can be accessed </em><a href="https://colab.research.google.com/drive/1k6VKE0Db7idIzi6-8iclJr8VSCG91vqq?usp=sharing"><em>here</em></a><em>.</em></p><h3>Problem Formulation</h3><blockquote>Given a batch of N (image, text) pairs, CLIP is trained to predict which of the N × N possible (image, text) pairings across a batch actually occurred. To do this, CLIP learns a multi-modal embedding space by jointly training an image encoder and text encoder to maximize the cosine similarity of the image and text embeddings of the N real pairs in the batch while minimizing the cosine similarity of the embeddings of the N^2 − N incorrect pairings</blockquote><p>Here’s How we are going to Code to achieve our objective:</p><ol><li>Create a dataset of (Image, text) pairs.</li><li>Create an Image Encoder (IE) and a Text Encoder (TE)</li><li>Project the outputs of IE and TE in the same dimensional space.</li><li>Let’s say the batch size is N. Then compute the dot product ( cosine similarity) of every Image embedding with every text embedding. This will give an N * N matrix.</li><li>Now, remember, the inputs of IE and TE must be aligned and so outputs will also be aligned, and in that case, the entry &lt;i, i&gt; in such a matrix should correspond to the cell with the correct pairing. With this trick, we know that for the ith image the value in cell &lt;i, i&gt; is the probability we need to maximize. Now if you just transpose the matrix, the ith row will correspond to the cosine similarity score of ith text with all the images and &lt;i, i&gt; would be the correct pairing. With this setting, we can use our old friend, the cross-entropy loss to evaluate how good the model is doing.</li><li>This setting can then be optimized using Gradient Descent Method.</li></ol><h3>Create a dataset of (Image, text) pairs</h3><p>The dataset we are going to use is MNIST. But there is a small problem, this dataset has &lt;image, label&gt; as a data point. The “label” is an int referring to which digit the image corresponds to. But we need &lt;image, text&gt; pairs. So we have to convert our int labels to their string representation. Since our dataset is small so we can simply use a small hack: dictionary!!!</p><pre>int_to_str = { 1 : &quot;One..&quot;, 2 : &quot;Two..&quot;, 3: &quot;Three&quot;, 4: &quot;Four.&quot;, 5: &quot;Five.&quot;, <br> 6: &quot;Six..&quot;, 7:&quot;Seven&quot;, 8:&quot;Eight&quot;, 9:&quot;Nine.&quot;, 0: &quot;Zero.&quot;}</pre><p>Now if you check carefully, you might ask, what are those extra “.” appended to each word? The thing is, in the real-world, the caption would rarely have the same length. and models like Transformer expect a fixed length input, so generally what we do is that we decide a maximum length our model can accept and if the input string length is smaller than expected then we pad it with a special token. For us “. “ is that special token. The maximum length a digit’s text can have is Five. So, we take that as the maximum length, and any text shorter than that gets appended by the required number of special tokens.</p><h3>Image Encoder</h3><p>Encoding Images is quite straightforward. We can make a basic encoder using the convolution layer as follows.</p><pre>def encoder_conv_block(ic, oc, ks, stride, padding):<br>    return nn.Sequential(<br>              nn.Conv2d(ic, oc, ks, stride=stride, padding=padding),<br>              nn.BatchNorm2d(oc),<br>              nn.ReLU(),<br>            )<br><br>class ImageEncoder(nn.Module):<br>    <br>    def __init__(self):<br>        super(ImageEncoder, self).__init__()<br>        self.input_block =  encoder_conv_block(1, 16, 3, stride=2, padding=(1,1)) <br>        self.conv_2 = encoder_conv_block(16, 32, 3, stride=2, padding=(1,1)) <br>        self.conv_3 = encoder_conv_block(32, 8, 3, stride=2, padding=(1,1)) <br>        self.conv_4 = encoder_conv_block(8, 4, 3, stride=2, padding=(1,1)) <br>        self.w_i = nn.Linear(16, 4)<br>        self.ln = nn.LayerNorm(4)<br><br>        <br>    def forward(self, x):<br>        b,c,w,h = x.shape<br>        x = self.input_block(x)<br>        x = self.conv_2(x)<br>        x = self.conv_3(x)<br>        x = self.conv_4(x)<br>        x = x.view(b,-1)<br>        x = self.w_i(x)<br>        x = self.ln(x)<br>        return x</pre><h3>Text Encoder</h3><p>So it’s a bit tricky. Images usually exist in a format that can be passed directly to a neural network for training. But Text needs to be tokenized first. For example, even the character you are currently reading are given some “tokens”. Refer to <a href="https://man7.org/linux/man-pages/man7/ascii.7.html">this Linux manual page</a> for a detailed description. That means we need to assign some tokens to our characters and then we need to tokenize our strings. Refer to <a href="https://www.youtube.com/watch?v=kCc8FmEb1nY">this GPT lecture</a> by Andrej Karpathy to understand this better and the following code is directly taken from there.</p><pre># collect complete text in a big string<br>text = &quot;&quot;.join([value for key, value in int_to_str.items()])<br><br># here are all the unique characters that occur in this text<br>chars = sorted(list(set(text)))<br>vocab_size = len(chars) # 20 <br><br># create a mapping from characters to integers<br>stoi = {ch: i for i, ch in enumerate(chars)}<br>itos = {i: ch for i, ch in enumerate(chars)}<br>encode = lambda s: [<br>    stoi[c] for c in s<br>]  # encoder: take a string, output a list of integers<br>decode = lambda l: &quot;&quot;.join([itos[i] for i in l])<br>encode(&quot;One..&quot;) # will produce [4, 12, 8, 0, 0]</pre><p>Now let’s work with the encoding of -&gt; “One..” which is [4, 12, 8, 0, 0] as you can see: ‘O’-&gt;4, ‘n’-&gt;12, ‘e’-&gt;8, ‘.’-&gt;0.</p><p>Note that these tokenization are a hard representation. That is once assigned, these representations are going to be static for the entire training and inference period. So we need a way to let the neural network learn the best way to represent them. We will use an Embedding Table of size VOCAB_SIZE x EMBEDDING_DIMENSION. The ith row of this table represents an embedding for a character which have “i” as its token. Initially, these embedding are randomly initialized and the network learns the representation as it trains.</p><p>let the embedding dimension be 4, and since the max input length is 5, so we have 5 tokens as input. now every token can be indexed into the embedding table to get its embedding vector. That means we would have 5 embedding vectors. Since We want to keep everything super simple, so there are two simple ways we can use here. Either we can concatenate these vectors or we can take a point-wise sum of these vectors. We will take the second approach. To illustrate the ideas, suppose we have the following embedding for each character in “One.” :-</p><p>“O”:- [0.2, 0.3, -0.2, 0.3]</p><p>“n”:- [-0.3, 0.2, 0.1, -0.1]</p><p>“e”:- [0.1, -0.1, 0.2, 0.0]</p><p>“.”:- [-0.1, 0.1, -0.2, 0.3]</p><p>Take their pointwise sum and average it. For the above case we would get us:-</p><p>[-0.0250, 0.1250, -0.0250, 0.1250]</p><p>now we can just pass this through a simple feedforward network to get the final embedding. So with all this information, the following is our text encoder:</p><pre>class TextEncoder(nn.Module):<br>    <br>    def __init__(self, vocab_size, emb_dim, hidden_dim, out_dim):<br>        super(TextEncoder, self).__init__()<br>        self.emb = nn.Embedding(vocab_size, emb_dim)<br>        self.ff1 = nn.Linear(emb_dim, hidden_dim)<br>        self.ff2 = nn.Linear(hidden_dim, hidden_dim)<br>        self.ff3 = nn.Linear(hidden_dim, out_dim)<br>        self.w_t = nn.Linear(out_dim, 4)<br>        self.ln = nn.LayerNorm(4)<br><br>    <br>    def forward(self, idx):<br>        <br>        x = self.emb(idx)<br>        x = x.sum(axis=1, keepdim=True) / x.shape[1]<br>        x = self.ff1(x)<br>        x = F.dropout(F.relu(x),0.2)<br>        x = self.ff2(x)<br>        x = F.dropout(F.relu(x),0.2)<br>        x = self.ff3(x)<br>        x = F.dropout(F.relu(x),0.2)<br>        x = self.w_t(x)<br>        x = self.ln(x)<br>        return x</pre><h3>How to Optimize?</h3><p>So we have both our Image Encoder and Text Encoder. Carefully observe that, the output projection has same dimension for both IE and TE so that we can compute their dot product ( cosine similarity). Now we see an example. Suppose we have following batch of &lt;Image, Text&gt; pairs,</p><p>&lt;img_1, txt_1&gt;, &lt;img_2, txt_2&gt;, &lt;img_3, txt_3&gt;</p><p>Since our projected dimension is 4. so we would have one matrix carrying image encodings of dimension 3x4 and another carrying text encodings of the same dimension. Now we have to calculate the similarity score of each embedding in the Image batch with all embedding in the text batch which would give rise to a similarity matrix of dimension 3x3.</p><blockquote>Similarity Score Matrix = matrix_multiplication (i _e, t_e.T)</blockquote><p>We have to take the transpose of the second operand to get the desired result. Because this is matrix multiplication, and the cell &lt;i,j&gt; in the output matrix denotes the dot product of an ith row of the first matrix with a jth column of the second matrix, and if you take the transpose of the second matrix, the jth column would represent the embedding vector corresponding to the jth data point. And so will compute the desired result.</p><p>Great, We have a similarity matrix. We need a way to guide our framework to produce the desired matrix. What do I mean by the term “desired”? If you carefully observe, the diagonal of this similarity matrix is quite special. The element at &lt;i, i&gt; of this matrix is the similarity score of the right pair of the image and text embeddings. So in any row, i, the element at &lt;i, i&gt; should have the highest score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*C95XOJ7cHS5DH7c_NmtcFw.png" /><figcaption>CLIP jointly trains an image encoder and a text encoder to predict the correct pairings of a batch of (image, text) training examples — From CLIP Paper</figcaption></figure><p>Analyze the above diagram which is directly taken from the CLIP paper. Corresponding to the first image I₁, is the row having a similarity score of this image with every other text embedding in the batch. In the ideal case, Which cell should have the highest score? it’s &lt;1,1&gt;. if you use the same reasoning for all rows, it’s easy to understand that for every row I, we can use cross entropy loss with an ith element of that row as a ground truth. But this would only compute that given an image, which text it is likely to correspond to. We also need to calculate the inverse. That is Given a text, which Image it is likely to correspond to? We can take the transpose of the above matrix and take Cross Entropy loss with the same thought process as described above.</p><p>Below is just one optimization step of a batch. You can access the full working <a href="https://colab.research.google.com/drive/1k6VKE0Db7idIzi6-8iclJr8VSCG91vqq?usp=sharing">colab notebook here</a>. You will get better intuition if you play with individual pieces of this notebook.</p><pre>inputs, labels = get_batch(trainloader)<br>str_labels = [int_to_str[digit.item()] for digit in labels]<br>encoded_text = torch.stack( [ torch.tensor(encode(s)) for s in str_labels], axis=0)<br><br>inputs = inputs.to(device)<br>encoded_text = encoded_text.to(device)<br>logits = net(inputs, encoded_text)<br><br># zero the parameter gradients<br>opt.zero_grad()<br># symmetric loss function<br>loss_i = ce(logits, target)<br>loss_t = ce(logits.T, target)<br>loss = (loss_i + loss_t)/2<br>loss.backward()<br>opt.step()</pre><p><em>To give any feedback please leave a comment.</em></p><p><strong><em>If you notice any discrepancy in this article please leave a comment so that any issue can be addressed at the earliest.</em></strong></p><h3>References</h3><ol><li>CLIP <a href="https://openai.com/research/clip">Connecting Text and Images by OPENAI</a>.</li><li><a href="https://arxiv.org/pdf/2103.00020.pdf">Learning Transferable Visual Models From Natural Language Supervision</a>.</li><li><a href="https://arxiv.org/pdf/2005.14165.pdf">Language Models are Few-Shot Learners</a> — To understand the importance of unsupervised pre-training.</li><li><a href="https://youtube.com/playlist?list=PLAqhIrjkxbuWI23v9cThsA9GvCAUhRvKZ">Neural Networks: Zero to Hero</a> — Andrej Karpathy.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f281b161c9fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a DQN in PyTorch: Balancing Cart Pole with Deep RL]]></title>
            <link>https://medium.com/fynd-team/building-a-deep-q-network-in-pytorch-fa1086aa5435?source=rss-3405b7e9c40c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa1086aa5435</guid>
            <category><![CDATA[artificial-neural-network]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Mohit Pilkhan]]></dc:creator>
            <pubDate>Sun, 02 Aug 2020 17:23:37 GMT</pubDate>
            <atom:updated>2023-12-24T11:40:45.648Z</atom:updated>
            <content:encoded><![CDATA[<h4>CONTINUOUS LEARNING SERIES</h4><h4>Part 3 in Reinforcement Learning Series</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KdvkActeILo9HmyrfymFDg.jpeg" /><figcaption><a href="http://www.linkedin.com/in/nancy-kataria">Design By Nancy Kataria</a></figcaption></figure><h4>Introduction</h4><p>Hi Geeks, welcome to Part-3 of our Reinforcement Learning Series. In the last two blogs, we covered some basic concepts in RL and also <a href="https://blog.gofynd.com/multi-armed-bandit-solution-methods-e85e6b19fb2d?source=friends_link&amp;sk=d5ce27c4f7240f81cbc283b690de741c">studied the multi-armed bandit problem</a> and its solution methods. This blog will be a bit longer as we will first learn some new concepts and then we will apply Deep Learning to build a deep RL agent. We will then train this agent to balance the cart pole.</p><blockquote>The code repository corresponding to this blog can be accessed <a href="https://github.com/mahakal001/reinforcement-learning/tree/master/cartpole-dqn">here</a>.</blockquote><h3>The Cart Pole Balancing Problem</h3><p>We will be using the <a href="https://github.com/openai/gym/wiki/CartPole-v0">CartPole-v0 environment</a> provided by OpenAI GYM. I am still including a complete environment description here for the sake of completeness.</p><h4>Description</h4><p>A pole is attached by an un-actuated joint to a cart, which moves along a frictionless track. The pendulum starts upright, and the goal is to prevent it from falling over by increasing and reducing the cart’s velocity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*-ipKnKpwgmtiDKfr.gif" /><figcaption>Cart Pole Environment</figcaption></figure><h4>State Space</h4><p>The observation of this environment is a four tuple :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*4442c6wVsFUFOPtu7-cT3Q.png" /></figure><h4>Action Space</h4><p>There are just two possible actions: Left or Right, corresponding to the direction in which the agent can push the cart pole.</p><h4>Reward</h4><p>The reward is 1 for every step taken, including the termination step.</p><h4>Starting State</h4><p>All observations are assigned a uniform random value between ±0.05.</p><h4>Episode Termination</h4><pre>1. Pole Angle is more than ±12°</pre><pre>2. Cart Position is more than ±2.4 (center of the cart reaches the edge of the display)</pre><pre>3. Episode length is greater than 200 (500 for v1).</pre><h4>Solved Requirements</h4><p>Considered solved when the average reward is greater than or equal to 195.0 over 100 consecutive trials.</p><h3>The Behavior of a Random Agent</h3><p>We will first check the average reward that a random agent can earn. By Random Agent, I am referring to an agent selecting actions randomly i.e without using any environment information. Running this snippet gave an average reward of 23.3 in my case. It may vary slightly in your case. But still, the problem is far from solved.</p><h3>The Real Question !!!</h3><p>Consider the following interaction between Agent and Environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*hMsaWJZjlBrdSu-QzaRaDQ.png" /><figcaption>Taken From <a href="https://mitpress.mit.edu/books/reinforcement-learning-second-edition">Reinforcement Learning — An Introduction</a></figcaption></figure><p>Based on the received observations and rewards from the environment, the agent selects some action. The agent must have some policy (aka strategy) according to which it selects an action. Just having a policy is not enough, the agent must have a mechanism to improve this strategy as it interacts more and more with the environment. Now (some of ) the questions are:</p><pre>1. How to represent a policy?</pre><pre>2. How to evaluate the current policy ( Policy Evaluation)?</pre><pre>3. How to improve the policy ( Policy Improvement )?</pre><h4>Deep Learning to The Rescue</h4><p>Ideally, we should first discuss these issues with traditional methods but that will make this blog very long. To summarize, we will still be using the traditional approaches but with the deep neural networks as function approximators. In the absence of deep neural network, to apply these algorithms we would need to store a table of dimension S x A where S is the number of possible states and A is the number of actions that can be taken in the environment. Even with a simple environment, this table is too large to be usable in practice.</p><p>Let us see how we can use Deep Learning to address the above concerns :</p><ol><li>In DL we use neural networks as function approximators. We can represent our policy via Deep NN. This NN will look at the given observation and will tell us which action is best to take in the current state. We refer to such Deep Neural Networks as Policy Network.</li><li>By policy evaluation, we mean to check how “good’ or “impactful” is our current policy. The loss of Policy Network can be used to check this. In this blog, we will use the Mean Squared Error between predicted and target returns to evaluate our policy network.</li><li>The Policy Evaluation step gives us the loss value of the current policy network. With this information, we can use Gradient Descent to optimize the weights of the policy network to minimize this loss. In this way, the policy network can be improved.</li></ol><h3>Deep Q-Network</h3><p>A DQN is a Q-value function approximator. At each time step, we pass the current environment observations as input. The output is the Q-value corresponding to each possible action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*w8XwcjOPMe7Mw0PQg_fu1A.jpeg" /><figcaption>Q-Network</figcaption></figure><h4>But wait… where are the ground truths ???</h4><p>In Supervised Learning, we have a ground truth corresponding to each input data point. The network prediction can be compared against the corresponding ground truth to evaluate its performance. But here we do not have the ground truths or at least not in the popular sense.</p><p>In most cases, we do not have the exact dynamics of the environment. That means we do not exactly know the value of selecting an action in a state even if the environment dynamics are known, then we would need to run the agent-environment interaction for a sufficiently long time or ideally until the end of the episodes. Then we can go back and update the ground-truth value. Note that this also means that we would need to store the entire sequence of interaction which is not feasible in most scenarios.</p><h4>Discounted Returns as Ground Truth</h4><p>The value of taking action a in state s i.e q(s, a) can be written as :</p><pre>q(s{t}, a{t} ) = R{t} + <em>γ </em>* R{t+1} + <em>γ</em>² * R{t+2} + <em>γ</em>³ * R{t+3} + …….</pre><p>where <em>γ is the discount factor, </em>the value of which belongs to the interval [0,1]. The idea here is that we care not only for the immediate rewards but also for the future rewards that can result after taking this action.</p><blockquote>The discount rate determines the present value of future rewards: a reward received k time steps in the future is worth only <strong>pow(<em>γ </em>,k-1)</strong> times what it would be worth if it were received immediately¹.</blockquote><p>With a bit rearrangement, the above equation can be simplified to :</p><pre>q(s{t}, a{t} ) = R{t} + <em>γ * MAX-OVER-ACTION q( s(t+1), a)</em></pre><h3>Training Algorithm</h3><pre><strong>Step-1</strong>: Initialize game state and get initial observations.</pre><pre><strong>Step-2:</strong> Input the observation (obs) to Q-network and get Q-value corresponding to each action. Store the maximum of the q-value in X.</pre><pre><strong>Step-3:</strong> With a probability, epsilon selects random action otherwise select action corresponding to max q-value. </pre><pre><strong>Step-4:</strong> Execute the selected action in the game state and collect the generated reward( r{t} ) and next state observation(obs_next).</pre><pre><strong>Step-5:</strong> Pass these next state observation through Q-network and store the maximum of these Q-values in a variable say q_next_state. If the discount factor is Gamma then the ground truth can be calculated as :</pre><pre><strong><em>Y = r{t} + Gamma * q_next_state</em></strong></pre><pre><strong>Step-6:</strong> Take X as the predicted return of current state and Y as the actual return. Calculate loss and perform an optimization step.</pre><pre><strong>Step-7:</strong> Set obs = obs_next.</pre><pre><strong>Step-8: </strong>Repeat Step-2 to Step-7 for n episodes.</pre><p><strong>Balancing Exploration and Exploitation</strong></p><p>In the beginning, our agent has no idea of the environment dynamics. So we should let it explore and as it interacts with the environment and it should increasingly exploit its learning along with exploration. There is a need to balance this exploration and exploitation. We can either choose the action corresponding to maximum Q-value(exploitation) or with a small probability, epsilon, a random action can be selected(exploration). In this agent’s training, we started with epsilon = 1 i.e 100% exploration and slowly decrease it to 0.05.</p><h4>Catastrophic Forgetting and Need For Replay Buffer</h4><p>There is a serious issue with the above training process. After each step of agent-environment interaction, we are performing an optimization step. This can lead to <a href="https://en.wikipedia.org/wiki/Catastrophic_interference">catastrophic forgetting</a>.</p><blockquote>Today’s deep learning methods struggle to learn rapidly in the incremental, online settings that are most natural for the reinforcement learning algorithms emphasized in this book. The problem is sometimes described as one of “catastrophic interference” or “correlated data.” When something new is learned it tends to replace what has previously been learned rather than adding to it, with the result that the benefit of the older learning is lost. Techniques such as “replay buffers” are often used to retain and replay old data so that its benefits are not permanently lost¹.</blockquote><p>So as you might have guessed by now, we will be using replay buffers to address this problem. The agent will gather the experience in replay buffer and then a random batch of experience will be sampled from this buffer. This batch will be used for training the agent using mini-batch gradient descent.</p><h4>Training Instability and Need for Two Identical Q-Network</h4><p>Until now, the same Q-network is used for predicting the Q-value of the current state and next state. The Q-value of the next state is then used to calculate ground truth. In simple words,</p><blockquote>We executed our optimization step to bring the prediction close to ground truth but at the same time we are changing the weights of the network which gave us the ground truth. This causes instability in training.</blockquote><p>The solution is to have another network called Target Network which is an exact copy of the Main Network. This target network is used to generate target values or ground truth. The weights of this network are held fixed for a fixed number of training steps after which these are updated with the weight of Main Network. In this way, the distribution of our target return is also held fixed for some fixed iterations which increase training stability.</p><p>Also, note that we are using the term policy network and q-network almost interchangeably but these are two different types of networks. Given a state, a policy network generates a probability distribution over actions while a Q-network generates Q-values corresponding to every action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jx8sj5KNKYR_ElLKwsGVLA.jpeg" /><figcaption><a href="https://quotefancy.com/">https://quotefancy.com/</a></figcaption></figure><h4>Coding our DQN Agent</h4><p>It seems quite natural to wrap our agent in a class. The agent receives state observations and rewards from the environment. It then acts on the environment based on current observation. The Deep Q-Network is the brain of our agent. The agent learns from interactions and adjusts the weight of Q-network accordingly. Let us quickly go through the code :</p><p>The init function builds two identical deep neural networks. Before that we first seed torch random generator. In this way, the weights of the neural network are initialized deterministically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*U37f_aBfO_Ep9_fIBc5x2g.png" /><figcaption><strong>“Seed is also a Hyper-parameter” 🙂</strong></figcaption></figure><p>Kindly remove all occurrences of “.cuda()” from this code if you do not have Cuda support on your machine. The variable <strong>network_sync_freq </strong>donate the number of training steps to take before updating the target network with the weight of the main network. The variable <strong>network_sync_counter </strong>is incremented after each training step in <strong>train()</strong> function and is reset to 0 when it reaches <strong>network_sync_freq. </strong>The variable <strong>experience_replay </strong>is a deque. In <strong>train()</strong> function, the Q-value of the current state is estimated using Main Q-Network. The Q-value of the next state is calculated using Target Network, which is then used to calculate the target return.</p><p>The rest of the code is pretty much self-explanatory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7f345a377f01dcc56b99aa5fd464d6c/href">https://medium.com/media/d7f345a377f01dcc56b99aa5fd464d6c/href</a></iframe><h4>Driver code</h4><p>The driver code is very simple. We first initialize both environment and agent. Then the replay buffer is filled to its full capacity, 256 in this case. Then we fix it for 4 training steps and during each training step, a batch of length 16 is sampled randomly from this buffer. Then the agent interacts with the environment for the next 128 time steps and collects the experience in the buffer. Note that since it is a deque after it is filled to its full capacity ( which we do before the main training loop), with each new experience inserted into it, one element from the front is also removed.</p><p>To balance exploration and exploitation, we are using the epsilon-greedy strategy. We first promote full exploration by setting epsilon =1 and update it after each episode to slowly decrease it to 0.05.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e438b1526739f800b851a3ce1d9f7ec/href">https://medium.com/media/7e438b1526739f800b851a3ce1d9f7ec/href</a></iframe><h4>Some Plots</h4><ol><li>This plot shows how reward varies as we make progress in training. Roughly after 6500 episodes, it scores maximum in each episode.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*BHIx3DdChZRY7rvF2wXLeQ.png" /><figcaption>Variation of Reward with episode</figcaption></figure><p>2. This plot shows the variation in loss value as the training progress.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*Hs_Dt_8bMRS0Ol0a_249EA.png" /><figcaption>x-axis: epoch, y-axis: loss</figcaption></figure><p>3. This plot shows the variation of epsilon as the training progress.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*tPj_pHJSUJ41o-12L4QSnw.png" /><figcaption>x-axis: epoch, y-axis: epsilon</figcaption></figure><h4>Video Time !!!</h4><p>This video shows how gracefully our agent is balancing the cart pole. The Pole almost appears to be still. It scored the maximum score each time I tried. Although taking the average over a large number of episodes is a much better idea.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*btCItzp_JvBVrkRS.gif" /><figcaption>CartPole Balancing via Deep Q-Network</figcaption></figure><p>The above video is generated by the following code snippet :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0abd351106c33807fe207ef6566f1b9/href">https://medium.com/media/a0abd351106c33807fe207ef6566f1b9/href</a></iframe><h3>Limitations</h3><p>There are some limitations to our DQN Agent. Let us look at some of them.</p><h4>Hacks… A lot of them !!!</h4><p>As you can easily observe that getting the right values of hyperparameters needs a lot of experimentation. Even the way neural networks are initialized has a significant effect on network training.</p><h4>Online vs Offline training</h4><p>Due to the need for a target network to stabilize training and use of replay buffer to address catastrophic forgetting, our agent is not trainable in an online manner.</p><h4>Bad Generalization</h4><p>I was not able to get the same agent work in other environments. The reason being is our agent is a very basic one. However, the agent described in the original DQN paper was able to generalize in different environments.</p><h3>Conclusion</h3><p>Combining Deep Learning and Reinforcement learning is very fascinating. Building this DQN and getting it to work was an amazing experience. But still, there are a lot of limitations to this approach.<a href="https://arxiv.org/pdf/1312.5602.pdf"> DQN was introduced in 2013</a>. The DQN we implemented in this blog is a much simpler version of the proposed DQN. In the paper, it is described as :</p><blockquote><em>We refer to convolutional networks trained with our approach as Deep Q-Networks (DQN).</em></blockquote><p>After 2013 a lot of progress has been made in Deep Reinforcement Learning. There is a great compilation of the resources at this <a href="https://spinningup.openai.com/en/latest/spinningup/keypapers.html"><em>link</em></a><em>. </em>With this blog, I just tried to scratch the surface. There is a long way to go from here. So we will keep exploring!!!</p><h3>What’s Next: A Journey to AWS DeepRacer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*7p9-3TCUOOTxlRaVeFKjOg.gif" /><figcaption>Our Team <strong>FRacer </strong>in Time Trial Race of AWS Deep Racer</figcaption></figure><p>In the next few blogs, we will take you through a journey of the <a href="https://aws.amazon.com/deepracer/">AWS Deep Racer Platform</a>. We will describe how we made use of these skills to break into the top 1% global ranking in the AWS DeepRacer Virtual Circuit contest for the month of August 2020.</p><h3>WHO IS THIS GUY?</h3><p>Hi, I am <a href="http://mahakal001.github.io/portfolio/">Mohit Pilkhan</a>. I have got a lot of interest in designing AI-powered applications and serving them via cloud and edge devices. Currently, I am a member of the Machine Learning Team at <a href="http://research.fynd.com/">Fynd</a>.</p><p><em>To give any feedback please leave a comment. Know more about our current research at </em><a href="https://research.fynd.com/">https://research.fynd.com/</a>.</p><p><strong><em>If you notice any discrepancy in this article please leave a comment below so that any issue can be addressed at earliest.</em></strong></p><h3>References</h3><ol><li>Richard Sutton and Andrew Barto. Reinforcement Learning: An Introduction.The MIT Press, 2018.</li><li>Alex Irpan (2018). Deep Reinforcement Learning Doesn’t Work Yet. <a href="https://www.alexirpan.com/2018/02/14/rl-hard.html">https://www.alexirpan.com/2018/02/14/rl-hard.html</a>.</li><li>Stuart Russell, Peter Norvig. <a href="http://aima.cs.berkeley.edu/">Artificial Intelligence — A Modern Approach</a>. Pearson, 2010.</li><li>Alexander Zai and Brandon Brown. <a href="https://www.manning.com/books/deep-reinforcement-learning-in-action">Deep Reinforcement Learning in Action</a>. Manning Publication, 2020.</li><li>Volodymyr Mnih, Koray Kavukcuoglu, David Silver, Alex Graves, Ioannis Antonoglou, Daan Wierstra, Martin Riedmiller (2013). Playing Atari with Deep Reinforcement Learning. <em>ArXiv, abs/</em><a href="https://arxiv.org/abs/1312.5602">1312.5602</a>.</li><li><a href="https://gym.openai.com/">Gym</a> is a toolkit for developing and comparing reinforcement learning algorithms. It supports teaching agents everything from <a href="https://gym.openai.com/envs/Humanoid-v1">walking</a> to playing games like <a href="https://gym.openai.com/envs/Pong-ram-v0">Pong</a> or <a href="https://gym.openai.com/envs/VideoPinball-ram-v0">Pinball</a></li><li><a href="https://spinningup.openai.com/">Spinning Up</a> is an educational resource produced by OpenAI that makes it easier to learn about deep reinforcement learning (deep RL).</li><li>The Github repository corresponding to this blog can be accessed <a href="https://github.com/mahakal001/reinforcement-learning/tree/master/cartpole-dqn">here</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa1086aa5435" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fynd-team/building-a-deep-q-network-in-pytorch-fa1086aa5435">Building a DQN in PyTorch: Balancing Cart Pole with Deep RL</a> was originally published in <a href="https://medium.com/fynd-team">Building Fynd</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Armed Bandit: Solution Methods]]></title>
            <link>https://medium.com/fynd-team/multi-armed-bandit-solution-methods-e85e6b19fb2d?source=rss-3405b7e9c40c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e85e6b19fb2d</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[exploration]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Mohit Pilkhan]]></dc:creator>
            <pubDate>Tue, 19 May 2020 12:36:36 GMT</pubDate>
            <atom:updated>2023-12-24T11:43:33.023Z</atom:updated>
            <content:encoded><![CDATA[<h4>Continuous Learning Series</h4><h4>Part 2 in Reinforcement Learning Series</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KdvkActeILo9HmyrfymFDg.jpeg" /><figcaption><a href="http://www.linkedin.com/in/nancy-kataria">Design By Nancy Kataria</a></figcaption></figure><blockquote>With every single action we perform, with every thought and emotion we generate, we can create a better situation around us.</blockquote><blockquote>- Sadhguru JV</blockquote><p>In this blog, we will discuss Multi-Armed Bandits and we will also see how to set up a testbed for experimentation. Multi-Armed Bandit helps us to understand the key idea behind RL in very simplistic settings. Let us assume that the task is stationary and non-associative ( Refer to Part 1 if you did not get those two terms). The corresponding code is available at <a href="https://github.com/mahakal001/reinforcement-learning">GitHub</a>.</p><p>In this blog, we will also see various methods to solve this testbed. Every concept has its corresponding Python notebook to explore it yourself. Let us start…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/0*l7Ra4R_CpJfc-hjz.png" /><figcaption>Multi-Armed Bandit Problem</figcaption></figure><h3>K-armed Bandit Problem</h3><blockquote>Suppose in certain situations you have to select one action from a set of k possible actions ( for that particular state). After each choice you receive a numerical reward chosen from a stationary probability distribution ( i.e the true reward does not change) depending upon the action you selected. Your objective is to maximize the expected total reward over some time period¹.</blockquote><h4>Setting Up TestBed</h4><p>In a 10-armed bandit, we have a set of 10 actions. Let us first sample the true rewards form a normal distribution with mean 0 and variance 1. This is one Bandit Problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1C41bwDiAhdeWi-lgYsBzw.png" /><figcaption>Distribution of True Rewards In One 10-armed Bandit Problem</figcaption></figure><p>Now we have got true rewards but hold on, pay attention to the next line. <strong>While running our experiments, we will not return these true rewards </strong>rather whenever our agent will select an action then we will sample a reward from a normal distribution <strong>with mean = True Reward</strong> ( corresponding to selected action) and unit variance. Now let us visualize, how such a distribution will look like when each of the 10-arms is selected 1000 times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*T_-zM7hQzvb3G1-aTZtz6w.png" /></figure><p>The visualization is a bit different from the one given in the book because I could not find a way to vary the thickness of the bar based on the frequency of sampled reward at that point. If you can help with this, create a PR on the corresponding GitHub repository.</p><h4>The Final Experimental Settings</h4><p>In the above section, we have seen how we will generate a bandit problem and how true rewards will be used during an experimental run. But let us assume that you have designed a very smart learning algorithm- <em>L</em>. How will you benchmark its performance? Will it be good to run it over a single Bandit Problem and claim the superiority? Certainly Not. So we will create 2000 different bandit problems. We will run 1000 time steps per bandit problem and in the end, we will average the return obtained on each step.</p><blockquote>For any learning method, we can measure its performance and behavior as it improves with experience over 1000 time steps when applied to one of the bandit problems. This makes up one run. Repeating this for 2000 independent runs, each with a different bandit problem, we obtained measures of the learning algorithm’s average behavior¹ .</blockquote><p>In the next sections, we will briefly discuss various approaches to solve the Multi-armed bandit problem. I have already written well-illustrated notebooks on these approaches which you can immediately refer and get your hands dirty. A few of them are listed below. For an up-to-date list, check out my corresponding <a href="https://github.com/mahakal001/reinforcement-learning">GitHub repository</a>.</p><h3>Search For a Balance Between Exploration and Exploitation</h3><p>Suppose the 10-lever arms in our Bandit Problem are named as 1,2,…,10. Now suppose the first time you decided to pull 5th arm which generated a reward r. What will you do next? You can choose to <strong><em>exploit</em></strong> the current information and keep pulling the 5th arm to generate the same reward r. But can we do better? 9 other arms are waiting to get <strong><em>explored !!! </em></strong>We do not know whether any of them is worth trying or not. So we have two ways to go from here :</p><h4>1. Greedy Action-Selection</h4><p>This approach exploits current knowledge to maximize immediate rewards. It spends no time at all sampling <em>apparently</em> inferior actions to see if they might really be better.</p><h4>2. Epsilon-Greedy Action-Selection</h4><p>Now instead of being greedy all the time, with a small probability (say Epsilon), we will select randomly from among all the actions with equal probability,<strong> independently of the action-values estimates¹.</strong></p><p>Let us take an example to understand it. Suppose in the Bandit Problem, we are allowed to pull the arms 1000 times. Let Epsilon = 0.1. Then among all 1000 available steps, we act greedy 900 times which means that we will pull the arm with a maximum known reward at that time step. For the rest of the steps ( 100 = 0.1 * 1000), we ignore our current reward information and will just randomly select one of the 10 arms with equal probabilities.</p><p>Greedy Action-Selection is a special case of Epsilon-Greedy with Epsilon = 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*6MDMnINSKehzoa87Fo0rfg.png" /></figure><p>At the top left of this graph, the Epsilon values are given. The best results ( Average Reward Per Step in our case ) are obtained with epsilon = 0.1. While choosing a wild high value of 0.9 produce the worst result on our testbed.</p><p>Run this <a href="https://github.com/mahakal001/reinforcement-learning/blob/master/chapter02/10-armed-bandit-part-2-Incremental-Implementation.ipynb">notebook</a> to explore Greedy and Epsilon-greedy methods.</p><h3>Optimistic Initial Value</h3><p>Can we promote exploration without using Epsilon-Greedy?</p><p>It turns out that we can do this using the concept of Optimistic Initial Value.</p><h4>Without Optimistic Initial Value</h4><p>Let us understand it. Initially, we do not know the true reward associated with each action. But we will make estimates as we progress.</p><pre>At t = 0, estimated_rewards = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]</pre><p>Let us assume that we select to pull the first lever and get a reward of 0.2. So average reward for this arm will be (0 + 0.2)/2 = 0.1 .</p><pre>At t = 1, estimated_rewards = [0.1, 0, 0, 0, 0, 0, 0, 0, 0]</pre><p>Now because we are following Greedy Action Selection (not Epsilon), so as we progress in this game we will just keep selecting the first lever. Let the pull of the first lever arm give a reward of 0.18 (remember that the rewards given at runtime are sampled from true rewards). So average reward for this arm will be (0 + 0.2 + 0.18)/3 = 0.126 .</p><pre>At t =2, estimated_rewards = [0.126, 0, 0, 0, 0, 0, 0, 0, 0]</pre><p>So we will keep selecting the first arm. Since we are not exploring so there are fair chances that we are missing the optimal return. Can we do better?</p><h4>With Optimistic Initial Value</h4><p>Now suppose we initialize the estimated rewards with a value of +5 each. So initially we have :</p><pre>At t = 0, estimated_rewards = [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]</pre><p>Let us again assume that we select to pull the first arm and get a reward of 0.2. So average reward for this arm will be (5 + 0.2)/2 = 2.6.</p><pre>At t = 1, estimated_rewards = [2.6, 5, 5, 5, 5, 5, 5, 5, 5, 5]</pre><p>Did you notice that? The estimated average reward from the selected arm is lower than its initial estimates. So our agent will be a bit disappointed and this will motivate the agent to explore other arms. Now the greedy policy has 9 choices ( because the maximum value 5 is associated with 9 other actions). Assuming that ties are broken randomly, a random action from among the remaining 9 will be chosen. Let us suppose the 3rd arm is selected this time. So average reward for this arm will be (5 + 0.2)/2 = 2.6.</p><pre>At t = 2, estimated_reward = [2.6, 5, 2.6, 5, 5, 5, 5, 5, 5, 5]</pre><p>Notice that while calculating average we do not divide by the time step. Rather the denominator is the number of times that particular action has been selected in the past.</p><p>It is easy to observe that as we continue this way, every arm will be explored at least once. So we observed how Optimistic Initial Value can make a big difference. We can also combine the Optimistic Initial Value technique with epsilon Greedy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*GGwK5_glUfoluBk_Xkx0pw.png" /></figure><p>In the above graph, the blue trajectory corresponds to greedy action-selection with estimated rewards initialized to 5. The red trajectory corresponds to epsilon-greedy with epsilon = 0.1 and reward estimates initialized to 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*xAGZH2kOEJxINyPCsDxVPQ.png" /></figure><p>In the above graph, we have epsilon-greedy action-selection methods with reward estimates initialized to different values of 0.0, 5.0, -5.0, 10.0, and an identical value of epsilon = 0.01.</p><p>You can take the blue trajectory as a basis to compare. This is because it corresponds to our popular epsilon-greedy action selection with epsilon = 0.01 and reward estimates initialized to 0.</p><p>Run this <a href="https://github.com/mahakal001/reinforcement-learning/blob/master/chapter02/10-armed-bandit-part-3-Optimistic-Initial-Value.ipynb">notebook</a> to explore the Optimistic Initial Value Method.</p><h3>Upper Confidence Bound</h3><p>You might have noticed that in epsilon-greedy when we choose to explore, one of all possible actions is selected randomly with equal probability. What that means is that even the greedy action is taken into account during exploration. Let’s see the idea behind UCB :</p><blockquote>It would be better to select among the non-greedy actions according to their potential for actually being optimal, taking into account both how close their estimates are to being maximal and the uncertainties in those estimates¹.</blockquote><p>This time we will maintain an array that will be updated during each step. Then we will select the action having the highest value in the array. This can be presented as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*9W3-o16HVLeT9g42cugQAA.png" /><figcaption>Upper Confidence Bound</figcaption></figure><pre><strong>Q(a)</strong>: Running Reward Average corresponding to action a.</pre><pre><strong>c &gt; 0:</strong> Control the degree of exploration.</pre><pre><strong>t: </strong>Time steps that have already taken place.</pre><pre><strong>N(a):</strong> Number of times action a has been selected until time t.</pre><h4>How does it help in Exploration?</h4><p>Pay Attention to the second term in the above equation. Whenever you select an action, the square root term computes the uncertainty in the estimate of a’s value. What does that mean? Suppose you have never selected some action a, thus N(a) = 0. Theoretically, this will lead to a very large number. So naturally, the value array will be maximum at this action and will be selected next. Now How does c help in exploration? Putting c = 0 in the above equation will reduce it to the greedy action-selection scheme. As we increase the value of c, the uncertainty gets scaled by that factor. The more the uncertainty in some action, the more the value of that action will be in our array, so more chance of getting selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*zWi9qmU17RvOQLeZo3uFig.png" /></figure><p>In the above graph, we compare the performance of epsilon-greedy action selection with UCB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*_4B1UxCWfO75-AinWm7mPg.png" /></figure><p>The above graph shows the performance of UCB with c = 0, 2, and 5.</p><p>Run this <a href="https://github.com/mahakal001/reinforcement-learning/blob/master/chapter02/10-armed-bandit-part-4-Upper-Confidence-Bound.ipynb">notebook</a> to explore this method of Upper Confidence Bound.</p><h3>Gradient Bandit Algorithms</h3><p>In all the above methods, we are taking roughly two steps :</p><pre>1. Compute some estimates of action-value</pre><pre>2. Select actions based on those estimates</pre><p>There is another technique, in which we compute a <strong>numerical preference </strong>of one action over another at every time step. Then these numerical preferences H(a), are used to compute the probability π(a), of taking an action <em>a</em> at some time <em>t</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*4SfYKOwqP34QPwrSa9mRww.png" /></figure><p>We will later see how to compute these preferences. But For time being pay attention to the following: When you apply softmax over numerical preferences, you get a probability distribution over action. we will use this distribution to select the next action and of course, the action with maximum probability has <strong>more </strong>chance of getting selected <strong>but there is no guarantee. That’s where we get our guarantee of exploration.</strong></p><p>The below diagram shows how to compute the numerical preferences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*z5SWbv8MSkYhvoscIRXpQA.jpeg" /><figcaption>Computing Numerical Preferences</figcaption></figure><p><em>Now the question is how to compute the baseline?</em></p><p>The baseline can be any scalar that does not depend on x where x is a value of Random Variable <em>𝐴</em>(t). Here we will calculate our baseline as an average reward of pervious steps(t) irrespective of the actions(a) taken during those steps. So suppose rewards gained at steps t = 1,2,3 are 5,20,35 respectively, then the new baseline for t = 4 will be (5+20+35)/3 = 20.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*SImSPz0iXjaEBegdSTHsbQ.png" /></figure><p>The bottom right labels are written in the following format :</p><pre>( learning_rate , whether baseline is applied or not? )</pre><p>As we can observe that with <strong>baseline applied = True </strong>performance is much better than otherwise.</p><p>Run this <a href="https://github.com/mahakal001/reinforcement-learning/blob/master/chapter02/10-armed-bandit-part-6-gradient-bandit.ipynb">notebook</a> to explore the Gradient Bandit Method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*22gSvrgjx6QYjNR7.jpg" /></figure><p>This concludes our discussion of Solution Methods to the Bandit Problem. Please note that throughout this discussion we assumed that the Problem is stationary( the true reward does not change with time) and non-associative, that is you just need to figure out one best action which will generate maximum rewards in all situations as opposed to associative task in which different situation would have to be mapped to different actions to get the best return. But even with this simple setting, we have explored four important methods to solve the problem. The study of Bandit Problem is crucial in understanding the basics of RL and worth investing in some time.</p><h3>WHO IS THIS GUY?</h3><p>Hi, I am Mohit Pilkhan. I have got a rich interest in Software Designing and Artificial Intelligence. You can follow my work at <a href="https://github.com/mahakal001">GitHub</a>. Currently, I am working on the application of Machine Learning and computer vision in e-commerce.</p><h3>References</h3><ol><li><a href="https://www.amazon.in/Reinforcement-Learning-Introduction-Richard-Sutton/dp/0262039249">Reinforcement Learning — An Introduction</a>.</li><li>The Github repository corresponding to this blog is <a href="https://github.com/mahakal001/reinforcement-learning">here</a>.</li></ol><p><em>To give any other feedback please leave a comment. Know more about our current research at </em><a href="https://research.fynd.com/">https://research.fynd.com/</a>.</p><p><strong><em>If you notice any discrepancy in this article please leave a comment below so that any issue can be addressed as soon as possible.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e85e6b19fb2d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fynd-team/multi-armed-bandit-solution-methods-e85e6b19fb2d">Multi-Armed Bandit: Solution Methods</a> was originally published in <a href="https://medium.com/fynd-team">Building Fynd</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning — A Quick Overview]]></title>
            <link>https://medium.com/fynd-team/reinforcement-learning-a-quick-technical-overview-14cdd17ca88b?source=rss-3405b7e9c40c------2</link>
            <guid isPermaLink="false">https://medium.com/p/14cdd17ca88b</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aritificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Mohit Pilkhan]]></dc:creator>
            <pubDate>Mon, 11 May 2020 12:58:35 GMT</pubDate>
            <atom:updated>2023-12-24T11:42:32.542Z</atom:updated>
            <content:encoded><![CDATA[<h4>Continuous Learning Series</h4><h3>Reinforcement Learning: A Quick Overview</h3><h4><em>Part 1 in Reinforcement Learning Series</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KdvkActeILo9HmyrfymFDg.jpeg" /><figcaption><a href="http://www.linkedin.com/in/nancy-kataria">Design By Nancy Kataria</a></figcaption></figure><blockquote>When you wish to instruct, be brief. — Cicero</blockquote><p>I was in the third year of college when I bought the book <a href="https://www.amazon.in/Artificial-Intelligence-3e-Modern-Approach/dp/9332543518"><em>Artificial Intelligence-A Modern Approach</em></a>. I was deeply impressed by the cover page of the book that shows a mechanical hand playing chess. This book might be one of the many reasons why I love working in this field.</p><figure><img alt="Cover Page of Artificial Intelligence — A Modern Approach" src="https://cdn-images-1.medium.com/max/382/1*3jjjL2vYgyR5q7hZI-e9Ew.jpeg" /></figure><p>Artificial Intelligence or AI is where science, technology, and the future overlaps. And at Fynd, we apply AI to craft smarter solutions for the retail and ecommerce industry.</p><p>As a company we believe in <strong>continuous self-improvement. </strong>This is also one of our core values. We are always eager to learn and use new technologies to make our products better. The <a href="http://research.fynd.com/">ML team</a> has been researching <em>Reinforcement Learning or RL</em> and its system of rewards and penalties for sometime.We believe that exploring together can create better opportunities for everyone, hence this blog.</p><p>This series on RL, will help you discover RL and keep you updated with our research and progress.In this blog, we will look at the basic concepts in RL. So, lets get started.</p><h3>What is Reinforcement Learning?</h3><p>Reinforcement Learning or RL is learning “What to Do” and how to map situations to actions — to maximise a numerical Reward Signal instead of trying to find hidden structures (as in Machine Learning) however these can be used to maximize the reward.</p><p>If you are interested in deep learning then you must have observed that lately many research papers are combining reinforcement learning, genetic algorithms, and deep learning techniques to solve various problems. The problem of <a href="https://en.wikipedia.org/wiki/Neural_architecture_search">neural architecture search</a> is especially being addressed with RL.</p><p>Those of you familiar with RL may also understand the Multi-Armed Bandit problem. The <a href="https://en.wikipedia.org/wiki/Multi-armed_bandit">multi-armed bandit</a> problem is a classic problem that demonstrates the <em>exploration vs exploitation</em> dilemma. We will talk about it in detail in our next blog post.</p><p>Another interesting exploration is the monthly AWS DeepRacer. For our team, it has turned out to be a fun way to experiment in reinforcement learning.</p><h4>RL Resources and Examples</h4><ul><li><a href="https://medium.com/@rexrothX/ai-visual-design-is-already-here-and-it-wont-hesitate-to-take-over-your-petty-design-job-934d756db82e">Alibaba Luban:</a> Luban is an automatic banner design tool. It uses RL to learn the “preferred” kind of Design.</li><li><a href="https://arxiv.org/abs/1611.02167">Designing Neural Network</a>: This paper is an excellent read showing how automating the process of neural network design can be addressed with the use of RL.</li><li><a href="https://www.youtube.com/watch?v=WXuK6gekU1Y">AlphaGo</a>: Go is a very complex game. While <a href="https://www.theguardian.com/technology/2016/mar/09/google-deepmind-alphago-ai-defeats-human-lee-sedol-first-game-go-contest">discussing</a> the complexity of the game, <a href="https://en.wikipedia.org/wiki/Demis_Hassabis">Demis Hassabis</a> said: “<em>There are more possible Go positions than there are atoms in the universe</em>”. This may seem like an <a href="http://norvig.com/atoms.html">exaggeration</a>, but DeepMind’s AlphaGo did beat the world champion <a href="https://en.wikipedia.org/wiki/Lee_Sedol">Lee Sedol</a> in 4 out of total 5 games. AlphaGo used techniques of Deep RL.</li></ul><h3>Some Basic RL Concepts and Terminologies</h3><p>Below are some important concepts in RL. These terms will continue to be used in our upcoming blogs where we will talk about implementing solutions for various problems.</p><h4>1. Evaluative vs Instructive Feedback</h4><blockquote><em>Purely evaluative feedback indicates how good the action taken was, but not whether it was the best or the worst action possible. Purely instructive feedback, on the other hand, indicates the correct action to take, independently of the action actually taken. [1]</em></blockquote><p>The main difference between reinforcement and supervised learning is whether the feedback received is evaluative or instructive.</p><p>In reinforcement learning, we take the action and <strong>evaluate</strong> the reward that is returned. In supervised learning, we take the action, for example, assigning class labels in an image classification task. We then compare the action with the correct action that should have been taken. This comparison is done using some appropriate loss function and then used to <strong>instruct</strong> the learning algorithm (using optimizers like Adam) to take the correct action.</p><h4><strong>2. Associative vs Non-Associative task</strong></h4><p>An associative task is the one in which there are more than one state in the environment. So now you need to associate some action to each state. If in case there is only a single state, it is identified as a non-associative task.</p><h4><strong>3. Stationary vs Non-Stationary task</strong></h4><p>In stationary problem settings, the true reward of an action does not change. Suppose you have 10 lever-arms to pull in a 10-armed bandit problem. If the true reward of each lever-arm does not change throughout the play, then we say “the problem setting is stationary”. We can make a fairly good approximation for such tasks in a fair number of repeated play.</p><p>In non-stationary problem settings, the true reward of an action changes. Each time you pull a lever-arm, the underlying mechanism ( i.e which is responsible for assigning true rewards) changes the true rewards for all or some of the arms based on some criteria. But if you continue to pull that arm, you may not receive the same reward. This setting is non-stationary.</p><h4><strong>4. Exploitation vs Exploration</strong></h4><p>Suppose you are driving a car and whenever you come across any intersection, it offers four choices [LEFT, RIGHT, STRAIGHT, TURN BACK]. Suppose the first time when you came across an intersection you randomly chose an action. Let’s say you chose LEFT and received a reward of 100 dollars.</p><p>Now, what will you do at the next intersection?</p><p>You can keep taking a LEFT turn and earn 100 dollars each time (assuming the problem is stationary ) i.e <strong>exploiting</strong> the current information you have. However if you take the right turn, you may be rewarded with 1000 dollars or just 10 dollars. The worst scenario is that taking a turn may get you a negative reward. This means that instead of receiving money you will be paying money. The dilemma here is that since you have incomplete information, you will be wondering if better rewards are waiting at another turn. With exploration, we take some risk to collect information about unknown options.</p><h3>Conclusion</h3><p>We now have a foundation of reinforcement learning concepts, and are ready to explore the Multi Armed Bandit Problem. In the next blog, we will set a k-armed bandit testbed as shown in the figure below. Then we will explore various methods to solve the k-armed bandit problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JE5kU-s0ny-rayU4Xo0Aiw.png" /><figcaption>10-armed Bandit Testbed</figcaption></figure><h3>WHO IS THIS GUY?</h3><p>Hi, I am Mohit Pilkhan. I am a Software Engineer and currently a member of the Machine Learning Team at <a href="https://www.fynd.com/">Fynd</a>. At Fynd, We are continuously leveraging the latest trends in AI in order to make our products better.</p><h4>References</h4><ol><li><a href="https://www.amazon.in/Reinforcement-Learning-Introduction-Richard-Sutton/dp/0262039249">Reinforcement Learning — An Introduction</a></li><li><a href="https://github.com/mahakal001/reinforcement-learning">https://github.com/mahakal001/reinforcement-learning</a></li><li>Designing Neural Network Architectures Using Reinforcement Learning. <a href="https://arxiv.org/pdf/1611.02167.pdf">https://arxiv.org/pdf/1611.02167.pdf</a></li><li><a href="https://medium.com/@rexrothX/ai-visual-design-is-already-here-and-it-wont-hesitate-to-take-over-your-petty-design-job-934d756db82e">AI visual design is already here — and it won’t hesitate to take over your petty design job</a></li><li>Mastering Chess and Shogi by Self-Play with a General Reinforcement Learning Algorithm. <a href="https://arxiv.org/pdf/1712.01815.pdf">https://arxiv.org/pdf/1712.01815.pdf</a></li></ol><p><em>To give feedback, please leave a comment. You can learn more about our current research at </em><a href="https://research.fynd.com/">https://research.fynd.com/</a>.</p><p><strong><em>If you notice any discrepancy in this article please leave a comment below so that I can address the issue as soon as possible.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14cdd17ca88b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fynd-team/reinforcement-learning-a-quick-technical-overview-14cdd17ca88b">Reinforcement Learning — A Quick Overview</a> was originally published in <a href="https://medium.com/fynd-team">Building Fynd</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End To End Project Example In Mediapipe]]></title>
            <link>https://medium.com/@mahakal001/end-to-end-project-example-in-mediapipe-b74a4a8ebb61?source=rss-3405b7e9c40c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b74a4a8ebb61</guid>
            <category><![CDATA[tensorflowjs]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[mediapipe]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificalintelligence]]></category>
            <dc:creator><![CDATA[Mohit Pilkhan]]></dc:creator>
            <pubDate>Fri, 13 Mar 2020 17:24:23 GMT</pubDate>
            <atom:updated>2023-12-24T11:41:52.221Z</atom:updated>
            <content:encoded><![CDATA[<p><em>If you have a tough question that you can’t answer, start by tackling a simpler question that you can’t answer.</em><br> — Max Tegmark</p><p>MediaPipe is slowly becoming a buzzword in Machine Learning due to its modular approach towards building ML Pipelines. Recently Google has launched some exciting new features via this framework. You can read more about it at <a href="https://mediapipe.readthedocs.io/">https://mediapipe.readthedocs.io/</a>.</p><blockquote><a href="http://github.com/google/mediapipe"><strong><em>MediaPipe</em></strong></a><strong><em> is a graph-based framework for building multimodal (video, audio, and sensor) applied machine learning pipelines. MediaPipe is cross-platform running on mobile devices, workstations and servers, and supports mobile GPU acceleration.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*X4ao-Z2LrIdAT-xWMY2VxA.png" /></figure><h3>Introduction</h3><p>Although Google has been using MediaPipe for many years, it wasn’t until recently that it was made public. There are very few tutorials on the internet to get started with it. Initially, MediaPipe was like a black box to me, but then I decided to go through the source code in order to understand how different pieces come together to do the magic.</p><h3>What will You learn?</h3><p>We will build a very simple Desktop Application using MediaPipe. We will write a custom calculator and all required BUILD files. The final application will perform the following function :</p><blockquote>It will take input stream from webcam and output it on display as it is.</blockquote><p>Clone media pipe project from <a href="https://github.com/google/mediapipe">https://github.com/google/mediapipe</a>.</p><p>Let’s start at…</p><h3>Step 1: Define Master BUILD file</h3><p>We will be creating an end-to-end desktop example named <strong>face_keypoint</strong>. Create a folder named <strong>face_keypoint </strong>in <strong>mediapipe/examples/desktop/. </strong>Create a file named <strong>BUILD</strong> in this new folder and paste the following code in it. This file is required by the build a system to spot project dependencies.</p><pre>licenses([“notice”]) # Apache 2.0</pre><pre>package(default_visibility = [“//mediapipe/examples:__subpackages__”])</pre><pre>cc_binary(<br>name = “face_keypoint_cpu”,<br>deps = [<br>“//mediapipe/examples/desktop:demo_run_graph_main”,<br>“//mediapipe/graphs/face_keypoint:desktop_tflite_calculators”,<br>],<br>)</pre><p>The syntax of listing dependencies is :</p><pre><strong>RELATIVE_FOLDER_PATH:TARGET </strong></pre><p>This tells — Check the BUILD file in RELATIVE_FOLDER_PATH. This BUILD should contain dependencies required to build the TARGET.<br> What are our dependencies in this case?</p><ol><li><strong>demo_run_graph_main</strong> : The BUILD file in <strong>mediapipe/examples/desktop</strong>/ instructs to build <strong>demo_run_graph_main.cc </strong>which is the typical driver file containing main( ) function .</li><li><strong>desktop_tflite_calculators</strong>: A graph defines the order in which information ( packets ) flows through calculators. Every node corresponds to an instance of a calculator and there can be multiple instances of the same calculator. So the BUILD file in <strong>mediapipe/graphs/face_keypoint/ </strong>contains the list of all calculators required to build the target desktop_tflite_calculator ( We are yet to create this in this guide ).</li></ol><h3>Step 2: Define a Simple Calculator</h3><p>We will define a calculator in the file “<strong>mediapipe/calculators/util/simple_flow_calculator.cc</strong>”. Every custom Calculator is inherited from the same base class CalculatorBase. There are three methods that need to define for every calculator. A Brief discussion about this is as follow :</p><pre><strong>GetContract( )</strong> : Used to check whether the incoming and outgoing streams types are as expected.</pre><pre><strong>Open( ) </strong>: It is a configuration step and invoked once during initialization.</pre><pre><strong>Process ( )</strong> : It define the operatioins to be executed on each input packet.</pre><p>The source code for <strong>simple_flow_calculators.cc</strong> can be downloaded from <a href="https://drive.google.com/open?id=1tx3UJZAEoWdMRt_VQgAUer-YDQ-i95fx">this google drive link</a>. I have also commented on it properly so that you can write your own calculator after reading this file.</p><p><strong><em>Question:</em> </strong>So you added a new calculator file…COOL…BUT how do you inform the build system about it?<br><strong> <em>Answer: </em></strong>The BUILD file in the same folder need to make aware of the arrival of a new family member ( i.e source code implementing our custom calculator). So open the BUILD file of the same folder i.e <strong>mediapipe/calculators/util/ </strong>and paste following code after the line declaring LICENSE ( exports_files([“LICENSE”]) ). As you can see, this also declares all the dependencies required to compile the source file.</p><pre>cc_library(<br> name = “simple_flow_calculator”,<br> srcs = [“simple_flow_calculator.cc”],<br> visibility = [<br> “//visibility:public”,<br> ],<br> deps = [<br> “//mediapipe/framework:calculator_framework”,<br> “//mediapipe/framework:calculator_options_cc_proto”,<br> “//mediapipe/framework:timestamp”,<br> “//mediapipe/framework/port:status”,<br> “@com_google_absl//absl/time”,<br> “@com_google_absl//absl/strings”,<br> “//mediapipe/framework/formats:rect_cc_proto”,<br> “//mediapipe/framework/port:ret_check”,<br> “//mediapipe/framework/formats:image_frame”,<br> “//mediapipe/framework/formats:image_frame_opencv”,<br> “//mediapipe/framework/port:opencv_core”,<br> “//mediapipe/framework/port:opencv_imgproc”,</pre><pre>],<br> alwayslink = 1,<br>)</pre><h3>Step 3: Writing Graph pipeline</h3><p>Please understand that each calculator is to be written in c++ but how these calculators are to be arranged in a pipeline is to be defined in a .pbtxt format. Here we will write a very basic pipeline constituting a single node using the calculator we just built above.</p><p>Create a <strong>face_keypoint</strong> folder in<strong> mediapipe/graphs/. </strong>In this new folder, create a file <strong>face_keypoint_desktop_live</strong>.<strong>pbtxt ( </strong>This file will be passed as an argument to the main function ) and paste following code into it :</p><pre>input_stream: “input_video”<br>output_stream: “output_video”</pre><pre>node {<br> calculator : “SimpleFlowCalculator”<br> input_stream : “IMAGE:input_video”<br> output_stream: “IMAGE:output_video”<br> }</pre><p><strong><em>Question:</em></strong> How to notify our Build System about the calculators required to build this graph?<br> <strong><em>Answer:</em></strong> Create a local Build file ( i.e In the current folder itself which is <strong>mediapipe/graphs/face_keypoint/ )</strong> named BUILD and paste the following code into it :</p><pre>licenses([“notice”]) # Apache 2.0<br>package(default_visibility = [“//visibility:public”])</pre><pre>cc_library(<br> name = “desktop_tflite_calculators”,<br> deps = [<br> “//mediapipe/calculators/util:simple_flow_calculator”,<br> ],<br> )</pre><h3><strong><em>In a Nutshell,</em></strong></h3><p><strong><em>We have created : </em></strong><br> <em>1. One new c++ file — </em>Implementing our Calculator<em>. </em><br> <em>2. One .pbtxt file — </em>Defining the Graph<em>.</em><br> <em>3. Two BUILD files — </em>One To notify build system about all calculator dependencies required by target ( desktop_tflite_calculators in this case ) the second one is the Main BUILD file ( at the top of this Blog) .</p><p><strong><em>We have also modified already existing :</em></strong><br> <em>1. One BUILD file (</em><strong>mediapipe/calculators/util/BUILD)</strong><em> — </em>Listing dependencies to build our new calculator.</p><h3>Step 4: Build Example</h3><p>Change to the root directory of the MediaPipe repository. In this directory build our example with the following command :</p><blockquote>$ bazel-1.2.1 build -c opt — define MEDIAPIPE_DISABLE_GPU=1 mediapipe/examples/desktop/face_keypoint:face_keypoint_cpu</blockquote><h3>Step 5: Execute It</h3><p>To run this example, execute the following command</p><p><strong><em>Bazel-bin/mediapipe/examples/desktop/face_keypoint/face_keypoint_cpu</em></strong> and pass .pbtxt file defining our graph as an argument in the following manner</p><blockquote>- -calculator_graph_config_file=mediapipe/graphs/face_keypoint/face_keypoint_desktop_live.pbtxt</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTAVjb552nIk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTAVjb552nIk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTAVjb552nIk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/939bc9db4ee7fec2a3d2b3e26c9c4d29/href">https://medium.com/media/939bc9db4ee7fec2a3d2b3e26c9c4d29/href</a></iframe><h3>WHO IS THIS GUY?</h3><p>Hi, I am Mohit Pilkhan. I am a Software Engineer and currently a member of the Machine Learning Team at <a href="https://www.fynd.com/">Fynd</a>. At Fynd, We are continuously leveraging the latest trends in AI in order to make our products better.</p><p><em>To give any other feedback please leave a comment. Know more about our current research at </em><a href="https://research.fynd.com/">https://research.fynd.com/</a>.</p><p><strong><em>If you notice any discrepancy in this article please leave a comment below so that I can address the issue as soon as possible.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b74a4a8ebb61" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>