env-ssl-wrapper 0.4.0__tar.gz → 0.4.1__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 (24) hide show
  1. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/PKG-INFO +1 -1
  2. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/env_ssl_wrapper/standardize/auto_batched_wrapper.py +16 -3
  3. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/env_ssl_wrapper/standardize/episode_padding_wrapper.py +20 -5
  4. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/env_ssl_wrapper/standardize/helpers.py +109 -17
  5. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/env_ssl_wrapper/standardize/standardize_env_wrapper.py +2 -2
  6. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/env_ssl_wrapper/standardize/standardize_wrapper.py +0 -1
  7. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/env_ssl_wrapper/standardize/tensor_wrapper.py +21 -4
  8. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/env_ssl_wrapper/standardize/utils.py +4 -2
  9. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/env_ssl_wrapper/standardize/vector.py +12 -29
  10. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/pyproject.toml +1 -1
  11. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/.gitignore +0 -0
  12. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/LICENSE +0 -0
  13. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/README.md +0 -0
  14. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/env_ssl_wrapper/__init__.py +0 -0
  15. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/env_ssl_wrapper/memory_trace.py +0 -0
  16. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/env_ssl_wrapper/standardize/__init__.py +0 -0
  17. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/env_ssl_wrapper/standardize/action_transform_wrapper.py +0 -0
  18. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/env_ssl_wrapper/standardize/adapters.py +0 -0
  19. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/env_ssl_wrapper/standardize/done_tracker_wrapper.py +0 -0
  20. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/env_ssl_wrapper/standardize/flatten_obs_wrapper.py +0 -0
  21. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/env_ssl_wrapper/standardize/image_wrapper.py +0 -0
  22. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/env_ssl_wrapper/standardize/mocks.py +0 -0
  23. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/env_ssl_wrapper/standardize/spaces.py +0 -0
  24. {env_ssl_wrapper-0.4.0 → env_ssl_wrapper-0.4.1}/env_ssl_wrapper/standardize/time_limit_wrapper.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: env-ssl-wrapper
3
- Version: 0.4.0
3
+ Version: 0.4.1
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,7 +7,18 @@ import torch
7
7
  from torch.utils._pytree import tree_map
8
8
  from einops import rearrange
9
9
 
10
- from .helpers import EnvWrapper, default, exists, first_existing, get_attr, is_array, is_scalar, is_tensor, is_vectorized
10
+ from .helpers import (
11
+ FINAL_OBSERVATION_KEYS,
12
+ EnvWrapper,
13
+ default,
14
+ exists,
15
+ first_existing,
16
+ get_attr,
17
+ is_array,
18
+ is_scalar,
19
+ is_tensor,
20
+ is_vectorized,
21
+ )
11
22
  from .spaces import space_from_action_spec
12
23
 
13
24
  # helper functions
@@ -202,7 +213,9 @@ class AutoBatchedWrapper(EnvWrapper):
202
213
 
203
214
  obs, reward, terminated, truncated, info = *maybe_expand_dim(out[:4]), out[4]
204
215
 
205
- if isinstance(info, dict) and 'final_observation' in info:
206
- info['final_observation'] = maybe_expand_dim(info['final_observation'])
216
+ if isinstance(info, dict):
217
+ for key in FINAL_OBSERVATION_KEYS:
218
+ if key in info:
219
+ info[key] = maybe_expand_dim(info[key])
207
220
 
208
221
  return obs, reward, terminated, truncated, info
@@ -8,7 +8,16 @@ from torch import is_tensor
8
8
  from torch.utils._pytree import tree_map
9
9
  from einops import rearrange
10
10
 
11
- from .helpers import EnvWrapper, copy_leaf, dones_of, env_autoresets, exists, is_vectorized, to_numpy
11
+ from .helpers import (
12
+ EnvWrapper,
13
+ copy_leaf,
14
+ dones_of,
15
+ env_autoresets,
16
+ exists,
17
+ first_existing,
18
+ is_vectorized,
19
+ to_numpy
20
+ )
12
21
 
13
22
  # helpers
14
23
 
@@ -60,10 +69,11 @@ def merge_final(current, value, mask):
60
69
  # class
61
70
 
62
71
  class EpisodePaddingWrapper(EnvWrapper):
63
- def __init__(self, env):
72
+ def __init__(self, env, pad_autoreset: bool = True):
64
73
  super().__init__(env)
65
74
  self.is_vector = is_vectorized(env)
66
75
  self.autoreset = env_autoresets(env)
76
+ self.pad_autoreset = pad_autoreset
67
77
  self._last_obs = None
68
78
  self._is_done = None
69
79
  self._final_obs = None
@@ -97,15 +107,20 @@ class EpisodePaddingWrapper(EnvWrapper):
97
107
  self._is_done |= mask
98
108
 
99
109
  if newly.any():
100
- value = info['final_observation'] if 'final_observation' in info else self._last_obs
110
+ final_val = first_existing(info, 'final_observation', 'final_obs')
111
+ value = final_val if exists(final_val) else self._last_obs
101
112
 
102
113
  if self._final_obs is None:
103
114
  self._final_obs = tree_map(copy_leaf, value)
104
115
  else:
105
116
  self._final_obs = tree_map(partial(merge_final, mask = newly), self._final_obs, value)
106
117
 
107
- obs = tree_map(partial(zero_mask, mask = mask), obs)
108
- reward = zero_mask(reward, mask & ~newly, fill_scalar = 0.0)
118
+ # zero pad done slots — non-autoresetting envs stay frozen on the terminal transition,
119
+ # while autoresetting envs already re-emit the true terminal obs (unless told to pad anyway)
120
+
121
+ if not self.autoreset or self.pad_autoreset:
122
+ obs = tree_map(partial(zero_mask, mask = mask), obs)
123
+ reward = zero_mask(reward, mask & ~newly, fill_scalar = 0.0)
109
124
 
110
125
  info['final_observation'] = self._final_obs
111
126
  info['_final_observation'] = back_to_mask_type(dones, mask)
@@ -2,8 +2,9 @@ from __future__ import annotations
2
2
 
3
3
  import inspect
4
4
  import numpy as np
5
+ import torch
5
6
  from torch import is_tensor
6
- from torch.utils._pytree import tree_map
7
+ from torch.utils._pytree import tree_flatten, tree_map, tree_structure, tree_unflatten
7
8
 
8
9
  # helpers
9
10
 
@@ -32,10 +33,13 @@ def truthy_attr(value):
32
33
 
33
34
  def first_existing(obj, *names):
34
35
  for name in names:
35
- value = get_attr(obj, name)
36
-
37
- if exists(value):
38
- return value
36
+ if isinstance(obj, dict):
37
+ if name in obj and exists(obj[name]):
38
+ return obj[name]
39
+ else:
40
+ value = get_attr(obj, name)
41
+ if exists(value):
42
+ return value
39
43
 
40
44
  return None
41
45
 
@@ -67,6 +71,58 @@ def dones_of(terminated, truncated):
67
71
  return terminated | truncated
68
72
  return tree_map(lambda a, b: a | b, terminated, truncated)
69
73
 
74
+ def _zero_leaf(x):
75
+ if is_tensor(x):
76
+ return torch.zeros_like(x)
77
+ if isinstance(x, np.ndarray):
78
+ return np.zeros_like(x)
79
+ if isinstance(x, bool):
80
+ return False
81
+ if isinstance(x, (int, float, np.number)):
82
+ return np.zeros_like(x)
83
+ return 0
84
+
85
+ def _stack_leaves(leaves):
86
+ if all(map(is_tensor, leaves)):
87
+ return torch.stack(leaves)
88
+ return np.stack(leaves)
89
+
90
+ def stack_trees(trees):
91
+ first = trees[0]
92
+
93
+ if is_tensor(first):
94
+ return torch.stack(trees)
95
+
96
+ if isinstance(first, np.ndarray):
97
+ return np.stack(trees)
98
+
99
+ if isinstance(first, dict):
100
+ return {key: stack_trees([t[key] for t in trees]) for key in first}
101
+
102
+ if isinstance(first, tuple):
103
+ return tuple(stack_trees([t[i] for t in trees]) for i in range(len(first)))
104
+
105
+ leaves = [tree_flatten(tree)[0] for tree in trees]
106
+ stacked = [_stack_leaves(col) for col in zip(*leaves)]
107
+ return tree_unflatten(stacked, tree_structure(trees[0]))
108
+
109
+ def unpack_vector_observations(arr):
110
+ # unpacks a 1D sequence / numpy object array of unbatched single-env observations
111
+ # (or None for un-terminated slots) into the canonical batched pytree format matching obs
112
+
113
+ if not isinstance(arr, (np.ndarray, list, tuple)):
114
+ return arr
115
+
116
+ if isinstance(arr, np.ndarray) and arr.dtype != object:
117
+ return arr
118
+
119
+ sample = next((x for x in arr if x is not None), None)
120
+ if sample is None:
121
+ return arr
122
+
123
+ trees = [tree_map(_zero_leaf, sample) if x is None else x for x in arr]
124
+ return stack_trees(trees)
125
+
70
126
  # environment probes
71
127
 
72
128
  def get_adapter(env):
@@ -88,12 +144,23 @@ def env_render(env, height, width, camera = None):
88
144
  def is_vectorized(env) -> bool:
89
145
  return get_adapter(env).is_vectorized
90
146
 
147
+ # gymnasium 1.x surfaces final observations as 'final_obs' / '_final_obs', everything here uses 'final_observation' / '_final_observation'
148
+
149
+ FINAL_OBSERVATION_KEYS = ('final_observation', 'final_obs')
150
+ FINAL_OBSERVATION_MASK_KEYS = ('_final_observation', '_final_obs')
151
+
152
+ # (gymnasium 1.x name, standard name)
153
+
154
+ FINAL_OBS_ALIASES = (('final_obs', 'final_observation'), ('_final_obs', '_final_observation'))
155
+
91
156
  def has_final_observation(info):
92
- return isinstance(info, dict) and 'final_observation' in info
157
+ return isinstance(info, dict) and any(key in info for key in FINAL_OBSERVATION_KEYS)
93
158
 
94
159
  def maybe_get_final_observation(info):
95
160
  if isinstance(info, dict):
96
- return info.get('final_observation')
161
+ for key in FINAL_OBSERVATION_KEYS:
162
+ if key in info:
163
+ return info[key]
97
164
 
98
165
  return None
99
166
 
@@ -112,12 +179,33 @@ def maybe_transform_final_observation(info, fn):
112
179
  if not has_final_observation(info):
113
180
  return info
114
181
 
115
- info['final_observation'] = fn(info['final_observation'])
182
+ for key in FINAL_OBSERVATION_KEYS:
183
+ if key in info:
184
+ info[key] = fn(info[key])
185
+
116
186
  return info
117
187
 
118
188
  def mark_terminal_obs(info, obs, dones, is_vector):
119
- # single-env terminal contract — vector envs handled by EpisodePaddingWrapper
120
- if not is_vector and isinstance(info, dict) and 'final_observation' not in info and any_true(dones):
189
+ if not isinstance(info, dict) or not any_true(dones):
190
+ return
191
+
192
+ # vector envs: gymnasium provides final_obs as a 1D object array of single-env obs (or None).
193
+ # unpack into the standardized batched pytree format matching obs.
194
+
195
+ if is_vector:
196
+ for key in FINAL_OBSERVATION_KEYS:
197
+ if key in info:
198
+ info[key] = unpack_vector_observations(info[key])
199
+
200
+ # gymnasium 1.x names these 'final_obs' / '_final_obs' — alias to the standard names when provided
201
+
202
+ for src, dst in FINAL_OBS_ALIASES:
203
+ if src in info and dst not in info:
204
+ info[dst] = info[src]
205
+
206
+ # single envs get the final observation synthesized on termination if the sim provided none
207
+
208
+ if not is_vector and 'final_observation' not in info:
121
209
  info['final_observation'] = obs
122
210
  info['_final_observation'] = True
123
211
 
