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
Commit ·
1ddfac5
0
Parent(s):
Duplicate from ReasoningKingdom/LITOperator
Browse filesFiles changed (30)
- .gitattributesAdded+56
- LICENSEAdded+21
- MakefileAdded+33
- README.mdAdded+110
- demo/LITOperator_architecture.pngAdded
- demo/demo.pyAdded+58
- demo/lit_lerobot_sim.gifAdded
- demo/selfbootstrap.pyAdded+80
- demo/tree_io.pyAdded+64
- lit_operator/dense.cAdded+94
- lit_operator/dense.hAdded+58
- lit_operator/lit_core.cAdded+675
- lit_operator/lit_core.hAdded+120
- lit_operator/lit_main.cAdded+441
- lit_operator/lit_operator.cAdded+2996
- lit_operator/lit_operator.hAdded+292
- lit_operator/lit_world.pyAdded+572
- replay.mp4Added+3
- sandbox/lerobot_host/lit_codec.pyAdded+388
- sandbox/lerobot_host/lit_drive.pyAdded+247
- sandbox/lerobot_host/lit_libero.pyAdded+205
- sandbox/lerobot_host/lit_pretrain.pyAdded+490
- sandbox/lerobot_host/lit_robot_api.pyAdded+35
- sandbox/lerobot_host/lit_selfloop.pyAdded+456
- sandbox/lerobot_host/lit_stream.pyAdded+472
- sandbox/lerobot_host/requirements.txtAdded+6
- sandbox/lit_robot.pyAdded+76
- weights/LITOperator-community_open_pretrain.safetensorsAdded+3
- weights/LITOperator-community_open_selfboot.safetensorsAdded+3
- weights/README.mdAdded+22
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textLITOperator_architecture.png filter=lfs diff=lfs merge=lfs -textdemo/lit_arm_control_3d.mp4 filter=lfs diff=lfs merge=lfs -textdemo/lit_arm_control_3d.gif filter=lfs diff=lfs merge=lfs -textreplay.mp4 filter=lfs diff=lfs merge=lfs -textdemo/lit_lerobot_sim.gif filter=lfs diff=lfs merge=lfs -textdemo/lit_lerobot_sim.mp4 filter=lfs diff=lfs merge=lfs -textdemo/so_arm100/assets/Base.stl filter=lfs diff=lfs merge=lfs -textdemo/so_arm100/assets/Base_Motor.stl filter=lfs diff=lfs merge=lfs -textdemo/so_arm100/assets/Fixed_Jaw.stl filter=lfs diff=lfs merge=lfs -textdemo/so_arm100/assets/Fixed_Jaw_Motor.stl filter=lfs diff=lfs merge=lfs -textdemo/so_arm100/assets/Lower_Arm.stl filter=lfs diff=lfs merge=lfs -textdemo/so_arm100/assets/Lower_Arm_Motor.stl filter=lfs diff=lfs merge=lfs -textdemo/so_arm100/assets/Moving_Jaw.stl filter=lfs diff=lfs merge=lfs -textdemo/so_arm100/assets/Rotation_Pitch.stl filter=lfs diff=lfs merge=lfs -textdemo/so_arm100/assets/Rotation_Pitch_Motor.stl filter=lfs diff=lfs merge=lfs -textdemo/so_arm100/assets/Upper_Arm.stl filter=lfs diff=lfs merge=lfs -textdemo/so_arm100/assets/Upper_Arm_Motor.stl filter=lfs diff=lfs merge=lfs -textdemo/so_arm100/assets/Wrist_Pitch_Roll.stl filter=lfs diff=lfs merge=lfs -textdemo/so_arm100/assets/Wrist_Pitch_Roll_Motor.stl filter=lfs diff=lfs merge=lfs -textdemo/so_arm100/so_arm100.png filter=lfs diff=lfs merge=lfs -textsandbox/particles/particles_100.png filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021MIT License
Copyright (c) 2026 Zixi Li
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233UNAME_S := $(shell uname -s)ifeq ($(UNAME_S),Darwin)LIB := sandbox/lerobot_host/liblit.dylibLIBFLAGS := -dynamiclibelseLIB := sandbox/lerobot_host/liblit.soLIBFLAGS := -shared -fPICendif
CORES := lit_operator/lit_core.c \ lit_operator/lit_operator.c \ lit_operator/dense.c
.PHONY: all lib product demo clean
all: lib
lib: $(LIB)
$(LIB): $(CORES) lit_operator/lit_core.h lit_operator/lit_operator.h \ lit_operator/dense.h clang -O2 -std=c11 -Wall -Wextra -I lit_operator \ $(LIBFLAGS) $(CORES) -o $(LIB)
product: clang -O2 -std=c11 -Wall -Wextra -Ilit_operator \ lit_operator/*.c -o lit
demo: lib python3 demo/demo.py
clean: rm -f $(LIB) lit123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110---license: mitpipeline_tag: roboticstags:- robotics- robot-learning- robot-world-model- world-model- lerobot- so101- earthrover- exact-controldatasets:- lerobot/community_dataset_v3---
# LITOperator = Li Tsz-kai's Typeball Operator
LITOperator is an exact robot model and robot world model. A small Coperator turns an observation and an instruction into exact action, andstores what actions do as one persistent causal tree.
The state is a 64-slot u64 key (camera hashes, proprio, instructionhash); the action is one packed u64; the judge is one IF. Training,self-bootstrapping and inference are open-set: one open step, one sampledaction, no nearest-neighbor estimate.


## Contract
- State: 64 u64 slots; cameras 8x8 hard hashes; instruction hash; raw IEEE proprio.- Action: one packed u64; hard-quantized from the dataset min/max.- Judge: one line of IF at the halt.- Open set: one open step, one sampled action per decision.
## Training
Open-set ingestion over `lerobot/community_dataset_v3`, streamed overHTTPS, never written to disk. Each observed edge is paired with onesampled counterfactual action; the next state is the action target.
```shcd sandbox/lerobot_hostpython3 lit_pretrain.py --minutes 0 \ --datasets lerobot/community_dataset_v3 --community \ --checkpoint-every 10 --out community_open```
Resume from the safetensors checkpoint (add `--start-root <subdataset>`to resume in the middle of the pass):
```shpython3 lit_pretrain.py --minutes 0 \ --datasets lerobot/community_dataset_v3 --community \ --checkpoint-every 10 --out community_open \ --resume community_open.safetensors```
## Weights
- `weights/LITOperator-community_open_pretrain.safetensors` — the data pass: 635,998 nodes, 318,269 open.- `weights/LITOperator-community_open_selfboot.safetensors` — three minutes of open-set self-bootstrap on top: 666,327 nodes (+30,329), same 318,269 open frontier.
Both snapshots are in this repository under `weights/` and on the Hub.Load with `lit_search_load_safetensors` in C, or inspect with`demo/tree_io.py`.
## Usage
Build the host library and run the one-step demo:
```shmake libmake demo```
## Examples
- `lit_operator/` — the C cores and the open-loop world model (`lit_world.py`).- `sandbox/lerobot_host/` — the LeRobot host.- `sandbox/lit_robot.py` — the foolproof robot interface (`program()`).- `demo/tree_io.py` — snapshot inspector.
## Safety
A research operator, not a certified controller. Enforce velocity, force,workspace, and hardware-stop limits on the robot.
## License
MIT.
## Citation
```bibtex@misc{litoperator2026, author = {Li, Zixi}, title = {LITOperator: the exact robot model and robot world model}, year = {2026}, url = {https://github.com/zixi-reasoning/lit-operator}}```12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758#!/usr/bin/env python3"""demo.py — one open-set decision of the robot model.
Builds the C core as a shared library (`make lib`), then runs the drivehost on a tiny synthetic world: root = the current observation key,actions = one freshly sampled action (open set, one step), judge = oneIF. The first action of the found path is printed.
Run from the repo root:
make demo"""import osimport sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.insert(0, os.path.join(ROOT, "sandbox", "lerobot_host"))
from lit_codec import FeatureCodec # noqa: E402from lit_drive import act # noqa: E402
def build_codec(): """Two action dims, two proprio dims; everything is 16-hex on the wire.""" return 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]}}, [])
def main(): codec = build_codec() frame = {"s0": 0.5, "s1": 0.5, "action": [0.0, 0.0], "task_index": 0}
# The task's one-line IF. This synthetic judge accepts the low # quarter of the first action bin; on a robot it is the real task IF. def judge(code, words): _ = words return 1 if (code & 0xFFFF) < 0x4000 else 0
# One open step per decision. If the single sampled action misses, # the next decision samples again; nothing is fabricated. for decision in range(32): action, rc, path_len = act(codec, frame, seed=decision, judge=judge) if action is not None: print("decision", decision, "rc", rc, "path", path_len) print("action", [round(float(x), 4) for x in action]) return 0 print("no one-step win in 32 decisions") return 1
if __name__ == "__main__": raise SystemExit(main())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980#!/usr/bin/env python3"""selfbootstrap.py — open-set self-bootstrap on a released tree.
Loads a safetensors snapshot, opens the action set (one sampled actionper expansion), and lets the operator grow the tree for a few minuteswithout any new data. The result is a new snapshot for the Hub.
python3 demo/selfbootstrap.py --minutes 3 # weights/LITOperator-community_open_selfboot.safetensors"""import argparseimport ctypes as Cimport osimport sysimport time
HERE = os.path.dirname(os.path.abspath(__file__))ROOT = os.path.dirname(HERE)sys.path.insert(0, os.path.join(ROOT, "sandbox", "lerobot_host"))
from lit_pretrain import DataHost, LIB, search_pass, stats # noqa: E402from lit_stream import make_codec # noqa: E402
BASE = os.path.join(ROOT, "weights", "LITOperator-community_open_pretrain.safetensors")OUT = os.path.join(ROOT, "weights", "LITOperator-community_open_selfboot.safetensors")REPO = "lerobot/community_dataset_v3"ROOT_TAG = "1g0rrr/demo3_frames_grab3"
def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument("--base", default=BASE) p.add_argument("--out", default=OUT) p.add_argument("--minutes", type=float, default=3.0) p.add_argument("--codec-root", default=ROOT_TAG) p.add_argument("--seed", type=int, default=0) args = p.parse_args()
host = DataHost(open_actions=1, new_actions=1, seed=args.seed) s = LIB.lit_search_load_safetensors(C.byref(host.host), args.base.encode()) if not s: raise SystemExit("load failed: " + args.base) host.s = s codec, _info = make_codec(REPO, args.codec_root) host.codec = codec print("base", stats(s), "codec", args.codec_root, flush=True)
t0 = time.time() last = t0 passes = 0 try: while time.time() - t0 < args.minutes * 60.0: rc, _pops, _nodes, _path = search_pass(s, 1) passes += 1 now = time.time() if now - last >= 10.0: n, u, o = stats(s) print("t=%.0fs passes=%d nodes=%d seen=%d open=%d rc=%d" % (now - t0, passes, n, u, o, rc), flush=True) last = now if rc == 1: # LIT_SEARCH_EMPTY break finally: if LIB.lit_search_save_safetensors(s, args.out.encode()) != 0: raise SystemExit("save failed") n, u, o = stats(s) print("saved", args.out, "nodes", n, "seen", u, "open", o, "passes", passes, "elapsed %.1fs" % (time.time() - t0), flush=True) LIB.lit_search_free(s) with open(os.path.splitext(args.out)[0] + ".progress", "w") as f: f.write("selfbootstrap:%s\n" % args.codec_root) return 0
if __name__ == "__main__": raise SystemExit(main())12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364#!/usr/bin/env python3"""tree_io.py — read a pretrained LIT tree snapshot with numpy.
The C safetensors loader rejects checkpoints that contain duplicatekeys, which an open-set tree produces. The snapshot arrays are standardsafetensors tensors, so the render demos read them directly."""import jsonimport osimport structimport sys
import numpy as np
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.insert(0, os.path.join(ROOT, "sandbox", "lerobot_host"))CKPT = os.path.join(ROOT, "sandbox", "lerobot_host", "community_open_pretrain.safetensors")REPO = "lerobot/community_dataset_v3"SUB = "00ri/so100_battery"LINK = (0.10, 0.12, 0.12, 0.08)_DT = {"U32": "<u4", "U64": "<u8", "U8": "u1"}
def load_snapshot(path=CKPT): with open(path, "rb") as f: hlen = struct.unpack("<Q", f.read(8))[0] hdr = json.loads(f.read(hlen)) data = f.read()
def tensor(name): h = hdr[name] dt = _DT[h["dtype"]] a = h["data_offsets"][0] n = int(np.prod(h["shape"])) return np.frombuffer(data, dtype=dt, count=n, offset=a).reshape( h["shape"])
return {k: tensor(k) for k in hdr if k != "__metadata__"}
def children_map(parent): children = {} for i in range(1, len(parent)): children.setdefault(int(parent[i]), []).append(i) return children
def chain_from(children, g, start, limit=4000): """Follow g == 0 (data) children from a start node.""" cur = start path = [] for _ in range(limit): ch = [c for c in children.get(cur, []) if int(g[c]) == 0] if not ch: break nxt = min(ch) path.append(nxt) cur = nxt return path
def data_path(parent, g, limit=4000): return chain_from(children_map(parent), g, 0, limit)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394/* * dense.c — the dense body simulator: symbols x symbols x time. * * The body is never stored. Every cell is a coordinate name, and the * cut mask is a function evaluated on demand. A search therefore * spends memory only on the tree it walks. */#include "dense.h"
#include <string.h>
int dense_init(dense *d, uint32_t symbols, uint64_t steps, int (*cut)(void *ctx, uint32_t a, uint32_t b, uint64_t t), void *ctx){ uint64_t x2;
if (!d || symbols == 0 || steps == 0) { return -1; } x2 = (uint64_t)symbols * symbols; if (x2 > UINT64_MAX / steps) { return -1; } memset(d, 0, sizeof(*d)); d->symbols = symbols; d->steps = steps; d->cells = x2 * steps; d->cut = cut; d->ctx = ctx; return 0;}
void dense_free(dense *d){ if (d) { memset(d, 0, sizeof(*d)); }}
uint64_t dense_cells(const dense *d){ return d ? d->cells : 0;}
uint64_t dense_index(const dense *d, uint32_t a, uint32_t b, uint64_t t){ if (!d || a >= d->symbols || b >= d->symbols || t >= d->steps) { return UINT64_MAX; } return ((t * d->symbols + a) * d->symbols) + b;}
int dense_cell(const dense *d, uint64_t cell, uint32_t *a, uint32_t *b, uint64_t *t){ uint64_t x2;
if (!d || cell >= d->cells) { return -1; } x2 = (uint64_t)d->symbols * d->symbols; if (a) { *a = (uint32_t)((cell / d->symbols) % d->symbols); } if (b) { *b = (uint32_t)(cell % d->symbols); } if (t) { *t = cell / x2; } return 0;}
int dense_cut(const dense *d, uint64_t cell){ uint32_t a; uint32_t b; uint64_t t; uint64_t x2;
if (!d || cell >= d->cells) { return 1; } if (!d->cut) { return 0; } x2 = (uint64_t)d->symbols * d->symbols; b = (uint32_t)(cell % d->symbols); a = (uint32_t)((cell / d->symbols) % d->symbols); t = cell / x2; return d->cut(d->ctx, a, b, t) ? 1 : 0;}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758/* * dense.h — the dense body simulator: symbols x symbols x time. * * Nothing is materialized. The cell count, the linear index, and the * decode are pure arithmetic; the structural mark (cut) is computed by * the mask callback on demand. The body is dense in names and sparse * in memory: a search spends only the tree it actually walks. * * A cell is (a, b, t): symbol a at time t, symbol b at time t+1. Every * cell is hard-connected to every other cell; no edge is stored, and a * DO names a cell by its linear index and jumps there in O(1). */#ifndef DENSE_H#define DENSE_H
#include <stddef.h>#include <stdint.h>
#ifdef __cplusplusextern "C" {#endif
typedef struct { uint32_t symbols; /* X: the alphabet size */ uint64_t steps; /* T: the time slices */ uint64_t cells; /* X * X * T */ /* The causal/domain mask: return non-zero to cut the cell. It is evaluated on demand; no cut is ever stored. */ int (*cut)(void *ctx, uint32_t a, uint32_t b, uint64_t t); void *ctx;} dense;
/* Define the body. No allocation: `cells` is computed, nothing is * stored. `cut` may be NULL (nothing is cut). Returns 0 or -1. */int dense_init(dense *d, uint32_t symbols, uint64_t steps, int (*cut)(void *ctx, uint32_t a, uint32_t b, uint64_t t), void *ctx);void dense_free(dense *d);
uint64_t dense_cells(const dense *d);
/* The O(1) jump: (a, b, t) -> linear cell, or UINT64_MAX if out of * range. Any cell to any cell is one DO, so the target needs no edge. */uint64_t dense_index(const dense *d, uint32_t a, uint32_t b, uint64_t t);
/* Decode a linear cell back to (a, b, t). Any out pointer may be NULL. * Returns 0 or -1. */int dense_cell(const dense *d, uint64_t cell, uint32_t *a, uint32_t *b, uint64_t *t);
/* Evaluate the mask for a cell: 1 = cut, 0 = open. Nothing is written; * the whole body is computable at any time. */int dense_cut(const dense *d, uint64_t cell);
#ifdef __cplusplus}#endif#endif /* DENSE_H */123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675/* * lit_core.c — LITCORE: the LIT algebraic core, language-agnostic C. * * The core is brainless and hard-halting. It broadcasts the graph, * computes, reduces by strict-less Hamming, rewires, and repeats; it * never interprets what a symbol or a program means. There is no * semantics inside the core. * * One tick is three steps, in this order: * * 1. transition: next[i] = V[src[i]] * gain[i] * 2. swap: prev = V (the snapshot), V = next * 3. reduction: M[i] = prev[i] & ~V[i] * d += weight[i] * popcount(M[i]) * * The machine holds two arrays, V and prev, and swaps their roles; there * is no third snapshot array. The reduction is the strict-less Hamming: * it counts only the bits that turned OFF, prev=1 -> V=0. The * integer-lattice iteration only ever goes strictly down (there is no * <=, hence no self-connection loop); a self-edge or an increase * contributes d=0, which is the natural halt. The mask M is retained in * diff, per slot: d says how much changed, diff says where. The core * never interprets the mask; it is an observation for the caller. * * The graph (src/gain/weight) lives in the same machine as V. Writing * src/gain is the reconnect; it takes effect on the next tick and does * not itself trigger a commit. The prev snapshot is what keeps * "rewire" and "read" from racing inside one tick. * * A machine owns `clusters` independent copies of the n-slot table. The * same transition is applied to every cluster: that is the broadcast. * Clusters are independent; the reduction is exact integer weighted * Hamming per cluster. * * This file has no CPython dependency. The `lit` dispatcher and the * `litc` CLI link this core; `litc --python` is the C ingest for raw * Python code units. There is no Python interface. */#include "lit_core.h"
#include <stdio.h>#include <stdlib.h>#include <string.h>
#ifdef _OPENMP#include <omp.h>#endif
static inline uint64_t lit_popcount_u64(uint64_t x){ return (uint64_t)__builtin_popcountll(x);}
/* * VF map composition: the map is arrays, not a machine stack. * * F(V)_i = V[s_i] * g_i (self) * G(V)_i = V[r_i] * h_i (other) * (G o F)(V)_i = V[s_{r_i}] * (g_{r_i} * h_i) * * so the composed wiring is src'[i] = s[r_i], gain'[i] = g[r_i] * h[i]. * The arrays do not grow. */static void compose_flat(const uint32_t *sf, const uint64_t *gf, const uint32_t *sg, const uint64_t *gg, uint32_t *so, uint64_t *go, size_t count, uint32_t n){ for (size_t i = 0; i < count; i++) { size_t base = (i / n) * (size_t)n; size_t j = base + sf[i]; /* first map's source, same cluster */
so[i] = sg[j]; /* second map reads it */ go[i] = gg[j] * gf[i]; }}
static void machine_free_arrays(lit_machine *m){ free(m->a); free(m->b); free(m->src); free(m->gain); free(m->weight); free(m->dist); free(m->diff); free(m->flat_src); free(m->flat_gain); free(m->flat_as); free(m->flat_bs); free(m->flat_ag); free(m->flat_bg); m->a = NULL; m->b = NULL; m->V = NULL; m->prev = NULL; m->src = NULL; m->gain = NULL; m->weight = NULL; m->dist = NULL; m->diff = NULL; m->flat_src = NULL; m->flat_gain = NULL; m->flat_as = NULL; m->flat_bs = NULL; m->flat_ag = NULL; m->flat_bg = NULL;}
void lit_machine_free(lit_machine *m){ if (!m) { return; } machine_free_arrays(m); memset(m, 0, sizeof(*m));}
static int machine_alloc(lit_machine *m, uint64_t *state, int own_state){ size_t count; size_t n = (size_t)m->n; uint32_t lv = m->levels ? m->levels : 1;
if (n == 0 || m->k == 0) { return -1; } if ((size_t)m->k > SIZE_MAX / n) { return -1; } count = (size_t)m->k * n; if (count > SIZE_MAX / lv) { return -1; } m->owns_state = own_state; m->a = own_state ? malloc(count * sizeof(uint64_t)) : NULL; m->b = malloc(count * sizeof(uint64_t)); m->src = malloc(count * sizeof(uint32_t)); m->gain = malloc(count * sizeof(uint64_t)); m->weight = malloc(count * sizeof(uint64_t)); m->dist = malloc((size_t)m->k * sizeof(uint64_t)); m->diff = malloc(count * sizeof(uint64_t)); m->flat_src = malloc(count * lv * sizeof(uint32_t)); m->flat_gain = malloc(count * lv * sizeof(uint64_t)); m->flat_as = malloc(n * sizeof(uint32_t)); m->flat_bs = malloc(n * sizeof(uint32_t)); m->flat_ag = malloc(n * sizeof(uint64_t)); m->flat_bg = malloc(n * sizeof(uint64_t)); if ((own_state && !m->a) || !m->b || !m->src || !m->gain || !m->weight || !m->dist || !m->diff || !m->flat_src || !m->flat_gain || !m->flat_as || !m->flat_bs || !m->flat_ag || !m->flat_bg) { machine_free_arrays(m); return -1; } m->V = own_state ? m->a : state; m->prev = m->b; m->flat_dirty = 1; memset(m->b, 0, count * sizeof(uint64_t)); memset(m->diff, 0, count * sizeof(uint64_t)); return 0;}
static int machine_setup(lit_machine *m, uint64_t *state, uint32_t n, uint32_t k, uint32_t bits, int own){ size_t count;
if (!m || !state || n == 0 || k == 0 || bits < 1 || bits > 64) { return -1; } memset(m, 0, sizeof(*m)); m->n = n; m->k = k; m->bits = bits; m->mask = (bits == 64) ? ~(uint64_t)0 : (((uint64_t)1 << bits) - 1); m->levels = 0; while (m->levels < 31 && ((uint32_t)1 << m->levels) < n) { m->levels++; } m->halt = n + 1; if (machine_alloc(m, state, own) != 0) { return -1; } count = (size_t)k * n; if (own) { memcpy(m->a, state, count * sizeof(uint64_t)); } for (size_t i = 0; i < count; i++) { m->V[i] &= m->mask; } for (uint32_t c = 0; c < k; c++) { for (uint32_t i = 0; i < n; i++) { size_t idx = (size_t)c * n + i;
m->src[idx] = i; m->gain[idx] = 1; m->weight[idx] = 1; } } memset(m->dist, 0, (size_t)k * sizeof(uint64_t)); return 0;}
int lit_machine_init(lit_machine *m, const uint64_t *state, uint32_t n, uint32_t k, uint32_t bits){ return machine_setup(m, (uint64_t *)state, n, k, bits, 1);}
int lit_machine_init_borrowed(lit_machine *m, uint64_t *state, uint32_t n, uint32_t k, uint32_t bits){ return machine_setup(m, state, n, k, bits, 0);}
/* * The six-item graph sequence: the base VF graph F plus the local * recurrence G_{i+1} = G_i o G_i gives F^2, F^4, F^8, F^16, F^32, * F^64. It is built once per wiring change; the step applies the last * item, so one tick is F^64 and 2^6 = 64 is the 64/65 edge. */static void machine_rebuild_flat(lit_machine *m){ const uint32_t k = m->k; const uint32_t n = m->n; uint32_t *as = m->flat_as; uint32_t *bs = m->flat_bs; uint64_t *ag = m->flat_ag; uint64_t *bg = m->flat_bg;
for (uint32_t cc = 0; cc < k; cc++) { memcpy(as, m->src + (size_t)cc * n, (size_t)n * sizeof(uint32_t)); memcpy(ag, m->gain + (size_t)cc * n, (size_t)n * sizeof(uint64_t)); for (uint32_t c = 0; c < m->levels; c++) { compose_flat(as, ag, as, ag, bs, bg, n, n); { uint32_t *p = as; as = bs; bs = p; } { uint64_t *p = ag; ag = bg; bg = p; } memcpy(m->flat_src + ((size_t)cc * m->levels + c) * n, as, (size_t)n * sizeof(uint32_t)); memcpy(m->flat_gain + ((size_t)cc * m->levels + c) * n, ag, (size_t)n * sizeof(uint64_t)); } } m->flat_dirty = 0;}
/* * VF_TRANSFER: next = F(V), then swap: V becomes the committed state and * prev keeps the snapshot. Two arrays total (V and prev), not three. * Each cluster only touches its own slice, so the cluster loop is the * broadcast parallel loop. */static void machine_transfer(lit_machine *m){ const uint32_t k = m->k; const uint32_t n = m->n;
if (m->flat_dirty) { machine_rebuild_flat(m); }#ifdef _OPENMP#pragma omp parallel for schedule(static) if (k > 1)#endif for (long cc = 0; cc < (long)k; cc++) { size_t base = (size_t)cc * n; const uint64_t *V = m->V + base; uint64_t *next = m->prev + base; const uint32_t *src; const uint64_t *gain;
if (m->levels == 0) { src = m->src + base; gain = m->gain + base; } else { src = m->flat_src + ((size_t)cc * m->levels + (m->levels - 1)) * n; gain = m->flat_gain + ((size_t)cc * m->levels + (m->levels - 1)) * n; } for (uint32_t i = 0; i < n; i++) { next[i] = (V[src[i]] * gain[i]) & m->mask; } } { uint64_t *tmp = m->V;
m->V = m->prev; m->prev = tmp; } m->pending = 1;}
/* * HAMMING_REDUCE: strict-less weighted Hamming, exact: the bits of the * snapshot that turned off in the committed state (prev & ~V), never the * bits that turned on. The per-slot mask is kept in diff; the weighted * sum is dist. Without a pending transfer every distance and mask is 0. */static void machine_reduce(lit_machine *m){ const uint32_t k = m->k; const uint32_t n = m->n;
if (!m->pending) { memset(m->dist, 0, (size_t)k * sizeof(uint64_t)); memset(m->diff, 0, (size_t)k * n * sizeof(uint64_t)); return; }#ifdef _OPENMP#pragma omp parallel for schedule(static) if (k > 1)#endif for (long cc = 0; cc < (long)k; cc++) { size_t base = (size_t)cc * n; const uint64_t *V = m->V + base; const uint64_t *prev = m->prev + base; const uint64_t *weight = m->weight + base; uint64_t *diff = m->diff + base; uint64_t d = 0;
for (uint32_t i = 0; i < n; i++) { uint64_t mask = (prev[i] & ~V[i]) & m->mask;
diff[i] = mask; d += weight[i] * lit_popcount_u64(mask); } m->dist[cc] = d; } m->pending = 0;}
void lit_machine_step(lit_machine *m){ machine_transfer(m); machine_reduce(m);}
void lit_machine_run(lit_machine *m, uint64_t max_cycles, uint64_t *cycles_out, int *converged_out){ uint64_t cycles = 0; int converged = 0;
if (max_cycles == 0) { max_cycles = 1; /* one tick is F^64: one step, early halt */ } if (max_cycles > m->halt) { max_cycles = m->halt; /* the hard halt is n + 1 (65 at n=64) */ } for (;;) { lit_machine_step(m); cycles++; converged = 1; for (uint32_t c = 0; c < m->k; c++) { if (m->dist[c] != 0) { converged = 0; break; } } if (converged || cycles >= max_cycles) { break; } } if (cycles_out) { *cycles_out = cycles; } if (converged_out) { *converged_out = converged; }}
int lit_machine_connect(lit_machine *m, uint32_t slot, uint32_t src, uint64_t gain, const uint64_t *weight, int cluster){ uint32_t c0, c1;
if (!m) { return -1; } if (slot >= m->n || src >= m->n) { return -1; } if (cluster < -1 || cluster >= (int)m->k) { return -2; } c0 = (cluster < 0) ? 0 : (uint32_t)cluster; c1 = (cluster < 0) ? m->k : (uint32_t)cluster + 1; for (uint32_t c = c0; c < c1; c++) { size_t idx = (size_t)c * m->n + slot;
m->src[idx] = src; m->gain[idx] = gain; if (weight) { m->weight[idx] = *weight; } } m->flat_dirty = 1; return 0;}
int lit_machine_graph(lit_machine *m, const uint32_t *src, const uint64_t *gain, const uint64_t *weight, int cluster){ uint32_t c0, c1;
if (!m || !src || !gain || !weight) { return -1; } if (cluster < -1 || cluster >= (int)m->k) { return -2; } for (uint32_t i = 0; i < m->n; i++) { if (src[i] >= m->n) { return -1; } } c0 = (cluster < 0) ? 0 : (uint32_t)cluster; c1 = (cluster < 0) ? m->k : (uint32_t)cluster + 1; for (uint32_t c = c0; c < c1; c++) { size_t base = (size_t)c * m->n;
memcpy(m->src + base, src, (size_t)m->n * sizeof(uint32_t)); memcpy(m->gain + base, gain, (size_t)m->n * sizeof(uint64_t)); memcpy(m->weight + base, weight, (size_t)m->n * sizeof(uint64_t)); } m->flat_dirty = 1; return 0;}
void lit_machine_load(lit_machine *m, const uint64_t *words){ if (!m || !words) { return; } for (uint32_t c = 0; c < m->k; c++) { memcpy(m->V + (size_t)c * m->n, words, (size_t)m->n * sizeof(uint64_t)); } m->pending = 0;}
void lit_machine_ring(lit_machine *m){ const uint32_t n = m->n;
if (!m) { return; } for (uint32_t c = 0; c < m->k; c++) { size_t base = (size_t)c * n;
for (uint32_t i = 0; i < n; i++) { m->src[base + i] = (i == 0) ? n - 1 : i - 1; m->gain[base + i] = 1; m->weight[base + i] = 1; } } m->flat_dirty = 1;}
void lit_machine_copy_v(const lit_machine *m, uint64_t *out){ if (!m || !out) { return; } memcpy(out, m->V, (size_t)m->n * sizeof(uint64_t)); /* cluster 0 */}
static inline uint32_t bc_u32(const uint8_t *p){ return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);}
static inline uint64_t bc_u64(const uint8_t *p){ uint64_t v = 0;
for (int i = 7; i >= 0; i--) { v = (v << 8) | p[i]; } return v;}
/* * Validate the stream and count reductions before running anything. * Returns 1 if HALT was seen, 0 if the stream ended, -1 truncated, * -2 unknown opcode, -3 slot/src out of range. */static int bc_scan(const uint8_t *code, size_t len, uint32_t n, size_t *reductions){ size_t pc = 0, red = 0;
while (pc < len) { uint8_t op = code[pc++];
switch (op) { case LIT_BC_LOAD: if (len - pc < 12) { return -1; } if (bc_u32(code + pc) >= n) { return -3; } pc += 12; break; case LIT_BC_WIRE: if (len - pc < 24) { return -1; } if (bc_u32(code + pc) >= n || bc_u32(code + pc + 4) >= n) { return -3; } pc += 24; break; case LIT_BC_BROADCAST: case LIT_BC_VF_TRANSFER: break; case LIT_BC_HAMMING_REDUCE: red++; break; case LIT_BC_HALT: *reductions = red; return 1; default: return -2; } } *reductions = red; return 0;}
int lit_machine_run_bytecode(lit_machine *m, const uint8_t *code, size_t len, uint64_t **history, size_t *reductions, uint64_t *ticks_out, int *halted, int *broadcast, char *err, size_t errlen){ size_t nred = 0, red_i = 0, hist_count; int scan; uint64_t ticks = 0, *hist = NULL; size_t pc = 0; int was_broadcast = 0;
if (!m || !code) { if (err && errlen) { snprintf(err, errlen, "null machine or code"); } return -1; } scan = bc_scan(code, len, m->n, &nred); if (scan < 0) { if (err && errlen) { if (scan == -1) { snprintf(err, errlen, "truncated LIT bytecode"); } else if (scan == -3) { snprintf(err, errlen, "LIT bytecode slot/src out of range"); } else { snprintf(err, errlen, "unknown LIT opcode"); } } return -1; } hist_count = nred * (size_t)m->k; if (hist_count) { hist = malloc(hist_count * sizeof(uint64_t)); if (!hist) { if (err && errlen) { snprintf(err, errlen, "out of memory"); } return -1; } }
while (pc < len) { uint8_t op = code[pc++];
switch (op) { case LIT_BC_LOAD: { uint32_t slot = bc_u32(code + pc); uint64_t value = bc_u64(code + pc + 4);
pc += 12; for (uint32_t c = 0; c < m->k; c++) { m->V[(size_t)c * m->n + slot] = value & m->mask; } break; } case LIT_BC_WIRE: { uint32_t slot = bc_u32(code + pc); uint32_t src = bc_u32(code + pc + 4); uint64_t gain = bc_u64(code + pc + 8); uint64_t weight = bc_u64(code + pc + 16);
pc += 24; for (uint32_t c = 0; c < m->k; c++) { size_t idx = (size_t)c * m->n + slot;
m->src[idx] = src; m->gain[idx] = gain; m->weight[idx] = weight; } m->flat_dirty = 1; break; } case LIT_BC_BROADCAST: was_broadcast = 1; break; case LIT_BC_VF_TRANSFER: machine_transfer(m); ticks++; break; case LIT_BC_HAMMING_REDUCE: machine_reduce(m); if (hist) { for (uint32_t c = 0; c < m->k; c++) { hist[red_i * m->k + c] = m->dist[c]; } } red_i++; break; case LIT_BC_HALT: pc = len; break; } }
*history = hist; if (reductions) { *reductions = nred; } if (ticks_out) { *ticks_out = ticks; } if (halted) { *halted = (scan == 1); } if (broadcast) { *broadcast = was_broadcast; } return 0;}
uint64_t lit_ring_tick(uint64_t *v, size_t n, uint32_t bits, int wrap){ uint64_t mask, last, d = 0;
if (!v || n == 0) { return 0; } if (bits < 1) { bits = 1; } if (bits > 64) { bits = 64; } mask = (bits == 64) ? ~(uint64_t)0 : (((uint64_t)1 << bits) - 1); last = v[n - 1]; for (size_t i = n - 1; i > 0; i--) { uint64_t old = v[i]; uint64_t nx = v[i - 1]; /* the source is still old */
d += lit_popcount_u64(old & ~nx & mask); v[i] = nx; } { uint64_t old = v[0]; uint64_t nx = wrap ? last : old;
d += lit_popcount_u64(old & ~nx & mask); v[0] = nx; } return d;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120/* * lit_core.h — LITCORE: the LIT algebraic core, language-agnostic C. * * LITCORE is brainless: broadcast the graph, multiply, reduce, * rewire, repeat. It never interprets what a symbol means; there is * no semantics inside the core. * * Six is the optimal operation; DO NOT TOUCH IT. */#ifndef LIT_CORE_H#define LIT_CORE_H
#include <stddef.h>#include <stdint.h>
#ifdef __cplusplusextern "C" {#endif
/* LIT bytecode: LOAD slot:u32 value:u64; WIRE slot:u32 src:u32 * gain:u64 weight:u64; everything else is one byte. Little-endian. */#define LIT_BC_LOAD 0x01#define LIT_BC_WIRE 0x02#define LIT_BC_BROADCAST 0x03#define LIT_BC_VF_TRANSFER 0x04#define LIT_BC_HAMMING_REDUCE 0x05#define LIT_BC_HALT 0x06
/* lit flat: 2^LIT_FLAT = 64, the 64/65 halt edge. */#define LIT_FLAT 6
/* The hard halt bound: 65 ticks at L=64. A run is one tick by * default (one tick applies F^64, so the step is already the whole * job) and never exceeds LIT_HALT ticks even if asked. */#define LIT_HALT 65
typedef struct lit_machine { uint32_t n; /* slots per cluster */ uint32_t k; /* clusters */ uint64_t *a; /* owned state when owns_state */ uint64_t *b; /* transition buffer */ uint64_t *V; /* current state (a or a borrowed buffer) */ uint64_t *prev; /* state before the last transfer (b) */ uint32_t *src; /* k*n wiring */ uint64_t *gain; /* k*n */ uint64_t *weight; /* k*n */ uint64_t *dist; /* k, last per-cluster distance */ uint64_t *diff; /* k*n, last strict-less difference mask */ uint32_t *flat_src; /* k*LIT_FLAT*n */ uint64_t *flat_gain; /* k*LIT_FLAT*n */ uint32_t *flat_as; /* n-word recurrence scratch */ uint32_t *flat_bs; uint64_t *flat_ag; uint64_t *flat_bg; int flat_dirty; /* the base graph changed; rebuild on the tick */ int pending; /* a VF_TRANSFER awaits HAMMING_REDUCE */ int owns_state; /* a was allocated by the core */ uint32_t bits; /* L: symbol width, 1..64 */ uint64_t mask; /* (1<<L)-1, or ~0 for L=64 */ uint32_t levels; /* flat exponent: ceil(log2(n)); 6 for n=64 */ uint32_t halt; /* hard halt: n + 1; 65 for n=64 */} lit_machine;
/* Copy `state` (n*k words) into the machine. Returns 0, or -1 on OOM. */int lit_machine_init(lit_machine *m, const uint64_t *state, uint32_t n, uint32_t k, uint32_t bits);
/* Borrow caller-owned `state` (n*k words); the core never frees it. */int lit_machine_init_borrowed(lit_machine *m, uint64_t *state, uint32_t n, uint32_t k, uint32_t bits);
/* Release every array the core owns; the borrowed state is untouched. */void lit_machine_free(lit_machine *m);
/* One complete tick: transfer then strict-less Hamming reduce. */void lit_machine_step(lit_machine *m);
/* Run one tick (F^64) with early halt; max_cycles 0 means one tick, * any larger request is clamped to LIT_HALT. Writes the ticks taken * and whether every cluster's d reached 0. */void lit_machine_run(lit_machine *m, uint64_t max_cycles, uint64_t *cycles, int *converged);
/* Rewire one slot (weight NULL keeps the existing weight). 0 or -1/-2. */int lit_machine_connect(lit_machine *m, uint32_t slot, uint32_t src, uint64_t gain, const uint64_t *weight, int cluster);
/* Rewrite a cluster's or every cluster's wiring. 0 or -1/-2. */int lit_machine_graph(lit_machine *m, const uint32_t *src, const uint64_t *gain, const uint64_t *weight, int cluster);
/* Load one n-word window into every cluster; no tick, no commit. */void lit_machine_load(lit_machine *m, const uint64_t *words);
/* Wire every cluster as a ring: slot i reads slot i-1, gain/weight 1. */void lit_machine_ring(lit_machine *m);
/* Copy cluster 0's committed V into out (n words). */void lit_machine_copy_v(const lit_machine *m, uint64_t *out);
/* * Execute LIT bytecode. On success returns 0 and writes a malloc'ed * history (reductions*k words), the reduction count, ticks, halted and * broadcast flags. The caller frees *history. On failure returns -1 * and writes a message into err (if err is non-NULL). */int lit_machine_run_bytecode(lit_machine *m, const uint8_t *code, size_t len, uint64_t **history, size_t *reductions, uint64_t *ticks, int *halted, int *broadcast, char *err, size_t errlen);
/* One in-place forward-ring tick over a writable uint64 buffer. */uint64_t lit_ring_tick(uint64_t *v, size_t n, uint32_t bits, int wrap);
#ifdef __cplusplus}#endif
#endif /* LIT_CORE_H */123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441/* * lit_main.c — the product's world main: the foolproof world interface. * * The world is the only thing customized here. LIT is fixed: the host * supplies the world's root, actions, and oracle; the operator owns the * global tree, the frontier, the comparison, and the seen set. There is * no score, no attention, no pruning, and no branch stack here. * * Usage: * lit [go [rows [cols]]] default: go 19 (19 x 19 board) * lit dense [x y z] default: dense 4 4 64 * * The go world is the gel {black,white} x {black,white} x board_cells: * the causal pair (a,b) is the smallest predecessor/successor state, and * the board cells are the orthogonal time axis. * * The search is global. The operator picks the next node from the whole * tree; the host does not walk branches. As soon as a node reaches the * last time slice it has stopped; the player's IF is the halt judge. * A win is the goal and stops the search; a non-win is an ordinary leaf * and the global search continues. The whole tree is saved as JSON and * safetensors. */#include "dense.h"#include "lit_operator.h"
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <time.h>
typedef struct { dense world; lit_action *acts; /* one time slice of actions */ size_t nacts; int (*win)(void *ctx, const lit_action *path, size_t path_len); void *win_ctx; uint64_t wins;} world_host;
static int parse_u64(const char *s, uint64_t *out){ char *end; unsigned long long v;
if (!s || !*s || *s == '-') { return -1; } v = strtoull(s, &end, 10); if (end == s || *end != '\0') { return -1; } *out = (uint64_t)v; return 0;}
static int host_init(world_host *h, uint32_t symbols, uint64_t steps){ memset(h, 0, sizeof(*h)); if (dense_init(&h->world, symbols, steps, NULL, NULL) != 0) { return -1; } if (symbols == 0 || (size_t)symbols > SIZE_MAX / symbols) { dense_free(&h->world); return -1; } h->nacts = (size_t)symbols * symbols; if (h->nacts == 0 || h->nacts > SIZE_MAX / sizeof(*h->acts)) { dense_free(&h->world); return -1; } h->acts = malloc(h->nacts * sizeof(*h->acts)); if (!h->acts) { dense_free(&h->world); return -1; } return 0;}
static void host_free(world_host *h){ free(h->acts); h->acts = NULL; dense_free(&h->world);}
/* The world root is virtual: it is not a cell. Its actions are all * cells of time 0, so every cell of the world is reachable. */static int host_root(void *ctx, lit_key *key, int *goal, int *dead){ (void)ctx; key->hi = UINT64_MAX; key->lo = 0; *goal = 0; *dead = 0; return 0;}
/* Every action is one cell of the next time slice. The operator never * interprets the cell; the world names it and the oracle decides. */static int host_actions(void *ctx, const lit_action *path, size_t path_len, const lit_action **acts, size_t *n){ world_host *h = ctx; uint64_t nt = path_len ? (uint64_t)path[path_len - 1].kind + 1 : 0; size_t i = 0;
if (nt >= h->world.steps) { *acts = NULL; *n = 0; return 0; } for (uint32_t a = 0; a < h->world.symbols; a++) { for (uint32_t b = 0; b < h->world.symbols; b++) { h->acts[i].kind = (uint32_t)nt; h->acts[i].id = 0; h->acts[i].x = a; h->acts[i].y = b; h->acts[i].cost = 1; i++; } } *acts = h->acts; *n = i; return 0;}
/* The judge is one line of IF: when a node reaches the last time slice * it has stopped, and the player's IF decides whether the stop is a * win. A win is the goal (the search returns the path); a non-win is an * ordinary leaf and the global search simply continues. */static int halt_goal(const world_host *h, const lit_action *act){ if ((uint64_t)act->kind + 1 < h->world.steps) { return 0; } return act->y == 0;}
/* The world oracle has no goal; the gel cut is the only structural * mask. Key is the cell, so the operator's seen set dedupes the world. * This is called per action, before the seen check; it has no side * effects and never judges a win. */static int host_eval(void *ctx, const lit_action *path, size_t path_len, const lit_action *act, uint64_t child_g, lit_key *child, int *goal, int *dead){ world_host *h = ctx; uint64_t cell = dense_index(&h->world, act->x, act->y, act->kind);
(void)path; (void)path_len; (void)child_g; if (cell == UINT64_MAX) { child->hi = 0; child->lo = 0; *goal = 0; *dead = 1; return 0; } child->hi = cell; child->lo = 0; *goal = halt_goal(h, act); *dead = dense_cut(&h->world, cell); return 0;}
/* Batch expansion: one host round trip per parent instead of one per * action. The same world oracle as host_eval, filled for every action * at once; this is the shape a GPU/NPU/robot host wants. */static int host_expand(void *ctx, const lit_action *path, size_t path_len, const lit_action *acts, const uint64_t *child_g, size_t nacts, lit_key *keys, int *goals, int *deads){ world_host *h = ctx;
(void)path; (void)path_len; (void)child_g; for (size_t i = 0; i < nacts; i++) { uint64_t cell = dense_index(&h->world, acts[i].x, acts[i].y, acts[i].kind);
if (cell == UINT64_MAX) { keys[i].hi = 0; keys[i].lo = 0; goals[i] = 0; deads[i] = 1; continue; } keys[i].hi = cell; keys[i].lo = 0; goals[i] = halt_goal(h, &acts[i]); deads[i] = dense_cut(&h->world, cell); } return 0;}
/* The player's win IF, run at the halt. A win is the halt judge and * stops the search; a non-win is an ordinary leaf and the search * continues. Replace this one line to change the win judgment. */static int player_win(void *ctx, const lit_action *path, size_t path_len){ (void)ctx; if (path_len == 0) { return 0; } return path[path_len - 1].y == 0; /* example: last stone black */}
/* Observation only. The operator calls it after expanding a node. The * halt judge is set in eval/expand (the goal); this callback only * reports the stopped nodes that were not goals. */static void host_event(void *ctx, const lit_action *path, size_t path_len, uint64_t pops, uint64_t nodes, size_t open, double g, double score, int goal){ world_host *h = ctx;
(void)pops; (void)nodes; (void)open; (void)g; (void)score; (void)goal; if ((uint64_t)path_len == h->world.steps && h->win && h->win(h->win_ctx, path, path_len)) { h->wins++; printf("win-stop: depth %zu\n", path_len); }}
int main(int argc, char **argv){ int go = 1; int base = 1; uint64_t rows = 19; uint64_t cols = 19; uint64_t x = 4; uint64_t y = 4; uint64_t z = 64; uint64_t symbols; uint64_t steps; const char *stem; char json_path[64]; char st_path[64]; world_host h; lit_host lh; lit_search_opts opts; lit_path path; lit_search *s; int rc; int eval_mode = 0; struct timespec t0, t1;
/* --eval keeps the per-action host path; the default is the batch expand path. Remove the flags so the positional world arguments keep their positions. */ for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "--eval") == 0) { eval_mode = 1; } else if (strcmp(argv[i], "--expand") == 0) { eval_mode = 0; } else { continue; } for (int j = i; j < argc - 1; j++) { argv[j] = argv[j + 1]; } argc--; i--; }
if (argc > 1) { if (strcmp(argv[1], "dense") == 0) { go = 0; base = 2; } else if (strcmp(argv[1], "go") == 0) { go = 1; base = 2; } else { fprintf(stderr, "usage: %s [go [rows [cols]] | dense [x y z]] [--eval]\n", argv[0]); return 2; } }
if (go) { if (argc > base && parse_u64(argv[base], &rows) != 0) { fprintf(stderr, "usage: %s [go [rows [cols]] | dense [x y z]] [--eval]\n", argv[0]); return 2; } cols = rows; if (argc > base + 1 && parse_u64(argv[base + 1], &cols) != 0) { fprintf(stderr, "usage: %s [go [rows [cols]] | dense [x y z]] [--eval]\n", argv[0]); return 2; } if (rows == 0 || cols == 0 || rows > UINT32_MAX || cols > UINT32_MAX || rows > UINT32_MAX / cols) { fprintf(stderr, "go world needs 0 < rows*cols <= %u\n", UINT32_MAX); return 2; } symbols = 2; steps = rows * cols; stem = "lit_go"; } else { if (argc > base && parse_u64(argv[base], &x) != 0) { fprintf(stderr, "usage: %s [go [rows [cols]] | dense [x y z]] [--eval]\n", argv[0]); return 2; } y = x; if (argc > base + 1) { if (parse_u64(argv[base + 1], &y) != 0) { fprintf(stderr, "usage: %s [go [rows [cols]] | dense [x y z]] [--eval]\n", argv[0]); return 2; } } if (argc > base + 2 && parse_u64(argv[base + 2], &z) != 0) { fprintf(stderr, "usage: %s [go [rows [cols]] | dense [x y z]] [--eval]\n", argv[0]); return 2; } if (x == 0 || y == 0 || z == 0 || x != y || x > UINT32_MAX || y > UINT32_MAX || z > UINT32_MAX) { fprintf(stderr, "dense world needs 0 < x == y <= %u and 0 < z <= %u\n", UINT32_MAX, UINT32_MAX); return 2; } symbols = x; steps = z; stem = "lit_dense"; }
if (host_init(&h, (uint32_t)symbols, steps) != 0) { fprintf(stderr, "world init failed\n"); return 1; } h.win = player_win; h.win_ctx = &h;
if (go) { printf("world: go\n"); printf("board: %llu x %llu = %llu cells\n", (unsigned long long)rows, (unsigned long long)cols, (unsigned long long)steps); printf("causal: 2 x 2 (black/white)\n"); printf("shape: 2 x 2 x %llu\n", (unsigned long long)steps); } else { printf("world: dense\n"); printf("shape: %llu x %llu x %llu\n", (unsigned long long)x, (unsigned long long)y, (unsigned long long)z); } printf("gel: dense\n"); printf("cells: %llu\n", (unsigned long long)dense_cells(&h.world)); printf("stop: judged as soon as a node reaches the last time slice\n"); printf("judge: player IF at the halt (win stops, non-win continues)\n");
memset(&lh, 0, sizeof(lh)); lh.ctx = &h; lh.root = host_root; lh.actions = host_actions; lh.eval = host_eval; if (!eval_mode) { lh.expand = host_expand; } lh.event = host_event;
memset(&opts, 0, sizeof(opts)); memset(&path, 0, sizeof(path));
s = lit_search_new(&lh); if (!s) { fprintf(stderr, "lit_search_new failed\n"); host_free(&h); return 1; } timespec_get(&t0, TIME_UTC); rc = lit_search_continue(s, &opts, &path); timespec_get(&t1, TIME_UTC);
printf("search: %s pops: %llu nodes: %llu\n", rc == LIT_SEARCH_EMPTY ? "exhausted (all worlds explored)" : rc == LIT_SEARCH_BUDGET ? "budget" : rc == LIT_SEARCH_FOUND ? "found" : "error", (unsigned long long)path.pops, (unsigned long long)path.nodes); { long long ns = (long long)(t1.tv_sec - t0.tv_sec) * 1000000000LL + (t1.tv_nsec - t0.tv_nsec); double nodes = (double)path.nodes;
if (ns < 0) { ns = 0; } printf("time: %.3f ms %.1f ns/node %.0f nodes/s [%s]\n", (double)ns / 1e6, path.nodes ? (double)ns / nodes : 0.0, ns ? nodes * 1e9 / (double)ns : 0.0, eval_mode ? "eval" : "expand"); } if (rc == LIT_SEARCH_FOUND && path.n > 0) { const lit_action *last = &path.acts[path.n - 1];
printf("halt: depth %zu last cell (%u,%u,%u) judge: win\n", path.n, last->kind, last->x, last->y); } else { printf("judge: no win at the halt; the search would continue\n"); }
snprintf(json_path, sizeof(json_path), "%s.json", stem); snprintf(st_path, sizeof(st_path), "%s.safetensors", stem); if (lit_search_save_json(s, json_path) != 0) { fprintf(stderr, "save json failed\n"); } else { printf("tree: %s\n", json_path); } if (lit_search_save_safetensors(s, st_path) != 0) { fprintf(stderr, "save safetensors failed\n"); } else { printf("tree: %s\n", st_path); }
lit_path_free(&path); lit_search_free(s); host_free(&h); return (rc == LIT_SEARCH_EMPTY || rc == LIT_SEARCH_FOUND) ? 0 : 1;}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996/* lit_operator.c — the LIT DO search operator: the DO node arena and * the frontier scan. The tree stores interventions, not machine * states: a node's state is replayed from its DO chain. This is the * mainline for synthesis: the search path, flattened, is the program. * The Coder only mines macros. No game, no ARC, no Python: the caller * supplies the machine/state, the actions, and the oracle. */#include "lit_operator.h"
#include <stdarg.h>#include <stdio.h>#include <stdlib.h>#include <string.h>
int lit_do_apply(lit_machine *m, const lit_do *d){ if (!m || !d || !m->V || m->pending || d->slot >= m->n) { return -1; } switch (d->kind) { case LIT_DO_LOAD: { uint64_t value = d->value & m->mask;
for (uint32_t c = 0; c < m->k; c++) { m->V[(size_t)c * m->n + d->slot] = value; } return 0; } case LIT_DO_WIRE: if (d->src >= m->n) { return -1; } return lit_machine_connect(m, d->slot, d->src, d->gain, &d->weight, -1); default: return -1; }}
int lit_do_restore(const lit_donode *node, lit_machine *m){ const lit_donode *nd; lit_do *ops; size_t depth = 0; size_t i;
if (!node || !m) { return -1; } for (nd = node; nd->parent; nd = nd->parent) { depth++; } if (depth == 0) { return 0; } ops = malloc(depth * sizeof(*ops)); if (!ops) { return -1; } depth = 0; for (nd = node; nd->parent; nd = nd->parent) { ops[depth++] = nd->op; } for (i = depth; i > 0; i--) { if (lit_do_apply(m, &ops[i - 1]) != 0) { free(ops); return -1; } } free(ops); return 0;}
/* ---------------------------------------------------------------- *//* DO node arena *//* ---------------------------------------------------------------- */
lit_donode *lit_do_alloc(lit_do_arena *a, lit_donode *parent, const lit_do *op, uint32_t depth){ lit_donode *n;
if (a->used == a->cap) { lit_donode **chunk = realloc(a->chunk, (a->nchunk + 1) * sizeof(*chunk));
if (!chunk) { return NULL; } a->chunk = chunk; a->chunk[a->nchunk] = malloc(LIT_DO_CHUNK * sizeof(lit_donode)); if (!a->chunk[a->nchunk]) { return NULL; } a->nchunk++; a->cap += LIT_DO_CHUNK; } n = &a->chunk[a->used / LIT_DO_CHUNK][a->used % LIT_DO_CHUNK]; a->used++; memset(n, 0, sizeof(*n)); n->parent = parent; if (op) { n->op = *op; } n->depth = depth; n->state = LIT_DO_OPEN; if (parent) { n->next_sibling = parent->first_child; parent->first_child = n; } return n;}
void lit_do_arena_free(lit_do_arena *a){ for (size_t i = 0; i < a->nchunk; i++) { free(a->chunk[i]); } free(a->chunk); memset(a, 0, sizeof(*a));}
/* ---------------------------------------------------------------- *//* Flat DO tree + full machine state *//* ---------------------------------------------------------------- */
/* Find the arena index of a node; chunk pointers stay stable. */static int node_index(const lit_do_arena *a, const lit_donode *node, uint32_t *out){ uintptr_t addr = (uintptr_t)node; size_t bytes = LIT_DO_CHUNK * sizeof(lit_donode);
for (size_t c = 0; c < a->nchunk; c++) { uintptr_t base = (uintptr_t)a->chunk[c];
if (addr >= base && addr < base + bytes) { size_t off = (addr - base) / sizeof(lit_donode); size_t idx = c * LIT_DO_CHUNK + off;
if (idx > UINT32_MAX) { return -1; } *out = (uint32_t)idx; return 0; } } return -1;}
static int tree_alloc(lit_tree *t, uint32_t n, uint32_t words, uint32_t slots, uint32_t clusters, uint32_t bits){ size_t nsz = n; size_t wsz = words; size_t ksz = clusters;
if (n == 0 || words == 0 || slots == 0 || clusters == 0 || bits < 1 || bits > 64 || (uint64_t)slots * clusters != words) { return -1; } if (nsz > SIZE_MAX / sizeof(uint32_t) || nsz > SIZE_MAX / sizeof(uint64_t) || wsz > SIZE_MAX / sizeof(uint32_t) || wsz > SIZE_MAX / sizeof(uint64_t) || ksz > SIZE_MAX / sizeof(uint64_t)) { return -1; } memset(t, 0, sizeof(*t)); t->n = n; t->words = words; t->slots = slots; t->clusters = clusters; t->bits = bits; t->parent = malloc(nsz * sizeof(uint32_t)); t->kind = malloc(nsz * sizeof(uint32_t)); t->slot = malloc(nsz * sizeof(uint32_t)); t->do_src = malloc(nsz * sizeof(uint32_t)); t->gain = malloc(nsz * sizeof(uint64_t)); t->weight = malloc(nsz * sizeof(uint64_t)); t->value = malloc(nsz * sizeof(uint64_t)); t->depth = malloc(nsz * sizeof(uint32_t)); t->root_v = malloc(wsz * sizeof(uint64_t)); t->root_src = malloc(wsz * sizeof(uint32_t)); t->root_gain = malloc(wsz * sizeof(uint64_t)); t->root_weight = malloc(wsz * sizeof(uint64_t)); t->root_dist = malloc(ksz * sizeof(uint64_t)); t->root_diff = malloc(wsz * sizeof(uint64_t)); if (!t->parent || !t->kind || !t->slot || !t->do_src || !t->gain || !t->weight || !t->value || !t->depth || !t->root_v || !t->root_src || !t->root_gain || !t->root_weight || !t->root_dist || !t->root_diff) { lit_tree_free(t); return -1; } return 0;}
static int tree_valid(const lit_tree *t){ if (!t || t->n == 0 || t->words == 0 || t->slots == 0 || t->clusters == 0 || t->bits < 1 || t->bits > 64 || (uint64_t)t->slots * t->clusters != t->words) { return 0; } return t->parent && t->kind && t->slot && t->do_src && t->gain && t->weight && t->value && t->depth && t->root_v && t->root_src && t->root_gain && t->root_weight && t->root_dist && t->root_diff;}
int lit_tree_flatten(lit_tree *t, const lit_do_arena *a, const lit_machine *root){ size_t n; size_t words; size_t clusters;
if (!t || !a || !root || !root->V || !root->src || !root->gain || !root->weight || !root->dist || !root->diff || root->n == 0 || root->k == 0 || root->bits < 1 || root->bits > 64 || root->pending) { return -1; } if ((uint64_t)root->n * root->k > UINT32_MAX) { return -1; } n = a->used; if (n == 0 || n > UINT32_MAX) { return -1; } memset(t, 0, sizeof(*t)); if (tree_alloc(t, (uint32_t)n, (uint32_t)((uint64_t)root->n * root->k), root->n, root->k, root->bits) != 0) { return -1; } words = t->words; clusters = t->clusters; memcpy(t->root_v, root->V, words * sizeof(uint64_t)); memcpy(t->root_src, root->src, words * sizeof(uint32_t)); memcpy(t->root_gain, root->gain, words * sizeof(uint64_t)); memcpy(t->root_weight, root->weight, words * sizeof(uint64_t)); memcpy(t->root_diff, root->diff, words * sizeof(uint64_t)); memcpy(t->root_dist, root->dist, clusters * sizeof(uint64_t)); for (size_t i = 0; i < n; i++) { const lit_donode *node = &a->chunk[i / LIT_DO_CHUNK][i % LIT_DO_CHUNK];
t->parent[i] = UINT32_MAX; if (node->parent && node_index(a, node->parent, &t->parent[i]) != 0) { lit_tree_free(t); return -1; } if (t->parent[i] != UINT32_MAX && t->parent[i] >= (uint32_t)n) { lit_tree_free(t); return -1; } t->kind[i] = (uint32_t)node->op.kind; t->slot[i] = node->op.slot; t->do_src[i] = node->op.src; t->gain[i] = node->op.gain; t->weight[i] = node->op.weight; t->value[i] = node->op.value; t->depth[i] = node->depth; } return 0;}
int lit_tree_restore(const lit_tree *t, uint32_t i, lit_machine *m){ uint32_t *chain; size_t depth = 0; uint32_t cur;
if (!t || !m || !tree_valid(t) || i >= t->n || !m->V || !m->src || !m->gain || !m->weight || !m->dist || !m->diff || m->n != t->slots || m->k != t->clusters || m->bits != t->bits || m->pending) { return -1; } memcpy(m->V, t->root_v, (size_t)t->words * sizeof(uint64_t)); memcpy(m->src, t->root_src, (size_t)t->words * sizeof(uint32_t)); memcpy(m->gain, t->root_gain, (size_t)t->words * sizeof(uint64_t)); memcpy(m->weight, t->root_weight, (size_t)t->words * sizeof(uint64_t)); memcpy(m->diff, t->root_diff, (size_t)t->words * sizeof(uint64_t)); memcpy(m->dist, t->root_dist, (size_t)t->clusters * sizeof(uint64_t)); m->pending = 0; m->flat_dirty = 1; for (cur = i; cur != UINT32_MAX; cur = t->parent[cur]) { depth++; } if (depth <= 1) { return 0; /* the root: nothing to replay */ } chain = malloc((depth - 1) * sizeof(*chain)); if (!chain) { return -1; } depth = 0; for (cur = i; t->parent[cur] != UINT32_MAX; cur = t->parent[cur]) { chain[depth++] = cur; } while (depth > 0) { lit_do d; uint32_t at = chain[--depth];
d.kind = (lit_do_kind)t->kind[at]; d.slot = t->slot[at]; d.src = t->do_src[at]; d.gain = t->gain[at]; d.weight = t->weight[at]; d.value = t->value[at]; if (lit_do_apply(m, &d) != 0) { free(chain); return -1; } } free(chain); return 0;}
void lit_tree_free(lit_tree *t){ if (!t) { return; } free(t->parent); free(t->kind); free(t->slot); free(t->do_src); free(t->gain); free(t->weight); free(t->value); free(t->depth); free(t->root_v); free(t->root_src); free(t->root_gain); free(t->root_weight); free(t->root_dist); free(t->root_diff); memset(t, 0, sizeof(*t));}
#define LIT_TREE_MAGIC 0x4c495434u /* LIT4: no per-node states */
int lit_tree_save(const lit_tree *t, const char *path){ FILE *f; uint32_t magic = LIT_TREE_MAGIC; uint32_t n, words, slots, clusters, bits; int bad = 0;
if (!tree_valid(t) || !path) { return -1; } f = fopen(path, "wb"); if (!f) { return -1; } n = t->n; words = t->words; slots = t->slots; clusters = t->clusters; bits = t->bits; if (fwrite(&magic, sizeof(magic), 1, f) != 1 || fwrite(&n, sizeof(n), 1, f) != 1 || fwrite(&words, sizeof(words), 1, f) != 1 || fwrite(&slots, sizeof(slots), 1, f) != 1 || fwrite(&clusters, sizeof(clusters), 1, f) != 1 || fwrite(&bits, sizeof(bits), 1, f) != 1 || fwrite(t->parent, sizeof(uint32_t), n, f) != n || fwrite(t->kind, sizeof(uint32_t), n, f) != n || fwrite(t->slot, sizeof(uint32_t), n, f) != n || fwrite(t->do_src, sizeof(uint32_t), n, f) != n || fwrite(t->gain, sizeof(uint64_t), n, f) != n || fwrite(t->weight, sizeof(uint64_t), n, f) != n || fwrite(t->value, sizeof(uint64_t), n, f) != n || fwrite(t->depth, sizeof(uint32_t), n, f) != n || fwrite(t->root_v, sizeof(uint64_t), words, f) != words || fwrite(t->root_src, sizeof(uint32_t), words, f) != words || fwrite(t->root_gain, sizeof(uint64_t), words, f) != words || fwrite(t->root_weight, sizeof(uint64_t), words, f) != words || fwrite(t->root_diff, sizeof(uint64_t), words, f) != words || fwrite(t->root_dist, sizeof(uint64_t), clusters, f) != clusters) { bad = 1; } if (fclose(f) != 0) { bad = 1; } return bad ? -1 : 0;}
int lit_tree_load(lit_tree *t, const char *path){ FILE *f; uint32_t magic; uint32_t n, words, slots, clusters, bits; int bad = 0;
if (!t || !path) { return -1; } memset(t, 0, sizeof(*t)); f = fopen(path, "rb"); if (!f) { return -1; } if (fread(&magic, sizeof(magic), 1, f) != 1 || fread(&n, sizeof(n), 1, f) != 1 || fread(&words, sizeof(words), 1, f) != 1 || fread(&slots, sizeof(slots), 1, f) != 1 || fread(&clusters, sizeof(clusters), 1, f) != 1 || fread(&bits, sizeof(bits), 1, f) != 1 || magic != LIT_TREE_MAGIC) { fclose(f); return -1; } if (tree_alloc(t, n, words, slots, clusters, bits) != 0) { fclose(f); return -1; } if (fread(t->parent, sizeof(uint32_t), n, f) != n || fread(t->kind, sizeof(uint32_t), n, f) != n || fread(t->slot, sizeof(uint32_t), n, f) != n || fread(t->do_src, sizeof(uint32_t), n, f) != n || fread(t->gain, sizeof(uint64_t), n, f) != n || fread(t->weight, sizeof(uint64_t), n, f) != n || fread(t->value, sizeof(uint64_t), n, f) != n || fread(t->depth, sizeof(uint32_t), n, f) != n || fread(t->root_v, sizeof(uint64_t), words, f) != words || fread(t->root_src, sizeof(uint32_t), words, f) != words || fread(t->root_gain, sizeof(uint64_t), words, f) != words || fread(t->root_weight, sizeof(uint64_t), words, f) != words || fread(t->root_diff, sizeof(uint64_t), words, f) != words || fread(t->root_dist, sizeof(uint64_t), clusters, f) != clusters) { bad = 1; } if (fclose(f) != 0) { bad = 1; } if (!bad) { for (uint32_t i = 0; i < n; i++) { if (t->parent[i] != UINT32_MAX && t->parent[i] >= n) { bad = 1; break; } } } if (bad) { lit_tree_free(t); return -1; } return 0;}
static void put_u32(FILE *f, const char *name, const char *field, const uint32_t *v, size_t n){ fprintf(f, "static const uint32_t %s_%s[%zu] = {", name, field, n); for (size_t i = 0; i < n; i++) { fprintf(f, "%s%u", i ? "," : "", v[i]); } fprintf(f, "};\n");}
static void put_u64(FILE *f, const char *name, const char *field, const uint64_t *v, size_t n){ fprintf(f, "static const uint64_t %s_%s[%zu] = {", name, field, n); for (size_t i = 0; i < n; i++) { fprintf(f, "%s%llu", i ? "," : "", (unsigned long long)v[i]); } fprintf(f, "};\n");}
int lit_tree_write_c(const lit_tree *t, const char *path, const char *name){ FILE *f; int bad;
if (!tree_valid(t) || !path || !name) { return -1; } f = fopen(path, "w"); if (!f) { return -1; } fprintf(f, "/* generated by the LIT operator: DO tree C array */\n"); fprintf(f, "#include <stdint.h>\n\n"); fprintf(f, "#define %s_N %u\n", name, t->n); fprintf(f, "#define %s_WORDS %u\n", name, t->words); fprintf(f, "#define %s_SLOTS %u\n", name, t->slots); fprintf(f, "#define %s_CLUSTERS %u\n", name, t->clusters); fprintf(f, "#define %s_BITS %u\n\n", name, t->bits); put_u32(f, name, "parent", t->parent, t->n); put_u32(f, name, "kind", t->kind, t->n); put_u32(f, name, "slot", t->slot, t->n); put_u32(f, name, "do_src", t->do_src, t->n); put_u64(f, name, "gain", t->gain, t->n); put_u64(f, name, "weight", t->weight, t->n); put_u64(f, name, "value", t->value, t->n); put_u32(f, name, "depth", t->depth, t->n); put_u64(f, name, "root_v", t->root_v, t->words); put_u32(f, name, "root_src", t->root_src, t->words); put_u64(f, name, "root_gain", t->root_gain, t->words); put_u64(f, name, "root_weight", t->root_weight, t->words); put_u64(f, name, "root_diff", t->root_diff, t->words); put_u64(f, name, "root_dist", t->root_dist, t->clusters); bad = ferror(f); if (fclose(f) != 0) { bad = 1; } return bad ? -1 : 0;}
/* ---------------------------------------------------------------- *//* Generic program-search driver. The operator owns the tree (every *//* node carries its dynamic score), the path nodes, and the seen *//* set; the host owns the game. Nothing else is trusted: every *//* counterfactual branch is expanded, and a bounded world is walked *//* to exhaustion. The goal is only the stopping condition. *//* ---------------------------------------------------------------- */
typedef struct { uint32_t parent; /* UINT32_MAX = root */ lit_action act; lit_key key; uint64_t g; /* the DO score accumulated along the path */ uint32_t depth; uint32_t first_child; /* UINT32_MAX = none */ uint32_t next_sibling; /* UINT32_MAX = none */ uint8_t goal; uint8_t dead; uint8_t expanded;} lit_snode;
typedef struct { lit_snode *v; size_t n; size_t cap;} lit_sarena;
static void sarena_free(lit_sarena *a){ free(a->v); a->v = NULL; a->n = 0; a->cap = 0;}
static int sarena_add(lit_sarena *a, const lit_snode *node, uint32_t *idx){ if (a->n >= UINT32_MAX) { return -1; } if (a->n == a->cap) { size_t cap = a->cap ? a->cap * 2 : 1024; lit_snode *v;
if (cap < a->cap || cap > SIZE_MAX / sizeof(*v)) { return -1; } v = realloc(a->v, cap * sizeof(*v)); if (!v) { return -1; } a->v = v; a->cap = cap; } a->v[a->n] = *node; a->v[a->n].first_child = UINT32_MAX; a->v[a->n].next_sibling = UINT32_MAX; *idx = (uint32_t)a->n; a->n++; return 0;}
typedef struct { lit_key key; uint32_t node; uint8_t used;} lit_kslot;
typedef struct { lit_kslot *v; size_t cap; /* power of two, or zero */ size_t n;} lit_ktab;
static uint64_t key_mix(uint64_t x){ x ^= x >> 30; x *= 0xbf58476d1ce4e5b9ULL; x ^= x >> 27; x *= 0x94d049bb133111ebULL; x ^= x >> 31; return x;}
static int key_eq(lit_key a, lit_key b){ return a.hi == b.hi && a.lo == b.lo;}
static size_t ktab_slot(const lit_ktab *t, lit_key k){ size_t mask = t->cap - 1; size_t i = (size_t)key_mix(k.hi ^ (k.lo + 0x9e3779b97f4a7c15ULL + (k.hi << 6) + (k.hi >> 2))) & mask;
while (t->v[i].used && !key_eq(t->v[i].key, k)) { i = (i + 1) & mask; } return i;}
static void lit_ktab_free(lit_ktab *t){ free(t->v); t->v = NULL; t->cap = 0; t->n = 0;}
static int ktab_resize(lit_ktab *t, size_t cap){ lit_kslot *v; size_t i;
if (cap < 1024) { cap = 1024; } v = calloc(cap, sizeof(*v)); if (!v) { return -1; } for (i = 0; i < t->cap; i++) { if (t->v[i].used) { size_t j = (size_t)key_mix(t->v[i].key.hi ^ (t->v[i].key.lo + 0x9e3779b97f4a7c15ULL + (t->v[i].key.hi << 6) + (t->v[i].key.hi >> 2))) & (cap - 1);
while (v[j].used) { j = (j + 1) & (cap - 1); } v[j] = t->v[i]; } } free(t->v); t->v = v; t->cap = cap; return 0;}
static int ktab_insert(lit_ktab *t, lit_key key, uint32_t node){ size_t i;
if (t->cap == 0) { if (ktab_resize(t, 1024) != 0) { return -1; } } else if ((t->n + 1) * 10 >= t->cap * 7) { if (t->cap > SIZE_MAX / 2 || ktab_resize(t, t->cap * 2) != 0) { return -1; } } i = ktab_slot(t, key); if (t->v[i].used) { return 0; } t->v[i].key = key; t->v[i].node = node; t->v[i].used = 1; t->n++; return 1;}
static int build_path(const lit_sarena *a, uint32_t idx, lit_action *buf, size_t cap, size_t *len){ size_t d = a->v[idx].depth; size_t pos = d; uint32_t cur = idx;
if (d > cap) { return -1; } while (cur != UINT32_MAX && a->v[cur].depth > 0) { if (pos == 0) { return -1; } buf[--pos] = a->v[cur].act; cur = a->v[cur].parent; } if (pos != 0) { return -1; } *len = d; return 0;}
static int fill_out_path(const lit_sarena *a, uint32_t idx, lit_path *out){ size_t d = a->v[idx].depth; lit_action *p;
out->acts = NULL; out->n = 0; if (d == 0) { return 0; } if (d > SIZE_MAX / sizeof(*p)) { return -1; } p = malloc(d * sizeof(*p)); if (!p) { return -1; } if (build_path(a, idx, p, d, &out->n) != 0) { free(p); return -1; } out->acts = p; return 0;}
struct lit_search { lit_host host; lit_sarena nodes; lit_ktab seen; uint32_t *heap; /* max-heap of frontier node indices */ size_t heap_n; size_t heap_cap; lit_action *pathbuf; size_t pathcap; lit_action *actbuf; size_t actcap; lit_key *kbuf; int *gbuf; int *dbuf; uint64_t *cgbuf; size_t rescap; lit_node_view *views; size_t views_cap; uint64_t *sbuf; size_t scorecap; uint32_t anchor; int anchor_valid;};
/* Max-heap of flat node indices: the top is the unexpanded, non-dead * node with the largest g; ties take the smaller index. The frontier * is this heap, not a linear scan. The comparison is the same direct * comparison the operator always used, only now in O(log n). */static int heap_better(const lit_sarena *a, uint32_t x, uint32_t y){ const lit_snode *nx = &a->v[x]; const lit_snode *ny = &a->v[y];
if (nx->g != ny->g) { return nx->g > ny->g; } return x < y;}
static int heap_push(lit_search *s, uint32_t idx){ size_t i;
if (s->heap_n == s->heap_cap) { size_t cap = s->heap_cap ? s->heap_cap * 2 : 1024; uint32_t *h;
if (cap < s->heap_cap || cap > SIZE_MAX / sizeof(*h)) { return -1; } h = realloc(s->heap, cap * sizeof(*h)); if (!h) { return -1; } s->heap = h; s->heap_cap = cap; } i = s->heap_n++; s->heap[i] = idx; while (i > 0) { size_t p = (i - 1) / 2; uint32_t t;
if (heap_better(&s->nodes, s->heap[p], s->heap[i])) { break; } t = s->heap[p]; s->heap[p] = s->heap[i]; s->heap[i] = t; i = p; } return 0;}
static uint32_t heap_pop(lit_search *s){ uint32_t top; size_t i = 0;
if (s->heap_n == 0) { return UINT32_MAX; } top = s->heap[0]; s->heap[0] = s->heap[--s->heap_n]; for (;;) { size_t l = i * 2 + 1; size_t r = l + 1; size_t best = i; uint32_t t;
if (l < s->heap_n && heap_better(&s->nodes, s->heap[l], s->heap[best])) { best = l; } if (r < s->heap_n && heap_better(&s->nodes, s->heap[r], s->heap[best])) { best = r; } if (best == i) { break; } t = s->heap[best]; s->heap[best] = s->heap[i]; s->heap[i] = t; i = best; } return top;}
static void link_child(lit_search *s, uint32_t parent, uint32_t child){ s->nodes.v[child].next_sibling = s->nodes.v[parent].first_child; s->nodes.v[parent].first_child = child;}
/* Append a child, link it into the parent's child list, and push it on * the open heap unless it is dead. This is the one place a node enters * the tree, so the child links and the heap can never disagree. */static int add_child(lit_search *s, uint32_t parent, const lit_snode *child, uint32_t *idx){ if (sarena_add(&s->nodes, child, idx) != 0) { return -1; } link_child(s, parent, *idx); if (!child->dead && heap_push(s, *idx) != 0) { return -1; } return 0;}
static lit_search *search_alloc(const lit_host *host){ lit_search *s;
if (!host || !host->root || !host->actions || (!host->eval && !host->expand)) { return NULL; } if (host->score && !host->expand) { return NULL; } s = calloc(1, sizeof(*s)); if (!s) { return NULL; } s->host = *host; s->anchor = UINT32_MAX; s->anchor_valid = 0; return s;}
lit_search *lit_search_new(const lit_host *host){ lit_search *s; lit_key root_key = {0, 0}; int root_goal = 0; int root_dead = 0; lit_snode root; uint32_t root_idx;
s = search_alloc(host); if (!s) { return NULL; } if (host->root(host->ctx, &root_key, &root_goal, &root_dead) != 0) { lit_search_free(s); return NULL; } memset(&root, 0, sizeof(root)); root.parent = UINT32_MAX; root.key = root_key; root.goal = (uint8_t)(root_goal != 0); root.dead = (uint8_t)(root_dead != 0); if (sarena_add(&s->nodes, &root, &root_idx) != 0 || ktab_insert(&s->seen, root_key, root_idx) != 1 || heap_push(s, root_idx) != 0) { lit_search_free(s); return NULL; } return s;}
/* Bulk ingest one causal edge. The node is just another flat-tree * node: parent index, opaque action, host key, accumulated g, judge * flags. It starts unexpanded, so a later continue can grow from it; * the seen set records the key so the search keeps its dedupe. The * operator never interprets the action or the key. */uint32_t lit_search_ingest(lit_search *s, uint32_t parent, const lit_action *act, lit_key key, uint64_t g, int goal, int dead){ lit_snode node; uint32_t idx;
if (!s || !act || parent >= s->nodes.n) { return UINT32_MAX; } memset(&node, 0, sizeof(node)); node.parent = parent; node.act = *act; node.key = key; node.g = g; node.depth = s->nodes.v[parent].depth + 1; node.goal = (uint8_t)(goal != 0); node.dead = (uint8_t)(dead != 0); node.expanded = 0; if (add_child(s, parent, &node, &idx) != 0) { return UINT32_MAX; } if (ktab_insert(&s->seen, key, idx) < 0) { return UINT32_MAX; } return idx;}
/* Extend the read-only node views by the delta [views_n, nodes.n). Nodes * are append-only, so an index always means the same node and the host * only has to look at the new tail. */static void view_fill(const lit_snode *nd, lit_node_view *v){ v->parent = nd->parent; v->depth = nd->depth; v->g = nd->g; v->key = nd->key; v->act = nd->act; v->first_child = nd->first_child; v->next_sibling = nd->next_sibling; v->goal = nd->goal; v->dead = nd->dead; v->expanded = nd->expanded;}
static int views_ensure(lit_search *s){ size_t n = s->nodes.n; size_t i;
if (s->views_cap < n) { lit_node_view *v = realloc(s->views, n * sizeof(*v));
if (!v) { return -1; } s->views = v; s->views_cap = n; } /* Refresh every view: goal, dead, and expanded are node state that changes after the view was first built. Indices stay stable. */ for (i = 0; i < n; i++) { view_fill(&s->nodes.v[i], &s->views[i]); } return 0;}
uint32_t lit_search_follow(const lit_search *s, const lit_action *path, size_t path_len, lit_key *key){ uint32_t node = 0; size_t i;
if (!s || !path || s->nodes.n == 0) { return UINT32_MAX; } for (i = 0; i < path_len; i++) { uint32_t c = s->nodes.v[node].first_child;
while (c != UINT32_MAX) { if (memcmp(&s->nodes.v[c].act, &path[i], sizeof(lit_action)) == 0) { break; } c = s->nodes.v[c].next_sibling; } if (c == UINT32_MAX) { return UINT32_MAX; } node = c; } if (key) { *key = s->nodes.v[node].key; } return node;}
int lit_search_node(const lit_search *s, uint32_t i, lit_node_view *out){ if (!s || !out || i >= s->nodes.n) { return -1; } view_fill(&s->nodes.v[i], out); return 0;}
void lit_search_stats(const lit_search *s, uint64_t *nodes, uint64_t *unique, uint64_t *open){ if (!s) { return; } if (nodes) { *nodes = (uint64_t)s->nodes.n; } if (unique) { *unique = (uint64_t)s->seen.n; } if (open) { *open = (uint64_t)s->heap_n; }}
/* Host-chosen interventions: the operator exposes the whole tree and the * host picks any node to expand next (jump/backtrack). No open list and * no seen set: every intervention creates a new branch. */static int search_choose(lit_search *s, const lit_search_opts *opts, lit_path *out){ uint64_t pops = 0; uint64_t max_nodes = opts ? opts->max_nodes : 0; int rc = LIT_SEARCH_ERROR;
if (!s->host.expand) { return -1; } for (;;) { uint32_t idx; lit_snode parent; const lit_action *acts = NULL; size_t nact = 0; size_t plen; size_t i;
if (max_nodes && pops >= max_nodes) { rc = LIT_SEARCH_BUDGET; break; } if (views_ensure(s) != 0) { rc = LIT_SEARCH_ERROR; break; } if (s->host.choose(s->host.ctx, s->views, s->nodes.n, &idx) != 0 || idx >= s->nodes.n) { rc = LIT_SEARCH_EMPTY; break; } parent = s->nodes.v[idx]; pops++; if (s->host.seek) { (void)s->host.seek(s->host.ctx, &parent.key); } plen = parent.depth; if (plen > s->pathcap) { lit_action *p;
if (plen > SIZE_MAX / sizeof(*p)) { rc = LIT_SEARCH_ERROR; break; } p = realloc(s->pathbuf, plen * sizeof(*p)); if (!p) { rc = LIT_SEARCH_ERROR; break; } s->pathbuf = p; s->pathcap = plen; } if (build_path(&s->nodes, idx, s->pathbuf, s->pathcap, &plen) != 0) { rc = LIT_SEARCH_ERROR; break; } if (s->host.actions(s->host.ctx, s->pathbuf, plen, &acts, &nact) != 0) { rc = LIT_SEARCH_ERROR; break; } if (nact != 0 && !acts) { rc = LIT_SEARCH_ERROR; break; } if (nact > s->actcap) { lit_action *p;
if (nact > SIZE_MAX / sizeof(*p)) { rc = LIT_SEARCH_ERROR; break; } p = realloc(s->actbuf, nact * sizeof(*p)); if (!p) { rc = LIT_SEARCH_ERROR; break; } s->actbuf = p; s->actcap = nact; } if (nact != 0) { memcpy(s->actbuf, acts, nact * sizeof(*s->actbuf)); } if (nact > s->rescap) { lit_key *nk = realloc(s->kbuf, nact * sizeof(*nk)); int *ng; int *nd; uint64_t *ncg;
if (!nk) { rc = LIT_SEARCH_ERROR; break; } s->kbuf = nk; ng = realloc(s->gbuf, nact * sizeof(*ng)); if (!ng) { rc = LIT_SEARCH_ERROR; break; } s->gbuf = ng; nd = realloc(s->dbuf, nact * sizeof(*nd)); if (!nd) { rc = LIT_SEARCH_ERROR; break; } s->dbuf = nd; ncg = realloc(s->cgbuf, nact * sizeof(*ncg)); if (!ncg) { rc = LIT_SEARCH_ERROR; break; } s->cgbuf = ncg; s->rescap = nact; } for (i = 0; i < nact; i++) { uint64_t cost = s->actbuf[i].cost;
s->cgbuf[i] = (UINT64_MAX - parent.g < cost) ? UINT64_MAX : parent.g + cost; } if (s->host.expand(s->host.ctx, s->pathbuf, plen, s->actbuf, s->cgbuf, nact, s->kbuf, s->gbuf, s->dbuf) != 0) { rc = LIT_SEARCH_ERROR; break; } for (i = 0; i < nact; i++) { lit_snode child; uint32_t cidx;
if (s->cgbuf[i] == UINT64_MAX) { continue; } memset(&child, 0, sizeof(child)); child.parent = idx; child.act = s->actbuf[i]; child.key = s->kbuf[i]; child.g = s->cgbuf[i]; child.depth = parent.depth + 1; child.goal = (uint8_t)(s->gbuf[i] != 0); child.dead = (uint8_t)(s->dbuf[i] != 0); if (add_child(s, idx, &child, &cidx) != 0) { rc = LIT_SEARCH_ERROR; goto done; } } if (s->host.event) { s->host.event(s->host.ctx, s->pathbuf, plen, pops, s->nodes.n, 0, parent.g, 0.0, parent.goal); } }done: out->acts = NULL; out->n = 0; out->pops = pops; if (s->nodes.n != 0) { out->nodes = s->nodes.n; } return rc == LIT_SEARCH_ERROR ? -1 : rc;}
/* Global attention: the host scores every node of the whole tree with * integer scores; the operator expands the largest by a direct * comparison (ties take the earlier node). Expanded nodes may be * chosen again (backtracking) and the seen set is bypassed: every * intervention creates a new branch. Dead nodes are skipped; a chosen * goal returns its path. No float, no heuristic: only the host's * numbers and the operator's compare. */static int search_score(lit_search *s, const lit_search_opts *opts, lit_path *out, uint64_t base_g){ uint64_t pops = 0; uint64_t max_steps = opts ? opts->max_steps : 0; uint64_t max_nodes = opts ? opts->max_nodes : 0; int rc = LIT_SEARCH_ERROR;
for (;;) { uint32_t sel = UINT32_MAX; lit_snode parent; const lit_action *acts = NULL; size_t nact = 0; size_t plen; size_t i;
if (max_nodes && pops >= max_nodes) { rc = LIT_SEARCH_BUDGET; break; } if (views_ensure(s) != 0) { rc = LIT_SEARCH_ERROR; break; } if (s->nodes.n > s->scorecap) { uint64_t *p = realloc(s->sbuf, s->nodes.n * sizeof(*s->sbuf));
if (!p) { rc = LIT_SEARCH_ERROR; break; } s->sbuf = p; s->scorecap = s->nodes.n; } if (s->host.score(s->host.ctx, s->views, s->nodes.n, s->sbuf) != 0) { rc = LIT_SEARCH_EMPTY; break; } for (i = 0; i < s->nodes.n; i++) { if (s->nodes.v[i].dead) { continue; } if (sel == UINT32_MAX || s->sbuf[i] > s->sbuf[sel]) { sel = (uint32_t)i; } } if (sel == UINT32_MAX) { rc = LIT_SEARCH_EMPTY; break; } s->nodes.v[sel].expanded = 1; parent = s->nodes.v[sel]; if (max_steps && parent.g - base_g > max_steps) { rc = LIT_SEARCH_BUDGET; break; } pops++; if (parent.goal) { if (fill_out_path(&s->nodes, sel, out) != 0) { rc = LIT_SEARCH_ERROR; break; } s->anchor = sel; s->anchor_valid = 1; rc = LIT_SEARCH_FOUND; break; } if (s->host.seek) { (void)s->host.seek(s->host.ctx, &parent.key); } plen = parent.depth; if (plen > s->pathcap) { lit_action *p;
if (plen > SIZE_MAX / sizeof(*p)) { rc = LIT_SEARCH_ERROR; break; } p = realloc(s->pathbuf, plen * sizeof(*p)); if (!p) { rc = LIT_SEARCH_ERROR; break; } s->pathbuf = p; s->pathcap = plen; } if (build_path(&s->nodes, sel, s->pathbuf, s->pathcap, &plen) != 0) { rc = LIT_SEARCH_ERROR; break; } if (s->host.actions(s->host.ctx, s->pathbuf, plen, &acts, &nact) != 0) { rc = LIT_SEARCH_ERROR; break; } if (nact != 0 && !acts) { rc = LIT_SEARCH_ERROR; break; } if (nact > s->actcap) { lit_action *p;
if (nact > SIZE_MAX / sizeof(*p)) { rc = LIT_SEARCH_ERROR; break; } p = realloc(s->actbuf, nact * sizeof(*p)); if (!p) { rc = LIT_SEARCH_ERROR; break; } s->actbuf = p; s->actcap = nact; } if (nact != 0) { memcpy(s->actbuf, acts, nact * sizeof(*s->actbuf)); } if (nact > s->rescap) { lit_key *nk = realloc(s->kbuf, nact * sizeof(*nk)); int *ng; int *nd; uint64_t *ncg;
if (!nk) { rc = LIT_SEARCH_ERROR; break; } s->kbuf = nk; ng = realloc(s->gbuf, nact * sizeof(*ng)); if (!ng) { rc = LIT_SEARCH_ERROR; break; } s->gbuf = ng; nd = realloc(s->dbuf, nact * sizeof(*nd)); if (!nd) { rc = LIT_SEARCH_ERROR; break; } s->dbuf = nd; ncg = realloc(s->cgbuf, nact * sizeof(*ncg)); if (!ncg) { rc = LIT_SEARCH_ERROR; break; } s->cgbuf = ncg; s->rescap = nact; } for (i = 0; i < nact; i++) { uint64_t cost = s->actbuf[i].cost;
s->cgbuf[i] = (UINT64_MAX - parent.g < cost) ? UINT64_MAX : parent.g + cost; } if (s->host.expand(s->host.ctx, s->pathbuf, plen, s->actbuf, s->cgbuf, nact, s->kbuf, s->gbuf, s->dbuf) != 0) { rc = LIT_SEARCH_ERROR; break; } for (i = 0; i < nact; i++) { lit_snode child; uint32_t cidx;
if (s->cgbuf[i] == UINT64_MAX) { continue; } memset(&child, 0, sizeof(child)); child.parent = sel; child.act = s->actbuf[i]; child.key = s->kbuf[i]; child.g = s->cgbuf[i]; child.depth = parent.depth + 1; child.goal = (uint8_t)(s->gbuf[i] != 0); child.dead = (uint8_t)(s->dbuf[i] != 0); if (add_child(s, sel, &child, &cidx) != 0) { rc = LIT_SEARCH_ERROR; goto done; } } if (s->host.event) { s->host.event(s->host.ctx, s->pathbuf, plen, pops, s->nodes.n, 0, parent.g, 0.0, parent.goal); } }done: out->pops = pops; if (s->nodes.n != 0) { out->nodes = s->nodes.n; } if (rc != LIT_SEARCH_FOUND) { free(out->acts); out->acts = NULL; out->n = 0; } return rc == LIT_SEARCH_ERROR ? -1 : rc;}
static int search_continue(lit_search *s, const lit_search_opts *opts, lit_path *out){ uint64_t pops = 0; uint64_t max_steps = opts ? opts->max_steps : 0; uint64_t max_nodes = opts ? opts->max_nodes : 0; uint64_t base_g = 0; int rc = LIT_SEARCH_ERROR;
if (s->host.choose) { return search_choose(s, opts, out); }
if (s->anchor_valid) { size_t i;
s->nodes.v[s->anchor].goal = 0; s->nodes.v[s->anchor].dead = 0; base_g = s->nodes.v[s->anchor].g; /* A new level starts from the anchor alone: every other node is closed. The tree stays; the seen set belongs to the level. */ for (i = 0; i < s->nodes.n; i++) { s->nodes.v[i].expanded = 1; } s->nodes.v[s->anchor].expanded = 0; s->heap_n = 0; if (heap_push(s, s->anchor) != 0) { return -1; } lit_ktab_free(&s->seen); if (ktab_insert(&s->seen, s->nodes.v[s->anchor].key, s->anchor) != 1) { return -1; } s->anchor_valid = 0; } if (s->host.score) { return search_score(s, opts, out, base_g); } for (;;) { uint32_t sel; size_t frontier; lit_snode parent; const lit_action *acts = NULL; size_t nact = 0; size_t plen; size_t i;
/* The frontier is the max-heap. Its top is the unexpanded, non-dead node with the largest score; ties take the earlier node. The open pool grows and shrinks with the tree. */ frontier = s->heap_n; sel = heap_pop(s); if (sel == UINT32_MAX) { rc = LIT_SEARCH_EMPTY; break; } s->nodes.v[sel].expanded = 1; parent = s->nodes.v[sel]; if (max_steps && parent.g - base_g > max_steps) { rc = LIT_SEARCH_BUDGET; break; } pops++; if (parent.goal) { if (fill_out_path(&s->nodes, sel, out) != 0) { rc = LIT_SEARCH_ERROR; break; } s->anchor = sel; s->anchor_valid = 1; rc = LIT_SEARCH_FOUND; break; } if (parent.dead) { continue; } /* O(1) restore: the host may move the world by the node key instead of replaying the whole action path. When it does, the path is not built at all: the host promised not to read it for a restored node. */ plen = parent.depth; if (s->host.seek && s->host.seek(s->host.ctx, &parent.key) == 0) { plen = 0; } else { if (plen > s->pathcap) { lit_action *p;
if (plen > SIZE_MAX / sizeof(*p)) { rc = LIT_SEARCH_ERROR; break; } p = realloc(s->pathbuf, plen * sizeof(*p)); if (!p) { rc = LIT_SEARCH_ERROR; break; } s->pathbuf = p; s->pathcap = plen; } if (build_path(&s->nodes, sel, s->pathbuf, s->pathcap, &plen) != 0) { rc = LIT_SEARCH_ERROR; break; } } if (s->host.actions(s->host.ctx, s->pathbuf, plen, &acts, &nact) != 0) { rc = LIT_SEARCH_ERROR; break; } if (nact != 0 && !acts) { rc = LIT_SEARCH_ERROR; break; } if (nact > s->actcap) { lit_action *p;
if (nact > SIZE_MAX / sizeof(*p)) { rc = LIT_SEARCH_ERROR; break; } p = realloc(s->actbuf, nact * sizeof(*p)); if (!p) { rc = LIT_SEARCH_ERROR; break; } s->actbuf = p; s->actcap = nact; } if (nact != 0) { memcpy(s->actbuf, acts, nact * sizeof(*s->actbuf)); } if (s->host.expand) { if (nact > s->rescap) { lit_key *nk = realloc(s->kbuf, nact * sizeof(*nk)); int *ng; int *nd; uint64_t *ncg;
if (!nk) { rc = LIT_SEARCH_ERROR; break; } s->kbuf = nk; ng = realloc(s->gbuf, nact * sizeof(*ng)); if (!ng) { rc = LIT_SEARCH_ERROR; break; } s->gbuf = ng; nd = realloc(s->dbuf, nact * sizeof(*nd)); if (!nd) { rc = LIT_SEARCH_ERROR; break; } s->dbuf = nd; ncg = realloc(s->cgbuf, nact * sizeof(*ncg)); if (!ncg) { rc = LIT_SEARCH_ERROR; break; } s->cgbuf = ncg; s->rescap = nact; } for (i = 0; i < nact; i++) { uint64_t cost = s->actbuf[i].cost ? s->actbuf[i].cost : 1;
s->cgbuf[i] = (UINT64_MAX - parent.g < cost) ? UINT64_MAX : parent.g + cost; } if (s->host.expand(s->host.ctx, s->pathbuf, plen, s->actbuf, s->cgbuf, nact, s->kbuf, s->gbuf, s->dbuf) != 0) { rc = LIT_SEARCH_ERROR; break; } for (i = 0; i < nact; i++) { lit_action act = s->actbuf[i]; uint64_t child_g = s->cgbuf[i]; lit_key ck; int goal; int dead; int fresh; lit_snode child; uint32_t idx;
if (child_g == UINT64_MAX) { continue; } if (max_steps && child_g - base_g > max_steps) { continue; } ck = s->kbuf[i]; goal = s->gbuf[i]; dead = s->dbuf[i]; if (dead) { continue; } fresh = ktab_insert(&s->seen, ck, (uint32_t)s->nodes.n); if (fresh < 0) { rc = LIT_SEARCH_ERROR; goto done; } if (fresh == 0) { continue; } memset(&child, 0, sizeof(child)); child.parent = sel; child.act = act; child.key = ck; child.g = child_g; child.depth = parent.depth + 1; child.goal = (uint8_t)(goal != 0); if (add_child(s, sel, &child, &idx) != 0) { rc = LIT_SEARCH_ERROR; goto done; } } } else { for (i = 0; i < nact; i++) { lit_action act = s->actbuf[i]; uint64_t cost = act.cost; uint64_t child_g; lit_key ck = {0, 0}; int goal = 0; int dead = 0; int fresh; lit_snode child; uint32_t idx;
if (UINT64_MAX - parent.g < cost) { continue; } child_g = parent.g + cost; if (max_steps && child_g - base_g > max_steps) { continue; } if (s->host.eval(s->host.ctx, s->pathbuf, plen, &act, child_g, &ck, &goal, &dead) != 0) { continue; } if (dead) { continue; } fresh = ktab_insert(&s->seen, ck, (uint32_t)s->nodes.n); if (fresh < 0) { rc = LIT_SEARCH_ERROR; goto done; } if (fresh == 0) { continue; } memset(&child, 0, sizeof(child)); child.parent = sel; child.act = act; child.key = ck; child.g = child_g; child.depth = parent.depth + 1; child.goal = (uint8_t)(goal != 0); if (add_child(s, sel, &child, &idx) != 0) { rc = LIT_SEARCH_ERROR; goto done; } } } if (s->host.event) { s->host.event(s->host.ctx, s->pathbuf, plen, pops, s->nodes.n, frontier, parent.g, (double)parent.act.cost, parent.goal); } if (max_nodes && pops >= max_nodes) { rc = LIT_SEARCH_BUDGET; break; } }done: out->pops = pops; if (s->nodes.n != 0) { out->nodes = s->nodes.n; } if (rc != LIT_SEARCH_FOUND) { free(out->acts); out->acts = NULL; out->n = 0; } return rc == LIT_SEARCH_ERROR ? -1 : rc;}
int lit_search_continue(lit_search *s, const lit_search_opts *opts, lit_path *out){ if (!s || !out) { return -1; } memset(out, 0, sizeof(*out)); return search_continue(s, opts, out);}
int lit_search_run(const lit_host *host, const lit_search_opts *opts, lit_path *out){ lit_search *s; int rc;
if (!out) { return -1; } s = lit_search_new(host); if (!s) { return -1; } rc = lit_search_continue(s, opts, out); lit_search_free(s); return rc;}
int lit_memory_search(const lit_host *host, const lit_search_opts *opts, lit_path *out){ lit_action *path = NULL; size_t n = 0, cap = 0; uint64_t cursor = 0, step = 0; int rc = LIT_SEARCH_BUDGET;
if (!host || !host->root || !host->actions || !host->eval || !out) { return -1; } out->acts = NULL; out->n = 0; out->pops = 0; out->nodes = 0; { lit_key rk; int rg = 0, rd = 0;
if (host->root(host->ctx, &rk, &rg, &rd) != 0) { return -1; } if (rg) { return LIT_SEARCH_FOUND; } } for (;;) { const lit_action *acts = NULL; size_t na = 0, k; int chosen = -1, goal = 0; lit_key ck;
if (opts && ((opts->max_steps && step >= opts->max_steps) || (opts->max_nodes && step >= opts->max_nodes))) { rc = LIT_SEARCH_BUDGET; break; } if (host->actions(host->ctx, path, n, &acts, &na) != 0) { rc = LIT_SEARCH_ERROR; break; } out->pops++; if (na == 0 || !acts) { rc = LIT_SEARCH_EMPTY; break; } { size_t start = (size_t)(cursor % na); uint32_t best = 0;
/* Every candidate is hard-wired to the current path; the DO score is its cost. Compare directly, take the largest; there is no open list. */ for (k = 0; k < na; k++) { size_t idx = (start + k) % na; int g2 = 0, d2 = 0; uint32_t score = acts[idx].cost;
if (host->eval(host->ctx, path, n, &acts[idx], step + 1, &ck, &g2, &d2) != 0 || d2) { continue; } if (chosen < 0 || score > best) { chosen = (int)idx; best = score; goal = g2; } } } if (chosen < 0) { rc = LIT_SEARCH_EMPTY; break; } if (n == cap) { size_t nc = cap ? cap * 2 : 64; lit_action *np = realloc(path, nc * sizeof(*np));
if (!np) { free(path); return -1; } path = np; cap = nc; } path[n++] = acts[chosen]; cursor++; step++; out->nodes++; if (goal) { out->acts = malloc(n * sizeof(*out->acts)); if (!out->acts) { free(path); return -1; } memcpy(out->acts, path, n * sizeof(*out->acts)); out->n = n; rc = LIT_SEARCH_FOUND; break; } } free(path); return rc;}
void lit_search_free(lit_search *s){ if (!s) { return; } free(s->pathbuf); free(s->actbuf); free(s->kbuf); free(s->gbuf); free(s->dbuf); free(s->cgbuf); free(s->views); free(s->sbuf); free(s->heap); lit_ktab_free(&s->seen); sarena_free(&s->nodes); free(s);}
void lit_path_free(lit_path *p){ if (!p) { return; } free(p->acts); p->acts = NULL; p->n = 0; p->pops = 0; p->nodes = 0;}
/* ---------------------------------------------------------------- *//* Search-tree persistence: JSON and safetensors *//* ---------------------------------------------------------------- */
/* Every number in the two formats is a non-negative integer, so the * minimal JSON reader below carries numbers as u64 and never loses a * 64-bit key. Standard short escapes are handled; \u is rejected. */
typedef enum { JV_NUM, JV_STR, JV_ARR, JV_OBJ} jv_type;
typedef struct jv { jv_type type; uint64_t num; /* JV_NUM */ char *str; /* JV_STR */ char *key; /* object member name */ struct jv *child; /* first array element / object member */ struct jv *next; /* sibling */ struct jv *alloc; /* allocation list */} jv;
typedef struct { jv *arena;} jv_parser;
static jv *jv_new(jv_parser *jp, jv_type type){ jv *v = calloc(1, sizeof(*v));
if (!v) { return NULL; } v->type = type; v->alloc = jp->arena; jp->arena = v; return v;}
static void jv_free(jv_parser *jp){ jv *v = jp->arena;
while (v) { jv *next = v->alloc;
free(v->str); free(v->key); free(v); v = next; } jp->arena = NULL;}
static void jv_ws(const char **pp, const char *end){ const char *p = *pp;
while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) { p++; } *pp = p;}
static char *jv_str(const char **pp, const char *end){ const char *p = *pp; const char *q; char *s; char *d;
if (p >= end || *p != '"') { return NULL; } p++; for (q = p; q < end; q++) { if (*q == '"') { break; } if (*q == '\\') { if (q + 1 >= end || q[1] == 'u') { return NULL; } q++; } } if (q >= end) { return NULL; } s = malloc((size_t)(q - p) + 1); if (!s) { return NULL; } d = s; while (p < q) { char c = *p++;
if (c == '\\') { c = *p++; switch (c) { case '"': case '\\': case '/': break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; default: free(s); return NULL; } } *d++ = c; } *d = '\0'; *pp = q + 1; return s;}
static int jv_num(const char **pp, const char *end, uint64_t *out){ const char *p = *pp; uint64_t v = 0;
if (p >= end || *p < '0' || *p > '9') { return -1; } while (p < end && *p >= '0' && *p <= '9') { unsigned d = (unsigned)(*p - '0');
if (v > (UINT64_MAX - d) / 10) { return -1; } v = v * 10 + d; p++; } *pp = p; *out = v; return 0;}
static jv *jv_value(jv_parser *jp, const char **pp, const char *end, int depth){ const char *p = *pp; jv *v; jv *tail;
if (depth > 64) { return NULL; } jv_ws(&p, end); if (p >= end) { return NULL; } if (*p == '{') { p++; v = jv_new(jp, JV_OBJ); if (!v) { return NULL; } tail = NULL; jv_ws(&p, end); if (p < end && *p == '}') { *pp = p + 1; return v; } for (;;) { char *key; jv *m;
jv_ws(&p, end); key = jv_str(&p, end); if (!key) { return NULL; } jv_ws(&p, end); if (p >= end || *p != ':') { free(key); return NULL; } p++; m = jv_value(jp, &p, end, depth + 1); if (!m) { free(key); return NULL; } m->key = key; if (tail) { tail->next = m; } else { v->child = m; } tail = m; jv_ws(&p, end); if (p < end && *p == ',') { p++; continue; } if (p < end && *p == '}') { *pp = p + 1; return v; } return NULL; } } if (*p == '[') { p++; v = jv_new(jp, JV_ARR); if (!v) { return NULL; } tail = NULL; jv_ws(&p, end); if (p < end && *p == ']') { *pp = p + 1; return v; } for (;;) { jv *e = jv_value(jp, &p, end, depth + 1);
if (!e) { return NULL; } if (tail) { tail->next = e; } else { v->child = e; } tail = e; jv_ws(&p, end); if (p < end && *p == ',') { p++; continue; } if (p < end && *p == ']') { *pp = p + 1; return v; } return NULL; } } if (*p == '"') { v = jv_new(jp, JV_STR); if (!v) { return NULL; } v->str = jv_str(&p, end); if (!v->str) { return NULL; } *pp = p; return v; } { uint64_t num;
if (jv_num(&p, end, &num) != 0) { return NULL; } v = jv_new(jp, JV_NUM); if (!v) { return NULL; } v->num = num; *pp = p; return v; }}
static const jv *jv_get(const jv *obj, const char *key){ const jv *m;
if (!obj || obj->type != JV_OBJ) { return NULL; } for (m = obj->child; m; m = m->next) { if (m->key && strcmp(m->key, key) == 0) { return m; } } return NULL;}
static const jv *jv_at(const jv *arr, size_t i){ const jv *e;
if (!arr || arr->type != JV_ARR) { return NULL; } for (e = arr->child; e && i > 0; e = e->next) { i--; } return e;}
static size_t jv_len(const jv *arr){ size_t n = 0; const jv *e;
if (!arr || arr->type != JV_ARR) { return 0; } for (e = arr->child; e; e = e->next) { n++; } return n;}
static int jv_obj_u32(const jv *obj, const char *key, uint32_t *out){ const jv *v = jv_get(obj, key);
if (!v || v->type != JV_NUM || v->num > UINT32_MAX) { return -1; } *out = (uint32_t)v->num; return 0;}
static int jv_obj_u64(const jv *obj, const char *key, uint64_t *out){ const jv *v = jv_get(obj, key);
if (!v || v->type != JV_NUM) { return -1; } *out = v->num; return 0;}
static int jv_arr_u64(const jv *arr, size_t i, uint64_t *out){ const jv *e = jv_at(arr, i);
if (!e || e->type != JV_NUM) { return -1; } *out = e->num; return 0;}
static int jv_str_is(const jv *v, const char *s){ return v && v->type == JV_STR && v->str && strcmp(v->str, s) == 0;}
/* Snapshot of the search tree in flat arrays, one array per field. */typedef struct { uint32_t n; uint32_t *parent; uint32_t *kind; uint32_t *id; uint32_t *x; uint32_t *y; uint32_t *cost; uint64_t *key_hi; uint64_t *key_lo; uint64_t *g; uint32_t *depth; uint8_t *goal; uint8_t *dead; uint32_t *open; size_t open_n; uint32_t anchor; int anchor_valid;} lit_search_snap;
static void snap_free(lit_search_snap *sn){ free(sn->parent); free(sn->kind); free(sn->id); free(sn->x); free(sn->y); free(sn->cost); free(sn->key_hi); free(sn->key_lo); free(sn->g); free(sn->depth); free(sn->goal); free(sn->dead); free(sn->open); memset(sn, 0, sizeof(*sn));}
static int snap_alloc(lit_search_snap *sn, uint32_t n, size_t open_n){ memset(sn, 0, sizeof(*sn)); if (n == 0 || (uint64_t)n > SIZE_MAX / sizeof(uint32_t) || open_n > SIZE_MAX / sizeof(uint32_t)) { return -1; } sn->n = n; sn->open_n = open_n; sn->parent = malloc((size_t)n * sizeof(*sn->parent)); sn->kind = malloc((size_t)n * sizeof(*sn->kind)); sn->id = malloc((size_t)n * sizeof(*sn->id)); sn->x = malloc((size_t)n * sizeof(*sn->x)); sn->y = malloc((size_t)n * sizeof(*sn->y)); sn->cost = malloc((size_t)n * sizeof(*sn->cost)); sn->key_hi = malloc((size_t)n * sizeof(*sn->key_hi)); sn->key_lo = malloc((size_t)n * sizeof(*sn->key_lo)); sn->g = malloc((size_t)n * sizeof(*sn->g)); sn->depth = malloc((size_t)n * sizeof(*sn->depth)); sn->goal = malloc((size_t)n * sizeof(*sn->goal)); sn->dead = malloc((size_t)n * sizeof(*sn->dead)); sn->open = open_n ? malloc(open_n * sizeof(*sn->open)) : NULL; if (!sn->parent || !sn->kind || !sn->id || !sn->x || !sn->y || !sn->cost || !sn->key_hi || !sn->key_lo || !sn->g || !sn->depth || !sn->goal || !sn->dead || (open_n && !sn->open)) { snap_free(sn); return -1; } return 0;}
static int snap_from_search(const lit_search *s, lit_search_snap *sn){ size_t frontier = 0; size_t f = 0;
if (!s || s->nodes.n == 0 || s->nodes.n > UINT32_MAX) { return -1; } for (uint32_t i = 0; i < s->nodes.n; i++) { if (!s->nodes.v[i].expanded && !s->nodes.v[i].dead) { frontier++; } } if (snap_alloc(sn, (uint32_t)s->nodes.n, frontier) != 0) { return -1; } for (uint32_t i = 0; i < sn->n; i++) { const lit_snode *node = &s->nodes.v[i];
sn->parent[i] = node->parent; sn->kind[i] = node->act.kind; sn->id[i] = node->act.id; sn->x[i] = node->act.x; sn->y[i] = node->act.y; sn->cost[i] = node->act.cost; sn->key_hi[i] = node->key.hi; sn->key_lo[i] = node->key.lo; sn->g[i] = node->g; sn->depth[i] = node->depth; sn->goal[i] = node->goal; sn->dead[i] = node->dead; if (!node->expanded && !node->dead) { sn->open[f++] = i; } } sn->anchor = s->anchor; sn->anchor_valid = s->anchor_valid; return 0;}
static int read_whole(const char *path, char **out, size_t *outlen){ FILE *f; long sz; char *buf; size_t got;
f = fopen(path, "rb"); if (!f) { return -1; } if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return -1; } sz = ftell(f); if (sz < 0) { fclose(f); return -1; } if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return -1; } buf = malloc((size_t)sz + 1); if (!buf) { fclose(f); return -1; } got = fread(buf, 1, (size_t)sz, f); if (got != (size_t)sz || fclose(f) != 0) { free(buf); return -1; } buf[sz] = '\0'; *out = buf; *outlen = (size_t)sz; return 0;}
static int json_write_snap(const lit_search_snap *sn, const char *path){ FILE *f; char *vbuf; int bad = 0;
f = fopen(path, "wb"); if (!f) { return -1; } vbuf = malloc(1 << 20); if (vbuf) { setvbuf(f, vbuf, _IOFBF, 1 << 20); } fprintf(f, "{\"format\":\"lit-search-tree\",\"version\":1,"); fprintf(f, "\"n\":%u,\"anchor\":%u,\"anchor_valid\":%d,\"nodes\":[\n", (unsigned)sn->n, (unsigned)sn->anchor, sn->anchor_valid ? 1 : 0); for (uint32_t i = 0; i < sn->n; i++) { fprintf(f, "%s{\"parent\":%u,\"kind\":%u,\"id\":%u,\"x\":%u," "\"y\":%u,\"cost\":%u,\"key_hi\":%llu,\"key_lo\":%llu," "\"g\":%llu,\"depth\":%u,\"goal\":%u,\"dead\":%u}", i ? ",\n" : "", (unsigned)sn->parent[i], (unsigned)sn->kind[i], (unsigned)sn->id[i], (unsigned)sn->x[i], (unsigned)sn->y[i], (unsigned)sn->cost[i], (unsigned long long)sn->key_hi[i], (unsigned long long)sn->key_lo[i], (unsigned long long)sn->g[i], (unsigned)sn->depth[i], (unsigned)sn->goal[i], (unsigned)sn->dead[i]); } fprintf(f, "\n],\"open\":["); for (size_t i = 0; i < sn->open_n; i++) { fprintf(f, "%s%u", i ? "," : "", (unsigned)sn->open[i]); } fprintf(f, "]}\n"); if (ferror(f)) { bad = 1; } if (fclose(f) != 0) { bad = 1; } free(vbuf); return bad ? -1 : 0;}
static int json_read_snap(const jv *root, lit_search_snap *sn){ const jv *nodes; const jv *open; size_t nopen; uint64_t v64; uint64_t n;
if (!root || root->type != JV_OBJ || !jv_str_is(jv_get(root, "format"), "lit-search-tree") || jv_obj_u64(root, "version", &v64) != 0 || v64 != 1) { return -1; } nodes = jv_get(root, "nodes"); open = jv_get(root, "open"); if (!nodes || nodes->type != JV_ARR) { return -1; } n = jv_len(nodes); if (n == 0 || n > UINT32_MAX || jv_obj_u64(root, "n", &v64) != 0 || v64 != n) { return -1; } if (open && open->type != JV_ARR) { return -1; } nopen = jv_len(open); if (snap_alloc(sn, (uint32_t)n, nopen) != 0) { return -1; } if (jv_obj_u32(root, "anchor", &sn->anchor) != 0 || jv_obj_u64(root, "anchor_valid", &v64) != 0 || v64 > 1) { goto fail; } sn->anchor_valid = (int)v64; if (sn->anchor_valid && sn->anchor >= sn->n) { goto fail; } for (uint32_t i = 0; i < sn->n; i++) { const jv *node = jv_at(nodes, i); uint32_t bit;
if (!node || node->type != JV_OBJ) { goto fail; } if (jv_obj_u32(node, "parent", &sn->parent[i]) != 0) { goto fail; } if (sn->parent[i] != UINT32_MAX && sn->parent[i] >= sn->n) { goto fail; } if (jv_obj_u32(node, "kind", &sn->kind[i]) != 0 || jv_obj_u32(node, "id", &sn->id[i]) != 0 || jv_obj_u32(node, "x", &sn->x[i]) != 0 || jv_obj_u32(node, "y", &sn->y[i]) != 0 || jv_obj_u32(node, "cost", &sn->cost[i]) != 0 || jv_obj_u64(node, "key_hi", &sn->key_hi[i]) != 0 || jv_obj_u64(node, "key_lo", &sn->key_lo[i]) != 0 || jv_obj_u64(node, "g", &sn->g[i]) != 0 || jv_obj_u32(node, "depth", &sn->depth[i]) != 0 || jv_obj_u32(node, "goal", &bit) != 0 || bit > 1) { goto fail; } sn->goal[i] = (uint8_t)bit; if (jv_obj_u32(node, "dead", &bit) != 0 || bit > 1) { goto fail; } sn->dead[i] = (uint8_t)bit; } for (size_t i = 0; i < sn->open_n; i++) { const jv *e = jv_at(open, i); uint64_t idx;
if (!e || e->type != JV_NUM) { goto fail; } idx = e->num; if (idx >= sn->n) { goto fail; } sn->open[i] = (uint32_t)idx; } return 0;fail: snap_free(sn); return -1;}
typedef struct { const char *name; const char *dtype; uint64_t count; size_t esize; const void *data;} st_tensor;
static int st_append(char *buf, size_t cap, size_t *len, const char *fmt, ...){ va_list ap; int w;
va_start(ap, fmt); w = vsnprintf(buf + *len, cap - *len, fmt, ap); va_end(ap); if (w < 0 || (size_t)w >= cap - *len) { return -1; } *len += (size_t)w; return 0;}
static int st_write_snap(const lit_search_snap *sn, const char *path){ st_tensor t[13]; size_t nt = 0; char hdr[8192]; size_t len = 0; uint64_t off = 0; FILE *f; int bad = 0;
t[nt++] = (st_tensor){"parent", "U32", sn->n, 4, sn->parent}; t[nt++] = (st_tensor){"act_kind", "U32", sn->n, 4, sn->kind}; t[nt++] = (st_tensor){"act_id", "U32", sn->n, 4, sn->id}; t[nt++] = (st_tensor){"act_x", "U32", sn->n, 4, sn->x}; t[nt++] = (st_tensor){"act_y", "U32", sn->n, 4, sn->y}; t[nt++] = (st_tensor){"act_cost", "U32", sn->n, 4, sn->cost}; t[nt++] = (st_tensor){"key_hi", "U64", sn->n, 8, sn->key_hi}; t[nt++] = (st_tensor){"key_lo", "U64", sn->n, 8, sn->key_lo}; t[nt++] = (st_tensor){"g", "U64", sn->n, 8, sn->g}; t[nt++] = (st_tensor){"depth", "U32", sn->n, 4, sn->depth}; t[nt++] = (st_tensor){"goal", "U8", sn->n, 1, sn->goal}; t[nt++] = (st_tensor){"dead", "U8", sn->n, 1, sn->dead}; t[nt++] = (st_tensor){"open", "U32", sn->open_n, 4, sn->open};
if (st_append(hdr, sizeof(hdr), &len, "{") != 0) { return -1; } for (size_t i = 0; i < nt; i++) { uint64_t bytes = t[i].count * t[i].esize;
if (st_append(hdr, sizeof(hdr), &len, "%s\"%s\":{\"dtype\":\"%s\",\"shape\":[%llu]," "\"data_offsets\":[%llu,%llu]}", i ? "," : "", t[i].name, t[i].dtype, (unsigned long long)t[i].count, (unsigned long long)off, (unsigned long long)(off + bytes)) != 0) { return -1; } off += bytes; } if (st_append(hdr, sizeof(hdr), &len, ",\"__metadata__\":{\"format\":\"lit-search-tree\"," "\"version\":\"1\",\"anchor\":\"%u\"," "\"anchor_valid\":\"%d\",\"n\":\"%u\"}}", (unsigned)sn->anchor, sn->anchor_valid ? 1 : 0, (unsigned)sn->n) != 0) { return -1; } while (len % 8 != 0) { if (len + 1 >= sizeof(hdr)) { return -1; } hdr[len++] = ' '; } f = fopen(path, "wb"); if (!f) { return -1; } { unsigned char sz[8]; uint64_t hlen = (uint64_t)len;
for (int i = 0; i < 8; i++) { sz[i] = (unsigned char)(hlen >> (8 * i)); } if (fwrite(sz, 1, 8, f) != 8) { bad = 1; } } if (!bad && fwrite(hdr, 1, len, f) != len) { bad = 1; } for (size_t i = 0; i < nt && !bad; i++) { if (t[i].count != 0 && fwrite(t[i].data, t[i].esize, t[i].count, f) != t[i].count) { bad = 1; } } if (fclose(f) != 0) { bad = 1; } return bad ? -1 : 0;}
static int st_shape1(const jv *root, const char *name, uint64_t *out){ const jv *t = jv_get(root, name); const jv *shape;
if (!t || t->type != JV_OBJ) { return -1; } shape = jv_get(t, "shape"); if (!shape || shape->type != JV_ARR || jv_len(shape) != 1) { return -1; } return jv_arr_u64(shape, 0, out);}
static int st_tensor_get(const jv *root, const char *name, const char *dtype, uint64_t count, size_t esize, const char *data, size_t dlen, void *out){ const jv *t = jv_get(root, name); const jv *shape; const jv *offs; uint64_t dim; uint64_t begin; uint64_t end;
if (!t || t->type != JV_OBJ) { return -1; } if (!jv_str_is(jv_get(t, "dtype"), dtype)) { return -1; } shape = jv_get(t, "shape"); offs = jv_get(t, "data_offsets"); if (!shape || shape->type != JV_ARR || jv_len(shape) != 1 || jv_arr_u64(shape, 0, &dim) != 0 || dim != count) { return -1; } if (!offs || offs->type != JV_ARR || jv_len(offs) != 2 || jv_arr_u64(offs, 0, &begin) != 0 || jv_arr_u64(offs, 1, &end) != 0) { return -1; } if (end < begin || end > dlen || end - begin != count * esize) { return -1; } if (count != 0) { memcpy(out, data + begin, (size_t)(end - begin)); } return 0;}
static int jv_meta_u64(const jv *meta, const char *key, uint64_t *out){ const jv *v = jv_get(meta, key); char *endp; unsigned long long x;
if (!v) { return 1; } if (v->type != JV_STR || !v->str) { return -1; } x = strtoull(v->str, &endp, 10); if (endp == v->str || *endp != '\0') { return -1; } *out = (uint64_t)x; return 0;}
static int st_read_snap(const jv *root, const char *data, size_t dlen, lit_search_snap *sn){ const jv *meta; uint64_t n; uint64_t open_n; uint64_t v; int rc;
if (!root || root->type != JV_OBJ) { return -1; } if (st_shape1(root, "parent", &n) != 0 || n == 0 || n > UINT32_MAX) { return -1; } if (st_shape1(root, "open", &open_n) != 0 || open_n > (uint64_t)(SIZE_MAX / sizeof(uint32_t))) { return -1; } if (snap_alloc(sn, (uint32_t)n, (size_t)open_n) != 0) { return -1; } if (st_tensor_get(root, "parent", "U32", n, 4, data, dlen, sn->parent) != 0 || st_tensor_get(root, "act_kind", "U32", n, 4, data, dlen, sn->kind) != 0 || st_tensor_get(root, "act_id", "U32", n, 4, data, dlen, sn->id) != 0 || st_tensor_get(root, "act_x", "U32", n, 4, data, dlen, sn->x) != 0 || st_tensor_get(root, "act_y", "U32", n, 4, data, dlen, sn->y) != 0 || st_tensor_get(root, "act_cost", "U32", n, 4, data, dlen, sn->cost) != 0 || st_tensor_get(root, "key_hi", "U64", n, 8, data, dlen, sn->key_hi) != 0 || st_tensor_get(root, "key_lo", "U64", n, 8, data, dlen, sn->key_lo) != 0 || st_tensor_get(root, "g", "U64", n, 8, data, dlen, sn->g) != 0 || st_tensor_get(root, "depth", "U32", n, 4, data, dlen, sn->depth) != 0 || st_tensor_get(root, "goal", "U8", n, 1, data, dlen, sn->goal) != 0 || st_tensor_get(root, "dead", "U8", n, 1, data, dlen, sn->dead) != 0 || st_tensor_get(root, "open", "U32", open_n, 4, data, dlen, sn->open) != 0) { goto fail; } sn->anchor = UINT32_MAX; sn->anchor_valid = 0; meta = jv_get(root, "__metadata__"); if (meta) { rc = jv_meta_u64(meta, "anchor", &v); if (rc < 0 || (rc == 0 && v > UINT32_MAX)) { goto fail; } if (rc == 0) { sn->anchor = (uint32_t)v; } rc = jv_meta_u64(meta, "anchor_valid", &v); if (rc < 0 || (rc == 0 && v > 1)) { goto fail; } if (rc == 0) { sn->anchor_valid = (int)v; } } if (sn->anchor_valid && sn->anchor >= sn->n) { goto fail; } for (uint32_t i = 0; i < sn->n; i++) { if (sn->parent[i] != UINT32_MAX && sn->parent[i] >= sn->n) { goto fail; } if (sn->goal[i] > 1 || sn->dead[i] > 1) { goto fail; } } for (size_t i = 0; i < sn->open_n; i++) { if (sn->open[i] >= sn->n) { goto fail; } } return 0;fail: snap_free(sn); return -1;}
static lit_search *search_from_snap(const lit_host *host, const lit_search_snap *sn){ lit_search *s; uint32_t idx;
if (!sn || sn->n == 0) { return NULL; } s = search_alloc(host); if (!s) { return NULL; } for (uint32_t i = 0; i < sn->n; i++) { lit_snode node; lit_key key;
memset(&node, 0, sizeof(node)); node.parent = sn->parent[i]; node.act.kind = sn->kind[i]; node.act.id = sn->id[i]; node.act.x = sn->x[i]; node.act.y = sn->y[i]; node.act.cost = sn->cost[i]; key.hi = sn->key_hi[i]; key.lo = sn->key_lo[i]; node.key = key; node.g = sn->g[i]; node.depth = sn->depth[i]; node.goal = sn->goal[i]; node.dead = sn->dead[i]; node.expanded = 1; if (sarena_add(&s->nodes, &node, &idx) != 0 || idx != i) { goto fail; } } for (uint32_t i = 1; i < sn->n; i++) { uint32_t p = s->nodes.v[i].parent;
if (p != UINT32_MAX && p < i) { link_child(s, p, i); } } for (uint32_t i = 0; i < sn->n; i++) { lit_key key;
key.hi = sn->key_hi[i]; key.lo = sn->key_lo[i]; /* Open-set trees deliberately contain duplicate keys (a sampled * counterfactual can land on a seen state). The seen table keeps * the first node; a duplicate is not a load error. */ if (ktab_insert(&s->seen, key, i) < 0) { goto fail; } } for (size_t i = 0; i < sn->open_n; i++) { uint32_t node = sn->open[i];
if (node >= sn->n) { goto fail; } s->nodes.v[node].expanded = 0; } for (size_t i = 0; i < sn->open_n; i++) { if (heap_push(s, sn->open[i]) != 0) { goto fail; } } s->anchor = sn->anchor; s->anchor_valid = sn->anchor_valid; if (s->anchor_valid && s->anchor >= sn->n) { goto fail; } if (!s->anchor_valid) { s->anchor = UINT32_MAX; } return s;fail: lit_search_free(s); return NULL;}
int lit_search_save_json(const lit_search *s, const char *path){ lit_search_snap sn; int rc;
if (!s || !path || snap_from_search(s, &sn) != 0) { return -1; } rc = json_write_snap(&sn, path); snap_free(&sn); return rc;}
int lit_search_save_safetensors(const lit_search *s, const char *path){ lit_search_snap sn; int rc;
if (!s || !path || snap_from_search(s, &sn) != 0) { return -1; } rc = st_write_snap(&sn, path); snap_free(&sn); return rc;}
lit_search *lit_search_load_json(const lit_host *host, const char *path){ jv_parser jp; char *file = NULL; size_t len = 0; const char *p; const char *end; const jv *root; lit_search_snap sn; lit_search *s = NULL;
if (!host || !path || read_whole(path, &file, &len) != 0) { return NULL; } memset(&jp, 0, sizeof(jp)); p = file; end = file + len; jv_ws(&p, end); root = jv_value(&jp, &p, end, 0); if (root) { jv_ws(&p, end); if (p != end) { root = NULL; } } memset(&sn, 0, sizeof(sn)); if (root && json_read_snap(root, &sn) == 0) { s = search_from_snap(host, &sn); } snap_free(&sn); jv_free(&jp); free(file); return s;}
lit_search *lit_search_load_safetensors(const lit_host *host, const char *path){ jv_parser jp; char *file = NULL; size_t len = 0; uint64_t hlen = 0; const char *p; const char *end; const jv *root; const char *data; size_t dlen; lit_search_snap sn; lit_search *s = NULL;
if (!host || !path || read_whole(path, &file, &len) != 0 || len < 8) { free(file); return NULL; } for (int i = 0; i < 8; i++) { hlen |= (uint64_t)(unsigned char)file[i] << (8 * i); } if (hlen < 2 || hlen > len - 8 || hlen % 8 != 0) { free(file); return NULL; } memset(&jp, 0, sizeof(jp)); p = file + 8; end = p + hlen; jv_ws(&p, end); root = jv_value(&jp, &p, end, 0); if (root) { jv_ws(&p, end); if (p != end) { root = NULL; } } data = file + 8 + hlen; dlen = len - 8 - (size_t)hlen; memset(&sn, 0, sizeof(sn)); if (root && st_read_snap(root, data, dlen, &sn) == 0) { s = search_from_snap(host, &sn); } snap_free(&sn); jv_free(&jp); free(file); return s;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292/* * lit_operator.h — the LIT DO search operator, the mainline for * program synthesis. * * One intervention per DO node; the tree stores the interventions, not * machine states. A search path, flattened, is a program: the actions * from the root to a goal are exactly the program text. The Coder is * the macro miner that supplies material; it is not the mainline. * * The operator owns the DO node arena, the frontier scan, the optional * global attention (score), and the flat C array; the caller supplies * the machine/state, the actions, and the oracle. There is no game, * no DFS engine, and no metadata hash. */#ifndef LIT_OPERATOR_H#define LIT_OPERATOR_H
#include "lit_core.h"
#include <stddef.h>#include <stdint.h>
#ifdef __cplusplusextern "C" {#endif
#define LIT_DO_MAX 256
typedef enum { LIT_DO_WIRE = 0, LIT_DO_LOAD = 1} lit_do_kind;
typedef struct { lit_do_kind kind; uint32_t slot; uint32_t src; uint64_t gain; uint64_t weight; uint64_t value;} lit_do;
typedef struct lit_donode { struct lit_donode *parent; struct lit_donode *first_child; struct lit_donode *next_sibling; lit_do op; uint32_t depth; uint8_t state;} lit_donode;
#define LIT_DO_OPEN 0#define LIT_DO_CLOSED 1#define LIT_DO_CUT 2
/* Apply one DO to a settled machine, in every cluster: a LOAD writes * value at slot (masked to L), a WIRE reconnects slot. No tick; the * caller calls lit_machine_step() next. Returns 0 or -1. */int lit_do_apply(lit_machine *m, const lit_do *d);
/* Rebuild a node's machine state by replaying its DO chain from the * root: `m` must already hold the root machine state (before the first * intervention), and the root node replays nothing. Wiring made by * WIRE DOs is replayed too, so counterfactual worlds never contaminate * each other. Returns 0 or -1. */int lit_do_restore(const lit_donode *node, lit_machine *m);
/* Stable chunked DO node arena: the tree. */#define LIT_DO_CHUNK 65536
typedef struct { lit_donode **chunk; size_t nchunk; size_t used; size_t cap;} lit_do_arena;
lit_donode *lit_do_alloc(lit_do_arena *a, lit_donode *parent, const lit_do *op, uint32_t depth);void lit_do_arena_free(lit_do_arena *a);
/* Flat, high-dimensional C array of the DO tree. This is the weight, * not a walkthrough: parent, the full DO (kind/slot/src/gain/weight/ * value), depth, plus the root machine state stored once. Every other * node's state is replayed from its DO chain; no per-node state is * stored. Root has parent UINT32_MAX and no usable DO. It can be * saved as a binary sidecar and emitted as a static const C source. */typedef struct { uint32_t n; uint32_t words; /* slots * clusters */ uint32_t slots; uint32_t clusters; uint32_t bits; uint32_t *parent; /* UINT32_MAX = root */ uint32_t *kind; uint32_t *slot; uint32_t *do_src; uint64_t *gain; /* DO gain */ uint64_t *weight; /* DO weight */ uint64_t *value; /* LOAD value */ uint32_t *depth; /* the root machine state, one copy */ uint64_t *root_v; /* words */ uint32_t *root_src; /* words */ uint64_t *root_gain; /* words */ uint64_t *root_weight; /* words */ uint64_t *root_dist; /* clusters */ uint64_t *root_diff; /* words */} lit_tree;
int lit_tree_flatten(lit_tree *t, const lit_do_arena *a, const lit_machine *root);/* Replay flat-tree node i from the stored root state into m. */int lit_tree_restore(const lit_tree *t, uint32_t i, lit_machine *m);void lit_tree_free(lit_tree *t);int lit_tree_save(const lit_tree *t, const char *path);int lit_tree_load(lit_tree *t, const char *path);int lit_tree_write_c(const lit_tree *t, const char *path, const char *name);
/* The tree keeps one node per DO. Each node's score is the DO's score, * accumulated along its path from the root (g); the host supplies each * action's score as its cost. There is no heuristic and no estimate of * the goal: nothing predicts how far a node is from done, and the goal * is only the stopping condition. There is no open list: the next node * to expand is the unexpanded node with the largest score, found by a * linear comparison (< / >); ties take the earlier node. Duplicate * observations are dropped when they are generated (seen set). */typedef struct { uint32_t kind; uint32_t id; uint32_t x; uint32_t y; uint32_t cost; /* the DO's score, accumulated into g */} lit_action;
typedef struct { uint64_t hi; uint64_t lo;} lit_key;
/* A read-only view of one node of the search tree, for a host that * chooses the next intervention itself (jump/backtrack to any node, * not just the open frontier). Indices are stable: a node index never * changes and nodes are only appended. */typedef struct { uint32_t parent; /* UINT32_MAX = root */ uint32_t depth; uint64_t g; lit_key key; lit_action act; /* the node's own opaque action */ uint32_t first_child; /* UINT32_MAX = none */ uint32_t next_sibling; /* UINT32_MAX = none */ uint8_t goal; uint8_t dead; uint8_t expanded; /* already expanded once (read-only) */} lit_node_view;
/* Optional host choice. When set on the host, the operator does not * pick from the frontier: it asks the host for any node index in [0, n) * and expands that node (a node already expanded may be chosen again: * backtracking). The seen set is bypassed, so every intervention * creates a new branch; dead nodes are kept in the tree for the host. * Return 0 and write the index, or non-zero to stop the search (the * driver returns LIT_SEARCH_EMPTY). The host owns the policy; the * operator only exposes the tree. */typedef int (*lit_choose_fn)(void *ctx, const lit_node_view *nodes, size_t n, uint32_t *node);
/* Optional global attention. When set (and choose is not), the operator * asks the host for one score per node of the whole tree (the same * append-only view array choose sees) and expands the largest by a * direct comparison; ties take the earlier node. Dead nodes are * skipped; a chosen goal returns its path. Expanded nodes may be * chosen again (backtracking) and the seen set is bypassed: every * intervention creates a new branch. The host supplies the numbers * (material); the operator owns the comparison and the jump. Return * non-zero to stop the search (LIT_SEARCH_EMPTY). Score mode requires * the batch expand callback. */typedef int (*lit_score_fn)(void *ctx, const lit_node_view *nodes, size_t n, uint64_t *scores);
typedef struct { void *ctx; int (*root)(void *ctx, lit_key *key, int *goal, int *dead); /* The host rebuilds the state by replaying `path` from the root; no per-node machine state is stored anywhere. With choose set the key is informational only. */ int (*actions)(void *ctx, const lit_action *path, size_t path_len, const lit_action **acts, size_t *n); /* Batch expansion: one game-engine round trip per parent. The host evaluates acts[0..nacts) from the state at path and fills keys, goals, and deads. Returns 0. */ int (*expand)(void *ctx, const lit_action *path, size_t path_len, const lit_action *acts, const uint64_t *child_g, size_t nacts, lit_key *keys, int *goals, int *deads); int (*eval)(void *ctx, const lit_action *path, size_t path_len, const lit_action *act, uint64_t child_g, lit_key *child, int *goal, int *dead); /* Optional O(1) restore. The operator calls it with the popped node's key before asking the host for actions; returning 0 means the world is already at that node, so the host may skip the reset plus path replay. Non-zero is not an error: the host falls back to its own restore. */ int (*seek)(void *ctx, const lit_key *key); void (*event)(void *ctx, const lit_action *path, size_t path_len, uint64_t pops, uint64_t nodes, size_t open, double g, double score, int goal); lit_choose_fn choose; /* optional: jump/backtrack policy */ lit_score_fn score; /* optional: global attention (choose wins) */} lit_host;
typedef struct { uint64_t max_steps; /* 0 = unlimited */ uint64_t max_nodes; /* 0 = unlimited; counts pops */} lit_search_opts;
typedef struct { lit_action *acts; size_t n; uint64_t pops; uint64_t nodes;} lit_path;
enum { LIT_SEARCH_FOUND = 0, LIT_SEARCH_EMPTY = 1, LIT_SEARCH_BUDGET = 2, LIT_SEARCH_ERROR = -1};
int lit_search_run(const lit_host *host, const lit_search_opts *opts, lit_path *out);
/* Memory search: the path is the working memory. Every step asks the * host for its actions (the hard-wired neighbourhood of the current * state), scores every child with the host's DO score (the action's * cost), and takes the largest by a direct comparison; the goal is only * the stopping condition. No open list, no heuristic, no softmax, no * learned weight. Lives in the operator so the policy is part of the * machine, not of the host. */int lit_memory_search(const lit_host *host, const lit_search_opts *opts, lit_path *out);
/* A persistent search session: the tree and seen set keep growing. A * found path becomes the anchor for the next level; the next continue * closes the rest of the tree and grows from that node. The host's * root callback is used once, at session creation. */typedef struct lit_search lit_search;lit_search *lit_search_new(const lit_host *host);int lit_search_continue(lit_search *s, const lit_search_opts *opts, lit_path *out);/* Bulk ingest one causal edge: append a node under `parent` with an * opaque action, a host key, an accumulated g, and the judge flags. * The node starts unexpanded, so a later continue can grow from it. * The seen set records the key for the search. Returns the new index, * or UINT32_MAX on error. The operator never interprets the action. */uint32_t lit_search_ingest(lit_search *s, uint32_t parent, const lit_action *act, lit_key key, uint64_t g, int goal, int dead);/* Follow a path's opaque actions through the tree's child links; return * the node index (UINT32_MAX if a step has no matching child) and, when * key is non-NULL, the node's key. */uint32_t lit_search_follow(const lit_search *s, const lit_action *path, size_t path_len, lit_key *key);/* Copy one node view: action, key, child links, flags. */int lit_search_node(const lit_search *s, uint32_t i, lit_node_view *out);/* Tree statistics: flat nodes, unique keys (seen), open heap size. */void lit_search_stats(const lit_search *s, uint64_t *nodes, uint64_t *unique, uint64_t *open);void lit_search_free(lit_search *s);void lit_path_free(lit_path *p);
/* Persist a search session: the tree nodes (parent, action, key, g, * depth, goal, dead), the frontier of unexpanded nodes, and the anchor. * JSON is the inspectable text form; safetensors is the tensor form, one * U32/U64/U8 tensor per node array, little-endian. Loading rebinds the * host without calling its root callback, so the next continue resumes * the tree; the game itself stays in the host. */int lit_search_save_json(const lit_search *s, const char *path);int lit_search_save_safetensors(const lit_search *s, const char *path);lit_search *lit_search_load_json(const lit_host *host, const char *path);lit_search *lit_search_load_safetensors(const lit_host *host, const char *path);
#ifdef __cplusplus}#endif#endif /* LIT_OPERATOR_H */123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572#!/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
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}123version https://git-lfs.github.com/spec/v1oid sha256:198069ba63b1a18764c271a4111d00ebaa57357a924c05241eea319651100641size 5564111123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388#!/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 isexactly 16 hex digits. A state is a fixed 64-slot u64 vector (pad withzero); its key is a 64-bit hash, also written as 16 hex digits. Anaction is packed dims in one u64, again 16 hex digits.
The codec is schema-driven: the robot/dataset supplies dim ranges andbit widths, and the codec never interprets them. The operator sees onlythe resulting u64 key/action; the tree can be shared across schemasbecause every key is schema-tagged."""import hashlibimport struct
U64 = 1 << 64U64_MASK = U64 - 1SLOTS = 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))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247#!/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 decisionopens 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 thearm. If no path reaches the judge, no action is fabricated: the callergets ``None`` and the search set stays open."""import argparseimport ctypes as Cimport randomimport sys
from lit_codec import FeatureCodecfrom 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_uint32LIB.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 argtypesfrom 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))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205#!/usr/bin/env python3"""lit_libero.py — LIBERO arm adapter for the LIT DO search operator.
The operator is the product core (liblit.dylib / liblit.so). This fileis only the host: it names the world (one LIBERO task), supplies theaction space (one 7-dim grid per robot), encodes a canonical task-spacestate key, and runs the one-line success judge at the halt.
The operator never sees a robot, a joint, or a task. The action spacelives here and can change per robot; the tree stores only lit_actionand lit_key."""import ctypes as Cimport osimport sys
import numpy as np
from lit_codec import FeatureCodec
HERE = os.path.dirname(os.path.abspath(__file__))SANDBOX = os.path.dirname(HERE)REPO = os.path.dirname(SANDBOX)OP = os.path.join(REPO, "lit_operator")if OP not in sys.path: sys.path.insert(0, OP)
from lit_world import ( # noqa: E402 ACTIONS_FN, CHOOSE_FN, EVAL_FN, EVENT_FN, EXPAND_FN, LIB, LIT_SEARCH_BUDGET, LIT_SEARCH_EMPTY, LIT_SEARCH_FOUND, LitAction, LitHost, LitKey, LitNodeView, LitPath, LitSearchOpts, ROOT_FN, SCORE_FN, SEEK_FN)
# ------------------------------------------------------------- the hostclass LiberoHost: """The arm world as the operator sees it: opaque actions and keys.
The action space (the grid) is assembled here, per robot. The operator stores only LitAction; nothing about Panda / LIBERO crosses the ABI. The judge is check_success() at the halt, one line of IF. """
def __init__(self, env, grid, max_depth=3, verbose=False): self.env = env self.grid = [np.asarray(a, dtype=np.float32) for a in grid] self.max_depth = max_depth self.verbose = verbose self.root_state = None self.expansions = 0 obs = self.env.reset() features = {} for k, v in obs.items(): arr = np.asarray(v) features[k] = {"dtype": "float32", "shape": list(arr.shape) or [1]} action_features = {"action%d" % i: float for i in range(len(self.grid[0]))} self.codec = FeatureCodec.from_robot("libero", features, action_features)
n = len(self.grid) self.acts_buf = (LitAction * n)() for i in range(n): self.acts_buf[i].kind = i # the grid index is the action self.acts_buf[i].cost = 1 # the DO score
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.ctx = None 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 encoding: canonical task-space features, quantized ----- def state_key(self, obs): return (self.codec.state_key(self.codec.state_words(obs)), 0)
# -- replay a path from the seeded root --------------------------- def _replay(self, path, path_len): self.env.seed(0) obs = self.env.reset() for i in range(path_len): a = self.grid[path[i].kind] obs, _, _, _ = self.env.step(a) return obs
# -- callbacks ---------------------------------------------------- def _root(self, ctx, key, goal, dead): _ = ctx self.env.seed(0) obs = self.env.reset() self.root_state = self.env.get_sim_state() key[0].hi, key[0].lo = self.state_key(obs) goal[0] = 0 dead[0] = 0 return 0
def _actions(self, ctx, path, path_len, acts_out, n_out): _ = ctx, path if path_len >= self.max_depth: n_out[0] = 0 return 0 acts_out[0] = C.cast(self.acts_buf, C.POINTER(LitAction)) n_out[0] = len(self.grid) return 0
def _expand(self, ctx, path, path_len, acts, child_g, nacts, keys, goals, deads): _ = ctx, child_g self._replay(path, path_len) state = self.env.get_sim_state() for i in range(nacts): self.env.set_state(state) self.env.env.sim.forward() a = self.grid[acts[i].kind] obs2, _, _, _ = self.env.step(a) success = self.env.check_success() # one line of IF key = self.state_key(obs2) keys[i].hi, keys[i].lo = key goals[i] = 1 if success else 0 deads[i] = 0 self.env.set_state(state) self.env.env.sim.forward() self.expansions += 1 return 0
def _event(self, ctx, path, path_len, pops, nodes, open_n, g, score, goal): _ = ctx, path, open_n, g, score if self.verbose: print("event: pops=%d nodes=%d depth=%d goal=%d" % (pops, nodes, path_len, goal))
# ------------------------------------------------------------- the rundef make_env(task_index=0, suite_name="libero_spatial"): from libero.libero import benchmark, get_libero_path from libero.libero.envs.env_wrapper import ControlEnv
suite = benchmark.get_benchmark_dict()[suite_name]() task = suite.get_task(task_index) bddl = os.path.join(get_libero_path("bddl_files"), task.problem_folder, task.bddl_file) print("task:", task.name) print("language:", task.language) env = ControlEnv( bddl_file_name=bddl, use_camera_obs=False, has_offscreen_renderer=False, has_renderer=False, hard_reset=True, camera_heights=64, camera_widths=64, ) return env, task
def main(argv): task_index = int(argv[1]) if len(argv) > 1 else 0 max_depth = int(argv[2]) if len(argv) > 2 else 3 max_nodes = int(argv[3]) if len(argv) > 3 else 40
env, _ = make_env(task_index) # Three actions for the first smoke: stay, push +x, push -x; the # gripper stays open. The external action space can be anything. grid = [ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0], [0.5, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0], [-0.5, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0], ] host = LiberoHost(env, grid, max_depth=max_depth, verbose=True) s = LIB.lit_search_new(C.byref(host.host)) if not s: raise SystemExit("lit_search_new failed")
opts = LitSearchOpts(max_steps=0, max_nodes=max_nodes) path = LitPath() rc = LIB.lit_search_continue(s, C.byref(opts), C.byref(path)) print("search rc=%d pops=%d nodes=%d path=%d expansions=%d" % (rc, path.pops, path.nodes, path.n, host.expansions)) if rc == LIT_SEARCH_FOUND and path.n: acts = [path.acts[i].kind for i in range(path.n)] print("found path:", acts)
out = os.path.join(HERE, "lit_libero.json") if LIB.lit_search_save_json(s, out.encode()) != 0: print("save failed") else: print("tree:", out)
LIB.lit_path_free(C.byref(path)) LIB.lit_search_free(s) env.close() return 0 if rc in (LIT_SEARCH_FOUND, LIT_SEARCH_EMPTY, LIT_SEARCH_BUDGET) else 1
if __name__ == "__main__": raise SystemExit(main(sys.argv))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490#!/usr/bin/env python3"""lit_pretrain.py — 2-hour world-machine pretraining, C-side edge index.
Stream LeRobot v3 real-robot datasets over HTTPS (no dataset on disk),encode every causal edge with the 16-hex codec, ingest it into the Cflat tree, run the per-edge open-pool search, discard the raw data, andcheckpoint the tree.
The datasets are polled round-robin: each gets an equal slice of therun (total minutes / number of datasets) before the next one, so onelarge corpus cannot eat the whole window. Data inside a dataset staysin its natural order; search does not need a shuffled feed.
Ingestion is open-set too: every expansion returns the stored childrenplus freshly sampled counterfactual actions whose next proprioceptivestate is the action target itself. The tree grows states the data nevershowed; the closed edge set is never the only frontier.
The C tree is the only edge table: ``lit_search_ingest`` appends a node,``lit_search_follow`` walks a path through the child links, and``lit_search_node`` reads one view. Python keeps no per-edge dict, somemory is the operator's ~68 B/node, not a tuple/list graph. That iswhat lets a laptop hold the pretraining."""import argparseimport ctypes as Cimport hashlibimport osimport randomimport time
from lit_libero import ( ACTIONS_FN, EVENT_FN, EXPAND_FN, LIB, LitAction, LitHost, LitKey, LitNodeView, LitPath, LitSearchOpts, ROOT_FN,)from lit_stream import community_roots, iter_transitions
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_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_p
def read_progress(stem): for path in (stem + ".progress", os.path.splitext(stem)[0] + ".progress"): try: with open(path) as f: return f.read().strip() except OSError: pass return ""
def write_progress(stem, label): try: with open(stem + ".progress", "w") as f: f.write(label) except OSError: pass
REAL_DATASETS = [ "lerobot/svla_so101_pickplace", "lerobot/droid_100", "lerobot/svla_so100_pickplace", "lerobot/aloha_static_coffee", "lerobot/aloha_mobile_cabinet", "lerobot/koch_pick_place_1_lego", "lerobot/piper-collect", "lerobot/abc_130k_v3_smoke", "lerobot/umi_cup_in_the_wild", "lerobot/droid_1.0.1", "lerobot/abc_130k_v3_train", "lerobot/full_folding",]
def all_real_datasets(): """One-click select-all: every real-robot LeRobot dataset.
Simulation corpora, assets, hardware-modification repos and benchmark result dumps are excluded; a real dataset whose name merely contains e.g. "pusht_real" is kept. If the Hub is unreachable, the curated REAL_DATASETS list is the fallback. """ try: from huggingface_hub import HfApi ids = [d.id for d in HfApi().list_datasets(author="lerobot", limit=500)] except Exception: return list(REAL_DATASETS) sim_prefix = ( "libero", "pusht", "metaworld", "behavior1k", "robocasa", "robotwin", "vlabench", "calvin", "aloha_sim", "robomme", "usc_cloth_sim", ) non_data = ( "assets", "urdfs", "usds", "hardware-modifications", "config_examples", "benchmark", "smpl", "cosmos3", "depth", ) out = [] for i in ids: name = i.split("/", 1)[-1].lower() if any(name.startswith(p) for p in sim_prefix): continue if any(n in name for n in non_data): continue out.append(i) return out or list(REAL_DATASETS)
class DataHost: """The C tree is the only edge table; the search set is open.
Every expansion returns the ingested children plus freshly sampled counterfactual actions. A sampled action's next state is predicted by the kinematic rule: the action is the target, so the next proprioceptive state is the action vector itself, encoded with the same 16-hex codec. Training therefore grows states the data never showed, instead of only replaying the closed edge set. """
def __init__(self, open_actions=1, new_actions=1, seed=0): self.root_key = None self.s = None self.current_children = [] self.current_samples = [] self.codec = None self.open_actions = int(open_actions) > 0 self.new_actions = int(new_actions) self.rng = random.Random(seed) 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
@staticmethod def _start_code(repo, ep): h = hashlib.blake2b(("%s:%s" % (repo, ep)).encode(), digest_size=8).digest() return 0x8000000000000000 | (int.from_bytes(h, "little") & 0x7FFFFFFFFFFFFFFF)
def set_root(self, key): self.root_key = key
def add_start(self, sess, repo, ep, codec, frame): self.codec = codec sk = codec.state_key(codec.state_words(frame)) sc = self._start_code(repo, ep) act = LitAction(0, sc & 0xFFFFFFFF, (sc >> 32) & 0xFFFFFFFF, 0, 1) return LIB.lit_search_ingest(sess, 0, C.byref(act), LitKey(sk, 0), 0, 0, 0)
def add_edge(self, sess, parent, codec, action, next_frame, done): self.codec = codec nk = codec.state_key(codec.state_words(next_frame)) ac = codec.action_code(action) act = LitAction(0, ac & 0xFFFFFFFF, (ac >> 32) & 0xFFFFFFFF, 0, 1) goal = 1 if done else 0 return LIB.lit_search_ingest(sess, parent, C.byref(act), LitKey(nk, 0), 0, goal, 0)
def _root(self, ctx, key, goal, dead): _ = ctx k = self.root_key if self.root_key is not None else (0, 0) key[0].hi, key[0].lo = k goal[0] = 0 dead[0] = 0 return 0
def _view(self, node): v = LitNodeView() if LIB.lit_search_node(self.s, node, C.byref(v)) != 0: return None return v
def _actions(self, ctx, path, path_len, acts_out, n_out): _ = ctx, acts_out node = LIB.lit_search_follow(self.s, path, path_len, None) if node == 0xFFFFFFFF: self.current_children = [] self.current_samples = [] n_out[0] = 0 return 0 v = self._view(node) if v is None: self.current_children = [] self.current_samples = [] n_out[0] = 0 return 0 children = [] c = v.first_child while c != 0xFFFFFFFF: cv = self._view(c) if cv is None: break children.append(cv) c = cv.next_sibling self.current_children = children
samples = [] if self.open_actions and self.codec is not None and \ self.codec.action_dims: for _ in range(self.new_actions): code = 0 shift = 0 for d in self.codec.action_dims: code |= self.rng.randrange(1 << d.bits) << shift shift += d.bits samples.append(code & ((1 << 64) - 1)) self.current_samples = samples
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, cv in enumerate(children): self._buf[i] = cv.act for j, code in enumerate(samples): self._buf[len(children) + j] = LitAction( 0, code & 0xFFFFFFFF, (code >> 32) & 0xFFFFFFFF, 0, 1) 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, path, path_len, child_g nc = len(self.current_children) for i in range(nacts): if i < nc: cv = self.current_children[i] keys[i].hi, keys[i].lo = cv.key.hi, cv.key.lo goals[i] = cv.goal deads[i] = 0 continue # kinematic world model: the action is the next proprio state code = (acts[i].id | (acts[i].x << 32)) & ((1 << 64) - 1) vec = self.codec.action_vec(code) words = [0] * 64 for j, (_name, _j, d) in enumerate(self.codec.state_slots[:64]): if j < len(vec): words[j] = d.state_word(vec[j]) nk = self.codec.state_key(words) keys[i].hi, keys[i].lo = nk, 0 goals[i] = 0 deads[i] = 0 return 0
def _event(self, ctx, path, path_len, pops, nodes, open_n, g, score, goal): _ = ctx, path, g, score if goal or pops % 100 == 0: print("search: pops=%d nodes=%d open=%d depth=%d goal=%d" % (pops, nodes, open_n, path_len, goal), flush=True)
def search_pass(s, max_nodes=0): """One open-pool search; with open actions the per-edge budget bounds it.""" opts = LitSearchOpts(max_steps=0, max_nodes=max_nodes) path = LitPath() rc = LIB.lit_search_continue(s, C.byref(opts), C.byref(path)) pops, nodes, n = path.pops, path.nodes, path.n LIB.lit_path_free(C.byref(path)) return rc, pops, nodes, n
def save_tree(s, stem): if LIB.lit_search_save_safetensors(s, (stem + ".safetensors").encode()) != 0: print("save safetensors failed", flush=True) if LIB.lit_search_save_json(s, (stem + ".json").encode()) != 0: print("save json failed", flush=True) else: print("tree saved:", stem + ".json", flush=True)
def stats(s): nodes = C.c_uint64() unique = C.c_uint64() open_n = C.c_uint64() LIB.lit_search_stats(s, C.byref(nodes), C.byref(unique), C.byref(open_n)) return nodes.value, unique.value, open_n.value
def main(argv): p = argparse.ArgumentParser(description=__doc__) p.add_argument("--minutes", type=float, default=120.0) p.add_argument("--datasets", default="all") p.add_argument("--checkpoint-every", type=float, default=10.0) p.add_argument("--no-video", action="store_true", help="skip cameras; state/action/text/peripherals only") p.add_argument("--max-edges", type=int, default=0) p.add_argument("--community", action="store_true", help="datasets are community repos: stream every " "<contributor>/<dataset> subdataset") p.add_argument("--roots", default="", help="comma-separated subdataset roots for --community") p.add_argument("--start-root", default="", help="resume a community pass at this root") p.add_argument("--seed", type=int, default=0) p.add_argument("--out", default="pretrain") p.add_argument("--resume", default=None) args = p.parse_args(argv[1:])
host = DataHost(open_actions=1, new_actions=1, seed=args.seed) s = None edges = 0 passes = 0 found = 0 if args.resume: loader = (LIB.lit_search_load_safetensors if args.resume.endswith(".safetensors") else LIB.lit_search_load_json) s = loader(C.byref(host.host), args.resume.encode()) if not s: print("resume failed", flush=True) return 1 host.s = s print("resume: tree loaded", flush=True) if not args.start_root: args.start_root = read_progress(args.out) if args.start_root: print("resume: start root", args.start_root, flush=True)
if args.datasets.strip().lower() == "all": repos = all_real_datasets() else: repos = [r.strip() for r in args.datasets.split(",") if r.strip()] print("datasets: %d" % len(repos), flush=True)
if args.community: want = [r.strip() for r in args.roots.split(",") if r.strip()] units = [] for repo in repos: roots = community_roots(repo) if want: roots = [r for r in roots if r in want or any(r.endswith("/" + w) or r == w for w in want)] units.extend((repo, r) for r in roots) print("community units: %d" % len(units), flush=True) else: units = [(repo, "") for repo in repos]
start = time.time() deadline = (start + args.minutes * 60.0 if args.minutes > 0 else float("inf")) per_unit = (None if args.community or args.minutes <= 0 else args.minutes * 60.0 / max(1, len(units))) last_ckpt = start last_print = start prev_node = None cur_ep = None try: skip_until = bool(args.start_root) while time.time() < deadline and \ not (args.max_edges and edges >= args.max_edges): for repo, root in units: label = repo if not root else repo + "/" + root if skip_until: if args.start_root in (root, label): skip_until = False else: continue if time.time() >= deadline or \ (args.max_edges and edges >= args.max_edges): break unit_deadline = (deadline if per_unit is None else min(deadline, time.time() + per_unit)) prev_node = None cur_ep = None repo_edges = 0 try: for ep, fi, frame, ac, nframe, done, sch, _task in \ iter_transitions(repo, args.no_video, root): _ = fi, _task if time.time() >= unit_deadline and repo_edges >= 200: break repo_edges += 1 if time.time() >= deadline: break if args.max_edges and edges >= args.max_edges: break if s is None: sk = sch.state_key(sch.state_words(frame)) host.set_root((sk, 0)) s = LIB.lit_search_new(C.byref(host.host)) if not s: raise RuntimeError("lit_search_new failed") host.s = s prev_node = 0 cur_ep = ep if cur_ep != ep: prev_node = host.add_start(s, label, ep, sch, frame) cur_ep = ep if prev_node == 0xFFFFFFFF: continue child = host.add_edge(s, prev_node, sch, ac, nframe, done) if child == 0xFFFFFFFF: continue prev_node = child edges += 1 if done: found += 1 rc, pops, nodes, path_n = search_pass(s, 1) passes += 1 if rc == 0 and path_n: found += 1 if edges % 2000 == 0: tn, un, on = stats(s) print("edges=%d tree=%d unique=%d open=%d " "search rc=%d pops=%d found=%d " "elapsed=%.1fs" % (edges, tn, un, on, rc, pops, found, time.time() - start), flush=True) now = time.time() if now - last_print >= 10.0: tn, un, on = stats(s) print("hb: repo=%s edges=%d tree=%d unique=%d " "open=%d elapsed=%.1fs" % (label, edges, tn, un, on, now - start), flush=True) last_print = now if now - last_ckpt >= args.checkpoint_every * 60.0: save_tree(s, args.out) write_progress(args.out, label) last_ckpt = now except Exception as e: print("dataset %s failed: %s" % (label, e), flush=True) continue if time.time() >= deadline: break if args.max_edges and edges >= args.max_edges: break if args.minutes <= 0: break if s is not None: save_tree(s, args.out) write_progress(args.out, locals().get("label", "")) tn, un, on = stats(s) print("final: edges=%d tree=%d unique=%d open=%d passes=%d " "found=%d elapsed=%.1fs" % (edges, tn, un, on, passes, found, time.time() - start), flush=True) finally: if s is not None: LIB.lit_search_free(s) return 0
if __name__ == "__main__": raise SystemExit(main(__import__("sys").argv))1234567891011121314151617181920212223242526272829303132333435#!/usr/bin/env python3"""lit_robot_api.py — the LeRobot glue for lit_robot.LITOperator.
from lit_robot_api import default_operator op = default_operator() program = op(frame) # [action, ...] open-loop
A frame is the usual LeRobot observation dict: cameras, `observation.state`, task. The community tree's canonical codec root is`1g0rrr/demo3_frames_grab3`."""import osimport sys
HERE = os.path.dirname(os.path.abspath(__file__))SANDBOX = os.path.dirname(HERE)REPO = os.path.dirname(SANDBOX)sys.path.insert(0, os.path.join(REPO, "lit_operator"))sys.path.insert(0, SANDBOX)
from lit_robot import LITOperator # noqa: E402
REPO_ID = "lerobot/community_dataset_v3"ROOT = "1g0rrr/demo3_frames_grab3"TREE = os.path.join(REPO, "weights", "LITOperator-community_open_selfboot.safetensors")
def lerobot_operator(tree=TREE, repo=REPO_ID, root=ROOT): from lit_stream import make_codec codec, _info = make_codec(repo, root) return LITOperator(tree, codec)
default_operator = lerobot_operator123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456#!/usr/bin/env python3"""lit_selfloop.py — the two empty-runs.
brain: the LIT machine is the world. State = V + wiring, action = DO(LOAD/WIRE), transition = lit_machine_step (one tick = F^64). Theoperator expands DOs, the tick creates new states, the convergence isthe halt judge, and the tree grows without any external data.
body: the EarthRover Mini Plus is the world. State = 22 telemetryfloats + two camera hashes, action = (linear_velocity, angular_velocity)in [-1, 1], transition = the real robot via the Frodobots SDK. Thebody cannot rewind, so it is sequential experience; each edge isingested into the same flat tree with lit_search_ingest.
Both use the 16-hex lit_codec: u64 state key, u64 action code."""import argparseimport ctypes as Cimport hashlibimport mathimport structimport sysimport time
import numpy as np
from lit_codec import FeatureCodec, hex16from lit_libero import ( ACTIONS_FN, EVENT_FN, EXPAND_FN, LIB, LIT_SEARCH_BUDGET, LIT_SEARCH_EMPTY, LIT_SEARCH_FOUND, LitAction, LitHost, LitKey, LitPath, LitSearchOpts, ROOT_FN,)
MASK = (1 << 64) - 1
# ---------------------------------------------------------------- core ABIclass LitMachine(C.Structure): _fields_ = [ ("n", C.c_uint32), ("k", C.c_uint32), ("a", C.POINTER(C.c_uint64)), ("b", C.POINTER(C.c_uint64)), ("V", C.POINTER(C.c_uint64)), ("prev", C.POINTER(C.c_uint64)), ("src", C.POINTER(C.c_uint32)), ("gain", C.POINTER(C.c_uint64)), ("weight", C.POINTER(C.c_uint64)), ("dist", C.POINTER(C.c_uint64)), ("diff", C.POINTER(C.c_uint64)), ("flat_src", C.POINTER(C.c_uint32)), ("flat_gain", C.POINTER(C.c_uint64)), ("flat_as", C.POINTER(C.c_uint32)), ("flat_bs", C.POINTER(C.c_uint32)), ("flat_ag", C.POINTER(C.c_uint64)), ("flat_bg", C.POINTER(C.c_uint64)), ("flat_dirty", C.c_int), ("pending", C.c_int), ("owns_state", C.c_int), ("bits", C.c_uint32), ("mask", C.c_uint64), ("levels", C.c_uint32), ("halt", C.c_uint32), ]
class LitDo(C.Structure): _fields_ = [ ("kind", C.c_int), ("slot", C.c_uint32), ("src", C.c_uint32), ("gain", C.c_uint64), ("weight", C.c_uint64), ("value", C.c_uint64), ]
LIB.lit_machine_init.argtypes = [ C.POINTER(LitMachine), C.POINTER(C.c_uint64), C.c_uint32, C.c_uint32, C.c_uint32]LIB.lit_machine_init.restype = C.c_intLIB.lit_machine_free.argtypes = [C.POINTER(LitMachine)]LIB.lit_machine_load.argtypes = [C.POINTER(LitMachine), C.POINTER(C.c_uint64)]LIB.lit_machine_graph.argtypes = [ C.POINTER(LitMachine), C.POINTER(C.c_uint32), C.POINTER(C.c_uint64), C.POINTER(C.c_uint64), C.c_int]LIB.lit_machine_graph.restype = C.c_intLIB.lit_machine_step.argtypes = [C.POINTER(LitMachine)]LIB.lit_machine_copy_v.argtypes = [C.POINTER(LitMachine), C.POINTER(C.c_uint64)]LIB.lit_do_apply.argtypes = [C.POINTER(LitMachine), C.POINTER(LitDo)]LIB.lit_do_apply.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_uint32
# ---------------------------------------------------------------- brainclass BrainHost: """The LIT machine as a self-generated world.
Root state V and wiring are fixed. The action set is open: every expansion samples new WIRE DOs the closed world never had, so the tick explores new V/wiring and the tree grows beyond the root set. The convergence (dist == 0) is the halt judge. """
def __init__(self, max_depth=6, seed=0, new_actions=1): self.n = 64 self.max_depth = max_depth self.new_actions = int(new_actions) self.rng = np.random.default_rng(seed) self.m = LitMachine() root_v = [((i * 0x9E3779B97F4A7C15) + 0x123456789ABCDEF0) & MASK for i in range(self.n)] self.root_v = (C.c_uint64 * self.n)(*root_v) if LIB.lit_machine_init(C.byref(self.m), self.root_v, self.n, 1, 64) != 0: raise RuntimeError("lit_machine_init failed") self.root_src = (C.c_uint32 * self.n)( *[(i * 7 + 3) % self.n for i in range(self.n)]) self.root_gain = (C.c_uint64 * self.n)( *[(((i * 2 + 1) << 33) | 1) & MASK for i in range(self.n)]) self.root_weight = (C.c_uint64 * self.n)(*([1] * self.n)) LIB.lit_machine_graph(C.byref(self.m), self.root_src, self.root_gain, self.root_weight, -1)
self.dos = [ LitDo(0, i, (i + 1) % self.n, (0x9E3779B97F4A7C15 ^ (i << 40)) & MASK, 1, 0) for i in range(8) ] self.acts_buf = (LitAction * len(self.dos))() for i in range(len(self.dos)): self.acts_buf[i].kind = i self.acts_buf[i].cost = 1
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
def _grow(self): """Open the action set: new WIRE DOs the closed world never had.""" for _ in range(self.new_actions): self.dos.append(LitDo( 0, int(self.rng.integers(self.n)), int(self.rng.integers(self.n)), (int(self.rng.integers(0, 1 << 63)) << 1) | 1, int(self.rng.integers(1, 4)), 0)) self.acts_buf = (LitAction * len(self.dos))() for i in range(len(self.dos)): self.acts_buf[i].kind = i self.acts_buf[i].cost = 1
def close(self): LIB.lit_machine_free(C.byref(self.m))
# -- root / replay ------------------------------------------------ def _restore_root(self): LIB.lit_machine_load(C.byref(self.m), self.root_v) LIB.lit_machine_graph(C.byref(self.m), self.root_src, self.root_gain, self.root_weight, -1)
def _apply(self, idx): d = self.dos[idx] LIB.lit_do_apply(C.byref(self.m), C.byref(d)) LIB.lit_machine_step(C.byref(self.m))
def _key(self): h = hashlib.blake2b(digest_size=16) h.update(b"litcore") for i in range(self.n): h.update(struct.pack("<Q", self.m.V[i])) h.update(struct.pack("<I", self.m.src[i])) h.update(struct.pack("<Q", self.m.gain[i])) h.update(struct.pack("<Q", self.m.weight[i])) d = h.digest() return (int.from_bytes(d[:8], "little"), int.from_bytes(d[8:], "little"))
def _snapshot(self): v = (C.c_uint64 * self.n)() LIB.lit_machine_copy_v(C.byref(self.m), v) return (v, [self.m.src[i] for i in range(self.n)], [self.m.gain[i] for i in range(self.n)], [self.m.weight[i] for i in range(self.n)])
def _restore(self, snap): v, src, gain, weight = snap LIB.lit_machine_load(C.byref(self.m), v) s = (C.c_uint32 * self.n)(*src) g = (C.c_uint64 * self.n)(*gain) w = (C.c_uint64 * self.n)(*weight) LIB.lit_machine_graph(C.byref(self.m), s, g, w, -1)
# -- callbacks ---------------------------------------------------- def _root(self, ctx, key, goal, dead): _ = ctx self._restore_root() key[0].hi, key[0].lo = self._key() goal[0] = 0 dead[0] = 0 return 0
def _actions(self, ctx, path, path_len, acts_out, n_out): _ = ctx, path if path_len >= self.max_depth: n_out[0] = 0 return 0 self._grow() acts_out[0] = C.cast(self.acts_buf, C.POINTER(LitAction)) n_out[0] = len(self.dos) return 0
def _expand(self, ctx, path, path_len, acts, child_g, nacts, keys, goals, deads): _ = ctx, child_g self._restore_root() for j in range(path_len): self._apply(path[j].kind) snap = self._snapshot() for i in range(nacts): self._restore(snap) self._apply(acts[i].kind) keys[i].hi, keys[i].lo = self._key() goals[i] = 1 if self.m.dist[0] == 0 else 0 deads[i] = 0 self._restore(snap) return 0
def _event(self, ctx, path, path_len, pops, nodes, open_n, g, score, goal): _ = ctx, path, open_n, g, score if goal or pops % 25 == 0: print("brain: pops=%d nodes=%d depth=%d goal=%d" % (pops, nodes, path_len, goal))
# ---------------------------------------------------------------- body# EarthRover Mini Plus telemetry (22 numeric dims; the two camera hashes# take slots 22 and 23 of the 64-slot state).BODY_STATE = [ ("speed", -100.0, 100.0), ("battery_level", 0.0, 100.0), ("orientation", -360.0, 360.0), ("gps_latitude", -90.0, 90.0), ("gps_longitude", -180.0, 180.0), ("gps_signal", 0.0, 100.0), ("signal_level", 0.0, 5.0), ("vibration", 0.0, 10000.0), ("lamp", 0.0, 1.0), ("accelerometer_x", -100.0, 100.0), ("accelerometer_y", -100.0, 100.0), ("accelerometer_z", -100.0, 100.0), ("gyroscope_x", -100.0, 100.0), ("gyroscope_y", -100.0, 100.0), ("gyroscope_z", -100.0, 100.0), ("magnetometer_filtered_x", -1000.0, 1000.0), ("magnetometer_filtered_y", -1000.0, 1000.0), ("magnetometer_filtered_z", -1000.0, 1000.0), ("wheel_rpm_0", -1000.0, 1000.0), ("wheel_rpm_1", -1000.0, 1000.0), ("wheel_rpm_2", -1000.0, 1000.0), ("wheel_rpm_3", -1000.0, 1000.0),]
BODY_GRID = [(lin, ang) for lin in (-1.0, 0.0, 1.0) for ang in (-1.0, 0.0, 1.0)]
class BodyHost: """The EarthRover Mini Plus as a sequential world.
The robot cannot rewind, so this host only supplies the root key and the dummy search callbacks; every real action is ingested into the same flat tree with lit_search_ingest. """
def __init__(self, robot): self.robot = robot stats = {n: {"min": [lo], "max": [hi]} for n, lo, hi in BODY_STATE} self.codec = FeatureCodec.from_robot( "earthrover_mini_plus", robot.observation_features, robot.action_features, stats) 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 key(self, obs): return (self.codec.state_key(self.codec.state_words(obs)), 0)
def action_code(self, lin, ang): return self.codec.action_code([lin, ang])
def _root(self, ctx, key, goal, dead): _ = ctx k = self.key(self.robot.get_observation()) key[0].hi, key[0].lo = k goal[0] = 0 dead[0] = 0 return 0
def _actions(self, ctx, path, path_len, acts_out, n_out): _ = ctx, path, path_len, acts_out 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
# ---------------------------------------------------------------- runsdef run_brain(args): h = BrainHost(max_depth=args.max_depth, seed=args.seed) s = LIB.lit_search_new(C.byref(h.host)) if not s: raise SystemExit("lit_search_new failed") try: for level in range(args.levels): opts = LitSearchOpts(max_steps=0, max_nodes=args.nodes) path = LitPath() rc = LIB.lit_search_continue(s, C.byref(opts), C.byref(path)) print("brain level %d: rc=%d pops=%d nodes=%d path=%d actions=%d" % (level, rc, path.pops, path.nodes, path.n, len(h.dos))) if rc == LIT_SEARCH_FOUND and path.n: acts = [path.acts[i].kind for i in range(path.n)] print("brain win path:", acts) LIB.lit_path_free(C.byref(path)) if rc not in (LIT_SEARCH_FOUND, LIT_SEARCH_EMPTY, LIT_SEARCH_BUDGET): break finally: LIB.lit_search_free(s) h.close() return 0
def haversine(lat1, lon1, lat2, lon2): r = 6371000.0 p1, p2 = math.radians(lat1), math.radians(lat2) dp = math.radians(lat2 - lat1) dl = math.radians(lon2 - lon1) a = (math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2) return 2 * r * math.asin(math.sqrt(a))
def run_body(args): try: from lerobot.robots.earthrover_mini_plus import ( EarthRoverMiniPlus, EarthRoverMiniPlusConfig) except Exception as e: print("LeRobot EarthRover Mini Plus import failed:", e) return 1
robot = EarthRoverMiniPlus(EarthRoverMiniPlusConfig()) try: robot.connect() except Exception as e: print("Frodobots SDK is not running:", e) print("Start it first:") print(" git clone https://github.com/frodobots-org/earth-rovers-sdk.git") print(" cd earth-rovers-sdk && pip install -r requirements.txt") print(" # .env: SDK_API_TOKEN, BOT_SLUG, CHROME_EXECUTABLE_PATH, MISSION_SLUG") print(" hypercorn main:app --reload") print(" open http://localhost:8000 and click Join") return 1
if args.target_lat is not None and args.target_lon is not None: def judge(obs): return 1 if haversine(obs["gps_latitude"], obs["gps_longitude"], args.target_lat, args.target_lon) <= args.radius else 0 else: def judge(obs): _ = obs return 0
host = BodyHost(robot) s = LIB.lit_search_new(C.byref(host.host)) if not s: robot.disconnect() raise SystemExit("lit_search_new failed")
rng = np.random.default_rng(args.seed) parent = 0 try: for step in range(args.steps): if args.policy == "random": lin, ang = BODY_GRID[int(rng.integers(len(BODY_GRID)))] else: lin, ang = BODY_GRID[step % len(BODY_GRID)] code = host.action_code(lin, ang) act = LitAction(0, code & 0xFFFFFFFF, (code >> 32) & 0xFFFFFFFF, 0, 1) robot.send_action({"linear_velocity": lin, "angular_velocity": ang}) time.sleep(1.0 / args.fps) obs = robot.get_observation() k = host.key(obs) goal = judge(obs) parent = LIB.lit_search_ingest( s, parent, C.byref(act), LitKey(k[0], k[1]), step + 1, goal, 0) print("body: step=%d a=(%.1f,%.1f) code=%s key=%s goal=%d" % (step, lin, ang, hex16(code), hex16(k[0]), goal)) if parent == 0xFFFFFFFF: print("ingest failed") break if goal: print("body: judge win at step", step) break finally: LIB.lit_search_free(s) robot.disconnect() return 0
def main(argv): p = argparse.ArgumentParser(description=__doc__) p.add_argument("--mode", choices=["brain", "body"], default="brain") p.add_argument("--nodes", type=int, default=100) p.add_argument("--levels", type=int, default=3) p.add_argument("--max-depth", type=int, default=6) p.add_argument("--steps", type=int, default=100) p.add_argument("--fps", type=float, default=10.0) p.add_argument("--policy", choices=["cycle", "random"], default="cycle") p.add_argument("--seed", type=int, default=0) p.add_argument("--target-lat", type=float, default=None) p.add_argument("--target-lon", type=float, default=None) p.add_argument("--radius", type=float, default=3.0) args = p.parse_args(argv[1:]) if args.mode == "brain": return run_brain(args) return run_body(args)
if __name__ == "__main__": raise SystemExit(main(sys.argv))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472#!/usr/bin/env python3"""lit_stream.py — stream LeRobot datasets over HTTPS; nothing hits disk.
The menu is the Hugging Face `lerobot` org. A dataset is read asParquet row batches through HfFileSystem; the LeRobot `features` dict ishanded to `lit_codec.FeatureCodec`, which translates every feature(state, action, camera/video, text/task, peripherals) into 64 u64 slotsplus one packed action code. A video is an MP4 sample table read withHTTP Range requests; each frame is hashed from its compressed samplebytes. No decoder, no whole-file download, never stored."""import functoolsimport hashlibimport jsonimport sysimport threadingfrom collections import OrderedDictfrom concurrent.futures import ThreadPoolExecutor
import pyarrow.parquet as pqfrom huggingface_hub import HfApi, HfFileSystem
import lit_codec
FS = HfFileSystem()API = HfApi()
def _join(root, path): return "%s/%s" % (root, path) if root else path
def read_json(repo, path, root=""): with FS.open("datasets/%s/%s" % (repo, _join(root, path)), "rb") as f: return json.loads(f.read().decode())
@functools.lru_cache(maxsize=8)def repo_files(repo): """One listing per repo; both data and meta walk the same list.""" return API.list_repo_files(repo, repo_type="dataset")
def data_files(repo, root=""): pref = _join(root, "data/") return sorted(f for f in repo_files(repo) if f.startswith(pref) and f.endswith(".parquet"))
def community_roots(repo): """Every subdataset root: the directory holding meta/info.json.""" suf = "/meta/info.json" return sorted(p[:-len(suf)] for p in repo_files(repo) if p.endswith(suf))
def read_tasks(repo, root=""): """meta/tasks.parquet -> the task strings, in task_index order.""" try: with FS.open("datasets/%s/%s" % (repo, _join(root, "meta/tasks.parquet")), "rb") as f: d = pq.read_table(f).to_pydict() except Exception: return [] if "task" in d: return [str(x) for x in d["task"]] if "tasks" in d: return [str(x) for x in d["tasks"]] if "task_index" in d and "__index_level_0__" in d: out = [""] * len(d["task_index"]) for i, ti in enumerate(d["task_index"]): out[int(ti)] = str(d["__index_level_0__"][i]) return out return []
@functools.lru_cache(maxsize=2)def _read_episodes_cached(repo, root, cams, fps): eps = {} pref = _join(root, "meta/episodes/") for path in repo_files(repo): if not path.startswith(pref) or not path.endswith(".parquet"): continue with FS.open("datasets/%s/%s" % (repo, path), "rb") as f: names = set(pq.ParquetFile(f).schema_arrow.names) wanted = ["episode_index"] for cam in cams: for suf in ("chunk_index", "file_index", "from_timestamp"): c = "videos/%s/%s" % (cam, suf) if c in names: wanted.append(c) d = pq.read_table( f, columns=[c for c in wanted if c in names]).to_pydict() n = len(d.get("episode_index", [])) for i in range(n): ep = d["episode_index"][i] camsd = {} for cam in cams: ck = "videos/%s/chunk_index" % cam fk = "videos/%s/file_index" % cam tk = "videos/%s/from_timestamp" % cam if ck not in d or fk not in d: continue off = 0 if fps and tk in d: off = int(round(float(d[tk][i]) * fps)) camsd[cam] = (d[ck][i], d[fk][i], off) if camsd: eps[ep] = camsd return eps
def read_episodes(repo, cams=(), fps=0, root=""): """episode -> {camera: (chunk, file, sample_offset)} from meta/episodes.
``from_timestamp`` is relative to the video file, so the first frame of the episode is sample ``round(from_timestamp * fps)``. Only the needed columns are read; per-episode stats blobs stay on the Hub. """ return _read_episodes_cached(repo, root, tuple(cams), float(fps))
def _mp4_box(data, start, end, typ): p = start while p + 8 <= end: size = int.from_bytes(data[p:p + 4], "big") t = data[p + 4:p + 8] hdr = 8 if size == 1 and p + 16 <= end: size = int.from_bytes(data[p + 8:p + 16], "big") hdr = 16 if size < hdr or p + size > end: break if t == typ: return p + hdr, p + size p += size return None
def _mp4_samples(data): """Sample table: [(byte_offset, byte_size)] for every video frame.
No decoder; the MP4 stbl (stsz/stco/stsc) is the 4D volume's address map. Each sample is the compressed frame, ready to hash. """ moov = _mp4_box(data, 0, len(data), b"moov") if not moov: return [] trak = _mp4_box(data, moov[0], moov[1], b"trak") if not trak: return [] mdia = _mp4_box(data, trak[0], trak[1], b"mdia") if not mdia: return [] minf = _mp4_box(data, mdia[0], mdia[1], b"minf") if not minf: return [] stbl = _mp4_box(data, minf[0], minf[1], b"stbl") if not stbl: return [] stsz = _mp4_box(data, stbl[0], stbl[1], b"stsz") stco = _mp4_box(data, stbl[0], stbl[1], b"stco") stsc = _mp4_box(data, stbl[0], stbl[1], b"stsc") if not stsz or not stco or not stsc: return [] p = stsz[0] + 4 sample_size = int.from_bytes(data[p:p + 4], "big") p += 4 count = int.from_bytes(data[p:p + 4], "big") p += 4 if sample_size: sizes = [sample_size] * count else: sizes = [] for _ in range(count): sizes.append(int.from_bytes(data[p:p + 4], "big")) p += 4 p = stco[0] + 4 n = int.from_bytes(data[p:p + 4], "big") p += 4 chunks = [int.from_bytes(data[p + 4 * i:p + 4 * i + 4], "big") for i in range(n)] p = stsc[0] + 4 n = int.from_bytes(data[p:p + 4], "big") p += 4 entries = [] for _ in range(n): first = int.from_bytes(data[p:p + 4], "big") spc = int.from_bytes(data[p + 4:p + 8], "big") entries.append((first, spc)) p += 12 out = [] si = 0 for ci, off in enumerate(chunks, 1): spc = 0 for first, n in entries: if ci >= first: spc = n else: break for _ in range(spc): if si >= len(sizes): break out.append((off, sizes[si])) off += sizes[si] si += 1 return out
def video_hash_block(repo, path, per_frame=True): """Offline: the whole video volume -> (top, per-sample hashes).
This reads the entire file; the streaming path below never calls it. """ with FS.open("datasets/%s/%s" % (repo, path), "rb") as f: data = f.read() top = int.from_bytes(hashlib.blake2b(data, digest_size=8).digest(), "little") if not per_frame: return top, [] try: samples = _mp4_samples(data) except Exception: return top, [] hashes = [] for off, size in samples: hashes.append(int.from_bytes( hashlib.blake2b(data[off:off + size], digest_size=8).digest(), "little")) return top, hashes
@functools.lru_cache(maxsize=8)def make_codec(repo, root=""): """LeRobot features + stats + tasks -> the universal FeatureCodec.""" info = read_json(repo, "meta/info.json", root) stats = read_json(repo, "meta/stats.json", root) tasks = read_tasks(repo, root) name = repo if not root else repo + "/" + root return lit_codec.FeatureCodec.from_dataset( name, info["features"], stats, tasks), info
_VCOUNT = 0
class VideoReader: """One MP4 volume, read by Range: moov once, then one block at a time.
The sample table (stsz/stco/stsc) is the address map; ``sample(i)`` seeks to frame i's compressed bytes and hashes them. A block cache (1 MiB) makes a run of consecutive frames one request, so a frame costs a slice of an already-fetched block, not a whole-file read. """
def __init__(self, repo, path, block=1 << 20): self.repo = repo self.path = path self.block = block self.f = FS.open("datasets/%s/%s" % (repo, path), "rb") self._buf = b"" self._buf_off = -1 self._lock = threading.Lock() self.samples = [] self.top = 0 self._open_table() global _VCOUNT _VCOUNT += 1 if _VCOUNT <= 12 or _VCOUNT % 200 == 0: print("video #%d %s samples=%d top=%016x" % (_VCOUNT, path, len(self.samples), self.top), flush=True)
def _size(self): size = getattr(self.f, "size", None) if size: return int(size) try: return int(FS.info("datasets/%s/%s" % (self.repo, self.path))["size"]) except Exception: return 0
def _open_table(self): """Walk top-level boxes to moov, then parse the sample table.""" size = self._size() p = 0 moov = None while size and p + 8 <= size: self.f.seek(p) hdr = self.f.read(16) if len(hdr) < 8: break sz = int.from_bytes(hdr[0:4], "big") typ = hdr[4:8] hdrlen = 8 if sz == 1 and len(hdr) >= 16: sz = int.from_bytes(hdr[8:16], "big") hdrlen = 16 elif sz == 0: sz = size - p if sz < hdrlen: break if typ == b"moov": moov = p break p += sz if moov is None: return self.f.seek(moov) blob = self.f.read(sz) if not blob: return self.top = int.from_bytes( hashlib.blake2b(blob, digest_size=8).digest(), "little") try: self.samples = _mp4_samples(blob) except Exception: self.samples = []
def _read(self, off, size): if self._buf_off >= 0 and \ self._buf_off <= off and off + size <= self._buf_off + len(self._buf): s = off - self._buf_off return self._buf[s:s + size] self.f.seek(off) self._buf = self.f.read(max(self.block, size)) or b"" self._buf_off = off return self._buf[:size]
def sample(self, i): """Frame i's compressed bytes -> one u64 (16 hex digits).""" if not self.samples: return self.top i = int(i) if i < 0 or i >= len(self.samples): return self.top off, size = self.samples[i] if size <= 0: return self.top with self._lock: data = self._read(off, size) return int.from_bytes(hashlib.blake2b(data, digest_size=8).digest(), "little")
def close(self): try: self.f.close() except Exception: pass
def _get_reader(readers, repo, path, key, cap=16): r = readers.get(key) if r is not None: readers.move_to_end(key) return r r = VideoReader(repo, path) readers[key] = r while len(readers) > cap: _, old = readers.popitem(last=False) old.close() return r
def _grab_off(job): cam, r, i = job return cam, (r.sample(i) if r is not None else 0)
def iter_frames(repo, no_video=False, root=""): """Every frame: all data columns + one hash per camera (Range reads).""" codec, info = make_codec(repo, root) cams = [] if no_video else list(codec.cameras) episodes = (read_episodes(repo, cams, info.get("fps") or 0, root) if cams else {}) readers = OrderedDict() pool = (ThreadPoolExecutor(max_workers=max(1, min(8, len(cams)))) if cams else None) try: for path in data_files(repo, root): with FS.open("datasets/%s/%s" % (repo, path), "rb") as f: pf = pq.ParquetFile(f) for batch in pf.iter_batches(batch_size=128): d = batch.to_pydict() n = len(d.get("frame_index", [])) for i in range(n): fr = {k: d[k][i] for k in d} ep = fr.get("episode_index") fi = int(fr.get("frame_index", 0)) if cams: jobs = [] for cam in cams: cf = episodes.get(ep, {}).get(cam) off = cf[2] if cf else 0 r = None if cf: key = (int(cf[0]), int(cf[1]), cam) r = readers.get(key) if r is None: vpath = ("%svideos/%s/chunk-%03d/" "file-%03d.mp4" % (_root_prefix(root), cam, int(cf[0]), int(cf[1]))) r = _get_reader(readers, repo, vpath, key) else: readers.move_to_end(key) jobs.append((cam, r, fi + off)) for cam, h in pool.map(_grab_off, jobs): fr[cam] = h yield fr finally: if pool is not None: pool.shutdown(wait=True) for r in readers.values(): r.close()
def _root_prefix(root): return (root + "/") if root else ""
def iter_transitions(repo, no_video=False, root=""): """Yield (episode, frame, state_frame, action, next_frame, done, codec, task_index). The next frame is the causal edge; the episode end is the one-line judge.""" codec, _info = make_codec(repo, root) prev = None prev_action = None for fr in iter_frames(repo, no_video, root): cur = (fr["episode_index"], fr["frame_index"], fr) if prev is not None: ep, fi, frame = prev if cur[0] == ep and cur[1] == fi + 1: yield (ep, fi, frame, prev_action, cur[2], 0, codec, fr.get("task_index", 0)) else: yield (ep, fi, frame, prev_action, frame, 1, codec, fr.get("task_index", 0)) prev = cur prev_action = fr[codec.action_feature] if prev is not None: yield (prev[0], prev[1], prev[2], prev_action, prev[2], 1, codec, 0)
def main(argv): repo = argv[1] if len(argv) > 1 else "lerobot/svla_so101_pickplace" limit = int(argv[2]) if len(argv) > 2 else 5 codec, info = make_codec(repo) print("repo", repo, "robot", info.get("robot_type"), "eps", info.get("total_episodes"), "fps", info.get("fps")) print("features", list(codec.features.keys())) print("state slots", len(codec.state_slots), "cameras", codec.cameras, "texts", codec.texts, "extras", len(codec.extras), "action dims", len(codec.action_dims)) n = 0 for ep, fi, frame, ac, nframe, done, sch, task in iter_transitions(repo): sh = lit_codec.hex16(sch.state_key(sch.state_words(frame))) ah = lit_codec.hex16(sch.action_code(ac)) print("ep=%d f=%d task=%s state=%s action=%s done=%d" % (ep, fi, task, sh, ah, done)) n += 1 if n >= limit: break print("edges", n) return 0
if __name__ == "__main__": raise SystemExit(main(sys.argv))123456numpyavpyarrowhuggingface_hub# optional: lerobot (only for the EarthRover body adapter)# optional: mujoco (only for demo/render_lerobot_sim.py)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576#!/usr/bin/env python3"""lit_robot.py — the foolproof robot interface.
from lit_robot import LITOperator op = LITOperator("weights/tree.safetensors", codec) actions = op(observation) # open-loop program: [action, ...]
One observation in, the whole action path out. Inference is open-loop:the tree is searched once and the program is returned; the world isnever stepped and never asked for feedback. `None` means the tree knowsno goal path from this observation; no action is fabricated.
The codec is the host's 16-hex glue (LeRobot features -> 64 u64 slots),supplied by the caller. The operator itself never interprets a robot,a camera, or an action."""import osimport sys
HERE = os.path.dirname(os.path.abspath(__file__))REPO = os.path.dirname(HERE)OP = os.path.join(REPO, "lit_operator")if OP not in sys.path: sys.path.insert(0, OP)
from lit_world import LitWorld # noqa: E402
U64_MASK = (1 << 64) - 1
class ProgramWorld: """The only two host facts inference needs: key and decode."""
def __init__(self, codec): self.codec = codec
def key(self, frame): words = self.codec.state_words(frame) return (self.codec.state_key(words), 0)
def decode(self, act): code = (int(act.id) | (int(act.x) << 32)) & U64_MASK return self.codec.action_vec(code)
class LITOperator: """Load a tree once; call it like a library."""
def __init__(self, tree, codec): self.codec = codec self.world = ProgramWorld(codec) self.model = LitWorld(self.world) self.session = self.model.load_tree(tree)
def program(self, observation): """Observation -> the whole open-loop action path, or None.""" return self.model.program(observation)
def program_key(self, key): """Same, when the host already has the 128-bit observation key.""" return self.model.program_key(key)
__call__ = program
def stats(self): return self.session.stats()
def close(self): self.model.free()
def __enter__(self): return self
def __exit__(self, *exc): self.close() return False123version https://git-lfs.github.com/spec/v1oid sha256:67036336fdfbe64580a1efeac1a471a6654eafb2c111c8103408ad25a73c5a9asize 35618072123version https://git-lfs.github.com/spec/v1oid sha256:da26a73c85953fb769689e2785631d9c1b620f689873b0ae74b6bf8b042508b3size 3725583812345678910111213141516171819202122# LITOperator causal tree
Two snapshots of the same append-only tree:
- `LITOperator-community_open_pretrain.safetensors` — the data pass over `lerobot/community_dataset_v3`: 635,998 nodes, 318,269 open.- `LITOperator-community_open_selfboot.safetensors` — three minutes of open-set self-bootstrap on top of the data pass: 666,327 nodes (+30,329), same 318,269 open frontier.
Format: safetensors, one tensor per node field (`parent`, `act_*`,`key_*`, `g`, `depth`, `goal`, `dead`, `open`). License: MIT.
Load a snapshot with the C core:
```clit_search *s = lit_search_load_safetensors(&host, path);```
or inspect it with `demo/tree_io.py` (numpy). The tree is append-only:a node index is stable across snapshots. Duplicate keys are intentionalin an open-set tree (a sampled counterfactual can land on a seen state)..gitattributesAdded+56
LICENSEAdded+21
MakefileAdded+33
README.mdAdded+110
demo/LITOperator_architecture.pngAdded

