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

CUDA Memory Profile Analyzer #9860

Closed
wants to merge 13 commits into from

Conversation

tonyjie
Copy link

@tonyjie tonyjie commented Jul 24, 2024

What does this PR do ?

  • Collect CUDA memory snapshot based on the previous commit (CUDA memory profile #9096 ), and further analyze which parts of the model contribute to the total memory footprint.
  • The memory profile will generate two pickle file, one for weight, one for activation. The user can load the file in the below page: https://pytorch.org/memory_viz
  • If out-of-memory (CUDA OOM) occurs, the tool will capture the snapshot before OOM occurs, and generate the pickle file.
  • With knobs analysis_enabled: True, the memory profile analyzer will generate two csv files each for weight/activation/OOM. The output csv files includes:
    1. Weight
      • alive_memory_weight.csv
      • group_by_alloc_frames_weight.csv
    2. Activation
      • alive_memory_memory.csv
      • group_by_alloc_frames_memory.csv
    3. OOM
      • alive_memory_oom.csv
      • group_by_alloc_frames_oom.csv

Changelog

  • Fix some issues of previous memory profile
    • batch_idx mismatch issue.
    • max_entries is too small, which makes the generated snapshot easily truncated.
  • Add weight memory capturing.
  • Add OOM case support.
  • Added the option to enable further analysis to the generated memory snapshot file. The analyzer finds the peak memory of the snapshot, and generate two csv files, including
    1. All the alive memory buffers at that peak moment
    2. Group them by allocation frames, showing the relationship between model layer and its corresponding memory footprint.

Usage

  • Add the below knobs to the yaml run config.
# Memory Profile
memory_profile:                                                                      
   enabled: true                                                                      
   start_step: 1                                                                      
   end_step: 3                                                                        
   rank: 0                                                                            
   output_path: <path/to/out_file>
   analysis_enabled: true

GitHub Actions CI

The Jenkins CI system has been replaced by GitHub Actions self-hosted runners.

The GitHub Actions CI will run automatically when the "Run CICD" label is added to the PR.
To re-run CI remove and add the label again.
To run CI on an untrusted fork, a NeMo user with write access must first click "Approve and run".

Before your PR is "Ready for review"

Pre checks:

  • Make sure you read and followed Contributor guidelines
  • Did you write any new necessary tests?
  • Did you add or update any necessary documentation?
  • Does the PR affect components that are optional to install? (Ex: Numba, Pynini, Apex etc)
    • Reviewer: Does the PR have correct import guards for all optional libraries?

PR Type:

  • New Feature
  • Bugfix
  • Documentation

If you haven't finished some of the above items you can still open "Draft" PR.

Who can review?

Anyone in the community is free to review the PR once the checks have passed.
Contributor guidelines contains specific people who can review PRs to various areas.

Additional Information

  • Related to # (issue)

@github-actions github-actions bot added the core Changes to NeMo Core label Jul 24, 2024
@tonyjie tonyjie marked this pull request as draft July 24, 2024 05:38
@tonyjie tonyjie marked this pull request as ready for review July 24, 2024 05:39
Copy link
Collaborator

Choose a reason for hiding this comment

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

this file needs a copyright header

@ericharper ericharper requested review from akoumpa and titu1994 July 31, 2024 21:35
@@ -204,6 +206,8 @@ def __init__(self, cfg: DictConfig, trainer: Trainer = None):

# Setup nsys profiling if it has been enabled in the model config
self._setup_profiling()
# real accurate _batch_idx. We found that the `batch_idx` in `on_train_batch_start` and `on_train_batch_end` has a bug.
Copy link
Member

Choose a reason for hiding this comment

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

Hi, can you expand what bug was found?

@@ -49,6 +49,8 @@
from nemo.utils.debug_hook import register_debug_hooks
from nemo.utils.exceptions import NeMoBaseException
from nemo.utils.get_rank import get_rank, is_global_rank_zero
# from nemo.utils.memory_profile_analyzer import peak_memory_analysis_activation, peak_memory_analysis_weight, peak_memory_analysis_oom
Copy link
Member

Choose a reason for hiding this comment

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

is the commented line needed?

logging.info(f"===== Memory Profile Analysis: OOM ======")
peak_memory_analysis(self._memory_profile_snapshot_file_oom, self._memory_profile_analysis_path, 'oom', self._memory_profile_rank)
else:
raise Exception(f"Snapshot file not found: {self._memory_profile_snapshot_file_oom}")
Copy link
Member

Choose a reason for hiding this comment

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

Maybe move this after line 1833 torch.cuda.memory._dump_snapshot?

return

# Call the analysis function
if self._memory_profile_analysis_enabled:
Copy link
Member

Choose a reason for hiding this comment

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

do you need this if ? I would assume _memory_profile_analysis_enabled does not change value and in line 1880 you already check whether it's true or not.

logging.info(f"====== Memory Profile Analysis: Weight ======")
peak_memory_analysis(self._memory_profile_snapshot_file_weight, self._memory_profile_analysis_path, 'weight', self._memory_profile_rank)
else:
raise Exception(f"Snapshot file not found: {self._memory_profile_snapshot_file_weight}")
Copy link
Member

Choose a reason for hiding this comment

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

if batch_idx >= self._memory_profile_start_step and get_rank() == self._memory_profile_rank:
logging.info("====== Start CUDA memory profiling ======")
torch.cuda.memory._record_memory_history(max_entries=100000)
if self._real_batch_idx == self._memory_profile_start_step and get_rank() == self._memory_profile_rank:
Copy link
Member

Choose a reason for hiding this comment

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

why is it self._real_batch_idx == self._memory_profile_start_step instead of self._real_batch_idx >= self._memory_profile_start_step ?

logging.info("====== End nsys profiling ======")
torch.cuda.cudart().cudaProfilerStop()
self._nsys_profile_complete = True

if hasattr(self, '_memory_profile_enabled'):
if self._memory_profile_enabled and not self._memory_profile_complete:
if batch_idx >= self._memory_profile_end_step and get_rank() == self._memory_profile_rank:
logging.info("====== End CUDA memory profiling ======")
if self._real_batch_idx == self._memory_profile_end_step and get_rank() == self._memory_profile_rank:
Copy link
Member

Choose a reason for hiding this comment

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

)
torch.cuda.memory._record_memory_history(enabled=None)
self._memory_profile_complete = True
# Call the analysis function
if self._memory_profile_analysis_enabled and self._memory_profile_complete:
Copy link
Member

Choose a reason for hiding this comment

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

same as previously, self._memory_profile_analysis_enabled should be true? due to line 1890

Add `\n` in between each frame for the readability.
"""
# Prune Frames
after_prune_frames = [prune_frames(x[3]) for x in alive_memory]
Copy link
Member

@akoumpa akoumpa Aug 1, 2024

Choose a reason for hiding this comment

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

what's x[3]? can you add a comment?



# ===== Function: for two time points, check the corresponding alive memory, and compare them to see: what's new, what's gone, what's unchanged.
def compare_alive_memory(tracker, time_us_1, time_us_2):
Copy link
Member

Choose a reason for hiding this comment

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

can you add a couple tests for this?

return frame
return None

def alloc_memory_timeline(trace):
Copy link
Member

Choose a reason for hiding this comment

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

if that finds the maximum/min alloc memory and the corresponding timestamps, it would be helpful if that was reflected in the name.

for idx, timepoint in enumerate(trace):
(time_us, addr, action, size, frames, stream) = read_tp(timepoint)

if (action == "alloc"):
Copy link
Member

Choose a reason for hiding this comment

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

you don't need brackets.




def record_alloc_memory_timeline(trace):
Copy link
Member

Choose a reason for hiding this comment

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

this looks very similar to alloc_memory_timeline can you refactor to reduce duplicate code?

Copy link
Member

@akoumpa akoumpa left a comment

Choose a reason for hiding this comment

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

Thanks, just a few minor comments, this looks great overall.

@akoumpa
Copy link
Member

akoumpa commented Aug 1, 2024

One more request @tonyjie , can you rebase to the latest main & use --signoff to your commits and push again ? Otherwise CI won't play.

nemo/utils/memory_profile_analyzer.py Fixed Show fixed Hide fixed
nemo/utils/memory_profile_analyzer.py Fixed Show fixed Hide fixed
nemo/utils/memory_profile_analyzer.py Fixed Show fixed Hide fixed
nemo/utils/memory_profile_analyzer.py Fixed Show fixed Hide fixed
@tonyjie tonyjie force-pushed the jiajiel/mem_snapshot_pr1 branch 5 times, most recently from dc21178 to 8e81820 Compare September 8, 2024 22:27
@tonyjie tonyjie force-pushed the jiajiel/mem_snapshot_pr1 branch 2 times, most recently from 8e81820 to f11590e Compare September 8, 2024 23:15
tonyjie and others added 12 commits September 8, 2024 16:15
…l analysis the memory at the global peak of the trace, and generate CSV files

Signed-off-by: tonyjie <jl4257@cornell.edu>
…activation.

Signed-off-by: tonyjie <jl4257@cornell.edu>
Signed-off-by: tonyjie <jl4257@cornell.edu>
Signed-off-by: tonyjie <jl4257@cornell.edu>
…ing the setup

Signed-off-by: tonyjie <jl4257@cornell.edu>
Signed-off-by: tonyjie <jl4257@cornell.edu>
Signed-off-by: tonyjie <jl4257@cornell.edu>
Signed-off-by: tonyjie <jl4257@cornell.edu>
Signed-off-by: tonyjie <jl4257@cornell.edu>
Signed-off-by: tonyjie <jl4257@cornell.edu>
Signed-off-by: tonyjie <jl4257@cornell.edu>
Signed-off-by: tonyjie <jl4257@cornell.edu>
@tonyjie tonyjie force-pushed the jiajiel/mem_snapshot_pr1 branch from f11590e to 2cb2497 Compare September 8, 2024 23:16
…ch_version; fix other minor issues based on review
@github-actions github-actions bot removed the stale label Sep 9, 2024
@akoumpa akoumpa added Run CICD and removed Run CICD labels Sep 9, 2024
Copy link
Contributor

This PR is stale because it has been open for 14 days with no activity. Remove stale label or comment or update or this will be closed in 7 days.

@github-actions github-actions bot added the stale label Sep 24, 2024
Copy link
Contributor

github-actions bot commented Oct 1, 2024

This PR was closed because it has been inactive for 7 days since being marked as stale.

@github-actions github-actions bot closed this Oct 1, 2024
@pzelasko
Copy link
Collaborator

This PR seems to have slipped through. Should we merge it? @ericharper @titu1994

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