Publish deployment package and measured Franka evaluation
Browse filesFiles changed (11)
- README.mdAdded+43
- deployment/LICENSEAdded+29
- deployment/NOTICEAdded+3
- deployment/agent.yamlAdded+32
- deployment/brain/adapt.pyAdded+168
- deployment/brain/contract.pyAdded+62
- deployment/brain/policy.pyAdded+289
- deployment/brain/prefix.pyAdded+65
- deployment/brain/refine.pyAdded+89
- deployment/train/README.mdAdded+4
- deployment/train/miner_training.jsonAdded+44
12345678910111213141516171819202122232425262728293031323334353637383940414243---tags:- robotics- manipulation---
# Franka π0.5 trained on a second-object correction
This experimental policy controls a simulated Franka arm using wrist and exterior RGB images, measured joint and gripper positions, and an instruction. It produces seven joint targets and a gripper command at 15 Hz. It accounts for four committed actions and executes eight actions per inference.
The starting model was the retained Unidroid Franka policy. We made 40 action-expert LoRA updates at batch size four and peak learning rate 0.000003. One 307-frame, physically verified expert continuation from a state reached by the original miner received 25% of sampling mass alongside the training demonstrations. The original weights of all 51 frozen parameter arrays were verified after training. [Parent model](https://huggingface.co/magicvec/unidroid-franka-prefix-160-v1)
## Local evaluation
A complete paired 60-task replay has been scheduled. On six fresh procedural sauce-and-raisin seeds this checkpoint completed three jobs with mean score 0.68256. Its parent completed zero with mean score 0.35000. These results came from local evaluator replays. Official ranking is determined on the Unidroid service.
## Deployment
The weights-only revision is `868e2719d6f0d66e362443624c85b7fd0c6dd870`. Use that revision for the model reference in a Unidroid submission. Download the matching code and weights into a new submission folder as follows.
```pythonfrom pathlib import Pathfrom shutil import copyfilefrom huggingface_hub import HfApi, hf_hub_downloadimport yaml
repo = "magicvec/unidroid-franka-second-object-40"weights_revision = "868e2719d6f0d66e362443624c85b7fd0c6dd870"code_revision = HfApi().model_info(repo).shatarget = Path("franka-second-object-40")target.mkdir()for name in HfApi().list_repo_files(repo, revision=code_revision): if name.startswith("deployment/"): dest = target / name.removeprefix("deployment/") dest.parent.mkdir(parents=True, exist_ok=True) copyfile(hf_hub_download(repo, name, revision=code_revision), dest)for name in yaml.safe_load((target / "agent.yaml").read_text())["weights"]: dest = target / "weights" / name dest.parent.mkdir(parents=True, exist_ok=True) copyfile(hf_hub_download(repo, name, revision=weights_revision), dest)```
Check the package with `udcli submission check --path franka-second-object-40 --challenge pi05-franka-tabletop-v1`. The brain entry is `policy:Pi05DroidJointposBrain` with ten flow steps and four-action overlap.1234567891011121314151617181920212223242526272829BSD 3-Clause License
Copyright (c) 2026, UnidroidAll rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.123Reference brain adapted from Unidroid-AI/template-pi05 at 10fc83c.Copyright (c) 2026, Nepher Robotics. All rights reserved.The reference brain source files identify the BSD-3-Clause license.1234567891011121314151617181920212223242526272829303132entry: policy:Pi05DroidJointposBrainhorizon: 15action_dim: 8policy_config: pi05_droid_jointposarchitecture: action-loraalignment: overlapprefetch_offset: 4flow_steps: 10sampler: prefix-trainedmax_gpu_mem_gb: 16observation: cameras: cam_exterior_left,cam_wrist image_hw: 126x224parent_submission: nullweights: assets/droid/norm_stats.json: 57ce9956f9e07d65f8a8205aabec72d436a2c8927f53edb40c7a77b14a5a90c7 params/_CHECKPOINT_METADATA: 05c7cd86d850ec46a1e224a239c1f42199f5179fb51c25206f326ba951de4124 params/_METADATA: 5763d5526a8ced3cc8a78bbf62d0926fff2179371ed8b0cf1163c7cfe420fee9 params/_sharding: 0495313232fdebb1e217f8176230ab98e9732a625d881572baebbdba075b8c63 params/array_metadatas/process_0: 6e769f5e6c2c1f99888780b3c046f9cc41feabdcaab678d8afa9d4b8ba226eb6 params/d/0bb2246db61432cf02450cf0ce8a106b: 562de2902fac112adb4b2135b342bf126a450e2df83d32cc7eab123ddf772658 params/manifest.ocdbt: 753cfab273ebb9ddde7e67ded7ee6595693aa1088a091032d10affdc5e8a0ada params/ocdbt.process_0/d/1819b97229b84e3c73681af3648adde8: 42ad1846d4f85ed9559214890b67b87d1c9202c12fd022c319d12fdf4750d3d5 params/ocdbt.process_0/d/222a57aeee4c1da64216637a21dd729d: 5f39ce1e4fdfa14c01c2407e1958e353b2176c20622448e3d0b333b621a1e328 params/ocdbt.process_0/d/3746efb3706931a42e65cdf5985a15b6: 3f12ac907cfc6ede30b1c5c5230d1651a36506aac1a586583a6f2110fe172762 params/ocdbt.process_0/d/625c23f9a86ce787e0ed838503bef0a0: d785886bf151df9c77d7c1aae4fe99cab528cc6ab0b42851cb7b655b6efb8fbe params/ocdbt.process_0/d/88d72b03e89bf20621f5e53a0f998a57: ccc8f96da7024ef75fa38c5ff592e6ee557a04ac07dd2e2b544a52e3dfee2de9 params/ocdbt.process_0/d/88ff9ec92e08613585b47d5ff63d58e4: fb9da0a34499b6a1b662c67705bc5d702da9966f13f3bc34a83ed0b6ec71272f params/ocdbt.process_0/d/bfa75a9c9a4f3ddad4e55d860d0c778a: b88d13a68ceb1ba91b77481e74734795ca998b99ee913cd180c0f7ef153ffe9d params/ocdbt.process_0/d/ca93499a64757136e34159e430cbf919: f0a5a25812d6d4b461043ac1fd9a3dff8789708fb288e5032e783c078b78a8ae params/ocdbt.process_0/d/e0c363b42a5d589202c2ed41545c0599: cfd65ffdc88a50452a3edebba20372d30403ae898d0b374d268f9048529e0908 params/ocdbt.process_0/manifest.ocdbt: a6115fc685712c16a0605cf67326cc0f5744dbc1391d43b2510415f6743d8857123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168# Copyright (c) 2026, Nepher Robotics# All rights reserved.## SPDX-License-Identifier: BSD-3-Clause
"""Map observations to a pi0.5 DROID policy and back to absolute joints."""
from __future__ import annotations
import numpy as np
IMAGE_HW = (224, 224)
BATCH_SIZES = (1, 4, 16)"""Row counts the model is compiled for. A call is padded up to the next one."""
def padded_rows(rows: int) -> int: """Return the compiled batch size that holds ``rows`` rows.
The size depends only on ``rows``, so a row is always computed in the same program no matter how many calls the server has merged or in what order.
Args: rows: Number of real rows, at most ``BATCH_SIZES[-1]``. """ for size in BATCH_SIZES: if rows <= size: return size raise ValueError(f"{rows} rows exceed the largest batch size {BATCH_SIZES[-1]}")
def row_slices(rows: int) -> list[slice]: """Split ``rows`` into slices of at most ``BATCH_SIZES[-1]`` rows.""" limit = BATCH_SIZES[-1] return [slice(start, min(start + limit, rows)) for start in range(0, rows, limit)]
def stack_padded(items: list, size: int): """Stack nested dicts of arrays on a new axis 0 and pad to ``size`` rows.
Pad rows repeat the first row, so they never feed zeros or NaNs to the model.
Args: items: One nested dict of arrays per row, all with the same structure. size: Row count after padding, at least ``len(items)``. """ if len(items) > size: raise ValueError(f"{len(items)} rows do not fit in a batch of {size}") padded = list(items) + [items[0]] * (size - len(items)) return _stack(padded)
def _stack(items: list): first = items[0] if isinstance(first, dict): return {key: _stack([item[key] for item in items]) for key in first} return np.stack([np.asarray(item) for item in items], axis=0)
def resize_with_pad(image: np.ndarray, height: int = IMAGE_HW[0], width: int = IMAGE_HW[1]) -> np.ndarray: """Resize one HWC image to ``height`` x ``width`` without stretching.
Scale uniformly and pad the short side with zeros, matching ``openpi_client.image_tools.resize_with_pad``. An image that is already the target size is returned unchanged.
Args: image: uint8 image, shape [H, W, C]. height: Target height [pixels]. width: Target width [pixels]. """ array = np.asarray(image) if array.shape[-3:-1] == (height, width): return array from PIL import Image
if array.dtype != np.uint8: array = np.clip(array, 0, 255).astype(np.uint8) current_height, current_width = array.shape[0], array.shape[1] ratio = max(current_width / width, current_height / height) resized_height = int(current_height / ratio) resized_width = int(current_width / ratio) resized = Image.fromarray(array).resize((resized_width, resized_height), resample=Image.BILINEAR) canvas = Image.new(resized.mode, (width, height), 0) pad_height = max(0, int((height - resized_height) / 2)) pad_width = max(0, int((width - resized_width) / 2)) canvas.paste(resized, (pad_width, pad_height)) return np.asarray(canvas)
def joint_chunk(actions: np.ndarray, horizon: int, *, offset: int = 0) -> np.ndarray: """Keep absolute joint targets [rad] and snap the gripper.
The pi0.5 DROID joint-position config adds the observed joints back onto the first seven columns, so those values are already absolute. The eighth column is the gripper. A value above 0.5 closes it.
Args: actions: Policy actions, shape [H, 8] or wider. horizon: Number of steps to keep.
Returns: Actions, shape [horizon, 8]. The last column is 0 open or 1 closed. """ raw = np.asarray(actions, dtype=np.float32) if raw.ndim != 2 or raw.shape[0] < horizon or raw.shape[1] < 8: raise ValueError(f"expected at least {(horizon, 8)} actions, got {raw.shape}") if not 0 <= offset < horizon: raise ValueError(f"offset must be between 0 and {horizon - 1}") # Keep the advertised wire horizon after shifting the executable prefix. # The pinned evaluator consumes only the first eight rows. indices = np.minimum(np.arange(horizon) + offset, horizon - 1) chunk = raw[indices, :8] if not np.isfinite(chunk).all(): raise ValueError("the policy produced non-finite joint commands") chunk[..., -1] = (chunk[..., -1] > 0.5).astype(chunk.dtype) return chunk
def blend_overlap( chunk: np.ndarray, previous: np.ndarray, previous_start: int, executed_steps: int,) -> None: """Blend arm targets for the same future steps when both chunks agree on gripper state.""" overlap = min(executed_steps, previous.shape[1] - previous_start) if previous_start <= 0 or overlap <= 0: return old = previous[:, previous_start:previous_start + overlap, :8] new = chunk[:, :overlap, :] agree = (old[..., 7] > 0.5) == (new[..., 7] > 0.5) # Taper the old prediction's influence and preserve the new gripper command. taper = 0.5 * (1.0 - np.arange(overlap, dtype=np.float32) / overlap) weight = (agree * taper)[..., None] new[..., :7] += weight * (old[..., :7] - new[..., :7])
def committed_actions(previous, step: int, count: int, length: int) -> np.ndarray | None: """Return queued absolute commands starting at this observation timestamp.""" if previous is None or length == 0: return None start, sent = previous index = step - start if index < 0 or index + length > sent.shape[1] or sent.shape[0] != count: return None return sent[:, index:index + length].copy()
def select_consistent(plans: np.ndarray, committed: np.ndarray, joint_scale: np.ndarray) -> np.ndarray: """Select one complete sampled trajectory per row by likelihood of its queued prefix.""" prefix = plans[:, :, :committed.shape[1], :8] arm_error = (prefix[..., :7] - committed[None, ..., :7]) / joint_scale # At contact, the temporal order of opening and closing is as important as one arm joint. grip_error = (np.clip(prefix[..., 7], 0, 1) - committed[None, ..., 7]) ** 2 distance = np.mean(np.square(arm_error), axis=-1) + grip_error best = np.argmin(distance.mean(axis=-1), axis=0) return plans[best, np.arange(plans.shape[1])]
def normalized_prefix(commands, joints, lower, upper, delay, padded_dim): """Express queued absolute joint targets in this observation's DROID delta coordinates.""" count = len(joints) result = np.zeros((count, delay, padded_dim), dtype=np.float32) if commands is not None: delta = commands.copy() delta[..., :7] -= joints[:, None, :7] result[..., :8] = (delta - lower) / (upper - lower + 1e-6) * 2 - 1 result[..., 8] = 1 return result1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""Model and timing contract shared by the trainer and submission."""
import numpy as np
HORIZON = 15ACTION_DIM = 8PADDED_DIM = 32CONTROL_HZ = 15EXECUTED_STEPS = 8PREFETCH_STEPS = 4IMAGE_HW = (126, 224)POLICY_CONFIG = "pi05_droid_jointpos"CAMERAS = ("cam_exterior_left", "cam_wrist")MODEL_VARIANTS = { "base": ("gemma_2b", "gemma_300m"), "action-lora": ("gemma_2b", "gemma_300m_lora"), "lora": ("gemma_2b_lora", "gemma_300m_lora"),}ALIGNMENTS = ("stock", "prefetch", "overlap")SAMPLERS = ("stock", "refined", "prefix-select", "prefix-trained")
def model_config(architecture: str): from openpi.models.pi0_config import Pi0Config
backbone, expert = MODEL_VARIANTS[architecture] return Pi0Config( action_horizon=HORIZON, action_dim=PADDED_DIM, pi05=True, paligemma_variant=backbone, action_expert_variant=expert, )
def joint_transforms(config, *, training: bool = False): from openpi import transforms from openpi.policies.droid_policy import DroidInputs, DroidOutputs
mask = transforms.make_bool_mask(7, -1) inputs = [DroidInputs(model_type=config.model_type)] if training: inputs.append(transforms.DeltaActions(mask)) return transforms.Group(inputs=inputs, outputs=[transforms.AbsoluteActions(mask), DroidOutputs()])
def alignment_offset(mode: str, step: int, prefetch_offset: int = PREFETCH_STEPS) -> int: """The pinned evaluator calls at 0, 4, 12, 20, ... and starts execution at 0, 8, 16, 24, ...""" if mode in ("prefetch", "overlap") and step % EXECUTED_STEPS == PREFETCH_STEPS: return prefetch_offset return 0
def policy_example(exterior, wrist, joints, grip, prompt): """Canonical features consumed by OpenPI's DROID transform.""" return { "observation/exterior_image_1_left": exterior, "observation/wrist_image_left": wrist, "observation/joint_position": np.asarray(joints, dtype=np.float32), "observation/gripper_position": np.asarray(grip, dtype=np.float32).reshape(-1), "prompt": prompt, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289# 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 OpenPIruntime lives in the brain image. The policy reads the left exterior and wristcameras, the seven arm joints, and the gripper, then returns an 8-Dabsolute joint command."""
from __future__ import annotations
import jsonimport osimport subprocessimport sysfrom pathlib import Path
import numpy as npfrom 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 Brainfrom 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)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465"""Causal flow matching with clean committed action tokens for the pinned π0.5 architecture."""
from __future__ import annotations
import jaximport jax.numpy as jnpfrom openpi.models import model as openpi_modelfrom openpi.models.pi0 import make_attn_mask
# Eight physical channels are followed by zero padding in the DROID model input.# This tag identifies a clean committed token under the model's shared noise-level embedding.TAG = 8MAX_DELAY = 4
def tag_prefix(actions, lengths): rows = actions[:, :MAX_DELAY] return rows.at[:, :, TAG].set(jnp.arange(MAX_DELAY)[None, :] < lengths[:, None])
def clamp_prefix(latent, prefix): first = jnp.where(prefix[..., TAG:TAG + 1] > 0, prefix, latent[:, :MAX_DELAY]) return latent.at[:, :MAX_DELAY].set(first)
def prefix_loss(model, rng, observation, actions, *, train=False): preprocess, gaussian, times, delays = jax.random.split(rng, 4) observation = openpi_model.preprocess_observation(preprocess, observation, train=train) time = jax.random.beta(times, 1.5, 1, (actions.shape[0],)) * 0.999 + 0.001 noise = jax.random.normal(gaussian, actions.shape) latent = time[:, None, None] * noise + (1 - time[:, None, None]) * actions # The validator normally uses four committed actions, with no delay at reset. choices = jnp.array([0, 0, 1, 2, 3, 4, 4, 4], dtype=jnp.int32) lengths = jax.random.choice(delays, choices, shape=(actions.shape[0],)) latent = clamp_prefix(latent, tag_prefix(actions, lengths)) context, visible, causal = model.embed_prefix(observation) suffix, valid, ar, conditioning = model.embed_suffix(observation, latent, time) mask = jnp.concatenate((visible, valid), axis=1) (_, output), _ = model.PaliGemma.llm( [context, suffix], mask=make_attn_mask(mask, jnp.concatenate((causal, ar))), positions=jnp.cumsum(mask, axis=1) - 1, adarms_cond=[None, conditioning], ) velocity = model.action_out_proj(output[:, -model.action_horizon:]) errors = jnp.mean(jnp.square(velocity - (noise - actions)), axis=-1) free = jnp.arange(model.action_horizon)[None, :] >= lengths[:, None] return errors * free * (model.action_horizon / free.sum(axis=-1, keepdims=True))
def sample_prefix(model, rng, observation, *, num_steps=10, noise=None, prefix=None): from refine import cached_velocity
observation = openpi_model.preprocess_observation(None, observation, train=False) batch = observation.state.shape[0] if noise is None: noise = jax.random.normal(rng, (batch, model.action_horizon, model.action_dim)) if prefix is None: prefix = jnp.zeros_like(noise[:, :MAX_DELAY]) velocity = cached_velocity(model, observation) dt = 1.0 / num_steps
def euler(index, latent): latent = clamp_prefix(latent, prefix) return latent - dt * velocity(latent, 1.0 - index * dt)
return clamp_prefix(jax.lax.fori_loop(0, num_steps, euler, noise), prefix)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889"""Predict-and-perturb sampling for the pinned OpenPI π0.5 flow model."""
from __future__ import annotations
import jaximport jax.numpy as jnpfrom openpi.models import model as openpi_modelfrom openpi.models.pi0 import make_attn_mask
FLOW_STEPS = 10GRIPPER = 7
def refine_trajectory(velocity, noise): """Aggregate stock and refined samples, then project the average toward the action distribution.""" dt = 1.0 / FLOW_STEPS bits = jax.lax.bitcast_convert_type(noise[:, 0, :2].astype(jnp.float32), jnp.uint32) keys = jax.vmap(lambda pair: jax.random.fold_in(jax.random.PRNGKey(pair[0]), pair[1]))(bits)
def perturb(clean, time, index): epsilon = jax.vmap(lambda key: jax.random.normal( jax.random.fold_in(key, index), shape=noise.shape[1:], dtype=noise.dtype ))(keys) return (1.0 - time) * clean + time * epsilon
def refine(x, time, count, start): def iteration(i, latent): return perturb(latent - time * velocity(latent, time), time, start + i)
return jax.lax.fori_loop(0, count, iteration, x)
def euler(index, x): time = 1.0 - index * dt return x - dt * velocity(x, time)
def refined_euler(index, x): count = jnp.where(index == 1, 3, jnp.where(index <= 3, 1, 0)) time = 1.0 - index * dt x = refine(x, time, count, index * 4) return euler(index, x)
# Share the first step, since both trajectories start from the same observation and noise. first = euler(0, noise) stock = jax.lax.fori_loop(1, FLOW_STEPS, euler, first) refined = jax.lax.fori_loop(1, FLOW_STEPS, refined_euler, first) mean = (stock + refined) * 0.5 mean = mean.at[..., GRIPPER].set(stock[..., GRIPPER]) start = FLOW_STEPS - 3 time = 3 * dt latent = perturb(mean, time, 4 * FLOW_STEPS) projected = refine(latent, time, 3, 4 * FLOW_STEPS + 1) actions = jax.lax.fori_loop(start, FLOW_STEPS, euler, projected) return actions.at[..., GRIPPER].set(stock[..., GRIPPER])
def sample_refined(model, rng, observation, *, num_steps=FLOW_STEPS, noise=None): """Build the π0.5 image/text cache once and reuse it for both action trajectories.""" del num_steps # The packaged sampler uses the ten-step schedule above. observation = openpi_model.preprocess_observation(None, observation, train=False) batch = observation.state.shape[0] if noise is None: noise = jax.random.normal(rng, (batch, model.action_horizon, model.action_dim))
return refine_trajectory(cached_velocity(model, observation), noise)
def cached_velocity(model, observation): """Encode the observation once and return the velocity field for successive Euler steps.""" batch = observation.state.shape[0] tokens, mask, causal = model.embed_prefix(observation) prefix_len = mask.shape[-1] positions = jnp.cumsum(mask, axis=1) - 1 _, cache = model.PaliGemma.llm([tokens, None], mask=make_attn_mask(mask, causal), positions=positions) valid_prefix = jnp.sum(mask, axis=-1, keepdims=True)
def velocity(latent, time): suffix, valid, causal, conditioning = model.embed_suffix( observation, latent, jnp.broadcast_to(time, (batch,)) ) prefix_mask = jnp.broadcast_to(mask[:, None, :], (batch, suffix.shape[1], prefix_len)) full_mask = jnp.concatenate((prefix_mask, make_attn_mask(valid, causal)), axis=-1) suffix_positions = valid_prefix + jnp.cumsum(valid, axis=-1) - 1 (_, output), _ = model.PaliGemma.llm( [None, suffix], mask=full_mask, positions=suffix_positions, kv_cache=cache, adarms_cond=[None, conditioning], ) return model.action_out_proj(output[:, -model.action_horizon:])
return velocity1234# Training
OpenPI π0.5 DROID joint-position checkpoint, architecture `action-lora`.The brain uses the DROID quantile normalization assets stored with the checkpoint.1234567891011121314151617181920212223242526272829303132333435363738394041424344{ "name": "second-object-40", "architecture": "action-lora", "prefix_conditioning": true, "adapters_only": true, "steps": 40, "batch_size": 4, "lr": 3e-06, "stride": 4, "holdout_fraction": 0.1, "task_balance": 0.5, "recovery_fraction": 0.25, "gripper_transition_weight": 0.0, "switch_window_mix": 0.0, "approach_window_mix": 0.0, "gripper_logistic_weight": 0.0, "seed": 42, "openpi_commit": "215abfb217dbac7d5f1273282331b9b1866c0479", "caches": [ { "cache": "full-preview-cache", "recovery": false, "require_predicate": false, "accepted_episodes": 50, "manifest_sha256": "76523ef8357dafea33a43e4026fd255cd4ab69be9a7063453623eabeac0da7e2" }, { "cache": "v0-preview-cache", "recovery": false, "require_predicate": false, "accepted_episodes": 100, "manifest_sha256": "199cad0c7cd30b6ce221aef2e1dc8eea16c582fb63f838363f22e50cf488b9d9" }, { "cache": "recovery", "recovery": true, "require_predicate": true, "accepted_episodes": 1, "manifest_sha256": "ba10ab4c0a5298ada5cba5b14b1ddb1b635a00ed8b84fa61d6eea14751baedfe" } ], "training_episodes": 128, "heldout_episodes": 23}README.mdAdded+43
deployment/LICENSEAdded+29
deployment/NOTICEAdded+3
deployment/agent.yamlAdded+32
deployment/brain/adapt.pyAdded+168
deployment/brain/contract.pyAdded+62
deployment/brain/policy.pyAdded+289
deployment/brain/prefix.pyAdded+65
deployment/brain/refine.pyAdded+89
deployment/train/README.mdAdded+4
deployment/train/miner_training.jsonAdded+44