Skip to content

perf(webgpu): Cut per-frame CPU work on native hosts - #26565

Merged
ramezgerges merged 4 commits into
unoplatform:masterfrom
ramezgerges:dev/rara/webgpu-wgpu-native-overhead
Nov 24, 2026
Merged

ramezgerges merged 4 commits into
unoplatform:masterfrom
ramezgerges:dev/rara/webgpu-wgpu-native-overhead

Conversation

@ramezgerges

Copy link
Copy Markdown
Contributor

GitHub Issue: closes #26564

PR Type:

💬 Other: performance

What changed? 🚀

On native hosts, the WebGPU backend spent much of its frame creating objects that wgpu-native makes expensive. With these changes, wgpu-native runs level with Dawn across the 28 SamplesApp performance scenes.

  • Upload batching (binding layer): the renderer's queue writes are copied into an arena and uploaded once per submit, with a prepended command buffer copying each range into place. wgpu-native otherwise allocates a staging buffer per write (about 5 µs on Vulkan and 30 µs on D3D12 per call).
    • Only the renderer's function table batches. A WebGpuCanvasElement gets the plain table, so its writes behave as webgpu.h specifies (a destroy, map or error scope between a write and its submit).
    • Large or unaligned writes, writes on a queue the arena doesn't know, and a failed staging allocation fall back to the native write.
    • Not used in the browser.
  • Blur in two render passes: the downsample that sets the blur radius is one pass instead of one per 2× level. Each output pixel averages its whole footprint with linear taps spread over it, so region sizes that don't divide evenly are still covered. A top level of at most 128×128 then runs the 9-tap gaussian in both axes in one pass. Each render pass costs a D3D12 command list in wgpu-native.
  • Bind groups: the clip uniform binding takes a dynamic offset, so one group serves every clip slot of a slab buffer; an op carries the shared group and its slot's offset. Pass, bake, site and clip groups live in one cache keyed by what each entry binds. A group kept past the frame is pinned until released, and every release path tells the cache, so a reused handle never gets a stale group.
  • One mask atlas: glyph and fill cache entries, recording-owned masks, per-frame masks and cached shadows share one atlas. Masks bake one batch per page instead of a texture and a pass pair each. Each slot is freed with its recording, at the next frame start, or by the cache's idle sweep; oversized entries get a standalone page kept as a spare.
  • One buffer pool for per-frame rentals and buffers a recording holds until it is released.
  • Occlusion cull on partial repaints (a fix): a partial repaint's pass is scissored to the damage, but the cull compared the damage-sized cover with each op's full bounds, so nothing was ever culled. Stacked full-window backgrounds were filled again inside the damage, and ops outside it were still issued. On a phone-shaped Android emulator, frames with a damage band cull 25–36 ops and run about 40% faster.

Measurements

Intel UHD 620 laptop, wgpu-native, uncapped, ms per frame, one 15 s run per cell (single runs vary by about ±10%). Measured before the review fixes and the final blur change below.

Scene D3D12 before D3D12 after Vulkan before Vulkan after
RenderStress/ShapeSwarm 104.1 29.8 39.0 26.1
RenderStress/Strokes 42.5 11.4 22.1 9.8
RenderStress/ClipGrid 29.4 11.5 11.6 9.3
RenderStress/Gradients 27.1 11.2 13.9 8.5
RenderStress/LayerStack 18.2 10.1 9.1 7.6
RenderStress/Text 18.1 10.5 9.5 9.7
RealWorld/GanttSchedule 16.5 10.1 9.3 9.1
RealWorld/AcrylicShell 19.1 12.6 9.8 9.8
  • Median over the 28 scenes: −7.9% on D3D12, +1.3% on Vulkan (within noise).
  • Dawn vs wgpu-native afterwards: a median gap of 0.9% on Vulkan and 2.2% on D3D12.
  • Dawn also gains on Strokes (−72% on D3D12, −32% on Vulkan), from the mask atlas.
  • The final blur (one downsample pass) against the per-level downsample, D3D12, two runs each: AcrylicShell 14.6 → 12.3 ms; Shadows within noise.
  • Known cost: dynamic clip offsets make fill-bound scenes about 8% slower on Vulkan (RenderStress/RadialGlow 16.1 → 17.3 ms; D3D12 is unaffected). Going back to fixed offsets brings back per-frame clip groups, because the group key then includes the slot and the mask page: Gradients on D3D12 goes 11.0 → 21.8 ms. Making the atlas pages layers of one array texture would remove that trade-off.

