Skip to content

fix(infer): reduce CUDA OOM retries during evaluation - #6024

Merged
njzjz merged 2 commits into
deepmodeling:masterfrom
OutisLi:pr/oom
Sep 17, 2026
Merged

njzjz merged 2 commits into
deepmodeling:masterfrom
OutisLi:pr/oom

Conversation

@OutisLi

@OutisLi OutisLi commented Sep 14, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Automatic GPU batching currently grows until an allocation fails. Evaluation can recover, but the CUDA allocator may emit OOM warnings and retry allocations while searching for a usable batch size.

This PR reduces those avoidable retries in dp test and full validation:

  • Keep batch selection, execution, observation, and OOM backoff in the shared AutoBatchSize runner. Back off from the actual attempted batch, including the remaining input length, so the same oversized tail is not retried repeatedly.
  • Add an atom-based workspace estimate for automatic multi-frame evaluation with the native PyTorch CUDA allocator. Start with one calibration frame and limit growth using available memory with a 10% margin. PT and PT-expt share this implementation; no model-specific or neighbor-count profiling is added.
  • Account for reusable default-pool cache, unreleasable split cache, and existing CUDA Graph private pools without resetting global peak counters or changing allocator memory limits.
  • Release unused full-validation workspace after restoring model mode and exiting the EMA context, before training resumes or checkpoint assembly allocates memory.

The memory estimate is a heuristic. Unexpected workload or device-memory changes retain the existing OOM fallback. Explicit DP_INFER_BATCH_SIZE, CPU, single-frame calls, and non-native CUDA allocators do not opt into memory-based sizing. The existing multiplicative growth/backoff factor is unchanged.

Validation

  • Shared/PT batching, retry-signal, and validation tests: 56 passed, plus 15 subtests.
  • GPU PT/PT-expt dp test and full-validation tests: 33 passed, plus 9 subtests.
  • Controlled CUDA allocation workload with expandable_segments=True and a 512 MiB process limit: OOM-driven sizing incurred 3 OOMs and 3 allocator retries; memory-based sizing incurred none. Live private-pool and static-buffer CUDA Graph cases also completed without OOM/retries and replayed correctly.
  • AdamW step -> full validation -> AdamW step under the same controlled limit: releasing validation cache reduced resumed-training allocator retries from 1 to 0, with unchanged live memory and valid graph replay. This is a controlled workspace test, not a production training benchmark.
  • Existing water model fixture, energy/force/virial evaluation: matching outputs; steady-state median 169.85 ms versus 170.14 ms over 15 measurements, with no steady-state cache releases in either case.
  • Independent code review and focused regression coverage include active private pools, stale allocation peaks, unreleasable cache, workload changes, and normal/error-path validation cleanup.

Summary by CodeRabbit

  • New Features

    • GPU batch sizes now adapt to available memory and observed workspace usage with a safety margin.
    • Batch processing respects remaining frame limits during multi-frame operations.
  • Bug Fixes

    • Improved out-of-memory recovery with more accurate retry sizing.
    • Single-frame out-of-memory errors are now reported instead of suppressed.
    • Validation releases unused GPU memory before training resumes.
  • Documentation

    • Updated GPU batch-size behavior and configuration guidance.

@OutisLi OutisLi added the Test CUDA Trigger test CUDA workflow label Sep 14, 2026
@OutisLi
OutisLi requested review from njzjz and a lite review from Copilot September 14, 2026 09:04

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 Python Docs and removed Test CUDA Trigger test CUDA workflow labels Sep 14, 2026
Comment thread deepmd/utils/batch_size.py Fixed
Comment thread deepmd/utils/batch_size.py Fixed
@coderabbitai

coderabbitai Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview 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: 1f01b123-36df-4e32-9f4f-21b151e05383

📥 Commits

Reviewing files that changed from the base of the PR and between cc5c880 and c176105.

📒 Files selected for processing (5)
  • deepmd/utils/batch_size.py
  • source/tests/pt/model/test_atomic_model_atomic_stat.py
  • source/tests/pt/model/test_atomic_model_global_stat.py
  • source/tests/pt/model/test_polar_atomic_model_stat.py
  • source/tests/pt/test_auto_batch_size.py

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


📝 Walkthrough

Walkthrough

The change adds budget-aware batch execution with native CUDA memory calibration, cache release after validation, updated environment documentation, regression coverage, and frame-parameterized atomic statistic test fixtures.

Changes

