File size: 6,854 Bytes
ba3901b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
"""Minimal inference example for Inkling-MuJoCo, the Inkling 2 Mini LIBERO adapter (libero4_v1, final checkpoint).

What this file does:
  - builds the model input exactly as the project's evaluator does (two camera images, centre crop,
    JPEG data URIs, system prompt, "Task: <instruction>", thinking effort 0, tml_v0 renderer);
  - samples 16 replies at temperature 1.0 and turns them into the executed actions with the
    reported decoder (lower median per number, gripper by majority, execute 4 of 8).

What it needs: Python 3.11, numpy, pillow, tinker==0.40.0, tinker-cookbook==0.7.1, tml-renderers==0.4.2,
and a Tinker sampler checkpoint of this adapter that your Tinker API key can read (TINKER_API_KEY in the
environment). The adapter files in this repository are Tinker's LoRA export; loading them into the
Hub checkpoint of the base model with PEFT/transformers has NOT been tested (see the model card).

The pure functions below (prepare_image, encode/decode, aggregate_chunks) were checked against the
project's own code on the same inputs; the Tinker call itself was not run when this card was written.
"""

from __future__ import annotations

import base64
import io
import json
import math
import re
from pathlib import Path

import numpy as np
from PIL import Image

HERE = Path(__file__).parent
STATS = json.loads((HERE / "libero_action_stats.json").read_text())
LOW, HIGH = np.asarray(STATS["min"], np.float64), np.asarray(STATS["max"], np.float64)
CHUNK, DIM, TOP_BIN = 8, 7, 999
RESOLUTION = 256
CROP = round(RESOLUTION * math.sqrt(0.9))  # 243
SYSTEM_PROMPT = (
    "You control a Franka Panda robot arm with a parallel gripper. The first image is a third-person "
    "view and the second is from the wrist camera. Predict the next 8 actions; each is 7 numbers: "
    "dx dy dz droll dpitch dyaw gripper. Reply with 56 integers from 0 to 999 on one line, separated by "
    "single spaces, the 8 actions in order. Reply with the numbers only."
)
_SPACED = re.compile(r"(?:0|[1-9]\d{0,2})(?: (?:0|[1-9]\d{0,2}))*")


def prepare_image(image: np.ndarray) -> str:
    """256x256x3 uint8 camera image (already rotated 180 degrees, as in the training data) -> JPEG data URI.

    Centre crop of 243x243, bilinear resize back to 256x256, JPEG quality 90.
    """
    assert image.shape == (RESOLUTION, RESOLUTION, 3) and image.dtype == np.uint8
    top = left = (RESOLUTION - CROP) // 2
    pil = Image.fromarray(image).crop((left, top, left + CROP, top + CROP))
    pil = pil.resize((RESOLUTION, RESOLUTION), Image.Resampling.BILINEAR)
    buffer = io.BytesIO()
    Image.fromarray(np.asarray(pil)).save(buffer, format="JPEG", quality=90)
    return "data:image/jpeg;base64," + base64.b64encode(buffer.getvalue()).decode("ascii")


def to_bins(actions: np.ndarray) -> np.ndarray:
    scaled = (np.asarray(actions, np.float64) - LOW) / (HIGH - LOW)
    return np.clip(np.rint(scaled * TOP_BIN), 0, TOP_BIN).astype(int)


def from_bins(bins: np.ndarray) -> np.ndarray:
    return LOW + np.asarray(bins, np.float64) / TOP_BIN * (HIGH - LOW)


def decode(text: str) -> np.ndarray:
    """One reply -> [k, 7] float32 actions (k <= 8; 0 if the reply is not in the spaced format)."""
    text = text.strip()
    if not _SPACED.fullmatch(text):
        return np.zeros((0, DIM), np.float32)
    bins = [int(t) for t in text.split(" ")]
    k = min(len(bins) // DIM, CHUNK)
    actions = from_bins(np.asarray(bins[: k * DIM]).reshape(k, DIM))
    actions[:, -1] = np.where(actions[:, -1] >= 0, 1.0, -1.0)  # +1 closes, -1 opens
    return actions.astype(np.float32)


def aggregate_chunks(chunks: list[np.ndarray], previous_gripper: float) -> np.ndarray | None:
    """The reported decoder: lower median of the integer bins per number, gripper by majority."""
    usable = [c for c in chunks if len(c) == CHUNK]
    if not usable:
        return None
    bins = np.sort(np.stack([to_bins(c) for c in usable]), axis=0)
    actions = from_bins(bins[(len(usable) - 1) // 2]).astype(np.float32)
    votes = np.sign(np.stack([c[:, -1] for c in usable])).sum(axis=0)
    gripper = previous_gripper
    for i, vote in enumerate(votes):
        gripper = 1.0 if vote > 0 else -1.0 if vote < 0 else gripper
        actions[i, -1] = gripper
    return actions


def messages(instruction: str, third_person: np.ndarray, wrist: np.ndarray) -> list[dict]:
    content = [{"type": "image", "image": prepare_image(third_person)},
               {"type": "image", "image": prepare_image(wrist)},
               {"type": "text", "text": f"Task: {instruction}"}]
    return [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": content}]


class TinkerPolicy:
    """One decision: 16 samples at temperature 1.0 from a Tinker sampler checkpoint, aggregated."""

    def __init__(self, sampler_path: str, base_model: str = "thinkingmachines/Inkling-2-Mini:peft:65536:free"):
        import tinker
        from tinker_cookbook.renderers import get_renderer, get_text_content
        from tinker_cookbook.tokenizer_utils import get_tokenizer

        self.renderer = get_renderer("tml_v0", get_tokenizer(base_model))
        self.get_text = get_text_content
        self.sampler = tinker.ServiceClient().create_sampling_client(model_path=sampler_path).result()
        self.params = tinker.SamplingParams(max_tokens=160, temperature=1.0, stop=self.renderer.get_stop_sequences())

    def act(self, instruction: str, third_person: np.ndarray, wrist: np.ndarray, previous_gripper: float) -> np.ndarray:
        prompt = self.renderer.build_generation_prompt(messages(instruction, third_person, wrist), effort=0.0)
        sequences = self.sampler.sample(prompt=prompt, num_samples=16, sampling_params=self.params).result().sequences
        texts = []
        for sequence in sequences:
            try:
                texts.append(self.get_text(self.renderer.parse_response(sequence.tokens)[0]))
            except ValueError:
                texts.append("")
        actions = aggregate_chunks([decode(t) for t in texts], previous_gripper)
        if actions is None:  # no usable sample: hold still for one call interval
            actions = np.zeros((4, DIM), np.float32)
            actions[:, -1] = previous_gripper
        return actions[:4]  # execute 4 of the 8 predicted actions, then observe and ask again


# Usage, inside a LIBERO episode (full evaluator: https://github.com/kratik1/inkling-libero):
#   policy = TinkerPolicy(sampler_path)                 # Tinker sampler checkpoint path of this adapter
#   gripper = -1.0                                      # open at episode start
#   images = <both cameras rendered at 256x256 and rotated 180 degrees: frame[::-1, ::-1]>
#   for action in policy.act(env_instruction, images["agentview"], images["wrist"], gripper):
#       done = env.step(action); gripper = float(action[-1])