Rendering

Output is unchanged except for blurs: the single downsample pass rounds differently from the per-level one. Given_AcrylicBrush.When_Drawn, which compares acrylic with Skia's blur, measures 0.0392 against its 0.04 threshold (0.0382 before).

PR Checklist ✅

No new tests; the existing WebGPU runtime tests cover these paths. Locally, on desktop WebGPU (Windows, wgpu-native): the Composition, Media and Shapes namespaces (448 tests) and the WebGPU canvas tests pass. WASM, Android, iOS, macOS and Linux are left to CI.

🤖 Generated with Claude Code

ramezgerges and others added 4 commits November 17, 2026 14:29
wgpu-native allocates a staging buffer for every queue write (about
5 us on Vulkan and 30 us on D3D12 per call). The renderer's writes are
now copied into a per-queue arena, and the next submit uploads it once
and prepends a command buffer copying each range into place, which
keeps the ordering queue writes promise.

Only the renderer's function table batches. A WebGpuCanvasElement gets
the plain one, since deferring its writes to the next submit would
change what it sees (a destroy or map between a write and its submit).
Large or unaligned writes, writes on a queue the arena doesn't know,
and a failed staging allocation fall back to the native write.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The downsample that sets the blur radius is one pass instead of one per
2x level: each output pixel averages its whole footprint with linear
taps spread over it, so region sizes that don't divide evenly are still
covered. A top level of at most 128x128 then runs the 9-tap gaussian in
both axes in one pass, its product kernel unrolled, instead of a
horizontal and a vertical pass. wgpu-native's D3D12 backend pays a
command list per pass; AcrylicShell runs 15% faster there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Recordings rebuilt or restamped every frame created bind groups,
buffers and mask textures every frame, which wgpu-native makes far
more expensive than Dawn.

- The clip group's uniform takes a dynamic offset, so one group serves
  every clip slot of a slab buffer; an op carries the shared group and
  its slot's offset.
- One bind-group cache, keyed by what each entry binds, holds the pass,
  bake and site groups and the clip groups. A group kept past the
  frame is pinned until its holder lets go.
- One mask atlas holds glyph and fill cache entries, recording-owned
  masks, per-frame masks and cached shadows, so masks bake one batch
  per page instead of a texture and a pass pair each. Each slot is
  freed with its recording, at the next frame start, or by the cache
  sweep; oversized entries take a standalone page kept as a spare.
- One buffer pool serves per-frame rentals and buffers a recording
  holds until it is released.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A partial repaint's pass is scissored to the damage, but the occlusion cull compared the
damage-sized cover with each op's full bounds, so nothing was ever culled: stacked full-window
backgrounds were filled again inside the damage and ops outside it were still issued.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mergify

mergify Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

@unodevops

Copy link
Copy Markdown
Contributor

🤖 Your WebAssembly Sample App stage site is ready! Visit it here:

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 247162 found UI Test snapshots differences: skia-linux-screenshots: 446, skia-windows-screenshots: 501

Details
  • skia-linux-screenshots: 446 changed over 2502

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • Accessibility_ScreenReader.png
    • AnimatedVisualsTestbedPage.png
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png
    • Accessibility_Showcase.png-dark
    • BasicAcrylicBrushTest.png-dark
    • BasicAcrylicBrushTest.png
    • BenchmarkDotNet.png-dark
    • BenchmarkDotNet.png
    • CompositionPath.png-dark
    • CompositionPath.png
    • Accessibility_ScreenReader.png-dark
    • AutomationProperties_StructureAndProps.png-dark
    • AutomationProperties_StructureAndProps.png
    • CheckBox_DisabledInDisabledListView.png-dark
    • CheckBox_DisabledInDisabledListView.png
    • Accessibility_Showcase.png
    • AnimatedVisualsTestbedPage.png-dark
  • skia-windows-screenshots: 501 changed over 2502

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AnimatedVisualsTestbedPage.png-dark
    • AutomationProperties_AutomationId.png-dark
    • BenchmarkDotNet.png-dark
    • BenchmarkDotNet.png
    • Buttons.png-dark
    • CheckBox_DisabledInDisabledListView.png-dark
    • CheckBox_DisabledInDisabledListView.png
    • AnimatedVisualsTestbedPage.png
    • Border_CornerRadius_Binding.png-dark
    • Border_CornerRadius_Binding.png
    • BreadcrumbBarPage.png-dark
    • BreadcrumbBarPage.png
    • CompositionPath.png-dark
    • CompositionPath.png
    • Accessibility_ScreenReader.png-dark
    • Accessibility_Showcase.png-dark
    • AnimatedBackVisualSourceSamplePage.png
    • AppWindowTitleBar Properties.png-dark
    • AppWindowTitleBar Properties.png
    • BasicAcrylicBrushTest.png-dark

@Xiaoy312 Xiaoy312 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The performance gains are well supported. Splitting the work into four commits (upload batching, blur, bind groups plus atlas, cull) makes it easy to review. The group cache and atlas lifetimes hold up: NoteDestroyed is called on every path that destroys a handle, and the dynamic-offset clip binding is applied at all three call sites. Approving. None of the points below blocks, but the first two are design points worth a reply.

1. Medium: masks nobody looks up count against the glyph/fill cache's 8-page limit

src/Uno.UI.Composition.WebGpu/WebGpuMaskAtlas.cs (Allocate → Reserve(w, h, MaxPages))

Reserve refuses a new page when RegularPages >= MaxPages (8). RegularPages now also counts pages opened by AllocateKeyless / AllocateKeylessGroup, which may go up to MaxSharedPages (32). Those keyless masks are per-frame fill/clip masks and masks owned by recordings. Before this PR they used their own textures, and the keyed cache had its 8 pages to itself.

A UI heavy with path clips, or with fills that aren't cached, can open 8 or more shared pages. Once those are full, glyph and fill entries get AtlasNoRoom, AtlasStarved is set, and evictions start every frame. Text then takes the uncached route.

There's a second effect: short-lived keyless masks now share shelves with long-lived glyph entries. A page holding glyphs never empties, so shelf space used by keyless masks of size classes that stop recurring is never reclaimed.

Suggestion: count the keyed limit only against pages the cache opened (or count keyed slots per page), or keep keyless masks on their own shared pages.

2. Medium: writes that bypass the batch are not ordered with the batched ones

src/Uno.UI.Composition.WebGpu.Init/SilkCompat/SilkCompat.Uploads.cs (BatchedWriteBuffer)

Writes of DirectWriteBytes (1 MiB) or more, and writes whose size isn't a multiple of 4, go straight to _nativeWriteBuffer, so they run at the native write's point in the queue. Batched writes only land through the copy command buffer prepended at the next submit, which runs after all native writes. A small write followed by a large write to an overlapping range therefore ends with the small write's data. That breaks the "keeps the ordering queue writes promise" claim in the file header and the commit message.

Today's code is close to this: WebGpuClipSlab chunks are exactly 1 << 20 bytes, so a full-chunk flush goes direct while dirty-range flushes are batched. Both write the same shadow data today, so nothing breaks yet.

Suggestion: when a direct write hits a queue that has pending copies, first send the upload command buffer on its own (FlushUploads plus a native submit of that one buffer), then do the native write. Alternatively, send any aligned write to the arena while copies are pending.

