Skip to content

perf(pt): pass is_inference to compile_fx_inner for compiled eval graphs - #6056

Open
long-yi-2019 wants to merge 2 commits into
deepmodeling:masterfrom
long-yi-2019:pr/eval-is-inference
Open

long-yi-2019 wants to merge 2 commits into
deepmodeling:masterfrom
long-yi-2019:pr/eval-is-inference

Conversation

@long-yi-2019

@long-yi-2019 long-yi-2019 commented Oct 7, 2026 •

Copy link
Copy Markdown

Motivation

The custom inference compiler entry in sezm_model.py calls
compile_fx_inner(fx_gm, fx_inputs) without the is_inference flag, so
Inductor plans memory for the eval graph under training assumptions:
outputs are allocated early and autograd-visible intermediates stay
alive, inflating peak VRAM of compiled inference.

torch.compile's own default path already passes is_inference=True
through its inference compiler (see compile_fx's
inference_compiler = functools.partial(fw_compiler_base, is_inference=True)).
This PR makes the custom entry match that behavior for eval graphs;
training graphs are unchanged (is_inference=not self.training).

Change

One-line semantic change plus a comment in
deepmd/pt/model/model/sezm_model.py::_inductor_inference_compiler.

Measurements

SeZM model, N=4096 atoms (~646k edges), RTX 5090, torch 2.12.1+cu130,
DP_COMPILE_INFER=1, throughput mode (16 evals, P50):

build per-eval (ms) peak VRAM alloc (MB)
master (5b9fe07) 153.5 23935
this PR 154.0 (+0.5, noise) 22865 (−1070 MB, −4.5%)

Accuracy (same input, master vs this PR, compiled eval): energy rel diff
2.2e-10; max force diff 4.5e-6 with max |f| ~ 3.9 — outputs agree to
rounding level; this is a scheduling-only change.

The gain grows when more of the peak is scheduler-visible intermediates:
on a heavier memory-optimized kernel stack the same flag measures −12.5%
peak VRAM (23647→20696 MB), and −13.9% on an H800.

Tests

  • source/tests/pt/model/test_descriptor_sezm.py on this branch, default
    configuration: 61 passed, 122 subtests passed.
  • ruff check / format clean.

Summary by CodeRabbit

  • Bug Fixes
    • Improved model compilation during evaluation by applying inference-specific handling to evaluation runs. Training compilation behavior remains unchanged, and surrounding compilation options are preserved. This keeps evaluation and training on their respective compilation paths.

The custom inference compiler entry calls compile_fx_inner without the
is_inference flag, so Inductor plans memory under training assumptions:
outputs are allocated early and autograd-visible intermediates stay
alive.  torch.compile's own default path passes is_inference=True through
its inference compiler; this change matches that for the eval graph
(training keeps False).  Scheduling-only change: outputs agree to
rounding level.

Measured at N=4096 (SeZM eval compile, DP_COMPILE_INFER=1):
peak VRAM -12.5% (23647 -> 20696 MB, RTX 5090); independently -13.9% on
an H800 baseline.
Copilot AI balanced review requested due to automatic review settings October 7, 2026 10:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions github-actions Bot added the Python label Oct 7, 2026
@coderabbitai

coderabbitai Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5d6c9417-2d34-488c-80ed-89cad0ce4df0
📥 Commits

Reviewing files that changed from the base of the PR and between 1e3e40c and 31067de.

📒 Files selected for processing: 1
  • deepmd/pt/model/model/sezm_model.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

📝 Walkthrough

The SeZM eval compiler callback now calls compile_fx_inner with is_inference=True. Comments distinguish this eval lowering from the separate training torch.compile path.

Changes: SeZM compilation mode

Layer / File(s) Summary
Set inference compilation flag
deepmd/pt/model/model/sezm_model.py
The eval callback now sets is_inference=True when it calls compile_fx_inner. Comments distinguish this from the training torch.compile path.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~5 minutes

Change: Bug fix

Suggested reviewers: outisli

Merge Risk: ⚪ Minimal · up to 31067

The change selects inference lowering for eval compilation, and the supported GPU PyTorch version accepts the argument. No merge-blocking behavior is established.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 1 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely identifies the main change: passing is_inference to compile_fx_inner for compiled evaluation graphs.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 1
🧪 Generate unit tests (beta)
  • Create a new PR
🛠️ Fix failing CI checks: 💡
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@njzjz-bot njzjz-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the exact one-file diff and its inference/training integration. No new actionable correctness defect found.

The flag is appropriate for this specific graph, rather than being justified by .eval() alone: make_fx has already materialized edge_energy_deriv's energy-to-edge/spin derivatives and force/virial assembly, with create_graph=False. Both aot_module_simplified lowering and compiled eval execution are inside torch.no_grad(). Training uses the separate torch.compile branch with create_graph=True, and the cache distinguishes training/eval. The changed callback therefore does not suppress the first derivatives needed to return forces or alter force-loss double-backward training.

Checked upstream compile_fx_inner and default inference dispatch in PyTorch tags 2.11.0, 2.12.1 and 2.13.0, covering this repository's compile allowlist: all accept is_inference and propagate it to lowering; default inference dispatch supplies True.

Validation remains incomplete. The reported default test_descriptor_sezm.py run does not establish compiled-model coverage. Please run the existing TestSeZMModelCompile eval cache/shape-change and first-frame tests in test_sezm_model.py, plus its force-loss double-backward test, on a supported PyTorch build. The standard CUDA workflow currently pins torch 2.10.0, which skips these compile tests, so a green CUDA badge alone would not establish this coverage.

