Skip to content

metal: cheap conversion-cache hits and per-draw lookups (-51% worker instructions on the live map) - #507

Merged
RINNECODER merged 1 commit into
mainfrom
perf/metal-draw-hit-path
Oct 15, 2026
Merged

RINNECODER merged 1 commit into
mainfrom
perf/metal-draw-hit-path

Conversation

@RINNECODER

@RINNECODER RINNECODER commented Oct 15, 2026 •

Copy link
Copy Markdown
Owner

Depends on #505 (the AGC frame-replay tool; this branch is stacked on it).

What

Makes the Metal per-draw hit path cheap. Profiled first (/usr/bin/sample on the live-map replay, agc-queue-0 thread, blocking waits excluded), then fixed the top items:

rank (baseline, % of MetalDraw::Draw CPU) cause fix
1. ConvertToMetal 25.5% (key building 12%, cache inserts 5%, Result copy 8%) draws with per-draw push constants never repeat their exact key: each built 3 keys (one over all SPIR-V words), probed 3 caches, inserted 2 entries; Returned() deep-copied the MSL text ModuleConversionCache keyed by SPIR-V identity + stable key, holding the shared converted shader; hit = RestorePushConstants (what a StableConversionCache hit already did). Result::source is a SharedSource (copies share the text)
2. Bindings 17% / texture() 13.5% CPU (+ GPU drains) see texture notes below mirror() and the compute-buffer lookup index the snapshot's mirrors instead of building an NSArray per call
3. Pipeline ctor 6% (CachedShaderFunction ~4-8%) compares the whole source on every function-cache hit CachedConvertedShaderFunction: by the identity of the shared text first
- StoresThroughBda searched the whole source twice per draw recorded once by ConvertToMetal (storesThroughBda)

After: ConvertToMetal is 1.2% of Draw CPU.

Texture lookup (the "25-30%" from the earlier profile): about 80% of its wall time is textureKeys -> BeforeCpuRead draining the GPU timeline before reading DCC keys the GPU just wrote (precise already: MayHaveWritten), not CPU lookup. Its CPU part is GuestImageCache::Find (~6% of Draw CPU: re-hashing whole surfaces after every Expire, ~22 per frame; 870 MiB hashed per frame incl. inserts) and real uploads. Not changed here: a cheaper safe proof needs the guest write tracker (GuestMemory::UnchangedSince), which the Metal path does not use yet.

Measurements (live map captures/agc-live-map, 10 interleaved A/B pairs, separate processes, --repeat 2, 2 s pauses)

build worker M instr worker CPU ms wall ms GPU busy ms --expect-hash 5e5670079f1ae58a
#505 baseline 8673 (IQR 1.7%) 836 1570 764 9/10
this PR 4192 (IQR 4.6%) 467 1262 758 10/10

Paired deltas: instructions median -51.3% (range -53.0..-49.5%), worker CPU -44.5%. The one baseline failure is the known 1 px GPU-order flake (pixel 508,770, hash 87c73baf34838f3f); a 14-repeat profiling run of this PR hit it once too.
Menu (captures/agc-menu, --expect-png replay-ref.png --max-diff-pixels 8): pass on both builds (0-3 px), same flickering hash set.
Tests: anyps5_metal_shader_bridge_test (conversion-cache expectations updated: push-constant values now hit and must return the caller's push constants), anyps5_metal_conversion_disk_cache_test, metal_utility_tests: pass.

Note: the shader disk-cache source version changes with the bridge sources, so the first launch after this change converts again.

Review findings (chatgpt-codex-connector, commit ac5fd06)

# sev where finding action
1 P1 tools/agc-replay/AgcReplay.mm:596 (#505's code) command-buffer page words restored before the earlier submission's delta hook runs; a shared 64 KiB page can make the hook skip its CPU delta not in this PR's commit; belongs to #505
2 P2 tools/agc-replay/AgcReplay.mm:138 (#505's code) remapped guest ranges are appended, not coalesced, so captures with address reuse overlap in Configure not in this PR's commit; belongs to #505

No findings on the draw-path commit (ac5fd06's own files).

🤖 Generated with Claude Code

https://claude.ai/code/session_01DgW4n3qYgi5jAAohEmXRQj

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T04:14:03.233004Z ac5fd06 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6dcc017c-ba0b-43b5-a329-74ae70bd8207
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ac5fd0617e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +595 to +596
if (submit->count != 0) std::memcpy(host(submit->address), submit->words, std::size_t{submit->count} * 4);
driver.SubmitCommandBuffer(submit->address, submit->count, 0, submit->queue);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Apply page deltas before overwriting command-buffer pages

When two queued submissions use command buffers in the same 64 KiB page, this loop can copy the later submission's words before the first worker executes its replay hook. The first hook then sees a page matching neither its recorded previous nor hash, treats it as GPU-modified, and skips the entire recorded CPU delta, silently losing unrelated writes on that page and corrupting replay results. Restore each submission's command words at the same serialized boundary as its delta, rather than mutating guest memory ahead of worker execution.

Useful? React with 👍 / 👎.

Comment on lines +136 to +138
Range range{in.Get<std::uint64_t>(), in.Get<std::uint64_t>(), in.Get<std::uint32_t>() != 0, {}};
range.chunks.assign((range.bytes + Capture::ChunkBytes - 1) / Capture::ChunkBytes, nullptr);
file.ranges.push_back(std::move(range));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Coalesce remapped guest ranges before configuring replay

If the title unmaps and later reuses a guest address during the captured frame, SnapshotRange emits another Range because the host pointer changed, and the loader appends both historical mappings here. Replay subsequently passes both overlapping guest ranges to MetalDriver::Configure, where NativeGuestMemory::BorrowedRangesScope rejects them as overlapping, so captures containing address reuse cannot be replayed. Range records need lifetime-aware replacement/coalescing instead of accumulating every mapping into one simultaneous range set.

Useful? React with 👍 / 👎.

Profiled the live-map replay (sample, worker thread, waits excluded): inside
MetalDraw::Draw, ConvertToMetal took 25% of CPU even on hits. Draws with
per-draw push constants never repeated their exact key, so each built three
keys (one over all SPIR-V words), probed three caches and inserted two
entries. Returned() then deep-copied the MSL text.

- ModuleConversionCache is keyed by SPIR-V identity plus the stable key and
  holds the shared converted shader; a hit restores the draw's own push
  constants (as a StableConversionCache hit already did).
- Result::source is a SharedSource: copies share the immutable text.
- CachedConvertedShaderFunction finds the MTLFunction by the shared text's
  identity instead of comparing the whole source on every pipeline.
- ConvertToMetal records storesThroughBda, so draws stop searching the source.
- MetalShaderResources::mirror and the compute-buffer lookup index the
  snapshot's mirrors instead of building an NSArray per call.

Live map, 10 interleaved A/B processes: worker instructions 8673 M -> 4192 M
(paired median -51%), worker CPU 836 -> 467 ms; pixel hash unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgW4n3qYgi5jAAohEmXRQj
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.

1 participant