Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

docs(webcam): the workload is overhead-bound, so quantisation is the wrong lever

EtienneLescot08a65bfb12af
diff --git a/technical-documentation/engineering/webcam-segmentation-bench-brief.md b/technical-documentation/engineering/webcam-segmentation-bench-brief.md
index 1f3ee0b22..7bc14237c 100644
--- a/technical-documentation/engineering/webcam-segmentation-bench-brief.md
+++ b/technical-documentation/engineering/webcam-segmentation-bench-brief.md
@@ -1,147 +1,111 @@
-# Brief — webcam segmentation feasibility measurement
+# Brief — segmentation experiment ladder (round 2)
-Self-contained brief for an agent running on a test machine. Everything needed is here; read
-[webcam-segmentation.md](webcam-segmentation.md) for the surrounding decision.
+Self-contained brief for an agent on a test machine. Read
+[webcam-segmentation.md](webcam-segmentation.md) for the decision this feeds.
----
-
-## Mission
+Round 1 answered "is realtime affordable?" — *qualified yes, 2.59 ms of headroom against a floor
+estimate*. Its report is in
+[PR #493](https://github.com/getopenscreen/openscreen/pull/493#issuecomment-5410489010).
-Answer one question with admissible numbers:
+Round 2 answers a different question: **where do the 3.8 ms actually go, and which lever gets
+them back?** A flatbuffer parse of the vendored model says the GPU is idle 96 % of the time, so
+the time is overhead, not arithmetic. Confirm that, then attack it.
-> **Can the target GPU run a 256×144 segmentation model once per frame while the compositor
-> still holds its frame budget?**
-
-A "yes" unlocks moving AI segmentation into the native compositor. A "no" kills that design and
-we keep segmenting in the renderer. **You are not implementing the feature. You are measuring
-whether it is affordable.**
+---
## Hard constraints
-- **Do not modify any production code.** No changes under `src/`, `electron/`, or
- `crates/compositor/`. Measurement scaffolding lives in a scratch directory or a throwaway
- crate you do not commit.
-- **Do not add dependencies to the app.** Nothing enters `package.json`, `Cargo.toml`, or the
- packaging config. Install what you need on the machine, outside the repo.
-- **Do not push, do not open a PR.** Report back; a human decides.
-- **Do not download model weights without naming the source and getting it approved.** Prefer
- converting the model already vendored in the repo — see Task 1.
-
-## Environment
-
-Repo: `getopenscreen/openscreen`, branch `feat/webcam-effects`.
-
-Build wrapper: `crates\x.bat` (`x.bat run --release -- …`) — it sets up vcvars, puts ffmpeg on
-PATH, and calls cargo. Two things break on a fresh machine:
+Unchanged from round 1: **no production code touched** (nothing under `src/`, `electron/`,
+`crates/compositor/`), **no dependency added to the app**, **nothing pushed**, and **no model
+weights downloaded without the source being named and approved.** Everything here uses files
+already in the repo.
-- its hardcoded Visual Studio path (`…\Visual Studio\18\Insiders\…`) may not exist — the file's
- own comment says to adjust it;
-- if you are in a **git worktree**, `crates/thirdparty/` is absent (gitignored). Copy it from a
- full checkout or nothing builds. Bindgen also needs `LIBCLANG_PATH` pointing at an LLVM `bin`.
+Protocol per [rendering-performance.md](rendering-performance.md) §C.2 — warm-up sweep discarded,
+`--repeat 3`, interleaved arms, **any arm above 15 % spread is VOID**, quiet machine, and **only
+within-run ratios transfer**. Round 1 caught a fake result this way (a "60 Hz" load actually
+running at 38 Hz, reporting a reassuring and wrong 0.945); assume the same traps are still there.
-The bench needs a fixture directory containing `screen.mp4`, `webcam.mp4` and
-`screen.cursor.json`. `crates/fixture/fixture.json` is the frozen manifest; regenerate with
-`-c copy` so the bitstream is untouched.
-
-**Report the hardware.** GPU model, driver version, whether it is integrated or discrete, and
-whether the machine is on battery. This matters more than any number you produce: the design
-targets an **integrated** GPU. If this machine has a discrete GPU, say so prominently — the
-result does not transfer, and you should state that rather than let it read as a green light.
-
-## Measurement discipline — non-negotiable
-
-Governed by `technical-documentation/engineering/rendering-performance.md` §C.2. That document
-records several runs that were **VOID** and explains why. Follow it or your numbers are worthless:
-
-- discard one full warm-up sweep before anything you report;
-- `--repeat 3`, and interleave A/B/A/B — never all-A-then-all-B;
-- **spread gate: any arm above 15 % spread declares the run VOID.** Report it as VOID; do not
- quote it;
-- quiet machine. The documented VOID example had ~40 browser and Electron processes live. Close
- them;
-- thermal and battery drift have *inverted conclusions* on this hardware before. Re-run if in doubt;
-- **only within-run ratios transfer between machines, never absolute times.** Your deliverable is
- a ratio.
-
----
+**Report the hardware again**, and if this is not the same box as round 1, say so — the round-1
+absolutes do not transfer to it.
-## Task 1 — isolated inference latency
+## E0 — prove the bound *(do this first; it decides the rest)*
-**Goal:** ms per inference, warm, p50 and p95, batch 1.
+Sweep the input resolution and see whether time tracks pixels.
-**Model.** MediaPipe SelfieSegmentation, *landscape* variant. The repo already vendors the
-weights at `public/mediapipe/selfie_segmentation/selfie_segmentation_landscape.tflite`
-(249,792 bytes). This is the runtime configuration in use today
-(`webcamSegmentation.ts`: `modelSelection: 1`).
+- 256×144 (the shipped landscape variant), then 192×108, 128×72, 64×36.
+- The square variant is **already vendored** at
+ `public/mediapipe/selfie_segmentation/selfie_segmentation.tflite` — use it for a 256×256 point,
+ at zero supply-chain cost.
+- **Prediction to falsify:** 64×36 has 16× fewer pixels and will *not* be 16× faster — expect
+ roughly 2.5–3.5 ms against 3.803. If time is flat across the sweep, the workload is
+ overhead-bound and E1–E3 are where the milliseconds live. If it tracks pixels, the hypothesis
+ is wrong, and fp16/int8 become live again.
-Preferred route — **convert what we already ship**, so no new supply chain:
+Also worth one profiler pass: per-node timings. The claim to check is that the ten
+Squeeze-and-Excitation blocks — `MEAN → CONV1×1 → RELU → CONV1×1 → LOGISTIC → MUL`, some doing
+**128 MACs in a whole dispatch** — cost comparable wall time to convolutions doing 2.36 M MACs.
+A ~500× arithmetic difference showing up as ~1× time difference is the signature.
-1. Install `tensorflow` + `tf2onnx` on the test machine (this is fine here; it is not fine on a
- dev machine and must never enter the repo's dependencies).
-2. Convert the vendored `.tflite` to ONNX.
-3. **Derive the input/output tensor shapes and dtypes from the converted model — do not assume
- them.** Report what you find.
-4. Sanity-check correctness on one real webcam frame: run it and confirm the mask actually
- segments a person. A latency number for a broken graph is worthless.
+## E1 — 30 Hz instead of 60
-If conversion proves impractical, stop and report that, naming what failed. Do not substitute a
-pre-converted model from the internet without the source being approved first.
+The largest single win available, and it is a scheduling change, not engineering. A silhouette
+does not meaningfully change in 16 ms. Expected: **+1.5 ms of headroom** (2.59 → 4.09 ms).
-**Measure.** ONNX Runtime with the **DirectML** execution provider. Report:
+Re-run the round-1 contention bench with the load generator at 30 Hz. Verify the achieved rate
+inside every arm — round 1's void was caused by exactly this going unverified.
-- p50 / p95 ms per inference, warm, over ≥ 200 iterations after ≥ 20 discarded;
-- the same on the **CPU** execution provider, as a floor to compare against;
-- ONNX Runtime version, DirectML version, and the ops that fell back to CPU if any.
+## E2 — ONNX Runtime session hygiene
-## Task 2 — contention
+DirectML (3.803 ms) and the CPU EP (3.575 ms) agreeing within 6.4 % across two unrelated engines
+points at a shared constant of ~2–2.5 ms **outside both providers**, in ORT's per-`Run()` path.
-**Goal:** does inference running alongside compositing cost the compositor its budget?
+- **Predicted finding, stated so it can be falsified:** whole-graph fusion was *off* in the
+ round-1 run — a run with it on would not report 32 separate `DmlFusedConv` nodes. If that is
+ right, this is a config change worth more than everything else combined.
+- Get the authoritative config keys from `onnxruntime_session_options_config_keys.h` in the
+ installed package. **Do not trust remembered spellings** — an unknown key throws, which is a
+ cheap way to check.
+- Expect the DML EP to want `enable_mem_pattern = False` and `ORT_SEQUENTIAL`; graph capture, if
+ available, additionally wants static shapes (satisfied — this graph is fully static) and
+ pre-bound, address-stable I/O via `IOBinding`.
+- Measure with `IOBinding` to device-resident tensors versus the naive numpy round-trip. The gap
+ is the per-`Run()` overhead.
-This needs **no integration work**. Two arms:
+## E3 — CPU EP under contention
-- **Arm A:** the C8 bench alone.
- ```
- crates\x.bat run --release -- --cfg C8 --fixture fixture --repeat 3 --out out\
- ```
-- **Arm B:** the same, while a separate process runs the Task 1 inference in a loop at **60 Hz**
- (one inference every 16.7 ms) on the same GPU.
+The arm that could keep the **full 5.6 ms** of compositor headroom, because it never touches the
+contended GPU queue — and it removes the D3D11↔D3D12 interop from the design entirely.
-Interleave A/B/A/B. Report fps for each arm, the spread per arm, and the **ratio B/A**.
+Re-run the contention bench with a **CPU-side** inference load instead of a GPU-side one. Keep
+the no-op control arm from round 1: without it, a drop cannot be attributed.
-If you have budget, add a third probe: arm B′ with inference running *as fast as possible*
-rather than at 60 Hz. That is an upper bound, not the realistic load, and should be labelled as
-such.
+Report how many cores the load occupies, and whether the compositor's own CPU work (decode, mux)
+starts to suffer — on Linux especially, where the export path is already CPU-heavy.
-## What to report back
+## E4 — a hand-fused Squeeze-and-Excitation block
-A short written report, in this shape:
+Only if E0 confirms overhead-bound. This decides whether hand-written compute is worth three
+implementations.
-| | value |
-|---|---|
-| GPU / driver / integrated or discrete | |
-| Machine representative of the target? | |
-| Inference p50 / p95 (DirectML) | |
-| Inference p50 / p95 (CPU EP) | |
-| Model input / output shapes as measured | |
-| C8 fps — arm A (spread) | |
-| C8 fps — arm B (spread) | |
-| **Ratio B/A** | |
-| Run admissible under §C.2? | |
+Write one fused depthwise-separable + SE block as a compute shader (HLSL `cs_5_0` is fine for the
+probe), time it against the same block as the runtime executes it, and extrapolate. The estimate
+to check: fusing away ~19 SE dispatches ≈ **1.6–2.2 ms**, more than fp16 and int8 combined could
+plausibly deliver.
-Then, in prose:
+## What to report
-- **the gate**: does the compositor still hold its budget with inference in the loop? Answer
- yes/no and show the arithmetic;
-- anything that surprised you, and anything you could not measure;
-- every run you discarded and why. A VOID run reported as VOID is a useful result; a VOID run
- reported as a number is a harmful one.
+The round-1 table shape, plus per experiment: the number, the spread, whether it was admissible,
+and **whether it confirmed or falsified the stated prediction**. A falsified prediction is the
+most valuable thing you can bring back.
-## What would change the answer
+Then: which lever you would pull first, and what you would stop pursuing.
-Flag these if you hit them:
+## Do not pursue
-- ops falling back to the CPU EP — that changes the latency picture entirely;
-- DirectML failing to initialise on this GPU/driver;
-- the fixture not being representative (resolution, frame rate) of a real recording;
-- the compositor bench not reaching its documented ~126 fps ballpark on arm A, which would mean
- the machine is not comparable to the reference and the ratio is all you can offer.
+- **int8 in any form**, unless E0 falsifies the overhead-bound finding. The weights are already
+ fp16 at rest (110 `DEQUANTIZE` nodes in the shipped `.tflite`); an apparent int8 win would
+ largely be undoing a conversion artifact.
+- **RobustVideoMatting** — GPL-3.0 against an MIT app. A licence landmine, before its recurrent
+ state is even relevant.
+- MODNet, BiSeNet, SelfieMulticlass, ROI-tracking-as-a-perf-lever. Only **PP-HumanSeg v2 Lite** is
+ worth an hour, and only to count its operators against this model's 136.
diff --git a/technical-documentation/engineering/webcam-segmentation.md b/technical-documentation/engineering/webcam-segmentation.md
index 22853e76d..d71d7991f 100644
--- a/technical-documentation/engineering/webcam-segmentation.md
+++ b/technical-documentation/engineering/webcam-segmentation.md
@@ -69,6 +69,8 @@ What is *not* cheap is producing that mask on the device that consumes it.
so zero-copy between the two is unreachable from that side.
- **DirectML binds to a D3D12 device, not D3D11.** "Run ONNX Runtime on the compositor's device"
is therefore not a thing; it needs D3D11↔D3D12 shared-handle interop on a matching adapter LUID.
+- The Linux backend is **wgpu 24 + WGSL**, not raw Vulkan — `layer.wgsl`/`blur.wgsl` are compiled
+ at runtime by naga. There is no SPIR-V toolchain to reuse and no raw `VkDevice` exposed.
## Options
@@ -84,31 +86,119 @@ mask is currently perfectly aligned, because MediaPipe segments the very frame t
Sourcing it from a second decoder means pairing by PTS and accepting a lag, which shows on
moving edges.
-**C** matches the repo's habit of writing GPU maths from scratch, but means porting a
-MobileNet-class graph to HLSL *and* Metal *and* GLSL, with the numerical validation that implies.
+The choice between **B** and **C** turns on a single question — is the cost compute or overhead? —
+which the next section answers. Read it before weighing the table above: it moves **C** from
+"purist but too expensive" to the only option that addresses the measured bottleneck, because
+fusion is exactly what an off-the-shelf runtime will not do for you.
-**B** is the recommended direction — with the interop cost stated honestly above.
+## What the measurement found
-### The platform multiplier
+Run of 2026-08-25 on a Radeon 610M (2 CU RDNA2, integrated — the pessimistic end of the target
+class). Full report in [PR #493](https://github.com/getopenscreen/openscreen/pull/493#issuecomment-5410489010).
-This is the part that dominates B's cost, and it is not Windows-shaped:
+| | |
+|---|---|
+| Inference p50, DirectML | 3.803 ms |
+| Inference p50, CPU EP | **3.575 ms — the CPU is faster** |
+| Compositor alone | 11.07 ms/frame |
+| With a 60 Hz inference load | 14.08 ms/frame (**+3.01 ms, −21.4 % throughput**) |
+| Headroom at 60 fps | 5.60 ms → **2.59 ms** |
-| | Compositor | GPU inference | Interop needed |
-|---|---|---|---|
-| Windows | D3D11 | DirectML (D3D12) | D3D11↔D3D12 |
-| macOS | Metal | MPSGraph / CoreML | none — same `MTLDevice` |
-| Linux | Vulkan | ORT has no Vulkan EP | depends on the EP |
+It passes the gate, but thinly, and +3.01 ms is a *floor*: it excludes the D3D11↔D3D12 interop,
+the NV12→RGB preprocessing and the mask upload that the design actually adds.
+
+### The workload is overhead-bound, not compute-bound
+
+Parsing the vendored `selfie_segmentation_landscape.tflite` as a flatbuffer settles it without
+further measurement:
+
+- 246 nodes, of which **110 are `DEQUANTIZE`** — the weights are **already fp16 at rest**;
+- 136 real ops: `CONV_2D` 43, `RELU` 22, `ADD` 14, `HARD_SWISH` 11, `DEPTHWISE_CONV_2D` 11,
+ `LOGISTIC` 11, `MEAN` 10, `MUL` 10, `RESIZE_BILINEAR` 3, and one MediaPipe custom
+ `Convolution2DTransposeBias`. The `MEAN → CONV1×1 → RELU → CONV1×1 → LOGISTIC → MUL` pattern
+ repeats ten times: Squeeze-and-Excitation blocks;
+- **33.325 M MACs = 66.65 MFLOP** per inference;
+- **48 of the 136 ops have a 1×1 spatial output.** Op 15 is `CONV_2D [1,1,1,16] → [1,1,1,8]`:
+ **128 MACs in an entire dispatch.**
-Linux is the weak leg. Note that **ggml with a Vulkan backend already ships in this app** —
-whisper.cpp builds it for Windows and Linux, Metal for macOS arm64, with the Vulkan-SDK CI leg
-already debugged (`.github/workflows/build-whisper-stt.yml`). An engine covering all three
-platforms is therefore already packaged; what it lacks is a graph for this model, which would be
-written once rather than three times. That trade deserves to be re-examined if ORT's Linux story
-proves as thin as it looks.
+Against ~486 GFLOP/s the ALU floor is **0.137 ms**, and the unfused-bandwidth floor 0.37–0.93 ms.
+Measured: 3.803 ms. **3.6 % of peak — 38 % of the dispatches perform 0.1 % of the arithmetic.**
-## The measurement that decides
+Two consequences, both load-bearing:
-Do not build the interop before this is answered. The ledger already records the directly
+1. **Quantisation should not be pursued.** It halves 416 KiB of weights that already sit in L2,
+ on a GPU idle 96 % of the time, and removes no dispatch. The model is already fp16 anyway —
+ an apparent int8 "win" would mostly be undoing a conversion artifact.
+2. **DirectML and the CPU EP agreeing within 6.4 % across two unrelated engines** points at a
+ shared additive constant of ~2–2.5 ms *outside both providers*, in ONNX Runtime's per-`Run()`
+ path. If so, the fix is binding/session hygiene, not a model or a kernel.
+
+## The levers, in order of expected payoff
+
+| # | Lever | Expected | Cost |
+|---|---|---|---|
+| 1 | **Inference at 30 Hz, not 60** | **+1.5 ms headroom** (2.59 → 4.09) | a scheduling change; export already runs at 30 Hz |
+| 2 | **ORT graph capture / session hygiene** | up to ~2 ms | config, if whole-graph fusion was simply off |
+| 3 | **Fuse away the ~19 SE dispatches** | **1.6–2.2 ms** | needs hand-written kernels — no off-the-shelf runtime fuses an SE branch into its preceding conv |
+| 4 | fp16 the ONNX graph | 0.3–1.0 ms | free, zero accuracy cost |
+| 5 | **CPU EP** | keeps the *full* 5.6 ms of GPU headroom | it never touches the contended queue |
+| — | int8 / model swap | ~nothing | do not pursue |
+
+Lever 5 deserves attention: the CPU EP is already the faster of the two measured, and it removes
+the D3D11↔D3D12 interop, the cross-queue serialisation and the packaging cost in one move.
+
+## Per platform
+
+The three backends are not the same problem.
+
+**Windows — D3D11, feature level 11_1.** DirectML binds to a **D3D12** device, so it needs adapter
+LUID matching (`IDXGIFactory4::EnumAdapterByLuid`), a shared NT handle for the mask texture
+(`CreateSharedHandle` → `ID3D11Device1::OpenSharedResource1`) and a shared fence
+(`ID3D11Device5::OpenSharedFence` + `ID3D11DeviceContext4::Wait`). All present in the pinned
+`windows` 0.58 crate, but `Win32_Graphics_Direct3D12` is not yet in the workspace feature list.
+**A queue cannot be shared between a D3D11 and a D3D12 device — no API exists**, and with 2 CUs
+there is no idle silicon for async compute to fill. That is a floor, not a tuning knob.
+`onnxruntime-node` in `electron-builder.json5` is a stale comment, not a dependency.
+
+**macOS — Metal. The cleanest of the three.** `d3d_macos.rs:109-119` creates one `MTLDevice` and
+one `MTLCommandQueue`, and `compositor_macos.rs:525-531` shows the compositor *clones* (retains)
+them rather than making its own — preview and export already share the same objects. MPSGraph and
+CoreML can take that same device: **no interop layer at all**, and CoreML may route to the ANE,
+which would remove GPU contention entirely. The macOS composite baseline has never been measured;
+the 11.07 ms figure is a Radeon number and does not transfer.
+
+**Linux — wgpu 24 + WGSL, not raw Vulkan.** `layer.wgsl` and `blur.wgsl` are compiled at runtime
+by naga; there is no SPIR-V toolchain to reuse and no raw `VkDevice` exposed. ONNX Runtime with a
+GPU EP is vendor-locked and unshippable to unknown hardware, and `libonnxruntime.so` risks symbol
+collision with Chromium's protobuf/abseil. The realistic options are WGSL compute on the existing
+wgpu device, or the CPU EP.
+
+Only `texture(3)` / `t3` / `@binding(4)` is common to all three — the mask binding is mechanical
+everywhere, and can be built before the engine question is settled.
+
+## The experiment ladder
+
+Run these before building anything; each can falsify the one after it.
+
+- **E0 — prove the bound.** Sweep input resolution (256×144, 192×108, 128×72, 64×36) using the
+ square variant already vendored at `selfie_segmentation.tflite`. If 16× fewer pixels is not
+ ~16× faster — prediction: it lands at 2.5–3.5 ms against 3.803 — the workload is overhead-bound
+ and levers 1–3 are where the time is.
+- **E1 — 30 Hz.** The largest single win, and it is free.
+- **E2 — ORT session hygiene.** Check whether whole-graph fusion was simply off: a run with it on
+ would not report 32 separate `DmlFusedConv` nodes. Config keys must be confirmed against
+ `onnxruntime_session_options_config_keys.h` for the pinned version — do not trust remembered
+ spellings.
+- **E3 — CPU EP under contention.** Re-run the bench with a CPU-side load instead of a GPU-side
+ one. This is the arm that could keep the full 5.6 ms.
+- **E4 — a fused SE block**, hand-written, timed against the runtime's version. This decides
+ whether lever 3 is worth three implementations.
+
+**Licence landmine:** RobustVideoMatting is GPL-3.0 against an MIT app. Do not vendor it.
+
+## Why it was measured first
+
+The interop was deliberately not built before this was answered. The ledger already records the directly
analogous outcome:
> **Encoder pipelining** — *Implemented and measured: a loss on the target integrated GPU,