<?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 Areeb Ahmad on Medium]]></title>
        <description><![CDATA[Stories by Areeb Ahmad on Medium]]></description>
        <link>https://medium.com/@ahmadareeb3026?source=rss-885a42f360fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yO-JdOyyrnNosnVbGNpBjA.jpeg</url>
            <title>Stories by Areeb Ahmad on Medium</title>
            <link>https://medium.com/@ahmadareeb3026?source=rss-885a42f360fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:28:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmadareeb3026/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[Deploying your ComfyUI workflows on the Runpod serverless]]></title>
            <link>https://medium.com/@ahmadareeb3026/deploying-your-comfyui-workflows-on-the-runpod-serverless-2f0f0a79a8e8?source=rss-885a42f360fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f0f0a79a8e8</guid>
            <dc:creator><![CDATA[Areeb Ahmad]]></dc:creator>
            <pubDate>Thu, 23 Oct 2025 21:57:39 GMT</pubDate>
            <atom:updated>2025-10-23T22:10:36.240Z</atom:updated>
            <content:encoded><![CDATA[<h3>Runpod Serverless Deployment</h3><p>In this article, we will see how to deploy a comfyUI workflow on runpod serverless</p><ul><li>We will deploy a simple Flux Kontext workflow that takes an image and a reference image to transfer pose.</li><li>We will use the pre-existing volume for this, in which we have models already downloaded.</li><li>You will see how to deploy a workflow such that runpod workers handle the serverless request for you</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BXoYJKGeRRl789d8.png" /></figure><h3>Flux kontext Workflow (pose transfer):</h3><p>The workflow that we will deploy will use a Flux Kontext model, a lora, and basically our workflow will take 2 images, in which one image will be a reference image for the pose and the other image will be as image on which we want to apply the pose.</p><h3>Nodes and models used in the workflow:</h3><p><strong>Custom nodes:</strong> LogicUtils, KJnodes, comfyui_controlnet_aux, comfyui_essentials</p><p><strong>lora:</strong> RefControl_Flux_Kontext.safetensors</p><p><strong>vae:</strong> ae.safetensors</p><p><strong>model</strong>: flux1-dev-kontext_fp8_scaled.safetensors</p><p><strong>“clip_name1”:</strong> “clip_l.safetensors”,</p><p><strong>“clip_name2”:</strong> “t5xxl_fp8_e4m3fn_scaled.safetensors”,</p><h3>Deployment Begin:</h3><ul><li>We will refer to the <a href="https://github.com/runpod-workers/worker-comfyui">Runpod-worker-github-repo</a></li></ul><p><strong>Prerequisites</strong></p><ul><li>Docker</li><li>GitHub account</li><li>Runpod account</li><li>DockerHub account</li></ul><p>The main aim is to make an environment that contains all the necessary dependencies to run our comfyUI workflow.</p><h3>Setup Instructions</h3><h4><strong>Setting up workflow in a RunPod:</strong></h4><p>Running a runpod using either the comfyui community base image or the torch image, checking the dependencies and running the workflow to know which nodes we need to install and workflow setup.</p><p>After knowing the models used and the workflow’s custom nodes, you can proceed to deploy and add the models and custom nodes in the Dockerfile</p><p><strong>Models download:</strong></p><ul><li>For the models download, you can opt for 2 strategies,</li><li><strong>One,</strong> you can make a download_model.sh script that will download the model when the container starts</li><li><strong>Second</strong> is you can make a persistent volume in the runpod, and you can download the models there beforehand while you are setting up your workflow in the pod for testing. Once all the required models are downloaded we can point to those directories in the <strong><em>extra_models_paths.yaml.</em></strong></li><li>Basically, we are doing this Creating symlink: comfy/models/Llavacheckpoint → runpod-volume/models/Llavacheckpoint</li></ul><h3><strong>Now proceeding to the serverless deployment</strong></h3><h4><strong>1. Initial Setup</strong></h4><p>First, refer to the official <a href="https://github.com/runpod-workers/worker-comfyui">runpod-worker-comfyui</a> repository for detailed documentation.</p><p>Actually, when we will use the runpod-worker base image, we don’t have to make the <a href="http://handler.py/">handler.py</a> or <a href="http://startup.sh/">startup.sh</a> files, as they come in the base image as is, which you can refer to as well in <a href="https://github.com/runpod-workers/worker-comfyui">runpod-worker-comfyu</a>.</p><h4><strong>2. Creating folder structure</strong></h4><p>For this configuration, I have used the same convention that is in the <a href="https://github.com/CodeAcme-io/Comfy-Runpod"><strong>comfy runpod</strong></a><strong> </strong>repository for making the folder/repo structure.</p><p>Folder structure would be like this for the workflow to deploy:</p><ul><li><strong>Dockerfile</strong></li><li><strong>test_input.json</strong></li><li><strong>extra_models_path.yaml</strong></li><li><a href="http://script.sh/"><strong>script.sh</strong></a><strong> </strong>(this is not necessary, but it is a rough script that we use to add the commands in sequence that we use while installing necessary dependencies.)</li><li><strong>download_models.sh</strong> (in this shell script you can specify the models you will download on the startup of the container, if you don’t plan to have a persistent volume and use it for deployment)</li></ul><h4><strong>3. Dockerfile Configuration</strong></h4><p><strong>Dockerfile:</strong></p><pre>FROM runpod/worker-comfyui:5.2.0-base<br><br><br>RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends \<br>    build-essential \<br>    cmake \<br>    wget \<br>    git \<br>    python3-dev \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br><br><br># Check Python and PyTorch versions<br>RUN python3 --version &amp;&amp; \<br>    python3 -c &quot;import torch; print(&#39;PyTorch version:&#39;, torch.__version__)&quot;<br><br><br><br><br>RUN python --version<br>RUN pip install --upgrade pip<br><br><br># Install required ComfyUI nodes for upscaling workflow<br>RUN comfy-node-install comfyui-kjnodes comfyui_controlnet_aux  comfyui_essentials comfyui-logicutils<br><br><br># for updating the comfyui with latest github commit<br>RUN cd /comfyui \<br>    git pull \<br>    cd /<br><br><br># Set Hugging Face cache directory to persistent volume<br>ENV HF_HOME=/runpod-volume/models/huggingface<br><br><br>RUN ls /comfyui<br>RUN rm -f /comfyui/extra_model_paths.yaml<br>RUN ls /comfyui<br>ADD extra_model_paths.yaml /comfyui/extra_model_paths.yaml<br><br><br>RUN rm -f /comfyui/test_input.json<br>RUN ls /comfyui<br>ADD test_input.json /comfyui/test_input.json</pre><ul><li><strong>To know the names of the nodes, you can go to the comfyUI registry here: </strong><a href="https://registry.comfy.org/"><strong><em>comfyui registry</em></strong></a></li><li>Already, a test_input.json is present in the base image <strong>(runpod/worker-comfyui:5.2.0-base)</strong> that we are using in our Dockerfile. We have to remove it; otherwise, it causes a clash while testing the image on RunPod, as it might contain the dependencies that your Docker environment doesn&#39;t have</li><li>Test_input is basically the JSON that goes in post request to your endpoint when you test your Docker image as a running container.</li></ul><h4>Creating a Symlink for the models downloaded</h4><p><strong>Extra model paths yaml:</strong></p><pre>runpod_worker_comfy:<br>  base_path: /runpod-volume/ComfyUI/<br>  checkpoints: models/checkpoints/<br>  text_encoders: models/text_encoders/<br>  diffusion_models: models/diffusion_models/<br>  clip: models/clip/<br>  clip_vision: models/clip_vision/<br>  configs: models/configs/<br>  controlnet: models/controlnet/<br>  embeddings: models/embeddings/<br>  loras: models/loras/<br>  upscale_models: models/upscale_models/<br>  vae: models/vae/<br>  unet: models/unet/<br>  llava: models/LLavacheckpoints<br>  BEN: models/BEN<br>  facexlib: models/facexlib<br>  insightface: models/insightface<br>  pulid: models/pulid<br>  sams: models/sams<br>  ipadapter: models/ipadapter</pre><h4><strong>GitHub Actions for CI/CD pipeline to create a docker image:</strong></h4><pre>name: Docker Build and Push cloth try on workflow<br><br><br>on:<br>  push:<br>    branches:<br>      - fluxkontext-posecontrol-example-deplyment # Trigger only on the &#39;deployment&#39; branch<br><br><br>    paths:<br>      - &quot;kontext_pose_control/**&quot; # Trigger only if files in this path are changed<br><br><br>jobs:<br>  build-and-push:<br>    runs-on: ubuntu-latest<br><br><br>    steps:<br>      - name: Delete huge unnecessary tools folder<br>        run: rm -rf /opt/hostedtoolcache<br><br><br>      - name: Remove unnecessary files<br>        run: |<br>          sudo rm -rf /usr/share/dotnet<br>          sudo rm -rf &quot;$AGENT_TOOLSDIRECTORY&quot;<br>      - name: Check disk space<br>        run: df . -h<br><br><br>      - name: Free disk space<br>        run: |<br>          sudo docker rmi $(docker image ls -aq) &gt;/dev/null 2&gt;&amp;1 || true<br>          sudo rm -rf \<br>            /usr/share/dotnet /usr/local/lib/android /opt/ghc \<br>            /usr/local/share/powershell /usr/share/swift /usr/local/.ghcup \<br>            /usr/lib/jvm || true<br>          echo &quot;some directories deleted&quot;<br>          sudo apt install aptitude -y &gt;/dev/null 2&gt;&amp;1<br>          sudo aptitude purge aria2 ansible azure-cli shellcheck rpm xorriso zsync \<br>            esl-erlang firefox gfortran-8 gfortran-9 google-chrome-stable \<br>            google-cloud-sdk imagemagick \<br>            libmagickcore-dev libmagickwand-dev libmagic-dev ant ant-optional kubectl \<br>            mercurial apt-transport-https mono-complete libmysqlclient \<br>            unixodbc-dev yarn chrpath libssl-dev libxft-dev \<br>            libfreetype6 libfreetype6-dev libfontconfig1 libfontconfig1-dev \<br>            snmp pollinate libpq-dev postgresql-client powershell ruby-full \<br>            sphinxsearch subversion mongodb-org azure-cli microsoft-edge-stable \<br>            -y -f &gt;/dev/null 2&gt;&amp;1<br>          sudo aptitude purge google-cloud-sdk -f -y &gt;/dev/null 2&gt;&amp;1<br>          sudo aptitude purge microsoft-edge-stable -f -y &gt;/dev/null 2&gt;&amp;1 || true<br>          sudo apt purge microsoft-edge-stable -f -y &gt;/dev/null 2&gt;&amp;1 || true<br>          sudo aptitude purge &#39;~n ^mysql&#39; -f -y &gt;/dev/null 2&gt;&amp;1<br>          sudo aptitude purge &#39;~n ^php&#39; -f -y &gt;/dev/null 2&gt;&amp;1<br>          sudo aptitude purge &#39;~n ^dotnet&#39; -f -y &gt;/dev/null 2&gt;&amp;1<br>          sudo apt-get autoremove -y &gt;/dev/null 2&gt;&amp;1<br>          sudo apt-get autoclean -y &gt;/dev/null 2&gt;&amp;1<br>          echo &quot;some packages purged&quot;<br><br><br>      - name: Check disk space<br>        run: |<br>          sudo dpkg-query -Wf &#39;${Installed-Size}\t${Package}\n&#39; | sort -nr | head<br>          df . -h<br>          sudo du /usr/ -hx -d 4 --threshold=1G | sort -hr | head<br><br><br>      - name: Checkout repository<br>        uses: actions/checkout@v4<br><br><br>      - name: Log in to Docker Hub<br>        uses: docker/login-action@v3<br>        with:<br>          username: ${{ secrets.DOCKERHUB_USERNAME }}<br>          password: ${{ secrets.DOCKERHUB_TOKEN }}<br><br><br>      - name: Set up Docker Buildx<br>        uses: docker/setup-buildx-action@v3<br><br><br>      - name: Build and push Docker image (Lite)<br>        uses: docker/build-push-action@v5<br>        with:<br>          context: ./kontext_pose_control<br>          push: true<br>          tags: ${{ secrets.DOCKERHUB_USERNAME }}/kontext_pose_control_workflow:latest<br>          # build-args: |<br>          #   HUGGINGFACE_ACCESS_TOKEN=${{ secrets.HUGGINGFACE_ACCESS_TOKEN }}  </pre><ul><li>After putting it in .github/workflows</li><li>Push to GitHub, it will create an image and store it in your Docker Hub account.</li></ul><blockquote>you can see GitHub actions workflow on GitHub like this</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*_LUWekKTMHLk0bcRTfwKpw.png" /></figure><h3>Post Docker Image creation</h3><h4>Creating a template:</h4><ul><li>After you have created a Docker image and it has been pushed to Docker Hub, go to your runpod console and create a template to use the image afterwards in the pod and serverless</li><li>New template-&gt; edit template</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*FFwBFIofFDRxvM4vq6ZV3w.png" /></figure><ul><li>Expose 2 HTTP ports for the UI of ComfyUI and the Jupyter Lab, as it uses the base Docker image of the runpod worker</li><li>Make sure you set the volume mount path to /runpod-volume</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*ZuKe-ud5zxiaToYDRTDCeA.png" /></figure><h3>Creating a template for pod:</h3><ul><li>When creating a template for the pod, everything remains the same an extra thing is in the environment variables, we add the SERVE_API_LOCALLY=true</li><li>Set environment variable: SERVE_API_LOCALLY=true</li><li>Expose ports 8188 and 8000 for ComfyUI</li><li>Use your latest Docker image build</li><li>Configure volume mount to runpod-volume (matches extra_models_path.yaml)</li></ul><h3>Set up a debugging pod:</h3><ul><li>To check that you have correctly made your Docker image with all dependencies, you first instantiate a pod using your template that you created</li><li>First, test your workflow in a pod environment</li><li>Then test the same workflow in serverless</li><li>If it works in pod but not serverless, the issue is with the serverless setup</li></ul><p><strong>Creating a pod to test your Docker image via template:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*SC9FFePlNGgp_XwlKtf4sg.png" /></figure><ul><li>Changing the template and selecting our own template</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*xzf0CyQPBWBm_r4Kl_Tk9w.png" /></figure><ul><li>Template overrides according to your needs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*2Ibx7V1pAUI6EW3msQ4Mkg.png" /></figure><ul><li>Deploy the pod and see the logs. Make sure to select the same volume in which models are downloaded in the ComfyUI/models/</li></ul><h3>Deploying on serverless:</h3><ul><li>When deploying on serverless, choose the template that you have created earlier</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*TdCqI6dNhYd8PODlTrg-DQ.png" /></figure><ul><li>After this, name your endpoint and choose a gpu for this. Remember, only those GPUs will be available where your network volume is deployed</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Uo_6S_PdlpWfW8YU51osYQ.png" /></figure><ul><li>After creating your endpoint, go to manage endpoint advanced and select your desired network volume, as this option might not show earlier</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*ZdWRpcYR2Oy-Nn-ei515NQ.png" /></figure><ul><li>After deploying, you will see an interface like this. Paste your body for the post request that will contain workflow and hit run. Your requests will appear in the tab below</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*o2Cnit5s9yNlhimdkGhZJQ.png" /></figure><ul><li>For monitoring and debugging, go to the workers tab and check the logs of worker in which your request is running.</li><li>Your succesful output will be like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*HECLQUDRVjXvZUpefbyagg.png" /></figure><p><strong>Test_input.json/Request body for endpoint:</strong></p><pre>{<br>    &quot;input&quot;: {<br>        &quot;uid&quot;: &quot;test_input&quot;,<br>        &quot;customModles&quot;: [],<br>        &quot;customNodes&quot;: [],<br>        &quot;images&quot;: [],<br>        &quot;workflow&quot;: {<br>            &quot;1&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;vae_name&quot;: &quot;ae.safetensors&quot;<br>                },<br>                &quot;class_type&quot;: &quot;VAELoader&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;Load VAE&quot;<br>                }<br>            },<br>            &quot;2&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;conditioning&quot;: [<br>                        &quot;18&quot;,<br>                        0<br>                    ]<br>                },<br>                &quot;class_type&quot;: &quot;ConditioningZeroOut&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;ConditioningZeroOut&quot;<br>                }<br>            },<br>            &quot;3&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;guidance&quot;: 2.5,<br>                    &quot;conditioning&quot;: [<br>                        &quot;6&quot;,<br>                        0<br>                    ]<br>                },<br>                &quot;class_type&quot;: &quot;FluxGuidance&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;FluxGuidance&quot;<br>                }<br>            },<br>            &quot;6&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;conditioning&quot;: [<br>                        &quot;18&quot;,<br>                        0<br>                    ],<br>                    &quot;latent&quot;: [<br>                        &quot;15&quot;,<br>                        0<br>                    ]<br>                },<br>                &quot;class_type&quot;: &quot;ReferenceLatent&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;ReferenceLatent&quot;<br>                }<br>            },<br>            &quot;9&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;seed&quot;: 236,<br>                    &quot;steps&quot;: 20,<br>                    &quot;cfg&quot;: 1,<br>                    &quot;sampler_name&quot;: &quot;euler&quot;,<br>                    &quot;scheduler&quot;: &quot;simple&quot;,<br>                    &quot;denoise&quot;: 1,<br>                    &quot;model&quot;: [<br>                        &quot;25&quot;,<br>                        0<br>                    ],<br>                    &quot;positive&quot;: [<br>                        &quot;3&quot;,<br>                        0<br>                    ],<br>                    &quot;negative&quot;: [<br>                        &quot;2&quot;,<br>                        0<br>                    ],<br>                    &quot;latent_image&quot;: [<br>                        &quot;15&quot;,<br>                        0<br>                    ]<br>                },<br>                &quot;class_type&quot;: &quot;KSampler&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;KSampler&quot;<br>                }<br>            },<br>            &quot;12&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;unet_name&quot;: &quot;flux1-dev-kontext_fp8_scaled.safetensors&quot;,<br>                    &quot;weight_dtype&quot;: &quot;default&quot;<br>                },<br>                &quot;class_type&quot;: &quot;UNETLoader&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;Load Diffusion Model&quot;<br>                }<br>            },<br>            &quot;13&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;clip_name1&quot;: &quot;clip_l.safetensors&quot;,<br>                    &quot;clip_name2&quot;: &quot;t5xxl_fp8_e4m3fn_scaled.safetensors&quot;,<br>                    &quot;type&quot;: &quot;flux&quot;,<br>                    &quot;device&quot;: &quot;default&quot;<br>                },<br>                &quot;class_type&quot;: &quot;DualCLIPLoader&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;DualCLIPLoader&quot;<br>                }<br>            },<br>            &quot;14&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;direction&quot;: &quot;right&quot;,<br>                    &quot;match_image_size&quot;: true,<br>                    &quot;image1&quot;: [<br>                        &quot;44&quot;,<br>                        0<br>                    ],<br>                    &quot;image2&quot;: [<br>                        &quot;30&quot;,<br>                        0<br>                    ]<br>                },<br>                &quot;class_type&quot;: &quot;ImageConcanate&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;Image Concatenate&quot;<br>                }<br>            },<br>            &quot;15&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;pixels&quot;: [<br>                        &quot;20&quot;,<br>                        0<br>                    ],<br>                    &quot;vae&quot;: [<br>                        &quot;1&quot;,<br>                        0<br>                    ]<br>                },<br>                &quot;class_type&quot;: &quot;VAEEncode&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;VAE Encode&quot;<br>                }<br>            },<br>            &quot;16&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;images&quot;: [<br>                        &quot;20&quot;,<br>                        0<br>                    ]<br>                },<br>                &quot;class_type&quot;: &quot;PreviewImage&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;Preview Image&quot;<br>                }<br>            },<br>            &quot;17&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;filename_prefix&quot;: &quot;ComfyUI&quot;,<br>                    &quot;images&quot;: [<br>                        &quot;19&quot;,<br>                        0<br>                    ]<br>                },<br>                &quot;class_type&quot;: &quot;SaveImage&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;Save Image&quot;<br>                }<br>            },<br>            &quot;18&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;text&quot;: &quot;refcontrolpose recreate all poses in photo with reference from left side, preserve face, white background, professional photography&quot;,<br>                    &quot;clip&quot;: [<br>                        &quot;25&quot;,<br>                        1<br>                    ]<br>                },<br>                &quot;class_type&quot;: &quot;CLIPTextEncode&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;CLIP Text Encode (Positive Prompt)&quot;<br>                }<br>            },<br>            &quot;19&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;samples&quot;: [<br>                        &quot;9&quot;,<br>                        0<br>                    ],<br>                    &quot;vae&quot;: [<br>                        &quot;1&quot;,<br>                        0<br>                    ]<br>                },<br>                &quot;class_type&quot;: &quot;VAEDecode&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;VAE Decode&quot;<br>                }<br>            },<br>            &quot;20&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;image&quot;: [<br>                        &quot;14&quot;,<br>                        0<br>                    ]<br>                },<br>                &quot;class_type&quot;: &quot;FluxKontextImageScale&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;FluxKontextImageScale&quot;<br>                }<br>            },<br>            &quot;21&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;filename_prefix&quot;: &quot;ComfyUI&quot;,<br>                    &quot;images&quot;: [<br>                        &quot;23&quot;,<br>                        0<br>                    ]<br>                },<br>                &quot;class_type&quot;: &quot;SaveImage&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;Save Image&quot;<br>                }<br>            },<br>            &quot;22&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;filename_prefix&quot;: &quot;ComfyUI&quot;,<br>                    &quot;images&quot;: [<br>                        &quot;20&quot;,<br>                        0<br>                    ]<br>                },<br>                &quot;class_type&quot;: &quot;SaveImage&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;Save Image&quot;<br>                }<br>            },<br>            &quot;23&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;direction&quot;: &quot;down&quot;,<br>                    &quot;match_image_size&quot;: true,<br>                    &quot;image1&quot;: [<br>                        &quot;20&quot;,<br>                        0<br>                    ],<br>                    &quot;image2&quot;: [<br>                        &quot;19&quot;,<br>                        0<br>                    ]<br>                },<br>                &quot;class_type&quot;: &quot;ImageConcanate&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;Image Concatenate&quot;<br>                }<br>            },<br>            &quot;24&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;filename_prefix&quot;: &quot;ComfyUI&quot;,<br>                    &quot;images&quot;: [<br>                        &quot;19&quot;,<br>                        0<br>                    ]<br>                },<br>                &quot;class_type&quot;: &quot;SaveImage&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;Save Image&quot;<br>                }<br>            },<br>            &quot;25&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;lora_name&quot;: &quot;RefControl_Flux_Kontext.safetensors&quot;,<br>                    &quot;strength_model&quot;: 1,<br>                    &quot;strength_clip&quot;: 1,<br>                    &quot;model&quot;: [<br>                        &quot;12&quot;,<br>                        0<br>                    ],<br>                    &quot;clip&quot;: [<br>                        &quot;13&quot;,<br>                        0<br>                    ]<br>                },<br>                &quot;class_type&quot;: &quot;LoraLoader&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;Load LoRA&quot;<br>                }<br>            },<br>            &quot;30&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;detect_hand&quot;: &quot;enable&quot;,<br>                    &quot;detect_body&quot;: &quot;enable&quot;,<br>                    &quot;detect_face&quot;: &quot;enable&quot;,<br>                    &quot;resolution&quot;: 1024,<br>                    &quot;scale_stick_for_xinsr_cn&quot;: &quot;disable&quot;,<br>                    &quot;image&quot;: [<br>                        &quot;43&quot;,<br>                        0<br>                    ]<br>                },<br>                &quot;class_type&quot;: &quot;OpenposePreprocessor&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;OpenPose Pose&quot;<br>                }<br>            },<br>            &quot;34&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;detect_hand&quot;: &quot;enable&quot;,<br>                    &quot;detect_body&quot;: &quot;enable&quot;,<br>                    &quot;detect_face&quot;: &quot;enable&quot;,<br>                    &quot;resolution&quot;: 512,<br>                    &quot;scale_stick_for_xinsr_cn&quot;: &quot;disable&quot;,<br>                    &quot;image&quot;: [<br>                        &quot;35&quot;,<br>                        0<br>                    ]<br>                },<br>                &quot;class_type&quot;: &quot;OpenposePreprocessor&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;OpenPose Pose&quot;<br>                }<br>            },<br>            &quot;35&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;image&quot;: &quot;character_sheet_flux_00004_.png&quot;<br>                },<br>                &quot;class_type&quot;: &quot;LoadImage&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;Load Image&quot;<br>                }<br>            },<br>            &quot;36&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;images&quot;: [<br>                        &quot;34&quot;,<br>                        0<br>                    ]<br>                },<br>                &quot;class_type&quot;: &quot;PreviewImage&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;Preview Image&quot;<br>                }<br>            },<br>            &quot;43&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;url_or_path&quot;: &quot;https://i.postimg.cc/9fLvQZys/Comfy-UI-temp-irbjm-00007.png&quot;<br>                },<br>                &quot;class_type&quot;: &quot;LoadImageFromUrlOrPath&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;LoadImageFromUrlOrPath&quot;<br>                }<br>            },<br>            &quot;44&quot;: {<br>                &quot;inputs&quot;: {<br>                    &quot;url_or_path&quot;: &quot;https://i.postimg.cc/GhvVsZkF/pexels-allan-2155569510-33799456.jpg&quot;<br>                },<br>                &quot;class_type&quot;: &quot;LoadImageFromUrlOrPath&quot;,<br>                &quot;_meta&quot;: {<br>                    &quot;title&quot;: &quot;LoadImageFromUrlOrPath&quot;<br>                }<br>            }<br>        }<br>    }<br>}</pre><blockquote>Thats all folks, happy learning and building<br>If you have any questions reachout to me on <a href="/service/mailto:ahmadareeb3026@gmail.com">gmail</a></blockquote><p><strong>References:</strong></p><ul><li><a href="https://github.com/runpod-workers/worker-comfyui">https://github.com/runpod-workers/worker-comfyui</a></li><li><a href="https://github.com/runpod-workers/worker-comfyui/blob/main/docs/deployment.md">https://github.com/runpod-workers/worker-comfyui/blob/main/docs/deployment.md</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f0f0a79a8e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Training WAN2.2 for your character/custom-style ultra-realistic images]]></title>
            <link>https://medium.com/@ahmadareeb3026/training-wan2-2-for-your-character-custom-style-ultra-realistic-images-f8993350c862?source=rss-885a42f360fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8993350c862</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[stable-diffusion]]></category>
            <category><![CDATA[image-generation]]></category>
            <category><![CDATA[art]]></category>
            <category><![CDATA[instagram]]></category>
            <dc:creator><![CDATA[Areeb Ahmad]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 22:04:28 GMT</pubDate>
            <atom:updated>2025-08-26T22:04:28.043Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been diving into diffusion models for a while now, and honestly — I’m loving it. Along the way, I’ve explored different techniques for creating ultra-realistic images. If you’ve ever wondered how those Instagram-style influencers or consistent character portraits keep popping up, you’re in the right spot. My focus has been on capturing that polished, aesthetic ‘Instagram look. In this article, we will explore how we can train LORAs for the consistent characters and</p><p>These shots were produced by feeding a single frame into Wan’s text-to-video model, enhanced with a LoRA fine-tuned on an Instagram-inspired dataset — think ultra-trendy aesthetics, filtered vibes, and that coveted ‘Gram-style’ glow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T2lGdZhHcwRC3Qsj7nzWSw.png" /><figcaption>getting that realistic and retro style</figcaption></figure><p>Mainly, for achieving these types of images, you have to choose, experiment, and select different components in your pipeline that include the model that you use for generating images, upscalers, different LORAs combinations, an encoder, and a decoder. The list can be exhaustive depending on how you desire to make your pipeline complex. For achieving this pipeline, the most famous tool in the industry right now being used is ComfyUI (which I have been playing around with). So, instead of integrating different components using code, you can drag and drop components in the ComfyUI interface.</p><p><a href="https://learn2train.medium.com/fine-tuning-wan-2-1-with-a-curated-dataset-step-by-step-guide-a6f0b334ab79">This article</a> that came across describes how they created <a href="https://en.wikipedia.org/wiki/Monica_Vitti">Monica Vitti</a> in her 30s, but she passed away in 2022 at the age of 91 years old. They have described Wan as a model for a time machine, as it can capture people through training and generate their real-life pics. At the end of the day, WAN is a diffusion model that has the ability to learn from data.</p><h4><strong>Wait… Wan 2.2? Who invited that to the party?</strong></h4><p><em>Unveiled by</em><strong><em> Alibaba’s Tongyi Lab </em></strong><em>on </em><strong><em>July 28, 2025</em></strong><em>, Wan 2.2 is the first open-source video generation model built on a groundbreaking </em><strong><em>Mixture-of-Experts (MoE)</em></strong><em> architecture, </em><a href="https://www.deeplearning.ai/the-batch/alibabas-wan-2-2-video-models-adopt-a-new-architecture-to-sort-noisy-from-less-noisy-inputs"><em>GitHubDeepLearning.ai</em></a><em> — meaning it delivers cinematic visuals with lighting, composition, and motion control that speak director-level fluency. With support for text-to-video, image-to-video, and hybrid inputs, Wan 2.2 runs silky smooth, even on consumer GPUs, thanks to its mix of high-capacity design and smart efficiency<br>Alibaba released its model weights, inference code, and even Diffusers and ComfyUI integrations </em><a href="https://github.com/Wan-Video/Wan2.2"><strong><em>GitHub</em></strong></a>, <a href="https://huggingface.co/Wan-AI/Wan2.2-T2V-A14B"><strong><em>Hugging Face</em></strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qa6x9PwW3NvxvSLaeOUS3w.png" /><figcaption>MOE Architecture</figcaption></figure><p><strong>– So… what’s new under the hood?</strong></p><ul><li>Smarter motion too: trained on <strong>65.6 % more images</strong> and <strong>83.2 % more videos</strong> than 2.1, giving you smoother, more dynamic scenes. <a href="https://huggingface.co/Wan-AI/Wan2.2-T2V-A14B">Hugging Face</a>.</li><li>And yes — it supports <strong>text-to-video</strong>, <strong>image-to-video</strong>, and <strong>hybrid text+image inputs</strong>. The TI2V-5B model runs at <strong>720p, 24fps</strong>, even on GPUs like the 4090. <a href="https://huggingface.co/Wan-AI/Wan2.2-I2V-A14B">Image2Video</a></li></ul><p><strong>– Still free?</strong><br> Absolutely — it’s open source under <strong>Apache 2.0</strong>, fully free to use, tinker with, or build upon <a href="https://github.com/Wan-Video/Wan2.2">GitHub</a>.</p><p><strong>Alright, let’s cut to the chase . . . !</strong></p><h3>Training</h3><p><strong>In this Guide</strong></p><p>We’re going to walk through how to fine-tune <strong>Wan 2.2</strong> — the heavyweight <strong>14B parameter</strong> version (as opposed to the smaller 5B model). Once you’ve got your fine-tuned checkpoints, you’ll be able to generate <strong>custom-style images</strong> in <strong>ComfyUI</strong> that reflect your own unique aesthetic, objects, or places. Don’t have a dataset prepared? No worries — I’ve included resources below to help you get started.</p><p>By the end of this tutorial, you’ll know how to:</p><ul><li>Set up a Wan 2.2 trainer (Diffusion-pipe)</li><li>Launch a training session on Wan 2.2 (14B)</li><li>Generate styled image samples with ComfyUI</li><li>Evaluate your LoRA checkpoints</li><li>Export generated samples back to your ComfyUI by <a href="https://github.com/comfyanonymous">comfyanonymous</a>.</li><li>Monitor your training runs with TensorBoard</li></ul><h4><strong>Wan 2.2 Training for the Ultra Realism Text to Image</strong></h4><p>For Training we will use PEFT (Parameter Efficient Finetuning) and train LORAs as full finetuning will cost us huge, and the tool we will use is <a href="https://github.com/tdrussell/diffusion-pipe/"><strong><em>diffusion-pipeline</em></strong></a><strong><em>.</em></strong></p><p>Keep in mind — you’re not limited to just one approach. This walkthrough can also serve as a starting point for fine-tuning on <strong>specific objects, locations, visual styles, or even camera motions</strong>. The results will depend heavily on the images you collect and the way you caption them. The key is to bring in your own dataset.</p><h4><strong>Dataset technique Triggered Word</strong></h4><p>To train diffusion models like Wan for a use case like Text to Image, we will use an image and captioning dataset.<br> Ok, the most important thing to consider is the concept of a trigger word while training your LORAs. We have to introduce a trigger word in our captions for the images, and the trigger word is usually a non-English word that triggers the model to use the generation process to generate the same style that is followed by the trained LORAs.</p><p>It could be anything like “<strong><em>s33s</em></strong>” that you put in start of your caption while training, as well as start ofthe prompt while inferencing. An example would be</p><blockquote>s33s, POV selfie of a 24-year-old white man with light stubble, wavy brown hair under a beanie, standing alone in a mist-covered pine forest.</blockquote><h4><strong>GPU Instance and cost</strong></h4><p>For this, we’ll be using a <strong>RunPod </strong>instance to utilise the <strong>GPU</strong>. The type of GPU you choose really depends on your use case. In my case, I used an <strong>H200</strong>, which ran for around <strong>22 hours</strong> because I wanted to capture the style of the images — mainly targeting ultra-realism with Instagram-trendy filter vibes, the kind influencers actually use.</p><p>My dataset had a little over <strong>500 images</strong>, and I trained it for<strong> 100+ epochs</strong>. The total cost came to about <strong>USD 80.</strong><br> That said, you can also train a <strong>LoRA with as few as 15 high-quality images,</strong> and by running it for 100 epochs, you can get good results in just 1 hour, which costs only about <strong>$2–3.</strong></p><p><strong>Not bad, right?</strong><br> Alright, let’s get into the steps.</p><h4><strong>Step 1: Setting up an instance with a GPU:</strong></h4><p>I used RunPod for this training; you can use any platform like <strong>AWS or GCP.</strong><br>You can use any GPU like the <strong>A100 PCIe </strong>— it will cost you around <strong>2–3 USD </strong>if you do training for 100 epochs.<br> For storage, you can keep it more than <strong>150GB.</strong> I would suggest you have a <strong>persistent network volume </strong>for this one. Once you set up your pod with 150GB of storage, we will start creating the Conda environment and installations.<br> For the Docker template, you can use Torch version 2.8 or above. It doesn’t matter because in the Conda environment, we will be making a separate Conda environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7FNFn4BbVH4ZBwzdEOm8Bg.png" /><figcaption>selecting the docker template initially</figcaption></figure><p><strong>Step 2: Creating a conda environment and cloning the diffusion pipeline repository:</strong></p><pre>mkdir -p ~/miniconda3<br>wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda3/miniconda.sh<br><br>bash ~/miniconda3/miniconda.sh -b -u -p ~/miniconda3<br><br>rm ~/miniconda3/miniconda.sh<br>source ~/miniconda3/bin/activate<br><br>conda init --all<br>conda create -n diffusion-pipe python=3.12<br>conda activate diffusion-pipe<br><br>which python       <br>python --version<br><br># installing torch compatible version for the latest flashh-attn support<br>pip install torch==2.7.1 torchvision==0.22.1 torchaudio==2.7.1 --index-url https://download.pytorch.org/whl/cu128<br>conda install nvidia/label/cuda-12.1.1::cuda-nvcc</pre><p>Now<strong> let’s clone the diffusion-pipe repository</strong>.</p><pre># clone the repo diffusion pipe for the training<br>git clone --recurse-submodules https://github.com/tdrussell/diffusion-pipe<br><br>cd diffusion-pipe<br><br>pip install -r requirements.txt<br><br># check if flash-attn 2.8.1 is not installed yet if any other version is installed then install the version below<br>pip install flash-attn==2.8.1 --no-build-isolation</pre><h4><strong>Downloading Models</strong></h4><p>For this tutorial, we will be downloading and fine-tuning the 14B Wan 2.2 Text to Video model. An important thing to note is that Wan 2.2 comes with a high-noise model and a low-noise model. So, both models are fine-tuned in parallel, as we will be using both models’ LORAs in our ComfyUI workflow.</p><p><strong>Wan 2.2 High-Noise Model</strong><br>This expert excels in the early denoising stages — focusing on scene layout, motion, and structural consistency. Built from scratch as part of the MoE design, it handles high-SNR timesteps exclusively and shares parameters efficiently (14B active, part of a 27B parameter total).</p><p><strong>Wan 2.2 Low-Noise Model<br></strong>Optimised for the later denoising phases, this model fine-tunes textures, aesthetic details, and temporal coherence with precision. It’s essentially a refined continuation that further polishes output in cleaner, low-noise conditions. <a href="https://huggingface.co/Wan-AI/Wan2.2-T2V-A14B">Hugging</a>, <a href="https://www.runpod.io/blog/wan-2-2-releases-with-a-plethora-of-new-features">FaceRunpod</a>.<br>The good thing is LORAs trained on Wan 2.1 will work perfectly well on Wan2.2 low noise model, as the architecture remains the same.</p><p>Ok, now let&#39;s download our models.</p><pre># make a directory models<br>mkdir /workspace/models/wan2.2<br>cd /workspace/models/wan2.2<br># download the wan2.2 T2V14B-fp16 high noise model<br>wget https://huggingface.co/Comfy-Org/Wan_2.2_ComfyUI_Repackaged/resolve/main/split_files/diffusion_models/wan2.2_t2v_high_noise_14B_fp16.safetensors<br><br># download the wan2.2 T2V14B-fp16 low noise model<br># for low noise you can use another instance maybe or another terminal for the training if you wish to train one<br># wget https://huggingface.co/Comfy-Org/Wan_2.2_ComfyUI_Repackaged/resolve/main/split_files/diffusion_models/wan2.2_t2v_low_noise_14B_fp16.safetensors<br><br># download the encoder and decoder model<br># again we are using here fp16 encoder <br>wget https://huggingface.co/Comfy-Org/Wan_2.2_ComfyUI_Repackaged/resolve/main/split_files/text_encoders/umt5_xxl_fp16.safetensors<br><br># download the wan2.2 decoder model for fp16<br>wget https://huggingface.co/Comfy-Org/Wan_2.2_ComfyUI_Repackaged/resolve/main/split_files/vae/wan2.2_vae.safetensors</pre><p>Now we will download the Hugging Face repository. Make sure you don&#39;t download any models here along with the repository, as you have already downloaded your models, you can exclude them in the exclude argument below. The directory below includes the config files and JSONs.</p><pre>huggingface-cli download Wan-AI/Wan2.2-T2V-A14B --local-dir /workspace/models/wan2.2/Wan2.2-T2V-14B --exclude &quot;diffusion_pytorch_model*&quot; &quot;models_t5*&quot;</pre><p>Just make sure to add the decoder VAE model in your downloaded HF repo, if you did not download it along with the repo, as when you will give the path of the repo in your configuration toml file, the diffusion-pipe will look for the decoder model inside it.</p><p><strong>Dataset Guide</strong></p><p>Before we dive into the configuration for our model, another important thing is to make sure the folder where your dataset is present, the image and the relevant caption/prompt text file for that particular image have the same filename. is is an example of how images and caption files are formatted in our dataset:</p><ul><li>image1.jpg</li><li>image1.txt &lt;= Same filename as the image file</li></ul><p>The text file image1.txt contains the caption describing image-name1.jpg, say, for example: m44m,a photo of a man wearing a red jacket on a skateboard with on a cracked road, golden light. <br>Also, the <em>“m44m” </em>is the trigger word that we discussed earlier</p><p>Note that the trainer can accept the usual image file formats, such as <strong>JPG, JPEG, PNG, and WEBP</strong>. It is supposed to take video as well (but I haven’t tested it yet).</p><p>I haven’t added a dataset to this guide, but you can prepare your dataset exactly by following the concepts provided above.</p><h4><strong>Training Arguments:</strong></h4><p><strong>Batch Size:</strong><br>Now that you have finished setting up the dataset and downloading the models, let’s configure the arguments. Batch size really depends on the type of GPU you are using. It’s an experimental process — choose a batch size that keeps your GPU utilisation around 85%, as I don’t recommend going above this.<br> For all the other arguments, there is a very good one-line description provided for each argument in the diffusion-pipe repository at:<br><a href="https://github.com/tdrussell/diffusion-pipe/blob/main/examples/main_example.toml"><em>diffusion-pipe/examples/main_example.toml</em></a></p><p><strong>Model Configuration:<br></strong> Now, for the model configuration, we will point the arguments to use the models that we downloaded:</p><pre>[model]<br>ckpt_path = &#39;/workspace/models/wan2.2/Wan2.2-T2V-14B&#39;<br>type = &#39;wan&#39;<br>transformer_path = &#39;/workspace/models/wan2.2/wan2.2_t2v_high_noise_14B_fp16.safetensors&#39;<br>vae_path = &#39;/workspace/models/wan2.2/wan2.2_vae.safetensors&#39;<br>llm_path = &#39;/workspace/models/wan2.2/umt5_xxl_fp16.safetensors&#39;</pre><p>Perfect, so now our basic configuration file is ready and its time to shoot for training. If your configuration file is wan2_1.toml then this command will start the training.</p><pre>NCCL_P2P_DISABLE=&quot;1&quot; NCCL_IB_DISABLE=&quot;1&quot; deepspeed --num_gpus=1 train.py --deepspeed --config examples/wan2_1.toml</pre><h3>Tensorboard for Viewing Training Loss</h3><p>Now, for selecting the best epoch checkpoint that you have saved during training, use the parameter save_every_n_epochs = x in your configuration file. You can run the events file to check the training loss. Your events file might look like this: events.out.tfevents.1755602196.e4ab77ab012d.2093.0.<br> You can find this event file in the output directory that you have specified in your configuration.toml file. You can run this using TensorBoard by using the following command, and it will provide you with the dashboard at <a href="http://localhost:6006/">http://localhost:6006/</a>.</p><pre># logdir is directory where this file is available<br>tensorboard --logdir=logs/ </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*VuDstRdOg-hjN6mRbhqElQ.png" /><figcaption>tensorboard UI</figcaption></figure><p>That’s all, folks. Happy learning and happy experimentation.<br>Reach out to me on <a href="https://pk.linkedin.com/in/areeb-ahmad-13a83a219">LinkedIn</a>, if you have any questions.</p><h4>References:</h4><p><a href="https://github.com/tdrussell/diffusion-pipe/">https://github.com/tdrussell/diffusion-pipe/</a><br><a href="https://huggingface.co/Wan-AI/Wan2.2-I2V-A14B">https://huggingface.co/Wan-AI/Wan2.2-I2V-A14B</a><br><a href="https://huggingface.co/Wan-AI/Wan2.2-T2V-A14B">https://huggingface.co/Wan-AI/Wan2.2-T2V-A14B</a><br><a href="https://github.com/Wan-Video/Wan2.2">https://github.com/Wan-Video/Wan2.2</a><br><a href="https://www.deeplearning.ai/the-batch/alibabas-wan-2-2-video-models-adopt-a-new-architecture-to-sort-noisy-from-less-noisy-inputs">https://www.deeplearning.ai/the-batch/alibabas-wan-2-2-video-models-adopt-a-new-architecture-to-sort-noisy-from-less-noisy-inputs</a><br><a href="https://learn2train.medium.com/fine-tuning-wan-2-1-with-a-curated-dataset-step-by-step-guide-a6f0b334ab79">https://learn2train.medium.com/fine-tuning-wan-2-1-with-a-curated-dataset-step-by-step-guide-a6f0b334ab79</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8993350c862" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM as Operating Systems: Agent Memory]]></title>
            <link>https://medium.com/@ahmadareeb3026/llm-as-operating-systems-agent-memory-b70c1213a5f7?source=rss-885a42f360fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/b70c1213a5f7</guid>
            <category><![CDATA[memgpt]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Areeb Ahmad]]></dc:creator>
            <pubDate>Wed, 16 Jul 2025 13:39:25 GMT</pubDate>
            <atom:updated>2025-07-16T13:49:10.509Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’ll explore the core ideas from the <a href="https://arxiv.org/abs/2310.08560"><strong>MemGPT</strong></a> paper and walk through how these concepts are applied in practice. MemGPT introduces a fascinating way to think of Large Language Models (LLMs) not just as tools, but as operating systems — managing memory, reasoning over time, and adapting to changing inputs.<br>Just like a traditional operating system handles data across main memory and disk storage, MemGPT equips LLMs with the ability to manage <strong>short-term context</strong>, <strong>long-term memory</strong>, and <strong>persistent state</strong>, enabling more intelligent, stateful agents.</p><blockquote><strong>Disclaimer: </strong>The article inspiration and screenshots are taken from the deeplearning.ai course <a href="https://learn.deeplearning.ai/courses/llms-as-operating-systems-agent-memory">LLMs as Operating Systems</a>, taught by the Founders of <a href="https://www.letta.com/">Letta</a>, <a href="https://www.linkedin.com/in/charles-packer">Charles Packer</a> and <a href="https://www.linkedin.com/in/wooders">Sarah Wooders</a></blockquote><h3>Introduction to MemGPT</h3><p>MemGPT enhances agents by enabling the LLM to manage its own context window. In this lesson, you’ll learn the key ideas behind the MemGPT research paper: self-editing, memory, inner thoughts, heartbeats, context compilation, and virtual context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*ynoFM_j2BGD4Xfq0XisX4w.png" /><figcaption>Image from <a href="https://learn.deeplearning.ai/courses/llms-as-operating-systems-agent-memory">LLMs as Operating Systems</a></figcaption></figure><h4>Understanding MemGPT and Its Core Philosophy</h4><p>So, what is MemGPT? The MemGPT Research paper introduced a new way to think about using our LLMs to build agents. The primary way to control the behaviour of an LLM agent is by modifying its input or context window. However, it’s often not so simple to determine how to construct an optimal context window for an LLM. Particularly with complex LLM agents, context windows need to include everything an agent needs to know to complete a task, including information from various external data sources, user data, prior messages, the results of tool calls, and previous reasoning steps or chain of thought.</p><p>The MemGPT research paper showed how to build an OS for your LLM that manages the context window. In other words, an LLM OS that performs memory management. In MemGPT, this OS is itself also an LLM agent. So the memory management is done automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*C3dXEQna3ftss2KVwlpKbQ.png" /><figcaption>Image from <a href="https://learn.deeplearning.ai/courses/llms-as-operating-systems-agent-memory">LLMs as Operating Systems</a></figcaption></figure><h3>Key Ideas Behind MemGPT</h3><h4>Self-Editing Memory</h4><p>The first is the concept of self-editing memory. This refers to the ability of an LLM to edit its own memory. In many LLM applications, the system instructions or personalisation information of the LLM is fixed. In MemGPT, an agent can update its own instructions or personalisation information based on things it learns during a chat.</p><h4>Inner Thoughts (Inner Monologue)</h4><p>The second key idea is inner thoughts or inner monologue. In MemGPT, agents are always thinking to themselves, even if they don’t reply directly to a user.</p><h4>Tool Usage and Heartbeats</h4><p>In MemGPT, agents always call tools. For example, when the agent wants to communicate with the user, it has to call the send message tool. The only time an agent doesn’t call a tool is if it’s outputting inner thoughts. MemGPT agents are designed to run many LLM steps off of a single user input. For example, if the user asks the agent to do a complicated task, you would expect the agent to run for many steps as it breaks down the different aspects of the problem into subtasks.</p><p>In MemGPT, agents are able to loop through the use of <strong><em>heartbeats</em></strong>. Whenever a MemGPT agent calls a tool, it can add a special heartbeat request to any tool, which will trigger a follow-up call.</p><p>Altogether, these abilities — self-editing memory, inner thoughts, tool outputs, looping via heartbeats — enable MemGPT agents to be autonomous and self-improving. We call MemGPT agents autonomous because they can take actions by themselves while looping. We call MemGPT agents self-improving because they can edit their own long-term memories over time.</p><h4>Example: Agent Memory and Response Flow</h4><p>Let’s walk through an example MemGPT agent step. Here the agent receives a new message from the user: “My name is Sarah.”</p><p>The MemGPT agent first generates some inner thoughts:</p><p>· The human shared their name.</p><p>· That seems like important information to remember.</p><p>· I agree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*RK6kZTTpUW9nuydGtiTsAA.png" /><figcaption>Inner Thoughts and Function Call (Image by <a href="https://learn.deeplearning.ai/courses/llms-as-operating-systems-agent-memory">LLMs as Operating Systems</a>)</figcaption></figure><p>Next, you can see that the agent calls a memory function to save this new fact to its permanent memory bank. However, if that’s the only step we let the agent take, the user may become confused because the agent never said anything back to the user.</p><blockquote>So Sarah might say : “Hello. Is anyone there?”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*pNdONA7ZaWl1dlUUzIqKUw.png" /><figcaption>Example Memgpt agent step (Image from <a href="https://learn.deeplearning.ai/courses/llms-as-operating-systems-agent-memory">LLMs as Operating Systems</a>)</figcaption></figure><p>To allow for multi-step reasoning, the MemGPT agent can use the special heartbeat feature by adding a special request heartbeat argument to the function it calls. The MemGPT agent is requesting follow-up execution — basically, looping. Now it can first edit its long-term memory and then follow up with the response to the user by calling the send message function with <strong><em>“Thanks for letting me know”.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*tLiUhGyqJfPsx_53aGNHkw.png" /><figcaption>memgpt agents heearbeat usage</figcaption></figure><p>Now the user won’t be confused.</p><h3>Agent State and Persistence</h3><p>All the different data that makes up our agent is collectively called the agent state. When we run LLM agents in a loop, each step in the loop is modifying the agent state. In most agent frameworks, this agent state is simply made up of different Python variables held in program memory. In MemGPT, this state is kept inside of a database so the agent can persist over time.</p><p>For example, you could close your Python script and rerun the same agent and your MemGPT agent will remember everything from the last time you ran it.</p><h3>Context Compilation: Turning State into Prompts</h3><p>Each time you want to let the agent take a step, we have to decide how we want to turn our agent state into a prompt that will go into the LLM. At the end of the day, an LLM is just a machine that takes tokens in and spits tokens out. We call the process of going from the agent state to a prompt: context compilation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*pro0TuQ-E1_AztkI6wm_jg.png" /><figcaption>Context Compilation (Image by <a href="https://learn.deeplearning.ai/courses/llms-as-operating-systems-agent-memory">LLMs as Operating Systems</a>)</figcaption></figure><p>How we perform context compilation can dramatically affect the behaviour of the agent. For example, if we have more messages than we can fit inside the prompt or the context window, how should we decide which messages should leave out and what messages we should include?</p><p>This is what MemGPT is all about. These are the sorts of important decisions that an LLM OS can actually make automatically for you.</p><h3>Context Structure in MemGPT</h3><p>Let’s break down exactly what goes into the prompt or context window of an LLM.</p><p>In most popular LLM APIs, the LLM input is divided into two sections:</p><blockquote>The system prompt<br>The chat history</blockquote><p>The system prompt contains the instructions that can customize or change the behavior of the LLM to make it different from the base LLM. In this example that we are taking, our system prompt is quite simple: “You are a helpful assistant who answers questions.”</p><p>The chat history contains a list of messages between the user and the assistant or agent. You can view the job of the LLM here as simply generating a new reply based on the current chat history. Once the LLM generates the new reply, we can add it to the end of the chat history.</p><h4>Core Memory: Personalised Knowledge</h4><p><strong>In MemGPT, we create a special section of the context window that we call core memory</strong>.</p><blockquote>Core memory is used to store important information about the user. To personalise the agent.</blockquote><p>Think about how your conversations with your friends are different from your conversations with strangers. This is because you know information about your friends that conditions or personalises the conversation.</p><p>In MemGPT, the system prompt also includes information about how to edit the core memory. So a MemGPT agent will see both a special reserve section of the context for long-term memory, as well as understand that it has the power to edit this memory if it sees fit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*4J1aU2xlkivZwCJJ8eWNFQ.png" /><figcaption>Breaking the Context Window</figcaption></figure><p><strong>Memory Edit Example</strong></p><p>Let&#39;s take an example in which we can see that the user corrects an incorrect fact in the agent’s memory (See the Image below for reference). The user asks, “Who am I?” The agent says, “I know your name is Charles, and that you do AI research.” The user then says, “My name is actually Sarah.”</p><p>The MemGPT agent can then use its core memory replace tool to immediately correct this incorrect fact in its core memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*GuKAuGYhI2eEE_or--R8fQ.png" /><figcaption>Memory Edit Example</figcaption></figure><p>Core memory can be customised. For example, we can split it into different sections — one to store information about the user or human, and another section to store information about the agent. Depending on what you want your agent to do, you can make this memory module as simple or as complex as you want it to be.</p><p>Core memory in MemGPT is what gives agents the ability to learn over time. It’s a special reserve section of the context window that is always visible to the agent, no matter what.</p><h3>Benefits of Learning Over Time</h3><p>Why do we want our agents to have the ability to learn over time? The ability to learn over time is part of what makes humans so useful. As we make mistakes or receive additional training, we adapt our behaviour to improve.</p><p>One reason you might want agents with persistent memory is that they’re much more engaging. For example, imagine if a user asked a chatbot what kind of ice cream they like most. The chatbot replies that their favourite ice cream flavour is vanilla.</p><p>In most LLM chatbots that are being used in the MVP, there’s rare concept of persistent memory, so the chatbot will eventually forget that it said its favourite flavour is vanilla. So when the user makes a reference later, the chatbot may say something completely different. This breaks immersion.</p><p>A MemGPT agent can recognise that it stated a preference and commit it to long-term memory. So when asked again, it can give a realistic and consistent response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*fJ2IVj5D5YuYPOHev1dZUg.png" /><figcaption>Learning over time</figcaption></figure><h3>Recall Memory and Message Summarisation</h3><p>When the context window becomes full, MemGPT doesn’t discard messages like many frameworks. Instead, it performs a smart operation: it replaces evicted messages with a recursive summary and <strong>stores the full conversation in a persistent storage called recall memory.</strong></p><p>This approach ensures that no message is ever truly lost — everything is saved in a way that allows the agent to retrieve it when needed. The recursive nature of the summary means that summaries can include previous summaries, preserving key context efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*ZgJarPEbn8Lzwe4aeL4mjw.png" /><figcaption>Replacing evicted Messages with Summary</figcaption></figure><p>If the agent wants to retrieve something from this recall memory, it uses a conversation search tool. This tool lets the agent search through past messages, similar to how you might search your chat history in an app like WhatsApp or Messenger. For example, if a user previously mentioned that “Timber bit me,” and then later says something about Timber, the agent can search the recall memory, find that Timber is a dog, and reply appropriately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*CAmhdBiSi40gNf9C6S6Qog.png" /><figcaption>Recall Memory</figcaption></figure><h3>Archival Memory: Secondary Persistent Storage</h3><p>Like chat history and core memory, core memory also has storage limits. If important new facts can’t fit within <strong>core memory</strong>, MemGPT moves them to another layer called archival memory.</p><p>Archival memory is used to store general long-term data that isn’t needed all the time in the core memory. For instance, large documents like a company handbook or facts about past preferences can be stored in archival memory.</p><p>This ensures the agent doesn’t lose track of information. It just moves it to a more spacious, less frequently accessed storage. And when it needs it, it uses specialized tools to retrieve it — such as fetching a policy from a handbook stored in archival memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*PH8ReVrxosx7YsiDy-ec6w.png" /><figcaption>Archival Memory</figcaption></figure><h3>External Memory Statistics and Intelligent Retrieval</h3><p>One challenge with external memories, like recall or archival, is knowing when and what to fetch. MemGPT handles this with memory statistics — a special section in the context window that informs the agent about what’s available in external memory.</p><p>If the user asks a question and the answer isn’t clearly in the core memory or chat history, the agent checks memory stats. If recall and archival contain many entries, the agent can search them. If they’re empty, the agent knows there’s nothing relevant to look for.</p><p>This step ensures efficiency and reduces hallucination since the agent doesn’t blindly search for information unless necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*tgKckl_5En-FznAJH_TGrQ.png" /><figcaption>Archival and Recall Memory Stats</figcaption></figure><h3>Final Summary: MemGPT’s Memory Tiers and Agent Design</h3><p>MemGPT’s memory system is split into two broad categories: in-context memory (core memory and chat history) and external memory (recall memory and archival memory).</p><p>Core memory stores personal, always-relevant data. Chat history keeps the short-term interaction context. Recall memory ensures no message is lost by saving old conversations. Archival memory stores general-purpose long-term data like PDFs, documents, or background facts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*V78iAqHrcg0MteW2tmqUKw.png" /><figcaption>Two tiers of memory</figcaption></figure><p>Together, these systems allow agents to be persistent, consistent, and context-aware over long interactions — all while maintaining a manageable token footprint during inference.</p><p>By structuring agent state in a database, transforming it into context via context compilation, and leveraging these layered memories, MemGPT builds agents that feel more intelligent, human-like, and useful over time.</p><p>As a developer learning this, I now see how crucial memory architecture is to designing truly powerful LLM agents.</p><h3>References:</h3><ul><li>Memgpt Paper: <a href="https://arxiv.org/abs/2310.08560">https://arxiv.org/abs/2310.08560</a></li><li>Course from Deeplearning.ai, <a href="https://learn.deeplearning.ai/courses/llms-as-operating-systems-agent-memory">LLMs as Operating Systems</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b70c1213a5f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inferencing a Persisted Keras Model from S3 using Containerized AWS Lambda]]></title>
            <link>https://medium.com/@ahmadareeb3026/reading-and-prediction-using-persisted-keras-model-on-aws-lambda-using-docker-image-03d959a5521e?source=rss-885a42f360fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/03d959a5521e</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[aws-ecr]]></category>
            <category><![CDATA[s3]]></category>
            <dc:creator><![CDATA[Areeb Ahmad]]></dc:creator>
            <pubDate>Wed, 22 May 2024 13:55:36 GMT</pubDate>
            <atom:updated>2024-05-22T20:32:17.874Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’ll outline the process of leveraging all extracted features from a triggered API in AWS Lambda to read and predict labels. The data transmission is facilitated through Postman.</p><p>So the overall structure looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e2LWaDAqcRlOZsM_Of6LMQ.png" /><figcaption>The Project Structure</figcaption></figure><h3>Intro and Problem</h3><p>I was exploring the internet and couldn&#39;t find a satisfactory answer to my problem, so I decided to write this article. I delved into MLOps recently and used <strong>MWAA</strong> for training (<strong>which I will discuss in another blog</strong>) an ANN with about like 26 features and the labels included 8 categories.</p><p>The persisted model was stored in the s3 bucket, now the AWS Lambda function had to be used for reading the model and used for predicting the label for the features that are being obtained as post request from Postman to the API gateway of the Lambda function.</p><p>Now, in order to read a persisted Keras-trained model you should have the same Keras version installed in the environment on which the Keras model was trained. The problem arises here that <strong>Tensorflow </strong>itself is <strong><em>300MB</em></strong> and then there are other dependencies like Pandas and Numpy, and AWS Lambda offers the dependency limits in the following order</p><ul><li><strong>AWS Console Editor:</strong> 3MB (This is for quick edits to existing functions, not ideal for deploying functions with dependencies)</li><li><strong>Zipped for direct upload:</strong> 50MB (This is a common approach, but can be limiting for functions with large dependencies)</li><li><strong>Unzipped deployment package (using S3 bucket):</strong> 250MB (This offers more space but requires additional configuration)</li><li><strong>Container image:</strong> 10GB (This provides the most space for dependencies, but comes with its complexities)</li></ul><p>So the best solution was to build a docker image on a local machine using docker and then upload it to the <strong>ECR(Elastic container Registry)</strong> repository.</p><p>The most important thing to keep in mind here is that the TensorFlow version used to read the persisted model should be the same TensorFlow version which was used to train the model, otherwise, you will get an error like this</p><blockquote>Layer ‘conv2d_11’ expected 2 variables, but received 0 variables during loading. Expected: [‘conv2d_11/kernel:0’, ‘conv2d_11/bias:0’]</blockquote><p>There might be other solutions to this problem but I used the same version of Keras for reading, I found the solution to my problem at this link on StackOverflow<br><a href="https://stackoverflow.com/questions/77353981/layer-conv2d-11-expected-2-variables-but-received-0-variables-during-loading"><em>https://stackoverflow.com/questions/77353981/layer-conv2d-11-expected-2-variables-but-received-0-variables-during-loading</em></a></p><h3>Building Docker Image</h3><p>Now let&#39;s build the docker image, I used Tensorflow 2.16.1 to train the model so the image also had this version</p><p>I used the following AWS documentation for my reference:<br><a href="https://aws.amazon.com/blogs/machine-learning/using-container-images-to-run-tensorflow-models-in-aws-lambda/">https://aws.amazon.com/blogs/machine-learning/using-container-images-to-run-tensorflow-models-in-aws-lambda/</a></p><p>The Hierarchy of the folder for the docker image is like this</p><pre>project_folder/<br>│<br>├── app.py<br>├── Dockerfile<br>└── requirements.txt</pre><h4>Code for the Dockerfile</h4><p>Here is my docker file that is used for building the image:</p><pre># Pull the base image with python 3.8 as a runtime for your Lambda<br>FROM public.ecr.aws/lambda/python:3.11<br><br>COPY requirements.txt ./<br><br># Install the python requirements from requirements.txt<br>RUN python3.11 -m pip install -r requirements.txt<br><br># Copy the earlier created app.py file to the container<br>COPY app.py ./<br><br># Set the CMD to your handler<br>CMD [&quot;app.lambda_handler&quot;]</pre><h4>Requirements.txt file:</h4><p>The requirements.txt file specifies the specific versions of the libraries to be installed like Tensorflow version 2.16.1, we also have to verify the versions that which python version is compatible with Tensorflow version 2.16.1.</p><pre># List all python libraries for the lambda<br>numpy == 1.24.4<br>scikit-learn == 1.3.2<br>scipy == 1.10.1<br>pandas<br>tensorflow == 2.16.1<br>matplotlib == 3.7.5<br>seaborn<br>boto3<br>s3fs<br>joblib == 1.4.0</pre><h3>Main Prediction Code (app.py)and its explanation:</h3><p>The code in app.py that will be used by the AWS Lambda function for prediction, I have split it into chunks:</p><p><strong>Setup:</strong> It loads necessary libraries like Pandas, NumPy, TensorFlow, etc.<br>Accessing Data: The incoming data is converted into a Pandas DataFrame called df.</p><pre>import json<br>import numpy as np<br>import pandas as pd<br>from sklearn.preprocessing import MinMaxScaler<br>import boto3<br>import pickle<br>import tensorflow<br>from tensorflow import keras<br></pre><p><strong>Parsing Data:</strong> The function lambda_handler is triggered by an event, parsing JSON data from it.</p><p>Also the name of s3 bucket and path to trained model and pre-processed encoded labels model is specified</p><pre>def lambda_handler(event, context):<br>    # Parse incoming JSON data<br>    data = json.loads(event[&#39;body&#39;])<br>    <br>    try:<br>        # Load required libraries and data<br>        from tensorflow import keras<br>        df = pd.DataFrame([data])<br>        <br>        # Define S3 bucket and keys<br>        bucket_name = &#39;sp-classifier-mwaa&#39;<br>        key_trained = &#39;trained model/trained_model.pkl&#39;<br>        key_preprocessed = &#39;preprocessing output/preprocessing_ouput.pkl&#39;<br></pre><p><strong>Accessing Model and Preprocessing Data:</strong> It retrieves a trained machine learning model and preprocessed data from an AWS S3 bucket.<br>Feature Selection: It selects specific features (‘A’ to ‘Z’) from the data frame for prediction.</p><pre># Initialize S3 client<br>        s3 = boto3.client(&#39;s3&#39;)<br>        <br>        # Retrieve trained model from S3<br>        response = s3.get_object(Bucket=bucket_name, Key=key_trained)<br>        model_bytes = response[&#39;Body&#39;].read()<br>        model = pickle.loads(model_bytes)<br>        <br>        # Retrieve preprocessed data from S3<br>        pre_processed_response = s3.get_object(Bucket=bucket_name, Key=key_preprocessed)<br>        pre_processed_bytes = pre_processed_response[&#39;Body&#39;].read()<br>        pre_processed = pickle.loads(pre_processed_bytes)<br>        <br>        # the preprocessed includes the encoded label that was also used <br>        # when preprocessing before training the model so it inverses the label encoder in the same way<br>        # Extract required data<br>        encoded_scaler_label = pre_processed[&#39;encoded_scaler_label&#39;]<br>        categorical_labels = pre_processed[&#39;categorical_labels&#39;]<br>        <br>        # Select features for prediction<br>        X = df[[&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, <br>                &#39;E&#39;, &#39;F&#39;, &#39;G&#39;, &#39;H&#39;, <br>                &#39;I&#39;, &#39;J&#39;, &#39;K&#39;, &#39;L&#39;, &#39;M&#39;, <br>                &#39;N&#39;, &#39;O&#39;, &#39;P&#39;, <br>                &#39;Q&#39;, &#39;R&#39;, &#39;S&#39;, &#39;T&#39;, &#39;U&#39;, <br>                &#39;V&#39;, &#39;W&#39;, &#39;X&#39;, &#39;Y&#39;, &#39;Z&#39;]]<br>        <br>    </pre><p><strong>Handling Missing Values:</strong> Any missing values in the data are replaced with column means to ensure consistency.</p><p><strong>Normalization:</strong> Features are normalized using Min-Max Scaling to bring them within a specific range.</p><p><strong>Prediction:</strong> The trained model predicts labels for the normalized features.</p><pre># Convert data to numpy array and handle missing values<br>        X_np = np.array(X)<br>        column_means = np.nanmean(X_np, axis=0)<br>        nan_indices = np.isnan(X_np)<br>        X_np[nan_indices] = np.take(column_means, np.where(nan_indices)[1])<br><br>        # Normalize features<br>        scaler = MinMaxScaler()<br>        normalized_features = scaler.fit_transform(X_np)<br><br>        # Predict using the trained model<br>        predicted_normalized_features = model.predict(normalized_features)<br>        predicted_label_full_dataset = [np.argmax(i) for i in predicted_normalized_features]<br></pre><p><strong>Inverse Transformation:</strong> Encoded labels are inverse-transformed to their original form using the same encoded model that was used in the preprocessing before training the Keras model in MWAA, basically the encoded model was stored in the s3 bucket in pickle format and is now being read so that the encoded labels are inverse transformed in the same way as they were transformed.</p><pre># Inverse transform encoded labels<br>        original_labels = encoded_scaler_label.inverse_transform(predicted_label_full_dataset)<br>        <br>        # Create DataFrame for predictions<br>        predictions = pd.DataFrame({&#39;original_labels&#39;: original_labels})<br>        <br>        # Convert predictions to JSON<br>        predictions_json = predictions.to_json(orient=&#39;records&#39;)<br>        <br>        # Return predictions<br>        return {<br>            &#39;statusCode&#39;: 200,<br>            &#39;body&#39;: predictions_json<br>        }<br>        </pre><p><strong>Output Preparation:</strong> Predictions are organized into a data frame and converted into JSON format.<br><strong>Response:</strong> Finally, the predictions are returned with a success status code (200). If an error occurs, an error message with status code 500 is returned.</p><pre>  except Exception as e:<br>          # Return error message if an exception occurs<br>          return {&quot;statusCode&quot;: 500, &quot;body&quot;: str(e)}</pre><h3>Testing the image Locally</h3><p>Before pushing the docker image on ecr, it is a good practice to run it on local machine to resolve the errors. If you are not interested in testing it locally and confident that it will run on AWS Lambda directly, skip to uploading the image on ECR Section.</p><h4>Some changes in code for local testing deployment</h4><p>Now the code for local testing must be changed accordingly. Some of the changes are</p><pre>def lambda_handler(event, context):<br>    # TODO implement<br>    <br>    # here we are directly using the data being passed as a parameter<br>    data = event <br>    <br>    <br>    try:<br>        <br>        from tensorflow import keras<br>        dfp = pd.DataFrame([data])<br>        # Assuming the S3 bucket and key where the model is stored<br>        bucket_name = &#39;sp-classifier-mwaa&#39;<br>        <br>        key_trained = &#39;trained model/trained_model.pkl&#39;<br>        <br>        key_preprocessed = &#39;preprocessing output/preprocessing_ouput.pkl&#39;        <br>        <br>        pre_processed = joblib.load(&#39;preprocessing_output.pkl&#39;)<br>        <br>        encoded_scaler_label = pre_processed[&#39;encoded_scaler_label&#39;]<br>        categorical_labels = pre_processed[&#39;categorical_labels&#39;]<br><br>        <br>        print(&quot;model loading&quot;)<br><br>        with open(&#39;trained_model.pkl&#39;, &#39;rb&#39;) as f:<br>            model = pickle.load(f)<br>        <br>        print (&quot;model loaded&quot;)<br>        # prediction starts here<br>        from tensorflow.keras.models import load_model</pre><h4>Similarly Changes in the Dockerfile for local Deployment:</h4><p>Now you will be copying the trained_model.pkl or whatever file you have for your persisted model in the docker image as the s3 bucket is not involved in it.</p><pre># Pull the base image with python 3.11 as a runtime for your Lambda<br>FROM public.ecr.aws/lambda/python:3.11<br><br>COPY requirements.txt ./<br><br># Install the python requirements from requirements.txt<br>RUN python3.11 -m pip install -r requirements.txt<br><br>COPY trained_model.pkl ./<br>COPY preprocessing_output.pkl ./<br><br><br>COPY app.py ./<br><br># Set the CMD to your handler<br>CMD [&quot;app.lambda_handler&quot;]</pre><h4>Building image and testing it</h4><ol><li>First, we build the image:</li></ol><pre># Build the docker image<br>docker build -t  lambda-tensorflow-example .</pre><p>2. Then start the Docker image with the docker run command. In this example, <strong><em>lambda-tensorflow-example</em></strong> is the image name and latest is the tag.</p><pre>docker run --platform linux/amd64 -p 9000:8080 lambda-tensorflow-example:latest</pre><p>3. This command runs the image as a container and creates a local endpoint at localhost:9000/2015-03-31/functions/function/invocations</p><p>4. Now you can use Postman for sending data to the localhost URL given above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hU4fImZ_pusUjhMjO4KN0w.png" /></figure><p>5. The postman request should give you the desired result.</p><h3>Uploading the docker Image on ECR:</h3><p>For uploading the docker image on AWS ECR you need <strong>AWS CLI </strong>for an efficient CI/CD process. For installation and configuration of AWS CLI, you can refer to the following documentation.</p><p><a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">Installing or updating to the latest version of the AWS CLI</a></p><p>You can build and push the container image to Amazon ECR with the following bash commands. Replace the <strong><em>&lt;AWS_ACCOUNT_ID&gt;</em></strong><em> </em>with your own AWS account ID and also specify a <strong><em>&lt;REGION&gt;</em></strong>.</p><pre><br><br># Create a ECR repository<br>aws ecr create-repository --repository-name lambda-tensorflow-example --image-scanning-configuration scanOnPush=true --region &lt;REGION&gt;<br><br># Tag the image to match the repository name<br>docker tag lambda-tensorflow-example:latest &lt;AWS_ACCOUNT_ID&gt;.dkr.ecr.&lt;REGION&gt;.amazonaws.com/lambda-tensorflow-example:latest<br><br># Register docker to ECR<br>aws ecr get-login-password --region &lt;REGION&gt; | docker login --username AWS --password-stdin &lt;AWS_ACCOUNT_ID&gt;.dkr.ecr.&lt;REGION&gt;.amazonaws.com<br><br># Push the image to ECR<br>docker push &lt;AWS_ACCOUNT_ID&gt;.dkr.ecr.&lt;REGION&gt;.amazonaws.com/lambda-tensorflow-example:latest</pre><p>Note: The pushing of image takes time depending upon the size of image and internet speed.</p><h3>Creating Lambda Function</h3><p>So Folks, the image is uploaded and the next step is to create the lambda function for the prediction</p><p>On the console go to the Aws Lambda function and select Container image. In the container image URI browse and select the image you have uploaded on ECR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EAHOl632kKdkH8Na70FfQg.png" /><figcaption>AWS Lambda Function creation interface</figcaption></figure><p>After you have created the lambda function, Now we have to Create the Triggered API associated with the Lambda Function so that the Postman can send a request and the lambda function can infer the model.</p><h3>Creating API-triggered Gateway for Lambda Function <strong>in order to send HTTP Post requests</strong></h3><ol><li>Search api triggers in search bar of console</li><li>Then click create API</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Y9HowSuublQazuu9Ivs_XA.png" /></figure><p>3. Select “Build” HTTP API</p><p>4 . In create and configure integration</p><p>· Select add integration</p><p>· Select integration type lambda</p><p>· Select lambda function from the drop-down menu here I have selected the sample_function lambda function</p><p>· Type a name for the trigger API</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*nA1NFReJwyB86m48Axl5Yw.png" /></figure><p>· Click next</p><p>5. <strong>In configure routes</strong></p><p>· <strong>Select method type “POST”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*16LySaFDEkex8QpkOgGF2A.png" /></figure><p>· Click next</p><p>· In define stages click next</p><p>· In review and create click create</p><h4><strong>Verify the trigger API</strong></h4><p>· Once you have selected created the api and added the integration, come back to lambda function to verify the trigger API is available there</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*isw3VzJiWL3l4U-Tdlfr2w.png" /></figure><p>· Click on the API gateway and copy the API endpoint.</p><p>· Next open the Postman and then create a new POST request with API endpoint you copied above. After the request is sent the response will be like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XKL6cihLSGAxAvaZkQqV2A.png" /><figcaption>postman request response</figcaption></figure><blockquote>Disclaimer: Some explanation of the code was generated using chatGPT</blockquote><p><em>And that’s all, Folks! Feel free to ask me if you have any questions</em></p><h4>Reference Links:</h4><ul><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/images-test.html#images-test-AWSbase">Testing Lambda container images locally</a></li><li><a href="https://aws.amazon.com/blogs/machine-learning/using-container-images-to-run-tensorflow-models-in-aws-lambda/">Using container images to run TensorFlow models in AWS Lambda | Amazon Web Services</a></li></ul><p>My LinkedIn: <a href="https://www.linkedin.com/in/areeb-ahmad02">https://www.linkedin.com/in/areeb-ahmad02</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03d959a5521e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Microservices of a MERN App on GCP using GKE: A Comprehensive guide]]></title>
            <link>https://medium.com/@ahmadareeb3026/streamlining-microservices-of-a-mern-app-on-gcp-using-gke-a-comprehensive-guide-286a80f2ec38?source=rss-885a42f360fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/286a80f2ec38</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Areeb Ahmad]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 01:36:28 GMT</pubDate>
            <atom:updated>2024-02-02T11:31:49.113Z</atom:updated>
            <content:encoded><![CDATA[<p>In the article, I have explained the deployment of 5 Microservices of a MERN Application <strong>Nuvexa-Photos </strong>on GCP using Google Kubernetes Cluster (GKE), along with the explanation of deployment, ingress controller and Skaffold configurations files. In the end, I have also shown the load testing of the application</p><p><strong>Github repo:</strong><em> </em><a href="https://github.com/AreebAhmad-02/Nuvexa-Photos"><em>AreebAhmad-02/Nuvexa-Photos</em></a></p><h3>1. Introduction</h3><p>Nuvexa Photosis a web App based on Microservices Architecture for uploading and deleting pictures, Users can watch the amount of storage used by him/her as well as daily usage transactions done. This project is a full-stack application with a frontend built with React and a backend built with Node.js and Express.js. It’s organized into several microservices, each with its responsibilities, and uses MongoDB as the database. The project includes Dockerfiles and Kubernetes configuration files for deploying the microservices.</p><h3>Overview Of Project Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M5GV9zSZxFeFDQhAv7I5dw.png" /><figcaption>Cloud Architecture GCP</figcaption></figure><h3>Storage Units</h3><h4>MongoDB Atlas</h4><ul><li>All microservices have a separate database on MongoDB Atlas</li></ul><h4>Cloudinary</h4><ul><li>All photos of the users are being stored on Cloudinary</li></ul><h3>2. Structure Of Project</h3><pre>- Root<br>  |<br>  |-- frontend/<br>  |     |<br>  |     |-- Dockerfile<br>  |<br>  |-- node/<br>  |     |<br>  |     |-- FrontendService/<br>  |     |     |-- other-code-files<br>  |     |     |-- Dockerfile<br>  |<br>  |     |-- LoggingService/<br>  |     |     |-- other-code-files<br>  |     |     |-- Dockerfile<br>  |<br>  |     |-- UsageMngService/<br>  |     |     |-- other-code-files<br>  |     |     |-- Dockerfile<br>  |<br>  |     |-- StorageMngService/<br>  |     |     |-- other-code-files<br>  |     |     |-- Dockerfile<br>  |<br>  |     |-- PhotosMngService/<br>  |     |     |-- other-code-files<br>  |     |     |-- Dockerfile<br>  |<br>  |     |-- UserMngService/<br>  |           |-- other-code-files<br>  |           |-- Dockerfile<br>  |<br>  |-- infra/<br>  |     |<br>  |     |-- k8s/<br>  |           |<br>  |           |-- frontend.-dpl.yaml<br>              |-- loggingservice.-dpl.yaml<br>              |-- photosmngservice.-dpl.yaml<br>              |-- storagemngservice.-dpl.yaml<br>              |-- usagemngservice.-dpl.yaml<br>              |-- usermngservice.-dpl.yaml<br>              |-- ingress-srv.yaml<br>  |<br>  |-- skaffold.yaml<br>  |<br>  |-- Images/<br>  |<br>  |-- load testing/<br>        |<br>        |-- locustfile.py</pre><h4>Overview Of Microservices</h4><p><strong>FrontendService:</strong><br>Handles the user interface and interactions.<br><strong>LoggingService: </strong><br>Collects logs whenever users update, delete, or add images.<br><strong>UsageMngService: </strong><br>Monitors daily transactions and usage, stores data on MongoDB Cloud Atlas.<br><strong>StorageMngService:</strong><br>Ensures that no user can upload more than 10MB of storage.<br><strong>PhotosMngService: </strong><br>Stores all the photos on Cloudinary.<br><strong>UserMngService: </strong><br>Manages and storesuser data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3DvUai1XMLCKAnjl0QQ0WA.png" /><figcaption>Communication among Microservices</figcaption></figure><h3>3. Deployment Of Microservices</h3><ul><li>Microservices are communicating within a node in a Kubernetes cluster, here we are using Google Kubernetes Cluster</li><li>When you see the project structure you will find a docker file in each microservice directory inside the node directory</li><li>These docker files are used to build the images and skaffold.yaml file is used to create all the running containers from these docker files when they are pushed to the GCP repository image</li><li>Usually, when we are using docker desktop and not using any CI/CD tool we first build images and then create running containers from them and the images are stored on the docker hub, but in this project, we are using Skaffold.</li><li>Skaffold is a command line tool that increases productivity by orchestrating continuous Integration and Continuous Development. Skaffold.yaml file is discussed later in this article.</li></ul><h4>Concept of Pods and Services</h4><p>In <strong>Kubernetes</strong>, a Pod is the smallest deployable unit. Think of it as the smallest and simplest Kubernetes object. A Pod can contain one or more containers, and these containers share the same network namespace, allowing them to communicate with each other using localhost(in case they are running on your local machine). Pods are a way to organize and deploy containers together.</p><p><strong>Service</strong>, on the other hand, provides a consistent endpoint to access a set of Pods. It abstracts away the details of the individual Pods and enables load balancing and service discovery. Services ensure that no matter how many Pods are running, they can be accessed using the Service’s IP address.</p><h4>Deployment files:</h4><p>In Kubernetes, a Deployment is an object that helps manage the deployment of Pods. It allows you to describe the desired state for your application, including the number of replicas (Pods) and the container image to use.</p><ul><li>In this project, Every pod contains only 1 microservice container running in it and associated Deployment Service with it</li></ul><p>Below is an example of a Logging Service Deployment file (loggingservice-deployment.yaml). This file specifies the configuration for deploying the Logging Service:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: loggingservice-depl<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: loggingservice<br>  template:<br>    metadata:<br>      labels:<br>        app: loggingservice<br>    spec:<br>      containers:<br>        - name: loggingservice<br>          image: us.gcr.io/image-project-123/loggingservice<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: loggingservice-srv<br>spec:<br>  selector:<br>    app: loggingservice<br>  ports:<br>    - name: loggingservice<br>      protocol: TCP<br>      port: 8004<br><br>      targetPort: 8004</pre><p><strong>1. Deployment Definition:</strong></p><ul><li>A Kubernetes Deployment named loggingservice-depl is defined.</li><li>This Deployment manages the deployment of the Logging Service.</li></ul><p><strong>2. Replicas:</strong></p><ul><li>The replicas field is set to 1, indicating that there should always be one instance (Pod) of the Logging Service running every time in the cluster, if one pod dies for some reason, immediately another one of the same service is created</li></ul><p><strong>3. Selector:</strong></p><ul><li>The selector field specifies that the Pods managed by this Deployment should have labels matching app: loggingservice.</li></ul><p><strong>4. Pod Template:</strong></p><ul><li>The template field defines the structure of the Pod to be deployed.</li><li>Labels within the Pod are set to app: loggingservice.</li></ul><p><strong>5. Container Definition:</strong></p><ul><li>The Pod contains a single container named loggingservice.</li><li>The container uses the Docker image us.gcr.io/image-project-123/loggingservice.</li></ul><p><strong>6. Service Definition:</strong></p><ul><li>Following the Deployment definition, a Service named loggingservice-srv is defined.</li><li>The Service selects Pods with labels app: loggingservice.</li></ul><p><strong>7. Ports:</strong></p><ul><li>The Service is configured to expose the port 8004 for external access.</li><li>It forwards requests to the same port (8004) on the Pods.</li></ul><p><strong>8. External Access:</strong></p><ul><li>The Service ensures that external applications can access the Logging Service using a port 8004.</li></ul><p><em>Similarly all other microservices deployment files can be found and explained</em></p><h3>4. Ingress Controller:</h3><p>In a microservices architecture, an Ingress Controller is a component responsible for directing external request to specific and desired services within the system.</p><blockquote>It acts as an entry point, directing and controlling incoming HTTP and HTTPS traffic to specific microservices based on defined rules.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*HJulweom2oEVYFdY5L-ZZw.png" /><figcaption>How the Ingress Controller Works</figcaption></figure><p>The ingress.yaml file of Nuvexa-photos is given below:</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: ingress-srv<br>  annotations:<br>    kubernetes.io/ingress.class: nginx<br>    nginx.ingress.kubernetes.io/use-regex: &quot;true&quot;<br>    nginx.ingress.kubernetes.io/proxy-body-size: &quot;0&quot;<br><br>spec:<br>  rules:<br>    - host: nuvexaphotos.com<br>      http:<br>        paths:<br>          - path: /api/photo/upload<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: photosmngservice-srv<br>                port:<br>                  number: 8001<br>          - path: /api/photo/user/?(.*)<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: photosmngservice-srv<br>                port:<br>                  number: 8001<br>          - path: /api/photo/?(.*)<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: photosmngservice-srv<br>                port:<br>                  number: 8001<br>          - path: /api/user/login<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: usermngservice-srv<br>                port:<br>                  number: 8000<br>          - path: /api/user/register<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: usermngservice-srv<br>                port:<br>                  number: 8000<br>          - path: /api/storage/user/?(.*)<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: storagemngservice-srv<br>                port:<br>                  number: 8002<br>          - path: /api/usage/user/?(.*)<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: usagemngservice-srv<br>                port:<br>                  number: 8003<br>          - path: /<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: frontend-srv<br>                port:<br>                  number: 3000</pre><p>spec: Defines the rules for routing traffic:<br>rules: Describes the rules for routing based on the host.<br>- host: nuvexaphotos.com: Specifies that these rules apply when the request&#39;s host is &quot;nuvexaphotos.com.&quot;<br>http: Describes the HTTP-specific configurations.<br>paths: Lists different paths and their corresponding backends.<br>Each path configuration specifies:<br>path: The URL path pattern.<br>pathType: Prefix: The path matching type.<br>backend: Defines the backend service for this path.<br>service.name: The name of the Kubernetes service.<br>service.port.number: The port number on which the service is exposed.</p><ul><li>Requests to <em>“/api/photo/upload</em>,” <em>“/api/photo/user/…,” </em>and <em>“/api/photo/…” </em>are routed to the ‘<em>photosmngservice-srv</em>’ on <strong>port 8001</strong>.</li><li>Requests to “<em>/api/user/login</em>” and <em>“/api/user/register” </em>are routed to the <em>‘usermngservice-srv’</em> on <strong>port 8000</strong>.</li><li>Requests to <em>“/api/storage/user/…”</em> are directed to <em>‘storagemngservice-srv’ </em>on <strong>port 8002.</strong></li><li>Requests to <em>“/api/usage/user/…” </em>are directed to <em>‘usagemngservice-srv’</em> on <strong>port 8003.</strong></li><li>The default path <em>“/” </em>is routed to the ‘frontend-srv’ on <strong>port 3000.</strong></li></ul><h3>5. Continuous Integration and Continuous Deployment CI/CD</h3><p>For CI/CD, we are using Skaffold. Skaffold simplifies the build process by orchestrating the building of Docker images for each microservice in the Nuvexa-Photos project. The provided skaffold.yaml configuration file defines the build settings and deployment instructions.</p><pre>apiVersion: skaffold/v2alpha3<br>kind: Config<br>deploy:<br>  kubectl:<br>    manifests:<br>      - ./infra/k8s/*<br>build:<br>  googleCloudBuild:<br>    projectId: image-project-123<br>  artifacts:<br>    - image: us.gcr.io/image-project-123/photosmngservice<br>      context: PhotosMngService<br>      docker:<br>        dockerfile: Dockerfile<br>      sync:<br>        manual:<br>          - src: &quot;*.js&quot;<br>            dest: .<br>    - image: us.gcr.io/image-project-123/loggingservice<br>      context: LoggingService<br>      docker:<br>        dockerfile: Dockerfile<br>      sync:<br>        manual:<br>          - src: &quot;*.js&quot;<br>            dest: .<br>    - image: us.gcr.io/image-project-123/frontend<br>      context: FrontendService<br>      docker:<br>        dockerfile: Dockerfile<br>      sync:<br>        manual:<br>          - src: &quot;*.js&quot;<br>            dest: .<br>    - image: us.gcr.io/image-project-123/storagemngservice<br>      context: StorageMngService<br>      docker:<br>        dockerfile: Dockerfile<br>      sync:<br>        manual:<br>          - src: &quot;*.js&quot;<br>            dest: .<br>    - image: us.gcr.io/image-project-123/usagemngservice<br>      context: UsageMngService<br>      docker:<br>        dockerfile: Dockerfile<br>      sync:<br>        manual:<br>          - src: &quot;*.js&quot;<br>            dest: .<br>    - image: us.gcr.io/image-project-123/usermngservice<br>      context: UserMngService<br>      docker:<br>        dockerfile: Dockerfile<br>      sync:<br>        manual:<br>          - src: &quot;*.js&quot;<br>            dest: .</pre><ul><li>Build Section (build): Specifies the container image build process for each microservice.</li><li>For example, the PhotosMngService is defined with an image name (us.gcr.io/image-project-123/photosmngservice), source code context (PhotosMngService directory), and a Dockerfile (Dockerfile). Additionally, a sync configuration is specified, indicating that all JavaScript files (*.js) in the source directory should be included in the Docker build context.</li><li>This pattern is repeated for other microservices like LoggingService, FrontendService, StorageMngService, UsageMngService, and UserMngService.</li><li>Google Cloud Build Section (googleCloudBuild): Configures the Google Cloud Build settings, including the GCP project ID (image-project-123).</li><li>Deploy Section (deploy): Specifies the deployment process using Kubernetes (kubectl). It points to the Kubernetes manifests located in the ./infra/k8s/ directory.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RN0S-MKRwL4lWvUgcwGSqA.jpeg" /><figcaption>CI/CD Using Skaffold</figcaption></figure><p>In essence, this Skaffold configuration orchestrates the continuous integration and deployment process for the Nuvexa-Photos microservices. It utilizes Google Cloud Build for efficient container image builds and Kubernetes for seamless deployment. The sync configurations ensure that relevant source files are included in the Docker build context, creating a streamlined development and deployment pipeline for the entire project.</p><h3>6. Getting Started</h3><h4>Prerequisites</h4><ol><li><strong>GCP Account:</strong><br>Create or log in to your Google Cloud Platform (GCP) account.</li><li><strong>Enable Kubernetes Cluster API:<br></strong>Enable the Kubernetes Cluster API before creating a cluster.</li></ol><h4>Set Up GCP Terminal</h4><blockquote><strong>Install GCloud terminal for your ease or you can go with the GCP terminal</strong></blockquote><pre># Install GCloud Terminal<br>gcloud auth login<br>gcloud init<br></pre><pre># Choose option 1 to re-initialize the default configuration with new settings.<br># Select your GCP account and project.</pre><h4>Install Kubectl on GCP</h4><pre>gcloud components install kubectl<br>gcloud container clusters get-credentials &lt;cluster-name&gt;</pre><h3>Google Cloud Build</h3><h4>1. Enable Cloud Build:</h4><p>Enable the Cloud Build service on GCP.</p><h4>2. Update Skaffold Configuration:</h4><p><em>In infra/k8s/skaffol.yaml:</em></p><ul><li>Change <strong><em>projectId</em></strong> to your <strong>GCP project ID.</strong></li><li><em>Update the image field to match your </em><strong><em>project ID</em></strong><em>.</em></li></ul><h4>3. Setup Ingress-Nginx:</h4><p>You can Go to the <a href="https://www.kubernetes.github.io/ingress-nginx">Ingress controller documentation</a><br>and follow the steps to install the ingress controller but if you want to follow my commands they are given below. Commands change from time to time accordingly so you may have to refer to documentation.</p><p>Run:</p><pre>kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.8.2/deploy/static/provider/cloud/deploy.yaml</pre><ul><li>Verify pods are running:</li></ul><pre>kubectl get pods --namespace=ingress-nginx</pre><h4>Deploy Services with Skaffold</h4><p><strong>Restart Skaffold:<br></strong>First Stop any running Skaffold instances, if you are running the project for the first time there won&#39;t be any running instance</p><ul><li>Now run Skaffold Configuration file</li></ul><pre>skaffold dev -v debug</pre><ul><li>Skaffold will build images using Google Cloud Build, and images will be stored in the Google Cloud Repository.</li><li>The above commands that we executed created 2 things for us. First it created Ingress controller and the other one is Load balancer</li></ul><h4>Connect to Load Balancer:</h4><ul><li>Find the Load Balancer IP address on GCP Networking Service &gt; Load Balancer.</li><li>Update your hosts file (e.g., c:\Windows\System32\Drivers\etc\hosts in Windows 10) to map the IP address to your domain (e.g., nuvexaphotos.com). If you are using Linux you can find it at etc/hosts</li><li>add the IP address like : 34.66.119.150 <a href="https://nuvexaphotos.com/">https://nuvexaphotos.com</a> (e.g your load balancer IP address is 34.66.119.150 you will change it accordingly)</li><li>All building processes are executed in Google Cloud Build, and the services will now be running on a remote virtual machine.</li></ul><h4>Access Your Application:</h4><p>Open your browser and go to https://nuvexaphotos.com to access your running application.</p><h3>7. Load Testing</h3><p>To ensure the scalability and performance of the microservices, load testing can be performed using <a href="https://locust.io/">Locust</a>, a Python-based load testing tool.</p><h4>Prerequisites</h4><ul><li>Install Locust: pip install locust</li></ul><h4>Running Load Tests</h4><ol><li>Run Locust in your terminal:</li></ol><pre>locust -f locustfile.py</pre><p><strong>Screen Shots of the Load Testing are attached below:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*knCe7qMZG82URj_s4ZT1yQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zIicHG7KQgCiXOTwd309Fg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ERuqju5IA-tV69CP3JQEcA.jpeg" /></figure><h3>Summary:</h3><p>The article might have been long but was necessary to explain deployment files along with the deployment steps</p><p>In this article we:</p><ul><li>Reviewed the structure of the project</li><li>Saw a brief explanation of microservices</li><li>analyzed the Deployment file of the logging service and similarly deployment files of other services can be reviewed</li><li>learnt how the configuration files ingress controller was routing the external traffic to specific microservice</li><li>learnt about the CI/CD configuration of docker images and containers using Skaffold</li><li>have explored the steps involved in initiating the project code</li><li>finally, load tested the application using the Python locust library</li></ul><p>If you found this article of interest, please give me a clap as that helps me identify what people find useful and what future articles I should write. If you have any suggestions, please add them in the comments section.</p><h3>Links</h3><p>GitHub Repository:<a href="https://github.com/AreebAhmad-02/Nuvexa-Photos"> AreebAhmad-02/Nuvexa-Photos</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=286a80f2ec38" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>