Skip to content

Commit f2011c4

Browse files
Update dependencies (#209)
* Updating minor packages * Updating pytorch * Updating numpy
1 parent dd9fcb6 commit f2011c4

18 files changed

Lines changed: 88 additions & 88 deletions

File tree

.pre-commit-config.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
repos:
1111
- repo: https://github.com/pre-commit/pre-commit-hooks
12-
rev: v5.0.0
12+
rev: v6.0.0
1313
hooks:
1414
- id: check-ast
1515
- id: check-yaml
@@ -26,7 +26,7 @@ repos:
2626
- id: double-quote-string-fixer
2727

2828
- repo: https://github.com/pycqa/isort
29-
rev: 6.0.1
29+
rev: 6.1.0
3030
hooks:
3131
- id: isort
3232
name: isort

examples/rl/train_rl_model.sh

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ SYS='cartpole'
44
# SYS='quadrotor_2D'
55
# SYS='quadrotor_3D'
66

7-
TASK='stab'
8-
# TASK='track'
7+
# TASK='stab'
8+
TASK='track'
99

1010
ALGO='ppo'
1111
# ALGO='sac'

pyproject.toml

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,27 +7,27 @@ license = "MIT"
77

88
[tool.poetry.dependencies]
99
python = "^3.10"
10-
matplotlib = "^3.5.1"
11-
munch = "^2.5.0"
10+
matplotlib = "^3.10"
11+
munch = "^4.0"
1212
PyYAML = "^6.0"
13-
imageio = "^2.14.1"
14-
dict-deep = "^4.1.2"
15-
scikit-optimize = "^0.9.0"
16-
scikit-learn = "^1.3.0"
13+
imageio = "^2.37"
14+
dict-deep = "^4.1"
15+
scikit-optimize = "^0.10"
16+
scikit-learn = "^1.7"
1717
gymnasium = "^0.28"
18-
torch = "^1.10.2"
19-
gpytorch = "^1.6.0"
20-
tensorboard = "^2.12.0"
21-
casadi = "^3.6.0"
22-
pybullet = "^3.2.0"
23-
numpy = "^1.22.1"
24-
cvxpy = "^1.1.18"
25-
pycddlib = "^2.1.7"
18+
torch = "^2.8"
19+
gpytorch = "^1.14"
20+
tensorboard = "^2.20"
21+
casadi = "^3.7"
22+
pybullet = "^3.2"
23+
numpy = "^2.2"
24+
cvxpy = "^1.7"
25+
pycddlib = "^2.1"
2626
pytope = "^0.0.4"
27-
Mosek = "^10.0.18"
28-
termcolor = "^1.1.0"
29-
pytest = "^7.2.2"
30-
pre-commit = "^3.3.2"
27+
Mosek = "^11.0"
28+
termcolor = "^3.1"
29+
pytest = "^8.4"
30+
pre-commit = "^4.3"
3131
optuna = "^3.0"
3232
optuna-dashboard = "^0.9"
3333
mysql-connector-python = "8.0.33"
@@ -36,5 +36,5 @@ pymysql = "1.1.1"
3636
[tool.poetry.dev-dependencies]
3737

3838
[build-system]
39-
requires = ["poetry-core @ git+https://github.com/python-poetry/poetry-core.git@main"]
39+
requires = ["poetry-core"]
4040
build-backend = "poetry.core.masonry.api"

safe_control_gym/controllers/base_controller.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def __init__(self,
4242
self.__dict__[key] = value
4343

4444
self.use_gpu = self.use_gpu and torch.cuda.is_available()
45-
self.device = 'cpu' if self.use_gpu is False else 'cuda'
45+
self.device = torch.device('cuda' if self.use_gpu and torch.cuda.is_available() else 'cpu')
4646

4747
self.setup_results_dict()
4848

safe_control_gym/controllers/ddpg/ddpg.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ def save(self, path, save_buffer=True):
142142

143143
def load(self, path):
144144
'''Restores model and experiment given checkpoint path.'''
145-
state = torch.load(path)
145+
state = torch.load(path, weights_only=False) # Safe since we're loading our own models
146146

147147
# restore params
148148
self.agent.load_state_dict(state['agent'])
@@ -194,7 +194,7 @@ def learn(self, env=None, **kwargs):
194194
eval_results['ep_returns'].std()))
195195
# save best model
196196
eval_score = eval_results['ep_returns'].mean()
197-
eval_best_score = getattr(self, 'eval_best_score', -np.infty)
197+
eval_best_score = getattr(self, 'eval_best_score', -np.inf)
198198
if self.eval_save_best and eval_best_score < eval_score:
199199
self.eval_best_score = eval_score
200200
self.save(os.path.join(self.output_dir, 'model_best.pt'))
@@ -214,7 +214,7 @@ def select_action(self, obs, info=None):
214214
action (ndarray): The action chosen by the controller.
215215
'''
216216

217-
with torch.no_grad():
217+
with torch.inference_mode():
218218
obs = torch.FloatTensor(obs).to(self.device)
219219
action = self.agent.ac.act(obs)
220220

@@ -278,7 +278,7 @@ def train_step(self, **kwargs):
278278
if self.total_steps < self.warm_up_steps:
279279
act = np.stack([self.env.action_space.sample() for _ in range(self.rollout_batch_size)])
280280
else:
281-
with torch.no_grad():
281+
with torch.inference_mode():
282282
act = self.agent.ac.act(torch.FloatTensor(obs).to(self.device))
283283
# apply action noise if specified in training config
284284
if self.noise_process:

safe_control_gym/controllers/ddpg/ddpg_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ def unscale_fn(x): # Rescale action from [-1, 1] to [low, high]
172172

173173
def act(self, obs, **kwargs):
174174
a = self.actor(obs)
175-
return a.cpu().numpy()
175+
return a.cpu().numpy().astype(np.float32)
176176

177177

178178
# -----------------------------------------------------------------------------------

safe_control_gym/controllers/mpc/gp_utils.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -670,11 +670,11 @@ def init_with_hyperparam(self,
670670
if self.target_mask is not None:
671671
train_targets = train_targets[:, self.target_mask]
672672
device = torch.device('cpu')
673-
state_dict = torch.load(path_to_statedict, map_location=device)
673+
state_dict = torch.load(path_to_statedict, map_location=device, _use_new_zipfile_serialization=True)
674674
self._init_model(train_inputs, train_targets)
675675

676676
self.model.load_state_dict(state_dict)
677-
self.model.double() # needed otherwise loads state_dict as float32
677+
self.model = self.model.to(dtype=torch.float64) # needed otherwise loads state_dict as float32
678678
self._compute_GP_covariances(train_inputs)
679679
self.casadi_predict = self.make_casadi_prediction_func(train_inputs, train_targets)
680680

@@ -724,8 +724,8 @@ def train(self,
724724
test_y = test_y.cuda()
725725
self.model = self.model.cuda()
726726
self.likelihood = self.likelihood.cuda()
727-
self.model.double()
728-
self.likelihood.double()
727+
self.model = self.model.to(dtype=torch.float64)
728+
self.likelihood = self.likelihood.to(dtype=torch.float64)
729729
self.model.train()
730730
self.likelihood.train()
731731
self.optimizer = torch.optim.Adam(self.model.parameters(), lr=learning_rate)
@@ -735,7 +735,7 @@ def train(self,
735735
loss = torch.tensor(0)
736736
i = 0
737737
while i < n_train and torch.abs(loss - last_loss) > 1e-2:
738-
with torch.no_grad():
738+
with torch.inference_mode():
739739
self.model.eval()
740740
self.likelihood.eval()
741741
test_output = self.model(test_x.unsqueeze(0).repeat(self.output_dimension, 1, 1))
@@ -754,7 +754,7 @@ def train(self,
754754
if test_loss < best_loss:
755755
best_loss = test_loss
756756
state_dict = self.model.state_dict()
757-
torch.save(state_dict, fname)
757+
torch.save(state_dict, fname, _use_new_zipfile_serialization=True)
758758
best_epoch = i
759759

760760
i += 1
@@ -765,7 +765,7 @@ def train(self,
765765
self.likelihood = self.likelihood.cpu()
766766
train_x = train_x.cpu()
767767
train_y = train_y.cpu()
768-
self.model.load_state_dict(torch.load(fname))
768+
self.model.load_state_dict(torch.load(fname, weights_only=False))
769769
self._compute_GP_covariances(train_x)
770770
self.casadi_predict = self.make_casadi_prediction_func(train_x, train_y)
771771

@@ -791,7 +791,7 @@ def predict(self,
791791
self.model.eval()
792792
self.likelihood.eval()
793793
if isinstance(x, np.ndarray):
794-
x = torch.from_numpy(x).double()
794+
x = torch.tensor(x, dtype=torch.float64)
795795
if self.input_mask is not None:
796796
x = x[:, self.input_mask]
797797
if requires_grad:
@@ -986,12 +986,12 @@ def init_with_hyperparam(self,
986986
if self.target_mask is not None:
987987
train_targets = train_targets[:, self.target_mask]
988988
device = torch.device('cpu')
989-
state_dict = torch.load(path_to_statedict, map_location=device)
989+
state_dict = torch.load(path_to_statedict, map_location=device, _use_new_zipfile_serialization=True)
990990
self._init_model(train_inputs, train_targets)
991991
if self.NORMALIZE:
992992
train_inputs = torch.from_numpy(self.scaler.transform(train_inputs.numpy()))
993993
self.model.load_state_dict(state_dict)
994-
self.model.double() # needed otherwise loads state_dict as float32
994+
self.model = self.model.to(dtype=torch.float64) # needed otherwise loads state_dict as float32
995995
self._compute_GP_covariances(train_inputs)
996996
self.casadi_predict = self.make_casadi_prediction_func(train_inputs, train_targets)
997997

@@ -1045,8 +1045,8 @@ def train(self,
10451045
test_y = test_y.cuda()
10461046
self.model = self.model.cuda()
10471047
self.likelihood = self.likelihood.cuda()
1048-
self.model.double()
1049-
self.likelihood.double()
1048+
self.model = self.model.to(dtype=torch.float64)
1049+
self.likelihood = self.likelihood.to(dtype=torch.float64)
10501050
self.model.train()
10511051
self.likelihood.train()
10521052
self.optimizer = torch.optim.Adam(self.model.parameters(), lr=learning_rate)
@@ -1056,7 +1056,7 @@ def train(self,
10561056
loss = torch.tensor(0)
10571057
i = 0
10581058
while i < n_train and torch.abs(loss - last_loss) > 1e-2:
1059-
with torch.no_grad():
1059+
with torch.inference_mode():
10601060
self.model.eval()
10611061
self.likelihood.eval()
10621062
test_output = self.model(test_x)
@@ -1074,7 +1074,7 @@ def train(self,
10741074
if test_loss < best_loss:
10751075
best_loss = test_loss
10761076
state_dict = self.model.state_dict()
1077-
torch.save(state_dict, fname)
1077+
torch.save(state_dict, fname, _use_new_zipfile_serialization=True)
10781078
best_epoch = i
10791079

10801080
i += 1
@@ -1085,7 +1085,7 @@ def train(self,
10851085
self.likelihood = self.likelihood.cpu()
10861086
train_x = train_x.cpu()
10871087
train_y = train_y.cpu()
1088-
self.model.load_state_dict(torch.load(fname))
1088+
self.model.load_state_dict(torch.load(fname, weights_only=False))
10891089
self._compute_GP_covariances(train_x)
10901090
self.casadi_predict = self.make_casadi_prediction_func(train_x, train_y)
10911091

@@ -1109,7 +1109,7 @@ def predict(self,
11091109
self.model.eval()
11101110
self.likelihood.eval()
11111111
if isinstance(x, np.ndarray):
1112-
x = torch.from_numpy(x).double()
1112+
x = torch.tensor(x, dtype=torch.float64)
11131113
if self.input_mask is not None:
11141114
x = x[:, self.input_mask]
11151115
if self.NORMALIZE:

safe_control_gym/controllers/ppo/ppo.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ def load(self,
134134
path
135135
):
136136
'''Restores model and experiment given checkpoint path.'''
137-
state = torch.load(path)
137+
state = torch.load(path, weights_only=False) # Safe since we're loading our own models
138138
# Restore policy.
139139
self.agent.load_state_dict(state['agent'])
140140
self.obs_normalizer.load_state_dict(state['obs_normalizer'])
@@ -182,7 +182,7 @@ def learn(self,
182182
eval_results['ep_returns'].std()))
183183
# Save best model.
184184
eval_score = eval_results['ep_returns'].mean()
185-
eval_best_score = getattr(self, 'eval_best_score', -np.infty)
185+
eval_best_score = getattr(self, 'eval_best_score', -np.inf)
186186
if self.eval_save_best and eval_best_score < eval_score:
187187
self.eval_best_score = eval_score
188188
self.save(os.path.join(self.output_dir, 'model_best.pt'))
@@ -201,7 +201,7 @@ def select_action(self, obs, info=None):
201201
action (ndarray): The action chosen by the controller.
202202
'''
203203

