Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(pt): detach computed descriptor tensor to prevent OOM #4547

Draft
wants to merge 1 commit into
base: devel
Choose a base branch
from

Conversation

njzjz
Copy link
Member

@njzjz njzjz commented Jan 11, 2025

Fix #4544.

Summary by CodeRabbit

  • Optimization
    • Improved descriptor handling in the atomic model to enhance computational efficiency and memory management during backpropagation.

@Copilot Copilot bot review requested due to automatic review settings January 11, 2025 03:49

Choose a reason for hiding this comment

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

Copilot reviewed 1 out of 1 changed files in this pull request and generated no comments.

@njzjz njzjz linked an issue Jan 11, 2025 that may be closed by this pull request
Copy link
Contributor

coderabbitai bot commented Jan 11, 2025

📝 Walkthrough

Walkthrough

The pull request modifies the forward_atomic method in the DPAtomicModel class within the dp_atomic_model.py file. The primary change involves how descriptors are handled during evaluation, specifically by using .detach() when appending descriptors to the eval_descriptor_list. This modification aims to prevent gradient tracking during backpropagation, which could potentially help address memory-related issues during descriptor evaluation.

Changes

File Change Summary
deepmd/pt/model/atomic_model/dp_atomic_model.py Modified descriptor handling in forward_atomic method by using .detach() when appending to eval_descriptor_list

Assessment against linked issues