CUDA batch sizing

Layer / File(s) Summary
Batch budget execution
deepmd/utils/batch_size.py, source/tests/common/test_auto_batch_size.py
AutoBatchSize now supports backend budgets, frame limits, budget observation, and batch-size retries. Regression tests cover retry sizes and fatal single-frame out-of-memory errors.
CUDA memory budget
deepmd/pt/utils/auto_batch_size.py, source/tests/pt/test_auto_batch_size.py, doc/env.md
Native CUDA execution estimates workspace use, accounts for allocator cache and memory fractions, and limits batch capacity. Tests cover calibration, cache handling, allocator behavior, and error propagation.
Validation workspace release
deepmd/pt_expt/train/validation.py, source/tests/pt/test_validation.py
Full validation clears the CUDA cache after restoring training mode. Tests cover successful and failing validation paths.

Frame-aware statistic tests

Layer / File(s) Summary
Frame-parameterized atomic statistics
source/tests/pt/model/test_atomic_model_*stat.py
Atomic statistic test fixtures now provide fparam values and select output frames with those values before validating statistic results.

Priority: ➖ Normal

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant AutoBatchSize
  participant _CudaMemoryBudget
  participant CUDAAllocator
  participant EvaluationCallable
  AutoBatchSize->>_CudaMemoryBudget: request batch limit
  _CudaMemoryBudget->>CUDAAllocator: read memory statistics
  CUDAAllocator-->>_CudaMemoryBudget: return memory statistics
  _CudaMemoryBudget-->>AutoBatchSize: return admissible batch size
  AutoBatchSize->>EvaluationCallable: execute batch
  EvaluationCallable-->>AutoBatchSize: return result or OOM
  AutoBatchSize->>_CudaMemoryBudget: observe completed attempt
Loading

Merge Risk: ⚪ Minimal · up to c1761

No actionable current-head risk remains from the reviewed changes.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.16% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 74 functions across 9 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ 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 summarizes the main change: reducing avoidable CUDA OOM retries during inference evaluation. It matches the batching, memory-budgeting, and validation changes.
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
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

Requesting changes for the cold-start path. The allocator accounting/backoff logic looks well covered, and I did not find a correctness regression in the tail backoff, private-pool handling, or PyTorch 2.1 compatibility. The remaining issue is that the one-frame calibration replaces the original 1024-atom proposal, so a fresh dp test / full-validation evaluation grows geometrically from 1 frame. The PR reports a steady-state benchmark, which does not exercise this cost. Please preserve/jump back toward the pre-calibration proposal after the first observation, or demonstrate with a cold-start benchmark that the extra forward/snapshot calls are negligible and add regression coverage for that path.

CI is still running, so this review is code-level only.

Agent: ChatGPT
Model: GPT-5.6 Sol

Comment thread deepmd/pt/utils/auto_batch_size.py
@codecov

codecov Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.21429% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 77.01%. Comparing base (0192667) to head (c176105).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
deepmd/pt/utils/auto_batch_size.py 98.59% 1 Missing ⚠️
deepmd/utils/batch_size.py 97.43% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #6024      +/-   ##
==========================================
- Coverage   77.23%   77.01%   -0.23%     
==========================================
  Files        1153     1153              
  Lines      139166   139258      +92     
  Branches     5062     5062              
==========================================
- Hits       107481   107243     -238     
- Misses      29802    30133     +331     
+ Partials     1883     1882       -1     

☔ 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.

@OutisLi

OutisLi commented Sep 15, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed the review and CUDA CI failures in c176105.

  • Preserved the pre-calibration atom-budget proposal, with a cold-start regression and fresh-process latency/memory measurements in the review reply.
  • Removed the two redundant ellipsis statements reported by CodeQL; the documented Protocol signatures are unchanged.
  • Reproduced all five CUDA Python failures locally. They came from statistics-test fitting doubles that always returned two frames, then reshaped those results using the incoming batch size. Single-frame calibration exposed that assumption. The doubles now select each sample's fixed predictions through an explicit frame parameter, so full and split batches are equivalent. All original bias/standard-deviation expectations remain unchanged; production statistics code is untouched.

Local validation: 64 related CPU tests and 69 related GPU tests passed. The three statistics suites also passed all 7 tests with CPU inference forced to one frame per batch. Normal pre-commit hooks passed. CUDA CI is being retriggered for the new commit.

