RLPack
 
Loading...
Searching...
No Matches
rlpack.dqn.dqn_rank_based_prioritization_agent.DqnRankBasedPrioritizationAgent Class Reference

This class implements the DQN with Rank-Based prioritization strategy. More...

+ Inheritance diagram for rlpack.dqn.dqn_rank_based_prioritization_agent.DqnRankBasedPrioritizationAgent:
+ Collaboration diagram for rlpack.dqn.dqn_rank_based_prioritization_agent.DqnRankBasedPrioritizationAgent:

Public Member Functions

def __init__ (self, pytorch.nn.Module target_model, pytorch.nn.Module policy_model, pytorch.optim.Optimizer optimizer, Union[LRScheduler, None] lr_scheduler, LossFunction loss_function, float gamma, float epsilon, float min_epsilon, float epsilon_decay_rate, int epsilon_decay_frequency, int memory_buffer_size, int target_model_update_rate, int policy_model_update_rate, int backup_frequency, float lr_threshold, int batch_size, int num_actions, str save_path, int bootstrap_rounds=1, str device="cpu", Optional[Dict[str, Any]] prioritization_params=None, float force_terminal_state_selection_prob=0.0, float tau=1.0, int apply_norm=-1, int apply_norm_to=-1, float eps_for_norm=5e-12, int p_for_norm=2, int dim_for_norm=0, Optional[float] max_grad_norm=None, Optional[float] grad_norm_p=2.0)
 
- Public Member Functions inherited from rlpack.dqn.dqn_agent.DqnAgent
def __init__ (self, pytorch.nn.Module target_model, pytorch.nn.Module policy_model, pytorch.optim.Optimizer optimizer, Union[LRScheduler, None] lr_scheduler, LossFunction loss_function, float gamma, float epsilon, float min_epsilon, float epsilon_decay_rate, int epsilon_decay_frequency, int memory_buffer_size, int target_model_update_rate, int policy_model_update_rate, int backup_frequency, float lr_threshold, int batch_size, int num_actions, str save_path, int bootstrap_rounds=1, str device="cpu", Optional[Dict[str, Any]] prioritization_params=None, float force_terminal_state_selection_prob=0.0, float tau=1.0, Union[int, str] apply_norm=-1, Union[int, List[str]] apply_norm_to=-1, float eps_for_norm=5e-12, int p_for_norm=2, int dim_for_norm=0, Optional[float] max_grad_norm=None, float grad_norm_p=2.0)
 
None load (self, Optional[str] custom_name_suffix=None)
 This method loads the target_model, policy_model, optimizer, lr_scheduler and agent_states from the supplied save_path argument in the DQN Agent class' constructor (also called init). More...
 
int policy (self, Union[ndarray, pytorch.Tensor, List[float]] state_current)
 The policy for the agent. More...
 
None save (self, Optional[str] custom_name_suffix=None)
 This method saves the target_model, policy_model, optimizer, lr_scheduler and agent_states in the supplied save_path argument in the DQN Agent class' constructor (also called init). More...
 
int train (self, Union[pytorch.Tensor, np.ndarray, List[Union[float, int]]] state_current, Union[pytorch.Tensor, np.ndarray, List[Union[float, int]]] state_next, Union[int, float] reward, Union[int, float] action, Union[bool, int] done, Optional[Union[pytorch.Tensor, np.ndarray, float]] priority=1.0, Optional[Union[pytorch.Tensor, np.ndarray, float]] probability=1.0, Optional[Union[pytorch.Tensor, np.ndarray, float]] weight=1.0)
 
- Public Member Functions inherited from rlpack.utils.base.agent.Agent
Dict[str, Any] __getstate__ (self)
 To get the agent's current state (dict of attributes). More...
 
def __init__ (self)
 The class initializer. More...
 
None __setstate__ (self, Dict[str, Any] state)
 To load the agent's current state (dict of attributes). More...
 
None load (self, *args, **kwargs)
 Load method for the agent. More...
 
Any policy (self, *args, **kwargs)
 Policy method for the agent. More...
 
None save (self, *args, **kwargs)
 Save method for the agent. More...
 
Any train (self, *args, **kwargs)
 Training method for the agent. More...
 

Private Member Functions

None _apply_prioritization_strategy (self, pytorch.Tensor td_value, pytorch.Tensor random_indices)
 Void private method that applies the relevant prioritization strategy for the DQN. More...
 

Private Attributes

 __prioritization_strategy_code
 