Objective Addressed Explanation
Resolve OOM in DeepPot.eval_descriptor [#4544] Modification might help reduce memory usage, but requires further testing to confirm complete resolution

Suggested labels

Python

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
deepmd/pt/model/atomic_model/dp_atomic_model.py (1)

247-247: LGTM! Effective solution for preventing OOM during descriptor evaluation.

The addition of .detach() is the correct approach here as it:

  1. Prevents unnecessary gradient tracking in the evaluation cache
  2. Maintains the original tensor's gradients for the fitting network
  3. Reduces memory usage by not retaining the computational graph for cached descriptors

This is a memory-efficient solution since:

  • The evaluation hook only needs the tensor values, not the gradients
  • The original descriptor tensor still maintains its gradients for the fitting network
  • The detached tensor shares the same memory as the original tensor but without the gradient overhead
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 65ca05a and 9f37532.

📒 Files selected for processing (1)
  • deepmd/pt/model/atomic_model/dp_atomic_model.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (21)
  • GitHub Check: Build wheels for cp310-manylinux_aarch64
  • GitHub Check: Build wheels for cp311-macosx_x86_64
  • GitHub Check: Test Python (5, 3.12)
  • GitHub Check: Test Python (4, 3.12)
  • GitHub Check: Test Python (4, 3.9)
  • GitHub Check: Test Python (3, 3.12)
  • GitHub Check: Test Python (3, 3.9)
  • GitHub Check: Build C++ (clang, clang)
  • GitHub Check: Test Python (2, 3.12)
  • GitHub Check: Build C++ (rocm, rocm)
  • GitHub Check: Test Python (2, 3.9)
  • GitHub Check: Analyze (python)
  • GitHub Check: Build C++ (cuda120, cuda)
  • GitHub Check: Test Python (1, 3.12)
  • GitHub Check: Test Python (1, 3.9)
  • GitHub Check: Build C++ (cuda, cuda)
  • GitHub Check: Build C library (2.14, >=2.5.0rc0,<2.15, libdeepmd_c_cu11.tar.gz)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (c-cpp)
  • GitHub Check: Build C++ (cpu, cpu)
  • GitHub Check: Build C library (2.18, libdeepmd_c.tar.gz)

Copy link

codecov bot commented Jan 11, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 84.57%. Comparing base (65ca05a) to head (9f37532).

Additional details and impacted files
@@            Coverage Diff             @@
##            devel    #4547      +/-   ##
==========================================
- Coverage   84.57%   84.57%   -0.01%     
==========================================
  Files         677      677              
  Lines       63916    63915       -1     
  Branches     3486     3488       +2     
==========================================
- Hits        54060    54059       -1     
+ Misses       8730     8729       -1     
- Partials     1126     1127       +1     

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

@QuantumMisaka
Copy link

@njzjz Thanks for your rapid reply!
I've check the test example in my issue #4544 after add your fix to deepmd-kit-3.0.0rc0 code and pip install ., but the OOM problem still exist in my test case.

@njzjz njzjz marked this pull request as draft January 11, 2025 05:54
@njzjz
Copy link
Member Author

njzjz commented Jan 11, 2025

@njzjz Thanks for your rapid reply! I've check the test example in my issue #4544 after add your fix to deepmd-kit-3.0.0rc0 code and pip install ., but the OOM problem still exist in my test case.

Thanks for testing it.

@QuantumMisaka
Copy link

@njzjz However, this change will fix another thing. While using the scripts below to generate descriptors in one python scripts:

import dpdata
from deepmd.infer.deep_pot import DeepPot
#from deepmd.calculator import DP
import numpy as np
import os
from multiprocessing import pool
import gc
import glob
import logging
import torch
import warnings

datadir = "./sampled-data-direct-10p-npy"
modelpath = "./model.ckpt.pt"
savedir = "descriptors"

omp = 16
proc = 4
os.environ['OMP_NUM_THREADS'] = f'{omp}'

def descriptor_from_model(sys: dpdata.LabeledSystem, model:DeepPot):
    coords = sys.data["coords"]
    cells = sys.data["cells"]
    model_type_map = model.get_type_map()
    type_trans = np.array([model_type_map.index(i) for i in sys.data['atom_names']])
    atypes = list(type_trans[sys.data['atom_types']])
    predict = model.eval_descriptor(coords, cells, atypes)
    return predict
#alldata = dpdata.MultiSystems.from_dir(datadir,datakey,fmt="deepmd/npy")
all_set_directories = glob.glob(os.path.join(
    datadir, '**', 'set.*'), recursive=True)
all_directories = set()
for directory in all_set_directories:
    coord_path = os.path.join(directory, 'coord.npy')
    if os.path.exists(coord_path):
        all_directories.add(os.path.dirname(directory))
all_directories = list(all_directories)
all_directories.sort()

# 配置日志格式,包含时间戳、日志级别和日志信息
logging.basicConfig(
    level=logging.INFO,  # 设置日志级别为 INFO
    format='%(asctime)s - %(levelname)s - %(message)s',  # 定义日志格式
    datefmt='%Y-%m-%d %H:%M:%S'  # 定义时间戳格式
)


logging.info("Start Generating Descriptors")

if not os.path.exists(savedir):
    os.mkdir(savedir)

with open("running", "w") as fo:
    for onedir in all_directories:
        onedata = dpdata.LabeledSystem(onedir, fmt="deepmd/npy")
        key = onedata.short_name
        save_key = f"{savedir}/{key}"
        logging.info(f"Generating descriptors for {key}")
        if os.path.exists(save_key):
            if os.path.exists(f"{save_key}/desc.npy"):
                logging.info(f"Descriptors for {key} already exist, skip")
                continue
        model = DeepPot(modelpath, head="Target_FTS")
        try:
            desc = descriptor_from_model(onedata, model)
        except torch.cuda.OutOfMemoryError:
            warnings.warn(f"CUDA OOM, Skipping {key}")
            continue
        except Exception as e:
            raise e
            
        logging.info(f"Descriptors for {key} generated")
        os.mkdir(save_key)
        np.save(f"{savedir}/{key}/desc.npy", desc)
        logging.info(f"Descriptors for {key} saved")
        del onedata, model, desc
        torch.cuda.empty_cache()

logging.info("All Done !!!")
os.system("mv running done")

Before this adjustment, the CUDA memory cannot be cleaned after each LabeledSystem evaluated, which is fixed after the adjustment of this PR.

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.

[BUG] OOM in DeepPot.eval_descriptor while dp test works
2 participants