LITOperator / sandbox /lerobot_host /lit_drive.py
OzTianlu's picture
Duplicate from ReasoningKingdom/LITOperator
1ddfac5
Raw History Blame Contribute Delete
8.65 kB
#!/usr/bin/env python3
"""lit_drive.py — open-set drive host: DO search, no nearest neighbor.
There is no demo replay and no nearest-zero estimate. Every decision
opens the search set:
root = the current observation key (16-hex)
actions = the tree's stored children + freshly sampled actions
expand = the next state (the action target is the next proprio
state, or the bound world's step)
judge = the task's one-line IF
The operator searches; the first action of the found path drives the
arm. If no path reaches the judge, no action is fabricated: the caller
gets ``None`` and the search set stays open.
"""
import argparse
import ctypes as C
import random
import sys
from lit_codec import FeatureCodec
from lit_libero import (
ACTIONS_FN,
EVENT_FN,
EXPAND_FN,
LIB,
LIT_SEARCH_FOUND,
LitAction,
LitHost,
LitKey,
LitPath,
LitSearchOpts,
ROOT_FN,
)
LIB.lit_search_follow.argtypes = [
C.c_void_p, C.POINTER(LitAction), C.c_size_t, C.POINTER(LitKey)]
LIB.lit_search_follow.restype = C.c_uint32
LIB.lit_search_node.argtypes = [
C.c_void_p, C.c_uint32, C.POINTER(__import__("lit_libero").LitNodeView)]
LIB.lit_search_node.restype = C.c_int
INVALID = 0xFFFFFFFF
def sample_code(codec, rng):
code = 0
shift = 0
for d in codec.action_dims:
code |= rng.randrange(1 << d.bits) << shift
shift += d.bits
return code & ((1 << 64) - 1)
class OpenHost:
"""One search, rooted at the current observation, action set open.
``world.step(words, code) -> (next_words, success)`` binds the real
arm or a simulator. Without a world the next state is kinematic:
the action target is the next proprioceptive state.
"""
def __init__(self, codec, root_words, open_actions=1, seed=0,
world=None, judge=None, max_depth=8):
self.codec = codec
self.root_words = list(root_words)
self.open_actions = int(open_actions)
self.rng = random.Random(seed)
self.world = world
self.judge = judge or (lambda code, words: 0)
self.max_depth = max_depth
self.s = None
self.current_children = []
self.goal_action = None # a one-step win found during expansion
self._buf = None
self._root_cb = ROOT_FN(self._root)
self._actions_cb = ACTIONS_FN(self._actions)
self._expand_cb = EXPAND_FN(self._expand)
self._event_cb = EVENT_FN(self._event)
self.host = LitHost()
self.host.root = self._root_cb
self.host.actions = self._actions_cb
self.host.expand = self._expand_cb
self.host.event = self._event_cb
# -- state model --------------------------------------------------
def _kinematic(self, code):
vec = self.codec.action_vec(code)
words = [0] * 64
for j, (_n, _i, d) in enumerate(self.codec.state_slots[:64]):
if j < len(vec):
words[j] = d.state_word(vec[j])
return words
def _step(self, words, code):
if self.world is not None:
return self.world.step(words, code)
nw = self._kinematic(code)
return nw, int(self.judge(code, nw))
def _path_words(self, path, path_len):
words = list(self.root_words)
for j in range(path_len):
code = path[j].id | (path[j].x << 32)
words, _ok = self._step(words, code)
return words
# -- callbacks ----------------------------------------------------
def _root(self, ctx, key, goal, dead):
_ = ctx
k = self.codec.state_key(self.root_words)
key[0].hi, key[0].lo = k, 0
goal[0] = 0
dead[0] = 0
return 0
def _actions(self, ctx, path, path_len, acts_out, n_out):
_ = ctx, acts_out
children = []
if self.s is not None and path_len < self.max_depth:
node = LIB.lit_search_follow(self.s, path, path_len, None)
if node != INVALID:
v = LitNodeView()
if LIB.lit_search_node(self.s, node, C.byref(v)) == 0:
c = v.first_child
while c != INVALID:
cv = LitNodeView()
if LIB.lit_search_node(self.s, c,
C.byref(cv)) != 0:
break
children.append(cv.act)
c = cv.next_sibling
self.current_children = children
if path_len >= self.max_depth:
n_out[0] = 0
return 0
samples = [LitAction(0, code & 0xFFFFFFFF,
(code >> 32) & 0xFFFFFFFF, 0, 1)
for code in (sample_code(self.codec, self.rng)
for _ in range(self.open_actions))]
total = len(children) + len(samples)
if total == 0:
n_out[0] = 0
return 0
if self._buf is None or len(self._buf) < total:
self._buf = (LitAction * total)()
for i, a in enumerate(children):
self._buf[i] = a
for j, a in enumerate(samples):
self._buf[len(children) + j] = a
acts_out[0] = C.cast(self._buf, C.POINTER(LitAction))
n_out[0] = total
return 0
def _expand(self, ctx, path, path_len, acts, child_g, nacts,
keys, goals, deads):
_ = ctx, child_g
nc = len(self.current_children)
words = self._path_words(path, path_len)
for i in range(nacts):
if i < nc:
cv = self.current_children[i]
code = cv.id | (cv.x << 32)
stored_goal = int(cv.goal)
else:
code = acts[i].id | (acts[i].x << 32)
stored_goal = 0
nw, ok = self._step(words, code)
ok = int(ok) or stored_goal
if ok and self.goal_action is None:
self.goal_action = code
nk = self.codec.state_key(nw)
keys[i].hi, keys[i].lo = nk, 0
goals[i] = int(ok)
deads[i] = 0
return 0
def _event(self, ctx, path, path_len, pops, nodes, open_n, g, score,
goal):
_ = ctx, path, pops, nodes, open_n, g, score, goal
# LitNodeView is defined in lit_libero; import it late to keep argtypes
from lit_libero import LitNodeView # noqa: E402
def act(codec, frame, open_actions=1, max_nodes=1, seed=0, world=None,
judge=None, max_depth=8):
"""One open-set decision. Returns (action_vector|None, rc, path_len)."""
words = codec.state_words(frame)
h = OpenHost(codec, words, open_actions=open_actions, seed=seed,
world=world, judge=judge, max_depth=max_depth)
s = LIB.lit_search_new(C.byref(h.host))
if not s:
raise RuntimeError("lit_search_new failed")
h.s = s
opts = LitSearchOpts(max_steps=0, max_nodes=max_nodes)
path = LitPath()
try:
rc = LIB.lit_search_continue(s, C.byref(opts), C.byref(path))
out = None
if rc == LIT_SEARCH_FOUND and path.n:
code = path.acts[0].id | (path.acts[0].x << 32)
out = codec.action_vec(code)
elif h.goal_action is not None:
# one-step open search: the expansion itself found a win
out = codec.action_vec(h.goal_action)
rc = LIT_SEARCH_FOUND
return out, rc, path.n
finally:
LIB.lit_path_free(C.byref(path))
LIB.lit_search_free(s)
def main(argv):
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--demo", action="store_true",
help="synthetic judge: succeed on action dim0 bin 0")
p.add_argument("--seed", type=int, default=0)
args = p.parse_args(argv[1:])
if not args.demo:
raise SystemExit(__doc__)
# A tiny synthetic codec: 2 action dims, 8 bits each, 2 state dims.
from lit_codec import Dim
codec = FeatureCodec(
"demo",
{"action": {"dtype": "float32", "shape": [2]},
"s0": {"dtype": "float32", "shape": [1]},
"s1": {"dtype": "float32", "shape": [1]}},
{"action": {"min": [0.0, 0.0], "max": [1.0, 1.0]}},
[])
frame = {"s0": 0.5, "s1": 0.5, "action": [0.0, 0.0],
"task_index": 0}
def judge(code, words):
_ = words
return 1 if (code & 0xFFFF) < 0x4000 else 0
out, rc, n = act(codec, frame, seed=args.seed, judge=judge)
print("rc=%d path=%d action=%s" % (rc, n, out))
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv))