File size: 2,788 Bytes
80a8599 | 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 | """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
|