@@ -198,8 +286,10 @@ class TransformObservationWrapper(EnvWrapper):
198
286
  obs, info = self.env.reset(**kwargs)
199
287
  obs = self.transform_obs(obs)
200
288
 
201
- if isinstance(info, dict) and 'final_observation' in info:
202
- info['final_observation'] = self.transform_obs(info['final_observation'])
289
+ if isinstance(info, dict):
290
+ for key in FINAL_OBSERVATION_KEYS:
291
+ if key in info:
292
+ info[key] = self.transform_obs(info[key])
203
293
 
204
294
  return obs, info
205
295
 
@@ -209,11 +299,13 @@ class TransformObservationWrapper(EnvWrapper):
209
299
 
210
300
  out = self.transform_obs(obs, done = done) if self.takes_done else self.transform_obs(obs)
211
301
 
212
- if isinstance(info, dict) and 'final_observation' in info:
213
- if not self.takes_done:
214
- info['final_observation'] = self.transform_obs(info['final_observation'])
215
- elif not self.autoresets:
216
- info['final_observation'] = out
302
+ if isinstance(info, dict):
303
+ for key in FINAL_OBSERVATION_KEYS:
304
+ if key in info:
305
+ if not self.takes_done:
306
+ info[key] = self.transform_obs(info[key])
307
+ elif not self.autoresets:
308
+ info[key] = out
217
309
 
218
310
  return out, reward, terminated, truncated, info
219
311
 
@@ -1,7 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import torch
4
- from .helpers import EnvWrapper, exists, default
4
+ from .helpers import EnvWrapper, exists, default, is_vectorized
5
5
  from .utils import compose_env
6
6
 
7
7
  class StandardizeEnvWrapper(EnvWrapper):
@@ -35,7 +35,7 @@ class StandardizeEnvWrapper(EnvWrapper):
35
35
  if exists(max_timesteps):
36
36
  wrappers.append(('time_limit', dict(max_timesteps = max_timesteps)))
37
37
 
38
- if auto_batch:
38
+ if auto_batch and not is_vectorized(env):
39
39
  wrappers.append('auto_batch')
40
40
 
41
41
  if exists(device):
