Skip to content

perf(autogram): Avoid tensor creation in autogram hook - #820

Merged
ValerianRey merged 2 commits into
mainfrom
perf/autogram-hook-smallest-output
Oct 7, 2026
Merged

ValerianRey merged 2 commits into
mainfrom
perf/autogram-hook-smallest-output

Conversation

@ValerianRey

Copy link
Copy Markdown
Member

At every forward pass of every hooked module, Hook.__call__ built a CPU tensor of its output sizes and called argmin().item() on it, just to pick the smallest output. It now uses min(rg_outputs, key=lambda t: t.numel()), which selects the same output (the first one in case of ties) without creating a tensor.

Measured on a model with 200 small hooked modules (median of 5 alternated runs of old and new code):

forward forward + compute_gramian
CPU 23.4 → 19.5 ms (−17%) 152.0 → 147.3 ms (−3%)
CUDA 31.6 → 27.6 ms (−13%) 209.0 → 206.2 ms (−1%, within noise)

This is close to a worst case: the gain per module is fixed (about 6 µs), so it's smaller in relative terms with larger modules. The Gramians are bit-identical on CPU and CUDA, and the autogram tests pass.

🤖 Generated with Claude Code

The forward hook of each module built a CPU tensor of output sizes and called
argmin().item() on it to find its smallest output. It now uses Python's min
with a key, which selects the same output (the first one in case of ties)
without creating a tensor at every forward pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ValerianRey ValerianRey added package: autogram cc: perf Conventional commit type for changes mostly focused on performance improvements (memory or speed). labels Oct 7, 2026
@github-actions github-actions Bot changed the title Avoid tensor creation in autogram hook perf(autogram): Avoid tensor creation in autogram hook Oct 7, 2026
@ValerianRey
ValerianRey marked this pull request as ready for review October 7, 2026 16:28
@ValerianRey
ValerianRey enabled auto-merge (squash) October 7, 2026 16:28
@ValerianRey
ValerianRey merged commit 51fddc4 into main Oct 7, 2026
18 checks passed
@ValerianRey
ValerianRey deleted the perf/autogram-hook-smallest-output branch October 7, 2026 19:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cc: perf Conventional commit type for changes mostly focused on performance improvements (memory or speed). package: autogram

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant