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.

  • The Model base class constructor must be invoked before the mixins constructor.

Note

For models in JAX/Flax it is imperative to define all parameters (except observation_space, state_space, action_space and device) with default values to avoid errors during initialization (TypeError: __init__() missing N required positional argument).

In addition, it is necessary to initialize the model’s state_dict (via the init_state_dict method) after its instantiation to avoid errors during its use (AttributeError: object has no attribute "state_dict". If "state_dict" is defined in '.setup()', remember these fields are only accessible from inside 'init' or 'apply').

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

Concept

Categorical model Categorical model

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-light.svg ../../_images/model_categorical_mlp-dark.svg

import torch
import torch.nn as nn

from skrl.models.torch import Model, CategoricalMixin


# define the model
class MLP(CategoricalMixin, Model):
    def __init__(self, observation_space, state_space, action_space, device, unnormalized_log_prob=True):
        Model.__init__(
            self,
            observation_space=observation_space,
            state_space=state_space,
            action_space=action_space,
            device=device,
        )
        CategoricalMixin.__init__(self, unnormalized_log_prob=unnormalized_log_prob)

        self.net = nn.Sequential(
            nn.Linear(self.num_observations, 64),
            nn.ReLU(),
            nn.Linear(64, 32),
            nn.ReLU(),
            nn.Linear(32, self.num_actions),
        )

    def compute(self, inputs, role):
        return self.net(inputs["observations"]), {}


# instantiate the model (given a wrapped environment: `env`)
policy = MLP(
    observation_space=env.observation_space,
    state_space=env.state_space,
    action_space=env.action_space,
    device=env.device,
    unnormalized_log_prob=True,
)

API


PyTorch

CategoricalMixin

Categorical mixin model (stochastic model).

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

Bases: object

Categorical mixin model (stochastic model).

Parameters:
  • unnormalized_log_prob – Flag to indicate how to the model’s output will be interpreted. 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 – Role played by the model.

Methods:

act(inputs, *[, role])

Act stochastically in response to the observations/states of the environment.

distribution(*[, role])

Get the current distribution of the model.

get_entropy(*[, role])

Compute and return the entropy of the model.

act(inputs: dict[str, Any], *, role: str = '') tuple[torch.Tensor, dict[str, Any]][source]

Act stochastically in response to the observations/states of the environment.

Parameters:
  • inputs

    Model inputs. The most common keys are:

    • "observations": observation of the environment used to make the decision.

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

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

  • role – Role played by the model.

Returns:

Model output. The first component is the expected action/value returned by the model. The second component is a dictionary containing the following extra output values:

  • "log_prob": log of the probability density function.

  • "net_output": network output.

distribution(*, role: str = '') torch.distributions.Categorical[source]

Get the current distribution of the model.

Parameters:

role – Role played by the model.

Returns:

Distribution of the model.

get_entropy(*, role: str = '') torch.Tensor[source]

Compute and return the entropy of the model.

Parameters:

role – Role played by the model.

Returns:

Entropy of the model.


JAX

CategoricalMixin

Categorical mixin model (stochastic model).

class skrl.models.jax.categorical.CategoricalMixin(*, unnormalized_log_prob: bool = True, role: str = '')[source]

Bases: object

Categorical mixin model (stochastic model).

Parameters:
  • unnormalized_log_prob – Flag to indicate how to the model’s output will be interpreted. 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 – Role played by the model.

Methods:

act(inputs, *[, role, params])

Act stochastically in response to the observations/states of the environment.

get_entropy(stddev, *[, role])

Compute and return the entropy of the model.

act(inputs: dict[str, Any], *, role: str = '', params: jax.Array | None = None) tuple[jax.Array, dict[str, Any]][source]

Act stochastically in response to the observations/states of the environment.

Parameters:
  • inputs

    Model inputs. The most common keys are:

    • "observations": observation of the environment used to make the decision.

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

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

  • role – Role played by the model.

  • params – Parameters used to compute the output. If not provided, internal parameters will be used.

Returns:

Model output. The first component is the expected action/value returned by the model. The second component is a dictionary containing the following extra output values:

  • "log_prob": log of the probability density function.

  • "net_output": network output.

get_entropy(stddev: jax.Array, *, role: str = '') jax.Array[source]

Compute and return the entropy of the model.

Parameters:
  • stddev – Model standard deviation.

  • role – Role played by the model.

Returns:

Entropy of the model.