file_path
stringlengths 21
224
| content
stringlengths 0
80.8M
|
---|---|
Toni-SM/skrl/docs/source/api/agents/ddpg.rst | Deep Deterministic Policy Gradient (DDPG)
=========================================
DDPG is a **model-free**, **deterministic** **off-policy** **actor-critic** algorithm that uses deep function approximators to learn a policy (and to estimate the action-value function) in high-dimensional, **continuous** action spaces
Paper: `Continuous control with deep reinforcement learning <https://arxiv.org/abs/1509.02971>`_
.. raw:: html
<br><hr>
Algorithm
---------
.. raw:: html
<br>
Algorithm implementation
^^^^^^^^^^^^^^^^^^^^^^^^
| Main notation/symbols:
| - policy function approximator (:math:`\mu_\theta`), critic function approximator (:math:`Q_\phi`)
| - states (:math:`s`), actions (:math:`a`), rewards (:math:`r`), next states (:math:`s'`), dones (:math:`d`)
| - loss (:math:`L`)
.. raw:: html
<br>
Decision making
"""""""""""""""
|
| :literal:`act(...)`
| :math:`a \leftarrow \mu_\theta(s)`
| :math:`noise \leftarrow` sample :guilabel:`noise`
| :math:`scale \leftarrow (1 - \text{timestep} \;/` :guilabel:`timesteps` :math:`) \; (` :guilabel:`initial_scale` :math:`-` :guilabel:`final_scale` :math:`) \;+` :guilabel:`final_scale`
| :math:`a \leftarrow \text{clip}(a + noise * scale, {a}_{Low}, {a}_{High})`
.. raw:: html
<br>
Learning algorithm
""""""""""""""""""
|
| :literal:`_update(...)`
| :green:`# sample a batch from memory`
| [:math:`s, a, r, s', d`] :math:`\leftarrow` states, actions, rewards, next_states, dones of size :guilabel:`batch_size`
| :green:`# gradient steps`
| **FOR** each gradient step up to :guilabel:`gradient_steps` **DO**
| :green:`# compute target values`
| :math:`a' \leftarrow \mu_{\theta_{target}}(s')`
| :math:`Q_{_{target}} \leftarrow Q_{\phi_{target}}(s', a')`
| :math:`y \leftarrow r \;+` :guilabel:`discount_factor` :math:`\neg d \; Q_{_{target}}`
| :green:`# compute critic loss`
| :math:`Q \leftarrow Q_\phi(s, a)`
| :math:`L_{Q_\phi} \leftarrow \frac{1}{N} \sum_{i=1}^N (Q - y)^2`
| :green:`# optimization step (critic)`
| reset :math:`\text{optimizer}_\phi`
| :math:`\nabla_{\phi} L_{Q_\phi}`
| :math:`\text{clip}(\lVert \nabla_{\phi} \rVert)` with :guilabel:`grad_norm_clip`
| step :math:`\text{optimizer}_\phi`
| :green:`# compute policy (actor) loss`
| :math:`a \leftarrow \mu_\theta(s)`
| :math:`Q \leftarrow Q_\phi(s, a)`
| :math:`L_{\mu_\theta} \leftarrow - \frac{1}{N} \sum_{i=1}^N Q`
| :green:`# optimization step (policy)`
| reset :math:`\text{optimizer}_\theta`
| :math:`\nabla_{\theta} L_{\mu_\theta}`
| :math:`\text{clip}(\lVert \nabla_{\theta} \rVert)` with :guilabel:`grad_norm_clip`
| step :math:`\text{optimizer}_\theta`
| :green:`# update target networks`
| :math:`\theta_{target} \leftarrow` :guilabel:`polyak` :math:`\theta + (1 \;-` :guilabel:`polyak` :math:`) \theta_{target}`
| :math:`\phi_{target} \leftarrow` :guilabel:`polyak` :math:`\phi + (1 \;-` :guilabel:`polyak` :math:`) \phi_{target}`
| :green:`# update learning rate`
| **IF** there is a :guilabel:`learning_rate_scheduler` **THEN**
| step :math:`\text{scheduler}_\theta (\text{optimizer}_\theta)`
| step :math:`\text{scheduler}_\phi (\text{optimizer}_\phi)`
.. raw:: html
<br>
Usage
-----
.. note::
Support for recurrent neural networks (RNN, LSTM, GRU and any other variant) is implemented in a separate file (:literal:`ddpg_rnn.py`) to maintain the readability of the standard implementation (:literal:`ddpg.py`)
.. tabs::
.. tab:: Standard implementation
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../../snippets/agents_basic_usage.py
:language: python
:emphasize-lines: 2
:start-after: [torch-start-ddpg]
:end-before: [torch-end-ddpg]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../../snippets/agents_basic_usage.py
:language: python
:emphasize-lines: 2
:start-after: [jax-start-ddpg]
:end-before: [jax-end-ddpg]
.. tab:: RNN implementation
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. note::
When using recursive models it is necessary to override their :literal:`.get_specification()` method. Visit each model's documentation for more details
.. literalinclude:: ../../snippets/agents_basic_usage.py
:language: python
:emphasize-lines: 2
:start-after: [torch-start-ddpg-rnn]
:end-before: [torch-end-ddpg-rnn]
.. raw:: html
<br>
Configuration and hyperparameters
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. literalinclude:: ../../../../skrl/agents/torch/ddpg/ddpg.py
:language: python
:start-after: [start-config-dict-torch]
:end-before: [end-config-dict-torch]
.. raw:: html
<br>
Spaces
^^^^^^
The implementation supports the following `Gym spaces <https://www.gymlibrary.dev/api/spaces>`_ / `Gymnasium spaces <https://gymnasium.farama.org/api/spaces>`_
.. list-table::
:header-rows: 1
* - Gym/Gymnasium spaces
- .. centered:: Observation
- .. centered:: Action
* - Discrete
- .. centered:: :math:`\square`
- .. centered:: :math:`\square`
* - MultiDiscrete
- .. centered:: :math:`\square`
- .. centered:: :math:`\square`
* - Box
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\blacksquare`
* - Dict
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\square`
.. raw:: html
<br>
Models
^^^^^^
The implementation uses 4 deterministic function approximators. These function approximators (models) must be collected in a dictionary and passed to the constructor of the class under the argument :literal:`models`
.. list-table::
:header-rows: 1
* - Notation
- Concept
- Key
- Input shape
- Output shape
- Type
* - :math:`\mu_\theta(s)`
- Policy (actor)
- :literal:`"policy"`
- observation
- action
- :ref:`Deterministic <models_deterministic>`
* - :math:`\mu_{\theta_{target}}(s)`
- Target policy
- :literal:`"target_policy"`
- observation
- action
- :ref:`Deterministic <models_deterministic>`
* - :math:`Q_\phi(s, a)`
- Q-network (critic)
- :literal:`"critic"`
- observation + action
- 1
- :ref:`Deterministic <models_deterministic>`
* - :math:`Q_{\phi_{target}}(s, a)`
- Target Q-network
- :literal:`"target_critic"`
- observation + action
- 1
- :ref:`Deterministic <models_deterministic>`
.. raw:: html
<br>
Features
^^^^^^^^
Support for advanced features is described in the next table
.. list-table::
:header-rows: 1
* - Feature
- Support and remarks
- .. centered:: |_4| |pytorch| |_4|
- .. centered:: |_4| |jax| |_4|
* - Shared model
- \-
- .. centered:: :math:`\square`
- .. centered:: :math:`\square`
* - RNN support
- RNN, LSTM, GRU and any other variant
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\square`
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.agents.torch.ddpg.DDPG_DEFAULT_CONFIG
.. autoclass:: skrl.agents.torch.ddpg.DDPG
:undoc-members:
:show-inheritance:
:private-members: _update
:members:
.. automethod:: __init__
.. autoclass:: skrl.agents.torch.ddpg.DDPG_RNN
:undoc-members:
:show-inheritance:
:private-members: _update
:members:
.. automethod:: __init__
.. raw:: html
<br>
API (JAX)
---------
.. autoclass:: skrl.agents.jax.ddpg.DDPG_DEFAULT_CONFIG
.. autoclass:: skrl.agents.jax.ddpg.DDPG
:undoc-members:
:show-inheritance:
:private-members: _update
:members:
.. automethod:: __init__
|
Toni-SM/skrl/docs/source/api/resources/noises.rst | Noises
======
.. toctree::
:hidden:
Gaussian noise <noises/gaussian>
Ornstein-Uhlenbeck <noises/ornstein_uhlenbeck>
Definition of the noises used by the agents during the exploration stage. All noises inherit from a base class that defines a uniform interface.
.. raw:: html
<br><hr>
.. list-table::
:header-rows: 1
* - Noises
- .. centered:: |_4| |pytorch| |_4|
- .. centered:: |_4| |jax| |_4|
* - :doc:`Gaussian <noises/gaussian>` noise
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\blacksquare`
* - :doc:`Ornstein-Uhlenbeck <noises/ornstein_uhlenbeck>` noise |_2|
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\blacksquare`
Base class
----------
.. note::
This is the base class for all the other classes in this module.
It provides the basic functionality for the other classes.
**It is not intended to be used directly**.
.. raw:: html
<br>
Basic inheritance usage
^^^^^^^^^^^^^^^^^^^^^^^
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../../snippets/noises.py
:language: python
:start-after: [start-base-class-torch]
:end-before: [end-base-class-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../../snippets/noises.py
:language: python
:start-after: [start-base-class-jax]
:end-before: [end-base-class-jax]
.. raw:: html
<br>
API (PyTorch)
^^^^^^^^^^^^^
.. autoclass:: skrl.resources.noises.torch.base.Noise
:undoc-members:
:show-inheritance:
:inherited-members:
:members:
.. automethod:: __init__
.. raw:: html
<br>
API (JAX)
^^^^^^^^^
.. autoclass:: skrl.resources.noises.jax.base.Noise
:undoc-members:
:show-inheritance:
:inherited-members:
:members:
.. automethod:: __init__
|
Toni-SM/skrl/docs/source/api/resources/schedulers.rst | Learning rate schedulers
========================
.. toctree::
:hidden:
KL Adaptive <schedulers/kl_adaptive>
Learning rate schedulers are techniques that adjust the learning rate over time to improve the performance of the agent.
.. raw:: html
<br><hr>
.. list-table::
:header-rows: 1
* - Learning rate schedulers
- .. centered:: |_4| |pytorch| |_4|
- .. centered:: |_4| |jax| |_4|
* - :doc:`KL Adaptive <schedulers/kl_adaptive>`
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\blacksquare`
|
**Implementation according to the ML framework:**
- **PyTorch**: The implemented schedulers inherit from the PyTorch :literal:`_LRScheduler` class. Visit `How to adjust learning rate <https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate>`_ in the PyTorch documentation for more details.
- **JAX**: The implemented schedulers must parameterize and return a function that maps step counts to values. Visit `Schedules <https://optax.readthedocs.io/en/latest/api.html#schedules>`_ in the Optax documentation for more details.
.. raw:: html
<br>
Usage
-----
The learning rate scheduler usage is defined in each agent's configuration dictionary. The scheduler class is set under the :literal:`"learning_rate_scheduler"` key and its arguments are set under the :literal:`"learning_rate_scheduler_kwargs"` key as a keyword argument dictionary, without specifying the optimizer (first argument).
The following examples show how to set the scheduler for an agent:
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. tab:: PyTorch scheduler
.. code-block:: python
:emphasize-lines: 2, 5-6
# import the scheduler class
from torch.optim.lr_scheduler import StepLR
cfg = DEFAULT_CONFIG.copy()
cfg["learning_rate_scheduler"] = StepLR
cfg["learning_rate_scheduler_kwargs"] = {"step_size": 1, "gamma": 0.9}
.. tab:: skrl scheduler
.. code-block:: python
:emphasize-lines: 2, 5-6
# import the scheduler class
from skrl.resources.schedulers.torch import KLAdaptiveLR
cfg = DEFAULT_CONFIG.copy()
cfg["learning_rate_scheduler"] = KLAdaptiveLR
cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.01}
.. group-tab:: |_4| |jax| |_4|
.. tabs::
.. tab:: JAX (Optax) scheduler
.. code-block:: python
:emphasize-lines: 2, 5-6
# import the scheduler function
from optax import constant_schedule
cfg = DEFAULT_CONFIG.copy()
cfg["learning_rate_scheduler"] = constant_schedule
cfg["learning_rate_scheduler_kwargs"] = {"value": 1e-4}
.. tab:: skrl scheduler
.. code-block:: python
:emphasize-lines: 2, 5-6
# import the scheduler class
from skrl.resources.schedulers.jax import KLAdaptiveLR # or kl_adaptive (Optax style)
cfg = DEFAULT_CONFIG.copy()
cfg["learning_rate_scheduler"] = KLAdaptiveLR
cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.01}
|
Toni-SM/skrl/docs/source/api/resources/preprocessors.rst | Preprocessors
=============
.. toctree::
:hidden:
Running standard scaler <preprocessors/running_standard_scaler>
Preprocessors are functions used to transform or encode raw input data into a form more suitable for the learning algorithm.
.. raw:: html
<br><hr>
.. list-table::
:header-rows: 1
* - Preprocessors
- .. centered:: |_4| |pytorch| |_4|
- .. centered:: |_4| |jax| |_4|
* - :doc:`Running standard scaler <preprocessors/running_standard_scaler>` |_4|
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\blacksquare`
|
Toni-SM/skrl/docs/source/api/resources/optimizers.rst | Optimizers
==========
.. toctree::
:hidden:
Adam <optimizers/adam>
Optimizers are algorithms that adjust the parameters of artificial neural networks to minimize the error or loss function during the training process.
.. raw:: html
<br><hr>
.. list-table::
:header-rows: 1
* - Optimizers
- .. centered:: |_4| |pytorch| |_4|
- .. centered:: |_4| |jax| |_4|
* - :doc:`Adam <optimizers/adam>`\ |_5| |_5| |_5| |_5| |_5| |_5| |_3|
- .. centered:: :math:`\scriptscriptstyle \texttt{PyTorch}`
- .. centered:: :math:`\blacksquare`
|
Toni-SM/skrl/docs/source/api/resources/schedulers/kl_adaptive.rst | KL Adaptive
===========
Adjust the learning rate according to the value of the Kullback-Leibler (KL) divergence.
.. raw:: html
<br><hr>
Algorithm
---------
.. raw:: html
<br>
Algorithm implementation
^^^^^^^^^^^^^^^^^^^^^^^^
The learning rate (:math:`\eta`) at each step is modified as follows:
| **IF** :math:`\; KL >` :guilabel:`kl_factor` :guilabel:`kl_threshold` **THEN**
| :math:`\eta_{t + 1} = \max(\eta_t \,/` :guilabel:`lr_factor` :math:`,` :guilabel:`min_lr` :math:`)`
| **IF** :math:`\; KL <` :guilabel:`kl_threshold` :math:`/` :guilabel:`kl_factor` **THEN**
| :math:`\eta_{t + 1} = \min(` :guilabel:`lr_factor` :math:`\eta_t,` :guilabel:`max_lr` :math:`)`
.. raw:: html
<br>
Usage
-----
The learning rate scheduler usage is defined in each agent's configuration dictionary. The scheduler class is set under the :literal:`"learning_rate_scheduler"` key and its arguments are set under the :literal:`"learning_rate_scheduler_kwargs"` key as a keyword argument dictionary, without specifying the optimizer (first argument). The following examples show how to set the scheduler for an agent:
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. code-block:: python
:emphasize-lines: 2, 5-6
# import the scheduler class
from skrl.resources.schedulers.torch import KLAdaptiveLR
cfg = DEFAULT_CONFIG.copy()
cfg["learning_rate_scheduler"] = KLAdaptiveLR
cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.01}
.. group-tab:: |_4| |jax| |_4|
.. code-block:: python
:emphasize-lines: 2, 5-6
# import the scheduler class
from skrl.resources.schedulers.jax import KLAdaptiveLR # or kl_adaptive (Optax style)
cfg = DEFAULT_CONFIG.copy()
cfg["learning_rate_scheduler"] = KLAdaptiveLR
cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.01}
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.resources.schedulers.torch.kl_adaptive.KLAdaptiveLR
:show-inheritance:
:inherited-members:
:members:
.. automethod:: __init__
.. raw:: html
<br>
API (JAX)
---------
.. autoclass:: skrl.resources.schedulers.jax.kl_adaptive.KLAdaptiveLR
:show-inheritance:
:inherited-members:
:members:
.. automethod:: __init__
|
Toni-SM/skrl/docs/source/api/resources/preprocessors/running_standard_scaler.rst | Running standard scaler
=======================
Standardize input features by removing the mean and scaling to unit variance.
.. raw:: html
<br><hr>
Algorithm
---------
.. raw:: html
<br>
Algorithm implementation
^^^^^^^^^^^^^^^^^^^^^^^^
| Main notation/symbols:
| - mean (:math:`\bar{x}`), standard deviation (:math:`\sigma`), variance (:math:`\sigma^2`)
| - running mean (:math:`\bar{x}_t`), running variance (:math:`\sigma^2_t`)
|
**Standardization by centering and scaling**
| :math:`\text{clip}((x - \bar{x}_t) / (\sqrt{\sigma^2} \;+` :guilabel:`epsilon` :math:`), -c, c) \qquad` with :math:`c` as :guilabel:`clip_threshold`
|
**Scale back the data to the original representation (inverse transform)**
| :math:`\sqrt{\sigma^2_t} \; \text{clip}(x, -c, c) + \bar{x}_t \qquad` with :math:`c` as :guilabel:`clip_threshold`
|
**Update the running mean and variance** (See `parallel algorithm <https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm>`_)
| :math:`\delta \leftarrow x - \bar{x}_t`
| :math:`n_T \leftarrow n_t + n`
| :math:`M2 \leftarrow (\sigma^2_t n_t) + (\sigma^2 n) + \delta^2 \dfrac{n_t n}{n_T}`
| :green:`# update internal variables`
| :math:`\bar{x}_t \leftarrow \bar{x}_t + \delta \dfrac{n}{n_T}`
| :math:`\sigma^2_t \leftarrow \dfrac{M2}{n_T}`
| :math:`n_t \leftarrow n_T`
.. raw:: html
<br>
Usage
-----
The preprocessors usage is defined in each agent's configuration dictionary.
The preprocessor class is set under the :literal:`"<variable>_preprocessor"` key and its arguments are set under the :literal:`"<variable>_preprocessor_kwargs"` key as a keyword argument dictionary. The following examples show how to set the preprocessors for an agent:
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. code-block:: python
:emphasize-lines: 2, 5-8
# import the preprocessor class
from skrl.resources.preprocessors.torch import RunningStandardScaler
cfg = DEFAULT_CONFIG.copy()
cfg["state_preprocessor"] = RunningStandardScaler
cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device}
cfg["value_preprocessor"] = RunningStandardScaler
cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device}
.. group-tab:: |_4| |jax| |_4|
.. code-block:: python
:emphasize-lines: 2, 5-8
# import the preprocessor class
from skrl.resources.preprocessors.jax import RunningStandardScaler
cfg = DEFAULT_CONFIG.copy()
cfg["state_preprocessor"] = RunningStandardScaler
cfg["state_preprocessor_kwargs"] = {"size": env.observation_space}
cfg["value_preprocessor"] = RunningStandardScaler
cfg["value_preprocessor_kwargs"] = {"size": 1}
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.resources.preprocessors.torch.running_standard_scaler.RunningStandardScaler
:private-members: _parallel_variance, _get_space_size
:members:
.. automethod:: __init__
.. raw:: html
<br>
API (JAX)
---------
.. autoclass:: skrl.resources.preprocessors.jax.running_standard_scaler.RunningStandardScaler
:undoc-members:
:private-members: _parallel_variance, _get_space_size
:members:
.. automethod:: __init__
.. automethod:: __call__
|
Toni-SM/skrl/docs/source/api/resources/noises/ornstein_uhlenbeck.rst | .. _ornstein-uhlenbeck-noise:
Ornstein-Uhlenbeck noise
========================
Noise generated by a stochastic process that is characterized by its mean-reverting behavior.
.. raw:: html
<br><hr>
Usage
-----
The noise usage is defined in each agent's configuration dictionary. A noise instance is set under the :literal:`"noise"` sub-key. The following examples show how to set the noise for an agent:
|
.. image:: ../../../_static/imgs/noise_ornstein_uhlenbeck.png
:width: 75%
:align: center
:alt: Ornstein-Uhlenbeck noise
.. raw:: html
<br><br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../../../snippets/noises.py
:language: python
:emphasize-lines: 1, 4
:start-after: [torch-start-ornstein-uhlenbeck]
:end-before: [torch-end-ornstein-uhlenbeck]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../../../snippets/noises.py
:language: python
:emphasize-lines: 1, 4
:start-after: [jax-start-ornstein-uhlenbeck]
:end-before: [jax-end-ornstein-uhlenbeck]
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.resources.noises.torch.ornstein_uhlenbeck.OrnsteinUhlenbeckNoise
:undoc-members:
:show-inheritance:
:inherited-members:
:private-members: _update
:members:
.. automethod:: __init__
.. raw:: html
<br>
API (JAX)
---------
.. autoclass:: skrl.resources.noises.jax.ornstein_uhlenbeck.OrnsteinUhlenbeckNoise
:undoc-members:
:show-inheritance:
:inherited-members:
:private-members: _update
:members:
.. automethod:: __init__
|
Toni-SM/skrl/docs/source/api/resources/noises/gaussian.rst | .. _gaussian-noise:
Gaussian noise
==============
Noise generated by normal distribution.
.. raw:: html
<br><hr>
Usage
-----
The noise usage is defined in each agent's configuration dictionary. A noise instance is set under the :literal:`"noise"` sub-key. The following examples show how to set the noise for an agent:
|
.. image:: ../../../_static/imgs/noise_gaussian.png
:width: 75%
:align: center
:alt: Gaussian noise
.. raw:: html
<br><br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../../../snippets/noises.py
:language: python
:emphasize-lines: 1, 4
:start-after: [torch-start-gaussian]
:end-before: [torch-end-gaussian]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../../../snippets/noises.py
:language: python
:emphasize-lines: 1, 4
:start-after: [jax-start-gaussian]
:end-before: [jax-end-gaussian]
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.resources.noises.torch.gaussian.GaussianNoise
:undoc-members:
:show-inheritance:
:inherited-members:
:private-members: _update
:members:
.. automethod:: __init__
.. raw:: html
<br>
API (JAX)
---------
.. autoclass:: skrl.resources.noises.jax.gaussian.GaussianNoise
:undoc-members:
:show-inheritance:
:inherited-members:
:private-members: _update
:members:
.. automethod:: __init__
|
Toni-SM/skrl/docs/source/api/resources/optimizers/adam.rst | Adam
====
An extension of the stochastic gradient descent algorithm that adaptively changes the learning rate for each neural network parameter.
.. raw:: html
<br><hr>
Usage
-----
.. note::
This class is the result of isolating the Optax optimizer that is mixed with the model parameters, as defined in the `Flax's TrainState <https://flax.readthedocs.io/en/latest/api_reference/flax.training.html#train-state>`_ class. It is not intended to be used directly by the user, but by agent implementations.
.. tabs::
.. group-tab:: |_4| |jax| |_4|
.. code-block:: python
:emphasize-lines: 2, 5, 8
# import the optimizer class
from skrl.resources.optimizers.jax import Adam
# instantiate the optimizer
optimizer = Adam(model=model, lr=1e-3)
# step the optimizer
optimizer = optimizer.step(grad, model)
.. raw:: html
<br>
API (JAX)
---------
.. autoclass:: skrl.resources.optimizers.jax.adam.Adam
:show-inheritance:
:inherited-members:
:members:
.. automethod:: __new__
|
Toni-SM/skrl/docs/source/api/trainers/step.rst | Step trainer
============
Train agents controlling the training/evaluation loop step-by-step.
.. raw:: html
<br><hr>
Concept
-------
.. image:: ../../_static/imgs/manual_trainer-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Step-by-step trainer
.. image:: ../../_static/imgs/manual_trainer-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Step-by-step trainer
.. raw:: html
<br>
Usage
-----
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../../snippets/trainer.py
:language: python
:start-after: [pytorch-start-step]
:end-before: [pytorch-end-step]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../../snippets/trainer.py
:language: python
:start-after: [jax-start-step]
:end-before: [jax-end-step]
.. raw:: html
<br>
Configuration
-------------
.. literalinclude:: ../../../../skrl/trainers/torch/step.py
:language: python
:start-after: [start-config-dict-torch]
:end-before: [end-config-dict-torch]
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.trainers.torch.step.STEP_TRAINER_DEFAULT_CONFIG
.. autoclass:: skrl.trainers.torch.step.StepTrainer
:undoc-members:
:show-inheritance:
:inherited-members:
:members:
.. automethod:: __init__
.. raw:: html
<br>
API (JAX)
---------
.. autoclass:: skrl.trainers.jax.step.STEP_TRAINER_DEFAULT_CONFIG
.. autoclass:: skrl.trainers.jax.step.StepTrainer
:undoc-members:
:show-inheritance:
:inherited-members:
:members:
.. automethod:: __init__
|
Toni-SM/skrl/docs/source/api/trainers/sequential.rst | Sequential trainer
==================
Train agents sequentially (i.e., one after the other in each interaction with the environment).
.. raw:: html
<br><hr>
Concept
-------
.. image:: ../../_static/imgs/sequential_trainer-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Sequential trainer
.. image:: ../../_static/imgs/sequential_trainer-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Sequential trainer
.. raw:: html
<br>
Usage
-----
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../../snippets/trainer.py
:language: python
:start-after: [pytorch-start-sequential]
:end-before: [pytorch-end-sequential]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../../snippets/trainer.py
:language: python
:start-after: [jax-start-sequential]
:end-before: [jax-end-sequential]
.. raw:: html
<br>
Configuration
-------------
.. literalinclude:: ../../../../skrl/trainers/torch/sequential.py
:language: python
:start-after: [start-config-dict-torch]
:end-before: [end-config-dict-torch]
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.trainers.torch.sequential.SEQUENTIAL_TRAINER_DEFAULT_CONFIG
.. autoclass:: skrl.trainers.torch.sequential.SequentialTrainer
:undoc-members:
:show-inheritance:
:inherited-members:
:members:
.. automethod:: __init__
.. raw:: html
<br>
API (JAX)
---------
.. autoclass:: skrl.trainers.jax.sequential.SEQUENTIAL_TRAINER_DEFAULT_CONFIG
.. autoclass:: skrl.trainers.jax.sequential.SequentialTrainer
:undoc-members:
:show-inheritance:
:inherited-members:
:members:
.. automethod:: __init__
|
Toni-SM/skrl/docs/source/api/trainers/manual.rst | Manual training
===============
Train agents by manually controlling the training/evaluation loop.
.. raw:: html
<br><hr>
Concept
-------
.. image:: ../../_static/imgs/manual_trainer-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Manual trainer
.. image:: ../../_static/imgs/manual_trainer-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Manual trainer
.. raw:: html
<br>
Usage
-----
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: Training
.. literalinclude:: ../../snippets/trainer.py
:language: python
:start-after: [pytorch-start-manual-training]
:end-before: [pytorch-end-manual-training]
.. group-tab:: Evaluation
.. literalinclude:: ../../snippets/trainer.py
:language: python
:start-after: [pytorch-start-manual-evaluation]
:end-before: [pytorch-end-manual-evaluation]
.. group-tab:: |_4| |jax| |_4|
.. tabs::
.. group-tab:: Training
.. literalinclude:: ../../snippets/trainer.py
:language: python
:start-after: [jax-start-manual-training]
:end-before: [jax-end-manual-training]
.. group-tab:: Evaluation
.. literalinclude:: ../../snippets/trainer.py
:language: python
:start-after: [jax-start-manual-evaluation]
:end-before: [jax-end-manual-evaluation]
.. raw:: html
<br>
|
Toni-SM/skrl/docs/source/api/trainers/parallel.rst | Parallel trainer
================
Train agents in parallel using multiple processes.
.. raw:: html
<br><hr>
Concept
-------
.. image:: ../../_static/imgs/parallel_trainer-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Parallel trainer
.. image:: ../../_static/imgs/parallel_trainer-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Parallel trainer
.. raw:: html
<br>
Usage
-----
.. note::
Each process adds a GPU memory overhead (~1GB, although it can be much higher) due to PyTorch's CUDA kernels. See PyTorch `Issue #12873 <https://github.com/pytorch/pytorch/issues/12873>`_ for more details
.. note::
At the moment, only simultaneous training and evaluation of agents with local memory (no memory sharing) is implemented
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../../snippets/trainer.py
:language: python
:start-after: [pytorch-start-parallel]
:end-before: [pytorch-end-parallel]
.. raw:: html
<br>
Configuration
-------------
.. literalinclude:: ../../../../skrl/trainers/torch/parallel.py
:language: python
:start-after: [start-config-dict-torch]
:end-before: [end-config-dict-torch]
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.trainers.torch.parallel.PARALLEL_TRAINER_DEFAULT_CONFIG
.. autoclass:: skrl.trainers.torch.parallel.ParallelTrainer
:undoc-members:
:show-inheritance:
:inherited-members:
:members:
.. automethod:: __init__
|
Toni-SM/skrl/docs/source/api/models/categorical.rst | .. _models_categorical:
Categorical model
=================
Categorical models run **discrete-domain stochastic** policies.
.. raw:: html
<br><hr>
skrl provides a Python mixin (:literal:`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 :ref:`Model <models_base_class>` base class at the end.
* The :ref:`Model <models_base_class>` base class constructor must be invoked before the mixins constructor.
.. warning::
For models in JAX/Flax it is imperative to define all parameters (except ``observation_space``, ``action_space`` and ``device``) with default values to avoid errors (``TypeError: __init__() missing N required positional argument``) during initialization.
In addition, it is necessary to initialize the model's ``state_dict`` (via the ``init_state_dict`` method) after its instantiation to avoid errors (``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'``) during its use.
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../../snippets/categorical_model.py
:language: python
:emphasize-lines: 1, 3-4
:start-after: [start-definition-torch]
:end-before: [end-definition-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../../snippets/categorical_model.py
:language: python
:emphasize-lines: 1, 3-4
:start-after: [start-definition-jax]
:end-before: [end-definition-jax]
.. raw:: html
<br>
Concept
-------
.. image:: ../../_static/imgs/model_categorical-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Categorical model
.. image:: ../../_static/imgs/model_categorical-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Categorical model
.. raw:: html
<br>
Usage
-----
* Multi-Layer Perceptron (**MLP**)
* Convolutional Neural Network (**CNN**)
* Recurrent Neural Network (**RNN**)
* Gated Recurrent Unit RNN (**GRU**)
* Long Short-Term Memory RNN (**LSTM**)
.. tabs::
.. tab:: MLP
.. image:: ../../_static/imgs/model_categorical_mlp-light.svg
:width: 40%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_categorical_mlp-dark.svg
:width: 40%
:align: center
:class: only-dark
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/categorical_model.py
:language: python
:start-after: [start-mlp-sequential-torch]
:end-before: [end-mlp-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/categorical_model.py
:language: python
:start-after: [start-mlp-functional-torch]
:end-before: [end-mlp-functional-torch]
.. group-tab:: |_4| |jax| |_4|
.. tabs::
.. group-tab:: setup-style
.. literalinclude:: ../../snippets/categorical_model.py
:language: python
:start-after: [start-mlp-setup-jax]
:end-before: [end-mlp-setup-jax]
.. group-tab:: compact-style
.. literalinclude:: ../../snippets/categorical_model.py
:language: python
:start-after: [start-mlp-compact-jax]
:end-before: [end-mlp-compact-jax]
.. tab:: CNN
.. image:: ../../_static/imgs/model_categorical_cnn-light.svg
:width: 100%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_categorical_cnn-dark.svg
:width: 100%
:align: center
:class: only-dark
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/categorical_model.py
:language: python
:start-after: [start-cnn-sequential-torch]
:end-before: [end-cnn-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/categorical_model.py
:language: python
:start-after: [start-cnn-functional-torch]
:end-before: [end-cnn-functional-torch]
.. group-tab:: |_4| |jax| |_4|
.. tabs::
.. group-tab:: setup-style
.. literalinclude:: ../../snippets/categorical_model.py
:language: python
:start-after: [start-cnn-setup-jax]
:end-before: [end-cnn-setup-jax]
.. group-tab:: compact-style
.. literalinclude:: ../../snippets/categorical_model.py
:language: python
:start-after: [start-cnn-compact-jax]
:end-before: [end-cnn-compact-jax]
.. tab:: RNN
.. image:: ../../_static/imgs/model_categorical_rnn-light.svg
:width: 90%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_categorical_rnn-dark.svg
:width: 90%
:align: center
:class: only-dark
where:
.. math::
\begin{aligned}
N ={} & \text{batch size} \\
L ={} & \text{sequence length} \\
D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\
H_{in} ={} & \text{input_size} \\
H_{out} ={} & \text{hidden_size}
\end{aligned}
.. raw:: html
<hr>
The following points are relevant in the definition of recurrent models:
* The ``.get_specification()`` method must be overwritten to return, under a dictionary key ``"rnn"``, a sub-dictionary that includes the sequence length (under key ``"sequence_length"``) as a number and a list of the dimensions (under key ``"sizes"``) of each initial hidden state
* The ``.compute()`` method's ``inputs`` parameter will have, at least, the following items in the dictionary:
* ``"states"``: state of the environment used to make the decision
* ``"taken_actions"``: actions taken by the policy for the given states, if applicable
* ``"terminated"``: episode termination status for sampled environment transitions. This key is only defined during the training process
* ``"rnn"``: list of initial hidden states ordered according to the model specification
* The ``.compute()`` method must include, under the ``"rnn"`` key of the returned dictionary, a list of each final hidden state
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/categorical_model.py
:language: python
:start-after: [start-rnn-sequential-torch]
:end-before: [end-rnn-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/categorical_model.py
:language: python
:start-after: [start-rnn-functional-torch]
:end-before: [end-rnn-functional-torch]
.. tab:: GRU
.. image:: ../../_static/imgs/model_categorical_rnn-light.svg
:width: 90%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_categorical_rnn-dark.svg
:width: 90%
:align: center
:class: only-dark
where:
.. math::
\begin{aligned}
N ={} & \text{batch size} \\
L ={} & \text{sequence length} \\
D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\
H_{in} ={} & \text{input_size} \\
H_{out} ={} & \text{hidden_size}
\end{aligned}
.. raw:: html
<hr>
The following points are relevant in the definition of recurrent models:
* The ``.get_specification()`` method must be overwritten to return, under a dictionary key ``"rnn"``, a sub-dictionary that includes the sequence length (under key ``"sequence_length"``) as a number and a list of the dimensions (under key ``"sizes"``) of each initial hidden state
* The ``.compute()`` method's ``inputs`` parameter will have, at least, the following items in the dictionary:
* ``"states"``: state of the environment used to make the decision
* ``"taken_actions"``: actions taken by the policy for the given states, if applicable
* ``"terminated"``: episode termination status for sampled environment transitions. This key is only defined during the training process
* ``"rnn"``: list of initial hidden states ordered according to the model specification
* The ``.compute()`` method must include, under the ``"rnn"`` key of the returned dictionary, a list of each final hidden state
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/categorical_model.py
:language: python
:start-after: [start-gru-sequential-torch]
:end-before: [end-gru-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/categorical_model.py
:language: python
:start-after: [start-gru-functional-torch]
:end-before: [end-gru-functional-torch]
.. tab:: LSTM
.. image:: ../../_static/imgs/model_categorical_rnn-light.svg
:width: 90%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_categorical_rnn-dark.svg
:width: 90%
:align: center
:class: only-dark
where:
.. math::
\begin{aligned}
N ={} & \text{batch size} \\
L ={} & \text{sequence length} \\
D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\
H_{in} ={} & \text{input_size} \\
H_{cell} ={} & \text{hidden_size} \\
H_{out} ={} & \text{proj_size if } \text{proj_size}>0 \text{ otherwise hidden_size} \\
\end{aligned}
.. raw:: html
<hr>
The following points are relevant in the definition of recurrent models:
* The ``.get_specification()`` method must be overwritten to return, under a dictionary key ``"rnn"``, a sub-dictionary that includes the sequence length (under key ``"sequence_length"``) as a number and a list of the dimensions (under key ``"sizes"``) of each initial hidden/cell states
* The ``.compute()`` method's ``inputs`` parameter will have, at least, the following items in the dictionary:
* ``"states"``: state of the environment used to make the decision
* ``"taken_actions"``: actions taken by the policy for the given states, if applicable
* ``"terminated"``: episode termination status for sampled environment transitions. This key is only defined during the training process
* ``"rnn"``: list of initial hidden/cell states ordered according to the model specification
* The ``.compute()`` method must include, under the ``"rnn"`` key of the returned dictionary, a list of each final hidden/cell states
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/categorical_model.py
:language: python
:start-after: [start-lstm-sequential-torch]
:end-before: [end-lstm-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/categorical_model.py
:language: python
:start-after: [start-lstm-functional-torch]
:end-before: [end-lstm-functional-torch]
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.models.torch.categorical.CategoricalMixin
:show-inheritance:
:members:
.. automethod:: __init__
.. raw:: html
<br>
API (JAX)
---------
.. autoclass:: skrl.models.jax.categorical.CategoricalMixin
:show-inheritance:
:members:
.. automethod:: __init__
|
Toni-SM/skrl/docs/source/api/models/multivariate_gaussian.rst | .. _models_multivariate_gaussian:
Multivariate Gaussian model
===========================
Multivariate Gaussian models run **continuous-domain stochastic** policies.
.. raw:: html
<br><hr>
skrl provides a Python mixin (:literal:`MultivariateGaussianMixin`) 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 :ref:`Model <models_base_class>` base class at the end.
* The :ref:`Model <models_base_class>` base class constructor must be invoked before the mixins constructor.
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../../snippets/multivariate_gaussian_model.py
:language: python
:emphasize-lines: 1, 4-5
:start-after: [start-definition-torch]
:end-before: [end-definition-torch]
.. raw:: html
<br>
Concept
-------
.. image:: ../../_static/imgs/model_multivariate_gaussian-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Multivariate Gaussian model
.. image:: ../../_static/imgs/model_multivariate_gaussian-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Multivariate Gaussian model
.. raw:: html
<br>
Usage
-----
* Multi-Layer Perceptron (**MLP**)
* Convolutional Neural Network (**CNN**)
* Recurrent Neural Network (**RNN**)
* Gated Recurrent Unit RNN (**GRU**)
* Long Short-Term Memory RNN (**LSTM**)
.. tabs::
.. tab:: MLP
.. image:: ../../_static/imgs/model_gaussian_mlp-light.svg
:width: 42%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_gaussian_mlp-dark.svg
:width: 42%
:align: center
:class: only-dark
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/multivariate_gaussian_model.py
:language: python
:start-after: [start-mlp-sequential-torch]
:end-before: [end-mlp-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/multivariate_gaussian_model.py
:language: python
:start-after: [start-mlp-functional-torch]
:end-before: [end-mlp-functional-torch]
.. tab:: CNN
.. image:: ../../_static/imgs/model_gaussian_cnn-light.svg
:width: 100%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_gaussian_cnn-dark.svg
:width: 100%
:align: center
:class: only-dark
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/multivariate_gaussian_model.py
:language: python
:start-after: [start-cnn-sequential-torch]
:end-before: [end-cnn-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/multivariate_gaussian_model.py
:language: python
:start-after: [start-cnn-functional-torch]
:end-before: [end-cnn-functional-torch]
.. tab:: RNN
.. image:: ../../_static/imgs/model_gaussian_rnn-light.svg
:width: 90%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_gaussian_rnn-dark.svg
:width: 90%
:align: center
:class: only-dark
where:
.. math::
\begin{aligned}
N ={} & \text{batch size} \\
L ={} & \text{sequence length} \\
D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\
H_{in} ={} & \text{input_size} \\
H_{out} ={} & \text{hidden_size}
\end{aligned}
.. raw:: html
<hr>
The following points are relevant in the definition of recurrent models:
* The ``.get_specification()`` method must be overwritten to return, under a dictionary key ``"rnn"``, a sub-dictionary that includes the sequence length (under key ``"sequence_length"``) as a number and a list of the dimensions (under key ``"sizes"``) of each initial hidden state
* The ``.compute()`` method's ``inputs`` parameter will have, at least, the following items in the dictionary:
* ``"states"``: state of the environment used to make the decision
* ``"taken_actions"``: actions taken by the policy for the given states, if applicable
* ``"terminated"``: episode termination status for sampled environment transitions. This key is only defined during the training process
* ``"rnn"``: list of initial hidden states ordered according to the model specification
* The ``.compute()`` method must include, under the ``"rnn"`` key of the returned dictionary, a list of each final hidden state
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/multivariate_gaussian_model.py
:language: python
:start-after: [start-rnn-sequential-torch]
:end-before: [end-rnn-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/multivariate_gaussian_model.py
:language: python
:start-after: [start-rnn-functional-torch]
:end-before: [end-rnn-functional-torch]
.. tab:: GRU
.. image:: ../../_static/imgs/model_gaussian_rnn-light.svg
:width: 90%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_gaussian_rnn-dark.svg
:width: 90%
:align: center
:class: only-dark
where:
.. math::
\begin{aligned}
N ={} & \text{batch size} \\
L ={} & \text{sequence length} \\
D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\
H_{in} ={} & \text{input_size} \\
H_{out} ={} & \text{hidden_size}
\end{aligned}
.. raw:: html
<hr>
The following points are relevant in the definition of recurrent models:
* The ``.get_specification()`` method must be overwritten to return, under a dictionary key ``"rnn"``, a sub-dictionary that includes the sequence length (under key ``"sequence_length"``) as a number and a list of the dimensions (under key ``"sizes"``) of each initial hidden state
* The ``.compute()`` method's ``inputs`` parameter will have, at least, the following items in the dictionary:
* ``"states"``: state of the environment used to make the decision
* ``"taken_actions"``: actions taken by the policy for the given states, if applicable
* ``"terminated"``: episode termination status for sampled environment transitions. This key is only defined during the training process
* ``"rnn"``: list of initial hidden states ordered according to the model specification
* The ``.compute()`` method must include, under the ``"rnn"`` key of the returned dictionary, a list of each final hidden state
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/multivariate_gaussian_model.py
:language: python
:start-after: [start-gru-sequential-torch]
:end-before: [end-gru-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/multivariate_gaussian_model.py
:language: python
:start-after: [start-gru-functional-torch]
:end-before: [end-gru-functional-torch]
.. tab:: LSTM
.. image:: ../../_static/imgs/model_gaussian_rnn-light.svg
:width: 90%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_gaussian_rnn-dark.svg
:width: 90%
:align: center
:class: only-dark
where:
.. math::
\begin{aligned}
N ={} & \text{batch size} \\
L ={} & \text{sequence length} \\
D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\
H_{in} ={} & \text{input_size} \\
H_{cell} ={} & \text{hidden_size} \\
H_{out} ={} & \text{proj_size if } \text{proj_size}>0 \text{ otherwise hidden_size} \\
\end{aligned}
.. raw:: html
<hr>
The following points are relevant in the definition of recurrent models:
* The ``.get_specification()`` method must be overwritten to return, under a dictionary key ``"rnn"``, a sub-dictionary that includes the sequence length (under key ``"sequence_length"``) as a number and a list of the dimensions (under key ``"sizes"``) of each initial hidden/cell states
* The ``.compute()`` method's ``inputs`` parameter will have, at least, the following items in the dictionary:
* ``"states"``: state of the environment used to make the decision
* ``"taken_actions"``: actions taken by the policy for the given states, if applicable
* ``"terminated"``: episode termination status for sampled environment transitions. This key is only defined during the training process
* ``"rnn"``: list of initial hidden/cell states ordered according to the model specification
* The ``.compute()`` method must include, under the ``"rnn"`` key of the returned dictionary, a list of each final hidden/cell states
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/multivariate_gaussian_model.py
:language: python
:start-after: [start-lstm-sequential-torch]
:end-before: [end-lstm-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/multivariate_gaussian_model.py
:language: python
:start-after: [start-lstm-functional-torch]
:end-before: [end-lstm-functional-torch]
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.models.torch.multivariate_gaussian.MultivariateGaussianMixin
:show-inheritance:
:members:
.. automethod:: __init__
|
Toni-SM/skrl/docs/source/api/models/multicategorical.rst | .. _models_multicategorical:
Multi-Categorical model
=======================
Multi-Categorical models run **discrete-domain stochastic** policies.
.. raw:: html
<br><hr>
skrl provides a Python mixin (:literal:`MultiCategoricalMixin`) 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 :ref:`Model <models_base_class>` base class at the end.
* The :ref:`Model <models_base_class>` base class constructor must be invoked before the mixins constructor.
.. warning::
For models in JAX/Flax it is imperative to define all parameters (except ``observation_space``, ``action_space`` and ``device``) with default values to avoid errors (``TypeError: __init__() missing N required positional argument``) during initialization.
In addition, it is necessary to initialize the model's ``state_dict`` (via the ``init_state_dict`` method) after its instantiation to avoid errors (``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'``) during its use.
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../../snippets/multicategorical_model.py
:language: python
:emphasize-lines: 1, 3-4
:start-after: [start-definition-torch]
:end-before: [end-definition-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../../snippets/multicategorical_model.py
:language: python
:emphasize-lines: 1, 3-4
:start-after: [start-definition-jax]
:end-before: [end-definition-jax]
.. raw:: html
<br>
Concept
-------
.. image:: ../../_static/imgs/model_multicategorical-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Multi-Categorical model
.. image:: ../../_static/imgs/model_multicategorical-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Multi-Categorical model
.. raw:: html
<br>
Usage
-----
* Multi-Layer Perceptron (**MLP**)
* Convolutional Neural Network (**CNN**)
* Recurrent Neural Network (**RNN**)
* Gated Recurrent Unit RNN (**GRU**)
* Long Short-Term Memory RNN (**LSTM**)
.. tabs::
.. tab:: MLP
.. image:: ../../_static/imgs/model_categorical_mlp-light.svg
:width: 40%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_categorical_mlp-dark.svg
:width: 40%
:align: center
:class: only-dark
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/multicategorical_model.py
:language: python
:start-after: [start-mlp-sequential-torch]
:end-before: [end-mlp-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/multicategorical_model.py
:language: python
:start-after: [start-mlp-functional-torch]
:end-before: [end-mlp-functional-torch]
.. group-tab:: |_4| |jax| |_4|
.. tabs::
.. group-tab:: setup-style
.. literalinclude:: ../../snippets/multicategorical_model.py
:language: python
:start-after: [start-mlp-setup-jax]
:end-before: [end-mlp-setup-jax]
.. group-tab:: compact-style
.. literalinclude:: ../../snippets/multicategorical_model.py
:language: python
:start-after: [start-mlp-compact-jax]
:end-before: [end-mlp-compact-jax]
.. tab:: CNN
.. image:: ../../_static/imgs/model_categorical_cnn-light.svg
:width: 100%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_categorical_cnn-dark.svg
:width: 100%
:align: center
:class: only-dark
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/multicategorical_model.py
:language: python
:start-after: [start-cnn-sequential-torch]
:end-before: [end-cnn-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/multicategorical_model.py
:language: python
:start-after: [start-cnn-functional-torch]
:end-before: [end-cnn-functional-torch]
.. group-tab:: |_4| |jax| |_4|
.. tabs::
.. group-tab:: setup-style
.. literalinclude:: ../../snippets/multicategorical_model.py
:language: python
:start-after: [start-cnn-setup-jax]
:end-before: [end-cnn-setup-jax]
.. group-tab:: compact-style
.. literalinclude:: ../../snippets/multicategorical_model.py
:language: python
:start-after: [start-cnn-compact-jax]
:end-before: [end-cnn-compact-jax]
.. tab:: RNN
.. image:: ../../_static/imgs/model_categorical_rnn-light.svg
:width: 90%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_categorical_rnn-dark.svg
:width: 90%
:align: center
:class: only-dark
where:
.. math::
\begin{aligned}
N ={} & \text{batch size} \\
L ={} & \text{sequence length} \\
D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\
H_{in} ={} & \text{input_size} \\
H_{out} ={} & \text{hidden_size}
\end{aligned}
.. raw:: html
<hr>
The following points are relevant in the definition of recurrent models:
* The ``.get_specification()`` method must be overwritten to return, under a dictionary key ``"rnn"``, a sub-dictionary that includes the sequence length (under key ``"sequence_length"``) as a number and a list of the dimensions (under key ``"sizes"``) of each initial hidden state
* The ``.compute()`` method's ``inputs`` parameter will have, at least, the following items in the dictionary:
* ``"states"``: state of the environment used to make the decision
* ``"taken_actions"``: actions taken by the policy for the given states, if applicable
* ``"terminated"``: episode termination status for sampled environment transitions. This key is only defined during the training process
* ``"rnn"``: list of initial hidden states ordered according to the model specification
* The ``.compute()`` method must include, under the ``"rnn"`` key of the returned dictionary, a list of each final hidden state
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/multicategorical_model.py
:language: python
:start-after: [start-rnn-sequential-torch]
:end-before: [end-rnn-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/multicategorical_model.py
:language: python
:start-after: [start-rnn-functional-torch]
:end-before: [end-rnn-functional-torch]
.. tab:: GRU
.. image:: ../../_static/imgs/model_categorical_rnn-light.svg
:width: 90%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_categorical_rnn-dark.svg
:width: 90%
:align: center
:class: only-dark
where:
.. math::
\begin{aligned}
N ={} & \text{batch size} \\
L ={} & \text{sequence length} \\
D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\
H_{in} ={} & \text{input_size} \\
H_{out} ={} & \text{hidden_size}
\end{aligned}
.. raw:: html
<hr>
The following points are relevant in the definition of recurrent models:
* The ``.get_specification()`` method must be overwritten to return, under a dictionary key ``"rnn"``, a sub-dictionary that includes the sequence length (under key ``"sequence_length"``) as a number and a list of the dimensions (under key ``"sizes"``) of each initial hidden state
* The ``.compute()`` method's ``inputs`` parameter will have, at least, the following items in the dictionary:
* ``"states"``: state of the environment used to make the decision
* ``"taken_actions"``: actions taken by the policy for the given states, if applicable
* ``"terminated"``: episode termination status for sampled environment transitions. This key is only defined during the training process
* ``"rnn"``: list of initial hidden states ordered according to the model specification
* The ``.compute()`` method must include, under the ``"rnn"`` key of the returned dictionary, a list of each final hidden state
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/multicategorical_model.py
:language: python
:start-after: [start-gru-sequential-torch]
:end-before: [end-gru-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/multicategorical_model.py
:language: python
:start-after: [start-gru-functional-torch]
:end-before: [end-gru-functional-torch]
.. tab:: LSTM
.. image:: ../../_static/imgs/model_categorical_rnn-light.svg
:width: 90%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_categorical_rnn-dark.svg
:width: 90%
:align: center
:class: only-dark
where:
.. math::
\begin{aligned}
N ={} & \text{batch size} \\
L ={} & \text{sequence length} \\
D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\
H_{in} ={} & \text{input_size} \\
H_{cell} ={} & \text{hidden_size} \\
H_{out} ={} & \text{proj_size if } \text{proj_size}>0 \text{ otherwise hidden_size} \\
\end{aligned}
.. raw:: html
<hr>
The following points are relevant in the definition of recurrent models:
* The ``.get_specification()`` method must be overwritten to return, under a dictionary key ``"rnn"``, a sub-dictionary that includes the sequence length (under key ``"sequence_length"``) as a number and a list of the dimensions (under key ``"sizes"``) of each initial hidden/cell states
* The ``.compute()`` method's ``inputs`` parameter will have, at least, the following items in the dictionary:
* ``"states"``: state of the environment used to make the decision
* ``"taken_actions"``: actions taken by the policy for the given states, if applicable
* ``"terminated"``: episode termination status for sampled environment transitions. This key is only defined during the training process
* ``"rnn"``: list of initial hidden/cell states ordered according to the model specification
* The ``.compute()`` method must include, under the ``"rnn"`` key of the returned dictionary, a list of each final hidden/cell states
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/multicategorical_model.py
:language: python
:start-after: [start-lstm-sequential-torch]
:end-before: [end-lstm-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/multicategorical_model.py
:language: python
:start-after: [start-lstm-functional-torch]
:end-before: [end-lstm-functional-torch]
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.models.torch.multicategorical.MultiCategoricalMixin
:show-inheritance:
:members:
.. automethod:: __init__
.. raw:: html
<br>
API (JAX)
---------
.. autoclass:: skrl.models.jax.multicategorical.MultiCategoricalMixin
:show-inheritance:
:members:
.. automethod:: __init__
|
Toni-SM/skrl/docs/source/api/models/tabular.rst | .. _models_tabular:
Tabular model
=============
Tabular models run **discrete-domain deterministic/stochastic** policies.
.. raw:: html
<br><hr>
skrl provides a Python mixin (:literal:`TabularMixin`) to assist in the creation of these types of models, allowing users to have full control over the table definitions. Note that the use of this mixin must comply with the following rules:
* The definition of multiple inheritance must always include the :ref:`Model <models_base_class>` base class at the end.
* The :ref:`Model <models_base_class>` base class constructor must be invoked before the mixins constructor.
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../../snippets/tabular_model.py
:language: python
:emphasize-lines: 1, 3-4
:start-after: [start-definition-torch]
:end-before: [end-definition-torch]
.. raw:: html
<br>
Usage
-----
.. tabs::
.. tab:: :math:`\epsilon`-greedy policy
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../../snippets/tabular_model.py
:language: python
:start-after: [start-epsilon-greedy-torch]
:end-before: [end-epsilon-greedy-torch]
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.models.torch.tabular.TabularMixin
:show-inheritance:
:exclude-members: to, state_dict, load_state_dict, load, save
:members:
.. automethod:: __init__
|
Toni-SM/skrl/docs/source/api/models/deterministic.rst | .. _models_deterministic:
Deterministic model
===================
Deterministic models run **continuous-domain deterministic** policies.
.. raw:: html
<br><hr>
skrl provides a Python mixin (:literal:`DeterministicMixin`) 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 :ref:`Model <models_base_class>` base class at the end.
* The :ref:`Model <models_base_class>` base class constructor must be invoked before the mixins constructor.
.. warning::
For models in JAX/Flax it is imperative to define all parameters (except ``observation_space``, ``action_space`` and ``device``) with default values to avoid errors (``TypeError: __init__() missing N required positional argument``) during initialization.
In addition, it is necessary to initialize the model's ``state_dict`` (via the ``init_state_dict`` method) after its instantiation to avoid errors (``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'``) during its use.
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../../snippets/deterministic_model.py
:language: python
:emphasize-lines: 1, 3-4
:start-after: [start-definition-torch]
:end-before: [end-definition-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../../snippets/deterministic_model.py
:language: python
:emphasize-lines: 1, 3-4
:start-after: [start-definition-jax]
:end-before: [end-definition-jax]
.. raw:: html
<br>
Concept
-------
.. image:: ../../_static/imgs/model_deterministic-light.svg
:width: 65%
:align: center
:class: only-light
:alt: Deterministic model
.. image:: ../../_static/imgs/model_deterministic-dark.svg
:width: 65%
:align: center
:class: only-dark
:alt: Deterministic model
.. raw:: html
<br>
Usage
-----
* Multi-Layer Perceptron (**MLP**)
* Convolutional Neural Network (**CNN**)
* Recurrent Neural Network (**RNN**)
* Gated Recurrent Unit RNN (**GRU**)
* Long Short-Term Memory RNN (**LSTM**)
.. tabs::
.. tab:: MLP
.. image:: ../../_static/imgs/model_deterministic_mlp-light.svg
:width: 35%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_deterministic_mlp-dark.svg
:width: 35%
:align: center
:class: only-dark
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/deterministic_model.py
:language: python
:start-after: [start-mlp-sequential-torch]
:end-before: [end-mlp-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/deterministic_model.py
:language: python
:start-after: [start-mlp-functional-torch]
:end-before: [end-mlp-functional-torch]
.. group-tab:: |_4| |jax| |_4|
.. tabs::
.. group-tab:: setup-style
.. literalinclude:: ../../snippets/deterministic_model.py
:language: python
:start-after: [start-mlp-setup-jax]
:end-before: [end-mlp-setup-jax]
.. group-tab:: compact-style
.. literalinclude:: ../../snippets/deterministic_model.py
:language: python
:start-after: [start-mlp-compact-jax]
:end-before: [end-mlp-compact-jax]
.. tab:: CNN
.. image:: ../../_static/imgs/model_deterministic_cnn-light.svg
:width: 100%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_deterministic_cnn-dark.svg
:width: 100%
:align: center
:class: only-dark
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/deterministic_model.py
:language: python
:start-after: [start-cnn-sequential-torch]
:end-before: [end-cnn-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/deterministic_model.py
:language: python
:start-after: [start-cnn-functional-torch]
:end-before: [end-cnn-functional-torch]
.. group-tab:: |_4| |jax| |_4|
.. tabs::
.. group-tab:: setup-style
.. literalinclude:: ../../snippets/deterministic_model.py
:language: python
:start-after: [start-cnn-setup-jax]
:end-before: [end-cnn-setup-jax]
.. group-tab:: compact-style
.. literalinclude:: ../../snippets/deterministic_model.py
:language: python
:start-after: [start-cnn-compact-jax]
:end-before: [end-cnn-compact-jax]
.. tab:: RNN
.. image:: ../../_static/imgs/model_deterministic_rnn-light.svg
:width: 90%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_deterministic_rnn-dark.svg
:width: 90%
:align: center
:class: only-dark
where:
.. math::
\begin{aligned}
N ={} & \text{batch size} \\
L ={} & \text{sequence length} \\
D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\
H_{in} ={} & \text{input_size} \\
H_{out} ={} & \text{hidden_size}
\end{aligned}
.. raw:: html
<hr>
The following points are relevant in the definition of recurrent models:
* The ``.get_specification()`` method must be overwritten to return, under a dictionary key ``"rnn"``, a sub-dictionary that includes the sequence length (under key ``"sequence_length"``) as a number and a list of the dimensions (under key ``"sizes"``) of each initial hidden state
* The ``.compute()`` method's ``inputs`` parameter will have, at least, the following items in the dictionary:
* ``"states"``: state of the environment used to make the decision
* ``"taken_actions"``: actions taken by the policy for the given states, if applicable
* ``"terminated"``: episode termination status for sampled environment transitions. This key is only defined during the training process
* ``"rnn"``: list of initial hidden states ordered according to the model specification
* The ``.compute()`` method must include, under the ``"rnn"`` key of the returned dictionary, a list of each final hidden state
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/deterministic_model.py
:language: python
:start-after: [start-rnn-sequential-torch]
:end-before: [end-rnn-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/deterministic_model.py
:language: python
:start-after: [start-rnn-functional-torch]
:end-before: [end-rnn-functional-torch]
.. tab:: GRU
.. image:: ../../_static/imgs/model_deterministic_rnn-light.svg
:width: 90%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_deterministic_rnn-dark.svg
:width: 90%
:align: center
:class: only-dark
where:
.. math::
\begin{aligned}
N ={} & \text{batch size} \\
L ={} & \text{sequence length} \\
D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\
H_{in} ={} & \text{input_size} \\
H_{out} ={} & \text{hidden_size}
\end{aligned}
.. raw:: html
<hr>
The following points are relevant in the definition of recurrent models:
* The ``.get_specification()`` method must be overwritten to return, under a dictionary key ``"rnn"``, a sub-dictionary that includes the sequence length (under key ``"sequence_length"``) as a number and a list of the dimensions (under key ``"sizes"``) of each initial hidden state
* The ``.compute()`` method's ``inputs`` parameter will have, at least, the following items in the dictionary:
* ``"states"``: state of the environment used to make the decision
* ``"taken_actions"``: actions taken by the policy for the given states, if applicable
* ``"terminated"``: episode termination status for sampled environment transitions. This key is only defined during the training process
* ``"rnn"``: list of initial hidden states ordered according to the model specification
* The ``.compute()`` method must include, under the ``"rnn"`` key of the returned dictionary, a list of each final hidden state
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/deterministic_model.py
:language: python
:start-after: [start-gru-sequential-torch]
:end-before: [end-gru-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/deterministic_model.py
:language: python
:start-after: [start-gru-functional-torch]
:end-before: [end-gru-functional-torch]
.. tab:: LSTM
.. image:: ../../_static/imgs/model_deterministic_rnn-light.svg
:width: 90%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_deterministic_rnn-dark.svg
:width: 90%
:align: center
:class: only-dark
where:
.. math::
\begin{aligned}
N ={} & \text{batch size} \\
L ={} & \text{sequence length} \\
D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\
H_{in} ={} & \text{input_size} \\
H_{cell} ={} & \text{hidden_size} \\
H_{out} ={} & \text{proj_size if } \text{proj_size}>0 \text{ otherwise hidden_size} \\
\end{aligned}
.. raw:: html
<hr>
The following points are relevant in the definition of recurrent models:
* The ``.get_specification()`` method must be overwritten to return, under a dictionary key ``"rnn"``, a sub-dictionary that includes the sequence length (under key ``"sequence_length"``) as a number and a list of the dimensions (under key ``"sizes"``) of each initial hidden/cell states
* The ``.compute()`` method's ``inputs`` parameter will have, at least, the following items in the dictionary:
* ``"states"``: state of the environment used to make the decision
* ``"taken_actions"``: actions taken by the policy for the given states, if applicable
* ``"terminated"``: episode termination status for sampled environment transitions. This key is only defined during the training process
* ``"rnn"``: list of initial hidden/cell states ordered according to the model specification
* The ``.compute()`` method must include, under the ``"rnn"`` key of the returned dictionary, a list of each final hidden/cell states
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/deterministic_model.py
:language: python
:start-after: [start-lstm-sequential-torch]
:end-before: [end-lstm-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/deterministic_model.py
:language: python
:start-after: [start-lstm-functional-torch]
:end-before: [end-lstm-functional-torch]
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.models.torch.deterministic.DeterministicMixin
:show-inheritance:
:members:
.. automethod:: __init__
.. raw:: html
<br>
API (JAX)
---------
.. autoclass:: skrl.models.jax.deterministic.DeterministicMixin
:show-inheritance:
:members:
.. automethod:: __init__
|
Toni-SM/skrl/docs/source/api/models/shared_model.rst | Shared model
============
Sometimes it is desirable to define models that use shared layers or network to represent multiple function approximators. This practice, known as *shared parameters* (or *parameter sharing*), *shared layers*, *shared model*, *shared networks* or *joint architecture* among others, is typically justified by the following criteria:
* Learning the same characteristics, especially when processing large inputs (such as images, e.g.).
* Reduce the number of parameters in the whole system.
* Make the computation more efficient.
.. raw:: html
<br><hr>
Implementation
--------------
By combining the implemented mixins, it is possible to define shared models with skrl. In these cases, the use of the :literal:`role` argument (a Python string) is relevant. The agents will call the models by setting the :literal:`role` argument according to their requirements. Visit each agent's documentation (*Key* column of the table under *Spaces and models* section) to know the possible values that this parameter can take.
The code snippet below shows how to define a shared model. The following practices for building shared models can be identified:
* The definition of multiple inheritance must always include the :ref:`Model <models_base_class>` base class at the end.
* The :ref:`Model <models_base_class>` base class constructor must be invoked before the mixins constructor.
* All mixin constructors must be invoked.
* Specify :literal:`role` argument is optional if all constructors belong to different mixins.
* If multiple models of the same mixin type are required, the same constructor must be invoked as many times as needed. To do so, it is mandatory to specify the :literal:`role` argument.
* The :literal:`.act(...)` method needs to be overridden to disambiguate its call.
* The same instance of the shared model must be passed to all keys involved.
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../../snippets/shared_model.py
:language: python
:start-after: [start-mlp-torch]
:end-before: [end-mlp-torch]
|
Toni-SM/skrl/docs/source/api/models/gaussian.rst | .. _models_gaussian:
Gaussian model
==============
Gaussian models run **continuous-domain stochastic** policies.
.. raw:: html
<br><hr>
skrl provides a Python mixin (:literal:`GaussianMixin`) 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 :ref:`Model <models_base_class>` base class at the end.
* The :ref:`Model <models_base_class>` base class constructor must be invoked before the mixins constructor.
.. warning::
For models in JAX/Flax it is imperative to define all parameters (except ``observation_space``, ``action_space`` and ``device``) with default values to avoid errors (``TypeError: __init__() missing N required positional argument``) during initialization.
In addition, it is necessary to initialize the model's ``state_dict`` (via the ``init_state_dict`` method) after its instantiation to avoid errors (``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'``) during its use.
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../../snippets/gaussian_model.py
:language: python
:emphasize-lines: 1, 4-5
:start-after: [start-definition-torch]
:end-before: [end-definition-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../../snippets/gaussian_model.py
:language: python
:emphasize-lines: 1, 4-5
:start-after: [start-definition-jax]
:end-before: [end-definition-jax]
.. raw:: html
<br>
Concept
-------
.. image:: ../../_static/imgs/model_gaussian-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Gaussian model
.. image:: ../../_static/imgs/model_gaussian-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Gaussian model
.. raw:: html
<br>
Usage
-----
* Multi-Layer Perceptron (**MLP**)
* Convolutional Neural Network (**CNN**)
* Recurrent Neural Network (**RNN**)
* Gated Recurrent Unit RNN (**GRU**)
* Long Short-Term Memory RNN (**LSTM**)
.. tabs::
.. tab:: MLP
.. image:: ../../_static/imgs/model_gaussian_mlp-light.svg
:width: 42%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_gaussian_mlp-dark.svg
:width: 42%
:align: center
:class: only-dark
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/gaussian_model.py
:language: python
:start-after: [start-mlp-sequential-torch]
:end-before: [end-mlp-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/gaussian_model.py
:language: python
:start-after: [start-mlp-functional-torch]
:end-before: [end-mlp-functional-torch]
.. group-tab:: |_4| |jax| |_4|
.. tabs::
.. group-tab:: setup-style
.. literalinclude:: ../../snippets/gaussian_model.py
:language: python
:start-after: [start-mlp-setup-jax]
:end-before: [end-mlp-setup-jax]
.. group-tab:: compact-style
.. literalinclude:: ../../snippets/gaussian_model.py
:language: python
:start-after: [start-mlp-compact-jax]
:end-before: [end-mlp-compact-jax]
.. tab:: CNN
.. image:: ../../_static/imgs/model_gaussian_cnn-light.svg
:width: 100%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_gaussian_cnn-dark.svg
:width: 100%
:align: center
:class: only-dark
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/gaussian_model.py
:language: python
:start-after: [start-cnn-sequential-torch]
:end-before: [end-cnn-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/gaussian_model.py
:language: python
:start-after: [start-cnn-functional-torch]
:end-before: [end-cnn-functional-torch]
.. group-tab:: |_4| |jax| |_4|
.. tabs::
.. group-tab:: setup-style
.. literalinclude:: ../../snippets/gaussian_model.py
:language: python
:start-after: [start-cnn-setup-jax]
:end-before: [end-cnn-setup-jax]
.. group-tab:: compact-style
.. literalinclude:: ../../snippets/gaussian_model.py
:language: python
:start-after: [start-cnn-compact-jax]
:end-before: [end-cnn-compact-jax]
.. tab:: RNN
.. image:: ../../_static/imgs/model_gaussian_rnn-light.svg
:width: 90%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_gaussian_rnn-dark.svg
:width: 90%
:align: center
:class: only-dark
where:
.. math::
\begin{aligned}
N ={} & \text{batch size} \\
L ={} & \text{sequence length} \\
D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\
H_{in} ={} & \text{input_size} \\
H_{out} ={} & \text{hidden_size}
\end{aligned}
.. raw:: html
<hr>
The following points are relevant in the definition of recurrent models:
* The ``.get_specification()`` method must be overwritten to return, under a dictionary key ``"rnn"``, a sub-dictionary that includes the sequence length (under key ``"sequence_length"``) as a number and a list of the dimensions (under key ``"sizes"``) of each initial hidden state
* The ``.compute()`` method's ``inputs`` parameter will have, at least, the following items in the dictionary:
* ``"states"``: state of the environment used to make the decision
* ``"taken_actions"``: actions taken by the policy for the given states, if applicable
* ``"terminated"``: episode termination status for sampled environment transitions. This key is only defined during the training process
* ``"rnn"``: list of initial hidden states ordered according to the model specification
* The ``.compute()`` method must include, under the ``"rnn"`` key of the returned dictionary, a list of each final hidden state
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/gaussian_model.py
:language: python
:start-after: [start-rnn-sequential-torch]
:end-before: [end-rnn-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/gaussian_model.py
:language: python
:start-after: [start-rnn-functional-torch]
:end-before: [end-rnn-functional-torch]
.. tab:: GRU
.. image:: ../../_static/imgs/model_gaussian_rnn-light.svg
:width: 90%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_gaussian_rnn-dark.svg
:width: 90%
:align: center
:class: only-dark
where:
.. math::
\begin{aligned}
N ={} & \text{batch size} \\
L ={} & \text{sequence length} \\
D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\
H_{in} ={} & \text{input_size} \\
H_{out} ={} & \text{hidden_size}
\end{aligned}
.. raw:: html
<hr>
The following points are relevant in the definition of recurrent models:
* The ``.get_specification()`` method must be overwritten to return, under a dictionary key ``"rnn"``, a sub-dictionary that includes the sequence length (under key ``"sequence_length"``) as a number and a list of the dimensions (under key ``"sizes"``) of each initial hidden state
* The ``.compute()`` method's ``inputs`` parameter will have, at least, the following items in the dictionary:
* ``"states"``: state of the environment used to make the decision
* ``"taken_actions"``: actions taken by the policy for the given states, if applicable
* ``"terminated"``: episode termination status for sampled environment transitions. This key is only defined during the training process
* ``"rnn"``: list of initial hidden states ordered according to the model specification
* The ``.compute()`` method must include, under the ``"rnn"`` key of the returned dictionary, a list of each final hidden state
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/gaussian_model.py
:language: python
:start-after: [start-gru-sequential-torch]
:end-before: [end-gru-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/gaussian_model.py
:language: python
:start-after: [start-gru-functional-torch]
:end-before: [end-gru-functional-torch]
.. tab:: LSTM
.. image:: ../../_static/imgs/model_gaussian_rnn-light.svg
:width: 90%
:align: center
:class: only-light
.. image:: ../../_static/imgs/model_gaussian_rnn-dark.svg
:width: 90%
:align: center
:class: only-dark
where:
.. math::
\begin{aligned}
N ={} & \text{batch size} \\
L ={} & \text{sequence length} \\
D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\
H_{in} ={} & \text{input_size} \\
H_{cell} ={} & \text{hidden_size} \\
H_{out} ={} & \text{proj_size if } \text{proj_size}>0 \text{ otherwise hidden_size} \\
\end{aligned}
.. raw:: html
<hr>
The following points are relevant in the definition of recurrent models:
* The ``.get_specification()`` method must be overwritten to return, under a dictionary key ``"rnn"``, a sub-dictionary that includes the sequence length (under key ``"sequence_length"``) as a number and a list of the dimensions (under key ``"sizes"``) of each initial hidden/cell states
* The ``.compute()`` method's ``inputs`` parameter will have, at least, the following items in the dictionary:
* ``"states"``: state of the environment used to make the decision
* ``"taken_actions"``: actions taken by the policy for the given states, if applicable
* ``"terminated"``: episode termination status for sampled environment transitions. This key is only defined during the training process
* ``"rnn"``: list of initial hidden/cell states ordered according to the model specification
* The ``.compute()`` method must include, under the ``"rnn"`` key of the returned dictionary, a list of each final hidden/cell states
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. tabs::
.. group-tab:: nn.Sequential
.. literalinclude:: ../../snippets/gaussian_model.py
:language: python
:start-after: [start-lstm-sequential-torch]
:end-before: [end-lstm-sequential-torch]
.. group-tab:: nn.functional
.. literalinclude:: ../../snippets/gaussian_model.py
:language: python
:start-after: [start-lstm-functional-torch]
:end-before: [end-lstm-functional-torch]
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.models.torch.gaussian.GaussianMixin
:show-inheritance:
:members:
.. automethod:: __init__
.. raw:: html
<br>
API (JAX)
---------
.. autoclass:: skrl.models.jax.gaussian.GaussianMixin
:show-inheritance:
:members:
.. automethod:: __init__
|
Toni-SM/skrl/docs/source/api/multi_agents/mappo.rst | Multi-Agent Proximal Policy Optimization (MAPPO)
================================================
MAPPO is a **model-free**, **stochastic** **on-policy** **policy gradient** CTDE (centralized training, decentralized execution) **multi-agent** algorithm that uses a centralized value function to estimate a single value that is used to guide the policy updates of all agents, improving coordination and cooperation between them
Paper: `The Surprising Effectiveness of PPO in Cooperative, Multi-Agent Games <https://arxiv.org/abs/2103.01955>`_
.. raw:: html
<br><hr>
Algorithm
---------
| For each iteration do:
| For each agent do:
| :math:`\bullet \;` Collect, in a rollout memory, a set of states :math:`s`, actions :math:`a`, rewards :math:`r`, dones :math:`d`, log probabilities :math:`logp` and values :math:`V` on policy using :math:`\pi_\theta` and :math:`V_\phi`
| :math:`\bullet \;` Estimate returns :math:`R` and advantages :math:`A` using Generalized Advantage Estimation (GAE(:math:`\lambda`)) from the collected data [:math:`r, d, V`]
| :math:`\bullet \;` Compute the entropy loss :math:`{L}_{entropy}`
| :math:`\bullet \;` Compute the clipped surrogate objective (policy loss) with :math:`ratio` as the probability ratio between the action under the current policy and the action under the previous policy: :math:`L^{clip}_{\pi_\theta} = \mathbb{E}[\min(A \; ratio, A \; \text{clip}(ratio, 1-c, 1+c))]`
| :math:`\bullet \;` Compute the value loss :math:`L_{V_\phi}` as the mean squared error (MSE) between the predicted values :math:`V_{_{predicted}}` and the estimated returns :math:`R`
| :math:`\bullet \;` Optimize the total loss :math:`L = L^{clip}_{\pi_\theta} - c_1 \, L_{V_\phi} + c_2 \, {L}_{entropy}`
.. raw:: html
<br>
Algorithm implementation
^^^^^^^^^^^^^^^^^^^^^^^^
| Main notation/symbols:
| - policy function approximator (:math:`\pi_\theta`), value function approximator (:math:`V_\phi`)
| - states (:math:`s`), actions (:math:`a`), rewards (:math:`r`), next states (:math:`s'`), dones (:math:`d`)
| - shared states (:math:`s_{_{shared}}`), shared next states (:math:`s'_{_{shared}}`)
| - values (:math:`V`), advantages (:math:`A`), returns (:math:`R`)
| - log probabilities (:math:`logp`)
| - loss (:math:`L`)
.. raw:: html
<br>
Learning algorithm
""""""""""""""""""
|
| :literal:`compute_gae(...)`
| :blue:`def` :math:`\;f_{GAE} (r, d, V, V_{_{last}}') \;\rightarrow\; R, A:`
| :math:`adv \leftarrow 0`
| :math:`A \leftarrow \text{zeros}(r)`
| :green:`# advantages computation`
| **FOR** each reverse iteration :math:`i` up to the number of rows in :math:`r` **DO**
| **IF** :math:`i` is not the last row of :math:`r` **THEN**
| :math:`V_i' = V_{i+1}`
| **ELSE**
| :math:`V_i' \leftarrow V_{_{last}}'`
| :math:`adv \leftarrow r_i - V_i \, +` :guilabel:`discount_factor` :math:`\neg d_i \; (V_i' \, -` :guilabel:`lambda` :math:`adv)`
| :math:`A_i \leftarrow adv`
| :green:`# returns computation`
| :math:`R \leftarrow A + V`
| :green:`# normalize advantages`
| :math:`A \leftarrow \dfrac{A - \bar{A}}{A_\sigma + 10^{-8}}`
|
| :literal:`_update(...)`
| **FOR** each agent **DO**
| :green:`# compute returns and advantages`
| :math:`V_{_{last}}' \leftarrow V_\phi(s'_{_{shared}})`
| :math:`R, A \leftarrow f_{GAE}(r, d, V, V_{_{last}}')`
| :green:`# sample mini-batches from memory`
| [[:math:`s, a, logp, V, R, A`]] :math:`\leftarrow` states, actions, log_prob, values, returns, advantages
| :green:`# learning epochs`
| **FOR** each learning epoch up to :guilabel:`learning_epochs` **DO**
| :green:`# mini-batches loop`
| **FOR** each mini-batch [:math:`s, a, logp, V, R, A`] up to :guilabel:`mini_batches` **DO**
| :math:`logp' \leftarrow \pi_\theta(s, a)`
| :green:`# compute approximate KL divergence`
| :math:`ratio \leftarrow logp' - logp`
| :math:`KL_{_{divergence}} \leftarrow \frac{1}{N} \sum_{i=1}^N ((e^{ratio} - 1) - ratio)`
| :green:`# early stopping with KL divergence`
| **IF** :math:`KL_{_{divergence}} >` :guilabel:`kl_threshold` **THEN**
| **BREAK LOOP**
| :green:`# compute entropy loss`
| **IF** entropy computation is enabled **THEN**
| :math:`{L}_{entropy} \leftarrow \, -` :guilabel:`entropy_loss_scale` :math:`\frac{1}{N} \sum_{i=1}^N \pi_{\theta_{entropy}}`
| **ELSE**
| :math:`{L}_{entropy} \leftarrow 0`
| :green:`# compute policy loss`
| :math:`ratio \leftarrow e^{logp' - logp}`
| :math:`L_{_{surrogate}} \leftarrow A \; ratio`
| :math:`L_{_{clipped\,surrogate}} \leftarrow A \; \text{clip}(ratio, 1 - c, 1 + c) \qquad` with :math:`c` as :guilabel:`ratio_clip`
| :math:`L^{clip}_{\pi_\theta} \leftarrow - \frac{1}{N} \sum_{i=1}^N \min(L_{_{surrogate}}, L_{_{clipped\,surrogate}})`
| :green:`# compute value loss`
| :math:`V_{_{predicted}} \leftarrow V_\phi(s_{_{shared}})`
| **IF** :guilabel:`clip_predicted_values` is enabled **THEN**
| :math:`V_{_{predicted}} \leftarrow V + \text{clip}(V_{_{predicted}} - V, -c, c) \qquad` with :math:`c` as :guilabel:`value_clip`
| :math:`L_{V_\phi} \leftarrow` :guilabel:`value_loss_scale` :math:`\frac{1}{N} \sum_{i=1}^N (R - V_{_{predicted}})^2`
| :green:`# optimization step`
| reset :math:`\text{optimizer}_{\theta, \phi}`
| :math:`\nabla_{\theta, \, \phi} (L^{clip}_{\pi_\theta} + {L}_{entropy} + L_{V_\phi})`
| :math:`\text{clip}(\lVert \nabla_{\theta, \, \phi} \rVert)` with :guilabel:`grad_norm_clip`
| step :math:`\text{optimizer}_{\theta, \phi}`
| :green:`# update learning rate`
| **IF** there is a :guilabel:`learning_rate_scheduler` **THEN**
| step :math:`\text{scheduler}_{\theta, \phi} (\text{optimizer}_{\theta, \phi})`
.. raw:: html
<br>
Usage
-----
.. tabs::
.. tab:: Standard implementation
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../../snippets/multi_agents_basic_usage.py
:language: python
:emphasize-lines: 2
:start-after: [start-mappo-torch]
:end-before: [end-mappo-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../../snippets/multi_agents_basic_usage.py
:language: python
:emphasize-lines: 2
:start-after: [start-mappo-jax]
:end-before: [end-mappo-jax]
.. raw:: html
<br>
Configuration and hyperparameters
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. note::
The specification of a single value is automatically extended to all involved agents, unless the configuration of each individual agent is specified using a dictionary. For example:
.. code-block:: python
# specify a configuration value for each agent (agent names depend on environment)
cfg["discount_factor"] = {"agent_0": 0.99, "agent_1": 0.995, "agent_2": 0.985}
.. literalinclude:: ../../../../skrl/multi_agents/torch/mappo/mappo.py
:language: python
:start-after: [start-config-dict-torch]
:end-before: [end-config-dict-torch]
.. raw:: html
<br>
Spaces
^^^^^^
The implementation supports the following `Gym spaces <https://www.gymlibrary.dev/api/spaces>`_ / `Gymnasium spaces <https://gymnasium.farama.org/api/spaces>`_
.. list-table::
:header-rows: 1
* - Gym/Gymnasium spaces
- .. centered:: Observation
- .. centered:: Action
* - Discrete
- .. centered:: :math:`\square`
- .. centered:: :math:`\blacksquare`
* - MultiDiscrete
- .. centered:: :math:`\square`
- .. centered:: :math:`\blacksquare`
* - Box
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\blacksquare`
* - Dict
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\square`
.. raw:: html
<br>
Models
^^^^^^
The implementation uses 1 stochastic (discrete or continuous) and 1 deterministic function approximator. These function approximators (models) must be collected in a dictionary and passed to the constructor of the class under the argument :literal:`models`
.. list-table::
:header-rows: 1
* - Notation
- Concept
- Key
- Input shape
- Output shape
- Type
* - :math:`\pi_\theta(s)`
- Policy
- :literal:`"policy"`
- observation
- action
- :ref:`Categorical <models_categorical>` /
|br| :ref:`Multi-Categorical <models_multicategorical>` /
|br| :ref:`Gaussian <models_gaussian>` /
|br| :ref:`MultivariateGaussian <models_multivariate_gaussian>`
* - :math:`V_\phi(s)`
- Value
- :literal:`"value"`
- observation
- 1
- :ref:`Deterministic <models_deterministic>`
.. raw:: html
<br>
Features
^^^^^^^^
Support for advanced features is described in the next table
.. list-table::
:header-rows: 1
* - Feature
- Support and remarks
- .. centered:: |_4| |pytorch| |_4|
- .. centered:: |_4| |jax| |_4|
* - Shared model
- for Policy and Value
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\square`
* - RNN support
- \-
- .. centered:: :math:`\square`
- .. centered:: :math:`\square`
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.multi_agents.torch.mappo.MAPPO_DEFAULT_CONFIG
.. autoclass:: skrl.multi_agents.torch.mappo.MAPPO
:undoc-members:
:show-inheritance:
:private-members: _update
:members:
.. automethod:: __init__
.. raw:: html
<br>
API (JAX)
---------
.. autoclass:: skrl.multi_agents.jax.mappo.MAPPO_DEFAULT_CONFIG
.. autoclass:: skrl.multi_agents.jax.mappo.MAPPO
:undoc-members:
:show-inheritance:
:private-members: _update
:members:
.. automethod:: __init__
|
Toni-SM/skrl/docs/source/api/multi_agents/ippo.rst | Independent Proximal Policy Optimization (IPPO)
===============================================
IPPO is a **model-free**, **stochastic** **on-policy** **policy gradient** DTDE (decentralized training, decentralized execution) **multi-agent** algorithm in which each agent learns independently using its own local observations of the environment and has its own independent critic network to estimate the value function
Paper: `Is Independent Learning All You Need in the StarCraft Multi-Agent Challenge? <https://arxiv.org/abs/2011.09533>`_
.. raw:: html
<br><hr>
Algorithm
---------
| For each iteration do:
| For each agent do:
| :math:`\bullet \;` Collect, in a rollout memory, a set of states :math:`s`, actions :math:`a`, rewards :math:`r`, dones :math:`d`, log probabilities :math:`logp` and values :math:`V` on policy using :math:`\pi_\theta` and :math:`V_\phi`
| :math:`\bullet \;` Estimate returns :math:`R` and advantages :math:`A` using Generalized Advantage Estimation (GAE(:math:`\lambda`)) from the collected data [:math:`r, d, V`]
| :math:`\bullet \;` Compute the entropy loss :math:`{L}_{entropy}`
| :math:`\bullet \;` Compute the clipped surrogate objective (policy loss) with :math:`ratio` as the probability ratio between the action under the current policy and the action under the previous policy: :math:`L^{clip}_{\pi_\theta} = \mathbb{E}[\min(A \; ratio, A \; \text{clip}(ratio, 1-c, 1+c))]`
| :math:`\bullet \;` Compute the value loss :math:`L_{V_\phi}` as the mean squared error (MSE) between the predicted values :math:`V_{_{predicted}}` and the estimated returns :math:`R`
| :math:`\bullet \;` Optimize the total loss :math:`L = L^{clip}_{\pi_\theta} - c_1 \, L_{V_\phi} + c_2 \, {L}_{entropy}`
.. raw:: html
<br>
Algorithm implementation
^^^^^^^^^^^^^^^^^^^^^^^^
| Main notation/symbols:
| - policy function approximator (:math:`\pi_\theta`), value function approximator (:math:`V_\phi`)
| - states (:math:`s`), actions (:math:`a`), rewards (:math:`r`), next states (:math:`s'`), dones (:math:`d`)
| - values (:math:`V`), advantages (:math:`A`), returns (:math:`R`)
| - log probabilities (:math:`logp`)
| - loss (:math:`L`)
.. raw:: html
<br>
Learning algorithm
""""""""""""""""""
|
| :literal:`compute_gae(...)`
| :blue:`def` :math:`\;f_{GAE} (r, d, V, V_{_{last}}') \;\rightarrow\; R, A:`
| :math:`adv \leftarrow 0`
| :math:`A \leftarrow \text{zeros}(r)`
| :green:`# advantages computation`
| **FOR** each reverse iteration :math:`i` up to the number of rows in :math:`r` **DO**
| **IF** :math:`i` is not the last row of :math:`r` **THEN**
| :math:`V_i' = V_{i+1}`
| **ELSE**
| :math:`V_i' \leftarrow V_{_{last}}'`
| :math:`adv \leftarrow r_i - V_i \, +` :guilabel:`discount_factor` :math:`\neg d_i \; (V_i' \, -` :guilabel:`lambda` :math:`adv)`
| :math:`A_i \leftarrow adv`
| :green:`# returns computation`
| :math:`R \leftarrow A + V`
| :green:`# normalize advantages`
| :math:`A \leftarrow \dfrac{A - \bar{A}}{A_\sigma + 10^{-8}}`
|
| :literal:`_update(...)`
| **FOR** each agent **DO**
| :green:`# compute returns and advantages`
| :math:`V_{_{last}}' \leftarrow V_\phi(s')`
| :math:`R, A \leftarrow f_{GAE}(r, d, V, V_{_{last}}')`
| :green:`# sample mini-batches from memory`
| [[:math:`s, a, logp, V, R, A`]] :math:`\leftarrow` states, actions, log_prob, values, returns, advantages
| :green:`# learning epochs`
| **FOR** each learning epoch up to :guilabel:`learning_epochs` **DO**
| :green:`# mini-batches loop`
| **FOR** each mini-batch [:math:`s, a, logp, V, R, A`] up to :guilabel:`mini_batches` **DO**
| :math:`logp' \leftarrow \pi_\theta(s, a)`
| :green:`# compute approximate KL divergence`
| :math:`ratio \leftarrow logp' - logp`
| :math:`KL_{_{divergence}} \leftarrow \frac{1}{N} \sum_{i=1}^N ((e^{ratio} - 1) - ratio)`
| :green:`# early stopping with KL divergence`
| **IF** :math:`KL_{_{divergence}} >` :guilabel:`kl_threshold` **THEN**
| **BREAK LOOP**
| :green:`# compute entropy loss`
| **IF** entropy computation is enabled **THEN**
| :math:`{L}_{entropy} \leftarrow \, -` :guilabel:`entropy_loss_scale` :math:`\frac{1}{N} \sum_{i=1}^N \pi_{\theta_{entropy}}`
| **ELSE**
| :math:`{L}_{entropy} \leftarrow 0`
| :green:`# compute policy loss`
| :math:`ratio \leftarrow e^{logp' - logp}`
| :math:`L_{_{surrogate}} \leftarrow A \; ratio`
| :math:`L_{_{clipped\,surrogate}} \leftarrow A \; \text{clip}(ratio, 1 - c, 1 + c) \qquad` with :math:`c` as :guilabel:`ratio_clip`
| :math:`L^{clip}_{\pi_\theta} \leftarrow - \frac{1}{N} \sum_{i=1}^N \min(L_{_{surrogate}}, L_{_{clipped\,surrogate}})`
| :green:`# compute value loss`
| :math:`V_{_{predicted}} \leftarrow V_\phi(s)`
| **IF** :guilabel:`clip_predicted_values` is enabled **THEN**
| :math:`V_{_{predicted}} \leftarrow V + \text{clip}(V_{_{predicted}} - V, -c, c) \qquad` with :math:`c` as :guilabel:`value_clip`
| :math:`L_{V_\phi} \leftarrow` :guilabel:`value_loss_scale` :math:`\frac{1}{N} \sum_{i=1}^N (R - V_{_{predicted}})^2`
| :green:`# optimization step`
| reset :math:`\text{optimizer}_{\theta, \phi}`
| :math:`\nabla_{\theta, \, \phi} (L^{clip}_{\pi_\theta} + {L}_{entropy} + L_{V_\phi})`
| :math:`\text{clip}(\lVert \nabla_{\theta, \, \phi} \rVert)` with :guilabel:`grad_norm_clip`
| step :math:`\text{optimizer}_{\theta, \phi}`
| :green:`# update learning rate`
| **IF** there is a :guilabel:`learning_rate_scheduler` **THEN**
| step :math:`\text{scheduler}_{\theta, \phi} (\text{optimizer}_{\theta, \phi})`
.. raw:: html
<br>
Usage
-----
.. tabs::
.. tab:: Standard implementation
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../../snippets/multi_agents_basic_usage.py
:language: python
:emphasize-lines: 2
:start-after: [start-ippo-torch]
:end-before: [end-ippo-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../../snippets/multi_agents_basic_usage.py
:language: python
:emphasize-lines: 2
:start-after: [start-ippo-jax]
:end-before: [end-ippo-jax]
.. raw:: html
<br>
Configuration and hyperparameters
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. note::
The specification of a single value is automatically extended to all involved agents, unless the configuration of each individual agent is specified using a dictionary. For example:
.. code-block:: python
# specify a configuration value for each agent (agent names depend on environment)
cfg["discount_factor"] = {"agent_0": 0.99, "agent_1": 0.995, "agent_2": 0.985}
.. literalinclude:: ../../../../skrl/multi_agents/torch/ippo/ippo.py
:language: python
:start-after: [start-config-dict-torch]
:end-before: [end-config-dict-torch]
.. raw:: html
<br>
Spaces
^^^^^^
The implementation supports the following `Gym spaces <https://www.gymlibrary.dev/api/spaces>`_ / `Gymnasium spaces <https://gymnasium.farama.org/api/spaces>`_
.. list-table::
:header-rows: 1
* - Gym/Gymnasium spaces
- .. centered:: Observation
- .. centered:: Action
* - Discrete
- .. centered:: :math:`\square`
- .. centered:: :math:`\blacksquare`
* - MultiDiscrete
- .. centered:: :math:`\square`
- .. centered:: :math:`\blacksquare`
* - Box
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\blacksquare`
* - Dict
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\square`
.. raw:: html
<br>
Models
^^^^^^
The implementation uses 1 stochastic (discrete or continuous) and 1 deterministic function approximator. These function approximators (models) must be collected in a dictionary and passed to the constructor of the class under the argument :literal:`models`
.. list-table::
:header-rows: 1
* - Notation
- Concept
- Key
- Input shape
- Output shape
- Type
* - :math:`\pi_\theta(s)`
- Policy
- :literal:`"policy"`
- observation
- action
- :ref:`Categorical <models_categorical>` /
|br| :ref:`Multi-Categorical <models_multicategorical>` /
|br| :ref:`Gaussian <models_gaussian>` /
|br| :ref:`MultivariateGaussian <models_multivariate_gaussian>`
* - :math:`V_\phi(s)`
- Value
- :literal:`"value"`
- observation
- 1
- :ref:`Deterministic <models_deterministic>`
.. raw:: html
<br>
Features
^^^^^^^^
Support for advanced features is described in the next table
.. list-table::
:header-rows: 1
* - Feature
- Support and remarks
- .. centered:: |_4| |pytorch| |_4|
- .. centered:: |_4| |jax| |_4|
* - Shared model
- for Policy and Value
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\square`
* - RNN support
- \-
- .. centered:: :math:`\square`
- .. centered:: :math:`\square`
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.multi_agents.torch.ippo.IPPO_DEFAULT_CONFIG
.. autoclass:: skrl.multi_agents.torch.ippo.IPPO
:undoc-members:
:show-inheritance:
:private-members: _update
:members:
.. automethod:: __init__
.. raw:: html
<br>
API (JAX)
---------
.. autoclass:: skrl.multi_agents.jax.ippo.IPPO_DEFAULT_CONFIG
.. autoclass:: skrl.multi_agents.jax.ippo.IPPO
:undoc-members:
:show-inheritance:
:private-members: _update
:members:
.. automethod:: __init__
|
Toni-SM/skrl/docs/source/api/config/frameworks.rst | ML frameworks configuration
===========================
Configurations for behavior modification of Machine Learning (ML) frameworks.
.. raw:: html
<br><hr>
JAX
---
JAX specific configuration
.. raw:: html
<br>
API
^^^
.. py:data:: skrl.config.jax.backend
:type: str
:value: "numpy"
Backend used by the different components to operate and generate arrays
This configuration excludes models and optimizers.
Supported backend are: ``"numpy"`` and ``"jax"``
.. py:data:: skrl.config.jax.key
:type: jnp.ndarray
:value: [0, 0]
Pseudo-random number generator (PRNG) key
|
Toni-SM/skrl/docs/source/api/utils/isaacgym_utils.rst | Isaac Gym utils
===============
Utilities for ease of programming of Isaac Gym environments.
.. raw:: html
<br><hr>
Control of robotic manipulators
-------------------------------
.. raw:: html
<br>
Inverse kinematics using damped least squares method
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This implementation attempts to unify under a single and reusable function the whole set of procedures used to calculate the inverse kinematics of a robotic manipulator shown in Isaac Gym's example: Franka IK Picking (:literal:`franka_cube_ik_osc.py`)
:math:`\Delta\theta = J^T (JJ^T + \lambda^2 I)^{-1} \, \vec{e}`
where
| :math:`\qquad \Delta\theta \;` is the change in joint angles
| :math:`\qquad J \;` is the Jacobian
| :math:`\qquad \lambda \;` is a non-zero damping constant
| :math:`\qquad \vec{e} \;` is the Cartesian pose error (position and orientation)
.. raw:: html
<br>
API
^^^
.. autofunction:: skrl.utils.isaacgym_utils.ik
.. raw:: html
<br>
Web viewer for development without X server
-------------------------------------------
This library provides an API for instantiating a lightweight web viewer useful, mostly, for designing Isaac Gym environments in remote workstations or docker containers without X server
.. raw:: html
<br>
Gestures and actions
^^^^^^^^^^^^^^^^^^^^
+---------------------------------------------------------+------------+--------------+
| Gestures / actions | Key | Mouse |
+=========================================================+============+==============+
| Orbit (rotate view around a point) | :kbd:`Alt` | Left click |
+---------------------------------------------------------+------------+--------------+
| Pan (rotate view around itself) | | Right click |
+---------------------------------------------------------+------------+--------------+
| Walk mode (move view linearly to the current alignment) | | Middle click |
+---------------------------------------------------------+------------+--------------+
| Zoom in/out | | Scroll wheel |
+---------------------------------------------------------+------------+--------------+
| Freeze view | :kbd:`V` | |
+---------------------------------------------------------+------------+--------------+
| Toggle image type (color, depth) | :kbd:`T` | |
+---------------------------------------------------------+------------+--------------+
Watch an animation of the gestures and actions in the following video
.. raw:: html
<video width="100%" controls autoplay>
<source src="https://user-images.githubusercontent.com/22400377/157323911-40729895-6175-48d2-85d7-c1b30fe0ee9c.mp4" type="video/mp4">
</video>
<br>
.. raw:: html
<br>
Requirements
^^^^^^^^^^^^
The web viewer is build on top of `Flask <https://flask.palletsprojects.com>`_ and requires the following package to be installed
.. code-block:: bash
pip install Flask
Also, to be launched in Visual Studio Code (Preview in Editor), the `Live Preview - VS Code Extension <https://marketplace.visualstudio.com/items?itemName=ms-vscode.live-server>`_ must be installed
.. raw:: html
<br>
Usage
^^^^^
.. tabs::
.. tab:: Snippet
.. literalinclude:: ../../snippets/isaacgym_utils.py
:language: python
:emphasize-lines: 4, 8, 56, 65-68
.. raw:: html
<br>
API
^^^
.. autoclass:: skrl.utils.isaacgym_utils.WebViewer
:undoc-members:
:show-inheritance:
:inherited-members:
:private-members: _route_index, _route_stream, _route_input_event, _stream
:members:
.. automethod:: __init__
|
Toni-SM/skrl/docs/source/api/utils/huggingface.rst | Hugging Face integration
========================
The Hugging Face (HF) Hub is a platform for building, training, and deploying ML models, as well as accessing a variety of datasets and metrics for further analysis and validation.
.. raw:: html
<br><hr>
Integration
-----------
.. raw:: html
<br>
Download model from HF Hub
^^^^^^^^^^^^^^^^^^^^^^^^^^
Several skrl-trained models (agent checkpoints) for different environments/tasks of Gym/Gymnasium, Isaac Gym, Omniverse Isaac Gym, etc. are available in the Hugging Face Hub
These models can be used as comparison benchmarks, for collecting environment transitions in memory (for offline reinforcement learning, e.g.) or for pre-initialization of agents for performing similar tasks, among others
Visit the `skrl organization on the Hugging Face Hub <https://huggingface.co/skrl>`_ to access publicly available models!
.. raw:: html
<br>
API
---
.. autofunction:: skrl.utils.huggingface.download_model_from_huggingface
|
Toni-SM/skrl/docs/source/api/utils/postprocessing.rst | File post-processing
====================
Utilities for processing files generated during training/evaluation.
.. raw:: html
<br><hr>
Exported memories
-----------------
This library provides an implementation for quickly loading exported memory files to inspect their contents in future post-processing steps. See the section :ref:`Library utilities (skrl.utils module) <library_utilities>` for a real use case
.. raw:: html
<br>
Usage
^^^^^
.. tabs::
.. tab:: PyTorch (.pt)
.. literalinclude:: ../../snippets/utils_postprocessing.py
:language: python
:emphasize-lines: 1, 5-6
:start-after: [start-memory_file_iterator-torch]
:end-before: [end-memory_file_iterator-torch]
.. tab:: NumPy (.npz)
.. literalinclude:: ../../snippets/utils_postprocessing.py
:language: python
:emphasize-lines: 1, 5-6
:start-after: [start-memory_file_iterator-numpy]
:end-before: [end-memory_file_iterator-numpy]
.. tab:: Comma-separated values (.csv)
.. literalinclude:: ../../snippets/utils_postprocessing.py
:language: python
:emphasize-lines: 1, 5-6
:start-after: [start-memory_file_iterator-csv]
:end-before: [end-memory_file_iterator-csv]
.. raw:: html
<br>
API
^^^
.. autoclass:: skrl.utils.postprocessing.MemoryFileIterator
:undoc-members:
:show-inheritance:
:inherited-members:
:private-members: _format_numpy, _format_torch, _format_csv
:members:
.. automethod:: __init__
.. automethod:: __iter__
.. automethod:: __next__
.. raw:: html
<br>
Tensorboard files
-----------------
This library provides an implementation for quickly loading Tensorboard files to inspect their contents in future post-processing steps. See the section :ref:`Library utilities (skrl.utils module) <library_utilities>` for a real use case
.. raw:: html
<br>
Requirements
^^^^^^^^^^^^
This utility requires the `TensorFlow <https://www.tensorflow.org/>`_ package to be installed to load and parse Tensorboard files:
.. code-block:: bash
pip install tensorflow
.. raw:: html
<br>
Usage
^^^^^
.. tabs::
.. tab:: Tensorboard (events.out.tfevents.*)
.. literalinclude:: ../../snippets/utils_postprocessing.py
:language: python
:emphasize-lines: 1, 5-7
:start-after: [start-tensorboard_file_iterator-list]
:end-before: [end-tensorboard_file_iterator-list]
.. raw:: html
<br>
API
^^^
.. autoclass:: skrl.utils.postprocessing.TensorboardFileIterator
:undoc-members:
:show-inheritance:
:inherited-members:
:members:
.. automethod:: __init__
.. automethod:: __iter__
.. automethod:: __next__
|
Toni-SM/skrl/docs/source/api/utils/model_instantiators.rst | Model instantiators
===================
Utilities for quickly creating model instances.
.. raw:: html
<br><hr>
.. TODO: add snippet
.. list-table::
:header-rows: 1
* - Models
- .. centered:: |_4| |pytorch| |_4|
- .. centered:: |_4| |jax| |_4|
* - :doc:`Tabular model <../models/tabular>` (discrete domain)
- .. centered:: :math:`\square`
- .. centered:: :math:`\square`
* - :doc:`Categorical model <../models/categorical>` (discrete domain)
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\blacksquare`
* - :doc:`Gaussian model <../models/gaussian>` (continuous domain)
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\blacksquare`
* - :doc:`Multivariate Gaussian model <../models/multivariate_gaussian>` (continuous domain)
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\square`
* - :doc:`Deterministic model <../models/deterministic>` (continuous domain)
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\blacksquare`
* - :doc:`Shared model <../models/shared_model>`
- .. centered:: :math:`\blacksquare`
- .. centered:: :math:`\square`
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.utils.model_instantiators.torch.Shape
.. py:property:: ONE
Flag to indicate that the model's input/output has shape (1,)
This flag is useful for the definition of critic models, where the critic's output is a scalar
.. py:property:: STATES
Flag to indicate that the model's input/output is the state (observation) space of the environment
It is an alias for :py:attr:`OBSERVATIONS`
.. py:property:: OBSERVATIONS
Flag to indicate that the model's input/output is the observation space of the environment
.. py:property:: ACTIONS
Flag to indicate that the model's input/output is the action space of the environment
.. py:property:: STATES_ACTIONS
Flag to indicate that the model's input/output is the combination (concatenation) of the state (observation) and action spaces of the environment
.. autofunction:: skrl.utils.model_instantiators.torch.categorical_model
.. autofunction:: skrl.utils.model_instantiators.torch.deterministic_model
.. autofunction:: skrl.utils.model_instantiators.torch.gaussian_model
.. autofunction:: skrl.utils.model_instantiators.torch.multivariate_gaussian_model
.. autofunction:: skrl.utils.model_instantiators.torch.shared_model
.. raw:: html
<br>
API (JAX)
---------
.. autoclass:: skrl.utils.model_instantiators.jax.Shape
.. py:property:: ONE
Flag to indicate that the model's input/output has shape (1,)
This flag is useful for the definition of critic models, where the critic's output is a scalar
.. py:property:: STATES
Flag to indicate that the model's input/output is the state (observation) space of the environment
It is an alias for :py:attr:`OBSERVATIONS`
.. py:property:: OBSERVATIONS
Flag to indicate that the model's input/output is the observation space of the environment
.. py:property:: ACTIONS
Flag to indicate that the model's input/output is the action space of the environment
.. py:property:: STATES_ACTIONS
Flag to indicate that the model's input/output is the combination (concatenation) of the state (observation) and action spaces of the environment
.. autofunction:: skrl.utils.model_instantiators.jax.categorical_model
.. autofunction:: skrl.utils.model_instantiators.jax.deterministic_model
.. autofunction:: skrl.utils.model_instantiators.jax.gaussian_model
|
Toni-SM/skrl/docs/source/api/utils/omniverse_isaacgym_utils.rst | Omniverse Isaac Gym utils
=========================
Utilities for ease of programming of Omniverse Isaac Gym environments.
.. raw:: html
<br><hr>
Control of robotic manipulators
-------------------------------
.. raw:: html
<br>
Differential inverse kinematics
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This implementation attempts to unify under a single and reusable function the whole set of procedures used to compute the inverse kinematics of a robotic manipulator, originally shown in the Isaac Orbit framework's task space controllers section, but this time for Omniverse Isaac Gym.
:math:`\Delta\theta =` :guilabel:`scale` :math:`J^\dagger \, \vec{e}`
where
| :math:`\qquad \Delta\theta \;` is the change in joint angles
| :math:`\qquad \vec{e} \;` is the Cartesian pose error (position and orientation)
| :math:`\qquad J^\dagger \;` is the pseudoinverse of the Jacobian estimated as follows:
The pseudoinverse of the Jacobian (:math:`J^\dagger`) is estimated as follows:
* Tanspose: :math:`\; J^\dagger = J^T`
* Pseduoinverse: :math:`\; J^\dagger = J^T(JJ^T)^{-1}`
* Damped least-squares: :math:`\; J^\dagger = J^T(JJ^T \, +` :guilabel:`damping`:math:`{}^2 I)^{-1}`
* Singular-vale decomposition: See `buss2004introduction <https://mathweb.ucsd.edu/~sbuss/ResearchWeb/ikmethods/iksurvey.pdf>`_ (section 6)
.. raw:: html
<br>
API
^^^
.. autofunction:: skrl.utils.omniverse_isaacgym_utils.ik
.. raw:: html
<br>
OmniIsaacGymEnvs-like environment instance
------------------------------------------
Instantiate a VecEnvBase-based object compatible with OmniIsaacGymEnvs for use outside of the OmniIsaacGymEnvs implementation.
.. raw:: html
<br>
API
^^^
.. autofunction:: skrl.utils.omniverse_isaacgym_utils.get_env_instance
|
Toni-SM/skrl/docs/source/api/utils/seed.rst | Random seed
===========
Utilities for seeding the random number generators.
.. raw:: html
<br><hr>
Seed the random number generators
---------------------------------
.. raw:: html
<br>
API
^^^
.. autofunction:: skrl.utils.set_seed
|
Toni-SM/skrl/docs/source/api/memories/random.rst | Random memory
=============
Random sampling memory
.. raw:: html
<br><hr>
Usage
-----
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../../snippets/memories.py
:language: python
:emphasize-lines: 2, 5
:start-after: [start-random-torch]
:end-before: [end-random-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../../snippets/memories.py
:language: python
:emphasize-lines: 2, 5
:start-after: [start-random-jax]
:end-before: [end-random-jax]
.. raw:: html
<br>
API (PyTorch)
-------------
.. autoclass:: skrl.memories.torch.random.RandomMemory
:undoc-members:
:show-inheritance:
:inherited-members:
:members:
.. automethod:: __init__
.. automethod:: __len__
.. raw:: html
<br>
API (JAX)
---------
.. autoclass:: skrl.memories.jax.random.RandomMemory
:undoc-members:
:show-inheritance:
:inherited-members:
:members:
.. automethod:: __init__
.. automethod:: __len__
|
Toni-SM/skrl/docs/source/intro/getting_started.rst | Getting Started
===============
In this section, you will learn how to use the various components of the **skrl** library to create reinforcement learning tasks. Whether you are a beginner or an experienced researcher, we hope this section will provide you with a solid foundation to build upon.
We recommend visiting the :doc:`Examples <examples>` to see how the components can be integrated and applied in practice. Let's get started!
.. raw:: html
<br><hr>
**Reinforcement Learning schema**
---------------------------------
**Reinforcement Learning (RL)** is a Machine Learning sub-field for decision making that allows an agent to learn from its interaction with the environment as shown in the following schema:
.. image:: ../_static/imgs/rl_schema-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Reinforcement Learning schema
.. image:: ../_static/imgs/rl_schema-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Reinforcement Learning schema
.. raw:: html
<br>
At each step (also called timestep) of interaction with the environment, the agent sees an observation :math:`o_t` of the complete description of the state :math:`s_t \in S` of the environment. Then, it decides which action :math:`a_t \in A` to take from the action space using a policy. The environment, which changes in response to the agent's action (or by itself), returns a reward signal :math:`r_t = R(s_t, a_t, s_{t+1})` as a measure of how good or bad the action was that moved it to its new state :math:`s_{t+1}`. The agent aims to maximize the cumulative reward (discounted or not by a factor :math:`\gamma \in (0,1]`) by adjusting the policy's behaviour via some optimization algorithm.
**From this schema, this section is intended to guide in the creation of a RL system using skrl**
.. raw:: html
<br>
1. Environments
^^^^^^^^^^^^^^^
The environment plays a fundamental role in the definition of the RL schema. For example, the selection of the agent depends strongly on the observation and action space nature. There are several interfaces to interact with the environments such as OpenAI Gym / Farama Gymnasium or DeepMind. However, each of them has a different API and work with non-compatible data types.
* For **single-agent** environments, skrl offers a function to **wrap environments** based on the Gym/Gymnasium, DeepMind, NVIDIA Isaac Gym, Isaac Orbit and Omniverse Isaac Gym interfaces, among others. The wrapped environments provide, to the library components, a common interface (based on Gym/Gymnasium) as shown in the following figure. Refer to the :doc:`Wrapping (single-agent) <../api/envs/wrapping>` section for more information.
* For **multi-agent** environments, skrl offers a function to **wrap environments** based on the PettingZoo and Bi-DexHands interfaces. The wrapped environments provide, to the library components, a common interface (based on PettingZoo) as shown in the following figure. Refer to the :doc:`Wrapping (multi-agents) <../api/envs/multi_agents_wrapping>` section for more information.
.. tabs::
.. group-tab:: Single-agent environments
.. image:: ../_static/imgs/wrapping-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Environment wrapping
.. image:: ../_static/imgs/wrapping-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Environment wrapping
.. group-tab:: Multi-agent environments
.. image:: ../_static/imgs/multi_agent_wrapping-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Environment wrapping
.. image:: ../_static/imgs/multi_agent_wrapping-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Environment wrapping
Among the methods and properties defined in the wrapped environment, the observation and action spaces are one of the most relevant for instantiating other library components. The following code snippets show how to load and wrap environments based on the supported interfaces:
.. tabs::
.. group-tab:: Single-agent environments
.. tabs::
.. tab:: Omniverse Isaac Gym
.. tabs::
.. tab:: Common environment
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-omniverse-isaacgym]
:end-before: [pytorch-end-omniverse-isaacgym]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-omniverse-isaacgym]
:end-before: [jax-end-omniverse-isaacgym]
.. tab:: Multi-threaded environment
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-omniverse-isaacgym-mt]
:end-before: [pytorch-end-omniverse-isaacgym-mt]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-omniverse-isaacgym-mt]
:end-before: [jax-end-omniverse-isaacgym-mt]
.. tab:: Isaac Orbit
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-isaac-orbit]
:end-before: [pytorch-end-isaac-orbit]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-isaac-orbit]
:end-before: [jax-end-isaac-orbit]
.. tab:: Isaac Gym
.. tabs::
.. tab:: Preview 4 (isaacgymenvs.make)
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-isaacgym-preview4-make]
:end-before: [pytorch-end-isaacgym-preview4-make]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-isaacgym-preview4-make]
:end-before: [jax-end-isaacgym-preview4-make]
.. tab:: Preview 4
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-isaacgym-preview4]
:end-before: [pytorch-end-isaacgym-preview4]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-isaacgym-preview4]
:end-before: [jax-end-isaacgym-preview4]
.. tab:: Preview 3
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-isaacgym-preview3]
:end-before: [pytorch-end-isaacgym-preview3]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-isaacgym-preview3]
:end-before: [jax-end-isaacgym-preview3]
.. tab:: Preview 2
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-isaacgym-preview2]
:end-before: [pytorch-end-isaacgym-preview2]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-isaacgym-preview2]
:end-before: [jax-end-isaacgym-preview2]
.. tab:: Gym / Gymnasium
.. tabs::
.. tab:: Gym
.. tabs::
.. tab:: Single environment
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-gym]
:end-before: [pytorch-end-gym]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-gym]
:end-before: [jax-end-gym]
.. tab:: Vectorized environment
Visit the Gym documentation (`Vector <https://www.gymlibrary.dev/api/vector>`__) for more information about the creation and usage of vectorized environments
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-gym-vectorized]
:end-before: [pytorch-end-gym-vectorized]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-gym-vectorized]
:end-before: [jax-end-gym-vectorized]
.. tab:: Gymnasium
.. tabs::
.. tab:: Single environment
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-gymnasium]
:end-before: [pytorch-end-gymnasium]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-gymnasium]
:end-before: [jax-end-gymnasium]
.. tab:: Vectorized environment
Visit the Gymnasium documentation (`Vector <https://gymnasium.farama.org/api/vector>`__) for more information about the creation and usage of vectorized environments
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-gymnasium-vectorized]
:end-before: [pytorch-end-gymnasium-vectorized]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [jax-start-gymnasium-vectorized]
:end-before: [jax-end-gymnasium-vectorized]
.. tab:: DeepMind
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-deepmind]
:end-before: [pytorch-end-deepmind]
.. .. group-tab:: |_4| |jax| |_4|
.. .. literalinclude:: ../snippets/wrapping.py
.. :language: python
.. :start-after: [jax-start-deepmind]
.. :end-before: [jax-end-deepmind]
.. tab:: robosuite
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [pytorch-start-robosuite]
:end-before: [pytorch-end-robosuite]
.. .. group-tab:: |_4| |jax| |_4|
.. .. literalinclude:: ../snippets/wrapping.py
.. :language: python
.. :start-after: [jax-start-robosuite]
.. :end-before: [jax-end-robosuite]
.. group-tab:: Multi-agent environments
.. tabs::
.. tab:: PettingZoo
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [start-pettingzoo-torch]
:end-before: [end-pettingzoo-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [start-pettingzoo-jax]
:end-before: [end-pettingzoo-jax]
.. tab:: Bi-DexHands
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [start-bidexhands-torch]
:end-before: [end-bidexhands-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/wrapping.py
:language: python
:start-after: [start-bidexhands-jax]
:end-before: [end-bidexhands-jax]
Once the environment is known (and instantiated), it is time to configure and instantiate the agent. Agents are composed, apart from the optimization algorithm, by several components, such as memories, models or noises, for example, according to their nature. The following subsections focus on those components.
.. raw:: html
<br>
2. Memories
^^^^^^^^^^^
Memories are storage components that allow agents to collect and use/reuse recent or past experiences or other types of information. These can be large in size (such as replay buffers used by off-policy algorithms like DDPG, TD3 or SAC) or small in size (such as rollout buffers used by on-policy algorithms like PPO or TRPO to store batches that are discarded after use).
skrl provides **generic memory definitions** that are not tied to the agent implementation and can be used for any role, such as rollout or replay buffers. They are empty shells when they are instantiated and the agents are in charge of defining the tensors according to their needs. The total space occupied is the product of the memory size (:literal:`memory_size`), the number of environments (:literal:`num_envs`) obtained from the wrapped environment and the data size for each defined tensor.
The following code snippets show how to instantiate a memory:
.. tabs::
.. tab:: Random memory
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/memories.py
:language: python
:start-after: [start-random-torch]
:end-before: [end-random-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/memories.py
:language: python
:start-after: [start-random-jax]
:end-before: [end-random-jax]
Memories are passed directly to the agent constructor, if required (not all agents require memory, such as Q-learning or SARSA, for example), during its instantiation under the argument :literal:`memory` (or :literal:`memories`).
.. raw:: html
<br>
3. Models
^^^^^^^^^
Models are the agents' brains. Agents can have one or several models and their parameters are adjusted via the optimization algorithms.
In contrast to other libraries, skrl does not provide predefined models or fixed templates (this practice tends to hide and reduce the flexibility of the system, forcing developers to deeply inspect the code to make even small changes). Nevertheless, **helper mixins are provided** to create discrete and continuous (stochastic or deterministic) models with the library. In this way, the user/researcher should only be concerned with the definition of the approximation functions (tables or artificial neural networks), having all the control in his hands. The following diagrams show the concept of the provided mixins.
.. tabs::
.. tab:: Categorical
.. image:: ../_static/imgs/model_categorical-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Categorical model
.. image:: ../_static/imgs/model_categorical-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Categorical model
.. raw:: html
<br>
For snippets refer to :ref:`Categorical <models_categorical>` model section.
.. tab:: Gaussian
.. image:: ../_static/imgs/model_gaussian-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Gaussian model
.. image:: ../_static/imgs/model_gaussian-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Gaussian model
.. raw:: html
<br>
For snippets refer to :ref:`Gaussian <models_gaussian>` model section.
.. tab:: Multivariate Gaussian
.. image:: ../_static/imgs/model_multivariate_gaussian-light.svg
:width: 100%
:align: center
:class: only-light
:alt: Multivariate Gaussian model
.. image:: ../_static/imgs/model_multivariate_gaussian-dark.svg
:width: 100%
:align: center
:class: only-dark
:alt: Multivariate Gaussian model
.. raw:: html
<br>
For snippets refer to :ref:`Multivariate Gaussian <models_multivariate_gaussian>` model section.
.. tab:: Deterministic
.. image:: ../_static/imgs/model_deterministic-light.svg
:width: 60%
:align: center
:class: only-light
:alt: Deterministic model
.. image:: ../_static/imgs/model_deterministic-dark.svg
:width: 60%
:align: center
:class: only-dark
:alt: Deterministic model
.. raw:: html
<br>
For snippets refer to :ref:`Deterministic <models_deterministic>` model section.
.. tab:: Tabular
For snippets refer to :ref:`Tabular <models_tabular>` model section.
Models must be collected in a dictionary and passed to the agent constructor during its instantiation under the argument :literal:`models`. The dictionary keys are specific to each agent. Visit their respective documentation for more details (under *Spaces and models* section). For example, the PPO agent requires the policy and value models as shown below:
.. code-block:: python
models = {}
models["policy"] = Policy(env.observation_space, env.action_space, env.device)
models["value"] = Value(env.observation_space, env.action_space, env.device)
Models can be saved and loaded to and from the file system. However, the recommended practice for loading checkpoints to perform evaluations or continue an interrupted training is through the agents (they include, in addition to the models, other components and internal instances such as preprocessors or optimizers). Refer to :doc:`Saving, loading and logging <data>` (under *Checkpoints* section) for more information.
.. raw:: html
<br>
4. Noises
^^^^^^^^^
Noise plays a fundamental role in the exploration stage, especially in agents of a deterministic nature, such as DDPG or TD3, for example.
skrl provides, as part of its resources, **classes for instantiating noises** as shown in the following code snippets. Refer to :doc:`Noises <../api/resources/noises>` documentation for more information. Noise instances are passed to the agents in their respective configuration dictionaries.
.. tabs::
.. tab:: Gaussian noise
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/noises.py
:language: python
:start-after: [torch-start-gaussian]
:end-before: [torch-end-gaussian]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/noises.py
:language: python
:start-after: [jax-start-gaussian]
:end-before: [jax-end-gaussian]
.. tab:: Ornstein-Uhlenbeck noise
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/noises.py
:language: python
:start-after: [torch-start-ornstein-uhlenbeck]
:end-before: [torch-end-ornstein-uhlenbeck]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/noises.py
:language: python
:start-after: [jax-start-ornstein-uhlenbeck]
:end-before: [jax-end-ornstein-uhlenbeck]
.. raw:: html
<br>
5. Learning rate schedulers
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Learning rate schedulers help RL system converge faster and improve accuracy.
skrl **supports all PyTorch and JAX (Optax) learning rate schedulers** and provides, as part of its resources, **additional schedulers**. Refer to :doc:`Learning rate schedulers <../api/resources/schedulers>` documentation for more information.
Learning rate schedulers classes and their respective arguments (except the :literal:`optimizer` argument) are passed to the agents in their respective configuration dictionaries. For example, for the PPO agent, one of the schedulers can be configured as shown below:
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. code-block:: python
from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG
from skrl.resources.schedulers.torch import KLAdaptiveRL
agent_cfg = PPO_DEFAULT_CONFIG.copy()
agent_cfg["learning_rate_scheduler"] = KLAdaptiveRL
agent_cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008}
.. group-tab:: |_4| |jax| |_4|
.. code-block:: python
from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG
from skrl.resources.schedulers.jax import KLAdaptiveRL
agent_cfg = PPO_DEFAULT_CONFIG.copy()
agent_cfg["learning_rate_scheduler"] = KLAdaptiveRL
agent_cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008}
.. raw:: html
<br>
6. Preprocessors
^^^^^^^^^^^^^^^^
Data preprocessing can help increase the accuracy and efficiency of training by cleaning or making data suitable for machine learning models.
skrl provides, as part of its resources, **preprocessors** classes. Refer to :doc:`Preprocessors <../api/resources/preprocessors>` documentation for more information.
Preprocessors classes and their respective arguments are passed to the agents in their respective configuration dictionaries. For example, for the PPO agent, one of the preprocessors can be configured as shown below:
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. code-block:: python
from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG
from skrl.resources.preprocessors.torch import RunningStandardScaler
agent_cfg["state_preprocessor"] = RunningStandardScaler
agent_cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": env.device}
agent_cfg["value_preprocessor"] = RunningStandardScaler
agent_cfg["value_preprocessor_kwargs"] = {"size": 1, "device": env.device}
.. group-tab:: |_4| |jax| |_4|
.. code-block:: python
from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG
from skrl.resources.preprocessors.jax import RunningStandardScaler
agent_cfg["state_preprocessor"] = RunningStandardScaler
agent_cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": env.device}
agent_cfg["value_preprocessor"] = RunningStandardScaler
agent_cfg["value_preprocessor_kwargs"] = {"size": 1, "device": env.device}
.. raw:: html
<br>
7. Agents
^^^^^^^^^
Agents are the components in charge of decision making. They are much more than models (neural networks, for example) and include the optimization algorithms that compute the optimal policy
skrl provides **state-of-the-art agents**. Their implementations are focused on readability, simplicity and code transparency. Each agent is implemented independently even when two or more agents may contain code in common. Refer to each agent documentation for more information about the models and spaces they support, their respective configurations, algorithm details and more.
.. tabs::
.. group-tab:: (Single) agents
* :doc:`Advantage Actor Critic <../api/agents/a2c>` (**A2C**)
* :doc:`Adversarial Motion Priors <../api/agents/amp>` (**AMP**)
* :doc:`Cross-Entropy Method <../api/agents/cem>` (**CEM**)
* :doc:`Deep Deterministic Policy Gradient <../api/agents/ddpg>` (**DDPG**)
* :doc:`Double Deep Q-Network <../api/agents/ddqn>` (**DDQN**)
* :doc:`Deep Q-Network <../api/agents/dqn>` (**DQN**)
* :doc:`Proximal Policy Optimization <../api/agents/ppo>` (**PPO**)
* :doc:`Q-learning <../api/agents/q_learning>` (**Q-learning**)
* :doc:`Robust Policy Optimization <../api/agents/rpo>` (**RPO**)
* :doc:`Soft Actor-Critic <../api/agents/sac>` (**SAC**)
* :doc:`State Action Reward State Action <../api/agents/sarsa>` (**SARSA**)
* :doc:`Twin-Delayed DDPG <../api/agents/td3>` (**TD3**)
* :doc:`Trust Region Policy Optimization <../api/agents/trpo>` (**TRPO**)
.. group-tab:: Multi-agents
* :doc:`Independent Proximal Policy Optimization <../api/multi_agents/ippo>` (**IPPO**)
* :doc:`Multi-Agent Proximal Policy Optimization <../api/multi_agents/mappo>` (**MAPPO**)
Agents generally expect, as arguments, the following components: models and memories, as well as the following variables: observation and action spaces, the device where their logic is executed and a configuration dictionary with hyperparameters and other values. The remaining components, mentioned above, are collected through the configuration dictionary. For example, the PPO agent can be instantiated as follows:
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. code-block:: python
from skrl.agents.torch.ppo import PPO
agent = PPO(models=models, # models dict
memory=memory, # memory instance, or None if not required
cfg=agent_cfg, # configuration dict (preprocessors, learning rate schedulers, etc.)
observation_space=env.observation_space,
action_space=env.action_space,
device=env.device)
.. group-tab:: |_4| |jax| |_4|
.. code-block:: python
from skrl.agents.jax.ppo import PPO
agent = PPO(models=models, # models dict
memory=memory, # memory instance, or None if not required
cfg=agent_cfg, # configuration dict (preprocessors, learning rate schedulers, etc.)
observation_space=env.observation_space,
action_space=env.action_space,
device=env.device)
Agents can be saved and loaded to and from the file system. This is the **recommended practice** for loading checkpoints to perform evaluations or to continue interrupted training (since they include, in addition to models, other internal components and instances such as preprocessors or optimizers). Refer to :doc:`Saving, loading and logging <data>` (under *Checkpoints* section) for more information.
.. raw:: html
<br>
8. Trainers
^^^^^^^^^^^
Now that both actors, the environment and the agent, are instantiated, it is time to put the RL system in motion.
skrl offers classes (called :doc:`Trainers <../api/trainers>`) that manage the interaction cycle between the environment and the agent(s) for both: training and evaluation. These classes also enable the simultaneous training and evaluation of several agents by scope (subsets of environments among all available environments), which may or may not share resources, in the same run.
The following code snippets show how to train/evaluate RL systems using the available trainers:
.. tabs::
.. tab:: Sequential trainer
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/trainer.py
:language: python
:start-after: [pytorch-start-sequential]
:end-before: [pytorch-end-sequential]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/trainer.py
:language: python
:start-after: [jax-start-sequential]
:end-before: [jax-end-sequential]
.. tab:: Parallel trainer
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/trainer.py
:language: python
:start-after: [pytorch-start-parallel]
:end-before: [pytorch-end-parallel]
.. tab:: Step trainer
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/trainer.py
:language: python
:start-after: [pytorch-start-step]
:end-before: [pytorch-end-step]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/trainer.py
:language: python
:start-after: [jax-start-step]
:end-before: [jax-end-step]
.. raw:: html
<br><hr>
**What's next?**
Visit the :doc:`Examples <examples>` section for training and evaluation demonstrations with different environment interfaces and highlighted practices, among others.
|
Toni-SM/skrl/docs/source/intro/installation.rst | Installation
============
In this section, you will find the steps to install the library, troubleshoot known issues, review changes between versions, and more.
.. raw:: html
<br><hr>
**Dependencies**
----------------
**skrl** requires Python 3.6 or higher and the following libraries (they will be installed automatically):
* `gym <https://www.gymlibrary.dev>`_ / `gymnasium <https://gymnasium.farama.org/>`_
* `tqdm <https://tqdm.github.io>`_
* `packaging <https://packaging.pypa.io>`_
* `tensorboard <https://www.tensorflow.org/tensorboard>`_
Machine learning (ML) framework
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
According to the specific ML frameworks, the following libraries are required:
PyTorch
"""""""
* `torch <https://pytorch.org>`_ 1.9.0 or higher
JAX
"""
* `jax <https://jax.readthedocs.io>`_ / `jaxlib <https://jax.readthedocs.io>`_ 0.4.3 or higher
* `flax <https://flax.readthedocs.io>`_
* `optax <https://optax.readthedocs.io>`_
.. raw:: html
<br><hr>
**Library Installation**
------------------------
.. raw:: html
<br>
Python Package Index (PyPI)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
To install **skrl** with pip, execute:
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. code-block:: bash
pip install skrl["torch"]
.. group-tab:: |_4| |jax| |_4|
.. warning::
JAX installs its CPU version if not specified. For GPU/TPU versions visit the JAX
`installation <https://github.com/google/jax#installation>`_ page before proceeding with the steps described below.
.. code-block:: bash
pip install skrl["jax"]
.. group-tab:: All ML frameworks
.. code-block:: bash
pip install skrl["all"]
.. group-tab:: No ML framework
.. code-block:: bash
pip install skrl
.. raw:: html
<br>
GitHub repository
^^^^^^^^^^^^^^^^^
Clone or download the library from its GitHub repository (https://github.com/Toni-SM/skrl)
.. code-block:: bash
git clone https://github.com/Toni-SM/skrl.git
cd skrl
* **Install in editable/development mode** (links the package to its original location allowing any modifications to be reflected directly in its Python environment)
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. code-block:: bash
pip install -e .["torch"]
.. group-tab:: |_4| |jax| |_4|
.. warning::
JAX installs its CPU version if not specified. For GPU/TPU versions visit the JAX
`installation <https://github.com/google/jax#installation>`_ page before proceeding with the steps described below.
.. code-block:: bash
pip install -e .["jax"]
.. group-tab:: All ML frameworks
.. code-block:: bash
pip install -e .["all"]
.. group-tab:: No ML framework
.. code-block:: bash
pip install -e .
* **Install in the current Python site-packages directory** (modifications to the code downloaded from GitHub will not be reflected in your Python environment)
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. code-block:: bash
pip install .["torch"]
.. group-tab:: |_4| |jax| |_4|
.. warning::
JAX installs its CPU version if not specified. For GPU/TPU versions visit the JAX
`installation <https://github.com/google/jax#installation>`_ page before proceeding with the steps described below.
.. code-block:: bash
pip install .["jax"]
.. group-tab:: All ML frameworks
.. code-block:: bash
pip install .["all"]
.. group-tab:: No ML framework
.. code-block:: bash
pip install .
.. raw:: html
<br><hr>
**Discussions and issues**
--------------------------
To ask questions or discuss about the library visit skrl's GitHub discussions
.. centered:: https://github.com/Toni-SM/skrl/discussions
Bug detection and/or correction, feature requests and everything else are more than welcome. Come on, open a new issue!
.. centered:: https://github.com/Toni-SM/skrl/issues
.. raw:: html
<br><hr>
**Known issues and troubleshooting**
------------------------------------
1. When using the parallel trainer with PyTorch 1.12.
See PyTorch issue `#80831 <https://github.com/pytorch/pytorch/issues/80831>`_
.. code-block:: text
AttributeError: 'Adam' object has no attribute '_warned_capturable_if_run_uncaptured'
2. When installing the JAX version in Python 3.7 (e.g. OmniIsaacGymEnvs or Isaac Orbit on Isaac Sim 2022.2.1 and earlier).
.. code-block:: text
ERROR: Ignored the following versions that require a different python version: 0.4.0 Requires-Python >=3.8; ...
ERROR: Could not find a version that satisfies the requirement jax>=0.4.3; extra == "jax" (from skrl[jax]) (from versions: 0.0, ..., 0.3.25)
ERROR: No matching distribution found for jax>=0.4.3; extra == "jax"
JAX support for Python 3.7 is up to version 0.3.25, while skrl requires ``jax>=0.4.3``.
Furthermore, ``jaxlib<=0.3.25`` builds are only available up to NVIDIA CUDA 11 and cuDNN 8.2 versions.
However, it is possible to use **skrl** under these circumstances, subject to the following points:
* Install JAX, Flax and Optax manually using ``pip install jax flax optax`` and ignore the installation errors for skrl.
* The ``jax.Device = jax.xla.Device`` statement is required by skrl to support ``jax<0.4.3``.
* Overload models ``__hash__`` method to avoid :literal:`"TypeError: Failed to hash Flax Module"`.
3. When training/evaluating using JAX in Python 3.7 (e.g. OmniIsaacGymEnvs or Isaac Orbit on Isaac Sim 2022.2.1 and earlier).
.. code-block:: text
TypeError: Failed to hash Flax Module. The module probably contains unhashable attributes
Overload the ``__hash__`` method for each defined model to avoid this issue:
.. code-block:: python
def __hash__(self):
return id(self)
4. When training/evaluating using JAX with the NVIDIA Isaac Gym Preview, Isaac Orbit or Omniverse Isaac Gym environments.
.. code-block:: text
PxgCudaDeviceMemoryAllocator fail to allocate memory XXXXXX bytes!! Result = 2
RuntimeError: CUDA error: an illegal memory access was encountered
NVIDIA environments use PyTorch as a backend, and both PyTorch (for CUDA kernels, among others) and JAX preallocate GPU memory,
which can lead to out-of-memory (OOM) problems. Reduce or disable GPU memory preallocation as indicated in JAX
`GPU memory allocation <https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html>`_ to avoid this issue. For example:
.. code-block:: bash
export XLA_PYTHON_CLIENT_MEM_FRACTION=.50 # lowering preallocated GPU memory to 50%
.. raw:: html
<br><hr>
**Changelog**
-------------
.. literalinclude:: ../../../CHANGELOG.md
:language: markdown
|
Toni-SM/skrl/docs/source/intro/examples.rst | Examples
========
In this section, you will find a variety of examples that demonstrate how to use this library to solve reinforcement learning tasks. With the knowledge and skills you gain from trying these examples, you will be well on your way to using this library to solve your reinforcement learning problems.
.. note::
It is recommended to use the table of contents in the right sidebar for better navigation.
.. raw:: html
<br><hr>
**Gymnasium / Gym**
-------------------
.. raw:: html
<br>
Gymnasium / Gym environments
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Training/evaluation of an agent in `Gymnasium <https://gymnasium.farama.org/>`_ / `Gym <https://www.gymlibrary.dev/>`_ environments (**one agent, one environment**)
.. image:: ../_static/imgs/example_gym.png
:width: 100%
:align: center
:alt: Gymnasium / Gym environments
.. raw:: html
<br>
**Benchmark results** are listed in `Benchmark results #32 (Gymnasium/Gym) <https://github.com/Toni-SM/skrl/discussions/32#discussioncomment-4308370>`_
.. tabs::
.. group-tab:: Gymnasium
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - CartPole
- :download:`torch_gymnasium_cartpole_cem.py <../examples/gymnasium/torch_gymnasium_cartpole_cem.py>`
|br| :download:`torch_gymnasium_cartpole_dqn.py <../examples/gymnasium/torch_gymnasium_cartpole_dqn.py>`
-
* - FrozenLake
- :download:`torch_gymnasium_frozen_lake_q_learning.py <../examples/gymnasium/torch_gymnasium_frozen_lake_q_learning.py>`
-
* - Pendulum
- :download:`torch_gymnasium_pendulum_ddpg.py <../examples/gymnasium/torch_gymnasium_pendulum_ddpg.py>`
|br| :download:`torch_gymnasium_pendulum_ppo.py <../examples/gymnasium/torch_gymnasium_pendulum_ppo.py>`
|br| :download:`torch_gymnasium_pendulum_sac.py <../examples/gymnasium/torch_gymnasium_pendulum_sac.py>`
|br| :download:`torch_gymnasium_pendulum_td3.py <../examples/gymnasium/torch_gymnasium_pendulum_td3.py>`
-
* - PendulumNoVel*
|br| (RNN / GRU / LSTM)
- :download:`torch_gymnasium_pendulumnovel_ddpg_rnn.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_ddpg_rnn.py>`
|br| :download:`torch_gymnasium_pendulumnovel_ddpg_gru.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_ddpg_gru.py>`
|br| :download:`torch_gymnasium_pendulumnovel_ddpg_lstm.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_ddpg_lstm.py>`
|br| :download:`torch_gymnasium_pendulumnovel_ppo_rnn.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_ppo_rnn.py>`
|br| :download:`torch_gymnasium_pendulumnovel_ppo_gru.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_ppo_gru.py>`
|br| :download:`torch_gymnasium_pendulumnovel_ppo_lstm.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_ppo_lstm.py>`
|br| :download:`torch_gymnasium_pendulumnovel_sac_rnn.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_sac_rnn.py>`
|br| :download:`torch_gymnasium_pendulumnovel_sac_gru.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_sac_gru.py>`
|br| :download:`torch_gymnasium_pendulumnovel_sac_lstm.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_sac_lstm.py>`
|br| :download:`torch_gymnasium_pendulumnovel_td3_rnn.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_td3_rnn.py>`
|br| :download:`torch_gymnasium_pendulumnovel_td3_gru.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_td3_gru.py>`
|br| :download:`torch_gymnasium_pendulumnovel_td3_lstm.py <../examples/gymnasium/torch_gymnasium_pendulumnovel_td3_lstm.py>`
-
* - Taxi
- :download:`torch_gymnasium_taxi_sarsa.py <../examples/gymnasium/torch_gymnasium_taxi_sarsa.py>`
-
.. group-tab:: |_4| |jax| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - CartPole
- :download:`jax_gymnasium_cartpole_cem.py <../examples/gymnasium/jax_gymnasium_cartpole_cem.py>`
|br| :download:`jax_gymnasium_cartpole_dqn.py <../examples/gymnasium/jax_gymnasium_cartpole_dqn.py>`
-
* - FrozenLake
-
-
* - Pendulum
- :download:`jax_gymnasium_pendulum_ddpg.py <../examples/gymnasium/jax_gymnasium_pendulum_ddpg.py>`
|br| :download:`jax_gymnasium_pendulum_ppo.py <../examples/gymnasium/jax_gymnasium_pendulum_ppo.py>`
|br| :download:`jax_gymnasium_pendulum_sac.py <../examples/gymnasium/jax_gymnasium_pendulum_sac.py>`
|br| :download:`jax_gymnasium_pendulum_td3.py <../examples/gymnasium/jax_gymnasium_pendulum_td3.py>`
-
* - PendulumNoVel*
|br| (RNN / GRU / LSTM)
- |br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
-
* - Taxi
-
-
.. note::
(*) The examples use a wrapper around the original environment to mask the velocity in the observation. The intention is to make the MDP partially observable and to show the capabilities of recurrent neural networks
.. group-tab:: Gym
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - CartPole
- :download:`torch_gym_cartpole_cem.py <../examples/gym/torch_gym_cartpole_cem.py>`
|br| :download:`torch_gym_cartpole_dqn.py <../examples/gym/torch_gym_cartpole_dqn.py>`
-
* - FrozenLake
- :download:`torch_gym_frozen_lake_q_learning.py <../examples/gym/torch_gym_frozen_lake_q_learning.py>`
-
* - Pendulum
- :download:`torch_gym_pendulum_ddpg.py <../examples/gym/torch_gym_pendulum_ddpg.py>`
|br| :download:`torch_gym_pendulum_ppo.py <../examples/gym/torch_gym_pendulum_ppo.py>`
|br| :download:`torch_gym_pendulum_sac.py <../examples/gym/torch_gym_pendulum_sac.py>`
|br| :download:`torch_gym_pendulum_td3.py <../examples/gym/torch_gym_pendulum_td3.py>`
-
* - PendulumNoVel*
|br| (RNN / GRU / LSTM)
- :download:`torch_gym_pendulumnovel_ddpg_rnn.py <../examples/gym/torch_gym_pendulumnovel_ddpg_rnn.py>`
|br| :download:`torch_gym_pendulumnovel_ddpg_gru.py <../examples/gym/torch_gym_pendulumnovel_ddpg_gru.py>`
|br| :download:`torch_gym_pendulumnovel_ddpg_lstm.py <../examples/gym/torch_gym_pendulumnovel_ddpg_lstm.py>`
|br| :download:`torch_gym_pendulumnovel_ppo_rnn.py <../examples/gym/torch_gym_pendulumnovel_ppo_rnn.py>`
|br| :download:`torch_gym_pendulumnovel_ppo_gru.py <../examples/gym/torch_gym_pendulumnovel_ppo_gru.py>`
|br| :download:`torch_gym_pendulumnovel_ppo_lstm.py <../examples/gym/torch_gym_pendulumnovel_ppo_lstm.py>`
|br| :download:`torch_gym_pendulumnovel_sac_rnn.py <../examples/gym/torch_gym_pendulumnovel_sac_rnn.py>`
|br| :download:`torch_gym_pendulumnovel_sac_gru.py <../examples/gym/torch_gym_pendulumnovel_sac_gru.py>`
|br| :download:`torch_gym_pendulumnovel_sac_lstm.py <../examples/gym/torch_gym_pendulumnovel_sac_lstm.py>`
|br| :download:`torch_gym_pendulumnovel_td3_rnn.py <../examples/gym/torch_gym_pendulumnovel_td3_rnn.py>`
|br| :download:`torch_gym_pendulumnovel_td3_gru.py <../examples/gym/torch_gym_pendulumnovel_td3_gru.py>`
|br| :download:`torch_gym_pendulumnovel_td3_lstm.py <../examples/gym/torch_gym_pendulumnovel_td3_lstm.py>`
-
* - Taxi
- :download:`torch_gym_taxi_sarsa.py <../examples/gym/torch_gym_taxi_sarsa.py>`
-
.. group-tab:: |_4| |jax| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - CartPole
- :download:`jax_gym_cartpole_cem.py <../examples/gym/jax_gym_cartpole_cem.py>`
|br| :download:`jax_gym_cartpole_dqn.py <../examples/gym/jax_gym_cartpole_dqn.py>`
-
* - FrozenLake
-
-
* - Pendulum
- :download:`jax_gym_pendulum_ddpg.py <../examples/gym/jax_gym_pendulum_ddpg.py>`
|br| :download:`jax_gym_pendulum_ppo.py <../examples/gym/jax_gym_pendulum_ppo.py>`
|br| :download:`jax_gym_pendulum_sac.py <../examples/gym/jax_gym_pendulum_sac.py>`
|br| :download:`jax_gym_pendulum_td3.py <../examples/gym/jax_gym_pendulum_td3.py>`
-
* - PendulumNoVel*
|br| (RNN / GRU / LSTM)
- |br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
|br|
-
* - Taxi
-
-
.. note::
(*) The examples use a wrapper around the original environment to mask the velocity in the observation. The intention is to make the MDP partially observable and to show the capabilities of recurrent neural networks
.. raw:: html
<br>
Gymnasium / Gym vectorized environments
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Training/evaluation of an agent in `Gymnasium <https://gymnasium.farama.org/>`_ / `Gym <https://www.gymlibrary.dev/>`_ vectorized environments (**one agent, multiple independent copies of the same environment in parallel**)
.. tabs::
.. group-tab:: Gymnasium
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - CartPole
- :download:`torch_gymnasium_cartpole_vector_dqn.py <../examples/gymnasium/torch_gymnasium_cartpole_vector_dqn.py>`
-
* - FrozenLake
- :download:`torch_gymnasium_frozen_lake_vector_q_learning.py <../examples/gymnasium/torch_gymnasium_frozen_lake_vector_q_learning.py>`
-
* - Pendulum
- :download:`torch_gymnasium_pendulum_vector_ddpg.py <../examples/gymnasium/torch_gymnasium_pendulum_vector_ddpg.py>`
-
* - Taxi
- :download:`torch_gymnasium_taxi_vector_sarsa.py <../examples/gymnasium/torch_gymnasium_taxi_vector_sarsa.py>`
-
.. group-tab:: |_4| |jax| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - CartPole
- :download:`jax_gymnasium_cartpole_vector_dqn.py <../examples/gymnasium/jax_gymnasium_cartpole_vector_dqn.py>`
-
* - FrozenLake
-
-
* - Pendulum
- :download:`jax_gymnasium_pendulum_vector_ddpg.py <../examples/gymnasium/jax_gymnasium_pendulum_vector_ddpg.py>`
-
* - Taxi
-
-
.. group-tab:: Gym
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - CartPole
- :download:`torch_gym_cartpole_vector_dqn.py <../examples/gym/torch_gym_cartpole_vector_dqn.py>`
-
* - FrozenLake
- :download:`torch_gym_frozen_lake_vector_q_learning.py <../examples/gym/torch_gym_frozen_lake_vector_q_learning.py>`
-
* - Pendulum
- :download:`torch_gym_pendulum_vector_ddpg.py <../examples/gym/torch_gym_pendulum_vector_ddpg.py>`
-
* - Taxi
- :download:`torch_gym_taxi_vector_sarsa.py <../examples/gym/torch_gym_taxi_vector_sarsa.py>`
-
.. group-tab:: |_4| |jax| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - CartPole
- :download:`jax_gym_cartpole_vector_dqn.py <../examples/gym/jax_gym_cartpole_vector_dqn.py>`
-
* - FrozenLake
-
-
* - Pendulum
- :download:`jax_gym_pendulum_vector_ddpg.py <../examples/gym/jax_gym_pendulum_vector_ddpg.py>`
-
* - Taxi
-
-
.. raw:: html
<br>
Shimmy (API conversion)
^^^^^^^^^^^^^^^^^^^^^^^
The following examples show the training in several popular environments (Atari, DeepMind Control and OpenAI Gym) that have been converted to the Gymnasium API using the `Shimmy <https://github.com/Farama-Foundation/Shimmy>`_ (API conversion tool) package
.. image:: ../_static/imgs/example_shimmy.png
:width: 100%
:align: center
:alt: Shimmy (API conversion)
.. note::
From **skrl**, no extra implementation is necessary, since it fully supports Gymnasium API
.. note::
Because the Gymnasium API requires that the rendering mode be specified during the initialization of the environment, it is not enough to set the :literal:`headless` option in the trainer configuration to render the environment. In this case, it is necessary to call the :literal:`gymnasium.make` function using :literal:`render_mode="human"` or any other supported option
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - Atari: Pong
- :download:`torch_shimmy_atari_pong_dqn.py <../examples/shimmy/torch_shimmy_atari_pong_dqn.py>`
-
* - DeepMind: Acrobot
- :download:`torch_shimmy_dm_control_acrobot_swingup_sparse_sac.py <../examples/shimmy/torch_shimmy_dm_control_acrobot_swingup_sparse_sac.py>`
-
* - Gym-v21 compatibility
- :download:`torch_shimmy_openai_gym_compatibility_pendulum_ddpg.py <../examples/shimmy/torch_shimmy_openai_gym_compatibility_pendulum_ddpg.py>`
-
.. group-tab:: |_4| |jax| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - Atari: Pong
- :download:`jax_shimmy_atari_pong_dqn.py <../examples/shimmy/jax_shimmy_atari_pong_dqn.py>`
-
* - DeepMind: Acrobot
- :download:`jax_shimmy_dm_control_acrobot_swingup_sparse_sac.py <../examples/shimmy/jax_shimmy_dm_control_acrobot_swingup_sparse_sac.py>`
-
* - Gym-v21 compatibility
- :download:`jax_shimmy_openai_gym_compatibility_pendulum_ddpg.py <../examples/shimmy/jax_shimmy_openai_gym_compatibility_pendulum_ddpg.py>`
-
.. raw:: html
<br><hr>
**Other supported APIs**
------------------------
.. raw:: html
<br>
DeepMind environments
^^^^^^^^^^^^^^^^^^^^^
These examples perform the training of one agent in a DeepMind environment (**one agent, one environment**)
.. image:: ../_static/imgs/example_deepmind.png
:width: 100%
:align: center
:alt: DeepMind environments
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - Control: Cartpole SwingUp
- :download:`dm_suite_cartpole_swingup_ddpg.py <../examples/deepmind/dm_suite_cartpole_swingup_ddpg.py>`
-
* - Manipulation: Reach Site Vision
- :download:`dm_manipulation_stack_sac.py <../examples/deepmind/dm_manipulation_stack_sac.py>`
-
.. raw:: html
<br>
Robosuite environments
^^^^^^^^^^^^^^^^^^^^^^
These examples perform the training of one agent in a robosuite environment (**one agent, one environment**)
.. image:: ../_static/imgs/example_robosuite.png
:width: 50%
:align: center
:alt: robosuite environments
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - TwoArmLift
- :download:`td3_robosuite_two_arm_lift.py <../examples/robosuite/td3_robosuite_two_arm_lift.py>`
-
.. raw:: html
<br>
Bi-DexHands environments
^^^^^^^^^^^^^^^^^^^^^^^^
Multi-agent training/evaluation in a `Bi-DexHands <https://github.com/PKU-MARL/DexterousHands>`_ environment
.. image:: ../_static/imgs/example_bidexhands.png
:width: 75%
:align: center
:alt: bidexhands environments
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - ShadowHandOver
- :download:`torch_bidexhands_shadow_hand_over_ippo.py <../examples/bidexhands/torch_bidexhands_shadow_hand_over_ippo.py>`
|br| :download:`torch_bidexhands_shadow_hand_over_mappo.py <../examples/bidexhands/torch_bidexhands_shadow_hand_over_mappo.py>`
-
.. group-tab:: |_4| |jax| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - ShadowHandOver
- :download:`jax_bidexhands_shadow_hand_over_ippo.py <../examples/bidexhands/jax_bidexhands_shadow_hand_over_ippo.py>`
|br| :download:`jax_bidexhands_shadow_hand_over_mappo.py <../examples/bidexhands/jax_bidexhands_shadow_hand_over_mappo.py>`
-
.. raw:: html
<br><hr>
**NVIDIA Isaac Gym preview**
----------------------------
.. raw:: html
<br>
Isaac Gym environments
^^^^^^^^^^^^^^^^^^^^^^
Training/evaluation of an agent in `Isaac Gym environments <https://github.com/NVIDIA-Omniverse/IsaacGymEnvs>`_ (**one agent, multiple environments**)
.. image:: ../_static/imgs/example_isaacgym.png
:width: 100%
:align: center
:alt: Isaac Gym environments
.. raw:: html
<br>
The agent configuration is mapped, as far as possible, from the `IsaacGymEnvs configuration <https://github.com/NVIDIA-Omniverse/IsaacGymEnvs/tree/main/isaacgymenvs/cfg/train>`_ for rl_games. Shared models or separated models are used depending on the value of the :literal:`network.separate` variable. The following list shows the mapping between the two configurations:
.. tabs::
.. tab:: PPO
.. code-block:: bash
# memory
memory_size = horizon_length
# agent
rollouts = horizon_length
learning_epochs = mini_epochs
mini_batches = horizon_length * num_actors / minibatch_size
discount_factor = gamma
lambda = tau
learning_rate = learning_rate
learning_rate_scheduler = skrl.resources.schedulers.torch.KLAdaptiveLR
learning_rate_scheduler_kwargs = {"kl_threshold": kl_threshold}
random_timesteps = 0
learning_starts = 0
grad_norm_clip = grad_norm # if truncate_grads else 0
ratio_clip = e_clip
value_clip = e_clip
clip_predicted_values = clip_value
entropy_loss_scale = entropy_coef
value_loss_scale = 0.5 * critic_coef
kl_threshold = 0
rewards_shaper = lambda rewards, timestep, timesteps: rewards * scale_value
# trainer
timesteps = horizon_length * max_epochs
.. tab:: DDPG / TD3 / SAC
.. code-block:: bash
# memory
memory_size = replay_buffer_size / num_envs
# agent
gradient_steps = 1
batch_size = batch_size
discount_factor = gamma
polyak = critic_tau
actor_learning_rate = actor_lr
critic_learning_rate = critic_lr
random_timesteps = num_warmup_steps * num_steps_per_episode
learning_starts = num_warmup_steps * num_steps_per_episode
grad_norm_clip = 0
learn_entropy = learnable_temperature
entropy_learning_rate = alpha_lr
initial_entropy_value = init_alpha
target_entropy = None
rewards_shaper = lambda rewards, timestep, timesteps: rewards * scale_value
# trainer
timesteps = num_steps_per_episode * max_epochs
**Benchmark results** are listed in `Benchmark results #32 (NVIDIA Isaac Gym) <https://github.com/Toni-SM/skrl/discussions/32#discussioncomment-3774815>`_
.. note::
Isaac Gym environments implement a functionality to get their configuration from the command line. Because of this feature, setting the :literal:`headless` option from the trainer configuration will not work. In this case, it is necessary to invoke the scripts as follows: :literal:`python script.py headless=True` for Isaac Gym environments (preview 3 and preview 4) or :literal:`python script.py --headless` for Isaac Gym environments (preview 2)
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - AllegroHand
- :download:`torch_allegro_hand_ppo.py <../examples/isaacgym/torch_allegro_hand_ppo.py>`
-
* - Ant
- :download:`torch_ant_ppo.py <../examples/isaacgym/torch_ant_ppo.py>`
|br| :download:`torch_ant_ddpg.py <../examples/isaacgym/torch_ant_ddpg.py>`
|br| :download:`torch_ant_td3.py <../examples/isaacgym/torch_ant_td3.py>`
|br| :download:`torch_ant_sac.py <../examples/isaacgym/torch_ant_sac.py>`
- `IsaacGymEnvs-Ant-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Ant-PPO>`_
|br|
|br|
|br|
* - Anymal
- :download:`torch_anymal_ppo.py <../examples/isaacgym/torch_anymal_ppo.py>`
- `IsaacGymEnvs-Anymal-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Anymal-PPO>`_
* - AnymalTerrain
- :download:`torch_anymal_terrain_ppo.py <../examples/isaacgym/torch_anymal_terrain_ppo.py>`
- `IsaacGymEnvs-AnymalTerrain-PPO <https://huggingface.co/skrl/IsaacGymEnvs-AnymalTerrain-PPO>`_
* - BallBalance
- :download:`torch_ball_balance_ppo.py <../examples/isaacgym/torch_ball_balance_ppo.py>`
- `IsaacGymEnvs-BallBalance-PPO <https://huggingface.co/skrl/IsaacGymEnvs-BallBalance-PPO>`_
* - Cartpole
- :download:`torch_cartpole_ppo.py <../examples/isaacgym/torch_cartpole_ppo.py>`
- `IsaacGymEnvs-Cartpole-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Cartpole-PPO>`_
* - FactoryTaskNutBoltPick
- :download:`torch_factory_task_nut_bolt_pick_ppo.py <../examples/isaacgym/torch_factory_task_nut_bolt_pick_ppo.py>`
- `IsaacGymEnvs-FactoryTaskNutBoltPick-PPO <https://huggingface.co/skrl/IsaacGymEnvs-FactoryTaskNutBoltPick-PPO>`_
* - FactoryTaskNutBoltPlace
- :download:`torch_factory_task_nut_bolt_place_ppo.py <../examples/isaacgym/torch_factory_task_nut_bolt_place_ppo.py>`
- `IsaacGymEnvs-FactoryTaskNutBoltPlace-PPO <https://huggingface.co/skrl/IsaacGymEnvs-FactoryTaskNutBoltPlace-PPO>`_
* - FactoryTaskNutBoltScrew
- :download:`torch_factory_task_nut_bolt_screw_ppo.py <../examples/isaacgym/torch_factory_task_nut_bolt_screw_ppo.py>`
- `IsaacGymEnvs-FactoryTaskNutBoltScrew-PPO <https://huggingface.co/skrl/IsaacGymEnvs-FactoryTaskNutBoltScrew-PPO>`_
* - FrankaCabinet
- :download:`torch_franka_cabinet_ppo.py <../examples/isaacgym/torch_franka_cabinet_ppo.py>`
- `IsaacGymEnvs-FrankaCabinet-PPO <https://huggingface.co/skrl/IsaacGymEnvs-FrankaCabinet-PPO>`_
* - FrankaCubeStack
- :download:`torch_franka_cube_stack_ppo.py <../examples/isaacgym/torch_franka_cube_stack_ppo.py>`
-
* - Humanoid
- :download:`torch_humanoid_ppo.py <../examples/isaacgym/torch_humanoid_ppo.py>`
- `IsaacGymEnvs-Humanoid-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Humanoid-PPO>`_
* - Humanoid-AMP
- :download:`torch_humanoid_amp.py <../examples/isaacgym/torch_humanoid_amp.py>`
-
* - Ingenuity
- :download:`torch_ingenuity_ppo.py <../examples/isaacgym/torch_ingenuity_ppo.py>`
- `IsaacGymEnvs-Ingenuity-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Ingenuity-PPO>`_
* - Quadcopter
- :download:`torch_quadcopter_ppo.py <../examples/isaacgym/torch_quadcopter_ppo.py>`
- `IsaacGymEnvs-Quadcopter-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Quadcopter-PPO>`_
* - ShadowHand
- :download:`torch_shadow_hand_ppo.py <../examples/isaacgym/torch_shadow_hand_ppo.py>`
-
* - Trifinger
- :download:`torch_trifinger_ppo.py <../examples/isaacgym/torch_trifinger_ppo.py>`
-
.. group-tab:: |_4| |jax| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - AllegroHand
- :download:`jax_allegro_hand_ppo.py <../examples/isaacgym/jax_allegro_hand_ppo.py>`
-
* - Ant
- :download:`jax_ant_ppo.py <../examples/isaacgym/jax_ant_ppo.py>`
|br| :download:`jax_ant_ddpg.py <../examples/isaacgym/jax_ant_ddpg.py>`
|br| :download:`jax_ant_td3.py <../examples/isaacgym/jax_ant_sac.py>`
|br| :download:`jax_ant_sac.py <../examples/isaacgym/jax_ant_td3.py>`
- `IsaacGymEnvs-Ant-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Ant-PPO>`_
|br|
|br|
|br|
* - Anymal
- :download:`jax_anymal_ppo.py <../examples/isaacgym/jax_anymal_ppo.py>`
- `IsaacGymEnvs-Anymal-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Anymal-PPO>`_
* - AnymalTerrain
- :download:`jax_anymal_terrain_ppo.py <../examples/isaacgym/jax_anymal_terrain_ppo.py>`
- `IsaacGymEnvs-AnymalTerrain-PPO <https://huggingface.co/skrl/IsaacGymEnvs-AnymalTerrain-PPO>`_
* - BallBalance
- :download:`jax_ball_balance_ppo.py <../examples/isaacgym/jax_ball_balance_ppo.py>`
- `IsaacGymEnvs-BallBalance-PPO <https://huggingface.co/skrl/IsaacGymEnvs-BallBalance-PPO>`_
* - Cartpole
- :download:`jax_cartpole_ppo.py <../examples/isaacgym/jax_cartpole_ppo.py>`
- `IsaacGymEnvs-Cartpole-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Cartpole-PPO>`_
* - FactoryTaskNutBoltPick
- :download:`jax_factory_task_nut_bolt_pick_ppo.py <../examples/isaacgym/jax_factory_task_nut_bolt_pick_ppo.py>`
- `IsaacGymEnvs-FactoryTaskNutBoltPick-PPO <https://huggingface.co/skrl/IsaacGymEnvs-FactoryTaskNutBoltPick-PPO>`_
* - FactoryTaskNutBoltPlace
- :download:`jax_factory_task_nut_bolt_place_ppo.py <../examples/isaacgym/jax_factory_task_nut_bolt_place_ppo.py>`
- `IsaacGymEnvs-FactoryTaskNutBoltPlace-PPO <https://huggingface.co/skrl/IsaacGymEnvs-FactoryTaskNutBoltPlace-PPO>`_
* - FactoryTaskNutBoltScrew
- :download:`jax_factory_task_nut_bolt_screw_ppo.py <../examples/isaacgym/jax_factory_task_nut_bolt_screw_ppo.py>`
- `IsaacGymEnvs-FactoryTaskNutBoltScrew-PPO <https://huggingface.co/skrl/IsaacGymEnvs-FactoryTaskNutBoltScrew-PPO>`_
* - FrankaCabinet
- :download:`jax_franka_cabinet_ppo.py <../examples/isaacgym/jax_franka_cabinet_ppo.py>`
- `IsaacGymEnvs-FrankaCabinet-PPO <https://huggingface.co/skrl/IsaacGymEnvs-FrankaCabinet-PPO>`_
* - FrankaCubeStack
- :download:`jax_franka_cube_stack_ppo.py <../examples/isaacgym/jax_franka_cube_stack_ppo.py>`
-
* - Humanoid
- :download:`jax_humanoid_ppo.py <../examples/isaacgym/jax_humanoid_ppo.py>`
- `IsaacGymEnvs-Humanoid-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Humanoid-PPO>`_
* - Humanoid-AMP
-
-
* - Ingenuity
- :download:`jax_ingenuity_ppo.py <../examples/isaacgym/jax_ingenuity_ppo.py>`
- `IsaacGymEnvs-Ingenuity-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Ingenuity-PPO>`_
* - Quadcopter
- :download:`jax_quadcopter_ppo.py <../examples/isaacgym/jax_quadcopter_ppo.py>`
- `IsaacGymEnvs-Quadcopter-PPO <https://huggingface.co/skrl/IsaacGymEnvs-Quadcopter-PPO>`_
* - ShadowHand
- :download:`jax_shadow_hand_ppo.py <../examples/isaacgym/jax_shadow_hand_ppo.py>`
-
* - Trifinger
- :download:`jax_trifinger_ppo.py <../examples/isaacgym/jax_trifinger_ppo.py>`
-
.. raw:: html
<br><hr>
**NVIDIA Isaac Orbit**
----------------------
.. raw:: html
<br>
Isaac Orbit environments
^^^^^^^^^^^^^^^^^^^^^^^^
Training/evaluation of an agent in `Isaac Orbit environments <https://isaac-orbit.github.io/orbit/index.html>`_ (**one agent, multiple environments**)
.. image:: ../_static/imgs/example_isaac_orbit.png
:width: 100%
:align: center
:alt: Isaac Orbit environments
.. raw:: html
<br>
The agent configuration is mapped, as far as possible, from the `Isaac Orbit configuration <https://github.com/NVIDIA-Omniverse/Orbit/tree/main/source/extensions/omni.isaac.orbit_envs/data/rl_games>`_ for rl_games. Shared models or separated models are used depending on the value of the :literal:`network.separate` variable. The following list shows the mapping between the two configurations:
.. tabs::
.. tab:: PPO
.. code-block:: bash
# memory
memory_size = horizon_length
# agent
rollouts = horizon_length
learning_epochs = mini_epochs
mini_batches = horizon_length * num_actors / minibatch_size
discount_factor = gamma
lambda = tau
learning_rate = learning_rate
learning_rate_scheduler = skrl.resources.schedulers.torch.KLAdaptiveLR
learning_rate_scheduler_kwargs = {"kl_threshold": kl_threshold}
random_timesteps = 0
learning_starts = 0
grad_norm_clip = grad_norm # if truncate_grads else 0
ratio_clip = e_clip
value_clip = e_clip
clip_predicted_values = clip_value
entropy_loss_scale = entropy_coef
value_loss_scale = 0.5 * critic_coef
kl_threshold = 0
rewards_shaper = lambda rewards, timestep, timesteps: rewards * scale_value
# trainer
timesteps = horizon_length * max_epochs
.. tab:: DDPG / TD3 / SAC
.. code-block:: bash
# memory
memory_size = replay_buffer_size / num_envs
# agent
gradient_steps = 1
batch_size = batch_size
discount_factor = gamma
polyak = critic_tau
actor_learning_rate = actor_lr
critic_learning_rate = critic_lr
random_timesteps = num_warmup_steps * num_steps_per_episode
learning_starts = num_warmup_steps * num_steps_per_episode
grad_norm_clip = 0
learn_entropy = learnable_temperature
entropy_learning_rate = alpha_lr
initial_entropy_value = init_alpha
target_entropy = None
rewards_shaper = lambda rewards, timestep, timesteps: rewards * scale_value
# trainer
timesteps = num_steps_per_episode * max_epochs
**Benchmark results** are listed in `Benchmark results #32 (NVIDIA Isaac Orbit) <https://github.com/Toni-SM/skrl/discussions/32#discussioncomment-4744446>`_
.. note::
Isaac Orbit environments implement a functionality to get their configuration from the command line. Because of this feature, setting the :literal:`headless` option from the trainer configuration will not work. In this case, it is necessary to invoke the scripts as follows: :literal:`orbit -p script.py --headless`
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - Isaac-Ant-v0
- :download:`torch_ant_ppo.py <../examples/isaacorbit/torch_ant_ppo.py>`
|br| :download:`torch_ant_ddpg.py <../examples/isaacorbit/torch_ant_ddpg.py>`
|br| :download:`torch_ant_td3.py <../examples/isaacorbit/torch_ant_td3.py>`
|br| :download:`torch_ant_sac.py <../examples/isaacorbit/torch_ant_sac.py>`
- `IsaacOrbit-Isaac-Ant-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Ant-v0-PPO>`_
|br|
|br|
|br|
* - Isaac-Cartpole-v0
- :download:`torch_cartpole_ppo.py <../examples/isaacorbit/torch_cartpole_ppo.py>`
- `IsaacOrbit-Isaac-Cartpole-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Cartpole-v0-PPO>`_
* - Isaac-Humanoid-v0
- :download:`torch_humanoid_ppo.py <../examples/isaacorbit/torch_humanoid_ppo.py>`
- `IsaacOrbit-Isaac-Humanoid-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Humanoid-v0-PPO>`_
* - Isaac-Lift-Franka-v0
- :download:`torch_lift_franka_ppo.py <../examples/isaacorbit/torch_lift_franka_ppo.py>`
- `IsaacOrbit-Isaac-Lift-Franka-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Lift-Franka-v0-PPO>`_
* - Isaac-Reach-Franka-v0
- :download:`torch_reach_franka_ppo.py <../examples/isaacorbit/torch_reach_franka_ppo.py>`
- `IsaacOrbit-Isaac-Reach-Franka-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Reach-Franka-v0-PPO>`_
* - Isaac-Velocity-Anymal-C-v0
- :download:`torch_velocity_anymal_c_ppo.py <../examples/isaacorbit/torch_velocity_anymal_c_ppo.py>`
-
.. group-tab:: |_4| |jax| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - Isaac-Ant-v0
- :download:`jax_ant_ppo.py <../examples/isaacorbit/jax_ant_ppo.py>`
|br| :download:`jax_ant_ddpg.py <../examples/isaacorbit/jax_ant_ddpg.py>`
|br| :download:`jax_ant_td3.py <../examples/isaacorbit/jax_ant_td3.py>`
|br| :download:`jax_ant_sac.py <../examples/isaacorbit/jax_ant_sac.py>`
- `IsaacOrbit-Isaac-Ant-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Ant-v0-PPO>`_
|br|
|br|
|br|
* - Isaac-Cartpole-v0
- :download:`jax_cartpole_ppo.py <../examples/isaacorbit/jax_cartpole_ppo.py>`
- `IsaacOrbit-Isaac-Cartpole-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Cartpole-v0-PPO>`_
* - Isaac-Humanoid-v0
- :download:`jax_humanoid_ppo.py <../examples/isaacorbit/jax_humanoid_ppo.py>`
- `IsaacOrbit-Isaac-Humanoid-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Humanoid-v0-PPO>`_
* - Isaac-Lift-Franka-v0
- :download:`jax_lift_franka_ppo.py <../examples/isaacorbit/jax_lift_franka_ppo.py>`
- `IsaacOrbit-Isaac-Lift-Franka-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Lift-Franka-v0-PPO>`_
* - Isaac-Reach-Franka-v0
- :download:`jax_reach_franka_ppo.py <../examples/isaacorbit/jax_reach_franka_ppo.py>`
- `IsaacOrbit-Isaac-Reach-Franka-v0-PPO <https://huggingface.co/skrl/IsaacOrbit-Isaac-Reach-Franka-v0-PPO>`_
* - Isaac-Velocity-Anymal-C-v0
- :download:`jax_velocity_anymal_c_ppo.py <../examples/isaacorbit/jax_velocity_anymal_c_ppo.py>`
-
.. raw:: html
<br><hr>
**NVIDIA Omniverse Isaac Gym**
------------------------------
.. raw:: html
<br>
Omniverse Isaac Gym environments (OIGE)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Training/evaluation of an agent in `Omniverse Isaac Gym environments (OIGE) <https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs>`_ (**one agent, multiple environments**)
.. image:: ../_static/imgs/example_omniverse_isaacgym.png
:width: 100%
:align: center
:alt: Isaac Gym environments
.. raw:: html
<br>
The agent configuration is mapped, as far as possible, from the `OmniIsaacGymEnvs configuration <https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs/tree/main/omniisaacgymenvs/cfg/train>`_ for rl_games. Shared models or separated models are used depending on the value of the :literal:`network.separate` variable. The following list shows the mapping between the two configurations:
.. tabs::
.. tab:: PPO
.. code-block:: bash
# memory
memory_size = horizon_length
# agent
rollouts = horizon_length
learning_epochs = mini_epochs
mini_batches = horizon_length * num_actors / minibatch_size
discount_factor = gamma
lambda = tau
learning_rate = learning_rate
learning_rate_scheduler = skrl.resources.schedulers.torch.KLAdaptiveLR
learning_rate_scheduler_kwargs = {"kl_threshold": kl_threshold}
random_timesteps = 0
learning_starts = 0
grad_norm_clip = grad_norm # if truncate_grads else 0
ratio_clip = e_clip
value_clip = e_clip
clip_predicted_values = clip_value
entropy_loss_scale = entropy_coef
value_loss_scale = 0.5 * critic_coef
kl_threshold = 0
rewards_shaper = lambda rewards, timestep, timesteps: rewards * scale_value
# trainer
timesteps = horizon_length * max_epochs
.. tab:: DDPG / TD3 / SAC
.. code-block:: bash
# memory
memory_size = replay_buffer_size / num_envs
# agent
gradient_steps = 1
batch_size = batch_size
discount_factor = gamma
polyak = critic_tau
actor_learning_rate = actor_lr
critic_learning_rate = critic_lr
random_timesteps = num_warmup_steps * num_steps_per_episode
learning_starts = num_warmup_steps * num_steps_per_episode
grad_norm_clip = 0
learn_entropy = learnable_temperature
entropy_learning_rate = alpha_lr
initial_entropy_value = init_alpha
target_entropy = None
rewards_shaper = lambda rewards, timestep, timesteps: rewards * scale_value
# trainer
timesteps = num_steps_per_episode * max_epochs
**Benchmark results** are listed in `Benchmark results #32 (NVIDIA Omniverse Isaac Gym) <https://github.com/Toni-SM/skrl/discussions/32#discussioncomment-3774894>`_
.. note::
Omniverse Isaac Gym environments implement a functionality to get their configuration from the command line. Because of this feature, setting the :literal:`headless` option from the trainer configuration will not work. In this case, it is necessary to invoke the scripts as follows: :literal:`python script.py headless=True`
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - AllegroHand
- :download:`torch_allegro_hand_ppo.py <../examples/omniisaacgym/torch_allegro_hand_ppo.py>`
- `OmniIsaacGymEnvs-AllegroHand-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-AllegroHand-PPO>`_
* - Ant
- :download:`torch_ant_ppo.py <../examples/omniisaacgym/torch_ant_ppo.py>`
|br| :download:`torch_ant_ddpg.py <../examples/omniisaacgym/torch_ant_ddpg.py>`
|br| :download:`torch_ant_td3.py <../examples/omniisaacgym/torch_ant_td3.py>`
|br| :download:`torch_ant_sac.py <../examples/omniisaacgym/torch_ant_sac.py>`
- `OmniIsaacGymEnvs-Ant-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-Ant-PPO>`_
|br|
|br|
|br|
* - Ant (multi-threaded)
- :download:`torch_ant_mt_ppo.py <../examples/omniisaacgym/torch_ant_mt_ppo.py>`
- `OmniIsaacGymEnvs-Ant-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-Ant-PPO>`_
* - Anymal
- :download:`torch_anymal_ppo.py <../examples/omniisaacgym/torch_anymal_ppo.py>`
-
* - AnymalTerrain
- :download:`torch_anymal_terrain_ppo.py <../examples/omniisaacgym/torch_anymal_terrain_ppo.py>`
-
* - BallBalance
- :download:`torch_ball_balance_ppo.py <../examples/omniisaacgym/torch_ball_balance_ppo.py>`
- `OmniIsaacGymEnvs-BallBalance-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-BallBalance-PPO>`_
* - Cartpole
- :download:`torch_cartpole_ppo.py <../examples/omniisaacgym/torch_cartpole_ppo.py>`
- `OmniIsaacGymEnvs-Cartpole-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-Cartpole-PPO>`_
* - Cartpole (multi-threaded)
- :download:`torch_cartpole_mt_ppo.py <../examples/omniisaacgym/torch_cartpole_mt_ppo.py>`
- `OmniIsaacGymEnvs-Cartpole-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-Cartpole-PPO>`_
* - Crazyflie
- :download:`torch_crazyflie_ppo.py <../examples/omniisaacgym/torch_crazyflie_ppo.py>`
- `OmniIsaacGymEnvs-Crazyflie-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-Crazyflie-PPO>`_
* - FactoryTaskNutBoltPick
- :download:`torch_factory_task_nut_bolt_pick_ppo.py <../examples/omniisaacgym/torch_factory_task_nut_bolt_pick_ppo.py>`
-
* - FrankaCabinet
- :download:`torch_franka_cabinet_ppo.py <../examples/omniisaacgym/torch_franka_cabinet_ppo.py>`
- `OmniIsaacGymEnvs-FrankaCabinet-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-FrankaCabinet-PPO>`_
* - Humanoid
- :download:`torch_humanoid_ppo.py <../examples/omniisaacgym/torch_humanoid_ppo.py>`
- `OmniIsaacGymEnvs-Humanoid-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-Humanoid-PPO>`_
* - Ingenuity
- :download:`torch_ingenuity_ppo.py <../examples/omniisaacgym/torch_ingenuity_ppo.py>`
- `OmniIsaacGymEnvs-Ingenuity-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-Ingenuity-PPO>`_
* - Quadcopter
- :download:`torch_quadcopter_ppo.py <../examples/omniisaacgym/torch_quadcopter_ppo.py>`
- `OmniIsaacGymEnvs-Quadcopter-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-Quadcopter-PPO>`_
* - ShadowHand
- :download:`torch_shadow_hand_ppo.py <../examples/omniisaacgym/torch_shadow_hand_ppo.py>`
- `OmniIsaacGymEnvs-ShadowHand-PPO <https://huggingface.co/skrl/OmniIsaacGymEnvs-ShadowHand-PPO>`_
.. group-tab:: |_4| |jax| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - AllegroHand
- :download:`jax_allegro_hand_ppo.py <../examples/omniisaacgym/jax_allegro_hand_ppo.py>`
-
* - Ant
- :download:`jax_ant_ppo.py <../examples/omniisaacgym/jax_ant_ppo.py>`
|br| :download:`jax_ant_ddpg.py <../examples/omniisaacgym/jax_ant_ddpg.py>`
|br| :download:`jax_ant_td3.py <../examples/omniisaacgym/jax_ant_sac.py>`
|br| :download:`jax_ant_sac.py <../examples/omniisaacgym/jax_ant_td3.py>`
- |br|
|br|
|br|
|br|
* - Ant (multi-threaded)
- :download:`jax_ant_mt_ppo.py <../examples/omniisaacgym/jax_ant_mt_ppo.py>`
-
* - Anymal
- :download:`jax_anymal_ppo.py <../examples/omniisaacgym/jax_anymal_ppo.py>`
-
* - AnymalTerrain
- :download:`jax_anymal_terrain_ppo.py <../examples/omniisaacgym/jax_anymal_terrain_ppo.py>`
-
* - BallBalance
- :download:`jax_ball_balance_ppo.py <../examples/omniisaacgym/jax_ball_balance_ppo.py>`
-
* - Cartpole
- :download:`jax_cartpole_ppo.py <../examples/omniisaacgym/jax_cartpole_ppo.py>`
-
* - Cartpole (multi-threaded)
- :download:`jax_cartpole_mt_ppo.py <../examples/omniisaacgym/jax_cartpole_mt_ppo.py>`
-
* - Crazyflie
- :download:`jax_crazyflie_ppo.py <../examples/omniisaacgym/jax_crazyflie_ppo.py>`
-
* - FactoryTaskNutBoltPick
- :download:`jax_factory_task_nut_bolt_pick_ppo.py <../examples/omniisaacgym/jax_factory_task_nut_bolt_pick_ppo.py>`
-
* - FrankaCabinet
- :download:`jax_franka_cabinet_ppo.py <../examples/omniisaacgym/jax_franka_cabinet_ppo.py>`
-
* - Humanoid
- :download:`jax_humanoid_ppo.py <../examples/omniisaacgym/jax_humanoid_ppo.py>`
-
* - Ingenuity
- :download:`jax_ingenuity_ppo.py <../examples/omniisaacgym/jax_ingenuity_ppo.py>`
-
* - Quadcopter
- :download:`jax_quadcopter_ppo.py <../examples/omniisaacgym/jax_quadcopter_ppo.py>`
-
* - ShadowHand
- :download:`jax_shadow_hand_ppo.py <../examples/omniisaacgym/jax_shadow_hand_ppo.py>`
-
.. raw:: html
<br>
Omniverse Isaac Gym environments (simultaneous learning by scope)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Simultaneous training/evaluation by scopes (subsets of environments among all available environments) of several agents in the same run in `OIGE <https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs>`_'s Ant environment (**multiple agents and environments**)
.. image:: ../_static/imgs/example_parallel.jpg
:width: 100%
:align: center
:alt: Simultaneous training
.. raw:: html
<br>
Three cases are presented:
* Simultaneous (**sequential**) training of agents that **share the same memory** and whose scopes are automatically selected to be as equal as possible.
* Simultaneous (**sequential**) training of agents **without sharing memory** and whose scopes are specified manually.
* Simultaneous (**parallel**) training of agents **without sharing memory** and whose scopes are specified manually.
.. note::
Omniverse Isaac Gym environments implement a functionality to get their configuration from the command line. Because of this feature, setting the :literal:`headless` option from the trainer configuration will not work. In this case, it is necessary to invoke the scripts as follows: :literal:`python script.py headless=True`
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Type
- Script
* - Sequential training (shared memory)
- :download:`torch_ant_ddpg_td3_sac_sequential_shared_memory.py <../examples/omniisaacgym/torch_ant_ddpg_td3_sac_sequential_shared_memory.py>`
* - Sequential training (unshared memory)
- :download:`torch_ant_ddpg_td3_sac_sequential_unshared_memory.py <../examples/omniisaacgym/torch_ant_ddpg_td3_sac_sequential_unshared_memory.py>`
* - Parallel training (unshared memory)
- :download:`torch_ant_ddpg_td3_sac_parallel_unshared_memory.py <../examples/omniisaacgym/torch_ant_ddpg_td3_sac_parallel_unshared_memory.py>`
.. raw:: html
<br>
Omniverse Isaac Sim (single environment)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Training/evaluation of an agent in Omniverse Isaac Sim environment implemented using the Gym interface (**one agent, one environment**)
.. tabs::
.. tab:: Isaac Sim 2022.X.X (Cartpole)
This example performs the training of an agent in the Isaac Sim's Cartpole environment described in the `Creating New RL Environment <https://docs.omniverse.nvidia.com/isaacsim/latest/tutorial_gym_new_rl_example.html>`_ tutorial
Use the steps described below to setup and launch the experiment after follow the tutorial
.. code-block:: bash
# download the sample code from GitHub in the directory containing the cartpole_task.py script
wget https://raw.githubusercontent.com/Toni-SM/skrl/main/docs/source/examples/isaacsim/torch_isaacsim_cartpole_ppo.py
# run the experiment
PYTHON_PATH torch_isaacsim_cartpole_ppo.py
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - Cartpole
- :download:`torch_isaacsim_cartpole_ppo.py <../examples/isaacsim/torch_isaacsim_cartpole_ppo.py>`
-
.. tab:: Isaac Sim 2021.2.1 (JetBot)
This example performs the training of an agent in the Isaac Sim's JetBot environment. The following components or practices are exemplified (highlighted):
- Define and instantiate Convolutional Neural Networks (CNN) to learn from 128 X 128 RGB images
Use the steps described below (for a local workstation or a remote container) to setup and launch the experiment
.. tabs::
.. tab:: Local workstation (setup)
.. code-block:: bash
# create a working directory and change to it
mkdir ~/.local/share/ov/pkg/isaac_sim-2021.2.1/standalone_examples/api/omni.isaac.jetbot/skrl_example
cd ~/.local/share/ov/pkg/isaac_sim-2021.2.1/standalone_examples/api/omni.isaac.jetbot/skrl_example
# install the skrl library in editable mode from the working directory
~/.local/share/ov/pkg/isaac_sim-2021.2.1/python.sh -m pip install -e git+https://github.com/Toni-SM/skrl.git#egg=skrl
# download the sample code from GitHub
wget https://raw.githubusercontent.com/Toni-SM/skrl/main/docs/source/examples/isaacsim/torch_isaacsim_jetbot_ppo.py
# copy the Isaac Sim sample environment (JetBotEnv) to the working directory
cp ../stable_baselines_example/env.py .
# run the experiment
~/.local/share/ov/pkg/isaac_sim-2021.2.1/python.sh torch_isaacsim_jetbot_ppo.py
.. tab:: Remote container (setup)
.. code-block:: bash
# create a working directory and change to it
mkdir /isaac-sim/standalone_examples/api/omni.isaac.jetbot/skrl_example
cd /isaac-sim/standalone_examples/api/omni.isaac.jetbot/skrl_example
# install the skrl library in editable mode from the working directory
/isaac-sim/kit/python/bin/python3 -m pip install -e git+https://github.com/Toni-SM/skrl.git#egg=skrl
# download the sample code from GitHub
wget https://raw.githubusercontent.com/Toni-SM/skrl/main/docs/source/examples/isaacsim/torch_isaacsim_jetbot_ppo.py
# copy the Isaac Sim sample environment (JetBotEnv) to the working directory
cp ../stable_baselines_example/env.py .
# run the experiment
/isaac-sim/python.sh torch_isaacsim_jetbot_ppo.py
.. raw:: html
<br>
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. list-table::
:align: left
:header-rows: 1
:stub-columns: 1
:class: nowrap
* - Environment
- Script
- Checkpoint (Hugging Face)
* - JetBot
- :download:`torch_isaacsim_jetbot_ppo.py <../examples/isaacsim/torch_isaacsim_jetbot_ppo.py>`
-
.. raw:: html
<br><hr>
**Real-world examples**
-----------------------
These examples show basic real-world and sim2real use cases to guide and support advanced RL implementations
.. raw:: html
<br>
.. tabs::
.. tab:: Franka Emika Panda
**3D reaching task (Franka's gripper must reach a certain target point in space)**. The training was done in Omniverse Isaac Gym. The real robot control is performed through the Python API of a modified version of *frankx* (see `frankx's pull request #44 <https://github.com/pantor/frankx/pull/44>`_), a high-level motion library around *libfranka*. Training and evaluation is performed for both Cartesian and joint control space
.. raw:: html
<br>
**Implementation** (see details in the table below):
* The observation space is composed of the episode's normalized progress, the robot joints' normalized positions (:math:`q`) in the interval -1 to 1, the robot joints' velocities (:math:`\dot{q}`) affected by a random uniform scale for generalization, and the target's position in space (:math:`target_{_{XYZ}}`) with respect to the robot's base
* The action space, bounded in the range -1 to 1, consists of the following. For the joint control it's robot joints' position scaled change. For the Cartesian control it's the end-effector's position (:math:`ee_{_{XYZ}}`) scaled change. The end-effector position frame corresponds to the point where the left finger connects to the gripper base in simulation, whereas in the real world it corresponds to the end of the fingers. The gripper fingers remain closed all the time in both cases
* The instantaneous reward is the negative value of the Euclidean distance (:math:`\text{d}`) between the robot end-effector and the target point position. The episode terminates when this distance is less than 0.035 meters in simulation (0.075 meters in real-world) or when the defined maximum timestep is reached
* The target position lies within a rectangular cuboid of dimensions 0.5 x 0.5 x 0.2 meters centered at (0.5, 0.0, 0.2) meters with respect to the robot's base. The robot joints' positions are drawn from an initial configuration [0º, -45º, 0º, -135º, 0º, 90º, 45º] modified with uniform random values between -7º and 7º approximately
.. list-table::
:header-rows: 1
* - Variable
- Formula / value
- Size
* - Observation space
- :math:`\dfrac{t}{t_{max}},\; 2 \dfrac{q - q_{min}}{q_{max} - q_{min}} - 1,\; 0.1\,\dot{q}\,U(0.5,1.5),\; target_{_{XYZ}}`
- 18
* - Action space (joint)
- :math:`\dfrac{2.5}{120} \, \Delta q`
- 7
* - Action space (Cartesian)
- :math:`\dfrac{1}{100} \, \Delta ee_{_{XYZ}}`
- 3
* - Reward
- :math:`-\text{d}(ee_{_{XYZ}},\; target_{_{XYZ}})`
-
* - Episode termination
- :math:`\text{d}(ee_{_{XYZ}},\; target_{_{XYZ}}) \le 0.035 \quad` or :math:`\quad t \ge t_{max} - 1`
-
* - Maximum timesteps (:math:`t_{max}`)
- 100
-
.. raw:: html
<br>
**Workflows:**
.. tabs::
.. tab:: Real-world
.. warning::
Make sure you have the e-stop on hand in case something goes wrong in the run. **Control via RL can be dangerous and unsafe for both the operator and the robot**
.. raw:: html
<video width="100%" controls autoplay>
<source src="https://user-images.githubusercontent.com/22400377/190899202-6b80c48d-fc49-48e9-b277-24814d0adab1.mp4" type="video/mp4">
</video>
<strong>Target position entered via the command prompt or generated randomly</strong>
<br><br>
<video width="100%" controls autoplay>
<source src="https://user-images.githubusercontent.com/22400377/190899205-752f654e-9310-4696-a6b2-bfa57d5325f2.mp4" type="video/mp4">
</video>
<strong>Target position in X and Y obtained with a USB-camera (position in Z fixed at 0.2 m)</strong>
|
**Prerequisites:**
A physical Franka Emika Panda robot with `Franka Control Interface (FCI) <https://frankaemika.github.io/docs/index.html>`_ is required. Additionally, the *frankx* library must be available in the python environment (see `frankx's pull request #44 <https://github.com/pantor/frankx/pull/44>`_ for the RL-compatible version installation)
**Files**
* Environment: :download:`reaching_franka_real_env.py <../examples/real_world/franka_emika_panda/reaching_franka_real_env.py>`
* Evaluation script: :download:`reaching_franka_real_skrl_eval.py <../examples/real_world/franka_emika_panda/reaching_franka_real_skrl_eval.py>`
* Checkpoints (:literal:`agent_joint.pt`, :literal:`agent_cartesian.pt`): :download:`trained_checkpoints.zip <https://github.com/Toni-SM/skrl/files/9595293/trained_checkpoints.zip>`
**Evaluation:**
.. code-block:: bash
python3 reaching_franka_real_skrl_eval.py
**Main environment configuration:**
.. note::
In the joint control space the final control of the robot is performed through the Cartesian pose (forward kinematics from specified values for the joints)
The control space (Cartesian or joint), the robot motion type (waypoint or impedance) and the target position acquisition (command prompt / automatically generated or USB-camera) can be specified in the environment class constructor (from :literal:`reaching_franka_real_skrl_eval.py`) as follow:
.. code-block:: python
control_space = "joint" # joint or cartesian
motion_type = "waypoint" # waypoint or impedance
camera_tracking = False # True for USB-camera tracking
.. tab:: Simulation (Omniverse Isaac Gym)
.. raw:: html
<video width="100%" controls autoplay>
<source src="https://user-images.githubusercontent.com/22400377/211668430-7cd4668b-e79a-46a9-bdbc-3212388b6b6d.mp4" type="video/mp4">
</video>
.. raw:: html
<img width="100%" src="https://user-images.githubusercontent.com/22400377/190921341-6feb255a-04d4-4e51-bc7a-f939116dd02d.png">
|
**Prerequisites:**
All installation steps described in Omniverse Isaac Gym's `Overview & Getting Started <https://docs.omniverse.nvidia.com/isaacsim/latest/tutorial_gym_isaac_gym.html>`_ section must be fulfilled (especially the subsection 1.3. Installing Examples Repository)
**Files** (the implementation is self-contained so no specific location is required):
* Environment: :download:`reaching_franka_omniverse_isaacgym_env.py <../examples/real_world/franka_emika_panda/reaching_franka_omniverse_isaacgym_env.py>`
* Training script: :download:`reaching_franka_omniverse_isaacgym_skrl_train.py <../examples/real_world/franka_emika_panda/reaching_franka_omniverse_isaacgym_skrl_train.py>`
* Evaluation script: :download:`reaching_franka_omniverse_isaacgym_skrl_eval.py <../examples/real_world/franka_emika_panda/reaching_franka_omniverse_isaacgym_skrl_eval.py>`
* Checkpoints (:literal:`agent_joint.pt`, :literal:`agent_cartesian.pt`): :download:`trained_checkpoints.zip <https://github.com/Toni-SM/skrl/files/9595293/trained_checkpoints.zip>`
**Training and evaluation:**
.. code-block:: bash
# training (local workstation)
~/.local/share/ov/pkg/isaac_sim-*/python.sh reaching_franka_omniverse_isaacgym_skrl_train.py
# training (docker container)
/isaac-sim/python.sh reaching_franka_omniverse_isaacgym_skrl_train.py
.. code-block:: bash
# evaluation (local workstation)
~/.local/share/ov/pkg/isaac_sim-*/python.sh reaching_franka_omniverse_isaacgym_skrl_eval.py
# evaluation (docker container)
/isaac-sim/python.sh reaching_franka_omniverse_isaacgym_skrl_eval.py
**Main environment configuration:**
The control space (Cartesian or joint) can be specified in the task configuration dictionary (from :literal:`reaching_franka_omniverse_isaacgym_skrl_train.py`) as follow:
.. code-block:: python
TASK_CFG["task"]["env"]["controlSpace"] = "joint" # "joint" or "cartesian"
.. tab:: Simulation (Isaac Gym)
.. raw:: html
<video width="100%" controls autoplay>
<source src="https://user-images.githubusercontent.com/22400377/193537523-e0f0f8ad-2295-410c-ba9a-2a16c827a498.mp4" type="video/mp4">
</video>
.. raw:: html
<img width="100%" src="https://user-images.githubusercontent.com/22400377/193546966-bcf966e6-98d8-4b41-bc15-bd7364a79381.png">
|
**Prerequisites:**
All installation steps described in Isaac Gym's `Installation <https://github.com/NVIDIA-Omniverse/IsaacGymEnvs#installation>`_ section must be fulfilled
**Files** (the implementation is self-contained so no specific location is required):
* Environment: :download:`reaching_franka_isaacgym_env.py <../examples/real_world/franka_emika_panda/reaching_franka_isaacgym_env.py>`
* Training script: :download:`reaching_franka_isaacgym_skrl_train.py <../examples/real_world/franka_emika_panda/reaching_franka_isaacgym_skrl_train.py>`
* Evaluation script: :download:`reaching_franka_isaacgym_skrl_eval.py <../examples/real_world/franka_emika_panda/reaching_franka_isaacgym_skrl_eval.py>`
**Training and evaluation:**
.. note::
The checkpoints obtained in Isaac Gym were not evaluated with the real robot. However, they were evaluated in Omniverse Isaac Gym showing successful performance
.. code-block:: bash
# training (with the Python virtual environment active)
python reaching_franka_isaacgym_skrl_train.py
.. code-block:: bash
# evaluation (with the Python virtual environment active)
python reaching_franka_isaacgym_skrl_eval.py
**Main environment configuration:**
The control space (Cartesian or joint) can be specified in the task configuration dictionary (from :literal:`reaching_franka_isaacgym_skrl_train.py`) as follow:
.. code-block:: python
TASK_CFG["env"]["controlSpace"] = "joint" # "joint" or "cartesian"
.. tab:: Kuka LBR iiwa
**3D reaching task (iiwa's end-effector must reach a certain target point in space)**. The training was done in Omniverse Isaac Gym. The real robot control is performed through the Python, ROS and ROS2 APIs of `libiiwa <https://libiiwa.readthedocs.io>`_, a scalable multi-control framework for the KUKA LBR Iiwa robots. Training and evaluation is performed for both Cartesian and joint control space
.. raw:: html
<br>
**Implementation** (see details in the table below):
* The observation space is composed of the episode's normalized progress, the robot joints' normalized positions (:math:`q`) in the interval -1 to 1, the robot joints' velocities (:math:`\dot{q}`) affected by a random uniform scale for generalization, and the target's position in space (:math:`target_{_{XYZ}}`) with respect to the robot's base
* The action space, bounded in the range -1 to 1, consists of the following. For the joint control it's robot joints' position scaled change. For the Cartesian control it's the end-effector's position (:math:`ee_{_{XYZ}}`) scaled change
* The instantaneous reward is the negative value of the Euclidean distance (:math:`\text{d}`) between the robot end-effector and the target point position. The episode terminates when this distance is less than 0.035 meters in simulation (0.075 meters in real-world) or when the defined maximum timestep is reached
* The target position lies within a rectangular cuboid of dimensions 0.2 x 0.4 x 0.4 meters centered at (0.6, 0.0, 0.4) meters with respect to the robot's base. The robot joints' positions are drawn from an initial configuration [0º, 0º, 0º, -90º, 0º, 90º, 0º] modified with uniform random values between -7º and 7º approximately
.. list-table::
:header-rows: 1
* - Variable
- Formula / value
- Size
* - Observation space
- :math:`\dfrac{t}{t_{max}},\; 2 \dfrac{q - q_{min}}{q_{max} - q_{min}} - 1,\; 0.1\,\dot{q}\,U(0.5,1.5),\; target_{_{XYZ}}`
- 18
* - Action space (joint)
- :math:`\dfrac{2.5}{120} \, \Delta q`
- 7
* - Action space (Cartesian)
- :math:`\dfrac{1}{100} \, \Delta ee_{_{XYZ}}`
- 3
* - Reward
- :math:`-\text{d}(ee_{_{XYZ}},\; target_{_{XYZ}})`
-
* - Episode termination
- :math:`\text{d}(ee_{_{XYZ}},\; target_{_{XYZ}}) \le 0.035 \quad` or :math:`\quad t \ge t_{max} - 1`
-
* - Maximum timesteps (:math:`t_{max}`)
- 100
-
.. raw:: html
<br>
**Workflows:**
.. tabs::
.. tab:: Real-world
.. warning::
Make sure you have the smartHMI on hand in case something goes wrong in the run. **Control via RL can be dangerous and unsafe for both the operator and the robot**
.. raw:: html
<video width="100%" controls autoplay>
<source src="https://user-images.githubusercontent.com/22400377/212192766-9698bfba-af27-41b8-8a11-17ed3d22c020.mp4" type="video/mp4">
</video>
**Prerequisites:**
A physical Kuka LBR iiwa robot is required. Additionally, the *libiiwa* library must be installed (visit the `libiiwa <https://libiiwa.readthedocs.io>`_ documentation for installation details)
**Files**
* Environment: :download:`reaching_iiwa_real_env.py <../examples/real_world/kuka_lbr_iiwa/reaching_iiwa_real_env.py>`
* Evaluation script: :download:`reaching_iiwa_real_skrl_eval.py <../examples/real_world/kuka_lbr_iiwa/reaching_iiwa_real_skrl_eval.py>`
* Checkpoints (:literal:`agent_joint.pt`, :literal:`agent_cartesian.pt`): :download:`trained_checkpoints.zip <https://github.com/Toni-SM/skrl/files/10406561/trained_checkpoints.zip>`
**Evaluation:**
.. code-block:: bash
python3 reaching_iiwa_real_skrl_eval.py
**Main environment configuration:**
The control space (Cartesian or joint) can be specified in the environment class constructor (from :literal:`reaching_iiwa_real_skrl_eval.py`) as follow:
.. code-block:: python
control_space = "joint" # joint or cartesian
.. tab:: Real-world (ROS/ROS2)
.. warning::
Make sure you have the smartHMI on hand in case something goes wrong in the run. **Control via RL can be dangerous and unsafe for both the operator and the robot**
.. raw:: html
<video width="100%" controls autoplay>
<source src="https://user-images.githubusercontent.com/22400377/212192817-12115478-e6a8-4502-b33f-b072664b1959.mp4" type="video/mp4">
</video>
**Prerequisites:**
A physical Kuka LBR iiwa robot is required. Additionally, the *libiiwa* library must be installed (visit the `libiiwa <https://libiiwa.readthedocs.io>`_ documentation for installation details) and a Robot Operating System (ROS or ROS2) distribution must be available
**Files**
* Environment (ROS): :download:`reaching_iiwa_real_ros_env.py <../examples/real_world/kuka_lbr_iiwa/reaching_iiwa_real_ros_env.py>`
* Environment (ROS2): :download:`reaching_iiwa_real_ros2_env.py <../examples/real_world/kuka_lbr_iiwa/reaching_iiwa_real_ros2_env.py>`
* Evaluation script: :download:`reaching_iiwa_real_ros_ros2_skrl_eval.py <../examples/real_world/kuka_lbr_iiwa/reaching_iiwa_real_ros_ros2_skrl_eval.py>`
* Checkpoints (:literal:`agent_joint.pt`, :literal:`agent_cartesian.pt`): :download:`trained_checkpoints.zip <https://github.com/Toni-SM/skrl/files/10406561/trained_checkpoints.zip>`
.. note::
Source the ROS/ROS2 distribution and the ROS/ROS workspace containing the libiiwa packages before executing the scripts
**Evaluation:**
.. note::
The environment (:literal:`reaching_iiwa_real_ros_env.py` or :literal:`reaching_iiwa_real_ros2_env.py`) to be loaded will be automatically selected based on the sourced ROS distribution (ROS or ROS2) at script execution
.. code-block:: bash
python3 reaching_iiwa_real_ros_ros2_skrl_eval.py
**Main environment configuration:**
The control space (Cartesian or joint) can be specified in the environment class constructor (from :literal:`reaching_iiwa_real_ros_ros2_skrl_eval.py`) as follow:
.. code-block:: python
control_space = "joint" # joint or cartesian
.. tab:: Simulation (Omniverse Isaac Gym)
.. raw:: html
<video width="100%" controls autoplay>
<source src="https://user-images.githubusercontent.com/22400377/211668313-7bcbcd41-cde5-441e-abb4-82fff7616f06.mp4" type="video/mp4">
</video>
.. raw:: html
<img width="100%" src="https://user-images.githubusercontent.com/22400377/212194442-f6588b98-38af-4f29-92a3-3c853a7e31f4.png">
|
**Prerequisites:**
All installation steps described in Omniverse Isaac Gym's `Overview & Getting Started <https://docs.omniverse.nvidia.com/isaacsim/latest/tutorial_gym_isaac_gym.html>`_ section must be fulfilled (especially the subsection 1.3. Installing Examples Repository)
**Files** (the implementation is self-contained so no specific location is required):
* Environment: :download:`reaching_iiwa_omniverse_isaacgym_env.py <../examples/real_world/kuka_lbr_iiwa/reaching_iiwa_omniverse_isaacgym_env.py>`
* Training script: :download:`reaching_iiwa_omniverse_isaacgym_skrl_train.py <../examples/real_world/kuka_lbr_iiwa/reaching_iiwa_omniverse_isaacgym_skrl_train.py>`
* Evaluation script: :download:`reaching_iiwa_omniverse_isaacgym_skrl_eval.py <../examples/real_world/kuka_lbr_iiwa/reaching_iiwa_omniverse_isaacgym_skrl_eval.py>`
* Checkpoints (:literal:`agent_joint.pt`, :literal:`agent_cartesian.pt`): :download:`trained_checkpoints.zip <https://github.com/Toni-SM/skrl/files/10406561/trained_checkpoints.zip>`
* Simulation files: (.usd assets and robot class): :download:`simulation_files.zip <https://github.com/Toni-SM/skrl/files/10409551/simulation_files.zip>`
Simulation files must be structured as follows:
.. code-block::
<some_folder>
├── agent_cartesian.pt
├── agent_joint.pt
├── assets
│ ├── iiwa14_instanceable_meshes.usd
│ └── iiwa14.usd
├── reaching_iiwa_omniverse_isaacgym_env.py
├── reaching_iiwa_omniverse_isaacgym_skrl_eval.py
├── reaching_iiwa_omniverse_isaacgym_skrl_train.py
├── robots
│ ├── iiwa14.py
│ └── __init__.py
**Training and evaluation:**
.. code-block:: bash
# training (local workstation)
~/.local/share/ov/pkg/isaac_sim-*/python.sh reaching_iiwa_omniverse_isaacgym_skrl_train.py
# training (docker container)
/isaac-sim/python.sh reaching_iiwa_omniverse_isaacgym_skrl_train.py
.. code-block:: bash
# evaluation (local workstation)
~/.local/share/ov/pkg/isaac_sim-*/python.sh reaching_iiwa_omniverse_isaacgym_skrl_eval.py
# evaluation (docker container)
/isaac-sim/python.sh reaching_iiwa_omniverse_isaacgym_skrl_eval.py
**Main environment configuration:**
The control space (Cartesian or joint) can be specified in the task configuration dictionary (from :literal:`reaching_iiwa_omniverse_isaacgym_skrl_train.py`) as follow:
.. code-block:: python
TASK_CFG["task"]["env"]["controlSpace"] = "joint" # "joint" or "cartesian"
.. raw:: html
<br><hr>
.. _library_utilities:
**Library utilities (skrl.utils module)**
-----------------------------------------
This example shows how to use the library utilities to carry out the post-processing of files and data generated by the experiments
.. raw:: html
<br>
.. tabs::
.. tab:: Tensorboard files
.. image:: ../_static/imgs/utils_tensorboard_file_iterator.svg
:width: 100%
:alt: Tensorboard file iterator
.. raw:: html
<br><br>
Example of a figure, generated by the code, showing the total reward (left) and the mean and standard deviation (right) of all experiments located in the runs folder
:download:`tensorboard_file_iterator.py <../examples/utils/tensorboard_file_iterator.py>`
**Note:** The code will load all the Tensorboard files of the experiments located in the :literal:`runs` folder. It is necessary to adjust the iterator's parameters for other paths
.. literalinclude:: ../examples/utils/tensorboard_file_iterator.py
:language: python
:emphasize-lines: 4, 11-13
|
Toni-SM/skrl/docs/source/intro/data.rst | Saving, loading and logging
===========================
In this section, you will find the information you need to log data with TensorBoard or Weights & Biases and to save and load checkpoints and memories to and from persistent storage.
.. raw:: html
<br><hr>
**TensorBoard integration**
---------------------------
`TensorBoard <https://www.tensorflow.org/tensorboard>`_ is used for tracking and visualizing metrics and scalars (coefficients, losses, etc.). The tracking and writing of metrics and scalars is the responsibility of the agents (**can be customized independently for each agent using its configuration dictionary**).
.. .. admonition:: |jax|
.. note::
A standalone JAX installation does not include any package for writing events to Tensorboard. In this case it is necessary to install (if not installed) one of the following frameworks/packages:
* `PyTorch <https://pytorch.org/get-started/locally>`_
* `TensorFlow <https://www.tensorflow.org/install>`_
* `TensorboardX <https://github.com/lanpa/tensorboardX#install>`_
.. raw:: html
<br>
Configuration
^^^^^^^^^^^^^
Each agent offers the following parameters under the :literal:`"experiment"` key:
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 5-7
:start-after: [start-tensorboard-configuration]
:end-before: [end-tensorboard-configuration]
* **directory**: directory path where the data generated by the experiments (a subdirectory) are stored. If no value is set, the :literal:`runs` folder (inside the current working directory) will be used (and created if it does not exist).
* **experiment_name**: name of the experiment (subdirectory). If no value is set, it will be the current date and time and the agent's name (e.g. :literal:`22-01-09_22-48-49-816281_DDPG`).
* **write_interval**: interval for writing metrics and values to TensorBoard (default is 250 timesteps). A value equal to or less than 0 disables tracking and writing to TensorBoard.
.. raw:: html
<br>
Tracked metrics/scales visualization
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
To visualize the tracked metrics/scales, during or after the training, TensorBoard can be launched using the following command in a terminal:
.. code-block:: bash
tensorboard --logdir=PATH_TO_RUNS_DIRECTORY
.. image:: ../_static/imgs/data_tensorboard.jpg
:width: 100%
:align: center
:alt: TensorBoard panel
|
The following table shows the metrics/scales tracked by each agent ([**+**] all the time, [**-**] only when such a function is enabled in the agent's configuration):
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
|Tag |Metric / Scalar |.. centered:: A2C |.. centered:: AMP |.. centered:: CEM |.. centered:: DDPG|.. centered:: DDQN|.. centered:: DQN |.. centered:: PPO |.. centered:: Q-learning |.. centered:: SAC |.. centered:: SARSA |.. centered:: TD3 |.. centered:: TRPO|
+===========+====================+==================+==================+==================+==================+==================+==================+==================+=========================+==================+====================+==================+==================+
|Coefficient|Entropy coefficient | | | | | | | | |.. centered:: + | | | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Return threshold | | |.. centered:: + | | | | | | | | | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Mean disc. returns | | |.. centered:: + | | | | | | | | | |
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
|Episode |Total timesteps |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
|Exploration|Exploration noise | | | |.. centered:: + | | | | | | |.. centered:: + | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Exploration epsilon | | | | |.. centered:: + |.. centered:: + | | | | | | |
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
|Learning |Learning rate |.. centered:: + |.. centered:: + |.. centered:: -- | |.. centered:: -- |.. centered:: -- |.. centered:: -- | | | | | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Policy learning rate| | | |.. centered:: -- | | | | |.. centered:: -- | |.. centered:: -- | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Critic learning rate| | | |.. centered:: -- | | | | |.. centered:: -- | |.. centered:: -- | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Return threshold | | | | | | | | | | | |.. centered:: -- |
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
|Loss |Critic loss | | | |.. centered:: + | | | | |.. centered:: + | |.. centered:: + | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Entropy loss |.. centered:: -- |.. centered:: -- | | | | |.. centered:: -- | |.. centered:: -- | | | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Discriminator loss | |.. centered:: + | | | | | | | | | | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Policy loss |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + | | |.. centered:: + | |.. centered:: + | |.. centered:: + |.. centered:: + |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Q-network loss | | | | |.. centered:: + |.. centered:: + | | | | | | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Value loss |.. centered:: + |.. centered:: + | | | | |.. centered:: + | | | | |.. centered:: + |
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
|Policy |Standard deviation |.. centered:: + |.. centered:: + | | | | |.. centered:: + | | | | |.. centered:: + |
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
|Q-network |Q1 | | | |.. centered:: + | | | | |.. centered:: + | |.. centered:: + | |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Q2 | | | | | | | | |.. centered:: + | |.. centered:: + | |
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
|Reward |Instantaneous reward|.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |
+ +--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
| |Total reward |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |.. centered:: + |
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
|Target |Target | | | |.. centered:: + |.. centered:: + |.. centered:: + | | |.. centered:: + | |.. centered:: + | |
+-----------+--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+-------------------------+------------------+--------------------+------------------+------------------+
.. raw:: html
<br>
Tracking custom metrics/scales
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* **Tracking custom data attached to the agent's control and timing logic (recommended)**
Although the TensorBoard's writing control and timing logic is controlled by the base class Agent, it is possible to track custom data. The :literal:`track_data` method can be used (see :doc:`Agent <../api/agents>` class for more details), passing as arguments the data identification (tag) and the scalar value to be recorded.
For example, to track the current CPU usage, the following code can be used:
.. code-block:: python
# assuming agent is an instance of an Agent subclass
agent.track_data("Resource / CPU usage", psutil.cpu_percent())
* **Tracking custom data directly to Tensorboard**
It is also feasible to access directly to the `SummaryWriter <https://pytorch.org/docs/stable/tensorboard.html#torch.utils.tensorboard.writer.SummaryWriter>`_ instance through the :literal:`writer` property if it is desired to write directly to Tensorboard, avoiding the base class's control and timing logic.
For example, to write directly to TensorBoard:
.. code-block:: python
# assuming agent is an instance of an Agent subclass
agent.writer.add_scalar("Resource / CPU usage", psutil.cpu_percent(), global_step=1000)
.. raw:: html
<br><hr>
**Weights & Biases integration**
--------------------------------
`Weights & Biases (wandb) <https://wandb.ai>`_ is also supported for tracking and visualizing metrics and scalars. Its configuration is responsibility of the agents (**can be customized independently for each agent using its configuration dictionary**).
Follow the steps described in Weights & Biases documentation (`Set up wandb <https://docs.wandb.ai/quickstart#1.-set-up-wandb>`_) to login to the :literal:`wandb` library on the current machine.
.. note::
The :literal:`wandb` library is not installed by default. Install it in a Python 3 environment using pip as follows:
.. code-block:: bash
pip install wandb
.. raw:: html
<br>
Configuration
^^^^^^^^^^^^^
Each agent offers the following parameters under the :literal:`"experiment"` key. Visit the Weights & Biases documentation for more details about the configuration parameters.
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 12-13
:start-after: [start-wandb-configuration]
:end-before: [end-wandb-configuration]
* **wandb**: whether to enable support for Weights & Biases.
* **wandb_kwargs**: keyword argument dictionary used to parameterize the `wandb.init <https://docs.wandb.ai/ref/python/init>`_ function. If no values are provided for the following parameters, the following values will be set for them:
* :literal:`"name"`: will be set to the name of the experiment directory.
* :literal:`"sync_tensorboard"`: will be set to :literal:`True`.
* :literal:`"config"`: will be updated with the configuration dictionaries of both the agent (and its models) and the trainer. The update will be done even if a value has been set for the parameter.
.. raw:: html
<br><hr>
**Checkpoints**
---------------
.. raw:: html
<br>
Saving checkpoints
^^^^^^^^^^^^^^^^^^
The checkpoints are saved in the :literal:`checkpoints` subdirectory of the experiment's directory (its path can be customized using the options described in the previous subsection). The checkpoint name is the key referring to the agent (or models, optimizers and preprocessors) and the current timestep (e.g. :literal:`runs/22-01-09_22-48-49-816281_DDPG/checkpoints/agent_2500.pt`).
The checkpoint management, as in the previous case, is the responsibility of the agents (**can be customized independently for each agent using its configuration dictionary**).
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 9,10
:start-after: [start-checkpoint-configuration]
:end-before: [end-checkpoint-configuration]
* **checkpoint_interval**: interval for checkpoints (default is 1000 timesteps). A value equal to or less than 0 disables the checkpoint creation.
* **store_separately**: if set to :literal:`True`, all the modules that an agent contains (models, optimizers, preprocessors, etc.) will be saved each one in a separate file. By default (:literal:`False`) the modules are grouped in a dictionary and stored in the same file.
**Checkpointing the best models**
The best models, attending the mean total reward, will be saved in the :literal:`checkpoints` subdirectory of the experiment's directory. The checkpoint name is the word :literal:`best` and the key referring to the model (e.g. :literal:`runs/22-01-09_22-48-49-816281_DDPG/checkpoints/best_agent.pt`).
The best models are updated internally on each TensorBoard writing interval :literal:`"write_interval"` and they are saved on each checkpoint interval :literal:`"checkpoint_interval"`. The :literal:`"store_separately"` key specifies whether the best modules are grouped and stored together or separately.
.. raw:: html
<br>
Loading checkpoints
^^^^^^^^^^^^^^^^^^^
Checkpoints can be loaded (e.g. to resume or continue training) for each of the instantiated agents (or models) independently via the :literal:`.load(...)` method (`Agent.load <../modules/skrl.agents.base_class.html#skrl.agents.torch.base.Agent.load>`_ or `Model.load <../modules/skrl.models.base_class.html#skrl.models.torch.base.Model.load>`_). It accepts the path (relative or absolute) of the checkpoint to load as the only argument. The checkpoint will be dynamically mapped to the device specified as argument in the class constructor (internally the torch load's :literal:`map_location` method is used during loading).
.. note::
The agents or models instances must have the same architecture/structure as the one used to save the checkpoint. The current implementation load the model's state-dict directly.
.. note::
Warnings such as :literal:`[skrl:WARNING] Cannot load the <module> module. The agent doesn't have such an instance` can be ignored without problems during evaluation. The reason for this is that during the evaluation not all components, such as optimizers or other models apart from the policy, may be defined.
The following code snippets show how to load the checkpoints through the instantiated agent (recommended) or models. See the :doc:`Examples <examples>` section for showcases about how to checkpoints and use them to continue the training or evaluate experiments.
.. tabs::
.. tab:: Agent (recommended)
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 12
:start-after: [start-checkpoint-load-agent-torch]
:end-before: [end-checkpoint-load-agent-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 12
:start-after: [start-checkpoint-load-agent-jax]
:end-before: [end-checkpoint-load-agent-jax]
.. tab:: Model
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 22
:start-after: [start-checkpoint-load-model-torch]
:end-before: [end-checkpoint-load-model-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 22
:start-after: [start-checkpoint-load-model-jax]
:end-before: [end-checkpoint-load-model-jax]
In addition, it is possible to load, through the library utilities, trained agent checkpoints from the Hugging Face Hub (`huggingface.co/skrl <https://huggingface.co/skrl>`_). See the :doc:`Hugging Face integration <../api/utils/huggingface>` for more information.
.. tabs::
.. tab:: Agent (from Hugging Face Hub)
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 2, 13-14
:start-after: [start-checkpoint-load-huggingface-torch]
:end-before: [end-checkpoint-load-huggingface-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 2, 13-14
:start-after: [start-checkpoint-load-huggingface-jax]
:end-before: [end-checkpoint-load-huggingface-jax]
.. raw:: html
<br>
Migrating external checkpoints
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
It is possible to load checkpoints generated with external reinforcement learning libraries into skrl agents (or models) via the :literal:`.migrate(...)` method (`Agent.migrate <../modules/skrl.agents.base_class.html#skrl.agents.torch.base.Agent.migrate>`_ or `Model.migrate <../modules/skrl.models.base_class.html#skrl.models.torch.base.Model.migrate>`_).
.. note::
In some cases it will be necessary to specify a parameter mapping, especially in ambiguous models (where 2 or more parameters, for source or current model, have equal shape). Refer to the respective method documentation for more details in these cases.
The following code snippets show how to migrate checkpoints from other libraries to the agents or models implemented in skrl:
.. tabs::
.. tab:: Agent
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 12
:start-after: [start-checkpoint-migrate-agent-torch]
:end-before: [end-checkpoint-migrate-agent-torch]
.. tab:: Model
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 22, 25, 28-29
:start-after: [start-checkpoint-migrate-model-torch]
:end-before: [end-checkpoint-migrate-model-torch]
.. raw:: html
<br><hr>
**Memory export/import**
------------------------
.. raw:: html
<br>
Exporting memories
^^^^^^^^^^^^^^^^^^
Memories can be automatically exported to files at each filling cycle (before data overwriting is performed). Its activation, the output files' format and their path can be modified through the constructor parameters when an instance is created.
.. tabs::
.. group-tab:: |_4| |pytorch| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 7-9
:start-after: [start-export-memory-torch]
:end-before: [end-export-memory-torch]
.. group-tab:: |_4| |jax| |_4|
.. literalinclude:: ../snippets/data.py
:language: python
:emphasize-lines: 7-9
:start-after: [start-export-memory-jax]
:end-before: [end-export-memory-jax]
* **export**: enable or disable the memory export (default is disabled).
* **export_format**: the format of the exported memory (default is :literal:`"pt"`). Supported formats are PyTorch (:literal:`"pt"`), NumPy (:literal:`"np"`) and Comma-separated values (:literal:`"csv"`).
* **export_directory**: the directory where the memory will be exported (default is :literal:`"memory"`).
.. raw:: html
<br>
Importing memories
^^^^^^^^^^^^^^^^^^
TODO :red:`(coming soon)`
|
Toni-SM/semu.misc.jupyter_notebook/README.md | ## Embedded Jupyter Notebook for NVIDIA Omniverse
> This extension can be described as the [Jupyter](https://jupyter.org/) notebook version of Omniverse's [Script Editor](https://docs.omniverse.nvidia.com/extensions/latest/ext_script-editor.html). It allows to open a Jupyter Notebook embedded in the current NVIDIA Omniverse application scope.
<br>
**Target applications:** Any NVIDIA Omniverse app
**Supported OS:** Windows and Linux
**Changelog:** [CHANGELOG.md](exts/semu.misc.jupyter_notebook/docs/CHANGELOG.md)
**Table of Contents:**
- [Extension setup](#setup)
- [Troubleshooting](#setup-troubleshooting)
- [Extension usage](#usage)
- [Code autocompletion](#usage-autocompletion)
- [Code introspection](#usage-introspection)
- [Configuring the extension](#config)
- [Implementation details](#implementation)
<br>

<hr>
<a name="setup"></a>
### Extension setup
1. Add the extension using the [Extension Manager](https://docs.omniverse.nvidia.com/extensions/latest/ext_extension-manager.html) or by following the steps in [Extension Search Paths](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_advanced.html#git-url-paths)
* Git url (git+https) as extension search path
```
git+https://github.com/Toni-SM/semu.misc.jupyter_notebook.git?branch=main&dir=exts
```
* Compressed (.zip) file for import
[semu.misc.jupyter_notebook.zip](https://github.com/Toni-SM/semu.misc.jupyter_notebook/releases)
2. Enable the extension using the [Extension Manager](https://docs.omniverse.nvidia.com/extensions/latest/ext_extension-manager.html) or by following the steps in [Extension Enabling/Disabling](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_advanced.html#extension-enabling-disabling)
<a name="setup-troubleshooting"></a>
#### Troubleshooting
* Failed installation (particularly in Kit 105 based applications - Python 3.10)
**Issues/Errors:**
```ini
[Warning] [omni.kit.pipapi.pipapi] 'jupyterlab' failed to install.
[Warning] [omni.kit.pipapi.pipapi] 'notebook' failed to install.
```
**Solution:**
Upgrade `pip` to the latest version and install required libraries manually. Replace `<USER>`, `<OMNIVERSE_APP>`, `<APP_NAME>`, and `<APP_VERSION>` according to your system configuration. Example:
- `<USER>`: toni
- `<OMNIVERSE_APP>`: create-2023.1.1
- `<APP_NAME>`: USD.Composer
- `<APP_VERSION>`: 2023.1
<br>
Linux
```xml
/home/<USER>/.local/share/ov/pkg/<OMNIVERSE_APP>/kit/python/bin/python3 -m pip install --upgrade pip
/home/<USER>/.local/share/ov/pkg/<OMNIVERSE_APP>/kit/python/bin/python3 -m pip --isolated install --upgrade --target=/home/<USER>/.local/share/ov/data/Kit/<APP_NAME>/<APP_VERSION>/pip3-envs/default jupyterlab notebook jedi
```
Windows
```xml
C:\Users\<USER>\AppData\Local\ov\pkg\<OMNIVERSE_APP>\kit\python\python.exe -m pip install --upgrade pip
C:\Users\<USER>\AppData\Local\ov\pkg\<OMNIVERSE_APP>\kit\python\python.exe -m pip --isolated install --upgrade --target=C:\Users\<USER>\AppData\Local\ov\data\Kit\<APP_NAME>\<APP_VERSION>\pip3-envs\default jupyterlab notebook jedi
```
<hr>
<a name="usage"></a>
### Extension usage
#### Omniverse app
Enabling the extension launches the Jupyter Notebook server ([JupyterLab](https://jupyterlab.readthedocs.io/en/stable/) or [Jupyter Notebook](https://jupyter-notebook.readthedocs.io/en/latest/)) in the background. The notebook can then be opened in the browser via its URL (`http://WORKSTATION_IP:PORT/`), which is also indicated inside the Omniverse application in the *Windows > Embedded Jupyter Notebook* menu.
> **Note:** The Jupyter Notebook URL port may change if the configured port is already in use.
<br>
<p align="center">
<img src="exts/semu.misc.jupyter_notebook/data/preview1.png" width="75%">
</p>
Disabling the extension shutdowns the Jupyter Notebook server and the openened kernels.
#### Jupyter Notebook
To execute Python code in the current NVIDIA Omniverse application scope use the following kernel:
<br>
<table align="center" class="table table-striped table-bordered">
<thead>
</thead>
<tbody>
<tr>
<td>Embedded Omniverse (Python 3)</td>
<td><p align="center" style="margin: 0"><img src="exts/semu.misc.jupyter_notebook/data/kernels/embedded_omniverse_python3_socket/logo-64x64.png" width="50px"></p></td>
</tr>
</tbody>
</table>
<a name="usage-autocompletion"></a>
##### Code autocompletion
Use the <kbd>Tab</kbd> key for code autocompletion.
<a name="usage-introspection"></a>
##### Code introspection
Use the <kbd>Ctrl</kbd> + <kbd>i</kbd> keys for code introspection (display *docstring* if available).
<hr>
<a name="config"></a>
### Configuring the extension
The extension can be configured by editing the [config.toml](exts/semu.misc.jupyter_notebook/config/extension.toml) file under `[settings]` section. The following parameters are available:
<br>
**Extension settings**
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Parameter</th>
<th>Value</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>socket_port</td>
<td>8224</td>
<td>The port on which the Jupyter Notebook server will be listening for connections</td>
</tr>
<tr>
<td>classic_notebook_interface</td>
<td>false</td>
<td>Whether the Jupyter Notebook server will use the JupyterLab interface (default interface) or the classic Jupyter Notebook interface</td>
</tr>
<tr>
<td>kill_processes_with_port_in_use</td>
<td>true</td>
<td>Whether to kill applications/processes that use the same ports (8224 and 8225 by default) before activating the extension. Disable this option if you want to launch multiple applications that have this extension active</td>
</tr>
</tbody>
</table>
<br>
**Jupyter Notebook server settings**
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Parameter</th>
<th>Value</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>notebook_ip</td>
<td>"0.0.0.0"</td>
<td>The IP address on which the Jupyter Notebook server will be launched</td>
</tr>
<tr>
<td>notebook_port</td>
<td>8225</td>
<td>The port on which the Jupyter Notebook server will be launched. If the port is already in use, the server will be launched on a different incrementing port</td>
</tr>
<tr>
<td>token</td>
<td>""</td>
<td>The Jupyter Notebook server token. If empty, the default configuration, the server will be launched without authentication</td>
</tr>
<tr>
<td>notebook_dir</td>
<td>""</td>
<td>The Jupyter Notebook server directory</td>
</tr>
<tr>
<td>command_line_options</td>
<td>"--allow-root --no-browser"</td>
<td>The Jupyter Notebook server command line options excluding the previously mentioned parameters</td>
</tr>
</tbody>
</table>
<hr>
<a name="implementation"></a>
### Implementation details
Both the Jupyter Notebook server and the IPython kernels are designed to be launched as independent processes (or subprocesses). Due to this specification, the Jupyter Notebook server and the IPython kernels are launched in separate (sub)processes.
<br>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th></th>
<th>Jupyter Notebook as (sub)process</th>
</tr>
</thead>
<tbody>
<tr>
<td>Kernel (display name)</td>
<td>Embedded Omniverse (Python 3)</td>
</tr>
<tr>
<td>Kernel (logo)</td>
<td><p align="center"><img src="exts/semu.misc.jupyter_notebook/data/kernels/embedded_omniverse_python3_socket/logo-64x64.png" width="50px"></p></td>
</tr>
<tr>
<td>Kernel (raw name)</td>
<td>embedded_omniverse_python3_socket</td>
</tr>
<tr>
<td>Instanceable kernels</td>
<td>Unlimited</td>
</tr>
<tr>
<td>Python backend</td>
<td>Omniverse Kit embedded Python</td>
</tr>
<tr>
<td>Code execution</td>
<td>Intercept Jupyter-IPython communication, forward and execute code in Omniverse Kit and send back the results to the published by the notebook</td>
</tr>
<tr>
<td>Main limitations</td>
<td>
<ul>
<li>IPython magic commands are not available</li>
<li>Printing, inside callbacks, is not displayed in the notebook but in the Omniverse terminal</li>
<li>Matplotlib plotting is not available in notebooks</li>
</ul>
</td>
</tr>
</tbody>
</table>
|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/semu/misc/jupyter_notebook/__init__.py | from .scripts.extension import * |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/semu/misc/jupyter_notebook/scripts/extension.py | import __future__
import os
import sys
import jedi
import json
import glob
import socket
import asyncio
import traceback
import subprocess
import contextlib
from io import StringIO
from dis import COMPILER_FLAG_NAMES
try:
from ast import PyCF_ALLOW_TOP_LEVEL_AWAIT
except ImportError:
PyCF_ALLOW_TOP_LEVEL_AWAIT = 0
import carb
import omni.ext
def _get_coroutine_flag() -> int:
"""Get the coroutine flag for the current Python version
"""
for k, v in COMPILER_FLAG_NAMES.items():
if v == "COROUTINE":
return k
return -1
COROUTINE_FLAG = _get_coroutine_flag()
def _has_coroutine_flag(code) -> bool:
"""Check if the code has the coroutine flag set
"""
if COROUTINE_FLAG == -1:
return False
return bool(code.co_flags & COROUTINE_FLAG)
def _get_compiler_flags() -> int:
"""Get the compiler flags for the current Python version
"""
flags = 0
for value in globals().values():
try:
if isinstance(value, __future__._Feature):
f = value.compiler_flag
flags |= f
except BaseException:
pass
flags = flags | PyCF_ALLOW_TOP_LEVEL_AWAIT
return flags
def _get_event_loop() -> asyncio.AbstractEventLoop:
"""Backward compatible function for getting the event loop
"""
try:
if sys.version_info >= (3, 7):
return asyncio.get_running_loop()
else:
return asyncio.get_event_loop()
except RuntimeError:
return asyncio.get_event_loop_policy().get_event_loop()
class Extension(omni.ext.IExt):
WINDOW_NAME = "Embedded Jupyter Notebook"
MENU_PATH = f"Window/{WINDOW_NAME}"
def on_startup(self, ext_id):
self._globals = {**globals()}
self._locals = self._globals
self._server = None
self._process = None
self._settings = carb.settings.get_settings()
self._extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id)
sys.path.append(os.path.join(self._extension_path, "data", "provisioners"))
# get extension settings
self._token = self._settings.get("/exts/semu.misc.jupyter_notebook/token")
self._notebook_ip = self._settings.get("/exts/semu.misc.jupyter_notebook/notebook_ip")
self._notebook_port = self._settings.get("/exts/semu.misc.jupyter_notebook/notebook_port")
self._notebook_dir = self._settings.get("/exts/semu.misc.jupyter_notebook/notebook_dir")
self._command_line_options = self._settings.get("/exts/semu.misc.jupyter_notebook/command_line_options")
self._classic_notebook_interface = self._settings.get("/exts/semu.misc.jupyter_notebook/classic_notebook_interface")
self._socket_port = self._settings.get("/exts/semu.misc.jupyter_notebook/socket_port")
kill_processes_with_port_in_use = self._settings.get("/exts/semu.misc.jupyter_notebook/kill_processes_with_port_in_use")
# menu item
self._editor_menu = omni.kit.ui.get_editor_menu()
if self._editor_menu:
self._menu = self._editor_menu.add_item(Extension.MENU_PATH, self._show_notification, toggle=False, value=False)
# shutdown stream
self.shutdown_stream_event = omni.kit.app.get_app().get_shutdown_event_stream() \
.create_subscription_to_pop(self._on_shutdown_event, name="semu.misc.jupyter_notebook", order=0)
# ensure port is free
if kill_processes_with_port_in_use:
# windows
if sys.platform == "win32":
pids = []
cmd = ["netstat", "-ano"]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in p.stdout:
if f":{self._socket_port}".encode() in line or f":{self._notebook_port}".encode() in line:
if "listening".encode() in line.lower():
carb.log_info(f"Open port: {line.strip().decode()}")
pids.append(line.strip().split(b" ")[-1].decode())
p.wait()
for pid in pids:
if not pid.isnumeric():
continue
carb.log_warn(f"Forced process shutdown with PID {pid}")
cmd = ["taskkill", "/PID", pid, "/F"]
subprocess.Popen(cmd).wait()
# linux
elif sys.platform == "linux":
pids = []
cmd = ["netstat", "-ltnup"]
try:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in p.stdout:
if f":{self._socket_port}".encode() in line or f":{self._notebook_port}".encode() in line:
carb.log_info(f"Open port: {line.strip().decode()}")
pids.append([chunk for chunk in line.strip().split(b" ") if b'/' in chunk][-1].decode().split("/")[0])
p.wait()
except FileNotFoundError as e:
carb.log_warn(f"Command (netstat) not available. Install it using `apt install net-tools`")
for pid in pids:
if not pid.isnumeric():
continue
carb.log_warn(f"Forced process shutdown with PID {pid}")
cmd = ["kill", "-9", pid]
subprocess.Popen(cmd).wait()
# create socket
self._create_socket()
# run jupyter notebook in a separate process
self._launch_jupyter_process()
# jedi (autocompletion)
# application root path
app_folder = carb.settings.get_settings().get_as_string("/app/folder")
if not app_folder:
app_folder = carb.tokens.get_tokens_interface().resolve("${app}")
path = os.path.normpath(os.path.join(app_folder, os.pardir))
# get extension paths
folders = [
"exts",
"extscache",
os.path.join("kit", "extensions"),
os.path.join("kit", "exts"),
os.path.join("kit", "extsPhysics"),
os.path.join("kit", "extscore"),
]
added_sys_path = []
for folder in folders:
sys_paths = glob.glob(os.path.join(path, folder, "*"))
for sys_path in sys_paths:
if os.path.isdir(sys_path):
added_sys_path.append(sys_path)
# python environment
python_exe = "python.exe" if sys.platform == "win32" else "bin/python3"
environment_path = os.path.join(path, "kit", "python", python_exe)
# jedi project
carb.log_info("Autocompletion: jedi.Project")
carb.log_info(f" |-- path: {path}")
carb.log_info(f" |-- added_sys_path: {len(added_sys_path)} items")
carb.log_info(f" |-- environment_path: {environment_path}")
self._jedi_project = jedi.Project(path=path,
environment_path=environment_path,
added_sys_path=added_sys_path,
load_unsafe_extensions=False)
def on_shutdown(self):
# clean extension paths from sys.path
if self._extension_path is not None:
sys.path.remove(os.path.join(self._extension_path, "data", "provisioners"))
self._extension_path = None
# clean up menu item
if self._menu is not None:
self._editor_menu.remove_item(self._menu)
self._menu = None
# close the socket
if self._server:
self._server.close()
_get_event_loop().run_until_complete(self._server.wait_closed())
# close the jupyter notebook (external process)
if self._process is not None:
process_pid = self._process.pid
try:
self._process.terminate() # .kill()
except OSError as e:
if sys.platform == 'win32':
if e.winerror != 5:
raise
else:
from errno import ESRCH
if not isinstance(e, ProcessLookupError) or e.errno != ESRCH:
raise
# make sure the process is not running anymore in Windows
if sys.platform == 'win32':
subprocess.call(['taskkill', '/F', '/T', '/PID', str(process_pid)])
# wait for the process to terminate
self._process.wait()
self._process = None
# extension ui methods
def _on_shutdown_event(self, event):
if event.type == omni.kit.app.POST_QUIT_EVENT_TYPE:
self.on_shutdown()
def _show_notification(self, *args, **kwargs) -> None:
"""Show a Jupyter Notebook URL in the notification area
"""
display_url = ""
if self._process is not None:
notebook_txt = os.path.join(self._extension_path, "data", "launchers", "notebook.txt")
if os.path.exists(notebook_txt):
with open(notebook_txt, "r") as f:
display_url = f.read()
if display_url:
notification = "Jupyter Notebook is running at:\n\n - " + display_url.replace(" or ", " - ")
status=omni.kit.notification_manager.NotificationStatus.INFO
else:
notification = "Unable to identify Jupyter Notebook URL"
status=omni.kit.notification_manager.NotificationStatus.WARNING
ok_button = omni.kit.notification_manager.NotificationButtonInfo("OK", on_complete=None)
omni.kit.notification_manager.post_notification(notification,
hide_after_timeout=False,
duration=0,
status=status,
button_infos=[ok_button])
print(notification)
carb.log_info(notification)
# internal socket methods
def _create_socket(self) -> None:
"""Create a socket server to listen for incoming connections from the IPython kernel
"""
socket_txt = os.path.join(self._extension_path, "data", "launchers", "socket.txt")
# delete socket.txt file
if os.path.exists(socket_txt):
os.remove(socket_txt)
class ServerProtocol(asyncio.Protocol):
def __init__(self, parent) -> None:
super().__init__()
self._parent = parent
def connection_made(self, transport):
peername = transport.get_extra_info('peername')
carb.log_info('Connection from {}'.format(peername))
self.transport = transport
def data_received(self, data):
code = data.decode()
# completion
if code[:3] == "%!c":
code = code[3:]
asyncio.run_coroutine_threadsafe(self._parent._complete_code_async(code, self.transport), _get_event_loop())
# introspection
elif code[:3] == "%!i":
code = code[3:]
pos = code.find('%')
line, column = [int(i) for i in code[:pos].split(':')]
code = code[pos + 1:]
asyncio.run_coroutine_threadsafe(self._parent._introspect_code_async(code, line, column, self.transport), _get_event_loop())
# execution
else:
asyncio.run_coroutine_threadsafe(self._parent._exec_code_async(code, self.transport), _get_event_loop())
async def server_task():
self._server = await _get_event_loop().create_server(protocol_factory=lambda: ServerProtocol(self),
host="127.0.0.1",
port=self._socket_port,
family=socket.AF_INET,
reuse_port=None if sys.platform == 'win32' else True)
await self._server.start_serving()
task = _get_event_loop().create_task(server_task())
# write the socket port to socket.txt file
carb.log_info("Internal socket server is running at port {}".format(self._socket_port))
with open(socket_txt, "w") as f:
f.write(str(self._socket_port))
async def _complete_code_async(self, statement: str, transport: asyncio.Transport) -> None:
"""Complete objects under the cursor and send the result to the IPython kernel
:param statement: statement to complete
:type statement: str
:param transport: transport to send the result to the IPython kernel
:type transport: asyncio.Transport
:return: reply dictionary
:rtype: dict
"""
# generate completions
script = jedi.Script(statement, project=self._jedi_project)
completions = script.complete()
delta = completions[0].get_completion_prefix_length() if completions else 0
reply = {"matches": [c.name for c in completions], "delta": delta}
# send the reply to the IPython kernel
reply = json.dumps(reply)
transport.write(reply.encode())
# close the connection
transport.close()
async def _introspect_code_async(self, statement: str, line: int, column: int, transport: asyncio.Transport) -> None:
"""Introspect code under the cursor and send the result to the IPython kernel
:param statement: statement to introspect
:type statement: str
:param line: the line where the definition occurs
:type line: int
:param column: the column where the definition occurs
:type column: int
:param transport: transport to send the result to the IPython kernel
:type transport: asyncio.Transport
:return: reply dictionary
:rtype: dict
"""
# generate introspection
script = jedi.Script(statement, project=self._jedi_project)
definitions = script.infer(line=line, column=column)
reply = {"found": False, "data": "TODO"}
if len(definitions):
reply["found"] = True
reply["data"] = definitions[0].docstring()
# send the reply to the IPython kernel
reply = json.dumps(reply)
transport.write(reply.encode())
# close the connection
transport.close()
async def _exec_code_async(self, statement: str, transport: asyncio.Transport) -> None:
"""Execute the statement in the Omniverse scope and send the result to the IPython kernel
:param statement: statement to execute
:type statement: str
:param transport: transport to send the result to the IPython kernel
:type transport: asyncio.Transport
:return: reply dictionary
:rtype: dict
"""
_stdout = StringIO()
try:
with contextlib.redirect_stdout(_stdout):
should_exec_code = True
# try 'eval' first
try:
code = compile(statement, "<string>", "eval", flags= _get_compiler_flags(), dont_inherit=True)
except SyntaxError:
pass
else:
result = eval(code, self._globals, self._locals)
should_exec_code = False
# if 'eval' fails, try 'exec'
if should_exec_code:
code = compile(statement, "<string>", "exec", flags= _get_compiler_flags(), dont_inherit=True)
result = eval(code, self._globals, self._locals)
# await the result if it is a coroutine
if _has_coroutine_flag(code):
result = await result
except Exception as e:
# clean traceback
_traceback = traceback.format_exc()
_i = _traceback.find('\n File "<string>"')
if _i != -1:
_traceback = _traceback[_i + 20:]
_traceback = _traceback.replace(", in <module>\n", "\n")
# build reply dictionary
reply = {"status": "error",
"traceback": [_traceback],
"ename": str(type(e).__name__),
"evalue": str(e)}
else:
reply = {"status": "ok"}
# add output to reply dictionary for printing
reply["output"] = _stdout.getvalue()
# send the reply to the IPython kernel
reply = json.dumps(reply)
transport.write(reply.encode())
# close the connection
transport.close()
# launch Jupyter Notebook methods
def _launch_jupyter_process(self) -> None:
"""Launch the Jupyter notebook in a separate process
"""
# get packages path
paths = [p for p in sys.path if "pip3-envs" in p]
packages_txt = os.path.join(self._extension_path, "data", "launchers", "packages.txt")
with open(packages_txt, "w") as f:
f.write("\n".join(paths))
if sys.platform == 'win32':
executable_path = os.path.abspath(os.path.join(os.path.dirname(os.__file__), "..", "python.exe"))
else:
executable_path = os.path.abspath(os.path.join(os.path.dirname(os.__file__), "..", "..", "bin", "python3"))
cmd = [executable_path,
os.path.join(self._extension_path, "data", "launchers", "jupyter_launcher.py"),
self._notebook_ip,
str(self._notebook_port),
self._token,
str(self._classic_notebook_interface),
self._notebook_dir,
self._command_line_options]
carb.log_info("Starting Jupyter server in separate process")
carb.log_info(" |-- command: " + " ".join(cmd))
try:
self._process = subprocess.Popen(cmd, cwd=os.path.join(self._extension_path, "data", "launchers"))
except Exception as e:
carb.log_error("Error starting Jupyter server: {}".format(e))
self._process = None
|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/config/extension.toml | [core]
reloadable = true
order = 0
[package]
version = "0.1.1"
category = "Utility"
feature = false
app = false
title = "Embedded Jupyter Notebook"
description = "Jupyter Notebook version of Omniverse's script editor"
authors = ["Toni-SM"]
repository = "https://github.com/Toni-SM/semu.misc.jupyter_notebook"
keywords = ["jupyter", "notebook", "ipython", "editor"]
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[package.target]
config = ["release"]
platform = ["linux-*", "windows-*"]
python = ["*"]
[dependencies]
"omni.kit.test" = {}
"omni.kit.uiapp" = {}
"omni.kit.notification_manager" = {}
[[python.module]]
name = "semu.misc.jupyter_notebook"
[python.pipapi]
requirements = ["jupyterlab", "notebook", "jedi"]
use_online_index = true
[settings]
# extension settings
exts."semu.misc.jupyter_notebook".socket_port = 8224
exts."semu.misc.jupyter_notebook".classic_notebook_interface = false
exts."semu.misc.jupyter_notebook".kill_processes_with_port_in_use = true
# jupyter notebook settings
exts."semu.misc.jupyter_notebook".notebook_ip = "0.0.0.0"
exts."semu.misc.jupyter_notebook".notebook_port = 8225
exts."semu.misc.jupyter_notebook".token = ""
exts."semu.misc.jupyter_notebook".notebook_dir = ""
# jupyter notebook's command line options other than: '--ip', '--port', '--token', '--notebook-dir'
exts."semu.misc.jupyter_notebook".command_line_options = "--allow-root --no-browser --JupyterApp.answer_yes=True"
|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [0.1.1] - 2023-08-08
### Added
- Code autocompletion (<kbd>Tab</kbd>)
- Code introspection (<kbd>Ctrl</kbd> + <kbd>i</kbd>)
### Changed
- Implement embedded kernel on `ipykernel.kernelbase.Kernel`
- Update links in resource notebooks
### Removed
- Threaded kernel implementation
## [0.1.0] - 2023-08-07
The release was yanked
## [0.0.3-beta] - 2022-12-31
### Added
- Add `kill_processes_with_port_in_use` to extension settings
- Add Omniverse documentation and developer resource to notebooks
### Fixed
- Fix port in use when starting up and shutting down
## [0.0.2-beta] - 2022-08-14
### Added
- Jupyter Lab
- Launch Jupyter in separate (sub)process
- Embedded kernel using socket
## [0.0.1-beta] - 2022-08-08
### Added
- Jupyter Notebook
|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/docs/README.md | # semu.misc.jupyter_notebook
This extension can be described as the Jupyter notebook version of Omniverse's script editor. It allows to open a Jupyter Notebook embedded in the current NVIDIA Omniverse application scope
Visit https://github.com/Toni-SM/semu.misc.jupyter_notebook to read more about its use
|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/snippets/carb/get_setting.ipynb | {
"cells": [
{
"cell_type": "markdown",
"id": "b0a73d2a-08ef-4e4b-b2a0-1d37418aa2f6",
"metadata": {},
"source": [
"### Get settings\n",
"<hr>"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a45e9c6e-9f34-4d37-9072-f1eb5ed92fe1",
"metadata": {},
"outputs": [],
"source": [
"import carb\n",
"\n",
"# get settings\n",
"settings = carb.settings.get_settings()"
]
},
{
"cell_type": "markdown",
"id": "8f32bc05-0ffb-47c7-9dc7-c2bc47c19547",
"metadata": {},
"source": [
"**Omniverse application settings** (e.g. extension folders)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c89af54f-6400-4bd8-9119-b6196cf161a9",
"metadata": {},
"outputs": [],
"source": [
"folders = settings.get(\"/app/exts/folders\")\n",
"print(folders)"
]
},
{
"cell_type": "markdown",
"id": "7b2bbc08-a4e9-4927-b6da-1c421cdb5c4d",
"metadata": {},
"source": [
"**Extension settings** (e.g. `docUrl` at `kit/exts/omni.kit.window.extensions/config/extension.toml`)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5cb91298-44c1-42f3-b0b3-0974fce36046",
"metadata": {},
"outputs": [],
"source": [
"folders = settings.get(\"/exts/omni.kit.window.extensions/docUrl\")\n",
"print(folders)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Embedded Omniverse (Python 3)",
"language": "python",
"name": "embedded_omniverse_python3_socket"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/snippets/usd/get_usd_stage.ipynb | {
"cells": [
{
"cell_type": "markdown",
"id": "b0a73d2a-08ef-4e4b-b2a0-1d37418aa2f6",
"metadata": {},
"source": [
"### USD: Get USD Stage\n",
"<hr>"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a45e9c6e-9f34-4d37-9072-f1eb5ed92fe1",
"metadata": {},
"outputs": [],
"source": [
"import omni.usd\n",
"\n",
"# get stage\n",
"stage = omni.usd.get_context().get_stage()\n",
"print(stage)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Embedded Omniverse (Python 3)",
"language": "python",
"name": "embedded_omniverse_python3_socket"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/snippets/usd/world_space_transform.ipynb | {
"cells": [
{
"cell_type": "markdown",
"id": "3e81c525-e9d3-41ba-87c5-19994617f292",
"metadata": {},
"source": [
"### USD: Compute a prim's world-space transform\n",
"<hr>"
]
},
{
"cell_type": "markdown",
"id": "eb988c9e-326f-4605-8a0c-a5186235898d",
"metadata": {},
"source": [
"**Compute a prim's world-space (local to world) transform** (See [ComputeLocalToWorldTransform](https://graphics.pixar.com/usd/release/api/class_usd_geom_imageable.html#a8e3fb09253ba63d63921f665d63cd270))\n",
"\n",
"(e.g. `/World/defaultLight` in a new scene: *File > New* menu)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3e646c77-2063-4e53-9274-8437b164b6f2",
"metadata": {},
"outputs": [],
"source": [
"import omni\n",
"from pxr import Gf, Usd, UsdGeom\n",
"\n",
"stage = omni.usd.get_context().get_stage()\n",
"prim = stage.GetPrimAtPath(\"/World/defaultLight\")\n",
"\n",
"# compute world-space transform\n",
"transform = Gf.Transform()\n",
"transform.SetMatrix(UsdGeom.Xformable(prim).ComputeLocalToWorldTransform(Usd.TimeCode.Default()))\n",
"\n",
"# get position and orientation\n",
"position = transform.GetTranslation()\n",
"rotation = transform.GetRotation().GetQuat()\n",
"\n",
"print(f\"Prim position: {position}\")\n",
"print(f\"Prim rotation: {rotation}\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Embedded Omniverse (Python 3)",
"language": "python",
"name": "embedded_omniverse_python3_socket"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/snippets/usd/get_prim_and_attributes.ipynb | {
"cells": [
{
"cell_type": "markdown",
"id": "b0a73d2a-08ef-4e4b-b2a0-1d37418aa2f6",
"metadata": {},
"source": [
"### USD: Get prim and access its attributes\n",
"<hr>"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a45e9c6e-9f34-4d37-9072-f1eb5ed92fe1",
"metadata": {},
"outputs": [],
"source": [
"import omni.usd\n",
"from pxr import Gf\n",
"\n",
"# get stage\n",
"stage = omni.usd.get_context().get_stage()"
]
},
{
"cell_type": "markdown",
"id": "8f32bc05-0ffb-47c7-9dc7-c2bc47c19547",
"metadata": {},
"source": [
"**Get prim** (e.g. `/World/defaultLight` in a new scene: *File > New* menu)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c89af54f-6400-4bd8-9119-b6196cf161a9",
"metadata": {},
"outputs": [],
"source": [
"prim = stage.GetPrimAtPath(\"/World/defaultLight\")\n",
"print(prim)"
]
},
{
"cell_type": "markdown",
"id": "7b2bbc08-a4e9-4927-b6da-1c421cdb5c4d",
"metadata": {},
"source": [
"**Get prim attribute** (e.g. `color`)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5cb91298-44c1-42f3-b0b3-0974fce36046",
"metadata": {},
"outputs": [],
"source": [
"attribute = prim.GetAttribute(\"color\")\n",
"value = attribute.Get()\n",
"\n",
"print(f\"attribute: {attribute}\")\n",
"print(f\"value: {value}\")\n",
"print(f\"type: {type(value)}\")"
]
},
{
"cell_type": "markdown",
"id": "a5b08b03-5dc4-4c6e-af42-93f55ee0e6b7",
"metadata": {},
"source": [
"**Set prim attribute** (e.g. `color` to `R:255, G:128, B:0`)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d6176c70-6773-4ae7-96bc-29c54e53eb3f",
"metadata": {},
"outputs": [],
"source": [
"new_value = Gf.Vec3f(1.0, 0.5, 0.0)\n",
"attribute = prim.GetAttribute(\"color\")\n",
"attribute.Set(new_value)\n",
"\n",
"print(f\"attribute: {attribute}\")\n",
"print(f\"value: {attribute.Get()}\")\n",
"print(f\"type: {type(value)}\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Embedded Omniverse (Python 3)",
"language": "python",
"name": "embedded_omniverse_python3_socket"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/snippets/events/physics_event.ipynb | {
"cells": [
{
"cell_type": "markdown",
"id": "638f71d1-619f-4997-93fd-a0bd50c2cfb2",
"metadata": {},
"source": [
"### Events: Physics event\n",
"<hr>"
]
},
{
"cell_type": "markdown",
"id": "af1ee30d-b5dd-42e5-9f07-9c1a7856101e",
"metadata": {},
"source": [
"#### Physics event\n",
"\n",
"The event callback has as parameter: \n",
"- **dt**: float"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2a2c9e62-2157-415d-8887-dc8e7d9591d0",
"metadata": {},
"outputs": [],
"source": [
"import carb.events\n",
"import omni.physx\n",
"\n",
"# callback\n",
"def on_physics_event(dt):\n",
" print(f\"Physics event: {dt}\")\n",
"\n",
"# subscription\n",
"physics_event_sub = (omni.physx.acquire_physx_interface()\n",
" .subscribe_physics_step_events(on_physics_event))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "21ee1623-7b8a-4e91-9abb-9c3f9c4d5447",
"metadata": {},
"outputs": [],
"source": [
"# unsubscription\n",
"physics_event_sub = None"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Embedded Omniverse (Python 3)",
"language": "python",
"name": "embedded_omniverse_python3_socket"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/snippets/events/timeline_event.ipynb | {
"cells": [
{
"cell_type": "markdown",
"id": "638f71d1-619f-4997-93fd-a0bd50c2cfb2",
"metadata": {},
"source": [
"### Events: Timeline event\n",
"<hr>"
]
},
{
"cell_type": "markdown",
"id": "af1ee30d-b5dd-42e5-9f07-9c1a7856101e",
"metadata": {},
"source": [
"#### Timeline event\n",
"\n",
"[carb.events.IEvent](https://docs.omniverse.nvidia.com/py/kit/docs/api/carb/carb.events.html?#carb.events.IEvent) has:\n",
"- **type**: int ([omni.timeline.TimelineEventType](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.timeline/docs/index.html?#omni.timeline.TimelineEventType))\n",
"- **sender** id: int\n",
"- **payload**: dictionary like item with arbitrary data. The timeline event may have the following items:\n",
" - `currentTime`: float\n",
" - `startTime`: float\n",
" - `endTime`: float\n",
" - `timeCodesPerSecond`: float\n",
" - `autoUpdate`: bool\n",
" - `prerolling`: bool\n",
" - `looping`: bool"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2a2c9e62-2157-415d-8887-dc8e7d9591d0",
"metadata": {},
"outputs": [],
"source": [
"import carb.events\n",
"import omni.timeline\n",
"\n",
"# callback\n",
"def on_timeline_event(event):\n",
" print(f\"Timeline event: {event.type} {event.sender} {event.payload}\")\n",
" if event.type == int(omni.timeline.TimelineEventType.PLAY):\n",
" pass\n",
" elif event.type == int(omni.timeline.TimelineEventType.PAUSE):\n",
" pass\n",
" elif event.type == int(omni.timeline.TimelineEventType.STOP):\n",
" pass\n",
" elif event.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_CHANGED):\n",
" pass\n",
" elif event.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED):\n",
" pass\n",
" elif event.type == int(omni.timeline.TimelineEventType.LOOP_MODE_CHANGED):\n",
" pass\n",
" elif event.type == int(omni.timeline.TimelineEventType.START_TIME_CHANGED):\n",
" pass\n",
" elif event.type == int(omni.timeline.TimelineEventType.END_TIME_CHANGED):\n",
" pass\n",
" elif event.type == int(omni.timeline.TimelineEventType.TIME_CODE_PER_SECOND_CHANGED):\n",
" pass\n",
" elif event.type == int(omni.timeline.TimelineEventType.AUTO_UPDATE_CHANGED):\n",
" pass\n",
" elif event.type == int(omni.timeline.TimelineEventType.PREROLLING_CHANGED):\n",
" pass\n",
"\n",
"# subscription\n",
"timeline_event_sub = (omni.timeline.get_timeline_interface()\n",
" .get_timeline_event_stream()\n",
" .create_subscription_to_pop(on_timeline_event, name=\"subscription Name\"))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "21ee1623-7b8a-4e91-9abb-9c3f9c4d5447",
"metadata": {},
"outputs": [],
"source": [
"# unsubscription\n",
"timeline_event_sub = None"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Embedded Omniverse (Python 3)",
"language": "python",
"name": "embedded_omniverse_python3_socket"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/snippets/events/update_event.ipynb | {
"cells": [
{
"cell_type": "markdown",
"id": "638f71d1-619f-4997-93fd-a0bd50c2cfb2",
"metadata": {},
"source": [
"### Events: Update event\n",
"<hr>"
]
},
{
"cell_type": "markdown",
"id": "af1ee30d-b5dd-42e5-9f07-9c1a7856101e",
"metadata": {},
"source": [
"#### Update event\n",
"\n",
"[carb.events.IEvent](https://docs.omniverse.nvidia.com/py/kit/docs/api/carb/carb.events.html?#carb.events.IEvent) has:\n",
"- **type**: int\n",
"- **sender** id: int\n",
"- **payload**: dictionary like item with arbitrary data. The update event may have the following items:\n",
" - `SWHFrameNumber`: int\n",
" - `dt`: float"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2a2c9e62-2157-415d-8887-dc8e7d9591d0",
"metadata": {},
"outputs": [],
"source": [
"import carb.events\n",
"import omni.kit.app\n",
"\n",
"# callback\n",
"def on_update_event(event):\n",
" print(f\"Update event: {event.type} {event.sender} {event.payload}\")\n",
"\n",
"# subscription\n",
"update_event_sub = (omni.kit.app.get_app()\n",
" .get_update_event_stream()\n",
" .create_subscription_to_pop(on_update_event, name=\"subscription Name\"))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "21ee1623-7b8a-4e91-9abb-9c3f9c4d5447",
"metadata": {},
"outputs": [],
"source": [
"# unsubscription\n",
"update_event_sub = None"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Embedded Omniverse (Python 3)",
"language": "python",
"name": "embedded_omniverse_python3_socket"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/snippets/events/input_event.ipynb | {
"cells": [
{
"cell_type": "markdown",
"id": "638f71d1-619f-4997-93fd-a0bd50c2cfb2",
"metadata": {},
"source": [
"### Events: Input event\n",
"<hr>"
]
},
{
"cell_type": "markdown",
"id": "5d5631cc-5936-4a95-be4d-0a73218b0d25",
"metadata": {},
"source": [
"#### Keyboard event\n",
"\n",
"[carb.input.KeyboardEvent](https://docs.omniverse.nvidia.com/py/kit/docs/api/carb/carb.input.html?#carb.input.KeyboardEvent) has:\n",
"- **device**: [carb.input.InputDevice](https://docs.omniverse.nvidia.com/py/kit/docs/api/carb/carb.input.html?#carb.input.InputDevice)\n",
"- **input**: [carb.input.KeyboardInput](https://docs.omniverse.nvidia.com/py/kit/docs/api/carb/carb.input.html?#carb.input.KeyboardInput)\n",
"- **keyboard**: [carb.input.Keyboard](https://docs.omniverse.nvidia.com/py/kit/docs/api/carb/carb.input.html?#carb.input.Keyboard)\n",
"- **modifiers**: int\n",
"- **type**: [carb.input.KeyboardEventType](https://docs.omniverse.nvidia.com/py/kit/docs/api/carb/carb.input.html?#carb.input.KeyboardEventType)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "474a38b0-e549-4678-b673-6d8537bb62c8",
"metadata": {},
"outputs": [],
"source": [
"import carb.input\n",
"import omni.appwindow\n",
"\n",
"# callback\n",
"def on_keyboard_event(event):\n",
" print(f\"Input event: {event.device} {event.input} {event.keyboard} {event.modifiers} {event.type}\")\n",
" # e.g. key A pressed/released\n",
" if event.input == carb.input.KeyboardInput.A:\n",
" if event.type == carb.input.KeyboardEventType.KEY_PRESS:\n",
" print(\"Key A pressed\")\n",
" elif event.type == carb.input.KeyboardEventType.KEY_RELEASE:\n",
" print(\"Key A released\")\n",
"\n",
"# get keyboard\n",
"keyboard = omni.appwindow.get_default_app_window().get_keyboard()\n",
"\n",
"# subscription\n",
"keyboard_event_sub = (carb.input.acquire_input_interface()\n",
" .subscribe_to_keyboard_events(keyboard, on_keyboard_event))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "72bb9f82-fec6-43c4-bc59-566dd35fe1b5",
"metadata": {},
"outputs": [],
"source": [
"# unsubscription\n",
"(carb.input.acquire_input_interface()\n",
" .unsubscribe_to_keyboard_events(keyboard, keyboard_event_sub))"
]
},
{
"cell_type": "markdown",
"id": "af1ee30d-b5dd-42e5-9f07-9c1a7856101e",
"metadata": {},
"source": [
"#### Mouse event (viewport)\n",
"\n",
"[carb.events.IEvent](https://docs.omniverse.nvidia.com/py/kit/docs/api/carb/carb.events.html?#carb.events.IEvent) has:\n",
"- **type**: int\n",
"- **sender** id: int\n",
"- **payload**: dictionary like item with arbitrary data. The mouse event may have the following items:\n",
" - `mouse_pos_x`: int\n",
" - `mouse_pos_y`: int\n",
" - `mouse_pos_z`: int\n",
" - `prim_path`: str"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2a2c9e62-2157-415d-8887-dc8e7d9591d0",
"metadata": {},
"outputs": [],
"source": [
"import carb.input\n",
"import omni.kit.viewport_legacy\n",
"\n",
"# callback\n",
"def on_viewport_mouse_event(event):\n",
" print(f\"Input event: {event.type} {event.sender} {event.payload}\")\n",
" # e.g. check for the context menu\n",
" if event.type == int(omni.kit.ui.MenuEventType.ACTIVATE):\n",
" print(\"Context menu\")\n",
"\n",
"# get viewport window\n",
"viewport_window = omni.kit.viewport_legacy.get_viewport_interface().get_viewport_window()\n",
"\n",
"# subscription\n",
"viewport_mouse_event_sub = (viewport_window.get_mouse_event_stream()\n",
" .create_subscription_to_pop(on_viewport_mouse_event))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "21ee1623-7b8a-4e91-9abb-9c3f9c4d5447",
"metadata": {},
"outputs": [],
"source": [
"# unsubscription\n",
"viewport_mouse_event_sub = None"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Embedded Omniverse (Python 3)",
"language": "python",
"name": "embedded_omniverse_python3_socket"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/snippets/events/usd_stage_event.ipynb | {
"cells": [
{
"cell_type": "markdown",
"id": "638f71d1-619f-4997-93fd-a0bd50c2cfb2",
"metadata": {},
"source": [
"### Events: USD stage event\n",
"<hr>"
]
},
{
"cell_type": "markdown",
"id": "8f72ba70-f6e9-4219-be5a-896129ec7f88",
"metadata": {},
"source": [
"#### Stage event\n",
"\n",
"[carb.events.IEvent](https://docs.omniverse.nvidia.com/py/kit/docs/api/carb/carb.events.html?#carb.events.IEvent) has:\n",
"- **type**: int ([omni.usd.StageEventType](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.usd/docs/index.html?#omni.usd.StageEventType))\n",
"- **sender** id: int\n",
"- **payload**: dictionary like item with arbitrary data"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "474a38b0-e549-4678-b673-6d8537bb62c8",
"metadata": {},
"outputs": [],
"source": [
"import carb.events\n",
"import omni.usd\n",
"\n",
"# callback\n",
"def on_stage_event(event):\n",
" print(f\"Stage event: {event.type} {event.sender} {event.payload}\")\n",
" if event.type == int(omni.usd.StageEventType.SAVED):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.SAVE_FAILED):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.OPENING):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.OPENED):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.OPEN_FAILED):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.CLOSING):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.CLOSED):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.ASSETS_LOADED):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.ASSETS_LOAD_ABORTED):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.GIZMO_TRACKING_CHANGED):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.MDL_PARAM_LOADED):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.SETTINGS_LOADED):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.SETTINGS_SAVING):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.OMNIGRAPH_START_PLAY):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.OMNIGRAPH_STOP_PLAY):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.SIMULATION_START_PLAY):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.SIMULATION_STOP_PLAY):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.ANIMATION_START_PLAY):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.ANIMATION_STOP_PLAY):\n",
" pass\n",
" elif event.type == int(omni.usd.StageEventType.DIRTY_STATE_CHANGED):\n",
" pass\n",
"\n",
"# subscription \n",
"stage_event_sub = (omni.usd.get_context()\n",
" .get_stage_event_stream()\n",
" .create_subscription_to_pop(on_stage_event, name=\"subscription name\"))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9cef81ff-14c5-492e-9733-edf91f18e319",
"metadata": {},
"outputs": [],
"source": [
"# unsubscription\n",
"stage_event_sub = None"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Embedded Omniverse (Python 3)",
"language": "python",
"name": "embedded_omniverse_python3_socket"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/developer/VS Code link.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/extensions/latest/ext_vs-code-link.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/extensions/latest/ext_vs-code-link.html"
</script>
<title>VS Code link</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/extensions/latest/ext_vs-code-link.html">VS Code link</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/developer/PhysX 5 SDK.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://nvidia-omniverse.github.io/PhysX/physx">
<script type="text/javascript">
window.location.href = "https://nvidia-omniverse.github.io/PhysX/physx"
</script>
<title>PhysX 5 SDK</title>
</head>
<body>
<a href="https://nvidia-omniverse.github.io/PhysX/physx">PhysX 5 SDK</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/developer/Omni-UI.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/kit/docs/omni.ui/latest/Overview.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/kit/docs/omni.ui/latest/Overview.html"
</script>
<title>Omni::UI</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/kit/docs/omni.ui/latest/Overview.html">Omni::UI</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/developer/USD data types.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/dev-guide/latest/dev_usd/quick-start/usd-types.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/dev-guide/latest/dev_usd/quick-start/usd-types.html"
</script>
<title>USD data types</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/dev-guide/latest/dev_usd/quick-start/usd-types.html">USD data types</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/developer/Extensions.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_basic.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_basic.html"
</script>
<title>Extensions</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_basic.html">Extensions</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/developer/Kit programming manual.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/kit_overview.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/kit_overview.html"
</script>
<title>Kit programming manual</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/kit_overview.html">Kit programming manual</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/developer/OmniGraph.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/kit/docs/omni.graph.core/latest/Overview.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/kit/docs/omni.graph.core/latest/Overview.html"
</script>
<title>OmniGraph</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/kit/docs/omni.graph.core/latest/Overview.html">OmniGraph</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/developer/SceneUI.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/kit/docs/omni.ui.scene/latest/Overview.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/kit/docs/omni.ui.scene/latest/Overview.html"
</script>
<title>SceneUI</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/kit/docs/omni.ui.scene/latest/Overview.html">SceneUI</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/developer/Python scripting component.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/extensions/latest/ext_python-scripting-component.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/extensions/latest/ext_python-scripting-component.html"
</script>
<title>Python scripting component</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/extensions/latest/ext_python-scripting-component.html">Python scripting component</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/developer/Kit code samples.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/dev-guide/latest/programmer_ref.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/dev-guide/latest/programmer_ref.html"
</script>
<title>Kit code samples</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/dev-guide/latest/programmer_ref.html">Kit code samples</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/developer/USD Python snippets.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/dev-guide/latest/programmer_ref/usd.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/dev-guide/latest/programmer_ref/usd.html"
</script>
<title>USD Python snippets</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/dev-guide/latest/programmer_ref/usd.html">USD Python snippets</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/App - USDView.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/usdview/latest/index.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/usdview/latest/index.html"
</script>
<title>App: USDView</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/usdview/latest/index.html">App: USDView</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/Omniverse Utilities.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/utilities/latest/index.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/utilities/latest/index.html"
</script>
<title>Omniverse Utilities</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/utilities/latest/index.html">Omniverse Utilities</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/App - Kaolin.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/kaolin/latest/index.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/kaolin/latest/index.html"
</script>
<title>App: Kaolin</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/kaolin/latest/index.html">App: Kaolin</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/App - Create XR.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/create-xr/latest/index.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/create-xr/latest/index.html"
</script>
<title>App: Create XR</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/create-xr/latest/index.html">App: Create XR</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/App - Isaac Sim.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/isaacsim/latest/index.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/isaacsim/latest/index.html"
</script>
<title>App: Isaac Sim</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/isaacsim/latest/index.html">App: Isaac Sim</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/App - Code.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/code/latest/index.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/code/latest/index.html"
</script>
<title>App: Code</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/code/latest/index.html">App: Code</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/App - Showroom.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/showroom/latest/index.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/showroom/latest/index.html"
</script>
<title>App: Showroom</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/showroom/latest/index.html">App: Showroom</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/Omniverse SimReady.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/simready/latest/index.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/simready/latest/index.html"
</script>
<title>Omniverse SimReady</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/simready/latest/index.html">Omniverse SimReady</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/App - USD Presenter.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/presenter/latest/index.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/presenter/latest/index.html"
</script>
<title>App: USD Presenter</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/presenter/latest/index.html">App: USD Presenter</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/App - Farm.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/farm/latest/index.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/farm/latest/index.html"
</script>
<title>App: Farm</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/farm/latest/index.html">App: Farm</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/Platform Overview.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/platform/latest/index.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/platform/latest/index.html"
</script>
<title>Platform Overview</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/platform/latest/index.html">Platform Overview</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/App - USD Composer.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/composer/latest/index.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/composer/latest/index.html"
</script>
<title>App: USD Composer</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/composer/latest/index.html">App: USD Composer</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/App - Navigator.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/navigator/latest/index.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/navigator/latest/index.html"
</script>
<title>App: Navigator</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/navigator/latest/index.html">App: Navigator</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/App - Machinima.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/machinima/latest/index.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/machinima/latest/index.html"
</script>
<title>App: Machinima</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/machinima/latest/index.html">App: Machinima</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/App - Omniverse Streaming Client.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/streaming-client/latest/index.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/streaming-client/latest/index.html"
</script>
<title>App: Omniverse Streaming Client</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/streaming-client/latest/index.html">App: Omniverse Streaming Client</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/App - Audio2Face.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/audio2face/latest/index.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/audio2face/latest/index.html"
</script>
<title>App: Audio2Face</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/audio2face/latest/index.html">App: Audio2Face</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/Omniverse Services.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/services/latest/index.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/services/latest/index.html"
</script>
<title>Omniverse Services</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/services/latest/index.html">Omniverse Services</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/Omniverse Developer Documentation.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/kit_overview.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/kit_overview.html"
</script>
<title>Omniverse Developer Documentation</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/kit_overview.html">Omniverse Developer Documentation</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/Omniverse Workflows.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/workflows/latest/index.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/workflows/latest/index.html"
</script>
<title>Omniverse Workflows</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/workflows/latest/index.html">Omniverse Workflows</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/notebooks/resources/documentation/Omniverse Digital Twins.html | <!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=https://docs.omniverse.nvidia.com/digital-twins/latest/index.html">
<script type="text/javascript">
window.location.href = "https://docs.omniverse.nvidia.com/digital-twins/latest/index.html"
</script>
<title>Omniverse Digital Twins</title>
</head>
<body>
<a href="https://docs.omniverse.nvidia.com/digital-twins/latest/index.html">Omniverse Digital Twins</a>
</body>
</html> |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/launchers/jupyter_launcher.py | from typing import List
import os
import sys
PACKAGES_PATH = []
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
# add packages to sys.path
with open(os.path.join(SCRIPT_DIR, "packages.txt"), "r") as f:
for p in f.readlines():
p = p.strip()
if p:
PACKAGES_PATH.append(p)
if p not in sys.path:
print("Adding package to sys.path: {}".format(p))
sys.path.append(p)
# add provisioners to sys.path
sys.path.append(os.path.abspath(os.path.join(SCRIPT_DIR, "..", "provisioners")))
from jupyter_client.kernelspec import KernelSpecManager as _KernelSpecManager
class KernelSpecManager(_KernelSpecManager):
def __init__(self, *args, **kwargs):
"""Custom kernel spec manager to allow for loading of custom kernels
"""
super().__init__(*args, **kwargs)
kernel_dir = os.path.abspath(os.path.join(SCRIPT_DIR, "..", "kernels"))
if kernel_dir not in self.kernel_dirs:
self.kernel_dirs.append(kernel_dir)
def main(ip: str = "0.0.0.0", port: int = 8225, argv: List[str] = [], classic_notebook_interface: bool = False) -> None:
"""Entry point for launching Juptyter Notebook/Lab
:param ip: Notebook server IP address (default: "0.0.0.0")
:type code: str, optional
:param port: Notebook server port number (default: 8225)
:type code: int, optional
:param argv: Command line arguments to pass to Jupyter Notebook/Lab (default: [])
:type code: List of strings, optional
:param classic_notebook_interface: Whether to use the classic notebook interface (default: False)
If false, the Juptyter Lab interface will be used
:type code: bool, optional
"""
# jupyter notebook
if classic_notebook_interface:
from notebook.notebookapp import NotebookApp
app = NotebookApp(ip=ip,
port=port,
kernel_spec_manager_class=KernelSpecManager)
app.initialize(argv=argv)
# jupyter lab
else:
from jupyterlab.labapp import LabApp
from jupyter_server.serverapp import ServerApp
jpserver_extensions = {LabApp.get_extension_package(): True}
find_extensions = LabApp.load_other_extensions
if "jpserver_extensions" in LabApp.serverapp_config:
jpserver_extensions.update(LabApp.serverapp_config["jpserver_extensions"])
LabApp.serverapp_config["jpserver_extensions"] = jpserver_extensions
find_extensions = False
app = ServerApp.instance(ip=ip,
port=port,
kernel_spec_manager_class=KernelSpecManager,
jpserver_extensions=jpserver_extensions)
app.aliases.update(LabApp.aliases)
app.initialize(argv=argv,
starter_extension=LabApp.name,
find_extensions=find_extensions)
# write url to file in script directory
with open(os.path.join(SCRIPT_DIR, "notebook.txt"), "w") as f:
f.write(app.display_url)
app.start()
if __name__ == "__main__":
argv = sys.argv[1:]
# testing the launcher
if not len(argv):
print("Testing the launcher")
argv = ['0.0.0.0', # ip
'8888', # port
'', # token
'False', # classic_notebook_interface
'', # notebook_dir
'--allow-root --no-browser'] # extra arguments
# get function arguments
ip = argv[0]
port = int(argv[1])
token = argv[2]
classic_notebook_interface = argv[3] == "True"
# buld notebook_dir
if not argv[4]:
notebook_dir = os.path.abspath(os.path.join(SCRIPT_DIR, "..", "notebooks"))
notebook_dir = "--notebook-dir={}".format(notebook_dir)
# build token
if classic_notebook_interface:
token = "--NotebookApp.token={}".format(token)
else:
token = "--ServerApp.token={}".format(token)
# assets path
app_dir = []
if not classic_notebook_interface:
for p in PACKAGES_PATH:
print("Checking package to app_dir: {}".format(p))
if os.path.exists(os.path.join(p, "share", "jupyter", "lab")):
app_dir = ["--app-dir={}".format(os.path.join(p, "share", "jupyter", "lab"))]
if os.path.exists(os.path.join(p, "jupyterlab", "static")):
app_dir = ["--app-dir={}".format(os.path.join(p, "jupyterlab"))]
if app_dir:
break
print("app_dir: {}".format(app_dir))
# clean up the argv
argv = app_dir + [token] + [notebook_dir] + argv[5].split(" ")
# run the launcher
print("Starting Jupyter {} at {}:{}".format("Notebook" if classic_notebook_interface else "Lab", ip, port))
print(" with argv: {}".format(" ".join(argv)))
main(ip=ip, port=port, argv=argv, classic_notebook_interface=classic_notebook_interface)
# delete notebook.txt
try:
os.remove(os.path.join(SCRIPT_DIR, "notebook.txt"))
except:
pass
|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/launchers/ipykernel_launcher.py | import os
import sys
import json
import socket
import asyncio
SOCKET_HOST = "127.0.0.1"
SOCKET_PORT = 8224
PACKAGES_PATH = []
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
# add packages to sys.path
with open(os.path.join(SCRIPT_DIR, "packages.txt"), "r") as f:
for p in f.readlines():
p = p.strip()
if p:
PACKAGES_PATH.append(p)
if p not in sys.path:
print("Adding package to sys.path: {}".format(p))
sys.path.append(p)
from ipykernel.kernelbase import Kernel
from ipykernel.kernelapp import IPKernelApp
async def _send_and_recv(message):
reader, writer = await asyncio.open_connection(host=SOCKET_HOST,
port=SOCKET_PORT,
family=socket.AF_INET)
writer.write(message.encode())
await writer.drain()
data = await reader.read()
writer.close()
await writer.wait_closed()
return data.decode()
def _get_line_column(code, cursor_pos):
line = code.count('\n', 0, cursor_pos) + 1
last_newline_pos = code.rfind('\n', 0, cursor_pos)
column = cursor_pos - last_newline_pos - 1
return line, column
class EmbeddedKernel(Kernel):
"""Omniverse Kit Python wrapper kernels
It re-use the IPython's kernel machinery
https://jupyter-client.readthedocs.io/en/latest/wrapperkernels.html
"""
# kernel info: https://jupyter-client.readthedocs.io/en/latest/messaging.html#kernel-info
implementation = "Omniverse Kit (Python 3)"
implementation_version = "0.1.0"
language_info = {
"name": "python",
"version": "3.7", # TODO: get from Omniverse Kit
"mimetype": "text/x-python",
"file_extension": ".py",
}
banner = "Embedded Omniverse (Python 3)"
help_links = [{"text": "semu.misc.jupyter_notebook", "url": "https://github.com/Toni-SM/semu.misc.jupyter_notebook"}]
async def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False):
"""Execute user code
"""
# https://jupyter-client.readthedocs.io/en/latest/messaging.html#execute
execute_reply = {"status": "ok",
"execution_count": self.execution_count,
"payload": [],
"user_expressions": {}}
# no code
if not code.strip():
return execute_reply
# magic commands
if code.startswith('%'):
# TODO: process magic commands
pass
# python code
try:
data = await _send_and_recv(code)
reply_content = json.loads(data)
except Exception as e:
# show network error in client
print("\x1b[0;31m==================================================\x1b[0m")
print("\x1b[0;31mKernel error at port {}\x1b[0m".format(SOCKET_PORT))
print(e)
print("\x1b[0;31m==================================================\x1b[0m")
reply_content = {"status": "error", "output": "", "traceback": [], "ename": str(type(e).__name__), "evalue": str(e)}
# code execution stdout: {"status": str, "output": str}
if not silent:
if reply_content["output"]:
stream_content = {"name": "stdout", "text": reply_content["output"]}
self.send_response(self.iopub_socket, "stream", stream_content)
reply_content.pop("output", None)
# code execution error: {"status": str("error"), "output": str, "traceback": list(str), "ename": str, "evalue": str}
if reply_content["status"] == "error":
self.send_response(self.iopub_socket, "error", reply_content)
# update reply
execute_reply["status"] = reply_content["status"]
execute_reply["execution_count"] = self.execution_count, # the base class increments the execution count
return execute_reply
def do_debug_request(self, msg):
return {}
async def do_complete(self, code, cursor_pos):
"""Code completation
"""
# https://jupyter-client.readthedocs.io/en/latest/messaging.html#msging-completion
complete_reply = {"status": "ok",
"matches": [],
"cursor_start": 0,
"cursor_end": cursor_pos,
"metadata": {}}
# parse code
code = code[:cursor_pos]
if not code or code[-1] in [' ', '=', ':', '(', ')']:
return complete_reply
# generate completions
try:
data = await _send_and_recv("%!c" + code)
reply_content = json.loads(data)
except Exception as e:
# show network error in client
print("\x1b[0;31m==================================================\x1b[0m")
print("\x1b[0;31mKernel error at port {}\x1b[0m".format(SOCKET_PORT))
print(e)
print("\x1b[0;31m==================================================\x1b[0m")
reply_content = {"matches": [], "delta": cursor_pos}
# update replay: {"matches": list(str), "delta": int}
complete_reply["matches"] = reply_content["matches"]
complete_reply["cursor_start"] = cursor_pos - reply_content["delta"]
return complete_reply
async def do_inspect(self, code, cursor_pos, detail_level=0, omit_sections=()):
"""Object introspection
"""
# https://jupyter-client.readthedocs.io/en/latest/messaging.html#msging-inspection
inspect_reply = {"status": "ok",
"found": False,
"data": {},
"metadata": {}}
line, column = _get_line_column(code, cursor_pos)
# generate introspection
try:
data = await _send_and_recv(f"%!i{line}:{column}%" + code)
reply_content = json.loads(data)
except Exception as e:
# show network error in client
print("\x1b[0;31m==================================================\x1b[0m")
print("\x1b[0;31mKernel error at port {}\x1b[0m".format(SOCKET_PORT))
print(e)
print("\x1b[0;31m==================================================\x1b[0m")
reply_content = {"found": False, "data": cursor_pos}
# update replay: {"found": bool, "data": str}
if reply_content["found"]:
inspect_reply["found"] = reply_content["found"]
inspect_reply["data"] = {"text/plain": reply_content["data"]}
return inspect_reply
if __name__ == "__main__":
if sys.path[0] == "":
del sys.path[0]
# read socket port from file
if os.path.exists(os.path.join(SCRIPT_DIR, "socket.txt")):
with open(os.path.join(SCRIPT_DIR, "socket.txt"), "r") as f:
SOCKET_PORT = int(f.read())
IPKernelApp.launch_instance(kernel_class=EmbeddedKernel)
|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/provisioners/embedded_omniverse_python3.egg-info/top_level.txt | embedded_omniverse_python3
|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/provisioners/embedded_omniverse_python3.egg-info/entry_points.txt | [jupyter_client.kernel_provisioners]
embedded-omniverse-provisioner-socket = embedded_omniverse_python3.provisioner_socket:Provisioner
|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/provisioners/embedded_omniverse_python3/__init__.py | |
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/provisioners/embedded_omniverse_python3/provisioner_socket.py | from typing import Any, List
import os
import sys
from jupyter_client.provisioning import LocalProvisioner
from jupyter_client.connect import KernelConnectionInfo
from jupyter_client.launcher import launch_kernel
class Provisioner(LocalProvisioner):
async def launch_kernel(self, cmd: List[str], **kwargs: Any) -> KernelConnectionInfo:
# set paths
if sys.platform == 'win32':
cmd[0] = os.path.abspath(os.path.join(os.path.dirname(os.__file__), "..", "python.exe"))
else:
cmd[0] = os.path.abspath(os.path.join(os.path.dirname(os.__file__), "..", "..", "bin", "python3"))
cmd[1] = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "launchers", "ipykernel_launcher.py"))
self.log.info("Launching kernel: %s", " ".join(cmd))
scrubbed_kwargs = LocalProvisioner._scrub_kwargs(kwargs)
self.process = launch_kernel(cmd, **scrubbed_kwargs)
pgid = None
if hasattr(os, "getpgid"):
try:
pgid = os.getpgid(self.process.pid)
except OSError:
pass
self.pid = self.process.pid
self.pgid = pgid
return self.connection_info
|
Toni-SM/semu.misc.jupyter_notebook/exts/semu.misc.jupyter_notebook/data/kernels/embedded_omniverse_python3_socket/kernel.json | {
"argv": ["AUTOMATICALLY_REPLACED", "AUTOMATICALLY_REPLACED", "-f", "{connection_file}"],
"display_name": "Embedded Omniverse (Python 3)",
"language": "python",
"interrupt_mode": "message",
"metadata": {
"debugger": true,
"kernel_provisioner": {
"provisioner_name": "embedded-omniverse-provisioner-socket"
}
}
}
|
Toni-SM/semu.misc.jupyter_notebook/PACKAGE-LICENSES/dependencies/notebook-LICENSE.txt | This project is licensed under the terms of the Modified BSD License
(also known as New or Revised or 3-Clause BSD), as follows:
- Copyright (c) 2001-2015, IPython Development Team
- Copyright (c) 2015-, Jupyter Development Team
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of the Jupyter Development Team nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
## About the Jupyter Development Team
The Jupyter Development Team is the set of all contributors to the Jupyter project.
This includes all of the Jupyter subprojects.
The core team that coordinates development on GitHub can be found here:
https://github.com/jupyter/.
## Our Copyright Policy
Jupyter uses a shared copyright model. Each contributor maintains copyright
over their contributions to Jupyter. But, it is important to note that these
contributions are typically only changes to the repositories. Thus, the Jupyter
source code, in its entirety is not the copyright of any single person or
institution. Instead, it is the collective copyright of the entire Jupyter
Development Team. If individual contributors want to maintain a record of what
changes/contributions they have specific copyright on, they should indicate
their copyright in the commit message of the change, when they commit the
change to one of the Jupyter repositories.
With this in mind, the following banner should be used in any source code file
to indicate the copyright and license terms:
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
|
Toni-SM/semu.misc.jupyter_notebook/PACKAGE-LICENSES/dependencies/jupyterlab-LICENSE.txt | Copyright (c) 2015-2022 Project Jupyter Contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Semver File License
===================
The semver.py file is from https://github.com/podhmo/python-semver
which is licensed under the "MIT" license. See the semver.py file for details.
|
Toni-SM/semu.misc.jupyter_notebook/PACKAGE-LICENSES/dependencies/ptpython-LICENSE.txt | Copyright (c) 2015, Jonathan Slenders
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
Toni-SM/semu.data.visualizer/README.md | ## Data visualizer for NVIDIA Omniverse apps
This extension allows to switch [Matplotlib](https://matplotlib.org/) and [OpenCV](https://docs.opencv.org/) backend to display graphics and images inside NVIDIA Omniverse apps without modifying the code logic
<br>
**Target applications:** Any NVIDIA Omniverse app
**Supported OS:** Windows and Linux
**Changelog:** [CHANGELOG.md](src/semu.data.visualizer/docs/CHANGELOG.md)
**Table of Contents:**
- [Extension setup](#setup)
- [Extension usage](#usage)
<br>

<hr>
<a name="setup"></a>
### Extension setup
1. Add the extension using the [Extension Manager](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_extension-manager.html) or by following the steps in [Extension Search Paths](https://docs.omniverse.nvidia.com/py/kit/docs/guide/extensions.html#extension-search-paths)
* Git url (git+https) as extension search path
```
git+https://github.com/Toni-SM/semu.data.visualizer.git?branch=main&dir=exts
```
To install the source code version use the following url
```
git+https://github.com/Toni-SM/semu.data.visualizer.git?branch=main&dir=src
```
* Compressed (.zip) file for import
[semu.data.visualizer.zip](https://github.com/Toni-SM/semu.data.visualizer/releases)
2. Enable the extension using the [Extension Manager](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_extension-manager.html) or by following the steps in [Extension Enabling/Disabling](https://docs.omniverse.nvidia.com/py/kit/docs/guide/extensions.html#extension-enabling-disabling)
<hr>
<a name="usage"></a>
### Extension usage
**Enabling the extension** switches the Matplotlib and OpenCV backends **to display graphics and images in the Omniverse app**
Disabling the extension reverts the changes: graphics and images will be displayed in their respective windows by default, outside the Omniverse app
> **Note:** The current implementation does not support interaction with the displayed graphics or images
|
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/clean_extension.bash | #!/bin/bash
# delete old files
rm -r build
rm *.so
rm semu/data/visualizer/*.c
rm semu/data/visualizer/*.so
|
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/compile_extension.bat |
SET OV_PYTHON_INTERPRETER=%USERPROFILE%\AppData\Local\ov\pkg\code-2022.1.0\kit\python\python.exe
@REM delete old files
CALL clean_extension
@REM compile code
%OV_PYTHON_INTERPRETER% compile_extension.py build_ext --inplace --compiler=mingw32 -DMS_WIN64
@REM move compiled files
MOVE *.pyd semu\\data\\visualizer
@REM delete temporal data
RMDIR /S /Q build
DEL /F /Q semu\\data\\visualizer\\*.c
|
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/BUILD.md | ## Building form source
### Linux
```bash
cd src/semu.data.visualizer
bash compile_extension.bash
```
### Windows (Microsoft Visual C++ (MSVC))
We don't do that here!
### Windows (MinGW64)
#### Build extension
```batch
cd src\semu.data.visualizer
compile_extension.bat
```
#### Troubleshooting
* **Cannot find -lvcruntime140: No such file or directory**
```
cannot find -lvcruntime140: No such file or directory
```
Find and copy `vcruntime140.dll` to `...mingw64\lib\`
* **Error: enumerator value for '__pyx_check_sizeof_voidp' is not an integer constant**
```
error: enumerator value for '__pyx_check_sizeof_voidp' is not an integer constant
```
Add -DMS_WIN64 to the build command (Cython issue [#2670](https://github.com/cython/cython/issues/2670#issuecomment-432212671))
* **ValueError: Unknown MS Compiler version XXXX**
```
ValueError: Unknown MS Compiler version XXXX
```
Apply this [path](https://bugs.python.org/file40608/patch.diff) or just return `return ['vcruntime140']` in `...distutils\cygwinccompiler.py`
## Removing old compiled files
Get a fresh clone of the repository and follow the next steps
```bash
# remove compiled files _visualizer.cpython-37m-x86_64-linux-gnu.so
git filter-repo --invert-paths --path exts/semu.data.visualizer/semu/data/visualizer/_visualizer.cpython-37m-x86_64-linux-gnu.so
git filter-repo --invert-paths --path exts/semu.data.visualizer/semu/data/visualizer/_visualizer.cp37-win_amd64.pyd
# add origin
git remote add origin [email protected]:Toni-SM/semu.data.visualizer.git
# push changes
git push origin --force --all
git push origin --force --tags
```
## Packaging the extension
```bash
cd src/semu.data.visualizer
bash package_extension.bash
``` |
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/compile_extension.py | import os
import sys
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
# OV python (kit\python\include)
if sys.platform == 'win32':
python_library_dir = os.path.join(os.path.dirname(sys.executable), "include")
elif sys.platform == 'linux':
python_library_dir = os.path.join(os.path.dirname(sys.executable), "..", "include")
if not os.path.exists(python_library_dir):
raise Exception("OV Python library directory not found: {}".format(python_library_dir))
ext_modules = [
Extension("_visualizer",
[os.path.join("semu", "data", "visualizer", "visualizer.py")],
library_dirs=[python_library_dir]),
]
setup(
name = 'semu.data.visualizer',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
|
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/clean_extension.bat |
@REM delete old files
RMDIR /S /Q build
DEL /F /Q *.pyd
DEL /F /Q semu\\data\\visualizer\\*.c
DEL /F /Q semu\\data\\visualizer\\*.pyd
|
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/package_extension.bash | #!/bin/bash
extension_dir=../../exts/semu.data.visualizer
extension_tree=semu/data/visualizer
# delete old files
rm -r $extension_dir
mkdir -p $extension_dir/$extension_tree
mkdir -p $extension_dir/$extension_tree/scripts
mkdir -p $extension_dir/$extension_tree/tests
cp -r config $extension_dir
cp -r data $extension_dir
cp -r docs $extension_dir
# scripts folder
cp $extension_tree/scripts/extension.py $extension_dir/$extension_tree/scripts
# tests folder
cp $extension_tree/tests/__init__.py $extension_dir/$extension_tree/tests
cp $extension_tree/tests/test_visualizer.py $extension_dir/$extension_tree/tests
# single files
cp $extension_tree/__init__.py $extension_dir/$extension_tree/
cp $extension_tree/*.pyd $extension_dir/$extension_tree/
cp $extension_tree/*.so $extension_dir/$extension_tree/
|
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/compile_extension.bash | #!/bin/bash
export LIBRARY_PATH=~/.local/share/ov/pkg/code-2022.1.0/kit/python/include
# delete old files
. clean_extension.bash
# compile code
~/.local/share/ov/pkg/code-2022.1.0/kit/python/bin/python3 compile_extension.py build_ext --inplace
# # move compiled file
mv *.so semu/data/visualizer/
# delete temporal data
rm -r build
rm semu/data/visualizer/*.c
|
Toni-SM/semu.data.visualizer/src/semu.data.visualizer/semu/data/visualizer/__init__.py | from .scripts.extension import *
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.