Categorical model

Categorical models run discrete-domain stochastic policies.

skrl provides a Python mixin (CategoricalMixin) to assist in the creation of these types of models, allowing users to have full control over the function approximator definitions and architectures. Note that the use of this mixin must comply with the following rules:

  • The definition of multiple inheritance must always include the Model base class at the end.

    class CategoricalModel(CategoricalMixin, Model):
        def __init__(self, observation_space, action_space, device, unnormalized_log_prob=True):
            Model.__init__(self, observation_space, action_space, device)
            CategoricalMixin.__init__(self, unnormalized_log_prob)
    
  • The Model base class constructor must be invoked before the mixins constructor.

    class CategoricalModel(CategoricalMixin, Model):
        def __init__(self, observation_space, action_space, device, unnormalized_log_prob=True):
            Model.__init__(self, observation_space, action_space, device)
            CategoricalMixin.__init__(self, unnormalized_log_prob)
    

Concept

Categorical model

Basic usage

  • Multi-Layer Perceptron (MLP)

  • Convolutional Neural Network (CNN)

  • Recurrent Neural Network (RNN)

  • Gated Recurrent Unit RNN (GRU)

  • Long Short-Term Memory RNN (LSTM)

../_images/model_categorical_mlp.svg
 1import torch
 2import torch.nn as nn
 3
 4from skrl.models.torch import Model, CategoricalMixin
 5
 6
 7# define the model
 8class MLP(CategoricalMixin, Model):
 9    def __init__(self, observation_space, action_space, device, unnormalized_log_prob=True):
10        Model.__init__(self, observation_space, action_space, device)
11        CategoricalMixin.__init__(self, unnormalized_log_prob)
12
13        self.net = nn.Sequential(nn.Linear(self.num_observations, 64),
14                                 nn.ReLU(),
15                                 nn.Linear(64, 32),
16                                 nn.ReLU(),
17                                 nn.Linear(32, self.num_actions))
18
19    def compute(self, inputs, role):
20        return self.net(inputs["states"]), {}
21
22
23# instantiate the model (assumes there is a wrapped environment: env)
24policy = MLP(observation_space=env.observation_space,
25             action_space=env.action_space,
26             device=env.device,
27             unnormalized_log_prob=True)

API

class skrl.models.torch.categorical.CategoricalMixin(unnormalized_log_prob: bool = True, role: str = '')

Bases: object

__init__(unnormalized_log_prob: bool = True, role: str = '') None

Categorical mixin model (stochastic model)

Parameters
  • unnormalized_log_prob (bool, optional) – Flag to indicate how to be interpreted the model’s output (default: True). If True, the model’s output is interpreted as unnormalized log probabilities (it can be any real number), otherwise as normalized probabilities (the output must be non-negative, finite and have a non-zero sum)

  • role (str, optional) – Role play by the model (default: "")

Example:

# define the model
>>> import torch
>>> import torch.nn as nn
>>> from skrl.models.torch import Model, CategoricalMixin
>>>
>>> class Policy(CategoricalMixin, Model):
...     def __init__(self, observation_space, action_space, device="cuda:0", unnormalized_log_prob=True):
...         Model.__init__(self, observation_space, action_space, device)
...         CategoricalMixin.__init__(self, unnormalized_log_prob)
...
...         self.net = nn.Sequential(nn.Linear(self.num_observations, 32),
...                                  nn.ELU(),
...                                  nn.Linear(32, 32),
...                                  nn.ELU(),
...                                  nn.Linear(32, self.num_actions))
...
...     def compute(self, inputs, role):
...         return self.net(inputs["states"]), {}
...
>>> # given an observation_space: gym.spaces.Box with shape (4,)
>>> # and an action_space: gym.spaces.Discrete with n = 2
>>> model = Policy(observation_space, action_space)
>>>
>>> print(model)
Policy(
  (net): Sequential(
    (0): Linear(in_features=4, out_features=32, bias=True)
    (1): ELU(alpha=1.0)
    (2): Linear(in_features=32, out_features=32, bias=True)
    (3): ELU(alpha=1.0)
    (4): Linear(in_features=32, out_features=2, bias=True)
  )
)
act(inputs: Mapping[str, Union[torch.Tensor, Any]], role: str = '') Tuple[torch.Tensor, Optional[torch.Tensor], Mapping[str, Union[torch.Tensor, Any]]]

Act stochastically in response to the state of the environment

Parameters
  • inputs (dict where the values are typically torch.Tensor) –

    Model inputs. The most common keys are:

    • "states": state of the environment used to make the decision

    • "taken_actions": actions taken by the policy for the given states

  • role (str, optional) – Role play by the model (default: "")

Returns

Model output. The first component is the action to be taken by the agent. The second component is the log of the probability density function. The third component is a dictionary containing the network output "net_output" and extra output values

Return type

tuple of torch.Tensor, torch.Tensor or None, and dictionary

Example:

>>> # given a batch of sample states with shape (4096, 4)
>>> actions, log_prob, outputs = model.act({"states": states})
>>> print(actions.shape, log_prob.shape, outputs["net_output"].shape)
torch.Size([4096, 1]) torch.Size([4096, 1]) torch.Size([4096, 2])
distribution(role: str = '') torch.distributions.categorical.Categorical

Get the current distribution of the model

Returns

Distribution of the model

Return type

torch.distributions.Categorical

Parameters

role (str, optional) – Role play by the model (default: "")

Example:

>>> distribution = model.distribution()
>>> print(distribution)
Categorical(probs: torch.Size([4096, 2]), logits: torch.Size([4096, 2]))