Factor shared scaffolding out of the allocating Enzyme rules#736
Merged
Conversation
The 8 rules for allocating ops (imrotate, upsample_nearest/linear, grid_sample, ctc_loss, batchnorm, unfold, fold) each repeated the same augmented/reverse plumbing: run the forward, allocate an output shadow, and on reverse loop over the batch width feeding the shadow to the op's ∇ function and accumulating into each differentiable input. Collapse that into four helpers: - `_enz_alloc_augmented(config, y, extra)` — the standard augmented pass. - `_enz_alloc_reverse!(config, shadow, args, backward)` — the reverse loop; `backward(dy)` returns one cotangent per `arg`. - `_enz_accum!` — a `Base.tail` recursive unroll of the per-input accumulation, keeping it type-stable (a `zip` over the heterogeneous arg/grad tuples would dynamically dispatch). - `_enz_active_reverse!` — the scalar `Active`-return variant (ctc_loss). Each rule now shrinks to its forward call + a one-line backward closure, so the per-op logic (which ∇, which inputs, what to cache) is all that remains visible. Removes the now-unused `_enz_pairs`. Pure refactor — no behavior change. Verified equivalent: CPU rotation/upsample/fold/sampling/ctc suites unchanged; `EnzymeTestUtils.test_reverse` across all activity combos incl. BatchDuplicated (width>1) passes for imrotate/upsample/unfold/fold, and grid_sample reproduces the same pre-existing finite-difference discrepancies (grid gradient, 0-padding) byte-for-byte against the pre-refactor code; GPU batchnorm and grid_sample still match Zygote; untouched conv/pool rules pass (1402 + 4117). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Follow-up refactor after #735 (merged). No behavior change — purely reduces boilerplate in the Enzyme extension.
Motivation
The 8 EnzymeRules for allocating ops (
y = f(...)) —imrotate,upsample_nearest,upsample_linear,grid_sample,ctc_loss,batchnorm,unfold,fold— each repeated the same augmented/reverse scaffolding: run the forward, allocate an output shadow, then on reverse loop over the batch width feeding the shadow to the op's∇function and accumulating into each differentiable input. Adding an op meant copy-pasting that plumbing (and it was exactly that copy-paste that hid the width-1_enz_slicescalar-indexing bug fixed in #735).Change
Four small helpers capture the shared structure:
_enz_alloc_augmented(config, y, extra)— the standard augmented pass (primal/shadow per config, cache(shadow, extra...))._enz_alloc_reverse!(config, shadow, args, backward)— the reverse loop;backward(dy)returns one cotangent perarg._enz_accum!— aBase.tailrecursive unroll of the per-input accumulation, keeping it type-stable (azipover the heterogeneous arg/grad tuples would dynamically dispatch)._enz_active_reverse!— the scalarActive-return variant (ctc_loss).Each rule now shrinks to its forward call plus a one-line
backwardclosure, so only the per-op specifics (which∇, which inputs, what to cache) remain visible. The now-unused_enz_pairshelper is removed. Signatures stay per-rule (needed for dispatch, kwargs defaults, and theConst{<:DenseConvDims}constraints). Scope is deliberately limited to these allocating rules; the in-placeconv!/pool!/softmax!/gather!/scatter!/_dropout!rules andbatched_mulare left untouched (theiroverwritten-based caching is subtle and varies per rule).Net −7 lines despite adding the helper infrastructure, and each of the 8 rules is roughly halved.
Verification (behavior-preserving)
rotation347/347,upsample74/74,fold67/67,sampling30/30,ctc5/5.EnzymeTestUtils.test_reverseacross all activity combinations includingBatchDuplicated(width > 1):imrotate,upsample_nearest,upsample_linear,unfold(123/123),fold(147/147) all pass.grid_samplereproduces the same pre-existing finite-difference discrepancies (grid gradient under 0-padding) byte-for-byte against the pre-refactor code (78 pass / 6 fail on both).batchnorm(g/b/x) andgrid_sample(input/grid) still match Zygote.cpu/pooling1402/1402,cpu/conv4117 pass.🤖 Generated with Claude Code