Skip to content

LR-EDIT-LIGHT-SHADOWS: fix Highlights/Shadows block artefacts in fine detail; 4× faster GPU median - #3462

Merged
FredApps merged 10 commits into
storytold:mainfrom
jeremyh:shadows-base-gaps
Nov 11, 2026
Merged

FredApps merged 10 commits into
storytold:mainfrom
jeremyh:shadows-base-gaps

Conversation

@jeremyh

@jeremyh jeremyh commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #3460
Related: #2936 (slow GPU kernel compiles on Windows/DX12). This PR builds the GPU kernels without wgpu's workgroup-memory zeroing, which took a DX12 release start from ~87 s to 1.4 s on a GTX 1070 with the new median kernels; it may shorten the compiles there too, but does not close it.

Problem

Raising Shadows on a photo with dark lettering on a bright panel makes bright blocks grow beside the
letters. On a Canon CR3 of a bus (6960×4640) with a black fleet number on a yellow panel, Shadows +75
puts bright yellow rectangles in the gaps where the digits pinch together and inside the 4's counter.
At Shadows +5 there is none of this; at +75 it shows at any zoom. Narrow gaps between dark objects
generally can do it: the pinned corpus has the same thing in the gap between two posts under a machine
(Hasselblad, coverage-6568.fff).

Cause