At 11:00 UTC, the exact-head test/build/CodeQL workflows report action_required and have not provided test results; pre-commit passed and Read the Docs failed. I ran source/AST checks only: PyTorch is not installed in this review environment, and I did not reproduce the GPU parity or memory measurements.

Agent: dot
Reviewed head: 1e3e40c

@long-yi-2019

Copy link
Copy Markdown
Author

Following the review, ran the requested compile coverage on this branch head (1e3e40c), on a supported build with CUDA available (RTX 5090, torch 2.12.1+cu130):

  • source/tests/pt/model/test_sezm_model.py::TestSeZMModelCompile: 9 passed (0:09:35) — including test_eval_compile_first_frame_nloc_matches_trace_edge_count, test_compile_cache_slots_and_eval_shape_change, test_eval_compile_policy, and test_forward_backward_double_backward_matches_compile (the force-loss double backward).

For completeness, also on this branch:

  • source/tests/pt/model/test_descriptor_sezm.py default configuration: 61 passed / 122 subtests.
  • Two-state accuracy at N=4096, compiled eval (master vs this branch, same input): energy rel diff 2.2e-10; max force diff 4.5e-6 with max |f| ~ 3.9.

@codecov

codecov Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 77.61%. Comparing base (5b9fe07) to head (1e3e40c).
⚠️ Report is 3 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #6056      +/-   ##
==========================================
- Coverage   77.74%   77.61%   -0.14%     
==========================================
  Files        1155     1170      +15     
  Lines      139649   140912    +1263     
  Branches     5056     5056              
==========================================
+ Hits       108573   109363     +790     
- Misses      29191    29666     +475     
+ Partials     1885     1883       -2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@long-yi-2019

Copy link
Copy Markdown
Author

@OutisLi @wanghan-iapcm @njzjz requesting a review, please. Following the 2026-10-13 discussion we validated the combined stack of our six performance PRs (#6056, #6057, #6060, #6070, #6071, #6072) with a multi-scale gate: diamond + bcc-Cu at ~500 / ~2000 / ~4400 atoms, three columns (pure torch.compile with all custom kernels off / current master / our changes on). All accuracy cells sit within 2.2x the pure baseline's own run-to-run band (criterion: 3x), and no tested atom count regresses in time or memory — full numbers in the PR descriptions. Suggested review order for the six: #6056 -> #6057 -> #6060 (small and self-contained) -> #6070 -> #6071 -> #6072.

@wanghan-iapcm wanghan-iapcm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified at head 1e3e40c (torch 2.11.0+cpu, CPU only):

  • _inductor_inference_compiler is only reached from the eval branch (aot_module_simplified under torch.no_grad()), so the new kwarg is always is_inference=True; the training graph still goes through torch.compile and is unaffected.
  • With the flag, Inductor's post-grad reorder_for_locality pass now runs on the eval graph (instrumented: it runs on this head and does not run on the parent commit); config.memory_planning stays off, and reorder_for_peak_memory=False from build_inductor_compile_options(inference=True) is still applied.
  • compile_fx_inner accepts is_inference as a keyword in torch 2.11 (checked locally; it defaults to False).
  • Local runs: TestSeZMModelCompile 9 passed; TestSeZMEmbeddingForward::test_compiled_matches_eager and TestSeZMSpinModel::test_compile_matches_eager passed. Compiled eval matches eager for energy, force and virial on the tiny test system.
  • The CPU CI jobs install torch 2.11.0+cpu, so the compile tests in test_sezm_model.py ran in CI and passed. The VRAM reduction was not reproduced here because no GPU was available.

@OutisLi OutisLi left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One non-blocking clarity suggestion for _inductor_inference_compiler in deepmd/pt/model/model/sezm_model.py:2370-2388: please express this callback's inference-only contract directly with is_inference=True.

The callback is defined only in the evaluation branch, and aot_module_simplified is invoked under torch.no_grad(). Training takes the separate torch.compile branch above. Consequently, not self.training adds a dependency on mutable model state where the graph's inference-only role already determines the value. The added sentence about the training graph keeping False also suggests that training passes through this callback, which it does not.

Please keep the hardware-specific memory measurements and before/after validation results in the PR description rather than in the implementation comment. A short explanation that this callback lowers the forward-only AOTAutograd inference graph is sufficient release-grade documentation.

No functional blocker found in this change. Local validation: 61 tests and 122 subtests passed; actual CPU Inductor inference matched eager energy, force, and virial for 3- and 5-atom inputs; the evaluation cache remained usable after a train/eval switch; training backward produced finite gradients for 82 parameters. GPU memory savings were not independently measured.

@long-yi-2019

Copy link
Copy Markdown
Author

Thank you both for the reviews!

@wanghan-iapcm thanks for the verification and approval.

@OutisLi addressed in 31067de: the callback now states its contract directly with is_inference=True, and the implementation comment is reduced to a short description (measurements stay in the PR description only). Both of your points about the misleading training-graph sentence are correct — the callback only exists in the eval branch, so the mutable-state dependency is gone.

Validation on my side (CUDA, torch 2.12.1+cu130): TestSeZMModelCompile passes at the new head. For the record, two tests fail identically on the parent commit in my local environment (test_eval_compile_policy, TestSeZMModelBridging::test_change_out_bias_is_invariant_for_self_labels) — they appear environment-specific (your local run and CI are CPU/torch-2.11) and are untouched by this diff.

This branch has not been deployed

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants