Metadata-Version: 2.4
Name: sheeprl
Version: 1.0.0rc7
Summary: High-quality, single file and distributed implementation of Deep Reinforcement Learning algorithms with production-friendly features
Author-email: Federico Belotti <federico.belotti@orobix.com>, Davide Angioni <davide.angioni@orobix.com>, Refik Can Malli <refikcan.malli@orobix.com>, Michele Milesi <michele.milesi@orobix.com>
Maintainer-email: Federico Belotti <federico.belotti@orobix.com>, Davide Angioni <davide.angioni@orobix.com>, Refik Can Malli <refikcan.malli@orobix.com>, Michele Milesi <michele.milesi@orobix.com>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright 2023 Eclectic Sheep Team
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: homepage, https://eclecticsheep.ai
Project-URL: repository, https://github.com/Eclectic-Sheep/sheeprl
Keywords: reinforcement,machine,learning,distributed,production
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: <3.14,>=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: gymnasium[classic-control]<2,>=1.1
Requires-Dist: moviepy>=2.0
Requires-Dist: tensorboard>=2.10
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: lightning>=2.6.1
Requires-Dist: hydra-core<1.4,>=1.3.2
Requires-Dist: torchmetrics>=1.0
Requires-Dist: rich>=13.5
Requires-Dist: opencv-python>=4.10
Requires-Dist: torch>=2.6
Requires-Dist: numpy<3,>=1.26
Provides-Extra: test
Requires-Dist: pytest>=8; extra == "test"
Requires-Dist: pytest-timeout>=2.3; extra == "test"
Requires-Dist: pytest-cov>=5; extra == "test"
Requires-Dist: pytest-xdist>=3.5; extra == "test"
Provides-Extra: dev
Requires-Dist: pre-commit==3.5.0; extra == "dev"
Requires-Dist: mypy==1.2.0; extra == "dev"
Requires-Dist: black==26.5.1; extra == "dev"
Requires-Dist: isort==5.13.2; extra == "dev"
Requires-Dist: autoflake==2.2.1; extra == "dev"
Requires-Dist: ruff==0.1.11; extra == "dev"
Provides-Extra: mujoco
Requires-Dist: gymnasium[mujoco]<2,>=1.1; extra == "mujoco"
Provides-Extra: dmc
Requires-Dist: dm_control>=1.0.12; extra == "dmc"
Provides-Extra: box2d
Requires-Dist: swig; extra == "box2d"
Requires-Dist: gymnasium[box2d]<2,>=1.1; extra == "box2d"
Provides-Extra: atari
Requires-Dist: ale-py>=0.9; extra == "atari"
Provides-Extra: minedojo
Requires-Dist: minedojo==0.1; extra == "minedojo"
Requires-Dist: importlib_resources==5.12.0; extra == "minedojo"
Requires-Dist: gym==0.21.0; extra == "minedojo"
Provides-Extra: minerl
Requires-Dist: setuptools==66.0.0; extra == "minerl"
Requires-Dist: minerl==0.4.4; extra == "minerl"
Requires-Dist: gym==0.19.0; extra == "minerl"
Provides-Extra: diambra
Requires-Dist: diambra==0.0.17; extra == "diambra"
Requires-Dist: diambra-arena==2.2.6; extra == "diambra"
Provides-Extra: crafter
Requires-Dist: crafter==1.8.3; extra == "crafter"
Provides-Extra: mlflow
Requires-Dist: mlflow<4,>=3.11; extra == "mlflow"
Provides-Extra: supermario
Requires-Dist: gym-super-mario-bros==7.4.0; extra == "supermario"
Requires-Dist: gym<0.26; extra == "supermario"
Dynamic: license-file

# ⚡ SheepRL 🐑

