Repository navigation
[BugFix] Apply prioritized-replay weights in CQL, IQL, REDQ, CrossQ and QMixer losses - #4694
Merged
Merged
Conversation
…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.
🔗 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 FailuresAs of commit 4804db1 with merge base 5674798 ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
…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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
CQLLoss,DiscreteCQLLoss,IQLLoss,DiscreteIQLLoss,REDQLoss,CrossQLossandQMixerLosswritetd_errorpriorities for prioritized replay but never read the importance-sampling weights back, so PER training with them is biased.SACLoss,DQNLoss,DDPGLoss,TD3Loss,TD3BCLoss,TQCLossandFQLLossalready apply them.Each of the seven losses now, matching
SACLoss:priority_weightkey in_AcceptedKeys(default"priority_weight") and ause_prioritized_weightsconstructor flag (default"auto";Falseignores the weights);_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,CQLLossConfigandQMixerLossConfig(REDQ and CrossQ have no config);QMixerLossConfigalso gainspriority_weight_key.Supporting changes:
CQLLoss.cql_lossnow computes the CQL(H) regularizer of the paper and reference implementation (aviralkumar2907/CQL,min_q_version=3): one logsumexp over all3 * num_randomsampled 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_qalso broadcast to a[B, B * num_random]tensor that mixed states, so no per-sample weight could attach to it. This changesloss_cqlfor every CQL user (it grows by about2 * min_q_weight * temperature * log(num_random), so a tunedlagrange_threshmeans something different).reduction="none"values ofloss_cqland the storedcql_q1_loss/cql_q2_lossare per sample ([B]).test_cql_regularizer_matches_cql_hchecks the value against a closed form with an observation-dependent uniform policy and a state-only Q-function.LossModule._maybe_get_priority_weightaccepts nestedpriority_weightkeys (it raisedTypeErrorfor every loss before), andDQNLossnow reads them through it too.IQLLoss.qvalue_lossreduces against the full input, so it honours("collector", "mask")like the other terms.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_lossbroadcasts 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".QMixerLossreduces through_reduce_losswithout passing the input, so it still ignores loss masks as before.Breaking changes:
use_prioritized_weights=Falserestores 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_cqlchanges for every CQL user (see above).Tests: one per loss in the existing files (
test_cql.py,test_iql.py,test_sac.pyfor CrossQ/REDQ,test_dqn.pyfor QMixer, the latter also with a nested key and withuse_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) andREDQLoss_deprecated. Also run:test_cql.py,test_iql.py,test_dqn.py,test_sac.pyandtest_loss_module.py(3644 passed), and the loss tests intest_configs.py.Not addressed (on main already): with
with_lagrange=True, thealpha_primeloss sends gradients into the Q networks andloss_cqlis not scaled byalpha_primeas in the reference;CQLLoss(with_lagrange=True, reduction="none")raises.Motivation and Context
Weights from a
PrioritizedSamplerwere silently dropped by these losses while SAC applied them. close #955 (every loss that writes priorities now applies the weights).Types of changes
Checklist