<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://t2ncay.github.io/feed.xml" rel="self" type="application/atom+xml"/><link href="https://t2ncay.github.io/" rel="alternate" type="text/html" hreflang="en"/><updated>2026-11-17T21:56:42+00:00</updated><id>https://t2ncay.github.io/feed.xml</id><title type="html">Tunjay Gafarli</title><subtitle>Computer Engineering Undergrad at Türkiye-Azerbaijan University. Building Vyne: a region-based compiler for deterministic Edge AI, CUDA, and bare-metal microcontrollers. </subtitle><entry><title type="html">The ESP32 Memory Wall: What Bounded Vyne Actually Saves—and What TFLM Wins</title><link href="https://t2ncay.github.io/blog/2026/esp32-memory-wall-vyne-tflm/" rel="alternate" type="text/html" title="The ESP32 Memory Wall: What Bounded Vyne Actually Saves—and What TFLM Wins"/><published>2026-11-17T01:00:00+00:00</published><updated>2026-11-17T01:00:00+00:00</updated><id>https://t2ncay.github.io/blog/2026/esp32-memory-wall-vyne-tflm</id><content type="html" xml:base="https://t2ncay.github.io/blog/2026/esp32-memory-wall-vyne-tflm/"><![CDATA[<p>When deploying neural networks onto microcontrollers like the classic ESP32, the bottleneck rarely starts with raw FLOPs—it starts with static SRAM. You are working inside a few hundred kilobytes shared across your network buffers, runtime metadata, task stacks, and system heap.</p> <p>To test how my compiler, <strong>Vyne</strong>, holds up against the industry standard, I ran a falsifiable, apples-to-apples hardware benchmark on a classic ESP32 (240 MHz, PSRAM disabled, Wi-Fi/BT off) against <strong>TensorFlow Lite for Microcontrollers (TFLM)</strong>.</p> <p>Instead of cherry-picking a workload where Vyne wins everything, I wanted to measure the exact trade-offs: where static region-based scratch saves real memory, what happens when a compiler accidentally falls back to boxed soft-float arithmetic, and where TFLM still wins on raw execution speed.</p> <hr/> <h3 id="-1-the-wall-and-a-falsifiable-experiment">🧱 1. The Wall and a Falsifiable Experiment</h3> <p>To avoid classification accuracy or dataset quirks muddying the systems metrics, both runtimes execute the exact same <strong>Float32 <code class="language-plaintext highlighter-rouge">64 → 32 → 10</code> MLP</strong> (ReLU hidden activation, linear output logits, 2,410 parameters / 9,640 bytes of flash-resident weights).</p> <ul> <li><strong>Identical Weights &amp; Validation:</strong> Trained deterministically for 5 epochs on seed <code class="language-plaintext highlighter-rouge">20261117</code>, exported to <code class="language-plaintext highlighter-rouge">.vwt</code> for Vyne and converted via an equivalent Keras graph into a TFLite FlatBuffer. Both runtimes must pass numerical verification across all 8 test vectors (<code class="language-plaintext highlighter-rouge">atol=2e-5, rtol=2e-4</code>) before a single timing sample is accepted.</li> <li><strong>Strict Timing Protocol:</strong> After 10 warmup passes, each cold-reset run executes 20 batches of 100 inferences timed via the 64-bit <code class="language-plaintext highlighter-rouge">esp_timer_get_time()</code> hardware counter—including input copy, math, and 10 volatile logit stores to prevent dead-code elimination.</li> <li><strong>Fail-Closed Harness:</strong> If <code class="language-plaintext highlighter-rouge">AllocateTensors()</code> fails, outputs drift, or a capture drops batches, the runner rejects the run and logs the failure rather than publishing partial numbers.</li> </ul> <hr/> <h3 id="️-2-two-fixed-buffers-different-orchestration">⚙️ 2. Two Fixed Buffers, Different Orchestration</h3> <p>Neither runtime uses <code class="language-plaintext highlighter-rouge">malloc</code> inside the inference loop—both avoid conventional per-inference heap fragmentation—but they manage static memory differently:</p> <ul> <li><strong>TFLM (Manual Arena + Runtime Planner):</strong> You supply a statically allocated byte array (<code class="language-plaintext highlighter-rouge">tensor_arena</code>), and <code class="language-plaintext highlighter-rouge">AllocateTensors()</code> plans activation reuse and stores persistent interpreter metadata inside it. For this MLP, TFLM’s planner requires <strong>904 bytes</strong> of arena space. Give it <code class="language-plaintext highlighter-rouge">1,024</code> bytes (<code class="language-plaintext highlighter-rouge">sized</code> profile) and it runs cleanly; give it <code class="language-plaintext highlighter-rouge">896</code> bytes and <code class="language-plaintext highlighter-rouge">AllocateTensors()</code> fails deterministically on the device.</li> <li><strong>Vyne (<code class="language-plaintext highlighter-rouge">@bounded</code> Lexical Scratch):</strong> Instead of an interpreter planner, Vyne allocates activation buffers (<code class="language-plaintext highlighter-rouge">64 + 32 + 10</code> floats = <strong>424 bytes</strong>) directly on the stack inside a lexically scoped <code class="language-plaintext highlighter-rouge">@bounded</code> region. The compiler enforces a conservative static budget (<code class="language-plaintext highlighter-rouge">@bounded&lt;848&gt;</code>, currently accounting at 8 bytes/element) and rejects over-budget scratch at compile time (<code class="language-plaintext highlighter-rouge">VNE-101</code>).</li> </ul> <p><strong>The Explicit Integration Cost:</strong> To keep this honest, Vyne is not yet a standalone <code class="language-plaintext highlighter-rouge">.vwt</code> microcontroller framework. Because Vyne lacks embedded VFS loading and native C FFI bindings today, the benchmark runner emits ESP32-targeted C code and swaps in checked flash-weight accessors and telemetry stubs (verifying via SHA-256 that the generated <code class="language-plaintext highlighter-rouge">vyne_setup()</code> inference body remains byte-for-byte untouched).</p> <hr/> <h3 id="-3-the-numbers-including-the-inconvenient-results">📊 3. The Numbers (Including the Inconvenient Results)</h3> <p>Before fixing a critical codegen bottleneck in Vyne, my first hardware runs hit a wall—not in memory, but in latency.</p> <p>In the initial baseline (<code class="language-plaintext highlighter-rouge">caa738e</code>), Vyne’s multiply-accumulate expression:</p> <pre><code class="language-vyne">acc = float32(acc + float32(input[k] * bench_weight1(j * 64 + k)));
</code></pre> <p>lost its native <code class="language-plaintext highlighter-rouge">Float32</code> type information across <code class="language-plaintext highlighter-rouge">float32(...)</code> conversion boundaries, falling back to generic boxed dispatchers and <code class="language-plaintext highlighter-rouge">Float32 ↔ Float64</code> software emulation helpers (<code class="language-plaintext highlighter-rouge">__extendsfdf2</code> / <code class="language-plaintext highlighter-rouge">__truncdfsf2</code>). That dragged Vyne down to <strong>3.10 ms/inference</strong> and kept its unused 64 KiB runtime arena linked into <code class="language-plaintext highlighter-rouge">.bss</code>.</p> <p>After updating <code class="language-plaintext highlighter-rouge">BuiltInCallNode</code> and <code class="language-plaintext highlighter-rouge">codegen/builtins.cpp</code> to materialize native <code class="language-plaintext highlighter-rouge">Float32</code> temporaries directly into the compiler’s fast path, the Xtensa disassembly (<code class="language-plaintext highlighter-rouge">vyne-setup.asm</code>) confirmed pure hardware <code class="language-plaintext highlighter-rouge">mul.s</code> and <code class="language-plaintext highlighter-rouge">add.s</code> instructions—and the dead arena dropped out of the linked ELF image completely (<strong>0 linked arena bytes</strong>).</p> <p>Here are the cold-reset hardware results across 20,000 timed inferences (10 accepted runs, order-reversed between passes):</p> <table> <thead> <tr> <th>Profile</th> <th>Runtime</th> <th>Configured / Linked Arena</th> <th>Arena Used / Scratch</th> <th>Static DRAM (<code class="language-plaintext highlighter-rouge">.data</code>/<code class="language-plaintext highlighter-rouge">.bss</code>)</th> <th>Flash Image</th> <th>Median Latency (min–max)</th> </tr> </thead> <tbody> <tr> <td><strong>Default</strong></td> <td>TFLM</td> <td>16,384 B / 16,384 B</td> <td>904 B / 0 B</td> <td>39,060 B</td> <td>322,272 B</td> <td><strong>0.077040 ms</strong> (0.07699–0.07706)</td> </tr> <tr> <td><strong>Default</strong></td> <td>Vyne</td> <td>65,536 B / <strong>0 B</strong></td> <td>0 B / <strong>424 B</strong></td> <td><strong>22,324 B</strong></td> <td><strong>283,424 B</strong></td> <td>0.132350 ms (0.13234–0.13239)</td> </tr> <tr> <td><strong>Sized</strong></td> <td>TFLM</td> <td>1,024 B / 1,024 B</td> <td>904 B / 0 B</td> <td>23,700 B</td> <td>322,272 B</td> <td><strong>0.077040 ms</strong> (0.07699–0.07709)</td> </tr> <tr> <td><strong>Sized</strong></td> <td>Vyne</td> <td>1,024 B / <strong>0 B</strong></td> <td>0 B / <strong>424 B</strong></td> <td><strong>22,324 B</strong></td> <td><strong>283,424 B</strong></td> <td>0.132350 ms (0.13234–0.13239)</td> </tr> </tbody> </table> <p><em>(Note: Total device peak SRAM is not a single counter on ESP-IDF; static <code class="language-plaintext highlighter-rouge">.data</code>/<code class="language-plaintext highlighter-rouge">.bss</code>, task-stack high-water marks—7,036 B free of 8,192 B on Vyne vs. 6,688–6,720 B on TFLM—and internal heap telemetry are tracked separately without double-counting.)</em></p> <p><strong>What the data actually says:</strong></p> <ol> <li><strong>23.4× Internal Speedup:</strong> Eliminating boxed/double conversions cut Vyne’s latency from <code class="language-plaintext highlighter-rouge">3.101680 ms</code> down to <strong><code class="language-plaintext highlighter-rouge">0.132350 ms</code></strong> (a <strong>95.7% latency reduction</strong>).</li> <li><strong>TFLM Still Wins on Latency (1.72× Faster):</strong> Even with native hardware <code class="language-plaintext highlighter-rouge">mul.s</code>/<code class="language-plaintext highlighter-rouge">add.s</code> instructions, TFLM finishes in <strong><code class="language-plaintext highlighter-rouge">0.077040 ms</code></strong>—about <strong>55 microseconds faster</strong> per inference. TFLM’s fused <code class="language-plaintext highlighter-rouge">FullyConnected</code> kernels and vendor-tuned inner loops still beat Vyne’s straightforward emitted C loops and flash-accessor calls.</li> <li><strong>Vyne Wins on Linked Footprint:</strong> Without interpreter metadata or a persistent tensor arena, Vyne saves <strong>1,376 B of static DRAM (~5.8%)</strong> even against a tightly sized 1 KiB TFLM build (and <strong>16,736 B / ~42.9%</strong> against default arena reservations), while shrinking the Flash binary by <strong>38,848 B (~12.1%)</strong>.</li> <li><strong>Honest Engineering Effort:</strong> Counting only the core inference loop (<code class="language-plaintext highlighter-rouge">52</code> LOC in Vyne vs. <code class="language-plaintext highlighter-rouge">62</code> LOC in TFLM) would be misleading—once you include the data bridge stubs (<code class="language-plaintext highlighter-rouge">11</code> LOC), MCU Float32 compatibility header (<code class="language-plaintext highlighter-rouge">9</code> LOC), and staging machinery (<code class="language-plaintext highlighter-rouge">401</code> LOC), Vyne currently requires more surrounding plumbing than dropping in TFLM.</li> </ol> <hr/> <h3 id="-4-what-i-would-shipand-what-i-need-to-fix-next">🚀 4. What I Would Ship—and What I Need to Fix Next</h3> <p>If I were shipping a Float32 or Int8 microcontroller product <strong>today</strong>, I would still ship <strong>TFLM</strong>. It has mature operator coverage, battle-tested CMSIS-NN/ESP-NN SIMD kernels, and a 1.72× latency lead on this workload—and once you properly size its arena using <code class="language-plaintext highlighter-rouge">arena_used_bytes()</code>, its static RAM overhead is modest.</p> <p>Where <strong>Vyne’s</strong> model proves compelling is ultra-tight Flash/DRAM budgets where carrying a ~322 KB interpreter runtime isn’t viable, and where compile-time region budgets (<code class="language-plaintext highlighter-rouge">@bounded</code>) prevent silent memory creep before flashing the board.</p> <p>To close the remaining <strong>55 µs gap</strong> and turn this prototype into a standalone embedded ML target, three things are next on my compiler roadmap:</p> <ul> <li><strong>Loop Unrolling &amp; Direct Flash Pointer Lowering:</strong> Eliminating per-element accessor overhead and unrolling inner dot-product accumulators to hide Xtensa FPU pipeline latency.</li> <li><strong>Tighter Static Scratch Accounting:</strong> Refining <code class="language-plaintext highlighter-rouge">@bounded</code> static analysis from conservative 8-byte slots down to exact <code class="language-plaintext highlighter-rouge">Float32</code> width (<code class="language-plaintext highlighter-rouge">424 B</code> instead of <code class="language-plaintext highlighter-rouge">848 B</code>).</li> <li><strong>Int8 Quantization &amp; Hardware Energy Profiling:</strong> Measuring quantized kernels against ESP-NN alongside real power/current draw and long-running multi-region allocation stress tests.</li> </ul> <h3 id="-reproduce-the-benchmark">🔗 Reproduce the Benchmark</h3> <p>All capture logs, ELF section tables, disassembly audits (<code class="language-plaintext highlighter-rouge">vyne-setup.asm</code>), and automated failure tests are reproducible directly from the repository: <a href="https://github.com/t2ncay/vyne">Vyne ESP32 Memory Benchmark (<code class="language-plaintext highlighter-rouge">esp32_memory_bench</code>)</a></p> <p><code class="language-plaintext highlighter-rouge">#CompilerDesign</code> <code class="language-plaintext highlighter-rouge">#ESP32</code> <code class="language-plaintext highlighter-rouge">#TinyML</code> <code class="language-plaintext highlighter-rouge">#EmbeddedSystems</code> <code class="language-plaintext highlighter-rouge">#EdgeAI</code></p>]]></content><author><name></name></author><category term="systems"/><category term="compiler"/><category term="embedded"/><category term="esp32"/><category term="tinyml"/><category term="systems"/><summary type="html"><![CDATA[When deploying neural networks onto microcontrollers like the classic ESP32, the bottleneck rarely starts with raw FLOPs—it starts with static SRAM. You are working inside a few hundred kilobytes shared across your network buffers, runtime metadata, task stacks, and system heap.]]></summary></entry><entry><title type="html">Reducing Neural Network VRAM by 94%: Fixing PyTorch’s Memory and Determinism Problems</title><link href="https://t2ncay.github.io/blog/2026/vyne-vram-reduction/" rel="alternate" type="text/html" title="Reducing Neural Network VRAM by 94%: Fixing PyTorch’s Memory and Determinism Problems"/><published>2026-11-13T06:00:00+00:00</published><updated>2026-11-13T06:00:00+00:00</updated><id>https://t2ncay.github.io/blog/2026/vyne-vram-reduction</id><content type="html" xml:base="https://t2ncay.github.io/blog/2026/vyne-vram-reduction/"><![CDATA[<p>Over the last few months, I’ve been attacking a specific bottleneck in Edge AI: the fact that modern ML frameworks are too heavy to train on constrained hardware, and they give slightly different results every time you run them.</p> <p>I recently benchmarked two iterations of the training graph in my compiler, <strong>Vyne</strong>, using an ESPCN Super-Resolution model on an NVIDIA RTX 5060.</p> <p>Here is what I found.</p> <hr/> <h3 id="-1-the-memory-problem-the-94-internal-drop">📉 1. The Memory Problem: The 94% Internal Drop</h3> <p>In an earlier version of Vyne (V1), the compiler naively called <code class="language-plaintext highlighter-rouge">cudaMalloc</code> inside the training loop for every iteration, causing massive VRAM churn and fragmentation. By upgrading the compiler to use a scoped <code class="language-plaintext highlighter-rouge">@device</code> region (V2B), I preallocated the entire forward and backward graph exactly once.</p> <p>Here is what the explicit allocation looks like in Vyne. Everything from the weights to the AdamW optimizer moments is allocated exactly once at the top of the region:</p> <pre><code class="language-vyne">@device&lt;cuda&gt; region train {
    # Weights
    d_w1 :: Int64 := device_alloc(w1f.size());
    d_b1 :: Int64 := device_alloc(model.c1);
    
    # Preallocated gradients (No dynamic allocation in the loop!)
    d_gw1 :: Int64 := device_alloc(w1f.size());
    d_gb1 :: Int64 := device_alloc(model.c1);
    
    # Preallocated AdamW optimizer moments (m and v)
    d_m_w1 :: Int64 := device_alloc(w1f.size());
    d_v_w1 :: Int64 := device_alloc(w1f.size());
    
    # ... training loop runs here, reusing these buffers ...
};
</code></pre> <ul> <li><strong>Vyne V1 (Dynamic Allocation):</strong> ~11.2 MB peak VRAM</li> <li><strong>Vyne V2B (Preallocated Graph):</strong> <strong>0.65 MB peak VRAM</strong></li> </ul> <p>That is a <strong>94% reduction</strong> within my own compiler’s architecture.</p> <p><strong>But how does this compare to PyTorch?</strong> To be clear, PyTorch doesn’t use raw <code class="language-plaintext highlighter-rouge">cudaMalloc</code> per iteration either; it uses a sophisticated caching allocator. However, PyTorch still pays a massive fixed “framework tax.” If you run this exact workload in PyTorch, the peak VRAM usage is typically <strong>300 MB to 700 MB</strong>.</p> <p>Why? Before PyTorch even loads your model weights, it initializes the CUDA context and dynamically loads vendor libraries like cuDNN and cuBLAS into VRAM. For massive LLMs on datacenter GPUs, this fixed overhead is negligible. But for Edge AI deploying a 0.65 MB model, paying a 500 MB framework tax is impossible.</p> <p>Vyne avoids this tax entirely by bypassing the heavy runtime and using the low-level CUDA Driver API to JIT-compile only the exact PTX kernels needed.</p> <h3 id="-2-the-determinism-problem-bit-exact-reproducibility">🔬 2. The Determinism Problem: Bit-Exact Reproducibility</h3> <p>If you run a PyTorch CUDA training script twice, the weights will be slightly different. This is because default PyTorch backward passes use <code class="language-plaintext highlighter-rouge">atomicAdd</code> operations, which introduce non-deterministic floating-point rounding order. (PyTorch does offer a deterministic mode via <code class="language-plaintext highlighter-rouge">torch.use_deterministic_algorithms(True)</code>, but it forces the framework to abandon its fastest vendor kernels, resulting in a severe performance penalty).</p> <p>To fix this without sacrificing speed, Vyne uses a <strong>“gather” formulation</strong> for the backward convolution kernels. Instead of many threads throwing their math into one shared bucket (scatter/atomicAdd), one thread owns one output element and loops sequentially over its inputs.</p> <p>When Vyne compiles the CUDA PTX, it injects it directly into the C binary. At runtime, Vyne loads the driver dynamically and JIT-compiles it:</p> <div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Inside the Vyne runtime (vdevice.h)</span>
<span class="c1">// We don't link against CUDA. We dynamically load the driver.</span>
<span class="n">VyneCudaLib</span> <span class="n">lib</span> <span class="o">=</span> <span class="n">LoadLibraryA</span><span class="p">(</span><span class="s">"nvcuda.dll"</span><span class="p">);</span>
<span class="n">cuModuleLoadDataEx</span><span class="p">(</span><span class="o">&amp;</span><span class="n">module</span><span class="p">,</span> <span class="n">VYNE_CUDA_PTX</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">);</span>
<span class="n">cuModuleGetFunction</span><span class="p">(</span><span class="o">&amp;</span><span class="n">kernel</span><span class="p">,</span> <span class="n">module</span><span class="p">,</span> <span class="s">"conv2d_backward_input_f32"</span><span class="p">);</span>

<span class="c1">// Launch the deterministic gather kernel</span>
<span class="n">cuLaunchKernel</span><span class="p">(</span><span class="n">kernel</span><span class="p">,</span> <span class="n">grid</span><span class="p">,</span> <span class="n">block</span><span class="p">,</span> <span class="p">...);</span>
</code></pre></div></div> <p>I ran my exact same Vyne training script twice. The <code class="language-plaintext highlighter-rouge">train_loss.csv</code> and <code class="language-plaintext highlighter-rouge">val_metrics.csv</code> matched <strong>byte-for-byte</strong>. No atomics. No drift. You get the exact same weights every single time.</p> <div class="row justify-content-sm-center"> <div class="col-sm-12 mt-3 mt-md-0"> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/cuda_benchmark-480.webp 480w,/assets/img/cuda_benchmark-800.webp 800w,/assets/img/cuda_benchmark-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/cuda_benchmark.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" title="Vyne CUDA Training and Inference Output" loading="lazy" onerror="this.onerror=null; document.querySelectorAll('.responsive-img-srcset').forEach(function (n) { n.remove(); });"/> </picture> </figure> </div> </div> <div class="caption"> Terminal output showing the explicit CUDA training loop (left) and inference metrics (right). Note the 0.66 MB device peak during training, identical CPU/GPU PSNR (33.1963 dB), and a max numerical difference of just 2.38e-07. </div> <p><em>(Note on the 62ms GPU inference time: This includes the one-time JIT compilation of the PTX string at runtime. For a tiny 64x64 image with 1x1 kernels, the math is so small that JIT and PCIe launch overhead dominate. The goal of this benchmark was to prove memory safety and determinism, not raw throughput. For large models, this overhead is amortized to zero.)</em></p> <h3 id="️-under-the-hood">🏗️ Under the Hood</h3> <p><em>(To be fully transparent, I architected this system and used AI to accelerate the boilerplate generation. The real engineering challenge was designing the explicit memory model, debugging the PTX kernels, and verifying the numerical parity down to 2e-7).</em></p> <p>The Vyne compiler bridges the gap between high-level numerical computing and hardware execution. By generating a self-contained C file with embedded PTX, the compiled binary doesn’t depend on heavy frameworks or vendor libraries. It dynamically links to the CUDA driver at runtime and executes only the exact math needed for the graph.</p> <h3 id="-read-the-code">🔗 Read the Code</h3> <p>I am currently planning to write a paper on deterministic, region-based static allocation for GPU training. If you are working on ML Systems, Compilers, or Edge AI, I’d love to connect.</p> <p>You can view the explicit determinism guarantees and benchmarks in the repository here: <a href="https://github.com/t2ncay/vyne/blob/master/examples/projects/espcn/EXPECTED.md">Vyne ESPCN Expected Metrics</a></p> <p><code class="language-plaintext highlighter-rouge">#CompilerDesign</code> <code class="language-plaintext highlighter-rouge">#CUDA</code> <code class="language-plaintext highlighter-rouge">#MachineLearning</code> <code class="language-plaintext highlighter-rouge">#EdgeAI</code> <code class="language-plaintext highlighter-rouge">#HPC</code></p>]]></content><author><name></name></author><category term="systems"/><category term="compiler"/><category term="cuda"/><category term="edge-ai"/><category term="pytorch"/><summary type="html"><![CDATA[Over the last few months, I’ve been attacking a specific bottleneck in Edge AI: the fact that modern ML frameworks are too heavy to train on constrained hardware, and they give slightly different results every time you run them.]]></summary></entry></feed>