Instructions to use NoesisLab/LITOperator with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- LeRobot
How to use NoesisLab/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
File size: 20,462 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 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 | #!/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}
|