Large File Pointer Details
- SHA256: e23536a7536b7dae908813dfc56ad54e74e7fadf2a58f89c0f56f896aa0526f8
- Pointer size: 131 Bytes
- Size of remote file: 434 kB
demo/demo.pyAdded+58
demo/lit_lerobot_sim.gifAdded

Large File Pointer Details
- SHA256: f0208c50bf989390ec27281e94b8775dd34ca5b15bedbc1dd576dbc80d686e53
- Pointer size: 132 Bytes
- Size of remote file: 4.81 MB
demo/selfbootstrap.pyAdded+80
demo/tree_io.pyAdded+64
lit_operator/dense.cAdded+94
lit_operator/dense.hAdded+58
lit_operator/lit_core.cAdded+675
lit_operator/lit_core.hAdded+120
lit_operator/lit_main.cAdded+441
lit_operator/lit_operator.cAdded+2996
lit_operator/lit_operator.hAdded+292
lit_operator/lit_world.pyAdded+572
replay.mp4Added+3
sandbox/lerobot_host/lit_codec.pyAdded+388
sandbox/lerobot_host/lit_drive.pyAdded+247
sandbox/lerobot_host/lit_libero.pyAdded+205
sandbox/lerobot_host/lit_pretrain.pyAdded+490
sandbox/lerobot_host/lit_robot_api.pyAdded+35
sandbox/lerobot_host/lit_selfloop.pyAdded+456
sandbox/lerobot_host/lit_stream.pyAdded+472
sandbox/lerobot_host/requirements.txtAdded+6
sandbox/lit_robot.pyAdded+76
weights/LITOperator-community_open_pretrain.safetensorsAdded+3
weights/LITOperator-community_open_selfboot.safetensorsAdded+3
weights/README.mdAdded+22