File size: 13,517 Bytes
a0d66db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# Copyright (c) 2026, Nepher Robotics
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause

"""pi0.5 DROID joint-position brain reference implementation.

``weights/`` is the released ``pi05_droid_jointpos`` checkpoint. The OpenPI
runtime lives in the brain image. The policy reads the left exterior and wrist
cameras, the seven arm joints, and the gripper, then returns an 8-D
absolute joint command.
"""

from __future__ import annotations

import json
import os
import subprocess
import sys
from pathlib import Path

import numpy as np
from adapt import (
    BATCH_SIZES,
    blend_overlap,
    committed_actions,
    joint_chunk,
    normalized_prefix,
    padded_rows,
    resize_with_pad,
    row_slices,
    select_consistent,
    stack_padded,
)
from brain_comm.brain import Brain
from contract import (
    ACTION_DIM,
    ALIGNMENTS,
    EXECUTED_STEPS,
    HORIZON,
    PADDED_DIM,
    POLICY_CONFIG,
    PREFETCH_STEPS,
    SAMPLERS,
    alignment_offset,
    joint_transforms,
    model_config,
    policy_example,
)

# Flow-matching noise is drawn at the checkpoint width, before the 8-D output slice.
_NOISE_SHAPE = (HORIZON, PADDED_DIM)

# OpenPI's ``Policy`` only exposes a one-example ``infer``. Batching reuses its pieces.
_POLICY_PARTS = ("_input_transform", "_output_transform", "_sample_actions", "_sample_kwargs", "_rng")