204-
with torch.no_grad():
204+
with torch.inference_mode():
205205
obs = torch.FloatTensor(obs).to(self.device)
206206
action = self.agent.ac.act(obs)
207207

@@ -264,7 +264,7 @@ def train_step(self):
264264
obs = self.obs
265265
start = time.time()
266266
for _ in range(self.rollout_steps):
267-
with torch.no_grad():
267+
with torch.inference_mode():
268268
act, v, logp = self.agent.ac.step(torch.FloatTensor(obs).to(self.device))
269269
next_obs, rew, done, info = self.env.step(act)
270270
next_obs = self.obs_normalizer(next_obs)

safe_control_gym/controllers/ppo/ppo_utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ def act(self,
235235
):
236236
dist, _ = self.actor(obs)
237237
action = dist.mode()
238-
return action.cpu().numpy()
238+
return action.cpu().numpy().astype(np.float32)
239239

240240

241241
class PPOBuffer(object):
@@ -303,7 +303,7 @@ def reset(self):
303303
vshape = info['vshape']
304304
dtype = info.get('dtype', np.float32)
305305
init = info.get('init', np.zeros)
306-
self.__dict__[k] = init(vshape, dtype=dtype)
306+
self.__dict__[k] = init(vshape).astype(dtype)
307307
self.t = 0
308308

