mean-conc-beta 0.0.1__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.
@@ -0,0 +1,220 @@
1
+ uv_publish.sh
2
+
3
+ # Byte-compiled / optimized / DLL files
4
+ __pycache__/
5
+ *.py[codz]
6
+ *$py.class
7
+
8
+ # C extensions
9
+ *.so
10
+
11
+ # Distribution / packaging
12
+ .Python
13
+ build/
14
+ develop-eggs/
15
+ dist/
16
+ downloads/
17
+ eggs/
18
+ .eggs/
19
+ lib/
20
+ lib64/
21
+ parts/
22
+ sdist/
23
+ var/
24
+ wheels/
25
+ share/python-wheels/
26
+ *.egg-info/
27
+ .installed.cfg
28
+ *.egg
29
+ MANIFEST
30
+
31
+ # PyInstaller
32
+ # Usually these files are written by a python script from a template
33
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
34
+ *.manifest
35
+ *.spec
36
+
37
+ # Installer logs
38
+ pip-log.txt
39
+ pip-delete-this-directory.txt
40
+
41
+ # Unit test / coverage reports
42
+ htmlcov/
43
+ .tox/
44
+ .nox/
45
+ .coverage
46
+ .coverage.*
47
+ .cache
48
+ nosetests.xml
49
+ coverage.xml
50
+ *.cover
51
+ *.py.cover
52
+ .hypothesis/
53
+ .pytest_cache/
54
+ cover/
55
+
56
+ # Translations
57
+ *.mo
58
+ *.pot
59
+
60
+ # Django stuff:
61
+ *.log
62
+ local_settings.py
63
+ db.sqlite3
64
+ db.sqlite3-journal
65
+
66
+ # Flask stuff:
67
+ instance/
68
+ .webassets-cache
69
+
70
+ # Scrapy stuff:
71
+ .scrapy
72
+
73
+ # Sphinx documentation
74
+ docs/_build/
75
+
76
+ # PyBuilder
77
+ .pybuilder/
78
+ target/
79
+
80
+ # Jupyter Notebook
81
+ .ipynb_checkpoints
82
+
83
+ # IPython
84
+ profile_default/
85
+ ipython_config.py
86
+
87
+ # pyenv
88
+ # For a library or package, you might want to ignore these files since the code is
89
+ # intended to run in multiple environments; otherwise, check them in:
90
+ # .python-version
91
+
92
+ # pipenv
93
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
94
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
95
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
96
+ # install all needed dependencies.
97
+ # Pipfile.lock
98
+
99
+ # UV
100
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
101
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
102
+ # commonly ignored for libraries.
103
+ # uv.lock
104
+
105
+ # poetry
106
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
107
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
108
+ # commonly ignored for libraries.
109
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
110
+ # poetry.lock
111
+ # poetry.toml
112
+
113
+ # pdm
114
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
115
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
116
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
117
+ # pdm.lock
118
+ # pdm.toml
119
+ .pdm-python
120
+ .pdm-build/
121
+
122
+ # pixi
123
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
124
+ # pixi.lock
125
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
126
+ # in the .venv directory. It is recommended not to include this directory in version control.
127
+ .pixi
128
+
129
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
130
+ __pypackages__/
131
+
132
+ # Celery stuff
133
+ celerybeat-schedule
134
+ celerybeat.pid
135
+
136
+ # Redis
137
+ *.rdb
138
+ *.aof
139
+ *.pid
140
+
141
+ # RabbitMQ
142
+ mnesia/
143
+ rabbitmq/
144
+ rabbitmq-data/
145
+
146
+ # ActiveMQ
147
+ activemq-data/
148
+
149
+ # SageMath parsed files
150
+ *.sage.py
151
+
152
+ # Environments
153
+ .env
154
+ .envrc
155
+ .venv
156
+ env/
157
+ venv/
158
+ ENV/
159
+ env.bak/
160
+ venv.bak/
161
+
162
+ # Spyder project settings
163
+ .spyderproject
164
+ .spyproject
165
+
166
+ # Rope project settings
167
+ .ropeproject
168
+
169
+ # mkdocs documentation
170
+ /site
171
+
172
+ # mypy
173
+ .mypy_cache/
174
+ .dmypy.json
175
+ dmypy.json
176
+
177
+ # Pyre type checker
178
+ .pyre/
179
+
180
+ # pytype static type analyzer
181
+ .pytype/
182
+
183
+ # Cython debug symbols
184
+ cython_debug/
185
+
186
+ # PyCharm
187
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
188
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
189
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
190
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
191
+ # .idea/
192
+
193
+ # Abstra
194
+ # Abstra is an AI-powered process automation framework.
195
+ # Ignore directories containing user credentials, local state, and settings.
196
+ # Learn more at https://abstra.io/docs
197
+ .abstra/
198
+
199
+ # Visual Studio Code
200
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
201
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
202
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
203
+ # you could uncomment the following to ignore the entire vscode folder
204
+ # .vscode/
205
+ # Temporary file for partial code execution
206
+ tempCodeRunnerFile.py
207
+
208
+ # Ruff stuff:
209
+ .ruff_cache/
210
+
211
+ # PyPI configuration file
212
+ .pypirc
213
+
214
+ # Marimo
215
+ marimo/_static/
216
+ marimo/_lsp/
217
+ __marimo__/
218
+
219
+ # Streamlit
220
+ .streamlit/secrets.toml
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 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,112 @@
1
+ Metadata-Version: 2.5
2
+ Name: mean-conc-beta
3
+ Version: 0.0.1
4
+ Summary: Beta distribution with mean / concentration parameterization, for bounded continuous action spaces in RL
5
+ Project-URL: Homepage, https://pypi.org/project/mean-conc-beta/
6
+ Project-URL: Repository, https://github.com/lucidrains/mean-conc-beta
7
+ Author-email: Phil Wang <lucidrains@gmail.com>
8
+ License: MIT License
9
+
10
+ Copyright (c) 2026 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,continuous control,deep learning,probability distribution,reinforcement learning
31
+ Classifier: Development Status :: 4 - Beta
32
+ Classifier: Intended Audience :: Developers
33
+ Classifier: License :: OSI Approved :: MIT License
34
+ Classifier: Programming Language :: Python :: 3.10
35
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
36
+ Requires-Python: >=3.10
37
+ Requires-Dist: torch>=2.0
38
+ Provides-Extra: test
39
+ Requires-Dist: gymnasium; extra == 'test'
40
+ Requires-Dist: mujoco; extra == 'test'
41
+ Requires-Dist: numpy; extra == 'test'
42
+ Requires-Dist: pytest; extra == 'test'
43
+ Description-Content-Type: text/markdown
44
+
45
+ ## mean-conc-beta
46
+
47
+ Beta distribution parameterized by mean and concentration for bounded continuous action spaces in reinforcement learning.
48
+
49
+ ## Install
50
+
51
+ ```bash
52
+ $ pip install mean-conc-beta
53
+ ```
54
+
55
+ ## Usage
56
+
57
+ ```python
58
+ import torch
59
+ import torch.nn.functional as F
60
+ from mean_conc_beta import Beta
61
+
62
+ beta = Beta()
63
+
64
+ # network output: (batch, num_actions, 2) for raw mean and concentration
65
+
66
+ params = torch.randn(16, 4, 2, requires_grad = True)
67
+
68
+ # distribution on (-1, 1)
69
+
70
+ dist = beta(params)
71
+
72
+ # sample actions
73
+
74
+ actions = dist.sample()
75
+ actions_reparam = dist.rsample()
76
+
77
+ # log prob and entropy
78
+
79
+ log_prob = beta.log_prob(dist, actions)
80
+ entropy = beta.entropy(dist)
81
+
82
+ # behavior cloning with mse loss on mean
83
+
84
+ expert_actions = torch.rand(16, 4)
85
+
86
+ pred_mean = beta.mean(params)
87
+
88
+ bc_loss = F.mse_loss(pred_mean, expert_actions)
89
+ bc_loss.backward()
90
+ ```
91
+
92
+ ## Citations
93
+
94
+ ```bibtex
95
+ @article{Ferrari2004BetaRF,
96
+ title = {Beta Regression for Modelling Rates and Proportions},
97
+ author = {Silvia L. P. Ferrari and Francisco Cribari-Neto},
98
+ journal = {Journal of Applied Statistics},
99
+ year = {2004},
100
+ volume = {31},
101
+ pages = {799 - 815}
102
+ }
103
+ ```
104
+
105
+ ```bibtex
106
+ @inproceedings{Chou2017TheBP,
107
+ title = {The Beta Policy for Continuous Reinforcement Learning},
108
+ author = {Po-Wei Chou and Daniel Maturana and Sebastian Scherer},
109
+ booktitle = {International Conference on Machine Learning},
110
+ year = {2017}
111
+ }
112
+ ```
@@ -0,0 +1,68 @@
1
+ ## mean-conc-beta
2
+
3
+ Beta distribution parameterized by mean and concentration for bounded continuous action spaces in reinforcement learning.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ $ pip install mean-conc-beta
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```python
14
+ import torch
15
+ import torch.nn.functional as F
16
+ from mean_conc_beta import Beta
17
+
18
+ beta = Beta()
19
+
20
+ # network output: (batch, num_actions, 2) for raw mean and concentration
21
+
22
+ params = torch.randn(16, 4, 2, requires_grad = True)
23
+
24
+ # distribution on (-1, 1)
25
+
26
+ dist = beta(params)
27
+
28
+ # sample actions
29
+
30
+ actions = dist.sample()
31
+ actions_reparam = dist.rsample()
32
+
33
+ # log prob and entropy
34
+
35
+ log_prob = beta.log_prob(dist, actions)
36
+ entropy = beta.entropy(dist)
37
+
38
+ # behavior cloning with mse loss on mean
39
+
40
+ expert_actions = torch.rand(16, 4)
41
+
42
+ pred_mean = beta.mean(params)
43
+
44
+ bc_loss = F.mse_loss(pred_mean, expert_actions)
45
+ bc_loss.backward()
46
+ ```
47
+
48
+ ## Citations
49
+
50
+ ```bibtex
51
+ @article{Ferrari2004BetaRF,
52
+ title = {Beta Regression for Modelling Rates and Proportions},
53
+ author = {Silvia L. P. Ferrari and Francisco Cribari-Neto},
54
+ journal = {Journal of Applied Statistics},
55
+ year = {2004},
56
+ volume = {31},
57
+ pages = {799 - 815}
58
+ }
59
+ ```
60
+
61
+ ```bibtex
62
+ @inproceedings{Chou2017TheBP,
63
+ title = {The Beta Policy for Continuous Reinforcement Learning},
64
+ author = {Po-Wei Chou and Daniel Maturana and Sebastian Scherer},
65
+ booktitle = {International Conference on Machine Learning},
66
+ year = {2017}
67
+ }
68
+ ```
@@ -0,0 +1 @@
1
+ from mean_conc_beta.mean_conc_beta import Beta, exists
@@ -0,0 +1,157 @@
1
+ from __future__ import annotations
2
+ import math
3
+
4
+ import torch
5
+ from torch import Tensor, Size
6
+ import torch.nn.functional as F
7
+ from torch.nn import Module
8
+ from torch.distributions import (
9
+ Distribution,
10
+ Beta as _Beta,
11
+ TransformedDistribution,
12
+ AffineTransform
13
+ )
14
+
15
+ # helpers
16
+
17
+ def exists(v):
18
+ return v is not None
19
+
20
+ def default(v, d):
21
+ return v if exists(v) else d
22
+
23
+ # beta distribution policy - unimodal mean-concentration reparameterization on (-1, 1),
24
+ # an affine shift of a unit-interval beta (y = 2x - 1)
25
+
26
+ class Beta(Module):
27
+ def __init__(
28
+ self,
29
+ pos_fn = 'exp',
30
+ init_conc = 10.,
31
+ min_conc = 0.,
32
+ eps = 1e-5,
33
+ detach_unimodal = True,
34
+ clamp_exp = (-10., 10.)
35
+ ):
36
+ super().__init__()
37
+ assert pos_fn in ('exp', 'softplus'), f'pos_fn must be either exp or softplus, got {pos_fn}'
38
+ assert min_conc >= 0., f'min_conc must be non-negative, got {min_conc}'
39
+ assert init_conc > min_conc, f'init_conc ({init_conc}) must be greater than min_conc ({min_conc})'
40
+
41
+ self.pos_fn = pos_fn
42
+ self.init_conc = init_conc
43
+ self.min_conc = min_conc
44
+ self.eps = eps
45
+ self.detach_unimodal = detach_unimodal
46
+
47
+ if isinstance(clamp_exp, (int, float)):
48
+ clamp_exp = (-float(clamp_exp), float(clamp_exp))
49
+
50
+ self.clamp_exp = clamp_exp
51
+
52
+ # raw offset so concentration at raw_conc = 0 is exactly init_conc
53
+
54
+ self.raw_init_conc = math.log(init_conc - min_conc) if pos_fn == 'exp' else math.log(math.expm1(init_conc - min_conc))
55
+
56
+ @property
57
+ def has_rsample(self) -> bool:
58
+ return True
59
+
60
+ def to_dist(self, params_or_dist: Tensor | Distribution) -> Distribution:
61
+ return params_or_dist if isinstance(params_or_dist, Distribution) else self(params_or_dist)
62
+
63
+ def concentration(
64
+ self,
65
+ raw_conc: Tensor
66
+ ) -> Tensor:
67
+ if self.pos_fn == 'exp':
68
+ if exists(self.clamp_exp):
69
+ min_val, max_val = self.clamp_exp
70
+ raw_conc = raw_conc.clamp(min = min_val, max = max_val)
71
+
72
+ return (raw_conc + self.raw_init_conc).exp() + self.min_conc
73
+
74
+ return F.softplus(raw_conc + self.raw_init_conc) + self.min_conc
75
+
76
+ def mean(
77
+ self,
78
+ params: Tensor
79
+ ) -> Tensor:
80
+ raw_mean, _ = params.unbind(dim = -1)
81
+ return raw_mean.tanh().clamp(min = -1. + self.eps, max = 1. - self.eps)
82
+
83
+ def mode(
84
+ self,
85
+ params_or_dist: Tensor | Distribution
86
+ ) -> Tensor:
87
+ dist = self.to_dist(params_or_dist)
88
+ base_dist = getattr(dist, 'base_dist', dist)
89
+ return base_dist.mode * 2. - 1.
90
+
91
+ def entropy(
92
+ self,
93
+ params_or_dist: Tensor | Distribution,
94
+ sum_action_dim = True
95
+ ) -> Tensor:
96
+ # shifted beta entropy = base entropy + log(2), the affine jacobian
97
+
98
+ dist = self.to_dist(params_or_dist)
99
+ base_dist = getattr(dist, 'base_dist', dist)
100
+ entropy = base_dist.entropy() + math.log(2.)
101
+ return entropy.sum(dim = -1) if sum_action_dim else entropy
102
+
103
+ def log_prob(
104
+ self,
105
+ params_or_dist: Tensor | Distribution,
106
+ action: Tensor,
107
+ sum_action_dim = True,
108
+ eps = None
109
+ ) -> Tensor:
110
+ eps = default(eps, self.eps)
111
+ action = action.clamp(min = -1. + eps, max = 1. - eps)
112
+ dist = self.to_dist(params_or_dist)
113
+ log_prob = dist.log_prob(action)
114
+ return log_prob.sum(dim = -1) if sum_action_dim else log_prob
115
+
116
+ def sample(
117
+ self,
118
+ params: Tensor,
119
+ sample_shape = ()
120
+ ) -> Tensor:
121
+ sample_shape = Size(sample_shape)
122
+ return self(params).sample(sample_shape)
123
+
124
+ def rsample(
125
+ self,
126
+ params: Tensor,
127
+ sample_shape = ()
128
+ ) -> Tensor:
129
+ sample_shape = Size(sample_shape)
130
+ return self(params).rsample(sample_shape)
131
+
132
+ def forward(
133
+ self,
134
+ params: Tensor
135
+ ) -> TransformedDistribution:
136
+ raw_mean, raw_conc = params.unbind(dim = -1)
137
+
138
+ # map (-1, 1) mean onto unit interval
139
+
140
+ mean = self.mean(params)
141
+ unit_mean = (mean + 1.) / 2.
142
+
143
+ conc = self.concentration(raw_conc)
144
+
145
+ # keep the beta unimodal without changing its mean
146
+
147
+ min_unit_mean = torch.minimum(unit_mean, 1. - unit_mean).clamp(min = self.eps / 2.)
148
+
149
+ if self.detach_unimodal:
150
+ min_unit_mean = min_unit_mean.detach()
151
+
152
+ conc = conc + 1. / min_unit_mean
153
+
154
+ alpha = unit_mean * conc
155
+ beta = (1. - unit_mean) * conc
156
+
157
+ return TransformedDistribution(_Beta(alpha, beta), AffineTransform(loc = -1., scale = 2.))
@@ -0,0 +1,71 @@
1
+ [project]
2
+ name = "mean-conc-beta"
3
+ version = "0.0.1"
4
+ description = "Beta distribution with mean / concentration parameterization, for bounded continuous action spaces in RL"
5
+ authors = [
6
+ { name = "Phil Wang", email = "lucidrains@gmail.com" }
7
+ ]
8
+ readme = "README.md"
9
+ requires-python = ">= 3.10"
10
+ license = { file = "LICENSE" }
11
+ keywords = [
12
+ 'artificial intelligence',
13
+ 'deep learning',
14
+ 'reinforcement learning',
15
+ 'continuous control',
16
+ 'probability distribution'
17
+ ]
18
+
19
+ classifiers = [
20
+ 'Development Status :: 4 - Beta',
21
+ 'Intended Audience :: Developers',
22
+ 'Topic :: Scientific/Engineering :: Artificial Intelligence',
23
+ 'License :: OSI Approved :: MIT License',
24
+ 'Programming Language :: Python :: 3.10',
25
+ ]
26
+
27
+ dependencies = [
28
+ "torch>=2.0"
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://pypi.org/project/mean-conc-beta/"
33
+ Repository = "https://github.com/lucidrains/mean-conc-beta"
34
+
35
+ [project.optional-dependencies]
36
+ test = [
37
+ "gymnasium",
38
+ "mujoco",
39
+ "numpy",
40
+ "pytest"
41
+ ]
42
+
43
+ [tool.pytest.ini_options]
44
+ testpaths = [
45
+ "tests"
46
+ ]
47
+ pythonpath = [
48
+ "."
49
+ ]
50
+
51
+ [build-system]
52
+ requires = ["hatchling"]
53
+ build-backend = "hatchling.build"
54
+
55
+ [tool.rye]
56
+ managed = true
57
+ dev-dependencies = []
58
+
59
+ [tool.hatch.metadata]
60
+ allow-direct-references = true
61
+
62
+ [tool.hatch.build.targets.wheel]
63
+ packages = ["mean_conc_beta"]
64
+
65
+ [tool.hatch.build.targets.sdist]
66
+ include = [
67
+ "mean_conc_beta",
68
+ "README.md",
69
+ "LICENSE",
70
+ "pyproject.toml",
71
+ ]