LITOperator / sandbox /lerobot_host /lit_codec.py
OzTianlu's picture
Duplicate from ReasoningKingdom/LITOperator
1ddfac5
Raw History Blame Contribute Delete
14 kB
#!/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))