redq#
Source code: tianshou/algorithm/modelfree/redq.py
- class REDQTrainingStats(alpha: float | None = None, alpha_loss: float | None = None, *, train_time: float = 0.0, smoothed_loss: dict = <factory>, actor_loss: float, critic_loss: float)[source]#
Bases:
DDPGTrainingStatsA data structure for storing loss statistics of the REDQ learn step.
- alpha: float | None = None#
- alpha_loss: float | None = None#
- class REDQPolicy(*, actor: Module | ContinuousActorProbabilistic, exploration_noise: BaseNoise | Literal['default'] | None = None, action_space: Space, deterministic_eval: bool = True, action_scaling: bool = True, action_bound_method: Literal['clip'] | None = 'clip', observation_space: Space | None = None)[source]#
Bases:
ContinuousPolicyWithExplorationNoise- Parameters:
actor – The actor network following the rules (s -> model_output)
action_space – the environment’s action_space.
deterministic_eval – flag indicating whether the policy should use deterministic actions (using the mode of the action distribution) instead of stochastic ones (using random sampling) during evaluation. When enabled, the policy will always select the most probable action according to the learned distribution during evaluation phases, while still using stochastic sampling during training. This creates a clear distinction between exploration (training) and exploitation (evaluation) behaviors. Deterministic actions are generally preferred for final deployment and reproducible evaluation as they provide consistent behavior, reduce variance in performance metrics, and are more interpretable for human observers. Note that this parameter only affects behavior when the policy is not within a training step. When collecting rollouts for training, actions remain stochastic regardless of this setting to maintain proper exploration behaviour.
observation_space – the environment’s observation space
action_scaling – flag indicating whether, for continuous action spaces, actions should be scaled from the standard neural network output range [-1, 1] to the environment’s action space range [action_space.low, action_space.high]. This applies to continuous action spaces only (gym.spaces.Box) and has no effect for discrete spaces. When enabled, policy outputs are expected to be in the normalized range [-1, 1] (after bounding), and are then linearly transformed to the actual required range. This improves neural network training stability, allows the same algorithm to work across environments with different action ranges, and standardizes exploration strategies. Should be disabled if the actor model already produces outputs in the correct range.
action_bound_method – the method used for bounding actions in continuous action spaces to the range [-1, 1] before scaling them to the environment’s action space (provided that action_scaling is enabled). This applies to continuous action spaces only (gym.spaces.Box) and should be set to None for discrete spaces. When set to “clip”, actions exceeding the [-1, 1] range are simply clipped to this range. When set to “tanh”, a hyperbolic tangent function is applied, which smoothly constrains outputs to [-1, 1] while preserving gradients. The choice of bounding method affects both training dynamics and exploration behavior. Clipping provides hard boundaries but may create plateau regions in the gradient landscape, while tanh provides smoother transitions but can compress sensitivity near the boundaries. Should be set to None if the actor model inherently produces bounded outputs. Typically used together with action_scaling=True.
- forward(batch: ObsBatchProtocol, state: dict | Batch | ndarray | None = None, **kwargs: Any) DistLogProbBatchProtocol[source]#
Defines the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- class REDQ(*, policy: REDQPolicy, policy_optim: OptimizerFactory, critic: Module, critic_optim: OptimizerFactory, ensemble_size: int = 10, subset_size: int = 2, tau: float = 0.005, gamma: float = 0.99, alpha: float | Alpha = 0.2, n_step_return_horizon: int = 1, actor_delay: int = 20, deterministic_eval: bool = True, target_mode: Literal['mean', 'min'] = 'min')[source]#
Bases:
ActorCriticOffPolicyAlgorithm[REDQPolicy,DistLogProbBatchProtocol]Implementation of REDQ. arXiv:2101.05982.
- Parameters:
policy – the policy
policy_optim – the optimizer factory for the policy’s model.
critic – the critic network. (s, a -> Q(s, a))
critic_optim – the optimizer factory for the critic network.
ensemble_size – the total number of critic networks in the ensemble. This parameter implements the randomized ensemble approach described in REDQ. The algorithm maintains ensemble_size different critic networks that all share the same architecture. During target value computation, a random subset of these networks (determined by subset_size) is used. Larger values increase the diversity of the ensemble but require more memory and computation. The original paper recommends a value of 10 for most tasks, balancing performance and computational efficiency.
subset_size – the number of critic networks randomly selected from the ensemble for computing target Q-values. During each update, the algorithm samples subset_size networks from the ensemble of ensemble_size networks without replacement. The target Q-value is then calculated as either the minimum or mean (based on target_mode) of the predictions from this subset. Smaller values increase randomization and sample efficiency but may introduce more variance. Larger values provide more stable estimates but reduce the benefits of randomization. The REDQ paper recommends a value of 2 for optimal sample efficiency. Must satisfy 0 < subset_size <= ensemble_size.
tau – the soft update coefficient for target networks, controlling the rate at which target networks track the learned networks. When the parameters of the target network are updated with the current (source) network’s parameters, a weighted average is used: target = tau * source + (1 - tau) * target. Smaller values (closer to 0) create more stable but slower learning as target networks change more gradually. Higher values (closer to 1) allow faster learning but may reduce stability. Typically set to a small value (0.001 to 0.01) for most reinforcement learning tasks.
gamma – the discount factor in [0, 1] for future rewards. This determines how much future rewards are valued compared to immediate ones. Lower values (closer to 0) make the agent focus on immediate rewards, creating “myopic” behavior. Higher values (closer to 1) make the agent value long-term rewards more, potentially improving performance in tasks where delayed rewards are important but increasing training variance by incorporating more environmental stochasticity. Typically set between 0.9 and 0.99 for most reinforcement learning tasks
alpha – the entropy regularization coefficient, which balances exploration and exploitation. This coefficient controls how much the agent values randomness in its policy versus pursuing higher rewards. Higher values (e.g., 0.5-1.0) strongly encourage exploration by rewarding the agent for maintaining diverse action choices, even if this means selecting some lower-value actions. Lower values (e.g., 0.01-0.1) prioritize exploitation, allowing the policy to become more focused on the highest-value actions. A value of 0 would completely remove entropy regularization, potentially leading to premature convergence to suboptimal deterministic policies. Can be provided as a fixed float (0.2 is a reasonable default) or as an instance of, in particular, class AutoAlpha for automatic tuning during training.
n_step_return_horizon – the number of future steps (> 0) to consider when computing temporal difference (TD) targets. Controls the balance between TD learning and Monte Carlo methods: higher values reduce bias (by relying less on potentially inaccurate value estimates) but increase variance (by incorporating more environmental stochasticity and reducing the averaging effect). A value of 1 corresponds to standard TD learning with immediate bootstrapping, while very large values approach Monte Carlo-like estimation that uses complete episode returns.
actor_delay – the number of critic updates performed before each actor update. The actor network is only updated once for every actor_delay critic updates, implementing a delayed policy update strategy similar to TD3. Larger values stabilize training by allowing critics to become more accurate before policy updates. Smaller values allow the policy to adapt more quickly but may lead to less stable learning. The REDQ paper recommends a value of 20 for most tasks.
target_mode – the method used to aggregate Q-values from the subset of critic networks. Can be either “min” or “mean”. If “min”, uses the minimum Q-value across the selected subset of critics for each state-action pair. If “mean”, uses the average Q-value across the selected subset of critics. Using “min” helps prevent overestimation bias but may lead to more conservative value estimates. Using “mean” provides more optimistic value estimates but may suffer from overestimation bias. Default is “min” following the conservative value estimation approach common in recent Q-learning algorithms.