<?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 Satyajit Ghana on Medium]]></title>
        <description><![CDATA[Stories by Satyajit Ghana on Medium]]></description>
        <link>https://medium.com/@satyajitghana?source=rss-4ccf9d79205d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*rMcB_vpHyypCGXJZUkJVJw.jpeg</url>
            <title>Stories by Satyajit Ghana on Medium</title>
            <link>https://medium.com/@satyajitghana?source=rss-4ccf9d79205d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 23:23:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@satyajitghana/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[Working with Large Dependencies (≥500MB) with AWS Lambda and EFS (Amazon Elastic File System)]]></title>
            <link>https://satyajitghana.medium.com/working-with-large-dependencies-500mb-with-aws-lambda-and-efs-amazon-elastic-file-system-137509e03c1a?source=rss-4ccf9d79205d------2</link>
            <guid isPermaLink="false">https://medium.com/p/137509e03c1a</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Satyajit Ghana]]></dc:creator>
            <pubDate>Sun, 03 Jan 2021 14:04:43 GMT</pubDate>
            <atom:updated>2021-01-03T14:04:43.178Z</atom:updated>
            <content:encoded><![CDATA[<p>This story begins with a lot of hard work put into deploying ML models into AWS Lambda and exhausting my entire free S3 Quota. I’ve built backends with AWS Lambda and Serverless framework, it makes it really easy to build and deploy model backends. But . . . continue reading . . .</p><h3>What is the storage issue with Lambda ?</h3><p>All of my backends are dependent on PyTorch and Torchvision, all deployments were fine until PyTorch 1.6.0 arrived, this exhausted my lambda storage, you get 500MB (uncompressed requirements) of storage in /tmp directory of lambda, and serverless python requirements also reside in that directory. and PyTorch 1.6.0 exceeded that. I had no other way to make it work, other than moving to Heroku, which solved all my problems !! Heroku has a “compressed requirements” slug limit of 500MB, and GBs of temporary storage, ofcourse that means when the system goes to down state all of the temp storage is released, but I had no state ! all I needed was for my dependencies to work.</p><p>Another huge issue was that I couldn’t bundle OpenCV, PyTorch and ScaPy models in the same Lambda due to the 500MB dependencies limit, I had to make different lambdas for different parts of the preprocessing and inferencing.</p><p>And on top of all this issues, I exhausted my S3 Quota 😕, what a bummer. It turns out serverless uploads to S3 and then deploys the Lambda, and it also keeps last 5 deployments, so like 1.2GB of space per lambda in S3, and for the free tier I get a max of 5GB, of-course it had to exhaust, in my experimentation phase I push about 4–5 times at-least to get the backend to work.</p><h3>What’s the solution ?</h3><p>I searched a lot for a good fitting solution, to solve my storage issue exhaustion, and also my deployment times, it took a lot of time just on deployment, since I always had to upload the 250MB slug to S3 and deploy every single time I changed something in my backend.</p><p>The deployment time can be solved easily by using Lambda Layers, which is a wonderful concept! it lets you create different layers with different dependencies, and you can simply always update your backend function without needing to change the layers, the layers are responsible to handle the dependencies, but . . . this DOES NOT solve my 500MB limit, all of the layers combined can have a total storage of 500MB, this means I can’t use the latest PyTorch 1.7.1, bummer . . .😖😕</p><h3>Then comes EFS (Amazon Elastic File System)</h3><p>Finally after discovering that EFS works with Lambda out-of-the-box I had to try this out, was it true ? could I use PyTorch+OpenCV+SpaCy+MyModels all on a single Lambda ?</p><p>yeah yeah read on . . .</p><p>I’ll be using Serverless framework to deploy my backend, since it makes it really easy to setup everything, I don’t have to do much work setting up the API Gateway and stuff.</p><p>More about EFS here: <a href="https://docs.aws.amazon.com/efs/latest/ug/how-it-works.html">https://docs.aws.amazon.com/efs/latest/ug/how-it-works.html</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/0*OlCdzphjNgFb-mUZ.png" /><figcaption>EFS FileSystem</figcaption></figure><h4>Let’s create an EFS instance !</h4><p>Go to your AWS Console -&gt; EFS -&gt; Create File System</p><p>(remember the VPC being used here)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*yvEH3AZyDvmHZ4qnlkz-yA.png" /></figure><p>Now go ahead and create an “Access Point” for this EFS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*oLYb5r94SA1jSEAvw1tGvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*PHUJyZmwyARhjAubaJS2lw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*91pmwSRGnBXOey5F5kIO7A.png" /></figure><p>The above just means that this Access Point has full access to the EFS</p><p>Now we have to somehow copy our dependencies into this newly created EFS</p><p>To make sure that our dependencies will definitely work with lambda, we’ll lambda’s docker image to get the dependencies first.</p><p>I built my docker image, mounted a folder, and installed the packages into that folder,</p><p>Here’s my Dockerfile</p><pre># since this will be deployed to lambda<br>FROM lambci/lambda:build-python3.8</pre><pre># this is just for local testing<br>RUN pip install uvicorn<br>EXPOSE 8000</pre><pre>WORKDIR /app</pre><pre>COPY requirements.txt .<br>RUN pip install -r requirements.txt</pre><pre>COPY . .</pre><pre>ENTRYPOINT [ &quot;uvicorn&quot;, &quot;tejas.main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><p>Above basically is installing all dependencies and copying my code into the image, nothing fancy</p><p>I built the image with docker build -t tejas .</p><p>and ran it with mounting the empty requirements folder into the container</p><pre>docker run -it --rm -v $(pwd)/requirements:/app/requirements --entrypoint /bin/bash tejas</pre><p>Then installed requirements into the requirements folder</p><pre>pip install -r requirements.txt -t requirements</pre><p>-t option for pip tells it to install the collected requirements in that given folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iVVeTpdiLZsQxELrtUGJKg.png" /><figcaption>Installing the requirements in the requirements folder mounted into docker container</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uGbIaD9-4e_Pv1Ftt-e38Q.png" /><figcaption>These are all the requirements copied to our host machine from the docker container</figcaption></figure><h3>It’s EC2 Time</h3><p>Now we need to spin and EC2 instance and copy these requirements to EC2 first, so go to your EC2 Dashboard, select a simple Ubuntu server and start it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5HWq9BVlfJ8pH_3mP0t1Jw.png" /><figcaption>EC2 selection</figcaption></figure><p>But you wont be able to mount your EFS, yet . . . to do that, go to the Security Groups and add an Inbound Connection to the SG associated with your EFS’s VPC, to allow EC2 to mount NFS over this VPC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*meUz1IMAzIZdngGkdwlaeQ.png" /><figcaption>Allowing NFS Inbound rule into EFS’s default VPS’s Security Group</figcaption></figure><p>When choosing the SG here, select the SG of your newly created EC2, which should probably come as launch-wizard-x.</p><p>Now lets connect to our EC2 and mount this EFS, go to your EC2 instance and click on CONNECT, you’ll get something like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*FAR87zM1kRhCkG0FC5cdEA.png" /><figcaption>Command to SSH into EC2</figcaption></figure><p>Now you can use your pem file and above command to connect to EC2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxi3IJwanKWDlt57EzpXnw.png" /></figure><p>To mount EFS volume, go to your EFS instance, and then click on ATTACH, you’ll get something like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jck0Kd0H-tS8Tlveo85YIg.png" /><figcaption>Command to mount EFS</figcaption></figure><p>Copy the “Using the NFS Client” command,</p><p>Run this in your EC2 to install the NFS Utilities:</p><p>sudo apt install nfs-common</p><p>and make an efs directory</p><p>mkdir efs</p><p>Now you can mount your NFS !</p><pre>sudo mount -t nfs4 -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport fs-xxxxxx.efs.ap-south-1.amazonaws.com:/ efs</pre><p>If you do a quick df -h you’ll see that your EFS is now mounted</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*4GHhhSjfdgbepLFIpd5yKA.png" /><figcaption>EFS mounted into EC2</figcaption></figure><p>I had ran into timeout errors because my SG weren’t right, the above steps shouldn’t cause any issues, if you aren’t able to mount then look into: <a href="https://docs.aws.amazon.com/efs/latest/ug/troubleshooting-efs-mounting.html#mount-hangs-fails-timeout">https://docs.aws.amazon.com/efs/latest/ug/troubleshooting-efs-mounting.html#mount-hangs-fails-timeout</a></p><p>Now we can copy over our requirements to this EFS, I’ll use scp for that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ch4Jz2zfq85SIo4myHchoQ.png" /><figcaption>Copying Requirements from local machine to EC2 via SCP</figcaption></figure><pre>scp -i &quot;satyajit.pem&quot; -r /mnt/d/Projects/ProjektTejas/tejas-service/requirements/ ubuntu@ec2-xx-xx-xx-xx.ap-south-1.compute.amazona<br>ws.com:/home/ubuntu/</pre><p>Now simply copy over the requirements to the EFS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7zSklmSrQcZPMDveDKHCjw.png" /><figcaption>Requirements copied to EFS via EC2</figcaption></figure><p>Isn’t this just amazing !!!!! You get 5 GB for free EFS storage, and you can use multiple lambdas with the same dependencies! and as soon as I update the EFS files, all the lambdas quickly pickup the new dependencies on new invocation !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6M1gJcQPBWBxpTkxsGwMrQ.png" /><figcaption>EFS Total Size</figcaption></figure><p>As you can see above all the dependencies in total are 854 MiB, and Lambda works with all of them ! damn right ?</p><p>Here’s my requirements.txt</p><pre><a href="https://download.pytorch.org/whl/cpu/torch-1.7.1%2Bcpu-cp38-cp38-linux_x86_64.whl">https://download.pytorch.org/whl/cpu/torch-1.7.1%2Bcpu-cp38-cp38-linux_x86_64.whl</a><br><a href="https://download.pytorch.org/whl/cpu/torchvision-0.8.2%2Bcpu-cp38-cp38-linux_x86_64.whl">https://download.pytorch.org/whl/cpu/torchvision-0.8.2%2Bcpu-cp38-cp38-linux_x86_64.whl</a><br>fastapi==0.63.0<br>mangum==0.10.0<br>loguru==0.5.3<br>boto3==1.16.47<br>python-multipart==0.0.5</pre><p>There are some drawbacks though</p><p>As you have large dependencies and you’ll be reading those files every time your Lambda starts up, it’ll cost you Read Operations, and EFS has a different way of billing you for it.</p><p>Also if multiple lambdas are using the common EFS for dependencies, and you decide to update it someday, you might break some of your lambdas as they might be holding on to some specific dependency versions. Well but i dont think its really an issue, I like to live on the edge 😂😂 bring in all the updated dependencies.</p><p>You’ll lose Internet access in Lambda, since you are on a VPC, but that can be solved easily: <a href="https://stackoverflow.com/questions/62240023/aws-lambda-function-cant-invoke-another-lambda-function-in-the-same-vpc/65541460#65541460">https://stackoverflow.com/questions/62240023/aws-lambda-function-cant-invoke-another-lambda-function-in-the-same-vpc/65541460#65541460</a></p><h3>Deploying Serverless with EFS attached</h3><p>Now I’ll deploy the serverless application 😁</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lMFcl5Eat0hPhxHRkYbE8Q.png" /></figure><h4>Look at that cute little zip file 😵😚😍 of just 9.02 KB ! awww, compared to 200–240 MB of zips being uploaded on every deployment, that’s quite an improvement, isn’t it ?</h4><p>My original plan was to use this Lambda to train a Deep Learning model, and I was successful !! (BTW this is one Lambda calling another Lambda to train the model, and both of them share the same EFS)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vD22NlucFBppXFo_k6bILA.png" /><figcaption>CloudLogs for Model Training</figcaption></figure><p>Here’s my serverless.yml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cab85b468e41287661231e69ccaecc54/href">https://medium.com/media/cab85b468e41287661231e69ccaecc54/href</a></iframe><p>This is an amazing blog on how to use EFS with Lambda : <a href="https://aws.amazon.com/blogs/compute/using-amazon-efs-for-aws-lambda-in-your-serverless-applications/">https://aws.amazon.com/blogs/compute/using-amazon-efs-for-aws-lambda-in-your-serverless-applications/</a></p><p>Some interesting links:</p><ul><li><a href="https://stackoverflow.com/questions/62240023/aws-lambda-function-cant-invoke-another-lambda-function-in-the-same-vpc/65541460#65541460">https://stackoverflow.com/questions/62240023/aws-lambda-function-cant-invoke-another-lambda-function-in-the-same-vpc/65541460#65541460</a></li><li><a href="https://docs.aws.amazon.com/efs/latest/ug/wt1-test.html">https://docs.aws.amazon.com/efs/latest/ug/wt1-test.html</a></li><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/services-efs.html">https://docs.aws.amazon.com/lambda/latest/dg/services-efs.html</a></li><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html">https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=137509e03c1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Human Pose Estimation and Quantization of PyTorch to ONNX Models — A Detailed Guide]]></title>
            <link>https://satyajitghana.medium.com/human-pose-estimation-and-quantization-of-pytorch-to-onnx-models-a-detailed-guide-b9c91ddc0d9f?source=rss-4ccf9d79205d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9c91ddc0d9f</guid>
            <category><![CDATA[artificalintelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[onnx]]></category>
            <category><![CDATA[quantization]]></category>
            <category><![CDATA[human-pose-estimation]]></category>
            <dc:creator><![CDATA[Satyajit Ghana]]></dc:creator>
            <pubDate>Tue, 25 Aug 2020 06:20:21 GMT</pubDate>
            <atom:updated>2020-08-25T17:26:06.027Z</atom:updated>
            <content:encoded><![CDATA[<h3>Human Pose Estimation and Quantization of PyTorch to ONNX Models — A Detailed Guide</h3><p>The story begins with a assignment given to me that needed me to deploy a Monocular Single Human Pose Estimation model on AWS Lambda. Me being a student, i prefer to be in the free tier of Lambda, where we get about 3GB of RAM and 500MB storage, the storage is quite less, and i had troubles fitting everything in one lambda, so i thought of trying out ONNX instead of using PyTorch. So let’s see how HPE works and how i converted a PyTorch Model to ONNX and then Quantized it.</p><p>Buckle up, this is going to be a long story !</p><p>If TL DR; then just see the below colab notebook</p><ul><li><a href="https://github.com/satyajitghana/TSAI-DeepVision-EVA4.0-Phase-2/blob/master/05-HumanPoseEstimation-ONNX/HumanPoseEstimation_ONNX_Quant.ipynb">satyajitghana/TSAI-DeepVision-EVA4.0-Phase-2</a></li><li><a href="https://colab.research.google.com/drive/1uFLEw-p9Syui0GoDMsZSIoyiCyILVoCO?usp=sharing">Google Colaboratory</a></li></ul><h3>Monocular Human Pose Estimation</h3><p>Human pose estimation is the process of estimating the configuration of the body (pose) from a single, typically monocular, image. It can be applied to many applications such as action/activity recognition, action detection, human tracking, in movies and animation, virtual reality, human-computer interaction, video surveillance, medical assistance, self-driving, sports motion analysis, etc.</p><p>Broadly there are 4 HPE Methods</p><ul><li>Generative and Discriminative (3D Single Person)</li><li>Top Down and Bottom Up (Multi-Person)</li><li>Regression and Detection Based (Single Person)</li><li>One-Stage and Multi-Stage</li></ul><p>But in this story we will be using the Bottom Up Approach, i.e. we will be detecting the body parts (joints, limbs, or small template patches) and then joining them to create our human body.</p><p>The model i am referring to here is from the <a href="https://arxiv.org/pdf/1804.06208.pdf">this</a> Paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*NAEoj1gL_VGAQCmSRsCqqw.png" /></figure><p>The paper describes and compares their model to SOTA hpe models that use the Hourglass model structure, the paper shows how even a very simple model, by adding deconv layers to the ResNet backbone can also give pretty good results. The code for this ResNet backbone PoseNet can be found <a href="https://github.com/microsoft/human-pose-estimation.pytorch">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*7cUfWGNb8KZvZQvNV4aiXw.png" /><figcaption>Simple Pose Benchmark</figcaption></figure><p>As you can see that a simple conv network has got a pretty good accuracy.</p><p>Enough of the model talk ! (i recommend reading the beautiful paper i referred above), Now let’s get to do some inferencing on the model and see what it outputs. Throughout this story i will be using <a href="http://colab.research.google.com/">Google Colab</a> for running everything.</p><p>Start by cloning the <a href="https://github.com/microsoft/human-pose-estimation.pytorch">human-pose-estimation.pytorch</a> repository</p><pre>! git clone https://github.com/microsoft/human-pose-estimation.pytorch &amp;&amp; cd human-pose-estimation.pytorch &amp;&amp; git checkout 18f1d0fa5b5db7fe08de640610f3fdbdbed8fb2f</pre><p>Add it to the sys.path so colab knows where the library is</p><pre>import sys</pre><pre>if &quot;/content/human-pose-estimation.pytorch/lib/&quot; not in sys.path:</pre><pre>  sys.path.insert(0, &quot;/content/human-pose-estimation.pytorch/lib/&quot;)</pre><p>Import everything !</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d01c02ec6a0ed7c0107ec212850dd21/href">https://medium.com/media/0d01c02ec6a0ed7c0107ec212850dd21/href</a></iframe><p>For this story we will use the ResNet50 model trained on 256x256 images of the <a href="http://human-pose.mpi-inf.mpg.de/">MPII Dataset</a>, it has 16 human body points. All of the MPII models can be found below</p><p><a href="https://drive.google.com/drive/folders/1g_6Hv33FG6rYRVLXx1SZaaHj871THrRW">pose_mpii - Google Drive</a></p><p>set the CONFIG_FILE and MODEL_PATH variables appropriately</p><pre>CONFIG_FILE = &#39;/content/human-pose-estimation.pytorch/experiments/mpii/resnet50/256x256_d256x3_adam_lr1e-3.yaml&#39;</pre><pre>MODEL_PATH = &#39;/content/pose_resnet_50_256x256.pth.tar&#39;</pre><p>update the config file</p><pre>update_config(CONFIG_FILE)</pre><pre>config.GPUS = &#39;&#39; # we are running on CPU</pre><p>Now we will load the model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a47b45e0146e334d46eabe4eac5e4be/href">https://medium.com/media/9a47b45e0146e334d46eabe4eac5e4be/href</a></iframe><p>We’ll be now using this guy’s image to detect pose. I wonder who this might be 🤔</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*c1djEQo2TfSmwcN5Ki9MlA.jpeg" /><figcaption>yeah this me</figcaption></figure><p>Time to finally run the model on the image ! (ofcourse doing some image transformations first), you’ll notice something called JOINTS in below code, we’ll use those later ! they are from the MPII dataset, and our model will output those 16 human points points.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2007b9b1642a31e7f4e7b1b28fba1daa/href">https://medium.com/media/2007b9b1642a31e7f4e7b1b28fba1daa/href</a></iframe><p>What now ? Lets do some visualizations !</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82be3b8cdfffe5c68c2e8def14b9e5b3/href">https://medium.com/media/82be3b8cdfffe5c68c2e8def14b9e5b3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*Kvw4a639NMIslywaBvB3Aw.png" /></figure><p>Looks Amazing right ! thats Bottom Up HPE approach ! we never detected a bbox for my body, just the 16 parts !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*PLATFT54cNgrlWqxblMkZQ.png" /></figure><p>What next ? just connect the dot !</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac0e2c9a5d31dea72a2e1b421ca03a46/href">https://medium.com/media/ac0e2c9a5d31dea72a2e1b421ca03a46/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*oqAXPrMKRAtoubD5ursbSQ.png" /></figure><p>It got all the 16 points ! 😲 (you can reduce the THRESHOLD if it didn’t)</p><p>But did you notice ? that lady in the back isn’t detected ? that’s because our model was trained on large human images only ! if we were to use a hourglass model kind of architecture, or maybe something like YOLO does for creating different resolution(scales) representations of the image, then we would have detected the pose for that lady as well.</p><h3>Converting to ONNX and Quantizing</h3><p>What is ONNX ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*OZA-la4uErLMTK--xGR6Tg.png" /></figure><p>ONNX is an open format built to represent machine learning models. ONNX defines a common set of operators — the building blocks of machine learning and deep learning models - and a common file format to enable AI developers to use models with a variety of frameworks, tools, runtimes, and compilers.</p><p>Install onnx and onnxruntime, we’ll need these</p><pre>! pip install onnx onnxruntime</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/994f010b4dd4006a7f0244a699b1b38f/href">https://medium.com/media/994f010b4dd4006a7f0244a699b1b38f/href</a></iframe><pre>print_size_of_model(model)</pre><pre>Size (MB): 136.326509</pre><p>Convert it to ONNX !</p><p>Also here is a tutorial</p><p><a href="https://pytorch.org/tutorials/advanced/super_resolution_with_onnxruntime.html">(optional) Exporting a Model from PyTorch to ONNX and Running it using ONNX Runtime - PyTorch Tutorials 2.4.0+cu121 documentation</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca97b86deb23a6c8122c9a04ad209e1b/href">https://medium.com/media/ca97b86deb23a6c8122c9a04ad209e1b/href</a></iframe><pre>Size (MB): 136.247923</pre><p>Now we’ve successfully converted our model to ONNX</p><p>At this point i tried to simply deploy the model to AWS Lambda, but the model size 130MB was too much, it didn’t fit in the 500MB provided.</p><h3>Quantize it all !</h3><p>A question you might have in your mind is, why not use the PyTorch’s Quantization ?</p><p>Well well well, i did take a look at that <a href="https://pytorch.org/tutorials/intermediate/quantized_transfer_learning_tutorial.html">here</a>, the issue being, but take a look at <a href="https://discuss.pytorch.org/t/am-i-correct-in-concluding-that-resnet-that-comes-with-pytorch-cant-be-quantized-by-pytorch/82405">this</a>, TL DR; the models we have right now cannot be quantized, only a few very special models can be like BERT, LSTM, or else you have to modify your model and add some special layers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bb501f6b0a2ccfdee957f8fac34d6df/href">https://medium.com/media/3bb501f6b0a2ccfdee957f8fac34d6df/href</a></iframe><pre>Size (MB): 65.933789</pre><p>Did you see that ? the model is half the size now ! although this comes with a caveat that the accuracy is reduced.</p><h3>Running the model on ONNX Runtime</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c631ec6b68a1e76afffaecf82ad055d2/href">https://medium.com/media/c631ec6b68a1e76afffaecf82ad055d2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ie9HFcP6TIwM16f_jhyhcw.png" /></figure><p>In the Quant Model i lost a hand 😟 maybe reducing threshold might bring it back</p><p>But what did i gain from doing all this ?</p><p>onnxruntime for cpu is really small, and now i am not dependent upon PyTorch libraries !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*J7euhcqHjTbmsiztQrCx9Q.png" /></figure><p>Look at the size ! its teeny-tiny for cpu, for my current deployment i was using torch-1.6.0 and torchvision-0.7.0 which took over 500MB uncompressed. something i can’t afford in AWS Lambda free tier. Now that i have the ONNX model and a really small runtime, everything will fit in a single free Lambda runtime !</p><p>Plus i have a plan to use onnx.js and run the model on the client side itself ! it’ll save the roundtrips made to Lambda.</p><p>Checkout the deployment at: <a href="https://thetensorclan-web.herokuapp.com/">https://thetensorclan-web.herokuapp.com/</a></p><p>That’s it Folks ! you now know how simple HPE works ! and how we can convert our PyTorch/Tensorflow/Caffe2 models to ONNX. And how we can then Quantize the model.</p><p>Below is the link to the Colab Notebook where all this code is situated, you can play with the data, modify stuff and rerun the notebook</p><p><a href="https://github.com/satyajitghana/TSAI-DeepVision-EVA4.0-Phase-2/blob/master/05-HumanPoseEstimation-ONNX/HumanPoseEstimation_ONNX_Quant.ipynb">satyajitghana/TSAI-DeepVision-EVA4.0-Phase-2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9c91ddc0d9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speed-Up your Model Training w/ TPU on Google Colab]]></title>
            <link>https://satyajitghana.medium.com/speed-up-your-model-training-w-tpu-on-google-colab-c55ac0f634d9?source=rss-4ccf9d79205d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c55ac0f634d9</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[tpu]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[google-colab]]></category>
            <dc:creator><![CDATA[Satyajit Ghana]]></dc:creator>
            <pubDate>Wed, 20 May 2020 11:23:09 GMT</pubDate>
            <atom:updated>2020-05-20T11:48:03.874Z</atom:updated>
            <content:encoded><![CDATA[<p>This is not a post for strictly benchmarking TPUs vs GPUs on a highly technical level, so let’s not get into too much of the technical details, its just my experience with TPUs and how the deep learning world is affected by it.</p><p>Model: ResNet-Unet like architecture, has ~30M parameters</p><p>Dataset: 1200K images (96x96x3)</p><p>seems straight forward right ? but there were many barriers even before i started training for a single epoch.</p><p>My first and obvious choice was to train the model on colab with those sweet little Tesla P100s (16GB), but there were memory issues</p><p>CUDA OOM (out-of-memory): The model size was ~135MB and my batch_size was 128, as per my calculations, it should fit in gpu memory, but then after a lot of poking around the model i realised my model is way too densly connected and the space required for allocating the gradients doesn’t fit in memory, something that i should have seen coming.</p><p>So now that out of the way i simply converted all my concatenation ops into addition ops and now it worked with a batch_size of 128, here is my code for it, i also timed every section of my code to see which part of the code consumes most of the time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab242470ba9df8a706035368c1b82f34/href">https://medium.com/media/ab242470ba9df8a706035368c1b82f34/href</a></iframe><p>and here’s the output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*chOqgo4lzGz9NCC7yEfxQA.png" /><figcaption>train on gpu (P100)</figcaption></figure><p>So in summary the model took ~2331s to train on one epoch, which is acceptable, but still i want it be be even less.</p><p>I’m not rich enough to buy 4xP100 and train them on parallel, i rely on colab for all my training.</p><p>The next best option is to use a TPU !</p><p>Tensorflow models have good support for TPU and its straight forward with Estimator API to train on TPU, but since i was already comfortable with PyTorch i did not want to move on to Tensorflow, one option is to use PyTorch Lightning, and you can easily find colab notebooks for running a model on TPU</p><p><a href="https://colab.research.google.com/drive/1-_LKx4HwAxl5M6xPJmqAAu444LTDQoa3">Google Colaboratory</a></p><p>But i felt most of these don’t work properly, and seems buggy, and there are a lot of issues, but will surely check it out some other time, for now i wanted to run my model with the least amount of changes.</p><blockquote>This repo is good start if you want to get started on working with TPUs https://github.com/pytorch/xla/tree/master/contrib/colab , try running their notebooks on colab</blockquote><p>So, i decided to follow the PyTorch XLA tutorials <a href="https://github.com/pytorch/xla/blob/master/contrib/colab/resnet18-training.ipynb">https://github.com/pytorch/xla/blob/master/contrib/colab/resnet18-training.ipynb</a></p><p>And came up with this code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/486801268acca44b4eb8436277235d6e/href">https://medium.com/media/486801268acca44b4eb8436277235d6e/href</a></iframe><p>Notice, there isn’t much changes (zero changes to the model), the only thing is to create a Parallel Loader, and then create a Sampler, then simply train the model, few things to note:</p><blockquote>A TPU is a Tensor processing unit. Each TPU has 8 cores where each core is optimized for 128x128 matrix multiplies. In general, a single TPU is about as fast as 5 V100 GPUs!</blockquote><blockquote>A TPU pod hosts many TPUs on it. Currently, TPU pod v2 has 2048 cores! You can request a full pod from Google cloud or a “slice” which gives you some subset of those 2048 cores. [1]</blockquote><ul><li>xm.optimizer_step() does not take a barrier argument this time</li><li>Model was declared outside the run function and was sent to Xla Device in the run fucntion whereas when using single TPU’s we did it simultaneously in one place</li><li>Something called Paraloader is wrapped around dataloader</li><li>USE of XLA_USE_BF16 Environment variable</li><li>And off course we now run the spawn function to execute the model training and eval</li><li>You get 8 TPU cores on Colab</li></ul><p>So a run on a TPU now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sWfSSwd3MaKmZersBgLqUA.png" /><figcaption>sample run on TPUs</figcaption></figure><p>Note that all the TPU cores run the model simultaneously, so in total it took ~740s for the model to run for one epoch, crazy amazing right !? 3X speedup ! now instead of training 1 epoch on GPU i could train 3 epochs on TPU ! and depending upon the model you could get even more speedup !</p><p>And these were the outputs from the model, basically is a mask+depth predictor, something i need to experiment is on the loss functions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*276b8AnHtaGtzf3zCTQvnQ.png" /><figcaption>model output</figcaption></figure><p>Further Improvements:</p><ul><li>Use PyTorch Lightning ?</li><li>Experiment with BFloats</li></ul><p>Further Reading</p><ul><li><a href="https://pytorch-lightning.readthedocs.io/en/latest/tpu.html">https://pytorch-lightning.readthedocs.io/en/latest/tpu.html</a></li><li><a href="https://github.com/pytorch/xla">https://github.com/pytorch/xla</a></li><li><a href="https://www.kaggle.com/tanulsingh077/pytorch-xla-understanding-tpu-s-and-xla">https://www.kaggle.com/tanulsingh077/pytorch-xla-understanding-tpu-s-and-xla</a></li><li><a href="https://www.kaggle.com/c/flower-classification-with-tpus/discussion/129820">https://www.kaggle.com/c/flower-classification-with-tpus/discussion/129820</a></li><li><a href="https://www.tensorflow.org/xla">https://www.tensorflow.org/xla</a></li></ul><p>References</p><p>[1] . <a href="https://pytorch-lightning.readthedocs.io/en/latest/tpu.html">https://pytorch-lightning.readthedocs.io/en/latest/tpu.html</a></p><p>GitHub Source Code for my model: <a href="https://github.com/satyajitghana/ProjektDepth">https://github.com/satyajitghana/ProjektDepth</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c55ac0f634d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to upgrade to 25GB RAM in Google Colab possibly w/ Tesla P100 GPU for Free]]></title>
            <link>https://satyajitghana.medium.com/how-to-upgrade-to-25gb-ram-in-google-colab-possibly-w-tesla-p100-gpu-for-free-115e7679f5de?source=rss-4ccf9d79205d------2</link>
            <guid isPermaLink="false">https://medium.com/p/115e7679f5de</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[free-gpu]]></category>
            <category><![CDATA[google-colab]]></category>
            <dc:creator><![CDATA[Satyajit Ghana]]></dc:creator>
            <pubDate>Sat, 16 May 2020 11:26:19 GMT</pubDate>
            <atom:updated>2020-05-16T11:26:19.003Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*kIm24zclHP3Cw9iEfuPwAw.png" /><figcaption>HIgh RAM Colab Runtime</figcaption></figure><p>I’ll keep this simple and sweet</p><blockquote>Open this Notebook in Colab and Run: <a href="https://github.com/satyajitghana/TSAI-DeepVision-EVA4.0/blob/master/Utils/Colab_25GBRAM_GPU.ipynb">https://github.com/satyajitghana/TSAI-DeepVision-EVA4.0/blob/master/Utils/Colab_25GBRAM_GPU.ipynb</a></blockquote><p>That is it, you have a 25GB High RAM 🤩 session in Colab, Go Crazy !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*gmvK_oxBWZZC-tbRmAH0uA.png" /><figcaption>25GB RAM</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*jVzgtCu84XXVRt3u9fzxPQ.png" /><figcaption>Tesla P100 16GB</figcaption></figure><p>If you open the .ipynb file with notepad then you’ll see this metadata</p><pre>&quot;machine_shape&quot;: &quot;hm&quot;</pre><p>which enables the High Memory runtime in Colab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*yIYpq9zzEinasFh9rYYbrw.png" /><figcaption>colab file opened with notepad</figcaption></figure><p>I feel high memory session tends to get a P100, but if you did not get a P100, try resetting the runtime</p><pre>Runtime -&gt; Factory reset runtime</pre><p>Reconnect and check if you got a P100, if not try with a different account, and repeat, usually new accounts get a P100 easily</p><p>That’s it Folks 😛</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=115e7679f5de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with huge datasets, 800K+ files in Google Colab and Google Drive]]></title>
            <link>https://satyajitghana.medium.com/working-with-huge-datasets-800k-files-in-google-colab-and-google-drive-bcb175c79477?source=rss-4ccf9d79205d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcb175c79477</guid>
            <category><![CDATA[google-colab]]></category>
            <category><![CDATA[google-drive]]></category>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[google-drive-api]]></category>
            <dc:creator><![CDATA[Satyajit Ghana]]></dc:creator>
            <pubDate>Mon, 04 May 2020 22:20:02 GMT</pubDate>
            <atom:updated>2020-05-04T22:20:02.318Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*BKyVeBWvz1TjhjkBLHpEsg.png" /><figcaption>colab + drive</figcaption></figure><p>Recently i had to make a dataset of 400K images + 400K image masks, and then had to train them on a Deep Neural Network using the Google Colab free Tesla P100 GPUs, this article is about the journey i had to go through, and learnt quite some nifty ways people have solved this issue.</p><p>Starting off, 800K files seemed pretty simple, i wrote a simple script for my dataset generator, that created 1kb jpeg each file and stored them to my SSHD, it took about ~17 mins to do so. Okay now that i know everything worked on my local machine, how about i put them into Google Drive.</p><p>Why am i trying to do this on google drive and colab ? i need to train a depth estimation model, that will ingest all this data and train, Google Colab provides them free sweeeeet Tesla P100s that are so damn goood :* , and my puny little 1050Ti is no match to it, if i have my dataset on google drive, its easy to mount it in colab and train the network, and periodically save the model directly on drive.</p><p>Here’s a snippet of my code for creating my dataset:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dc5a8faa6a012da57dd4f7a18167f49/href">https://medium.com/media/3dc5a8faa6a012da57dd4f7a18167f49/href</a></iframe><p>This code produced 800k+ files with total size of about ~2Gb, which is relatively small.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*rhI028q8b8x6a2DmGk9fkw.png" /></figure><p>So what now ? here were the options i tried</p><h3>1. Upload the entire folder to google drive containing the 800k+ images</h3><p>The result was that it will take an eternity to upload them, it takes a hell lot of time to do this, you could also use the Google Drive Sync, which i’ve used before for huge datasets, but for my current case, this was also way slow, i couldn’t wait for more than 8 hours, since my assignment deadline was closing in. This was a complete no no.</p><h3>2. Zip the dataset folder, Upload to GDrive and then unzip</h3><p>This seems that something that might work right ?</p><p>wrong ! although i tried to use .zip and .tar, both without any compression, uploaded to google drive as well, but the problem was unzipping it.</p><p>Google Drive has this ZipExtractor, which didn’t work for me, it went out of memory</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*q1wt_jjtww13JN9XpDPrMQ.png" /></figure><p>So why not try mounting the google drive on colab and then running unzip on it ? well . . . same story, it takes a damn long time to extract, something that i learned was that Google Drive limits your number of I/O operations performed on the drive using the Python GDrive API, it gets slower, my estimate was it would take about ~7 hours to unzip the entire dataset on google drive, and then i had to make sure it was extracted completely, also making sure that the colab runtime doesn’t disconnect, which is a big pain in the a anyways 😌.</p><h3>3. Create the dataset directly on Google Colab and write the files on drive</h3><p>One reason why the I/O operations were getting slower was because Drive will index your files and create thumbnail previews of them. You what else was really frustrating ? deleting the created dataset, i couldn’t use !rm -rf , drive was frequently getting disconnected, this also means a flag for you, your account might get suspended if you continue to attack the drive i/o like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*PEMhaZJbSYbZmEa2GAXJ3A.png" /><figcaption>This is damn long time for a single background image to process, each of these BG is creating 200*20 images</figcaption></figure><p>So i needed a solution that doesn’t work with too many files in drive at once, and makes sure that there are not too many i/o operations happening at a time, and drive doesn’t have to create thumbnail preview of my images.</p><h3>4. Maybe use threads ?</h3><p>😂 This is useless, you get 2 CPU cores in colab, and there isn’t any benefit of using multiprocessing here, same issue, an estimate of ~5 hours to create the dataset.</p><blockquote>Hmm . . . so what worked ! ?</blockquote><h3>Create the Dataset on Google Drive, directly into a .zip/.tar file 🥳🎊</h3><p>Python has a <a href="https://docs.python.org/3/library/zipfile.html#module-zipfile">ZipFile</a> package that can help you create .zip/.tar files and directly add files into it, just like a<em> directory</em> !, and moreover .zip files stays as single file, Google Drive doesn’t complain about working with too many files, and it doesn’t have to create those thumbnail previews.</p><p>Another advantage is that now you can directly read from the zip file while training your model as well, no need to unzip it and then train.</p><p>Awesome !! , so how do i do this ?</p><p>I modified my code to this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00ae248ffd881ee26b90dd2a22bf8bde/href">https://medium.com/media/00ae248ffd881ee26b90dd2a22bf8bde/href</a></iframe><p>And it took about and hour to finish, but the good thing is, now i can easily download the zip, i don’t have to manually go to the folder in gdrive and then wait for it to zip, which will again take a long time. Also it’s very easy to share my .zip file with others.</p><p>Lessons learnt:</p><ul><li>always work with your huge datasets in batches !</li><li>save your work in google drive periodically, use .zip files if you work with huge datasets, <strong>consider splitting them into parts if possible</strong></li><li>you might need to use the garbage collector in python to clear up memory</li></ul><p>I was finally able to create my dataset, well . . . now i have to run a depth estimation model on all the images, that’s gonna take a while . . . ☕</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*40x2gVZjU7WAou3d77BnPw.png" /><figcaption>Depth Estimation model run on my dataset</figcaption></figure><p>😂 Let&#39;s not comment on my bad model, the point is ZipFile works ! and works great for datasets that have a huge number of files.</p><p>Here are some tutorials on ZipFile</p><ul><li><a href="https://pymotw.com/2/zipfile/">https://pymotw.com/2/zipfile/</a></li><li><a href="https://www.geeksforgeeks.org/working-zip-files-python/">https://www.geeksforgeeks.org/working-zip-files-python/</a></li></ul><h3><strong>That’s all Folks!</strong></h3><p>This is my first medium article, hope you, the reader like it 😊😀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcb175c79477" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>