@@ -10,7 +10,6 @@ from .helpers import (
10
10
  default,
11
11
  dones_of,
12
12
  exists,
13
- first_existing,
14
13
  get_attr,
15
14
  instantiate_env,
16
15
  mark_terminal_obs,
@@ -7,7 +7,15 @@ import torch
7
7
  from torch import tensor, is_tensor, from_numpy, device as torch_device
8
8
  from torch.utils._pytree import tree_map
9
9
 
10
- from .helpers import EnvWrapper, exists, get_attr, is_scalar
10
+ from .helpers import (
11
+ EnvWrapper,
12
+ FINAL_OBSERVATION_KEYS,
13
+ FINAL_OBSERVATION_MASK_KEYS,
14
+ exists,
15
+ get_attr,
16
+ is_scalar,
17
+ unpack_vector_observations,
18
+ )
11
19
 
12
20
  # helpers
13
21
 
@@ -27,6 +35,9 @@ def to_torch_leaf(t, device, cast_obs_to_float = True):
27
35
 
28
36
  def numpy_to_torch(x, device, cast_obs_to_float = True):
29
37
  # numpy / scalars / foreign array-likes to torch; float32 unless disabled
38
+ if isinstance(x, np.ndarray) and x.dtype == object:
39
+ x = unpack_vector_observations(x)
40
+
30
41
  if not isinstance(x, (dict, list, tuple)):
31
42
  return to_torch_leaf(x, device, cast_obs_to_float)
32
43
 
@@ -88,10 +99,16 @@ class TensorWrapper(EnvWrapper):
88
99
  self.cast = partial(numpy_to_torch, device = self.device, cast_obs_to_float = self.cast_obs_to_float)
89
100
 
90
101
  def cast_info(self, info):
102
+ if not isinstance(info, dict):
103
+ return
104
+
105
+ for key in FINAL_OBSERVATION_KEYS:
106
+ if key in info:
107
+ info[key] = self.cast(info[key])
91
108
 
92
- if isinstance(info, dict) and 'final_observation' in info:
93
- info['final_observation'] = self.cast(info['final_observation'])
94
- info['_final_observation'] = contract(self.cast(info['_final_observation']))
109
+ for key in FINAL_OBSERVATION_MASK_KEYS:
110
+ if key in info:
111
+ info[key] = contract(self.cast(info[key]))
95
112
 
96
113
  def reset(self, **kwargs):
97
114
  obs, info = self.env.reset(**kwargs)
@@ -4,7 +4,7 @@ from functools import partial
4
4
  from .standardize_wrapper import StandardizeWrapper
5
5
  from .image_wrapper import ImageObservationWrapper
6
6
  from .auto_batched_wrapper import AutoBatchedWrapper
7
- from .helpers import instantiate_env, is_vectorized
7
+ from .helpers import instantiate_env, is_vectorized, env_autoresets
8
8
  from .tensor_wrapper import TensorWrapper
9
9
  from .action_transform_wrapper import ActionTransformWrapper
10
10
  from .done_tracker_wrapper import DoneTrackerWrapper
@@ -71,9 +71,11 @@ def compose_env(env, *wrappers, pad_episodes: bool = True):
71
71
  classes.insert(0, StandardizeWrapper)
72
72
 
73
73
  # vectorized envs get standardized episode padding + a persistent final_observation
74
+ # (autoresetting envs re-emit the true terminal obs, so no padding for those)
74
75
 
75
76
  if pad_episodes and EpisodePaddingWrapper not in classes and is_vectorized(env):
76
- funcs.insert(1, EpisodePaddingWrapper)
77
+ pad_wrapper = partial(EpisodePaddingWrapper, pad_autoreset = not env_autoresets(env))
78
+ funcs.insert(1, pad_wrapper)
77
79
  classes.insert(1, EpisodePaddingWrapper)
78
80
 
79
81
  from ..memory_trace import MemoryTraceWrapper
@@ -6,40 +6,23 @@ import torch
6
6
  from torch import is_tensor
7
7
  from torch.utils._pytree import tree_flatten, tree_map, tree_structure, tree_unflatten
8
8
 
9
- from .helpers import any_true, dones_of, exists, get_attr, instantiate_env, safe_close, truthy_attr
9
+ from .helpers import (
10
+ any_true,
11
+ dones_of,
12
+ exists,
13
+ get_attr,
14
+ instantiate_env,
15
+ safe_close,
16
+ stack_trees,
17
+ truthy_attr,
18
+ _zero_leaf,
19
+ )
10
20
  from .spaces import action_dim_of
11
21
  from .standardize_wrapper import StandardizeWrapper
12
22
 
13
23
  # leaf helpers
14
24
 
15
- def _zero_leaf(x):
16
- if is_tensor(x):
17
- return torch.zeros_like(x)
18
- return np.zeros_like(x)
19
-
20
- def _stack_leaves(leaves):
21
- if all(map(is_tensor, leaves)):
22
- return torch.stack(leaves)
23
- return np.stack(leaves)
24
-
25
- def _stack_trees(trees):
26
- first = trees[0]
27
-
28
- if is_tensor(first):
29
- return torch.stack(trees)
30
-
31
- if isinstance(first, np.ndarray):
32
- return np.stack(trees)
33
-
34
- if isinstance(first, dict):
35
- return {key: _stack_trees([t[key] for t in trees]) for key in first}
36
-
37
- if isinstance(first, tuple):
38
- return tuple(_stack_trees([t[i] for t in trees]) for i in range(len(first)))
39
-
40
- leaves = [tree_flatten(tree)[0] for tree in trees]
41
- stacked = [_stack_leaves(col) for col in zip(*leaves)]
42
- return tree_unflatten(stacked, tree_structure(trees[0]))
25
+ _stack_trees = stack_trees
43
26
 
44
27
  def _merge_infos(infos):
45
28
  infos = [info if isinstance(info, dict) else {} for info in infos]
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "env-ssl-wrapper"
3
- version = "0.4.0"
3
+ version = "0.4.1"
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