Skip to content

Avoid capturing input array x in the chunk pullback - #252

Merged
CarloLucibello merged 2 commits into
mainfrom
cl/chunk-rrule-avoid-capturing-x
Jul 31, 2026
Merged

Avoid capturing input array x in the chunk pullback#252
CarloLucibello merged 2 commits into
mainfrom
cl/chunk-rrule-avoid-capturing-x

Conversation

@CarloLucibello

Copy link
Copy Markdown
Member

Resolves the # TODO avoid capturing x in the pullback at src/utils.jl:219 (item 1 of #227).

Problem

rrule(::typeof(chunk), x) captured the whole input array x in its pullback closure, keeping it alive for the entire backward pass — even though chunk's gradient never uses x's values, only its axes, array type and element type.

Change

Capture ProjectTo(x) and an empty similar(x, 0) instead of x:

  • ProjectTo(x) carries x's axes and restores its structure.
  • similar(x, 0) carries x's array/element type (so the gradient allocates with the right backend, e.g. GPU) while holding no data.

∇chunk builds dx from these and returns project(dx). The second-order rrule(::typeof(∇chunk)) and the direct ∇chunk test are updated to the new signature.

On a 1000×500 input, the pullback's captured state shrinks from ~4 MB to 80 bytes; the all-zero branch still returns a materialized zero array, so type stability (checked by the size collection test) is preserved.

Also relaxes the CUDA test compat to 5, 6 so the test environment resolves on current Julia.

Testing

The full chunk testset passes (37/37) in the repo's test environment. CUDA.functional() was false locally, so the GPU branch was not exercised.

🤖 Generated with Claude Code

CarloLucibello and others added 2 commits July 31, 2026 07:34
The reverse rule for `chunk` captured the whole input array `x` in its
pullback closure, keeping it alive for the entire backward pass even
though `chunk`'s gradient only needs `x`'s axes, array type and element
type (never its values).

Capture `ProjectTo(x)` and an empty `similar(x, 0)` instead: together
they supply the axes, structure and array/element type needed to
allocate and project the gradient, without holding any of `x`'s data.
On a 1000x500 input the pullback's captures shrink from ~4 MB to 80 B.

`∇chunk` and its second-order rrule are updated to the new signature,
as is the direct `∇chunk` test (the `ProjectTo`/template args are held
fixed since they are non-differentiable).

Also relax the `CUDA` test compat to `5, 6` so the test environment
resolves on current Julia.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@CarloLucibello
CarloLucibello merged commit 0d80856 into main Jul 31, 2026
6 of 7 checks passed
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