Instructions to use ReasoningKingdom/LITOperator with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- LeRobot
How to use ReasoningKingdom/LITOperator with LeRobot:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
Sync the cleaned tree
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499#!/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 toa goal. The host executes that program open-loop; the model never asksthe 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 dataingestion 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 observationsand 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 Cimport osimport randomimport sysimport timefrom 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) breakelse: 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_pLIB.lit_search_continue.argtypes = [ C.c_void_p, C.POINTER(LitSearchOpts), C.POINTER(LitPath)]LIB.lit_search_continue.restype = C.c_intLIB.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_uint32LIB.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_uint32LIB.lit_search_node.argtypes = [ C.c_void_p, C.c_uint32, C.POINTER(LitNodeView)]LIB.lit_search_node.restype = C.c_intLIB.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_intLIB.lit_search_save_safetensors.argtypes = [C.c_void_p, C.c_char_p]LIB.lit_search_save_safetensors.restype = C.c_intLIB.lit_search_load_json.argtypes = [C.POINTER(LitHost), C.c_char_p]LIB.lit_search_load_json.restype = C.c_void_pLIB.lit_search_load_safetensors.argtypes = [C.POINTER(LitHost), C.c_char_p]LIB.lit_search_load_safetensors.restype = C.c_void_pLIB.lit_search_free.argtypes = [C.c_void_p]LIB.lit_path_free.argtypes = [C.POINTER(LitPath)]
LIT_SEARCH_FOUND = 0LIT_SEARCH_EMPTY = 1LIT_SEARCH_BUDGET = 2
U32 = 0xFFFFFFFF
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) if trees_dir: self.load()
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" 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.
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 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 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 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 continue g2, d2 = w.judge(obs2) cur = sess.ingest(cur, w.encode(act), w.key(obs2), int(g2), int(d2)) 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 fps=%.0f" % (steps, n, u, o, wins, deads, steps / (now - t0)), flush=True) last = now finally: if save: self.save() return {"steps": steps, "wins": wins, "deads": deads, "sessions": len(self.sessions), "elapsed": time.time() - t0}lit_operator/lit_world.pyAdded+499