File size: 13,965 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
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
#!/usr/bin/env python3
"""lit_codec.py — the universal 64-bit / 16-hex codec.

Every state dim and every action dim is one u64; the wire form is
exactly 16 hex digits.  A state is a fixed 64-slot u64 vector (pad with
zero); its key is a 64-bit hash, also written as 16 hex digits.  An
action is packed dims in one u64, again 16 hex digits.

The codec is schema-driven: the robot/dataset supplies dim ranges and
bit widths, and the codec never interprets them.  The operator sees only
the resulting u64 key/action; the tree can be shared across schemas
because every key is schema-tagged.
"""
import hashlib
import struct

U64 = 1 << 64
U64_MASK = U64 - 1
SLOTS = 64


def hex16(v):
    """One u64 -> exactly 16 hex digits."""
    return format(v & U64_MASK, "016x")


def unhex16(s):
    """16 hex digits -> one u64."""
    return int(s, 16) & U64_MASK


class Dim:
    """One scalar dimension: name, range, and action bit width."""

    __slots__ = ("name", "lo", "hi", "bits")

    def __init__(self, name, lo=-1.0, hi=1.0, bits=8):
        self.name = name
        self.lo = float(lo)
        self.hi = float(hi)
        self.bits = int(bits)

    def state_word(self, x):
        """Hard float -> u64: the raw IEEE-754 double bits.

        No range, no rounding, no normalization: the state slot is the
        exact float.  The 16-hex wire form is the exact bit pattern.
        """
        return struct.unpack("<Q", struct.pack("<d", float(x)))[0]

    def action_q(self, x):
        """Hard float -> action bin: truncation, no rounding."""
        x = min(max(float(x), self.lo), self.hi)
        n = (1 << self.bits) - 1
        if self.hi == self.lo:
            return 0
        return int((x - self.lo) / (self.hi - self.lo) * n)

    def action_x(self, q):
        """Inverse of action_q."""
        n = (1 << self.bits) - 1
        if n == 0:
            return self.lo
        return self.lo + (q / n) * (self.hi - self.lo)


class Schema:
    """A robot/dataset schema: state dims and action dims.

    The schema id is folded into the state key, so two robots with the
    same numbers never collide; one tree can hold both.
    """

    def __init__(self, name, state_dims, action_dims):
        self.name = name
        self.state_dims = list(state_dims)
        self.action_dims = list(action_dims)
        if len(self.state_dims) > SLOTS:
            raise ValueError("state needs <= %d dims" % SLOTS)
        total_bits = sum(d.bits for d in self.action_dims)
        if total_bits > 64:
            raise ValueError("action bits exceed 64: %d" % total_bits)
        self.schema_id = int.from_bytes(
            hashlib.blake2b(name.encode(), digest_size=8).digest(),
            "little")

    # -- state --------------------------------------------------------
    def state_words(self, vec):
        """Variable state vector -> 64 u64 slots (missing dims zero)."""
        if len(vec) != len(self.state_dims):
            raise ValueError("state dim %d != schema %d"
                             % (len(vec), len(self.state_dims)))
        words = [0] * SLOTS
        for i, (d, x) in enumerate(zip(self.state_dims, vec)):
            words[i] = d.state_word(x)
        return words

    def state_key(self, words):
        """64 u64 slots -> one 64-bit state key (16 hex digits)."""
        h = hashlib.blake2b(digest_size=8)
        h.update(struct.pack("<Q", self.schema_id))
        for w in words:
            h.update(struct.pack("<Q", w & U64_MASK))
        return int.from_bytes(h.digest(), "little")

    def key_hex(self, words):
        return hex16(self.state_key(words))

    # -- action -------------------------------------------------------
    def action_code(self, vec):
        """Variable action vector -> one packed u64 (16 hex digits)."""
        if len(vec) != len(self.action_dims):
            raise ValueError("action dim %d != schema %d"
                             % (len(vec), len(self.action_dims)))
        code = 0
        shift = 0
        for d, x in zip(self.action_dims, vec):
            code |= d.action_q(x) << shift
            shift += d.bits
        return code & U64_MASK

    def action_vec(self, code):
        """Packed u64 -> the action vector."""
        vec = []
        shift = 0
        for d in self.action_dims:
            q = (code >> shift) & ((1 << d.bits) - 1)
            vec.append(d.action_x(q))
            shift += d.bits
        return vec

    def action_hex(self, vec):
        return hex16(self.action_code(vec))

    # -- a transition -------------------------------------------------
    def transition(self, state, action, next_state):
        """The causal edge in wire form: (state_hex, action_hex, next_hex)."""
        sw = self.state_words(state)
        nw = self.state_words(next_state)
        return (hex16(self.state_key(sw)),
                hex16(self.action_code(action)),
                hex16(self.state_key(nw)))


def libero_schema(state_dim, action_dim=7, state_lo=-3.0, state_hi=3.0,
                  action_lo=-1.0, action_hi=1.0):
    """A generic schema for a LIBERO-like arm (state/action dims vary)."""
    sd = [Dim("s%d" % i, state_lo, state_hi) for i in range(state_dim)]
    ad = [Dim("a%d" % i, action_lo, action_hi) for i in range(action_dim)]
    return Schema("libero", sd, ad)


def dataset_schema(name, state_dim, action_dim,
                   state_lo=-10.0, state_hi=10.0,
                   action_lo=-1.0, action_hi=1.0):
    """A generic schema for a LeRobot dataset; dims are positional."""
    sd = [Dim("s%d" % i, state_lo, state_hi) for i in range(state_dim)]
    abits = max(1, min(16, 64 // max(1, action_dim)))
    ad = [Dim("a%d" % i, action_lo, action_hi, abits)
          for i in range(action_dim)]
    return Schema(name, sd, ad)


# ---------------------------------------------------------------- universal
# LeRobot features -> 64 x u64 slots + one packed action code.  This is
# the glue layer: LeRobot already names and tokenizes every feature; we
# translate each one into the LIT machine code (16-hex u64).

META_SKIP = {"timestamp", "frame_index", "episode_index", "index",
             "next.done"}
ACTION_NAMES = ("action", "actions")


def image_hash(img):
    """The 8x8 grid is the hash: one channel, hard 128 threshold.

    No channel mean, no average threshold, no pooling: the 8x8 samples
    are the hash; pooling throws away the detail.
    """
    if img is None:
        return 0
    if isinstance(img, int):
        return img & U64_MASK
    import numpy as np
    g = np.asarray(img)
    if g.ndim == 3:
        g = g[..., 0]
    if g.size == 0:
        return 0
    h, w = g.shape[:2]
    g = g[::max(1, h // 8), ::max(1, w // 8)][:8, :8]
    if g.shape[0] < 8 or g.shape[1] < 8:
        return 0
    v = 0
    for x in g.flat:
        v = (v << 1) | (1 if x > 128 else 0)
    return v & U64_MASK


class FeatureCodec:
    """One glue layer for every dataset and every robot.

    Numeric dims get one u64 slot each; video/image gets one 8x8 ahash
    slot; string/task gets one hash slot; action gets one packed u64
    code.  The schema id is the feature layout, so two robots never
    collide in the shared tree.  The operator never interprets any of
    it: it only sees the resulting key and action code.
    """

    def __init__(self, name, features, stats=None, tasks=None):
        self.name = name
        self.features = dict(features)
        self.stats = dict(stats or {})
        self.tasks = list(tasks or [])
        self.state_slots = []   # (feature, dim_index, Dim)
        self.cameras = []       # video/image feature names
        self.texts = []         # string/task feature names
        self.extras = []        # (feature, dim_index) for int/bool
        self.action_dims = []
        self.action_feature = None
        self._build()
        self.schema_id = int.from_bytes(
            hashlib.blake2b(self._layout_bytes(), digest_size=8).digest(),
            "little")

    def _minmax(self, name, n):
        st = self.stats.get(name) or {}
        lo = st.get("min")
        hi = st.get("max")
        if isinstance(lo, (list, tuple)) and len(lo) >= n:
            lo = [float(x) for x in lo[:n]]
        else:
            lo = [-1.0] * n
        if isinstance(hi, (list, tuple)) and len(hi) >= n:
            hi = [float(x) for x in hi[:n]]
        else:
            hi = [1.0] * n
        return lo, hi

    def _build(self):
        for name, spec in self.features.items():
            if name in ACTION_NAMES:
                shape = spec.get("shape") or [1]
                n = int(shape[0]) if shape else 1
                lo, hi = self._minmax(name, n)
                bits = max(1, min(16, 64 // max(1, n)))
                self.action_feature = name
                self.action_dims = [Dim("a%d" % i, lo[i], hi[i], bits)
                                    for i in range(n)]
        slot = 0
        for name, spec in self.features.items():
            if name in ACTION_NAMES or name in META_SKIP:
                continue
            dtype = str(spec.get("dtype", ""))
            shape = spec.get("shape") or [1]
            n = int(shape[0]) if shape else 1
            if name == "task_index" or dtype in ("string", "text"):
                self.texts.append(name)
                slot += 1
            elif dtype in ("video", "image"):
                self.cameras.append(name)
                slot += 1
            elif dtype.startswith("float"):
                lo, hi = self._minmax(name, n)
                for i in range(n):
                    self.state_slots.append(
                        (name, i, Dim("%s_%d" % (name, i), lo[i], hi[i])))
                    slot += 1
            elif dtype.startswith("int") or dtype == "bool":
                for i in range(n):
                    self.extras.append((name, i))
                    slot += 1
        self._slots = slot

    def _layout_bytes(self):
        h = hashlib.blake2b(digest_size=32)
        h.update(self.name.encode())
        for name, spec in self.features.items():
            h.update(name.encode())
            h.update(str(spec.get("dtype", "")).encode())
            h.update(str(spec.get("shape", [])).encode())
        return h.digest()

    def state_words(self, frame):
        """All features -> 64 u64 slots (16 hex each)."""
        words = [0] * SLOTS
        slot = 0
        for name, i, d in self.state_slots:
            if slot >= SLOTS:
                break
            v = frame.get(name, 0.0)
            try:
                v = v[i]
            except Exception:
                v = 0.0
            words[slot] = d.state_word(v)
            slot += 1
        for name in self.cameras:
            if slot >= SLOTS:
                break
            words[slot] = image_hash(frame.get(name))
            slot += 1
        for name in self.texts:
            if slot >= SLOTS:
                break
            if name == "task_index":
                ti = int(frame.get("task_index", 0))
                text = self.tasks[ti] if 0 <= ti < len(self.tasks) else ""
            else:
                text = frame.get(name, "")
            words[slot] = int.from_bytes(
                hashlib.blake2b(str(text).encode(), digest_size=8).digest(),
                "little")
            slot += 1
        for name, i in self.extras:
            if slot >= SLOTS:
                break
            try:
                v = int(frame.get(name, 0)[i])
            except Exception:
                v = 0
            words[slot] = v & U64_MASK
            slot += 1
        if self._slots > SLOTS:
            words[SLOTS - 1] = int.from_bytes(
                hashlib.blake2b(str(sorted(self.features)).encode(),
                                digest_size=8).digest(), "little")
        return words

    def state_key(self, words):
        h = hashlib.blake2b(digest_size=8)
        h.update(struct.pack("<Q", self.schema_id))
        for w in words:
            h.update(struct.pack("<Q", w & U64_MASK))
        return int.from_bytes(h.digest(), "little")

    def key_hex(self, frame):
        return hex16(self.state_key(self.state_words(frame)))

    def action_code(self, action):
        code = 0
        shift = 0
        for i, d in enumerate(self.action_dims):
            v = action[i] if i < len(action) else 0.0
            code |= d.action_q(v) << shift
            shift += d.bits
        return code & U64_MASK

    def action_vec(self, code):
        vec = []
        shift = 0
        for d in self.action_dims:
            q = (code >> shift) & ((1 << d.bits) - 1)
            vec.append(d.action_x(q))
            shift += d.bits
        return vec

    @classmethod
    def from_dataset(cls, name, features, stats=None, tasks=None):
        return cls(name, features, stats, tasks)

    @classmethod
    def from_robot(cls, name, observation_features, action_features,
                   stats=None):
        feats = {}
        act_names = list(action_features.keys())
        feats["action"] = {"dtype": "float32", "shape": [len(act_names)]}
        for k, v in observation_features.items():
            if isinstance(v, tuple) and len(v) == 3:
                feats[k] = {"dtype": "video", "shape": list(v)}
            else:
                feats[k] = {"dtype": "float32", "shape": [1]}
        st = dict(stats or {})
        st.setdefault("action", {"min": [-1.0] * len(act_names),
                                 "max": [1.0] * len(act_names)})
        return cls(name, feats, st, [])


if __name__ == "__main__":
    s = dataset_schema("demo", 7, 7)
    st = [0.1, -0.2, 0.3, 0.0, 0.0, 0.0, 0.5]
    ac = [0.5, 0.0, -0.5, 0.0, 0.0, 0.0, -1.0]
    st2 = [0.2, -0.1, 0.3, 0.0, 0.0, 0.0, 0.5]
    sh, ah, nh = s.transition(st, ac, st2)
    print("state", sh, "action", ah, "next", nh)
    print("len", len(sh), len(ah), len(nh))
    code = s.action_code(ac)
    print("action code", hex16(code), "back", s.action_vec(code))