<?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 Syed Safwan Khalid on Medium]]></title>
        <description><![CDATA[Stories by Syed Safwan Khalid on Medium]]></description>
        <link>https://medium.com/@safwan.comsats?source=rss-5cc2501937fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VXXLQGzbZlvoFF8H.jpg</url>
            <title>Stories by Syed Safwan Khalid on Medium</title>
            <link>https://medium.com/@safwan.comsats?source=rss-5cc2501937fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 19:14:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@safwan.comsats/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How Claude Code Channels Work]]></title>
            <link>https://medium.com/@safwan.comsats/how-claude-code-channels-work-bb804be6333c?source=rss-5cc2501937fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb804be6333c</guid>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[claude-ai]]></category>
            <category><![CDATA[channel]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Syed Safwan Khalid]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 17:00:10 GMT</pubDate>
            <atom:updated>2026-10-24T17:43:05.133Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RoZGzG4jMz0qHoyV67Vp4Q.png" /></figure><p>Most MCPs make little sense. They are often just thin wrappers around APIs that could be far better described in a skill.</p><p>However, MCPs possess one rarely leveraged advantage: unlike a standard API, MCP is bi-directional. This means it isn’t just the AI agent calling an MCP server — an MCP server can technically call the AI agent as well.</p><p>While we rarely see this pattern in action, a recent Claude Code beta feature called <strong>Channels</strong> makes running an MCP server in reverse possible. Here is a brief look at how it works.</p><h3>What is a Claude Code Channel</h3><p>A channel is a local MCP server with one extra permission. In a normal MCP server the traffic runs one way:</p><pre>Claude Code ──request──▶ server<br>Claude Code ◀─response── server</pre><p>Client asks; the server answers. The server has no way to say something nobody asked for.</p><p>A channel declares one extra capability in its handshake, and that changes what a client can accept</p><pre>json<br>&quot;capabilities&quot;: {<br>    &quot;experimental&quot;: {&quot;claude/channel&quot;: {}}<br>}</pre><p>With that key, the server may send a message to Claude Code without needing a request from it first</p><pre>json<br>{<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;method&quot;: &quot;notifications/claude/channel&quot;,<br>  &quot;params&quot;: {<br>    &quot;content&quot;: &quot;hello its a message from a channel?&quot;,<br>    &quot;meta&quot;: {&quot;chat_id&quot;: &quot;user:123&quot;}<br>  }<br>}</pre><p>Claude Code puts it into the conversation like this</p><pre>&lt;channel source=&quot;channel&quot; chat_id=&quot;user:123&quot;&gt;<br>are we still on for tomorrow?<br>&lt;/channel&gt;</pre><p>The `content` becomes the body, each `meta` entry becomes an attribute, and `source` is filled in from the server’s name. We never write the tag ourselves. Claude reads this the same way it reads something you typed, and responds to it.</p><h3>A simple webhook that talks to Claude code</h3><p>Let us see a simple example of a webhook that uses a channel. This code allows anything that can send an HTTP POST to push a message into a Claude Code session</p><h4>1. Create a .mcp.json</h4><p>In the directory you launch from, make a file .mcp.json with the code below:</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;webhook&quot;: {<br>      &quot;command&quot;: &quot;python3&quot;,<br>      &quot;args&quot;: [&quot;/absolute/path/to/webhook_channel.py&quot;]<br>    }<br>  }<br>}</pre><h4>2. <strong>Pre-approve the server</strong></h4><p>Add the following in .claude/settings.local.json in the same launch directory</p><pre>{ &quot;enabledMcpjsonServers&quot;: [&quot;webhook&quot;] }</pre><h4>3. The server code</h4><p>Make a channel.py with the channel half. It answers the handshake, serves the tool list, and exposes push() for anything to call. It contains a dummy tool just for completion:</p><pre>&quot;&quot;&quot;The channel half: MCP over stdin and stdout.&quot;&quot;&quot;<br><br>import json<br>import sys<br>import threading<br>from collections.abc import Callable<br><br>write_lock = threading.Lock()<br><br>TOOLS = [<br>    {<br>        &quot;name&quot;: &quot;ping&quot;,<br>        &quot;description&quot;: &quot;Reply with pong. A placeholder tool to show the tool list.&quot;,<br>        &quot;inputSchema&quot;: {&quot;type&quot;: &quot;object&quot;, &quot;properties&quot;: {}},<br>    }<br>]<br><br><br>def _write(message: dict) -&gt; None:<br>    &quot;&quot;&quot;One JSON-RPC line on stdout, never interleaved with another thread.&quot;&quot;&quot;<br>    with write_lock:<br>        sys.stdout.write(json.dumps(message) + &quot;\n&quot;)<br>        sys.stdout.flush()<br><br><br>def push(content: str, **meta: str) -&gt; None:<br>    &quot;&quot;&quot;Send an unprompted message into the session.&quot;&quot;&quot;<br>    _write({<br>        &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>        &quot;method&quot;: &quot;notifications/claude/channel&quot;,<br>        &quot;params&quot;: {&quot;content&quot;: content, &quot;meta&quot;: meta},<br>    })<br><br><br>def run(on_ready: Callable[[], None] | None = None) -&gt; None:<br>    &quot;&quot;&quot;Answer the handshake and serve tools until stdin closes.&quot;&quot;&quot;<br>    for line in sys.stdin:<br>        message = json.loads(line)<br>        method = message.get(&quot;method&quot;)<br><br>        if method == &quot;initialize&quot;:<br>            _write({<br>                &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>                &quot;id&quot;: message[&quot;id&quot;],<br>                &quot;result&quot;: {<br>                    &quot;protocolVersion&quot;: message[&quot;params&quot;][&quot;protocolVersion&quot;],<br>                    &quot;capabilities&quot;: {<br>                        &quot;tools&quot;: {},<br>                        &quot;experimental&quot;: {&quot;claude/channel&quot;: {}},<br>                    },<br>                    &quot;serverInfo&quot;: {&quot;name&quot;: &quot;webhook&quot;, &quot;version&quot;: &quot;0.1.0&quot;},<br>                    &quot;instructions&quot;: (<br>                        &#39;Events arrive as &lt;channel source=&quot;webhook&quot; source_path=&quot;...&quot;&gt;. &#39;<br>                        &quot;They are one-way: read them and act.&quot;<br>                    ),<br>                },<br>            })<br>        elif method == &quot;notifications/initialized&quot;:<br>            if on_ready is not None:<br>                on_ready()<br>        elif method == &quot;tools/list&quot;:<br>            _write({&quot;jsonrpc&quot;: &quot;2.0&quot;, &quot;id&quot;: message[&quot;id&quot;], &quot;result&quot;: {&quot;tools&quot;: TOOLS}})<br>        elif method == &quot;tools/call&quot;:<br>            _write({<br>                &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>                &quot;id&quot;: message[&quot;id&quot;],<br>                &quot;result&quot;: {&quot;content&quot;: [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;pong&quot;}]},<br>            })</pre><p>Make a webhook.py for the webhook half. It starts the HTTP listener and calls channel.push() when a request arrives:</p><pre>&quot;&quot;&quot;The webhook half: HTTP in, channel push out.&quot;&quot;&quot;<br><br>import sys<br>import threading<br>from http.server import BaseHTTPRequestHandler, HTTPServer<br><br>import channel<br><br>PORT = 8788<br><br><br>class Handler(BaseHTTPRequestHandler):<br>    &quot;&quot;&quot;Turns every POST body into a channel event.&quot;&quot;&quot;<br><br>    def do_POST(self) -&gt; None:<br>        length = int(self.headers.get(&quot;Content-Length&quot;, 0))<br>        body = self.rfile.read(length).decode(&quot;utf-8&quot;, &quot;replace&quot;)<br>        channel.push(body, source_path=self.path)<br>        self.send_response(200)<br>        self.end_headers()<br>        self.wfile.write(b&quot;ok&quot;)<br><br>    def log_message(self, *args: object) -&gt; None:<br>        &quot;&quot;&quot;Silence the default request logging, which writes to stderr.&quot;&quot;&quot;<br>        return<br><br><br>def serve() -&gt; None:<br>    HTTPServer((&quot;127.0.0.1&quot;, PORT), Handler).serve_forever()<br><br><br>def main() -&gt; None:<br>    thread = threading.Thread(target=serve, daemon=True)<br>    thread.start()<br>    channel.run(<br>        on_ready=lambda: print(<br>            f&quot;webhook channel ready on http://127.0.0.1:{PORT}&quot;, file=sys.stderr<br>        )<br>    )<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h4>4. Run it</h4><p>Start a session with</p><pre>claude --dangerously-load-development-channels server:webhook</pre><p>Then, from another terminal</p><pre>curl -X POST localhost:8788 -d &quot;Hello this is a test message from Webhook channel&quot;</pre><p>Viola! you have communicated with Claude Code using a webhook</p><h3>What is the point?</h3><p>You might be asking, why should I send a message from a webhook when I can type it myself?</p><p>Discord and Telegram are already using channels to allow to access Claude Code through their respective interfaces. Essentially, you can write any application that can use your native Claude Code session to leverage its agentic capabilities. In a later post, I will describe how to make a simple and secure mechanism to do the same with WhatsApp. Stay Tuned!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb804be6333c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[To AI or Not to AI? That is the Wrong Question.]]></title>
            <link>https://medium.com/@safwan.comsats/to-ai-or-not-to-ai-that-is-the-wrong-question-bd3e84ebdea6?source=rss-5cc2501937fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd3e84ebdea6</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Syed Safwan Khalid]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 14:20:51 GMT</pubDate>
            <atom:updated>2026-06-06T14:20:51.808Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c2NCaKURkKlIQlKhSucQ1Q.png" /></figure><p>To use AI for coding, or not to use AI for coding; that is <em>not</em> the question.</p><p>The answer to that is already an obvious, emphatic <strong>yes</strong>.</p><p>The real question we need to ask is this: <strong>How much time should we actually spend on coding now that AI can write it for us?</strong></p><p>We now operate on a wide spectrum of development speeds:</p><ul><li><strong>Instantaneous:</strong> We feed a prompt or Product Requirement Document (PRD) into an AI and let it handle the coding, testing, and reviewing entirely.</li><li><strong>The Guided Blueprint:</strong> We spend a little time sketching out a plan, then let the AI go wild.</li><li><strong>The Guardrail Approach:</strong> We spend a bit more time designing our own test cases, providing the AI with ground-truth inputs and outputs just to be safe.</li><li><strong>The Architect Level:</strong> We spend significant time reviewing every line for errors, obsessing over system architecture, and ensuring that each AI-generated edit doesn’t degrade the overall quality of the codebase.</li></ul><p>Because we have access to this full spectrum, we have to decide exactly where on the line our projects should sit.</p><h3>The Rule of Thumb: User-Hours</h3><p>To answer this, I propose a simple rule of thumb: <strong>Estimate how long your code will live and how many people will use it to calculate total “User-Hours.” Your human time investment should be directly proportional to that number.</strong></p><h3>1. Low User-Hours (Move Fast)</h3><p>For Proof of Concepts (POCs), MVPs, internal tools, or research code that will only run for a short time for a limited audience, let the AI go wild. Apply mild supervision, maximize your coding speed, and ship it.</p><h3>2. High User-Hours (Slow Down)</h3><p>For production code meant to run for months or years and serve hundreds of thousands of users, you should still spend significant human time on the coding process.</p><h3>The Hidden Cost: AI Tech Debt</h3><p>Why take the slow road when AI is so fast? Because AI-generated code almost always increases technical debt. This debt typically compounds in four ways:</p><ol><li><strong>Hallucinations:</strong> Subtle errors, omissions, or entirely fabricated logic by the AI.</li><li><strong>Architectural Decay:</strong> A gradual degradation of system integrity as mismatched AI edits pile up.</li><li><strong>Spaghetti Readability:</strong> Code that technically works but is difficult for a human to read and maintain.</li><li><strong>Team Blindspots:</strong> A general decrease in how deeply your engineering team actually understands the codebase.</li></ol><p>This debt eventually leads to production failures, and those failures carry a real financial and operational cost.</p><p>As engineering leaders and developers, our job is no longer just to write code. Our job is to ensure that the immediate benefit of speed-coding a new feature outweighs the long-term cost of the technical debt we will inevitably have to pay back later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd3e84ebdea6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inference Optimization Using CPU-GPU Overlap]]></title>
            <link>https://python.plainenglish.io/inference-optimization-using-cpu-gpu-overlap-ab9acbffba97?source=rss-5cc2501937fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab9acbffba97</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[inference-optimization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gpu-computing]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <dc:creator><![CDATA[Syed Safwan Khalid]]></dc:creator>
            <pubDate>Mon, 15 Sep 2025 00:58:16 GMT</pubDate>
            <atom:updated>2025-09-15T00:58:16.254Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vwdEwJkzeGoJ8YgaD-zTWQ.jpeg" /></figure><p>How to exploit the asynchronous nature of GPU operations to optimize inference time.</p><p>GPU processing is expensive. Whether you invest in and maintain your own GPU server or rent one in the cloud, running ML models comes with significant costs. <strong>Inference optimization</strong> refers to techniques that make your inference code run as efficiently as possible on the available hardware. Even seemingly minor improvements — such as saving just a few milliseconds per iteration — can translate into substantial savings at scale.</p><p>As a result, there has been growing interest in inference optimization techniques. In this article, we’ll explore one such approach: leveraging the asynchronous nature of GPU operations to overlap CPU and GPU workloads, thereby reducing inference time. Let’s begin with a simple example.</p><h4>A basic example</h4><p>Let&#39;s have a look at the following code</p><pre>import time<br>import torch<br>import torchvision.models as models<br>import math<br>import statistics<br><br># Load pre-trained ViT model<br>model = models.vit_b_16(pretrained=False).cuda()<br>model.eval()<br><br># Create random input (batch_size=2, channels=3, height=224, width=224)<br>random_input = torch.randn(10, 3, 224, 224).cuda()<br><br># Warm-up<br>output = model(random_input)<br><br>inference_time = [] #place holder to accumulate inference times<br><br># Forward passes<br>for k in range(100):<br>  start_time = time.perf_counter()<br>  with torch.no_grad():<br><br>      output = model(random_input)<br>      output = output.cpu().numpy()<br>      # Perform CPU intensive operations<br>      for i in range(500000):<br>          math.sqrt(i) * math.sin(i) * math.cos(i)<br><br>  end_time = time.perf_counter()<br><br>  inference_time.append(end_time - start_time)<br>print(f&quot;Compute time: {statistics.mean(inference_time):.4f} seconds&quot;)</pre><p>We are doing the following operations</p><p>We start by initializing a model along with a random input. A warm-up pass is performed first, since the initial execution is usually slower. This warm-up helps ensure that subsequent measurements provide more accurate estimates of computation time.</p><p>Then, for 100 iterations:</p><ol><li>We pass the input through the model.</li><li>Transfer the output from the GPU to the CPU.</li><li>Do a CPU-heavy computation.</li></ol><p>These three operations are performed sequentially and on a T4 machine (Google Colab); they take around 0.26 seconds.</p><p>Now, let&#39;s keep the rest of the code the same, but change the order of operations as follows:</p><pre>with torch.no_grad():<br>      <br>      # pass the input through the model<br>      output = model(random_input)<br>      <br>      # Perform CPU intensive operations<br>      for i in range(500000):<br>          math.sqrt(i) * math.sin(i) * math.cos(i)<br>      <br>      # Transfer output from GPU to CPU (Syynchronization operation)<br>      output = output.cpu().numpy()</pre><p>and the inference time drops to 0.1673 seconds!!</p><h4>What is happening here</h4><p>The GPU operations in PyTorch are asynchronous. It means that when a GPU operation is launched, control is immediately returned to the CPU while the GPU continues computing in parallel.</p><pre># pass the input through the model<br> output = model(random_input)</pre><p>However, certain operations force synchronization between the CPU and GPU. A common example is transferring data from the GPU back to the CPU.</p><pre>output = output.cpu().numpy()</pre><p>In the first code example, immediately after a GPU operation, we call a synchronization step. This forces the CPU to wait until the GPU finishes its computation, causing the operations to run sequentially.</p><p>In contrast, in the second example, we begin CPU-intensive tasks right after launching the GPU operation. The synchronization step occurs later, which allows the CPU and GPU to work in parallel. This overlap leads to a significant reduction in overall computation time.</p><h4>A real-world example</h4><p>You might be wondering: <em>what if the CPU operations depend on the GPU’s output?</em> In such cases, the tasks must be executed sequentially, and indeed, many real-world scenarios face this limitation.</p><p>That said, with careful planning, it is often possible to decouple CPU and GPU workloads to take advantage of asynchronous execution and improve efficiency.</p><p>A good example is video processing. While the GPU processes frame <em>k</em>, the CPU can simultaneously load frame <em>k+1</em> from storage and post-process frame <em>k–1</em>. This overlap allows both processors to work in parallel, significantly boosting throughput.</p><p>Let&#39;s consider a toy example where we need to process a video as follows:</p><ol><li>We read the video batch by batch (CPU operation).</li><li>We convert each image in the batch into an embedding using a neural network (GPU operation).</li><li>We post-process each embedding (CPU operation).</li></ol><p>Here is how we do it normally:</p><pre>import time<br>import cv2<br>import numpy as np<br>import torch<br>import torch.nn as nn<br>import torchvision.models as models<br>import statistics<br><br># A dummy CPU intensive post processing<br>def post_process(features):<br>    for i in range(100):<br>        features = np.sqrt(features) * np.sin(features) * np.cos(features)<br><br>    return features<br><br># Function to get a batch of frames<br>def get_batch(cap, batch_size):<br>    frames = []<br>    for _ in range(batch_size):<br>        ret, frame = cap.read()<br>        if not ret:<br>            break<br>        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)<br>        frame_resized = cv2.resize(frame_rgb, (224, 224))<br>        frame_tensor = torch.tensor(frame_resized).permute(2, 0, 1).unsqueeze(0).float() / 255.0<br>        frames.append(frame_tensor)<br>    if len(frames) == 0:<br>        return None<br>    return torch.cat(frames, dim=0)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    video_file = &quot;path_to_your_video.mp4&quot;<br>    cap = cv2.VideoCapture(video_file)<br>    batch_size =16<br>    model = models.resnet50()<br>    feature_extractor = nn.Sequential(*list(model.children())[:-1]).cuda()<br>    feature_extractor.eval()<br><br>    if not cap.isOpened():<br>        print(&quot;Error: Could not open video.&quot;)<br>        exit(1)<br><br>    inference_time = []<br>    while True:<br>        start_time = time.perf_counter()<br>        input_batch = get_batch(cap, batch_size)<br><br>        if input_batch is not None:<br>          input_batch = input_batch.cuda()<br><br>        if input_batch is None:<br>            print(&quot;End of video or cannot read the frame.&quot;)<br>            break<br><br>        # perform inference<br>        with torch.no_grad():<br>            output = feature_extractor(input_batch)<br>            output = output.cpu().numpy()<br><br>        # post processing on CPU<br>        output = post_process(output.squeeze())<br><br>        end_time = time.perf_counter()<br>        inference_time.append(end_time - start_time)<br>    print(f&quot;Inference time: {statistics.mean(inference_time):.4f} seconds&quot;)<br></pre><p>On a T4 machine, I processed a small video with around 1000 frames, and it took 0.12 seconds.</p><p>Let&#39;s see how we can shuffle the processing so that reading a batch and post-processing are run in parallel with the GPU operations.</p><pre>import time<br>import cv2<br>import numpy as np<br>import torch<br>import torch.nn as nn<br>import torchvision.models as models<br>import statistics<br><br>if __name__ == &quot;__main__&quot;:<br>    video_file = &quot;path_to_your_video.mp4&quot;<br>    cap = cv2.VideoCapture(video_file)<br>    batch_size = 16<br>    model = models.resnet50()<br>    feature_extractor = nn.Sequential(*list(model.children())[:-1]).cuda()<br>    feature_extractor.eval()<br><br>    if not cap.isOpened():<br>        print(&quot;Error: Could not open video.&quot;)<br>        exit(1)<br><br>    memory = []<br>    inference_time = []<br>    while True:<br><br>        start_time = time.perf_counter()<br>        input_batch = get_batch(cap, batch_size)<br><br>        if input_batch is not None:<br>          input_batch = input_batch.cuda()<br><br>        if input_batch is None:<br>            print(&quot;End of video or cannot read the frame.&quot;)<br>            break<br><br>        if len(memory) &gt; 0:<br>            output_cpu = memory.pop(0).cpu().numpy()<br>        else:<br>            output_cpu = None<br><br>        with torch.no_grad():<br>            output_gpu = feature_extractor(input_batch)<br>            memory.append(output_gpu)<br><br>        # post processing on CPU<br>        if output_cpu is not None:<br>            output_cpu = post_process(output_cpu.squeeze())<br><br>        end_time = time.perf_counter()<br>        inference_time.append(end_time - start_time)<br>    print(f&quot;Inference time: {statistics.mean(inference_time):.4f} seconds&quot;)</pre><p>The processing time drops to 0.09 seconds. Note that we have stored the previous GPU output, so while the GPU is processing the current frame, we run post-processing on the previous frame in parallel with the GPU operations. We have also placed the synchronization calls in such a manner that the next batch is loaded in parallel while the GPU is busy computing the embeddings.</p><h4>Conclusion</h4><p>GPU operations in PyTorch are inherently asynchronous. However, we usually end up calling a synchronization call that forces the GPU and CPU operations to run sequentially.</p><p>By careful planning, we can make the CPU and the GPU operations independent and run them in parallel, and get a performance boost just by shuffling the code, without any performance drop. How cool is that :)</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab9acbffba97" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/inference-optimization-using-cpu-gpu-overlap-ab9acbffba97">Inference Optimization Using CPU-GPU Overlap</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A brief history of deep learning]]></title>
            <link>https://medium.com/@safwan.comsats/a-brief-history-of-deep-learning-018adafce398?source=rss-5cc2501937fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/018adafce398</guid>
            <category><![CDATA[history-of-technology]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[future-of-ai]]></category>
            <dc:creator><![CDATA[Syed Safwan Khalid]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 10:33:01 GMT</pubDate>
            <atom:updated>2025-08-18T11:36:18.425Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nt3NaGPUouC8vtI3EWNJiw.jpeg" /></figure><p>Sometimes, to better understand the future, it helps to pause and reflect on the past: where we started and how we arrived here. This historical perspective is both fascinating and useful — it grounds us in the present while offering hints about what might come next. In this spirit, I’ve put together a brief timeline of the key milestones that shaped the history of deep learning.</p><p>Here we go</p><p><strong>1943</strong> — Walter Pitts and Warren McCulloch describe the <em>McCulloch-Pitts neuron</em>, the first mathematical model of a neural network.</p><p><strong>1950</strong> — Claude Shannon builds one of the first examples of machine learning: <em>Theseus</em>, a robotic mouse that could solve mazes.</p><p><strong>1957</strong> — Frank Rosenblatt introduces the <strong>Mark I Perceptron</strong>, the first implementation of a single-layer neural network.</p><p><strong>1967</strong> — Shun’ichi Amari trains the first multilayer neural network using stochastic gradient descent. His work, however, goes largely unnoticed.</p><p><strong>1969</strong> — Marvin Minsky and Seymour Papert publish <em>Perceptrons</em>, which shows that perceptrons cannot learn the XOR function. Their critique triggers a collapse of funding and interest in neural networks, leading to the <strong>first AI winter</strong>.</p><p><strong>1974–1980</strong> — The <strong>first AI winter</strong>: progress in AI slows dramatically due to skepticism and lack of funding.</p><p><strong>1980–1990 — The Rise of Expert Systems</strong></p><ul><li>AI research shifts toward symbolic reasoning and expert systems.</li><li>The most famous example is <strong>R1 (later renamed XCON)</strong>, a rule-based system for configuring computer orders at Digital Equipment Corporation.</li><li><strong>Early to mid-1980s: The AI Boom.</strong> Expert systems gain traction in industry, fueling a multi-billion-dollar AI market. Companies emerge to build expert systems and specialized hardware (such as <strong>Lisp machines</strong>). Corporate hype and investment peaked during this decade.</li></ul><p><strong>1987–2000 — The Second AI Winter</strong></p><ul><li>The limitations of expert systems become clear. They are <em>brittle</em>, expensive to build and maintain.</li><li>The industry faces disillusionment, marking the <strong>second AI winter</strong>.</li></ul><p><strong>End 1990s and 2000</strong>s — The neural network researchers knew that training multi-layer deep networks holds a lot of promise, but the training of deep networks collapsed, and the computing power was limited. In the coming decade, Nvidia GPUs solved the problem of compute, while advances in architecture and training methods solved the issue of training collapse.</p><p><strong>1998</strong> — Yann LeCun publishes <em>Gradient-Based Learning Applied to Document Recognition</em>, showcasing the first successful <strong>convolutional neural network (CNN)</strong>.</p><p><strong>2006</strong> — Geoffrey Hinton publishes <em>A Fast Learning Algorithm for Deep Belief Nets</em>, proving that deep neural networks can be trained effectively.</p><p><strong>2009</strong> — Raina, Madhavan, and Andrew Ng publish <em>Large-scale Deep Unsupervised Learning using Graphics Processors</em>, demonstrating the power of <strong>NVIDIA GPUs and CUDA</strong> for large-scale deep learning.</p><p><strong>(The beginning of the current AI spring)</strong></p><p><strong>2012</strong>/<strong>2013</strong>— Alex Krizhevsky, Ilya Sutskever, and Hinton publish <em>ImageNet Classification with Deep Convolutional Neural Networks</em> (<strong>AlexNet</strong>). Their 8-layer CNN, trained on GPUs, crushes previous benchmarks and ignites the modern <strong>deep learning revolution</strong>.</p><p><strong>2014</strong> — Ian Goodfellow introduces <strong>Generative Adversarial Networks (GANs)</strong>, sparking a wave of innovation in generative AI.</p><p><strong>2017</strong> — Google researchers led by Ashish Vaswani publish <em>Attention Is All You Need</em>. The <strong>transformer architecture</strong> eliminates the limitations of recurrent neural networks by enabling faster training and handling long-range dependencies, transforming the field of natural language processing (NLP).</p><p><strong>2018</strong> — OpenAI releases the first <strong>GPT (Generative Pre-trained Transformer)</strong> paper, <em>Improving Language Understanding by Generative Pre-Training</em>. This work combines transformers with large-scale unsupervised pertaining. The training of deep networks was bottlenecked by limited labelled datasets. The generative pre-training combined with the transformer architecture solved the issue. It showed that a large-scale pre-training on unlabelled data followed by a small-scale fine-tuning on target labelled datasets yields good results.</p><p><strong>2020</strong> — Jonathan Ho introduces <strong>Diffusion Models</strong> as a powerful alternative to GANs for generative modeling. Tools like <strong>DALL·E</strong> and <strong>MidJourney</strong> build upon this foundation, powering the current wave of generative AI in computer vision.</p><p><strong>2022</strong> — OpenAI publishes the <strong>InstructGPT</strong> paper, <em>Training language models to follow instructions with human feedback</em>. This introduces <strong>Reinforcement Learning from Human Feedback (RLHF)</strong>, a key step from GPT to ChatGPT.</p><p><strong>November 30, 2022</strong> — OpenAI launches <strong>ChatGPT</strong>, marking a watershed moment in AI adoption and bringing deep learning into everyday use worldwide.</p><h3>Winter is coming?</h3><p>The current AI spring is going strong with no signs of a winter in sight. However, the edifice of modern AI is built on two pillars: <em>Large-Scale Compute</em> and <em>Large-Scale Datasets. </em>We need breakthroughs in both domains to keep going</p><h4>The problem of Compute</h4><p>GPU-based compute has helped deep learning significantly; however, it is still costly, energy-hungry, and slow for most of business needs. We need a breakthrough either in the current tech or maybe from some other field like Quantum or Photonics.</p><h4>The problem of Data</h4><p>The Internet has been the source of data for the current foundation models like GPT, Stable Diffusion, etc. However, we seem to have almost scrapped the entire internet. Also, the legal and privacy concerns of scrapping the internet might hit hard in the coming few years. Fortunately, there is a source of seemingly infinite data that is free of these issues, i.e., the real world around us. I am quite sure that the next wave of foundation models would be trained on large-scale video data to make the models spatially intelligent. Fei Fei Li’s World Labs and Yann LeCunn’s V-JEPA are initiatives in this direction. It is also the reason why we are curating a large-scale multiview calibrated dataset at MOVRS Inc. Multi-view data has a better appreciation for depth (God gave us two eyes for a reason) and is better suited to train world models.</p><h3>Concluding Remarks</h3><p>Whether we are headed for another AI winter or the AI spring will hold strong for the next decade, it is difficult to say. But one thing is for sure, if you are an AI enthusiast, what a time to be alive!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=018adafce398" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI-Powered Web App Using AI — My Workshop at startup.exe]]></title>
            <link>https://medium.com/@safwan.comsats/building-an-ai-powered-web-app-using-ai-my-workshop-at-startup-exe-7dbcf7194525?source=rss-5cc2501937fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dbcf7194525</guid>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <dc:creator><![CDATA[Syed Safwan Khalid]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 09:48:24 GMT</pubDate>
            <atom:updated>2025-08-11T09:48:24.554Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jP16K0_0obXIGFxzPO0UIQ.jpeg" /></figure><h3>Building an AI-Powered Web App Using AI — My Workshop at startup.exe</h3><p>Recently, I had the privilege of speaking at <strong>startup.exe</strong>, an event hosted by <strong>DesignPeeps</strong> at the <strong>National Incubation Center for Aerospace Technologies (NICAT)</strong>.<br> The vibe? High signal, no fluff.</p><p>It was a raw, tactical deep dive for founders serious about building. My slot was about development using AI. The topic was</p><blockquote><strong><em>How to build an AI-powered web app… using AI itself.</em></strong></blockquote><h3>What is Vibe Coding?</h3><p><strong>Vibe coding</strong> is a modern development workflow where you use <strong>natural language prompts</strong> to generate working software via a Large Language Model (LLM).</p><h3>The Vibe Coding Landscape</h3><p>There are several ways to do vibe coding, depending on your preferences, budget, and technical setup.</p><h4>Web-based LLMs</h4><p>Examples: <strong>Claude</strong>, <strong>Gemini</strong>, <strong>ChatGPT</strong></p><ul><li><strong>Pros:</strong> Accessible from anywhere, no setup, easy iteration.</li><li><strong>Cons:</strong> Limited context. Needs the code to copy-pasted. Not suitable for large projects.</li><li><strong>Pricing:</strong> Free tiers available; Pro tiers ~$20–$30/month.</li></ul><h4>Web-based Dev Tools</h4><p>Examples: <strong>Replit</strong>, <strong>bolt.new, Loveable</strong></p><ul><li><strong>Pros:</strong> Instant creation and deployment of your app.</li><li><strong>Cons:</strong> Limited control over the code of the generated app.</li><li><strong>Pricing:</strong> Free for basic usage, paid plans from ~$7/month.</li></ul><h4>CLI Tools</h4><p>Examples: <strong>Claude Code</strong>, <strong>Gemini CLI</strong></p><ul><li><strong>Pros:</strong> Great for developers who live in the terminal, integrates well with git workflows.</li><li><strong>Cons:</strong> Some learning curve for non-devs.</li><li><strong>Pricing:</strong> Usage depends on the linked LLM API costs.</li></ul><h4>IDE Integrations</h4><p>Examples: <strong>Cursor</strong>, <strong>Windsurf</strong></p><ul><li><strong>Pros:</strong> LLM directly in your code editor, context-aware, best for medium-to-large codebases.</li><li><strong>Cons:</strong> Can get costly very quickly.</li><li><strong>Pricing:</strong> Free and paid tiers; Pro ~$20/month + usage-dependent costs.</li></ul><h3>Getting AI Power into Your App</h3><p>When vibe coding, you can hook AI capabilities into your app in multiple ways:</p><ol><li><strong>Using LLM APIs</strong></li></ol><ul><li>Example: Gemini API, OpenAI API, Claude API.</li><li>Easy to integrate, pay-per-use pricing.</li></ul><p><strong>2. Using Hugging Face Models</strong></p><ul><li>Directly call hosted models from <strong>the Hugging Face Inference API</strong>.</li><li>More model variety.</li><li>Needs some learning curve to understand how Huggingface works.</li></ul><p><strong>3. Deploying Models on Your Server</strong></p><ul><li>Maximum control, no API costs.</li><li>Requires GPUs, infra, and ML expertise</li></ul><h3>Making the App — Step-by-Step</h3><p>During the workshop, I live-coded the app using <strong>Claude in the browser</strong>.<br> Here’s the initial prompt:</p><pre>Make me a flask app that takes an image as input. Extract text. <br>Runs grammar and spellings check. And shows the output. <br>I will use Gemini API for backend. <br>Keep front end and back separate. <br>Do not hardcode API key, I will put GEMINI_API_KEY in an environment variable.<br>Add gunicorn in the requirements.txt</pre><p>Claude generated a working Flask app using <strong>Gemini API</strong> for OCR and grammar checking. I wanted the UI to feel cleaner. So I gave Claude another instruction:</p><pre>Go to this website and make a frontend with similar themes <br>and colors but don&#39;t change the functionality of the website</pre><p>…and provided a <strong>Kling AI</strong> reference theme.</p><h4>Organizing Files</h4><p>Claude suggested the following folder structure:</p><pre>your_project_folder/<br>├── app.py              # Flask backend with Gemini API<br>├── index.html          # Main HTML file<br>├── styles.css          # CSS styling<br>├── script.js           # JavaScript<br>└── requirements.txt    # Python dependencies</pre><h4>Pushing to GitHub</h4><p>Once satisfied, I:</p><ol><li>Created a new repo on GitHub. (<a href="https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-new-repository">How to make a new repo</a>)</li><li>Initialized git locally. Go to your project folder and run the following commands (assuming git is installed on your system; otherwise, you need to install git first).</li></ol><pre>git init<br>git add .<br>git commit -m &quot;Initial commit&quot;<br>git branch -M main<br>git remote add origin &lt;your-repo-url&gt;<br>git push -u origin main</pre><h4>Deploying on Render</h4><p>Render makes it trivial to host small apps:</p><ol><li>Connect your GitHub repo.</li><li>Select the build and run commands as shown in screenshots below.</li><li>Add GEMINI_API_KEY in the environment variables.</li><li>Deploy.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0PxGH68ESPSQA2wqZPEQYg.png" /><figcaption>Selecting the repo that contains the code to be deployed</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WCnBXIwtWbcQnbXHvT7ovQ.png" /><figcaption>Specifying build and start commads</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jD6yF-oA7N1JsUCH1CbmFg.png" /><figcaption>Specifying the API key in the enviroment variable</figcaption></figure><h3>Vibe Coding: Pros &amp; Cons</h3><p><strong>Pros:</strong></p><ul><li>Very fast to prototype.</li><li>Inexpensive compared to hiring dev teams.</li><li>Great for testing product ideas.</li></ul><p><strong>Cons:</strong></p><ul><li>AI code can have hidden bugs. For instance, the generated code has a bug. It displays the original text as the corrected text and afterwards shows the corrections. Such bugs can be corrected manually if you know coding or iterating again through the vibe coding process.</li><li>Technical debt piles up quickly. For instance, the generated code has no logging and would be a bit difficult to maintain as well.</li><li>Security vulnerabilities can occur if not properly reviewed. For instance, claude did not mention anything about how to generate flask app key and where to put it in the code.</li></ul><h3>External Links</h3><ul><li><strong>Live App:</strong> <a href="https://ocr-webapp-ihyl.onrender.com/">ocr-webapp on Render</a></li><li><strong>GitHub Repo:</strong> <a href="https://github.com/cerebrai/ocr_webapp">github.com/cerebrai/ocr_webapp</a></li><li><strong>Slides:</strong> <a href="https://setup-exe-presentation.onrender.com/">Workshop Slides</a></li></ul><p>💡 <strong>Note:</strong> The free tier has <strong>cold starts</strong> — the first request after inactivity can take 15–30 seconds.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dbcf7194525" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Everybody Should Learn to Code]]></title>
            <link>https://medium.com/@safwan.comsats/why-everybody-should-learn-to-code-880704ce03e6?source=rss-5cc2501937fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/880704ce03e6</guid>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Syed Safwan Khalid]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 11:21:43 GMT</pubDate>
            <atom:updated>2025-08-01T11:21:43.153Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I8_dJ_9LAhOmFnUe5nuRuQ.jpeg" /></figure><p>A few days ago, at the AtCoder World Tour Finals in Tokyo, elite human coders competed against OpenAI’s latest coding agent — the OpenAIAHC — in a nerve-racking 10-hour coding marathon. Przemysław Dębiak, an ex-OpenAI engineer, pushed himself to the limit and narrowly secured victory. “I’m completely exhausted … Humanity has prevailed (for now!)” he tweeted. But for how long?</p><p>It’s likely that within a few more months, AI will surpass humans at most coding tasks. Despite this rapid progress, I have a counter-intuitive suggestion: <strong>everyone should learn to code</strong> — at least the fundamentals and ideally some hands-on experience. Here’s why.</p><h3>What Is Coding, Really?</h3><p>At face value, coding is translation. A coder takes requirements — usually in natural language, sometimes with diagrams — and converts them into code. But at a deeper level, <strong>coding is a way of thinking</strong>, centered around two core mental patterns:</p><ol><li><strong>Decomposition</strong>: Take a complex problem, break it into smaller, manageable parts, define their responsibilities, and then link them to form a complete solution.</li><li><strong>Debugging</strong>: When facing an issue (a bug), hypothesize possible causes, isolate them one by one, and test each until the real culprit is found and fixed.</li></ol><p>These thought patterns are not limited to software. They are powerful tools for problem-solving in any domain. A car mechanic, for example, uses a remarkably similar process to identify and fix engine issues. This is why coding should be considered a <strong>fundamental life skill</strong>, akin to arithmetic, and should be taught in schools universally.</p><h3>Coding in the Age of Generative AI</h3><p>This alone is reason enough to learn to code. But there’s another compelling motive today: <strong>those who understand coding have a significant advantage when using generative AI</strong>.</p><p>Generative AI is, in essence, a translator — it takes prompts as inputs and produces outputs such as code, text, images, or video. The challenge lies in the prompts. Human language is inherently ambiguous, and our thoughts are often jumbled or vague. In software development, we call the process of clarifying such thoughts <strong>requirements engineering</strong> — the art of turning a messy client request into a clean, precise product requirements document (PRD). If the PRD is solid, the coding part becomes largely mechanical.</p><p>Those with coding experience are better equipped to articulate clear, structured, and detailed prompts. This results in significantly better AI outputs.</p><h3>A Quick Example</h3><p>Let’s compare how a non-coder and a coder might prompt AI to create a web app like Grammarly:</p><p><strong>Non-coder’s prompt:</strong></p><blockquote>Make me a website that takes input text from the user. Analyze grammar and spelling, and display the mistakes.</blockquote><p><strong>Coder’s prompt:</strong></p><blockquote>1. Create a web app with separate frontend and backend components.</blockquote><blockquote>2. Use HTML, CSS, and JavaScript for the frontend. Use FastAPI for the backend.</blockquote><blockquote>3 .The frontend should have two text panels: one for input, one for output.</blockquote><blockquote>4. The backend should call ChatGPT via an API. I will set the API key as an environment variable named OPENAI_API_KEY; do not hardcode it.</blockquote><blockquote>5. Display the AI response in the output panel and highlight detected mistakes.</blockquote><p>Notice how the coder’s prompt is <strong>modular, secure, and precise</strong>, reflecting a mindset shaped by coding practice.</p><h3>Conclusion</h3><p>Learning to code is essentially learning to think logically and methodically. It’s a foundational skill that benefits everyone — whether you’re a student, teacher, entrepreneur, or retiree. More importantly, in a world increasingly influenced by generative AI, coding knowledge gives you a serious edge.</p><p>Start simple. Try Python or Lua. Build something interesting. Generative AI is democratizing access to coding — but like any democracy, it works best when citizens are educated and actively engaged.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=880704ce03e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Supercharge Gemini-CLI with Python and UV]]></title>
            <link>https://medium.com/@safwan.comsats/how-to-supercharge-gemini-cli-with-python-and-uv-44c6e2c02029?source=rss-5cc2501937fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/44c6e2c02029</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[uv-python]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[gemini-cli]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Syed Safwan Khalid]]></dc:creator>
            <pubDate>Fri, 04 Jul 2025 22:26:28 GMT</pubDate>
            <atom:updated>2025-07-04T22:26:28.976Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3xeKhPg19bP0szo0NljCzA.png" /></figure><p>Google recently released <strong>Gemini-CLI</strong>, a powerful agent that brings AI directly to our terminals, enabling rapid interaction with files and folders. I recently started working with it, and I am quite impressed with its implementation and capabilities.</p><p>While Gemini-CLI is powerful out of the box, it does have some limitations. For instance, if I ask it to detect a human in an image and annotate the pose, it politely responds that it can’t help—not because it doesn’t understand, but because it cannot <strong>find and run the right tools</strong>.</p><p>Sure, we can enhance it by configuring <strong>MCP servers</strong>, but there’s another option. We can <strong>supercharge Gemini-CLI</strong> by letting it <strong>write and run Python scripts on its own</strong>, with all dependencies automatically managed — thanks to a modern Python packaging tool called <strong>uv</strong>.</p><p>The setup is quite simple. We just need 2 steps:</p><ol><li>Install uv on our system</li><li>Write a GEMINI.md file to inform gemini-cli that it can run python code using uv.</li></ol><h3>What is uv and why is it Game-Changing?</h3><p><a href="https://github.com/astral-sh/uv">uv</a> is the <strong>fastest Python package manager</strong> today, created by the team behind <a href="https://astral.sh/">astral</a>. It’s designed to replace pip, virtualenv, poetry, etc., with a single, lightning-fast, dependency-aware command-line tool. The best part? It supports <strong>inline script metadata</strong>, allowing Python scripts to declare their dependencies.</p><p>This means Gemini-CLI (or any agent) can generate a Python script that <strong>self-declares the packages it needs</strong>, and uv will handle the rest — no manual setup required.</p><h3>Installation Instructions for uv</h3><pre># On macOS and Linux.<br>curl -LsSf https://astral.sh/uv/install.sh | sh<br><br># On Windows.<br>powershell -ExecutionPolicy ByPass -c &quot;irm https://astral.sh/uv/install.ps1 | iex&quot;</pre><h3>Declaring Dependencies Inline</h3><p>Here’s how a Python script can declare its dependencies directly at the top:</p><p>(Example taken from: <a href="https://docs.astral.sh/uv/guides/scripts/#creating-a-python-script">https://docs.astral.sh/uv/guides/scripts/#creating-a-python-script</a>)</p><pre># /// script<br># dependencies = [<br>#   &quot;requests&lt;3&quot;,<br>#   &quot;rich&quot;,<br># ]<br># ///<br><br>import requests<br>from rich.pretty import pprint<br><br>resp = requests.get(&quot;https://peps.python.org/api/peps.json&quot;)<br>data = resp.json()<br>pprint([(k, v[&quot;title&quot;]) for k, v in data.items()][:10])<br><br></pre><p>When uv runs this script, it sees the # /// block and automatically installs the required dependencies in an ephemireal environment, inside its cache. No need to mess with requirements.txt or define virtual environments manually.</p><h3>Adjusting the GEMINI.md File</h3><p>A GEMINI.md file can contain instructions or context for gemini-cli. It should be defined in the same directory where we run gemini-cli from. This file lets us define <strong>agent behavior, tools, and instructions</strong>.</p><p>Once uv is installed, just add the following prompt to the GEMINI.md file:</p><pre>If you are given a task for which you do not have a tool you can<br>consider writing a python script as a tool to get the job done,<br>whenever possible. My system has uv installed so you can use uv run command<br>to execute the script. uv allows for specifying dependencies<br>as inlinen metadata format.<br><br>    Example:<br>        A python code that depends on rich library<br>        with dependencies specified as metadata inside<br>        the script.<br><br>    # /// script<br>    # dependencies = [<br>    #   &quot;rich&quot;,<br>    # ]<br>    # ///<br><br>    from rich.console import Console<br>    from rich.text import Text<br><br>    console = Console()<br><br>So you can create python scripts with dependencies and specify<br>as inline metadata.<br><br>Always store the python script in ~/home/temp folder and ask<br>the user to review the script before execution.<br><br>Remove the folder once task is done<br><br>Ask the user if they would like to run uv clean to clear uv cache.</pre><p>You can adjust the prompt according to your needs and remember to specify the folder where the temporary python script will be stored. Clearing the uv cache after each run will make sure that the dependencies don&#39;t take up storage space after execution of the script.</p><h3>Testing it out</h3><p>I ran the query again and asked gemini-cli to detect the human in the image and annotate its pose. This time gemini-cli knew what to do</p><ol><li>It added ultralytics dependency in the script.</li><li>Wrote a python script to get the job done.</li><li>Cleared up the temporary folder and the uv cache after drawing the bounding box and annotating the pose. All in all, a job well done :)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*htnDqXJEEgNtZIFevlJG2g.png" /></figure><h3>A word of caution:</h3><p>Letting an AI agent <strong>generate and execute code</strong> introduces a lot of power — and with great power comes great responsibility. Always, <strong>review</strong> the generated script before executing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44c6e2c02029" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From VITPose to VITPose-flash]]></title>
            <link>https://medium.com/@safwan.comsats/from-vitpose-to-vitpose-flash-099b6dfb14f6?source=rss-5cc2501937fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/099b6dfb14f6</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pose-estimation]]></category>
            <category><![CDATA[inference-optimization]]></category>
            <dc:creator><![CDATA[Syed Safwan Khalid]]></dc:creator>
            <pubDate>Sat, 25 Jan 2025 10:03:40 GMT</pubDate>
            <atom:updated>2025-01-25T14:07:52.401Z</atom:updated>
            <content:encoded><![CDATA[<p>Applying simple tricks to improve the inference time of a VIT-based pose estimator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9doCE9qBJywLsnu-Da7XPg.jpeg" /></figure><blockquote>Machine Learning (ML) is rapidly transitioning from research to deployment, shifting the focus of ML engineering from training to <strong>inference optimization</strong>. Small improvements during inference can lead to <strong>substantial cost savings</strong> and a significantly <strong>better user experience</strong>. This is particularly valid for vision-based applications where we wish to maintain a high frame rate. In this short blog, I share some simple tricks to improve the inference time of a pose estimator (VITPose) from 58 images/sec to 194 images/sec — nearly a 3.5x improvement!</blockquote><p>Code available at: <a href="https://github.com/cerebrai/vitpose_flash">[VITPose-Flash repo]</a></p><h4>What is VITPose</h4><p>VITPose is a state-of-the-art pose estimator based on the vision transformer architecture [1]. It is available in different model sizes, such as Base, Large, Huge, etc. Here, I experiment with the inference time of the VITPose Large model. All experiments are performed on Nvidia A100 Ampere GPU.</p><p>If we pass a single image through the standard VITPose Large model, operating at 32-bit precision, it takes, on average, 17.27 milliseconds to compute the output key points. In terms of throughput, this is 57.9 images processed per second.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*RUczLmUx6vXchwqFfAoQ3Q.jpeg" /></figure><h4>Reducing precision from 32-bit to 16-bit</h4><p>The simplest trick to improve the inference time of a deep learning model is to run it at reduced precision. The default precision in Pytorch is 32 bits; however, reducing it to 16 bits significantly improves the inference time and reduces the model&#39;s memory footprint. The performance degradation going from 32 bits to 16 bits is usually negligible.</p><p>In our case, processing a single image through VITPose Large, at 16-bit precision takes 15.75 milliseconds. Now we are running at 63.5 images/sec.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*vUoees7R0ejhXaYZcmUFtA.jpeg" /></figure><h4>Using Flash Attention</h4><p>Flash attention is a more efficient alternative to the standard attention mechanism [2]. In Pytorch, it only takes a few lines of code to move from standard attention to flash attention as shown below:</p><pre>#Setting up the flags<br>torch.backends.cuda.enable_flash_sdp(True)<br>torch.backends.cuda.enable_math_sdp(False)<br>torch.backends.cuda.enable_mem_efficient_sdp(False)<br><br># Importing flash attention functional<br>from torch.nn.functional import scaled_dot_product_attention<br><br># -- Code snippet from the Attention class<br>if not self.flash_attention:<br>            # standard attention code<br>            q = q * self.scale<br>            attn = (q @ k.transpose(-2, -1))<br><br>            attn = attn.softmax(dim=-1)<br>            attn = self.attn_drop(attn)<br><br>            x = (attn @ v).transpose(1, 2).reshape(B, N, -1)<br>        else:<br>            # flash attention code<br>            out = scaled_dot_product_attention(q, k, v)<br>            x = out.transpose(1, 2).reshape(B, N, -1)</pre><p>With flash attention, the throughput of VITPose Large increases from 63.5 images/sec to 92.51 images/sec.</p><p><em>Note: Instead of setting up the flags, we can run the flash attention code using a context manager as shown below; however, I was facing some issues with TensorRT compile, when using the context manager. Therefore, I defined the flags separately in the code.</em></p><pre>with torch.backends.cuda.sdp_kernel(enable_flash=True, <br>enable_math=False, enable_mem_efficient=False):<br>  # flash attention code<br>  out = scaled_dot_product_attention(q, k, v)<br>  x = out.transpose(1, 2).reshape(B, N, -1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4QEXcmPMJjZLpz27_EJ2zQ.jpeg" /></figure><h4>Compiling using TensorRT</h4><p>By default, Pytorch uses the “eager-mode” for executing the inference code. This can be optimized by compiling the model using Pytorch’s compile method. Pytorch offers several different compilation backends. TensorRT is the backend that has been particularly optimized for Nvidia GPUs. Compiling the model only takes a few lines of code:</p><pre><br>if compile_flag:<br>        # Compile the model<br>        # input shape is (batch_size, channels, height, width)<br>        inputs = [torch.rand(*input_shape, dtype=dtype).cuda()]<br>        exp_pgm = torch_tensorrt.dynamo.trace(model, inputs)<br>        model = torch_tensorrt.dynamo.compile(<br>            exp_pgm,<br>            inputs=inputs,<br>            enabled_precisions={dtype},<br>            min_block_size=1,<br>            debug=False,<br>            immutable_weights=False,<br>            reuse_cached_engines=False,<br>            make_refittable=True,<br>        )</pre><p>With TensorRT compile, we have increased our throughput to 125.6 images/sec.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*7cSpDgXr2Y1MZ5GHF4im5A.jpeg" /></figure><h4>Increasing batch size</h4><p>The final trick we will use is to increase the input batch size to improve inference time per image. Since we run our models on GPUs that are particularly suited for parallel processing, increasing the batch size offers another boost to our throughput. With a batch size of 32, and using all the tricks mentioned before, our final throughput is 194 images/sec.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*6sRdvi1d05hBAsI8d3XTag.jpeg" /></figure><h4>Conclusion</h4><p>We see that simple tricks and small changes in our code can significantly improve the processing time of our deep-learning model. This can prove crucial when deploying models in production.</p><p>We have improved the throughput of a VITPose Large model, from 58 images/sec to 194 images/sec using: reduced precision, flash attention, TensorRT compilation, and a large batch size. All these tricks required only a few lines of code.</p><h4>References</h4><ol><li>Yufei Xu, Jing Zhang, Qiming Zhang, Dacheng Tao. “ViTPose++: Vision Transformer for Generic Body Pose Estimation.” TPAMI 2023.</li><li>Dao, Tri, et al. “Flashattention: Fast and memory-efficient exact attention with io-awareness.” <em>Advances in Neural Information Processing Systems</em> 35 (2022): 16344–16359.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=099b6dfb14f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The lean research team: how to efficiently manage a research team]]></title>
            <link>https://medium.com/@safwan.comsats/the-lean-research-team-how-to-efficiently-manage-a-research-team-8f6528a30320?source=rss-5cc2501937fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f6528a30320</guid>
            <category><![CDATA[research-management]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[management-and-leadership]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Syed Safwan Khalid]]></dc:creator>
            <pubDate>Sat, 10 Aug 2024 09:43:10 GMT</pubDate>
            <atom:updated>2024-08-11T11:22:26.784Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MuvDrajVhUTffSbg3Bo_fQ.jpeg" /></figure><p>It was my last day at work. I had been working as an AI/ML team lead of a small research team in a big company and was now switching to a startup. I had completed all the tasks and waited for some reviews to finish the day. With some free time, I started looking into a small stack of books in the reading room that I could never find time to go through before. One particular book, “The Lean Startup,” caught my eye, and I started skimming through it. It immediately caught my attention as it seemed to suggest a solution to a long-standing problem I had, as a team lead, for the last two years.</p><h3>The problem</h3><p>A problem I had been thinking about for some time but had no satisfactory solution was “How to manage a research team”? More specifically, how to know if my team is working efficiently, and hence I am doing a good job? Let me share two anecdotes to explain this problem:</p><p>In 1939, George Dantzig, a PhD student at California, Berkeley, got late to a class and saw two problems scribbled on the board. Not knowing that these were actually “unsolved” problems in statistics, he mistook them for a home assignment. When he started working, he found those to be harder than usual. Yet, being a good student, he solved both problems and submitted the assignment.</p><p>In 1966, Seymour Papert at MIT AI Labs initiated the Summer Vision project. He encouraged graduate students to develop an object detection and segmentation system, which he believed could take a few months. Even more than half a century later, object detection and segmentation still need to be completely solved.</p><p>The point is, that research tasks are tricky — some could be solved in a few days others might take a few decades and it is nearly impossible to tell which one is which before we start working on them. But this creates a management problem — we would ideally like our objectives and goals to be measurable and time-bound, yet research tasks don&#39;t admit such management terms.</p><p>This also makes it difficult to align a research team with other engineering teams. While standard engineering might use Agile and sprints and quarterly goals; these techniques seem a bit artificial when applied to research teams.</p><h3>The insight</h3><p>The key insight I got from “The Lean Startup” is that startups and research teams share a common problem statement. Here is how Eric Ries defines a startup</p><p>“<em>A human institution designed to create a new product or service under conditions of extreme uncertainty.</em>”</p><p>A research team is the same, i.e., a bunch of people working under extreme uncertainty, trying to figure out how to make a product that nobody knows how to make. Uncertainty is the key component in both endeavors. Hence, similar to an efficient startup,</p><p>“<em>The primary job of a research team is to design and conduct experiments that resolve uncertainties in a project. A lean research team should focus on resolving the uncertainties as quickly as possible.</em>”</p><p>Unlike a standard engineering team, a research team does not develop a product or a feature. Instead, it figures out how to develop a new feature or a product. Therefore, its efficiency should not be judged based on the speed/number of products/features delivered. The actual yardstick for a research team should be how quickly they are moving from unknowns to knowns. Once the uncertainties have been resolved, then a standard engineering effort is required to actually make the product.</p><h3>The Solution</h3><p>Once a research team is given a task, the first thing to do is to make a list of questions (the unknowns). For example, let&#39;s say a team is tasked to make an LLM-based chatbot. Some possible unknows could be:</p><ol><li>Which LLM would satisfy the quality requirements at what cost?</li><li>How to define and measure the quality requirements?</li><li>Do we need any finetuning? Do we need more data?</li><li>What are the legal considerations?</li><li>Do we need our deployment or should we go with a paid API?</li></ol><p>Once all the questions are listed, then the team should sit with the management or the business teams and figure out the priority of each unknown. Finally, they should start designing and conducting experiments to resolve the highest priority uncertainty.</p><p>Under this framework, the management of the research team becomes easier:</p><ol><li>We can measure the efficiency of the team by looking into how quickly they are moving from unknowns to knowns.</li><li>The quarterly goals or the sprint goals can be described in simple terms, such as, “We would resolve uncertainty A in this quarter” or “We would design experiment Alpha to try to resolve uncertainty B in this Sprint” etc.</li><li>The business/management teams and the research team now have a shared language to discuss the progress and priorities of the research effort.</li></ol><h3>To pivot or not to pivot</h3><p>There are many times when a research team would realize, during the research effort, that the task they are working on cannot be completed, given the resource constraints and the quality expectations. This is the time to pivot, change the research direction, or start working on a different problem.</p><p>When setting priorities, it makes sense to first work on those questions that might lead to a pivot. The earlier a team realizes the futility of its current approach, the more quickly it can change directions and hence utilize its time and energies more efficiently.</p><h3>Conclusions</h3><ol><li>Research teams and startups share a common trait, i.e., they both operate under extreme uncertainties.</li><li>A lean research team should focus primarily on doing experiments to find resolve the uncertainties, as quickly as possible.</li><li>The efficiency of a research team can be measured by the speed at which they are moving from unknowns to knowns.</li><li>A lean research team should prioritize the questions that could potentially lead to a pivot.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f6528a30320" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>