SAC-pytorch 0.0.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sac_pytorch-0.0.2/.github/workflows/python-publish.yml +38 -0
- sac_pytorch-0.0.2/.gitignore +160 -0
- sac_pytorch-0.0.2/LICENSE +21 -0
- sac_pytorch-0.0.2/PKG-INFO +138 -0
- sac_pytorch-0.0.2/README.md +88 -0
- sac_pytorch-0.0.2/SAC_pytorch/SAC.py +805 -0
- sac_pytorch-0.0.2/SAC_pytorch/__init__.py +4 -0
- sac_pytorch-0.0.2/pyproject.toml +65 -0
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
# This workflow will upload a Python Package using Twine when a release is created
|
|
4
|
+
# For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries
|
|
5
|
+
|
|
6
|
+
# This workflow uses actions that are not certified by GitHub.
|
|
7
|
+
# They are provided by a third-party and are governed by
|
|
8
|
+
# separate terms of service, privacy policy, and support
|
|
9
|
+
# documentation.
|
|
10
|
+
|
|
11
|
+
name: Upload Python Package
|
|
12
|
+
|
|
13
|
+
on:
|
|
14
|
+
release:
|
|
15
|
+
types: [published]
|
|
16
|
+
|
|
17
|
+
jobs:
|
|
18
|
+
deploy:
|
|
19
|
+
|
|
20
|
+
runs-on: ubuntu-latest
|
|
21
|
+
|
|
22
|
+
steps:
|
|
23
|
+
- uses: actions/checkout@v2
|
|
24
|
+
- name: Set up Python
|
|
25
|
+
uses: actions/setup-python@v2
|
|
26
|
+
with:
|
|
27
|
+
python-version: '3.x'
|
|
28
|
+
- name: Install dependencies
|
|
29
|
+
run: |
|
|
30
|
+
python -m pip install --upgrade pip
|
|
31
|
+
pip install build
|
|
32
|
+
- name: Build package
|
|
33
|
+
run: python -m build
|
|
34
|
+
- name: Publish package
|
|
35
|
+
uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
|
|
36
|
+
with:
|
|
37
|
+
user: __token__
|
|
38
|
+
password: ${{ secrets.PYPI_API_TOKEN }}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
share/python-wheels/
|
|
24
|
+
*.egg-info/
|
|
25
|
+
.installed.cfg
|
|
26
|
+
*.egg
|
|
27
|
+
MANIFEST
|
|
28
|
+
|
|
29
|
+
# PyInstaller
|
|
30
|
+
# Usually these files are written by a python script from a template
|
|
31
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
32
|
+
*.manifest
|
|
33
|
+
*.spec
|
|
34
|
+
|
|
35
|
+
# Installer logs
|
|
36
|
+
pip-log.txt
|
|
37
|
+
pip-delete-this-directory.txt
|
|
38
|
+
|
|
39
|
+
# Unit test / coverage reports
|
|
40
|
+
htmlcov/
|
|
41
|
+
.tox/
|
|
42
|
+
.nox/
|
|
43
|
+
.coverage
|
|
44
|
+
.coverage.*
|
|
45
|
+
.cache
|
|
46
|
+
nosetests.xml
|
|
47
|
+
coverage.xml
|
|
48
|
+
*.cover
|
|
49
|
+
*.py,cover
|
|
50
|
+
.hypothesis/
|
|
51
|
+
.pytest_cache/
|
|
52
|
+
cover/
|
|
53
|
+
|
|
54
|
+
# Translations
|
|
55
|
+
*.mo
|
|
56
|
+
*.pot
|
|
57
|
+
|
|
58
|
+
# Django stuff:
|
|
59
|
+
*.log
|
|
60
|
+
local_settings.py
|
|
61
|
+
db.sqlite3
|
|
62
|
+
db.sqlite3-journal
|
|
63
|
+
|
|
64
|
+
# Flask stuff:
|
|
65
|
+
instance/
|
|
66
|
+
.webassets-cache
|
|
67
|
+
|
|
68
|
+
# Scrapy stuff:
|
|
69
|
+
.scrapy
|
|
70
|
+
|
|
71
|
+
# Sphinx documentation
|
|
72
|
+
docs/_build/
|
|
73
|
+
|
|
74
|
+
# PyBuilder
|
|
75
|
+
.pybuilder/
|
|
76
|
+
target/
|
|
77
|
+
|
|
78
|
+
# Jupyter Notebook
|
|
79
|
+
.ipynb_checkpoints
|
|
80
|
+
|
|
81
|
+
# IPython
|
|
82
|
+
profile_default/
|
|
83
|
+
ipython_config.py
|
|
84
|
+
|
|
85
|
+
# pyenv
|
|
86
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
87
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
88
|
+
# .python-version
|
|
89
|
+
|
|
90
|
+
# pipenv
|
|
91
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
92
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
93
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
94
|
+
# install all needed dependencies.
|
|
95
|
+
#Pipfile.lock
|
|
96
|
+
|
|
97
|
+
# poetry
|
|
98
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
99
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
100
|
+
# commonly ignored for libraries.
|
|
101
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
102
|
+
#poetry.lock
|
|
103
|
+
|
|
104
|
+
# pdm
|
|
105
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
106
|
+
#pdm.lock
|
|
107
|
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
|
108
|
+
# in version control.
|
|
109
|
+
# https://pdm.fming.dev/#use-with-ide
|
|
110
|
+
.pdm.toml
|
|
111
|
+
|
|
112
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
113
|
+
__pypackages__/
|
|
114
|
+
|
|
115
|
+
# Celery stuff
|
|
116
|
+
celerybeat-schedule
|
|
117
|
+
celerybeat.pid
|
|
118
|
+
|
|
119
|
+
# SageMath parsed files
|
|
120
|
+
*.sage.py
|
|
121
|
+
|
|
122
|
+
# Environments
|
|
123
|
+
.env
|
|
124
|
+
.venv
|
|
125
|
+
env/
|
|
126
|
+
venv/
|
|
127
|
+
ENV/
|
|
128
|
+
env.bak/
|
|
129
|
+
venv.bak/
|
|
130
|
+
|
|
131
|
+
# Spyder project settings
|
|
132
|
+
.spyderproject
|
|
133
|
+
.spyproject
|
|
134
|
+
|
|
135
|
+
# Rope project settings
|
|
136
|
+
.ropeproject
|
|
137
|
+
|
|
138
|
+
# mkdocs documentation
|
|
139
|
+
/site
|
|
140
|
+
|
|
141
|
+
# mypy
|
|
142
|
+
.mypy_cache/
|
|
143
|
+
.dmypy.json
|
|
144
|
+
dmypy.json
|
|
145
|
+
|
|
146
|
+
# Pyre type checker
|
|
147
|
+
.pyre/
|
|
148
|
+
|
|
149
|
+
# pytype static type analyzer
|
|
150
|
+
.pytype/
|
|
151
|
+
|
|
152
|
+
# Cython debug symbols
|
|
153
|
+
cython_debug/
|
|
154
|
+
|
|
155
|
+
# PyCharm
|
|
156
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
157
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
158
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
159
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
160
|
+
#.idea/
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Phil Wang
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: SAC-pytorch
|
|
3
|
+
Version: 0.0.2
|
|
4
|
+
Summary: Soft Actor Critic - Pytorch
|
|
5
|
+
Project-URL: Homepage, https://pypi.org/project/SAC-pytorch/
|
|
6
|
+
Project-URL: Repository, https://github.com/lucidrains/SAC-pytorch
|
|
7
|
+
Author-email: Phil Wang <lucidrains@gmail.com>
|
|
8
|
+
License: MIT License
|
|
9
|
+
|
|
10
|
+
Copyright (c) 2024 Phil Wang
|
|
11
|
+
|
|
12
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
13
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
14
|
+
in the Software without restriction, including without limitation the rights
|
|
15
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
16
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
17
|
+
furnished to do so, subject to the following conditions:
|
|
18
|
+
|
|
19
|
+
The above copyright notice and this permission notice shall be included in all
|
|
20
|
+
copies or substantial portions of the Software.
|
|
21
|
+
|
|
22
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
23
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
24
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
25
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
26
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
27
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
28
|
+
SOFTWARE.
|
|
29
|
+
License-File: LICENSE
|
|
30
|
+
Keywords: artificial intelligence,deep learning,reinforcement learning,soft actor critic
|
|
31
|
+
Classifier: Development Status :: 4 - Beta
|
|
32
|
+
Classifier: Intended Audience :: Developers
|
|
33
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
34
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
35
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
36
|
+
Requires-Python: >=3.9
|
|
37
|
+
Requires-Dist: adam-atan2-pytorch>=0.0.15
|
|
38
|
+
Requires-Dist: beartype
|
|
39
|
+
Requires-Dist: einops>=0.8.0
|
|
40
|
+
Requires-Dist: einx[torch]>=0.1.3
|
|
41
|
+
Requires-Dist: ema-pytorch>=0.6.2
|
|
42
|
+
Requires-Dist: jaxtyping
|
|
43
|
+
Requires-Dist: pytorch-custom-utils>=0.0.18
|
|
44
|
+
Requires-Dist: soft-moe-pytorch>=0.1.6
|
|
45
|
+
Requires-Dist: torch>=2.0
|
|
46
|
+
Provides-Extra: examples
|
|
47
|
+
Provides-Extra: test
|
|
48
|
+
Requires-Dist: pytest; extra == 'test'
|
|
49
|
+
Description-Content-Type: text/markdown
|
|
50
|
+
|
|
51
|
+
## SAC (Soft Actor Critic) - Pytorch (wip)
|
|
52
|
+
|
|
53
|
+
Implementation of Soft Actor Critic and some of its improvements in Pytorch. Interest comes from watching <a href="https://www.youtube.com/watch?v=17NrtKHdPDw">this lecture</a>
|
|
54
|
+
|
|
55
|
+
## Citations
|
|
56
|
+
|
|
57
|
+
```bibtex
|
|
58
|
+
@article{Haarnoja2018SoftAA,
|
|
59
|
+
title = {Soft Actor-Critic Algorithms and Applications},
|
|
60
|
+
author = {Tuomas Haarnoja and Aurick Zhou and Kristian Hartikainen and G. Tucker and Sehoon Ha and Jie Tan and Vikash Kumar and Henry Zhu and Abhishek Gupta and P. Abbeel and Sergey Levine},
|
|
61
|
+
journal = {ArXiv},
|
|
62
|
+
year = {2018},
|
|
63
|
+
volume = {abs/1812.05905},
|
|
64
|
+
url = {https://api.semanticscholar.org/CorpusID:55703664}
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
```bibtex
|
|
69
|
+
@article{Hiraoka2021DropoutQF,
|
|
70
|
+
title = {Dropout Q-Functions for Doubly Efficient Reinforcement Learning},
|
|
71
|
+
author = {Takuya Hiraoka and Takahisa Imagawa and Taisei Hashimoto and Takashi Onishi and Yoshimasa Tsuruoka},
|
|
72
|
+
journal = {ArXiv},
|
|
73
|
+
year = {2021},
|
|
74
|
+
volume = {abs/2110.02034},
|
|
75
|
+
url = {https://api.semanticscholar.org/CorpusID:238353966}
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
```bibtex
|
|
80
|
+
@inproceedings{ObandoCeron2024MixturesOE,
|
|
81
|
+
title = {Mixtures of Experts Unlock Parameter Scaling for Deep RL},
|
|
82
|
+
author = {Johan S. Obando-Ceron and Ghada Sokar and Timon Willi and Clare Lyle and Jesse Farebrother and Jakob Foerster and Gintare Karolina Dziugaite and Doina Precup and Pablo Samuel Castro},
|
|
83
|
+
year = {2024},
|
|
84
|
+
url = {https://api.semanticscholar.org/CorpusID:267637059}
|
|
85
|
+
}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
```bibtex
|
|
89
|
+
@inproceedings{Kumar2023MaintainingPI,
|
|
90
|
+
title = {Maintaining Plasticity in Continual Learning via Regenerative Regularization},
|
|
91
|
+
author = {Saurabh Kumar and Henrik Marklund and Benjamin Van Roy},
|
|
92
|
+
year = {2023},
|
|
93
|
+
url = {https://api.semanticscholar.org/CorpusID:261076021}
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
```bibtex
|
|
98
|
+
@inproceedings{Kuznetsov2020ControllingOB,
|
|
99
|
+
title = {Controlling Overestimation Bias with Truncated Mixture of Continuous Distributional Quantile Critics},
|
|
100
|
+
author = {Arsenii Kuznetsov and Pavel Shvechikov and Alexander Grishin and Dmitry P. Vetrov},
|
|
101
|
+
booktitle = {International Conference on Machine Learning},
|
|
102
|
+
year = {2020},
|
|
103
|
+
url = {https://api.semanticscholar.org/CorpusID:218581840}
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
```bibtex
|
|
108
|
+
@article{Zagoruyko2017DiracNetsTV,
|
|
109
|
+
title = {DiracNets: Training Very Deep Neural Networks Without Skip-Connections},
|
|
110
|
+
author={Sergey Zagoruyko and Nikos Komodakis},
|
|
111
|
+
journal = {ArXiv},
|
|
112
|
+
year = {2017},
|
|
113
|
+
volume = {abs/1706.00388},
|
|
114
|
+
url = {https://api.semanticscholar.org/CorpusID:1086822}
|
|
115
|
+
}
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
```bibtex
|
|
119
|
+
@article{Abbas2023LossOP,
|
|
120
|
+
title = {Loss of Plasticity in Continual Deep Reinforcement Learning},
|
|
121
|
+
author = {Zaheer Abbas and Rosie Zhao and Joseph Modayil and Adam White and Marlos C. Machado},
|
|
122
|
+
journal = {ArXiv},
|
|
123
|
+
year = {2023},
|
|
124
|
+
volume = {abs/2303.07507},
|
|
125
|
+
url = {https://api.semanticscholar.org/CorpusID:257504763}
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
```bibtex
|
|
130
|
+
@article{Nauman2024BiggerRO,
|
|
131
|
+
title = {Bigger, Regularized, Optimistic: scaling for compute and sample-efficient continuous control},
|
|
132
|
+
author = {Michal Nauman and Mateusz Ostaszewski and Krzysztof Jankowski and Piotr Milo's and Marek Cygan},
|
|
133
|
+
journal = {ArXiv},
|
|
134
|
+
year = {2024},
|
|
135
|
+
volume = {abs/2405.16158},
|
|
136
|
+
url = {https://api.semanticscholar.org/CorpusID:270063045}
|
|
137
|
+
}
|
|
138
|
+
```
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
## SAC (Soft Actor Critic) - Pytorch (wip)
|
|
2
|
+
|
|
3
|
+
Implementation of Soft Actor Critic and some of its improvements in Pytorch. Interest comes from watching <a href="https://www.youtube.com/watch?v=17NrtKHdPDw">this lecture</a>
|
|
4
|
+
|
|
5
|
+
## Citations
|
|
6
|
+
|
|
7
|
+
```bibtex
|
|
8
|
+
@article{Haarnoja2018SoftAA,
|
|
9
|
+
title = {Soft Actor-Critic Algorithms and Applications},
|
|
10
|
+
author = {Tuomas Haarnoja and Aurick Zhou and Kristian Hartikainen and G. Tucker and Sehoon Ha and Jie Tan and Vikash Kumar and Henry Zhu and Abhishek Gupta and P. Abbeel and Sergey Levine},
|
|
11
|
+
journal = {ArXiv},
|
|
12
|
+
year = {2018},
|
|
13
|
+
volume = {abs/1812.05905},
|
|
14
|
+
url = {https://api.semanticscholar.org/CorpusID:55703664}
|
|
15
|
+
}
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
```bibtex
|
|
19
|
+
@article{Hiraoka2021DropoutQF,
|
|
20
|
+
title = {Dropout Q-Functions for Doubly Efficient Reinforcement Learning},
|
|
21
|
+
author = {Takuya Hiraoka and Takahisa Imagawa and Taisei Hashimoto and Takashi Onishi and Yoshimasa Tsuruoka},
|
|
22
|
+
journal = {ArXiv},
|
|
23
|
+
year = {2021},
|
|
24
|
+
volume = {abs/2110.02034},
|
|
25
|
+
url = {https://api.semanticscholar.org/CorpusID:238353966}
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
```bibtex
|
|
30
|
+
@inproceedings{ObandoCeron2024MixturesOE,
|
|
31
|
+
title = {Mixtures of Experts Unlock Parameter Scaling for Deep RL},
|
|
32
|
+
author = {Johan S. Obando-Ceron and Ghada Sokar and Timon Willi and Clare Lyle and Jesse Farebrother and Jakob Foerster and Gintare Karolina Dziugaite and Doina Precup and Pablo Samuel Castro},
|
|
33
|
+
year = {2024},
|
|
34
|
+
url = {https://api.semanticscholar.org/CorpusID:267637059}
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
```bibtex
|
|
39
|
+
@inproceedings{Kumar2023MaintainingPI,
|
|
40
|
+
title = {Maintaining Plasticity in Continual Learning via Regenerative Regularization},
|
|
41
|
+
author = {Saurabh Kumar and Henrik Marklund and Benjamin Van Roy},
|
|
42
|
+
year = {2023},
|
|
43
|
+
url = {https://api.semanticscholar.org/CorpusID:261076021}
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
```bibtex
|
|
48
|
+
@inproceedings{Kuznetsov2020ControllingOB,
|
|
49
|
+
title = {Controlling Overestimation Bias with Truncated Mixture of Continuous Distributional Quantile Critics},
|
|
50
|
+
author = {Arsenii Kuznetsov and Pavel Shvechikov and Alexander Grishin and Dmitry P. Vetrov},
|
|
51
|
+
booktitle = {International Conference on Machine Learning},
|
|
52
|
+
year = {2020},
|
|
53
|
+
url = {https://api.semanticscholar.org/CorpusID:218581840}
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
```bibtex
|
|
58
|
+
@article{Zagoruyko2017DiracNetsTV,
|
|
59
|
+
title = {DiracNets: Training Very Deep Neural Networks Without Skip-Connections},
|
|
60
|
+
author={Sergey Zagoruyko and Nikos Komodakis},
|
|
61
|
+
journal = {ArXiv},
|
|
62
|
+
year = {2017},
|
|
63
|
+
volume = {abs/1706.00388},
|
|
64
|
+
url = {https://api.semanticscholar.org/CorpusID:1086822}
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
```bibtex
|
|
69
|
+
@article{Abbas2023LossOP,
|
|
70
|
+
title = {Loss of Plasticity in Continual Deep Reinforcement Learning},
|
|
71
|
+
author = {Zaheer Abbas and Rosie Zhao and Joseph Modayil and Adam White and Marlos C. Machado},
|
|
72
|
+
journal = {ArXiv},
|
|
73
|
+
year = {2023},
|
|
74
|
+
volume = {abs/2303.07507},
|
|
75
|
+
url = {https://api.semanticscholar.org/CorpusID:257504763}
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
```bibtex
|
|
80
|
+
@article{Nauman2024BiggerRO,
|
|
81
|
+
title = {Bigger, Regularized, Optimistic: scaling for compute and sample-efficient continuous control},
|
|
82
|
+
author = {Michal Nauman and Mateusz Ostaszewski and Krzysztof Jankowski and Piotr Milo's and Marek Cygan},
|
|
83
|
+
journal = {ArXiv},
|
|
84
|
+
year = {2024},
|
|
85
|
+
volume = {abs/2405.16158},
|
|
86
|
+
url = {https://api.semanticscholar.org/CorpusID:270063045}
|
|
87
|
+
}
|
|
88
|
+
```
|
|
@@ -0,0 +1,805 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from collections import namedtuple
|
|
5
|
+
|
|
6
|
+
import torch
|
|
7
|
+
import torch.nn.functional as F
|
|
8
|
+
from torch.distributions import Normal
|
|
9
|
+
from torch import nn, einsum, Tensor, tensor
|
|
10
|
+
from torch.nn import Module, ModuleList, Sequential
|
|
11
|
+
|
|
12
|
+
from adam_atan2_pytorch.adam_atan2_with_wasserstein_reg import AdamAtan2 as Adam
|
|
13
|
+
|
|
14
|
+
# tensor typing
|
|
15
|
+
|
|
16
|
+
import jaxtyping
|
|
17
|
+
from beartype import beartype
|
|
18
|
+
from beartype.door import is_bearable
|
|
19
|
+
|
|
20
|
+
class TorchTyping:
|
|
21
|
+
def __init__(self, abstract_dtype):
|
|
22
|
+
self.abstract_dtype = abstract_dtype
|
|
23
|
+
|
|
24
|
+
def __getitem__(self, shapes: str):
|
|
25
|
+
return self.abstract_dtype[Tensor, shapes]
|
|
26
|
+
|
|
27
|
+
Float = TorchTyping(jaxtyping.Float)
|
|
28
|
+
Int = TorchTyping(jaxtyping.Int)
|
|
29
|
+
Bool = TorchTyping(jaxtyping.Bool)
|
|
30
|
+
|
|
31
|
+
# ein notations
|
|
32
|
+
# b - batch
|
|
33
|
+
# n - number of actions
|
|
34
|
+
# nc - number of continuous actions
|
|
35
|
+
# nd - number of discrete actions
|
|
36
|
+
# c - critics
|
|
37
|
+
# q - quantiles
|
|
38
|
+
|
|
39
|
+
from einx import get_at
|
|
40
|
+
from einops import rearrange, repeat, reduce, pack, unpack
|
|
41
|
+
from einops.layers.torch import Rearrange
|
|
42
|
+
|
|
43
|
+
# EMA for target networks
|
|
44
|
+
|
|
45
|
+
from ema_pytorch import EMA
|
|
46
|
+
|
|
47
|
+
# constants
|
|
48
|
+
|
|
49
|
+
ContinuousOutput = namedtuple('ContinuousOutput', [
|
|
50
|
+
'mu',
|
|
51
|
+
'sigma'
|
|
52
|
+
])
|
|
53
|
+
|
|
54
|
+
SoftActorOutput = namedtuple('SoftActorOutput', [
|
|
55
|
+
'continuous',
|
|
56
|
+
'discrete'
|
|
57
|
+
])
|
|
58
|
+
|
|
59
|
+
SampledSoftActorOutput = namedtuple('SampledSoftActorOutput', [
|
|
60
|
+
'continuous',
|
|
61
|
+
'continuous_log_prob',
|
|
62
|
+
'discrete',
|
|
63
|
+
'discrete_action_logits',
|
|
64
|
+
])
|
|
65
|
+
|
|
66
|
+
# helpers
|
|
67
|
+
|
|
68
|
+
def exists(v):
|
|
69
|
+
return v is not None
|
|
70
|
+
|
|
71
|
+
def default(v, d):
|
|
72
|
+
return v if exists(v) else d
|
|
73
|
+
|
|
74
|
+
def compact(arr):
|
|
75
|
+
return [*filter(exists, arr)]
|
|
76
|
+
|
|
77
|
+
def identity(t):
|
|
78
|
+
return t
|
|
79
|
+
|
|
80
|
+
def cast_tuple(t, length = 1):
|
|
81
|
+
return t if isinstance(t, tuple) else ((t,) * length)
|
|
82
|
+
|
|
83
|
+
# tensor helpers
|
|
84
|
+
|
|
85
|
+
def log(t, eps = 1e-20):
|
|
86
|
+
return torch.log(t.clamp(min = eps))
|
|
87
|
+
|
|
88
|
+
def entropy(t, eps = 1e-20):
|
|
89
|
+
prob = t.softmax(dim = -1)
|
|
90
|
+
return (-prob * log(prob, eps = eps)).sum(dim = -1)
|
|
91
|
+
|
|
92
|
+
def gumbel_noise(t):
|
|
93
|
+
noise = torch.rand_like(t)
|
|
94
|
+
return -log(-log(noise))
|
|
95
|
+
|
|
96
|
+
def gumbel_sample(t, temperature = 1., dim = -1):
|
|
97
|
+
assert temperature > 0.
|
|
98
|
+
return ((t / temperature) + gumbel_noise(t)).argmax(dim = dim)
|
|
99
|
+
|
|
100
|
+
def init_(m):
|
|
101
|
+
if not isinstance(m, nn.Linear):
|
|
102
|
+
return
|
|
103
|
+
|
|
104
|
+
gain = torch.nn.init.calculate_gain('relu')
|
|
105
|
+
torch.nn.init.orthogonal_(m.weight, gain)
|
|
106
|
+
|
|
107
|
+
if not exists(m.bias):
|
|
108
|
+
return
|
|
109
|
+
|
|
110
|
+
torch.nn.init.zeros_(m.bias)
|
|
111
|
+
|
|
112
|
+
# helper classes
|
|
113
|
+
|
|
114
|
+
def Sequential(*modules):
|
|
115
|
+
return nn.Sequential(*filter(exists, modules))
|
|
116
|
+
|
|
117
|
+
class Residual(Module):
|
|
118
|
+
@beartype
|
|
119
|
+
def __init__(
|
|
120
|
+
self,
|
|
121
|
+
fn: Module,
|
|
122
|
+
dim_in,
|
|
123
|
+
dim_out
|
|
124
|
+
):
|
|
125
|
+
super().__init__()
|
|
126
|
+
self.fn = fn
|
|
127
|
+
self.residual_proj = nn.Linear(dim_in, dim_out) if dim_in != dim_out else identity
|
|
128
|
+
|
|
129
|
+
def forward(self, x, **kwargs):
|
|
130
|
+
return self.fn(x, **kwargs) + self.residual_proj(x)
|
|
131
|
+
|
|
132
|
+
# "bro" mlp
|
|
133
|
+
|
|
134
|
+
class BroMLP(Module):
|
|
135
|
+
@beartype
|
|
136
|
+
def __init__(
|
|
137
|
+
self,
|
|
138
|
+
dim,
|
|
139
|
+
dim_out,
|
|
140
|
+
dim_hidden = None,
|
|
141
|
+
depth = 3,
|
|
142
|
+
dropout = 0.,
|
|
143
|
+
activation = nn.ReLU,
|
|
144
|
+
expansion_factor = 2,
|
|
145
|
+
final_norm = False
|
|
146
|
+
):
|
|
147
|
+
super().__init__()
|
|
148
|
+
"""
|
|
149
|
+
following the design of BroNet https://arxiv.org/abs/2405.16158v1
|
|
150
|
+
"""
|
|
151
|
+
|
|
152
|
+
dim_hidden = default(dim_hidden, dim * 2)
|
|
153
|
+
|
|
154
|
+
layers = []
|
|
155
|
+
|
|
156
|
+
self.proj_in = nn.Sequential(
|
|
157
|
+
nn.Linear(dim, dim_hidden),
|
|
158
|
+
activation()
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
dim_inner = dim_hidden * expansion_factor
|
|
162
|
+
|
|
163
|
+
for _ in range(depth):
|
|
164
|
+
|
|
165
|
+
layer = Sequential(
|
|
166
|
+
nn.Linear(dim_hidden, dim_inner),
|
|
167
|
+
nn.Dropout(dropout),
|
|
168
|
+
nn.LayerNorm(dim_inner, bias = False),
|
|
169
|
+
activation(),
|
|
170
|
+
nn.Linear(dim_inner, dim_hidden),
|
|
171
|
+
nn.LayerNorm(dim_hidden, bias = False),
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
nn.init.constant_(layer[-1].weight, 1e-5)
|
|
175
|
+
layers.append(layer)
|
|
176
|
+
|
|
177
|
+
# final layer out
|
|
178
|
+
|
|
179
|
+
self.layers = ModuleList(layers)
|
|
180
|
+
|
|
181
|
+
self.final_norm = nn.LayerNorm(dim_hidden) if final_norm else nn.Identity()
|
|
182
|
+
|
|
183
|
+
self.proj_out = nn.Linear(dim_hidden, dim_out)
|
|
184
|
+
|
|
185
|
+
# init
|
|
186
|
+
|
|
187
|
+
self.apply(init_)
|
|
188
|
+
|
|
189
|
+
def forward(self, x):
|
|
190
|
+
|
|
191
|
+
x = self.proj_in(x)
|
|
192
|
+
|
|
193
|
+
for layer in self.layers:
|
|
194
|
+
x = layer(x) + x
|
|
195
|
+
|
|
196
|
+
x = self.final_norm(x)
|
|
197
|
+
return self.proj_out(x)
|
|
198
|
+
|
|
199
|
+
# main modules
|
|
200
|
+
|
|
201
|
+
class Actor(Module):
|
|
202
|
+
@beartype
|
|
203
|
+
def __init__(
|
|
204
|
+
self,
|
|
205
|
+
*,
|
|
206
|
+
dim_state,
|
|
207
|
+
num_cont_actions,
|
|
208
|
+
mlp_depth = 3,
|
|
209
|
+
num_discrete_actions: tuple[int, ...] = (),
|
|
210
|
+
dim_hidden = None,
|
|
211
|
+
eps = 1e-5
|
|
212
|
+
):
|
|
213
|
+
super().__init__()
|
|
214
|
+
self.eps = eps
|
|
215
|
+
|
|
216
|
+
discrete_action_dims = sum(num_discrete_actions)
|
|
217
|
+
cont_action_dims = num_cont_actions * 2
|
|
218
|
+
|
|
219
|
+
self.num_cont_actions = num_cont_actions
|
|
220
|
+
self.num_discrete_actions = num_discrete_actions
|
|
221
|
+
self.split_dims = (discrete_action_dims, cont_action_dims)
|
|
222
|
+
|
|
223
|
+
self.to_actions = BroMLP(
|
|
224
|
+
dim_state,
|
|
225
|
+
depth = mlp_depth,
|
|
226
|
+
dim_hidden = dim_hidden,
|
|
227
|
+
dim_out = discrete_action_dims + cont_action_dims
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def forward(
|
|
232
|
+
self,
|
|
233
|
+
state: Float['b ...'],
|
|
234
|
+
sample = False,
|
|
235
|
+
cont_reparametrize = False,
|
|
236
|
+
discrete_sample_temperature = 1.,
|
|
237
|
+
discrete_sample_deterministic = False,
|
|
238
|
+
) -> (
|
|
239
|
+
SoftActorOutput |
|
|
240
|
+
SampledSoftActorOutput
|
|
241
|
+
):
|
|
242
|
+
|
|
243
|
+
action_dims = self.to_actions(state)
|
|
244
|
+
|
|
245
|
+
discrete_actions, cont_actions = action_dims.split(self.split_dims, dim = -1)
|
|
246
|
+
discrete_action_logits = discrete_actions.split(self.num_discrete_actions, dim = -1)
|
|
247
|
+
|
|
248
|
+
mu, sigma = rearrange(cont_actions, '... (n mu_sigma) -> mu_sigma ... n', mu_sigma = 2)
|
|
249
|
+
sigma = sigma.sigmoid().clamp(min = self.eps)
|
|
250
|
+
|
|
251
|
+
cont_output = ContinuousOutput(mu, sigma)
|
|
252
|
+
discrete_output = discrete_action_logits
|
|
253
|
+
|
|
254
|
+
if not sample:
|
|
255
|
+
return SoftActorOutput(cont_output, discrete_output)
|
|
256
|
+
|
|
257
|
+
# handle continuous
|
|
258
|
+
|
|
259
|
+
if cont_reparametrize:
|
|
260
|
+
sampled_cont_actions = mu + sigma * torch.randn_like(sigma)
|
|
261
|
+
else:
|
|
262
|
+
sampled_cont_actions = torch.normal(mu, sigma)
|
|
263
|
+
|
|
264
|
+
squashed_cont_actions = sampled_cont_actions.tanh() # tanh squashing
|
|
265
|
+
|
|
266
|
+
cont_log_prob = Normal(mu, sigma).log_prob(sampled_cont_actions)
|
|
267
|
+
cont_log_prob = cont_log_prob - log(1. - squashed_cont_actions ** 2, eps = self.eps)
|
|
268
|
+
|
|
269
|
+
scaled_squashed_cont_actions = squashed_cont_actions * self.num_cont_actions
|
|
270
|
+
|
|
271
|
+
# handle discrete
|
|
272
|
+
|
|
273
|
+
sampled_discrete_actions = []
|
|
274
|
+
discrete_log_probs = []
|
|
275
|
+
|
|
276
|
+
for logits in discrete_action_logits:
|
|
277
|
+
|
|
278
|
+
if discrete_sample_deterministic:
|
|
279
|
+
sampled_action = logits.argmax(dim = -1)
|
|
280
|
+
else:
|
|
281
|
+
sampled_action = gumbel_sample(logits, temperature = discrete_sample_temperature)
|
|
282
|
+
|
|
283
|
+
sampled_discrete_actions.append(sampled_action)
|
|
284
|
+
|
|
285
|
+
log_probs = logits.log_softmax(dim = -1)
|
|
286
|
+
discrete_log_prob = get_at('... [d], ... -> ...', log_probs, sampled_action)
|
|
287
|
+
discrete_log_probs.append(discrete_log_prob)
|
|
288
|
+
|
|
289
|
+
# return all sampled continuous and discrete actions with their associated log prob
|
|
290
|
+
|
|
291
|
+
return SampledSoftActorOutput(
|
|
292
|
+
scaled_squashed_cont_actions,
|
|
293
|
+
torch.stack(sampled_discrete_actions, dim = -1),
|
|
294
|
+
cont_log_prob,
|
|
295
|
+
discrete_action_logits
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
class Critic(Module):
|
|
299
|
+
@beartype
|
|
300
|
+
def __init__(
|
|
301
|
+
self,
|
|
302
|
+
*,
|
|
303
|
+
dim_state,
|
|
304
|
+
num_cont_actions,
|
|
305
|
+
mlp_depth = 3,
|
|
306
|
+
num_discrete_actions: tuple[int, ...] = (),
|
|
307
|
+
dim_hidden = None,
|
|
308
|
+
layernorm = False,
|
|
309
|
+
dropout = 0.,
|
|
310
|
+
num_quantiles: int | None = None,
|
|
311
|
+
quantiles: tuple[float, ...] | None = None
|
|
312
|
+
):
|
|
313
|
+
super().__init__()
|
|
314
|
+
assert not exists(num_quantiles) or num_quantiles > 0
|
|
315
|
+
|
|
316
|
+
use_quantiles = exists(num_quantiles)
|
|
317
|
+
self.returning_quantiles = use_quantiles
|
|
318
|
+
|
|
319
|
+
num_actions_split = tensor((num_cont_actions, *num_discrete_actions))
|
|
320
|
+
|
|
321
|
+
# determine the output dimension of the critic
|
|
322
|
+
# which is the sum of all the actions (continous and discrete), multiplied by the number of quantiles
|
|
323
|
+
|
|
324
|
+
critic_dim_out = num_actions_split
|
|
325
|
+
if use_quantiles:
|
|
326
|
+
critic_dim_out = critic_dim_out * num_quantiles
|
|
327
|
+
|
|
328
|
+
self.to_values = BroMLP(
|
|
329
|
+
dim_state + num_cont_actions,
|
|
330
|
+
depth = mlp_depth,
|
|
331
|
+
dim_out = critic_dim_out.sum().item(),
|
|
332
|
+
dim_hidden = dim_hidden,
|
|
333
|
+
dropout = dropout
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
# save the number of quantiles and the number of actions, for splitting out the output of the critic correctly
|
|
337
|
+
|
|
338
|
+
self.num_quantiles = num_quantiles
|
|
339
|
+
self.num_actions_split = num_actions_split.tolist()
|
|
340
|
+
|
|
341
|
+
# for tensor typing
|
|
342
|
+
|
|
343
|
+
self._n = num_cont_actions
|
|
344
|
+
self._q = num_quantiles
|
|
345
|
+
|
|
346
|
+
# quantiles
|
|
347
|
+
|
|
348
|
+
if exists(quantiles):
|
|
349
|
+
quantiles = tensor(quantiles)
|
|
350
|
+
elif exists(num_quantiles):
|
|
351
|
+
quantiles = torch.linspace(0., 1., num_quantiles + 2)[1:-1] # excluding 0 and 1 - say 3 quantiles will be 0.25, 0.5, 0.75
|
|
352
|
+
|
|
353
|
+
self.register_buffer('quantiles', quantiles)
|
|
354
|
+
|
|
355
|
+
def forward(
|
|
356
|
+
self,
|
|
357
|
+
state: Float['b ...'],
|
|
358
|
+
cont_actions: Float['b {self._n}'] | None = None
|
|
359
|
+
) -> tuple[Float['b ...'], ...]:
|
|
360
|
+
|
|
361
|
+
pack_input = compact([state, cont_actions])
|
|
362
|
+
|
|
363
|
+
mlp_input, _ = pack(pack_input, 'b *')
|
|
364
|
+
|
|
365
|
+
values = self.to_values(mlp_input)
|
|
366
|
+
|
|
367
|
+
if self.returning_quantiles:
|
|
368
|
+
values = rearrange(values, '... (n q) -> ... n q', q = self.num_quantiles)
|
|
369
|
+
|
|
370
|
+
split_dim = -2 if self.returning_quantiles else -1
|
|
371
|
+
|
|
372
|
+
values = values.split(self.num_actions_split, dim = split_dim)
|
|
373
|
+
|
|
374
|
+
return values
|
|
375
|
+
|
|
376
|
+
class MultipleCritics(Module):
|
|
377
|
+
@beartype
|
|
378
|
+
def __init__(
|
|
379
|
+
self,
|
|
380
|
+
*critics: Critic,
|
|
381
|
+
use_softmin = False
|
|
382
|
+
):
|
|
383
|
+
super().__init__()
|
|
384
|
+
assert len(critics) > 0
|
|
385
|
+
assert all([not critic.returning_quantiles for critic in critics]), 'this wrapper only allows for non-quantile critics'
|
|
386
|
+
|
|
387
|
+
self.num_critics = len(critics)
|
|
388
|
+
self.critics = ModuleList(critics)
|
|
389
|
+
|
|
390
|
+
self.use_softmin = use_softmin
|
|
391
|
+
|
|
392
|
+
def forward(
|
|
393
|
+
self,
|
|
394
|
+
states: Float['b ...'],
|
|
395
|
+
cont_actions: Float['b nc'] | None = None,
|
|
396
|
+
discrete_actions: Int['b nd'] | None = None,
|
|
397
|
+
target_values: Float['b n'] | None = None,
|
|
398
|
+
return_breakdown = False,
|
|
399
|
+
**kwargs
|
|
400
|
+
):
|
|
401
|
+
critics_values = [critic(states, cont_actions) for critic in self.critics]
|
|
402
|
+
|
|
403
|
+
critics_values = [torch.stack(one_value_for_critics) for one_value_for_critics in zip(*critics_values)]
|
|
404
|
+
|
|
405
|
+
if not exists(target_values):
|
|
406
|
+
|
|
407
|
+
min_critic_values = []
|
|
408
|
+
|
|
409
|
+
for critic_values in critics_values:
|
|
410
|
+
if self.use_softmin:
|
|
411
|
+
values = torch.stack(values, dim = -1)
|
|
412
|
+
softmin = (-values).softmax(dim = -1)
|
|
413
|
+
|
|
414
|
+
min_critic_value = (softmin * critic_values).sum(dim = -1)
|
|
415
|
+
else:
|
|
416
|
+
min_critic_value = torch.minimum(*critic_values)
|
|
417
|
+
|
|
418
|
+
min_critic_values.append(min_critic_value)
|
|
419
|
+
|
|
420
|
+
if not return_breakdown:
|
|
421
|
+
return min_critic_values
|
|
422
|
+
|
|
423
|
+
return min_critic_values, values
|
|
424
|
+
|
|
425
|
+
cont_critics_values, *discrete_critics_values = critics_values
|
|
426
|
+
|
|
427
|
+
discrete_critics_values = [get_at('c b [l], b -> c b', discrete_critics_value, discrete_action) for discrete_critics_value, discrete_action in zip(discrete_critics_values, discrete_actions.unbind(dim = -1))]
|
|
428
|
+
|
|
429
|
+
values, _ = pack([cont_critics_values, *discrete_critics_values], 'c b *')
|
|
430
|
+
|
|
431
|
+
target_values = repeat(target_values, '... -> c ...', c = self.num_critics)
|
|
432
|
+
losses = F.mse_loss(values, target_values, reduction = 'none')
|
|
433
|
+
|
|
434
|
+
reduced_losses = reduce(losses, 'c b n -> b', 'sum').mean() # sum losses per action per critic, and average over batch
|
|
435
|
+
|
|
436
|
+
if not return_breakdown:
|
|
437
|
+
return reduced_losses
|
|
438
|
+
|
|
439
|
+
return reduced_losses, losses
|
|
440
|
+
|
|
441
|
+
class MultipleQuantileCritics(Module):
|
|
442
|
+
@beartype
|
|
443
|
+
def __init__(
|
|
444
|
+
self,
|
|
445
|
+
*critics: Critic,
|
|
446
|
+
frac_atom_keep = 0.75 # will truncate 25% of the top values
|
|
447
|
+
):
|
|
448
|
+
super().__init__()
|
|
449
|
+
assert len(critics) > 0
|
|
450
|
+
assert all([critic.returning_quantiles for critic in critics]), 'all critics must be returning quantiles'
|
|
451
|
+
assert len(set([critic.num_quantiles for critic in critics])) == 1, 'all critics must have same number of quantiles'
|
|
452
|
+
|
|
453
|
+
self.num_critics = len(critics)
|
|
454
|
+
|
|
455
|
+
self.critics = ModuleList(critics)
|
|
456
|
+
self.num_atom_keep = int(frac_atom_keep * self.num_critics * self.num_quantiles)
|
|
457
|
+
|
|
458
|
+
@property
|
|
459
|
+
def quantiles(self):
|
|
460
|
+
return self.critics[0].quantiles
|
|
461
|
+
|
|
462
|
+
@property
|
|
463
|
+
def num_quantiles(self):
|
|
464
|
+
return self.critics[0].num_quantiles
|
|
465
|
+
|
|
466
|
+
def forward(
|
|
467
|
+
self,
|
|
468
|
+
states: Float['b ...'],
|
|
469
|
+
cont_actions: Float['b nc'] | None = None,
|
|
470
|
+
discrete_actions: Int['b nd'] | None = None,
|
|
471
|
+
target_values: Float['b n q'] | None = None,
|
|
472
|
+
truncate_quantiles_across_critics = False,
|
|
473
|
+
return_breakdown = False
|
|
474
|
+
):
|
|
475
|
+
critics_quantile_atoms = [critic(states, cont_actions) for critic in self.critics]
|
|
476
|
+
|
|
477
|
+
critics_quantile_atoms = [torch.stack(one_value_for_critics) for one_value_for_critics in zip(*critics_quantile_atoms)]
|
|
478
|
+
|
|
479
|
+
if not exists(target_values):
|
|
480
|
+
|
|
481
|
+
if truncate_quantiles_across_critics:
|
|
482
|
+
truncated_means_per_action = []
|
|
483
|
+
|
|
484
|
+
for critic_quantile_atoms in critics_quantile_atoms:
|
|
485
|
+
quantile_atoms = rearrange(critic_quantile_atoms, 'c b ... q -> b ... (q c)')
|
|
486
|
+
|
|
487
|
+
# mean of the truncated distribution
|
|
488
|
+
|
|
489
|
+
truncated_quantiles = quantile_atoms.topk(self.num_atom_keep, largest = False).values
|
|
490
|
+
truncated_mean = truncated_quantiles.mean(dim = -1)
|
|
491
|
+
|
|
492
|
+
truncated_means_per_action.append(truncated_mean)
|
|
493
|
+
|
|
494
|
+
return_value = truncated_means_per_action
|
|
495
|
+
else:
|
|
496
|
+
|
|
497
|
+
min_critic_value_per_action = []
|
|
498
|
+
|
|
499
|
+
for critic_quantile_atoms in critics_quantile_atoms:
|
|
500
|
+
min_critic_value = torch.minimum(*critic_quantile_atoms)
|
|
501
|
+
min_critic_value_per_action.append(min_critic_value)
|
|
502
|
+
|
|
503
|
+
return_value = min_critic_value_per_action
|
|
504
|
+
|
|
505
|
+
if not return_breakdown:
|
|
506
|
+
return return_value
|
|
507
|
+
|
|
508
|
+
return return_value, critics_quantile_atoms
|
|
509
|
+
|
|
510
|
+
cont_quantile_atoms, *discrete_quantile_atoms = critics_quantile_atoms
|
|
511
|
+
discrete_quantile_atoms = [get_at('c b [l] q, b -> c b q', discrete_quantile_atom, discrete_action) for discrete_quantile_atom, discrete_action in zip(discrete_quantile_atoms, discrete_actions.unbind(dim = -1))]
|
|
512
|
+
|
|
513
|
+
quantile_atoms, _ = pack([cont_quantile_atoms, *discrete_quantile_atoms], 'c b * q')
|
|
514
|
+
|
|
515
|
+
# quantile regression if training
|
|
516
|
+
|
|
517
|
+
quantiles = self.quantiles
|
|
518
|
+
|
|
519
|
+
# quantile regression loss
|
|
520
|
+
|
|
521
|
+
error = target_values - quantile_atoms
|
|
522
|
+
losses = torch.maximum(error * quantiles, error * (quantiles - 1.))
|
|
523
|
+
|
|
524
|
+
reduced_losses = reduce(losses, 'c b n q -> b', 'sum').mean()
|
|
525
|
+
|
|
526
|
+
if not return_breakdown:
|
|
527
|
+
return reduced_losses
|
|
528
|
+
|
|
529
|
+
return reduced_losses, losses
|
|
530
|
+
|
|
531
|
+
# automatic entropy temperature adjustment
|
|
532
|
+
# will account for both continuous and discrete
|
|
533
|
+
|
|
534
|
+
class LearnedEntropyTemperature(Module):
|
|
535
|
+
def __init__(
|
|
536
|
+
self,
|
|
537
|
+
num_discrete_actions = 0,
|
|
538
|
+
num_cont_actions = 0
|
|
539
|
+
):
|
|
540
|
+
super().__init__()
|
|
541
|
+
|
|
542
|
+
self.log_alpha = nn.Parameter(tensor(0.))
|
|
543
|
+
|
|
544
|
+
self.has_discrete = len(num_discrete_actions) > 0
|
|
545
|
+
self.has_continuous = num_cont_actions > 0
|
|
546
|
+
|
|
547
|
+
self.discrete_entropy_targets = [0.98 * math.log(one_num_discrete_actions)for one_num_discrete_actions in num_discrete_actions]
|
|
548
|
+
self.continuous_entropy_target = num_cont_actions
|
|
549
|
+
|
|
550
|
+
@property
|
|
551
|
+
def alpha(self):
|
|
552
|
+
return self.log_alpha.exp()
|
|
553
|
+
|
|
554
|
+
def forward(
|
|
555
|
+
self,
|
|
556
|
+
cont_log_prob: Float['b nc'] | None = None,
|
|
557
|
+
discrete_logits: tuple[Float['b _'], ...] | None = None,
|
|
558
|
+
return_breakdown = False
|
|
559
|
+
):
|
|
560
|
+
assert exists(cont_log_prob) or exists(discrete_log_prob)
|
|
561
|
+
|
|
562
|
+
alpha = self.alpha
|
|
563
|
+
|
|
564
|
+
losses = []
|
|
565
|
+
|
|
566
|
+
if exists(discrete_logits):
|
|
567
|
+
|
|
568
|
+
for one_discrete_logits, discrete_entropy_target in zip(discrete_logits, self.discrete_entropy_targets):
|
|
569
|
+
discrete_log_prob = one_discrete_logits.log_softmax(dim = -1)
|
|
570
|
+
discrete_entropy_temp_loss = -alpha * (discrete_log_prob + discrete_entropy_target).detach()
|
|
571
|
+
|
|
572
|
+
losses.append(discrete_entropy_temp_loss.mean())
|
|
573
|
+
|
|
574
|
+
if exists(cont_log_prob):
|
|
575
|
+
cont_entropy_temp_loss = -alpha * (cont_log_prob + self.continuous_entropy_target).detach()
|
|
576
|
+
|
|
577
|
+
cont_entropy_temp_loss = cont_entropy_temp_loss.mean(dim = 0)
|
|
578
|
+
losses.append(cont_entropy_temp_loss)
|
|
579
|
+
|
|
580
|
+
reduced_losses, _ = pack(losses, '*')
|
|
581
|
+
reduced_losses = reduced_losses.sum()
|
|
582
|
+
|
|
583
|
+
if not return_breakdown:
|
|
584
|
+
return reduced_losses
|
|
585
|
+
|
|
586
|
+
return reduced_losses, losses
|
|
587
|
+
|
|
588
|
+
# main class
|
|
589
|
+
|
|
590
|
+
class SAC(Module):
|
|
591
|
+
@beartype
|
|
592
|
+
def __init__(
|
|
593
|
+
self,
|
|
594
|
+
actor: dict | Actor,
|
|
595
|
+
critics: (
|
|
596
|
+
list[dict] |
|
|
597
|
+
list[Critic] |
|
|
598
|
+
MultipleCritics |
|
|
599
|
+
MultipleQuantileCritics
|
|
600
|
+
),
|
|
601
|
+
quantiled_critics = False,
|
|
602
|
+
reward_discount_rate = 0.99,
|
|
603
|
+
reward_scale = 1.,
|
|
604
|
+
actor_learning_rate = 3e-4,
|
|
605
|
+
actor_regen_reg_rate = 1e-4,
|
|
606
|
+
critic_target_ema_decay = 0.99,
|
|
607
|
+
critics_learning_rate = 3e-4,
|
|
608
|
+
critics_regen_reg_rate = 1e-4,
|
|
609
|
+
temperature_learning_rate = 3e-4,
|
|
610
|
+
ema_kwargs: dict = dict()
|
|
611
|
+
):
|
|
612
|
+
super().__init__()
|
|
613
|
+
|
|
614
|
+
# set actor
|
|
615
|
+
|
|
616
|
+
if isinstance(actor, dict):
|
|
617
|
+
actor = Actor(**actor)
|
|
618
|
+
|
|
619
|
+
self.actor = actor
|
|
620
|
+
|
|
621
|
+
self.actor_optimizer = Adam(
|
|
622
|
+
actor.parameters(),
|
|
623
|
+
lr = actor_learning_rate,
|
|
624
|
+
regen_reg_rate = actor_regen_reg_rate
|
|
625
|
+
)
|
|
626
|
+
# based on the actor hyperparameters, init the leraned temperature container
|
|
627
|
+
|
|
628
|
+
self.learned_entropy_temperature = LearnedEntropyTemperature(
|
|
629
|
+
num_cont_actions = actor.num_cont_actions,
|
|
630
|
+
num_discrete_actions = actor.num_discrete_actions
|
|
631
|
+
)
|
|
632
|
+
|
|
633
|
+
self.temperature_optimizer = Adam(
|
|
634
|
+
self.learned_entropy_temperature.parameters(),
|
|
635
|
+
lr = temperature_learning_rate,
|
|
636
|
+
)
|
|
637
|
+
|
|
638
|
+
# set critics
|
|
639
|
+
# allow for usual double+ critic trick or truncated quantiled critics
|
|
640
|
+
|
|
641
|
+
if is_bearable(critics, list[dict]):
|
|
642
|
+
critics = [Critic(**critic) for critic in critics]
|
|
643
|
+
|
|
644
|
+
multiple_critic_klass = MultipleCritics if not quantiled_critics else MultipleQuantileCritics
|
|
645
|
+
|
|
646
|
+
if is_bearable(critics, list[Critic]):
|
|
647
|
+
critics = multiple_critic_klass(*critics)
|
|
648
|
+
|
|
649
|
+
assert isinstance(critics, multiple_critic_klass), f'expected {multiple_critic_klass.__name__} but received critics wrapped with {type(critics).__name__}'
|
|
650
|
+
|
|
651
|
+
self.critics = critics
|
|
652
|
+
|
|
653
|
+
self.quantiled_critics = quantiled_critics
|
|
654
|
+
|
|
655
|
+
# critic optimizers
|
|
656
|
+
|
|
657
|
+
self.critics_optimizer = Adam(
|
|
658
|
+
critics.parameters(),
|
|
659
|
+
lr = critics_learning_rate,
|
|
660
|
+
regen_reg_rate = critics_regen_reg_rate
|
|
661
|
+
)
|
|
662
|
+
|
|
663
|
+
# target critic network
|
|
664
|
+
|
|
665
|
+
self.critics_target = EMA(
|
|
666
|
+
critics,
|
|
667
|
+
beta = critic_target_ema_decay,
|
|
668
|
+
include_online_model = False,
|
|
669
|
+
**ema_kwargs
|
|
670
|
+
)
|
|
671
|
+
|
|
672
|
+
# reward related
|
|
673
|
+
|
|
674
|
+
self.reward_scale = reward_scale
|
|
675
|
+
self.reward_discount_rate = reward_discount_rate
|
|
676
|
+
|
|
677
|
+
def forward(
|
|
678
|
+
self,
|
|
679
|
+
states: Float['b ...'],
|
|
680
|
+
cont_actions: Float['b nc'],
|
|
681
|
+
discrete_actions: Int['b nd'],
|
|
682
|
+
rewards: Float['b'],
|
|
683
|
+
done: Bool['b'],
|
|
684
|
+
next_states: Float['b ...']
|
|
685
|
+
):
|
|
686
|
+
|
|
687
|
+
rewards = rewards * self.reward_scale
|
|
688
|
+
|
|
689
|
+
# bellman equation
|
|
690
|
+
# todo: setup n-step
|
|
691
|
+
|
|
692
|
+
entropy_temp = self.learned_entropy_temperature.alpha.detach()
|
|
693
|
+
|
|
694
|
+
γ = self.reward_discount_rate
|
|
695
|
+
not_terminal = (~done).float()
|
|
696
|
+
|
|
697
|
+
with torch.no_grad():
|
|
698
|
+
self.critics_target.eval()
|
|
699
|
+
|
|
700
|
+
next_cont_q_value, *next_discrete_q_values = self.critics_target(next_states, cont_actions = cont_actions)
|
|
701
|
+
|
|
702
|
+
# outputs from actor
|
|
703
|
+
|
|
704
|
+
actor_output = self.actor(states, sample = True)
|
|
705
|
+
|
|
706
|
+
cont_log_prob = actor_output.continuous_log_prob
|
|
707
|
+
discrete_logits = actor_output.discrete_action_logits
|
|
708
|
+
|
|
709
|
+
# learned temperature
|
|
710
|
+
|
|
711
|
+
learned_entropy_weight = self.learned_entropy_temperature.alpha
|
|
712
|
+
|
|
713
|
+
next_soft_state_values = []
|
|
714
|
+
|
|
715
|
+
# first handle continuous soft state value
|
|
716
|
+
|
|
717
|
+
if exists(cont_log_prob):
|
|
718
|
+
if self.quantiled_critics:
|
|
719
|
+
cont_log_prob = rearrange(cont_log_prob, '... -> ... 1')
|
|
720
|
+
|
|
721
|
+
cont_soft_state_value = next_cont_q_value - learned_entropy_weight * cont_log_prob
|
|
722
|
+
next_soft_state_values.append(cont_soft_state_value)
|
|
723
|
+
|
|
724
|
+
# then handle discrete contribution
|
|
725
|
+
|
|
726
|
+
if len(next_discrete_q_values) > 0:
|
|
727
|
+
|
|
728
|
+
for next_discrete_q_value, discrete_logit in zip(next_discrete_q_values, discrete_logits):
|
|
729
|
+
discrete_prob = discrete_logit.softmax(dim = -1)
|
|
730
|
+
discrete_log_prob = log(discrete_prob)
|
|
731
|
+
|
|
732
|
+
if self.quantiled_critics:
|
|
733
|
+
discrete_prob = rearrange(discrete_prob, '... -> ... 1')
|
|
734
|
+
discrete_log_prob = rearrange(discrete_log_prob, '... -> ... 1')
|
|
735
|
+
|
|
736
|
+
discrete_soft_state_value = (discrete_prob * (next_discrete_q_value - learned_entropy_weight * discrete_log_prob)).sum(dim = 1)
|
|
737
|
+
next_soft_state_values.append(discrete_soft_state_value)
|
|
738
|
+
|
|
739
|
+
if self.quantiled_critics:
|
|
740
|
+
next_soft_state_values, _ = pack(next_soft_state_values, 'b * q')
|
|
741
|
+
else:
|
|
742
|
+
next_soft_state_values, _ = pack(next_soft_state_values, 'b *')
|
|
743
|
+
|
|
744
|
+
target_q_values = rewards + not_terminal * γ * next_soft_state_values
|
|
745
|
+
|
|
746
|
+
critics_losses = self.critics(
|
|
747
|
+
states,
|
|
748
|
+
cont_actions = cont_actions,
|
|
749
|
+
discrete_actions = discrete_actions,
|
|
750
|
+
target_values = target_q_values
|
|
751
|
+
)
|
|
752
|
+
|
|
753
|
+
# update the critics
|
|
754
|
+
|
|
755
|
+
critics_losses.backward()
|
|
756
|
+
self.critics_optimizer.step()
|
|
757
|
+
self.critics_optimizer.zero_grad()
|
|
758
|
+
|
|
759
|
+
# update the actor
|
|
760
|
+
|
|
761
|
+
actor_output = self.actor(states, sample = True, cont_reparametrize = True)
|
|
762
|
+
|
|
763
|
+
cont_log_prob = actor_output.continuous_log_prob
|
|
764
|
+
discrete_logits = actor_output.discrete_action_logits
|
|
765
|
+
|
|
766
|
+
cont_q_values, *discrete_q_values = self.critics(
|
|
767
|
+
states,
|
|
768
|
+
cont_actions = actor_output.continuous,
|
|
769
|
+
discrete_actions = actor_output.discrete,
|
|
770
|
+
truncate_quantiles_across_critics = True
|
|
771
|
+
)
|
|
772
|
+
|
|
773
|
+
actor_action_losses = []
|
|
774
|
+
|
|
775
|
+
if exists(cont_log_prob):
|
|
776
|
+
cont_action_loss = (entropy_temp * cont_log_prob - cont_q_values).sum(dim = -1).mean()
|
|
777
|
+
|
|
778
|
+
actor_action_losses.append(cont_action_loss)
|
|
779
|
+
|
|
780
|
+
for discrete_logit, one_discrete_q_value in zip(discrete_logits, discrete_q_values):
|
|
781
|
+
discrete_prob = discrete_logit.softmax(dim = -1)
|
|
782
|
+
discrete_log_prob = log(discrete_prob)
|
|
783
|
+
|
|
784
|
+
one_discrete_actor_loss = (discrete_prob * (entropy_temp * discrete_log_prob - one_discrete_q_value)).mean()
|
|
785
|
+
|
|
786
|
+
actor_action_losses.append(one_discrete_actor_loss)
|
|
787
|
+
|
|
788
|
+
sum(actor_action_losses).backward()
|
|
789
|
+
self.actor_optimizer.step()
|
|
790
|
+
self.actor_optimizer.zero_grad()
|
|
791
|
+
|
|
792
|
+
# update the learned entropy temperature
|
|
793
|
+
|
|
794
|
+
temperature_loss = self.learned_entropy_temperature(
|
|
795
|
+
cont_log_prob = cont_log_prob,
|
|
796
|
+
discrete_logits = discrete_logits
|
|
797
|
+
)
|
|
798
|
+
|
|
799
|
+
temperature_loss.backward()
|
|
800
|
+
self.temperature_optimizer.step()
|
|
801
|
+
self.temperature_optimizer.zero_grad()
|
|
802
|
+
|
|
803
|
+
# update ema of all critics
|
|
804
|
+
|
|
805
|
+
self.critics_target.update()
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "SAC-pytorch"
|
|
3
|
+
version = "0.0.2"
|
|
4
|
+
description = "Soft Actor Critic - Pytorch"
|
|
5
|
+
authors = [
|
|
6
|
+
{ name = "Phil Wang", email = "lucidrains@gmail.com" }
|
|
7
|
+
]
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
requires-python = ">= 3.9"
|
|
10
|
+
license = { file = "LICENSE" }
|
|
11
|
+
keywords = [
|
|
12
|
+
'artificial intelligence',
|
|
13
|
+
'deep learning',
|
|
14
|
+
'reinforcement learning',
|
|
15
|
+
'soft actor critic'
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
classifiers=[
|
|
19
|
+
'Development Status :: 4 - Beta',
|
|
20
|
+
'Intended Audience :: Developers',
|
|
21
|
+
'Topic :: Scientific/Engineering :: Artificial Intelligence',
|
|
22
|
+
'License :: OSI Approved :: MIT License',
|
|
23
|
+
'Programming Language :: Python :: 3.9',
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
dependencies = [
|
|
27
|
+
'adam-atan2-pytorch>=0.0.15',
|
|
28
|
+
'beartype',
|
|
29
|
+
'einops>=0.8.0',
|
|
30
|
+
'einx[torch]>=0.1.3',
|
|
31
|
+
'ema-pytorch>=0.6.2',
|
|
32
|
+
'jaxtyping',
|
|
33
|
+
'pytorch-custom-utils>=0.0.18',
|
|
34
|
+
'soft-moe-pytorch>=0.1.6',
|
|
35
|
+
'torch>=2.0'
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
[project.urls]
|
|
39
|
+
Homepage = "https://pypi.org/project/SAC-pytorch/"
|
|
40
|
+
Repository = "https://github.com/lucidrains/SAC-pytorch"
|
|
41
|
+
|
|
42
|
+
[project.optional-dependencies]
|
|
43
|
+
examples = []
|
|
44
|
+
test = [
|
|
45
|
+
"pytest"
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
[tool.pytest.ini_options]
|
|
49
|
+
pythonpath = [
|
|
50
|
+
"."
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
[build-system]
|
|
54
|
+
requires = ["hatchling"]
|
|
55
|
+
build-backend = "hatchling.build"
|
|
56
|
+
|
|
57
|
+
[tool.rye]
|
|
58
|
+
managed = true
|
|
59
|
+
dev-dependencies = []
|
|
60
|
+
|
|
61
|
+
[tool.hatch.metadata]
|
|
62
|
+
allow-direct-references = true
|
|
63
|
+
|
|
64
|
+
[tool.hatch.build.targets.wheel]
|
|
65
|
+
packages = ["SAC_pytorch"]
|