File size: 3,791 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
"""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