vuer-lab 0.1.0__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.
- vuer_lab-0.1.0/LICENSE +21 -0
- vuer_lab-0.1.0/PKG-INFO +153 -0
- vuer_lab-0.1.0/README.md +135 -0
- vuer_lab-0.1.0/pyproject.toml +31 -0
- vuer_lab-0.1.0/setup.cfg +4 -0
- vuer_lab-0.1.0/src/vuer_lab/__init__.py +5 -0
- vuer_lab-0.1.0/src/vuer_lab/algorithms/__init__.py +5 -0
- vuer_lab-0.1.0/src/vuer_lab/algorithms/ppo.py +130 -0
- vuer_lab-0.1.0/src/vuer_lab/bundles.py +58 -0
- vuer_lab-0.1.0/src/vuer_lab/cli.py +156 -0
- vuer_lab-0.1.0/src/vuer_lab/config.py +293 -0
- vuer_lab-0.1.0/src/vuer_lab/dash.py +102 -0
- vuer_lab-0.1.0/src/vuer_lab/envs.py +172 -0
- vuer_lab-0.1.0/src/vuer_lab/policy.py +211 -0
- vuer_lab-0.1.0/src/vuer_lab/rollout.py +19 -0
- vuer_lab-0.1.0/src/vuer_lab/scene.py +50 -0
- vuer_lab-0.1.0/src/vuer_lab/training.py +314 -0
- vuer_lab-0.1.0/src/vuer_lab.egg-info/PKG-INFO +153 -0
- vuer_lab-0.1.0/src/vuer_lab.egg-info/SOURCES.txt +22 -0
- vuer_lab-0.1.0/src/vuer_lab.egg-info/dependency_links.txt +1 -0
- vuer_lab-0.1.0/src/vuer_lab.egg-info/entry_points.txt +2 -0
- vuer_lab-0.1.0/src/vuer_lab.egg-info/requires.txt +7 -0
- vuer_lab-0.1.0/src/vuer_lab.egg-info/top_level.txt +1 -0
- vuer_lab-0.1.0/tests/test_runtime.py +307 -0
vuer_lab-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 the vuer-env contributors
|
|
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.
|
vuer_lab-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: vuer-lab
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Policy training and experiment sweeps for vuer-env
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Documentation, https://fortyfive-labs.github.io/vuer-env/main/
|
|
7
|
+
Project-URL: Repository, https://github.com/fortyfive-labs/vuer-env/tree/main/packages/vuer-lab
|
|
8
|
+
Requires-Python: >=3.11
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Dist: vuer-env<0.2,>=0.1.4
|
|
12
|
+
Requires-Dist: params-proto<4,>=3.3
|
|
13
|
+
Requires-Dist: numpy<3,>=1.26
|
|
14
|
+
Requires-Dist: torch<3,>=2.4
|
|
15
|
+
Provides-Extra: dash
|
|
16
|
+
Requires-Dist: dreamlake<1,>=0.46.2; extra == "dash"
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# vuer-lab
|
|
20
|
+
|
|
21
|
+
Train and evaluate policies against a local `vuer-env` provider or a remote
|
|
22
|
+
environment service. Training parameters and sweeps use `params-proto`.
|
|
23
|
+
|
|
24
|
+
Install Vuer Lab from PyPI. Its dependencies include Vuer Env.
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
python -m pip install vuer-lab
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
To install both packages from source, run `uv pip install . ./packages/vuer-lab` from the repository root.
|
|
31
|
+
|
|
32
|
+
Supply a registered local environment ID or a WebSocket URL in `run.json`.
|
|
33
|
+
Local training can run several independent environments in one process. A
|
|
34
|
+
remote URL identifies one simulation environment. Set `VUER_ENV_TOKEN` on the
|
|
35
|
+
machine running `vuer-lab` to authenticate that connection.
|
|
36
|
+
|
|
37
|
+
```json
|
|
38
|
+
{
|
|
39
|
+
"target": "wss://simulation.example.com/env",
|
|
40
|
+
"seed": 7,
|
|
41
|
+
"num_envs": 1,
|
|
42
|
+
"learning_rate": 0.0003,
|
|
43
|
+
"experiment": "baseline"
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
vuer-lab envs
|
|
49
|
+
vuer-lab train run.json
|
|
50
|
+
vuer-lab play "runs/baseline/env/seed-7/<id>/policy.pt" --steps 1000
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
By default, local runs live under `runs/<experiment>/<environment>/seed-<seed>/<id>`.
|
|
54
|
+
Each launch creates a fresh ID. Set `run_suffix` to `""` for a baseline whose
|
|
55
|
+
path ends at `seed-<seed>`.
|
|
56
|
+
The CLI mirrors the config path under `experiments/` unless the config sets
|
|
57
|
+
`experiment`. For example, `experiments/locomotion/flat.json` maps to
|
|
58
|
+
`locomotion/flat`. Configs elsewhere use their filename stem. Set `output`
|
|
59
|
+
to select an explicit directory for a single run.
|
|
60
|
+
|
|
61
|
+
To sweep, write axes such as `{"seed": [100, 200], "learning_rate": [0.0003, 0.001]}`
|
|
62
|
+
to `axes.json`. The swept settings form folders above the seed, such as
|
|
63
|
+
`baseline/cartpole-balance-v0/learning-rate-0.0003/seed-100/<id>`.
|
|
64
|
+
|
|
65
|
+
```sh
|
|
66
|
+
vuer-lab sweep run.json axes.json > plan.jsonl
|
|
67
|
+
vuer-lab launch plan.jsonl
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
The saved plan contains the resolved local and Dash locations for every trial.
|
|
71
|
+
One launcher can consume plans from different experiments. An experiment
|
|
72
|
+
entrypoint can build its own plan with `sweep(config, axes, source=__file__)`
|
|
73
|
+
or start a single run with `configured(config, source=__file__)`.
|
|
74
|
+
|
|
75
|
+
The runner includes a native PPO algorithm and accepts an alternate on-policy optimizer. Environments can expose Box or Discrete actions, or
|
|
76
|
+
dictionaries of continuous Box actions. Observations are flattened before being
|
|
77
|
+
passed to the policy. Runs save the resolved parameters and trained policy locally.
|
|
78
|
+
|
|
79
|
+
## Building tasks
|
|
80
|
+
|
|
81
|
+
`vuer_lab.envs.ManagerBasedRLEnv` assembles named observation, action, reward,
|
|
82
|
+
termination, reset, and command terms around a scene factory. The factory
|
|
83
|
+
receives a `vuer_lab.scene.SceneCfg` with the model path, physics step,
|
|
84
|
+
decimation, episode horizon, and backend-specific settings. Bundle publishers
|
|
85
|
+
can declare these settings in a static physics entry. The consuming provider
|
|
86
|
+
reads that entry and passes it to the factory when constructing a task.
|
|
87
|
+
|
|
88
|
+
The CLI can register a task from a materialized bundle. Install the provider
|
|
89
|
+
wheel in the same Python environment as Vuer Lab, then pass the local bundle
|
|
90
|
+
path when listing environments, training, or playing a policy.
|
|
91
|
+
|
|
92
|
+
```sh
|
|
93
|
+
dl bundle pull 'fortyfive/cartpole-balance@2#balance' -o ./cartpole
|
|
94
|
+
uv pip install ./cartpole/wheels/*.whl
|
|
95
|
+
vuer-lab --bundle ./cartpole envs
|
|
96
|
+
vuer-lab --bundle ./cartpole train run.json
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
In this mode, `run.json` can omit `target` and the runner records the pinned
|
|
100
|
+
bundle reference automatically.
|
|
101
|
+
|
|
102
|
+
## DreamLake Dash
|
|
103
|
+
|
|
104
|
+
Install logging support from the repository root.
|
|
105
|
+
|
|
106
|
+
```sh
|
|
107
|
+
uv pip install . './packages/vuer-lab[dash]'
|
|
108
|
+
dl login
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Set `dash_prefix` to `namespace/project` to use the same experiment,
|
|
112
|
+
environment, and seed hierarchy in Dash. For example, a config named
|
|
113
|
+
`baseline.json` can write to
|
|
114
|
+
`fortyfive/vuer-lab/baseline/cartpole-balance-v0/seed-100/<id>`. You can supply a
|
|
115
|
+
qualified run path such as `fortyfive/vuer-lab/bench/native/seed-100`, or supply
|
|
116
|
+
its parent `fortyfive/vuer-lab/bench/native` and let Vuer Lab add the seed and ID.
|
|
117
|
+
Use `{id}` or `{uuid}` at the end of `dash_prefix` to specify the ID placeholder
|
|
118
|
+
explicitly. Reusing a saved plan generates fresh IDs for the runs with generated leaves.
|
|
119
|
+
Append a hexadecimal hash after the seed, such as `seed-100/a1b2c3d`, to keep
|
|
120
|
+
a separate version of that run. Local output uses the same hash when `output`
|
|
121
|
+
is omitted.
|
|
122
|
+
Set `dash_root` to record locally.
|
|
123
|
+
|
|
124
|
+
Dash records resolved training parameters, environment-step curves for PPO
|
|
125
|
+
updates and rollout returns, plus the policy checkpoint and a per-run dashboard.
|
|
126
|
+
The Compute view shows throughput, seconds per training iteration, and elapsed
|
|
127
|
+
time. Set `eval_steps` to record a separate fixed-budget evaluation
|
|
128
|
+
of the saved policy. The simulator uses `VUER_ENV_TOKEN` at connection time.
|
|
129
|
+
For a bundle-backed run, include the pinned `bundle_ref` and the resolved
|
|
130
|
+
`scene_config` in the training JSON to preserve its simulation provenance.
|
|
131
|
+
|
|
132
|
+
## Serving a task
|
|
133
|
+
|
|
134
|
+
Install the task provider and both packages on the simulation machine. Set
|
|
135
|
+
`VUER_ENV_TOKEN` there and start the service with the downloaded task bundle.
|
|
136
|
+
|
|
137
|
+
```sh
|
|
138
|
+
vuer-lab --bundle ./cartpole serve
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
The trainer uses `ws://127.0.0.1:8767` on the same machine or a `wss://` URL
|
|
142
|
+
when the service is configured with a certificate and key. The service owns
|
|
143
|
+
physics and the task, and returns observations and rewards to the trainer.
|
|
144
|
+
Set `VUER_ENV_TOKEN` in the trainer's environment before connecting.
|
|
145
|
+
|
|
146
|
+
### CI and evaluation
|
|
147
|
+
|
|
148
|
+
Run the runtime unit tests and a short training smoke run on pull requests.
|
|
149
|
+
Use a DreamLake CI/CT runner for the full pinned config and seed matrix.
|
|
150
|
+
Evaluate saved checkpoints in a separate
|
|
151
|
+
step using the fixed held-out reset seeds. Publish the checkpoint, per-seed
|
|
152
|
+
evaluation results, and timing alongside the Dash runs. Measure throughput on
|
|
153
|
+
the same runner and workload when using it to check for regressions. [DreamLake CI/CT](https://docs.dreamlake.ai/lakeshore/cict)
|
vuer_lab-0.1.0/README.md
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
# vuer-lab
|
|
2
|
+
|
|
3
|
+
Train and evaluate policies against a local `vuer-env` provider or a remote
|
|
4
|
+
environment service. Training parameters and sweeps use `params-proto`.
|
|
5
|
+
|
|
6
|
+
Install Vuer Lab from PyPI. Its dependencies include Vuer Env.
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
python -m pip install vuer-lab
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
To install both packages from source, run `uv pip install . ./packages/vuer-lab` from the repository root.
|
|
13
|
+
|
|
14
|
+
Supply a registered local environment ID or a WebSocket URL in `run.json`.
|
|
15
|
+
Local training can run several independent environments in one process. A
|
|
16
|
+
remote URL identifies one simulation environment. Set `VUER_ENV_TOKEN` on the
|
|
17
|
+
machine running `vuer-lab` to authenticate that connection.
|
|
18
|
+
|
|
19
|
+
```json
|
|
20
|
+
{
|
|
21
|
+
"target": "wss://simulation.example.com/env",
|
|
22
|
+
"seed": 7,
|
|
23
|
+
"num_envs": 1,
|
|
24
|
+
"learning_rate": 0.0003,
|
|
25
|
+
"experiment": "baseline"
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
vuer-lab envs
|
|
31
|
+
vuer-lab train run.json
|
|
32
|
+
vuer-lab play "runs/baseline/env/seed-7/<id>/policy.pt" --steps 1000
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
By default, local runs live under `runs/<experiment>/<environment>/seed-<seed>/<id>`.
|
|
36
|
+
Each launch creates a fresh ID. Set `run_suffix` to `""` for a baseline whose
|
|
37
|
+
path ends at `seed-<seed>`.
|
|
38
|
+
The CLI mirrors the config path under `experiments/` unless the config sets
|
|
39
|
+
`experiment`. For example, `experiments/locomotion/flat.json` maps to
|
|
40
|
+
`locomotion/flat`. Configs elsewhere use their filename stem. Set `output`
|
|
41
|
+
to select an explicit directory for a single run.
|
|
42
|
+
|
|
43
|
+
To sweep, write axes such as `{"seed": [100, 200], "learning_rate": [0.0003, 0.001]}`
|
|
44
|
+
to `axes.json`. The swept settings form folders above the seed, such as
|
|
45
|
+
`baseline/cartpole-balance-v0/learning-rate-0.0003/seed-100/<id>`.
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
vuer-lab sweep run.json axes.json > plan.jsonl
|
|
49
|
+
vuer-lab launch plan.jsonl
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The saved plan contains the resolved local and Dash locations for every trial.
|
|
53
|
+
One launcher can consume plans from different experiments. An experiment
|
|
54
|
+
entrypoint can build its own plan with `sweep(config, axes, source=__file__)`
|
|
55
|
+
or start a single run with `configured(config, source=__file__)`.
|
|
56
|
+
|
|
57
|
+
The runner includes a native PPO algorithm and accepts an alternate on-policy optimizer. Environments can expose Box or Discrete actions, or
|
|
58
|
+
dictionaries of continuous Box actions. Observations are flattened before being
|
|
59
|
+
passed to the policy. Runs save the resolved parameters and trained policy locally.
|
|
60
|
+
|
|
61
|
+
## Building tasks
|
|
62
|
+
|
|
63
|
+
`vuer_lab.envs.ManagerBasedRLEnv` assembles named observation, action, reward,
|
|
64
|
+
termination, reset, and command terms around a scene factory. The factory
|
|
65
|
+
receives a `vuer_lab.scene.SceneCfg` with the model path, physics step,
|
|
66
|
+
decimation, episode horizon, and backend-specific settings. Bundle publishers
|
|
67
|
+
can declare these settings in a static physics entry. The consuming provider
|
|
68
|
+
reads that entry and passes it to the factory when constructing a task.
|
|
69
|
+
|
|
70
|
+
The CLI can register a task from a materialized bundle. Install the provider
|
|
71
|
+
wheel in the same Python environment as Vuer Lab, then pass the local bundle
|
|
72
|
+
path when listing environments, training, or playing a policy.
|
|
73
|
+
|
|
74
|
+
```sh
|
|
75
|
+
dl bundle pull 'fortyfive/cartpole-balance@2#balance' -o ./cartpole
|
|
76
|
+
uv pip install ./cartpole/wheels/*.whl
|
|
77
|
+
vuer-lab --bundle ./cartpole envs
|
|
78
|
+
vuer-lab --bundle ./cartpole train run.json
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
In this mode, `run.json` can omit `target` and the runner records the pinned
|
|
82
|
+
bundle reference automatically.
|
|
83
|
+
|
|
84
|
+
## DreamLake Dash
|
|
85
|
+
|
|
86
|
+
Install logging support from the repository root.
|
|
87
|
+
|
|
88
|
+
```sh
|
|
89
|
+
uv pip install . './packages/vuer-lab[dash]'
|
|
90
|
+
dl login
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Set `dash_prefix` to `namespace/project` to use the same experiment,
|
|
94
|
+
environment, and seed hierarchy in Dash. For example, a config named
|
|
95
|
+
`baseline.json` can write to
|
|
96
|
+
`fortyfive/vuer-lab/baseline/cartpole-balance-v0/seed-100/<id>`. You can supply a
|
|
97
|
+
qualified run path such as `fortyfive/vuer-lab/bench/native/seed-100`, or supply
|
|
98
|
+
its parent `fortyfive/vuer-lab/bench/native` and let Vuer Lab add the seed and ID.
|
|
99
|
+
Use `{id}` or `{uuid}` at the end of `dash_prefix` to specify the ID placeholder
|
|
100
|
+
explicitly. Reusing a saved plan generates fresh IDs for the runs with generated leaves.
|
|
101
|
+
Append a hexadecimal hash after the seed, such as `seed-100/a1b2c3d`, to keep
|
|
102
|
+
a separate version of that run. Local output uses the same hash when `output`
|
|
103
|
+
is omitted.
|
|
104
|
+
Set `dash_root` to record locally.
|
|
105
|
+
|
|
106
|
+
Dash records resolved training parameters, environment-step curves for PPO
|
|
107
|
+
updates and rollout returns, plus the policy checkpoint and a per-run dashboard.
|
|
108
|
+
The Compute view shows throughput, seconds per training iteration, and elapsed
|
|
109
|
+
time. Set `eval_steps` to record a separate fixed-budget evaluation
|
|
110
|
+
of the saved policy. The simulator uses `VUER_ENV_TOKEN` at connection time.
|
|
111
|
+
For a bundle-backed run, include the pinned `bundle_ref` and the resolved
|
|
112
|
+
`scene_config` in the training JSON to preserve its simulation provenance.
|
|
113
|
+
|
|
114
|
+
## Serving a task
|
|
115
|
+
|
|
116
|
+
Install the task provider and both packages on the simulation machine. Set
|
|
117
|
+
`VUER_ENV_TOKEN` there and start the service with the downloaded task bundle.
|
|
118
|
+
|
|
119
|
+
```sh
|
|
120
|
+
vuer-lab --bundle ./cartpole serve
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
The trainer uses `ws://127.0.0.1:8767` on the same machine or a `wss://` URL
|
|
124
|
+
when the service is configured with a certificate and key. The service owns
|
|
125
|
+
physics and the task, and returns observations and rewards to the trainer.
|
|
126
|
+
Set `VUER_ENV_TOKEN` in the trainer's environment before connecting.
|
|
127
|
+
|
|
128
|
+
### CI and evaluation
|
|
129
|
+
|
|
130
|
+
Run the runtime unit tests and a short training smoke run on pull requests.
|
|
131
|
+
Use a DreamLake CI/CT runner for the full pinned config and seed matrix.
|
|
132
|
+
Evaluate saved checkpoints in a separate
|
|
133
|
+
step using the fixed held-out reset seeds. Publish the checkpoint, per-seed
|
|
134
|
+
evaluation results, and timing alongside the Dash runs. Measure throughput on
|
|
135
|
+
the same runner and workload when using it to check for regressions. [DreamLake CI/CT](https://docs.dreamlake.ai/lakeshore/cict)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77.0.3"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "vuer-lab"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Policy training and experiment sweeps for vuer-env"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
dependencies = [
|
|
14
|
+
"vuer-env>=0.1.4,<0.2",
|
|
15
|
+
"params-proto>=3.3,<4",
|
|
16
|
+
"numpy>=1.26,<3",
|
|
17
|
+
"torch>=2.4,<3",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Documentation = "https://fortyfive-labs.github.io/vuer-env/main/"
|
|
22
|
+
Repository = "https://github.com/fortyfive-labs/vuer-env/tree/main/packages/vuer-lab"
|
|
23
|
+
|
|
24
|
+
[project.optional-dependencies]
|
|
25
|
+
dash = ["dreamlake>=0.46.2,<1"]
|
|
26
|
+
|
|
27
|
+
[project.scripts]
|
|
28
|
+
vuer-lab = "vuer_lab.cli:main"
|
|
29
|
+
|
|
30
|
+
[tool.setuptools.packages.find]
|
|
31
|
+
where = ["src"]
|
vuer_lab-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Proximal Policy Optimization over an on-policy batch."""
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
from torch.distributions import kl_divergence
|
|
5
|
+
from torch.nn.utils import clip_grad_norm_
|
|
6
|
+
|
|
7
|
+
from ..rollout import Rollout
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def generalized_advantage(rollout: Rollout, gamma: float, gae_lambda: float):
|
|
11
|
+
"""Bootstrap a time limit from its final value and stop traces at every reset."""
|
|
12
|
+
bootstrap = ~rollout.terminated
|
|
13
|
+
continuation = ~(rollout.terminated | rollout.truncated)
|
|
14
|
+
delta = rollout.reward + gamma * rollout.next_value * bootstrap - rollout.value
|
|
15
|
+
advantages = torch.empty_like(delta)
|
|
16
|
+
advantage = torch.zeros_like(delta[0])
|
|
17
|
+
for index in range(len(delta) - 1, -1, -1):
|
|
18
|
+
advantage = delta[index] + gamma * gae_lambda * continuation[index] * advantage
|
|
19
|
+
advantages[index] = advantage
|
|
20
|
+
return advantages, advantages + rollout.value
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class PPO:
|
|
24
|
+
def __init__(self, policy, config):
|
|
25
|
+
self.policy = policy
|
|
26
|
+
self.cfg = config
|
|
27
|
+
self.optimizer = torch.optim.Adam(policy.parameters(), lr=config.learning_rate)
|
|
28
|
+
|
|
29
|
+
def update(self, rollout: Rollout) -> dict[str, float]:
|
|
30
|
+
cfg = self.cfg
|
|
31
|
+
advantages, returns = generalized_advantage(rollout, cfg.gamma, cfg.gae_lambda)
|
|
32
|
+
advantages = advantages.flatten()
|
|
33
|
+
advantages = (advantages - advantages.mean()) / (
|
|
34
|
+
advantages.std(unbiased=False) + 1e-8
|
|
35
|
+
)
|
|
36
|
+
returns = returns.flatten()
|
|
37
|
+
observations = rollout.actor_obs.flatten(0, 1)
|
|
38
|
+
critic_observations = rollout.critic_obs.flatten(0, 1)
|
|
39
|
+
actions = rollout.actions.flatten(0, 1)
|
|
40
|
+
old_parameters = rollout.old_parameters.flatten(0, 1)
|
|
41
|
+
old_log_prob = rollout.log_prob.flatten()
|
|
42
|
+
old_values = rollout.value.flatten()
|
|
43
|
+
batch_size = cfg.batch_size or len(returns) // cfg.num_mini_batches
|
|
44
|
+
if cfg.epochs < 1 or batch_size <= 0 or len(returns) % batch_size:
|
|
45
|
+
raise ValueError(
|
|
46
|
+
"PPO needs at least one epoch with evenly sized, nonempty minibatches"
|
|
47
|
+
)
|
|
48
|
+
diagnostics = []
|
|
49
|
+
for _ in range(cfg.epochs):
|
|
50
|
+
batch_order = torch.randperm(len(returns), device=returns.device)
|
|
51
|
+
for indices in batch_order.split(batch_size):
|
|
52
|
+
distribution = self.policy.distribution(observations[indices])
|
|
53
|
+
value = self.policy.value(critic_observations[indices])
|
|
54
|
+
new_log_prob = distribution.log_prob(actions[indices])
|
|
55
|
+
ratio = (new_log_prob - old_log_prob[indices]).exp()
|
|
56
|
+
advantage = advantages[indices]
|
|
57
|
+
clipped_ratio = ratio.clamp(1 - cfg.clip_ratio, 1 + cfg.clip_ratio)
|
|
58
|
+
policy_loss = -torch.minimum(
|
|
59
|
+
ratio * advantage, clipped_ratio * advantage
|
|
60
|
+
).mean()
|
|
61
|
+
clipped_value = old_values[indices] + (
|
|
62
|
+
value - old_values[indices]
|
|
63
|
+
).clamp(-cfg.clip_ratio, cfg.clip_ratio)
|
|
64
|
+
value_error = (value - returns[indices]).square()
|
|
65
|
+
if cfg.clip_value_loss:
|
|
66
|
+
value_error = torch.maximum(
|
|
67
|
+
value_error, (clipped_value - returns[indices]).square()
|
|
68
|
+
)
|
|
69
|
+
value_loss = value_error.mean()
|
|
70
|
+
entropy = distribution.entropy().mean()
|
|
71
|
+
with torch.no_grad():
|
|
72
|
+
previous = self.policy.distribution_from_parameters(
|
|
73
|
+
old_parameters[indices]
|
|
74
|
+
)
|
|
75
|
+
kl = kl_divergence(previous, distribution).mean()
|
|
76
|
+
clipped = ((ratio - 1).abs() > cfg.clip_ratio).float().mean()
|
|
77
|
+
self._adjust_learning_rate(float(kl))
|
|
78
|
+
|
|
79
|
+
loss = (
|
|
80
|
+
policy_loss
|
|
81
|
+
+ cfg.value_loss_coef * value_loss
|
|
82
|
+
- cfg.entropy_coef * entropy
|
|
83
|
+
)
|
|
84
|
+
self.optimizer.zero_grad(set_to_none=True)
|
|
85
|
+
loss.backward()
|
|
86
|
+
grad_norm = clip_grad_norm_(
|
|
87
|
+
self.policy.parameters(), cfg.max_grad_norm, error_if_nonfinite=True
|
|
88
|
+
)
|
|
89
|
+
self.optimizer.step()
|
|
90
|
+
self.policy.constrain_std()
|
|
91
|
+
diagnostics.append(
|
|
92
|
+
torch.stack(
|
|
93
|
+
(
|
|
94
|
+
policy_loss.detach(),
|
|
95
|
+
value_loss.detach(),
|
|
96
|
+
entropy.detach(),
|
|
97
|
+
kl,
|
|
98
|
+
clipped,
|
|
99
|
+
grad_norm,
|
|
100
|
+
)
|
|
101
|
+
)
|
|
102
|
+
)
|
|
103
|
+
metrics = torch.stack(diagnostics).mean(dim=0).cpu().tolist()
|
|
104
|
+
result = dict(
|
|
105
|
+
zip(
|
|
106
|
+
(
|
|
107
|
+
"policy_loss",
|
|
108
|
+
"value_loss",
|
|
109
|
+
"entropy",
|
|
110
|
+
"kl",
|
|
111
|
+
"clip_fraction",
|
|
112
|
+
"gradient_norm",
|
|
113
|
+
),
|
|
114
|
+
metrics,
|
|
115
|
+
strict=True,
|
|
116
|
+
),
|
|
117
|
+
learning_rate=self.optimizer.param_groups[0]["lr"],
|
|
118
|
+
)
|
|
119
|
+
if not self.policy.discrete:
|
|
120
|
+
result["action_std_mean"] = float(self.policy.std.detach().mean())
|
|
121
|
+
return result
|
|
122
|
+
|
|
123
|
+
def _adjust_learning_rate(self, kl: float):
|
|
124
|
+
if self.cfg.schedule != "adaptive":
|
|
125
|
+
return
|
|
126
|
+
for group in self.optimizer.param_groups:
|
|
127
|
+
if kl > 2 * self.cfg.desired_kl:
|
|
128
|
+
group["lr"] = max(1e-5, group["lr"] / 1.5)
|
|
129
|
+
elif 0 < kl < self.cfg.desired_kl / 2:
|
|
130
|
+
group["lr"] = min(1e-2, group["lr"] * 1.5)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Register a task from a materialized DreamLake bundle checkout."""
|
|
2
|
+
|
|
3
|
+
import importlib.util
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def register_bundle(root: Path, task: str | None = None) -> tuple[str, str]:
|
|
9
|
+
root = root.resolve(strict=True)
|
|
10
|
+
index_path = root / ".dreamlake" / "bundle-index.json"
|
|
11
|
+
index = json.loads(index_path.read_text()) if index_path.is_file() else {}
|
|
12
|
+
manifest_path = root / "bundles.json"
|
|
13
|
+
if not manifest_path.is_file():
|
|
14
|
+
manifest_path = root / "bundle.json"
|
|
15
|
+
entries = json.loads(manifest_path.read_text())["entries"]
|
|
16
|
+
candidates = [name for name, entry in entries.items() if entry["kind"] == "task"]
|
|
17
|
+
task = task or index.get("entry")
|
|
18
|
+
if task is None and len(candidates) == 1:
|
|
19
|
+
task = candidates[0]
|
|
20
|
+
if task not in candidates:
|
|
21
|
+
raise ValueError(f"Select a task entry from: {', '.join(candidates)}")
|
|
22
|
+
|
|
23
|
+
task_entry = entries[task]
|
|
24
|
+
backends = task_entry.get("backends", {})
|
|
25
|
+
backend = index.get("backend") if task == index.get("entry") else None
|
|
26
|
+
if isinstance(backend, dict):
|
|
27
|
+
backend = backend.get("name")
|
|
28
|
+
backend = backend or task_entry.get("defaultBackend")
|
|
29
|
+
backend_ref = backends.get(backend) if isinstance(backend, str) else None
|
|
30
|
+
if not isinstance(backend_ref, str) or not backend_ref.startswith("#"):
|
|
31
|
+
raise ValueError(f"Task {task!r} needs a local backend registration entry")
|
|
32
|
+
executable = entries[backend_ref[1:]]
|
|
33
|
+
if executable["kind"] != "backend":
|
|
34
|
+
raise ValueError(f"Entry {backend_ref!r} must be a backend")
|
|
35
|
+
path = (root / executable["path"]).resolve(strict=True)
|
|
36
|
+
if not path.is_relative_to(root):
|
|
37
|
+
raise ValueError(f"Backend registration path must be inside the bundle: {path}")
|
|
38
|
+
|
|
39
|
+
spec = importlib.util.spec_from_file_location(f"_vuer_lab_bundle_{path.stem}", path)
|
|
40
|
+
if spec is None or spec.loader is None:
|
|
41
|
+
raise ValueError(f"Cannot load backend registration from {path}")
|
|
42
|
+
module = importlib.util.module_from_spec(spec)
|
|
43
|
+
spec.loader.exec_module(module)
|
|
44
|
+
register = getattr(module, "register_tasks", None) or getattr(
|
|
45
|
+
module, "register", None
|
|
46
|
+
)
|
|
47
|
+
if not callable(register):
|
|
48
|
+
raise TypeError(f"{path} must expose register_tasks() or register()")
|
|
49
|
+
result = register()
|
|
50
|
+
target = (
|
|
51
|
+
result
|
|
52
|
+
if isinstance(result, str)
|
|
53
|
+
else getattr(getattr(result, "entry", None), "id", None)
|
|
54
|
+
)
|
|
55
|
+
if not isinstance(target, str) or not target:
|
|
56
|
+
raise ValueError(f"{path} must return the registered environment ID")
|
|
57
|
+
bundle_ref = index.get("ref", "") if task == index.get("entry") else ""
|
|
58
|
+
return target, bundle_ref
|