LITOperator / lit_operator /lit_world.py
OzTianlu's picture
Duplicate from ReasoningKingdom/LITOperator
1ddfac5
Raw History Blame Contribute Delete
20.5 kB
#!/usr/bin/env python3
"""lit_world.py — the generic, open-loop LIT world model.
The C operator is the model: one persistent causal tree of
(observation key, action, next key). Inference is open-loop:
program(obs) -> [action, action, ...]
Search the tree once from the observation and return the whole path to
a goal. The host executes that program open-loop; the model never asks
the world for feedback during inference. This is what keeps it general:
the output is an action program, not a controller tied to one loop.
The same file also carries `learn`, the tree-growth loop used for data
ingestion and self-bootstrapping: observation -> tree -> action -> step
-> ingest. That loop is training, not inference.
A world is anything with reset/step and a way to name its observations
and actions. The adapter supplies only:
reset() -> observation
step(action) -> observation
key(obs) -> (hi, lo) one 128-bit state key
judge(obs) -> (goal, dead) one line of IF
actions(obs) -> [action, ...] legal actions here
encode(action) -> LitAction opaque to the operator
decode(lit_action) -> action
sample(obs, rng) -> action | None optional open action
Everything else — the tree, the seen set, the visit counts, the path,
the persistence — is here and is shared by every world: ARC-AGI-3,
LIBERO, LeRobot, a real arm.
Policy:
1. BFS over the tree from the current node to a known goal;
2. an untried legal action at the current node (open set);
3. an adapter-sampled open action (ACTION6 coordinates, etc.);
4. the least-visited non-dead child (backtracking).
"""
import ctypes as C
import os
import random
import sys
import time
from collections import deque
HERE = os.path.dirname(os.path.abspath(__file__))
LIB_NAME = "liblit.dylib" if sys.platform == "darwin" else "liblit.so"
LIB_PATHS = (
os.path.join(HERE, LIB_NAME),
os.path.join(HERE, "..", "sandbox", "lerobot_host", LIB_NAME),
os.path.join(HERE, "..", LIB_NAME),
)
for _p in LIB_PATHS:
if os.path.exists(_p):
LIB_PATH = os.path.abspath(_p)
break
else:
raise OSError("liblit not built; run: make lib")
LIB = C.CDLL(LIB_PATH)
# ---------------------------------------------------------------- ABI
# The one Python binding of the C operator. Every host imports these
# names from here; no host owns a copy.
class LitKey(C.Structure):
_fields_ = [("hi", C.c_uint64), ("lo", C.c_uint64)]
class LitAction(C.Structure):
_fields_ = [
("kind", C.c_uint32),
("id", C.c_uint32),
("x", C.c_uint32),
("y", C.c_uint32),
("cost", C.c_uint32),
]
class LitNodeView(C.Structure):
_fields_ = [
("parent", C.c_uint32),
("depth", C.c_uint32),
("g", C.c_uint64),
("key", LitKey),
("act", LitAction),
("first_child", C.c_uint32),
("next_sibling", C.c_uint32),
("goal", C.c_uint8),
("dead", C.c_uint8),
("expanded", C.c_uint8),
]
class LitSearchOpts(C.Structure):
_fields_ = [("max_steps", C.c_uint64), ("max_nodes", C.c_uint64)]
class LitPath(C.Structure):
_fields_ = [
("acts", C.POINTER(LitAction)),
("n", C.c_size_t),
("pops", C.c_uint64),
("nodes", C.c_uint64),
]
ROOT_FN = C.CFUNCTYPE(
C.c_int, C.c_void_p, C.POINTER(LitKey), C.POINTER(C.c_int),
C.POINTER(C.c_int))
ACTIONS_FN = C.CFUNCTYPE(
C.c_int, C.c_void_p, C.POINTER(LitAction), C.c_size_t,
C.POINTER(C.POINTER(LitAction)), C.POINTER(C.c_size_t))
EXPAND_FN = C.CFUNCTYPE(
C.c_int, C.c_void_p, C.POINTER(LitAction), C.c_size_t,
C.POINTER(LitAction), C.POINTER(C.c_uint64), C.c_size_t,
C.POINTER(LitKey), C.POINTER(C.c_int), C.POINTER(C.c_int))
EVAL_FN = C.CFUNCTYPE(
C.c_int, C.c_void_p, C.POINTER(LitAction), C.c_size_t,
C.POINTER(LitAction), C.c_uint64, C.POINTER(LitKey),
C.POINTER(C.c_int), C.POINTER(C.c_int))
SEEK_FN = C.CFUNCTYPE(C.c_int, C.c_void_p, C.POINTER(LitKey))
EVENT_FN = C.CFUNCTYPE(
None, C.c_void_p, C.POINTER(LitAction), C.c_size_t, C.c_uint64,
C.c_uint64, C.c_size_t, C.c_double, C.c_double, C.c_int)
CHOOSE_FN = C.CFUNCTYPE(
C.c_int, C.c_void_p, C.POINTER(LitNodeView), C.c_size_t,
C.POINTER(C.c_uint32))
SCORE_FN = C.CFUNCTYPE(
C.c_int, C.c_void_p, C.POINTER(LitNodeView), C.c_size_t,
C.POINTER(C.c_uint64))
class LitHost(C.Structure):
_fields_ = [
("ctx", C.c_void_p),
("root", ROOT_FN),
("actions", ACTIONS_FN),
("expand", EXPAND_FN),
("eval", EVAL_FN),
("seek", SEEK_FN),
("event", EVENT_FN),
("choose", CHOOSE_FN),
("score", SCORE_FN),
]
LIB.lit_search_new.argtypes = [C.POINTER(LitHost)]
LIB.lit_search_new.restype = C.c_void_p
LIB.lit_search_continue.argtypes = [
C.c_void_p, C.POINTER(LitSearchOpts), C.POINTER(LitPath)]
LIB.lit_search_continue.restype = C.c_int
LIB.lit_search_ingest.argtypes = [
C.c_void_p, C.c_uint32, C.POINTER(LitAction), LitKey, C.c_uint64,
C.c_int, C.c_int]
LIB.lit_search_ingest.restype = C.c_uint32
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(LitNodeView)]
LIB.lit_search_node.restype = C.c_int
LIB.lit_search_stats.argtypes = [
C.c_void_p, C.POINTER(C.c_uint64), C.POINTER(C.c_uint64),
C.POINTER(C.c_uint64)]
LIB.lit_search_save_json.argtypes = [C.c_void_p, C.c_char_p]
LIB.lit_search_save_json.restype = C.c_int
LIB.lit_search_save_safetensors.argtypes = [C.c_void_p, C.c_char_p]
LIB.lit_search_save_safetensors.restype = C.c_int
LIB.lit_search_load_json.argtypes = [C.POINTER(LitHost), C.c_char_p]
LIB.lit_search_load_json.restype = C.c_void_p
LIB.lit_search_load_safetensors.argtypes = [C.POINTER(LitHost), C.c_char_p]
LIB.lit_search_load_safetensors.restype = C.c_void_p
LIB.lit_search_free.argtypes = [C.c_void_p]
LIB.lit_path_free.argtypes = [C.POINTER(LitPath)]
LIT_SEARCH_FOUND = 0
LIT_SEARCH_EMPTY = 1
LIT_SEARCH_BUDGET = 2
U32 = 0xFFFFFFFF
def manhattan(a, b):
"""L1 distance between two positions; the wandering guard's ruler."""
return sum(abs(float(x) - float(y)) for x, y in zip(a, b))
class Owner:
"""The ctypes host the operator holds; root is one level start."""
def __init__(self):
self.root_key = (0, 0)
self._root_cb = ROOT_FN(self._root)
self._actions_cb = ACTIONS_FN(self._actions)
self._expand_cb = EXPAND_FN(self._expand)
self.host = LitHost()
self.host.root = self._root_cb
self.host.actions = self._actions_cb
self.host.expand = self._expand_cb
def _root(self, ctx, key, goal, dead):
_ = ctx
key[0].hi, key[0].lo = self.root_key
goal[0] = 0
dead[0] = 0
return 0
def _actions(self, ctx, path, path_len, acts, n_out):
_ = ctx, path, path_len, acts
n_out[0] = 0
return 0
def _expand(self, ctx, path, path_len, acts, child_g, nacts,
keys, goals, deads):
_ = ctx, path, path_len, acts, child_g, nacts, keys, goals, deads
return 0
class Session:
"""One LIT tree rooted at one world-start observation key."""
def __init__(self, owner, root_key, s=None):
self.owner = owner
self.root_key = root_key
self.root_node = 0
self.key_node = {root_key: 0}
self.visits = {0: 0}
self.has_goal = False
if s is None:
owner.root_key = root_key
self.s = LIB.lit_search_new(C.byref(owner.host))
if not self.s:
raise RuntimeError("lit_search_new failed")
else:
self.s = s
self.rebuild()
def rebuild(self):
n, _u, _o = self.stats()
for i in range(n):
v = self.node(i)
if v is not None:
self.key_node.setdefault((v.key.hi, v.key.lo), i)
self.visits.setdefault(i, 0)
if v.goal:
self.has_goal = True
v0 = self.node(0)
if v0 is not None:
self.root_key = (v0.key.hi, v0.key.lo)
def stats(self):
n, u, o = C.c_uint64(), C.c_uint64(), C.c_uint64()
LIB.lit_search_stats(self.s, C.byref(n), C.byref(u), C.byref(o))
return n.value, u.value, o.value
def node(self, i):
v = LitNodeView()
if LIB.lit_search_node(self.s, i, C.byref(v)) != 0:
return None
return v
def children(self, node):
out = []
v = self.node(node)
if v is None:
return out
c = v.first_child
while c != U32:
cv = self.node(c)
if cv is None:
break
out.append((c, cv))
c = cv.next_sibling
return out
@staticmethod
def same_act(a, b):
return (a.kind, a.id, a.x, a.y) == (b.kind, b.id, b.x, b.y)
def ingest(self, parent, act, key, goal, dead):
for idx, cv in self.children(parent):
if self.same_act(cv.act, act) and \
(cv.key.hi, cv.key.lo) == key:
return idx
pv = self.node(parent)
g = pv.g + 1 if pv else 1
idx = LIB.lit_search_ingest(self.s, parent, C.byref(act),
LitKey(key[0], key[1]), g, goal, dead)
if idx == U32:
raise RuntimeError("ingest failed")
self.key_node.setdefault(key, idx)
self.visits.setdefault(idx, 0)
if goal:
self.has_goal = True
return idx
def plan(self, start):
"""BFS over known children: the nearest goal path, or None."""
if not self.has_goal:
return None
v = self.node(start)
if v is None:
return None
if v.goal:
return []
seen = {start}
q = deque([(start, [])])
while q:
node, path = q.popleft()
for idx, cv in self.children(node):
if idx in seen:
continue
seen.add(idx)
step = list(path) + [cv.act]
if cv.goal:
return step
if not cv.dead:
q.append((idx, step))
return None
def save(self, path):
os.makedirs(os.path.dirname(path), exist_ok=True)
return LIB.lit_search_save_safetensors(self.s, path.encode())
def free(self):
if self.s:
LIB.lit_search_free(self.s)
self.s = None
class LitWorld:
"""The generic model: one tree session per start key, one policy."""
def __init__(self, world, trees_dir=None, prefix="", seed=0):
self.world = world
self.owner = Owner()
self.sessions = {}
self.trees_dir = trees_dir
self.prefix = prefix
self.rng = random.Random(seed)
self.pos = {} # node -> position
self.walk = {} # node -> absolute Manhattan walk from the root
self.pruned = 0
if trees_dir:
self.load()
def _pos(self, obs):
"""Optional world.position(obs): the host's ruler, never the core's."""
fn = getattr(self.world, "position", None)
if fn is None:
return None
try:
p = fn(obs)
return tuple(float(x) for x in p) if p is not None else None
except Exception:
return None
def _root_pos(self, sess, obs):
p = self._pos(obs)
if p is not None:
self.pos.setdefault(sess.root_node, p)
self.walk.setdefault(sess.root_node, 0.0)
def _wandering(self, sess, parent, pos, walked):
"""Absolute Manhattan triangle inequality, no parameters.
walked(A -> C) >= d(A, C) with equality exactly on a shortest
path. Any excess is a detour; standing still is allowed, because
the state itself can change while the position does not. The
anchor is the session root and no window is used.
"""
ppos = self.pos.get(parent)
if ppos is None:
return False, walked
walked += manhattan(pos, ppos)
root_pos = self.pos.get(sess.root_node)
if root_pos is None:
return False, walked
direct = manhattan(pos, root_pos)
return (walked > direct), walked
def load_tree(self, path):
"""Load one safetensors tree as the model's world."""
s = LIB.lit_search_load_safetensors(
C.byref(self.owner.host), os.fspath(path).encode())
if not s:
raise RuntimeError("tree load failed: %s" % path)
sess = Session(self.owner, (0, 0), s)
self.sessions[sess.root_key] = sess
return sess
def load(self):
if not self.trees_dir or not os.path.isdir(self.trees_dir):
return
pfx = self.prefix + "_"
for name in sorted(os.listdir(self.trees_dir)):
if not name.startswith(pfx) or not name.endswith(".safetensors"):
continue
path = os.path.join(self.trees_dir, name)
s = LIB.lit_search_load_safetensors(C.byref(self.owner.host),
path.encode())
if not s:
continue
sess = Session(self.owner, (0, 0), s)
self.sessions[sess.root_key] = sess
print("loaded tree %s nodes %d" % (name, sess.stats()[0]),
flush=True)
def save(self):
for key, sess in self.sessions.items():
path = os.path.join(self.trees_dir, "%s_%016x%016x.safetensors"
% (self.prefix, key[0], key[1]))
if sess.save(path) == 0:
print("saved %s nodes %d" % (os.path.basename(path),
sess.stats()[0]), flush=True)
def free(self):
for sess in self.sessions.values():
sess.free()
def session(self, key):
if key not in self.sessions:
self.sessions[key] = Session(self.owner, key)
print("new tree %s %016x%016x sessions %d"
% (self.prefix, key[0], key[1], len(self.sessions)),
flush=True)
return self.sessions[key]
def program_key(self, key):
"""Open-loop inference from an observation key already in hand."""
for sess in self.sessions.values():
node = sess.key_node.get(key)
if node is None:
continue
path = sess.plan(node)
if path is None:
return None
return [self.world.decode(a) for a in path]
return None
def program(self, obs):
"""Open-loop inference: observation -> the whole action path.
Search the tree once; never call world.step. Returns a list of
host actions, or None when the tree knows no goal path from this
observation. The caller executes the program open-loop.
"""
return self.program_key(self.world.key(obs))
def choose(self, obs, sess, cur, kids):
w = self.world
path = sess.plan(cur)
if path:
return w.decode(path[0]), "plan"
sug = getattr(w, "suggest", None)
if sug is not None:
a = sug(obs, self.rng)
if a is not None:
return a, "suggest"
tried = {(cv.act.kind, cv.act.id, cv.act.x, cv.act.y)
for _i, cv in kids}
for a in w.actions(obs):
la = w.encode(a)
if (la.kind, la.id, la.x, la.y) not in tried:
return a, "open"
a = w.sample(obs, self.rng)
if a is not None:
return a, "sample"
alive = [(i, cv) for i, cv in kids if not cv.dead]
pool = alive or kids
if pool:
_i, best = min(pool, key=lambda t: sess.visits.get(t[0], 0))
return w.decode(best.act), "backtrack"
legal = w.actions(obs)
return (self.rng.choice(legal) if legal else None), "random"
def learn(self, max_steps, log_every=5.0, verbose=False, save=True,
on_step=None, stop_on_win=False):
"""Tree growth: observe -> tree -> act -> step -> ingest.
A host that exposes `position(obs)` gets the Manhattan triangle
guard for free: walked(A -> C) > d(A, C) is a detour, so that
node is ingested dead and the search never plans through the
water step. Standing still is allowed: the position need not
change while the state does. No window, no ratio, no threshold.
The C core still only compares keys, actions, and dead flags.
This is training/self-bootstrapping, not inference. Inference
is `program`, which returns a whole open-loop action path.
"""
w = self.world
obs = w.reset()
sess = self.session(w.key(obs))
cur = sess.root_node
sess.visits[cur] = sess.visits.get(cur, 0) + 1
self._root_pos(sess, obs)
wins = deads = steps = 0
t0 = last = time.time()
try:
while steps < max_steps:
goal, dead = w.judge(obs)
if dead:
deads += 1
obs = w.reset()
sess = self.session(w.key(obs))
cur = sess.root_node
sess.visits[cur] = sess.visits.get(cur, 0) + 1
self._root_pos(sess, obs)
continue
if goal:
wins += 1
print("WIN at step %d (%d/%d levels)"
% (steps, getattr(obs, "levels_completed", 0),
getattr(obs, "win_levels", 0)), flush=True)
if stop_on_win:
break
obs = w.reset()
sess = self.session(w.key(obs))
cur = sess.root_node
sess.visits[cur] = sess.visits.get(cur, 0) + 1
self._root_pos(sess, obs)
continue
kids = sess.children(cur)
act, why = self.choose(obs, sess, cur, kids)
if act is None:
break
obs2 = w.step(act)
if obs2 is None:
obs = w.reset()
sess = self.session(w.key(obs))
cur = sess.root_node
self._root_pos(sess, obs)
continue
g2, d2 = w.judge(obs2)
dead = int(d2)
parent = cur
pos = self._pos(obs2)
walked = self.walk.get(parent, 0.0)
if pos is not None:
pruned, walked = self._wandering(
sess, parent, pos, walked)
if pruned:
dead = 1
self.pruned += 1
cur = sess.ingest(cur, w.encode(act), w.key(obs2),
int(g2), dead)
if pos is not None:
self.pos[cur] = pos
self.walk[cur] = walked
sess.visits[cur] = sess.visits.get(cur, 0) + 1
obs = obs2
steps += 1
if on_step is not None:
on_step(steps, obs, act, why, sess.stats())
if verbose:
print("step %d %s %s" % (steps, act, why), flush=True)
now = time.time()
if now - last >= log_every:
n, u, o = sess.stats()
print("hb steps=%d nodes=%d unique=%d open=%d "
"wins=%d deads=%d pruned=%d fps=%.0f"
% (steps, n, u, o, wins, deads, self.pruned,
steps / (now - t0)), flush=True)
last = now
finally:
if save:
self.save()
return {"steps": steps, "wins": wins, "deads": deads,
"pruned": self.pruned, "sessions": len(self.sessions),
"elapsed": time.time() - t0}