File size: 1,840 Bytes
1ddfac5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""tree_io.py — read a pretrained LIT tree snapshot with numpy.

The C safetensors loader rejects checkpoints that contain duplicate
keys, which an open-set tree produces.  The snapshot arrays are standard
safetensors tensors, so the render demos read them directly.
"""
import json
import os
import struct
import sys

import numpy as np

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "sandbox", "lerobot_host"))
CKPT = os.path.join(ROOT, "sandbox", "lerobot_host",
                    "community_open_pretrain.safetensors")
REPO = "lerobot/community_dataset_v3"
SUB = "00ri/so100_battery"
LINK = (0.10, 0.12, 0.12, 0.08)
_DT = {"U32": "<u4", "U64": "<u8", "U8": "u1"}


def load_snapshot(path=CKPT):
    with open(path, "rb") as f:
        hlen = struct.unpack("<Q", f.read(8))[0]
        hdr = json.loads(f.read(hlen))
        data = f.read()

    def tensor(name):
        h = hdr[name]
        dt = _DT[h["dtype"]]
        a = h["data_offsets"][0]
        n = int(np.prod(h["shape"]))
        return np.frombuffer(data, dtype=dt, count=n, offset=a).reshape(
            h["shape"])

    return {k: tensor(k) for k in hdr if k != "__metadata__"}


def children_map(parent):
    children = {}
    for i in range(1, len(parent)):
        children.setdefault(int(parent[i]), []).append(i)
    return children


def chain_from(children, g, start, limit=4000):
    """Follow g == 0 (data) children from a start node."""
    cur = start
    path = []
    for _ in range(limit):
        ch = [c for c in children.get(cur, []) if int(g[c]) == 0]
        if not ch:
            break
        nxt = min(ch)
        path.append(nxt)
        cur = nxt
    return path


def data_path(parent, g, limit=4000):
    return chain_from(children_map(parent), g, 0, limit)