class Pi05DroidJointposBrain(Brain):
    """Load a pi0.5 DROID joint-position checkpoint and return absolute joint actions."""

    # Stock and prefetch only need the session's instructions. Setup disables
    # multiplexing for overlap, which also needs the preceding prediction.
    session_safe = True

    def setup(self, device: str, weights_dir: Path, config: dict) -> None:
        # JAX follows CUDA_VISIBLE_DEVICES, which the server sets for this replica.
        del device
        self.horizon = int(config["horizon"])
        self.action_dim = int(config["action_dim"])
        if (self.horizon, self.action_dim) != (HORIZON, ACTION_DIM):
            raise ValueError("the Franka checkpoint requires a 15-step, 8-dimensional action contract")
        self.alignment = config.get("alignment", "stock")
        if self.alignment not in ALIGNMENTS:
            raise ValueError(f"unknown action alignment {self.alignment!r}")
        self.prefetch_offset = int(config.get("prefetch_offset", PREFETCH_STEPS))
        if not 0 <= self.prefetch_offset <= PREFETCH_STEPS:
            raise ValueError(f"prefetch offset must be between zero and {PREFETCH_STEPS}")
        # A concurrent replica can restore instructions but cannot restore an old trajectory.
        self.session_safe = self.alignment != "overlap"
        self._previous: tuple[int, np.ndarray] | None = None
        self._latest: tuple[int, np.ndarray] | None = None
        _limit_gpu_memory(config.get("max_gpu_mem_gb"))
        flow_steps = int(config.get("flow_steps", 10))
        if flow_steps <= 0:
            raise ValueError("flow_steps must be positive")
        sampler = config.get("sampler", "stock")
        if sampler not in SAMPLERS:
            raise ValueError(f"unknown flow sampler {sampler!r}")
        self.sampler = sampler
        self._wire = self._before_wire = None
        if sampler in ("prefix-select", "prefix-trained"):
            if self.alignment not in ("prefetch", "overlap") or self.prefetch_offset != PREFETCH_STEPS:
                raise ValueError("prefix selection needs the full four-step prefetch offset")
            self.session_safe = False
            stats = json.loads((weights_dir / "assets/droid/norm_stats.json").read_text())["norm_stats"]["actions"]
            self._lower = np.array(stats["q01"][:8], dtype=np.float32)
            self._upper = np.array(stats["q99"][:8], dtype=np.float32)
            self._joint_scale = np.maximum((self._upper[:7] - self._lower[:7]) / 2, 1e-4)
        if sampler == "refined" and flow_steps != 10:
            raise ValueError("refined sampling requires ten Euler steps")
        self._policy = _load_policy(weights_dir, config.get("architecture", "base"), flow_steps)
        if sampler in ("refined", "prefix-trained"):
            from types import MethodType

            from openpi.shared.nnx_utils import module_jit
            if sampler == "refined":
                from refine import sample_refined as sample
            else:
                from prefix import sample_prefix as sample
            self._policy._sample_actions = module_jit(MethodType(sample, self._policy._model))
        if not _can_batch(self._policy):
            print("pi0.5: this OpenPI build cannot batch; answering one row per call", file=sys.stderr)
        # Compile every batch size now, so no control step waits for XLA.
        _warm_up(self._policy, prefix=sampler == "prefix-trained")
        self._instructions: list[str] = []

    def begin_episode(self, episode_ids: list[str], seeds: list[int], instructions: list[str]) -> None:
        del episode_ids, seeds
        self._instructions = list(instructions)
        self._previous = None
        self._latest = None
        self._wire = self._before_wire = None

    def end_episode(self, episode_ids: list[str]) -> None:
        del episode_ids
        self._instructions = []
        self._previous = None
        self._latest = None
        self._wire = self._before_wire = None

    def act(self, obs: dict[str, np.ndarray], step: int) -> np.ndarray:
        joints = np.asarray(obs["joint_pos"], dtype=np.float32)
        grip = np.asarray(obs["gripper_pos"], dtype=np.float32)
        exterior = np.asarray(obs["cam_exterior_left"])
        wrist = np.asarray(obs["cam_wrist"])
        count = joints.shape[0]
        if len(self._instructions) != count:
            raise ValueError(f"{len(self._instructions)} instructions for {count} envs")
        # Noise is drawn per row in row order, from the generator the server reseeded.
        noises = [np.random.standard_normal(_NOISE_SHAPE).astype(np.float32) for _ in range(count)]
        examples = [
            _example(exterior[index], wrist[index], joints[index], grip[index], self._instructions[index])
            for index in range(count)
        ]
        offset = alignment_offset(self.alignment, step, self.prefetch_offset)
        queued = None
        if self.sampler in ("prefix-select", "prefix-trained"):
            start = step + offset
            if self._wire is None or self._wire[0] != start:
                self._before_wire = self._wire
            queued = committed_actions(self._before_wire, step, count, offset)
        if self.sampler == "prefix-trained":
            prefix = normalized_prefix(queued, joints, self._lower, self._upper, PREFETCH_STEPS, PADDED_DIM)
            predictions = _infer(self._policy, examples, noises, prefix=prefix)
        else:
            predictions = _infer(self._policy, examples, noises)
        if self.sampler == "prefix-select" and queued is not None:
            plans = [predictions]
            for _ in range(2):
                other_noise = [np.random.standard_normal(_NOISE_SHAPE).astype(np.float32) for _ in range(count)]
                plans.append(_infer(self._policy, examples, other_noise))
            predictions = select_consistent(np.asarray(plans), queued, self._joint_scale)
        chunks = [joint_chunk(actions, self.horizon, offset=offset) for actions in predictions]
        stacked = np.stack(chunks, axis=0).astype(np.float32)
        if self.alignment == "overlap":
            raw = np.stack([action[:self.horizon, :self.action_dim] for action in predictions])
            if not np.isfinite(raw).all():
                raise ValueError("the policy produced non-finite joint commands")
            # A repeated request at the same step still sees the same preceding chunk.
            if self._latest is None or self._latest[0] != step:
                self._previous = self._latest
            if self._previous is not None:
                previous_step, previous = self._previous
                if step - previous_step in (PREFETCH_STEPS, EXECUTED_STEPS):
                    blend_overlap(stacked, previous, step + offset - previous_step, EXECUTED_STEPS)
            self._latest = (step, raw)
        if self.sampler in ("prefix-select", "prefix-trained"):
            self._wire = (step + offset, stacked[:, :EXECUTED_STEPS].copy())
        if stacked.shape[-1] != self.action_dim:
            raise ValueError(f"action width {stacked.shape[-1]} != {self.action_dim}")
        return stacked


def _load_policy(weights_dir: Path, architecture: str, flow_steps: int):
    if not (weights_dir / "params" / "_METADATA").is_file():
        raise FileNotFoundError(f"pi0.5 checkpoint is missing params/_METADATA in {weights_dir}")
    from openpi.policies import policy_config
    from openpi.training.config import AssetsConfig, DataConfig, SimpleDataConfig, TrainConfig

    # Same decode as the simeval ``pi05_droid_jointpos`` config: joint deltas
    # become absolute positions, and the gripper stays absolute.
    train_config = TrainConfig(
        name=POLICY_CONFIG,
        exp_name="inference",
        model=model_config(architecture),
        data=SimpleDataConfig(
            assets=AssetsConfig(asset_id="droid"),
            data_transforms=joint_transforms,
            base_config=DataConfig(prompt_from_task=True),
        ),
        wandb_enabled=False,
    )
    return policy_config.create_trained_policy(train_config, weights_dir, sample_kwargs={"num_steps": flow_steps})


