simforge-gym 0.2.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.
Files changed (61) hide show
  1. simforge_gym-0.2.0/LICENSE +202 -0
  2. simforge_gym-0.2.0/PKG-INFO +117 -0
  3. simforge_gym-0.2.0/README.md +98 -0
  4. simforge_gym-0.2.0/evidence/ppo-scenario-set/README.md +53 -0
  5. simforge_gym-0.2.0/pyproject.toml +31 -0
  6. simforge_gym-0.2.0/simforge_gym/__init__.py +58 -0
  7. simforge_gym-0.2.0/simforge_gym/batch.py +138 -0
  8. simforge_gym-0.2.0/simforge_gym/datasets.py +238 -0
  9. simforge_gym-0.2.0/simforge_gym/env.py +229 -0
  10. simforge_gym-0.2.0/simforge_gym/examples/__init__.py +1 -0
  11. simforge_gym-0.2.0/simforge_gym/examples/ppo.py +368 -0
  12. simforge_gym-0.2.0/simforge_gym/examples/rigs/alpamayo-fisheye.car.rig.json +74 -0
  13. simforge_gym-0.2.0/simforge_gym/pipe.py +125 -0
  14. simforge_gym-0.2.0/simforge_gym/py.typed +0 -0
  15. simforge_gym-0.2.0/simforge_gym/rewards.py +42 -0
  16. simforge_gym-0.2.0/simforge_gym/runtime.py +590 -0
  17. simforge_gym-0.2.0/simforge_gym/scenarios.py +390 -0
  18. simforge_gym-0.2.0/simforge_gym/server.py +208 -0
  19. simforge_gym-0.2.0/simforge_gym/tasks/belmont-research-center.json +160 -0
  20. simforge_gym-0.2.0/simforge_gym/tasks/easterbrook-discovery-school.json +160 -0
  21. simforge_gym-0.2.0/simforge_gym/tasks/el-camino-road.json +178 -0
  22. simforge_gym-0.2.0/simforge_gym/tasks/richmond-field-station.json +154 -0
  23. simforge_gym-0.2.0/simforge_gym/tasks/templates/adult-midblock-crossing.template.json +91 -0
  24. simforge_gym-0.2.0/simforge_gym/tasks/templates/backing-out-vehicle.template.json +81 -0
  25. simforge_gym-0.2.0/simforge_gym/tasks/templates/cpnco-parked-row.template.json +344 -0
  26. simforge_gym-0.2.0/simforge_gym/tasks/templates/cut-in-brake.template.json +81 -0
  27. simforge_gym-0.2.0/simforge_gym/tasks/templates/cutout-reveals-stopped.template.json +92 -0
  28. simforge_gym-0.2.0/simforge_gym/tasks/templates/cyclist-crossing-path.template.json +92 -0
  29. simforge_gym-0.2.0/simforge_gym/tasks/templates/disabled-vehicle.template.json +112 -0
  30. simforge_gym-0.2.0/simforge_gym/tasks/templates/lead-hard-brake.template.json +77 -0
  31. simforge_gym-0.2.0/simforge_gym/tasks/templates/left-turn-crosswalk.template.json +106 -0
  32. simforge_gym-0.2.0/simforge_gym/tasks/templates/light-corridor.template.json +170 -0
  33. simforge_gym-0.2.0/simforge_gym/tasks/templates/ltap-opposing.template.json +345 -0
  34. simforge_gym-0.2.0/simforge_gym/tasks/templates/oncoming-overtake.template.json +27 -0
  35. simforge_gym-0.2.0/simforge_gym/tasks/templates/opposing-turn-encroachment.template.json +26 -0
  36. simforge_gym-0.2.0/simforge_gym/tasks/templates/queue-tail.template.json +90 -0
  37. simforge_gym-0.2.0/simforge_gym/tasks/templates/red-light-late-entry.template.json +25 -0
  38. simforge_gym-0.2.0/simforge_gym/tasks/templates/right-turn-crosswalk.template.json +128 -0
  39. simforge_gym-0.2.0/simforge_gym/tasks/templates/sideswipe.template.json +81 -0
  40. simforge_gym-0.2.0/simforge_gym/tasks/templates/urban-mixed.template.json +1391 -0
  41. simforge_gym-0.2.0/simforge_gym/tasks/templates/vehicle-pulls-out.template.json +78 -0
  42. simforge_gym-0.2.0/simforge_gym/tasks/yale-street.json +184 -0
  43. simforge_gym-0.2.0/simforge_gym/transport.py +159 -0
  44. simforge_gym-0.2.0/simforge_gym/vector.py +49 -0
  45. simforge_gym-0.2.0/simforge_gym/wire.py +95 -0
  46. simforge_gym-0.2.0/simforge_gym/world.py +141 -0
  47. simforge_gym-0.2.0/tests/__init__.py +0 -0
  48. simforge_gym-0.2.0/tests/conftest.py +15 -0
  49. simforge_gym-0.2.0/tests/env_probe_runtime.py +15 -0
  50. simforge_gym-0.2.0/tests/fakes.py +248 -0
  51. simforge_gym-0.2.0/tests/test_batch.py +138 -0
  52. simforge_gym-0.2.0/tests/test_datasets.py +162 -0
  53. simforge_gym-0.2.0/tests/test_env.py +202 -0
  54. simforge_gym-0.2.0/tests/test_live.py +119 -0
  55. simforge_gym-0.2.0/tests/test_live_sensors.py +47 -0
  56. simforge_gym-0.2.0/tests/test_native_paths.py +38 -0
  57. simforge_gym-0.2.0/tests/test_runtime.py +95 -0
  58. simforge_gym-0.2.0/tests/test_scenarios.py +102 -0
  59. simforge_gym-0.2.0/tests/test_tasks.py +70 -0
  60. simforge_gym-0.2.0/tests/test_wire.py +63 -0
  61. simforge_gym-0.2.0/tests/test_world.py +179 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.4
