ClearPix engineering series · Part 22
Auto Detect got 48 more precise masks. Then we had to fix the memory bill.
On this page
Our latest watermark-selection pass did two things I would normally want to separate: it made Auto Detect more useful, and it exposed how easy it is to turn a small browser image into a very large temporary workload.
The final results are better on both human-labeled masks and the 500-frame platform set:
| Measurement | Before | After |
|---|---|---|
| Human cases with an automatic mask | 16 / 30 | 19 / 30 |
| Pixel precision | 45.1% | 50.9% |
| Pixel recall | 53.6% | 58.5% |
| Pixel IoU | 32.4% | 37.4% |
| Platform frames upgraded from a box to a mask | — | 48 / 500 |
| Platform fallback boxes | 263 | 215 |
| Total platform coverage | 473 / 500 | 473 / 500 |
| Oversized masks / runtime errors | 0 / 0 | 0 / 0 |
The 30-image set contains 142 manually chosen SAM layers and no negative examples, so it measures pixel precision and recall, not negative-case false alarms. The 500-frame set has no human pixel masks and is used for coverage and stability. Those are different kinds of evidence, and I do not want to turn them into one accuracy number.
Start with what did not work
Our previous 500-frame experiment showed that an editable box is much easier to provide than an exact mask. This round began with 30 newly annotated examples. The baseline generated masks for 16 of them, with 45.1% precision and 53.6% recall.
The obvious fix was to relax text containment and background limits. Replaying the same captured evidence made the trade clear. One relaxed configuration reached 67.2% recall, but precision fell from 59.4% to 53.2% on the replay metric. More target pixels came in, along with more scenery. That is not the behavior we want: a missed mark can be repaired manually, while an automatic mask over the subject can destroy the photo.
We also tried sending every high-confidence edge text box to SAM. Four additional cases received masks, but their precision ranged from 23.9% to 37.3%. The experiment was rejected rather than hidden inside a better aggregate.
The useful rule was much narrower:
Run SAM only for one high-confidence text box, and only after the existing text mask fails.
That last condition mattered. An earlier version ran SAM first. On one good text case, it reduced recall from 94.8% to 77.2% even though precision improved. We changed the order so an accepted glyph mask is never replaced by a SAM result. SAM is a fallback, not a vote that automatically outranks the text pipeline.
A gate can be bypassed without noticing
Another test used diagonal cursive text. Its aspect ratio was 0.539, above our existing 0.4 limit, and the original text mask was correctly rejected. SAM then produced a candidate that passed the geometric checks and selected it anyway.
The fix was not another SAM threshold. It was to prevent the fallback from bypassing the original aspect-ratio constraint. Containment or background failures may still trigger SAM; an abnormal text shape may not. The full Smart E2E suite now covers this rejection explicitly.
We also removed the text mask's extra one-pixel dilation. The canvas already expands masks by at least two pixels to give inpainting a safety margin. Growing small text twice made the selected background dominate the result. Removing only the extra text dilation kept the canvas margin intact and improved precision without changing how many cases received masks.
The resulting 30-case UI comparison produced 19 automatic masks instead of 16, with precision up 5.8 percentage points and recall up 4.9 points. False-positive pixels fell 13.7%, while false negatives fell 10.5%. Strict complete-case performance is still limited, so manual Smart, Paint and Rect remain normal parts of the workflow.
Small images can still exhaust memory
One test image was only 832×1120. Seeing memory access out of bounds there looks absurd until you count the work rather than the file dimensions.
An RGBA copy of that image is only 3.7MB, but detection and segmentation also involve model weights, inference sessions, activation buffers, candidate masks and backend fallback allocations. A browser can be under pressure long before the source image looks “large.”
In this particular reproduction, the decisive factor was my own test environment. A batch evaluator and the user's real browser were running inference at the same time. After the heavy test stopped, the same case worked. That is not something a threshold should pretend to fix. Heavy regression jobs now run serially with manual testing.
We still added product safeguards. Mobile no longer takes the new single-text SAM fallback, avoiding an extra model path where memory is most constrained. Existing similar-box and solid-region SAM behavior is unchanged. SAM preparation has a 60-second budget and decoding has a 20-second budget. Initialization, timeout and memory failures clear the prepare/ImageData cache and release the session, then return to a text mask or an editable box instead of leaving Detecting Watermark on screen forever.
The important part is that a failed session is not reused. Otherwise the next Auto Detect click simply waits on the same pending promise again.
The cheapest memory was work we never needed
The largest savings did not require a smaller model or a lower-resolution mask.
First, production no longer stores rejected SAM candidates in the evidence list. QA capture still keeps every candidate for analysis, but the normal path retains only the accepted result. Across the 30-case evidence set, 24 rejected candidates accounted for 14.15 MiB of cumulative allocations. One capped candidate is about 1.42 MiB at the current 1536 limit; the largest in this set was 0.88 MiB.
Second, Auto Detect and SAM preparation now share the existing ImageData instead of copying it through another canvas. Each avoided RGBA allocation is width × height × 4 bytes. Across 500 detections, that is 1,812 MiB of avoided cumulative allocation, averaging 3.62 MiB per image and reaching 31.64 MiB for one case. These are allocation totals, not a claim about a device's measured peak.
Third, the SAM encoder and decoder sessions are created sequentially rather than concurrently. Model downloads still run in parallel. This reduces initialization overlap without changing weights or outputs.
These choices follow the same lifecycle advice in the ONNX Runtime WebGPU documentation and Transformers.js memory guidance: reuse sessions, release resources deliberately, and avoid recreating expensive work in a hot loop.
One memory optimization had to be reverted
Batching all text boxes into one full-image glyph mask looked safe. Fewer full-image allocations, fewer temporary arrays, identical inputs—what could go wrong?
The problem is the later global guided-refinement stage. It can make neighboring boxes influence one another. Case 035 changed from one mask layer to three. We restored per-box generation and discarded the savings. This is why we compare actual mask RLE rather than assuming an optimization is behavior-preserving because its inputs look equivalent.
The final 500-frame comparison found zero RLE differences. Selection remained 473/500, fallback boxes stayed at 215, and there were no runtime errors or oversized masks. Eight hashes differed because candidate scores are included in the hash; the masks themselves were identical.
Video also passed its end-to-end test with 43.68 dB PSNR in the masked region.
What I would do again—and what I would not
The useful sequence was:
- Get human masks before tuning.
- Reject broad threshold relaxation and broad SAM expansion.
- Use SAM only where the existing mask has already failed.
- Keep the original constraints active through every fallback.
- Remove duplicate buffers and unwanted candidates before considering a smaller model.
I would not call Auto Detect solved. Strict complete-case accuracy still needs work, and SAM fallbacks add latency. But 48 more platform cases now get a real mask instead of just a box, human-mask precision and recall both improved, and the final 500 masks are byte-for-byte identical after the memory cleanup.
Try the current image watermark remover or the video watermark remover. The local-first architecture is unchanged: detection and inpainting still run on your device. Review the selection before removing, and use Smart, Paint or Rect for anything the conservative automatic path leaves behind.
Part 22 of the ClearPix engineering series. Evaluation entry points: apps/web/scripts/eval-auto-select-quality.mjs, apps/web/scripts/eval-auto-select-replay.mjs and apps/web/scripts/eval-watermark-batch.mjs. The 500-frame snapshot is a fixed internal QA sample, not a public accuracy benchmark.
ClearPix is free, unlimited and runs entirely in your browser. If this post saved you a debugging session, a coffee keeps the model hosting and bandwidth paid for — nothing here is locked behind it.
Buy me a coffee