rad-embeddings 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.
- rad_embeddings-0.1.0/.gitignore +174 -0
- rad_embeddings-0.1.0/.python-version +1 -0
- rad_embeddings-0.1.0/LICENSE +21 -0
- rad_embeddings-0.1.0/PKG-INFO +15 -0
- rad_embeddings-0.1.0/README.md +1 -0
- rad_embeddings-0.1.0/pyproject.toml +18 -0
- rad_embeddings-0.1.0/rad_embeddings/__init__.py +1 -0
- rad_embeddings-0.1.0/rad_embeddings/encoder.py +97 -0
- rad_embeddings-0.1.0/rad_embeddings/model.py +28 -0
- rad_embeddings-0.1.0/rad_embeddings/storage/DFAEnv-v0-encoder.zip +0 -0
- rad_embeddings-0.1.0/rad_embeddings/storage/DFAEnv-v1-encoder.zip +0 -0
- rad_embeddings-0.1.0/rad_embeddings/storage/runs/PPO_1/events.out.tfevents.1736972161.wifi-10-42-144-50.wifi.berkeley.edu.11863.0 +0 -0
- rad_embeddings-0.1.0/rad_embeddings/storage/runs/PPO_2/events.out.tfevents.1736974344.wifi-10-42-144-50.wifi.berkeley.edu.12484.0 +0 -0
- rad_embeddings-0.1.0/rad_embeddings/storage.zip +0 -0
- rad_embeddings-0.1.0/rad_embeddings/token_env_reach_avoid_policy/runs/PPO_1/events.out.tfevents.1736976150.wifi-10-42-144-50.wifi.berkeley.edu.13134.0 +0 -0
- rad_embeddings-0.1.0/rad_embeddings/train_token_env_policy.py +64 -0
- rad_embeddings-0.1.0/rad_embeddings/utils/__init__.py +4 -0
- rad_embeddings-0.1.0/rad_embeddings/utils/sb3_dfa_env_features_extractor.py +14 -0
- rad_embeddings-0.1.0/rad_embeddings/utils/sb3_logger_callback.py +50 -0
- rad_embeddings-0.1.0/rad_embeddings/utils/sb3_token_env_features_extractor.py +27 -0
- rad_embeddings-0.1.0/rad_embeddings/utils/utils.py +85 -0
- rad_embeddings-0.1.0/uv.lock +1235 -0
|
@@ -0,0 +1,174 @@
|
|
|
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
|
+
# UV
|
|
98
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
99
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
100
|
+
# commonly ignored for libraries.
|
|
101
|
+
#uv.lock
|
|
102
|
+
|
|
103
|
+
# poetry
|
|
104
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
105
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
106
|
+
# commonly ignored for libraries.
|
|
107
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
108
|
+
#poetry.lock
|
|
109
|
+
|
|
110
|
+
# pdm
|
|
111
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
112
|
+
#pdm.lock
|
|
113
|
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
|
114
|
+
# in version control.
|
|
115
|
+
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
|
116
|
+
.pdm.toml
|
|
117
|
+
.pdm-python
|
|
118
|
+
.pdm-build/
|
|
119
|
+
|
|
120
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
121
|
+
__pypackages__/
|
|
122
|
+
|
|
123
|
+
# Celery stuff
|
|
124
|
+
celerybeat-schedule
|
|
125
|
+
celerybeat.pid
|
|
126
|
+
|
|
127
|
+
# SageMath parsed files
|
|
128
|
+
*.sage.py
|
|
129
|
+
|
|
130
|
+
# Environments
|
|
131
|
+
.env
|
|
132
|
+
.venv
|
|
133
|
+
env/
|
|
134
|
+
venv/
|
|
135
|
+
ENV/
|
|
136
|
+
env.bak/
|
|
137
|
+
venv.bak/
|
|
138
|
+
|
|
139
|
+
# Spyder project settings
|
|
140
|
+
.spyderproject
|
|
141
|
+
.spyproject
|
|
142
|
+
|
|
143
|
+
# Rope project settings
|
|
144
|
+
.ropeproject
|
|
145
|
+
|
|
146
|
+
# mkdocs documentation
|
|
147
|
+
/site
|
|
148
|
+
|
|
149
|
+
# mypy
|
|
150
|
+
.mypy_cache/
|
|
151
|
+
.dmypy.json
|
|
152
|
+
dmypy.json
|
|
153
|
+
|
|
154
|
+
# Pyre type checker
|
|
155
|
+
.pyre/
|
|
156
|
+
|
|
157
|
+
# pytype static type analyzer
|
|
158
|
+
.pytype/
|
|
159
|
+
|
|
160
|
+
# Cython debug symbols
|
|
161
|
+
cython_debug/
|
|
162
|
+
|
|
163
|
+
# PyCharm
|
|
164
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
165
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
166
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
167
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
168
|
+
#.idea/
|
|
169
|
+
|
|
170
|
+
# PyPI configuration file
|
|
171
|
+
.pypirc
|
|
172
|
+
|
|
173
|
+
# macos
|
|
174
|
+
.DS_Store
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
3.12
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 RAD-Embeddings
|
|
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,15 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rad-embeddings
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Add your description here
|
|
5
|
+
License-File: LICENSE
|
|
6
|
+
Requires-Python: >=3.12
|
|
7
|
+
Requires-Dist: dfa-gym>=0.1.0
|
|
8
|
+
Requires-Dist: stable-baselines3>=2.4.1
|
|
9
|
+
Requires-Dist: tensorboard>=2.18.0
|
|
10
|
+
Requires-Dist: token-env>=0.2.1
|
|
11
|
+
Requires-Dist: torch-geometric>=2.6.1
|
|
12
|
+
Requires-Dist: torch<2.3.0
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# rad-embeddings
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# rad-embeddings
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "rad-embeddings"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Add your description here"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"dfa-gym>=0.1.0",
|
|
9
|
+
"stable-baselines3>=2.4.1",
|
|
10
|
+
"tensorboard>=2.18.0",
|
|
11
|
+
"token-env>=0.2.1",
|
|
12
|
+
"torch<2.3.0",
|
|
13
|
+
"torch-geometric>=2.6.1",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[build-system]
|
|
17
|
+
requires = ["hatchling"]
|
|
18
|
+
build-backend = "hatchling.build"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from encoder import Encoder
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from dfa import DFA
|
|
3
|
+
from dfa_gym import DFAEnv
|
|
4
|
+
from stable_baselines3 import PPO
|
|
5
|
+
from utils import dfa2obs
|
|
6
|
+
import gymnasium as gym
|
|
7
|
+
from utils import DFAEnvFeaturesExtractor, LoggerCallback
|
|
8
|
+
from stable_baselines3.common.callbacks import EvalCallback, StopTrainingOnNoModelImprovement
|
|
9
|
+
|
|
10
|
+
class Encoder():
|
|
11
|
+
def __init__(self, load_file: str):
|
|
12
|
+
model = PPO.load(load_file)
|
|
13
|
+
model.set_parameters(load_file)
|
|
14
|
+
for param in model.policy.parameters():
|
|
15
|
+
param.requires_grad = False
|
|
16
|
+
model.policy.eval()
|
|
17
|
+
self.obs2rad = model.policy.features_extractor
|
|
18
|
+
self.rad2token = lambda _rad: model.policy.action_net(_rad).argmax(dim=1)
|
|
19
|
+
self.n_tokens = self.obs2rad.n_tokens
|
|
20
|
+
|
|
21
|
+
def dfa2rad(self, dfa: DFA) -> np.array:
|
|
22
|
+
assert len(dfa.inputs) == self.n_tokens
|
|
23
|
+
obs = dfa2obs(dfa)
|
|
24
|
+
rad = self.obs2rad(obs)
|
|
25
|
+
return rad
|
|
26
|
+
|
|
27
|
+
@staticmethod
|
|
28
|
+
def train(n_tokens: int, train_env: gym.Env, save_dir: str, eval_env: gym.Env | None = None, id: str = "rad"):
|
|
29
|
+
save_dir = save_dir[:-1] if save_dir.endswith("/") else save_dir
|
|
30
|
+
config = dict(
|
|
31
|
+
policy = "MlpPolicy",
|
|
32
|
+
env = train_env,
|
|
33
|
+
learning_rate = 1e-3,
|
|
34
|
+
n_steps = 512,
|
|
35
|
+
batch_size = 1024,
|
|
36
|
+
n_epochs = 2,
|
|
37
|
+
gamma = 0.9,
|
|
38
|
+
gae_lambda = 0.5,
|
|
39
|
+
clip_range = 0.1,
|
|
40
|
+
ent_coef = 1e-2,
|
|
41
|
+
vf_coef = 0.5,
|
|
42
|
+
max_grad_norm = 0.5,
|
|
43
|
+
policy_kwargs = dict(
|
|
44
|
+
features_extractor_class = DFAEnvFeaturesExtractor,
|
|
45
|
+
features_extractor_kwargs = dict(features_dim=32, n_tokens=n_tokens),
|
|
46
|
+
net_arch=dict(pi=[], vf=[]),
|
|
47
|
+
share_features_extractor=True,
|
|
48
|
+
),
|
|
49
|
+
verbose = 10,
|
|
50
|
+
tensorboard_log = f"{save_dir}/runs/"
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
model = PPO(**config)
|
|
54
|
+
|
|
55
|
+
print("Total number of parameters:", sum(p.numel() for p in model.policy.parameters() if p.requires_grad))
|
|
56
|
+
print(model.policy)
|
|
57
|
+
|
|
58
|
+
callback_list = []
|
|
59
|
+
logger_callback = LoggerCallback(gamma=config["gamma"])
|
|
60
|
+
callback_list.append(logger_callback)
|
|
61
|
+
if eval_env is not None:
|
|
62
|
+
stop_train_callback = StopTrainingOnNoModelImprovement(max_no_improvement_evals=10, min_evals=20, verbose=1)
|
|
63
|
+
eval_callback = EvalCallback(eval_env, eval_freq=1000, callback_after_eval=stop_train_callback, verbose=1)
|
|
64
|
+
callback_list.append(eval_callback)
|
|
65
|
+
model.learn(10_000_000, callback=callback_list)
|
|
66
|
+
model.save(f"{save_dir}/{id}")
|
|
67
|
+
|
|
68
|
+
if __name__ == "__main__":
|
|
69
|
+
from stable_baselines3.common.env_util import make_vec_env
|
|
70
|
+
from stable_baselines3.common.env_checker import check_env
|
|
71
|
+
|
|
72
|
+
n_envs = 16
|
|
73
|
+
env_id = "DFAEnv-v1"
|
|
74
|
+
encoder_id = env_id + "-encoder"
|
|
75
|
+
save_dir = "storage"
|
|
76
|
+
|
|
77
|
+
env = gym.make(env_id)
|
|
78
|
+
check_env(env)
|
|
79
|
+
|
|
80
|
+
n_tokens = env.unwrapped.sampler.n_tokens
|
|
81
|
+
|
|
82
|
+
train_env = make_vec_env(env_id, n_envs=n_envs)
|
|
83
|
+
eval_env = gym.make(env_id)
|
|
84
|
+
|
|
85
|
+
Encoder.train(n_tokens=n_tokens, train_env=train_env, eval_env=eval_env, save_dir=save_dir, id=encoder_id)
|
|
86
|
+
|
|
87
|
+
sampler = env.unwrapped.sampler
|
|
88
|
+
encoder = Encoder(load_file=f"{save_dir}/{encoder_id}")
|
|
89
|
+
|
|
90
|
+
dfa = sampler.sample()
|
|
91
|
+
print(dfa)
|
|
92
|
+
|
|
93
|
+
rad = encoder.dfa2rad(dfa)
|
|
94
|
+
print(rad)
|
|
95
|
+
|
|
96
|
+
token = encoder.rad2token(rad)
|
|
97
|
+
print(token)
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import torch.nn as nn
|
|
3
|
+
from torch_geometric.nn import GATv2Conv
|
|
4
|
+
|
|
5
|
+
class Model(nn.Module):
|
|
6
|
+
def __init__(self, input_dim, output_dim, **kwargs):
|
|
7
|
+
super().__init__()
|
|
8
|
+
self.input_dim = input_dim
|
|
9
|
+
self.output_dim = output_dim
|
|
10
|
+
self.hidden_dim = kwargs.get("hidden_dim", 64)
|
|
11
|
+
self.num_layers = kwargs.get("num_layers", 8)
|
|
12
|
+
self.n_heads = kwargs.get("n_heads", 4)
|
|
13
|
+
self.linear_in = nn.Linear(self.input_dim, self.hidden_dim)
|
|
14
|
+
self.conv = GATv2Conv(2*self.hidden_dim, self.hidden_dim, heads=self.n_heads, add_self_loops=False)
|
|
15
|
+
self.activation = nn.Tanh()
|
|
16
|
+
self.g_embed = nn.Linear(self.hidden_dim, self.output_dim)
|
|
17
|
+
|
|
18
|
+
def forward(self, data):
|
|
19
|
+
feat = data.feat
|
|
20
|
+
edge_index = data.edge_index
|
|
21
|
+
current_state = data.current_state
|
|
22
|
+
h_0 = self.linear_in(feat.float())
|
|
23
|
+
h = h_0
|
|
24
|
+
for i in range(self.num_layers):
|
|
25
|
+
h = self.conv(torch.cat([h, h_0], dim=1), edge_index).view(h.shape[0], self.n_heads, self.hidden_dim).sum(dim=1)
|
|
26
|
+
h = self.activation(h)
|
|
27
|
+
hg = h[current_state.bool()]
|
|
28
|
+
return self.g_embed(hg)
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import token_env
|
|
3
|
+
import gymnasium as gym
|
|
4
|
+
from encoder import Encoder
|
|
5
|
+
from dfa_gym import DFAWrapper
|
|
6
|
+
from stable_baselines3 import PPO
|
|
7
|
+
from utils import TokenEnvFeaturesExtractor, LoggerCallback
|
|
8
|
+
from stable_baselines3.common.env_util import make_vec_env
|
|
9
|
+
from stable_baselines3.common.env_checker import check_env
|
|
10
|
+
from dfa_samplers import ReachSampler, ReachAvoidSampler, RADSampler
|
|
11
|
+
|
|
12
|
+
# import wandb
|
|
13
|
+
# from wandb.integration.sb3 import WandbCallback
|
|
14
|
+
|
|
15
|
+
# run = wandb.init(project="sb3", sync_tensorboard=True)
|
|
16
|
+
|
|
17
|
+
n_envs = 16
|
|
18
|
+
env_id = "TokenEnv-v0"
|
|
19
|
+
|
|
20
|
+
env = gym.make(env_id)
|
|
21
|
+
check_env(env)
|
|
22
|
+
n_tokens = env.unwrapped.n_tokens
|
|
23
|
+
|
|
24
|
+
# env_kwargs = dict(env_id = "TokenEnv-v0", sampler=RADSampler(n_tokens=n_tokens), label_f=token_env.TokenEnv.label_f)
|
|
25
|
+
env_kwargs = dict(env_id = "TokenEnv-v0", sampler=ReachAvoidSampler(n_tokens=n_tokens, max_size=4, prob_stutter=1.0), label_f=token_env.TokenEnv.label_f)
|
|
26
|
+
env = make_vec_env(DFAWrapper, env_kwargs=env_kwargs, n_envs=n_envs)
|
|
27
|
+
|
|
28
|
+
encoder = Encoder(load_file="storage/DFAEnv-v0-encoder")
|
|
29
|
+
|
|
30
|
+
config = dict(
|
|
31
|
+
policy = "MultiInputPolicy",
|
|
32
|
+
env = env,
|
|
33
|
+
n_steps = 128,
|
|
34
|
+
batch_size = 256,
|
|
35
|
+
gamma = 0.99,
|
|
36
|
+
policy_kwargs = dict(
|
|
37
|
+
features_extractor_class=TokenEnvFeaturesExtractor,
|
|
38
|
+
features_extractor_kwargs=dict(features_dim=1056, encoder=encoder),
|
|
39
|
+
net_arch=dict(pi=[64, 64, 64], vf=[64, 64]),
|
|
40
|
+
share_features_extractor=True,
|
|
41
|
+
activation_fn=torch.nn.ReLU
|
|
42
|
+
),
|
|
43
|
+
verbose = 10,
|
|
44
|
+
tensorboard_log = f"token_env_reach_avoid_policy/runs/"
|
|
45
|
+
# tensorboard_log = f"token_env_reach_avoid_policy/runs/{run.id}"
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
model = PPO(**config)
|
|
49
|
+
|
|
50
|
+
print("Total number of parameters:", sum(p.numel() for p in model.policy.parameters() if p.requires_grad))
|
|
51
|
+
print(model.policy)
|
|
52
|
+
|
|
53
|
+
logger_callback = LoggerCallback(gamma=config["gamma"])
|
|
54
|
+
# wandb_callback = WandbCallback(
|
|
55
|
+
# gradient_save_freq=100,
|
|
56
|
+
# model_save_freq=100,
|
|
57
|
+
# model_save_path=f"token_env_reach_avoid_policy/models/{run.id}",
|
|
58
|
+
# verbose=config["verbose"])
|
|
59
|
+
|
|
60
|
+
# model.learn(10_000_000, callback=[logger_callback, wandb_callback])
|
|
61
|
+
model.learn(1_000_000, callback=[logger_callback])
|
|
62
|
+
model.save("token_env_reach_avoid_policy/token_env_reach_avoid_policy")
|
|
63
|
+
|
|
64
|
+
# run.finish()
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from model import Model
|
|
2
|
+
from utils.utils import feature_inds, obs2feat
|
|
3
|
+
from stable_baselines3.common.torch_layers import BaseFeaturesExtractor
|
|
4
|
+
|
|
5
|
+
class DFAEnvFeaturesExtractor(BaseFeaturesExtractor):
|
|
6
|
+
def __init__(self, observation_space, features_dim, model_cls=Model, n_tokens=10):
|
|
7
|
+
super().__init__(observation_space, features_dim)
|
|
8
|
+
in_feat_size = n_tokens + len(feature_inds)
|
|
9
|
+
self.model = model_cls(in_feat_size, features_dim)
|
|
10
|
+
self.n_tokens = n_tokens
|
|
11
|
+
|
|
12
|
+
def forward(self, obs):
|
|
13
|
+
feat = obs2feat(obs, n_tokens=self.n_tokens)
|
|
14
|
+
return self.model(feat)
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from collections import deque
|
|
3
|
+
from stable_baselines3.common.callbacks import BaseCallback
|
|
4
|
+
|
|
5
|
+
class LoggerCallback(BaseCallback):
|
|
6
|
+
def __init__(self, gamma=0.9):
|
|
7
|
+
super().__init__()
|
|
8
|
+
self.gamma = gamma
|
|
9
|
+
self.n = 100
|
|
10
|
+
self.rewards = deque(maxlen=self.n)
|
|
11
|
+
self.discounted_rewards = deque(maxlen=self.n)
|
|
12
|
+
self.episode_lengths = deque(maxlen=self.n)
|
|
13
|
+
|
|
14
|
+
def _on_step(self):
|
|
15
|
+
# Log scalar value (here a random variable)
|
|
16
|
+
dones = self.locals["dones"]
|
|
17
|
+
infos = self.locals["infos"]
|
|
18
|
+
|
|
19
|
+
for idx, done in enumerate(dones):
|
|
20
|
+
info = infos[idx]
|
|
21
|
+
if (
|
|
22
|
+
done
|
|
23
|
+
and info.get("episode") is not None
|
|
24
|
+
):
|
|
25
|
+
episode_info = info["episode"]
|
|
26
|
+
reward = info["episode"]['r']
|
|
27
|
+
episode_length = info["episode"]['l']
|
|
28
|
+
t = episode_length - 1
|
|
29
|
+
discounted_reward = reward * (self.gamma ** t)
|
|
30
|
+
self.rewards.append(reward)
|
|
31
|
+
self.discounted_rewards.append(discounted_reward)
|
|
32
|
+
self.episode_lengths.append(episode_length)
|
|
33
|
+
|
|
34
|
+
return True
|
|
35
|
+
|
|
36
|
+
def _on_rollout_end(self):
|
|
37
|
+
ep_len_min = np.min(self.episode_lengths)
|
|
38
|
+
ep_len_max = np.max(self.episode_lengths)
|
|
39
|
+
ep_len_std = np.std(self.episode_lengths)
|
|
40
|
+
ep_rew_min = np.min(self.rewards)
|
|
41
|
+
ep_rew_max = np.max(self.rewards)
|
|
42
|
+
ep_rew_std = np.std(self.rewards)
|
|
43
|
+
ep_disc_rew_mean = np.mean(self.discounted_rewards)
|
|
44
|
+
self.logger.record("rollout/ep_len_min", ep_len_min)
|
|
45
|
+
self.logger.record("rollout/ep_len_max", ep_len_max)
|
|
46
|
+
self.logger.record("rollout/ep_len_std", ep_len_std)
|
|
47
|
+
self.logger.record("rollout/ep_rew_min", ep_rew_min)
|
|
48
|
+
self.logger.record("rollout/ep_rew_max", ep_rew_max)
|
|
49
|
+
self.logger.record("rollout/ep_rew_std", ep_rew_std)
|
|
50
|
+
self.logger.record("rollout/ep_rew_disc_mean", ep_disc_rew_mean)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
from torch import nn
|
|
3
|
+
from model import Model
|
|
4
|
+
from stable_baselines3.common.torch_layers import BaseFeaturesExtractor
|
|
5
|
+
|
|
6
|
+
class TokenEnvFeaturesExtractor(BaseFeaturesExtractor):
|
|
7
|
+
def __init__(self, observation_space, features_dim, encoder):
|
|
8
|
+
super().__init__(observation_space, features_dim)
|
|
9
|
+
self.encoder = encoder
|
|
10
|
+
c, w, h = observation_space["obs"].shape # CxWxH
|
|
11
|
+
self.image_conv = nn.Sequential(
|
|
12
|
+
nn.Conv2d(c, 16, (2, 2)),
|
|
13
|
+
nn.ReLU(),
|
|
14
|
+
nn.Conv2d(16, 32, (2, 2)),
|
|
15
|
+
nn.ReLU(),
|
|
16
|
+
nn.Conv2d(32, 64, (2, 2)),
|
|
17
|
+
nn.ReLU(),
|
|
18
|
+
nn.Flatten()
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
def forward(self, dict_obs):
|
|
22
|
+
dfa_obs = dict_obs["dfa_obs"]
|
|
23
|
+
obs = dict_obs["obs"]
|
|
24
|
+
rad = self.encoder.obs2rad(dfa_obs)
|
|
25
|
+
obs = self.image_conv(obs)
|
|
26
|
+
obs = torch.cat((obs, rad), dim=1)
|
|
27
|
+
return obs
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import numpy as np
|
|
3
|
+
from dfa import DFA
|
|
4
|
+
from dfa.utils import dfa2dict
|
|
5
|
+
from stable_baselines3 import PPO
|
|
6
|
+
from collections import OrderedDict
|
|
7
|
+
from torch_geometric.data import Data
|
|
8
|
+
from torch_geometric.data import Batch
|
|
9
|
+
from dfa.utils import min_distance_to_accept_by_state
|
|
10
|
+
|
|
11
|
+
feature_inds = {"temp": -5, "rejecting": -4, "accepting": -3, "init": -2, "normal": -1}
|
|
12
|
+
|
|
13
|
+
def obs2feat(dfa_obs, n_tokens):
|
|
14
|
+
if dfa_obs.ndim == 1:
|
|
15
|
+
return _obs2feat(dfa_obs, n_tokens=n_tokens)
|
|
16
|
+
elif dfa_obs.ndim == 2:
|
|
17
|
+
return Batch.from_data_list(list(map(lambda x: _obs2feat(x, n_tokens=n_tokens), dfa_obs)))
|
|
18
|
+
else:
|
|
19
|
+
raise ValueError(f"Invalid ndim for dfa_obs: expected 1 or 2, but got {dfa_obs.ndim}")
|
|
20
|
+
|
|
21
|
+
def _obs2feat(dfa_obs, n_tokens):
|
|
22
|
+
tokens = list(range(n_tokens))
|
|
23
|
+
feature_size = len(tokens) + len(feature_inds)
|
|
24
|
+
dfa_int = int("".join(map(str, map(int, dfa_obs.squeeze().tolist()))))
|
|
25
|
+
dfa = DFA.from_int(dfa_int, tokens)
|
|
26
|
+
dfa_dict, s_init = dfa2dict(dfa)
|
|
27
|
+
nodes = OrderedDict({s: np.zeros(feature_size) for s in dfa_dict.keys()})
|
|
28
|
+
if len(nodes) == 1:
|
|
29
|
+
edges = [(0, 0)]
|
|
30
|
+
else:
|
|
31
|
+
edges = [(s, s) for s in nodes]
|
|
32
|
+
for s in dfa_dict.keys():
|
|
33
|
+
label, transitions = dfa_dict[s]
|
|
34
|
+
leaving_transitions = [1 if s != transitions[a] else 0 for a in transitions.keys()]
|
|
35
|
+
if s not in nodes:
|
|
36
|
+
nodes[s] = np.zeros(feature_size)
|
|
37
|
+
nodes[s][feature_inds["normal"]] = 1
|
|
38
|
+
if s == s_init:
|
|
39
|
+
nodes[s][feature_inds["init"]] = 1
|
|
40
|
+
if label: # is accepting?
|
|
41
|
+
nodes[s][feature_inds["accepting"]] = 1
|
|
42
|
+
elif sum(leaving_transitions) == 0: # is rejecting?
|
|
43
|
+
nodes[s][feature_inds["rejecting"]] = 1
|
|
44
|
+
for e in dfa_dict.keys():
|
|
45
|
+
if s == e:
|
|
46
|
+
continue
|
|
47
|
+
for a in transitions:
|
|
48
|
+
if transitions[a] == e:
|
|
49
|
+
if (s, e) not in nodes:
|
|
50
|
+
nodes[(s, e)] = np.zeros(feature_size)
|
|
51
|
+
nodes[(s, e)][feature_inds["temp"]] = 1
|
|
52
|
+
nodes[(s, e)][a] = 1
|
|
53
|
+
s_idx = list(nodes.keys()).index(s)
|
|
54
|
+
t_idx = list(nodes.keys()).index((s, e))
|
|
55
|
+
e_idx = list(nodes.keys()).index(e)
|
|
56
|
+
# Reverse
|
|
57
|
+
if (e_idx, t_idx) not in edges:
|
|
58
|
+
edges.append((e_idx, t_idx))
|
|
59
|
+
if (t_idx, t_idx) not in edges:
|
|
60
|
+
edges.append((t_idx, t_idx))
|
|
61
|
+
if (t_idx, s_idx) not in edges:
|
|
62
|
+
edges.append((t_idx, s_idx))
|
|
63
|
+
feat = torch.from_numpy(np.array(list(nodes.values())))
|
|
64
|
+
edge_index = torch.from_numpy(np.array(edges))
|
|
65
|
+
current_state = torch.from_numpy(np.array([1] + [0] * (len(nodes) - 1))) # 0 is the current state
|
|
66
|
+
return Data(feat=feat, edge_index=edge_index.T, current_state=current_state)
|
|
67
|
+
|
|
68
|
+
def dfa2obs(dfa: DFA) -> Data:
|
|
69
|
+
return np.array([int(i) for i in str(dfa.to_int())])
|
|
70
|
+
|
|
71
|
+
def dfa2dist(dfa_obs, n_tokens):
|
|
72
|
+
tokens = list(range(n_tokens))
|
|
73
|
+
feature_size = len(tokens) + len(feature_inds)
|
|
74
|
+
|
|
75
|
+
dfa_int = int("".join(map(str, map(int, dfa_obs.squeeze().tolist()))))
|
|
76
|
+
dfa = DFA.from_int(dfa_int, tokens)
|
|
77
|
+
|
|
78
|
+
n = len(dfa.states())
|
|
79
|
+
|
|
80
|
+
dist = min_distance_to_accept_by_state(dfa)[0]
|
|
81
|
+
|
|
82
|
+
if dist == float("inf"):
|
|
83
|
+
dist = 0
|
|
84
|
+
|
|
85
|
+
return dist
|