lit_sb3.algorithms.dqn
source package lit_sb3.algorithms.dqn
Classes
-
CnnPolicy — Policy class for DQN when using images as input.
-
DQN — Deep Q-Network (DQN).
-
DQNPolicy — Policy class with Q-Value Net and target net for DQN.
-
MultiInputPolicy — Policy class for DQN when using dict observations as input.
-
QNetwork — Action-Value (Q-Value) network for DQN.
source class CnnPolicy(observation_space: spaces.Space, action_space: spaces.Discrete, lr_schedule: Schedule, net_arch: list[int] | None = None, activation_fn: type[nn.Module] = nn.ReLU, features_extractor_class: type[BaseFeaturesExtractor] = NatureCNN, features_extractor_kwargs: dict[str, Any] | None = None, normalize_images: bool = True, optimizer_class: type[torch.optim.Optimizer] = torch.optim.Adam, optimizer_kwargs: dict[str, Any] | None = None)
Bases : DQNPolicy
Policy class for DQN when using images as input.
Parameters
-
observation_space : spaces.Space — Observation space
-
action_space : spaces.Discrete — Action space
-
lr_schedule : Schedule — Learning rate schedule (could be constant)
-
net_arch : list[int] | None — The specification of the policy and value networks.
-
activation_fn : type[nn.Module] — Activation function
-
features_extractor_class : type[BaseFeaturesExtractor] — Features extractor to use.
-
normalize_images : bool — Whether to normalize images or not, dividing by 255.0 (True by default)
-
optimizer_class : type[torch.optim.Optimizer] — The optimizer to use,
torch.optim.Adamby default -
optimizer_kwargs : dict[str, Any] | None — Additional keyword arguments, excluding the learning rate, to pass to the optimizer
Attributes
-
device : torch.device — Infer which device this policy lives on by inspecting its parameters.
-
squash_output : bool — (bool) Getter for squash_output.
source class DQN(policy: str | type[DQNPolicy], learning_rate: float | Schedule = 0.0001, buffer_size: int = 1000000, learning_starts: int = 100, batch_size: int = 32, tau: float = 1.0, gamma: float = 0.99, train_freq: int | tuple[int, str] = 4, gradient_steps: int = 1, replay_buffer_class: type[ReplayBuffer] | None = None, replay_buffer_kwargs: dict[str, Any] | None = None, optimize_memory_usage: bool = False, n_steps: int = 1, target_update_interval: int = 10000, exploration_fraction: float = 0.1, exploration_initial_eps: float = 1.0, exploration_final_eps: float = 0.05, max_grad_norm: float = 10, stats_window_size: int = 100, policy_kwargs: dict[str, Any] | None = None, verbose: int = 0, seed: int | None = None, device: torch.device | str = 'auto', _init_setup_model: bool = True)
Bases : OffPolicyAlgorithm
Deep Q-Network (DQN).
Paper: https://arxiv.org/abs/1312.5602, https://www.nature.com/articles/nature14236 Default hyperparameters are taken from the Nature paper, except for the optimizer and learning rate that were taken from Stable Baselines defaults.
Parameters
-
policy : str | type[DQNPolicy] — The policy model to use (MlpPolicy, CnnPolicy, ...)
-
env — The environment to learn from (if registered in Gym, can be str)
-
learning_rate : float | Schedule — The learning rate, it can be a function of the current progress remaining (from 1 to 0)
-
buffer_size : int — size of the replay buffer
-
learning_starts : int — how many steps of the model to collect transitions for before learning starts
-
batch_size : int — Minibatch size for each gradient update
-
tau : float — the soft update coefficient ("Polyak update", between 0 and 1) default 1 for hard update
-
gamma : float — the discount factor
-
train_freq : int | tuple[int, str] — Update the model every
train_freqsteps. Alternatively pass a tuple of frequency and unit like(5, "step")or(2, "episode"). -
gradient_steps : int — How many gradient steps to do after each rollout (see
train_freq) Set to-1means to do as many gradient steps as steps done in the environment during the rollout. -
replay_buffer_class : type[ReplayBuffer] | None — Replay buffer class to use (for instance
HerReplayBuffer). IfNone, it will be automatically selected. -
replay_buffer_kwargs : dict[str, Any] | None — Keyword arguments to pass to the replay buffer on creation.
-
optimize_memory_usage : bool — Enable a memory efficient variant of the replay buffer at a cost of more complexity. See https://github.com/DLR-RM/stable-baselines3/issues/37#issuecomment-637501195
-
n_steps : int — When n_step > 1, uses n-step return (with the NStepReplayBuffer) when updating the Q-value network.
-
target_update_interval : int — update the target network every
target_update_intervalenvironment steps. -
exploration_fraction : float — fraction of entire training period over which the exploration rate is reduced
-
exploration_initial_eps : float — initial value of random action probability
-
exploration_final_eps : float — final value of random action probability
-
max_grad_norm : float — The maximum value for the gradient clipping
-
stats_window_size : int — Window size for the rollout logging, specifying the number of episodes to average the reported success rate, mean episode length, and mean reward over
-
tensorboard_log — the log location for tensorboard (if None, no logging)
-
policy_kwargs : dict[str, Any] | None — additional arguments to be passed to the policy on creation. See :ref:
dqn_policies -
verbose : int — Verbosity level: 0 for no output, 1 for info messages (such as device or wrappers used), 2 for debug messages
-
seed : int | None — Seed for the pseudo random generators
-
device : torch.device | str — Device (cpu, cuda, ...) on which the code should be run. Setting it to auto, the code will be run on the GPU if possible.
-
_init_setup_model : bool — Whether or not to build the network at the creation of the instance
Attributes
-
device : torch.device — Return current device (Lightning-aware).
-
hparams : Union[AttributeDict, MutableMapping] — meth:
save_hyperparameters. It is mutable by the user. For the frozen set of initial hyperparameters, use :attr:hparams_initial. -
hparams_initial : AttributeDict — meth:
save_hyperparameters. These contents are read-only. Manual updates to the saved hyperparameters can instead be performed through :attr:hparams. -
example_input_array : Optional[Union[Tensor, tuple, dict]] — meth:
forwardmethod. The return type is interpreted as follows: -
current_epoch : int — The current epoch in the
Trainer, or 0 if not attached. -
global_step : int — Total training batches seen across all epochs.
-
global_rank : int — The index of the current process across all nodes and devices.
-
local_rank : int — The index of the current process within a single node.
-
on_gpu : bool — Returns
Trueif this model is currently located on a GPU. -
strict_loading : bool — Determines how Lightning loads this model using
.load_state_dict(..., strict=model.strict_loading). -
logger : Optional[Union[Logger, FabricLogger]] — Reference to the logger object in the Trainer.
-
loggers : Union[list[Logger], list[FabricLogger]] — Reference to the list of loggers in the Trainer.
-
device_mesh : Optional['DeviceMesh'] — Strategies like
ModelParallelStrategywill create a device mesh that can be accessed in the :meth:~lightning.pytorch.core.hooks.ModelHooks.configure_modelhook to parallelize the LightningModule. -
env : VecEnv | None — Return the active training env from the trainer, or None.
Methods
-
training_step — Off-policy DQN step: collect env transitions then do gradient updates.
-
predict — Overrides the base_class predict function to include epsilon-greedy exploration.
source method DQN.configure_optimizers() → OptimizerLRScheduler
source method DQN.training_step(batch: Any, batch_idx: int) → None
Off-policy DQN step: collect env transitions then do gradient updates.
source method DQN.predict(observation: np.ndarray | dict[str, np.ndarray], state: tuple[np.ndarray, ...] | None = None, episode_start: np.ndarray | None = None, deterministic: bool = False) → tuple[np.ndarray, tuple[np.ndarray, ...] | None]
Overrides the base_class predict function to include epsilon-greedy exploration.
Parameters
-
observation : np.ndarray | dict[str, np.ndarray] — the input observation
-
state : tuple[np.ndarray, ...] | None — The last states (can be None, used in recurrent policies)
-
episode_start : np.ndarray | None — The last masks (can be None, used in recurrent policies)
-
deterministic : bool — Whether or not to return deterministic actions.
Returns
-
tuple[np.ndarray, tuple[np.ndarray, ...] | None] — the model's action and the next state (used in recurrent policies)
source method DQN.learn(total_timesteps: int, env: GymEnv | str | None = None, callback: MaybeCallback = None, log_every_n_steps: int | None = 4, tb_log_name: str = 'DQN', reset_num_timesteps: bool = True, progress_bar: bool = False, default_root_dir: str | Path | None = None) → SelfDQN
source class DQNPolicy(observation_space: spaces.Space, action_space: spaces.Discrete, lr_schedule: Schedule, net_arch: list[int] | None = None, activation_fn: type[nn.Module] = nn.ReLU, features_extractor_class: type[BaseFeaturesExtractor] = FlattenExtractor, features_extractor_kwargs: dict[str, Any] | None = None, normalize_images: bool = True, optimizer_class: type[torch.optim.Optimizer] = torch.optim.Adam, optimizer_kwargs: dict[str, Any] | None = None)
Bases : BasePolicy
Policy class with Q-Value Net and target net for DQN.
Parameters
-
observation_space : spaces.Space — Observation space
-
action_space : spaces.Discrete — Action space
-
lr_schedule : Schedule — Learning rate schedule (could be constant)
-
net_arch : list[int] | None — The specification of the policy and value networks.
-
activation_fn : type[nn.Module] — Activation function
-
features_extractor_class : type[BaseFeaturesExtractor] — Features extractor to use.
-
features_extractor_kwargs : dict[str, Any] | None — Keyword arguments to pass to the features extractor.
-
normalize_images : bool — Whether to normalize images or not, dividing by 255.0 (True by default)
-
optimizer_class : type[torch.optim.Optimizer] — The optimizer to use,
torch.optim.Adamby default -
optimizer_kwargs : dict[str, Any] | None — Additional keyword arguments, excluding the learning rate, to pass to the optimizer
Attributes
-
device : torch.device — Infer which device this policy lives on by inspecting its parameters.
-
squash_output : bool — (bool) Getter for squash_output.
Methods
-
set_training_mode — Put the policy in either training or evaluation mode.
source method DQNPolicy.make_q_net() → QNetwork
source method DQNPolicy.forward(obs: PyTorchObs, deterministic: bool = True) → torch.Tensor
source method DQNPolicy.set_training_mode(mode: bool) → None
Put the policy in either training or evaluation mode.
This affects certain modules, such as batch normalisation and dropout.
Parameters
-
mode : bool — if true, set to training mode, else set to evaluation mode
source class MultiInputPolicy(observation_space: spaces.Dict, action_space: spaces.Discrete, lr_schedule: Schedule, net_arch: list[int] | None = None, activation_fn: type[nn.Module] = nn.ReLU, features_extractor_class: type[BaseFeaturesExtractor] = CombinedExtractor, features_extractor_kwargs: dict[str, Any] | None = None, normalize_images: bool = True, optimizer_class: type[torch.optim.Optimizer] = torch.optim.Adam, optimizer_kwargs: dict[str, Any] | None = None)
Bases : DQNPolicy
Policy class for DQN when using dict observations as input.
Parameters
-
observation_space : spaces.Dict — Observation space
-
action_space : spaces.Discrete — Action space
-
lr_schedule : Schedule — Learning rate schedule (could be constant)
-
net_arch : list[int] | None — The specification of the policy and value networks.
-
activation_fn : type[nn.Module] — Activation function
-
features_extractor_class : type[BaseFeaturesExtractor] — Features extractor to use.
-
normalize_images : bool — Whether to normalize images or not, dividing by 255.0 (True by default)
-
optimizer_class : type[torch.optim.Optimizer] — The optimizer to use,
torch.optim.Adamby default -
optimizer_kwargs : dict[str, Any] | None — Additional keyword arguments, excluding the learning rate, to pass to the optimizer
Attributes
-
device : torch.device — Infer which device this policy lives on by inspecting its parameters.
-
squash_output : bool — (bool) Getter for squash_output.
source class QNetwork(observation_space: spaces.Space, action_space: spaces.Discrete, features_extractor: BaseFeaturesExtractor, features_dim: int, net_arch: list[int] | None = None, activation_fn: type[nn.Module] = nn.ReLU, normalize_images: bool = True)
Bases : BasePolicy
Action-Value (Q-Value) network for DQN.
Parameters
-
observation_space : spaces.Space — Observation space
-
action_space : spaces.Discrete — Action space
-
net_arch : list[int] | None — The specification of the policy and value networks.
-
activation_fn : type[nn.Module] — Activation function
-
normalize_images : bool — Whether to normalize images or not, dividing by 255.0 (True by default)
Attributes
-
device : torch.device — Infer which device this policy lives on by inspecting its parameters.
-
squash_output : bool — (bool) Getter for squash_output.
Methods
-
forward — Predict the q-values.
source method QNetwork.forward(obs: PyTorchObs) → torch.Tensor
Predict the q-values.
Parameters
-
obs : PyTorchObs — Observation
Returns
-
torch.Tensor — The estimated Q-Value for each action.