@OutisLi OutisLi added the Test CUDA Trigger test CUDA workflow label Sep 15, 2026
@github-actions github-actions Bot removed the Test CUDA Trigger test CUDA workflow label Sep 15, 2026

@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.

NEEDS HUMAN REVIEW

Re-reviewed the changed head after the previous cold-start concern was addressed. The fix now preserves the pre-calibration atom proposal: the first CUDA calibration call is still one frame, then the runner applies the measured capacity to the original proposal instead of growing geometrically from one frame. The new regression explicitly exercises that path ([1, 7] for an 8-frame input), and the author also provided fresh-process cold-start measurements. I reviewed all 10 changed files, including the shared batch runner, CUDA memory budget/accounting, validation cache release, documentation, and the frame-aware regression fixtures; I did not find a new high-confidence functional or compatibility blocker in the current diff.

I am not approving this head yet because relevant exact-head CI is still incomplete: Test Python, CodeQL, Test C++, one Test CUDA run, Build/upload to PyPI, and Read the Docs are still running/pending. The completed Build C++, Build C library, another Test CUDA run, pre-commit.ci, and CodeRabbit checks are successful. Please treat this as code-level review pending the remaining CI.

Agent: ChatGPT
Model: GPT-5.6 Sol
GitHub account: njzjz-bot
Reviewed head: c176105
Trigger: scheduled review-request monitoring

@OutisLi
OutisLi requested a review from njzjz-bot September 15, 2026 03:53

@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.

NEEDS HUMAN REVIEW

Re-reviewing this explicitly re-requested head. I re-checked the complete 10-file change, repository guidance, existing review threads/comments, and current-head CI. The previously identified cold-start calibration issue remains fixed: after the one-frame calibration, growth is constrained by the original proposal and the measured capacity, with focused regression coverage. I did not find a new high-confidence functional, compatibility, resource-management, or test-coverage blocker in the retrievable change.

I am not approving yet because relevant CI for this exact head is still incomplete. Build C++, Build C library, Build/upload to PyPI, CodeQL, and one Test CUDA run have completed successfully, while Test Python, Test C++, and another Test CUDA run are still in progress.

Agent: ChatGPT
Model: GPT-5.6 Sol
GitHub account: njzjz-bot
Reviewed head: c176105
Trigger: scheduled review-request monitoring

@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.

NEEDS HUMAN REVIEW

Re-checked this exact head because the CI context materially changed after the previous pending-CI review. The code-level conclusion is unchanged: the cold-start calibration fix is present, the 10-file diff remains coherent, and I do not see a new high-confidence functional or compatibility blocker in the reviewed changes.

The required CI is now red, however. On exact head c176105445718ba73580557a7ca6f37eab48f066, Test Python, Test C++, Build C++, Build C library, Build/upload to PyPI, CodeQL, one Test CUDA run, pre-commit.ci, CodeRabbit, and docs are successful, but Test CUDA run 34924511513 failed specifically in Test Python on CUDA (job 104239589664); Test C++ on CUDA in the same run passed. I cannot approve while that required CUDA job is failing. The current integration exposes the failed job/step but not the pytest failure log, so the actionable next step is to inspect/re-run that CUDA Python job and determine whether this is a reproducible regression or an infrastructure/flaky failure before approval.

Agent: ChatGPT
Model: GPT-5.6 Sol
GitHub account: njzjz-bot
Reviewed head: c176105
Trigger: scheduled all-PR monitoring

@njzjz
njzjz added this pull request to the merge queue Sep 17, 2026

@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.

Re-reviewed this exact head because the CI context materially changed after the previous pending/failed-CUDA review. I re-checked the complete 10-file diff, repository guidance, the existing inline thread and its fix, and the current exact-head workflow results. The cold-start calibration concern remains correctly addressed: the one-frame calibration preserves the original proposal and then jumps to the measured admissible batch, with regression coverage for the [1, 7] path. I did not find a remaining high-confidence functional, compatibility, resource-management, or test-coverage blocker.

The previously failing CUDA workflow has now been rerun successfully. Test Python, both Test CUDA runs, Test C++, Build C++, Build C library, CodeQL, and Build/upload to PyPI are all complete and green for this head, so I am approving.

Agent: ChatGPT
Model: GPT-5.6 Sol
GitHub account: njzjz-bot
Reviewed head: c176105
Trigger: scheduled all-PR monitoring

Merged via the queue into deepmodeling:master with commit e8725d0 Sep 17, 2026
63 of 65 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants