<?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 Vishnu Subramanian on Medium]]></title>
        <description><![CDATA[Stories by Vishnu Subramanian on Medium]]></description>
        <link>https://medium.com/@vishnuvig?source=rss-d7564bad2de------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*bV8EqUG8tqfvFxIjLup_jw.jpeg</url>
            <title>Stories by Vishnu Subramanian on Medium</title>
            <link>https://medium.com/@vishnuvig?source=rss-d7564bad2de------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:54:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vishnuvig/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[Langchain: A Practical Guide to Implementing a Chat App with your documentation]]></title>
            <link>https://medium.com/jarvislabs-ai/langchain-a-practical-guide-to-implementing-a-chat-app-with-your-documentation-b82a3a66a497?source=rss-d7564bad2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/b82a3a66a497</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Vishnu Subramanian]]></dc:creator>
            <pubDate>Tue, 20 Jun 2023 05:58:05 GMT</pubDate>
            <atom:updated>2023-06-20T05:58:05.949Z</atom:updated>
            <content:encoded><![CDATA[<p>The last few months have been crazy in the world of AI.</p><p>Applications like OpenAI ChatGPT, Google Bard, and Github Copilot are becoming integral parts of our day-to-day lives. These tools are powerful to answer many questions, but they fail to offer the right answers on topics they were not usually trained on. Let&#39;s look at a few examples</p><ol><li>They cannot answer questions based on recent knowledge.</li><li>Ability to answer questions based on private data like company documentation, and code.</li><li>If you want to know about a company&#39;s latest financials.</li></ol><p>In this blog let&#39;s build a simple chat application that can take a given documentation and answers question based on that. We will use tools like LangChain, OpenAI, and ChromaDB to do this.</p><p>You can find the notebook <a href="https://github.com/jarvislabsai/notebooks/blob/main/Langchain_fastai_docs.ipynb">here</a>.</p><h3>Finetuning vs Prompting</h3><p>There are 2 ways in which we can use custom data with LLMs.</p><p>The traditional approach is fintuning the LLM model which could be complex and expensive based on the use case.</p><p>Prompting has become popular in recent years which let us trick the LLM model to do tasks like classification or inject new knowledge into it.</p><p>Let&#39;s say we want to classify a movie review using LLM which was not trained for classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nu835E9vJ80QxfdI5wdkSQ.png" /></figure><p>Let&#39;s also check what happens when we ask questions based on recent events like, you want to understand who is the protagonist in the movie Extraction 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dhO4JezxASOKrn6ok-4AnQ.png" /></figure><p>As expected the AI/LLM will not be able to answer it. What if we give some context so that it can use that? So I instructed it to answer based on the knowledge I shared. A description from the IMDB website about the movie.</p><p>The LLM model can answer the question based on the new knowledge without ever training/fine-tuning on updated data.</p><h3>Limitations of the above approach</h3><p>In the above example, we passed on the additional knowledge manually. Let&#39;s look at how we can automate the process of</p><ol><li>Searching for relevant information, like getting the piece from Imdb.</li><li>Adding the relevant information to the prompt, like the description of the movie</li></ol><p>To do this, let&#39;s build a simple app that allows us to chat with the latest FastAPI docs.</p><blockquote><strong>FastAPI</strong> is a modern, fast (high-performance), web framework for building APIs</blockquote><p>The high-level steps of building our app will look like</p><ol><li>Data preparation</li><li>Creating a knowledge base</li><li>Use a popular LLM model to answer your questions based using the knowledge base</li></ol><p>LangChain provides a lot of helper classes to handle the above, so we will leverage them to build our small AI app.</p><h3>Data Preparation</h3><p>I took a smile approach of extracting all the useful links from <a href="https://fastapi.tiangolo.com/sitemap.xml">FastAPI</a> sitemap.xml. Then use <strong>UnstructuredURLLoader</strong> from LangChain to download and extract the text content from these URLs.</p><pre># Download sitemap.xml file from a website and extract all the links<br>def get_links(url):<br>    url = f&#39;{url}/sitemap.xml&#39;<br>    response = requests.get(url)<br>    if response.status_code == 200:<br>        soup = BeautifulSoup(response.text, &#39;lxml&#39;)<br>        links = [link.text for link in soup.find_all(&#39;loc&#39;)]<br>        return links<br>    else:<br>        print(f&#39;Error: {response.status_code}&#39;)<br>        return None<br><br># Download the contents of a webpage given its urls<br>def download_pages(urls: list[str]):<br>    data = UnstructuredURLLoader(urls=urls).load()<br>    return data  </pre><h3>Creating a Knowledge base using Chroma DB</h3><p>Once we have the data, we need to store it in some form of database, so that we can retrieve the relevant text when required. Since it is all text data, SQL databases may not be the right choice for storage.</p><p>Vector DBs like Chroma DB and Pinecone are built exclusively for this. Let&#39;s understand at a high level what it does.</p><ol><li>Convert all the text to smaller portions called chunks.</li><li>Convert these chunks to numerical representations called embeddings.</li><li>Given a search query, it will return the <strong>N(3)</strong> relevant pieces of text.</li></ol><pre># Index and Store data to Chroma<br>text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=20)<br>split_docs = text_splitter.split_documents(docs)<br>embeddings = OpenAIEmbeddings()<br>db = Chroma.from_documents(collection_name=&#39;webdata&#39;,<br>                           documents=split_docs,<br>                           embedding=embeddings,persist_directory=&#39;index_data&#39;)<br>db.persist()<br><br># Load the stored embeddings<br>db = Chroma(collection_name=&#39;webdata&#39;,<br>            embedding_function=embeddings,<br>            persist_directory=&#39;index_data/&#39;)<br>query = &quot;What is async code?&quot;<br><br># Fetch similar docs<br>docs = db.similarity_search(query,k=3)</pre><h3>LLMs answer using the knowledge base</h3><p>We have prepared our knowledge base, based on the fastapi docs. We can pass any question to an LLM model, query the index from Chroma DB to add relevant docs to the prompt, and answer them using the below simple code.</p><pre>llm = ChatOpenAI(model_name=&#39;gpt-3.5-turbo&#39;,temperature=0.0)<br>qa = RetrievalQA.from_chain_type(llm=llm, <br>                                 retriever=db.as_retriever(),<br>                                 chain_type=&#39;stuff&#39;)<br>qa.run(&#39;How is async used in fastai&#39;)</pre><blockquote>You can replace FastAPI docs with your own docs.</blockquote><h3>Things we can try:</h3><ol><li>How to use tools like Gradio or Streamlit to build a simple chat application, and connect to our app.</li><li>Let&#39;s explore how to use open-source LLMs on your GPUs. It helps in handling confidential data, that you do not want to share with OpenAI or a third-party provider.</li></ol><h3>Useful resources:</h3><p>Langchain is still new, the tool and its documentation are evolving fast. So the best place to check is their <a href="https://docs.langchain.com/docs/">docs</a>.</p><p>I also found this <a href="https://www.pinecone.io/learn/langchain-intro/">book</a> very useful to get an introduction to LangChain and several of its key concepts.</p><h4><strong>Hope you find the blog useful.</strong></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b82a3a66a497" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jarvislabs-ai/langchain-a-practical-guide-to-implementing-a-chat-app-with-your-documentation-b82a3a66a497">Langchain: A Practical Guide to Implementing a Chat App with your documentation</a> was originally published in <a href="https://medium.com/jarvislabs-ai">Jarvislabs.ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Invoke AI on Jarvislabs: Generate Beautiful Images Effortlessly in seconds.]]></title>
            <link>https://medium.com/jarvislabs-ai/invoke-ai-on-jarvislabs-generate-beautiful-images-effortlessly-in-seconds-45c07b4f78e?source=rss-d7564bad2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/45c07b4f78e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[art]]></category>
            <category><![CDATA[artist]]></category>
            <dc:creator><![CDATA[Vishnu Subramanian]]></dc:creator>
            <pubDate>Tue, 23 May 2023 13:56:54 GMT</pubDate>
            <atom:updated>2023-05-23T13:56:54.044Z</atom:updated>
            <content:encoded><![CDATA[<p>As an AI enthusiast, I’m always on the lookout for open-source tools that can help artists and designers create captivating visuals with ease. Invoke AI, an image generation tool powered by Stable Diffusion caught my attention recently. In this post, I’ll show how you can launch this fascinating tool on <a href="https://jarvislabs.ai/">Jarvislabs.ai</a> in less than a minute and generate images using some of the popular models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TiaSK6NoQahLUuCsmVwjcA.png" /></figure><h3>Understanding Invoke AI and Stable Diffusion</h3><p>InvokeAI is a cutting-edge creative platform designed to assist both professionals and enthusiasts in producing breathtaking visual content. Harness the power of advanced AI-driven technologies to generate and craft striking visual media.</p><p>Some of the key features :</p><ol><li>Text-to-Image: Transform written text into visually captivating images.</li><li>Image-to-Image: Modify a provided initial image (sketch or photograph) by generating a new version influenced by a textual prompt.</li><li>Unified Canvas: Interactively merges multiple images, expands them through outpainting, and alters specific parts of the image using inpainting. Erase sections of a starting image and let the AI complete the erased region based on a text prompt.</li></ol><h3>Getting Started with Invoke AI on Jarvislabs Platform</h3><p>To begin generating images with Invoke AI on the Jarvislabs platform, follow these straightforward steps:</p><ol><li>Create an account on the Jarvislabs platform (<a href="https://www.jarvislabs.ai/">https://www.jarvislabs.ai/</a>). If you’re an existing user, simply log in.</li><li>Once logged in, create an instance by choosing Invoke AI in the framework list. You can also choose GPU type and storage. We recommend trying it out with A5000 or A6000 GPUs.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b-xk8wrb6wX0Sv0Cdo79Ew.png" /></figure><p>3. In less than 45 seconds, you will have your instance up and running. Access the Invoke AI web console by right-clicking on your running instance and choosing the API endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5QZn4DUpRCx74IJJ7FlhQ.png" /></figure><p>The web UI may take a few seconds to load. If you do not see it, please refresh the page after a few seconds.</p><h3>Advanced options</h3><p>If you want more flexibility, you can easily stop the Invoke AI server and start tweaking it. To do that, please open a <a href="https://jupyterlab.readthedocs.io/en/stable/user/terminal.html">terminal</a> from Jupyter Lab, which can be accessed by pressing the green play button on your running instance. From the terminal, you can run the below commands to access the Invoke AI server.</p><pre>tmux attach -t invoke<br><br></pre><h3>Conclusion</h3><p>Invoke AI and the Jarvislabs platform provide a robust, accessible solution for generating visually stunning images. Whether you’re a seasoned artist or simply looking to enhance your projects with captivating visuals, Invoke AI can help you achieve the perfect image quickly and effortlessly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45c07b4f78e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jarvislabs-ai/invoke-ai-on-jarvislabs-generate-beautiful-images-effortlessly-in-seconds-45c07b4f78e">Invoke AI on Jarvislabs: Generate Beautiful Images Effortlessly in seconds.</a> was originally published in <a href="https://medium.com/jarvislabs-ai">Jarvislabs.ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide for finetuning Stablediffusion with your images]]></title>
            <link>https://medium.com/jarvislabs-ai/guide-for-finetuning-stablediffusion-with-your-images-fc6856c0c2a7?source=rss-d7564bad2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc6856c0c2a7</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai-art]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Vishnu Subramanian]]></dc:creator>
            <pubDate>Mon, 09 Jan 2023 14:34:48 GMT</pubDate>
            <atom:updated>2023-01-28T06:59:59.010Z</atom:updated>
            <content:encoded><![CDATA[<h4>Create personalized images of you, your favorite character, or your cat</h4><p>Have you dreamt of being a spiderman or iron man, I did while growing up (I want to keep it a secret that I still do😁). In the last few months, algorithms like Dall-E and Stable Diffusions have been able to generate beautiful images, and we can guide them through simple text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bYtYXJTYYKCRLnFXpJ0lQQ.png" /></figure><p>Though it generates random images, they struggle to generate images of certain persons, animals, or objects.</p><p>Let&#39;s take a look at some examples of outputs generated from SD, they get it slightly right but are not realistic for our favorite characters.</p><p>These are some of the popular Indian movie stars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8GOfdrakCdoTx2PUpBHphA.png" /></figure><p>Let&#39;s use a technique called <a href="https://dreambooth.github.io/">Dreambooth</a> a technique proposed by researchers at google that let&#39;s fine-tune these large image generation models to generate images of a specific object/person.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E9kPaJ_jifl2iOKRficPdw.png" /></figure><p>Let&#39;s take the example of a famous Indian actor “<a href="https://en.wikipedia.org/wiki/Mahesh_Babu">Mahesh Babu</a>” and walk through how to fine-tune the SD model and generate images like these.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sk34uR8VW16RhACUCaWq-g.jpeg" /><figcaption>Photos generated by SD and Automatic 1111 on Jarvislabs</figcaption></figure><h3>Quick steps to finetune SD</h3><ul><li>Setup the env and code required</li><li>Get images of your favorite character/object</li><li>Train the model, and understand key hyperparameters that may help in getting better results.</li><li>Convert the weights to a format compatible with Automatic 1111</li><li>Start generating images</li><li>Tips for prompt ideas</li></ul><h4>Setup environment</h4><p>For this post, I am using an Nvidia A6000 GPU instance from <a href="https://jarvislabs.ai/">Jarvislabs.ai</a>. It comes with <a href="https://jarvislabs.ai/docs/automatic/">Automatic 1111</a> prebuilt, making our lives easier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UyUc7ily23BV8e9GXb5jtg.png" /></figure><p>Note: You should be able to do most of the steps on your workstation.</p><p>Open the terminal from Jupyter Lab and run the below commands</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*Xky6GQK9bAJt6Nbfww1avg.png" /></figure><pre><br>wget https://gist.githubusercontent.com/svishnu88/f17d3b4233db69dfc119f77942104a91/raw/fd16254e5e78fe69c22ca06314c2c980c9c5cb61/setup_db_env.sh<br>bash setup_db_env.sh</pre><p>The script will take a few minutes to run. While it is getting executed, let&#39;s try to understand what the script does. It is completely optional to understand it 😊.</p><pre>#Create a python environment<br>python3 -m venv env_dream<br><br>#Activate the environment<br>source env_dream/bin/activate<br><br># Install libraries required to train StableDiffusion model<br>pip install ipykernel ipywidgets<br>python -m ipykernel install --user --name=dreambooth<br><br>#Clone the diffusers library and install the required libraries<br>git clone https://github.com/huggingface/diffusers.git<br>cd /home/diffusers/<br>pip install -e .<br>cd /home/diffusers/examples/dreambooth/<br>pip install -r requirements.txt<br>pip install datasets</pre><p>We create a separate python env, in which we install all the required libraries. If running the script does not throw any error, then we are good to train the model.</p><h4>Get Images of your favorite character</h4><p>We need to be careful while we pick the images we are using to train the model. Some of the tips to pick your input images.</p><ul><li>Pick a few close-up photos</li><li>Few photos with different sides of the face and body</li><li>Avoid objects or other people in the background.</li><li>Choose different locations.</li><li>Avoid photos with heavy makeup/ornaments.</li></ul><p>I took 9 images for this post, all from the internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jA5vf1H602MubvqLhGvecw.jpeg" /></figure><p>Create a folder called input_imgs under the home directory and upload all your input images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h1mPHNjFerRjl5zop4Ggjw.jpeg" /></figure><h4>Train Model</h4><p>From a terminal, you can run the below commands to start the model training. It could take close to 15+ minutes when you run the first time.</p><p>It would be faster the second time as it will skip some of the steps like downloading model weights and creating class images.</p><pre>source env_dream/bin/activate<br>wget https://gist.githubusercontent.com/svishnu88/9adbd8ccdfd679a991d7696ef753a175/raw/17990e718487910cd08df3ace48bb231b7d82587/train_dreambooth.sh<br>bash train_dreambooth.sh</pre><p>Let&#39;s look at what is happening inside the script so that you can tweak it for your needs.</p><pre>export MODEL_NAME=&quot;runwayml/stable-diffusion-v1-5&quot;<br>export CLASS_DIR=&quot;class_images&quot;<br>export INSTANCE_DIR=&quot;input_imgs&quot;<br>export OUTPUT_DIR=&quot;output&quot;<br><br>accelerate launch diffusers/examples/dreambooth/train_dreambooth.py \<br>  --pretrained_model_name_or_path=$MODEL_NAME  \<br>  --instance_data_dir=$INSTANCE_DIR \<br>  --class_data_dir=$CLASS_DIR \<br>  --output_dir=$OUTPUT_DIR \<br>  --with_prior_preservation --prior_loss_weight=1.0 \<br>  --instance_prompt=&quot;a photo of sks person&quot; \<br>  --class_prompt=&quot;Photo of Tom cruise&quot; \<br>  --resolution=512 \<br>  --train_batch_size=1 \<br>  --train_text_encoder \<br>  --gradient_accumulation_steps=1 \<br>  --learning_rate=1e-6 \<br>  --lr_scheduler=&quot;constant&quot; \<br>  --lr_warmup_steps=0 \<br>  --num_class_images=200 \<br>  --max_train_steps=1200 \<br>  --mixed_precision=&#39;bf16&#39; \<br>  --sample_batch_size=3</pre><p>Some of the key things you may need to tweak are</p><ul><li>instance_prompt</li><li>class_prompt</li><li>max_train_steps</li><li>mixed_precision</li></ul><p><strong>Instance prompt</strong>: &lt;sks&gt; is the keyword we assign to our character. We will be using it to generate images once our model is trained. &lt;person&gt; is the class to which our character/object belongs too. If we choose photos of a dog, then we replace “person” with “dog”.</p><p><strong>Class prompt</strong>: To avoid overfitting we need to pass images of the class in our case it is the person. You can upload your images, or let SD generate images. In this case, I am asking SD to generate images of Tom Cruise. If you want to train the model on a female character, then we can choose a popular actress instead of Tom cruise.</p><p>If you are using your images, then you can create a folder called class_images and upload your relevant images.</p><p><strong>Max train steps</strong>: This number would play an important role in the quality of the images generated. You can tweak the number based on the number of input images you choose. For a higher number of images, you may need to increase it and vice versa.</p><p><strong>Mixed precision</strong>: You can use ‘bf16’ if you are using Nvidia GPUs with Ampere generation, for example, A100, A6000, and A5000 belong to these. This helps in training the models faster. If you are using older generation GPUs, then you can replace it with ‘fp16’ or remove the flag.</p><h4>Convert model weights to .ckpt and use it with Automatic 1111</h4><p>Once the model training is completed let&#39;s convert the model weights to a suitable weight and use it with Automatic 1111 a popular UI for SD.</p><pre>python diffusers/scripts/convert_diffusers_to_original_stable_diffusion.py --model_path output/ --checkpoint_path my_model.ckpt</pre><p>Once we have our custom weights let&#39;s move the weights to a place where Automatic 1111 can pick them up.</p><p>Run the below commands from a new terminal and do not activate the environment we created earlier.</p><pre>mv my_model.ckpt /home/stable-diffusion-webui/models/Stable-diffusion/<br>cd stable-diffusion-webui<br>python launch.py</pre><p>The above command could take a few minutes, once done we can access the Automatic UI in the <a href="https://jarvislabs.ai/">Jarvislabs</a> platform like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zxc7B-8rOFQui5Pa6JgPw.png" /></figure><p>Time to generate images using our custom model 😀.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CGy6a8fvdl6jljOCO9py3w.png" /></figure><h4><strong>Tips to get your prompts</strong>:</h4><p>This is where I struggle. I am no artist and have very little idea about the domain of art. So I take help from another <a href="https://huggingface.co/spaces/Gustavosta/MagicPrompt-Stable-Diffusion">AI application</a> that can help us in generating initial prompts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WuuG4jsYDWyxaXkcPyB2KQ.png" /></figure><h3>See you soon</h3><p>Hope you found the blog helpful, would love to see what cool things you create. Have suggestions or need help, let me know will be happy to help.</p><p>If you are running it on Jarvislabs, you can also talk to the team using the chat window. We will love to help you. Happy New Year.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc6856c0c2a7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jarvislabs-ai/guide-for-finetuning-stablediffusion-with-your-images-fc6856c0c2a7">Guide for finetuning Stablediffusion with your images</a> was originally published in <a href="https://medium.com/jarvislabs-ai">Jarvislabs.ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stable Diffusion with Automatic 1111 on Jarvislabs]]></title>
            <link>https://medium.com/jarvislabs-ai/stable-diffusion-with-automatic-1111-on-jarvislabs-1cd281eb57f9?source=rss-d7564bad2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cd281eb57f9</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[generative-art]]></category>
            <category><![CDATA[stable-diffusion]]></category>
            <dc:creator><![CDATA[Vishnu Subramanian]]></dc:creator>
            <pubDate>Mon, 02 Jan 2023 15:03:26 GMT</pubDate>
            <atom:updated>2023-04-03T01:31:06.319Z</atom:updated>
            <content:encoded><![CDATA[<p>Generating images with Stable diffusion(SD) has gotten super easy over the last few months. <a href="https://github.com/AUTOMATIC1111/stable-diffusion-webui">Automatic 1111</a> is a popular open-source UI tool built to help enthusiasts and artists play around with SD and apply many advanced features.</p><p>In this blog post, we will delve into, how you can use Automatic1111 a powerful platform on <a href="https://jarvislabs.ai/">Jarvislabs.ai</a> in a few clicks and transform your creative process. Create stunning visuals with ease, with 10+ preloaded models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nWio5xSrKnfWSCLs.png" /></figure><h3>What is AUTOMATIC1111 — Stablediffusion UI?</h3><p>Automatic 1111 provides an open-source UI dashboard built on top of <a href="https://gradio.app/">Gradio</a>. With more than 350 active contributors, it brings in some of the latest advancements in Generative AI space to its users.</p><p>Key features of Automatic 1111:</p><ul><li>txt2img and img2img modes</li><li>Inpainting and Outpainting</li><li>Textual Inversion</li><li>CLIP interrogator, a button that tries to guess a prompt from an image</li></ul><p>There is a ton of features available and they are growing. Check <a href="https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features">here</a> for features with examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/0*51S4fVKm8cRTyzL4.png" /></figure><h3>Setting up AUTOMATIC1111 on JarvisLabs.ai</h3><p>Getting started with AUTOMATIC1111 is a breeze. Get started in less than 60+ seconds ⏰. It comes with 10+ preloaded models.</p><p>Launch an instance, choose</p><ul><li>Choose Automatic 1111 as a framework</li><li>GPU Typ — (Recommended A5000, A6000)</li><li>Storage — (You can increase or decrease it anytime)</li><li>Number of GPUs — (1 GPU should be ideal for most of the cases)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*33yDOR2clcFwhaIS.png" /></figure><p>Easily access the AUTOMATIC1111 application by right-clicking on the instance and selecting the API endpoint for a smooth creative experience on JarvisLabs.ai.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tx5ecTkMFNnWNfX2.png" /></figure><p>Note: The UI may need a few seconds to load, please refresh the UI if you don’t get the UI.</p><p>Keep an 👀 on the <a href="https://jarvislabs.ai/docs/automatic/">docs</a> for updated information.</p><h3>Exploring with 10+ Preloaded Models</h3><p>The first step in using Automatic 1111 is to choose the right model and place it in the right location. We have done the hard work of picking some of the most popular models and have placed them in the Automatic 1111 models directory. So you can focus on Image generation.</p><p>You can choose from one of the popular models and start generating images.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc7c43a6da2bcd1734ba02d80851b7a6/href">https://medium.com/media/fc7c43a6da2bcd1734ba02d80851b7a6/href</a></iframe><h3>Download model weights and config</h3><p>It is super simple to add any new models or custom pretrained models. You can follow these simple steps.</p><ul><li>Once your instance is launched, clicking the play button will start a Jupyter Lab.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k0eeAY__mrIVJal1_NTmlA.png" /></figure><ul><li>From the Jupyter lab, let&#39;s open a terminal to download the model weights and config.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LXOfVhrbollvXJxzgCXd9A.png" /></figure><ul><li>Download your favorite model from places like <a href="https://huggingface.co/models">Hugging face</a> or <a href="https://civitai.com/">civitai</a> and place it under</li></ul><pre>/home/stable-diffusion-webui/models/Stable-diffusion/</pre><p>To try SD 2.1, we need to download the weights and config.</p><pre>#Download weights<br>wget https://huggingface.co/stabilityai/stable-diffusion-2-1/resolve/main/v2-1_768-ema-pruned.ckpt<br><br>#Download config<br>wget https://raw.githubusercontent.com/Stability-AI/stablediffusion/main/configs/stable-diffusion/v2-inference-v.yaml<br></pre><p>Let&#39;s rename the config file and place it in the model&#39;s directory.</p><pre>mv v2-inference-v.yaml v2-1_768-ema-pruned.yaml<br>mv v2-1_768-ema-pruned* stable-diffusion-webui/models/Stable-diffusion/</pre><p>You do not need a config file for all the models.</p><h3>What&#39;s next</h3><p>In the coming weeks, I will create blogs that show</p><ul><li>How you can train models that create images of you, your pet, or any object.</li><li>How to use a technique called Textual Inversion to generate images in different styles.</li><li>How to upscale generated images and more.</li><li>Try another popular UI for SD called <a href="https://github.com/invoke-ai/InvokeAI">InvokeAI</a></li></ul><p>I hope you find the blog useful, would love to know your thoughts on how we can improve it. In case you have any suggestions/challenges you can comment or ping us on the chat available on <a href="https://jarvislabs.ai/">Jarvislabs.ai</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cd281eb57f9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jarvislabs-ai/stable-diffusion-with-automatic-1111-on-jarvislabs-1cd281eb57f9">Stable Diffusion with Automatic 1111 on Jarvislabs</a> was originally published in <a href="https://medium.com/jarvislabs-ai">Jarvislabs.ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy stable diffusion on GPU instance using FastAPI]]></title>
            <link>https://medium.com/jarvislabs-ai/deploy-stable-diffusion-on-gpu-instance-using-fastapi-d0743eeb735d?source=rss-d7564bad2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0743eeb735d</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-art]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[stable-diffusion]]></category>
            <dc:creator><![CDATA[Vishnu Subramanian]]></dc:creator>
            <pubDate>Mon, 31 Oct 2022 12:39:37 GMT</pubDate>
            <atom:updated>2022-10-31T12:39:37.370Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, let’s explore how we can deploy a Stable diffusion model on a GPU and expose it as an API. To do this we will use</p><ul><li>GPU instance using <a href="https://jarvislabs.ai/">Jarvislabs</a></li><li>FastAPI for developing API</li><li>Gunicorn to run the FastAPI application</li></ul><p>The demo code is available in the GitHub <a href="https://github.com/jarvislabsai/fastapi-sd-template">repo</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_tXCE5wONm-P1_0G" /><figcaption>Photo by <a href="https://unsplash.com/@spencerdavis?utm_source=medium&amp;utm_medium=referral">Spencer Davis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>GPU instance</h3><p>I will be using <a href="https://jarvislabs.ai/">Jarvislabs</a> GPU instances, which come with</p><ul><li>Cuda, Nvidia, and Pytorch libraries are preinstalled.</li><li>Build applications using your favorite IDE like JupyterLab and VScode.</li><li>Expose API using FastAPI in clicks.</li></ul><p>For this blog, let&#39;s use a PyTorch-powered instance.</p><p>Most of the below steps are applicable to local or other cloud platforms.</p><h4>Setting up environment</h4><p>Let&#39;s install some of the additional software required for FastAPI, stable diffusion, and diffusers (Hugging face library).</p><p>Run the below command from a terminal.</p><pre>pip install -r requirements.txt</pre><p>Which installs the below libraries.</p><pre>fastapi==0.85.0<br>uvicorn==0.18.3<br>diffusers==0.6.0<br>gunicorn==20.1.0<br>boto3==1.24.90<br>transformers==4.23.1<br>ftfy==6.1.1</pre><h3>Expose the Stable diffusion model as a rest API</h3><p>Let&#39;s explore the main.py from <a href="https://github.com/jarvislabsai/fastapi-sd-template/blob/main/main.py">here</a>.</p><p>It primarily contains code to:</p><h4>Load the Stable diffusion model</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f58749da4655ecdb63d1db47deee66e3/href">https://medium.com/media/f58749da4655ecdb63d1db47deee66e3/href</a></iframe><p>The above code is responsible for downloading the model weights and pushing the model to the GPU. I am using float16 as it is faster to download and also runs faster on most modern GPUs. Ensure that you do not include this code inside your API code, as it will cause the creation of new models which can fill your GPU memory in no time.</p><p>We want the model to be loaded once per application/worker.</p><p>In order to download the Stable diffusion model, you need to accept the <a href="https://huggingface.co/runwayml/stable-diffusion-v1-5">user agreement</a> and should have logged in. You can find/create the token for login <a href="https://huggingface.co/settings/tokens">here</a></p><pre>huggingface-cli login</pre><h4>Expose the Stable diffusion model as a RestAPI</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d122204b95800a2e736000611640a1c/href">https://medium.com/media/1d122204b95800a2e736000611640a1c/href</a></iframe><p>We are creating a rest API genimagewhich is responsible for accepting an input request containing prompt and guidance_scale. The model(pipe) uses the prompt text and guidance_scale values to generate the image.</p><p>You can modify the GenImage to include other parameters in the model like</p><ul><li>height</li><li>width</li><li>seed</li><li>num_inference_steps</li></ul><p>The generated image can be shared back to the client in multiple ways, in our case we upload the image and share the URL as a response.</p><h3>Deploy the FastAPI application using Gunicorn</h3><p>Once we are done with the code, we can either use unicorn or gunicorn to deploy the application.</p><p>Gunicorn lets us run the application on multiple workers and also queues the requests. So let&#39;s deploy our FastAPI app on gunicorn.</p><pre>gunicorn main:app --bind=0.0.0.0:6006 -w 4 -k uvicorn.workers.UvicornWorker --timeout 120</pre><p>The port number 6006 could vary depending on where you are running the application.</p><p>-w 4 We are using 4 workers for demonstration, which you may have to tweak depending on the GPU memory needed. Each worker could take 8–10GB for a float16 model.</p><p>If you are trying this on Jarvislabs.ai, you can quickly get your API link by right-clicking on your running instance to use it in your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*_uoQA5ke0QreQ8mC-_NEsA.png" /></figure><p>I hope you find the blog useful, in case you face any challenges let me know in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0743eeb735d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jarvislabs-ai/deploy-stable-diffusion-on-gpu-instance-using-fastapi-d0743eeb735d">Deploy stable diffusion on GPU instance using FastAPI</a> was originally published in <a href="https://medium.com/jarvislabs-ai">Jarvislabs.ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Lambda : Solving the cold start problems while accessing DB in VPC.]]></title>
            <link>https://medium.com/@vishnuvig/aws-lambda-solving-the-cold-start-problems-while-accessing-db-in-vpc-304daab5d3b5?source=rss-d7564bad2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/304daab5d3b5</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Vishnu Subramanian]]></dc:creator>
            <pubDate>Sat, 27 Apr 2019 16:15:11 GMT</pubDate>
            <atom:updated>2019-04-27T16:15:11.639Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS Lambda : Solving the cold start problems while accessing DB in VPC.</h3><p>With great power comes great responsibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7TBgvPkII5pflKz2" /><figcaption>Photo by <a href="https://unsplash.com/@clarktibbs?utm_source=medium&amp;utm_medium=referral">Clark Tibbs</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>AWS Lambda plays a key role in any of the modern architectures. It can be used to build powerful backend pipelines for websites, apps , build data pipelines for analytical solutions and much more.</p><p>It comes with a lot of advantages like reducing dependency on devops teams, continuous deployment, supporting polyglot (ability to use different programming languages like python, java, nodejs etc ). Sounds all good. It also comes with some major challenges like being stateless, cold start problems. In this blog I would like to introduce some of the cold start problems that you may face when using AWS Lambda or any other cloud based FAAS(Function as a service from platforms like GCP, Azure).</p><h4><strong>What is cold start problem:</strong></h4><p>In the server based world we have server up and running all the time. In the world of AWS Lambda we bring up the service only when required. The server stays up, running for a short period of time. In case of AWS Lambda it stays alive for maximum of 15 minutes from the last request it served. This reduces cost and also push the responsibility of scaling up and down to AWS, while we can focus on business needs. Sounds all good, not really it also comes with a challenge due to this design. Every time a user hits your backend the Lambda has to be brought up unless it is already running and free. The time that takes for the service to be up in general is around 20 ms. Which should be ideal for a lot of business applications. This gradually increases to 10s in the particular cases, where the Lambda has to access a DB in a VPC. 10s cold start for user facing service is a clear no for a lot of business cases. This problem has made architects rethink the usage of AWS Lambda.</p><h4>Some of the solutions for AWS Lambda cold start problems:</h4><p>When we faced a similar problem we started looking into possible solutions. After a lot of research, we identified 3 different solutions with its own pros and cons.</p><ol><li>AWS has announced in the 2018 ReInvent conference, that they are redesigning the AWS Lambda architecture to overcome the cold start problem when accessing database inside a VPC. Sounds good for a company which can bear with the cold start problem till the launch. AWS did not commit to a particular date, but it is expected to be launched anytime this year(2019). If the 10s cold start problem is not acceptable for your use case like us, then this solution of waiting may not work.</li><li>AWS announced last year(2018) Aurora serverless DB. Sounds very exciting. It basically allows architects and DBA teams not to worry about provisioning the right size for DB or worry about scaling the DB up and down. The serverless DB lets you configure your DB to scale up or down based on the business needs automatically. Saving precious dollars to the business. Serverless DB has to be only private by default and can be accessed with AWS Lambda through AWS SDK. If serverless db sounds good for your use case, it also comes with another advantage. It allows AWS Lambda to access serverless DB in a secure way even without having it in a separate VPC. This approach also solves the cold start problem.</li><li>The last solution is to have a seperate Lambda whose core functionality is to access the DB in the VPC. This Lambda alone suffers from cold start problem, which can be temporarily solved by keeping a few instances of Lambda warm. One of the strategy to keep AWS Lambda warm is by using Cloudwatch. All the other Lambda which needs access to DB can do so by accessing the Lambda which alone has access to DB.</li></ol><p>Feel free to share if you have solved the Lambda cold start problems using a different approach.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=304daab5d3b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 3 popular courses on DeepLearning]]></title>
            <link>https://medium.com/data-science/the-3-popular-courses-for-deeplearning-ai-ac37d4433bd?source=rss-d7564bad2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac37d4433bd</guid>
            <category><![CDATA[kdnuggets]]></category>
            <category><![CDATA[deep]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Vishnu Subramanian]]></dc:creator>
            <pubDate>Sat, 19 Aug 2017 10:42:48 GMT</pubDate>
            <atom:updated>2022-08-08T07:16:23.473Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/94/1*-2cOU7iKtRfRoj5YQdJvdw.png" /></figure><blockquote>I have been actively focussing on specialising Deep Learning for the last 2 years. My personal interest towards Deep learning started around 2015 when Google open sourced Tensorflow .Tried quickly couple of examples from the Tensorflow documentation and left with a feeling that Deep learning is difficult, partly because the framework was new and required better hardware and tons of patience .</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*yfizqHNKUuL_RUOkQdzLBQ.jpeg" /></figure><p>Fast forward to 2017 I have spent 100’s hours working on Deep learning projects and the technology has become more and more accessible due to several advancements in software(ease of usage — <a href="https://keras.io/">Keras</a>, <a href="http://pytorch.org/">PyTorch</a>), hardware(GPU becoming commercially viable for someone like me sitting in India -Not still cheap), availability of data, good books, and MOOCs. After completing the 3 most popular MOOCS in deep learning from <a href="http://www.fast.ai/">Fast.ai</a>, <a href="https://www.deeplearning.ai/">deeplearning.ai/Coursera</a> (which is not completely released), and <a href="https://in.udacity.com/">Udacity</a>, I believe a post about what you can expect from these 3 courses will be useful for future Deep learning enthusiasts.</p><p>In this post, I talk about 5 aspects of each course that will help you decide.</p><ol><li><strong>About the Guru:</strong> Each course is taught by amazing people who come with very different experiences. I believe these experiences have a high influence on the style of teaching. So we will look at the background of our Course Gurus.</li><li><strong>About the course: </strong>A high-level overview of the course.</li><li><strong>Highlights: </strong>Points highlighting where the course makes you feel wow.</li><li><strong>Limitations:</strong> I want to be very choosy of this word, as I know that all of them had put tremendous and sincere efforts on how to make the content easily accessible. I want this section to be interpreted as, what we missed in the course. Certain limitations could be because of the design of the course.</li><li><strong>Cost:</strong> Cost incurred to take the course.</li></ol><h3>Fast.ai :</h3><p>I came across this course when reading an article in <a href="http://www.kdnuggets.com/">KDNudggets</a>. For the first time, I heard about <a href="https://medium.com/u/34ab754f8c5e">Jeremy Howard</a>, searched about him on <a href="https://en.wikipedia.org/wiki/Jeremy_Howard_(entrepreneur)">Wikipedia</a>, and was impressed. Checked his MOOC which was taught by Jeremy and Rachel Thomas. Finished watching the first lesson, and was highly impressed with their teaching style.</p><blockquote>In a matter of hours you learn how to build a state of art image classifier in less than few $.</blockquote><h4>About the <a href="https://en.wikipedia.org/wiki/Guru">Guru</a> :</h4><p>Jeremy comes from a very different background than the usual professors, he does not have a Ph.D. from any of the top universities and does not work for any of the top companies like Google, Baidu, Microsoft, and many more. He is a self-taught, kaggle master, entrepreneur, and CEO of Fast.ai at present, with the sole aim of <strong>Making</strong> <strong>Deep learning uncool again</strong>. His uniqueness adds a huge differentiator to this course, as he teaches how deep learning can be used by people from varied backgrounds without access to either huge amounts of data or computation power.</p><h4>About the course :</h4><p>The course is divided into 2 parts, each 7 weeks long. The first part of the course teaches how to use deep learning in the fields of computer vision and Natural language processing (NLP). The second part teaches cutting-edge research work like generative networks, GANs, Sequence Sequence Models, how to read research papers, and a lot of practical tips on how to stay ahead in the deep learning space which is evolving at a tremendous speed.</p><p>This course is taught in a unique style. The authors of the course believe in a unique approach.</p><blockquote>You do not learn playing Cricket(Or any game) after reading about things like velocity , momentum , analytics and then go to field at 18 . Instead we go the field ,hold a ball or bat and then learn the rest on the fly .</blockquote><p>With this unique approach, you start by learning to set up your workstation on the cloud, install software, and quickly build solutions using Deep learning. Every week Jeremy picks a new problem, and then he teaches techniques to use to improve the performance of the models. He teaches practical things like using pre-convoluted features, pseudo labeling, and many tricks which are very useful. By the end of the first part, you will be able to use deep learning to build useful applications in the domain you are working in.</p><p>The 2nd part of the course introduces cutting-edge research by helping you to read, understand and implement various research papers in the space of generative models, image segmentation, and sequence2sequence models. You learn to build interesting projects like Style Transfer, Low-Resolution Images to High-Resolution Images, GAN, Image Segmentations, Language translation, and how to apply DL on structured data. The most important part of part 2 is setting up your own workstation. This proves to be very useful if you are passionate about deep learning and want to build various DL applications.</p><h4>Highlights :</h4><ol><li>Ability to build state of art systems in Vision and NLP.</li><li>Understand and use modern architectures that power a lot of Deep learning applications.</li><li>Loads of practical tips on how to apply DL quickly when you have limited data and computation power.</li><li>A huge community that supports you at different stages of learning and implementing your solutions.</li><li>Will be comfortable in using 3 popular DL frameworks namely Keras, TensorFlow, and PyTorch.</li><li>By the end of the course, you will be comfortable with reading research papers, building new projects, blogging about them, and an entire community to support you.</li></ol><h4>Limitations :</h4><ol><li>As this course follows a top-down approach, you will be relying heavily on the frameworks to abstract away the underlying math. It is helpful to understand the math that powers the DL if you are planning for a job or for more research in the space.</li><li>Some institutions may give importance to certificates as proof for course completions, but I guess Jeremy believes that we are mature kids and does not provide any form of certificates. Instead of traditional certificates, Jeremy and Rachel encourage to write blogs, build projects, and give talks at conferences. Which I personally believe to be really useful.</li></ol><h4>Cost :</h4><p>There is no cost associated with the MOOC. But to practice the projects, you will end up spending on AWS or you may set up your own machine which turns out to be expensive. But having a powerful workstation at the house is extremely helpful.</p><h3>Deeplearning.ai:</h3><p>I came across this course recently when <a href="https://medium.com/u/592ce2a67248">Andrew Ng</a> tweeted. I have been following him since early 2014, I was learning the math behind Machine learning from one of his courses on Coursera. Coming from an engineering background found his 1st course very interesting and at the same time a bit hard to complete. Fast forward to 2017, Andrew Ng left Baidu where he was working as a chief scientist and launched a new Deep learning specialization on August 8th. I thought of doing it sometime later this year as I was already occupied with a bunch of other projects. Then I read a <a href="https://medium.com/towards-data-science/thoughts-after-taking-the-deeplearning-ai-courses-8568f132153">blog</a> from a student of Fast.ai <a href="https://medium.com/u/6e6d06d4b300">Arvind N</a> on how he completed all the 3 parts in 4 days and his views on fast.ai and deeplearning.ai.</p><blockquote>I wanted to challenge myself , if I can complete the same in less than 4 days , and yes I finished the 3 courses in 3 days time.</blockquote><h4>About the Guru :</h4><p>Andrew Ng was a professor at Stanford University, cofounded Coursera, founded and led the Google Brain deep learning project, and was chief scientist at Baidu. The course reflects a lot of his learning from working on a wide variety of problems at scale.</p><blockquote>The course helps you in understanding Math required for deep learning and by the end of course 2 you would have built several key components of deep learning algorithms from scratch.</blockquote><h4>About the course :</h4><p>The course is divided into 5 parts. At the time of writing the first 3 were released. Andrew Ng takes a bottom-up approach for this course. In his earlier course, he picks octave for programming assignments, but he chooses python for this course.</p><ol><li>In course 1 he carefully covers the math, and intuitions required for a lot of concepts in deep learning. He carefully balances the course content, by carefully teaching only the math, that is required to understand the building blocks of deep learning. The assignment sessions are really useful in practicing math in a programmatic way. All the formulas are provided, so you can focus on implementing them, even if you do not have much expertise in math.</li><li>Course 2 covers a lot of techniques like regularisation, momentum, batch normalization, and dropout to improve the performance of your DL models. The best part of this course is you implement all of the techniques using python and NumPy.</li><li>In course 3 he explains a lot of tips and tricks that he learned from years of his experience. At the end of the 3rd course, he introduces DL frameworks. Course 3 ends with an assignment on how to use TensorFlow. The assignment was very clearly designed to be very intuitive.</li><li>Course4 will be on CNN. Will update this part once the course is released.</li><li>Course5 will be on RNN or Sequence data. I will update this part once the course is released.</li></ol><h4>Highlights :</h4><ol><li>By the time you complete 3 courses, you will have your fundamentals very strong.</li><li>First, 3 courses take a framework-independent approach, which will prepare you to use any framework with ease.</li><li>Loads of practical tips on how to design evaluation metrics, how to split datasets for training, and avoid variance and bias problems.</li><li>The best part of course 3 is a case study, where you get a chance to validate your understanding of how to execute deep learning projects successfully.</li><li>No need to worry about infra as all the assignments are provided in the form of jupyter notebooks running on Coursera servers.</li><li>After an amazing set of 3 courses, waiting for the next 2 parts.</li><li>Each week includes a talk named after “Heros of Deep learning”. It is a good source to know a lot about the history and inspirations behind deep learning.</li></ol><h4>Limitations :</h4><ol><li>For someone completely new to Deep Learning or Machine learning, it could be challenging to build each component from scratch and understand the math behind it.</li><li>Since it follows a bottom-up approach, even after the end of the 3rd course you will find it hard to build solutions using DL in your domain.</li><li>Since the Infra is provided, you will miss the learning of how to manage your workstation yourself. It is really important to be able to set up your machine on the cloud or at home/office if you want to use the lot of techniques that you pick up.</li><li>A lot of boilerplate code is provided to make the assignments easier. But to really pick up a skill it is essential, that you reimplement the entire assignment without using the boilerplate code. This may not be a limitation of the course, but it is really important if you want to make the best use of it.</li></ol><h4>Cost:</h4><p>All the course contents are available for free. However, I am not sure if the assignments are also available for free. If you are taking the paid version, then you end up spending approximately 3800Rs or 55$ per month.</p><h3>Siraj Raval’s Deep learning Nano degree foundation by Udacity :</h3><p>I am a great fan of Udacity. They have really amazing courses on a wide range of topics. So when I read their announcement on the Deep learning course early this year, I was damn excited and enrolled for the first batch.</p><h4>About the Guru’s:</h4><p>Some parts of the course include videos from <a href="https://medium.com/u/54526471f9bf">Siraj Raval</a> and the rest from Udacity. I came to know about Siraj Raval from some of his interesting videos on youtube. He is a multi-skilled person who smartly delivers educational videos in an interesting format by mixing it with music and videos. Some parts of the course were also taught by Andrew W.Trask and Ian Goodfellow.</p><h4>About the course :</h4><p>Unlike the other 2 courses, this course does not take a clear approach of either bottom up or top down. The course was divided into 5 parts and was given amazon credits of 100$. It covers a lot of Deep Learning techniques like CNN, RNN, GAN, and Auto Encoders.</p><h4>Highlights :</h4><ol><li>In the first few weeks of the course, you learn how to build a Neural network using python and the rest of the course focuses on using TensorFlow.</li><li>Personalized project reviews are provided for all the projects that are submitted as part of the course.</li><li>By the end of the course, you get comfortable using TensorFlow as you use TensorFlow for all the projects.</li><li>Amazing community and forum mentors, who are ready to help you all the time.</li></ol><h4>Limitations:</h4><ol><li>Practical tips on how to run DL optimally / get state of art performance results were not focused on.</li><li>Some of the projects were too simple for use in real-world scenarios. The dataset sizes used for this project were very small.</li><li>The boilerplate abstracts away a lot of complexity in building DL applications. But if you are focussed on learning it for real-world usage, it is advisable to implement the projects on your own without using the boilerplate code.</li></ol><h4><strong>Cost:</strong></h4><p>The course cost is on the higher side. No free version is available. When I took the course, there was a limited offer so it cost approximately 2500Rs or 350$.</p><h4>Recommendations :</h4><p>If someone is starting Deep learning today [Self-study], I would recommend finishing fast.ai as it has the minimum prerequisites and continuing with Coursera Deep learning specialization sequentially or in parallel. Thanks to all the amazing people for making sincere efforts to make this technology accessible.</p><p>This blog is also featured on <a href="https://www.kdnuggets.com/2017/10/3-popular-courses-deep-learning.html">KDnuggets</a>.</p><h3>Call to Action</h3><p>If you liked this article, <strong>hold that clap icon</strong> for as long as you think this article is worth it. I am always looking for feedback to improve my articles. If you have suggestions or questions, feel free to respond.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac37d4433bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-3-popular-courses-for-deeplearning-ai-ac37d4433bd">The 3 popular courses on DeepLearning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning at scale :- Accurate, Large Mini batch SGD:]]></title>
            <link>https://medium.com/data-science/deep-learning-at-scale-accurate-large-mini-batch-sgd-8207d54bfe02?source=rss-d7564bad2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/8207d54bfe02</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Vishnu Subramanian]]></dc:creator>
            <pubDate>Wed, 09 Aug 2017 02:48:33 GMT</pubDate>
            <atom:updated>2017-08-09T14:08:21.934Z</atom:updated>
            <content:encoded><![CDATA[<p>Working with distributed computing ( 😄 Big Data )for a while , I wonder how deep learning algorithms scale to multiple nodes. Facebook AI research (FAIR) recently published a <a href="https://arxiv.org/abs/1706.02677">paper</a> on how they ran successfully an resnet-50 layer model on ImageNet dataset with a mini batch size of 8192 images in an hour using 256 GPU’s . I believe a lot of information presented in the paper applies to everyone who is trying to build models quickly on a multi GPU setup. In this article I summarise the key insights from the paper that will be useful when you try to scale your deep learning implementations .</p><h3>Key Insights :</h3><ol><li>Distributed synchronous SGD provides a solution to the problem of dividing SGD mini batches over a bunch of nodes which can be multiple GPU’s.</li><li>Large mini-batch sizes causes optimization difficulties and there are techniques to solve it.</li><li>Use a Linear scaling rule for adjusting learning rate , which is a function of mini-batch size and a warm up scheme .</li></ol><h4>Why Scale matters ?</h4><p>In the recent times it is proved that deep learning algorithm works better when provided with huge amounts of data. With more data , it showed tremendous improvement in the fields of computer vision , natural language processing and speech. But running an architecture like Resnet -50 at scale of 256 nodes comes with its own challenges.</p><h4>What is distributed synchronous SGD ?</h4><p>Below is the SGD formulation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*1Nafq-Ecn_ogxrEq6zibtw.png" /></figure><p>Where X is the total dataset , x is sample from the data set , l(x,w) is the loss (Cross entropy loss) computed for each sample with respect to a label .</p><p>But in practice we use a mini batch SGD , where we calculate the loss and gradients for every batch and modify the weights accordingly. As formulated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*9fB5Xu5ef5XilP9DWEl9uA.png" /></figure><p>Where β represent the mini batch which is a subset of X .</p><p>In case of distributed synchronous SGD , each GPU runs the same graph on a subset of the mini batch data , once the GPU completes processing , the weights are transferred to parameter server which aggregates all the gradients from multiple GPU’s and sends back to them.</p><p>There are few tricks that needs to be applied like Linear scaling , warmup strategy to allow the model to achieve results in par to the models trained on smaller batches on a single GPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OBp5WcJqlGs4ijRPdsQAfQ.png" /><figcaption>Source : <a href="https://arxiv.org/abs/1706.02677">Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour</a></figcaption></figure><h4>Why are the tricks important ?</h4><p>One major challenge of using large batch sizes in order of 1000’s is , the gradients tend to oscillate when trained with normal learning rates. Hence experiments showed, it is difficult to train when batch size increases.</p><p>Three important solutions where proposed to mitigate the above problem.</p><ol><li>Linear Scaling Rule</li><li>Warmup Strategies</li><li>Batch Normalization with Large Mini Batches</li></ol><h4>What is Linear Scaling Rule?</h4><p>Ability to use large batch sizes is extremely useful to parallelise processing of the images across multiple worker nodes. All the linear scaling rule says is increase the learning rate by “k”times. Where “k” is the times your batch size is increased. Though the rule is simple , it turns out to be a powerful one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iUXQPXWTHbfPlKIzNq75mQ.png" /><figcaption>Source : <a href="https://arxiv.org/abs/1706.02677">Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour</a></figcaption></figure><p>The image with (a) shows how the model performs when just the linear scaling rule is applied. Looking at the results , it is evident that the model with a batch size of 8k performed nearly as good as the model that was trained with normal batches. The warmup strategy helps the model to perform as good as the one , that is trained with smaller batches.</p><h4>What are warmup strategies ?</h4><p>Two markup strategies are discussed. One is constant warmup and gradual warmup.</p><p><strong>Constant warmup:</strong> In constant warm up , you train the model with a small learning rate for few epochs (5 epochs in the paper) and then increase the learning rate to “k times learning rate” .However this approach causes a spike in the training error when the learning rate is changed. The observation is visible in the (b) image above. The models training error is also higher compared to the simple Linear scale rule.</p><p><strong>Gradual warmup:</strong> As the name suggests , you start with a small learning rate and then gradually increase it by a constant for each epoch till it reaches “k times learning rate”. This approach helps the model to perform better with huge batch sizes (8k in this example) , which is in par with the training error of the model trained with smaller batches.</p><h4>What is special about Batch Normalization when using large batch sizes?</h4><p>Batch Normalization computes statistics across the samples in a mini batch. When we calculate the losses of samples across multiple nodes ,it is important that a loss of a sample be independent of the other. But when you use batch normalization the loss function for a sample is no more independent of others. The mini batch statistics that is computed is a key component of the loss. If the per worker mini batch sample size is changed , it affects the underlying loss function being optimized .</p><p>Hence it is suggested to keep the mini batch size same across all worker nodes , in the paper it is 32 samples across each worker and the number of workers are 256. The batch normalization should be calculated at a node (of size 32)level rather than at a batch level(of size 8k).</p><h4>Subtleties and pitfalls of distributed SGD:</h4><ol><li>Scaling cross entropy loss is not equivalent to scaling learning rate.</li><li>There are two popular ways of applying momentum , one which calculates before using learning rate(eq 9) and one which uses learning rate(eq 10).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*XE_UV9X2pGMj7TULq15-RQ.png" /><figcaption>Source : <a href="https://arxiv.org/abs/1706.02677">Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*vbBQ3QOj4R60zKxzwF0v5Q.png" /><figcaption>Source : <a href="https://arxiv.org/abs/1706.02677">Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour</a></figcaption></figure><p>It is observed that applying momentum correction after changing learning rate provides more training stability.</p><p>3. When performing gradient aggregation , normalize the gradients in each worker by kn rather than n . “n” indicates the number of samples processed per worker node and “k” represents the total no of workers.</p><p>The paper also describes about the algorithms used for network communications , software used , hardware used and experiments conducted with various hyper parameters. Its a must read if you are planning to go on scale any time sooner.</p><p>Meet you with another post soon 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8207d54bfe02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deep-learning-at-scale-accurate-large-mini-batch-sgd-8207d54bfe02">Deep Learning at scale :- Accurate, Large Mini batch SGD:</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transfer Learning using PyTorch — Part 2]]></title>
            <link>https://medium.com/data-science/transfer-learning-using-pytorch-part-2-9c5b18e15551?source=rss-d7564bad2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c5b18e15551</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Vishnu Subramanian]]></dc:creator>
            <pubDate>Wed, 19 Apr 2017 13:19:50 GMT</pubDate>
            <atom:updated>2017-04-21T03:24:31.791Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@vishnuvig/transfer-learning-using-pytorch-4c3475f4495">previous blog </a>we discussed how Neural networks use transfer learning for various computer vision tasks .In this blog we will look into the following.</p><ol><li>VGG Architecture</li><li>Fine tune VGG using pre-convoluted features</li><li>Accuracy</li><li>Performance comparison between PyTorch and Keras on Tensorflow</li></ol><h4>VGG Architecture :</h4><p>One of the most studied Deep learning models for transfer learning is VGG. We will go through a high level overview of VGG to understand how it can be optimally used in transfer learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*3sD-1ZR9R6UaEOil9FFErQ.png" /></figure><p>VGG model can be split into two kinds of logical blocks</p><ol><li><strong>Convolution blocks:</strong></li></ol><p>The pre-trained VGG model is trained on Image net data set over 1000 categories. The convolutional block contains multiple convolution layers . The initial layers contain low level features like lines , curves . The last convolutional layers in this block contain more complex kind of features of images like hand, leg , eyes and many more.The below image captures what kind of features are captured in different layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*jPCEik198_CjtmSL2H6o4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*1Y6HZxK-lOmqB8KnizTCow.png" /></figure><p>As you can see from the above images , the features being captured by the convolution layers of a pre-trained model can be used across most kind of image problems. The above features may not work for problems like cartoon animations , medical images since they need completely different features.</p><p>The convolution layers exhibit 2 important properties -</p><ol><li>The number of parameters required is far less compared to fully connected layer. For example a Convolution layer with 3 * 3 * 64 size filters need only 576 parameters.</li><li>Convolution layers are computationally expensive and take longer to compute the output.</li></ol><p><strong>2. Fully Connected Block:</strong></p><p>This block contains Dense(in Keras) / Linear(in PyTorch) layers with dropouts. The number of parameters to learn in FC layers are huge but takes way less time to compute.</p><p>So, we generally end up taking pre convoluted features from Convolution block of VGG model as it is and training only the last few layers of the VGG model which are generally from fully connected block.</p><h4><strong>Fine tune VGG using pre convoluted features :</strong></h4><p>As we know that convolution layers are expensive to calculate , it makes sense to compute the output of the convolution layers once and use them to train the fully connected layer . This approach speeds up the process of training new models using transfer learning. For example , if it takes 3 minutes to train the model for 1 iteration , by pre computing the convolutional layer output(say it takes 2 min) and for the rest of the iterations in FC block only takes few seconds per iteration.</p><p><strong>Pre convoluted features :</strong></p><p>I am using<a href="https://www.kaggle.com/c/dogs-vs-cats-redux-kernels-edition/data"> <strong>dogs and cats</strong> dataset from <strong>kaggle</strong></a> , which contains 25000 images .I have kept 2000 images for validation and the remaining 23000 for training.</p><p><strong>Hardware benchmarked on :</strong></p><p>I am using an <strong>Intel i7 processor , 64 gb ram and Titan X GPU</strong> for the mentioned experiments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*90emu6g1cyUbpfnD-aZfRA.jpeg" /><figcaption>My Monster playing with NN weights :)</figcaption></figure><p>To compute the convolutional features ,we pass all the images through the convolutional layers . Luckily pytorch implements VGG as 2 logical blocks consisting of features(Convolutional block) and classifier block (FC). In the below code we will use the features block to compute convolutional layers output. We store it into a bcolz array for further processing. Bcolz array provides a compressed and faster way to process array.</p><pre>model_vgg = models.vgg16(pretrained=True)<br>for param in model_vgg.parameters():<br>    param.requires_grad = False<br>def preconvfeat(dataset):<br>    conv_features = []<br>    labels_list = []<br>    for data in dataset:<br>        inputs,labels = data</pre><pre>inputs , labels = Variable(inputs.cuda()),Variable(labels.cuda())<br>        x = model_vgg.features(inputs)<br>        conv_features.extend(x.data.cpu().numpy())<br>        labels_list.extend(labels.data.cpu().numpy())<br>    conv_features = np.concatenate([[feat] for feat in conv_features])<br>    return (conv_features,labels_list)</pre><p>It took me <strong>1 minute 8 seconds</strong> to calculate the features for training dataset of 23000 images . The approximate size is 600 mb.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VRpV55rqN8N_1m31uR3D1Q.png" /></figure><p><strong>Fine Tuning :</strong></p><p>We can use the processed features to train the fully connected layers. For <strong>10 iterations</strong> it took <strong>25 seconds</strong>.Code snippet for using VGG classifier block.</p><pre>for param in model_vgg.classifier[6].parameters():<br>    param.requires_grad = True<br>train_model(model=model_vgg.classifier,size=dset_sizes[&#39;train&#39;],conv_feat=conv_feat_train,labels=labels_train,epochs=10,optimizer=optimizer,train=True,shuffle=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SevYK4P8FwPpBwHK1RuQjg.png" /></figure><h4>Accuracy :</h4><p>After running the model for approximately 30 epochs , that is in less than few minutes , the validation accuracy reached to 97% . The accuracy can be improved further by adding Batch normalization and decreasing dropout values. In this <a href="https://github.com/svishnu88/pytorch/blob/master/TransferLearning.ipynb">notebook</a> I have included the other experiments that I have tried.</p><h4>Performance comparison between PyTorch VGG and Keras on Tensorflow VGG:</h4><p>I have been using Keras on Tensorflow for quite sometime. So I was eager to see how both of them perform in regards with time . I am using PyTorch version 0.1.11 and Tensorflow version 1.0.1 for the experiment.</p><p>Experiment Conducted : Ran pretrained VGG model with convolution layer weights unchanged. Did not calculate any convolution features. Ran on the 23000 images for 10 epochs. And below is my result.</p><p>PyTorch — 15 min 19s</p><p>Keras on Tensoflow — 31min 29s</p><p>PyTorch has data loaders which can use multiple threads at a time to load the data. When 6 threads are used the performance of the VGG model improves to 11 min.</p><p><strong>Update : Based on the below tweet , I have tried using keras with 6 workers for pre processing and the performance for each epoch improved to 1 min 40 seconds from 3 min 21 seconds. PyTorch for one epoch took 1 min 11 seconds using 6 workers.</strong></p><h3>François Chollet on Twitter</h3><p>@vishnuvig @hardmaru @mat_kelcey @stratospark @fkratzert @jeremyphoward @PyTorch @tensorflow Just use `pickle_safe=True` and `num_workers=4` (for instance) in your call to `fit_generator`. That is all.</p><p><strong>Conclusion: Few observations that I made when using Keras and pytorch . Keras is too abstract , good to start , build standard models quickly . Performance is expected to be better than PyTorch , but it does not look that way , though there are lot of improvements lined up with TensorFlow. On the other hand PyTorch provides similar API to Python NumPy along with ability to operate on GPU. The learning curve is a lot lesser than tensorflow and lot flexible than Keras. So if you are passionate about Deep Learning then you should definitely take a look at PyTorch.</strong></p><p><strong>Apart from frameworks, we discussed how we can use pre-convoluted features to train the model lot faster.In fact Jeremy Howard in his part 2 course , which will be soon available as </strong><a href="http://course.fast.ai/"><strong>MOOC</strong></a><strong> discusses an interesting approach of how Facebook uses these pre convoluted features. The approach states that “When different teams are working on the same data set , it makes a lot of sense to calculate these Convolution features and make it available for all the teams.” . This approach will save a lot of time while building models. In fact Facebook approaches the problem on similar lines.</strong></p><p>You can find the code associated for the experiments<a href="https://github.com/svishnu88/pytorch"> here</a>.</p><p>You can find me on <a href="http://www.linkedin.com/in/vishnusubramanian">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c5b18e15551" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/transfer-learning-using-pytorch-part-2-9c5b18e15551">Transfer Learning using PyTorch — Part 2</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transfer learning using pytorch — Part 1]]></title>
            <link>https://medium.com/data-science/transfer-learning-using-pytorch-4c3475f4495?source=rss-d7564bad2de------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c3475f4495</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Vishnu Subramanian]]></dc:creator>
            <pubDate>Thu, 13 Apr 2017 17:00:02 GMT</pubDate>
            <atom:updated>2017-04-19T13:58:15.742Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever wondered why ML models have to learn every time from scratch . What if the models can use knowledge learnt from recognising cats, dogs ,fish ,cars , bus and many more to identify a distracted car driver or to identify plant disease .In transfer learning we use a pre trained neural network in extracting features and training a new model for a particular use case. Not sure what it is.. just wait till the end of the blog.</p><h3>Why PyTorch</h3><p>There are many frameworks like Keras , Tensoflow , Theano ,Torch, Deeplearning.4J , etc which can be used for deep learning . Out all these my favourite is Keras on top of Tensorflow. Keras works great for a lot of mature architectures like CNN, feed forward neural network , Lstm for time series but it becomes bit tricky when you try to implement new architectures which are complex in nature. Since Keras was built in a nice modular fashion it lacks flexibility . Pytorch which is a new entrant ,provides us tools to build various deep learning models in object oriented fashion thus providing a lot of flexibility . A lot of the difficult architectures are being implemented in PyTorch recently. So I started exploring PyTorch and in this blog we will go through how easy it is to build a state of art of classifier with a very small dataset and in a few lines of code.</p><p>We will build a classifier for detecting ants and bees using the following steps.</p><ol><li>Download the dataset from <a href="https://download.pytorch.org/tutorial/hymenoptera_data.zip">here</a>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*00H4V_so4YYeQCGfN5cyjw.png" /></figure><p>2. Data augmentation.</p><p>3. Downloading pre trained resnet model (Transfer learning).</p><p>4. Training the model on the dataset .</p><p>5. How to decay the learning rate for every n<em>th</em> epoch.</p><h4>Download dataset :</h4><p>Download the dataset from the above link . It contains 224 images in the training dataset and 153 images in the validation dataset.</p><h4>Data augmentation :</h4><p>Data augmentation is a process where you make changes to existing photos like adjusting the colors , flipping it horizontally or vertically , scaling , cropping and many more. Pytorch provides a very useful library called torchvision.transforms which provides a lot of methods which helps to apply data augmentation. transforms comes with a compose method which takes a list of transformation.</p><pre>data_transforms <strong>=</strong> {</pre><pre>    &#39;train&#39;: transforms<strong>.</strong>Compose([<br>        transforms<strong>.</strong>RandomSizedCrop(224),<br>        transforms<strong>.</strong>RandomHorizontalFlip(),<br>        transforms<strong>.</strong>ToTensor(),<br>        transforms<strong>.</strong>Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])<br>    ]),<br>    &#39;val&#39;: transforms<strong>.</strong>Compose([<br>        transforms<strong>.</strong>Scale(256),<br>        transforms<strong>.</strong>CenterCrop(224),<br>        transforms<strong>.</strong>ToTensor(),<br>        transforms<strong>.</strong>Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])<br>    ]),<br>}</pre><h4>Transfer Learning :</h4><p>We will use a model called ResNet from Microsoft which won the ImageNet competition in 2015. It showed how deep networks can be made possible. Lets not get into the complexity of the ResNet. We will download the model and most of the modern deep learning frameworks makes loading a model easier. The ResNet model compromises of a bunch of ResNet blocks(Combination of convolution and identity block) and a fully connected layer. The model is trained on Imagenet dataset on 1000 categories , we will remove the last fully connected layer and add a new fully connected layer which outputs 2 categories which tells the probability of the image being Ant or Bee.</p><pre>model_conv <strong>=</strong> torchvision<strong>.</strong>models<strong>.</strong>resnet18(pretrained<strong>=</strong>True)<br><strong>for</strong> param <strong>in</strong> model_conv<strong>.</strong>parameters():    ----&gt; 1<br>    param<strong>.</strong>requires_grad <strong>=</strong> False<br><br><em># Parameters of newly constructed modules have requires_grad=True by default</em><br>num_ftrs <strong>=</strong> model_conv<strong>.</strong>fc<strong>.</strong>in_features<br>model_conv<strong>.</strong>fc <strong>=</strong> nn<strong>.</strong>Linear(num_ftrs, 2)   ----&gt; 2</pre><pre><strong>if</strong> use_gpu:<br>    model_conv <strong>=</strong> model_conv<strong>.</strong>cuda()       ----&gt; 3</pre><ol><li>We tell the model not to learn or modify the weights / parameters of the model.</li><li>Then we add a new fully connected layer to the existing model to train our model to classify 2 categories.</li><li>If you have a gpu .cuda() executes the model in GPU.</li></ol><p>Our model is ready and we need to pass the data to train.</p><h4>Training Model :</h4><p>For training model we need a couple of more things apart from the model like:</p><ol><li>PyTorch Variable : A variable wraps pytorch tensor .It contains data and the gradient associated with the data.</li><li>Loss Function : It helps in calculating how good is our model. We will be using categorical cross entropy here.</li><li>Optimizer : We will use SGD to optimise our weights with the gradients. In our case we update the weights of only the last layer.</li><li>Forward propagation : This is the simplest part where we pass our data through the model.</li><li>Backward propagation : This is the key for modern deep learning networks where all the magic happens. Where the optimizer starts calculating how much the weights need to be updated in order to reduce the loss or improve the accuracy. In most modern frameworks this is automated , so we can focus on building cool applications backed by deep learning.</li></ol><pre>if use_gpu:<br>    inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda()) --&gt; 1<br>else:<br>    inputs, labels = Variable(inputs), Variable(labels)</pre><pre>criterion = nn.CrossEntropyLoss() --&gt; 2</pre><pre># Observe that all parameters are being optimized<br>optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9) --&gt;3</pre><pre># zero the parameter gradients<br>optimizer.zero_grad()</pre><pre># forward <br>outputs = model(inputs) --&gt; 4<br>loss = criterion(outputs, labels)</pre><pre># backward + optimize only if in training phase<br>if phase == &#39;train&#39;: --&gt; 5<br>    loss.backward()<br>    optimizer.step()</pre><h4>Decaying Learning Rate :</h4><p>Most of the times we start with a higher learning rate so that we can reduce the loss faster and then after a few epochs you would like to reduce it so that the learning becoming slower. I found this function from pytorch <a href="http://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html">tutorials</a> very useful.</p><pre><strong>def</strong> <strong>lr_scheduler</strong>(optimizer, epoch, init_lr<strong>=</strong>0.001, lr_decay_epoch<strong>=</strong>7):<br>    &quot;&quot;&quot;Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs.&quot;&quot;&quot;<br>    lr <strong>=</strong> init_lr <strong>*</strong> (0.1<strong>**</strong>(epoch <strong>//</strong> lr_decay_epoch))<br><br>    <strong>if</strong> epoch <strong>%</strong> lr_decay_epoch <strong>==</strong> 0:<br>        <strong>print</strong>(&#39;LR is set to {}&#39;<strong>.</strong>format(lr))<br><br>    <strong>for</strong> param_group <strong>in</strong> optimizer<strong>.</strong>param_groups:<br>        param_group[&#39;lr&#39;] <strong>=</strong> lr<br><br>    <strong>return</strong> optimizer</pre><p>We are reducing the learning rate for every nth epoch , in the above example 7 with 0.1 . decay_rate is configurable. Even on a smaller dataset we can achieve state of art results using this approach.</p><p>Wanted to try transfer learning on your dataset using pytorch , the code resides <a href="http://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html">here</a>.</p><p>Interested in learning Deep learning do not forget to checkout the amazing MOOC <a href="http://course.fast.ai/">Deep learning for coders </a>by <a href="https://medium.com/@jeremyphoward">Jeremy Howard</a> .</p><p>In the <a href="https://medium.com/@vishnuvig/transfer-learning-using-pytorch-part-2-9c5b18e15551">next part</a> we will discuss different tricks how to make transfer learning much faster using VGG . And compare how it performs in PyTorch and Tensorflow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c3475f4495" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/transfer-learning-using-pytorch-4c3475f4495">Transfer learning using pytorch — Part 1</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>