Repository navigation
borealis: fuse Sobel and Canny NMS at submission - #1303
Conversation
GB6's Canny (Edge and Horizon Detection) records every stage in its own one-dispatch command buffer and submits them together. The NMS reads the Sobel's dir and mag (8 bytes per pixel) back from memory right after the Sobel wrote them. Run the two as one dispatch when they are adjacent in a submission: - hk_nir_build_sobel_nms() builds, for each matched 3x3 Sobel, a kernel with the Sobel's 128x8 tile that writes dir and mag exactly as the tiled Sobel does, keeps the magnitudes of the tile and a one-pixel ring in workgroup memory, and evaluates the NMS from there. It is compiled with the Sobel pipeline and serialized with it. - The tiled Sobel and NMS dispatches are recorded for the submit-time planner (HK_COMPUTE_PAIR_SOBEL3X3, HK_COMPUTE_PAIR_CANNY_NMS). - hk_compute_pair_canny_match() takes the pair only when the NMS reads exactly the Sobel's dir and mag over the same image, its output is clear of the Sobel's source, dir and mag by BO range and by address, and its direction tables stay within the one-pixel ring. The NMS inputs the Sobel's descriptors lack go in a submission-owned root (struct hk_sobel_nms_push). Anything else between the two command buffers, separate submissions, aliasing outputs or another mag buffer keep them apart. The new hk_canny_fuse test runs the tiled Sobel and NMS and the fused kernel on the NIR evaluator over 171 image cases, odd widths included, and requires every dir, mag and NMS byte to match, and checks the pairing rule's negatives. The evaluator gains ubitfield_extract, ptr_as_array and vector component derefs for it. Signed-off-by: DjDeveloperr <hey@djdev.me>
There was a problem hiding this comment.
Verdict: MERGE at f2ca0c97
Blockers: none (second GPU generation confirmation noted in Not yet:)
Checked: no Apple material, no AI attribution, human DCO Signed-off-by, Borealis naming clean, no chip/board/firmware gates, full diff (+1389/-46 across 12 files) verified — hk_nir_build_sobel_nms() shares sobel_3x3_outputs() with the standalone tiled Sobel so both dir and mag output buffers stay bit-identical while computing a 1-pixel halo in shared memory for NMS, hk_2d_stencil_sobel_nms_supported() verifies Sobel push-constant offsets stay strictly below HK_SOBEL_NMS_PUSH_OFFSET_B (224, leaving 24 bytes for struct hk_sobel_nms_push within the 256-byte push-constant root table), hk_compute_pair_canny_match() validates dimensions (>= 1, stride >= width, INT32_MAX byte bounds), hk_sobel_nms_lut_in_ring() ([-1, 1] offsets), exact BO+VA interval equality for dir/mag, and both BO-interval and VA disjointness for dst against src/dir/mag, hk_shader.c properly wires destroy/serialize/deserialize/cacheability/cache-clone for sobel_nms, hk_canny_fuse CPU NIR evaluator test covers bit-exact parity and negative pairing checks, exact-head J700 (G17P) hardware row PASS (-43..44% Sobel+NMS GPU time, 483 matching outputs, -13.2%/-21.2% Geekbench Horizon/Edge GPU time, 3,435/3,435 CTS matches, 10/10 gpubench-vk CRCs), PR body has Tested: and Risk: Two-way door, branch is MERGEABLE against aurora-wip.
Evidence
- Checked
hk_2d_stencil.h,hk_cmd_dispatch.c,hk_compute_pair.h,hk_compute_pair_interval.h,hk_nir_tile_2d_stencil.c,hk_queue.c,hk_shader.c,hk_shader.h,meson.build,hk_nir_eval_test.h, andtest-hk-canny-fuse.c:hk_record_canny_pair()restricts recording to primary, direct-grid, single-dispatch, non-meta, non-simultaneous, zero-base command buffers with valid uploaded root and non-push/non-buffer-active storage bindings.hk_pack_runs()validateshk_compute_pair_canny_match(),hk_fused_compute_shader_eligible(), andhk_pack_fusion_fits_run_limit()before suppressing the trailing NMS command buffer and copyingpl->sobel_nms_pushatrt->push + HK_SOBEL_NMS_PUSH_OFFSET_B.hk_shader.c:ralloc_steal(NULL, sobel_nms_nir)detaches fromtiled_nirbeforehk_compile_nir(), cleanly frees on failure/OOM, destroyssobel_nmsinhk_api_shader_destroy(), validateshas_sobel_nms <= 1on deserialize, checks payload cacheability, and clones both variants inhk_shader_binary_cache_clone().
- Exact-head J700 (
f2ca0c97e9e7) verification: Sobel+NMS-43..44%GPU time (483/483 matching outputs), Geekbench Vulkan Horizon-13.2%/ Edge-21.2%GPU time, 8/8 subtests validated, 3,435/3,435 CTS statuses matched, 10/10 gpubench-vk CRCs.
DjDeveloperr
left a comment
There was a problem hiding this comment.
Verdict: HOLD (independent review at f2ca0c97e9e7a9460d3d0f39357cf7d7df44a56c)
The fused Sobel + Canny NMS NIR kernel, shared-memory indexing (sh_src 12x132 / sh_mag 10x136, Phase 1 taps, 276-cell ring, sobel_nms_class parity, edge-tile scalar path including width < 4, unaligned dst stores), aliasing/bounds validation (hk_compute_pair_canny_match), OOM fallback, BO folding, and fail-closed footprint handling look sound. Two blockers must be fixed before merge:
Blockers
-
Use-after-free on
extra.canny.fusedif the Sobel pipeline/shader is destroyed after recording (src/asahi/vulkan/hk_cmd_dispatch.c:3548,src/asahi/vulkan/hk_shader.c:7329-7333,src/asahi/vulkan/hk_queue.c:5860,7765):hk_record_canny_pair()stores a raw, un-refcounted pointercanny->fused = (struct hk_shader *)&api->stencil_2d->sobel_nms;incs->compute_pairand leavesrecord.producer = NULL.hk_api_shader_destroy()immediately callshk_shader_destroy(dev, &obj->stencil_2d->sobel_nms, owns_payload)(releasingsobel_nms.only_linkedand its GPU code BO) andfree(obj->stencil_2d).- Unlike
hk_record_compute_pair()(hk_cmd_dispatch.c:3498-3499), which holds apipe_referenceviahk_compute_pair_producer_ref()specifically so submit-time fusion state survives pipeline destruction after recording (seehk_compute_pair.h:161-166andhk_compute_pair_fadd_producer_create()athk_shader.c:10893), nothing keepssobel_nmsalive between recording andvkQueueSubmit(). - If an application destroys the Sobel pipeline/shader after recording and then submits (or resubmits) the command buffer,
hk_pack_runs()dereferences freedcandathk_queue.c:5860,5883and freedfused_shader->only_linked->b.boathk_queue.c:7765. - Fix: Give the fused Sobel+NMS shader refcounted ownership shared between
hk_api_shaderandcs->compute_pair(e.g., wrapsobel_nmsin a refcountedhk_compute_pair_producerlikefadd, or add apipe_referenceon a small holder /hk_2d_stencil_variantunreffed inhk_cs_invalidate_compute_pair()), and add a lifetime test coveringhk_api_shaderdestruction beforehk_cs_invalidate_compute_pair().
-
Shader binary wire format changed without bumping
HK_*_SHADER_BINARY_VERSION(src/asahi/vulkan/hk_shader.c:12904,13675,src/asahi/vulkan/hk_agx3_vdm_decode.h:44-48,src/asahi/vulkan/tests/test-hk-execution-allowance.c:229-233):hk_api_shader_serialize()now unconditionally writesuint8_t has_sobel_nms(and optionalsobel_nmspayload) insideif (obj->stencil_2d), andhk_deserialize_api_shader_impl()unconditionally reads it wheneverhas_stencil_2dis set, changing the serialized layout of allhas_stencil_2dshaders.HK_AGX3_SHADER_BINARY_VERSION(54u),HK_CLASSIC_SHADER_BINARY_VERSION(41u), andHK_AGX2_SHADER_BINARY_VERSION(39u) were not bumped, violating the contract inhk_agx3_vdm_decode.h:24-26.- Fix: Bump all three shader binary version constants (
54u -> 55u,41u -> 42u,39u -> 40u), update the header comment, and updatetest-hk-execution-allowance.c:229-233.
Non-blocking note & merge gate
- In
hk_shader_binary_cache_clone()(hk_shader.c:13283-13297),s2d->sobel_nms.only_linkedisNULL(lazy_ht = true), so cloned cached binaries safely skip fusion inhk_fused_compute_shader_eligible()rather than crashing. - Once both blockers are fixed and re-verified on J700 + Fedora CI (release & assertions-on), a 2nd-gen HW confirmation row (e.g., J516s) will still be required before merge since this modifies shared
hk_shader.c/hk_queue.c/hk_cmd_dispatch.cpaths.
Sobel command streams retain the producer that owns the fused shader and its GPU code. Share the producer across binary cache wrappers so recorded work does not depend on the lifetime of the API shader or cache entry. Bump all three shader binary versions for the fused Sobel and Canny NMS payload and test that stream invalidation releases the recorded shader exactly once. Signed-off-by: DjDeveloperr <hey@djdev.me>
There was a problem hiding this comment.
Verdict: MERGE at 58caaab9 (confirm meson test --suite asahi at 58caaab9 in merge train)
Blockers: none
Checked:
- Audited
f2ca0c97 -> 58caaab9resolving both blockers from thef2ca0c97hold:- Refcounted fused Sobel+NMS shader lifetime (
hk_compute_pair.h,hk_shader.{c,h},hk_cmd_dispatch.c,hk_queue.c,hk_compute_pair_interval.h):hk_compute_pair_sobel_producer_create(dev)wraps the fused shader in a refcountedstruct hk_compute_pair_producer(variant_count = 1,hk_compute_pair_producer_destroy()freesvariants[0].shaderwithowns_payload = true).hk_record_canny_pair()takeshk_compute_pair_producer_ref(api->stencil_2d->sobel_nms)onrecord.producer(released inhk_cs_invalidate_compute_pair()),hk_api_shader_destroy()unrefsobj->stencil_2d->sobel_nms, andhk_shader_binary_cache_clone()safely shares the refcounted producer (hk_compute_pair_producer_ref()is NULL-safe).test_fused_shader_lifetime()intest-hk-canny-fuse.cexplicitly verifieshk_api_shader_destroy()before two submissions followed by idempotenthk_cs_invalidate_compute_pair()cleanup.
- Shader binary wire version bump (
hk_agx3_vdm_decode.h,test-hk-execution-allowance.c):- Bumps all three constants (
HK_AGX3_SHADER_BINARY_VERSION54 -> 55,HK_CLASSIC_SHADER_BINARY_VERSION41 -> 42,HK_AGX2_SHADER_BINARY_VERSION39 -> 40) with matching unit test assertions.
- Bumps all three constants (
- Refcounted fused Sobel+NMS shader lifetime (
- Core fused Sobel + Canny NMS kernel, aliasing checks, and J700 hardware verification (
-43..44%GPU on 5600x4200,3,435/3,435CTS0fail,10/10CRCs) remain unchanged and sound.
Evidence
hk_queue.c:329also adds the required second message argument tostatic_assert(...)for strict C11/C17 compatibility.
|
Exact-head verification for Recorded Sobel pairs now retain the fused shader and its GPU code. The lifetime test releases the API owner, verifies the linked shader stays live, and checks that stream invalidation cleans it up exactly once. Shader binary versions are AGX3 55, classic 42, and AGX2 40. Fedora Asahi passed 223/223 on the serial retry with default assertions disabled and 223/223 with J700 on stock |
DjDeveloperr
left a comment
There was a problem hiding this comment.
CODE-CLEAR at 58caaab920874d749bc9500bf94c4df45b473001. The J516s hardware confirmation remains the merge gate.
The recorded stream retains the fused Sobel producer and releases it on invalidation, reset or teardown. Packed submissions pin the GPU code through completion. The optional fused payload is covered by the AGX3, classic and AGX2 binary version bumps to 55, 42 and 40.
Verification
- Clean merge with
aurora-wipat5b64e3c144d1d9a350f4c0334a67b31be50cc22d, clean whitespace checks and DCO sign-offs on both commits. - The Fedora 44 arm64 release build passed 228/228
asahiandpolytests with assertions enabled and again with assertions disabled. - The lifetime test failed at the destruction-count check when its fixture dropped the producer reference. It still passed with only the production recorder's reference removed because the fixture takes its own reference at
src/asahi/vulkan/tests/test-hk-canny-fuse.c:522. - The exact-head J700 row matched 483 output hashes and recorded 219 fused submissions without GPU faults. J700 verification
TestingM3 Pro (T6030 / J516s) passed the Sobel + Canny NMS A/B at Test setup and healthBaseline |
What: Borealis fuses adjacent Sobel and Canny nonmaximum suppression dispatches in one submission. The fused workgroup reuses its magnitude tile and halo from shared memory and preserves both Sobel output buffers.
Tested: MacBook Neo J700 at
f2ca0c97e9e7. Sobel+NMS took 43–44% less GPU time, with 483 matching outputs. Geekbench Vulkan Horizon and Edge used 13.2% and 21.2% less GPU time per measured iteration. All eight subtests validated, 3,435 CTS statuses matched the baseline, and both builds passed all 10 gpubench-vk CRCs.Risk: Two-way door · Borealis GPUs eligible for compute submit packing. An optional fused variant adds pipeline compilation work for matched Sobel shaders. On J700, the full Horizon and Edge workload intervals grew 2.8% and 3.5%, respectively, with the additional time appearing between GPU submissions during tuning.
Not yet: Other GPU generations.
Details
The dispatches must use the same image bounds and the same direction and magnitude backing ranges. The NMS output must be disjoint in both buffer-object and virtual-address space, and all supported direction offsets must fit the one-pixel halo. The fused kernel uses the tiled Sobel’s 16-bit gradients and direction quantization and the submit planner’s device work limit.
Evidence
Build and hardware
7.3.0-41.fc44.aurora.aarch64 #1 SMP PREEMPT_DYNAMIC Mon Nov 16 16:49:34 UTC 2026. The apple-mcc boot log showed SLC allocation enabled on four planes.702dd0165bd0c92eca078844d7235428de8ba6ef, Vulkan library SHA-256aaf6a303fe498ecdf5efe755cf4c17b8229b246fe40cce25f9405d81856b6c74.f2ca0c97e9e7a9460d3d0f39357cf7d7df44a56c, Vulkan library SHA-2565a0b1090fa5f00705c2b62b4a3ef711027ff17214e60010846a6dd7174117618.Performance
Geekbench 6.7.1 Linux AArch64 Preview ran as
geekbench6 --gpu VulkanwithVK_DRIVER_FILESpointing to the staged ICD andLD_LIBRARY_PATHpointing to the staged lib64. Each process had a unique temporary home, a loopback-only network namespace and 512 MiB memlock. Both builds usedMESA_SHADER_CACHE_DISABLE=true,HK_FRAME_ANATOMY_EVERY=1andHK_FRAME_ANATOMY_TS=all. The GPU timing uses the union of firmware-timestamp intervals per measured iteration after tuning. Geekbench 6.7.1The execution order was
A1 B1 B2 A2 B3 A3 A4 B4, all on the same boot. Each pass ran all eight subtests and reached the offline upload marker with zero validation errors. There were 19 measured iterations per subtest per pass and 20 for Face Detection.Five controls stayed within 0.27% in GPU busy time. Gaussian Blur ran the same two GPU programs in both builds. Its low and high timing modes both occurred on both builds. The low-mode median was 11.128 → 11.127 ms and the high-mode median 14.104 → 14.041 ms. The overall median reflects different mode frequencies. Its workload wall time fell 0.43%.
Horizon and Edge improved in both orders. Their tuning phases had the same submit counts across builds and approximately the same GPU busy time, with longer host-side gaps on B. The workload marker intervals include this tuning cost.
GPU busy time per measured iteration
Wall time between workload markers
GPU busy times in execution order
Wall times in execution order
The isolated 5600×4200 Sobel and NMS probe records each stage in its own command buffer. The probe compared 483 cases against a CPU reference and compared full output hashes between drivers. It observed 219 fused submissions on B and zero on A. GPU timestamps were collected across consecutive pairs.
Conformance and CRCs
Vulkan CTS
vulkan-cts-1.4.7.1, with driver-ID registration and teardown fixes at3fd4ea318fe2. The target list used compute basic, built-in variable, indirect dispatch, explicit workgroup-memory layout and zero-initialization cases, plus synchronization smoke, basic, operation, signal-order, timeline semaphore and implicit synchronization cases. The runner useddeqp-vkwith the same case list and private ICD on both arms, two jobs, and log images and shader source disabled. Vulkan CTSAll 3,435 per-case statuses matched, with zero failures, crashes, timeouts, quality warnings or recoveries. gpubench-vk ran
compute.chain, bothcompute.edgemodes (Sobel and Harris at 1080p),render.deferredandrender.postfxwith--depths 1,4 --warmup-ms 100 --run-ms 300 --runs 2. All 10 CRC results per build matched the expected values and the other arm. gpubenchUnit tests and CI
The Fedora 44
--suite asahipassed 223/223 withb_ndebug=trueand 223/223 with-Db_ndebug=false, with zero new compiler warnings. Both configurations passed the 171-case Canny unit test. An earlier parallel run exceeded Meson’s 30-second limit in the existinghk_packtest. The complete serialized runs used--num-processes 1 --timeout-multiplier 3and passed without failures or timeouts. Canny unit test