env-ssl-wrapper 0.5.4__tar.gz → 0.5.5__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 (26) hide show
  1. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/PKG-INFO +1 -1
  2. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/action_chunk.py +6 -4
  3. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/evaluate.py +34 -22
  4. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/memory_trace.py +21 -2
  5. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/standardize/action_transform_wrapper.py +16 -17
  6. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/standardize/adapters.py +23 -95
  7. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/standardize/auto_batched_wrapper.py +4 -11
  8. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/standardize/episode_padding_wrapper.py +15 -5
  9. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/standardize/flatten_obs_wrapper.py +1 -1
  10. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/standardize/helpers.py +8 -21
  11. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/standardize/image_wrapper.py +8 -9
  12. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/standardize/standardize_env_wrapper.py +2 -1
  13. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/standardize/standardize_wrapper.py +3 -6
  14. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/standardize/tensor_wrapper.py +2 -4
  15. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/standardize/time_limit_wrapper.py +1 -1
  16. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/standardize/vector.py +11 -6
  17. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/pyproject.toml +1 -1
  18. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/.gitignore +0 -0
  19. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/LICENSE +0 -0
  20. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/README.md +0 -0
  21. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/__init__.py +0 -0
  22. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/standardize/__init__.py +0 -0
  23. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/standardize/done_tracker_wrapper.py +0 -0
  24. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/standardize/mocks.py +0 -0
  25. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/standardize/spaces.py +0 -0
  26. {env_ssl_wrapper-0.5.4 → env_ssl_wrapper-0.5.5}/env_ssl_wrapper/standardize/utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: env-ssl-wrapper
3
- Version: 0.5.4
3
+ Version: 0.5.5
4
4
  Summary: One torch-native interface for any MDP environment
5
5
  Project-URL: Homepage, https://pypi.org/project/env-ssl-wrapper/
6
6
  Project-URL: Repository, https://codeberg.org/lucidrains/env-ssl-wrapper
@@ -7,15 +7,17 @@ from torch import is_tensor
7
7
 
8
8
  from .standardize.helpers import (
9
9
  EnvWrapper,
10
+ any_true,
10
11
  copy_leaf,
11
12
  default,
12
- any_true,
13
13
  dones_of,
14
14
  env_takes_torch,
15
15
  first_existing,
16
16
  get_adapter,
17
17
  get_attr,
18
18
  is_vectorized,
19
+ normalize_reset_out,
20
+ normalize_step_out,
19
21
  to_numpy,
20
22
  )
21
23
 
@@ -72,7 +74,7 @@ class ActionChunkWrapper(EnvWrapper):
72
74
 
73
75
  # vectorized gym envs expose a batched action space - the single env space defines the chunk layout
74
76
 
75
- action_space = first_existing(env, 'single_action_space', 'action_space')
77
+ action_space = default(first_existing(env, 'single_action_space', 'action_space'), get_adapter(env).action_space)
76
78
  self.action_shape = tuple(get_attr(action_space, 'shape', ()) or ())
77
79
 
78
80
  self.expects_batch = is_vectorized(env)
@@ -83,7 +85,7 @@ class ActionChunkWrapper(EnvWrapper):
83
85
  return (self.chunk_len, *self.action_shape)
84
86
 
85
87
  def reset(self, **kwargs):
86
- return self.env.reset(**kwargs)
88
+ return normalize_reset_out(self.env.reset(**kwargs))
87
89
 
88
90
  def step(self, actions):
89
91
  if isinstance(actions, dict):
@@ -114,7 +116,7 @@ class ActionChunkWrapper(EnvWrapper):
114
116
  if not self.expects_batch:
115
117
  action = unbatch_step(action)
116
118
 
117
- out = self.env.step(action)
119
+ out = normalize_step_out(self.env.step(action))
118
120
  rewards.append(copy_leaf(out[1]))
119
121
 
120
122
  if any_true(dones_of(out[2], out[3])):
@@ -6,12 +6,11 @@ from typing import NamedTuple
6
6
  import numpy as np
7
7
  import torch
8
8
  from torch import nn, is_tensor
9
- from torch.distributions import Categorical, Distribution
10
- from torch.utils._pytree import tree_flatten, tree_map
9
+ from torch.distributions import Bernoulli, Categorical, Distribution
10
+ from torch.utils._pytree import tree_map
11
11
 
12
12
  from .standardize.spaces import action_space_is_discrete
13
13
  from .standardize.helpers import (
14
- EnvWrapper,
15
14
  dones_of,
16
15
  env_autoresets,
17
16
  env_num_envs,
@@ -97,6 +96,12 @@ def to_action(env, out, deterministic = True):
97
96
  if not deterministic:
98
97
  return val.sample()
99
98
 
99
+ if isinstance(val, Bernoulli):
100
+ return (val.probs > 0.5).long()
101
+
102
+ if isinstance(val, Categorical):
103
+ return val.probs.argmax(dim = -1)
104
+
100
105
  probs = get_attr(val, 'probs')
101
106
 
102
107
  # categorical-style probs carry a trailing action axis to argmax over
@@ -171,24 +176,26 @@ def to_env_action(env, action):
171
176
  if not env_takes_torch(env):
172
177
  action = tree_map(to_numpy, action)
173
178
 
174
- # single raw sims get the leading batch dim stripped, while discrete
175
- # actions additionally collapse to scalars
179
+ # single non-vectorized envs get the leading batch dim stripped, while discrete
180
+ # actions additionally collapse to scalars
176
181
 
177
- if not is_vectorized(env) and not exists(chunk_shape):
178
- def strip_leaf(a):
179
- if a.ndim > 1 and a.shape[0] == 1:
180
- a = a[0]
182
+ if not is_vectorized(env) and not exists(chunk_shape):
183
+ is_discrete = action_space_is_discrete(get_adapter(env).action_space)
181
184
 
182
- if action_space_is_discrete(get_adapter(env).action_space):
183
- if a.ndim > 0 and a.shape[0] == 1:
184
- a = a[0]
185
+ def strip_leaf(a):
186
+ if a.ndim > 1 and a.shape[0] == 1:
187
+ a = a[0]
185
188
 
186
- if a.ndim == 0:
187
- a = a.item()
189
+ if is_discrete:
190
+ if a.ndim > 0 and a.shape[0] == 1:
191
+ a = a[0]
192
+
193
+ if a.ndim == 0:
194
+ a = a.item()
188
195
 
189
- return a
196
+ return a
190
197
 
191
- action = tree_map(strip_leaf, action)
198
+ action = tree_map(strip_leaf, action)
192
199
 
193
200
  return action
194
201
 
@@ -292,7 +299,7 @@ def evaluate_actor(
292
299
  assert not (record and num_envs > 1), 'video recording requires a single env'
293
300
 
294
301
  obs, info = safe_reset(env, seed)
295
- batched = is_vectorized(env) or all(map(is_tensor, tree_flatten(obs)[0]))
302
+ batched = is_vectorized(env)
296
303
 
297
304
  goal = goal.expand(num_envs, -1) if exists(goal) and goal.shape[0] == 1 and num_envs > 1 else goal
298
305
 
@@ -326,10 +333,12 @@ def evaluate_actor(
326
333
  if reward.numel() > num_envs:
327
334
  reward = reward.reshape(num_envs, -1).sum(dim = -1)
328
335
 
329
- returns += reward if reward.numel() == num_envs else reward.expand(num_envs)
336
+ reward = reward if reward.numel() == num_envs else reward.expand(num_envs)
337
+ active_t = torch.from_numpy(active)
330
338
 
331
- lengths += info.get('chunk_length', 1) if isinstance(info, dict) else 1
332
- steps += 1
339
+ returns += torch.where(active_t, reward, 0.)
340
+ lengths += torch.where(active_t, float(info.get('chunk_length', 1) if isinstance(info, dict) else 1), 0.)
341
+ steps += torch.where(active_t, 1, 0)
333
342
 
334
343
  done = to_numpy(dones_of(terminated, truncated)).astype(bool).reshape(-1)
335
344
 
@@ -367,15 +376,18 @@ def evaluate_actor(
367
376
  steps[i] = 0
368
377
  active[i] = False
369
378
 
370
- if done.any() and len(done_returns) < episodes:
379
+ if (done.any() or not active.any()) and len(done_returns) < episodes:
371
380
  if record:
372
381
  frames = []
373
382
 
374
383
  # autoresetting envs reset themselves, everything else resets here
375
384
 
376
- if not env_autoresets(env) and (num_envs == 1 or done.all() or bool(get_attr(env, 'needs_reset', False))):
385
+ if not env_autoresets(env) and (num_envs == 1 or not active.any() or done.all() or bool(get_attr(env, 'needs_reset', False))):
377
386
  reset_seed = seed + len(done_returns) if exists(seed) and num_envs == 1 else None
378
387
  obs, info = safe_reset(env, reset_seed)
388
+ returns.zero_()
389
+ lengths.zero_()
390
+ steps.zero_()
379
391
  active[:] = True
380
392
  elif env_autoresets(env):
381
393
  active[newly_done] = True
@@ -1,4 +1,5 @@
1
1
  from __future__ import annotations
2
+ from functools import partial
2
3
  from typing import Sequence
3
4
 
4
5
  import torch
@@ -9,9 +10,12 @@ from .standardize.helpers import (
9
10
  any_true,
10
11
  cast_tuple,
11
12
  default,
13
+ dones_of,
12
14
  exists,
13
15
  is_array_like,
14
16
  is_scalar,
17
+ maybe_transform_final_observation,
18
+ normalize_step_out,
15
19
  )
16
20
 
17
21
  # helper functions
@@ -63,7 +67,7 @@ class MemoryTraceWrapper(TransformObservationWrapper):
63
67
  prefix = self.trace_key if key == self.obs_key else f'{key}_{self.trace_key}'
64
68
  return f'{prefix}_{lam}' if len(self.lambdas) > 1 else prefix
65
69
 
66
- def transform_obs(self, obs, done = None):
70
+ def transform_obs(self, obs, done = None, update_state: bool = True):
67
71
  if isinstance(obs, (tuple, list)):
68
72
  out = {f'{self.obs_key}_{i}': elem for i, elem in enumerate(obs)}
69
73
  elif isinstance(obs, dict):
@@ -96,7 +100,8 @@ class MemoryTraceWrapper(TransformObservationWrapper):
96
100
  else:
97
101
  traces = [prev.lerp(val_float, calc_lerp_weight(lam, done, val_float)) for lam, prev in zip(self.lambdas, self.traces[key])]
98
102
 
99
- self.traces[key] = traces
103
+ if update_state:
104
+ self.traces[key] = traces
100
105
 
101
106
  for lam, trace in zip(self.lambdas, traces):
102
107
  out[self.trace_key_for(key, lam)] = trace
@@ -106,3 +111,17 @@ class MemoryTraceWrapper(TransformObservationWrapper):
106
111
  def reset(self, **kwargs):
107
112
  self.traces = dict()
108
113
  return super().reset(**kwargs)
114
+
115
+ def step(self, action):
116
+ obs, reward, terminated, truncated, info = normalize_step_out(self.env.step(action))
117
+ done = dones_of(terminated, truncated)
118
+
119
+ # terminal observations are transformed against pre-reset traces without mutating state
120
+
121
+ maybe_transform_final_observation(
122
+ info,
123
+ partial(self.transform_obs, done = None, update_state = False)
124
+ )
125
+
126
+ out = self.transform_obs(obs, done = done, update_state = True)
127
+ return out, reward, terminated, truncated, info
@@ -6,8 +6,7 @@ from torch import is_tensor
6
6
  from torch.utils._pytree import tree_map
7
7
  from functools import partial
8
8
 
9
- from .helpers import EnvWrapper, copy_leaf, default, exists, first_existing, get_attr
10
- from .spaces import space_from_action_spec
9
+ from .helpers import EnvWrapper, copy_leaf, default, exists, first_existing, get_adapter, get_attr
11
10
 
12
11
  # helpers
13
12
 
@@ -22,7 +21,7 @@ def clamp(t, min_val, max_val):
22
21
  if is_tensor(t):
23
22
  return torch.clamp(t, min_val, max_val)
24
23
  if isinstance(t, np.ndarray):
25
- return np.clip(t, min_val, max_val)
24
+ return np.clip(t, min_val, max_val).astype(t.dtype, copy = False)
26
25
  return max(min_val, min(t, max_val))
27
26
 
28
27
  def rescale(
@@ -32,27 +31,19 @@ def rescale(
32
31
  ):
33
32
  from_min, from_max = from_range
34
33
  to_min, to_max = to_range
35
- return (t - from_min) / (from_max - from_min) * (to_max - to_min) + to_min
34
+ out = (t - from_min) / (from_max - from_min) * (to_max - to_min) + to_min
35
+ return out.astype(t.dtype, copy = False) if isinstance(t, np.ndarray) else out
36
36
 
37
37
  def action_bounds(env):
38
38
  # canonical per-env bounds — gymnasium spaces, or dm_control action_spec.
39
39
  # discrete spaces have nothing to rescale
40
40
 
41
- space = first_existing(env, 'single_action_space', 'action_space')
41
+ space = default(first_existing(env, 'single_action_space', 'action_space'), get_adapter(env).action_space)
42
42
 
43
- if exists(space):
44
- if exists(get_attr(space, 'n')):
45
- return None
46
-
47
- if exists(get_attr(space, 'low')):
48
- return np.asarray(space.low, dtype = float), np.asarray(space.high, dtype = float)
49
-
50
- spec = space_from_action_spec(env)
51
-
52
- if not exists(spec):
43
+ if not exists(space) or exists(get_attr(space, 'n')) or not exists(get_attr(space, 'low')):
53
44
  return None
54
45
 
55
- return np.asarray(spec.low, dtype = float), np.asarray(spec.high, dtype = float)
46
+ return np.asarray(space.low, dtype = float), np.asarray(space.high, dtype = float)
56
47
 
57
48
  # wrapper
58
49
 
@@ -80,7 +71,12 @@ class ActionTransformWrapper(EnvWrapper):
80
71
  self.bounds = action_bounds(env) if auto else None
81
72
 
82
73
  def reset(self, **kwargs):
83
- return self.env.reset(**kwargs)
74
+ out = self.env.reset(**kwargs)
75
+
76
+ if self.auto and not exists(self.bounds):
77
+ self.bounds = action_bounds(self.env)
78
+
79
+ return out
84
80
 
85
81
  def auto_transform(self, t):
86
82
  # rescale canonical range (default (0, 1), beta-friendly) to per-env
@@ -90,6 +86,7 @@ class ActionTransformWrapper(EnvWrapper):
90
86
  return t
91
87
 
92
88
  low, high = self.bounds
89
+ orig_dtype = t.dtype if isinstance(t, np.ndarray) else None
93
90
 
94
91
  # scalar (0-dim) actions — e.g. Box(shape = (), ...) — reshape out and back
95
92
 
@@ -125,6 +122,8 @@ class ActionTransformWrapper(EnvWrapper):
125
122
  rescaled = torch.where(valid_t, torch.clamp(rescaled, low, high), t)
126
123
  else:
127
124
  rescaled = np.where(valid_t, np.clip(rescaled, low, high), t)
125
+ if exists(orig_dtype):
126
+ rescaled = rescaled.astype(orig_dtype, copy = False)
128
127
 
129
128
  if was_scalar:
130
129
  rescaled = rescaled[0]
@@ -3,6 +3,7 @@ from __future__ import annotations
3
3
  from .helpers import (
4
4
  EnvWrapper,
5
5
  default,
6
+ env_render_mode,
6
7
  exists,
7
8
  first_existing,
8
9
  get_attr,
@@ -15,6 +16,10 @@ from .spaces import space_from_action_spec
15
16
 
16
17
  # helpers
17
18
 
19
+ def env_type_info(env) -> tuple[str, str]:
20
+ cls = type(env)
21
+ return cls.__name__, getattr(cls, '__module__', '')
22
+
18
23
  def render_with_dims(render, height, width, camera = None):
19
24
  # modern render(height, width, camera) vs legacy bare render()
20
25
 
@@ -89,7 +94,7 @@ class BaseEnvAdapter:
89
94
 
90
95
  render = get_attr(self.env, 'render')
91
96
 
92
- if callable(render):
97
+ if callable(render) and exists(env_render_mode(self.env)):
93
98
  return render_with_dims(render, height, width, camera)
94
99
 
95
100
  return None
@@ -200,10 +205,12 @@ class WrapperAdapter(BaseEnvAdapter):
200
205
  # dm control adapter
201
206
 
202
207
  class DMControlAdapter(BaseEnvAdapter):
208
+ is_vectorized = False
209
+ autoresets = False
210
+
203
211
  @classmethod
204
212
  def matches(cls, env):
205
- mod = getattr(type(env), '__module__', '')
206
- name = type(env).__name__
213
+ name, mod = env_type_info(env)
207
214
  is_dm_type = 'DMControl' in name or 'dm_control' in mod or 'dm_env' in mod
208
215
  has_physics = exists(get_attr(env, 'physics')) and callable(get_attr(get_attr(env, 'physics'), 'render'))
209
216
  return is_dm_type or has_physics
@@ -213,32 +220,17 @@ class DMControlAdapter(BaseEnvAdapter):
213
220
  if exists(random_state) and callable(get_attr(random_state, 'seed')):
214
221
  random_state.seed(seed)
215
222
  return
216
- if callable(get_attr(self.env, 'seed')):
217
- self.env.seed(seed)
218
- return
219
223
  super().seed(seed)
220
224
 
221
- def render(self, height: int, width: int, camera = None):
222
- physics = get_attr(self.env, 'physics')
223
- if exists(physics) and callable(get_attr(physics, 'render')):
224
- kwargs = dict(camera_id = camera) if exists(camera) else {}
225
- return physics.render(height = height, width = width, **kwargs)
226
- return super().render(height, width, camera)
227
-
228
- @property
229
- def action_space(self):
230
- return default(super().action_space, space_from_action_spec(self.env))
225
+ # pybullet adapter
231
226
 
227
+ class PyBulletAdapter(BaseEnvAdapter):
232
228
  is_vectorized = False
233
229
  autoresets = False
234
230
 
235
- # pybullet adapter
236
-
237
- class PyBulletAdapter(BaseEnvAdapter):
238
231
  @classmethod
239
232
  def matches(cls, env):
240
- mod = getattr(type(env), '__module__', '')
241
- name = type(env).__name__
233
+ name, mod = env_type_info(env)
242
234
  return 'PyBullet' in name or 'pybullet' in mod or (exists(get_attr(env, 'p')) and callable(get_attr(get_attr(env, 'p'), 'getCameraImage')))
243
235
 
244
236
  def render(self, height: int, width: int, camera = None):
@@ -251,15 +243,6 @@ class PyBulletAdapter(BaseEnvAdapter):
251
243
  return self.env.render(mode = 'rgb_array')
252
244
  return None
253
245
 
254
- def seed(self, seed: int):
255
- if callable(get_attr(self.env, 'seed')):
256
- self.env.seed(seed)
257
- return
258
- super().seed(seed)
259
-
260
- is_vectorized = False
261
- autoresets = False
262
-
263
246
  # mjlab adapter (manager-based rl envs on mujoco warp)
264
247
 
265
248
  class MjlabAdapter(BaseEnvAdapter):
@@ -268,8 +251,7 @@ class MjlabAdapter(BaseEnvAdapter):
268
251
 
269
252
  @classmethod
270
253
  def matches(cls, env):
271
- mod = getattr(type(env), '__module__', '')
272
- name = type(env).__name__
254
+ name, mod = env_type_info(env)
273
255
  return 'mjlab' in mod.lower() or name == 'ManagerBasedRlEnv'
274
256
 
275
257
  @property
@@ -285,8 +267,7 @@ class IsaacAdapter(BaseEnvAdapter):
285
267
 
286
268
  @classmethod
287
269
  def matches(cls, env):
288
- mod = getattr(type(env), '__module__', '')
289
- name = type(env).__name__
270
+ name, mod = env_type_info(env)
290
271
  isaac_kw = ('isaac', 'omni.isaac', 'isaacgym', 'isaaclab')
291
272
  return any(k in mod.lower() for k in isaac_kw) or 'Isaac' in name or exists(get_attr(env, 'sim_device')) or exists(get_attr(env, 'physics_sim_view'))
292
273
 
@@ -295,21 +276,10 @@ class IsaacAdapter(BaseEnvAdapter):
295
276
  class MujocoWarpAdapter(BaseEnvAdapter):
296
277
  @classmethod
297
278
  def matches(cls, env):
298
- mod = getattr(type(env), '__module__', '')
299
- name = type(env).__name__
279
+ name, mod = env_type_info(env)
300
280
  warp_kw = ('warp', 'mujoco_warp', 'brax', 'mjx')
301
281
  return any(k in mod.lower() for k in warp_kw) or 'Brax' in name or 'Mjx' in name or exists(get_attr(env, 'warp_device')) or exists(get_attr(env, 'wp_env'))
302
282
 
303
- @property
304
- def is_vectorized(self) -> bool:
305
- if truthy_attr(get_attr(self.env, 'is_vector')):
306
- return True
307
- return self.num_envs > 1
308
-
309
- @property
310
- def autoresets(self) -> bool:
311
- return truthy_attr(first_existing(self.env, 'autoreset', 'autoresets', 'autoreset_mode'))
312
-
313
283
  # pufferlib adapter
314
284
 
315
285
  class PufferLibAdapter(BaseEnvAdapter):
@@ -317,14 +287,9 @@ class PufferLibAdapter(BaseEnvAdapter):
317
287
 
318
288
  @classmethod
319
289
  def matches(cls, env):
320
- mod = getattr(type(env), '__module__', '')
321
- name = type(env).__name__
290
+ name, mod = env_type_info(env)
322
291
  return 'Puffer' in name or 'pufferlib' in mod or exists(get_attr(env, 'puffer_env'))
323
292
 
324
- @property
325
- def autoresets(self) -> bool:
326
- return truthy_attr(first_existing(self.env, 'autoreset', 'autoresets', 'autoreset_mode'))
327
-
328
293
  # robotics adapter (robosuite, maniskill, metaworld, trifinger, habitat, rlbench,
329
294
  # omnigibson, robomimic, myosuite, gymnasium-robotics, lerobot, ...)
330
295
  # sits before dm_control — several robotics sims expose `physics` but are not dm_control
@@ -340,39 +305,16 @@ ROBOTICS_KEYWORDS = (
340
305
  class RoboticsAdapter(BaseEnvAdapter):
341
306
  @classmethod
342
307
  def matches(cls, env):
343
- mod = getattr(type(env), '__module__', '').lower()
344
- name = type(env).__name__.lower()
308
+ name, mod = (s.lower() for s in env_type_info(env))
345
309
  has_sim_render = exists(get_attr(env, 'sim')) and callable(get_attr(get_attr(env, 'sim'), 'render'))
346
310
  return any(k in name or k in mod for k in ROBOTICS_KEYWORDS) or has_sim_render
347
311
 
348
- def render(self, height: int, width: int, camera = None):
349
- frame = render_sim(get_attr(self.env, 'sim'), height, width, camera)
350
-
351
- if exists(frame):
352
- return frame
353
-
354
- render = get_attr(self.env, 'render')
355
-
356
- if callable(render):
357
- return render_with_dims(render, height, width, camera)
358
-
359
- return super().render(height, width, camera)
360
-
361
- @property
362
- def is_vectorized(self) -> bool:
363
- if truthy_attr(get_attr(self.env, 'is_vector')):
364
- return True
365
- if exists(get_attr(self.env, 'single_action_space')):
366
- return True
367
- return self.num_envs > 1
368
-
369
312
  # farama gymnasium adapter
370
313
 
371
314
  class GymnasiumAdapter(BaseEnvAdapter):
372
315
  @classmethod
373
316
  def matches(cls, env):
374
- mod = getattr(type(env), '__module__', '')
375
- name = type(env).__name__
317
+ name, mod = env_type_info(env)
376
318
  if 'Gymnasium' in name or 'AutoresetVector' in name:
377
319
  return True
378
320
  try:
@@ -385,17 +327,13 @@ class GymnasiumAdapter(BaseEnvAdapter):
385
327
 
386
328
  @property
387
329
  def is_vectorized(self) -> bool:
388
- if truthy_attr(get_attr(self.env, 'is_vector')):
389
- return True
390
- if exists(get_attr(self.env, 'single_action_space')):
330
+ if super().is_vectorized:
391
331
  return True
392
332
  try:
393
333
  from gymnasium.vector import VectorEnv
394
- if isinstance(self.env, VectorEnv):
395
- return True
334
+ return isinstance(self.env, VectorEnv)
396
335
  except ImportError:
397
- pass
398
- return self.num_envs > 1
336
+ return False
399
337
 
400
338
  def unwrapped_adapter(self):
401
339
  # foreign gym wrappers (TimeLimit, RecordEpisodeStatistics, ...) inherit
@@ -432,9 +370,6 @@ class GymnasiumAdapter(BaseEnvAdapter):
432
370
  return
433
371
  except Exception:
434
372
  pass
435
- if callable(get_attr(self.env, 'seed')):
436
- self.env.seed(seed)
437
- return
438
373
  super().seed(seed)
439
374
 
440
375
  # legacy openai gym adapter
@@ -442,16 +377,9 @@ class GymnasiumAdapter(BaseEnvAdapter):
442
377
  class LegacyGymAdapter(BaseEnvAdapter):
443
378
  @classmethod
444
379
  def matches(cls, env):
445
- name = type(env).__name__
446
- mod = getattr(type(env), '__module__', '')
380
+ name, mod = env_type_info(env)
447
381
  return 'LegacyGym' in name or 'gym.' in mod or mod == 'gym'
448
382
 
449
- def seed(self, seed: int):
450
- if callable(get_attr(self.env, 'seed')):
451
- self.env.seed(seed)
452
- return
453
- super().seed(seed)
454
-
455
383
  # default fallback adapter
456
384
 
457
385
  class DefaultAdapter(BaseEnvAdapter):
@@ -7,16 +7,17 @@ import torch
7
7
  from torch.utils._pytree import tree_flatten, tree_map, tree_structure, tree_unflatten
8
8
 
9
9
  from .helpers import (
10
- FINAL_OBSERVATION_KEYS,
11
10
  EnvWrapper,
12
11
  default,
13
12
  exists,
14
13
  first_existing,
14
+ get_adapter,
15
15
  get_attr,
16
16
  is_array,
17
17
  is_scalar,
18
18
  is_tensor,
19
19
  is_vectorized,
20
+ maybe_transform_final_observation,
20
21
  )
21
22
 
22
23
  # helper functions
@@ -56,7 +57,6 @@ def get_action_space(env):
56
57
  if exists(unit_space):
57
58
  return unit_space, True
58
59
 
59
- from .helpers import get_adapter
60
60
  return get_adapter(env).action_space, False
61
61
 
62
62
  def action_shape_tree(space):
@@ -179,10 +179,7 @@ class AutoBatchedWrapper(EnvWrapper):
179
179
  return obs, info
180
180
 
181
181
  obs = maybe_expand_dim(obs)
182
- if isinstance(info, dict):
183
- for key in FINAL_OBSERVATION_KEYS:
184
- if key in info:
185
- info[key] = maybe_expand_dim(info[key])
182
+ maybe_transform_final_observation(info, maybe_expand_dim)
186
183
 
187
184
  return obs, info
188
185
 
@@ -195,10 +192,6 @@ class AutoBatchedWrapper(EnvWrapper):
195
192
 
196
193
  obs, reward, terminated, truncated, info = out
197
194
  obs, reward, terminated, truncated = (maybe_expand_dim(t) for t in (obs, reward, terminated, truncated))
198
-
199
- if isinstance(info, dict):
200
- for key in FINAL_OBSERVATION_KEYS:
201
- if key in info:
202
- info[key] = maybe_expand_dim(info[key])
195
+ maybe_transform_final_observation(info, maybe_expand_dim)
203
196
 
204
197
  return obs, reward, terminated, truncated, info
@@ -31,6 +31,11 @@ def broadcast_mask(mask, x):
31
31
 
32
32
  def zero_mask(x, mask, fill_scalar = None):
33
33
  if is_tensor(x):
34
+ if x.ndim == 0:
35
+ if not bool(to_numpy(mask).any()):
36
+ return x
37
+ return torch.tensor(fill_scalar, device = x.device, dtype = x.dtype) if exists(fill_scalar) else torch.zeros_like(x)
38
+
34
39
  return torch.where(broadcast_mask(mask, x), torch.zeros_like(x), x)
35
40
 
36
41
  arr = np.asarray(x)
@@ -40,6 +45,9 @@ def zero_mask(x, mask, fill_scalar = None):
40
45
  return fill_scalar
41
46
  return x
42
47
 
48
+ if arr.dtype.kind not in 'biufc':
49
+ return x
50
+
43
51
  out = arr.copy()
44
52
  out[mask] = 0
45
53
  return out
@@ -86,6 +94,7 @@ class EpisodePaddingWrapper(EnvWrapper):
86
94
 
87
95
  def step(self, action):
88
96
  obs, reward, terminated, truncated, info = self.env.step(action)
97
+ raw_obs = obs
89
98
 
90
99
  if self.is_vector:
91
100
  info = info if isinstance(info, dict) else {}
@@ -101,8 +110,9 @@ class EpisodePaddingWrapper(EnvWrapper):
101
110
 
102
111
  newly = mask if self.autoreset else mask & ~self._is_done
103
112
  self._is_done |= mask
113
+ done_mask = mask if self.autoreset else self._is_done
104
114
 
105
- if mask.any():
115
+ if done_mask.any():
106
116
  assert exists(self._last_obs), 'environment needs reset before calling step. call env.reset() first'
107
117
 
108
118
  if newly.any():
@@ -118,11 +128,11 @@ class EpisodePaddingWrapper(EnvWrapper):
118
128
  # while autoresetting envs already re-emit the true terminal obs (unless told to pad anyway)
119
129
 
120
130
  if not self.autoreset or self.pad_autoreset:
121
- obs = tree_map(partial(zero_mask, mask = mask), obs)
122
- reward = zero_mask(reward, mask & ~newly, fill_scalar = 0.0)
131
+ obs = tree_map(partial(zero_mask, mask = done_mask), obs)
132
+ reward = zero_mask(reward, done_mask & ~newly, fill_scalar = 0.0)
123
133
 
124
134
  info['final_observation'] = self._final_obs
125
- info['_final_observation'] = back_to_mask_type(dones, mask)
135
+ info['_final_observation'] = back_to_mask_type(dones, done_mask)
126
136
 
127
- self._last_obs = obs
137
+ self._last_obs = raw_obs
128
138
  return obs, reward, terminated, truncated, info
@@ -16,7 +16,7 @@ from .helpers import (
16
16
  # helpers
17
17
 
18
18
  def flattenable(t):
19
- if is_array(t) or is_scalar(t):
19
+ if is_tensor(t) or is_scalar(t):
20
20
  return True
21
21
 
22
22
  try:
@@ -301,12 +301,7 @@ def has_final_observation(info):
301
301
  return isinstance(info, dict) and any(key in info for key in FINAL_OBSERVATION_KEYS)
302
302
 
303
303
  def maybe_get_final_observation(info):
304
- if isinstance(info, dict):
305
- for key in FINAL_OBSERVATION_KEYS:
306
- if key in info:
307
- return info[key]
308
-
309
- return None
304
+ return first_existing(info, *FINAL_OBSERVATION_KEYS) if isinstance(info, dict) else None
310
305
 
311
306
  def get_final_observation(info, default = None):
312
307
  final_obs = maybe_get_final_observation(info)
@@ -424,29 +419,21 @@ class TransformObservationWrapper(EnvWrapper):
424
419
  return self.transform_obs(obs, done = done) if self.takes_done else self.transform_obs(obs)
425
420
 
426
421
  def reset(self, **kwargs):
427
- obs, info = self.env.reset(**kwargs)
422
+ obs, info = normalize_reset_out(self.env.reset(**kwargs))
428
423
  obs = self.transform(obs, done = None)
429
-
430
- if isinstance(info, dict):
431
- for key in FINAL_OBSERVATION_KEYS:
432
- if key in info:
433
- info[key] = self.transform(info[key], done = None)
434
-
424
+ maybe_transform_final_observation(info, self.transform)
435
425
  return obs, info
436
426
 
437
427
  def step(self, action):
438
- obs, reward, terminated, truncated, info = self.env.step(action)
428
+ obs, reward, terminated, truncated, info = normalize_step_out(self.env.step(action))
439
429
  done = dones_of(terminated, truncated) if self.autoresets else None
440
430
 
441
431
  out = self.transform(obs, done = done)
442
432
 
443
- if isinstance(info, dict):
444
- for key in FINAL_OBSERVATION_KEYS:
445
- if key in info:
446
- if not self.takes_done:
447
- info[key] = self.transform(info[key])
448
- elif not self.autoresets:
449
- info[key] = out
433
+ if not self.takes_done:
434
+ maybe_transform_final_observation(info, self.transform)
435
+ elif not self.autoresets:
436
+ maybe_transform_final_observation(info, lambda _: out)
450
437
 
451
438
  return out, reward, terminated, truncated, info
452
439
 
@@ -99,13 +99,11 @@ class ImageObservationWrapper(TransformObservationWrapper):
99
99
  normalize = self.normalize,
100
100
  normalize_divisor = self.normalize_divisor
101
101
  )
102
- return processed, is_batched
102
+ return processed if is_batched else rearrange(processed, '1 c h w -> c h w')
103
103
 
104
- def observation(self, obs):
105
- img, is_batched = self.render_frame()
106
-
107
- if not is_batched:
108
- img = rearrange(img, '1 c h w -> c h w')
104
+ def observation(self, obs, img = None):
105
+ if not exists(img):
106
+ img = self.render_frame()
109
107
 
110
108
  if not isinstance(obs, dict):
111
109
  return dict(state = obs, **{self.image_key: img})
@@ -124,14 +122,15 @@ class ImageObservationWrapper(TransformObservationWrapper):
124
122
 
125
123
  def step(self, action):
126
124
  obs, reward, terminated, truncated, info = normalize_step_out(self.env.step(action))
127
- out = self.observation(obs)
125
+ img = self.render_frame()
126
+ out = self.observation(obs, img = img)
128
127
 
129
128
  # terminal obs are augmented in place, preserving whatever the sim
130
129
  # or the padding wrapper froze as the true terminal observation
131
130
 
132
- if isinstance(info, dict) and not self.autoresets:
131
+ if isinstance(info, dict):
133
132
  for key in FINAL_OBSERVATION_KEYS:
134
133
  if key in info and not (isinstance(info[key], dict) and self.image_key in info[key]):
135
- info[key] = self.observation(info[key])
134
+ info[key] = self.observation(info[key], img = img)
136
135
 
137
136
  return out, reward, terminated, truncated, info
@@ -1,7 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import torch
4
- from .helpers import EnvWrapper, exists, is_vectorized
4
+ from .helpers import EnvWrapper, exists, instantiate_env, is_vectorized
5
5
  from .utils import compose_env
6
6
 
7
7
  class StandardizeEnvWrapper(EnvWrapper):
@@ -27,6 +27,7 @@ class StandardizeEnvWrapper(EnvWrapper):
27
27
  chunk_gamma: float = 1.,
28
28
  chunk_reward_mode: str = 'sum',
29
29
  ):
30
+ env = instantiate_env(env)
30
31
  wrappers = []
31
32
 
32
33
  if exists(image_size):
@@ -9,7 +9,7 @@ from .helpers import (
9
9
  instantiate_env,
10
10
  mark_terminal_obs,
11
11
  )
12
- from .spaces import infer_observation_space, space_from_action_spec
12
+ from .spaces import infer_observation_space
13
13
 
14
14
  # class
15
15
 
@@ -26,10 +26,7 @@ class StandardizeWrapper(EnvWrapper):
26
26
 
27
27
  # always expose single-env spaces
28
28
 
29
- self.action_space = default(
30
- self.adapter.action_space,
31
- space_from_action_spec(env)
32
- )
29
+ self.action_space = self.adapter.action_space
33
30
  self.observation_space = self.adapter.observation_space
34
31
 
35
32
  def reset(self, **kwargs):
@@ -41,7 +38,7 @@ class StandardizeWrapper(EnvWrapper):
41
38
  self.observation_space = infer_observation_space(obs, self.is_vector)
42
39
 
43
40
  if not exists(self.action_space):
44
- self.action_space = default(self.adapter.action_space, space_from_action_spec(self.env))
41
+ self.action_space = self.adapter.action_space
45
42
 
46
43
  return obs, info
47
44
 
@@ -9,12 +9,12 @@ from torch.utils._pytree import tree_map
9
9
 
10
10
  from .helpers import (
11
11
  EnvWrapper,
12
- FINAL_OBSERVATION_KEYS,
13
12
  FINAL_OBSERVATION_MASK_KEYS,
14
13
  exists,
15
14
  get_adapter,
16
15
  is_foreign_array,
17
16
  is_scalar,
17
+ maybe_transform_final_observation,
18
18
  unpack_vector_observations,
19
19
  )
20
20
 
@@ -112,9 +112,7 @@ class TensorWrapper(EnvWrapper):
112
112
  if not isinstance(info, dict) or not info:
113
113
  return
114
114
 
115
- for key in FINAL_OBSERVATION_KEYS:
116
- if key in info:
117
- info[key] = self.cast(info[key])
115
+ maybe_transform_final_observation(info, self.cast)
118
116
 
119
117
  for key in FINAL_OBSERVATION_MASK_KEYS:
120
118
  if key in info:
@@ -33,7 +33,7 @@ def back_to_like(t, numpy_arr):
33
33
  return numpy_arr
34
34
 
35
35
  class TimeLimitWrapper(EnvWrapper):
36
- priority = 40
36
+ priority = 5
37
37
 
38
38
  """
39
39
  caps episode length at max_timesteps, setting truncated = True for
@@ -7,6 +7,7 @@ from torch.utils._pytree import tree_flatten, tree_map, tree_unflatten
7
7
 
8
8
  from .helpers import (
9
9
  any_true,
10
+ default,
10
11
  dones_of,
11
12
  exists,
12
13
  get_adapter,
@@ -50,8 +51,8 @@ class WorkerError(RuntimeError):
50
51
 
51
52
  def _exec(env, cmd, payload):
52
53
  if cmd == 'step':
53
- if is_tensor(payload) and not get_adapter(env).torch_native:
54
- payload = to_numpy(payload)
54
+ if not get_adapter(env).torch_native:
55
+ payload = tree_map(lambda a: to_numpy(a) if is_tensor(a) else a, payload)
55
56
 
56
57
  if action_space_is_discrete(env.action_space):
57
58
  if hasattr(payload, 'item') and (not hasattr(payload, 'ndim') or payload.ndim <= 1):
@@ -224,8 +225,8 @@ class MultiprocessingVecEnv:
224
225
 
225
226
  self.action_space = self._get_attr('action_space')
226
227
  self.observation_space = self._get_attr('observation_space')
227
- self.action_dim = action_dim_of(self)
228
- self.obs_dim = obs_dim_of(self)
228
+ self.action_dim = default(action_dim_of(self), self._get_attr('action_dim'))
229
+ self.obs_dim = default(obs_dim_of(self), self._get_attr('obs_dim'))
229
230
 
230
231
  self.seed(seed)
231
232
 
@@ -286,11 +287,15 @@ class MultiprocessingVecEnv:
286
287
  _safe_send(conn, ('reset', worker_kwargs))
287
288
 
288
289
  results = _recv_all(self._conns)
290
+
291
+ if not exists(self.observation_space):
292
+ self.observation_space = self._get_attr('observation_space')
293
+ self.obs_dim = default(self.obs_dim, obs_dim_of(self))
294
+
289
295
  return stack_trees([obs for obs, _ in results]), _merge_infos([info for _, info in results])
290
296
 
291
297
  def step(self, actions):
292
- if is_tensor(actions):
293
- actions = to_numpy(actions)
298
+ actions = tree_map(lambda a: to_numpy(a) if is_tensor(a) else a, actions)
294
299
 
295
300
  actions = _split_actions(actions, self.num_envs)
296
301
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "env-ssl-wrapper"
3
- version = "0.5.4"
3
+ version = "0.5.5"
4
4
  description = "One torch-native interface for any MDP environment"
5
5
  authors = [
6
6
  { name = "Phil Wang", email = "lucidrains@gmail.com" }
File without changes