3. Minor: the flush and the native submit are not atomic

SilkCompat.Uploads.cs (BatchedSubmit / BatchedSubmitForIndex)

FlushUploads releases lock (p) before _nativeSubmit runs. Suppose thread A's flush picks up thread B's pending writes, and B then submits before A does. B's commands run before the copies that carry B's data. RenderGate serializes the renderer's own frames, but WebGpuSwapChainContext and WebGpuBrowserGraphicsContext also submit on this queue. Holding the per-queue lock until the native submit returns is cheap, and it makes the class correct by itself without relying on callers to serialize.

4. Minor: the first release drops pending writes and turns batching off

SilkCompat.Uploads.cs (BatchedQueueRelease)

Queues are reference-counted (DeviceGetQueue returns a new reference, and QueueReference exists). The first wgpuQueueRelease through the batched table removes the queue from _queueDevice and discards its pending copies. If renderer code ever takes and releases an extra reference, batching silently stops for the rest of the session, and the writes already queued are lost. Only teardown releases through this table today, so this is latent. Suggestion: flush the pending writes instead of dropping them, or count references through a wgpuQueueAddRef hook.

5. Minor (memory): held buffers are rounded up to a power of two

src/Uno.UI.Composition.WebGpu/WebGpuPools.cs (Take, via RentHeld in WebGpuFrame.cs)

A cached recording's vertex buffers used to be exact size. They're now rounded up to a power of two and kept for the recording's lifetime: a 520 KB arena holds 1 MB. Together with the upload arena and up to 32 shared mask pages (4 MB each), the session's high-water memory could rise noticeably. Consider finer size classes (for example ×1.25 steps above 64 KB) or exact size for large held rentals, and a before/after memory figure in the description.

6. Minor (test): the cull fix has no regression test

src/Uno.UI.Composition.WebGpu/WebGpuFrame.cs (CullOccluded, bounded-pass branch)

The partial-repaint cull is labelled a fix but nothing covers it. Consider a runtime test that triggers a partial repaint over stacked opaque backgrounds plus an op outside the damage, checking the composited pixels. That also guards against culling too much, such as an op sitting on the damage edge with fractional bounds.

7. Nit: a doc comment ended up on the wrong type

src/Uno.UI.Composition.WebGpu/WebGpuDrawOps.cs

ClipBinding was inserted between DrawOp's /// <summary> and DrawOp. ClipBinding now has two summaries, the first describing DrawOp, and DrawOp has none.

8. Nit: a failed page allocation now throws mid-frame

src/Uno.UI.Composition.WebGpu/WebGpuMaskAtlas.cs (StandalonePage)

It throws InvalidOperationException when texture creation returns null. This now runs on every per-frame mask path, in the middle of building the frame, where the old NewMaskTexture degraded instead. Returning null and letting the caller skip the mask, as Allocate already does, would be gentler.

Other notes

  • The Skia screenshot run reports 446 Linux and 501 Windows differences. Those runs use the Skia renderer, so this is probably baseline noise, but worth confirming given the claim that output is unchanged except for blurs.
  • An accepted trade-off worth a one-line note in SilkCompat.Uploads.cs: errors that used to fail a single write now fail the whole upload command buffer at submit. A buffer destroyed between its write and the submit would make wgpu reject the entire frame. No current renderer path does this; pool eviction only destroys buffers idle for more than 16 frames.

@ramezgerges
ramezgerges merged commit ec7ab27 into unoplatform:master Nov 24, 2026
71 checks passed
@ramezgerges

Copy link
Copy Markdown
Contributor Author

@Xiaoy312 thanks for the review. All eight points are addressed in #26698, one commit per point (2 to 4 share one); the PR description maps each to its change and lists what was validated. The note on a failing write now failing the whole upload command buffer is in the header of SilkCompat.Uploads.cs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Reduce the WebGPU backend's per-frame CPU work on native hosts

5 participants