Skip to content

fix: clear_cache_every_n_steps variable name - #1109

Merged
terrykong merged 2 commits into
mainfrom
bxyu/fix-clear-cache-name
Sep 10, 2025
Merged

fix: clear_cache_every_n_steps variable name#1109
terrykong merged 2 commits into
mainfrom
bxyu/fix-clear-cache-name

Conversation

@bxyu-nvidia

@bxyu-nvidia bxyu-nvidia commented Sep 10, 2025

Copy link
Copy Markdown
Contributor

What does this PR do ?

There is a mismatch between the variable name to clear_cache_every_n_steps and what is actually used in the code which is empty_cache_every_n_steps. I noticed this when some jobs that weren't oom'ing last week started oom'ing this week and it's because we stopped clearing the cache here.

Issues

List issues that this PR closes (syntax):

Usage

  • You can potentially add a usage example below
# Add a code snippet demonstrating how to use this

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 run the unit tests and functional tests locally? Visit our Testing Guide for how to run tests
  • Did you add or update any necessary documentation? Visit our Document Development Guide for how to write, build and test the docs.

Additional Information

  • ...

Summary by CodeRabbit

  • Refactor
    • Renamed the configuration key that controls periodic GPU cache clearing from empty_cache_every_n_steps to clear_cache_every_n_steps across DTensor policy workers.
    • Behavior remains the same; only the key name changed.
    • The previous key is no longer recognized—update your configuration to maintain cache-clearing behavior.

@coderabbitai

coderabbitai Bot commented Sep 10, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Updated both dtensor policy worker training loops to use dtensor_cfg.clear_cache_every_n_steps instead of dtensor_cfg.empty_cache_every_n_steps for periodic CUDA cache clearing. Logic for warnings and torch.cuda.empty_cache() calls remains unchanged.

Changes

Cohort / File(s) Summary
Config key rename for cache clearing
nemo_rl/models/policy/dtensor_policy_worker.py, nemo_rl/models/policy/dtensor_policy_worker_v2.py
Read config key renamed from clear interval at dtensor_cfg.empty_cache_every_n_steps to dtensor_cfg.clear_cache_every_n_steps; existing periodic torch.cuda.empty_cache() and warning logic retained.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Trainer
  participant Config as dtensor_cfg
  participant CUDA as torch.cuda

  Trainer->>Config: Read clear_cache_every_n_steps
  alt clear_cache_every_n_steps is set
    note right of Trainer: Warning logged about periodic cache clearing
    loop Every N steps
      Trainer->>CUDA: empty_cache()
      CUDA-->>Trainer: cache cleared
    end
  else not set / zero
    note right of Trainer: No periodic cache clearing
  end
Loading

Estimated code review effort

ðŸŽŊ 2 (Simple) | ⏱ïļ ~10 minutes

Poem

I twitch my ears at keys that change,
From empty to clear—still same range.
Each N steps, I sweep the heap,
CUDA dreams, a tidy sleep.
Hop, hop—configs crisp and neat,
Cache crumbs gone beneath my feet. 🐇âœĻ

Tip

ðŸ‘Ū Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.

âœĻ Finishing Touches
  • 📝 Generate Docstrings
🧊 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch bxyu/fix-clear-cache-name

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

@github-actions

Copy link
Copy Markdown

â„đïļ File Consistency Check

Check based on commit: 675b39e (PR #1109 from bxyu/fix-clear-cache-name)

✅ DTensor Policy Worker Synchronization Check

Both DTensor policy worker files were modified in this PR:

  • nemo_rl/models/policy/dtensor_policy_worker.py
  • nemo_rl/models/policy/dtensor_policy_worker_v2.py

Please ensure that the changes are consistent between both files where applicable.


This check ensures that related file implementations remain synchronized across the codebase. If you believe this warning is incorrect or the files should intentionally differ, please add a comment explaining the reasoning.

@bxyu-nvidia
bxyu-nvidia force-pushed the bxyu/fix-clear-cache-name branch from 675b39e to ecaf55f Compare September 10, 2025 02:50
@github-actions

Copy link
Copy Markdown

â„đïļ File Consistency Check

Check based on commit: ecaf55f (PR #1109 from bxyu/fix-clear-cache-name)

✅ DTensor Policy Worker Synchronization Check

Both DTensor policy worker files were modified in this PR:

  • nemo_rl/models/policy/dtensor_policy_worker.py
  • nemo_rl/models/policy/dtensor_policy_worker_v2.py

Please ensure that the changes are consistent between both files where applicable.


This check ensures that related file implementations remain synchronized across the codebase. If you believe this warning is incorrect or the files should intentionally differ, please add a comment explaining the reasoning.

@bxyu-nvidia bxyu-nvidia changed the title Fix clear_cache_every_n_steps variable name fix: clear_cache_every_n_steps variable name Sep 10, 2025
Signed-off-by: Brian Yu <bxyu@nvidia.com>
Signed-off-by: Brian Yu <bxyu@nvidia.com>
@github-actions

Copy link
Copy Markdown

â„đïļ File Consistency Check

Check based on commit: 59bfb55 (PR #1109 from bxyu/fix-clear-cache-name)

✅ DTensor Policy Worker Synchronization Check

Both DTensor policy worker files were modified in this PR:

  • nemo_rl/models/policy/dtensor_policy_worker.py
  • nemo_rl/models/policy/dtensor_policy_worker_v2.py

Please ensure that the changes are consistent between both files where applicable.


This check ensures that related file implementations remain synchronized across the codebase. If you believe this warning is incorrect or the files should intentionally differ, please add a comment explaining the reasoning.

@bxyu-nvidia
bxyu-nvidia force-pushed the bxyu/fix-clear-cache-name branch from 59bfb55 to 7662ab0 Compare September 10, 2025 02:53
@github-actions

Copy link
Copy Markdown

â„đïļ File Consistency Check

Check based on commit: 7662ab0 (PR #1109 from bxyu/fix-clear-cache-name)

✅ DTensor Policy Worker Synchronization Check

Both DTensor policy worker files were modified in this PR:

  • nemo_rl/models/policy/dtensor_policy_worker.py
  • nemo_rl/models/policy/dtensor_policy_worker_v2.py

Please ensure that the changes are consistent between both files where applicable.


This check ensures that related file implementations remain synchronized across the codebase. If you believe this warning is incorrect or the files should intentionally differ, please add a comment explaining the reasoning.

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠ïļ Outside diff range comments (2)
nemo_rl/models/policy/dtensor_policy_worker_v2.py (1)

577-585: Make the key change backward-compatible and validate input.

Switching to "clear_cache_every_n_steps" will silently disable cache clearing for any jobs still using the old "empty_cache_every_n_steps" key, risking more OOMs. Read the new key first, then fall back to the old key with a deprecation warning, and validate the value (int > 0).

Apply:

-                empty_cache_steps = self.cfg.get("dtensor_cfg", {}).get(
-                    "clear_cache_every_n_steps"
-                )
-                if empty_cache_steps:
-                    warnings.warn(
-                        f"Emptying cache every {empty_cache_steps} microbatches, doing so unnnecessarily would incur a large performance overhead."
-                    )
+                cfg_dt = self.cfg.get("dtensor_cfg", {})
+                empty_cache_steps = cfg_dt.get("clear_cache_every_n_steps")
+                if empty_cache_steps is None:
+                    empty_cache_steps = cfg_dt.get("empty_cache_every_n_steps")
+                    if empty_cache_steps is not None:
+                        warnings.warn(
+                            "dtensor_cfg.empty_cache_every_n_steps is deprecated; use dtensor_cfg.clear_cache_every_n_steps",
+                            DeprecationWarning,
+                        )
+                # normalize and validate
+                if empty_cache_steps is not None:
+                    try:
+                        empty_cache_steps = int(empty_cache_steps)
+                    except (TypeError, ValueError):
+                        warnings.warn(
+                            "dtensor_cfg.clear_cache_every_n_steps must be an int; disabling CUDA cache clearing.",
+                            RuntimeWarning,
+                        )
+                        empty_cache_steps = None
+                    if empty_cache_steps is not None and empty_cache_steps <= 0:
+                        empty_cache_steps = None
+                if empty_cache_steps and not getattr(self, "_warned_cache_clear_overhead", False):
+                    warnings.warn(
+                        f"Emptying cache every {empty_cache_steps} microbatches; unnecessary use can incur large performance overhead."
+                    )
+                    self._warned_cache_clear_overhead = True
nemo_rl/models/policy/dtensor_policy_worker.py (1)

633-640: Preserve compatibility with existing configs and validate the value.

Mirroring v2: support both config keys (new preferred: clear_cache_every_n_steps; old deprecated: empty_cache_every_n_steps) to prevent regressions and OOMs if older configs are still in circulation. Add basic type/positivity checks and warn once per process.

-                empty_cache_steps = self.cfg.get("dtensor_cfg", {}).get(
-                    "clear_cache_every_n_steps"
-                )
-                if empty_cache_steps:
-                    warnings.warn(
-                        f"Emptying cache every {empty_cache_steps} microbatches, doing so unnnecessarily would incur a large performance overhead."
-                    )
+                cfg_dt = self.cfg.get("dtensor_cfg", {})
+                empty_cache_steps = cfg_dt.get("clear_cache_every_n_steps")
+                if empty_cache_steps is None:
+                    empty_cache_steps = cfg_dt.get("empty_cache_every_n_steps")
+                    if empty_cache_steps is not None:
+                        warnings.warn(
+                            "dtensor_cfg.empty_cache_every_n_steps is deprecated; use dtensor_cfg.clear_cache_every_n_steps",
+                            DeprecationWarning,
+                        )
+                if empty_cache_steps is not None:
+                    try:
+                        empty_cache_steps = int(empty_cache_steps)
+                    except (TypeError, ValueError):
+                        warnings.warn(
+                            "dtensor_cfg.clear_cache_every_n_steps must be an int; disabling CUDA cache clearing.",
+                            RuntimeWarning,
+                        )
+                        empty_cache_steps = None
+                    if empty_cache_steps is not None and empty_cache_steps <= 0:
+                        empty_cache_steps = None
+                if empty_cache_steps and not getattr(self, "_warned_cache_clear_overhead", False):
+                    warnings.warn(
+                        f"Emptying cache every {empty_cache_steps} microbatches; unnecessary use can incur large performance overhead."
+                    )
+                    self._warned_cache_clear_overhead = True
ðŸ§đ Nitpick comments (4)
nemo_rl/models/policy/dtensor_policy_worker_v2.py (2)

589-591: Avoid clearing at mb_idx 0; clear after each N microbatches.

Current modulo clears on the first microbatch. Shift to (mb_idx + 1) % N == 0 so the first clear happens after N microbatches.

-                    if empty_cache_steps and mb_idx % empty_cache_steps == 0:
+                    if empty_cache_steps and (mb_idx + 1) % empty_cache_steps == 0:
                         torch.cuda.empty_cache()

581-584: Fix minor typos and improve wording.

  • "unnnecessarily" → "unnecessarily"
  • "Conditioanlly" → "Conditionally"
  • Slightly tighten the warning text.
-                    warnings.warn(
-                        f"Emptying cache every {empty_cache_steps} microbatches, doing so unnnecessarily would incur a large performance overhead."
-                    )
+                    warnings.warn(
+                        f"Emptying cache every {empty_cache_steps} microbatches; unnecessary use can incur large performance overhead."
+                    )
@@
-                    # Conditioanlly empty cache when sensitive to fragmentation
+                    # Conditionally empty cache when sensitive to fragmentation

Also applies to: 588-590

nemo_rl/models/policy/dtensor_policy_worker.py (2)

645-647: Shift clearing to occur after N microbatches, not at the first.

-                    if empty_cache_steps and mb_idx % empty_cache_steps == 0:
+                    if empty_cache_steps and (mb_idx + 1) % empty_cache_steps == 0:
                         torch.cuda.empty_cache()

637-639: Typos in user-facing text and comment.

  • "unnnecessarily" → "unnecessarily"
  • "Conditioanlly" → "Conditionally"
-                    warnings.warn(
-                        f"Emptying cache every {empty_cache_steps} microbatches, doing so unnnecessarily would incur a large performance overhead."
-                    )
+                    warnings.warn(
+                        f"Emptying cache every {empty_cache_steps} microbatches; unnecessary use can incur large performance overhead."
+                    )
@@
-                    # Conditioanlly empty cache when sensitive to fragmentation
+                    # Conditionally empty cache when sensitive to fragmentation

Also applies to: 644-645

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

ðŸ“Ĩ Commits

Reviewing files that changed from the base of the PR and between b060d1d and 7662ab0.

📒 Files selected for processing (2)
  • nemo_rl/models/policy/dtensor_policy_worker.py (1 hunks)
  • nemo_rl/models/policy/dtensor_policy_worker_v2.py (1 hunks)
🔇 Additional comments (1)
nemo_rl/models/policy/dtensor_policy_worker.py (1)

633-636: Consistent use of clear_cache_every_n_steps across code, schemas, and configs. No occurrences of empty_cache_every_n_steps were found in the schema (nemo_rl/models/policy/__init__.py), policy workers (dtensor_policy_worker.py & _v2.py), example YAMLs, or docs.

@terrykong
terrykong added this pull request to the merge queue Sep 10, 2025
github-merge-queue Bot pushed a commit that referenced this pull request Sep 10, 2025
Signed-off-by: Brian Yu <bxyu@nvidia.com>
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Sep 10, 2025
@terrykong
terrykong added this pull request to the merge queue Sep 10, 2025
@terrykong

Copy link
Copy Markdown
Collaborator

retrying, failure is related to a race condition in mbridge. fyi @yfw https://github.com/NVIDIA-NeMo/RL/actions/runs/17603234870/job/50009498530#step:3:8329

Merged via the queue into main with commit 9397ef8 Sep 10, 2025
24 checks passed
@terrykong
terrykong deleted the bxyu/fix-clear-cache-name branch September 10, 2025 09:48
guyueh1 pushed a commit to guyueh1/NeMo-RL that referenced this pull request Sep 15, 2025
Signed-off-by: Brian Yu <bxyu@nvidia.com>
PrinsYin pushed a commit to PrinsYin/RL that referenced this pull request Nov 30, 2025
Signed-off-by: Brian Yu <bxyu@nvidia.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants