Skip to content

[BugFix] Apply prioritized-replay weights in CQL, IQL, REDQ, CrossQ and QMixer losses - #4694

Merged
theap06 merged 5 commits into
pytorch:mainfrom
theap06:fix/losses-apply-priority-weights
Nov 6, 2026
Merged

theap06 merged 5 commits into
pytorch:mainfrom
theap06:fix/losses-apply-priority-weights

Conversation

@theap06

@theap06 theap06 commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Description

CQLLoss, DiscreteCQLLoss, IQLLoss, DiscreteIQLLoss, REDQLoss, CrossQLoss and QMixerLoss write td_error priorities for prioritized replay but never read the importance-sampling weights back, so PER training with them is biased. SACLoss, DQNLoss, DDPGLoss, TD3Loss, TD3BCLoss, TQCLoss and FQLLoss already apply them.

Each of the seven losses now, matching SACLoss:

  • exposes a priority_weight key in _AcceptedKeys (default "priority_weight") and a use_prioritized_weights constructor flag (default "auto"; False ignores the weights);
  • weights every per-sample loss term before reduction through _maybe_get_priority_weight / _reduce_loss: the TD and value terms, the CQL conservative term and Lagrange loss, and the actor and alpha terms, as SAC does.

The flag is added to IQLLossConfig, CQLLossConfig and QMixerLossConfig (REDQ and CrossQ have no config); QMixerLossConfig also gains priority_weight_key.

Supporting changes:

  • CQLLoss.cql_loss now computes the CQL(H) regularizer of the paper and reference implementation (aviralkumar2907/CQL, min_q_version=3): one logsumexp over all 3 * num_random sampled actions of each state (random, current-policy and next-state-policy actions, each with its importance correction), minus that state's data Q-value. Previously the logsumexp ran over groups of 3, one per sampled index, and the next-state policy actions were scored with the next observation instead of the current one. min_qf.flatten() - pred_q also broadcast to a [B, B * num_random] tensor that mixed states, so no per-sample weight could attach to it. This changes loss_cql for every CQL user (it grows by about 2 * min_q_weight * temperature * log(num_random), so a tuned lagrange_thresh means something different). reduction="none" values of loss_cql and the stored cql_q1_loss/cql_q2_loss are per sample ([B]). test_cql_regularizer_matches_cql_h checks the value against a closed form with an observation-dependent uniform policy and a state-only Q-function.
  • LossModule._maybe_get_priority_weight accepts nested priority_weight keys (it raised TypeError for every loss before), and DQNLoss now reads them through it too.
  • IQLLoss.qvalue_loss reduces against the full input, so it honours ("collector", "mask") like the other terms.
  • A weighted mean over a batch whose every element is masked out returns 0 instead of NaN.
  • REDQLoss_deprecated, which the REDQ example builds with a prioritized buffer by default, applies the weights too and gains the same key and flag.
  • LossModule._reduce_loss broadcasts weights to the loss shape with or without a mask (REDQ's losses carry a leading ensemble dimension). Previously an unmasked shape mismatch raised for "mean"/"sum" and broadcast incorrectly for "none".
  • QMixerLoss reduces through _reduce_loss without passing the input, so it still ignores loss masks as before.

Breaking changes:

  • Users who sample from a prioritized buffer with these losses now get weighted losses by default, as SAC/DQN users did after [Feature] Weight loss outputs when using prioritized sampler #3235. use_prioritized_weights=False restores the previous numbers; users without prioritized replay see no change from this part. This is treated as a bug fix rather than a deprecation cycle.
  • loss_cql changes for every CQL user (see above).

Tests: one per loss in the existing files (test_cql.py, test_iql.py, test_sac.py for CrossQ/REDQ, test_dqn.py for QMixer, the latter also with a nested key and with use_prioritized_weights=False). Each compares the weighted loss with a weighted mean of the per-sample losses and checks it differs from the plain mean, and all fail on main. Further tests cover the CQL(H) value, the DQN nested key, the IQL mask (partial and all-invalid) and REDQLoss_deprecated. Also run: test_cql.py, test_iql.py, test_dqn.py, test_sac.py and test_loss_module.py (3644 passed), and the loss tests in test_configs.py.

Not addressed (on main already): with with_lagrange=True, the alpha_prime loss sends gradients into the Q networks and loss_cql is not scaled by alpha_prime as in the reference; CQLLoss(with_lagrange=True, reduction="none") raises.

Motivation and Context

Weights from a PrioritizedSampler were silently dropped by these losses while SAC applied them. close #955 (every loss that writes priorities now applies the weights).

  • I have raised an issue to propose this change (required for new features and bug fixes)

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist

  • I have read the CONTRIBUTION guide (required)
  • My change requires a change to the documentation.
  • I have updated the tests accordingly (required for a bug fix or a new feature).
  • I have updated the documentation accordingly.

…nd QMixer losses

CQLLoss, DiscreteCQLLoss, IQLLoss, DiscreteIQLLoss, REDQLoss, CrossQLoss and
QMixerLoss wrote td_error priorities for prioritized replay but never read the
importance-sampling weights back, so PER training with them was biased.

Each loss now exposes a priority_weight key and a use_prioritized_weights
constructor flag (default "auto") and weights every per-sample loss term
before reduction, matching SACLoss. The flag is surfaced in the IQL, CQL and
QMixer Hydra configs.

CQLLoss now averages its sampled-action logsumexp terms per state before
subtracting that state's data Q-value, so the conservative term is a true
per-sample quantity that a weight can attach to. Unweighted mean results are
unchanged.

LossModule._maybe_get_priority_weight now supports nested priority_weight
keys, and _reduce_loss broadcasts weights to the loss shape with or without a
mask.
@pytorch-bot

pytorch-bot Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/rl/4694

Note: Links to docs will display an error until the docs builds have been completed.

✅ No Failures

As of commit 4804db1 with merge base 5674798 (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 5, 2026
…he current state

CQLLoss took a separate logsumexp over each (random, current-policy,
next-policy) triple and averaged them, and it evaluated the next-state policy
actions at the next state. The CQL(H) term, as in the reference
implementation, is one logsumexp over all 3 * num_random sampled actions per
state, each evaluated at the current state. Reshape the sampled Q-values to
[*batch, 3 * num_random] before the logsumexp and pair the next-state actions
with the current observation.

This changes loss_cql for every CQLLoss user. The new test uses a uniform
actor and a state-only Q-function, for which the regularizer has a closed form.
…s in IQL's Q-value loss

DQNLoss and DistributionalDQNLoss checked the weight key with
`key in tensordict.keys()`, which raises TypeError for a nested key, so
set_keys(priority_weight=(..., ...)) broke every call. Use the shared
_maybe_get_priority_weight helper.

IQLLoss.qvalue_loss reduced the loss against a selection of the input that
dropped the loss mask, so masked samples still counted (with or without
priority weights). Reduce against the input tensordict.
…or a fully masked weighted batch

REDQLoss_deprecated, which the REDQ example builds with a prioritized
replay buffer by default, now weights its losses like REDQLoss and gains
the priority_weight key and use_prioritized_weights flag. A weighted
mean over a batch whose every element is masked out divided 0 by 0;
it now returns 0, as the unweighted path does. QMixerLossConfig exposes
priority_weight_key, and the CQL(H) test uses an observation-dependent
policy so it checks the next-state log-probabilities.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

BugFix CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. Objectives Trainers

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request] DQN Loss importance sampling

1 participant