<?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 Ved Mulkalwar on Medium]]></title>
        <description><![CDATA[Stories by Ved Mulkalwar on Medium]]></description>
        <link>https://medium.com/@vedmkw?source=rss-411b0d24b564------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DST5L_5B_lty6vEgEtNbqw.jpeg</url>
            <title>Stories by Ved Mulkalwar on Medium</title>
            <link>https://medium.com/@vedmkw?source=rss-411b0d24b564------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 13:01:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vedmkw/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to create a good High Level Design — HLD]]></title>
            <link>https://medium.com/@vedmkw/how-to-create-a-good-high-level-design-hld-fddba7f6ae18?source=rss-411b0d24b564------2</link>
            <guid isPermaLink="false">https://medium.com/p/fddba7f6ae18</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[design-thinking]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[high-level-design]]></category>
            <dc:creator><![CDATA[Ved Mulkalwar]]></dc:creator>
            <pubDate>Tue, 09 May 2023 09:08:45 GMT</pubDate>
            <atom:updated>2025-07-24T05:36:21.033Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to create a good High Level Design — HLD</h3><p>Lets start with “<strong>WHY</strong>”. Why would you need to write a High Level Design aka “HLD” of a software?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*kkV4orqs1vntF-lN.jpg" /></figure><p>Here are few reasons why you might-</p><ol><li><strong>You want to write down a solution which is in your mind, into a more structured format.</strong><br>Its better to have something tangible to point and play rather than losing your sanity by staring into nothing, waving your arms in the air or mumbling to yourself.<br>A good HLD clarifies your design and makes you think about the details before you start coding. This also helps you avoid repetitive work.</li><li><strong>You want to explain the solution of a problem to someone else.</strong><br>Its better to explain something complex and (most likely) multiple times in a nice clean written/drawn format vs any other way.<br>The feedback from the second set of eyes will give a new perspective and help you avoid mistakes.</li><li><strong>Someone(Manager, Team Lead, etc) asked you to do so.</strong><br>Don’t you want to keep your job for the $$$ you need to buy that double cheese burst pizza!?!<br>Managers &amp; Executives will use this to understand your project. They might use this to determine the relative merit of assigning more resources to the project or even deciding not to pursue the project in the first place.</li><li><strong>You want to leave a behind a good legacy and a proper answer to <em>Why did someone do it this way.</em></strong><em><br></em>Systems are written once, maintained/extended/rewritten for a long time by multiple people. Documenting the system design and the thought process is extremely helpful for people maintaining and using it, and understanding how and why you built the system the way you did. People would be able to build on what you did later and learn from your work which would help you gain good karma.</li><li><strong>You need to collaborate with others.</strong><br>An HLD of your system will help you clearly define boundaries, which will help you avoid conflicts with other people’s work. It will help you stake you territory and avoid duplication of work. You will unlock the possibility of building pieces in parallel with others and actually having them meet up in the middle.</li><li><strong>You aspire to go to a higher ladder in your software related career and you see this an important skill.</strong><br>Having a documentation trail of your work would help you go a long way in your performance and promotion cycles. Starting with a good HLD and later detailing and implementing your design conveys a good story and shows the blood, sweat and tears you shed.</li><li><strong>Preparing for a Tech Company’s System Design Interview rounds.</strong><br>Because if the above said perf &amp; promo reviews don’t go in your favour, you would likely want to switch company, and almost all good companies for higher level candidate interviews ask you write a HLD in ~1 hourcall. Having a good structure(like the one suggested below) will help you excel at it.</li></ol><h4>Now to “WHAT”. What is a HLD?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*o5-UouZQzkeBG7FPkPobeA.jpeg" /></figure><p>HLD is the big picture of the solution. The purpose of HLD is to provide a common understanding of the system’s architecture among all stakeholders. This helps to ensure that everyone is on the same page and that the system is developed in a consistent manner. HLD also helps to identify potential risks and challenges early on, so that they can be addressed before they become major problems</p><h4>Next is “HOW”. How to write a good HLD?</h4><p>The key to writing a good HLD is to write it in the form a story, a story so good that the reader is engaged with its plot, the backstories of the characters and is on the edge of his/her seat with every plot twist(Okey we don’t have to go as far as adding plot twists). The idea is to keep the design simple to understand, easy to follow and clear about assumptions and tradeoffs. So naturally the first step is knowing your audience. A good HLD should be able to communicate your thoughts to your expected audience.</p><p>Hence a general pattern to follow is</p><ul><li><strong>Context</strong> — Scope out and clearly define the objective and context of problem you are solving.</li><li><strong>Design Overview</strong>—State the requirements of the solution with additional context like assumptions, back of the envelope calculation of number of users, size of data, etc.</li><li><strong>Detailed Design </strong>— This contains your actual design of the solution.</li><li><strong>Alternatives considered </strong>— This helps you convey comparison between tradeoffs. This is good place to focus of potential bottlenecks with each alternative.</li><li><strong>Quality Attributes </strong>— Shed light on property of the system like security, Reliability, Data Integrity, Privacy, Scalability, Latency, etc.</li><li><strong>Operations</strong> — Plan for maintenance of code like the monitoring, alerting and logging strategy.</li></ul><p>Find below a template which you can refer and follow. Based on your audience, not all sections will apply to your HLD. Use your judgement to delete a section and introduce new ones. Have fun!</p><h3>Context</h3><blockquote><strong>Objective</strong></blockquote><p>In one of two sentences, describe at high level what you are solving using this design. This section should not describe the problem (use “Background”) or propose a solution(use “Design”), not should it got into implementation details like stating list of requirements and features.</p><blockquote><strong>Background</strong></blockquote><p>Provide context for an unfamiliar reader to understand the proposal. In a crisp way cover what the problem is, why it is important to solve the problem and the historical context as appropriate. If the background requires a large write up or the reason to for solving the problem becomes verbose, separate docs like PRDs should be created first and linked here. Note: this is background, do not write about your design or ideas to solve the problem here.</p><h3>Design</h3><blockquote><strong>Overview</strong></blockquote><p>This contains high level overview of your design. Should be understandable by a non-engineer not working on the project. Diagrams can be especially useful to quickly convey the shape of the solution. This is going to be the trailer of your story, so keep it clean and concise.</p><blockquote><strong>Functional Requirements</strong></blockquote><p>Describe in brief the various aspects of the problem space like <br>1. What will the users do<br>2. Where are users based out of geographically<br>3. Which platforms, like mobile/web/physical would the users be using.</p><blockquote><strong>Capacity Estimates</strong></blockquote><p>Calculate approximates for the key data points. You can use below calculation for reference.<br><strong>Active Users </strong>— 2 Billion(B) Daily Active Users(DAU), 3B Monthly Active Users(MAU) — Approximate FB traffic estimate<br><strong>Read vs Write</strong> — 100:1<br><strong>Queries Per Second</strong> — <br>Reads — (2B DAU)*(100Read)/(24*60*60) — 2.4M req/sec<br>Writes — (2B DAU)*(1Write)/(24*60*60) — 24k req/sec<br><strong>Storage</strong> — (Assuming for 5 years)<br>No of objects — (2B DAU)*(5Y*12M*30D) — 3.6 Trillion(T)<br>Each Object Size — ~ 500 bytes<br>Total Object size — 3.6T*500 bytes — 1.8 PB<br><strong>Throughput</strong> — <br>Reads — (2.4M QPS)*(500bytes) — 1200 MB/s<br>Writes — (24K QPS)*(500bytes) — 12 MB/s<br>Cache — Following 80–20 rule. 20 % users would use 80% of objs) — (1200 MB/s)*(60m*60s)*(0.2) — 864 GB per hour<br><strong>Number of Instances required </strong>— <br>Application Services — <br>Assuming 100 MB/s per instance as bottleneck— (1200MBps/100MBps)=12<br>Database —<br>Assuming 10 TB per instance as bottleneck— 1.8PB/10TB= 180<br>Assuming 50 MBps disk throughput per instance as bottleneck — 1200MB/s/50 MB/s= 24<br>Caching — Assuming each instance offers 32 GB — 864/64 = 14</p><blockquote><strong>Interfaces</strong></blockquote><p>List out key interaction points between user and your system. Typically this has your API details like request and response parameters at a high level.</p><blockquote><strong>Data Model</strong></blockquote><p>This describes key entities of your solution. This space usually helps you to decide till which granularity do you want to break down your entities</p><h3>Detailed Design</h3><blockquote><strong>Details</strong></blockquote><p>Get into the detail of the design. Diagrams are best way to express the thought process here. You can start by drawing out the components( which has one or more Data Models identified in earlier section) and connecting them to each other(This is usually called “<a href="https://en.wikipedia.org/wiki/Component_diagram">Component Diagram</a>” and shows high level overview of how components are placed and interact with each others and users of the system).</p><p>Optionally, based on complexity of the proposal, you can have multiple types of diagrams like the <a href="https://en.wikipedia.org/wiki/Sequence_diagram">Sequence Diagram</a> (Good for representing a solution with cross-section of multiple use-cases across components and actors), <a href="https://en.wikipedia.org/wiki/Activity_diagram">Activity Diagram</a>(Helpful in representing how multiple components can be clubbed together), <a href="https://en.wikipedia.org/wiki/Deployment_diagram">Deployment Diagram</a>(If you want to get to lower level details), etc. Please choose diagrams which best explain your solution as every problem statement, and every solution is different.</p><blockquote><strong>Dependencies</strong></blockquote><p>Discuss your dependencies on other components and services. The fall-back plan when they’re unavailable for a period of time? Which services<br>must be running for your job to start up? <br>Are you introducing any cycles, such as blocking on a service that can’t run if your jobs aren’t already up?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DrK43lKJGJiXZmJx.png" /></figure><blockquote><strong>Migrations</strong></blockquote><p>Describe any data or system migrations which might be needed. Incomplete migrations hurt a system in the long run; they add<br>enormous complexity, hurt reliability, and make programming unpleasant. If existing systems must be turned down to achieve the proposed design, describe how that transition will happen. “How do we get there from here?” is difficult, but often overlooked.</p><blockquote><strong>Technical debt</strong></blockquote><p>Things to consider</p><ol><li>Is there known technical debt incurred by implementing this design?</li><li>Is there a risk associated with technical debt (e.g., deprecation of underlying technologies) incurred by implementing this design?</li><li>How will technical debt identified during the execution of this design be tracked and followed up with?</li><li>Are there libraries or code paths that would be deprecated? If so, what is the plan to migrate the usage to the new piece.</li><li>Are there libraries or code paths that would be obsolete? When will they be deleted?</li><li>Are there any servers that could be turned down? If so, please document the turndown process.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*onz259flnjWxdCWQ.png" /></figure><blockquote><strong>Potential patents</strong></blockquote><p>Are there potentially patentable inventions in the project? <br>The work may be patentable if the design:<br>● Provides for something not otherwise commercially available.<br>● Does something better/faster/cheaper than what currently exists.<br>● Addresses an unresolved need.</p><h3>Alternatives considered</h3><p>Clearly list the other potential approaches to meeting the objective that you considered and why the current proposal was ultimately selected. In the rare cases where requirements or system constraints only allow for one possible high-level approach, that should be highlighted here and alternatives to specific details should still be discussed in-line in the detailed design section.<br>An effective strategy is to compare dimensions of the solution space and how they vary across alternatives, such as latency, data staleness, cpu cost, engineering investment, etc. A color-coded table explaining favorability in that dimension and how important it is from green through yellow, orange and red quickly conveys the rationale to a reader, though this is just<br>one possible approach to explain the trade-offs. For example:</p><figure><img alt="A color-coded table comparing Advantages and Disadvantages of proposed solution and alternatives" src="https://cdn-images-1.medium.com/max/1024/1*3VQ91W3Q1p1o0zbi66cniQ.png" /></figure><h3>Quality attributes</h3><blockquote><strong>Security</strong></blockquote><p>Think about potential attacks on your system and describe the counter-measures you have in-place to prevent or mitigate each<br>attack. For each attack describe the worst case impact it would have. Also, list any known vulnerabilities or potentially insecure dependencies. If<br>somehow your application doesn’t have security considerations, explicitly state so and why.</p><p>Please consider attacks from a variety of sources, including both external and internal risks. When evaluating insider risk, include both insider risk from your co-employees as well as insider risk for customers (e.g. for enterprise products, employees of an enterprise; for consumer products,<br>family members or friends of customers)</p><blockquote><strong>Reliability</strong></blockquote><p>Discuss handling of local data loss, transient errors (e.g., temporary outages) and how they affect your system. Bear in mind that reliability issues with your dependencies can often cause reliability issues for your system.</p><p>What do you use that inherently provides reliability and redundancy for data? What do you use that requires data to be backed up? How is the data backed up? How is it restored? What happens between the time data is lost and the time it’s restored? In the case of a partial loss, can you keep serving and can you restore only missing portions of your backups to your serving datastore?</p><p>What are the costs of replicating your data?</p><blockquote><strong>Data integrity</strong></blockquote><p>Discuss how you will detect, provision for and recover from data corruption and loss.</p><p>How will you find out about data corruption or loss in your datastores? What sources of data loss are detected? (User error, application bug, storage platform bug, site/replica disaster.)</p><p>How long will it take to notice each of these types of losses? What is your plan to recover from each of these types of losses?</p><blockquote><strong>Privacy</strong></blockquote><p>Does your solution cover privacy standards in place? Is the customer PII protected by sufficient firewalls and encryptions? Are your private keys sufficiently protected?</p><blockquote><strong>Scalability</strong></blockquote><p>How does your system scale? Consider both data size increase (if applicable) and traffic increase (if applicable).</p><p>Please consider the current machine situation: adding more machines might take much longer than you think or might not happen during the lifetime of your project. What initial resources will you need? Plan early and carefully. Also, general machine utilization is a concern, using<br>more resources than you need will block expansion of your service.</p><blockquote><strong>Latency</strong></blockquote><p>This section can be skipped if you are not designing a server on a human facing path. What latency do you need/expect? In particular, make sure you understand the bottlenecks of the pieces you’re reusing. All services should define latency targets.</p><blockquote><strong>Testability</strong></blockquote><p>Specify the test plan. What are the sub-units of your system that will be independently testable?</p><p>How do you plan to test them? For example,</p><p>● Build a test harness around it that simulates its environment<br>● <em>Generate random/carefully controlled input data</em><br>● Compare with golden results/maintain state in the test harness</p><p>Are you tests run automatically by the CI/CD pipelines</p><p>What load can your server handle, and how will you verify that value?</p><p>If there are changes envisaged in your future work, would your tests verify the base functionality? If some of your tests cannot be easily automated, how will you document the needed special procedures?</p><p>Consider the external systems your system depends on<br>● How fast will your unit test cycle run?<br>● What test infrastructure (e.g. test doubles) from external systems will you use?<br>● Does the external system have a test instance for integration testing?<br>● Do you need any tests that run outside of the standard unit test cycle (e.g. presubmit, postsubmit, or release)?<br>Consider future systems that will depend on yours. What test facilities (e.g. test doubles, local instances for exploratory integration tests) will you provide so that they can run integration tests?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gR2Jo4-4lD6848qQ.png" /><figcaption>Why you should have a good test!</figcaption></figure><h3>Operations</h3><blockquote><strong>SLAs</strong></blockquote><p>If your application makes any service level guarantees, what mechanisms are in place for auditing, monitoring, etc.? And how can you guarantee the stated level of reliability?</p><blockquote><strong>Monitoring &amp; alerting</strong></blockquote><p>Is there a mechanism for monitoring and alerting for the running system. Is there an oncall and escalation metrics?</p><blockquote><strong>Logging plan</strong></blockquote><p>All systems must log information at various levels for the log analysis system to collect and analyze. Log information allows us to understand system user behavior and system related business metrics. In this section, describe the information that you are going to log.</p><blockquote><strong>Rollback strategy</strong></blockquote><p>In order to improve incident management response, which will result in reduced time to mitigate issues, teams should document and test their ability to rollback major change surfaces. This includes, but is not limited to:<br>● Documenting the overall rollback strategy;<br>● Identifying surface areas which are not able to be rolled back and defining a fix-forward strategy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*6n0Yjz9CFpKdZcfv4tZcvg.jpeg" /></figure><h3>Document history</h3><p>Readers must have the access to earlier versions of the design to see how it has changes and evolved.</p><p><a href="https://www.linkedin.com/in/vedmul/"><em>🔗 Connect with me on LinkedIn!</em></a></p><p><em>I hope you found this article helpful! If you’re interested in learning more and staying up-to-date with my latest insights and articles, or if you want to share your thoughts, don’t hesitate to comment below or connect with me on </em><a href="https://www.linkedin.com/in/vedmul/"><em>LinkedIn</em></a><em> . Feel free to share these posts with your friends and colleagues</em></p><p><em>Let’s grow our networks, engage in meaningful discussions, and share our experiences in the world of software development and beyond. Looking forward to connecting with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fddba7f6ae18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to become a Full Stack Machine Learning Engineer(Part 4): Automate]]></title>
            <link>https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-4-automate-1f20d784d64a?source=rss-411b0d24b564------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f20d784d64a</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Ved Mulkalwar]]></dc:creator>
            <pubDate>Tue, 24 Dec 2019 14:09:27 GMT</pubDate>
            <atom:updated>2019-12-24T14:09:27.234Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Objective: To create a Machine Learning prediction model, serve it by a http server on a remote cloud server and manage it like you would on production.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*r_-_ZWam5n6mQn0o121-6g.png" /><figcaption>Often reality is different from theory. Lets change that!</figcaption></figure><p>This is a <strong>hands-on</strong> approach where we will be writing code from scratch with explanation of all the code and jargons.<br>The final code for reference can be found <a href="https://github.com/vedsm/to-beer-or-not-to-beer">here</a></p><p>This is part 4 of a 4 part series:</p><ol><li><strong>Training</strong> a very basic ML model(which tells if there is any beer in a given image) using <a href="https://keras.io/">keras</a>(a python deep-learning library). We won’t get into depth of it, mostly intuition based.(<a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-1-train-ae3928a00aef">here</a>)</li><li>Writing an independent <strong>predict</strong> function which serves the model and then s<strong>erving</strong> the prediction using a <strong>HTTP API POST</strong> request.(<a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-2-predict-9b2e582ce0e0">here</a>)</li><li><strong>Dockerising</strong> the prediction api. Setting up a Dockerfile and <strong>building</strong> our own <strong>docker image</strong>. <strong>Deploying</strong> the prediction docker on a <strong>cloud machine</strong>. We will be able to the <strong>call the prediction api from anywhere</strong> and see the status and logs of the server for <strong>debugging</strong>.(<a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-3-deploy-1165abd0f900">here</a>)</li><li>Setting up basic <strong>CI/CD</strong> pipeline, i.e. setup our infra such that <strong>performing a commit automatically deploys the new code</strong> to production.</li></ol><p>This is a continuation of <a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-1-train-ae3928a00aef">Part 1</a>, <a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-2-predict-9b2e582ce0e0">Part 2</a> and <a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-3-deploy-1165abd0f900">Part 3</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*f7UwaIC8yvAZE19c8i71pQ.png" /></figure><p>For part 4 the idea is to be able to setup our resources so that deploying any new changes to our machines becomes as easy and hassle free as possible. Setting an automated CI/CD(continuous integration continuous deployment) pipeline would enable to us to perform development iterations faster without worrying getting slowed down by human errors. By the end of this we would be doing only a code commit for any new changes required, and the code will automatically get deployed.</p><p>We will walk through this using example for setting up a CI/CD pipeline using <a href="http://dev.azure.com/"><strong>azure devops console</strong></a><strong>.</strong> Signup and setup you organisation and project in the console. Once everything is setup follow the following steps.</p><h4>Create a git repository on azure devops</h4><ul><li>Go to the “Repos” tab on the left in the azure devops UI.</li><li>Click on the drop-down menu and click on “+ New Repository”.</li><li>Select Repository type as “Git” and specify the Repository name. (Uncheck the Add a README option and specify “Add a .gitignore” as None since we would be pushing our own existing code created in earlier posts to this repository)</li><li>You would get a page with title “&lt;repo-name&gt; is empty. Add some code!”. This page would have two sections: Clone to your computer and Push an existing repository from command line with some lines of code and a tab to select option as “HTTPS” and “SSH”. Its better to select “SSH” because in that case you won’t have to put your user-name password on every code update. Open ”Manage SSH keys” option and add your machine keys to it. Now your SSH is setup. Lets add our code to the repo. Keep a not of the origin url of our repo which is of the form “<a href="/service/mailto:git@ssh.dev.azure.com">git@ssh.dev.azure.com</a>:v3/&lt;org-name&gt;/&lt;project-name&gt;/&lt;repo-name&gt;”</li></ul><h4>Add our code to the git repository</h4><ul><li>cd into the folder which has your code created using previous posts. (if you are interested in just CI/CD and don’t want to follow the earlier post, only create the “docker-compose.yml” file which has contents from <a href="https://github.com/vedsm/to-beer-or-not-to-beer/blob/master/docker-compose.yml">here</a> )</li><li>Initiate the git repo by git init</li><li>Add a .gitignore which tells git which files and folders need to be ignored. This is important to avoid adding non-important files to our git repository so that pushing/pulling/cloning this repo later would be quick. <a href="https://github.com/vedsm/to-beer-or-not-to-beer/blob/master/.gitignore">Fill its contents using this.</a></li><li>Add location of the source of the repository on cloud by git remote add origin git@ssh.dev.azure.com:v3/&lt;org-name&gt;/&lt;project-name&gt;/repo-name&gt; <br>e.Finally add your files to be tracked by doing git add .</li><li>Commit your changes by git commit -m &quot;first commit&quot;</li><li>Push the changes by git push -u origin --all</li><li>Now if you refresh the repository page in your azure devops UI, you will see your code reflected there.</li></ul><h4>Setup a build pipeline</h4><p>We will now setup a build pipeline which will automatically get triggered on a new commit. For this we will use “Build” pipelines of azure.</p><ul><li>Go to the “Pipelines” &gt; “Builds” tab on the left in the azure devops UI.</li><li>Click on “+ New” button dropdown and “New Build Pipeline” option.</li><li>Select the “Azure Repos Git” option.</li><li>Select your git repository from the list of repos.</li><li>Select “Starter pipeline” option.</li><li>The next page will give you a basic azure-pipeline.yml file which you are going to modify. This file is what is going to be used to monitor our git repository for new commits; create our build; and other additional steps. Have a quick look at its <a href="https://aka.ms/yaml">official documentation</a> to know more. Replace this with the following lines</li></ul><pre># Add steps that build, run tests, deploy, and more:<br># https://aka.ms/yaml</pre><pre>trigger:<br>- master</pre><pre>pool:<br>vmImage: &#39;ubuntu-latest&#39;</pre><pre>variables:<br>- group: beer_variables</pre><pre>steps:<br>- script: docker login -u=&quot;$(DOCKER_USERNAME)&quot; -p=&quot;$(DOCKER_PASSWORD)&quot;<br>displayName: Logging-in to docker</pre><pre>- script: docker build -t veddev/beer:latest .<br>displayName: &#39;Building the docker image&#39;</pre><pre>- script: docker push veddev/beer:latest<br>displayName: &#39;Pushing the image to docker&#39;</pre><p>Let me explain what is happening here.</p><p>Pipelines are made of one or more stages describing a CI/CD process. Stages are the major divisions in a pipeline: “build this app”, “run these tests”, and “deploy to pre-production” are good examples of stages.<br>Stages consist of one or more jobs, which are units of work assignable to a particular machine. Both stages and jobs may be arranged into dependency graphs: “run this stage before that one” or “this job depends on the output of that job”.<br>Jobs consist of a linear series of steps. Steps can be tasks, scripts, or references to external templates.<br><strong>Triggers: </strong>A trigger specifies what branches will cause a continuous integration build to run. If left unspecified, pushes to every branch will trigger a build. Learn more about <a href="https://docs.microsoft.com/en-us/azure/devops/pipelines/build/triggers?tabs=yaml&amp;view=azure-devops#ci-triggers">triggers</a> and how to specify them. Also, be sure to see the note about <a href="https://docs.microsoft.com/en-us/azure/devops/pipelines/build/triggers?view=azure-devops#wildcards">wildcards in triggers</a>. In our case the pipeline will get triggered whenever a new commit happens on “master”.<br><strong>Variables:</strong> Hardcoded values can be added directly, or <a href="https://docs.microsoft.com/en-us/azure/devops/pipelines/library/variable-groups?view=azure-devops">variable groups</a> can be referenced. Variables may be specified at the pipeline, stage, or job level. <br><strong>Variable Groups:</strong> This contain the common strings(especially confidential strings like passwords which should not be ) which can get used across all pipelines. This is maintained in “Pipelines” &gt; “Library” tab on the left in the azure devops UI. Open devops UI in another browser window and create a new variable group “beer_variables” there and add two keys “DOCKER_USERNAME” and “DOCKER_PASSWORD” with their corresponding values of your docker-registry. This is going to get used in the pipeline when we want to push the build.<br><strong>Steps: </strong>Steps are a linear sequence of operations that make up a job. Each step runs in its own process on an agent and has access to the pipeline workspace on disk. This means environment variables are not preserved between steps but filesystem changes are. In our case, the first step does a docker login(i.e. establishing connection between the build system and the docker-repository); the next step builds the docker image; and the final step pushes the image to the docker repository.</p><ul><li>Finally click on “save and run” option on the right-top. This will trigger the build which you can view under the “Builds”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a8KPB_9LfS3boT5ktoETiw.png" /></figure><h4>Setup a release pipeline</h4><p>Now that we have our automated build part of our pipeline ready, lets setup our automated release part which will deploy our new build to our VM.</p><ul><li>Go to the “Pipelines” &gt; “Releases” tab on the left in the azure devops UI.</li><li>Click on “+ New” button dropdown and “New release Pipeline” option.</li><li>Select the “Empty job” option in the “Select a template” options.</li><li>In the “Artifacts” section, click on “+ Add an artifact” &gt; Select “Source type” as “Build” and select your build created in the earlier step. Finally click on “Add”.</li><li>Once the build is added as an artifact, click on the thunder-bolt symbol(which is at the top right corner of your newly added artifact box). This is your “Continuous deployment trigger” setting. Enable the option which says “Enabling the trigger will create a new release every time a new build is available”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EnQ-yMbhrZXFPnvV6D41ZQ.png" /></figure><ul><li>In the “Stages” section’s “Stage 1” box, click on the “1 job, 0 task” link. It will open a page where you can edit the “Stage 1”. Here click on the + icon next to “Agent job” tab. This will open options to “Add tasks”. Search and add an “SSH” task. This will help us run shell commands or a script on a remote machine using ssh.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5f1OGevVvxLM2BLVVWy1w.png" /></figure><ul><li>Now lets start editing the task. Click on it and fill in the configuration for this task.</li></ul><ol><li>Right click on “Manage” on right of SSH service connection and open it in new tab. In this window add your VM’s ssh connection credentials and save it. Once done come back to our page and click on refresh button. After that your VM’s ssh credentials should now be available in the drop-down. Select it.</li><li>In the run option choose “Inline Script”. This is the script which will get executed on your VM using SSH. Add the commands you would need to pull the latest docker image and then deploy this latest image. The commands are:</li></ol><pre>cd to-beer-or-not-to-beer<br>docker-compose -f docker-compose.yml pull<br>docker-compose -f docker-compose.yml up -d</pre><p>In the “Advanced” section disable “Fail on STDERR” as our script will be writing to some output which azure devops will consider an error and the build will be shown as failed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*63SnnjEvDVXlOJMWGKp_Ww.png" /></figure><p>Finally save this pipeline. Our CI CD is complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VjIEgTbmO4_t_EB8yl23IQ.png" /></figure><p>Go back to your original code and do some changes. For example add a new print statement to your server.py file and commit it to the master branch. As soon as you do it, the build will gets triggered automatically. Once the build is successful, the release will get get triggered after which your code with the new changes will get deployed on the VM.</p><p>You can add additional steps to your build and deployment pipeline. A good development practice would be to add a test script in your CI CD pipeline which tests if your latest code works as expected. This will ensure that any new changes does not break your existing working code. Additionally versioning your builds and deployments is also considered a good thing to have so that rolling back to previous versions is easier. More on this later(perhaps in the another blog). Just remember “With great power comes great responsibility”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*BKxVxS7o8A_QJ4XUj01YHQ.jpeg" /><figcaption>With great power comes great responsibility. So make your pipeline more resilient.</figcaption></figure><p>Hopefully these posts have helped you train, deploy and manage your own machine learning models. Feel free to share your thoughts in the comment below or drop me an email at ved.mulkalwar@gmail.com or connect with me on <a href="https://www.linkedin.com/in/vedmul/">LinkedIn</a>. Share these posts with your friends and colleagues who want to start out on the path of becoming a full stack machine learning engineer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f20d784d64a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to become a Full Stack Machine Learning Engineer(Part 3): Deploy]]></title>
            <link>https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-3-deploy-1165abd0f900?source=rss-411b0d24b564------2</link>
            <guid isPermaLink="false">https://medium.com/p/1165abd0f900</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Ved Mulkalwar]]></dc:creator>
            <pubDate>Tue, 24 Dec 2019 14:05:22 GMT</pubDate>
            <atom:updated>2020-06-22T14:32:11.871Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Objective: To create a Machine Learning prediction model, serve it by a http server on a remote cloud server and manage it like you would on production.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*GDJE4Jc1TRl86OIL5VLZCg.jpeg" /></figure><p>This is a <strong>hands-on</strong> approach where we will be writing code from scratch with explanation of all the code and jargons.<br>The final code for reference can be found <a href="https://github.com/vedsm/to-beer-or-not-to-beer">here</a></p><p>This is part 3 of a 4 part series:</p><ol><li><strong>Training</strong> a very basic ML model(which tells if there is any beer in a given image) using <a href="https://keras.io/">keras</a>(a python deep-learning library). We won’t get into depth of it, mostly intuition based.(<a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-1-train-ae3928a00aef">here</a>)</li><li>Writing an independent <strong>predict</strong> function which serves the model and then s<strong>erving</strong> the prediction using a <strong>HTTP API POST</strong> request.(<a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-2-predict-9b2e582ce0e0">here</a>)</li><li><strong>Dockerising</strong> the prediction api. Setting up a Dockerfile and <strong>building</strong> our own <strong>docker image</strong>. <strong>Deploying</strong> the prediction docker on a <strong>cloud machine</strong>. We will be able to the <strong>call the prediction api from anywhere</strong> and see the status and logs of the server for <strong>debugging</strong>.</li><li>Setting up basic <strong>CI/CD</strong> pipeline, i.e. setup our infra such that <strong>performing a commit automatically deploys the new code</strong> to production.(<a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-4-automate-1f20d784d64a">here</a>)</li></ol><p>This is a continuation of <a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-1-train-ae3928a00aef">Part 1</a> and <a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-2-predict-9b2e582ce0e0">Part 2</a>.</p><h3>Setting up a Dockerfile and <strong>building</strong> our own <strong>docker image</strong>.</h3><p>First of all why docker?</p><blockquote><strong>Docker</strong> is a tool designed to make it easier to create, deploy, and run applications by using containers. Containers allow a developer to package up an application with all of the parts it needs, such as libraries and other dependencies, and ship it all out as one package.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*bX-kjAwP23bs0RJkbO6htw.jpeg" /></figure><p>To explain it in a simple way, remember how we used to install and play Roadrash game on our old windows computers? To get that game running all we needed to do was just get the installation file with the “.exe” extension and double-click on it. After that the game would be installed. Once the game is installed, double-clicking on it would launch the game.</p><p>Dockers have made setup of code on our remote servers as easy. We just need to:</p><ol><li>Build a docker image using Dockerfile; which is equivalent to generating an .exe file.</li><li>Push this docker image to a docker registry, and pull it on any machine; which is equivalent to getting the .exe file from a friend or a CD.</li><li>Run the docker image; which is equivalent to running the .exe file</li></ol><p>And voila! You would have dockerised and deployed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*kD5zHyoiPFXtM1kw7vYnOA.jpeg" /></figure><p>This way we would be able to escape the hassle of installing and setting up our complex system requirements and dependency installations.</p><p>Lets start building our image by first creating a Dockerfile which contains the steps needed to create a container and configure it to our needs.</p><pre># Dockerfile<br>FROM python:3.7-slim</pre><pre># Installing requirements<br>ADD serving-requirements.txt /usr/src/app/<br>WORKDIR /usr/src/app<br>RUN pip3 install -r serving-requirements.txt</pre><pre># Adding remaining files<br># ADD . /usr/src/app<br>ADD src /usr/src/app/src<br>ADD trained_models /usr/src/app/trained_models</pre><pre>ENV PYTHONPATH &quot;${PYTHONPATH}:/usr/src/app&quot;<br>ENTRYPOINT [&quot;python3&quot;, &quot;./src/serving/server.py&quot;]</pre><p>The first line FROM python:3.7-slim tells the base image which is going to be used. One of the biggest advantages of docker is that you don’t have to build an image from scratch. You use one of the many base images available freely. We will be using this one officially maintained by <a href="https://hub.docker.com/_/python">python</a>.</p><p>Then we copy our serving-requirement.txt file to the image, install the packages required, copy the src folder which is contain the server files.</p><p>And finally the ENTRYPOINT line specifies what command is supposed to be run when the docker image gets deployed.</p><p>We need to name our docker image name which is going to be build. Generally the docker images are named in this format: &lt;optional-docker-host-name&gt;/&lt;docker-u-name&gt;/&lt;docker-image-name&gt;/&lt;tag&gt; . This name also contains the meta information which will get used to upload the image to a docker repository.</p><ul><li><strong>optional-docker-host-name</strong> is the name of the docker registry host. It can contain the IP of your docker registry host. If nothing is passed, it defaults to pointing to docker.io. eg. “&lt;org-name&gt;.azurecr.io”, “gcr.io”.</li><li><strong>docker-u-name</strong> is the username or the namespace in the docker registry where you want your image to reside.</li><li><strong>docker-image-name</strong> is the name of your image in docker repository.</li><li><strong>tag</strong> is the version number. Multiple versions of the same image name can be maintained using tags</li></ul><p>Naming your image like this is optional. You can also name it “anystring” if you want to run it locally. Its essential to name it in this above stated format if you want to available everywhere(i.e.by uploading it to a docker repository). For doing that you would need to setup a docker registry or connect to an already existing ones. For example docker.io maintains a docker repository. Creating an account on <a href="https://www.docker.com/">https://www.docker.com/</a> is free and easy. You can create unlimited public repositories and one private repository for free. After sign-up and sign-in, create a repository. For this post, we will create a free repository. Once done note the username and image name. Do a docker login to setup connection to the docker repository in your machine.</p><p>Finally build the docker container using the command docker build -t &lt;optnl-docker-host-name&gt;/&lt;docker-u-name&gt;/&lt;docker-imxtage-name&gt;/&lt;tag&gt; (example docker build -t veddev/beer:latest).</p><p>Once the image gets built, we can check if the image is built properly by running the command docker run &lt;docker-image-name&gt; [OPTIONS] (example docker run veddev/beer:latest). We need to specify the “OPTIONS” to expose and the open the port on which the server is running so that we can call the prediction API. Additionally, some environment variables can also be setup which the container might require while running. To make the management of [OPTIONS] easier, we will use docker-compose. This a tool built on top of docker to make maintaining of containers and their configuration easier. Define the docker-compose.yml file</p><pre># docker-compose.yml<br>version: &#39;3&#39;<br>services:<br>beer:<br>  build:<br>  context: .<br>  dockerfile: Dockerfile<br>  image: veddev/beer:latest<br>  environment:<br>    - BUILD_ENV=dev<br>  ports:<br>    - 4200:4200<br>  # command: /bin/bash -c &quot;sleep 7 &amp;&amp; python3 app.py&quot;<br></pre><p>We can build and run the docker images and containers much easily using docker-compose by using simple commands like docker-compose -f docker-compose.yml build and docker-compose -f docker-compose.yml up . Test if this docker image is able to serve the prediction API by calling the POST API from POSTMAN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RyovIrjuQbD5kDbmIqfTbQ.png" /></figure><p>Finally push this image to your docker registry using docker push &lt;docker-image-name&gt;(example docker push veddev/beer:latest) command so that this image can be downloaded in any machine on the internet.</p><p>As discussed in the previous post, our prediction server is ready and is running our personal system. For making this API available to the entire world, we would have to host it somewhere.</p><h4><strong>Deploying</strong> the prediction docker on a <strong>cloud machine</strong>. We will be able to the <strong>call the prediction api from anywhere</strong> and see the status and logs of the server for <strong>debugging</strong>.</h4><p>First create a virtual machine(VM) using <a href="https://aws.amazon.com/ec2/">AWS</a> or <a href="https://azure.microsoft.com/en-in/services/virtual-machines/">Azure</a> or <a href="https://cloud.google.com/compute/">GCE</a> or <a href="https://www.digitalocean.com/products/droplets/">Digitalocean</a> or any other cloud service provider. Most of these service providers you free initial signup credits which you can use to provision a basic machine for yourself. Use any OS as the base for your machine(it just has to support installation of docker). For this example we would be using an ubuntu OS. Once the VM is up and running, get inside it and follow the following steps.</p><ul><li>Install docker and docker-compose in it.<a href="https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-on-ubuntu-16-04">(reference)</a></li><li>Setup connection to your docker registry by logging in using docker login</li><li>Test of you are able to connect to your docker registry by trying to pull the docker image using docker pull &lt;docker-image&gt; (&lt;docker-imge&gt; is the name of the image build in the previous steps)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*5_Faeb_oFMdqhjHd8rdjOw.jpeg" /></figure><ul><li>Copy your docker-compose.yml file created in the above steps to your VM. You can do that by <br>a. Manually creating an empty file (vi docker-compose.yml ) and copy-pasting your content.<br>b. Commiting your code to a git repository and cloning that repository here.<br>c. Cloning my repository by calling git clone <a href="https://github.com/vedsm/to-beer-or-not-to-beer.git">https://github.com/vedsm/to-beer-or-not-to-beer.git</a> and editing the docer-image-name to the docker-image-name built by you.</li><li>cd to the folder which contains your docker-compose.yml (e.g. cd to-beer-or-not-to-beer)and run docker-compose -f docker-compose.yml up . This will pull the docker-image (if it wasn’t pulled earlier) and deploy the image. Run docker-compose -f docker-compose.yml up -d if you want the server to be running in the background.</li><li>Now your server is running. You can check the status of your server anytime by going into your VM and calling docker ps .This will tell you info on the running containers. You can look at logs of your server by calling docker logs -f &lt;container id or name&gt; .</li><li>For being able to call this Prediction API from anywhere you need to open the port “4200” for external traffic in your VM. This setting is generally available in the networks section of your VM in the cloud service provider’s web portal. You can also control who is allowed to call your API by specifying specific IP or a range of IPs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uhe9siHT-vhKAcMBX9lTQw.png" /><figcaption>Azure example for exposing the port 4200 of your VM</figcaption></figure><p>Now your API is up and ready to be consumed. Note the public IP address or the public domain name of your server(this is available in the VM page of the cloud service provider’s web portal) and send a POST request to it ( <a href="http://0.0.0.0:4200/isItBeer">http://&lt;public-ip|dns-of-VM&gt;:4200/isItBeer</a> ) from POSTMAN.</p><p>Your prediction API can now be consumed from anywhere and by anyone in the world. You can now create and distribute a website and/or an app to provide ease of use for this API. Well done!</p><p>Next steps will be to enhance our prediction server with some more functionalities like training a better model or adding a new API. After each of these refinement iterations we would have to build a new image; push it to our docker-repository; go inside the VM and pull the latest image; deploy the latest image. These steps can be cumbersome, and some human error is bound to creep into it. <a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-4-automate-1f20d784d64a">For this we will be setting up a CI/CD (continuous integration and continuous deployment) in the next post. After setting it up, the refinement iteration would become a lot more easier. We would just have to do a code commit with our changes and the rest of the steps will automatically get done and deployed to the VM.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1165abd0f900" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to become a Full Stack Machine Learning Engineer(Part 2): Predict]]></title>
            <link>https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-2-predict-9b2e582ce0e0?source=rss-411b0d24b564------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b2e582ce0e0</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ved Mulkalwar]]></dc:creator>
            <pubDate>Tue, 24 Dec 2019 14:02:59 GMT</pubDate>
            <atom:updated>2019-12-24T14:15:24.473Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Objective: To create a Machine Learning prediction model, serve it by a http server on a remote cloud server and manage it like you would on production.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*9EZzRVsUVbzFi6IHZYVelw.jpeg" /></figure><p>This is a <strong>hands-on</strong> approach where we will be writing code from scratch with explanation of all the code and jargons.<br>The final code for reference can be found <a href="https://github.com/vedsm/to-beer-or-not-to-beer">here</a></p><p>This is part 2 of a 4 part series:</p><ol><li><strong>Training</strong> a very basic ML model(which tells if there is any beer in a given image) using <a href="https://keras.io/">keras</a>(a python deep-learning library). We won’t get into depth of it, mostly intuition based.(<a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-1-train-ae3928a00aef">here</a>)</li><li>Writing an independent <strong>predict</strong> function which serves the model and then s<strong>erving</strong> the prediction using a <strong>HTTP API POST</strong> request.</li><li><strong>Dockerising</strong> the prediction api. Setting up a Dockerfile and <strong>building</strong> our own <strong>docker image</strong>. <strong>Deploying</strong> the prediction docker on a <strong>cloud machine</strong>. We will be able to the <strong>call the prediction api from anywhere</strong> and see the status and logs of the server for <strong>debugging</strong>.(<a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-3-deploy-1165abd0f900">here</a>)</li><li>Setting up basic <strong>CI/CD</strong> pipeline, i.e. setup our infra such that <strong>performing a commit automatically deploys the new code</strong> to production.(<a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-4-automate-1f20d784d64a">here</a>)</li></ol><p>This is a continuation of <a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-1-train-ae3928a00aef">Part 1.</a></p><h3>Writing a predict function which serves the model.</h3><p>Now using the trained model file generated in the previous part, we can start predicting if a given image has a beer of not.</p><pre># ./src/prediction/predict.py<br>import os<br>from src import config<br>from keras.models import load_model<br>from keras.preprocessing.image import img_to_array<br>import numpy as np</pre><pre>class Predictor(object):<br>  def __init__(self):<br>    self.model_name = config.trained_model_name<br>    self.model_path = config.trained_model_file<br>    self.model = load_model(self.model_path)<br>    print(&quot;Model &quot;+ self.model_name +&quot; loaded Successfully&quot;)</pre><pre>def prepare_image(self, image):<br>    # if the image mode is not RGB, convert it<br>    if image.mode != &quot;RGB&quot;:<br>      image = image.convert(&quot;RGB&quot;)<br>    # resize the image and transform it to expected input for the model. Note that this is the same ration which was used while training.<br>    image = image.resize(size=(config.img_width, config.img_height))<br>    image = img_to_array(image)<br>    image = np.expand_dims(image, axis=0)<br>    # return the processed image<br>    return image</pre><pre>def predict(self, image):<br>    result = self.model.predict(image)[0][0]<br>    print(&quot;prediction-&gt;&quot;, result)<br>    return result</pre><p>The “Predictor” class contains all the functions which we would be using to interact with our model.</p><ul><li>__init__ function loads the trained model(which was trained in the earlier part) using the load_model function.</li><li>prepare_image function would help us convert any given image into an input format which our model can read. In this case any image would first get resized into a image size which is same as our trained model’s input layer, then converted to an array and then the dimensions of this will get expanded using numpy library.</li><li>predict function would call the model’s prediction function and return 0 if there is beer and 1 if there is no beer in the provided image</li></ul><p>Lets try if the prediction works by passing it a local file stored on our system.</p><pre># ./src/prediction/run_prediction_on_file.py<br>import os<br>from src import config<br>from src.prediction.predict import Predictor<br>from PIL import Image</pre><pre>if __name__ == &quot;__main__&quot;:<br>  # test_validation<br>  test_img_path = config.test_img_dir_file<br>  print(&quot;test_img_path-&gt;&quot;, test_img_path)<br>  predictor = Predictor()<br>  image = Image.open(test_img_path)<br>  image = predictor.prepare_image(image)<br>  predictor.predict(image)</pre><p>Before running this piece of code, save an image of beer(or one which does not have any beer) in the location saved at test_img_dir_file in the config.py file. We will be testing our prediction model on this file. Try running the code by python3 ./src/prediction/run_prediction_on_file.py . The code first initiates the Prediction class(which will call the __init__ function of Predict class) where the model loading happens. After that the image gets prepared and then the prediction happens. If everything goes well, “1” or “0” will get printed on the console depending on what our model found in the image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*u5EaIVXs0XSg0AT2xP1A9A.png" /></figure><h4>Serving the prediction using a HTTP API POST request.</h4><p>Now that we have our model predicting if an image has beer, we want to make it easier for the prediction to be called. Updating the config file with a new image’s location is not that straightforward process. So Lets make calling prediction easier by creating a basic http API which will serve the predictions behind an http POST request. We will start by creating a basic Flask server.</p><p>Before that lets setup our sandbox, a new virtualenv to have dependencies needed for serving our ML api as a http api. To do that create a serving-requirements.txt file, add following dependencies to it and run pip install serving-requirements.txt (don’t forget to go out of the current training sandbox by running deactivate and create a new serving sandbox by running virtualenv serving-venv and activating that by source ./serving-venv/bin/activate )</p><p>Now onto creating the http server.<br>Creating a flask server is as simple as importing flask by from flask import Flask , then initiating the flask app by app = Flask(__name__) and finally running the app by app.run(debug=True, host=&#39;0.0.0.0&#39;, port=4200) (putting debug=True will monitor the files and will automatically restart the server whenever a file is edited). These steps are enough to create a flask app. Now an api on this app can be defined by</p><pre># ./src/serving/server.py<br>from flask import Flask</pre><pre>app = Flask(__name__)</pre><pre>@app.route(&quot;/example&quot;)<br>def root():<br>  return &quot;This the example page :)&quot;</pre><pre>if __name__ == &quot;__main__&quot;:<br>  app.run(debug=True, host=&#39;0.0.0.0&#39;, port=4200)</pre><p>Running this code by calling python3 ./src/serving/server.py will create a basic http server at ip 0.0.0.0 and port 4200 which has an api running on <a href="http://0.0.0.0/example">http://0.0.0.0:4200/example</a> . You can try opening this on the browser, you will find a page with “This the example page :)”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R18RvREG6M02IXVIKGPN4Q.png" /><figcaption>Response of calling <a href="http://0.0.0.0/example">http://0.0.0.0:4200/example</a> from browser</figcaption></figure><p>Now lets add our prediction call to this server. Edit the server.py with this.</p><pre># ./src/serving/server.py<br>from flask import Flask, request<br>from src.prediction.predict import Predictor<br>import tensorflow as tf<br>from PIL import Image<br>import io</pre><pre>app = Flask(__name__)</pre><pre>global graph<br>graph = tf.get_default_graph()</pre><pre>predictor = Predictor()</pre><pre>@app.route(&quot;/&quot;)<br>def root():<br>  return &quot;This the root page :)&quot;</pre><pre>@app.route(&quot;/health&quot;)<br>def health():<br>  return &quot;The show is going well :D&quot;</pre><pre>@app.route(&quot;/isItBeer&quot;, methods=[&#39;POST&#39;])<br>def is_it_beer():<br>  image = request.files[&quot;image&quot;].read()<br>  image = Image.open(io.BytesIO(image))<br>  # preprocess the image and prepare it for classification<br>  image = predictor.prepare_image(image)</pre><pre>with graph.as_default():<br>    prediction = predictor.predict(image)<br>    if prediction == 0:<br>      return &quot;This is beer! Tuu beer hai **!&quot;<br>    else:<br>      return &quot;This is not beer! Tuu beer nahi hai. Ja beer laa!&quot;</pre><pre>if __name__ == &quot;__main__&quot;:<br>  app.run(debug=True, host=&#39;0.0.0.0&#39;, port=4200, threaded=False)</pre><p>As you might have noticed, this API serves 3 endpoints. One is at the root level( <a href="http://0.0.0.0:4200/">http://0.0.0.0:4200/</a> ), another is a health check( <a href="http://0.0.0.0:4200/">http://0.0.0.0:4200/</a>health ) and the 3rd is API (at <a href="http://0.0.0.0:4200/">http://0.0.0.0:4200/</a>isItBeer ) which serves our prediction.<br>[Note that there are imports and code related to tensorflow and related graphs. Its because it’s also necessary to set up a reference to the tensorflow graph using tf.get_default_graph(). If this step is omitted, an exception may occur during the predict step. The condition with graph.as_default() is used to grab a threadsafe reference to the graph when making predictions. This is due to the way keras sets up the graphs internally using tensorflow and how it internally handles threading.]</p><p>We can send an image to our prediction api via a POST call and this will return “This is beer!” if the image had any beer and “This is not beer!” if the image didn’t have any beer. Try calling this via <a href="https://www.getpostman.com/">POSTMAN</a> .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RyovIrjuQbD5kDbmIqfTbQ.png" /><figcaption>Our API is working and serving the predictions! Yey!</figcaption></figure><p>Our prediction server is ready. Unfortunately this is running our personal system. For making this API available to the entire world, we would have to host it somewhere. Hosting it on our personal system won’t be good enough because of multiple reasons:</p><ul><li>Our IP address can change</li><li>Our system can be down for restart or any other reason</li><li>We might have some work which would need our server to be turned off.</li></ul><p>For these and many other reasons, we should host this server somewhere on a remote cloud machine so that its available anywhere and all the time.</p><p><a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-3-deploy-1165abd0f900">In the next parts we will be serving our http server on a remote cloud server/kubernetes cluster, and managing it like you would on production.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b2e582ce0e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to become a Full Stack Machine Learning Engineer(Part 1): Train]]></title>
            <link>https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-1-train-ae3928a00aef?source=rss-411b0d24b564------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae3928a00aef</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Ved Mulkalwar]]></dc:creator>
            <pubDate>Tue, 24 Dec 2019 13:59:37 GMT</pubDate>
            <atom:updated>2019-12-24T14:12:04.338Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Objective: To create a Machine Learning prediction model, serve it by a http server on a remote cloud server and manage it like you would on production.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aeYgMNBO2JmDR-SMxJfBng.jpeg" /></figure><p>This is a <strong>hands-on</strong> approach where we will be writing code from scratch with explanation of all the code and jargons.<br>The final code for reference can be found <a href="https://github.com/vedsm/to-beer-or-not-to-beer">here</a></p><p>This is part 1 of a 4 part series:</p><ol><li><strong>Training</strong> a very basic ML model(which tells if there is any beer in a given image) using <a href="https://keras.io/">keras</a>(a python deep-learning library). We won’t get into depth of it, mostly intuition based.</li><li>Writing an independent <strong>predict</strong> function which serves the model and then s<strong>erving</strong> the prediction using a <strong>HTTP API POST</strong> request.(<a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-2-predict-9b2e582ce0e0">here</a>)</li><li><strong>Dockerising</strong> the prediction api. Setting up a Dockerfile and <strong>building</strong> our own <strong>docker image</strong>. <strong>Deploying</strong> the prediction docker on a <strong>cloud machine</strong>. We will be able to the <strong>call the prediction api from anywhere</strong> and see the status and logs of the server for <strong>debugging</strong>.(<a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-3-deploy-1165abd0f900">here</a>)</li><li>Setting up basic <strong>CI/CD</strong> pipeline, i.e. setup our infra such that <strong>performing a commit automatically deploys the new code</strong> to production.(<a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-4-automate-1f20d784d64a">here</a>)</li></ol><h4>Project structure</h4><pre>.<br>├── data/                   # This folder contains the training data<br>  └── dataset/<br>    ├── train/ <br>      ├── beer/<br>      └── not_beer/<br>    └── validate/<br>      ├── beer/<br>      └── not_beer/<br>├── scripts                # These contain the standalone scripts.<br>├── src                    # Source files<br>  ├── training<br>    └── train.py <br>  ├── serving<br>    └── serve.py<br>  ├── prediction<br>    ├── predict.py<br>    └── run_predict_on_file.py<br>  └── config.py <br>├── test                   # Automated tests<br>├── .gitignore             # files to be ignored in commits <br>├── LICENSE<br>├── Makefile<br>├── README.md<br>├── serving-requirements.txt<br>└── training-requirements.txt</pre><p>Start with creating a blank folder mkdir to-beer-or-not-to-beer and cd into it.</p><h4>Dependency Management</h4><p>Then create a sandbox environment using <a href="https://pypi.org/project/virtualenv/">virtualenv</a>(pip install virtualenv). This will enable us to experiment with pip package versions which are different from pip packages installed on our system. Create this using virtualenv training-venv (a folder named venv gets created which will contain all your pip packages). Activate this using source ./training-venv/bin/activate</p><p>Install the dependencies which we would be needing for training<br>pip install numpy==1.17.4 tensorflow==1.14 keras==2.2.4 pillow==6.2.1 google-images-download==2.8.0</p><p>It is helpful to keep track of all the packages you are using in the project and their version numbers so that your code is easy to set-up and any new breaking changes to your dependencies don’t break your working code(This happens more often than you can imagine!).</p><p>To keep track of the packages you are using run this command pip freeze &gt; training-requirements.txt . This will create a new file “training-requirements.txt”. In this you will find the packages you have installed and their version numbers. Reinstalling the packages is as simple as running pip install -r training-requirements.txt .</p><h4>Collecting the data</h4><p>Now lets start collecting the data required. Create the scripts directory and lets create a web scrapper which will download images from google for keyword. Using this you can download your beer and not beer images. I used this script to download 1000 images of “beer” and 1000 images of “not_beer” for training and 200 each for validation. Make sure you put the data in the proper folders as shown in the project structure above.</p><pre># ./scripts/scrapers/google/image_downloader.py<br>from google_images_download import google_images_download</pre><pre>def image_download(output_dir, keywords , number_images):<br>  &quot;&quot;&quot;<br>    arguments:<br>    keywords : it refers to the keywords being searched<br>    number_images : Total number of images to be downloaded</pre><pre>&quot;&quot;&quot;<br>  response = google_images_download.googleimagesdownload()<br>  arguments = {&quot;keywords&quot;:keywords,&quot;limit&quot;:number_images,&quot;print_urls&quot;:True, &quot;output_directory&quot;: output_dir}   #creating list of arguments<br>  paths = response.download(arguments)   #passing args<br>  print(paths)   #printing absolute paths of the downloaded images</pre><pre>image_download(&#39;./data/datasets/train/beer&#39;, &#39;beer&#39;, 100)</pre><h4>Managing the configuration centrally</h4><p>Before we jump into training, lets define a config.py file which we would be using to manage the model related configuration. For trying with parameters, we would just have to tweak this file. This will help us maintain a clean code.</p><pre># ./src/config.py<br>dataset_dir = &quot;data/datasets/&quot;<br>train_data_dir = &quot;data/datasets/beer/train/&quot;<br>validation_data_dir = &quot;data/datasets/beer/validation/&quot;<br>trained_model_name = &quot;latest_model_ekdum_kadak&quot;<br>trained_model_file = &quot;trained_models/beer/latest.h5&quot;<br>epochs = 50<br>img_width = 150<br>img_height = 150<br>test_img_dir = &quot;data/datasets/beer/test_validation/&quot;<br>test_img_dir_file = &quot;data/datasets/beer/test_validation/beer.007.jpg&quot;</pre><h4>Training the model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*HhhtEySZJ6m-WzMIOORnUg.gif" /></figure><p>Now that we have the data, we are ready to train the model.<br>The right tool for an image classification job is a convnet, so let’s try to train one on our data, as an initial baseline. Since we only have few examples, our number one concern should be <strong>overfitting</strong>. Overfitting happens when a model exposed to too few examples learns patterns that do not generalise to new data, i.e. when the model starts using irrelevant features for making predictions. For instance, if you, as a human, only see three images of people who are lumberjacks, and three, images of people who are sailors, and among them only one lumberjack wears a cap, you might start thinking that wearing a cap is a sign of being a lumberjack as opposed to a sailor. You would then make a pretty lousy lumberjack/sailor classifier.</p><p>Data augmentation is one way to fight overfitting, but it isn’t enough since our augmented samples are still highly correlated. Your main focus for fighting overfitting should be the entropic capacity of your model — how much information your model is allowed to store. A model that can store a lot of information has the potential to be more accurate by leveraging more features, but it is also more at risk to start storing irrelevant features. Meanwhile, a model that can only store a few features will have to focus on the most significant features found in the data, and these are more likely to be truly relevant and to generalise better.</p><p>There are different ways to modulate entropic capacity. The main one is the choice of the number of parameters in your model, i.e. the number of layers and the size of each layer. Another way is the use of weight regularisation, such as L1 or L2 regularisation, which consists in forcing model weights to taker smaller values.</p><p>In our case we will use a very small convnet with few layers and few filters per layer, alongside data augmentation and dropout. Dropout also helps reduce overfitting, by preventing a layer from seeing twice the exact same pattern, thus acting in a way analogous to data augmentation (you could say that both dropout and data augmentation tend to disrupt random correlations occurring in your data).</p><p>The code snippet below is our first model, a simple stack of 3 convolution layers with a ReLU activation and followed by max-pooling layers. This is very similar to the architectures that Yann LeCun advocated in the 1990s for image classification (with the exception of ReLU).</p><pre>from src import config<br>import os<br>from keras.preprocessing.image import ImageDataGenerator<br>from keras.models import Sequential<br>from keras.layers import Conv2D, MaxPooling2D<br>from keras.layers import Activation, Dropout, Flatten, Dense<br>from keras import backend as K</pre><pre>if __name__ == &quot;__main__&quot;:<br>  print(&quot;Starting training using train_data_dir-&gt;&quot;, config.train_data_dir)<br>  train_data_dir = config.train_data_dir<br>  validation_data_dir = config.validation_data_dir<br>  nb_train_samples = 2000<br>  nb_validation_samples = 400<br>  epochs = config.epochs<br>  batch_size = 16</pre><pre>if K.image_data_format() == &#39;channels_first&#39;:<br>    input_shape = (3, config.img_width, config.img_height)<br>  else:<br>    input_shape = (config.img_width, config.img_height, 3)</pre><pre>model = Sequential()<br>  model.add(Conv2D(32, (3, 3), input_shape=input_shape))<br>  model.add(Activation(&#39;relu&#39;))<br>  model.add(MaxPooling2D(pool_size=(2, 2)))<br>  model.add(Conv2D(32, (3, 3)))<br>  model.add(Activation(&#39;relu&#39;))<br>  model.add(MaxPooling2D(pool_size=(2, 2)))<br>  model.add(Conv2D(64, (3, 3)))<br>  model.add(Activation(&#39;relu&#39;))<br>  model.add(MaxPooling2D(pool_size=(2, 2)))<br>  model.add(Flatten())<br>  model.add(Dense(64))<br>  model.add(Activation(&#39;relu&#39;))<br>  model.add(Dropout(0.5))<br>  model.add(Dense(1))<br>  model.add(Activation(&#39;sigmoid&#39;))<br>  model.compile(loss=&#39;binary_crossentropy&#39;, optimizer=&#39;rmsprop&#39;, metrics=[&#39;accuracy&#39;])</pre><pre># this is the augmentation configuration we will use for training<br>  train_datagen = ImageDataGenerator(rescale=1. / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)</pre><pre># this is the augmentation configuration we will use for testing:<br>  # only rescaling<br>  test_datagen = ImageDataGenerator(rescale=1. / 255)<br>  train_generator = train_datagen.flow_from_directory( train_data_dir, target_size=(config.img_width, config.img_height), batch_size=batch_size, class_mode=&#39;binary&#39;)</pre><pre>validation_generator = test_datagen.flow_from_directory(validation_data_dir, target_size=(config.img_width, config.img_height), batch_size=batch_size, class_mode=&#39;binary&#39;)</pre><pre>model.fit_generator(train_generator, steps_per_epoch=nb_train_samples // batch_size, epochs=epochs, validation_data=validation_generator, validation_steps=nb_validation_samples // batch_size)</pre><pre>model.save(config.trained_model_file)</pre><p>For data preprocessing and augmentation we use following options -&gt;</p><ul><li>rotation_range is a value in degrees (0-180), a range within which to randomly rotate pictures</li><li>width_shift and height_shift are ranges (as a fraction of total width or height) within which to randomly translate pictures vertically or horizontally</li><li>rescale is a value by which we will multiply the data before any other processing. Our original images consist in RGB coefficients in the 0-255, but such values would be too high for our models to process (given a typical learning rate), so we target values between 0 and 1 instead by scaling with a 1/255. factor.</li><li>shear_range is for randomly applying <a href="https://en.wikipedia.org/wiki/Shear_mapping">shearing transformations</a></li><li>zoom_range is for randomly zooming inside pictures</li><li>horizontal_flip is for randomly flipping half of the images horizontally --relevant when there are no assumptions of horizontal asymmetry (e.g. real-world pictures).</li><li>fill_mode is the strategy used for filling in newly created pixels, which can appear after a rotation or a width/height shift.</li></ul><p>After this code completes execution, if everything goes well, a trained model file will get created in “./trained_models/beer/latest.h5” . The network will get trained faster if this code is run on a machine with GPU. The predictions don’t need GPU. it only need the trained weights of the model and the architecture. So we will be using this generated file run the predictions separately, independent of our training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*O-Bm4M1qxBn97viRrCsUMw.jpeg" /><figcaption>Getting the perfect model requires many iterations</figcaption></figure><p>Note that this is just a basic model to provide you with intuition. Using a transfer learning on a pre-trained model might give a much better accuracy. This is enough to begin with. We can always come back later and train a better model. In the end a “&lt;something&gt;.h5” file will get generated which we will be using for prediction. This file can directly be used in the Prediction as it contains the information regarding the network architecture used and the weights of the neurons of the model.</p><p><a href="https://medium.com/@vedmkw/guide-to-become-a-full-stack-machine-learning-engineer-part-2-predict-9b2e582ce0e0">In the next parts we will be serving it by a http server on a remote cloud server and managing it like you would on production.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae3928a00aef" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>