Additional Inherited Members

- Data Fields inherited from rlpack.dqn.dqn_agent.DqnAgent
 apply_norm
 The input apply_norm argument; indicating the normalisation to be used. More...
 
 apply_norm_to
 The input apply_norm_to argument; indicating the quantity to normalise. More...
 
 backup_frequency
 The input model backup frequency in terms of timesteps. More...
 
 batch_size
 The batch size to be used when training policy model. More...
 
 bootstrap_rounds
 The input boostrap rounds. More...
 
 device
 The input device argument; indicating the device name. More...
 
 dim_for_norm
 The input dim_for_norm argument; indicating dimension along which we wish to normalise. More...
 
 eps_for_norm
 The input eps_for_norm argument; indicating epsilon to be used for normalisation. More...
 
 epsilon
 The input exploration factor. More...
 
 epsilon_decay_frequency
 The input epsilon decay frequency in terms of timesteps. More...
 
 epsilon_decay_rate
 The input epsilon decay rate. More...
 
 force_terminal_state_selection_prob
 The input force_terminal_state_selection_prob. More...
 
 gamma
 The input discounting factor. More...
 
 grad_norm_p
 The input grad_norm_p; indicating the p-value for p-normalisation for gradient clippings. More...
 
 loss_function
 The input loss function. More...
 
 lr_scheduler
 The input optional LR Scheduler (this can be None). More...
 
 lr_threshold
 The input LR Threshold. More...
 
 max_grad_norm
 The input max_grad_norm; indicating the maximum gradient norm for gradient clippings. More...
 
 memory
 The instance of rlpack._C.memory.Memory used for Replay buffer. More...
 
 memory_buffer_size
 The input argument memory_buffer_size; indicating the buffer size used. More...
 
 min_epsilon
 The input minimum exploration factor after decays. More...
 
 num_actions
 The input number of actions. More...
 
 optimizer
 The input optimizer wrapped with policy_model parameters. More...
 
 p_for_norm
 The input p_for_norm argument; indicating p-value for p-normalisation. More...
 
 policy_model
 The input policy model. More...
 
 policy_model_update_rate
 The input argument policy_model_update_rate; indicating the update rate of policy model. More...
 
 prioritization_params
 The input prioritization parameters. More...
 
 save_path
 The input save path for backing up agent models. More...
 
 step_counter
 The step counter; counting the total timesteps done so far up to memory_buffer_size. More...
 
 target_model
 The input target model. More...
 
 target_model_update_rate
 The input argument target_model_update_rate; indicating the update rate of target model. More...
 
 tau
 The input tau; indicating the soft update used to update target_model parameters. More...
 
- Data Fields inherited from rlpack.utils.base.agent.Agent
 loss
 The list of losses accumulated after each backward call. More...
 
 save_path
 The path to save agent states and models. More...
 

Detailed Description

This class implements the DQN with Rank-Based prioritization strategy.

Constructor & Destructor Documentation

◆ __init__()

