File size: 6,906 Bytes
36b714d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
"""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')

    @staticmethod
    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)