Download scripts/e5_rollout_history.py from ar-mine/e5-c3-code: direct link, hf CLI and curl.
- Browser
- Download file 7.23 kB
-
https://huggingface.co/datasets/ar-mine/e5-c3-code/resolve/main/scripts/e5_rollout_history.py
- Command line
-
hf download hf://datasets/ar-mine/e5-c3-code/scripts/e5_rollout_history.py
-
curl -L -o e5_rollout_history.py https://huggingface.co/datasets/ar-mine/e5-c3-code/resolve/main/scripts/e5_rollout_history.py
7.23 kB
| """E5 dual causal buffers: confirmed command prefix and prior public decisions. | |
| The caller invokes record_completed only after take_action returns and the public | |
| command counter advances. The cache never infers physical state from commands. | |
| Observe is called at the original 50-command decision boundaries. A reconnect | |
| invalidates both buffers until an explicit episode/session reset. | |
| """ | |
| from collections import deque | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| class RolloutCombinedHistory: | |
| def __init__(self, episode_id, output=None, stride=50, session_id=None): | |
| if stride != 50: | |
| raise ValueError('E5 retains the 50-command execution protocol') | |
| self.stride = stride | |
| self.output = Path(output) if output else None | |
| if self.output: | |
| self.output.mkdir(parents=True, exist_ok=True) | |
| self.reset(episode_id, session_id) | |
| def reset(self, episode_id, session_id=None): | |
| if episode_id is None: | |
| raise ValueError('Explicit episode identity required') | |
| self.episode_id = str(episode_id) | |
| self.session_id = None if session_id is None else str(session_id) | |
| self.commands = deque(maxlen=8) | |
| self.completed_commands = 0 | |
| self.decisions = [] | |
| self.last_fields = None | |
| self.invalidated = False | |
| self.episode_output = None | |
| if self.output: | |
| identity = json.dumps([self.session_id, self.episode_id]) | |
| self.episode_output = self.output / hashlib.sha256(identity.encode()).hexdigest() | |
| self.episode_output.mkdir(exist_ok=False) | |
| def invalidate_on_reconnect(self): | |
| self.commands.clear() | |
| self.decisions.clear() | |
| self.last_fields = None | |
| self.invalidated = True | |
| def _check_session(self, session_id): | |
| if self.invalidated: | |
| raise ValueError('Explicit episode reset required after reconnect') | |
| session_id = None if session_id is None else str(session_id) | |
| if session_id != self.session_id: | |
| self.invalidate_on_reconnect() | |
| raise ValueError('Session changed without explicit episode reset') | |
| def _counter(value): | |
| if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, np.integer)) or value < 0: | |
| raise ValueError('Expected nonnegative executed command counter') | |
| return int(value) | |
| def record_completed(self, commands, *, before_counter, after_counter, episode_id, session_id=None): | |
| """Append only commands confirmed by the returned execution interval.""" | |
| self._check_session(session_id) | |
| if str(episode_id) != self.episode_id: | |
| raise ValueError('Episode changed without explicit reset') | |
| before, after = self._counter(before_counter), self._counter(after_counter) | |
| values = np.asarray(commands, dtype=np.float32) | |
| if values.ndim != 2 or values.shape[1] != 14 or len(values) == 0 or not np.isfinite(values).all(): | |
| raise ValueError('Expected a nonempty finite executed command prefix of shape [N,14]') | |
| if before != self.completed_commands or after-before != len(values): | |
| raise ValueError('Execution confirmation must be contiguous and match the executed prefix') | |
| if not self.decisions or after > self.decisions[-1][0]+self.stride: | |
| raise ValueError('No current decision or command prefix exceeds frozen execution length') | |
| for value in values: | |
| self.commands.append(value.copy()) | |
| self.completed_commands = after | |
| def _attach(self, observation): | |
| actions, action_mask, states, state_mask = self.last_fields | |
| return {**observation, 'action_history_raw': {'action': actions.copy()}, | |
| 'action_history_mask': action_mask.copy(), | |
| 'state_history_raw': {'observation.state': states.copy()}, | |
| 'state_history_mask': state_mask.copy()} | |
| def observe(self, observation, action_counter, call=None, session_id=None): | |
| self._check_session(session_id) | |
| counter = self._counter(action_counter) | |
| state = np.asarray(observation['observation.state'], dtype=np.float32).copy() | |
| if state.shape != (14,) or not np.isfinite(state).all(): | |
| raise ValueError('Expected finite 14-dimensional public state; no command proxy substitution') | |
| if counter != self.completed_commands: | |
| raise ValueError('Observation counter differs from confirmed executed prefix') | |
| if self.decisions and counter == self.decisions[-1][0]: | |
| if not np.array_equal(state, self.decisions[-1][1]): | |
| raise ValueError('Public state changed without executed command advance') | |
| return self._attach(observation) | |
| expected = self.decisions[-1][0]+self.stride if self.decisions else 0 | |
| if counter != expected: | |
| raise ValueError('Decision interval/reset differs from frozen E5 protocol') | |
| actions = np.zeros((8,14), dtype=np.float32) | |
| action_mask = np.zeros(8, dtype=np.bool_) | |
| if self.commands: | |
| actions[-len(self.commands):] = np.stack(self.commands) | |
| action_mask[-len(self.commands):] = True | |
| states = np.zeros((2,14), dtype=np.float32) | |
| state_mask = np.zeros(2, dtype=np.bool_) | |
| recent = self.decisions[-2:] | |
| for slot, (_, old_state) in enumerate(recent, start=2-len(recent)): | |
| states[slot] = old_state | |
| state_mask[slot] = True | |
| self.last_fields = (actions.copy(), action_mask.copy(), states.copy(), state_mask.copy()) | |
| if self.output: | |
| artifact = self.episode_output/('combined_history_%05d.npz' % counter) | |
| np.savez_compressed(artifact, action_history_raw=actions, action_history_mask=action_mask, | |
| state_history_raw=states, state_history_mask=state_mask, current_public_state=state) | |
| with (self.episode_output/'combined_history_audit.jsonl').open('a') as handle: | |
| handle.write(json.dumps(dict(episode_id=self.episode_id, session_id=self.session_id, call=call, | |
| completed_commands=counter, past_decision_counters=[x[0] for x in recent], | |
| valid_action_rows=int(action_mask.sum()), valid_state_rows=int(state_mask.sum()), | |
| action_history_sha256=hashlib.sha256(actions.tobytes()).hexdigest(), | |
| state_history_sha256=hashlib.sha256(states.tobytes()).hexdigest(), | |
| action_source='confirmed executed command prefix; action offset0 normalization', | |
| state_source='prior public observation.state; state normalization; not measured qpos', | |
| history_masks_independent=True))+'\n') | |
| self.decisions.append((counter,state)) | |
| self.decisions = self.decisions[-2:] | |
| return self._attach(observation) | |
| def empty_history(): | |
| return {'action_history_raw': {'action': np.zeros((8,14),dtype=np.float32)}, | |
| 'action_history_mask': np.zeros(8,dtype=np.bool_), | |
| 'state_history_raw': {'observation.state': np.zeros((2,14),dtype=np.float32)}, | |
| 'state_history_mask': np.zeros(2,dtype=np.bool_)} | |