[![Python 3.10](https://img.shields.io/badge/python-3.10-blue.svg)](https://www.python.org/downloads/release/python-3100/)
[![Python 3.11](https://img.shields.io/badge/python-3.11-blue.svg)](https://www.python.org/downloads/release/python-3110/)
[![Python 3.12](https://img.shields.io/badge/python-3.12-blue.svg)](https://www.python.org/downloads/release/python-3120/)
[![Python 3.13](https://img.shields.io/badge/python-3.13-blue.svg)](https://www.python.org/downloads/release/python-3130/)

<p align="center">
  <img src="https://raw.githubusercontent.com/Eclectic-Sheep/sheeprl/main/assets/images/logo_half_scaled.png" alt="SheepRL" width="400">
</p>

<div align="center">
  <table>
    <tr>
      <td><img src="https://github.com/Eclectic-Sheep/sheeprl/assets/18405289/6efd09f0-df91-4da0-971d-92e0213b8835" width="200px"></td>
      <td><img src="https://github.com/Eclectic-Sheep/sheeprl/assets/18405289/dbba57db-6ef5-4db4-9c53-d7b5f303033a" width="200px"></td>
      <td><img src="https://github.com/Eclectic-Sheep/sheeprl/assets/18405289/3f38e5eb-aadd-4402-a698-695d1f99c048" width="200px"></td>
      <td><img src="https://github.com/Eclectic-Sheep/sheeprl/assets/18405289/93749119-fe61-44f1-94bb-fdb89c1869b5" width="200px"></td>
    </tr>
  </table>
</div>

<div align="center">
  <table>
    <thead>
      <tr>
        <th>Environment</th>
        <th>Total frames</th>
        <th>Training time</th>
        <th>Test reward</th>
        <th>Paper reward</th>
        <th>GPUs</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Crafter</td>
        <td>1M</td>
        <td>1d 3h</td>
        <td>12.1</td>
        <td>11.7</td>
        <td>1-V100</td>
      </tr>
      <tr>
        <td>Atari-MsPacman</td>
        <td>100K</td>
        <td>14h</td>
        <td>1542</td>
        <td>1327</td>
        <td>1-3080</td>
      </tr>
      <tr>
        <td> Atari-Boxing</td>
        <td>100K</td>
        <td>14h</td>
        <td>84</td>
        <td>78</td>
        <td>1-3080</td>
      </tr>
      <tr>
        <td>DOA++</td>
        <td>7M</td>
        <td>18d 22h</td>
        <td>2726/3328<sup>1</sup></td>
        <td>N.A.</td>
        <td>1-3080</td>
      </tr>
      <tr>
        <td>Minecraft-Nav</td>
        <td>8M</td>
        <td>16d 4h</td>
        <td>27% &gt;= 70<br>14% &gt;= 100</td>
        <td>N.A.</td>
        <td>1-V100</td>
      </tr>
    </tbody>
  </table>
</div>

1. Best [leaderboard score in DIAMBRA](https://diambra.ai/leaderboard) (11/7/2023)

#### Benchmarks
The training times of SheepRL compared to the ones of [Stable Baselines3](https://github.com/DLR-RM/stable-baselines3) on the CPU, in seconds:

| Algorithm | Devices | SheepRL 1.0 | Stable Baselines3 2.2.1 |
| --------- | ------- | ----------- | ----------------------- |
| PPO       | 1       | 23.9 ± 0.31 | 21.7 ± 0.11             |
| PPO       | 2       | 31.8 ± 0.24 | N.D.                    |
| A2C       | 1       | 31.6 ± 0.51 | 27.6 ± 0.09             |
| A2C       | 2       | 36.0 ± 0.54 | N.D.                    |
| SAC       | 1       | 136.3 ± 0.21 | 157.2 ± 1.53           |
| SAC       | 2       | 137.6 ± 1.45 | N.D.                   |

The training times of the Dreamers on the GPU, without and with the compiled losses (`algo.compile.enabled=True`), in seconds:

| Algorithm  | Eager | Compiled |
| ---------- | ----- | -------- |
| DreamerV1  | 98.9  | 52.9     |
| DreamerV2  | 86.2  | 47.2     |
| DreamerV3  | 116.2 | 43.2     |

##### The setup of the benchmarks

- **Hardware**: an Intel Core i7-14700KF (the CPU experiments are pinned to 4 of its efficiency cores, up to 4.3 GHz, with `taskset -c 20-23`), 32 GB of RAM and an NVIDIA GeForce RTX 5070 (12 GB, driver 580).
- **Software**: Python 3.11, PyTorch 2.14.1 (CUDA 13.0), Lightning 2.6.6, Gymnasium 1.3.0 and NumPy 2.4.6. Stable Baselines3 2.2.1 runs in its own environment, with Gymnasium 0.29 and NumPy 1.26.
- **SheepRL versions**: the CPU results on 1 device were measured with SheepRL 1.0.0rc2; the CPU results on 2 devices and the Dreamer results with SheepRL 1.0.0rc1, and haven't been measured again since.
- **Runs**: the CPU experiments run 5 times each, and the tables report the mean and the standard deviation of the runs, the first one (cold start) excluded. The Dreamers run once each; the compiled ones after a first run that fills the cache of `torch.compile`.
- **Timing**: the wall time of the whole run for SheepRL, including the start of Hydra and Fabric (about 0.6 s); from the creation of the environments to the end of the training for Stable Baselines3.

The experiments are the `exp=<algorithm>_benchmarks` configs (`sheeprl/configs/exp`), without the test, the logging, the checkpoints and the registration of the models, except the logging and the checkpoints of the Dreamers:

| Config | Environment | Envs per process | Policy steps | Main settings |
| ------ | ----------- | ---------------- | ------------ | ------------- |
| `ppo_benchmarks` | `CartPole-v1` | 1 | 65536 | rollouts of 128 steps, minibatches of 64, 10 epochs |
| `a2c_benchmarks` | `CartPole-v1` | 1 | 65536 | rollouts of 5 steps |
| `sac_benchmarks` | `LunarLanderContinuous-v3` (`-v2` in Stable Baselines3) | 4 | 65536 | batches of 256, one gradient step per iteration (`run_benchmarks: True`), learning starts after 100 steps |
| `dreamer_v1_benchmarks`, `dreamer_v2_benchmarks`, `dreamer_v3_benchmarks` | `MsPacmanNoFrameskip-v4` | 1 | 16384 | tiny models (8 dense units, a recurrent state of 8, a stochastic state of 4, 4×4 discrete in V2 and V3, CNN channel multiplier 2), a buffer of 16384 steps, replay ratio 1/16 after 1024 steps, `32-true` precision |

```bash
# On the CPU (2 devices: fabric.devices=2 fabric.strategy=ddp)
taskset -c 20-23 sheeprl exp=ppo_benchmarks
# On the GPU (eager: algo.compile.enabled=False)
sheeprl exp=dreamer_v3_benchmarks fabric.accelerator=cuda algo.compile.enabled=True
```

With these small models, 2 devices on 4 cores are not faster than 1: synchronizing the gradients costs more than splitting the work saves. `benchmarks/benchmark.py` and `benchmarks/benchmark_sb3.py` time a run of SheepRL and of Stable Baselines3.

## What

An easy-to-use framework for reinforcement learning in PyTorch, accelerated with [Lightning Fabric](https://lightning.ai/docs/fabric/stable/).  
The algorithms sheeped by sheeprl out-of-the-box are:

| Algorithm                 | Recurrent          | Vector obs         | Pixel obs          | Custom inputs      | Status             |
| ------------------------- | ------------------ | ------------------ | ------------------ | ------------------ | ------------------ |
| A2C                       | ❌                  | ✅                  | ✅                  | ✅                  | ✅                  |
| PPO                       | ❌                  | ✅                  | ✅                  | ✅                  | ✅                  |
| PPO Recurrent             | ✅                  | ✅                  | ✅                  | ✅                  | ✅                  |
| SAC                       | ❌                  | ✅                  | ❌                  | ❌                  | ✅                  |
| SAC-AE                    | ❌                  | ✅                  | ✅                  | ✅                  | ✅                  |
| DroQ                      | ❌                  | ✅                  | ❌                  | ❌                  | ✅                  |
| Dreamer-V1                | ✅                  | ✅                  | ✅                  | ✅                  | ✅                  |
| Dreamer-V2                | ✅                  | ✅                  | ✅                  | ✅                  | ✅                  |
| Dreamer-V3                | ✅                  | ✅                  | ✅                  | ✅                  | ✅                  |
| Dreamer-V3 (Nature)       | ✅                  | ✅                  | ✅                  | ✅                  | ✅                  |
| Plan2Explore (Dreamer V1) | ✅                  | ✅                  | ✅                  | ✅                  | ✅                  |
| Plan2Explore (Dreamer V2) | ✅                  | ✅                  | ✅                  | ✅                  | ✅                  |
| Plan2Explore (Dreamer V3) | ✅                  | ✅                  | ✅                  | ✅                  | ✅                  |

and more are coming soon! [Open a PR](https://github.com/Eclectic-Sheep/sheeprl/pulls) if you have any particular request 🐑

An agent reads the observation keys it is given, through declared inputs: groups of keys, each with its transforms (resize, frame stack, scaling, running standardization, ...) and its network. *Custom inputs* are inputs other than the image and vector ones, with their own transforms and networks (e.g. a grid read by small convolutions); SAC and DroQ read the vector observations only, as they are, and any other observation flattened. Check [how to select the observations](https://github.com/Eclectic-Sheep/sheeprl/blob/main/howto/inputs_and_outputs.md).


The actions supported by sheeprl agents are:
| Algorithm                 | Continuous         | Discrete           | Multi-Discrete     | Mixed              |
| ------------------------- | ------------------ | ------------------ | ------------------ | ------------------ |
| A2C                       | ✅                  | ✅                  | ✅                  | ✅                  |
| PPO                       | ✅                  | ✅                  | ✅                  | ✅                  |
| PPO Recurrent             | ✅                  | ✅                  | ✅                  | ✅                  |
| SAC                       | ✅                  | ❌                  | ❌                  | ❌                  |
| SAC-AE                    | ✅                  | ❌                  | ❌                  | ❌                  |
| DroQ                      | ✅                  | ❌                  | ❌                  | ❌                  |
| Dreamer-V1                | ✅                  | ✅                  | ✅                  | ✅                  |
| Dreamer-V2                | ✅                  | ✅                  | ✅                  | ✅                  |
| Dreamer-V3                | ✅                  | ✅                  | ✅                  | ✅                  |
| Dreamer-V3 (Nature)       | ✅                  | ✅                  | ✅                  | ✅                  |
| Plan2Explore (Dreamer V1) | ✅                  | ✅                  | ✅                  | ✅                  |
| Plan2Explore (Dreamer V2) | ✅                  | ✅                  | ✅                  | ✅                  |
| Plan2Explore (Dreamer V3) | ✅                  | ✅                  | ✅                  | ✅                  |

> **Note**
>
> The Dreamers and Plan2Explore play the bounded continuous actions in [-1, 1]: with `algo.normalize_actions=True` (their default), the `sheeprl.envs.wrappers.NormalizeAction` wrapper rescales them to the bounds of the action space of the environment.

The environments supported by sheeprl are:
| Environment        | Installation command         | More info                                       | Status             |
| ------------------ | ---------------------------- | ----------------------------------------------- | ------------------ |
| Classic Control    | `uv pip install sheeprl`           |                                                 | ✅ |
| Box2D              | `uv pip install "sheeprl[box2d]"`    | Please install first `swig` with `uv pip install swig` | ✅ |
| Mujoco (Gymnasium) | `uv pip install "sheeprl[mujoco]"`   | [how_to/mujoco](https://github.com/Eclectic-Sheep/sheeprl/blob/main/howto/learn_in_dmc.md)        | ✅ |
| Atari              | `uv pip install "sheeprl[atari]"`    | [how_to/atari](https://github.com/Eclectic-Sheep/sheeprl/blob/main/howto/learn_in_atari.md)       | ✅ |
| DeepMind Control   | `uv pip install "sheeprl[dmc]"`      | [how_to/dmc](https://github.com/Eclectic-Sheep/sheeprl/blob/main/howto/learn_in_dmc.md)           | ✅ |
| MineRL             | `uv pip install "sheeprl[minerl]"`   | [how_to/minerl](https://github.com/Eclectic-Sheep/sheeprl/blob/main/howto/learn_in_minerl.md)     | ✅ |
| MineDojo           | `uv pip install "sheeprl[minedojo]"` | [how_to/minedojo](https://github.com/Eclectic-Sheep/sheeprl/blob/main/howto/learn_in_minedojo.md) | ✅ |
| DIAMBRA            | `uv pip install "sheeprl[diambra]"`  | [how_to/diambra](https://github.com/Eclectic-Sheep/sheeprl/blob/main/howto/learn_in_diambra.md)   | ✅ |
| Crafter            | `uv pip install "sheeprl[crafter]"`  | https://github.com/danijar/crafter              | ✅ |
| Super Mario Bros   | `uv pip install "sheeprl[supermario]"` | https://github.com/Kautenja/gym-super-mario-bros/tree/master | ✅ |


## Why

We want to provide a framework for RL algorithms that is at the same time simple and scalable thanks to Lightning Fabric.

Moreover, in many RL repositories, the RL algorithm is tightly coupled with the environment, making it harder to extend them beyond the gym interface. We want to provide a framework that allows to easily decouple the RL algorithm from the environment, so that it can be used with any environment.

## How to use it

> Upgrading from sheeprl 0.x? See [howto/migrate_to_v1.md](https://github.com/Eclectic-Sheep/sheeprl/blob/main/howto/migrate_to_v1.md).

### Installation

SheepRL is installed with [uv](https://docs.astral.sh/uv/), a fast Python package manager. If you don't have it yet, install it with:

```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```

Then create a virtual environment and activate it: SheepRL and its dependencies are installed there. SheepRL supports Python 3.10 to 3.13.

```bash
uv venv --python 3.11
source .venv/bin/activate
```

Three options exist for installing SheepRL in it:

1. Install the latest version directly from the [PyPi index](https://pypi.org/project/sheeprl/)
2. Clone the repo and install the local version
3. Install the framework from its GitHub URL

Instructions for the three methods are shown below.

> **Note**
>
> SheepRL is installed with `uv pip install`, not with `uv sync`: some of its extras cannot be installed together (`minerl` and `minedojo` require different versions of `gym`), so the project has no lockfile. Install only the extras you need.

#### Install SheepRL from PyPi

You can install the latest version of SheepRL with

```bash
uv pip install sheeprl
```

> **Note**
> 
> To install optional dependencies one can run for example `uv pip install "sheeprl[atari,box2d,dev,mujoco,test]"`: the quotes keep shells like zsh from expanding the brackets

For a detailed information about all the optional dependencies you can install please have a look at the [What](https://github.com/Eclectic-Sheep/sheeprl#what) section

#### Cloning and installing a local version

First, clone the repo with:

```bash
git clone https://github.com/Eclectic-Sheep/sheeprl.git
cd sheeprl
```

From inside the newly created folder, with the virtual environment activated, run

```bash
uv pip install .
```

> **Note**
> 
> To install optional dependencies one can run for example `uv pip install ".[atari,box2d,dev,mujoco,test]"`

#### Installing the framework from the GitHub repo

With the virtual environment activated:

```sh
# if you do not wish to install extras such as mujoco, atari do
uv pip install "sheeprl @ git+https://github.com/Eclectic-Sheep/sheeprl.git"

# or, to install with atari and mujoco environment support, do
uv pip install "sheeprl[atari,mujoco,dev] @ git+https://github.com/Eclectic-Sheep/sheeprl.git"

# or, to install with box2d environment support, do
uv pip install swig
uv pip install "sheeprl[box2d] @ git+https://github.com/Eclectic-Sheep/sheeprl.git"

# or, to install with minedojo environment support, do
uv pip install "sheeprl[minedojo,dev] @ git+https://github.com/Eclectic-Sheep/sheeprl.git"

# or, to install with minerl environment support, do
uv pip install "sheeprl[minerl,dev] @ git+https://github.com/Eclectic-Sheep/sheeprl.git"

# or, to install with diambra environment support, do
uv pip install "sheeprl[diambra,dev] @ git+https://github.com/Eclectic-Sheep/sheeprl.git"

# or, to install with super mario bros environment support, do
uv pip install "sheeprl[supermario,dev] @ git+https://github.com/Eclectic-Sheep/sheeprl.git"

# or, to install all extras, do
uv pip install swig
uv pip install "sheeprl[box2d,atari,mujoco,minerl,supermario,dev,test] @ git+https://github.com/Eclectic-Sheep/sheeprl.git"
```

#### Additional: installing on an M-series Mac

> **Caution**
> 
> If you are on an M-series Mac and encounter an error attributed box2dpy during installation, you need to install SWIG using the instructions shown below.


It is recommended to use [homebrew](https://brew.sh/) to install [SWIG](https://formulae.brew.sh/formula/swig) to support [Gym](https://github.com/openai/gym).

```sh
# if needed install homebrew
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# then, do
brew install swig

# then attempt to install with the preferred method, such as
uv pip install "sheeprl[atari,box2d,mujoco,dev,test] @ git+https://github.com/Eclectic-Sheep/sheeprl.git"
```

#### Additional: MineRL and MineDojo

> **Note**
> 
> If you want to install the *minedojo* or *minerl* environment support, Java JDK 8 is required: you can install it by following the instructions at this [link](https://docs.minedojo.org/sections/getting_started/install.html#on-ubuntu-20-04).

> **Caution**
>
> **MineRL** and **MineDojo** environments have **conflicting requirements**, so **DO NOT install them together** with the `uv pip install "sheeprl[minerl,minedojo]"` command, but instead **install them individually** with either the command `uv pip install "sheeprl[minerl]"` or `uv pip install "sheeprl[minedojo]"` before running an experiment with the MineRL or MineDojo environment, respectively. 

### Run an experiment with SheepRL

Now you can use one of the already available algorithms, or create your own.
For example, to train a PPO agent on the CartPole environment with only vector-like observations, just run

```bash
python sheeprl.py exp=ppo env=gym env.id=CartPole-v1
```

if you have installed from a cloned repo, or

```bash
sheeprl exp=ppo env=gym env.id=CartPole-v1
```

if you have installed SheepRL from PyPi.

Similarly, you check all the available algorithms with

```bash
python sheeprl/available_agents.py
```

if you have installed from a cloned repo, or

```bash
sheeprl-agents
```
if you have installed SheepRL from PyPi.

That's all it takes to train an agent with SheepRL! 🎉

> Before you start using the SheepRL framework, it is **highly recommended** that you read the following instructional documents:
> 
> 1. How to [run experiments](https://github.com/Eclectic-Sheep/sheeprl/blob/main/howto/run_experiments.md)
> 2. How to [modify the default configs](https://github.com/Eclectic-Sheep/sheeprl/blob/main/howto/configs.md)
> 3. How to [work with steps](https://github.com/Eclectic-Sheep/sheeprl/blob/main/howto/work_with_steps.md)
> 4. How to [select the observations](https://github.com/Eclectic-Sheep/sheeprl/blob/main/howto/inputs_and_outputs.md) and [transform them](https://github.com/Eclectic-Sheep/sheeprl/blob/main/howto/add_transform.md)
>
> Moreover, there are other useful documents in the [`howto` folder](https://github.com/Eclectic-Sheep/sheeprl/tree/main/howto), these documents contain some guidance on how to properly use the framework.

### 📈 Check your results

Once you trained an agent, a new folder called `logs` will be created, containing the logs of the training. You can visualize them with [TensorBoard](https://www.tensorflow.org/tensorboard):

```bash
tensorboard --logdir logs
```

[A video of the logs in TensorBoard](https://github.com/Eclectic-Sheep/sheeprl/assets/7341604/46ad4acd-180d-449d-b46a-25b4a1f038d9)

### 🤓 More about running an algorithm

What you run is the PPO algorithm with the default configuration. But you can also change the configuration by passing arguments to the script.

For example, in the default configuration, the number of parallel environments is 4. Let's try to change it to 8 by passing the `env.num_envs` argument:

```bash
sheeprl exp=ppo env=gym env.id=CartPole-v1 env.num_envs=8
```

All the available arguments, with their descriptions, are listed in the `sheeprl/configs` directory. You can find more information about the hierarchy of configs [here](https://github.com/Eclectic-Sheep/sheeprl/blob/main/howto/configs.md).

### Running with Lightning Fabric

To run the algorithm with Lightning Fabric, you need to specify the Fabric parameters through the CLI. For example, to run the PPO algorithm on 2 processes on the CPU, each with 4 parallel environments, you can run:

```bash
sheeprl fabric.accelerator=cpu fabric.strategy=ddp fabric.devices=2 exp=ppo env=gym env.id=CartPole-v1
```

Every process plays in its own environments and trains its own copy of the agent: the processes start from the same weights, and the gradients are averaged over the processes at every optimizer step.

You can check the available parameters for Lightning Fabric [here](https://lightning.ai/docs/fabric/stable/api/fabric_args.html).

### Evaluate your Agents

You can easily evaluate your trained agents from checkpoints: training configurations are retrieved automatically.

```bash
sheeprl-eval checkpoint_path=/path/to/checkpoint.ckpt fabric.accelerator=gpu env.capture_video=True
```

For more information, check the corresponding [howto](https://github.com/Eclectic-Sheep/sheeprl/blob/main/howto/eval_your_agent.md).

## 📖 Repository structure

The repository is structured as follows:

- `algos`: contains the implementations of the algorithms. Each algorithm is in a separate folder, and (possibly) contains the following files:

  - `<algorithm>.py`: contains the implementation of the algorithm.
  - `agent`: optional, contains the implementation of the agent.
  - `loss.py`: contains the implementation of the loss functions of the algorithm.
  - `utils.py`: contains utility functions for the algorithm.
  - `evaluate.py`: contains the evaluation function of the algorithm, used by `sheeprl-eval`.
- `configs`: contains the default configs of the algorithms.
- `core`: contains the training loop shared by all the algorithms, and the interface that every algorithm implements.
- `data`: contains the implementation of the data buffers.
- `envs`: contains the implementation of the environment wrappers.
- `models`: contains the implementation of some standard models (building blocks), like the multi-layer perceptron (MLP) or a simple convolutional network (NatureCNN)
- `utils`: contains utility functions for the framework.

## ⚙️ How SheepRL works

### From the command line to the algorithm

```bash
sheeprl exp=ppo env=gym env.id=CartPole-v1 algo.total_steps=100000
```

1. [Hydra](https://hydra.cc) composes the configuration from `sheeprl/configs`: the `exp` file chooses the groups (`algo`, `env`, `buffer`, `fabric`, `metric`, `checkpoint`, ...) and overrides some of their keys, and every key can be overridden from the command line.
2. `sheeprl.cli.run` checks the configuration, creates the [Lightning Fabric](https://lightning.ai/docs/fabric/stable/) of the run (`fabric.accelerator`, `fabric.devices`, `fabric.strategy`, `fabric.precision`), starts one process per device and seeds them.
3. Every process calls the `main()` of the algorithm named by `algo.name`, registered with the `@register_algorithm()` decorator. `main()` creates the algorithm and hands it to the training loop shared by every algorithm, `sheeprl.core.run`; when the training ends, it tests the agent (`algo.run_test=True`) and registers its models (`model_manager.disabled=False`).

### The training loop

Every process has its own environments and its own copy of the agent, which interacts with the environments and executes the training loop.

<p align="center">
  <img src="https://raw.githubusercontent.com/Eclectic-Sheep/sheeprl/main/assets/images/sheeprl_coupled.png">
</p>

Every iteration of `sheeprl.core.run(fabric, cfg, algo)`:

1. **plays**: the `Collector` (`sheeprl.core.Collector`) steps the environments `algo.steps_per_iteration` times with the actions the policy of the algorithm chooses for the current observations (random actions before `algo.learning_starts` for the off-policy algorithms), and the writer of the algorithm writes every step in the *store* of the collected data (the rollout of the on-policy algorithms, the replay buffer of the off-policy ones). The collector resets the memory of the policy (e.g. a recurrent state, `Policy.reset_state`) for the environments that start a new episode, counts the policy steps (`TrainSchedule`) and logs the episodes that have ended;
2. **trains**: `algo.batches()` yields one batch per gradient step and `algo.train_step()` does the step, returning its metrics. The on-policy algorithms train on their rollout (epochs × minibatches); the off-policy ones start after `algo.learning_starts` policy steps (optionally with `algo.per_rank_pretrain_steps` gradient steps first) and then do `algo.replay_ratio` gradient steps per policy step (`TrainSchedule`);
3. **logs and saves**: the metrics are aggregated on the device and read on the host once every `metric.log_every` policy steps, and a checkpoint is saved every `checkpoint.every` policy steps (`Cadence`).

### The environments

The collector steps the environments through an `Environment` (`sheeprl.core.Environment`): the `num_envs` environments of the process, with their current observations (`obs`), `step(actions)`, `random_actions()`, `reset()` and `close()`. Every step returns an `EnvStep`: the observations the actions were chosen from and the next ones, the rewards, `terminated` and `truncated`, the last observations of the episodes that have just ended (`final_obs`: an environment whose episode ends starts the next one in the same step), the environments created again after a crash (`restarted`), the episodes that have just ended (`episodes`) and the `info` of the environments, which neither the training loop nor the writers read.

`GymEnvironment` implements it with the gymnasium environments created by `make_env` from the `env` configs, seeded differently on every process. Another backend only has to return the same `EnvStep`s: the algorithms, the logging and the checkpoints don't change.

### The interface of an algorithm

An algorithm is implemented in its `<algorithm>.py` file, as a subclass of `sheeprl.core.Algorithm` with the following methods:

- `build()`: creates the training state (modules, optimizers, ...) and the store of the collected data, a `ReplayStore`: a `ReplayBuffer` and its sampler (`sheeprl.core.rollout_store` for the rollout of the on-policy algorithms, read by the `EpochSampler` of the minibatches of an update; `sheeprl.core.transition_store` for the replay buffer of the off-policy algorithms trained on single steps, `sheeprl.core.sequence_store` for the one of the algorithms trained on sequences).
- `policy()`: returns the `Policy` that plays in the environments, sharing its weights with the trained modules: `act(obs, greedy)` returns an `Act`, the actions to play in the environments (`env_actions`) with the columns to store (e.g. the actions one-hot, their log-probabilities, the values) and anything else the writer needs (`extras`); `random(env)` returns random actions, `init_states(num_envs)` creates the memory of the policy (e.g. a recurrent state) before the first step and `reset_state(env_idxes)` forgets it for the environments that start a new episode, which reset themselves. The policy modules of the algorithms implement it (e.g. `class PPOPolicy(nn.Module, Policy)`), so it can also be compiled or exported.
- `writer()`: returns the `Writer`, whose `write(store, step, act)` writes a step of the environments (the `EnvStep`) played with the actions `act` in the store.
- `batches()`: prepares the training data of an iteration and yields one batch per gradient step.
- `train_step()`: executes one gradient step on a batch and returns the metrics to log, as tensors.
- `end_iteration()`: optional, updates what changes once per iteration (e.g. annealed coefficients).
- `test()`: plays a test episode with the trained policy (`sheeprl.core.run_test`, the same for every algorithm), at the end of the training and to evaluate a checkpoint.

Its class attributes tell the loop how to drive it: `steps_per_iteration` (e.g. the rollout length of the on-policy algorithms, 1 for the off-policy ones), `off_policy` (training on a replay buffer, with the learning starts and the replay ratio above), `random_warmup` (random actions until `algo.learning_starts`, e.g. not when finetuning a policy) and `restart_crashed_envs` (a crashed environment is created again instead of stopping the run).

Every algorithm of SheepRL (A2C, PPO, PPO Recurrent, SAC, DroQ, SAC-AE, DreamerV1, DreamerV2, DreamerV3, DreamerV3.5 and the exploration and finetuning of Plan2Explore) is implemented this way: the environments, the logging, the checkpoints and the resuming of a run are the same for all of them.

### Distributed training

The modules are not wrapped by `DistributedDataParallel`: every process computes the gradients on its own data, and `update` (`sheeprl.core.update`) averages them over the processes before every optimizer step. The processes start from the same weights, so they stay identical. Every process samples its own replay buffer, and the processes of an on-policy algorithm do the same number of gradient steps, even with rollouts split into different numbers of minibatches.

### Compiling the losses

With `algo.compile.enabled=True`, the losses of the algorithm (forward and backward passes) are compiled with `torch.compile`, also with several processes. With `algo.compile.mode=reduce-overhead` (the default), the compiled losses run as CUDA graphs in the `32-true` and `bf16-mixed` precisions (the other precisions use the default mode), which removes most of the cost of launching their many small kernels. With `algo.compile.policy=True` (the default), the step of the policy that plays in the environments is compiled too; the optimizer steps are not compiled.

The losses are written so that they compile into graphs that don't wait for the GPU: they don't read tensors on the host (`.item()`, an `if` on a tensor), their shapes don't depend on the data (e.g. masked sums instead of boolean indexing, and the minibatches of PPO Recurrent padded to a few sizes), and the recurrent layers are unrolled from their weights while compiling, since `torch.compile` doesn't trace `nn.LSTM` and `nn.GRU`.

Compiling takes from a few seconds (PPO, SAC) to a few minutes (the Dreamers) at the start of the run. Then, on an RTX 5070 in `32-true`, a gradient step of the default experiments is from about 1.2× (PPO on Atari and SAC-AE, on pixels) and 1.4-1.9× (the Dreamers) to 2.8× (PPO on CartPole) faster. CUDA graphs reserve more memory: when a large model doesn't fit, `algo.compile.mode=null` compiles without them.

### Checkpoints, resuming and evaluation

The training state is a `TrainState` dataclass: each of its fields (modules, optimizers, annealed coefficients, ...) is saved in the checkpoints and restored when a run is resumed. The evaluation (`sheeprl-eval`) and the registration of the models from a checkpoint (`sheeprl-registration`) restore it in the same way, with `sheeprl.core.load_trained_state`.

A resumed run starts from the iteration after the one of its checkpoint. The replay buffer of an off-policy run is saved in the checkpoints when `buffer.checkpoint=True`: a run resumed with it trains right away, without playing random actions again; without it, it first fills a new one, playing its policy for `algo.learning_starts` policy steps.

## Algorithms implementation

You can check inside the folder of each algorithm the `README.md` file for the details about the implementation.

All algorithms are kept as simple as possible, in a [CleanRL](https://github.com/vwxyzjn/cleanrl) fashion. But to allow for more flexibility and also more clarity, we tried to abstract away anything that is not strictly related to the algorithm: the environments, the logging, the checkpoints and the resuming of a run are handled by the shared training loop, and the `core` folder also provides the helpers for the device, the precision and the optimizer steps (`setup_module`, `autocast` and `update`).

For example, we decided to create a `models` folder with already-made models that can be composed to create the model of the agent.

For each algorithm, losses are kept in a separate module, so that their implementation is clear and can be easily utilized for the recurrent version of the algorithm.

## 🗂️ Buffer

For the buffer implementation, we choose to use a wrapper around a dictionary of Numpy arrays.

To enable a simple way to work with numpy memory-mapped arrays, we implemented the `sheeprl.utils.memmap.MemmapArray`, a container that handles the memory-mapped arrays.

Every algorithm stores its steps in a single kind of storage, the `ReplayBuffer`: the steps of every environment, with a write pointer per environment (`add` with `env_idxes` writes some environments only, e.g. the first steps of the ones that ended an episode). What the training reads from it is decided by the samplers of `sheeprl.data.samplers`, which draw the steps of the samples with their own random number generator and let the buffer gather them:

- `TransitionSampler`: single steps (SAC, DroQ, SAC-AE);
- `SequenceSampler`: sequences of consecutive steps of a single environment (the Dreamers, Plan2Explore);
- `EpisodeSampler`: sequences inside the episodes that ended, with their ends prioritized with `buffer.prioritize_ends` (DreamerV2 with `buffer.type=episode`);
- `CuriousSequenceSampler`: sequences drawn by the priorities of [Curious Replay](https://arxiv.org/abs/2306.15934), from the number of trainings on their steps and the losses of the world model on them (DreamerV3 and DreamerV3.5 with `buffer.curious.enabled=True`);
- `EpochSampler`: the minibatches of the epochs of an on-policy update (PPO, A2C, PPO-recurrent).

The off-policy algorithms train on a `sheeprl.data.store.ReplayStore`: a storage and a sampler, whose batches go to the device of the training. The store is saved in the checkpoints with its sampler, whose generator a resumed run continues. With `buffer.prefetch` the next batches are sampled in a thread while the training uses the current ones, and with `buffer.on_device` the storage is kept in the memory of the device, where its batches are gathered (see the [configs howto](https://github.com/Eclectic-Sheep/sheeprl/blob/main/howto/configs.md#buffer)).

### 🔍 Technical details

The shape of the Numpy arrays in the dictionary is `(T, B, *)`, where `T` is the number of timesteps, `B` is the number of parallel environments, and `*` is the shape of the data.

The on-policy algorithms (A2C, PPO and PPO Recurrent) store their rollout in a `ReplayBuffer` with `T` equal to `algo.rollout_steps` and `B` equal to `env.num_envs`, in a `ReplayStore` (`sheeprl.core.rollout_store`). For A2C and PPO, `buffer.size` must be equal to `algo.rollout_steps`.

## 🙇 Contributing

The best way to contribute is by opening an issue to discuss a new feature or a bug, or by opening a PR to fix a bug or to add a new feature.

## 📭 Contacts

You can contact us for any further questions or discussions:

- Federico Belotti: belo.fede@outlook.com
- Davide Angioni: davide.angioni@orobix.com
- Refik Can Malli: refikcan.malli@orobix.com
- Michele Milesi: michele.milesi@orobix.com