2
+ Name: simforge-gym
3
+ Version: 0.2.0
4
+ Summary: Gymnasium environments, scenario-set task distributions and the runtime-protocol client for the SimForge runtime
5
+ Author: SimForge
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
10
+ Requires-Python: >=3.10
11
+ Requires-Dist: gymnasium>=1.1
12
+ Requires-Dist: numpy>=1.24
13
+ Provides-Extra: dev
14
+ Requires-Dist: build==1.3.0; extra == 'dev'
15
+ Requires-Dist: pytest==9.1.1; extra == 'dev'
16
+ Provides-Extra: ppo
17
+ Requires-Dist: torch>=2.0; extra == 'ppo'
18
+ Description-Content-Type: text/markdown
19
+
20
+ # simforge-gym
21
+
22
+ SimForge Gym: train driving models in SimForge on your own machine. Today that is reinforcement learning; supervised fine-tuning recipes are coming. `simforge-gym` gives you Gymnasium environments over the SimForge runtime, task sets on the released SimForge maps, training on SimForge datasets, and a PPO example. Apache-2.0. Dependencies: `numpy` and `gymnasium`; the PPO example adds `torch` (`pip install 'simforge-gym[ppo]'`).
23
+
24
+ The episodes run in the SimForge runtime, a closed program you install after signing in; this package is the open client. It never imports runtime code and never substitutes another simulator: no runtime, no episode. Training runs locally; there is no cloud RL.
25
+
26
+ `simforge-gym` 0.2.0 is the package formerly published as `simforge-rl` (frozen at 0.1.4): `pip install simforge-gym` and `import simforge_gym`, with the same API. Scenario-set and run files now carry `simforge-gym.*` schema ids.
27
+
28
+ On Windows, the package requires a runtime that reports `capabilities.envSocketTransport: "named-pipe"` (the older `0.1.0+bfd484b7727b1cfd` runtime cannot run local RL). Update with `simforge runtime install`; older runtimes fail with `runtime_upgrade_required`. The same env-serve protocol uses secure same-user named pipes on Windows and Unix sockets on macOS/Linux.
29
+
30
+ ## Quickstart (CPU only)
31
+
32
+ State observations need no GPU. With the `simforge` CLI installed:
33
+
34
+ ```sh
35
+ simforge login # a browser approves the device code
36
+ simforge runtime install --accept-license # the closed runtime, under ~/.local/share/simforge/runtime
37
+ simforge maps pull richmond-field-station@v9 --accept-license # a released map
38
+ pip install 'simforge-gym[ppo]'
39
+ python -m simforge_gym.examples.ppo --tasks richmond-field-station --runtime --num-envs 8 --total-timesteps 200000 --out run/
40
+ ```
41
+
42
+ `run/` then holds `curve.csv`, `curve.svg`, `metadata.json` and `policy.pt`. `--runtime` runs each vector worker's episodes in its own `simforge-runtime serve` process; without it the example starts `simforge env serve` processes through the CLI instead. Both give the same observations and rewards.
43
+
44
+ In Python:
45
+
46
+ ```python
47
+ from simforge_gym import RuntimeSessions, ScenarioSet, make_vector_env
48
+
49
+ tasks = ScenarioSet.bundled("richmond-field-station") # 24 tasks: 15 templates at verified sites
50
+ with RuntimeSessions(tasks, "--no-sensors", workdir="work") as sessions:
51
+ envs = make_vector_env(tasks, sessions.transports(), num_envs=8)
52
+ obs, info = envs.reset(seed=0)
53
+ obs, reward, terminated, truncated, info = envs.step(envs.action_space.sample()) # [target_speed_mps, target_accel_mps2] per env
54
+ ```
55
+
56
+ ## Task sets on the released maps
57
+
58
+ `bundled_sets()` names the task sets shipped with the package: `belmont-research-center`, `easterbrook-discovery-school`, `el-camino-road`, `richmond-field-station` and `yale-street`, 24 to 29 tasks each. Each is a weighted set of scenario templates (car following, cut-ins, lead braking, crossing pedestrians and cyclists, unprotected turns, red-light runners, vehicles pulling out, ...), each at the sites of that map where it compiles and its authored episode runs, with every template weighted equally. A set is pinned to the OpenDRIVE digest of the map version it was verified on, so its episodes run on exactly that installed map: pull `NAME@VERSION` as the set's `map` says. [`evidence/task-sets/report.json`](evidence/task-sets/report.json) records every template, site and verification episode. Site ids come from the map pack's derived road data, so a republished pack comes with rebuilt sets (`scripts/build_task_sets.py`); a site the installed pack does not have fails with `no_site` rather than moving the task elsewhere.
59
+
60
+ Every actor in the templates is in the public CARLA asset pack. The urban mixed template uses `carla.vehicle_fuso_mitsubishi` for its oncoming bus; `vehicle.bus` is the full-size procedural model and is not in that pack.
61
+
62
+ ## Train on a dataset
63
+
64
+ ```python
65
+ tasks = ScenarioSet.from_dataset("data/my-dataset", split="train") # a pulled folder
66
+ tasks = ScenarioSet.from_dataset("usds_01JA...", split="train") # your hosted dataset, pulled with `simforge datasets pull`
67
+ ```
68
+
69
+ ```sh
70
+ simforge datasets pull usds_01JA... --include scenarios --out data/my-dataset
71
+ python -m simforge_gym.examples.ppo --dataset data/my-dataset --split train --runtime --max-open 16 --eval-limit 8 --out run/
72
+ ```
73
+
74
+ Both dataset formats work: the public SimForge dataset (`simforge.public-dataset/v1`) and hosted datasets pulled as files (`simforge.dataset-files/v1`). Every file is checked against its recorded digest and laid out once; a pulled scenario's episode is exactly the input its simulation ran, and every episode runs on the installed map the scenario's OpenDRIVE digest names. `--max-open` keeps at most that many sessions open per worker (least recently used close first), so a split of thousands of scenarios trains with a bounded number of sessions.
75
+
76
+ ## Camera observations
77
+
78
+ `observation="sensors"` returns rendered camera passes keyed `"<sourceId>/<pass>"` (`rgb` uint8 HxWx4, `depth` float32 HxW) and nothing else: the policy sees no engine state, object ids, reward terms or events. Rendering needs a supported GPU and an installed map's 3D pack. `simforge_gym/examples/rigs/alpamayo-fisheye.car.rig.json` is an Alpamayo-style rig: a 120-degree f-theta (fisheye) front camera and a 30-degree front tele camera, 512x384. Its lens is a generic equidistant calibration, not one taken from a real vehicle.
79
+
80
+ ```sh
81
+ simforge env serve ws --socket cam.sock --rig alpamayo-fisheye.car.rig.json --observation-profile sensors \
82
+ --passes rgb,depth --actor-closure "$(basename ~/.local/share/simforge/runtime/share/actors/closures/*.json .json)"
83
+ ```
84
+
85
+ ```python
86
+ env = SimForgeEnv(SocketTransport("cam.sock"), observation="sensors")
87
+ obs, info = env.reset(options={"episode_seed": 1})
88
+ frame = obs["camera_front_wide_120fov/rgb"] # (384, 512, 4) uint8
89
+ ```
90
+
91
+ If the policy drives the ego off the map, the runtime has no camera pose for that step and renders nothing. The step then returns the last rendered camera observation, `truncated=True`, and the runtime's `sensor_host_absent` warning (naming the absent actor) in `info["render_warnings"]`. Reset to start the next episode. Only a reset whose ego is already out of the world raises, because there is no earlier frame to return.
92
+
93
+ `ws` is a scenario workspace, for example `template_workspace(...)` of a bundled task. `simforge rig show alpamayo-fisheye.car.rig.json` reports each camera's field of view; the installed runtime plans the f-theta lens.
94
+
95
+ ## Rewards
96
+
97
+ `reward_fn(native_reward, info) -> float` replaces the reward; `info["native_reward"]` keeps the runtime's. `WeightedTerms({"progress": 1.0, "proximity": 2.0, "comfort": 1.0})` reweights the runtime's reward terms and `EventPenalty({"collision": 10.0})` subtracts per engine event; both need a state observation mode.
98
+
99
+ ## The PPO result
100
+
101
+ [`evidence/ppo-scenario-set`](evidence/ppo-scenario-set) is a recorded PPO run on the bundled Richmond Field Station set through the distributable runtime, with its learning curve, configuration and a same-seed repeat.
102
+
103
+ The policy sees pose-free ego state and the eight nearest object rows and outputs a speed and acceleration setpoint. Each evaluation also runs the scenarios' authored ego control on the same tasks as a baseline. `python -m simforge_gym.examples.ppo --help` lists every flag.
104
+
105
+ ## More
106
+
107
+ - [API reference](docs/api.md): environments, task sets, datasets, the runtime protocol client (episodes, CPU batches of up to 64 episodes, persistent worlds) and the PPO flags.
108
+ - [RL methodology](docs/methodology.md): what the environment simulates, how it is evaluated, and what has been measured.
109
+
110
+ ## Development
111
+
112
+ ```sh
113
+ uv run --project clients/gym --extra dev python -m pytest -q clients/gym/tests
114
+ python3 scripts/sdk/toolkit-release.py build --ref HEAD --out "$TMPDIR/wheels" # reproducible wheels
115
+ ```
116
+
117
+ `SIMFORGE_BIN` and `SIMFORGE_GYM_TEST_MAP_DIR` (Richmond Field Station v9, in a directory named `richmond-field-station`) enable the live runtime tests; `SIMFORGE_GYM_TEST_SENSOR_MAP` and `SIMFORGE_GYM_TEST_ACTOR_CLOSURE` add the camera test. Without them those tests are skipped and say so. `scripts/build_task_sets.py` rebuilds the bundled task sets from installed map packs.
@@ -0,0 +1,98 @@
1
+ # simforge-gym
2
+
3
+ SimForge Gym: train driving models in SimForge on your own machine. Today that is reinforcement learning; supervised fine-tuning recipes are coming. `simforge-gym` gives you Gymnasium environments over the SimForge runtime, task sets on the released SimForge maps, training on SimForge datasets, and a PPO example. Apache-2.0. Dependencies: `numpy` and `gymnasium`; the PPO example adds `torch` (`pip install 'simforge-gym[ppo]'`).
4
+
5
+ The episodes run in the SimForge runtime, a closed program you install after signing in; this package is the open client. It never imports runtime code and never substitutes another simulator: no runtime, no episode. Training runs locally; there is no cloud RL.
6
+
7
+ `simforge-gym` 0.2.0 is the package formerly published as `simforge-rl` (frozen at 0.1.4): `pip install simforge-gym` and `import simforge_gym`, with the same API. Scenario-set and run files now carry `simforge-gym.*` schema ids.
8
+
9
+ On Windows, the package requires a runtime that reports `capabilities.envSocketTransport: "named-pipe"` (the older `0.1.0+bfd484b7727b1cfd` runtime cannot run local RL). Update with `simforge runtime install`; older runtimes fail with `runtime_upgrade_required`. The same env-serve protocol uses secure same-user named pipes on Windows and Unix sockets on macOS/Linux.
10
+
11
+ ## Quickstart (CPU only)
12
+
13
+ State observations need no GPU. With the `simforge` CLI installed:
14
+
15
+ ```sh
16
+ simforge login # a browser approves the device code
17
+ simforge runtime install --accept-license # the closed runtime, under ~/.local/share/simforge/runtime
18
+ simforge maps pull richmond-field-station@v9 --accept-license # a released map
19
+ pip install 'simforge-gym[ppo]'
20
+ python -m simforge_gym.examples.ppo --tasks richmond-field-station --runtime --num-envs 8 --total-timesteps 200000 --out run/
21
+ ```
22
+
23
+ `run/` then holds `curve.csv`, `curve.svg`, `metadata.json` and `policy.pt`. `--runtime` runs each vector worker's episodes in its own `simforge-runtime serve` process; without it the example starts `simforge env serve` processes through the CLI instead. Both give the same observations and rewards.
24
+
25
+ In Python:
26
+
27
+ ```python
28
+ from simforge_gym import RuntimeSessions, ScenarioSet, make_vector_env
29
+
30
+ tasks = ScenarioSet.bundled("richmond-field-station") # 24 tasks: 15 templates at verified sites
31
+ with RuntimeSessions(tasks, "--no-sensors", workdir="work") as sessions:
32
+ envs = make_vector_env(tasks, sessions.transports(), num_envs=8)
33
+ obs, info = envs.reset(seed=0)
34
+ obs, reward, terminated, truncated, info = envs.step(envs.action_space.sample()) # [target_speed_mps, target_accel_mps2] per env
35
+ ```
36
+
37
+ ## Task sets on the released maps
38
+
39
+ `bundled_sets()` names the task sets shipped with the package: `belmont-research-center`, `easterbrook-discovery-school`, `el-camino-road`, `richmond-field-station` and `yale-street`, 24 to 29 tasks each. Each is a weighted set of scenario templates (car following, cut-ins, lead braking, crossing pedestrians and cyclists, unprotected turns, red-light runners, vehicles pulling out, ...), each at the sites of that map where it compiles and its authored episode runs, with every template weighted equally. A set is pinned to the OpenDRIVE digest of the map version it was verified on, so its episodes run on exactly that installed map: pull `NAME@VERSION` as the set's `map` says. [`evidence/task-sets/report.json`](evidence/task-sets/report.json) records every template, site and verification episode. Site ids come from the map pack's derived road data, so a republished pack comes with rebuilt sets (`scripts/build_task_sets.py`); a site the installed pack does not have fails with `no_site` rather than moving the task elsewhere.
40
+
41
+ Every actor in the templates is in the public CARLA asset pack. The urban mixed template uses `carla.vehicle_fuso_mitsubishi` for its oncoming bus; `vehicle.bus` is the full-size procedural model and is not in that pack.
42
+
43
+ ## Train on a dataset
44
+
45
+ ```python
46
+ tasks = ScenarioSet.from_dataset("data/my-dataset", split="train") # a pulled folder
47
+ tasks = ScenarioSet.from_dataset("usds_01JA...", split="train") # your hosted dataset, pulled with `simforge datasets pull`
48
+ ```
49
+
50
+ ```sh
51
+ simforge datasets pull usds_01JA... --include scenarios --out data/my-dataset
52
+ python -m simforge_gym.examples.ppo --dataset data/my-dataset --split train --runtime --max-open 16 --eval-limit 8 --out run/
53
+ ```
54
+
55
+ Both dataset formats work: the public SimForge dataset (`simforge.public-dataset/v1`) and hosted datasets pulled as files (`simforge.dataset-files/v1`). Every file is checked against its recorded digest and laid out once; a pulled scenario's episode is exactly the input its simulation ran, and every episode runs on the installed map the scenario's OpenDRIVE digest names. `--max-open` keeps at most that many sessions open per worker (least recently used close first), so a split of thousands of scenarios trains with a bounded number of sessions.
56
+
57
+ ## Camera observations
58
+
59
+ `observation="sensors"` returns rendered camera passes keyed `"<sourceId>/<pass>"` (`rgb` uint8 HxWx4, `depth` float32 HxW) and nothing else: the policy sees no engine state, object ids, reward terms or events. Rendering needs a supported GPU and an installed map's 3D pack. `simforge_gym/examples/rigs/alpamayo-fisheye.car.rig.json` is an Alpamayo-style rig: a 120-degree f-theta (fisheye) front camera and a 30-degree front tele camera, 512x384. Its lens is a generic equidistant calibration, not one taken from a real vehicle.
60
+
61
+ ```sh
62
+ simforge env serve ws --socket cam.sock --rig alpamayo-fisheye.car.rig.json --observation-profile sensors \
63
+ --passes rgb,depth --actor-closure "$(basename ~/.local/share/simforge/runtime/share/actors/closures/*.json .json)"
64
+ ```
65
+
66
+ ```python
67
+ env = SimForgeEnv(SocketTransport("cam.sock"), observation="sensors")
68
+ obs, info = env.reset(options={"episode_seed": 1})
69
+ frame = obs["camera_front_wide_120fov/rgb"] # (384, 512, 4) uint8
70
+ ```
71
+
72
+ If the policy drives the ego off the map, the runtime has no camera pose for that step and renders nothing. The step then returns the last rendered camera observation, `truncated=True`, and the runtime's `sensor_host_absent` warning (naming the absent actor) in `info["render_warnings"]`. Reset to start the next episode. Only a reset whose ego is already out of the world raises, because there is no earlier frame to return.
73
+
74
+ `ws` is a scenario workspace, for example `template_workspace(...)` of a bundled task. `simforge rig show alpamayo-fisheye.car.rig.json` reports each camera's field of view; the installed runtime plans the f-theta lens.
75
+
76
+ ## Rewards
77
+
78
+ `reward_fn(native_reward, info) -> float` replaces the reward; `info["native_reward"]` keeps the runtime's. `WeightedTerms({"progress": 1.0, "proximity": 2.0, "comfort": 1.0})` reweights the runtime's reward terms and `EventPenalty({"collision": 10.0})` subtracts per engine event; both need a state observation mode.
79
+
80
+ ## The PPO result
81
+
82
+ [`evidence/ppo-scenario-set`](evidence/ppo-scenario-set) is a recorded PPO run on the bundled Richmond Field Station set through the distributable runtime, with its learning curve, configuration and a same-seed repeat.
83
+
84
+ The policy sees pose-free ego state and the eight nearest object rows and outputs a speed and acceleration setpoint. Each evaluation also runs the scenarios' authored ego control on the same tasks as a baseline. `python -m simforge_gym.examples.ppo --help` lists every flag.
85
+
86
+ ## More
87
+
88
+ - [API reference](docs/api.md): environments, task sets, datasets, the runtime protocol client (episodes, CPU batches of up to 64 episodes, persistent worlds) and the PPO flags.
89
+ - [RL methodology](docs/methodology.md): what the environment simulates, how it is evaluated, and what has been measured.
90
+
91
+ ## Development
92
+
93
+ ```sh
94
+ uv run --project clients/gym --extra dev python -m pytest -q clients/gym/tests
95
+ python3 scripts/sdk/toolkit-release.py build --ref HEAD --out "$TMPDIR/wheels" # reproducible wheels
96
+ ```
97
+
98
+ `SIMFORGE_BIN` and `SIMFORGE_GYM_TEST_MAP_DIR` (Richmond Field Station v9, in a directory named `richmond-field-station`) enable the live runtime tests; `SIMFORGE_GYM_TEST_SENSOR_MAP` and `SIMFORGE_GYM_TEST_ACTOR_CLOSURE` add the camera test. Without them those tests are skipped and say so. `scripts/build_task_sets.py` rebuilds the bundled task sets from installed map packs.
@@ -0,0 +1,53 @@
1
+ # PPO on the bundled Richmond Field Station task set
2
+
3
+ PPO from `simforge_rl.examples.ppo`, trained for 1,228,800 environment steps (10,832 episodes, 38 minutes at the lowest CPU priority on a 24-core CPU host with no GPU) on the bundled `richmond-field-station` task set: 24 tasks from 15 scenario templates, each at a verified site of Richmond Field Station v9 as its distribution map pack has it. Episodes ran in the distributable runtime (`simforge-runtime 0.1.0+c9e184cc1b0b6292`, engine 0.31.0, installed with `simforge runtime install`), one `simforge-runtime serve` per vector worker, and the package was the reproducibly built `simforge_rl-0.1.1` wheel.
4
+
5
+ | | Initial policy | After training | Authored ego control |
6
+ |---|---|---|---|
7
+ | Mean evaluation return (24 tasks x 2 held-out seeds) | 0.79 | **2.74** | 0.71 |
8
+ | Mean training return (last 128 episodes) | -1.39 at 41k steps | 3.50 | |
9
+
10
+ ![reward vs environment steps](curve.svg)
11
+
12
+ The trained policy beats the scenarios' own authored driving on 12 of the 24 tasks and on average. It learned to cross behind cyclists and to pass well (cyclist-crossing-path@16d03889 20.3 against -8.2, oncoming-overtake@ddc37703 15.4 against 5.3, the unprotected left turn 11.0 against 2.9) and still crashes where the authored driving does not: both disabled-vehicle tasks, one lead-hard-brake and one parked-row task (about -7 to -8).
13
+
14
+ | Task | Authored control | Initial policy | After training |
15
+ |---|---|---|---|
16
+ | adult-midblock-crossing@158aa402 | 4.94 | -7.38 | 8.46 |
17
+ | adult-midblock-crossing@27d53507 | 3.20 | 8.80 | 0.67 |
18
+ | backing-out-vehicle@02931707 | -0.00 | 5.33 | 5.54 |
19
+ | backing-out-vehicle@2622e37c | -0.25 | -9.56 | -0.24 |
20
+ | cpnco-parked-row@c7794a7c | 2.38 | -7.15 | 0.22 |
21
+ | cpnco-parked-row@de9c337a | 2.40 | -7.06 | -7.08 |
22
+ | cyclist-crossing-path@0e7787e6 | -8.60 | 7.27 | 5.24 |
23
+ | cyclist-crossing-path@16d03889 | -8.17 | 8.43 | 20.25 |
24
+ | disabled-vehicle@69939930 | 0.55 | -8.18 | -8.18 |
25
+ | disabled-vehicle@894df17b | 1.22 | -8.26 | -8.28 |
26
+ | lead-hard-brake@1e29b9bd | 1.88 | -7.58 | -7.73 |
27
+ | lead-hard-brake@391af02d | 1.88 | -7.58 | 1.00 |
28
+ | light-corridor@1c0e6bed | 1.99 | 7.63 | 9.49 |
29
+ | ltap-opposing@9fc1b2c2 | 2.89 | 9.57 | 10.95 |
30
+ | oncoming-overtake@b1ed39e5 | -8.92 | 10.23 | -8.54 |
31
+ | oncoming-overtake@ddc37703 | 5.31 | 11.27 | 15.41 |
32
+ | opposing-turn-encroachment@23afb358 | 1.20 | 6.55 | 9.68 |
33
+ | queue-tail@1ae48fb3 | 1.55 | -7.62 | 0.20 |
34
+ | queue-tail@e2e894a1 | 1.55 | -7.62 | 0.35 |
35
+ | red-light-late-entry@027da72d | 5.02 | 5.02 | 4.84 |
36
+ | right-turn-crosswalk@109e9d91 | 1.26 | 6.69 | 5.05 |
37
+ | urban-mixed@42144495 | -0.89 | -8.44 | -0.98 |
38
+ | vehicle-pulls-out@6fcaaefa | 2.38 | 9.80 | 0.15 |
39
+ | vehicle-pulls-out@85b4ac66 | 2.29 | 8.78 | 9.29 |
40
+
41
+ Evaluation uses the policy's mean action, so a single crash moves a task to about -7 to -10.
42
+
43
+ - `curve.csv`: evaluation return (mean and per task) and training return against environment steps, every 10 updates.
44
+ - `metadata.json`: configuration, the map pin, every task's template digest and site, runtime and package versions.
45
+ - `reproducibility.json`: runtime release, archive and binary digests, wheel digest, map, policy and curve digests, and the same-seed repeat.
46
+
47
+ Reproduce, after `simforge runtime install` and `simforge maps pull richmond-field-station@v9`:
48
+
49
+ ```sh
50
+ pip install 'simforge-rl[ppo]==0.1.1'
51
+ python -m simforge_rl.examples.ppo --tasks richmond-field-station --runtime --num-envs 32 \
52
+ --total-timesteps 1228800 --eval-every 10 --seed 0 --out run --json
53
+ ```
@@ -0,0 +1,31 @@
1
+ [project]
2
+ name = "simforge-gym"
3
+ version = "0.2.0"
4
+ description = "Gymnasium environments, scenario-set task distributions and the runtime-protocol client for the SimForge runtime"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "SimForge" }]
10
+ classifiers = ["Programming Language :: Python :: 3", "Topic :: Scientific/Engineering :: Artificial Intelligence"]
11
+ dependencies = [
12
+ "gymnasium>=1.1",
13
+ "numpy>=1.24",
14
+ ]
15
+
16
+ [project.optional-dependencies]
17
+ ppo = ["torch>=2.0"]
18
+ dev = ["build==1.3.0", "pytest==9.1.1"]
19
+
20
+ [build-system]
21
+ requires = ["hatchling==1.27.0"]
22
+ build-backend = "hatchling.build"
23
+
24
+ [tool.hatch.build.targets.wheel]
25
+ packages = ["simforge_gym"]
26
+
27
+ [tool.hatch.build.targets.sdist]
28
+ include = ["simforge_gym", "tests", "examples", "LICENSE", "README.md"]
29
+
30
+ [tool.pytest.ini_options]
31
+ testpaths = ["tests"]
@@ -0,0 +1,58 @@
1
+ """Gymnasium environments and the runtime-protocol client for the SimForge runtime."""
2
+
3
+ import importlib.metadata
4
+
5
+ from .env import SimForgeEnv, action_space_for, sensor_space, state_space
6
+ from .rewards import EventPenalty, WeightedTerms, native
7
+ from .batch import SimForgeBatchVectorEnv
8
+ from .runtime import BatchResults, BatchRow, CommandResult, RuntimeBatch, RuntimeClient, RuntimeProtocolError
9
+ from .datasets import DatasetError, dataset_scenarios, pull_dataset, read_dataset
10
+ from .scenarios import MapPin, RuntimeSessions, Scenario, ScenarioServers, ScenarioSet, ScenarioSetEnv, bundled_sets
11
+ from .server import EnvServer, template_workspace
12
+ from .world import Subscription, TruthDelivery, WorldCheckpoint, WorldSession
13
+ from .transport import EnvTransport, RuntimeEnvTransport, SocketTransport
14
+ from .vector import make_vector_env
15
+ from .wire import PROTOCOL, EnvServeError, ProtocolError
16
+
17
+ __version__ = importlib.metadata.version("simforge-gym")
18
+
19
+ __all__ = [
20
+ "PROTOCOL",
21
+ "BatchResults",
22
+ "BatchRow",
23
+ "CommandResult",
24
+ "RuntimeBatch",
25
+ "SimForgeBatchVectorEnv",
26
+ "Subscription",
27
+ "TruthDelivery",
28
+ "WorldCheckpoint",
29
+ "WorldSession",
30
+ "EnvServeError",
31
+ "EnvServer",
32
+ "EnvTransport",
33
+ "DatasetError",
34
+ "EventPenalty",
35
+ "MapPin",
36
+ "ProtocolError",
37
+ "RuntimeClient",
38
+ "RuntimeEnvTransport",
39
+ "RuntimeProtocolError",
40
+ "RuntimeSessions",
41
+ "Scenario",
42
+ "ScenarioServers",
43
+ "ScenarioSet",
44
+ "ScenarioSetEnv",
45
+ "SimForgeEnv",
46
+ "SocketTransport",
47
+ "WeightedTerms",
48
+ "action_space_for",
49
+ "bundled_sets",
50
+ "dataset_scenarios",
51
+ "make_vector_env",
52
+ "native",
53
+ "pull_dataset",
54
+ "read_dataset",
55
+ "sensor_space",
56
+ "state_space",
57
+ "template_workspace",
58
+ ]