"""Host-RAM-bounded history buffers: frames are stored byte-for-byte in a disk memmap instead of a Python list. Only storage changes. The upstream policy sees the same uint8 arrays at the same indices (append, len, prefix deletion, positive/negative indexing, iteration, clear), so model inputs are bit-identical. """ import itertools import os import numpy as np class DiskFrames: _ids = itertools.count() def __init__(self, root): self.root = root; self.path = None; self.mm = None; self.cap = 0; self.start = 0; self.n = 0 self.shape = self.dtype = None def _alloc(self, cap): os.makedirs(self.root, exist_ok=True) path = os.path.join(self.root, f'frames-{os.getpid()}-{next(self._ids)}.u8') mm = np.memmap(path, dtype=self.dtype, mode='w+', shape=(cap,)+self.shape) for i in range(self.n): mm[i] = self.mm[(self.start+i) % self.cap] old = self.path; self.mm, self.path, self.cap, self.start = mm, path, cap, 0 if old: os.remove(old) def append(self, x): x = np.asarray(x) if self.mm is None: self.shape, self.dtype = x.shape, x.dtype; self._alloc(2048) if x.shape != self.shape or x.dtype != self.dtype: raise ValueError('frame shape/dtype changed') if self.n == self.cap: self._alloc(self.cap*2) self.mm[(self.start+self.n) % self.cap] = x; self.n += 1 def __len__(self): return self.n def _phys(self, i): i = int(i) if i < 0: i += self.n if not 0 <= i < self.n: raise IndexError(i) return (self.start+i) % self.cap def __getitem__(self, i): if isinstance(i, slice): return [self.mm[self._phys(j)] for j in range(*i.indices(self.n))] return self.mm[self._phys(i)] def __delitem__(self, i): if not (isinstance(i, slice) and i.start in (None, 0) and i.step in (None, 1)): raise TypeError('only prefix deletion is supported') k = len(range(*i.indices(self.n))) if k: self.start = (self.start+k) % self.cap; self.n -= k def __iter__(self): return (self.mm[self._phys(j)] for j in range(self.n)) def clear(self): self.start = 0; self.n = 0 def patch(root): """Swap every multi-frame (history-camera) buffer of the robomemarena policy class for a DiskFrames buffer.""" import robomemarena_sim.policy as native cls = native.RoboMemArenaPolicy if getattr(cls, '_disk_frames_patched', False): return original = cls.__init__ def __init__(self, *args, **kwargs): original(self, *args, **kwargs) for key, cap in self._buffer_caps.items(): if cap > 1: self._buffers[key] = DiskFrames(os.path.join(root, key.replace('/', '_'))) cls.__init__ = __init__; cls._disk_frames_patched = True