<?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 seven shark on Medium]]></title>
        <description><![CDATA[Stories by seven shark on Medium]]></description>
        <link>https://medium.com/@sharksevenluo?source=rss-5e0b234fcb0b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MpQ3mdbfJFwscNPC.</url>
            <title>Stories by seven shark on Medium</title>
            <link>https://medium.com/@sharksevenluo?source=rss-5e0b234fcb0b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 15:05:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sharksevenluo/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 LaMa Inpainting and Real-ESRGAN in the Browser: Tiles, Memory Walls, and the Optimizations…]]></title>
            <link>https://medium.com/@sharksevenluo/running-lama-inpainting-and-real-esrgan-in-the-browser-tiles-memory-walls-and-the-optimizations-5d25aca7cedf?source=rss-5e0b234fcb0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d25aca7cedf</guid>
            <dc:creator><![CDATA[seven shark]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 02:02:59 GMT</pubDate>
            <atom:updated>2026-10-26T02:02:59.148Z</atom:updated>
            <content:encoded><![CDATA[<h3>Running LaMa Inpainting and Real-ESRGAN in the Browser: Tiles, Memory Walls, and the Optimizations We Threw Away</h3><p>We build ClearPix, a set of media cleanup tools that run entirely in the browser — no uploads, no server GPUs. That means when a user removes a watermark, a LaMa inpainting model (102.8 MiB in fp16, 198MB in the fp32 fallback) runs inside their tab, and when they upscale an image, Real-ESRGAN runs next to it in the same JavaScript heap. This post is about what it actually takes to ship that: why we pinned a flagship inpainting model to WASM for months, how tiled inference keeps large images from blowing up the tab, which “obvious” optimizations we benchmarked and threw away, and the one rule that saved us repeatedly — profile before you touch anything.</p><blockquote><em>Update (2026–10–18): the WASM pinning described below is obsolete, and the reason for it was wrong. LaMa’s WebGPU failure was never a driver deadlock — it was a one-element off-by-one in the default </em><em>onnxruntime-web build&#39;s negative-step </em><em>Slice, which corrupts a Fourier branch and makes a downstream </em><em>Add see </em><em>63 against </em><em>64. Importing the WebGPU build fixes it: per tile, 4.06 s on WASM versus 0.86 s on WebGPU, at 71.6 dB PSNR agreement. The model is also now fp16 by default (86.3 MiB download, </em><a href="https://clearpix.org/blog/fp16-quantization-quality-loss-overflowed-tensor"><em>part 13</em></a><em>). We keep this post&#39;s investigation in place because the tiling, memory and sequencing work is still exactly what ships — but read the WebGPU verdicts through the </em><a href="https://clearpix.org/blog/lama-webgpu-slice-off-by-one"><em>part 14 correction</em></a><em>.</em></blockquote><h3>The real constraint is memory, not FLOPS</h3><p>Server-side model selection is mostly about quality-per-FLOP. In the browser that framing breaks down completely. Our constraints, in order of how often they bite:</p><ol><li>Memory. Model weights, WASM linear memory, tensors, source image, and output canvas all live in one renderer process. A 4K image alone is ~33MB as RGBA. Hold a large ONNX session open at the wrong moment and Chrome kills the tab — no exception, the page just vanishes.</li><li>Driver stability. A WebGPU session that <em>creates</em> successfully says nothing about whether session.run() will return. We&#39;ve seen big models deadlock mid-inference on specific GPU/driver combinations with no error at all.</li><li>FLOPS. Barely matters. Our profiling keeps showing browser inference is memory-bandwidth-bound, not compute-bound.</li></ol><p>This is why our model choices look odd from a papers-first perspective: we run Real-ESRGAN’s compact general-x4v3 variant instead of the classic RRDBNet x4plus — the “weaker” model won every acceptance case while running an order of magnitude faster, because “fast in the browser” is a property of the architecture, not the runtime. The full model-selection benchmark (and what happened when we later quantized the winner to fp16) is part 3 of this series; here we focus on what those models cost once they’re loaded.</p><h3>An honest inpainting model comparison: MI-GAN vs LaMa</h3><p>Our watermark remover ships two inpainting engines, and we picked them on a bench suite rather than paper reputation:</p><p>MI-GANLaMa (big-lama ONNX port)Size~29.5MB102.8 MiB fp16 (198MB fp32 fallback)Inputfixed 512x512, single 4-channel float32 tensorfixed 512x512, image + mask tensorsWASM speed per tile~0.6s~4.1s (about 7x slower)WebGPU speed per tile~0.4s~0.85s fp16 (4.7x faster than its own WASM path)Large-hole structural reconstructionweakstrong — our big-hole text case gained +11.6dB over MI-GANSmall isolated regionsslightly betterflat (-0.8dB on our small-logo case)</p><p>LaMa’s fast Fourier convolutions give it a global receptive field, which is exactly what you need when a watermark sits on top of a face or a building edge and the fill has to reconstruct structure, not just smear texture. MI-GAN is the better tool for small, isolated regions — faster and marginally cleaner there. So the product defaults to MI-GAN and offers LaMa as an explicit “HQ” opt-in. The HQ model is never prefetched; the user clicks HQ, sees the download size, and chooses.</p><p>If you want to run LaMa in a browser yourself, the tensor conventions that cost us a probe script to pin down: image is [1,3,512,512] float32 in 0–1, mask is [1,1,512,512] with 1 = inpaint, and the output is already on a 0–255 scale — the official demo casts straight to uint8, so don&#39;t normalize it again.</p><h3>Why our LaMa ran on WASM on purpose</h3><p>This is the decision people question most. Our MI-GAN path tries WebGPU first and falls back to WASM — and it’s great when it works: after upgrading onnxruntime-web to 1.30, the WebGPU execution provider took inpainting from 2100–3500ms down to ~400ms. But LaMa at 198MB fp32 kept hitting a nastier failure class: session creation or inference would fail on certain GPU/driver combinations, with no error we could act on and no timeout that could rescue it. A fallback you can’t trigger is not a fallback.</p><blockquote><em>Corrected 2026–10–18: “certain GPU/driver combinations” was our label for a bug that had nothing to do with either. Every reproduction we could build failed deterministically, with a shape error from a downstream </em><em>Add. See </em><a href="https://clearpix.org/blog/lama-webgpu-slice-off-by-one"><em>part 14</em></a><em> for the mechanism and the fix. The paragraph below is kept as the reasoning we shipped on at the time.</em></blockquote><p>Meanwhile, LaMa on WASM does one tile in ~4.1s — slow, but fine for an opt-in quality mode. So we pinned it:</p><pre>// initLama, before 2026-10-18 — reliability over peak speed: 198MB fp32 has<br>// repeatedly failed under WebGPU (creation *and* inference), so we never try.<br>const s = await createSession(bytes, onProgress, [&#39;wasm&#39;]);</pre><p>For the smaller MI-GAN we still gamble on WebGPU, but with a runtime safety net, because creation succeeding proves nothing. Every WebGPU run() is wrapped in a watchdog — 120s for MI-GAN, and 60s for LaMa now that a healthy tile is 0.86s (it was 300s while we believed the failure class was a hang; WASM gets no timeout, it&#39;s the final path and legitimately slow). On timeout or error, we rebuild the session from the cached model bytes (IndexedDB hit, no re-download), retry once on WASM, and then <em>stick</em> to WASM for the rest of the page lifetime instead of re-rolling the dice every pass.</p><p>One more production landmine in the same file: warming up models with a dummy forward pass hides 1–5s of shader compilation, but the warmup must be awaited before the first real inference. ORT&#39;s WebGPU EP does not tolerate concurrent run() calls on one session — we reproduced Session already started and tensor detach races three times in a row before adding that await.</p><h3>Where browser ONNX actually runs out of memory</h3><p>The OOMs we hit were never where we expected. Two real ones:</p><ul><li>Writing the full fp32 weight file (198MB) to IndexedDB in one chunk, while a session was being created on top of it, pushed the renderer over the edge and killed the tab. Chunking the IDB write into 32MB pieces fixed it — and the write is a third smaller today, now that HQ loads fp16.</li><li>Keeping inference sessions alive during video assembly. After per-frame processing finishes, we run the encoder — and that assembly step is the memory peak of the whole pipeline. If the ORT session is still holding hundreds of MB of WASM heap at that moment, low-end devices get their renderer OOM-killed: the “page silently crashes” bug report. So we explicitly release sessions before assembly; the model bytes stay in IndexedDB, so re-init later is cheap.</li></ul><p>The lesson generalizes: in the browser, your memory budget is a timeline, not a number. What matters is what you’re holding at the peak moment.</p><h3>Tiles and overlap-crop: staying under the memory wall</h3><p>Both engines take fixed 512x512 inputs (inpainting) or dynamic but memory-hungry inputs (super-resolution), so everything goes through tiles.</p><p>For Real-ESRGAN we feed overlapping 256x256 tiles and paste back only the <em>center</em> of each upscaled tile, discarding an 8px border on interior edges — classic overlap-crop. The border pixels of a super-resolved tile are where edge artifacts live, and discarding them makes tile seams invisible. Tiling also bounds peak memory: per-tile tensors are tiny and constant no matter how big the source is, so large inputs can’t crash the tab. (We still cap input at 1400px on the long side in the MVP — product guardrail, not a technical one.) The light model even let us grow tiles: going from 128px tiles with 16px margins to 256px tiles with 8px margins cut the redundant overlap pixels from about 1.78x to 1.14x of the image area.</p><p>Inpainting tiles are planned from the mask, not a fixed grid. The pipeline: connected components of the mask → group nearby components into clusters (boxes expanded by 80px that intersect are one watermark field) → per-cluster crops with context margin. Fine-detail passes use native-resolution tiles of at most 340px core, which with a 1.5x context margin stays under the 512px model input — zero downscaling, so no blurry patches. LaMa’s HQ path does the same with a 340px pixel grid and 1.3x context (crops stay ≤442px).</p><p>Two tiling lessons we learned the hard way:</p><ul><li>Never shatter dense regions into independent tiles. Each tile is an independent hallucination; stitching them produces visible discontinuities. Triggering tiling by cluster size once tanked one bench case from 19.7 to 11.9dB. The fix: trigger on the largest single connected component, plus a special case for long thin clusters — text lines with a union aspect ratio over 3 — because squashing a whole text line into 512x512 is exactly what produced the “you can tell it was edited” smearing. Dense near-square fields still get one global pass: one consistent hallucination beats many stitched ones.</li><li>Repaint glyphs, not rectangles. For text watermarks we build glyph-level masks — probability map above 0.5 as seeds, candidate pixels by color distance, keep only what’s connected to a seed, dilate 2px. If a box ends up under 8% covered we fall back to the plain rectangle (that guard is what keeps faint tiled watermarks from losing recall). This cut over-painting enough to move precision from 41.4% to 43.2% with recall untouched.</li></ul><h3>Optimizations we benchmarked and killed</h3><p>The most valuable section of our internal docs is the “do not retry” list. Three model-engineering entries we measured and killed: a frame-level worker pool for parallel inference (no faster than the serial path), IOBinding on the WASM path (the transfer tax it saves is a rounding error next to run() itself), and swapping x4v3 for CUGAN (a lateral move dressed up as a breakthrough by benchmarking against the old baseline). The numbers behind all three are in part 3 of this series — along with the one quantization change that <em>did</em> work, fp16 super-resolution weights, and its catastrophic mirror image when we tried it on LaMa. The short version: browser inference is memory-bandwidth-bound, so you win by moving fewer bytes, and whether quantization is safe is a property of the model&#39;s architecture, not of your tooling.</p><blockquote><em>Update (2026–10–17): that last clause is wrong, so the LaMa fp16 entry above comes off the list. The cause was a converter overflow — sixteen BatchNorm variance tensors above fp16’s 65,504 ceiling, silently clamped — not mask gating or precision sensitivity. Fixed algebraically, fp16 now matches fp32 and the download drops 52%. See </em><a href="https://clearpix.org/blog/fp16-quantization-quality-loss-overflowed-tensor"><em>part 13</em></a><em>.</em></blockquote><p>Every entry in that kill list exists because we measured first. The rule we now enforce: no performance work starts without a per-stage timing breakdown and an expected share of the total. If you can’t say what fraction of runtime you’re attacking, you’re guessing.</p><h3>Try it</h3><p>Everything described here runs in production, free, with no uploads — the models download to your browser and nothing leaves your machine. If you came here looking for LaMa inpainting online, <a href="https://clearpix.org/remove-watermark">clearpix.org/remove-watermark</a> is the dual-engine MI-GAN/LaMa pipeline described above. For a Real-ESRGAN web demo with the tiled overlap-crop pipeline, try <a href="https://clearpix.org/upscale-image">our image upscaler</a>. Video versions of the same engines power <a href="https://clearpix.org/remove-video-watermark">our free video watermark remover</a>.</p><p><em>Part 5 of the ClearPix engineering series — how we build free, private, in-browser media tools at </em><a href="https://clearpix.org/"><em>clearpix.org</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d25aca7cedf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Remove Watermarks from Video Fast: Motion-Adaptive Frame Skipping + Temporal EMA]]></title>
            <link>https://medium.com/@sharksevenluo/how-we-remove-watermarks-from-video-fast-motion-adaptive-frame-skipping-temporal-ema-df74232e9177?source=rss-5e0b234fcb0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/df74232e9177</guid>
            <dc:creator><![CDATA[seven shark]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 23:07:59 GMT</pubDate>
            <atom:updated>2026-10-23T23:09:58.617Z</atom:updated>
            <content:encoded><![CDATA[<p><em>(and the bug that froze our masks — a regression story about wiring performance switches to product options)</em></p><p>Running an inpainting model on every frame of a video is the obvious way to do video watermark removal — and unaffordable in a browser. This is the write-up of how we got 58–67% of frames to skip the model entirely: a motion-adaptive, anchor-based frame-skipping gate, a temporal EMA for flicker-free output, plus the failures behind the design — a chain-freeze bug (PSNR 38.7 → 16.7), an anchor-age regression (38.30 → 34.69), and a UX “simplification” that silently disabled the whole optimization and cost us 3x. All numbers are from our own benchmarks; all code is from the shipping pipeline.</p><h3>Per-frame video inpainting is the cost center</h3><p>ClearPix removes watermarks entirely client-side: ONNX-runtime inpainting on WebGPU or WASM, fed by WebCodecs decode, encoded back with MediaBunny. No server, no upload.</p><p>The profile was blunt. Inside one inpaint call, planning cost about 4.4ms while the model run() segment took 97% or more. Per frame, inpainting took 2100–3500ms on WASM; the WebGPU execution provider brought that to roughly 400ms — still the dominant line item. Pipeline overhead was already cut elsewhere (ffmpeg.wasm → WebCodecs + MediaBunny: 95s → 9s per job). The biggest lever left was not a faster model — it was not running the model at all.</p><h3>Frame skipping for video processing: reuse, don’t recompute</h3><p>The observation that makes skipping viable: most watermarks sit on content that barely changes — a corner logo over a talking head, a username stamp over a screen recording. Under a static mask, the pixels inside the mask bounding box are nearly identical frame to frame. If nothing in the region moved since the last inference, that output is already the correct answer — composite it onto the current frame instead of inferring again.</p><p>The per-frame gate, trimmed from RemoveVideoWatermark.tsx:</p><pre>const small = makeRegionGray(img, maskBbox);   // bbox region → ~64px-wide grayscale<br>// Compare against the anchor (last real inference frame); drift measured<br>// exactly against the anchor too<br>const mae = st.anchorSmall ? regionMAE(small, st.anchorSmall) : Infinity;<br>const deltaAnchor = st.anchorRaw<br>  ? estimateRegionDelta(img, st.anchorRaw, maskData, maskBbox)<br>  : [0, 0, 0];</pre><pre>if (mae &lt; st.skipThreshold &amp;&amp; st.anchorOut) {<br>  // Skip: composite the anchor&#39;s feathered mask region onto the current frame<br>  out = compositePrevRegion(img, st.anchorOut, maskData, maskBbox, deltaAnchor);<br>  st.skipped++;<br>} else {<br>  out = await runInpaint();<br>  st.anchorRaw = img;   // a real inference becomes the new anchor<br>  st.anchorOut = out;<br>  st.anchorSmall = small;<br>}</pre><p>The cheap part matters: the diff runs on the mask bbox downsampled to ~64px grayscale — under 5ms per frame, against hundreds for inference. On a skip, compositePrevRegion pastes the anchor&#39;s mask region back with the inpainter&#39;s own feathering semantics (100% inside the mask, transition band on clean pixels outside), so a reused frame looks like an inferred one.</p><p>The current build skips 58% of frames on our watermark e2e clip (threshold 5.00) and 67% on the subtitle e2e (threshold 4.21); the earlier gate measured 94 of 144 (65%).</p><p>The threshold is not a magic constant. The first five frames always run full inference; we collect their MAEs and set skipThreshold = median × 3, clamped to [2, 5]/255 — dark and noisy footage get different baselines for free. (The ceiling of 5 is itself a measured fix — keep reading.)</p><h3>The chain-freeze bug: PSNR 38.7 → 16.7</h3><p>The first version (v1) compared each frame to its immediate neighbor and reused the previous output. It passed screen-recording tests, then failed catastrophically on a slow-gradient clip.</p><p>On gradient footage each frame drifts ~1/255, so per-frame MAE stays below threshold and the gate skips forever — the mask region freezes at the last inference while the rest of the frame changes around it: a visible, motionless rectangle. E2e masked-region PSNR collapsed from 38.7 to 16.7.</p><p>Patch one was a cumulative drift budget: accumulate skipped-frame MAE since the last inference and force re-inference when the total crosses the threshold. That recovered PSNR only to 22.9 — reused pixels still lagged the scene’s exposure on gradients. Patch two added delta compensation (estimateRegionDelta): the per-channel mean difference between current and previous raw frames over the <em>non-mask</em> pixels in the bbox, added to historical pixels before blending. Budget + delta landed at 38.44 (vs a 38.74 no-skip reference), inside tolerance, with a clean three-clip visual check in real Chrome. That version shipped.</p><p>But the budget was always a proxy: the error we care about is “how far is this frame from the frame whose output we’re reusing,” and chained per-step MAEs only approximate that.</p><h3>Anchored comparison: the fix that deleted the budget</h3><p>So we refactored (v2): compare each frame directly against the anchor — the most recent frame that really ran inference — and reuse the anchor’s output on skips. Skip error is now exactly what the threshold bounds; the drift budget was deleted outright. Delta compensation became exact too — measured against the anchor itself.</p><p>The first anchored run gave us a proper scare: subtitles gained +3–4dB on all four e2e segments, but the gradient watermark clip <em>dropped</em> from 38.30 to 34.69dB masked-region. Root cause: that clip’s drift varies with y (a sinusoidal exposure gradient), so one mean delta can’t fully compensate it, and the residual grows with anchor age. Two measured fixes:</p><ul><li>Tighter threshold ceiling: 8 → 5. Anchors refresh more often, bounding how stale a reuse can get.</li><li>Split the deltas. Compositing reuses the anchor → to-anchor delta; the EMA blends against the previous frame’s output → to-neighbor delta. One mean delta serving both timebases was the bug.</li></ul><p>Final numbers: e2e-video masked region 39.84dB (+1.5dB over the chained baseline), 58% skipped (threshold 5.00); subtitles 37.3 / 32.3 / 28.7 / 30.1dB across four segments, 67% skipped (threshold 4.21).</p><h3>Flicker-free video watermark removal with a temporal EMA</h3><p>Skipping frames solves cost, but video inpainting temporal consistency needs one more layer. Even frames that <em>do</em> run inference can jitter: the model hallucinates slightly different textures each time, and at 30fps that reads as flicker inside the repaired region.</p><p>Our answer: a per-pixel exponential moving average, applied only inside the mask dilated by 4px, with a motion-adaptive blend factor (applyTemporalEMA, trimmed):</p><pre>// Per-pixel motion from raw frames (0..1)<br>const m = (|dr| + |dg| + |db|) / (3 * 255);<br>const t = Math.min(1, m / 0.08);   // motion 0→8%<br>const s = t * t * (3 - 2 * t);     // smoothstep<br>const a = 0.4 + 0.6 * s;           // alpha 0.4→1.0<br>// History term: to-neighbor deltaPrev (composite uses to-anchor deltaAnchor)<br>out = curr * a + (prev + delta) * (1 - a);</pre><p>Low motion → alpha 0.4 (lean on history, flicker dies); high motion → alpha 1.0 (pure current frame, no ghosting), with a smoothstep between. Three boundaries are deliberate:</p><ul><li>It runs only inside the dilated mask. The rest of the frame is already bit-identical to the source; touching it would only blur real motion.</li><li>It runs on both inferred and skipped frames, so reused composites get the same treatment as fresh inferences.</li><li>Its history term is compensated against the previous frame, not the anchor — the split described above.</li></ul><h3>Moving watermark removal: sampled re-detection that still skips frames</h3><p>Everything so far assumes a fixed mask — wrong for a watermark that moves. Our “Detect sampling” setting has three rates: First (detect once, reuse for the whole video), Med (every 5 frames), High (every frame). Moving watermarks need Med or High.</p><p>A rebuilt mask means all temporal state belongs to the <em>old</em> mask position — reusing it would smear content across the frame — so a refresh resets everything: the anchor group (anchorRaw/anchorOut/anchorSmall), the prev group (prevRaw/prevOut), and the dilation cache. No special-casing needed: anchorSmall = null makes the next MAE Infinity, forcing full inference on the re-detect frame (which becomes the new anchor), and prevOut = null makes the EMA skip itself. Between re-detects the watermark usually holds still, so skipping stays fully active on Med/High — the anchor gate handles the motion. (If detection fails or finds nothing, we keep the previous mask and leave temporal state untouched.)</p><p>The same machinery powers our subtitle-removal tool, which defaults to Med because burned-in subtitles change every few seconds.</p><h3>The rollback: how a UX cleanup cost us 3x</h3><p>Now the embarrassing one. In a September UX pass, the “First” sampling option looked like confusing jargon, so we removed it and forced per-frame re-detection for everyone.</p><p>What we didn’t trace: skipping and the EMA are keyed on the mask’s bounding box, and with per-frame re-detection the mask is rebuilt every frame, so maskBbox was never stable — the entire optimization path silently disabled itself, and video removal got ~3x slower. Users reported &quot;streaming feels slower&quot; — wrong; comparing the complaint timeline with the commit timeline pointed at the sampling default. We rolled back the next day.</p><p>The never-again rule: before deleting a “confusing” option, check whether a performance optimization is keyed to it. Performance switches must be explicitly bound to product options — the dependency belongs in a comment, a test, or the option’s name, not in someone’s memory. Our detectEvery state now carries exactly that comment.</p><h3>Numbers, in one place</h3><p>ChangeMeasurementResultSkip gate costmask-bbox frame diff&lt;5ms per framev1 chain-freeze bug (single-frame MAE)e2e masked-region PSNR38.7 → 16.7v1 drift budget onlye2e masked-region PSNR22.9v1 drift budget + delta (first shipped version)e2e masked-region PSNR / skip rate38.74 → 38.44; 94/144 skipped (65%), pipeline 20s vs 170–370s WASMv2 anchored, first rungradient clip masked-region PSNR38.30 → 34.69 (subtitles +3–4dB on all four segments)v2 anchored, final (ceiling 5, split deltas)e2e-video masked-region PSNR / skip39.84dB (+1.5dB vs chained baseline), 58% skipped (thr 5.00)v2 anchored, finale2e-subtitles, four segments37.3 / 32.3 / 28.7 / 30.1dB, 67% skipped (thr 4.21)Removing the “First” option (UX pass)video removal speed~3x regression, rolled back next day</p><h3>Try it</h3><p>Everything here ships in <a href="https://clearpix.org/remove-video-watermark">our free video watermark remover</a> — in-browser, no upload, the model runs on your GPU. If your real problem is burned-in text, the same pipeline drives our <a href="https://clearpix.org/remove-subtitles-from-video">subtitle removal tool</a>. Feedback on weird footage is how most of these fixes happened.</p><p><em>Part 4 of the ClearPix engineering series — how we build free, private, in-browser media tools at </em><a href="https://clearpix.org/"><em>clearpix.org</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df74232e9177" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FP16 Quantization Made Our In-Browser Real-ESRGAN 4.8x]]></title>
            <link>https://medium.com/@sharksevenluo/fp16-quantization-made-our-in-browser-real-esrgan-4-8x-6084d023e599?source=rss-5e0b234fcb0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6084d023e599</guid>
            <dc:creator><![CDATA[seven shark]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 09:17:45 GMT</pubDate>
            <atom:updated>2026-10-04T09:17:45.675Z</atom:updated>
            <content:encoded><![CDATA[<h3>FP16 Quantization Made Our In-Browser Real-ESRGAN 4.8x Faster — and Nearly Destroyed Our Inpainting Model</h3><p>We run super-resolution and watermark removal entirely in the browser at ClearPix, using ONNX Runtime Web on WebGPU. This post is the writeup of one optimization round that produced our single biggest inference speedup — 4.8x at page level from fp16 quantization — and, in the same week, two of our worst quality regressions when we applied the exact same trick to the wrong model.</p><p>If you’re fighting slow browser GPU inference with onnxruntime-web, you’ll get three things here: the performance model that explains why fp16 works and parallelism doesn’t, the real numbers behind choosing SRVGGNetCompact over the “stronger” RRDBNet, and a concrete failure case study of fp16 quantization quality loss in mask-gated models (with PSNR before/after). At the end: the decision order we now follow before touching any model.</p><h3>Why browser GPU inference is slow: bandwidth, not FLOPs</h3><p>The mental model most engineers bring from CUDA land is wrong for the browser. On a desktop GPU with a fat model, you’re often compute-bound and the answer to slowness is “more parallelism.” In the browser, running through onnxruntime-web’s WebGPU execution provider, our profiling kept saying the same thing: we are memory-bandwidth bound.</p><p>Two pieces of evidence forced this conclusion on us.</p><p>First, worker pools did nothing. We built a frame-level worker pool for parallel video inference — multiple workers, each with its own ONNX session, processing frames concurrently. The result: 396 seconds versus 393 seconds for the serial path. That’s within noise. Adding workers only added contention for the same memory bus. If more parallelism can’t help, FLOPs were never the bottleneck.</p><p>Second, IOBinding did nothing. We profiled the WASM path expecting the JS↔wasm tensor copies to be a meaningful tax, and planned to adopt IOBinding to shave it. The instrumented timings showed the transfer tax was 1–2% of the total; the run call itself was over 97%. Optimizing anything outside the run segment was rearranging deck chairs.</p><p>Once you accept “bandwidth-bound,” the optimization list writes itself: move fewer bytes. Halve the weight precision and you halve the bytes read per inference. That’s the entire theory behind what happened next.</p><h3>Architecture first: SRVGGNetCompact (x4v3) vs RRDBNet x4plus</h3><p>Before quantization, though, we made a bigger decision that fp16 later rode on top of: swapping the model architecture itself.</p><p>We started with Real-ESRGAN x4plus, the well-known RRDBNet — 1187 nodes, 67MB of weights. On paper it’s the stronger model. In the browser it was a disaster in a specific, instructive way: on ORT’s WebGPU EP it showed <em>no speedup at all</em> over CPU. Roughly 2.5 seconds per tile on both backends. A big RRDBNet pushes so many bytes through the graph that even the GPU just waits on memory. Runtime-side tuning space was, for practical purposes, exhausted.</p><p>So we switched to realesr-general-x4v3, which is SRVGGNetCompact — a compact architecture designed for general and video content. The numbers from our September benchmarks:</p><p>RRDBNet x4plusSRVGGNetCompact x4v3Graph size1187 nodes71 nodesWeight file67MB4.9MBCPU inference speedbaseline14–27x fasterQuality (3-case PSNR head-to-head)baselinewins every case, +0.1 to +1.5dB</p><p>The quality result deserves emphasis: the compact model didn’t just hold even, it won all three benchmark cases, by up to 1.5dB. The heavier RRDBNet’s texture hallucinations actually hurt fidelity on real content. Per-frame, the swap took us from about 75 seconds to about 7 seconds — 10x — before we touched precision at all.</p><p>Lesson one of model engineering for the browser: the first selection criterion is “designed for the deployment environment,” not “SOTA in the paper.” If you’re shipping a Real-ESRGAN in browser code, picking the compact variant matters more than anything you can do to the runtime.</p><h3>What fp16 actually bought us on onnxruntime-web WebGPU</h3><p>With x4v3 in place, we quantized the weights to fp16 and measured carefully before shipping:</p><ul><li>fp16 vs fp32 outputs compared against each other: PSNR 57dB+. For practical purposes the outputs are identical.</li><li>Single-tile inference on WebGPU: 403ms → 113ms. That’s 3.5x — better than the naive 2x you’d predict from halving bandwidth, because Apple GPUs also get an fp16 ALU throughput bonus.</li><li>Page level on our video upscaler (24 frames of 720p): 31.4s → 6.6s. 4.8x end-to-end.</li><li>The fp16 file is 2.4MB versus 4.9MB for fp32, which also halves the download.</li></ul><p>The implementation detail that kept this painless: we exported with keep_io_types, so the JavaScript side keeps its fp32 tensor contract and zero application code changed. The WASM EP also runs the fp16 model fine, so our Chromium e2e path needed no special-casing.</p><p>We still ship fp32 as a fallback spec. If every fp16 URL fails, the loader falls through to the original model; the feature keeps working, just at fp32 speed. This is a habit we’d recommend to anyone shipping models to browsers: every production incident we’ve had got closed by a fallback chain, not by the primary path.</p><pre>export const UPSCALE_MODEL: ModelSpec = {<br>  key: &#39;realesr_general_x4v3_fp16_v1&#39;,<br>  urls: [<br>    `${STATIC_BASE}/models/realesr-general-x4v3-fp16.onnx`,<br>    `${BASE}models/realesr-general-x4v3-fp16.onnx`,<br>  ],<br>  sha256: &#39;7e7b7f58...&#39;,<br>  expectedSize: 2444975,<br>  fallback: {<br>    key: &#39;realesr_general_x4v3_v1&#39;,<br>    urls: [/* R2, local, HF mirrors for the fp32 original */],<br>    expectedSize: 4866417,<br>  },<br>};</pre><p>So fp16 was a free 4.8x. Naturally, emboldened, we reached for the same hammer on the other model in our stack. That’s where the week went sideways.</p><h3>When fp16 quantization quality loss is real: the LaMa failure</h3><p>Our watermark removal pipeline uses LaMa, an inpainting model. Inpainting is a different beast from super-resolution in one structurally important way: LaMa is mask-gated. The mask doesn’t just mark where to work — it gates the network’s behavior. The model has to learn “trust these pixels, hallucinate those.”</p><p>We quantized LaMa to fp16. The benchmark came back: masked-region PSNR 21.1 → 11.9dB. That’s not a subtle regression — the watermark was left almost fully intact in the output. We tried int8 quantization too, both static and weight-only, because maybe it was an fp16-specific quirk. It wasn’t: int8 gave 24.5 → 15.6dB on our dark-text case, with the text watermark surviving completely.</p><p>The mechanism, once we thought about it, is almost obvious. A super-resolution network has no gating structure; its job is a smooth, local, well-conditioned transform, and half-precision noise mostly washes out. A mask-gated inpainter has a decision boundary inside the network: which regions are trustworthy context and which must be regenerated from scratch. Numeric precision degradation pushes the model across that boundary — the gating fails softly, and the model starts “copying” the input through instead of repairing it. The watermarked pixels in the masked region get treated as content to preserve rather than a hole to fill. Output looks “fine” at a glance, except the watermark is still there.</p><p>Both failures were caught by the benchmark before shipping, and both directions are now on our internal do-not-retry list. The takeaway isn’t “never quantize.” It’s that quantization feasibility is a property of the model’s architecture: does it have precision-sensitive structure — mask gating, large-magnitude outputs, long error-accumulation chains? If yes, fp16/int8 will almost certainly kill it. If no, fp16 is free bandwidth.</p><h3>The decision order we now follow</h3><p>After this round, we wrote down the order of operations for any model change, and it’s deliberately architecture-first:</p><ol><li>Architecture. Pick a model designed for the deployment environment. Lightweight and purpose-built beats paper SOTA. Our x4plus → x4v3 swap (10x, quality up) was worth more than every other inference optimization combined.</li><li>Bit width. Only after the architecture is fixed, ask whether the model has precision-sensitive internals. No gating, no long accumulation chains — fp16 is on the table, and it’s the cheapest 3–5x you’ll ever get. Gating present — walk away.</li><li>Runtime. Last, and with measured expectations. Worker pools, IOBinding, EP tuning: in our profiling these were the 1–2% layer. Profile first, write down the expected share of the total before touching anything, and be ready to be told “0x.”</li></ol><p>And one meta-rule that saved us repeatedly: quality admission is always the benchmark, never the paper’s numbers and never “it looks fine.” The LaMa fp16 output looked plausible. The PSNR said 11.9dB. Benchmarks saw it; eyes didn’t.</p><h3>Try it</h3><p>Everything above runs in production, client-side, with no uploads — your media never leaves the tab. You can feel the fp16 x4v3 path yourself in our <a href="https://clearpix.org/upscale-image">image upscaler</a> or the <a href="https://clearpix.org/upscale-video">video upscaler</a> (the 6.6-second page from this post). The LaMa side — kept safely at fp32 — powers our <a href="https://clearpix.org/remove-video-watermark">free video watermark remover</a> and the image tools on <a href="https://clearpix.org/">clearpix.org</a>.</p><p><em>Part 3 of the ClearPix engineering series — how we build free, private, in-browser media tools at </em><a href="https://clearpix.org/"><em>clearpix.org</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6084d023e599" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Processing video in the browser without ffmpeg.wasm: WebCodecs + MediaBunny, 95s→9s]]></title>
            <link>https://medium.com/@sharksevenluo/processing-video-in-the-browser-without-ffmpeg-wasm-webcodecs-mediabunny-95s-9s-e1b521c0aea9?source=rss-5e0b234fcb0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1b521c0aea9</guid>
            <category><![CDATA[ffmpeg]]></category>
            <category><![CDATA[web-codecs]]></category>
            <dc:creator><![CDATA[seven shark]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 01:21:01 GMT</pubDate>
            <atom:updated>2026-10-02T01:21:01.819Z</atom:updated>
            <content:encoded><![CDATA[<h3># Processing video in the browser without ffmpeg.wasm: WebCodecs + MediaBunny, 95s→9s</h3><p>If your browser-based video tool feels slow, the model probably isn’t your problem — the pipeline is. We run ClearPix, a set of free in-browser media tools, and our video watermark removal used to take 95 seconds end-to-end on ffmpeg.wasm. After migrating the whole pipeline to WebCodecs for hardware decode/encode and MediaBunny for muxing, the same job takes 9 seconds. This post walks through exactly why ffmpeg.wasm was slow for us, the architecture we replaced it with (with real code), the audio passthrough trick that avoids re-encoding entirely, and how a streaming single-pass design made memory O(1) so we could raise our duration limit from 30s to 120s.</p><p>## Why ffmpeg.wasm was slow: three taxes we kept paying</p><p>We didn’t abandon ffmpeg.wasm because it’s bad software — it’s remarkable that it exists at all. We abandoned it because every run paid three structural taxes that no amount of tuning removes:</p><p>1. **The 33MB core download.** Before a single frame is touched, the user downloads and compiles a 33MB WebAssembly build of ffmpeg. On a cold cache that’s the first several seconds of the session gone, and it’s pure overhead — none of it is doing work the user’s OS couldn’t do natively.<br>2. **The MEMFS round-trip.** ffmpeg.wasm operates on an in-memory virtual filesystem. Every input file gets copied in, every extracted frame gets written to it, every output gets copied back out. Our frames were making a JPEG round-trip through a fake filesystem purely so a C program from the 2000s could feel at home.<br>3. **Software encoding in wasm.** The encode step ran ffmpeg’s software H.264 encoder inside WebAssembly — no SIMD hardware encoder, no GPU. Meanwhile the machine sitting under the browser has a dedicated silicon block (VideoToolbox on our Macs) whose entire job is encoding H.264 fast.</p><p>The profiling rule this taught us: pipeline overhead and model overhead are the same order of magnitude, and pipeline overhead is usually cheaper to fix. JPEG round-trips, MEMFS copies, wasm software codecs, the 33MB download, materializing the whole video in memory — replacing ffmpeg.wasm removed all of them in one move, and that one move was worth roughly 10x.</p><p>## The dispatcher: two backends, one escape hatch</p><p>We didn’t delete the ffmpeg path. It’s still the fallback for environments without hardware H.264 support, and it’s deliberately **feature-frozen** — streaming it would cost a week of work on a path almost nobody runs, so it keeps its original behavior and its original hard limits.</p><p>A thin dispatcher picks the backend. The WebCodecs path probes for hardware encode *and* decode support with a representative 1080p config:</p><p>```ts<br>export async function isWebCodecsVideoSupported(): Promise&lt;boolean&gt; {<br> if (typeof VideoEncoder === ‘undefined’ || typeof VideoDecoder === ‘undefined’) return false;<br> const enc = await VideoEncoder.isConfigSupported({<br> codec: ‘avc1.640028’, width: 1920, height: 1080,<br> bitrate: 8_000_000, framerate: 30,<br> });<br> if (!enc.supported) return false;<br> const dec = await VideoDecoder.isConfigSupported({<br> codec: ‘avc1.640028’, codedWidth: 1920, codedHeight: 1080,<br> });<br> return !!dec.supported;<br>}<br>```</p><p>There’s also a manual override — `?vbackend=ffmpeg|webcodecs` in the URL or a localStorage key — which turned out to be essential for testing. Playwright’s bundled Chromium ships without an H.264 codec, so our end-to-end tests force `vbackend=ffmpeg`; real-Chrome runs exercise the WebCodecs path. `vbackend=webcodecs` intentionally skips the probe and hard-routes, so real errors surface during hardware testing instead of being silently masked by a fallback.</p><p>One pleasant surprise on the WebCodecs side: engine initialization is a zero-download no-op. Where the ffmpeg path starts with a 33MB fetch, the WebCodecs “init” just reports ready immediately.</p><p>## MediaBunny + hardware decode: browser video frames straight off the silicon</p><p>This is the closest thing to a WebCodecs video processing tutorial we can offer: the actual loop we ship. MediaBunny wraps the container demuxing; `VideoSampleSink` gives us decoded frames as an async iterator:</p><p>```ts<br>const input = new Input({ source: new BlobSource(file), formats: ALL_FORMATS });<br>const track = await input.getPrimaryVideoTrack();<br>if (!(await track.canDecode())) throw new Error(‘Frame extraction failed (unsupported codec?).’);</p><p>const sink = new VideoSampleSink(track);<br>for await (const sample of sink.samples()) {<br> sample.draw(ctx, 0, 0, w, h); // decoded on hardware, drawn to canvas<br> sample.close();<br> await launchEncode(name); // snapshot to JPEG, capped at 8 in flight<br>}<br>```</p><p>Two details worth stealing. First, `sample.draw()` handles rotation and flip metadata for free — phone footage comes out upright. Second, `canvas.toBlob` snapshots the canvas synchronously and encodes asynchronously, so we don’t await each JPEG; we let up to 8 encodes be in flight at once, which overlaps encoding with the next frame’s decode. H.264’s yuv420p requirement leaks into everything, so both dimensions get rounded to even numbers up front.</p><p>## Hardware video encoding in JavaScript: CanvasSource, plus a 3-second trap</p><p>On the output side, MediaBunny’s `CanvasSource` feeds a canvas into the platform’s hardware H.264 encoder:</p><p>```ts<br>const videoSource = new CanvasSource(canvas, {<br> codec: ‘avc’,<br> quality: new Quality(‘high’), // roughly the crf 18 look of our old ffmpeg path<br> keyFrameInterval: 2,<br>});<br>output.addVideoTrack(videoSource);<br>await output.start();<br>// per frame: draw, then<br>await videoSource.add(i * frameDur, frameDur);<br>```</p><p>Each `add()` returns a promise that resolves when the encoder has consumed the frame — this becomes important for backpressure later.</p><p>Now the trap. The first `VideoEncoder` session on our machines has a ~3 second cold start (VideoToolbox initialization). If you let that hit at assembly time, the user stares at a frozen progress bar right at the moment they expect a result. Our fix is a warmup: when frame extraction begins, we fire off — without awaiting — a throwaway 64×64 two-frame encode on a `BufferTarget`. By the time real assembly starts, the encoder is hot. Failure is silent; worst case you just pay the cold start you were going to pay anyway.</p><p>One caveat we learned the hard way elsewhere in the stack: **warmups must be awaited before the first real use of the same resource.** Our model warmup once raced the first real inference against the same WebGPU session and blew up with `Session already started`. The encoder warmup is safe precisely because the dummy encode fully finalizes its own `Output` before the real one starts.</p><p>## Audio without re-encoding: EncodedAudioPacketSource passthrough</p><p>Re-encoding audio that’s already fine is wasted work and a quality loss. Our audio plan has three tiers, decided before the muxer starts:</p><p>1. **Passthrough.** If the MP4 output container supports the input’s audio codec and we can get a `decoderConfig`, we stream the *encoded packets* straight through via `EncodedAudioPacketSource`. Zero decode, zero re-encode, bit-identical audio.<br>2. **Decode → AAC re-encode.** If the codec isn’t MP4-friendly but is decodable, we pull `AudioSampleSink` and re-encode to 128kbps AAC.<br>3. **Drop.** If neither works, the audio track is silently dropped — same semantics as ffmpeg’s `-map 1:a?`.</p><p>The passthrough loop is almost offensively simple:</p><p>```ts<br>const sink = new EncodedPacketSink(audio.track);<br>for await (const packet of sink.packets()) {<br> if (packet.timestamp &gt;= videoDur) break; // -shortest semantics<br> await audioSource.add(packet, first ? { decoderConfig } : undefined);<br> first = false;<br>}<br>```</p><p>The `decoderConfig` rides along with the first packet only; the rest are raw packets copied verbatim. Audio is truncated to the video duration, matching ffmpeg’s `-shortest` behavior, so A/V sync holds.</p><p>## Backpressure for free: the streaming single pass</p><p>The original architecture was three phases: extract all frames to an in-memory Map, process them all, then assemble. That materializes the entire video in memory twice and puts a hard ceiling on duration — it’s why the old limit was 30 seconds.</p><p>The streaming rewrite (`runVideoPipeline`) collapses it into one pass: decode a frame, hand it to the per-frame AI callback, encode the result into the muxer, move on. No frame warehouse. The surprise was that we never had to build a backpressure queue — the primitives already compose:</p><p>- `sink.samples()` is an async iterator, so decoding is *pulled* one frame at a time. Nothing buffers ahead unless we ask for it.<br>- `await videoSource.add(…)` is MediaBunny’s encoder/writer backpressure signal. Awaiting it means the in-flight window naturally converges to 1–2 frames.</p><p>Total live state: one or two frames, the encoder, and the inference session. That’s it.</p><p>We measured it: a 20-second clip peaks at **170MB** versus **162MB** for a 6-second clip. Memory is flat in input length — O(1) holds in practice, not just on the whiteboard. With the memory ceiling gone, the duration limit stopped being an engineering constraint and became a product decision: the watermark remover now allows 120s (soft limit with an estimated-time confirmation, 200MB file size as the only hard guardrail). Frame capping for the length guard happens inside the stream — skipped frames are just closed without ever touching a canvas. Cancellation is immediate, since the loop checks a flag between frames.</p><p>## Results</p><p>| | ffmpeg.wasm | WebCodecs + MediaBunny |<br>| — — | — — | — — |<br>| Engine download | 33MB wasm core | none |<br>| Decode / encode | software, in wasm | hardware (VideoToolbox etc.) |<br>| Frame storage | MEMFS + JPEG round-trip | 1–2 frame streaming window |<br>| Audio | re-encoded | packet passthrough when possible |<br>| End-to-end watermark removal | 95s | **9s** |<br>| Duration limit | 30s | 120s (soft) |<br>| Peak memory scaling | grows with input | flat (170MB @ 20s vs 162MB @ 6s) |</p><p>The 95s→9s number is the full watermark-removal flow measured on 2026–09–29, including the AI inpainting — the pipeline swap is what made the model the fast part.</p><p>## What we’d tell our past selves</p><p>- **Profile the pipeline before the model.** Our instinct was to optimize inference. The 10x was in transport.<br>- **Use the silicon.** Hardware video encoding in JavaScript is one `isConfigSupported` probe away. The browser is not a sandboxed CPU; it’s a thin layer over a media engine.<br>- **Keep the escape hatch.** A forced-backend URL parameter and a frozen fallback path made every regression debuggable and every rollout reversible. Fallbacks are a feature, not a TODO.<br>- **Don’t give fallback paths new features.** Streaming the ffmpeg path would have cost a week to serve a rounding error of users. Freeze it and spend the week on the path 99% of sessions take.</p><p>## Try it</p><p>Everything above runs in production today. Drop a clip into [our free video watermark remover](<a href="https://clearpix.org/remove-video-watermark">https://clearpix.org/remove-video-watermark</a>) to see the pipeline end-to-end, or try the [video upscaler](<a href="https://clearpix.org/upscale-video">https://clearpix.org/upscale-video</a>), which rides the same WebCodecs + MediaBunny rails. No upload, no signup — the file never leaves your browser.</p><p>— -<br>*Part 2 of the ClearPix engineering series — how we build free, private, in-browser media tools at [clearpix.org](<a href="https://clearpix.org).*/">https://clearpix.org).*</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1b521c0aea9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remove Watermark Without Uploading: How We Built an In-Browser AI Editor]]></title>
            <link>https://medium.com/@sharksevenluo/remove-watermark-without-uploading-how-we-built-an-in-browser-ai-editor-e7553581d3a7?source=rss-5e0b234fcb0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7553581d3a7</guid>
            <category><![CDATA[ai-upscaling]]></category>
            <category><![CDATA[image-removal]]></category>
            <dc:creator><![CDATA[seven shark]]></dc:creator>
            <pubDate>Thu, 01 Oct 2026 00:34:21 GMT</pubDate>
            <atom:updated>2026-10-01T00:34:21.949Z</atom:updated>
            <content:encoded><![CDATA[<p>Most online watermark removers ask you to hand over your photo first and ask questions later. We built ClearPix the other way around: the AI models come to your device, your files never leave it, and inference runs entirely in your browser tab. This post is the architecture overview of how that actually works in production — the ONNX Runtime Web + WebGPU inference stack, the model distribution pipeline (R2 CDN, multi-mirror fallback, SHA-256 self-healing cache), the places it broke on us, and how we keep the privacy claim structural instead of rhetorical. No marketing math; every number below comes from our own engineering logs.</p><h3>Does a watermark remover upload your photos? Usually, yes</h3><p>The upload question is not paranoia — it is the default architecture of the category. Nearly every “free online watermark remover” is a thin frontend over a server-side inference API. Your image goes up, gets processed on someone else’s GPU, and comes back down. Whether the privacy policy says the file is deleted afterward, you have no way to verify it, and neither do we. The structural fact is that your media crossed the wire.</p><p>We kept running into this as a genuine user anxiety, and we shared it. Photos with watermarks are often personal — screenshots, ID documents, family pictures, client work. “Trust us, we delete it” is a weak foundation for a tool people use on sensitive files. So we asked the harder question: can the inference just happen on the user’s machine?</p><p>The answer, in 2026, is yes — if you are willing to solve the distribution and reliability problems that server-side tools offload to a data center. That trade is the whole story of ClearPix.</p><h3>The architecture in one paragraph</h3><p>ClearPix is a static site. There is no processing backend. When you open a tool page, your browser downloads ONNX model weights (once, then cached forever), loads them into ONNX Runtime Web, and runs inference on WebGPU where available with a WASM fallback. Your image or video is decoded locally, processed locally, re-encoded locally, and never serialized into a network request. The only bytes that travel are the models coming down to you, and a small set of aggregate analytics events that contractually cannot contain your media.</p><p>That single paragraph hides about 90% of the engineering. Let’s unpack it.</p><h3>In-browser AI image processing: the runtime layer</h3><p>We run all neural inference through ONNX Runtime Web (ort 1.30.x), loaded via dynamic import so its ~1 MB parsed weight stays out of the initial page bundle — Core Web Vitals matter even for tools. Session creation prefers the WebGPU execution provider and falls back to WASM:</p><pre>export async function createSession(<br>  modelBytes: Uint8Array,<br>  providers: readonly string[] = [&#39;webgpu&#39;, &#39;wasm&#39;],<br>) {<br>  const ort = await getOrt();<br>  // ... try each execution provider in order, return first that works<br>}</pre><p>WebGPU is worth real money here: when we enabled the WebGPU EP (ort 1.30+), our inpainting step went from 2100–3500 ms to roughly 400 ms per region in our benchmarks. But “session created” does not mean “inference works” — we have seen WebGPU sessions deadlock silently. So the session runs behind a watchdog, and a dead WebGPU session falls back to WASM rather than hanging the tab. The fallback chain is not an afterthought; every production stall we have ever shipped was closed by one.</p><p>Even the runtime binaries need their own distribution strategy. The jsep.wasm file (28 MB) is a hard dependency of the WebGPU EP — if it fails to load, ORT silently drops back to CPU inference and the user just experiences a mysteriously slow tool. We serve the ORT runtime from jsDelivr first (measured ~7× the throughput of our own R2 custom domain for these files) with a 5-second HEAD probe, falling back to our self-hosted R2 copy when the CDN is unreachable — which happens in some network environments.</p><h3>A client-side watermark remover lives or dies by its model pipeline</h3><p>Here is the uncomfortable truth of client-side AI: you are now a software distribution company. A server-side tool updates weights by deploying a container. We have to push tens of megabytes of model files to arbitrary browsers on arbitrary networks, keep them intact, and never strand a user.</p><p><strong>Distribution.</strong> Models live in a Cloudflare R2 bucket behind a custom domain on our zone. This was a measured decision, not a default: direct r2.dev URLs gave us 75–110 KB/s, while the same-zone custom domain delivered 2.3 MB/s — a 20–30× difference that turns a model download from a coffee break into a pause. Models are also deliberately excluded from our deploy bundle; stripping them (plus internal bench assets) took our release zip from 27.4 MB down to 10 MB.</p><p><strong>Permanent caching.</strong> Once downloaded, model bytes go into IndexedDB and are reused forever — repeat visits load from the device, and the tool works offline. Two details cost us real debugging time. First, big models are written in 32 MB chunks (above a 64 MB threshold), because a single structured clone of a 198 MB model pushed the renderer process into OOM. Second, the cache is self-healing: we verify the SHA-256 of a cached model on every hit (~100 ms for a 67 MB file), because a download interrupted mid-write would otherwise poison a cache that never expires — permanently bricking that user’s tool with no visible error.</p><p><strong>Mirrors and fallback specs.</strong> Each model spec carries an ordered mirror list, a pinned SHA-256, and an optional fallback spec with a different weight format (fp16 → fp32) and an independent cache key. The first mirror whose bytes hash-match wins; a stalled connection (no bytes for 30 seconds) is aborted and handed to the next mirror; if every mirror fails, the fallback spec takes over:</p><pre>for (const url of spec.urls) {<br>  try {<br>    const bytes = await fetchWithProgress(url, onProgress);<br>    if (hash(bytes) !== spec.sha256) throw new Error(&#39;integrity check failed&#39;);<br>    await idbSet(spec.key, bytes); // best-effort<br>    return bytes;<br>  } catch (e) { lastErr = e; } // next mirror<br>}<br>if (spec.fallback) return loadModel(spec.fallback, onProgress);</pre><p>We learned this the hard way: on 2026–09–26 a mirror-chain failure took model loading down in production. Since then the rule is R2 first, public mirrors as backup, fallback spec chain underneath — designed before launch, not patched after an incident.</p><h3>Making the privacy claim structural</h3><p>“Private photo editor, no upload” is easy to print on a landing page. We wanted it to be checkable from inside the app.</p><p><strong>The Privacy Shield.</strong> Every tool page renders a live status bar: a “0 bytes uploaded” chip, per-model download state with an offline-ready badge, and — once an inference session exists — the active backend translated into plain language. It is driven by a status bus inside the model loader, so it reflects what the engine is actually doing, not what the copywriter hoped. You can open devtools and verify the claim yourself: the network tab shows model bytes coming in and nothing going out.</p><p><strong>An event contract we publish.</strong> We do collect a small set of aggregate events to know whether the tools work — things like process_complete (duration, backend, device tier) and result_feedback (thumbs up/down with reason tags). The contract, stated in our privacy policy, is that events never include images, file names, or file contents. Including them would defeat the point of the site.</p><p><strong>Analytics that can’t leak media.</strong> We use Microsoft Clarity for session replays to fix confusing UI. Because your files never reach a server this is already low-risk, but we additionally mark every canvas, image, and video element that can display user media with Clarity’s data-clarity-mask attribute, so replays are structurally incapable of containing your content even if a selector goes wrong.</p><h3>What this architecture costs us</h3><p>Honesty section, because dev.to deserves one:</p><ul><li><strong>First-visit cost is real.</strong> Downloading models and compiling WebGPU shaders makes the first run slower than a server round-trip. We hide shader compilation and encoder init behind prefetch and warmup, and IndexedDB makes visit two effectively free — but visit one pays the toll.</li><li><strong>We gave up control of the hardware.</strong> A data center GPU is a known quantity; a user’s browser is not. WebGPU flakiness, missing cross-origin isolation (which caps WASM threading), and mobile memory limits are all our problem now. The fallback chains exist because each of these has bitten us.</li><li><strong>Model choice is constrained by the browser.</strong> We pick architectures designed for the deployment environment over paper SOTA — swapping our upscaler to a compact architecture was a 10× per-frame win at equal-or-better quality, something no amount of tuning the heavyweight model would have produced. That is a full post on its own.</li></ul><p>We think the trade is overwhelmingly worth it, but it is a trade.</p><h3>Try it</h3><p>Everything described above is live and free, no account:</p><ul><li><a href="https://clearpix.org/remove-watermark">Remove a watermark from a photo</a> — detection, inpainting, and export all in-tab</li><li><a href="https://clearpix.org/remove-video-watermark">Our free video watermark remover</a> — streaming pipeline, up to two-minute clips</li><li><a href="https://clearpix.org/remove-subtitles-from-video">Remove hardcoded subtitles from a video</a></li><li><a href="https://clearpix.org/upscale-image">Upscale an image 4×</a> — the compact SR model mentioned above (video upscaling lives on the same stack)</li></ul><h3>What’s next in this series</h3><p>This overview skipped the interesting fights. The rest of the series goes deep on each one:</p><ol><li><strong>The video pipeline rewrite</strong> — how replacing ffmpeg.wasm with WebCodecs + MediaBunny took full video processing from 95 s to 9 s, and how a streaming single-pass pipeline got us to O(1) memory.</li><li><strong>Model selection and quantization in the browser</strong> — why fp16 was free bandwidth for our upscaler but destroyed our inpainting model (mask-gated architectures and precision sensitivity), and the decision framework we now apply before touching a weight.</li><li><strong>Video inpainting performance</strong> — motion-adaptive frame skipping lets 65% of frames avoid inference entirely, plus the temporal EMA that keeps the result flicker-free (and the UX change that accidentally switched the whole optimization off).</li><li><strong>Running a 198MB model in a browser tab</strong> — tiles, memory walls, the watchdog/fallback structure, and the optimizations we benchmarked and killed.</li><li><strong>Automatic watermark detection</strong> — a YOLO + OCR dual-engine detector and the glyph-level masks that raised precision without losing recall.</li></ol><p><em>Part 1 of the ClearPix engineering series — how we build free, private, in-browser media tools at </em><a href="https://clearpix.org/"><em>clearpix.org</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7553581d3a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>