"""Predict-and-perturb sampling for the pinned OpenPI π0.5 flow model.""" from __future__ import annotations import jax import jax.numpy as jnp from openpi.models import model as openpi_model from openpi.models.pi0 import make_attn_mask FLOW_STEPS = 10 GRIPPER = 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 velocity