Skip to content

[dynamo] Defer full garbage collections while compiling - #193289

Closed
anijain2305 wants to merge 23 commits into
gh/anijain2305/1311/basefrom
gh/anijain2305/1311/head
Closed

anijain2305 wants to merge 23 commits into
gh/anijain2305/1311/basefrom
gh/anijain2305/1311/head

Conversation

@anijain2305

@anijain2305 anijain2305 commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

A full (generation 2) collection walks every tracked object. Compiling creates
on the order of a million of them - FX nodes, SymNodes, sympy expressions - so
with CPython's default gen2 threshold of 10 the collector repeatedly rescans a
heap that is still growing. One model's cold compile spends 5.18s in gc, 4.22s
of it in 16 full collections at ~260ms each; perf shows gc_collect_main and its
helpers at ~4.8% of the process.

Raise the gen2 threshold for the duration of a compile and restore it after.
What goes away is paying for the same traversal over and over while the heap
grows, not the collection itself. gen0 and gen1 keep collecting throughout
(0.87s total) and non-cyclic garbage is still freed by refcounting the moment it
dies, so what is deferred is specifically cyclic garbage that has been promoted
to gen2. Note run_gc_after_compile does not cover that: it calls gc.collect(1),
which collects generations 0 and 1 only and frees nothing from gen2. The deferred
full collection is not skipped forever either - once the threshold is restored
the gen2 counter is already well past it, so the next gen1 collection promotes to
a full one shortly after the compile. Reentrant, so nested compiles share the
outermost adjustment.

The guard is applied in two places. Dynamo's _compile covers a frame's forward
compile, and lazily lowering the backward gets its own, since it runs later,
outside that scope, and builds as much graph as the forward did. That scope is
deliberate rather than exhaustive: fullgraph_capture (what torch.export uses,
bypassing compile_inner), compile_fx_aot for AOTInductor, and compiled
autograd's capture all build comparably large graphs and are left for a
follow-up. Note the existing run_gc_after_compile is only in the Dynamo path;
that looks incidental rather than deliberate (#143364 added it for training jobs
and only touched convert_frame), but this change does not extend it, because
forcing collections measured worse - an earlier prototype that suspended gc per
compile and forced a collect at the end was 4s slower than doing nothing.

The default is None on free-threaded builds, which never read threshold2 and
whose collector is not generational, so the knob would be silently inert there;
run_gc_after_compile gates on the same condition for the same reason. CPython
3.14.0 through 3.14.4 also ignore threshold2, but that window is closed as of
3.14.5, so it gets a comment rather than a guard. The threshold is also
overridable from the environment, and never lowers a gen2 threshold the caller
already raised past ours.

The backward is where the split shows up: with dynamic=True this model compiles
its backward eagerly with the forward (the lazy path takes 0.02s and there is
nothing to save), while with dynamic=False the lazy backward is 8.19s of wall
time containing exactly one full collection. Measured inside that window over
three runs, gc goes from 0.65/0.71/0.66s to 0.16/0.17/0.16s as that collection
stops firing, with gen0 and gen1 unchanged at ~915 and ~82 collections. That
0.5s is under the run-to-run noise of end-to-end wall clock, so it is measured
on the window rather than the total.

Sweeping the threshold on that model:

threshold full collections gc total compile
10 (default) 16 5.18s 45.41s
100 5 3.23s 42.96s
1000 0 0.87s 40.76s

Total compile time at 1000, measured as the union of top-level chromium events
over interleaved pairs:

pair 1: baseline 43.51s deferred 40.21s
pair 2: baseline 43.59s deferred 39.99s
pair 3: baseline 43.34s deferred 40.55s

43.48s -> 40.25s, -7.4%, no overlap between the two sets. The cost is peak
memory: max RSS went from 3581MB to 3626MB, +45MB or +1.3%, because cyclic
garbage waits longer to be reclaimed. Set
config.gc_gen2_threshold_during_compile = None to opt out.

This is not dynamic-shape overhead. The same model compiled with dynamic=False
also spends 2.63s in gc, 1.86s of it in 11 full collections, and the same change
takes it from 31.45s to 29.63s. Dynamic shapes make it worse on both multipliers
rather than causing it: they allocate more (520 gen1 collections vs 446, so gen2
falls due more often) and they enlarge the live heap that each full collection
walks (264ms per collection vs 169ms), because symbolic shapes add on the order
of a million SymNode and sympy objects that a static compile never creates.

Test plan:

python -m pytest -q test/dynamo/test_utils.py
# 32 passed, 2 skipped

python test/dynamo/test_misc.py

test_misc's failure set is identical to a run with the change stashed (this host
has pre-existing aarch64 CPU codegen failures). The four new tests in
test_utils.py exercise deferred_full_gc directly, covering install/restore,
nesting, the disabled case, and that an exception inside the scope still returns
the depth counter to zero - a leak there would silently turn the feature into a
no-op for the rest of the process and pin the raised threshold, which would
surface far from its cause.

This PR was authored with the assistance of an AI coding agent.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: dynamo topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants