Skip to content

[fsdp, algo] no grad for entropy and kl if the loss coef is 0#6519

Open
huaiyizhao wants to merge 2 commits into
verl-project:mainfrom
huaiyizhao:fix/no-grad-entropy-kl-metrics
Open

[fsdp, algo] no grad for entropy and kl if the loss coef is 0#6519
huaiyizhao wants to merge 2 commits into
verl-project:mainfrom
huaiyizhao:fix/no-grad-entropy-kl-metrics

Conversation

@huaiyizhao
Copy link
Copy Markdown
Contributor

What does this PR do?

Add concise overview of what this PR aims to achieve or accomplish. Reference related GitHub issues and PRs that help with the review.

This PR prevents logging-only entropy and KL metrics from unnecessarily extending the actor backward graph.

Checklist Before Starting

  • Search for similar PRs. Paste at least one query link here: ...
  • Format the PR title as [{modules}] {type}: {description} (This will be checked by the CI)
    • {modules} include fsdp, megatron, veomni, sglang, vllm, rollout, trainer, ci, training_utils, recipe, hardware, deployment, ray, worker, single_controller, misc, perf, model, algo, env, tool, ckpt, doc, data, cfg, reward, fully_async, one_step_off
    • If this PR involves multiple modules, separate them with , like [megatron, fsdp, doc]
    • {type} is in feat, fix, refactor, chore, test
    • If this PR breaks any API (CLI arguments, config, function signature, etc.), add [BREAKING] to the beginning of the title.
    • Example: [BREAKING][fsdp, megatron] feat: dynamic batching

Test

For changes that can not be tested by CI (e.g., algorithm implementation, new model support), validate by experiment(s) and show results like training curve plots, evaluation results, etc.

API and Usage Example

Demonstrate how the API changes if any, and provide usage example(s) if possible.

# Add code snippet or script demonstrating how to use this

Design & Code Changes

Demonstrate the high-level design if this PR is complex, and list the specific changes.

Checklist Before Submitting

Important

Please check all the following items before requesting a review, otherwise the reviewer might deprioritize this PR for review.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request optimizes gradient computation during training. In transformer_impl.py, it dynamically determines if entropy calculations require gradients based on the entropy_coeff value, running under torch.no_grad() when possible. In losses.py, it optimizes PPO loss when kl_loss_coef is 0.0 by detaching log_prob and computing the KL penalty inside a torch.no_grad() block. The reviewer suggested making the retrieval of entropy_coeff more robust by supporting both object attributes and dictionary lookups for loss_config to prevent unnecessary gradient tracking.

Comment on lines +1076 to +1084
entropy_needs_grad = calculate_entropy
if calculate_entropy and logits_processor_func is not None:
loss_config = getattr(logits_processor_func, "keywords", {}).get("config")
entropy_coeff = getattr(loss_config, "entropy_coeff", None)
if entropy_coeff is not None:
try:
entropy_needs_grad = float(entropy_coeff) != 0.0
except (TypeError, ValueError):
entropy_needs_grad = True
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.

high

The current implementation uses getattr(loss_config, "entropy_coeff", None) to retrieve the entropy coefficient. However, if loss_config is a standard Python dictionary (which is common in some testing environments or custom pipelines), getattr will return None instead of retrieving the key. This will silently cause entropy_needs_grad to default to True, unnecessarily extending the backward graph and consuming extra memory.

To make this robust, we should support retrieving entropy_coeff from both object attributes and dictionary keys.

Suggested change
entropy_needs_grad = calculate_entropy
if calculate_entropy and logits_processor_func is not None:
loss_config = getattr(logits_processor_func, "keywords", {}).get("config")
entropy_coeff = getattr(loss_config, "entropy_coeff", None)
if entropy_coeff is not None:
try:
entropy_needs_grad = float(entropy_coeff) != 0.0
except (TypeError, ValueError):
entropy_needs_grad = True
entropy_needs_grad = calculate_entropy
if calculate_entropy and logits_processor_func is not None:
loss_config = getattr(logits_processor_func, "keywords", {}).get("config")
entropy_coeff = None
if loss_config is not None:
if isinstance(loss_config, dict):
entropy_coeff = loss_config.get("entropy_coeff")
else:
entropy_coeff = getattr(loss_config, "entropy_coeff", None)
if entropy_coeff is None and hasattr(loss_config, "get"):
entropy_coeff = loss_config.get("entropy_coeff", None)
if entropy_coeff is not None:
try:
entropy_needs_grad = float(entropy_coeff) != 0.0
except (TypeError, ValueError):
entropy_needs_grad = True


policy_loss += kl_loss * config.kl_loss_coef
kl_loss_coeff = float(config.kl_loss_coef)
if kl_loss_coeff == 0.0:
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.

unify computation with nullcontext() as well.

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.

2 participants