File size: 4,463 Bytes
5a3fcf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Random access to the preprocessed shards (scripts/preprocess.py, listed by scripts/build_index.py).

One sample: agent and wrist images of one frame (uint8, res x res; a black wrist image and wrist_valid False when
the dataset has no wrist camera), the normalized 6-D joint state, and the next `chunk` actions normalized with the
dataset's statistics, padded with the episode's last action (act_mask False there).
  action_mode "delta"   a[t+k] - s[t] (relative to the current joint state, the joint-space form of PoP's
                        gripper-relative actions), normalized with delta_mean / delta_std
  action_mode "abs"     a[t+k], normalized with action_mean / action_std
"""
from __future__ import annotations

import json
import os

import numpy as np
import torch
from torch.utils.data import Dataset


class ShardDataset(Dataset):
    def __init__(self, shards_dir: str, chunk: int, action_mode: str = "delta"):
        assert action_mode in ("delta", "abs"), action_mode
        idx = json.load(open(os.path.join(shards_dir, "index.json")))
        assert chunk <= idx["chunk"] or action_mode == "abs", "delta statistics were computed for a shorter chunk"
        self.dir, self.res, self.chunk, self.mode = shards_dir, idx["res"], chunk, action_mode
        self.shards = idx["shards"]
        self.offsets = np.cumsum([0] + [s["frames"] for s in self.shards]).astype(np.int64)
        self.N = int(self.offsets[-1])
        st, ac, end, sid = [], [], [], []
        mu_s, sd_s, mu_a, sd_a = [], [], [], []
        for k, s in enumerate(self.shards):
            d = os.path.join(shards_dir, s["dir"])
            z = np.load(os.path.join(d, "arrays.npz"))
            eps = json.load(open(os.path.join(d, "episodes.json")))
            stats = json.load(open(os.path.join(d, "stats.json")))
            st.append(z["state"]); ac.append(z["action"])
            ep_end = np.array([e["start"] + e["length"] for e in eps], np.int64)
            end.append(ep_end[z["ep"]] + self.offsets[k])
            sid.append(np.full(s["frames"], k, np.int32))
            pre = "delta" if action_mode == "delta" else "action"
            mu_s.append(stats["state_mean"]); sd_s.append(stats["state_std"])
            mu_a.append(stats[f"{pre}_mean"]); sd_a.append(stats[f"{pre}_std"])
        self.state = np.concatenate(st).astype(np.float32)
        self.action = np.concatenate(ac).astype(np.float32)
        self.end = np.concatenate(end)
        self.sid = np.concatenate(sid)
        self.mu_s, self.sd_s = np.array(mu_s, np.float32), np.array(sd_s, np.float32)
        self.mu_a, self.sd_a = np.array(mu_a, np.float32), np.array(sd_a, np.float32)
        self.has_wrist = [s["has_wrist"] for s in self.shards]
        self._mm = {}
        self._black = np.zeros((self.res, self.res, 3), np.uint8)

    def __len__(self):
        return self.N

    def _images(self, k: int):
        if k not in self._mm:
            d = os.path.join(self.dir, self.shards[k]["dir"])
            shape = (self.shards[k]["frames"], self.res, self.res, 3)
            ag = np.memmap(os.path.join(d, "agent.u8"), np.uint8, "r", shape=shape)
            wr = np.memmap(os.path.join(d, "wrist.u8"), np.uint8, "r", shape=shape) if self.has_wrist[k] else None
            self._mm[k] = (ag, wr)
        return self._mm[k]

    def __getitem__(self, i):
        k = int(self.sid[i])
        j = i - int(self.offsets[k])
        ag, wr = self._images(k)
        ids = np.arange(i, i + self.chunk)
        mask = ids < self.end[i]
        ids = np.minimum(ids, self.end[i] - 1)
        s = self.state[i]
        a = self.action[ids] - s if self.mode == "delta" else self.action[ids]
        return {
            "agent": torch.from_numpy(np.array(ag[j])),
            "wrist": torch.from_numpy(np.array(wr[j]) if wr is not None else self._black),
            "wrist_valid": torch.tensor(wr is not None),
            "state": torch.from_numpy((s - self.mu_s[k]) / self.sd_s[k]),
            "actions": torch.from_numpy((a - self.mu_a[k]) / self.sd_a[k]),
            "act_mask": torch.from_numpy(mask),
        }

    def norm_stats(self) -> dict:
        """Per-dataset statistics, saved with every checkpoint."""
        return {s["dataset"]: {"state_mean": self.mu_s[k].tolist(), "state_std": self.sd_s[k].tolist(),
                               "action_mean": self.mu_a[k].tolist(), "action_std": self.sd_a[k].tolist()}
                for k, s in enumerate(self.shards)}