def rlpack.dqn.dqn_rank_based_prioritization_agent.DqnRankBasedPrioritizationAgent.__init__ (   self,
pytorch.nn.Module  target_model,
pytorch.nn.Module  policy_model,
pytorch.optim.Optimizer  optimizer,
Union[LRScheduler, None]  lr_scheduler,
LossFunction  loss_function,
float  gamma,
float  epsilon,
float  min_epsilon,
float  epsilon_decay_rate,
int  epsilon_decay_frequency,
int  memory_buffer_size,
int  target_model_update_rate,
int  policy_model_update_rate,
int  backup_frequency,
float  lr_threshold,
int  batch_size,
int  num_actions,
str  save_path,
int   bootstrap_rounds = 1,
str   device = "cpu",
Optional[Dict[str, Any]]   prioritization_params = None,
float   force_terminal_state_selection_prob = 0.0,
float   tau = 1.0,
int   apply_norm = -1,
int   apply_norm_to = -1,
float   eps_for_norm = 5e-12,
int   p_for_norm = 2,
int   dim_for_norm = 0,
Optional[float]   max_grad_norm = None,
Optional[float]   grad_norm_p = 2.0 
)
Parameters
target_modelnn.Module: The target network for DQN model. This the network which has its weights frozen.
policy_modelnn.Module: The policy network for DQN model. This is the network which is trained.
optimizeroptim.Optimizer: The optimizer wrapped with policy model's parameters.
lr_schedulerUnion[LRScheduler, None]: The PyTorch LR Scheduler with wrapped optimizer.
loss_functionLossFunction: The loss function from PyTorch's nn module. Initialized instance must be passed.
gammafloat: The gamma value for agent.
epsilonfloat: The initial epsilon for the agent.
min_epsilonfloat: The minimum epsilon for the agent. Once this value is reached, it is maintained for all further episodes.
epsilon_decay_ratefloat: The decay multiplier to decay the epsilon.
epsilon_decay_frequencyint: The number of timesteps after which the epsilon is decayed.
memory_buffer_sizeint: The buffer size of memory; or replay buffer for DQN.
target_model_update_rateint: The timesteps after which target model's weights are updated with policy model weights: weights are weighted as per tau: see below)).
policy_model_update_rateint: The timesteps after which policy model is trained. This involves backpropagation through the policy network.
backup_frequencyint: The timesteps after which models are backed up. This will also save optimizer, lr_scheduler and agent_states: epsilon the time of saving and memory.
lr_thresholdfloat: The threshold LR which once reached LR scheduler is not called further.
batch_sizeint: The batch size used for inference through target_model and train through policy model
num_actionsint: Number of actions for the environment.
save_pathstr: The save path for models: target_model and policy_model, optimizer, lr_scheduler and agent_states.
bootstrap_roundsint: The number of rounds until which gradients are to be accumulated before performing calling optimizer step. Gradients are mean reduced for bootstrap_rounds > 1. Default: 1.
devicestr: The device on which models are run. Default: "cpu".
prioritization_paramsOptional[Dict[str, Any]]: The parameters for prioritization in prioritized memory: or relay buffer). Default: None.
force_terminal_state_selection_probfloat: The probability for forcefully selecting a terminal state in a batch. Default: 0.0.
taufloat: The weighted update of weights from policy_model to target_model. This is done by formula target_weight = tau * policy_weight +: 1 - tau) * target_weight/. Default: -1.
apply_normUnion[int, str]: The code to select the normalization procedure to be applied on selected quantities; selected by apply_norm_to: see below)). Direct string can also be passed as per accepted keys. Refer below in Notes to see the accepted values. Default: -1
apply_norm_toUnion[int, List[str]]: The code to select the quantity to which normalization is to be applied. Direct list of quantities can also be passed as per accepted keys. Refer below in Notes to see the accepted values. Default: -1.
eps_for_normfloat: Epsilon value for normalization: for numeric stability. For min-max normalization and standardized normalization. Default: 5e-12.
p_for_normint: The p value for p-normalization. Default: 2: L2 Norm.
dim_for_normint: The dimension across which normalization is to be performed. Default: 0.
max_grad_normOptional[float]: The max norm for gradients for gradient clipping. Default: None
grad_norm_pOptional[float]: The p-value for p-normalization of gradients. Default: 2.0.

Notes

The codes for apply_norm are given as follows: -

  • No Normalization: -1; ("none")
  • Min-Max Normalization: 0; ("min_max")
  • Standardization: 1; ("standardize")
  • P-Normalization: 2; ("p_norm")

The codes for apply_norm_to are given as follows:

  • No Normalization: -1; (["none"])
  • On States only: 0; (["states"])
  • On Rewards only: 1; (["rewards"])
  • On TD value only: 2; (["td"])
  • On States and Rewards: 3; (["states", "rewards"])
  • On States and TD: 4; (["states", "td"])

If a valid max_norm_grad is passed, then gradient clipping takes place else gradient clipping step is skipped. If max_norm_grad value was invalid, error will be raised from PyTorch.

Reimplemented from rlpack.dqn.dqn_agent.DqnAgent.

Member Function Documentation

◆ _apply_prioritization_strategy()

None rlpack.dqn.dqn_rank_based_prioritization_agent.DqnRankBasedPrioritizationAgent._apply_prioritization_strategy (   self,
pytorch.Tensor  td_value,
pytorch.Tensor   random_indices 
)
private

Void private method that applies the relevant prioritization strategy for the DQN.

Parameters
td_valuepytorch.Tensor: The computed TD value.
random_indicesThe indices of randomly sampled transitions.

Reimplemented from rlpack.dqn.dqn_agent.DqnAgent.

Field Documentation

◆ __prioritization_strategy_code

rlpack.dqn.dqn_rank_based_prioritization_agent.DqnRankBasedPrioritizationAgent.__prioritization_strategy_code
private