From process V2 the Highlights/Shadows base (local::tone_base) is the edge-aware filter of a
separable median of log luminance, at a radius of 0.15 % of the long edge (10 px here), so that thin
detail (twigs, lines, #632) takes its surroundings' shift. Text strokes and gaps are about that wide,
so each row and column window is close to half letter and half panel, and the median picks one tone
or the other in rectangles: it fills the gaps between the digits and the 4's counter with the letters'
tone. The guided filter keeps those blocks, so panel pixels whose base reads as deep shadow get
Shadows' full lift (2^(1.7·s·w^1.5), up to ~1.3 EV at +75).

Examples

Top: before, bottom: after.

The fleet number on the bus photo, Whites +54, Blacks +31, Shadows +75, at 300 %:

example_photo_pair

The gap between two posts in the corpus' Hasselblad coverage-6568.fff (CC0, raw.pixls.us),
Shadows +100, at 300 %:

example_corpus_pair

Synthetic lettering at the scale of a bus number in a 7000 px photo, Shadows +75, at 200 %:

example_pair

Change

local::detail_free (CPU) and its GPU twin: each value of log luminance is clamped between its
separable median at r (as before) and the median of a 3× wider neighbourhood (the median at r of a
box-downscaled copy, enlarged bilinearly, like guided_fast's coefficients). The base is the guided
filter of that plane.

  • A twig or speck in an even surround has both medians on the surround's side and takes the nearer,
    as under the median alone (16 Bit tiffs/other files treated as 8bit #632 unchanged).
  • The gap between two strokes sits in a wider neighbourhood that is mostly panel: the medians
    disagree and the gap keeps its own tone. The strokes themselves count as fine dark detail on the
    panel (both medians agree) and keep their contrast, as twigs do.
  • Steps between regions stay exact (the fine median keeps them).
  • GPU: the coarse median reuses the box/bilinear resize, plus one clamp_between_k map kernel.
    CPU and GPU match (max 1 level).
  • GPU median kernels rewritten (median_h / median_v): each workgroup loads its taps into
    workgroup memory and selects by rank, 4 neighbouring outputs per thread. The old partial selection
    sort over a private 49-tap array sat in scratch memory. Same selection, so bit for bit the CPU's
    (median_matches_cpu_bit_for_bit, every r 1–24); renders are byte-identical to the old kernels.
    On 6960×4640 at r = 10 (M2 Max) the median takes 191 → 47 ms.
  • GPU kernels are built without wgpu's zeroing of workgroup memory (as nn.rs and faces.rs already
    are): on DX12 it made FXC take ~87 s over the new median kernels at every start of a release build
    (GTX 1070, 1.4 s without it). Every element of med_tile the kernels read is loaded before the barrier;
    renders are byte-identical.
  • Cost on the 6960×4640 bus CR3 with Whites +54, Blacks +31, Shadows +75 (M2 Max): GPU planes
    231 ms on main → 113 ms here (257 ms with this PR's first kernels); CPU base ~388 → ~453 ms.
    The CPU path enlarges the coarse median while it clamps, into the fine median in place
    (detail_free_matches_its_reference, bit for bit).
  • New process V8 (Process::LATEST). Existing edits keep their process and render as before, so RENDER_CACHE_VERSION is unchanged (it is 76 on main).
  • Docs: process-versions.md (V8 row, a paragraph on the lettering fix, revision history), parity-checklist.md
    (LR-EDIT-LIGHT-HIGHLIGHTS / -SHADOWS notes).

An earlier revision of this PR clamped each value to the quartiles of its window instead. It fixed
the lettering but stopped treating isolated lines between r/2 and r wide as detail (twigs of 3–6 px
against a dark wall were lifted less than the wall, as under V1), which the corpus run below caught.
A fixed window can't tell an isolated line from a gap between strokes; a wider neighbourhood can.

Process version

The new base applies from a new process, V8 (V7 plus local::detail_free; local::base_keeps_gaps is true from V8, CPU and GPU). v0.19.0 shipped V3 to V6, and crystal grain (#3630) took V7 on main, so V1 to V7 render exactly as before: tests_legacy still locks V1 and V2, and only_process_v8_on_takes_the_detail_free_base checks that every earlier process keeps the plain median. New photos get V8; photos already edited keep the blocks until Update to Current Process.

The faster median kernels and the workgroup-memory change don't change pixels, so they apply to every process. They stay in this PR: the zeroing only costs time on the new median kernels (on main the kernels compile in 0.8 s on the GTX 1070), so on its own it would speed up nothing.

How it was checked

  • New test gaps_between_letters_keep_their_own_tone_in_the_base: a row of synthetic "8"s
    sized like the bus number. With the median, 360 panel pixels sit more than 1 EV above their base
    (worst 2.25 EV); now none do (worst 0.8 EV). It fails with the median alone.
  • New test isolated_lines_up_to_the_detail_radius_stay_out_of_the_base: light lines 1–9 px wide
    on a dark ground (r = 10) stay out of the base, as under the median. It fails with the quartile
    clamp (a 6 px line 0.31 of the way into the base).
  • New test detail_free_keeps_steps_and_regions: steps and flat fields pass through unchanged;
    tiny, empty and NaN planes don't panic.
  • The 16 Bit tiffs/other files treated as 8bit #632 tests (twig/stalk contrast, local contrast, no halo at a strong edge, V1 unchanged)
    and the median reference tests pass unchanged.
  • lightcraft-gpu integration tests on a real adapter, including
    highlights_shadows_base_matches_on_every_process (max difference 1 level).
  • Corpus A/B: all 451 pinned raws (cargo xtask corpus --download) rendered at full size before
    and after, with Shadows +100 and with Highlights −100 (902 pairs, GPU). No failures. RMSE median
    0.18 % (Shadows) / 0.10 % (Highlights), max 0.86 %; pixels changed by more than 3 % at most 0.07 %
    of a photo; worst 8×8-block change median 10 / 7 levels, 99th percentile 44 / 41, max 61. I looked
    at the 22 largest local changes (old over new, at the worst block): no new artefacts. Most are a
    slightly different tone in small gaps among foliage or branches; one is the Hasselblad gap above.
  • User-visible change: rendered the bus photo at full size and at 2400 px with Whites +54,
    Blacks +31 and Shadows +5 / +75, and looked at the number, the plate, foliage against the sky and a
    brick lattice fence.
  • New tests median_matches_cpu_bit_for_bit (GPU, M2 Max) and detail_free_matches_its_reference (CPU).
  • After merging main and moving the base to V7 (Linux, Ryzen 5 7545U, RADV): cargo test --release of lightcraft-develop, -pipeline (including tests_legacy), -catalog, -engine, and -gpu on the real adapter (skipping running_out_of_device_memory_falls_back_without_stopping_the_gpu, which fills RAM on an APU; see above); cargo fmt, cargo clippy --workspace --all-targets -D warnings, cargo xtask layers, roots, assets, parity and wasm. Not run: the full cargo xtask ci, and the macOS-only tests_light::v1_and_v2_render_as_before_v3 (V1 and V2 don't change, so it shouldn't need re-capturing).
  • After merging main again (with crystal grain as V7) and moving the base to V8 (Linux, Ryzen 5 7545U, RADV): cargo test --release of lightcraft-develop, -pipeline (including tests_legacy and the grain tests), -catalog, -engine, and -gpu on the real adapter (skipping running_out_of_device_memory_falls_back_without_stopping_the_gpu); cargo fmt, cargo clippy --workspace --all-targets -D warnings, cargo xtask layers, roots, assets and parity. Not run: wasm and the full cargo xtask ci.
  • cargo xtask ci --quick (with CRAFT_FONTS_DIR): all steps pass. After the median change: all steps pass again (without CRAFT_FONTS_DIR), and the CR3 renders
    byte-identical to the first kernels on GPU and CPU.

Summary by CodeRabbit

  • Bug Fixes
    • Highlights and Shadows adjustments better preserve clean gaps in fine details such as lettering while maintaining the existing treatment of broader image features.
    • Tone adjustments are less likely to include isolated, narrow lines in the base used for processing.
    • The updated detail handling helps retain fine structure while reducing unwanted influence from closely packed details.
  • Documentation
    • Updated process notes to explain how fine-detail handling affects Highlights and Shadows adjustments.

From process V2 the Highlights/Shadows base was the edge-aware filter of a
separable median of log luminance (radius 0.15 % of the long edge). Dark
lettering on a bright panel (a bus number in a 7000 px raw: strokes and gaps
about one radius wide) makes every row and column window close to half letter,
half panel, so the median picked one tone or the other in rectangles: it filled
the gaps between the digits, their counters and the corners where they nearly
touch with the letters' tone, and parts of the strokes with the panel's.
Shadows +75 then lifted those patches of panel by up to ~1.3 EV into bright
yellow blocks, and lifted the strokes unevenly.

The base now clamps each value to the quartiles of its window
(`local::quartile_clamp_hv`, ranks r - r/2 and r + r/2 of 2r+1; at r = 1 the
3-tap median). A line thinner than about r/2 in an even surround is still a
minority of every window and takes the surround's tone, as storytold#632 wants; a window
that mixes two tones leaves its pixels alone, and steps stay exact. The storytold#632
twig/stalk tests keep their margins; twig meshes covering ~50 % of their area
keep less contrast than under the median (0.69 of Exposure's at -100, as V1).

GPU: the kernels count the centre's rank first and select only for pixels
outside the band, from the nearer end; the planes stage of a 32 MP render with
Shadows went from ~228 ms to ~165 ms. CPU cost unchanged. CPU and GPU match.

Lands in place on V2 under the bug-fix rule of docs/process-versions.md (the
blocks are output in neither the photo nor the edit), noted there.
RENDER_CACHE_VERSION 72 -> 73 so cached thumbnails re-render.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

The CPU and GPU Highlights/Shadows tone-base paths now use a detail-free plane before guided filtering when detail is nonzero. The GPU median implementation uses workgroup tiling and processes up to four outputs per thread. Tests, process documentation, and the render cache version are updated.

Changes: Highlights and Shadows Tone Base

Layer / File(s) Summary
CPU detail-free plane and validation
crates/pipeline/src/local.rs, crates/pipeline/src/tests_tone.rs, crates/gpu/tests/it/equivalence.rs, docs/parity-checklist.md, docs/process-versions.md
For nonzero detail, the CPU tone-base path clamps log luminance between fine and coarse median planes before guided filtering. Tests cover lettering, isolated lines, steps, flat regions, and edge cases. Documentation describes the updated V2 base.
GPU tiled median filtering
crates/gpu/src/wgsl/blur.wgsl, crates/gpu/src/render.rs, crates/gpu/src/ctx.rs
The median shader loads workgroup tiles and produces up to four adjacent outputs per thread. Dispatch dimensions are rounded up accordingly. The pipeline disables workgroup-memory zero initialization. Tests compare GPU and CPU median results bit for bit and include an ignored benchmark.
GPU detail-free filtering and integration
crates/gpu/src/wgsl/map.wgsl, crates/gpu/src/ctx.rs, crates/gpu/src/render.rs, crates/engine/src/media/source.rs, crates/gpu/tests/it/equivalence.rs
The GPU path adds and registers a clamp kernel, then filters the detail-free plane for nonzero detail. The render cache version changes from 72 to 73.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant tone_base
  participant detail_free
  participant guided_fast
  tone_base->>detail_free: prepare log luminance for nonzero detail
  detail_free-->>tone_base: return clamped plane
  tone_base->>guided_fast: filter the detail-free plane
Loading

Possibly related issues

Suggested reviewers: echelon, radialmonster

Merge Risk: Minimal · up to 14e87

No concrete merge-blocking issue remains identified. The tiled median implementation supports disabling redundant workgroup initialization; merge after normal checks pass.

Security architecture risk: Low · up to fcac3

This is a narrowly scoped photo-rendering change. Existing production input limits and cached-output separation remain in place. No introduced security flaw was identified, although downstream integrations and hardware-failure behavior were not fully validated.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The inspected reachability is confined to caller-provided image planes and existing render consumers. No new network entrypoint, identity transition, privileged operation, or cross-tenant access was identified in that scope. External downstream consumers remain unverified.

Trust Boundaries and Controls

  • observed — The new GPU median sequence clamps source coordinates, synchronizes shared-tile loading before divergent returns, bounds output writes, and assigns distinct output chunks to invocations. Host dispatch sizing matches the four-output shader layout.

Resilience and Maintainability Implications

  • observed — Existing GPU failure checks reject failed or unwritten output before publication. Cache generation and retirement checks guard interrupted or stale jobs, including deferred writes; disk publication uses a temporary file followed by rename. These controls are retained rather than newly introduced by this PR.
Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 73.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed

Check name Status Explanation
Linked Issues check Passed Issue #3460 reports discoloration when using the Shadows slider. The PR changes V2 local::tone_base to use detail_free, which preserves tones in narrow gaps before the guided filter. It adds `gaps…
Out of Scope Changes check Passed The changes remain connected to #3460. The CPU and GPU implementations, median-kernel rewrite, cache-version increment, documentation updates, and regression tests support the tone-base fix, cross-dev…
Title check Passed The title names two changes: a fix for Highlights/Shadows block artefacts in fine detail, and a faster GPU median. Both appear in the changeset. The raw summary covers the detail_free base change, the…
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Linked Issues check

Explanation

Issue #3460 reports discoloration when using the Shadows slider. The PR changes V2 local::tone_base to use detail_free, which preserves tones in narrow gaps before the guided filter. It adds gaps_between_letters_keep_their_own_tone_in_the_base and related regression tests. The reported CPU/GPU agreement and corpus validation support the fix.

Full details: Out of Scope Changes check

Explanation

The changes remain connected to #3460. The CPU and GPU implementations, median-kernel rewrite, cache-version increment, documentation updates, and regression tests support the tone-base fix, cross-device consistency, cache invalidation, or validation. No unrelated change is demonstrated.

Full details: Title check

Explanation

The title names two changes: a fix for Highlights/Shadows block artefacts in fine detail, and a faster GPU median. Both appear in the changeset. The raw summary covers the detail_free base change, the tone_base and local.rs updates, and the blur.wgsl median rewrite. The title is specific and clear, though the "LR-EDIT-LIGHT-SHADOWS" prefix is a tracking code and the title covers two changes.

Full details: Docstring Coverage

Explanation

Docstring coverage is 73.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 15 functions across 6 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • 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

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between fcac37b and 14e8783.

Files selected for processing: 2

  • crates/gpu/src/ctx.rs
  • crates/gpu/src/wgsl/blur.wgsl
Files skipped from review as they are similar to previous changes: 1

  • crates/gpu/src/wgsl/blur.wgsl

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Render-quality fixes landed in place are recorded in docs/process-versions.md
(as storytold#3272 was), not in the release notes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jeremyh
jeremyh marked this pull request as draft October 31, 2026 12:49
…n two medians

The interquartile clamp fixed the lettering but stopped treating isolated
lines between r/2 and r px wide as detail: on a corpus Sony A7 III (shadows
+100) twigs of 3-6 px against a dark wall were lifted less than the wall,
flattening them as V1 did. Light lines 6-10 px wide leaked 0.3-0.6 of the way
into the base (the median: none).

A fixed window can't tell an isolated line from the gap between two strokes;
a wider neighbourhood can (a twig's is mostly wall, a gap's is mostly panel).
`local::detail_free` therefore clamps each value between its separable median
at r (main's `median_hv`) and the median of a 3x wider neighbourhood (the
median at r of a box-downscaled copy, enlarged bilinearly). Both medians on
the same side of the pixel (a twig, a speck): it takes the nearer one. They
disagree (a gap between strokes): it keeps its own value. Steps stay exact
(the fine median keeps them).

- Lettering test: 0 panel px over 1 EV (median: 360; worst 0.8 EV).
- New test: isolated lines of 1-9 px stay out of the base as under the
  median; the quartile clamp fails it (6 px line 0.31 into the base).
- GPU: main's median kernels back, the coarse median through the existing
  box/bilinear resize, and a `clamp_between_k` map kernel. CPU and GPU
  match (max 1 level).
- 32 MP render with Shadows: GPU planes ~231 -> ~254 ms, CPU base
  ~400 -> ~465 ms; the same +10 % / +14 % on an ISO 3200 file.
- Corpus A/B (451 pinned raws x Shadows +100 / Highlights -100, old vs new,
  full size): no failures; RMSE median 0.18 % / 0.10 %, max 0.86 %; worst
  8x8 block median 10 / 7 levels, max 61. The 22 largest local changes
  inspected show no new artefacts, and one more instance of the bug fixed
  (a bright block in the gap between two posts, Hasselblad coverage-6568).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jeremyh
jeremyh marked this pull request as ready for review October 31, 2026 20:23
@insideTheFlux

Copy link
Copy Markdown
Contributor

The bus in the description is the photo from #3460 (6S4A2981.CR3, number 8894, with the same Whites +54, Blacks +31 and Shadows +75 in its video), so this looks like that issue's fix. Nothing links them yet, so Fixes #3460 would close it when this lands. I ran that file and the GPU side on Windows 11 with a GTX 1070 (DX12, FXC), at 73854d9 merged onto main c50b74d.

The reporter's view: in the desktop app at 300 %, on the GPU, main shows the bright blocks between the digits and inside the 4, and this PR doesn't. Full-size renders measure the same: the gaps read 208 to 223 in red on main and 171 to 188 here, against 172 to 183 for the panel around them, which doesn't change. The largest change in the render is 118 levels, on the gear on the far bus's roof. I looked at that spot, and main's hard-edged patches are gone there too. Unedited, the render is byte-identical to main.

CPU against GPU, full size: at most 1 level apart, none over 1, no fallback to the CPU, no driver errors logged.

  • Whites +54, Blacks +31, Shadows +75: the Discolorment while using Shadows slider #3460 CR3 and the CC0 EOS R100, EOS R8 and A7 IV samples
  • Highlights −100: the same three samples and coverage-6568.fff
  • Shadows +100: coverage-6568.fff

cargo test -p lightcraft-gpu passes on the card, and the only skip is the device-loss test. cargo test -p lightcraft-pipeline passes on the CPU, including your new tests.

The cost is higher on this card than the description's +10 %. GPU planes on the #3460 photo with those sliders, median of 6 alternating runs, each in a fresh process:

main This PR Change
Full size (6960×4640) 287 ms 482 ms +68 %
2560 px 35 ms 41 ms +17 %

That's about 195 ms in a full-size render that takes about 7 s in all, so it's small for an export. It may matter more on older cards than the +10 % suggests.

Not tested: macOS, Linux, other GPUs, and drafts while a slider moves (I only looked at finished renders). I didn't repeat your corpus run.

@jeremyh

jeremyh commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor Author

The cost is higher on this card than the description's +10 %

For reference, original tests were done on an Apple M2 Max on MacOS.

…s base

The base's separable median dominated the GPU planes stage: 191 ms of the
226 ms base on a 6960×4640 plane (r = 10, M2 Max). Each pixel ran a partial
selection sort over a private 49-tap array, which drivers keep in scratch
memory because it is indexed dynamically.

median_h / median_v now load each 16×16 workgroup's taps into workgroup
memory and select by rank, 4 neighbouring outputs per thread, which share
all but their first and last 3 taps. Same selection, so the output is bit
for bit the CPU's (new test median_matches_cpu_bit_for_bit, every r 1–24,
edge tiles, ties). Median 191 → 47 ms; full-size GPU planes on the storytold#3460
CR3 with Whites +54, Blacks +31, Shadows +75: main 231, before this commit
257, now 113 ms. Renders are byte-identical to before on GPU and CPU.

CPU: detail_free enlarges the coarse median while it clamps, into the fine
median in place, instead of storing two more full-size planes (same sums;
detail_free_matches_its_reference checks it bit for bit). ~10 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQTJhXnxfpjcQxB77dvuYA
@jeremyh

jeremyh commented Nov 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the 1070 numbers. Looking into it, the coarse median wasn't the main cost: the fine median the base already had on main was. It took 191 ms of the 226 ms base on 6960×4640 (r = 10, M2 Max), because each pixel ran a partial selection sort over a private 49-tap array, which drivers keep in scratch memory.

fcac37b rewrites median_h / median_v: each 16×16 workgroup loads its taps into workgroup memory, and each thread finds 4 neighbouring medians by rank (their windows share all but 3 taps at each end, so one count serves all four). It's the same selection, so the output is the CPU's bit for bit. A new test, median_matches_cpu_bit_for_bit, covers every r from 1 to 24, edge tiles and ties, and the #3460 CR3 renders byte-identical to 73854d9 on GPU and on CPU.

On the #3460 CR3 with Whites +54, Blacks +31, Shadows +75, full size, M2 Max (5 runs alternating):

main 73854d9 fcac37b
GPU planes 231 ms 257 ms 113 ms

The tile layout also avoids workgroup-memory bank conflicts, which NVIDIA penalises more than Apple. I haven't been able to measure it on NVIDIA. Could you rerun your 1070 timing on fcac37b?

The CPU path changes only a little (~10 ms; its median was already a sorted sliding window), so the CPU base is still about 16 % over main.

@FredApps FredApps 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.

ReviewerA — source-read COMMENT (not an approval)

I read the first hunk: RENDER_CACHE_VERSION goes from 72 to 73 (invalidating cached thumbnails because the pipeline's output changes), and per the title (LR-EDIT-LIGHT-SHADOWS) the Shadows adjustment no longer leaves bright blocks beside lettering. Bumping the cache version with a change in the output is the right rule. The change itself is in the pipeline, which I did not read. A fix for artefacts around high-contrast edges is in the part of the algorithm that builds a smooth base (a local filter): please attach before and after crops of the lettering case, and add a regression test with a synthetic image (black text on white, Shadows at +100) asserting that no pixel next to the text exceeds the maximum of its neighbourhood. Nothing was run.

I ran nothing and have no exact-head CI result for this PR, so this is not an approval. Where a diff was long I read its code hunks rather than every generated or documentation line.

Status: waiting_author.

@insideTheFlux

Copy link
Copy Markdown
Contributor

The rewrite helps on the 1070 too: full-size planes are now well under main. But on Windows release builds, FXC now takes about 87 s to compile the kernels, at every start. One line fixes that, and I tested it. All of this is Windows 11, a GTX 1070, DX12 and FXC, merged onto main c50b74d.

main fcac37b With the line
Kernel compile at each start (release) 0.8 s 87 s 1.4 s
GPU planes, full size (6960×4640) 290 ms 179 ms 154 ms
GPU planes, 2560 px 35–37 ms 45 ms 45 ms

The planes are the #3460 photo with Whites +54, Blacks +31 and Shadows +75, medians of 5 to 7 alternating runs, each in a fresh process. As pushed, bench_tone_base gives median_hv 66.6 ms and tone_base 83.1 ms.

What the delay looks like: in the desktop app, launch to a finished render at 300 % goes from 9.5 s on main to 93.6 s as pushed. The interface keeps answering, but the photo waits. FXC runs on the CPU, so I'd expect the delay on any Windows machine using DX12, though I've only measured this one. Debug builds hide it because they skip FXC's optimisation.

Cause and fix: wgpu zeroes med_tile by default, which is the case the comment at crates/gpu/src/nn.rs:515 describes: on DX12 that's one assignment per element. nn.rs and faces.rs already turn it off, but build_jobs doesn't (crates/gpu/src/ctx.rs:166):

compilation_options: wgpu::PipelineCompilationOptions { zero_initialize_workgroup_memory: false, ..Default::default() },

It looks safe here: med_tile is the only workgroup memory those modules use, and the load loop writes everything median4 reads (offsets up to span - 1 on each line) before the barrier.

With that line:

  • Renders are byte-identical to fcac37b as pushed, in all four cases: the Discolorment while using Shadows slider #3460 CR3 and the A7 IV sample with those sliders, the A7 IV with Highlights −100, and coverage-6568.fff with Shadows +100.
  • CPU against GPU at full size, same four: at most 1 level apart, none over 1, no fallback to the CPU, no driver errors logged.
  • median_matches_cpu_bit_for_bit and highlights_shadows_base_matches_on_every_process pass in debug and release. So does the rest of cargo test -p lightcraft-gpu, apart from the test below. The device-loss and face-model tests skip here.

One failure I don't think comes from this PR: running_out_of_device_memory_falls_back_without_stopping_the_gpu ended in "device lost" in full GPU suite runs: 1 of 1 as pushed, 2 of 2 with the line, and 1 of 2 on main. Alone, it passed 3 of 3 on both fcac37b and main. It renders default settings, which don't reach the median.

Not tested: macOS, Linux, other GPUs, drafts while a slider moves, and the full app launch with the line (the 1.4 s is the compile time the CLI logs).

…rnels

wgpu zeroes `var<workgroup>` arrays by default; on DX12 that is one
assignment per element of `med_tile`, and FXC took about 87 s over the
median kernels at every start of a release build (GTX 1070, reported on
storytold#3462). `nn.rs` and `faces.rs` already turn it off. The median kernels
are the only ones `build_jobs` builds that use workgroup memory, and
their load loop writes every element `median4` reads before the barrier.

Renders are byte-identical (the storytold#3460 CR3, Whites +54, Blacks +31,
Shadows +75, M2 Max).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QQTJhXBE6yZLw3xqWysb6P
@jeremyh

jeremyh commented Nov 1, 2026

Copy link
Copy Markdown
Contributor Author

@insideTheFlux Thanks, good catch. 14e8783 turns off workgroup-memory zeroing in build_jobs, as you suggested. The median kernels are the only ones it builds that use workgroup memory, and every element median4 reads is loaded before the barrier, for every r up to the cap of 24. Renders of the #3460 CR3 are byte-identical to fcac37b on the M2 Max, and the GPU tests pass in release. I can't measure FXC here, so if you get a moment, a check of the Windows startup time on 14e8783 would confirm it.

Agreed on running_out_of_device_memory_falls_back_without_stopping_the_gpu: it also fails on main and doesn't reach the median, so I'll leave it out of this PR.

@jeremyh

jeremyh commented Nov 1, 2026

Copy link
Copy Markdown
Contributor Author

@FredApps Both are already in the PR. The description has before/after crops of the lettering case at 300 % (the bus fleet number), plus the Hasselblad gap and synthetic lettering. The regression test is gaps_between_letters_keep_their_own_tone_in_the_base: synthetic dark "8"s on a bright panel, sized like the bus number. It checks that no panel pixel sits more than 1 EV above its tone base. With the old median alone, 360 pixels did (worst 2.25 EV), and the test fails. I checked the base rather than the maximum of each neighbourhood after Shadows, because the bug is in the base: that's the value that tells Shadows how much to lift.

@jeremyh

jeremyh commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Have now tested also on Linux with an AMD integrated GPU: Ryzen 5 7545U (RADV Phoenix2, Vulkan, Mesa), Fedora 44, kernel 7.2.7. This is 14e8783 merged onto main 07301cb, with no conflicts. The PR looks good here: it's faster, CPU and GPU agree, and unedited renders are unchanged. The only problems I hit come from code that main already has (below).

Tests: cargo test -p lightcraft-gpu -p lightcraft-pipeline passes in debug, and -p lightcraft-gpu passes in release. That includes median_matches_cpu_bit_for_bit, highlights_shadows_base_matches_on_every_process and the new pipeline tests. Nothing was skipped, so the GPU tests ran on the real adapter. I left out running_out_of_device_memory_falls_back_without_stopping_the_gpu (see below).

Timings: each row is 5 runs alternating main and this PR, each in a fresh process, on the CC0 EOS R100 CR3 (cr3-canon-r100-raw.cr3) with Whites +54, Blacks +31, Shadows +75:

main This PR
GPU planes, full size (6000×4000) ~540 ms ~197 ms (−63 %)
GPU planes, 2560 px ~50 ms ~29.5 ms
Kernel compile, Mesa shader cache disabled ~74 ms ~76 ms
Kernel compile, cache warm ~11 ms ~11 ms

Vulkan shows nothing like the FXC startup delay. bench_tone_base (6960×4640, r = 10): median_hv 117 ms, detail_free 154 ms, tone_base 182 ms. On the CPU, bench_tone_base_cpu gives tone_base 408 ms.

CPU against GPU (this PR): full size, at most 1 level apart in all six cases, with no warnings and no CPU fallback:

  • Whites +54, Blacks +31, Shadows +75: EOS R100, EOS R8 and A7 IV samples
  • Highlights −100: the A7 IV sample and coverage-6568.fff
  • Shadows +100: coverage-6568.fff

Unedited, the R100 and coverage-6568.fff render byte-identical to main.

main hangs this GPU on coverage-6568.fff (11656×8742), and this PR doesn't. Both times main rendered that file on the GPU, the kernel logged amdgpu: ring gfx_0.0.0 timeout naming lightcraft-cli, then reset the ring ("device wedged, but no recovery needed"). This PR renders the same file on the GPU with no timeout (planes 1.56 s). My guess is the old median kernel (a selection sort per pixel in scratch memory) takes long enough to trip the amdgpu job timeout at 100 MP on a slow integrated GPU, and the new kernel stays under it. That could be worth mentioning in the description. #3005 deals with the same kind of watchdog reset from the large-radius box blur, and the two branches merge cleanly.

Not from this PR, but a warning for anyone testing on an integrated GPU: running_out_of_device_memory_falls_back_without_stopping_the_gpu doesn't stop at the device: it fills system RAM. On an APU, GPU memory is system memory, so the test (thread ctx::tests::out…) set off the kernel OOM killer twice. The first time it killed the terminal session running the tests, the second time GDM, NetworkManager and the GNOME session. It happens the same way on main, since the test isn't touched here. #3499 already mentions the test failing on an RTX 4070 SUPER, where the device is lost. On integrated GPUs the effect is worse, and I didn't find an issue for that. I didn't run the test again.

Not tested: the desktop app (command line only), drafts while a slider moves, and the #3460 bus CR3 (not in the corpus).

🤖 Generated with Claude Code

@insideTheFlux

Copy link
Copy Markdown
Contributor

Confirmed on Windows at 14e8783 (GTX 1070, DX12, FXC, release build): the kernels now compile in about 1.4 s, against about 87 s at fcac37b and 0.8 s on main (median of 6 fresh starts). In the app, launch to a finished 300 % render took 4.2–5.6 s, against 5.1–6.0 s on main (3 starts each, a 24 MP ARW with Shadows +75). CPU and GPU were at most 1 level apart at 800 px, with no fallback and no driver events.

@jeremyh jeremyh changed the title LR-EDIT-LIGHT-SHADOWS: no bright blocks beside lettering under Shadows LR-EDIT-LIGHT-SHADOWS: fix Highlights/Shadows block artefacts in fine detail; 4× faster GPU median Nov 3, 2026
jeremyh added a commit to jeremyh/lightcraft that referenced this pull request Nov 3, 2026
jeremyh added a commit to jeremyh/lightcraft that referenced this pull request Nov 3, 2026
Conflict: docs/process-versions.md. Kept storytold#3462's updated V2 wording (the
two-median clamp) and moved "(the latest)" to storytold#3407's new V3 row.
@jeremyh
jeremyh requested a review from FredApps November 4, 2026 11:27
@FredApps
FredApps requested a review from aiongg November 5, 2026 08:55
@FredApps

FredApps commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

@aiongg assigning this to you and requesting your review.

Context: after merging current main, main's locked legacy test tests_legacy::v1_and_v2_samples_are_as_before_v3_on_every_platform fails (sample 40: 34655 vs 34667), because this PR changes the Highlights/Shadows base (local::detail_free) inside process V2. V1/V2 output has been frozen since V3/V4 landed (#1383), so taking it as is would change existing V2 edits and needs the legacy samples re-captured.

The preferred route is to gate the new base behind a new process version so V1–V4 stay pixel-identical, and to consider splitting out the DX12 workgroup-memory-zeroing speedup (no pixel change) so it can land on its own.

Could you also run the macOS testing where required? In particular, the macOS-only hash test tests_light::v1_and_v2_render_as_before_v3 (and re-capture it if V2 output does end up changing) can't be run on our Linux setup. Thanks!

jeremyh and others added 2 commits November 5, 2026 21:16
…cess V3

Main froze V1 and V2 with locked samples (tests_legacy), and this branch changed
V2's Highlights/Shadows base. V2 keeps its plain median now and `detail_free` applies
from V3 (`local::base_keeps_gaps`, on the CPU and the GPU), which is not in a release
yet (v0.18.1's latest is V2). V3 and V4 keep the same base as each other. The faster
median kernels and the workgroup-memory change don't change pixels and apply to all.

RENDER_CACHE_VERSION 76.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…process V7

v0.19.0 released processes V3 to V6, so the lettering fix can no longer
change V3: it becomes process V7 (V6 plus `local::detail_free`), and V1 to
V6 render as before. `local::base_keeps_gaps` is true from V7; the docs,
checklist rows and tests follow. The unknown-process test reads one past
the latest instead of a fixed 7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jeremyh

jeremyh commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

@FredApps Done in d2d39a0, on the route you preferred:

  • New process V7. Since this PR was written, v0.19.0 released V3 to V6, so the new base can't go into V3 any more. It now applies from V7 (V6 plus local::detail_free). V1 to V6 keep the plain median and render as before: tests_legacy::v1_and_v2_samples_are_as_before_v3_on_every_platform passes unchanged, and only_process_v7_on_takes_the_detail_free_base checks every earlier process. RENDER_CACHE_VERSION stays at main's 76, since no existing edit renders differently. The docs (process-versions.md V7 row, the checklist notes) follow.
  • The DX12 workgroup-memory change stays here. It only matters for this PR's new median kernels: they are the only pipeline kernels with workgroup memory, and on main the GTX 1070 compiled the kernels in 0.8 s (@insideTheFlux's numbers above). Landing it alone would speed up nothing, and landing the kernels without it would bring back the 87 s start. Neither change alters pixels.
  • macOS: V1 and V2 output is unchanged, so tests_light::v1_and_v2_render_as_before_v3 shouldn't need re-capturing. @aiongg, a run on macOS would still confirm it.

Run after the merge, on Linux (Ryzen 5 7545U, RADV): cargo test --release of develop, pipeline, catalog, engine, and gpu on the real adapter (skipping the device-memory test that fills RAM on an APU), plus fmt, clippy -D warnings, xtask layers / roots / assets / parity / wasm. Not run: the full cargo xtask ci, and macOS.

jeremyh and others added 2 commits November 9, 2026 22:52
…process V8

Crystal grain (storytold#3630) took process V7 on main, so the Highlights/Shadows
detail-free base now starts at V8 (V7 plus `local::detail_free`). V1 to V7
keep the plain median and render as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@FredApps FredApps 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.

Approving at d4bdd065.

The route I asked for on 11-05 is in. The detail-free base applies only from the new process V8 (settings.rs), so V1 to V7 render as before. only_process_v8_on_takes_the_detail_free_base checks every earlier process, main's locked legacy samples pass unchanged, and docs/process-versions.md has the V8 row. The rest of my original comment is covered too: the description has before/after crops, and gaps_between_letters_keep_their_own_tone_in_the_base is a synthetic regression that, by your run, fails with the old median.

The GPU side:

  • The new median is checked against the CPU bit for bit (median_matches_cpu_bit_for_bit, every r from 1 to 24, edge tiles and ties).
  • Workgroup-memory zeroing is turned off only in build_jobs. I checked that the only kernels it builds with workgroup memory are the new blur.wgsl medians. faces_*.wgsl and nn_conv.wgsl build their own pipelines and already had zeroing off.

insideTheFlux's Windows numbers (1.4 s compile, faster planes) and your RADV run cover the drivers I can't test.

What validated it: the Linux gate passes on this head. Windows was skipped by its path filter.

What I didn't run: I didn't build it or run the GPU tests locally, because the box has no GPU.

Rule 15 (not blocking): the description ends with "Generated with Claude Code" and seven commits carry Co-Authored-By: Claude trailers. Please leave AI attribution out of both.

@FredApps
FredApps merged commit bb414d2 into storytold:main Nov 11, 2026
8 checks passed
@FredApps

Copy link
Copy Markdown
Contributor

Thanks @jeremyh — this fixes Highlights/Shadows block artefacts in fine detail and speeds up the GPU median, gated on the new process version so legacy samples stay unchanged. Squash-merged as bb414d2.

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.

Discolorment while using Shadows slider

4 participants