File size: 2,176 Bytes
1ddfac5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/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 is
never stepped and never asked for feedback.  `None` means the tree knows
no 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 os
import 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 False