def _limit_gpu_memory(max_gpu_mem_gb: float | None) -> None:
    """Reserve at most ``max_gpu_mem_gb`` [GiB] of this GPU for JAX.

    JAX takes ``XLA_PYTHON_CLIENT_MEM_FRACTION`` of the whole GPU, and the brain
    image presets 0.5. A fixed budget wastes less on a large GPU. Without a known
    GPU size the environment is left as it is. Call this before JAX starts.
    """
    if max_gpu_mem_gb is None:
        return
    total_gib = _gpu_total_gib()
    if total_gib is None:
        return
    fraction = min(0.9, float(max_gpu_mem_gb) / total_gib)
    os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = f"{fraction:.4f}"


def _gpu_total_gib() -> float | None:
    """Return the memory [GiB] of the first visible GPU, without starting CUDA."""
    visible = os.environ.get("CUDA_VISIBLE_DEVICES", "0").split(",")[0].strip() or "0"
    command = ["nvidia-smi", f"--id={visible}", "--query-gpu=memory.total", "--format=csv,noheader,nounits"]
    try:
        output = subprocess.run(command, capture_output=True, text=True, timeout=30, check=True).stdout
        return float(output.strip().splitlines()[0]) / 1024.0
    except (OSError, subprocess.SubprocessError, ValueError, IndexError):
        return None


def _can_batch(policy) -> bool:
    return not getattr(policy, "_is_pytorch_model", False) and all(hasattr(policy, name) for name in _POLICY_PARTS)


def _infer(policy, examples: list[dict], noises: list[np.ndarray], *, prefix=None) -> list[np.ndarray]:
    """Return the policy's actions for each example, in order."""
    if not _can_batch(policy):
        if prefix is not None:
            raise RuntimeError("conditioned sampling requires the pinned JAX batch interface")
        return [
            policy.infer(example, noise=noise)["actions"] for example, noise in zip(examples, noises, strict=True)
        ]
    actions: list[np.ndarray] = []
    for rows in row_slices(len(examples)):
        batch_prefix = None if prefix is None else prefix[rows]
        actions.extend(_infer_batch(policy, examples[rows], noises[rows], prefix=batch_prefix))
    return actions


def _infer_batch(policy, examples: list[dict], noises: list[np.ndarray], *, prefix=None) -> list[np.ndarray]:
    """Run one padded forward pass; same steps as ``Policy.infer`` on a batch."""
    import jax
    import jax.numpy as jnp
    from openpi.models import model as openpi_model

    # Transforms may modify their input, so give each one its own shallow copy.
    inputs = [policy._input_transform(dict(example)) for example in examples]
    size = padded_rows(len(inputs))
    batch = stack_padded(inputs, size)
    noise = stack_padded(noises, size)
    policy._rng, key = jax.random.split(policy._rng)
    observation = openpi_model.Observation.from_dict(jax.tree.map(jnp.asarray, batch))
    kwargs = dict(policy._sample_kwargs)
    if prefix is not None:
        kwargs["prefix"] = jnp.asarray(stack_padded(list(prefix), size))
    sampled = np.asarray(
        policy._sample_actions(key, observation, noise=jnp.asarray(noise), **kwargs)
    )
    state = np.asarray(batch["state"])
    return [
        policy._output_transform({"state": state[row], "actions": sampled[row]})["actions"]
        for row in range(len(examples))
    ]


def _warm_up(policy, *, prefix=False) -> None:
    blank = np.zeros((224, 224, 3), dtype=np.uint8)
    example = _example(blank, blank, np.zeros(7, dtype=np.float32), np.zeros(1, dtype=np.float32), "warm up")
    noise = np.random.RandomState(0).standard_normal(_NOISE_SHAPE).astype(np.float32)
    for size in BATCH_SIZES if _can_batch(policy) else BATCH_SIZES[:1]:
        queued = np.zeros((size, PREFETCH_STEPS, PADDED_DIM), np.float32) if prefix else None
        _infer(policy, [example] * size, [noise] * size, prefix=queued)


def _example(exterior: np.ndarray, wrist: np.ndarray, joints: np.ndarray, grip: np.ndarray, prompt: str) -> dict:
    return policy_example(resize_with_pad(exterior), resize_with_pad(wrist), joints, grip, prompt)