309309
def push(self,

safe_control_gym/controllers/rarl/rap.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ def save(self, path):
143143

144144
def load(self, path):
145145
'''Restores model and experiment given checkpoint path.'''
146-
state = torch.load(path)
146+
state = torch.load(path, weights_only=False) # Safe since we're loading our own models
147147

148148
# restore pllicy
149149
self.agent.load_state_dict(state['agent'])
@@ -185,7 +185,7 @@ def learn(self, env=None, **kwargs):
185185
eval_results['ep_returns'].std()))
186186
# save best model
187187
eval_score = eval_results['ep_returns'].mean()
188-
eval_best_score = getattr(self, 'eval_best_score', -np.infty)
188+
eval_best_score = getattr(self, 'eval_best_score', -np.inf)
189189
if self.eval_save_best and eval_best_score < eval_score:
190190
self.eval_best_score = eval_score
191191
self.save(os.path.join(self.output_dir, 'model_best.pt'))
@@ -215,14 +215,14 @@ def run(self, env=None, render=False, n_episodes=10, verbose=False, use_adv=Fals
215215
frames = []
216216

217217
while len(ep_returns) < n_episodes:
218-
with torch.no_grad():
218+
with torch.inference_mode():
219219
obs = torch.FloatTensor(obs).to(self.device)
220220
action = self.agent.ac.act(obs)
221221

222222
# no disturbance during testing
223223
if use_adv:
224224
adv_idx = np.random.choice(self.num_adversaries)
225-
with torch.no_grad():
225+
with torch.inference_mode():
226226
action_adv = self.adversaries[adv_idx].ac.act(obs)
227227
else:
228228
action_adv = np.zeros(self.adv_act_space.shape[0])
@@ -362,7 +362,7 @@ def collect_rollouts(self):
362362

363363
for _ in range(self.rollout_steps):
364364
# get actions
365-
with torch.no_grad():
365+
with torch.inference_mode():
366366
act, v, logp = self.agent.ac.step(torch.FloatTensor(obs).to(self.device))
367367

368368
# adversary actions

0 commit comments

Comments
 (0)