<?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 Shivay Lamba on Medium]]></title>
        <description><![CDATA[Stories by Shivay Lamba on Medium]]></description>
        <link>https://medium.com/@shivaylamba?source=rss-af8e6cef0c35------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*A4ZwZKhP0gxMs04dQYEN7w.jpeg</url>
            <title>Stories by Shivay Lamba on Medium</title>
            <link>https://medium.com/@shivaylamba?source=rss-af8e6cef0c35------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:41:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shivaylamba/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[Running Qualcomm GenieX on a Mac with Apple Silicon]]></title>
            <link>https://shivaylamba.medium.com/running-qualcomm-geniex-on-a-mac-with-apple-silicon-7f3fb63c83f7?source=rss-af8e6cef0c35------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f3fb63c83f7</guid>
            <category><![CDATA[ai-on-device]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[genai]]></category>
            <dc:creator><![CDATA[Shivay Lamba]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 15:56:24 GMT</pubDate>
            <atom:updated>2026-10-29T15:56:24.195Z</atom:updated>
            <content:encoded><![CDATA[<h3>A practical guide to trying GenieX through its CPU-only Docker image</h3><p>GenieX is Qualcomm’s on-device inference runtime for LLMs and VLMs. Officially, it supports Snapdragon platforms running Windows ARM64, Android, and Linux ARM64. There is no native macOS build.</p><p>However, you can run it on an Apple Silicon Mac using Qualcomm’s <strong>CPU-only Linux ARM64 Docker image</strong>, which uses GenieX’s llama_cpp runtime.</p><p>I tested this setup on <strong>October 29, 2026</strong>, using:</p><ul><li>An Apple M1 Max</li><li>macOS 26.5</li><li>Docker Desktop 29.2.0</li><li>GenieX CLI v0.10.0</li></ul><p>This setup is useful for exploring the GenieX CLI, pulling models, and running prompts on a Mac. GenieX also includes an API server, although I did not test that part on macOS.</p><p><strong>This is not a Snapdragon performance benchmark.</strong> There is no access to the Qualcomm NPU, Apple GPU, or Metal through this setup. Inference runs entirely on the CPUs allocated to Docker’s Linux VM.</p><h3>1. Prerequisites</h3><p>You’ll need:</p><ul><li><strong>An Apple Silicon Mac:</strong> M1, M2, M3, M4, or later. The image is ARM64-only. Intel Macs would require emulation, which I have not tested.</li><li><strong>Docker Desktop:</strong> Complete its initial setup and approve any required macOS permission prompts.</li><li><strong>Around 3 GB of free disk space:</strong> The image is approximately 190 MB, and the small VLM used below is approximately 1.7 GB. Leave additional space for Docker overhead and downloads.</li><li><strong>At least 8 GB of RAM allocated to Docker:</strong> Adjust this under Docker Desktop → Settings → Resources. Allocating more CPUs can also help.</li></ul><p>Check that Docker is running:</p><pre>docker info | grep -E &#39;Server Version|Architecture|CPUs|Total Memory&#39;</pre><p>The architecture should be aarch64.</p><h3>2. Pull the GenieX CPU image</h3><p>Download the CPU image and check the installed version:</p><pre>docker pull qualcomm/geniex:latest-cpu</pre><pre>docker run --rm qualcomm/geniex:latest-cpu geniex version</pre><p>My test returned:</p><pre>GenieX CLI Version:     v0.10.0<br>QAIRT Runtime Version:<br>LlamaCPP Runtime Hash:  19cce69</pre><p><strong>Use the </strong><strong>latest-cpu tag.</strong> The default latest image expects Qualcomm NPU drivers mounted from the host using -v /usr/lib:/opt/qcom-lib and privileged container access. That setup does not apply to a Mac.</p><p>The latest-cpu tag can change, so your version output may differ.</p><h3>3. Start a persistent container</h3><p>Running commands in one container keeps the configuration and model cache together. The mounted data directory preserves them on your Mac even if you remove the container.</p><p>First, create directories for models, configuration, and input images:</p><pre>mkdir -p ~/geniex/data ~/geniex/img</pre><p>Then start the container:</p><pre>docker run -d --name gx \<br>  -v ~/geniex/data:/data \<br>  -v ~/geniex/img:/img:ro \<br>  -e GENIEX_DATADIR=/data \<br>  -p 18181:18181 \<br>  qualcomm/geniex:latest-cpu sleep infinity</pre><p>Here’s what each mount does:</p><ul><li>/data stores the model cache and GenieX configuration in ~/geniex/data on your Mac.</li><li>/img provides read-only access to images placed in ~/geniex/img.</li><li>-p 18181:18181 exposes the port used by the local server in section 7.</li></ul><h3>4. Configure a chipset</h3><p>GenieX requires a chipset configuration before pulling models.</p><p>Without a terminal attached, its interactive chipset picker fails with:</p><pre>No chipset configured. Please select your chipset first.<br>Error: huh: could not open a new TTY: open /dev/tty: no such device or address</pre><p>Set the chipset explicitly to avoid the interactive picker:</p><pre>docker exec gx geniex config set chipset QCS9075</pre><pre>docker exec gx geniex config list</pre><p>The configuration should include:</p><pre>chipset: QCS9075</pre><p>For this CPU-only workflow, the chipset setting satisfies the configuration requirement. It does not provide access to Qualcomm hardware on the Mac.</p><h3>5. Pull a GGUF model</h3><p>Use a GGUF model compatible with the bundled llama.cpp runtime. Specify both the precision and model type to avoid interactive prompts.</p><p>For this walkthrough, I used <strong>Qwen3-VL-2B-Instruct</strong>, a small vision-language model:</p><pre>docker exec gx geniex pull \<br>  unsloth/Qwen3-VL-2B-Instruct-GGUF:Q4_0 \<br>  --model-type vlm \<br>  --skip-update</pre><p>Check the downloaded model:</p><pre>docker exec gx geniex list --skip-update</pre><p>In my test, the model appeared as:</p><pre>NAME:        unsloth/Qwen3-VL-2B-Instruct-GGUF<br>SIZE:        1.7 GiB<br>PRECISIONS:  Q4_0</pre><p>For a text-only LLM, an example pull command is:</p><pre>docker exec gx geniex pull \<br>  unsloth/Phi-4-mini-instruct-GGUF:Q4_0 \<br>  --model-type llm \<br>  --skip-update</pre><p>For gated models, add a Hugging Face token to the docker run command when creating the container:</p><pre>-e HF_TOKEN=hf_...</pre><p><strong>QAIRT bundles from </strong><strong>ai-hub-models/* will not work in this CPU-only setup.</strong> Those bundles require the appropriate Qualcomm hardware and runtime. Use a compatible GGUF model instead.</p><h3>6. Run inference</h3><p><strong>Always pass </strong><strong>--compute cpu for inference in this setup.</strong> The default compute target is npu, which is unavailable here.</p><h3>Run a text prompt</h3><pre>docker exec gx geniex infer \<br>  unsloth/Qwen3-VL-2B-Instruct-GGUF:Q4_0 \<br>  --compute cpu \<br>  --skip-update \<br>  --think=false \<br>  -p &quot;Explain what an NPU is in two sentences.&quot;</pre><h3>Start an interactive chat</h3><p>Use -it to attach an interactive terminal:</p><pre>docker exec -it gx geniex infer \<br>  unsloth/Qwen3-VL-2B-Instruct-GGUF:Q4_0 \<br>  --compute cpu \<br>  --skip-update</pre><h3>Try object detection with a VLM</h3><p>This workflow uses a vision-language model to generate bounding boxes through prompting. It does not run a dedicated object detector such as YOLO or DETR.</p><p>GenieX detects image paths in the prompt automatically. <strong>Use absolute paths inside the container</strong>, such as /img/street.jpg.</p><p>Download a test image on your Mac:</p><pre>curl -L \<br>  -o ~/geniex/img/street.jpg \<br>  https://raw.githubusercontent.com/ultralytics/assets/main/im/bus.jpg</pre><p>Then ask the model to identify people and vehicles:</p><pre>docker exec gx geniex infer \<br>  unsloth/Qwen3-VL-2B-Instruct-GGUF:Q4_0 \<br>  --compute cpu \<br>  --skip-update \<br>  --think=false \<br>  --temperature 0 \<br>  --max-tokens 400 \<br>  -p &#39;Detect all people and vehicles in this image. Output ONLY a JSON list like [{&quot;label&quot;:&quot;person&quot;,&quot;bbox_2d&quot;:[x1,y1,x2,y2]}] with coordinates on a 0-1000 scale. Image: /img/street.jpg&#39;</pre><p>Here is the output from my test run:</p><pre>[<br>  {&quot;label&quot;: &quot;person&quot;, &quot;bbox_2d&quot;: [59, 368, 306, 834]},<br>  {&quot;label&quot;: &quot;person&quot;, &quot;bbox_2d&quot;: [279, 378, 422, 800]},<br>  {&quot;label&quot;: &quot;person&quot;, &quot;bbox_2d&quot;: [826, 361, 1000, 817]},<br>  {&quot;label&quot;: &quot;person&quot;, &quot;bbox_2d&quot;: [0, 515, 94, 808]},<br>  {&quot;label&quot;: &quot;vehicle&quot;, &quot;bbox_2d&quot;: [0, 215, 992, 680]}<br>]</pre><p>The CLI reported:</p><pre>13.5 tok/s • 196 tok • 104.6 s first token</pre><h3>Draw the bounding boxes on your Mac</h3><p>The prompt requests coordinates on a 0–1000 scale. Convert those coordinates to pixels using the image width and height.</p><p>Install Pillow:</p><pre>python3 -m pip install pillow</pre><p>Save the following script as draw.py:</p><pre>import json<br>import sys</pre><pre>from PIL import Image, ImageDraw</pre><pre>img_path = sys.argv[1]<br>detections = json.loads(sys.argv[2])</pre><pre>image = Image.open(img_path).convert(&quot;RGB&quot;)<br>width, height = image.size<br>draw = ImageDraw.Draw(image)</pre><pre>for detection in detections:<br>    x1, y1, x2, y2 = (<br>        value / 1000 * dimension<br>        for value, dimension in zip(<br>            detection[&quot;bbox_2d&quot;],<br>            [width, height, width, height],<br>        )<br>    )</pre><pre>    draw.rectangle(<br>        [x1, y1, x2, y2],<br>        outline=&quot;red&quot;,<br>        width=5,<br>    )</pre><pre>    draw.text(<br>        (x1 + 6, y1 + 6),<br>        detection[&quot;label&quot;],<br>        fill=&quot;red&quot;,<br>    )</pre><pre>image.save(&quot;detections.jpg&quot;)</pre><p>Run it with a detection list:</p><pre>python3 draw.py ~/geniex/img/street.jpg \<br>  &#39;[{&quot;label&quot;:&quot;person&quot;,&quot;bbox_2d&quot;:[59,368,306,834]}]&#39;</pre><pre>open detections.jpg</pre><p>Replace the sample JSON with the full list to draw all detected boxes.</p><h3>7. Local OpenAI-compatible server</h3><p><strong>I did not test this section on the Mac.</strong> These commands follow the GenieX documentation and are included as a starting point.</p><p>GenieX includes an OpenAI-compatible server on port 18181.</p><p>Before starting it, inspect the available options:</p><pre>docker exec gx geniex serve --help</pre><p>Check how to configure the listening address and select CPU inference. To reach the server through Docker’s published port, it must listen on 0.0.0.0 inside the container.</p><p>The documented basic startup command is:</p><pre>docker exec -d gx geniex serve --skip-update</pre><p>An example chat-completions request is:</p><pre>curl http://127.0.0.1:18181/v1/chat/completions \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;model&quot;: &quot;unsloth/Qwen3-VL-2B-Instruct-GGUF:Q4_0&quot;,<br>    &quot;messages&quot;: [<br>      {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: [<br>          {<br>            &quot;type&quot;: &quot;text&quot;,<br>            &quot;text&quot;: &quot;What objects are in this image?&quot;<br>          },<br>          {<br>            &quot;type&quot;: &quot;image_url&quot;,<br>            &quot;image_url&quot;: {<br>              &quot;url&quot;: &quot;/img/street.jpg&quot;<br>            }<br>          }<br>        ]<br>      }<br>    ]<br>  }&#39;</pre><p>The server’s CPU configuration and support for a container-local image path in this request still need to be verified on macOS.</p><h3>8. Performance on an M1 Max</h3><p>My test used Docker with <strong>4 vCPUs and 15.6 GB of memory</strong>.</p><p>For Qwen3-VL-2B at Q4_0 precision, processing an <strong>810 × 1080 image</strong> with the detection prompt produced:</p><ul><li><strong>Time to first token:</strong> approximately 105 seconds</li><li><strong>Generation speed:</strong> 13.5 tokens per second</li><li><strong>Generated tokens:</strong> 196</li></ul><p>The long first-token delay is consistent with the cost of processing an image on CPU, although I did not profile the individual inference stages.</p><p>To try improving performance, allocate more CPUs to Docker or use smaller input images.</p><p>For Snapdragon performance testing, run on actual supported hardware with an appropriate model and compute target, such as --compute npu or hybrid.</p><p><a href="https://qdc.qualcomm.com/">Qualcomm Device Cloud</a> provides access to remote Snapdragon devices.</p><h3>9. Troubleshooting</h3><h3>Docker cannot connect to the daemon</h3><p>If you see an error mentioning docker.sock, open Docker Desktop and wait for it to finish starting. Complete any pending permission prompts.</p><h3>“No chipset configured” or “could not open a new TTY”</h3><p>Set the chipset explicitly:</p><pre>docker exec gx geniex config set chipset QCS9075</pre><h3>Model pulls trigger interactive prompts</h3><p>Include a precision suffix such as :Q4_0 and specify either --model-type llm or --model-type vlm.</p><h3>Inference fails or hangs during loading</h3><p>Confirm that the inference command includes:</p><pre>--compute cpu</pre><p>The default NPU path is unavailable in this Mac setup.</p><h3>Models from ai-hub-models/* fail</h3><p>Those QAIRT bundles require Qualcomm hardware. Use a compatible GGUF model for the CPU runtime.</p><h3>The image is not recognised</h3><p>Use an absolute path inside the container:</p><pre>/img/street.jpg</pre><p>A Mac path such as ~/geniex/img/street.jpg is not the path visible to GenieX inside Docker.</p><h3>Inference is slow</h3><p>CPU inference, especially image processing, can be slow. Try increasing Docker’s CPU allocation, reducing image dimensions, or choosing a smaller quantized model.</p><h3>10. Cleanup</h3><p>To remove the downloaded model:</p><pre>docker exec gx geniex remove \<br>  unsloth/Qwen3-VL-2B-Instruct-GGUF</pre><p>To remove all cached models, use geniex clean instead.</p><p>Remove the container and Docker image:</p><pre>docker rm -f gx</pre><pre>docker rmi qualcomm/geniex:latest-cpu</pre><p>If you also want to delete the local model cache, configuration, and input images, remove the working directory:</p><pre>rm -rf ~/geniex</pre><h3>References</h3><ul><li><a href="https://geniex.aihub.qualcomm.com/en/get-started/what-is-geniex">GenieX overview</a></li><li><a href="https://geniex.aihub.qualcomm.com/en/get-started/platforms">Supported platforms and runtimes</a></li><li><a href="https://geniex.aihub.qualcomm.com/en/run/linux/install">Linux Docker installation</a></li><li><a href="https://geniex.aihub.qualcomm.com/en/models/supported">Supported models</a></li><li><a href="https://hub.docker.com/r/qualcomm/geniex">GenieX on Docker Hub</a></li><li><a href="https://github.com/qualcomm/GenieX">GenieX on GitHub</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f3fb63c83f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a QMX-Accelerated Gemma Chat App on the Galaxy S26 Ultra]]></title>
            <link>https://shivaylamba.medium.com/from-a-build-flag-to-proof-building-a-qmx-accelerated-gemma-chat-app-on-the-galaxy-s26-ultra-b2ff9f1676e9?source=rss-af8e6cef0c35------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2ff9f1676e9</guid>
            <dc:creator><![CDATA[Shivay Lamba]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 20:57:08 GMT</pubDate>
            <atom:updated>2026-08-19T20:57:46.568Z</atom:updated>
            <content:encoded><![CDATA[<p>On-device LLM demos often stop at a terminal benchmark. I wanted something closer to a product: a Kotlin chat app that could import a GGUF model, stream responses, remember follow-up questions, stay usable when the keyboard opened, and prove that inference was actually running on the CPU’s Qualcomm Matrix Extension (QMX) path.</p><p>The target was a Samsung Galaxy S26 Ultra (`SM-S948B`, Qualcomm `SM8850`). The first model was Gemma 4 E2B Instruct Q8_0; later, I added the Gemma 3 4B Q8_0 model linked as “Gemma 4B” in <a href="https://www.qualcomm.com/developer/blog/2026/04/llama-models-acceleration-on-cpu-qmx">Qualcomm’s QMX article </a>so I could make a closer benchmark comparison.</p><p>The finished sample, build instructions, and benchmark notes are available in the <a href="https://github.com/shivaylamba/qmx-gemma4-samsungs26ultra">qmx-gemma4-samsungs26ultra repository.</a></p><h3>QMX is CPU acceleration, not an NPU backend</h3><p>QMX is a matrix-multiplication capability in the CPU. It is compatible with Arm Scalable Matrix Extension (SME) instructions and is designed to accelerate operations such as the GEMM and GEMV kernels that dominate transformer inference. In our stack, [llama.cpp](<a href="https://github.com/ggml-org/llama.cpp">https://github.com/ggml-org/llama.cpp</a>) calls optimized kernels supplied through [KleidiAI](<a href="https://github.com/ARM-software/kleidiai">https://github.com/ARM-software/kleidiai</a>), which selects an SME implementation when the binary, runtime setting, and CPU capabilities all agree.</p><p>The application path looks like this:</p><p>Kotlin chat UI<br> ↓<br>JNI inference wrapper<br> ↓<br>llama.cpp / ggml CPU backend<br> ↓<br>KleidiAI Q8 SME kernels<br> ↓<br>QMX-capable CPU</p><p>There is no QNN, Vulkan, OpenCL, GPU, or NPU inference backend in the APK. That distinction matters: a phone can contain several accelerators, but this project is specifically about accelerating CPU execution.</p><h3>Building an app</h3><p>Qualcomm’s article gives the essential native recipe: use Android NDK r28b, enable `GGML_CPU_KLEIDIAI`, compile for Armv9.2 with SME-related features, set `GGML_KLEIDIAI_SME=1`, and run llama.cpp’s benchmark. That is a useful hardware and performance starting point. Turning it into a usable Android application adds another layer of engineering.</p><p>The sample uses a Kotlin activity for model selection and chat, a small JNI boundary, and a native inference engine built around llama.cpp. The model is imported through Android’s document picker and copied into private app storage rather than bundled in the APK. The native layer keeps a 2,048-token context, preserves the conversation and KV cache between turns, formats messages using the model’s chat template, and streams generated text back to Kotlin.</p><h3>How the app asks for QMX</h3><p>The native runtime must choose its kernel before model initialization, so the app sets the documented environment switch before loading the inference library:</p><pre>val qmxMode = intent.getStringExtra(&quot;qmx_mode&quot;) ?: &quot;1&quot;<br>Os.setenv(&quot;GGML_KLEIDIAI_SME&quot;, qmxMode, true)</pre><p>The CMake build enables the KleidiAI CPU integration for `arm64-v8a`:</p><pre>set(GGML_SYSTEM_ARCH &quot;ARM&quot;)<br>set(GGML_CPU_KLEIDIAI ON)</pre><p>That still does not mean every model tensor automatically uses a QMX-optimized buffer. KleidiAI repacks supported quantized weights into a CPU buffer suited to its kernels. In this app, `QMX_ACCELERATED_LAYERS` controls how many leading transformer blocks are assigned to the regular CPU buffer type and therefore become eligible for KleidiAI repacking. Other tensors remain memory-mapped and execute through the regular llama.cpp Arm CPU kernels.</p><p>This is why “six QMX layers” does not mean the other layers run on the GPU or NPU. All layers run on the CPU; the difference is which CPU kernel and weight layout they use.</p><h3>Proving that QMX is executing</h3><p>My first lesson was that a green badge based on a requested flag would prove almost nothing. The app reports <strong>QMX ACTIVE</strong> only after it observes all three of these native runtime signals:</p><pre>kleidiai: primary q8 kernel feature SME<br>kleidiai: SME enabled<br>load_tensors: CPU_KLEIDIAI model buffer size = 430.27 MiB</pre><p>Together, these show that KleidiAI selected an SME Q8 kernel, enabled SME, and actually repacked model weights into its buffer. The APK inspection provides a second line of evidence: it contains the CPU variants, llama.cpp, and `libkleidiai.so`, with none of the GPU/NPU backends mentioned earlier.</p><p>For a clean verification run:</p><pre>adb shell am force-stop com.example.qmxgemma<br>adb logcat -c<br>adb shell am start -n com.example.qmxgemma/.MainActivity<br>adb logcat -s ai-chat:I InferenceEngineImpl:I QmxGemma:I</pre><p>This runtime evidence is more reliable than inferring execution from build options. A feature can compile successfully yet fall back at runtime, or fail only when the first incompatible instruction executes.</p><h3>The memory cost nobody sees in a speedup chart</h3><p>Q8 weights are already large, and KleidiAI’s optimized representation is an additional allocation rather than a free replacement for the mapped model. The Android process also contains the Kotlin UI, JNI/native runtime, and a persistent chat context. Increasing the number of repacked layers therefore increases peak memory quickly.</p><p>For Gemma 4 E2B, the conservative app default repacks 6 of 35 blocks, producing a 430.27 MiB `CPU_KLEIDIAI` buffer. For Gemma 3 4B, the same six-block setting consumes 1,084.08 MiB. The rest of each model remains mapped and still executes on the CPU, just outside the QMX-repacked path.</p><p>I probed Gemma 3 in two-layer increments. Settings from 6 through 20 loaded successfully. Twenty of 34 blocks was the highest repeatably benchmarkable placement and used a 3,613.60 MiB KleidiAI buffer. Twenty-one blocks loaded and completed a short test once, but Android’s low-memory manager killed a later fresh load. Twenty-two blocks, at 3,974.96 MiB, was consistently killed before context initialization.</p><p>The practical answer was to keep six layers as the safe interactive default and use 20 layers only for controlled benchmarking. A dedicated benchmark process without a live chat context could likely reclaim enough memory to go further.</p><h3>The benchmark trap: “SME off” was not NEON</h3><p>The app includes an ADB-triggered harness with 128 prompt tokens, 128 generated tokens, one sequence, and explicit one- or four-thread contexts. Each mode runs in a fresh process because KleidiAI selects kernels during initialization.</p><p>Our first A/B test changed only this value:</p><pre>GGML_KLEIDIAI_SME=1 → SME/QMX<br>GGML_KLEIDIAI_SME=0 → non-SME</pre><p>The result looked disappointing. With only six Gemma 3 blocks repacked, one-thread prefill improved by 1.012× and decode by 1.074×. Four-thread results were effectively flat. Gemma 4 E2B was similarly close at 1.006× prefill and 1.027× decode.</p><p>The logs explained why: the supposed baseline selected KleidiAI’s optimized I8MM Q8 kernel. It was a valid non-SME comparison, but it was not the generic NEON-only baseline described in Qualcomm’s methodology. We were comparing one optimized CPU path against another while accelerating only a fraction of the model.</p><p>To create a real control, I built a second APK from the same source revision and benchmark harness with `-march=armv8-a`, `GGML_CPU_KLEIDIAI=OFF`, and `GGML_CPU_ALL_VARIANTS=OFF`. It packaged one generic CPU library, emitted no KleidiAI selection, and allocated no `CPU_KLEIDIAI` buffer. The QMX build used the same model and harness with 20 of 34 Gemma 3 blocks repacked.</p><h3>Results: Gemma 3 4B Q8_0, QMX versus generic NEON</h3><p>Both builds ran six trials per mode on the same phone with Android fixed-performance mode enabled. The first run was discarded as warm-up. Context size was 256 for the isolated test, batch and micro-batch were 128, Flash Attention resolved on, and thread count was held constant across each pair.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TF3U4KInKh9GJS3hMpRZfw.png" /></figure><p>These results finally showed the expected shape: the biggest gains appear during compute-heavy prefill, while decode improves less because it is more constrained by memory traffic. That matches Qualcomm’s explanation of why matrix acceleration helps GEMM-dominated prefill more than the GEMV- and bandwidth-heavy decode phase.</p><p>The numbers need two qualifications. First, our prefill ratio is calculated from fixed-prompt processing throughput, so it is a useful TTFT compute proxy rather than an end-to-end measurement from UI submission to first visible token. Second, one warmed one-thread QMX decode trial fell to 4.848 tok/s while the other warmed trials clustered between 8.030 and 8.046 tok/s. Keeping that outlier produces the conservative 1.571× result above; excluding it would produce 1.706×.</p><h3>How this compares with Qualcomm’s published results</h3><p>For Q8 models, Qualcomm reports maximum speedups of 2.9× TTFT and 1.5× decode with one thread, and 2.0× TTFT and 1.05× decode with four threads. Their tests used 128-token prompts and 128-token decode, fixed CPU frequencies, and a NEON-only baseline on the Snapdragon 8 Elite Gen 5 Mobile platform.</p><p>Our closest matched Gemma 3 experiment reaches 2.017×/1.571× with one thread and 2.356×/1.164× with four. That is encouraging, but it is not an apples-to-apples reproduction. Only 20 of 34 blocks used the QMX-repacked buffer, the app used Android’s fixed-performance mode rather than Qualcomm’s stated per-cluster frequency locks, and our prefill metric is not full TTFT. The four-thread series also warmed the phone from roughly 34 °C to 39 °C and showed late thermal decline.</p><p>The correct conclusion is not that our build “beats” or “loses to” Qualcomm’s. It is that QMX is demonstrably executing, provides a large advantage over a genuine generic-NEON control, and follows the same prefill-versus-decode pattern. Reproducing exact laboratory numbers requires the same source dependency graph, CPU affinity, frequency controls, thermal state, model file, tensor placement, and metric definition.</p><h3>What failed and what it taught us</h3><p>I also tried the exact llama.cpp commit pinned in Qualcomm’s article, built with NDK r28b, Android API 29, KleidiAI, and the documented Armv9.2/SME flags. Its non-SME run repacked all 34 Gemma 3 blocks, but still selected KleidiAI I8MM rather than a plain NEON baseline. Its QMX run repacked the full model and then terminated with `SIGILL` inside `libggml-cpu.so`.</p><p>The device reports base SME but not SME2. In that older source combination, the Q8 path selected SME2-named kernels from a base-SME feature check. The newer llama.cpp/KleidiAI revision pinned by this app takes a base-SME-compatible path and works. This is exactly why native dependency revisions must be pinned together and validated on the target device.</p><p>Trying the article’s very large `-b 2048 -ub 512` settings with a full model also triggered heavy paging on this app/device setup. Once the process is swapping gigabytes, the measurement describes storage pressure more than matrix compute. Bigger buffers are not automatically better on Android.</p><h3>Reproduce the app</h3><p>The repository pins the native dependency and includes an idempotent setup script:</p><pre>git clone - recurse-submodules https://github.com/shivaylamba/qmx-gemma4-samsungs26ultra.git<br>cd qmx-gemma4-samsungs26ultra<br>powershell -ExecutionPolicy Bypass -File .\scripts\setup.ps1<br>$env:JAVA_HOME = &quot;C:\path\to\jdk-21&quot;<br>.\gradlew.bat :app:assembleDebug :app:lintDebug<br>adb install -r .\app\build\outputs\apk\debug\app-debug.apk</pre><p>Open the app, choose a supported Q8_0 GGUF, wait for the native load to finish, and confirm that the badge reports **QMX ACTIVE**. The complete README contains the tested model hashes, exact ADB benchmark commands, layer-control option, and power-setting cleanup commands.</p><h3>Takeaways</h3><p>The most valuable part of this project was not getting a large speedup number. It was learning how to make that number defensible.</p><p>- QMX acceleration happens on the CPU through SME-compatible KleidiAI kernels; it is not QNN or NPU execution.<br>- A build flag requests a path. Kernel-selection logs plus a non-zero repacked buffer prove that the path actually ran.<br>- `GGML_KLEIDIAI_SME=0` can still select an optimized I8MM KleidiAI kernel, so it should not automatically be labeled “NEON baseline.”<br>- Partial layer repacking is a useful compromise for an interactive Android app, but memory policy can prevent full-model QMX placement even when the hardware supports it.<br>- Prefill benefits more than decode because the former is compute-bound and the latter quickly becomes memory-bound.<br>- Mobile benchmarks need fresh processes, warm-up handling, thermal reporting, identical model files, and explicit metric definitions.</p><p>The next step is to split interactive inference and laboratory benchmarking into separate native processes, measure actual first-visible-token latency from the UI, and test whether a smaller context or Q4 path can increase QMX coverage without introducing instruction-set compatibility issues.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2ff9f1676e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Gemma 4 E2B with llama.cpp on the Snapdragon Hexagon NPU]]></title>
            <link>https://shivaylamba.medium.com/running-gemma-4-e2b-with-llama-cpp-on-the-snapdragon-hexagon-npu-a5d970e3350e?source=rss-af8e6cef0c35------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5d970e3350e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[gemma-4]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llama-cpp]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <dc:creator><![CDATA[Shivay Lamba]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 22:24:26 GMT</pubDate>
            <atom:updated>2026-06-24T22:24:26.343Z</atom:updated>
            <content:encoded><![CDATA[<p>On modern Snapdragon Windows machines, the interesting question is not whether you can run a model. You can. The more useful question is whether you can run it through the right acceleration stack, observe what is happening, and build a repeatable workflow that does not collapse every time you swap models.</p><p>In this blog we showcase Gemma 4 E2B running with llama.cpp on a<br>Snapdragon X Elite Windows machine, targeting Qualcomm&#39;s Hexagon NPU through the experimental Snapdragon backend in ggml.</p><p>The end result is a local browser chat UI backed by:</p><pre>Browser UI<br>  -&gt; llama-server OpenAI-compatible API<br>  -&gt; llama.cpp<br>  -&gt; ggml<br>  -&gt; ggml Hexagon backend<br>  -&gt; Qualcomm HTP / Hexagon NPU device HTP0</pre><p>The model we tested:</p><pre>gemma-4-E2B-it-Q8_0.gguf</pre><p>The runtime:</p><pre>llama-server.exe</pre><p>The target accelerator:</p><pre>HTP0 : Hexagon</pre><p>And the important lesson:</p><p>The browser does not talk to the NPU. llama.cpp does not really &quot;talk to the<br>NPU&quot; directly either. The request travels through a stack of runtime layers,<br>and each layer has its own failure modes.</p><p>Understanding those layers is the difference between “it runs on my machine” and “I can explain, debug, and reproduce it.”</p><h3>Why Gemma 4 E2B?</h3><p>Google’s Gemma llama.cpp integration docs point to the official GGUF repository:</p><pre>ggml-org/gemma-4-E2B-it-GGUF</pre><p>Their quick-start path is intentionally simple:</p><pre>llama-cli -hf ggml-org/gemma-4-E2B-it-GGUF --prompt &quot;Write a poem about the Kraken.&quot;</pre><p>or:</p><pre>llama-server -hf ggml-org/gemma-4-E2B-it-GGUF</pre><p>That is the nice path.</p><p>On our Snapdragon Windows build, there was one practical wrinkle: the localllama.cpp binary had Hugging Face flags such as -hf, but it had not been built with HTTPS support for the internal downloader. So the -hf command failed with:</p><pre>HTTPS is not supported. Please rebuild with one of:<br>  -DLLAMA_BUILD_BORINGSSL=ON<br>  -DLLAMA_BUILD_LIBRESSL=ON<br>  -DLLAMA_OPENSSL=ON</pre><p>That does not prevent Gemma from running. It only means we download the GGUF with curl.exe and pass the local file path to llama.cpp.</p><h3>The Hardware And Software Stack</h3><p>The machine used for this test was a Snapdragon X Elite Windows PC.</p><p>At runtime, llama.cpp detected three relevant devices:</p><pre>GPUOpenCL: Qualcomm(R) Adreno(TM) X1-85 GPU<br>HTP0    : Hexagon<br>CPU     : Snapdragon(R) X Elite - Qualcomm(R) Oryon(TM) CPU</pre><p>The important device is HTP0.</p><p>In llama.cpp’s Snapdragon backend, the Hexagon NPU behaves like an offload device. That means it is selected with the same kind of flags you would use for GPU offload:</p><pre>--device HTP0 -ngl 99</pre><p>--device HTP0 selects the Hexagon NPU device.</p><p>-ngl 99 asks llama.cpp to offload as many model layers as possible to the<br>selected accelerator backend.</p><p>Under the hood, the stack looks like this:</p><pre>Prompt<br>  -&gt; Browser chat UI<br>  -&gt; fetch(&quot;/v1/chat/completions&quot;, stream: true)<br>  -&gt; llama-server.exe<br>  -&gt; llama.cpp model runtime<br>  -&gt; ggml compute graph<br>  -&gt; ggml Hexagon backend<br>  -&gt; libggml-htp-v73.so<br>  -&gt; Qualcomm HTP / Hexagon NPU</pre><p>One of the biggest misconceptions with on-device AI is that the app somehow calls the NPU directly.</p><p>It does not.</p><p>The app calls a local HTTP API. The HTTP API is served by llama-server. The server uses llama.cpp. llama.cpp builds a graph in ggml. The ggml backend scheduler places supported operations on the Hexagon backend. The Hexagon backend loads HTP-side libraries and dispatches supported compute to the NPU.</p><p>When something breaks, it is usually at one of those boundaries.</p><h3>Prerequisites For Windows On Snapdragon</h3><p>The upstream Snapdragon backend guide lists the native Windows ARM64 dependency set:</p><ul><li>Visual Studio 2026 Community or Pro</li><li>MSVC ARM64 libraries</li><li>UCRT and Driver Kit</li><li>LLVM core libraries and Clang</li><li>CMake, Git, and Python</li><li>Qualcomm OpenCL SDK 2.3 or later</li><li>Qualcomm Hexagon SDK Community Edition 6.6 or later</li><li>Latest Adreno GPU driver</li><li>Latest Qualcomm NPU/HND driver</li></ul><p>The tested local install used:</p><pre>C:\Qualcomm\OpenCL_SDK\2.3.2<br>C:\Qualcomm\Hexagon_SDK\6.6.0.0</pre><p>You should also confirm that Windows sees the NPU.</p><p>Depending on the driver and Windows build, one useful PowerShell check is:</p><pre>Get-PnpDevice -Class ComputeAccelerator</pre><p>The device we wanted to see was:</p><pre>Snapdragon(R) X Elite - X1E80100 - Qualcomm(R) Hexagon(TM) NPU</pre><p>The upstream Windows notes also call out Device Manager’s Neural Processors section. If no Qualcomm Hexagon NPU appears anywhere, do not debug llama.cpp yet. Fix the driver first.</p><h3>Why Signing Matters On Windows</h3><p>The Hexagon backend needs HTP ops libraries such as:</p><pre>libggml-htp-v73.so</pre><p>On Windows, these HTP-side libraries need to be included in a catalog file:</p><pre>libggml-htp.cat</pre><p>That catalog must be signed with a trusted certificate. This is specific to the<br>Hexagon NPU path. The Adreno OpenCL backend does not require this test-signing flow.</p><p>The upstream flow is:</p><ol><li>Enable Windows test-signing.</li><li>Reboot.</li><li>Create a personal certificate.</li><li>Import it into Trusted Root Certification Authorities.</li><li>Import it into Trusted Publishers.</li><li>Build/install llama.cpp so the HTP catalog is generated and signed.</li><li>Verify the catalog with signtool.</li></ol><p>Enable test-signing:</p><pre>bcdedit /set TESTSIGNING ON</pre><p>After reboot:</p><pre>bcdedit /enum</pre><p>You want:</p><pre>testsigning             Yes</pre><p>Create the certificate with Windows SDK tools:</p><pre>cd C:\Users\Admin<br>mkdir Certs<br>cd Certs</pre><pre>makecert -r -pe -ss PrivateCertStore -n CN=GGML.HTP.v1 -eku 1.3.6.1.5.5.7.3.3 -sv ggml-htp-v1.pvk ggml-htp-v1.cer<br>pvk2pfx.exe -pvk ggml-htp-v1.pvk -spc ggml-htp-v1.cer -pfx ggml-htp-v1.pfx</pre><p>Then import the resulting certificate into:</p><pre>Trusted Root Certification Authorities<br>Trusted Publishers</pre><p>After the build, verify:</p><pre>signtool.exe verify /v /pa .\pkg-snapdragon\lib\libggml-htp.cat</pre><p>You want:</p><pre>Successfully verified: .\pkg-snapdragon\lib\libggml-htp.cat</pre><p>If this piece is wrong, the backend can build but the runtime will fail when it tries to load HTP ops.</p><h3>Building llama.cpp With CPU, OpenCL, And Hexagon</h3><p>The Snapdragon backend guide uses CMake presets.</p><p>For Windows on Snapdragon, start from a native ARM64 PowerShell session. That detail matters. If you build from an x64 emulated shell, you are inviting weird toolchain behavior.</p><p>Set the Qualcomm and signing environment:</p><pre>$env:OPENCL_SDK_ROOT=&quot;C:\Qualcomm\OpenCL_SDK\2.3.2&quot;<br>$env:HEXAGON_SDK_ROOT=&quot;C:\Qualcomm\Hexagon_SDK\6.6.0.0&quot;<br>$env:HEXAGON_TOOLS_ROOT=&quot;C:\Qualcomm\Hexagon_SDK\6.6.0.0\tools\HEXAGON_Tools\19.0.07&quot;<br>$env:HEXAGON_HTP_CERT=&quot;C:\Users\Admin\Certs\ggml-htp-v1.pfx&quot;<br>$env:WINDOWS_SDK_BIN=&quot;C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0&quot;</pre><p>Copy the Snapdragon CMake user presets:</p><pre>Copy-Item docs\backend\snapdragon\CMakeUserPresets.json .</pre><p>Configure:</p><pre>cmake --preset arm64-windows-snapdragon-release -B build-wos</pre><p>Build:</p><pre>cmake --build build-wos --config Release</pre><p>Install into a portable package folder:</p><pre>cmake --install build-wos --prefix pkg-snapdragon</pre><p>The installed package should contain files like:</p><pre>pkg-snapdragon\bin\llama-server.exe<br>pkg-snapdragon\bin\llama-cli.exe<br>pkg-snapdragon\bin\ggml-hexagon.dll<br>pkg-snapdragon\lib\libggml-htp-v73.so<br>pkg-snapdragon\lib\libggml-htp.cat</pre><p>This package is what we run from the browser chat example.</p><h3>Sanity Testing The Hexagon Backend</h3><p>Before involving Gemma, the server, or a browser UI, test the backend directly.</p><p>The upstream guide shows test-backend-ops for MUL_MAT. On Windows, run:</p><pre>$env:Path = &quot;C:\Users\Admin\Documents\llamacpp\pkg-snapdragon\bin;$env:Path&quot;<br>$env:ADSP_LIBRARY_PATH = &quot;C:\Users\Admin\Documents\llamacpp\pkg-snapdragon\lib&quot;</pre><pre>.\pkg-snapdragon\bin\test-backend-ops.exe -b HTP0 -o MUL_MAT</pre><p>Useful signs:</p><pre>Backend 2/3: HTP0<br>Device description: Hexagon<br>MUL_MAT(...): OK</pre><p>This matters because language model failures can be caused by model format, prompt template, server options, or frontend parsing. Backend op tests remove most of that noise.</p><h3>Downloading Gemma 4 E2B GGUF</h3><p>The official Gemma llama.cpp integration points to:</p><pre>ggml-org/gemma-4-E2B-it-GGUF</pre><p>At the time of this test, the repo exposed:</p><pre>gemma-4-E2B-it-Q8_0.gguf<br>gemma-4-E2B-it-bf16.gguf<br>mmproj-gemma-4-E2B-it-Q8_0.gguf<br>mmproj-gemma-4-E2B-it-bf16.gguf</pre><p>For this text-only test, we used:</p><pre>gemma-4-E2B-it-Q8_0.gguf</pre><p>The file is large:</p><pre>4,967,494,592 bytes<br>about 4.63 GiB</pre><p>Create a model directory:</p><pre>mkdir gguf</pre><p>Download:</p><pre>curl.exe -L --fail --progress-bar `<br>  -o gguf\gemma-4-E2B-it-Q8_0.gguf `<br>  &quot;https://huggingface.co/ggml-org/gemma-4-E2B-it-GGUF/resolve/main/gemma-4-E2B-it-Q8_0.gguf?download=true&quot;</pre><h3>First Direct CLI Test</h3><p>Before starting a server, run the model once through llama-cli.</p><pre>$env:Path = &quot;C:\Users\Admin\Documents\llamacpp\pkg-snapdragon\bin;$env:Path&quot;<br>$env:ADSP_LIBRARY_PATH = &quot;C:\Users\Admin\Documents\llamacpp\pkg-snapdragon\lib&quot;</pre><pre>.\pkg-snapdragon\bin\llama-cli.exe `<br>  -m .\gguf\gemma-4-E2B-it-Q8_0.gguf `<br>  --device HTP0 `<br>  -ngl 99 `<br>  --no-mmap `<br>  --ctx-size 1024 `<br>  -n 32 `<br>  -p &quot;Write one short sentence confirming Gemma is running.&quot;</pre><p>This verified that the model could load and begin generating on the same<br>Snapdragon package.</p><h3>Starting A Local Browser Chat UI</h3><p>The repository for this example contains a tiny browser frontend:</p><pre>npu-chat\index.html<br>npu-chat\styles.css<br>npu-chat\app.js</pre><p>The page is served byllama-server itself.</p><p>The launcher:</p><pre>start-npu-chat.ps1</pre><p>sets the runtime paths and starts:</p><pre>.\pkg-snapdragon\bin\llama-server.exe `<br>  -m .\gguf\gemma-4-E2B-it-Q8_0.gguf `<br>  -a snapdragon-npu `<br>  --host 127.0.0.1 `<br>  --port 8080 `<br>  --path .\npu-chat `<br>  --no-mmap `<br>  --poll 1000 `<br>  -t 6 `<br>  --ctx-size 1024 `<br>  --ubatch-size 128 `<br>  -fa on `<br>  -ngl 99 `<br>  --device HTP0</pre><p>The short version:</p><pre>.\start-npu-chat.ps1 -Model &quot;gemma-4-E2B-it-Q8_0.gguf&quot;</pre><p>Then open:</p><pre>http://127.0.0.1:8080/</pre><p>The same llama-server process now serves both:</p><pre>http://127.0.0.1:8080/<br>http://127.0.0.1:8080/v1/chat/completions</pre><p>That keeps the example simple. The browser UI and inference API are same-origin, so there is no CORS dance and no separate dev server.</p><h3>Proving The NPU Path</h3><p>After starting the server, inspect:</p><pre>.\logs\npu-chat-server.err.log</pre><p>Useful command:</p><pre>Select-String .\logs\npu-chat-server.err.log `<br>  -Pattern &quot;HTP0|Hexagon|loading model|prompt eval time|eval time|server is listening&quot;</pre><p>For the Gemma run, the important lines were:</p><pre>HTP0    : Hexagon<br>loading model &#39;C:\Users\Admin\Documents\llamacpp\gguf\gemma-4-E2B-it-Q8_0.gguf&#39;<br>server is listening on http://127.0.0.1:8080</pre><p>And after requests:</p><pre>prompt eval time = 1154.47 ms / 23 tokens<br>eval time        = 1470.63 ms / 6 tokens</pre><p>The direct server /props endpoint also confirmed the model:</p><pre>Invoke-RestMethod -Uri http://127.0.0.1:8080/props |<br>  Select-Object model_alias, model_path, build_info</pre><p>Output:</p><pre>model_alias: snapdragon-npu<br>model_path : C:\Users\Admin\Documents\llamacpp\gguf\gemma-4-E2B-it-Q8_0.gguf<br>build_info : b1-a3900a6</pre><h3>Performance Notes</h3><p>Gemma 4 E2B Q8_0 worked, but it was not fast.</p><p>Observed on the tested Snapdragon X Elite machine:</p><pre>prompt eval: about 20 tokens/sec<br>generation: about 4 tokens/sec</pre><p>A short server request reported:</p><pre>prompt eval time = 1154.47 ms / 23 tokens<br>eval time        = 1470.63 ms / 6 tokens</pre><p>The conclusion is that model size, quantization, backend support, and prompt behavior all matter. For a fast demo, Qwen 0.5B Q4 is much more pleasant. For testing the official Gemma llama.cpp path, Gemma 4 E2B Q8_0 is the right target.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5d970e3350e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running OpenClaw AI Agents on Snapdragon X Elite NPU with Microsoft Foundry Local and QNN]]></title>
            <link>https://shivaylamba.medium.com/running-openclaw-ai-agents-on-snapdragon-x-elite-npu-with-microsoft-foundry-local-and-qnn-25e138626c98?source=rss-af8e6cef0c35------2</link>
            <guid isPermaLink="false">https://medium.com/p/25e138626c98</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[genai]]></category>
            <dc:creator><![CDATA[Shivay Lamba]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 09:16:37 GMT</pubDate>
            <atom:updated>2026-06-23T09:16:37.759Z</atom:updated>
            <content:encoded><![CDATA[<p>On-device generative AI is becoming practical on Windows AI PCs.</p><p>Earlier, running an AI agent usually meant routing everything through a cloud API. That works well, but it is not always ideal for demos, privacy-sensitive workflows, offline scenarios, or edge AI use cases.</p><p>With Snapdragon X Elite, Microsoft Foundry Local, and OpenClaw, we can run a local AI agent stack where:</p><ul><li>the model runs locally through Microsoft Foundry Local</li><li>inference is accelerated on the Snapdragon NPU</li><li>OpenClaw manages the agent loop</li><li>the agent calls local tools</li><li>the whole workflow runs on the Windows machine</li></ul><p>This post walks through how to run OpenClaw on a Snapdragon Windows machine using Microsoft Foundry Local and an NPU-backed Qwen model.</p><h3>What We Are Building</h3><p>The final architecture looks like this:</p><pre>OpenClaw Agent<br>   |<br>   v<br>Model alias endpoint<br>http://127.0.0.1:4001/v1<br>model: foundry-npu<br>   |<br>   v<br>Safe NPU proxy<br>http://127.0.0.1:5299/v1<br>   |<br>   v<br>Microsoft Foundry Local<br>http://127.0.0.1:5272/v1<br>   |<br>   v<br>Qwen 2.5 model on Snapdragon X Elite NPU</pre><p>OpenClaw sees a normal OpenAI-compatible model provider:</p><pre>foundry-npu/foundry-npu</pre><p>Underneath, that request goes to Microsoft Foundry Local, which serves an optimized local model on the Snapdragon NPU.</p><h3>Why Snapdragon X Elite NPU?</h3><p>Snapdragon X Elite is Qualcomm’s Windows AI PC platform. It includes a Qualcomm Hexagon NPU designed for efficient local AI inference. Qualcomm describes Snapdragon X Series NPUs as reaching 45 TOPS, which makes them a strong target for on-device AI workloads.</p><p>For developers, this matters because the local device is no longer just a thin client. It can run useful AI workloads directly on the machine.</p><p>That unlocks demos and products where:</p><ul><li>data stays local</li><li>latency is lower</li><li>the app can work without depending on a remote model endpoint</li><li>cloud cost is reduced</li><li>Windows AI PCs become real edge AI platforms</li></ul><h3>Why Microsoft Foundry Local?</h3><p>Microsoft Foundry Local gives developers a way to run AI models locally with a developer-friendly interface. It supports local model management, local inference, SDK integration, and OpenAI-compatible endpoints. Plus it is also open source.</p><p>In this demo, Foundry Local runs on:</p><pre>http://127.0.0.1:5272/v1</pre><p>The active model is:</p><pre>qwen2.5-7b-instruct-qnn-npu</pre><p>That model is served locally and accelerated through the Snapdragon NPU path.</p><h3>Why OpenClaw?</h3><p>Foundry Local gives us inference.</p><p>OpenClaw gives us the agent loop.</p><p>A simple model prompt is one request and one response. An agent loop is more interesting. The agent can:</p><ul><li>receive a user task</li><li>inspect available tools</li><li>decide which tool to call</li><li>call the tool</li><li>read the tool result</li><li>produce a final response</li></ul><p>For this demo, we exposed three local Snapdragon demo tools to OpenClaw:</p><pre>snapdragon-npu__get_current_time<br>snapdragon-npu__get_npu_status<br>snapdragon-npu__draft_stage_note</pre><p>The key proof is that OpenClaw calls:</p><pre>snapdragon-npu__get_npu_status</pre><p>That means the agent is not just producing text. It is actually using a local tool in the agent loop.</p><h3>Repository</h3><p>The demo repo is:</p><pre>https://github.com/shivaylamba/on-device-agents-xelite-qwen2.5</pre><p>Clone it:</p><pre>git clone https://github.com/shivaylamba/on-device-agents-xelite-qwen2.5.git<br>cd &quot;on-device-agents-xelite-qwen2.5&quot;</pre><p>The repo is structured into three major demo areas:</p><pre>microsoft-foundry-demo/<br>hermes-agent-demo/<br>openclaw-demo/</pre><p>For this article, the main folders are:</p><pre>microsoft-foundry-demo/<br>openclaw-demo/</pre><h3>Foundry Local on Snapdragon NPU</h3><p>The core Foundry Local bridge lives here:</p><pre>microsoft-foundry-demo/foundry/app.py</pre><p>This Python script starts Foundry Local, loads the NPU model, and exposes the OpenAI-compatible local endpoint.</p><p>A simplified version looks like this:</p><pre>from foundry_local_sdk import Configuration, FoundryLocalManager</pre><pre>MODEL_ALIAS = &quot;qwen2.5-7b&quot;<br>FOUNDRY_HOST = &quot;127.0.0.1&quot;<br>FOUNDRY_PORT = 5272</pre><pre>config = Configuration(<br>    app_name=&quot;snapdragon_agent&quot;,<br>    web=Configuration.WebService(<br>        urls=f&quot;http://{FOUNDRY_HOST}:{FOUNDRY_PORT}&quot;<br>    ),<br>)</pre><pre>FoundryLocalManager.initialize(config)<br>manager = FoundryLocalManager.instance</pre><p>Next, the script prepares execution providers:</p><pre>manager.download_and_register_eps()</pre><p>This is an important step. It prepares the local execution provider stack so Foundry Local can use the right hardware acceleration path.</p><p>Then we get the model from the Foundry Local catalog:</p><pre>model = manager.catalog.get_model(&quot;qwen2.5-7b&quot;)</pre><p>Download it if needed:</p><pre>model.download()</pre><p>Load it:</p><pre>model.load()</pre><p>Then start the local OpenAI-compatible web service:</p><pre>manager.start_web_service()</pre><p>At that point, the model is available at:</p><pre>http://127.0.0.1:5272/v1</pre><p>You can check it with:</p><pre>Invoke-RestMethod http://127.0.0.1:5272/v1/models</pre><p>Expected output should include something like:</p><pre>{<br>  &quot;id&quot;: &quot;qwen2.5-7b-instruct-qnn-npu&quot;<br>}</pre><h3>Why We Added a Safe NPU Proxy</h3><p>Agent prompts are larger than normal prompts.</p><p>A basic inference request might be tiny:</p><pre>Write a Python program to print 2+2.</pre><p>An agent request includes more:</p><ul><li>system prompt</li><li>workspace context</li><li>tool schemas</li><li>current user instruction</li><li>previous session state</li><li>tool result formatting rules</li></ul><p>That can put more pressure on local NPU runtimes.</p><p>During testing, larger prompts and repeated agent calls sometimes triggered Foundry/QNN errors like:</p><pre>GroupQueryAttention seqlens_k[0] is out of range</pre><p>That error happens below OpenClaw. It comes from the Foundry/QNN execution path.</p><p>To make the demo more stable, we added a safe proxy:</p><pre>microsoft-foundry-demo/safe-proxy/safe_npu_proxy.py</pre><p>It runs on:</p><pre>http://127.0.0.1:5299/v1</pre><p>The safe proxy does a few practical things:</p><ul><li>serializes requests</li><li>clamps output length</li><li>disables streaming</li><li>trims oversized messages</li><li>optionally preserves OpenAI tool schemas</li><li>converts tool-like JSON into OpenAI-style tool_calls for our demo tools</li></ul><p>The rough forwarding path looks like this:</p><pre>def _forward(method, path, payload=None):<br>    url = f&quot;{UPSTREAM}{path}&quot;<br>    data = None if payload is None else json.dumps(payload).encode(&quot;utf-8&quot;)</pre><pre>    request = urllib.request.Request(<br>        url,<br>        data=data,<br>        headers={&quot;Content-Type&quot;: &quot;application/json&quot;},<br>        method=method,<br>    )</pre><pre>    with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT) as response:<br>        raw = response.read()<br>        return response.status, json.loads(raw.decode(&quot;utf-8&quot;))</pre><p>The request sanitizer keeps generation bounded:</p><pre>def _sanitize_chat_payload(payload):<br>    clean = dict(payload)<br>    clean[&quot;max_tokens&quot;] = min(<br>        int(clean.get(&quot;max_tokens&quot;, MAX_TOKENS)),<br>        MAX_TOKENS,<br>    )<br>    clean[&quot;stream&quot;] = False<br>    return clean</pre><p>This does not magically fix every NPU runtime issue, but it makes the agent demo path much more reliable.</p><h3>Why We Added a Model Alias Proxy</h3><p>OpenClaw expects to call a provider/model pair like this:</p><pre>foundry-npu/foundry-npu</pre><p>But Foundry Local exposes the actual model name:</p><pre>qwen2.5-7b-instruct-qnn-npu</pre><p>So we added a lightweight OpenAI-compatible alias proxy:</p><pre>microsoft-foundry-demo/litellm/foundry_alias_proxy.py</pre><p>It runs on:</p><pre>http://127.0.0.1:4001/v1</pre><p>It exposes this model:</p><pre>foundry-npu</pre><p>And maps it to:</p><pre>qwen2.5-7b-instruct-qnn-npu</pre><p>The mapping is simple:</p><pre>ALIAS_MODEL = &quot;foundry-npu&quot;<br>TARGET_MODEL = &quot;qwen2.5-7b-instruct-qnn-npu&quot;</pre><p>When OpenClaw sends:</p><pre>{<br>  &quot;model&quot;: &quot;foundry-npu&quot;<br>}</pre><p>the alias proxy forwards:</p><pre>{<br>  &quot;model&quot;: &quot;qwen2.5-7b-instruct-qnn-npu&quot;<br>}</pre><p>to the safe proxy.</p><p>So the full local path becomes:</p><pre>OpenClaw<br>  -&gt; http://127.0.0.1:4001/v1<br>  -&gt; http://127.0.0.1:5299/v1<br>  -&gt; http://127.0.0.1:5272/v1<br>  -&gt; Snapdragon X Elite NPU</pre><h3>Starting the Full Stack</h3><p>From the repo root:</p><pre>cd &quot;C:\Users\Admin\Documents\microsoft foundary\on-device-agents-xelite-qwen2.5&quot;</pre><p>Apply the OpenClaw config:</p><pre>.\openclaw-demo\scripts\apply-openclaw-config.ps1</pre><p>Start Foundry Local, the safe proxy, and the model alias proxy:</p><pre>.\microsoft-foundry-demo\scripts\restart-npu-runtime.ps1 `<br>  -FoundryModel qwen2.5-7b `<br>  -KeepOpenAITools</pre><p>Expected output:</p><pre>Foundry Local: http://127.0.0.1:5272/v1<br>Safe Proxy:    http://127.0.0.1:5299/v1<br>Model alias:   http://127.0.0.1:4001/v1<br>Open WebUI:    http://127.0.0.1:8080</pre><p>Verify the endpoints:</p><pre>Invoke-RestMethod http://127.0.0.1:5272/v1/models<br>Invoke-RestMethod http://127.0.0.1:5299/health<br>Invoke-RestMethod http://127.0.0.1:4001/v1/models</pre><p>The model alias endpoint should return:</p><pre>{<br>  &quot;object&quot;: &quot;list&quot;,<br>  &quot;data&quot;: [<br>    {<br>      &quot;id&quot;: &quot;foundry-npu&quot;,<br>      &quot;object&quot;: &quot;model&quot;,<br>      &quot;owned_by&quot;: &quot;local-foundry-alias&quot;<br>    }<br>  ]<br>}</pre><h3>Running Plain OpenClaw Inference on the NPU</h3><p>Before testing tools, run a simple OpenClaw inference request:</p><pre>openclaw infer model run `<br>  --local `<br>  --model foundry-npu/foundry-npu `<br>  --prompt &quot;write a python program to print 2+2&quot; `<br>  --thinking off</pre><p>This uses OpenClaw’s model inference path, but routes the request to Foundry Local through the local alias proxy.</p><p>Expected answer:</p><pre>print(2 + 2)</pre><p>or something similar.</p><h3>Exposing Local Tools to OpenClaw</h3><p>The OpenClaw tool integration uses MCP.</p><p>The MCP server lives here:</p><pre>openclaw-demo/mcp/snapdragon-npu-tools.mjs</pre><p>It exposes three tools:</p><pre>server.registerTool(<br>  &quot;get_current_time&quot;,<br>  {<br>    description: &quot;Return the current local time for the Snapdragon NPU demo.&quot;,<br>    inputSchema: {<br>      timezone: z.string().default(&quot;Asia/Calcutta&quot;)<br>    },<br>  },<br>  async ({ timezone = &quot;Asia/Calcutta&quot; }) =&gt; {<br>    const now = new Date();<br>    return jsonText({<br>      timezone,<br>      iso_time: now.toISOString(),<br>      display_time: new Intl.DateTimeFormat(&quot;en-US&quot;, {<br>        dateStyle: &quot;medium&quot;,<br>        timeStyle: &quot;medium&quot;,<br>        timeZone: timezone,<br>      }).format(now),<br>    });<br>  },<br>);</pre><p>The NPU status tool checks the local Foundry endpoint:</p><pre>server.registerTool(<br>  &quot;get_npu_status&quot;,<br>  {<br>    description: &quot;Check the local Foundry endpoint and report the Snapdragon NPU model status.&quot;,<br>    inputSchema: {},<br>  },<br>  async () =&gt; {<br>    const started = Date.now();<br>    const response = await fetch(`${FOUNDRY_URL}/models`);<br>    const elapsedMs = Date.now() - started;<br>    const payload = await response.json();</pre><pre>    return jsonText({<br>      status: response.ok ? &quot;ready&quot; : &quot;error&quot;,<br>      endpoint: FOUNDRY_URL,<br>      latency_ms: elapsedMs,<br>      device: &quot;Snapdragon NPU&quot;,<br>      acceleration: &quot;QNNExecutionProvider&quot;,<br>    });<br>  },<br>);</pre><p>Probe the tools:</p><pre>openclaw mcp probe snapdragon-npu --json</pre><p>Expected tools:</p><pre>snapdragon-npu__draft_stage_note<br>snapdragon-npu__get_current_time<br>snapdragon-npu__get_npu_status</pre><h3>Running the OpenClaw Agent Tool Demo</h3><p>Now run the full OpenClaw agent tool test:</p><pre>.\openclaw-demo\scripts\test-openclaw-demo-tool.ps1 `<br>  -SessionKey &quot;agent:main:npu-demo-tool-real&quot;</pre><p>The expected proof is:</p><pre>&quot;toolSummary&quot;: {<br>  &quot;calls&quot;: 1,<br>  &quot;tools&quot;: [<br>    &quot;snapdragon-npu__get_npu_status&quot;<br>  ],<br>  &quot;failures&quot;: 0<br>}</pre><p>In our successful run, OpenClaw returned:</p><pre>&quot;aborted&quot;: false,<br>&quot;stopReason&quot;: &quot;stop&quot;,<br>&quot;executionTrace&quot;: {<br>  &quot;winnerProvider&quot;: &quot;foundry-npu&quot;,<br>  &quot;winnerModel&quot;: &quot;foundry-npu&quot;,<br>  &quot;attempts&quot;: [<br>    {<br>      &quot;provider&quot;: &quot;foundry-npu&quot;,<br>      &quot;model&quot;: &quot;foundry-npu&quot;,<br>      &quot;result&quot;: &quot;success&quot;,<br>      &quot;stage&quot;: &quot;assistant&quot;<br>    }<br>  ],<br>  &quot;fallbackUsed&quot;: false<br>},<br>&quot;toolSummary&quot;: {<br>  &quot;calls&quot;: 1,<br>  &quot;tools&quot;: [<br>    &quot;snapdragon-npu__get_npu_status&quot;<br>  ],<br>  &quot;failures&quot;: 0<br>}</pre><p>That is the key result.</p><p>It proves:</p><ul><li>OpenClaw ran the agent loop.</li><li>The model route was foundry-npu/foundry-npu.</li><li>The request went through the local Foundry/NPU stack.</li><li>OpenClaw called our real Snapdragon demo tool.</li><li>The tool call succeeded.</li><li>The model produced a final response.</li></ul><h3>Why This Matters</h3><p>This demo shows a real path for on-device agents on Windows AI PCs.</p><p>The agent framework does not need special NPU-specific logic. OpenClaw talks to an OpenAI-compatible endpoint. Foundry Local handles the local model runtime. The Snapdragon NPU accelerates the model underneath.</p><p>That separation is powerful.</p><p>It means developers can build agentic applications using familiar patterns:</p><pre>OpenAI-compatible API<br>local model endpoint<br>MCP tools<br>agent loop</pre><p>while still taking advantage of local hardware acceleration.</p><h3>Final Thoughts</h3><p>On-device AI agents are no longer theoretical.</p><p>With Snapdragon X Elite, Microsoft Foundry Local, and OpenClaw, we can run a local agent loop that:</p><ul><li>routes inference through the Snapdragon NPU</li><li>calls local tools</li><li>keeps the workflow on the Windows device</li><li>uses an OpenAI-compatible architecture</li><li>demonstrates a practical edge AI pattern</li></ul><p>The stack is still early. Large agent prompts can stress local NPU runtimes, and we had to add a safe proxy to make the demo reliable.</p><p>But the direction is clear.</p><p>The next wave of AI agents will not only live in the cloud. They will also run locally, on AI PCs, close to the user, close to the data, and close to the device capabilities they can act on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25e138626c98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Deep Dive into Model Compression and Hardware-Aware Optimization at the Edge]]></title>
            <link>https://shivaylamba.medium.com/a-practical-deep-dive-into-model-compression-and-hardware-aware-optimization-at-the-edge-cef58c141bfb?source=rss-af8e6cef0c35------2</link>
            <guid isPermaLink="false">https://medium.com/p/cef58c141bfb</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[quantization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shivay Lamba]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 14:15:34 GMT</pubDate>
            <atom:updated>2026-06-10T14:15:34.688Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this post, we’ll walk through how we take a model from its training-time form down to something that runs efficiently on constrained hardware. We’ll cover where model cost actually comes from, the three compression techniques that do the heavy lifting (quantization, distillation, and runtime graph optimization), why the same model behaves completely differently across CPU, GPU, and NPU, and the practical engineering decisions, including the failure modes, required to ship.</h4><h3>Why the Edge Is a Different Problem</h3><p>It’s tempting to think of edge AI as “datacenter AI, but smaller.” It isn’t. It’s a fundamentally different deployment architecture with a different set of binding constraints.</p><p>A datacenter model assumes abundant memory, powerful parallel compute, and continuous connectivity. An edge target violates all three assumptions at once:</p><ol><li><strong>Memory is shared and scarce.</strong> On a phone, your model competes with the OS and every other app for a single pool of RAM. There is no dedicated 80GB accelerator waiting for your weights.</li><li><strong>Power and thermals are hard limits.</strong> Every inference draws from a battery and generates heat. Run too hard, and the device throttles your clock speed or becomes too hot to hold, so your “fast” model silently becomes slow.</li><li><strong>Latency is felt, not measured.</strong> If your model backs a keyboard prediction or a camera effect, 200ms of latency doesn’t show up in a dashboard. It shows up as something that feels broken.</li><li><strong>Offline is mandatory.</strong> On a plane, in a tunnel, in a factory basement, the model still has to work with zero connectivity.</li></ol><p>The job, then, is an optimization problem across four competing axes: <strong>accuracy, latency, memory, and power.</strong> The catch is that these are coupled. Push one down and another usually pops up. Quantize aggressively and you win on memory and latency but risk accuracy. Restore accuracy with a bigger model and you’ve blown your power and latency budget. Real edge engineering is the art of balancing all four simultaneously.</p><h3>Where the Cost Actually Lives</h3><p>Before you can shrink a model, you need to know what’s expensive. Model cost is not a single number. It comes from four distinct sources:</p><ul><li><strong>Parameters.</strong> The static weights you ship. For a transformer, this is the bulk of your on-disk size.</li><li><strong>Activations.</strong> The live tensors flowing through the network during a forward pass. These are transient but can spike memory hard, especially in wide layers.</li><li><strong>KV cache.</strong> In autoregressive models, every generated token caches its key and value projections so they don’t have to be recomputed. This cache <strong>grows linearly with context length</strong>, and it’s the silent memory hog that turns a comfortable 1GB model into an out-of-memory crash halfway through a long conversation.</li><li><strong>Intermediate tensors.</strong> The short-lived scratch buffers between operations.</li></ul><p>The single biggest lever across all of these is <strong>numerical precision.</strong> The same model stored at different precisions has dramatically different footprints:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ymnxBV9H2yJtwE5ydlesQQ.png" /></figure><p>Moving from FP32 to INT8 is a 4x reduction in size for, very often, a negligible drop in quality. That nearly free 4x is why quantization is almost always the first thing we reach for.</p><h3>Technique 1: Quantization, the Biggest Single Win</h3><p>Quantization is the process of representing weights and activations with fewer bits, typically mapping 32-bit floats down to 8-bit or 4-bit integers. The wins compound across three of our four axes:</p><ul><li><strong>Smaller models</strong> (memory): fewer bits per weight, directly.</li><li><strong>Lower memory bandwidth</strong> (latency <em>and</em> power): this is the underrated one. On edge silicon, <em>moving</em> data costs far more energy and time than the arithmetic itself. A DRAM access can cost on the order of 100x the energy of a multiply. Smaller numbers mean you push less data across a constrained memory bus on every single inference.</li><li><strong>Faster inference</strong> (latency): integer math units are cheaper and more plentiful than floating-point units, especially on NPUs.</li></ul><p>There are two roads to a quantized model, and choosing between them is one of the most common decisions you’ll make.</p><h3>Post-Training Quantization (PTQ)</h3><p>You take an already-trained float model and quantize it after the fact, usually calibrating the activation ranges on a small representative dataset. PTQ is fast, needs no retraining, and can be done in an afternoon. The cost is some accuracy degradation, usually small for INT8, sometimes painful at INT4.</p><h3>Quantization-Aware Training (QAT)</h3><p>You simulate the rounding error of quantization <em>during</em> training (via “fake quant” nodes), so the model learns weights that are robust to being quantized. QAT recovers most or all of the accuracy PTQ loses, but it requires a full training pipeline plus the compute and time that come with it.</p><p><strong>The practical rule:</strong> always try PTQ first. It’s cheap, and for INT8 it’s frequently good enough to ship. Reach for QAT only when PTQ drops your accuracy below what the product can tolerate, most often when you’re pushing to INT4 or quantizing a model that’s sensitive to it.</p><h3>Technique 2: Distillation</h3><p>Quantization shrinks the <em>representation</em> of a model. Distillation shrinks the <em>model itself</em>.</p><p>The idea: a large, capable <strong>teacher</strong> model trains a small <strong>student</strong> to mimic its behavior. Crucially, the student doesn’t just learn from the ground-truth labels. It learns from the teacher’s full output distribution (the “soft targets”), which carries far richer information about how the teacher generalizes. The student ends up a fraction of the teacher’s size while retaining a surprising amount of its capability.</p><p>You’ve seen this pattern in the wild: the smaller variants in modern model families (a 2B distilled from a much larger sibling) are often distillation products. The payoff hits three axes at once: smaller footprint, faster inference, lower power.</p><p>The mental model to keep: <strong>quantization and distillation are different levers, not competitors.</strong> You distill to get a fundamentally smaller architecture, then quantize that student to shrink it further. They stack.</p><h3>Technique 3: Runtime Optimization</h3><p>Here’s the part most engineers never see, because it happens below the model, inside the runtime or compiler. The defining property of every technique in this section is that it is <strong>semantics-preserving</strong>: the output is numerically identical (or equivalent), so accuracy is completely untouched. These are the genuinely free wins.</p><p>The unifying insight is the same one from the quantization section: <strong>edge inference is overwhelmingly memory-bound, not compute-bound.</strong> Most of the gains here come from moving less data, not doing less math.</p><ul><li><strong>Operator fusion.</strong> Consider a Conv -&gt; BiasAdd -&gt; ReLU sequence. Run unfused, each op reads its input from DRAM, computes, and writes the result back: three full round-trips to main memory. Fusion collapses them into a single kernel that keeps intermediate values in registers or on-chip SRAM, so you read once and write once. The arithmetic is unchanged; you’ve simply deleted two expensive memory round-trips. This is usually the single largest runtime win.</li><li><strong>Graph optimization.</strong> A compile-time pass over the computation graph: constant folding (precompute any subgraph whose inputs are known ahead of time), dead-node elimination, and the classic example of folding BatchNorm into the preceding convolution’s weights. At inference, BatchNorm is just a frozen affine transform, so it can be algebraically merged into the conv, deleting an entire layer’s worth of work at zero accuracy cost.</li><li><strong>Memory planning.</strong> Activations are short-lived; a tensor is “live” only from when it’s produced to when its last consumer reads it. The planner computes these lifetimes and lets tensors whose lifetimes don’t overlap share the same physical buffer. It’s essentially register allocation, but for activation memory. This is what drives down <em>peak</em> memory, which is what decides whether the model fits on the device at all.</li><li><strong>Kernel selection.</strong> A single convolution has many valid implementations (direct, im2col + GEMM, Winograd), each with different tradeoffs depending on tensor shape and hardware. Runtimes pick the fastest one, often by auto-tuning on the actual device and caching the winner.</li></ul><p>You don’t usually implement these yourself. You get them from an inference runtime: ONNX Runtime, ExecuTorch, TensorRT, TVM, or a vendor stack like Qualcomm QNN. Pick the one that fits your target hardware and ecosystem; the underlying principles are identical across all of them.</p><h3>Not All Hardware Is Equal</h3><p>You can ship the exact same model file to three different chips and get three completely different latency and power profiles. The model is not the whole story; the silicon underneath it is.</p><ul><li><strong>CPU.</strong> Flexible, universally available, and a reliable fallback, but limited parallelism makes it the slowest option for heavy tensor math.</li><li><strong>GPU.</strong> Massive parallelism, excellent throughput for the large matrix multiplications at the heart of a transformer.</li><li><strong>NPU (Neural Processing Unit).</strong> Purpose-built for low-power inference. An NPU’s hardware is designed around exactly the operations neural nets need, and it runs them at a fraction of the energy a CPU or GPU would burn for the same work. On modern mobile silicon, the NPU is the real story for sustained, efficient, on-device AI.</li></ul><p>This is why “hardware-aware” optimization is not optional. The choice of precision, the kernels you select, and even the layout of your tensors should be made <em>with the target accelerator in mind.</em> Optimizing in the abstract leaves performance on the table.</p><h3>The End-to-End Pipeline</h3><p>In practice, these techniques aren’t a menu you pick one item from. They’re stages you stack into a repeatable pipeline:</p><p>Training -&gt; Export -&gt; Distillation -&gt; Quantization -&gt; Runtime Optimization -&gt; Deployment</p><p>You train (or start from) a capable model, export it to a portable format, optionally distill it down to a smaller student, quantize that student to INT8 or INT4, apply runtime graph optimizations for your specific hardware backend, and deploy. Once this pipeline exists, it becomes your standard road from a research checkpoint to a shipped artifact, and you don’t rebuild it by hand every time.</p><p>The cumulative effect is what makes edge deployment viable. Stacking these stages routinely yields a model several times faster and several times smaller than the original, frequently in the ballpark of a 3x to 5x improvement end-to-end. The exact numbers depend entirely on your model and target, so treat any single figure as illustrative and <strong>measure your own.</strong></p><h3>The Part Nobody Demos: Graceful Degradation</h3><p>Here’s the engineering reality that the tidy pipeline diagram hides. NPU acceleration usually depends on hardware-specific, pre-compiled binaries baked into the model artifact. If those binaries are missing, because you grabbed generic open-source weights or the device’s driver version doesn’t match, forcing the NPU path doesn’t gently degrade. <strong>It crashes.</strong></p><p>A production app cannot assume the happy path. The robust pattern is a <strong>fallback chain</strong>: attempt to initialize the NPU; if it throws, catch the specific exception, abandon the NPU, and initialize the GPU backend instead; if <em>that</em> fails, fall back to the CPU. Concretely:</p><p>NPU (best efficiency) -&gt; GPU (good throughput) -&gt; CPU (always works)</p><p>The model still runs everywhere; it just runs at the best tier each particular device can actually support. Building this fallback is unglamorous, it never appears in the benchmark slide, and it is the difference between an app that works on your test device and an app that works in the wild.</p><h3>Common Mistakes (Learned the Hard Way)</h3><p>Four traps catch nearly everyone at least once:</p><ol><li><strong>Optimizing only for accuracy.</strong> You celebrate 99% accuracy, ship it, and discover the model is too slow or drains the battery in an hour, because you forgot the other three axes existed.</li><li><strong>Ignoring memory bandwidth.</strong> You spend weeks optimizing compute, and your speedup never materializes, because the bottleneck was always data movement.</li><li><strong>Benchmarking on desktop hardware.</strong> Your dev laptop’s beefy GPU looks nothing like the target NPU. Desktop numbers don’t just differ; they actively mislead, because the bottlenecks shift entirely between platforms.</li><li><strong>Optimizing before profiling.</strong> You guess at the hotspot, optimize it, and find it was 5% of runtime. <strong>Profile first, on the real device, always.</strong> Then optimize the thing that’s actually slow, and re-profile to confirm it helped.</li></ol><h3>Case Study: Qwen3–4B on Qualcomm NPU vs Full-Precision CPU</h3><p>To make the compression story concrete, we ran a small case study with Qwen3–4B on a Windows ARM64 Snapdragon machine. The baseline was the original full-precision Qwen/Qwen3–4B model loaded through Hugging Face Transformers and PyTorch on CPU. The optimized path used Qualcomm’s prebuilt AIMET-generated w4a16 Qwen3–4B artifact, deployed through QAIRT / GENIE / QNN on the Qualcomm HTP/NPU path. This distinction matters: AIMET quantization is a host-side preparation step, while the Snapdragon NPU is the deployment target. In this demo, we did not locally run AIMET quantization from scratch; we used Qualcomm’s already AIMET-generated artifact and focused on measuring the deployment benefit.</p><p>The practical flow looked like this: first, capture the full-precision CPU baseline; second, fetch the Qualcomm GENIE runtime bundle for the quantized model; third, run the quantized artifact through genie-t2t-run with the QNN HTP backend. In code, the baseline and optimized runs looked roughly like:</p><pre>qwen3-quant-demo bench-fp `<br>  --python-executable &quot;C:\Program Files\Python312-arm64\python.exe&quot; `<br>  --allow-download `<br>  --warmups 2 `<br>  --measured-runs 5 `<br>  --max-new-tokens 64 `<br>  --output results\fp.json<br><br>qwen3-quant-demo bench-qnn `<br>  --artifact-manifest artifacts\qwen3_w4a16_genie_x_elite_manifest.json `<br>  --runner-command &quot;python examples\genie_t2t_runner.py --executable C:\Qualcomm\AIStack\QAIRT\2.45.0.260326\bin\aarch64-windows-msvc\genie-t2t-run.exe --artifact {artifact_dir} --prompt {prompt_file} --max-new-tokens {max_new_tokens} --output {output_json}&quot; `<br>  --warmups 2 `<br>  --measured-runs 5 `<br>  --max-new-tokens 64 `<br>  --output results\qnn.json</pre><p>The result was clear on throughput. The full-precision PyTorch CPU baseline averaged 51.05 seconds end-to-end and 1.26 tokens/second across five measured runs. The quantized w4a16 GENIE/QNN path averaged 47.71 seconds end-to-end and 11.54 tokens/second, with a measured time-to-first-token of about 0.118 seconds. That gives roughly a 9.2x generation-throughput improvement for the quantized Qualcomm NPU deployment path. The quantized runtime bundle was also much smaller in practice: about 2.97 GiB extracted, compared with roughly 7.5 GiB of full-precision Hugging Face model weights.</p><p>The main lesson is that quantization is not just a model-size trick; it is what makes the model compatible with the hardware acceleration path that actually matters at the edge. The original PyTorch model could run on CPU, but it could not simply be “sent to the NPU” as-is. To use the Qualcomm NPU, the model needs to become a QNN/GENIE-compatible deployment artifact, which is exactly what the AIMET-generated w4a16 path provides. This is why hardware-aware optimization matters: the performance win came not only from using fewer bits, but from turning the model into something the Snapdragon NPU runtime could execute efficiently.</p><p>You can find the entire benchmark with the scripts here: <a href="https://github.com/shivaylamba/qwen3-quanrization-benchmarks">https://github.com/shivaylamba/qwen3-quanrization-benchmarks</a></p><h3>Conclusion</h3><p>Getting a modern model onto constrained hardware comes down to three techniques and one mindset. Quantization is usually your single biggest win, so start there. Distillation preserves capability while reducing size, so reach for it when you need a fundamentally smaller model. And hardware-aware optimization, including the unglamorous fallback logic, is the line between a demo and production.</p><p>The mindset is the thing to internalize: <strong>deploying AI at the edge is an optimization problem, not just a modeling problem.</strong> Train the best model you can, then respect the four constraints (accuracy, latency, memory, and power) at every step from export to deployment. That’s how giants get shrunk down to fit in your pocket.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cef58c141bfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantizing Qwen3–4B for Snapdragon: An AIMET-to-NPU Deployment Case Study]]></title>
            <link>https://shivaylamba.medium.com/quantizing-qwen3-4b-for-snapdragon-an-aimet-to-npu-deployment-case-study-6979e69f45c0?source=rss-af8e6cef0c35------2</link>
            <guid isPermaLink="false">https://medium.com/p/6979e69f45c0</guid>
            <dc:creator><![CDATA[Shivay Lamba]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 08:02:03 GMT</pubDate>
            <atom:updated>2026-06-09T08:02:03.343Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is a developer-focused case study of our Qwen3–4B quantization benchmark. It starts from the basics of quantization, explains how AIMET fits into the workflow, and then documents the exact experiment we ran: a full-precision Qwen3–4B CPU baseline versus Qualcomm’s AIMET-generated w4a16 Qwen3–4B runtime bundle running through GENIE/QNN on a Snapdragon NPU path.</p><p>In our local experiment, we used Qualcomm’s prebuilt AIMET-generated w4a16 artifact and benchmarked it through Qualcomm’s NPU deployment runtime.</p><h3>Why Quantization Matters</h3><p>Large language models are usually trained and distributed in floating-point formats such as FP16, BF16, or FP32. Those formats are friendly to training and broad research usage, but they are expensive for edge deployment. A 4B-parameter model in full precision occupies multiple gigabytes of memory, stresses memory bandwidth, and is usually not in the format expected by a mobile or PC NPU runtime.</p><p>Quantization reduces that cost by representing weights, activations, or both with fewer bits. In our case, the quantized Qwen3–4B artifact is w4a16, meaning 4-bit weights and 16-bit activations. Weight-only 4-bit quantization is especially useful for LLMs because transformer inference is heavily memory-bandwidth constrained. Smaller weights mean less data movement, better cache behavior, lower memory pressure, and a model representation that can be exported into a deployment runtime such as Qualcomm GENIE/QNN.</p><p>AIMET runs before deployment. AIMET prepares the model, computes encodings, applies the quantization recipe, and exports artifacts. The NPU runs the prepared deployment artifact.</p><h3>The Three Artifacts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uCuoZVdkn0BR4oEEZqW4Xg.png" /></figure><h3>Where AIMET Fits</h3><p>AIMET is Qualcomm’s model-efficiency toolkit. In this flow, it is used before deployment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i7I9dhdQPV8lCo0PbwuPqg.png" /></figure><p>The official AIMET Qwen3 recipe documents a command shaped like this:</p><pre>python -m Examples.onnx.quantize \<br>  --model-id &quot;Qwen/Qwen3-4B&quot; \<br>  --recipe &quot;lpbq_seqmse&quot; \<br>  --export-path &quot;./qwen3_4b_lpbq_seqmse&quot; \<br>  --seqmse-num-batches 20</pre><p>Here is what that command means. Examples.onnx.quantize is not a Python standard-library module and it is not from this benchmark repo. It is an AIMET example module from Qualcomm’s AIMET documentation/examples environment. A reader can only run it after setting up AIMET and its example package on the right host environment. If they run that command on a plain laptop Python install, it will fail because Examples will not exist.</p><p>The flags are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjO64ZfT4Ekyg4ZdF6lgog.png" /></figure><h3>Minimal AIMET Host-Side Skeleton</h3><p>The exact Qwen3–4B recipe should be run from Qualcomm’s AIMET recipe environment because LLM export involves model-specific handling, calibration, and runtime export. Still, the core AIMET idea looks like this: load a model, create a quantization simulation, run calibration, then export encodings/artifacts.</p><pre># Run on an AIMET-supported host, not on the Snapdragon NPU target.<br># This is a skeleton showing the shape of the AIMET workflow.<br><br>from pathlib import Path<br><br>import onnx<br>from aimet_onnx.quantsim import QuantizationSimModel<br><br><br>def calibration_forward_pass(session, _):<br>    &quot;&quot;&quot;Feed representative calibration samples through the model.<br><br>    For a real Qwen3 recipe, this should tokenize representative prompts and<br>    run the exact input tensors expected by the exported ONNX graph.<br>    &quot;&quot;&quot;<br>    for batch in calibration_batches():<br>        session.run(None, batch)<br><br><br>model_path = Path(&quot;qwen3_4b.onnx&quot;)<br>export_dir = Path(&quot;qwen3_4b_aimet_export&quot;)<br>export_dir.mkdir(parents=True, exist_ok=True)<br><br>onnx_model = onnx.load(model_path)<br><br>sim = QuantizationSimModel(<br>    model=onnx_model,<br>    quant_scheme=&quot;tf_enhanced&quot;,<br>    default_param_bw=4,<br>    default_activation_bw=16,<br>)<br><br>sim.compute_encodings(<br>    forward_pass_callback=calibration_forward_pass,<br>    forward_pass_callback_args=None,<br>)<br><br>sim.export(<br>    path=str(export_dir),<br>    filename_prefix=&quot;qwen3_4b_w4a16&quot;,<br>)</pre><p>That skeleton is useful for understanding AIMET, but Qwen3–4B should use Qualcomm’s documented recipe rather than a hand-rolled minimal script. The recipe includes the model-specific quantization choices that make the exported artifact practical.</p><h3>What Our Repo CLI Is</h3><p>The command qwen3-quant-demo is only a convenience CLI from this repository. It is installed by this setup step:</p><pre>git clone https://github.com/shivaylamba/qwen3-quanrization-benchmarks.git<br>cd qwen3-quanrization-benchmarks<br><br>python -m venv .venv<br>.\.venv\Scripts\Activate.ps1<br>python -m pip install --upgrade pip<br>python -m pip install -e &quot;.[qnn,aihub,test]&quot;</pre><p>After that, this:</p><p>qwen3-quant-demo env-check --output results\env.json</p><p>is equivalent to running this Python module from our package:</p><p>python -m qwen3_quant_demo env-check --output results\env.json</p><p>So when the article says qwen3-quant-demo bench-qnn, it means “run our benchmark wrapper,” not “run a Qualcomm/AIMET command.”</p><h3>Full-Precision CPU Baseline Code</h3><p>The FP baseline uses Hugging Face Transformers and PyTorch. This is the core code without our CLI wrapper:</p><pre>import time<br><br>import torch<br>from transformers import AutoModelForCausalLM, AutoTokenizer<br><br><br>MODEL_ID = &quot;Qwen/Qwen3-4B&quot;<br>PROMPT = &quot;Explain quantization for edge AI in two concise paragraphs.&quot;<br>MAX_NEW_TOKENS = 64<br>WARMUPS = 2<br>MEASURED_RUNS = 5<br><br><br>tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)<br>model = AutoModelForCausalLM.from_pretrained(<br>    MODEL_ID,<br>    torch_dtype=torch.float32,<br>    low_cpu_mem_usage=True,<br>)<br>model.eval()<br><br>inputs = tokenizer(PROMPT, return_tensors=&quot;pt&quot;)<br><br>latencies = []<br>throughputs = []<br><br>for run_idx in range(WARMUPS + MEASURED_RUNS):<br>    measured = run_idx &gt;= WARMUPS<br><br>    with torch.no_grad():<br>        start = time.perf_counter()<br>        output_ids = model.generate(<br>            **inputs,<br>            max_new_tokens=MAX_NEW_TOKENS,<br>            do_sample=False,<br>            pad_token_id=tokenizer.eos_token_id,<br>        )<br>        latency_s = time.perf_counter() - start<br><br>    generated_tokens = int(output_ids.shape[-1] - inputs[&quot;input_ids&quot;].shape[-1])<br>    tokens_per_s = generated_tokens / latency_s<br><br>    if measured:<br>        latencies.append(latency_s)<br>        throughputs.append(tokens_per_s)<br><br>print({<br>    &quot;runtime&quot;: &quot;PyTorch CPU&quot;,<br>    &quot;mean_latency_s&quot;: sum(latencies) / len(latencies),<br>    &quot;mean_tokens_per_s&quot;: sum(throughputs) / len(throughputs),<br>})</pre><p>Our CLI command wraps that same logic and writes structured JSON:</p><pre>qwen3-quant-demo bench-fp `<br>  --python-executable &quot;C:\Program Files\Python312-arm64\python.exe&quot; `<br>  --allow-download `<br>  --limit-prompts 1 `<br>  --warmups 2 `<br>  --measured-runs 5 `<br>  --max-new-tokens 64 `<br>  --output results\fp.json</pre><p>We ran FP on CPU because a Hugging Face .safetensors model cannot be sent directly to the Qualcomm NPU. The NPU path needs a QNN/GENIE-compatible artifact.</p><h3>Quantized GENIE/QNN/NPU Benchmark Code</h3><p>The quantized path uses Qualcomm’s pre-exported GENIE runtime bundle. The bundle contains files like:</p><pre>genie_config.json<br>tokenizer.json<br>htp_backend_ext_config.json<br>qwen3_4b_w4a16_part_1_of_4.bin<br>qwen3_4b_w4a16_part_2_of_4.bin<br>qwen3_4b_w4a16_part_3_of_4.bin<br>qwen3_4b_w4a16_part_4_of_4.bin</pre><p>The actual inference command is Qualcomm’s genie-t2t-run. This is the core Python wrapper:</p><pre>import json<br>import os<br>import subprocess<br>import time<br>from pathlib import Path<br><br><br>QAIRT_ROOT = Path(r&quot;C:\Qualcomm\AIStack\QAIRT\2.45.0.260326&quot;)<br>GENIE_EXE = QAIRT_ROOT / &quot;bin&quot; / &quot;aarch64-windows-msvc&quot; / &quot;genie-t2t-run.exe&quot;<br>ARTIFACT_DIR = Path(<br>    r&quot;C:\Users\Admin\.qaihm\qai-hub-models\models\qwen3_4b&quot;<br>    r&quot;\releases\v0.54.0\qwen3_4b-genie-w4a16-qualcomm_snapdragon_x_elite&quot;<br>)<br>CONFIG = ARTIFACT_DIR / &quot;genie_config.json&quot;<br>PROMPT = (<br>    &quot;&lt;|im_start|&gt;user\n&quot;<br>    &quot;Explain quantization for edge AI in two concise paragraphs.&quot;<br>    &quot;&lt;|im_end|&gt;\n&quot;<br>    &quot;&lt;|im_start|&gt;assistant\n&quot;<br>)<br><br><br>env = os.environ.copy()<br>env[&quot;PATH&quot;] = (<br>    str(GENIE_EXE.parent)<br>    + os.pathsep<br>    + str(QAIRT_ROOT / &quot;lib&quot; / &quot;aarch64-windows-msvc&quot;)<br>    + os.pathsep<br>    + env.get(&quot;PATH&quot;, &quot;&quot;)<br>)<br>env[&quot;ADSP_LIBRARY_PATH&quot;] = str(QAIRT_ROOT / &quot;lib&quot; / &quot;hexagon-v73&quot; / &quot;unsigned&quot;)<br><br>profile_path = ARTIFACT_DIR / &quot;profile.json&quot;<br><br>command = [<br>    str(GENIE_EXE),<br>    &quot;-c&quot;,<br>    str(CONFIG),<br>    &quot;-p&quot;,<br>    PROMPT,<br>    &quot;--profile&quot;,<br>    str(profile_path),<br>]<br><br>start = time.perf_counter()<br>completed = subprocess.run(<br>    command,<br>    cwd=ARTIFACT_DIR,<br>    env=env,<br>    capture_output=True,<br>    text=True,<br>)<br>latency_s = time.perf_counter() - start<br><br>if completed.returncode != 0:<br>    raise RuntimeError(completed.stderr)<br><br>profile = json.loads(profile_path.read_text(encoding=&quot;utf-8&quot;))<br><br>print({<br>    &quot;runtime&quot;: &quot;GENIE/QNN/HTP&quot;,<br>    &quot;latency_s&quot;: latency_s,<br>    &quot;stdout&quot;: completed.stdout,<br>    &quot;stderr&quot;: completed.stderr,<br>    &quot;profile&quot;: profile,<br>})</pre><p>Our CLI command wraps this runner repeatedly with two warmups and five measured runs:</p><pre>qwen3-quant-demo bench-qnn `<br>  --artifact-manifest artifacts\qwen3_w4a16_genie_x_elite_manifest.json `<br>  --runner-command &quot;python examples\genie_t2t_runner.py --executable C:\Qualcomm\AIStack\QAIRT\2.45.0.260326\bin\aarch64-windows-msvc\genie-t2t-run.exe --artifact {artifact_dir} --prompt {prompt_file} --max-new-tokens {max_new_tokens} --output {output_json}&quot; `<br>  --limit-prompts 1 `<br>  --warmups 2 `<br>  --measured-runs 5 `<br>  --max-new-tokens 64 `<br>  --output results\qnn.json</pre><p>That command does not silently fall back to CPU. The artifact is a GENIE/QNN bundle, the config uses the QNN HTP backend, and the runner uses QAIRT libraries plus ADSP_LIBRARY_PATH for the Hexagon/HTP target.</p><h3>Results</h3><p>We used one fixed prompt, deterministic generation, max_new_tokens=64, two warmups, and five measured runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQFuPqbw_QLW9tosZsTuVw.png" /></figure><p>The headline is generation throughput: the quantized GENIE/QNN path reached about 9.2x higher tokens/sec than the FP PyTorch CPU baseline on the local Snapdragon Windows ARM64 machine.</p><p>Latency needs careful wording. The two paths are not the same runtime. The FP baseline is PyTorch CPU. The quantized path is GENIE/QNN/HTP and includes native runner initialization/profile overhead in the command-line measurement. So the clean comparison is not “same model, same runtime, only precision changed.” It is “developer FP CPU baseline versus practical quantized Qualcomm NPU deployment path.”</p><h3>What Developers Should Take Away</h3><p>First, quantization is not just a compression trick. For edge deployment, it is the step that makes the model fit the target runtime and hardware path. A full-precision Hugging Face model is easy to load in PyTorch, but that does not mean it is ready for an NPU.</p><p>Second, AIMET is a preparation tool, not the NPU runtime. You run AIMET on a capable host, produce quantized/exported artifacts, and then run those artifacts through a deployment runtime like GENIE/QNN.</p><p>Third, always separate artifact types. The 17 GB AIMET checkpoint is useful for quantization/export provenance. The smaller GENIE bundle is the practical local deployment artifact. Downloading the wrong one can cost hours without moving the benchmark forward.</p><p>Finally, if the goal is a clean quantization case study, start with a small smoke benchmark, verify the QNN/HTP runtime, then run the full measured benchmark. Do not download every available model asset until you know which artifact is actually needed for the path you want to test.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6979e69f45c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Offline Note Taker: Building Private Meeting Notes on Snapdragon X Elite with Whisper, Qwen, and…]]></title>
            <link>https://shivaylamba.medium.com/offline-note-taker-building-private-meeting-notes-on-snapdragon-x-elite-with-whisper-qwen-and-be1090adefff?source=rss-af8e6cef0c35------2</link>
            <guid isPermaLink="false">https://medium.com/p/be1090adefff</guid>
            <dc:creator><![CDATA[Shivay Lamba]]></dc:creator>
            <pubDate>Thu, 28 May 2026 07:11:31 GMT</pubDate>
            <atom:updated>2026-05-28T07:11:31.481Z</atom:updated>
            <content:encoded><![CDATA[<h3>Offline Note Taker: Building Private Meeting Notes on Snapdragon X Elite with Whisper, Qwen, and Qualcomm NPU</h3><p>Meetings are where decisions happen.</p><p>They are also where context disappears.</p><p>A task gets assigned. A deadline is mentioned. Someone raises a blocker. Five minutes later, the conversation has moved on. By the time the meeting ends, everyone vaguely remembers what happened, but nobody has a perfect record of who owns what.</p><p>Most modern meeting assistants solve this by sending your audio to the cloud.</p><p>That works, but it creates an obvious problem: meetings often contain product strategy, customer details, internal roadmaps, hiring conversations, financial discussions, and unfinished ideas. These are exactly the kinds of conversations you may not want leaving your machine.</p><p>So I built Offline Note Taker, a Windows desktop app that records or imports meeting audio, transcribes it locally using Whisper, and generates structured meeting notes with an on-device LLM.</p><p>The goal is simple:</p><blockquote>Turn meeting audio into private, structured, timestamp-grounded notes without sending audio, transcripts, or prompts to the cloud.</blockquote><h3>The Idea</h3><p>The app is designed for Snapdragon X Elite / Qualcomm NPU devices.</p><p>The core pipeline looks like this:</p><p>Meeting audio -&gt; local audio preprocessing -&gt; Whisper transcription on Snapdragon NPU -&gt; timestamped transcript -&gt; transcript chunking -&gt; local LLM notes generation -&gt; grounded action items, decisions, blockers, and Q&amp;A -&gt; local exports</p><p>The important part is not just that it generates notes.</p><p>The important part is that the app is built around a local-first promise:</p><ul><li>audio stays on the device</li><li>transcript stays on the device</li><li>meeting notes are generated locally</li><li>exports are written locally</li><li>diagnostics are local</li><li>Qualcomm SDK and model assets are detected locally, not bundled or uploaded</li></ul><p>This is not a wrapper around a hosted API. It is a local AI workflow.</p><h3>Why Snapdragon X Elite?</h3><p>Snapdragon X Elite machines are interesting because they bring a serious NPU into everyday Windows laptops.</p><p>That changes the shape of local AI apps.</p><p>Instead of treating the laptop as a thin client for cloud inference, you can start moving real workloads onto the device:</p><ul><li>speech-to-text</li><li>local summarization</li><li>document understanding</li><li>meeting intelligence</li><li>personal agents</li><li>private productivity tools</li></ul><p>For this app, the first high-value workload is transcription.</p><p>Whisper is computationally expensive enough that acceleration matters, but practical enough that users can immediately understand the value. If the transcript appears quickly and locally, the demo becomes real.</p><h3>Whisper: The First Local AI Layer</h3><p>For transcription, the app targets Qualcomm AI Hub’s Whisper Windows path with Whisper-Base as the practical baseline.</p><p>The reason is pragmatic: instead of starting with a research-only model export path, the app integrates around a working Windows sample path that uses ONNX Runtime execution provider support on Snapdragon hardware.</p><p>In the app, Whisper is abstracted behind a runner interface.</p><p>That means the GUI and meeting pipeline do not care whether transcription comes from:</p><ul><li>Qualcomm Whisper Windows</li><li>a future ExecuTorch + QNN path</li><li>a CPU fallback</li><li>another local transcription engine</li></ul><p>The app only expects a timestamped transcript with backend diagnostics.</p><p>A transcript result includes things like:</p><pre>{<br>  &quot;backend&quot;: &quot;qualcomm_whisper_windows&quot;,<br>  &quot;latency_ms&quot;: 18420,<br>  &quot;real_time_factor&quot;: 0.42,<br>  &quot;segments&quot;: [<br>    {<br>      &quot;start&quot;: &quot;00:00:00.000&quot;,<br>      &quot;end&quot;: &quot;00:00:07.200&quot;,<br>      &quot;text&quot;: &quot;Simon, you are responsible for delivering the app by tomorrow.&quot;<br>    }<br>  ]<br>}</pre><p>That backend field matters.</p><p>For a hardware demo, it is not enough to say “AI is running locally.” The app should show what actually ran, where it ran, how long it took, and what fallback path was used if something failed.</p><h3>Qwen and Local Meeting Notes</h3><p>After transcription, the next layer is meeting intelligence.</p><p>The app supports a local LLM notes runner, with the practical path focused on Qwen3–4B through Qualcomm Genie / QAIRT. Qwen2.5–7B-Instruct remains an important target model, but I do not present it as the production NPU path unless the exact target chipset, runtime, artifact, and profiling path are verified.</p><p>That distinction is important.</p><p>A polished AI demo should not overclaim. It should say clearly:</p><ul><li>what works today</li><li>what is configured locally</li><li>what is experimental</li><li>what is future-facing</li></ul><p>For the current demo beta, the strongest path is:</p><p>Whisper Windows / Whisper-Base on Snapdragon NPU -&gt; transcript -&gt; Qwen3-4B Genie local notes generation -&gt; validated meeting notes</p><p>The app can still fall back to deterministic transcript-grounded extraction when the LLM output is invalid, truncated, slow, or unavailable.</p><p>That fallback is not there to fake the demo. It is there because real local AI products need reliability.</p><p>A user should never lose the meeting just because the LLM failed to return clean JSON.</p><h3>Transcript First, Notes Second</h3><p>One important UX decision was to show the transcript first.</p><p>Originally, the app tried to behave like a single chat wall. That was confusing. The user would record a meeting, wait, and not know whether Whisper was running, whether Qwen was running, whether the NPU was active, or whether the app was stuck.</p><p>So I changed the flow:</p><ol><li>Record or upload audio.</li><li>Run local Whisper.</li><li>Show the transcript immediately.</li><li>Start local LLM notes generation.</li><li>Show progress while notes are being generated.</li><li>Validate notes.</li><li>Display clean final notes.</li><li>Enable Q&amp;A and export.</li></ol><p>This makes the product feel more honest.</p><p>Even if notes take longer, the user immediately sees that transcription worked. They can inspect the raw transcript, verify the model heard the meeting correctly, and then wait for the local LLM to extract structure.</p><h3>The Meeting Workspace</h3><p>The app is built as a Python Qt desktop app.</p><p>The UI is organized like a local meeting workspace:</p><ul><li>left sidebar for meeting history</li><li>center conversation flow for record/upload/transcript/notes/Q&amp;A</li><li>right panel for transcript, exports, runtime status, and performance proof</li><li>setup wizard for local Qualcomm asset paths</li><li>runtime doctor for checking dependencies</li><li>local session storage under the user’s app data directory</li></ul><p>Each meeting session stores local artifacts:</p><p>session/ audio.wav transcript.json notes.json diagnostics.json exports/ meeting_notes.md meeting_transcript.txt meeting_summary.json meeting_transcript.srt meeting_transcript.vtt</p><p>This makes the app feel less like a fragile demo script and more like a real beta product.</p><p>You can reopen meetings, search previous transcripts, rerun notes, export again, and inspect diagnostics.</p><h3>Grounding: The Hard Part</h3><p>The hardest part of meeting notes is not writing a nice summary.</p><p>The hard part is not inventing things.</p><p>If the transcript says:</p><blockquote>Simon, you are responsible for delivering the app by tomorrow.</blockquote><p>The app should extract:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g8_mYx3qOF0aLbC5AvRccQ.png" /></figure><p>But if the transcript does not mention a deadline, the app should say:</p><p>Deadline: not mentioned</p><p>It should not guess.</p><p>To make this reliable, the app uses an evidence-first approach:</p><ol><li>Parse transcript segments with timestamps.</li><li>Extract candidate action items, decisions, deadlines, risks, and questions.</li><li>Ask the local LLM to produce structured notes.</li><li>Validate the model output against transcript evidence.</li><li>Remove unsupported decisions or action items.</li><li>Preserve fallback notes if the LLM output is invalid.</li></ol><p>This gives the app a stronger safety story.</p><p>The final notes are clean, but the diagnostics still track what happened:</p><ul><li>unsupported decisions removed</li><li>citation coverage</li><li>fallback reason</li><li>backend used</li><li>Qwen elapsed time</li><li>Whisper latency</li><li>real-time factor</li></ul><p>For a recruiter or technical reviewer, this matters because it shows that the app is not just prompt engineering. It is a system with validation, observability, and failure handling.</p><h3>The Runtime Doctor</h3><p>Local AI apps fail in boring ways.</p><p>A missing DLL. A wrong model path. A broken environment variable. A model bundle downloaded to the wrong directory. A Python environment mismatch.</p><p>So I added a runtime doctor.</p><p>The app checks:</p><ul><li>Whisper Windows app path</li><li>Whisper encoder and decoder ONNX paths</li><li>Whisper Python environment</li><li>QAIRT path</li><li>genie-t2t-run.exe</li><li>Qwen Genie bundle</li><li>ADSP_LIBRARY_PATH</li><li>NPU visibility</li><li>configured local settings</li></ul><p>The CLI also supports:</p><p>offline-note-taker doctor offline-note-taker doctor --json</p><p>This is useful for debugging, but also useful for demos.</p><p>Before showing the app, I can run the doctor and prove the local runtime is configured.</p><h3>Performance and Local Proof</h3><p>The app includes a Performance panel with a copyable proof report.</p><p>After a run, it shows:</p><ul><li>Whisper backend</li><li>Whisper latency</li><li>Whisper real-time factor</li><li>Notes backend</li><li>Qwen elapsed time</li><li>fallback reason</li><li>NPU detected status</li><li>diagnostics path</li><li>session path</li></ul><p>This is the part I would show in a technical interview.</p><p>Not just “look, it generated notes,” but:</p><blockquote>Here is the transcript. Here are the notes. Here are the citations. Here is the backend. Here is the latency. Here is the local diagnostics file. Here is the NPU visible in Task Manager.</blockquote><p>That turns the demo from a UI prototype into a credible local AI system.</p><h3>Evals: Making Quality Measurable</h3><p>I also added an evaluation command:</p><p>offline-note-taker eval offline-note-taker eval --json</p><p>The eval suite uses golden transcript fixtures covering:</p><ul><li>clear owners and deadlines</li><li>ambiguous owners</li><li>no action items</li><li>decisions vs suggestions</li><li>noisy ASR wording</li><li>long transcript chunking</li></ul><p>The metrics include:</p><ul><li>action item extraction count</li><li>owner extraction accuracy</li><li>deadline extraction accuracy</li><li>unsupported decision count</li><li>citation coverage</li><li>fallback rate</li></ul><p>A sample benchmark table looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Y-oh_vp3m-czRsYsAJ2lw.png" /></figure><h3>Final Thought</h3><p>For the last decade, the default assumption was that useful AI apps had to be cloud apps.</p><p>That assumption is changing.</p><p>With hardware like Snapdragon X Elite, runtimes like QAIRT and Genie, model hubs like Qualcomm AI Hub, and efficient open models like Whisper and Qwen, we can build a new class of local-first AI products.</p><p>Offline Note Taker is my attempt to explore that future through a practical workflow everyone understands: meetings.</p><p>Record a meeting. Transcribe it locally. Generate notes locally. Ask questions locally. Export locally.</p><p>No cloud required.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be1090adefff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nova IDE Desktop: Bringing Local Agentic Coding to Snapdragon X Elite with WebGPU and LiteRT LM]]></title>
            <link>https://shivaylamba.medium.com/nova-ide-desktop-bringing-local-agentic-coding-to-snapdragon-x-elite-with-webgpu-and-litert-lm-a521fb606fec?source=rss-af8e6cef0c35------2</link>
            <guid isPermaLink="false">https://medium.com/p/a521fb606fec</guid>
            <category><![CDATA[gemma-4]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Shivay Lamba]]></dc:creator>
            <pubDate>Wed, 27 May 2026 12:07:45 GMT</pubDate>
            <atom:updated>2026-05-27T12:09:04.826Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This project is inspired by and built on top of the original browser-based Nova IDE by Kartikey Rawat, described in </em><a href="https://medium.com/@carrycooldude/nova-ide-redefining-local-coding-with-snapdragon-x-elite-and-webgpu-73b80abad168"><em>“Nova IDE: Redefining Local Coding with Snapdragon X Elite and WebGPU.” </em></a><em>The original project demonstrated that a browser-based coding environment could run local AI inference using WebGPU on Snapdragon X Elite-class hardware. Our desktop version extends that foundation into a real local coding application with Electron, JavaScript, LiteRT LM, real filesystem access, and a safer agentic coding workflow.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BcnpXKJOcUDpfvG29mijxw.png" /></figure><h3>From Browser Demo to Desktop Coding Agent</h3><p>The original Nova IDE proved an important idea: AI-assisted coding does not have to depend entirely on cloud APIs. By using WebGPU, the browser can access GPU acceleration directly and run local models on modern hardware such as the Snapdragon X Elite and its Qualcomm Adreno GPU.</p><p>Our desktop version takes that same local-first idea and asks a slightly different question:</p><p>What if this was not just a browser demo, but a real desktop code editor?</p><p>That means opening actual folders, reading and writing real files, preserving privacy, and giving the AI agent enough workspace context to behave more like a coding partner than a simple chatbot.</p><h3>Why Snapdragon X Elite and WebGPU Matter</h3><p>Snapdragon X Elite is especially interesting for this kind of application because it combines strong performance with power efficiency. The Qualcomm Adreno GPU can be exposed through Chromium’s WebGPU implementation, which means an Electron app can still use the same browser-grade GPU acceleration path.</p><p>In our architecture, Electron provides the native desktop shell, while the renderer remains a web application. That is important because LiteRT LM runs in the renderer and uses WebGPU for local inference.</p><p>So the stack becomes:</p><p><em>Electron Desktop App<br> ↓<br>Chromium Renderer<br> ↓<br>WebGPU<br> ↓<br>Qualcomm Adreno GPU<br> ↓<br>LiteRT LM Local Inference</em></p><p>This lets us keep the portability of web technologies while adding the practical capabilities users expect from a desktop IDE.</p><h3>Moving from MediaPipe GenAI to LiteRT LM</h3><p>The original browser Nova IDE used MediaPipe GenAI. In this desktop version, we replaced that layer with LiteRT LM for Web.</p><p>Instead of loading a MediaPipe .task model, the app now loads .litertlm models such as Gemma 4 E2B or E4B packaged for LiteRT LM. The model can be downloaded, uploaded manually, cached locally, or discovered from a desktop model folder.</p><p>This matters because LiteRT LM is designed for efficient on-device inference and fits naturally with the WebGPU-based runtime model. Once loaded, prompts and code context stay on the machine.</p><p>LiteRT LM stays in the Electron renderer because that is where Chromium exposes WebGPU:</p><pre>const { Engine } = await import(&#39;@litert-lm/core&#39;);<br><br>const engine = await Engine.create({<br>  model: modelStream,<br>  mainExecutorSettings: {<br>    maxNumTokens: 8192,<br>  },<br>});<br><br>const conversation = await engine.createConversation({<br>  sessionConfig: {<br>    samplerParams: {<br>      k: 40,<br>      temperature: 0.7,<br>      seed: 42,<br>    },<br>    maxOutputTokens: 8192,<br>  },<br>});</pre><p>That gives us a local inference path:</p><p><em>Electron Renderer → Chromium WebGPU → Adreno GPU → LiteRT LM</em></p><h3>Real Filesystem Access</h3><p>The browser version used IndexedDB as a virtual filesystem. That is great for a demo, but a real coding workflow needs real files.</p><p>The Electron version adds a secure filesystem bridge:</p><ul><li>Open a local folder</li><li>Read workspace files</li><li>Save files to disk</li><li>Create new files</li><li>Rename files</li><li>Delete files</li><li>Save as</li><li>Refresh the workspace tree</li></ul><p>The renderer does not get direct Node.js access. Instead, Electron’s preload script exposes a small window.novaDesktop API, and the main process validates every path before touching disk. Writes are restricted to the selected workspace. That gives us a more realistic IDE experience without giving the web layer unrestricted filesystem power.</p><pre>contextBridge.exposeInMainWorld(&#39;novaDesktop&#39;, {<br>  selectWorkspace: () =&gt; ipcRenderer.invoke(&#39;nova:select-workspace&#39;),<br>  readFile: path =&gt; ipcRenderer.invoke(&#39;nova:read-file&#39;, path),<br>  writeFile: (path, content) =&gt;<br>    ipcRenderer.invoke(&#39;nova:write-file&#39;, path, content),<br>});</pre><p>The main process validates every path before touching disk:</p><pre>function resolveWorkspacePath(relativePath = &#39;/&#39;) {<br>  assertWorkspaceRoot();<br><br>  const withoutLeadingSlash = normalizeRelativePath(relativePath).slice(1);<br>  const resolved = path.resolve(workspaceRoot, withoutLeadingSlash);<br>  const rootWithSep = workspaceRoot.endsWith(path.sep)<br>    ? workspaceRoot<br>    : `${workspaceRoot}${path.sep}`;<br><br>  if (resolved !== workspaceRoot &amp;&amp; !resolved.startsWith(rootWithSep)) {<br>    throw new Error(&#39;Path is outside the open workspace&#39;);<br>  }<br><br>  return resolved;<br>}</pre><p>This keeps agentic writes inside the selected workspace.</p><h3>Agentic Coding Modes</h3><p>A key change in the desktop app is the AI experience. Instead of one generic chat box, the app now has four modes:</p><p>Ask<br>Read-only codebase Q&amp;A. This mode is for understanding code, explaining files, and answering questions without showing apply buttons or writing changes.</p><p>Edit<br>Focused changes for the current selection or active file. This is where inline code edits and applyable code blocks make sense.</p><p>Agent<br>Multi-file tasks. The agent can inspect the workspace, search files, read relevant code, and propose changes across multiple files.</p><p>Architect<br>Planning mode. This is for implementation plans, architecture explanations, design tradeoffs, and test strategies.</p><p>This mode separation is important because not every AI interaction should be treated as an edit. Sometimes the right behavior is to explain. Sometimes it is to plan. Sometimes it is to propose a change.</p><h3>Safer Agentic File Changes</h3><p>One of the most important design decisions was this:</p><p>The agent should not directly overwrite files.</p><p>Instead, file-writing tools create proposals. The user sees a review surface with:</p><ul><li>changed file path</li><li>change type</li><li>added/removed line counts</li><li>diff preview</li><li>Apply</li><li>Discard</li><li>Apply all</li><li>Discard all</li><li>Rollback latest</li></ul><p>Before a proposal is applied, the app creates a checkpoint of affected files. If something goes wrong, the user can roll back the latest applied agent change.</p><p>This makes the agent feel powerful without making it feel reckless.</p><h3>Workspace Awareness</h3><p>To make the agent more useful, we added a lightweight local workspace index. The index scans the active workspace and tracks:</p><ul><li>file paths</li><li>languages</li><li>sizes</li><li>snippets</li><li>simple imports</li><li>searchable content</li></ul><p>Heavy folders and binary assets are excluded, including .git, node_modules, dist, release, and .litertlm files.</p><p>This lets the app answer questions like:</p><p>Which file contains wait_json and what does it do?</p><p>without relying entirely on the model to guess. The app can search the workspace directly, find the symbol, surface the file and line numbers, and then ask the model to explain the relevant snippet.</p><p>That hybrid approach is important for local models. Instead of expecting the model to magically know the whole project, the IDE gives it grounded context from real files.</p><p>Before asking the model to reason about code, the app can search locally:</p><pre>export function searchExactSymbol(symbol, maxResults = 20) {<br>  const needle = String(symbol || &#39;&#39;).trim();<br>  const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, &#39;\\$&amp;&#39;);<br>  const symbolRegex = new RegExp(`\\b${escaped}\\b`);<br><br>  const results = [];<br><br>  for (const file of vfs.files.values()) {<br>    const lines = String(file.content || &#39;&#39;).split(&#39;\n&#39;);<br>    const matches = [];<br><br>    for (let i = 0; i &lt; lines.length; i++) {<br>      if (!symbolRegex.test(lines[i])) continue;<br><br>      matches.push({<br>        line: i + 1,<br>        text: lines[i],<br>      });<br>    }<br><br>    if (matches.length) {<br>      results.push({<br>        path: file.path,<br>        language: file.language,<br>        matches,<br>      });<br>    }<br>  }<br><br>  return results.slice(0, maxResults);<br>}</pre><p>So a question like:</p><p>Which file contains wait_json and what does it do?</p><p>does not depend on the model guessing. The IDE finds the symbol first, then asks LiteRT LM to explain the relevant snippet.</p><h3>Agent Tools</h3><p>The agent implementation builds on the existing Nova example, but expands the tool layer. The local agent now has tools such as:</p><p>list_files search_workspace read_file propose_file_change create_file delete_file finish</p><p>The workflow is intentionally visible. The UI shows an agent timeline with steps such as:</p><p>Scanning workspace context Agent thinking Tool call: search_workspace Tool result Proposed file change Ready for review</p><p>This makes agentic coding easier to trust. You can see what the agent is doing instead of watching a black-box response appear.</p><p>The agent has workspace-aware tools:</p><pre>const ideTools = [<br>  {<br>    name: &#39;list_files&#39;,<br>    description: &#39;Lists workspace files.&#39;,<br>    execute: async () =&gt; [...vfs.files.keys()].join(&#39;\n&#39;),<br>  },<br>  {<br>    name: &#39;search_workspace&#39;,<br>    description: &#39;Searches filenames and file contents.&#39;,<br>    execute: async (args) =&gt; searchWorkspace(args.query),<br>  },<br>  {<br>    name: &#39;read_file&#39;,<br>    description: &#39;Reads a file from the workspace.&#39;,<br>    execute: async (args) =&gt; {<br>      const file = vfs.readFile(&#39;/&#39; + args.path.replace(/^\//, &#39;&#39;));<br>      return file ? file.content : &#39;Error: File not found.&#39;;<br>    },<br>  },<br>];</pre><h3>Technical Architecture</h3><p>At a high level, the desktop app has three layers:</p><p><em>Main Process<br>- Electron app lifecycle<br>- Native menus<br>- File dialogs<br>- Secure filesystem IPC<br>- Local model discovery</em></p><p><em>Preload Bridge<br>- Small window.novaDesktop API<br>- No direct Node access in renderer</em></p><p><em>Renderer<br>- CodeMirror editor<br>- LiteRT LM inference<br>- AI chat panel<br>- Agent modes<br>- Workspace index<br>- Proposal/checkpoint system</em></p><p>LiteRT LM stays in the renderer because that is where Chromium exposes WebGPU. Electron adds the desktop capabilities around it.</p><h3>Why This Matters</h3><p>Most AI coding tools today assume cloud inference. That works well for frontier-scale models, but it comes with tradeoffs: network dependency, latency, cost, and privacy concerns.</p><p>A local-first IDE changes the feel of the workflow. Your code stays on your machine. The model runs on your hardware. The editor can work offline once the model is available. On Snapdragon X Elite-class devices, WebGPU makes that experience practical inside a JavaScript desktop app.</p><p>This is not just about replacing the cloud. It is about exploring a different kind of coding environment: one where the agent is private, local, inspectable, and deeply integrated with the filesystem.</p><h3>Conclusion</h3><p>The desktop version of Nova IDE extends the original browser-based experiment into a more complete local coding environment.</p><p>It keeps the spirit of the original project: WebGPU-powered, local-first AI coding on Snapdragon hardware. But it adds the pieces needed for a real developer workflow:</p><ul><li>Electron desktop shell</li><li>real filesystem access</li><li>LiteRT LM support</li><li>local model loading</li><li>workspace indexing</li><li>explicit AI modes</li><li>agent tools</li><li>reviewable file proposals</li><li>rollback checkpoints</li></ul><p>The result is a glimpse of what local agentic coding can become: not just a chatbot inside an editor, but a private desktop coding agent powered by JavaScript, WebGPU, and modern edge AI hardware.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a521fb606fec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LiteRT LM on the Web: Running Generative AI Locally in the Browser]]></title>
            <link>https://shivaylamba.medium.com/litert-lm-on-the-web-running-generative-ai-locally-in-the-browser-f6d5393c3756?source=rss-af8e6cef0c35------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6d5393c3756</guid>
            <dc:creator><![CDATA[Shivay Lamba]]></dc:creator>
            <pubDate>Mon, 25 May 2026 14:01:54 GMT</pubDate>
            <atom:updated>2026-05-25T14:31:25.180Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j79RlWmkUxlUc3zaNJHI6g.png" /></figure><p>For the last few years, “AI in the browser” usually meant one of two things: either calling a cloud API from JavaScript, or using a highly specialized on-device runtime with a narrow task API. That is changing.</p><p>Google’s LiteRT LM Web API brings a more direct local language-model runtime to JavaScript and TypeScript applications. Instead of sending prompts to a remote server, a web app can load a compatible model, run inference with WebGPU, stream tokens back to the UI, and keep user data on the device.</p><p>That matters because the browser is no longer just a thin client. With WebGPU, IndexedDB/OPFS storage, and model formats designed for edge inference, the browser can become a real local AI runtime.</p><p>In this article, we’ll look at what LiteRT LM does, how it differs from the MediaPipe GenAI LLM Inference API, and how a simple demo app can use LiteRT LM to run a local coding assistant directly in the browser.</p><h3>What Is LiteRT LM?</h3><p>LiteRT LM is Google’s lightweight runtime for running large language models on-device. The Web API is available through the @litert-lm/core package and is designed for JavaScript and TypeScript browser applications.</p><p>According to Google’s docs, the LiteRT LM Web API is currently an early preview that supports text-in/text-out inference using WebGPU. It currently supports a limited set of web-compatible Gemma 4 models, including:</p><ul><li>gemma-4-E2B-it-web.litertlm</li><li>gemma-4-E4B-it-web.litertlm</li></ul><p>The basic programming model looks like this:</p><pre>import { Engine } from &#39;@litert-lm/core&#39;;<br><br>const engine = await Engine.create({<br>  model: &#39;https://huggingface.co/litert-community/gemma-4-E2B-it-litert-lm/resolve/main/gemma-4-E2B-it-web.litertlm&#39;,<br>  mainExecutorSettings: {<br>    maxNumTokens: 8192,<br>  },<br>});<br><br>const conversation = await engine.createConversation({<br>  preface: {<br>    messages: [<br>      { role: &#39;system&#39;, content: &#39;You are a helpful assistant.&#39; },<br>    ],<br>  },<br>});<br><br>const stream = conversation.sendMessageStreaming(&#39;Explain WebGPU simply.&#39;);<br><br>for await (const chunk of stream) {<br>  for (const item of chunk.content) {<br>    if (item.type === &#39;text&#39;) {<br>      console.log(item.text);<br>    }<br>  }<br>}</pre><p>The important pieces are:</p><ul><li>Engine: loads and owns the model runtime.</li><li>Conversation: represents a chat session.</li><li>sendMessageStreaming: streams generated output.</li><li>cancel(): stops generation.</li><li>delete(): releases runtime resources.</li></ul><p>That shape feels much closer to how modern AI apps are built: not as one-off text generation calls, but as ongoing sessions with context, streaming, cancellation, and lifecycle management.</p><blockquote>On Snapdragon X Elite systems, this WebGPU path can map directly onto the Qualcomm Adreno GPU, turning the browser into a local AI inference surface. A practical example is <a href="https://github.com/carrycooldude/Nova-IDE">Nova IDE</a> by Kartikey Rawat, a local-first coding environment that uses WebGPU and MediaPipe/LiteRT-style on-device inference so code and prompts stay inside the browser while generation runs on local hardware.</blockquote><h3>Why Local Browser Inference Matters</h3><p>Running an LLM in the browser has three big advantages.</p><p>First, privacy. User prompts, documents, and code do not need to leave the machine. This is especially important for developer tools, internal enterprise apps, education, healthcare prototypes, and offline-first products.</p><p>Second, latency control. Once the model is loaded, token generation happens locally. You avoid round trips to a cloud endpoint.</p><p>Third, deployment simplicity. A static web app can ship a local AI experience without requiring a backend inference server.</p><p>There are tradeoffs, of course. Model files are large. WebGPU support varies by browser and hardware. First load can be slow. Memory pressure is real. But the direction is exciting: browser apps can now own more of the AI stack.</p><h3>How LiteRT LM Differs From MediaPipe GenAI</h3><p>Google already has a browser-side LLM option through MediaPipe Tasks GenAI, specifically the LLM Inference API. That API also runs LLMs on-device in web apps and uses the @mediapipe/tasks-genai package.</p><p>Docs: <a href="https://ai.google.dev/edge/mediapipe/solutions/genai/llm_inference/web_js">MediaPipe LLM Inference for Web</a></p><p>At a high level, both approaches can run local models in the browser. The difference is mostly in the abstraction.</p><p>MediaPipe is a task-oriented API. LiteRT LM is a runtime/conversation-oriented API.</p><h3>MediaPipe GenAI Style</h3><p>MediaPipe’s LLM Inference API follows the broader MediaPipe Solutions pattern:</p><pre>const genai = await FilesetResolver.forGenAiTasks(<br>  &#39;https://cdn.jsdelivr.net/npm/@mediapipe/tasks-genai@latest/wasm&#39;<br>);<br><br>const llmInference = await LlmInference.createFromOptions(genai, {<br>  baseOptions: {<br>    modelAssetPath: &#39;/assets/model.litertlm&#39;,<br>  },<br>  maxTokens: 1000,<br>  topK: 40,<br>  temperature: 0.8,<br>  randomSeed: 101,<br>});<br><br>const response = await llmInference.generateResponse(inputPrompt);</pre><p>Streaming is also supported:</p><pre>llmInference.generateResponse(inputPrompt, (partialResult, done) =&gt; {<br>  output.textContent += partialResult;<br>});</pre><p>This is very approachable. If your app has a prompt box and an output area, MediaPipe gets you moving quickly.</p><h3>LiteRT LM Style</h3><p>LiteRT LM starts from an engine and conversation model:</p><pre>const engine = await Engine.create({ model });<br>const conversation = await engine.createConversation();<br><br>for await (const chunk of conversation.sendMessageStreaming(prompt)) {<br>  // render streamed content<br>}</pre><p>This is a better mental model for applications that have:</p><ul><li>chat history</li><li>system prompts</li><li>multiple sessions</li><li>cancellation</li><li>tool use</li><li>agent loops</li><li>local model lifecycle management</li></ul><p>The API feels less like “run this task” and more like “host a local model runtime.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*10EKMzTYdO3YgJH_WPwn8w.png" /></figure><h3>The Practical Difference for Developers</h3><p>The biggest practical difference is where the complexity lives.</p><p>With MediaPipe, the app often has to build its own conversation protocol. You may format prompts manually:</p><pre>&lt;start_of_turn&gt;user<br>Explain this code.<br>&lt;end_of_turn&gt;<br>&lt;start_of_turn&gt;model</pre><p>That can work, but the app is responsible for managing history, prompt templates, system instructions, and turns.</p><p>With LiteRT LM, conversation is part of the API:</p><pre>const conversation = await engine.createConversation({<br>  preface: {<br>    messages: [<br>      { role: &#39;system&#39;, content: &#39;You are a concise coding assistant.&#39; },<br>    ],<br>  },<br>});<br><br>await conversation.sendMessage({<br>  role: &#39;user&#39;,<br>  content: &#39;Explain this function.&#39;,<br>});</pre><p>For a demo chat app, this is cleaner. For an agentic app, it is much cleaner.</p><h3>How We Use LiteRT LM in a Demo Application</h3><p>Our demo app is intentionally simple: it is a browser-based coding environment used to show how local inference can work in a real UI.</p><p>The important part is not the IDE itself. The IDE is just a convenient example because it has all the things a local AI assistant needs:</p><ul><li>user input</li><li>file context</li><li>streaming output</li><li>long-running model loading</li><li>local persistence</li><li>an agent mode that can read and write local files</li></ul><p>The app uses LiteRT LM through a wrapper called AIEngine.</p><p>Conceptually, the wrapper does four jobs:</p><ol><li>Load a .litertlm model.</li><li>Create a LiteRT LM conversation.</li><li>Stream generated tokens into the chat UI.</li><li>Manage local model caching and cleanup.</li></ol><p>A simplified version looks like this:</p><pre>import { Engine } from &#39;@litert-lm/core&#39;;<br><br>class AIEngine {<br>  async loadModel(modelSource) {<br>    this.engine = await Engine.create({<br>      model: modelSource,<br>      mainExecutorSettings: {<br>        maxNumTokens: 8192,<br>      },<br>    });<br><br>    this.conversation = await this.engine.createConversation({<br>      preface: {<br>        messages: [<br>          {<br>            role: &#39;system&#39;,<br>            content: &#39;You are an expert coding assistant.&#39;,<br>          },<br>        ],<br>      },<br>    });<br>  }<br><br>  async generate(prompt, onToken) {<br>    let fullText = &#39;&#39;;<br><br>    const stream = this.conversation.sendMessageStreaming(prompt);<br><br>    for await (const chunk of stream) {<br>      for (const item of chunk.content) {<br>        if (item.type === &#39;text&#39;) {<br>          fullText += item.text;<br>          onToken(fullText);<br>        }<br>      }<br>    }<br><br>    return fullText;<br>  }<br><br>  async dispose() {<br>    await this.conversation?.delete();<br>    await this.engine?.delete();<br>  }<br>}</pre><p>The UI does not need to know much about LiteRT LM. It only calls:</p><pre>await aiEngine.loadModel(modelFileOrUrl);<br><br>await aiEngine.generate(userPrompt, partialText =&gt; {<br>  chatMessage.innerHTML = renderMarkdown(partialText);<br>});</pre><p>That separation matters. It lets the application stay focused on user experience while the model wrapper handles runtime details.</p><h3>Handling Large Model Downloads</h3><p>One lesson from building with browser LLMs: model loading is not just a runtime problem. It is also a storage and memory problem.</p><p>The Gemma 4 LiteRT LM web models are large. If you download the entire file into an array buffer before loading it, the browser can fail with memory allocation errors.</p><p>A better pattern is:</p><ol><li>Download the model as a stream.</li><li>Write chunks directly into OPFS, the browser’s Origin Private File System.</li><li>Load the model from the saved file stream.</li></ol><p>That avoids holding the entire multi-gigabyte model in JavaScript memory.</p><p>A simplified version:</p><pre>async function saveModelToOPFS(filename, response, onProgress) {<br>  const root = await navigator.storage.getDirectory();<br>  const fileHandle = await root.getFileHandle(filename, { create: true });<br>  const writable = await fileHandle.createWritable();<br><br>  const reader = response.body.getReader();<br>  const total = Number(response.headers.get(&#39;content-length&#39;) || 0);<br>  let received = 0;<br><br>  while (true) {<br>    const { done, value } = await reader.read();<br>    if (done) break;<br><br>    await writable.write(value);<br>    received += value.length;<br><br>    onProgress?.(received, total);<br>  }<br><br>  await writable.close();<br><br>  return await fileHandle.getFile();<br>}</pre><p>Then:</p><pre>const response = await fetch(modelUrl);<br>const file = await saveModelToOPFS(&#39;gemma-4-E2B-it-web.litertlm&#39;, response);<br><br>await aiEngine.loadModel(file.stream());</pre><p>This is one of those unglamorous details that makes a local AI demo feel solid instead of fragile.</p><h3>Running the Demo App</h3><p>A minimal Vite setup is enough.</p><p>Install dependencies:</p><p>npm install</p><p>Start the dev server:</p><p>npm run dev</p><p>Open the local URL, usually:</p><p><a href="http://127.0.0.1:5173/">http://127.0.0.1:5173/</a></p><p>If that port is busy, Vite will pick the next one, such as 5174.</p><p>In the app:</p><ol><li>Open the AI panel.</li><li>Select a LiteRT LM model:</li></ol><ul><li>Gemma 4 E2B LiteRT LM for a lighter demo.</li><li>Gemma 4 E4B LiteRT LM for a larger model.</li></ul><p>3. Check “Save to local disk (OPFS)” before downloading.</p><p>4. Click Download.</p><p>5. Wait for the model to initialize.</p><p>6. Start chatting.</p><p>For direct model URLs, use Hugging Face’s resolve/main links, not blob/main page URLs:</p><pre>https://huggingface.co/litert-community/gemma-4-E2B-it-litert-lm/resolve/main/gemma-4-E2B-it-web.litertlm<br>https://huggingface.co/litert-community/gemma-4-E4B-it-litert-lm/resolve/main/gemma-4-E4B-it-web.litertlm</pre><p>The blob/main URL is for viewing the file page in the browser. The resolve/main URL is for downloading the actual model file.</p><h3>Where MediaPipe Still Makes Sense</h3><p>This is not a “LiteRT LM good, MediaPipe bad” situation.</p><p>MediaPipe’s LLM Inference API is still very useful. It has broader documentation, a mature task-oriented feel, model conversion guidance, LoRA documentation, sample apps, and multimodal support for Gemma-3n in the web docs.</p><p>If you are building a quick text-generation demo, MediaPipe may be the fastest route. If you are already using MediaPipe for vision/audio tasks, staying in that ecosystem can also make sense.</p><p>MediaPipe is especially compelling when your app is built around a specific task:</p><ul><li>summarize this document</li><li>answer this one prompt</li><li>classify or transform this input</li><li>run multimodal prompting with supported models</li><li>experiment with documented LoRA workflows</li></ul><p>LiteRT LM becomes more attractive when your app starts to look like a full local AI product:</p><ul><li>chat sessions</li><li>local assistants</li><li>coding tools</li><li>agent loops</li><li>cancellation</li><li>long-lived conversations</li><li>explicit model lifecycle management</li></ul><h3>My Takeaway</h3><p>LiteRT LM is important because it gives web developers a cleaner primitive for local language models.</p><p>MediaPipe GenAI asks: “Do you want to run this LLM task?”</p><p>LiteRT LM asks: “Do you want to host a local language model conversation inside your app?”</p><p>That distinction is subtle, but it changes the architecture.</p><p>For our demo application, LiteRT LM fits because we want the browser to behave like a local AI runtime. The app loads a Gemma 4 .litertlm model, stores it locally, creates a conversation, streams output into the interface, and can use that same runtime for normal chat or more advanced agent behavior.</p><p>The browser is quietly becoming a serious place to run AI. LiteRT LM is one of the clearest signs of that shift.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6d5393c3756" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Local AI Face Recognition Demo with Arduino UNO Q, Modulino, and a Laptop NPU]]></title>
            <link>https://shivaylamba.medium.com/building-a-local-ai-face-recognition-demo-with-arduino-uno-q-modulino-and-a-laptop-npu-b2a5f9ed8a3f?source=rss-af8e6cef0c35------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2a5f9ed8a3f</guid>
            <dc:creator><![CDATA[Shivay Lamba]]></dc:creator>
            <pubDate>Mon, 04 May 2026 05:38:51 GMT</pubDate>
            <atom:updated>2026-05-04T05:38:51.734Z</atom:updated>
            <content:encoded><![CDATA[<p>How we combined Arduino hardware, a distance sensor, a browser camera, and local face recognition into a physical AI demo that runs without the cloud.</p><p>Most AI demos end at the screen.</p><p>A model runs, a result gets printed, maybe a bounding box appears on a camera feed, and then the demo stops there. For this project, we wanted the AI result to leave the screen and become physical.</p><p>The idea was simple:</p><p>```text<br>If someone comes close to the setup, detect their face locally.<br>If the face is known, stay quiet.<br>If the face is unknown, trigger a physical buzzer.<br>```</p><p>That became a local face recognition demo built with an Arduino UNO Q, Modulino Distance, Modulino Buzzer, a Windows ARM64 laptop, ONNX Runtime, and a browser dashboard.</p><p>The project demonstrates a useful edge AI pattern:</p><p>```text<br>Physical sensor -&gt; local AI inference -&gt; physical response<br>```</p><p>The full project is available on GitHub:</p><p><a href="https://github.com/shivaylamba/cavaface-detection-arduino-unoq-npu">https://github.com/shivaylamba/cavaface-detection-arduino-unoq-npu</a></p><p>## What the project does</p><p>This is a proximity-triggered face recognition system.</p><p>The Arduino UNO Q is connected to two Modulino components:</p><p>- Modulino Distance<br>- Modulino Buzzer</p><p>The distance sensor watches the space in front of the demo. When a person brings their hand or face close enough, the system treats that as a trigger. The laptop then captures a recent camera frame, detects the face, converts it into a face embedding, and compares it against a local database of known people.</p><p>If the face matches someone in the database, the dashboard shows a known match and the buzzer stays silent.</p><p>If the face does not match, the dashboard shows an unknown visitor and the laptop asks the Arduino UNO Q to activate the buzzer.</p><p>Everything in the recognition loop runs locally. The camera frame, face embedding, and known-face database stay on the machine. No cloud API is required to decide whether the face is known or unknown.</p><p>## The architecture</p><p>The project has four main layers:</p><p>1. Arduino hardware layer<br>2. Laptop AI layer<br>3. Browser camera and dashboard layer<br>4. Local face database</p><p>Here is the complete flow:</p><p>```text<br>Person approaches the demo<br> |<br> v<br>Modulino Distance measures proximity<br> |<br> v<br>Arduino UNO Q reads the sensor<br> |<br> v<br>Laptop app receives distance readings<br> |<br> + → Browser provides camera frames<br> |<br> + → MediaPipe-style ONNX detector finds the face<br> |<br> + → MobileFaceNet or CavaFace creates an embedding<br> |<br> + → Local database returns best match<br> |<br> v<br>Dashboard shows known or unknown<br> |<br> v<br>Arduino UNO Q triggers buzzer for unknown faces<br>```</p><p>The split is intentional.</p><p>The Arduino side is responsible for interacting with the physical world. It reads the distance sensor and controls the buzzer.</p><p>The laptop side is responsible for the heavier AI work. It handles camera frames, face detection, face embeddings, database comparison, and the demo UI.</p><p>This makes the system easier to explain. The Arduino detects that something happened in the real world. The laptop understands what the camera sees. The Arduino then turns that AI decision back into a physical response.</p><p>## Architecture at a glance</p><p>The demo can be summarized as:</p><p>```text<br>UNO Q + Modulino Distance<br> |<br>Python AI Bridge on Laptop<br> |<br>Browser Camera + Dashboard<br> |<br>Face Detector + Recognition Model<br> |<br>Known Face Database<br> |<br>UNO Q + Modulino Buzzer<br>```</p><p>That is the main idea behind the project: the Arduino board handles real-world sensing and output, while the laptop handles the AI inference and user-facing dashboard.</p><p>## Why Arduino UNO Q?</p><p>The Arduino UNO Q is useful here because it lets the demo connect software intelligence to real physical components.</p><p>In this project, the board does not need to run the face recognition model itself. Instead, it handles the parts that embedded hardware is great at:</p><p>- Reading a physical sensor<br>- Controlling an actuator<br>- Exposing a simple hardware interface to the laptop<br>- Keeping the hardware response reliable</p><p>The laptop communicates with the board using RouterBridge, with a serial fallback available for setups where RouterBridge is not being used.</p><p>From the laptop’s perspective, the board exposes simple actions:</p><p>```text<br>Check if the board is alive<br>Read the current distance<br>Set the distance threshold<br>Trigger the unknown-face buzzer pattern<br>Trigger a fault buzzer pattern<br>```</p><p>The Python application does not need to manage low-level sensor details. It only needs to ask, “How far away is the nearest object?” and tell the board, “Play the unknown-face alert.”</p><p>## The dashboard</p><p>For a live demo, terminal logs are not enough.</p><p>The browser dashboard is the explanation layer. It shows what is happening at each stage so a non-technical viewer can understand the system without reading Python output.</p><p>The dashboard shows:</p><p>- Live camera preview<br>- Distance sensor state<br>- Current face recognition result<br>- Match score<br>- Buzzer decision<br>- Known faces database<br>- Add Known Face workflow<br>- Active recognition model</p><p>This matters because the project is not only a technical prototype. It is something that can be shown in a store, classroom, workshop, or booth. The UI needs to answer the questions people naturally ask:</p><p>- Did the camera connect?<br>- Did the sensor trigger?<br>- Was a face detected?<br>- Was the face known or unknown?<br>- Why did the buzzer sound?<br>- Who is enrolled in the system?<br>- Can we add a new person right now?</p><p>That visibility turns the demo from “a Python script is running” into a clear hardware-plus-AI experience.</p><p>## The face recognition pipeline</p><p>The recognition system has three stages:</p><p>1. Detect the face in the image<br>2. Convert the face into an embedding<br>3. Compare that embedding with known faces</p><p>The app currently supports two face recognition backends:</p><p>- MobileFaceNet<br>- CavaFace</p><p>MobileFaceNet is the current preferred model for the demo because it gave better recognition quality in our testing environment. CavaFace is still available as a fallback so we can switch models without rebuilding the whole application.</p><p>At launch, the app can be configured with:</p><p>```powershell<br> — recognition-model mobilefacenet<br>```</p><p>or:</p><p>```powershell<br> — recognition-model cavaface<br>```</p><p>Both models follow the same basic idea:</p><p>```text<br>Face crop -&gt; neural network -&gt; embedding vector<br>```</p><p>An embedding is a compact numeric representation of a face. Instead of comparing two face images pixel by pixel, the system compares their embeddings.</p><p>MobileFaceNet produces a 128-dimensional embedding.</p><p>CavaFace produces a 512-dimensional embedding.</p><p>Because the dimensions are different, each model uses its own known-face database. A MobileFaceNet embedding cannot be compared directly with a CavaFace embedding.</p><p>## Step 1: Detecting the face</p><p>Before we can recognize a face, we need to find it.</p><p>The project uses a MediaPipe-style ONNX face detector. The detector runs locally through ONNX Runtime. On the Windows ARM64 laptop used for the demo, ONNX Runtime can use the QNN Execution Provider, which allows supported model operations to run on the laptop NPU.</p><p>At a high level, face detection works like this:</p><p>```text<br>1. Resize the camera frame<br>2. Convert the image to RGB<br>3. Normalize the pixel values<br>4. Run the ONNX face detector<br>5. Decode the model’s anchor boxes<br>6. Filter low-confidence detections<br>7. Apply non-maximum suppression<br>8. Select the best face<br>9. Crop the face with a small margin<br>```</p><p>The anchor decoding step converts the detector outputs into real image coordinates. Non-maximum suppression removes duplicate overlapping detections, so the app ends up with a clean face crop.</p><p>That face crop is then passed to the selected recognition model.</p><p>## Step 2: Creating the face embedding</p><p>MobileFaceNet and CavaFace both receive a normalized face image.</p><p>The preprocessing is:</p><p>```text<br>Resize the face to 112 x 112<br>Convert to RGB<br>Normalize pixels to the range [-1, 1]<br>Arrange the tensor as NCHW<br>```</p><p>The model then returns an embedding vector.</p><p>The app normalizes the embedding so it has a length close to 1:</p><p>```python<br>embedding = embedding / np.linalg.norm(embedding)<br>```</p><p>This one step makes matching simple. Once every embedding is normalized, cosine similarity becomes a dot product.</p><p>## Step 3: Storing known faces</p><p>The known-face database is intentionally simple.</p><p>For each enrolled face sample, the app stores:</p><p>- The person’s display name<br>- The model-generated embedding</p><p>For example, one person may have several samples:</p><p>```text<br>Rajath -&gt; sample 1 embedding<br>Rajath -&gt; sample 2 embedding<br>Rajath -&gt; sample 3 embedding<br>```</p><p>Multiple samples help because a person’s face may look different depending on lighting, glasses, head angle, camera distance, or expression.</p><p>The database is stored locally as a compressed NumPy file. There is no remote database and no cloud service involved in the recognition decision.</p><p>## How face enrollment works</p><p>Enrollment means adding a new known person.</p><p>The dashboard includes an Add Known Face screen. The operator enters a name and captures several samples from the live camera.</p><p>During enrollment, the app:</p><p>```text<br>1. Reads live frames from the browser camera<br>2. Detects a face in each frame<br>3. Crops the detected face<br>4. Runs MobileFaceNet or CavaFace<br>5. Normalizes the embedding<br>6. Adds the embedding to the local database<br>7. Saves the updated database<br>```</p><p>This is important: enrollment does not retrain the neural network.</p><p>The model stays fixed. We are only adding new face templates to the local database. That makes enrollment fast enough to use during a demo. A person can stand in front of the camera, capture a few samples, and immediately become part of the known-face list.</p><p>## What happens when a new face arrives</p><p>The runtime flow starts with the distance sensor.</p><p>The Python app continuously reads distance values from the Arduino UNO Q. When the measured distance drops below the configured threshold, the app treats that as a proximity event.</p><p>Then the AI flow starts:</p><p>```text<br>1. Capture recent camera frames<br>2. Find the best face crop<br>3. Run the selected face recognition model<br>4. Normalize the new embedding<br>5. Compare it with every stored embedding<br>6. Pick the highest similarity score<br>7. Apply the recognition threshold<br>8. Publish known or unknown result<br>9. Update the dashboard<br>10. Trigger the buzzer only if the face is unknown<br>```</p><p>The comparison is transparent.</p><p>Because the embeddings are normalized, matching is:</p><p>```python<br>scores = stored_embeddings @ query_embedding<br>best_index = scores.argmax()<br>best_score = scores[best_index]<br>best_name = names[best_index]<br>```</p><p>If the best score is above the threshold, the person is treated as known.</p><p>If the score is below the threshold, the person is treated as unknown.</p><p>The threshold is tunable. A lower threshold accepts more matches, but may increase false positives. A higher threshold is stricter, but may reject a known person if the camera angle or lighting changes.</p><p>## Known face path</p><p>When the best match passes the threshold, the app has a known result.</p><p>The dashboard can show:</p><p>```text<br>Known face matched<br>Name: Rajath<br>Score: 0.72<br>Buzzer: Silent<br>```</p><p>For this demo, silence is the success state. The system recognized the person, so there is no need to alert.</p><p>## Unknown face path</p><p>When the best match does not pass the threshold, the app has an unknown result.</p><p>The dashboard can show:</p><p>```text<br>Unknown face<br>Best score: 0.31<br>Buzzer: Alert sent<br>```</p><p>Then the laptop sends a command to the Arduino UNO Q. The board plays the unknown-face buzzer pattern through the Modulino Buzzer.</p><p>This is the moment where the demo becomes more than a camera app. A model made a decision locally, and the physical hardware responded.</p><p>## Why local AI matters</p><p>This project is intentionally local.</p><p>The camera frame is processed locally. The face detector runs locally. The recognition model runs locally. The known-face database is stored locally. The buzzer decision is made locally.</p><p>That gives the demo a clear edge AI story:</p><p>```text<br>The sensor is local.<br>The camera is local.<br>The model is local.<br>The database is local.<br>The response is local.<br>```</p><p>Local processing also makes the privacy discussion more concrete. Face recognition systems still require consent, careful handling of biometric data, and clear boundaries. But this architecture does not need to send face frames to an external cloud service for inference.</p><p>That is an important distinction for demos, workshops, and edge AI prototypes.</p><p>## Why support both MobileFaceNet and CavaFace?</p><p>The first version of the app used CavaFace. It worked, but in our demo environment the recognition quality was not as strong as we wanted.</p><p>We then added MobileFaceNet as another recognizer. Rather than deleting the CavaFace path, we made the recognition model selectable.</p><p>That gives us two advantages:</p><p>1. We can compare models in the same hardware setup.<br>2. We can switch back to CavaFace if needed.</p><p>The rest of the app does not need to know which model is active. Both recognizers expose the same kind of interface:</p><p>```text<br>Input: face crop<br>Output: normalized embedding<br>```</p><p>That is the useful abstraction. The detector, dashboard, database logic, Arduino communication, and buzzer flow can stay the same while the recognition model changes underneath.</p><p>## End-to-end demo flow</p><p>Here is the full demo experience:</p><p>```text<br>1. The operator starts the Python app.<br>2. The browser dashboard opens.<br>3. The camera stream connects.<br>4. The Arduino UNO Q reports sensor status.<br>5. A person approaches the setup.<br>6. Modulino Distance detects proximity.<br>7. The laptop captures a camera frame.<br>8. The ONNX face detector finds the face.<br>9. MobileFaceNet or CavaFace creates an embedding.<br>10. The app compares it with the local known-face database.<br>11. The dashboard shows the match result.<br>12. The buzzer stays silent for known faces.<br>13. The buzzer sounds for unknown faces.<br>```</p><p>The key point is that the system is not just running AI. It is connecting AI to the physical world in a way that people can immediately understand.</p><p>## What I would improve next</p><p>There are several natural next steps:</p><p>- Add liveness detection<br>- Show model latency directly in the dashboard<br>- Add per-person sample management<br>- Add a side-by-side MobileFaceNet versus CavaFace comparison view<br>- Add a Modulino Pixels module for visual status<br>- Add stricter enrollment quality checks<br>- Add consent and data management controls for real deployments</p><p>For a production face recognition system, there would be much more to consider around privacy, security, liveness detection, tamper resistance, auditability, and user consent.</p><p>But as a demo, this project already shows the core idea clearly: Arduino can sense the world, a local AI model can understand what is happening, and hardware can respond immediately.</p><p>## Closing</p><p>This project started with a simple question:</p><p>```text<br>Can we combine an Arduino sensor, a laptop AI model, and a physical buzzer into one local demo?<br>```</p><p>The answer is yes.</p><p>The Arduino UNO Q handles proximity sensing and physical output. The laptop runs local face detection and recognition using ONNX Runtime. The browser dashboard makes the flow visible. The Modulino Buzzer turns the AI decision into something people can hear.</p><p>That is what makes the demo compelling. It does not just recognize a face. It connects recognition to the real world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2a5f9ed8a3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>