File size: 11,747 Bytes
d8e9a5e | 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 | """SmolVLA as a stochastic policy for RL (ReinFlow-style noise injection), plus a critic.
SmolVLA turns Gaussian noise x_0 into a 50-step action chunk with 10 Euler steps of a learned
velocity field (VLAFlowMatching.sample_actions). Here each step adds Gaussian noise of a learned
per-step, per-joint size to the six real action dimensions:
x_{k+1} = x_k + dt * v(x_k, t_k) + sigma_k * eps_k
so the probability of the chain x_1 ... x_10 given x_0 is a product of Gaussians that can be
computed and differentiated (ReinFlow). With the noise off this is exactly SmolVLA's sampling.
Trained: the action expert (`vlm_with_expert.lm_expert`) and the action and time projections
(`action_in_proj`, `action_out_proj`, `action_time_mlp_in`, `action_time_mlp_out`), and a critic (an
MLP on the frozen backbone's pooled prefix output and the normalized state); optionally the noise
sizes. Frozen: the vision-language backbone and `state_proj`, which feeds it, so the prefix (images,
instruction, state) is computed without gradients. The noise and the critic are only for training;
`save()` writes a plain SmolVLA checkpoint with the baseline's own processors (normalization).
Numerics (sim/reports/rl/check): the backbone runs in bfloat16 and gives batch-size-dependent
results, and small noise sizes turn tiny differences in the mean into large log-probability
differences. So the prefix (KV cache, pad mask, pooled features, state) of every decision is kept
from sampling time and reused in the update (`split_prefix` / `stack_prefix`), and the action
expert runs in float32 (`expert_fp32`, also needed for small updates to register at all). The
noise size falls geometrically from `sigma_start` (first denoising step, where the flow turns it
into a coherent change of the whole chunk) to `sigma_end` (last step, which adds it directly to
the joint targets as frame-to-frame jitter).
"""
from __future__ import annotations
import math
import shutil
import sys
from pathlib import Path
import torch
from torch import nn
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
TRAINED = ("vlm_with_expert.lm_expert.", "action_in_proj.", "action_out_proj.", "action_time_mlp_in.",
"action_time_mlp_out.")
def gauss_logp(x: torch.Tensor, mean: torch.Tensor, sigma: torch.Tensor) -> torch.Tensor:
"""Log density of each element of x under N(mean, sigma^2): (B, T, A) -> (B, T, A). Kept per element:
PPO clips each element's ratio (as per-token ratios in language-model PPO); the sum over the 300
values of a step is far too sharp with the small noise of the last denoising steps."""
z = (x - mean) / sigma
return -0.5 * z * z - torch.log(sigma) - 0.5 * math.log(2 * math.pi)
class Critic(nn.Module):
def __init__(self, feat_dim: int, state_dim: int, hidden: int = 256):
super().__init__()
self.net = nn.Sequential(nn.Linear(feat_dim + state_dim, hidden), nn.Tanh(), nn.Linear(hidden, hidden), nn.Tanh(),
nn.Linear(hidden, 1))
def forward(self, feat, state):
return self.net(torch.cat([feat, state], dim=-1)).squeeze(-1)
class FlowRL(nn.Module):
def __init__(self, path: str, instruction: str, sigma_start=0.1, sigma_end=0.002, learn_sigma=False,
expert_fp32=True):
super().__init__()
from eval_policy import load_policy
policy, pre, post, device = load_policy(path, expert_fp32=expert_fp32)
self.policy, self.pre, self.post, self.device = policy, pre, post, device
self.src_path = Path(path)
self.model = policy.model
cfg = policy.config
self.n_steps, self.chunk, self.adim = cfg.num_steps, cfg.chunk_size, cfg.action_feature.shape[0]
self.max_adim = cfg.max_action_dim
self.instruction = instruction
for p in policy.parameters():
p.requires_grad_(False)
self.trained_names = []
for name, p in self.model.named_parameters():
if name.startswith(TRAINED):
p.requires_grad_(True)
self.trained_names.append(name)
frac = torch.linspace(0.0, 1.0, self.n_steps, device=device)[:, None]
init = math.log(sigma_start) + frac * (math.log(sigma_end) - math.log(sigma_start))
self.log_sigma = nn.Parameter(init.expand(self.n_steps, self.adim).clone(), requires_grad=learn_sigma)
self.sigma_min, self.sigma_max = 0.5 * min(sigma_start, sigma_end), 1.5 * max(sigma_start, sigma_end)
hidden = self.model.vlm_with_expert.config.text_config.hidden_size
self.critic = Critic(hidden, self.adim).to(device)
policy.eval()
# ------------------------------------------------------------------ inputs
def sigma(self) -> torch.Tensor:
return self.log_sigma.exp().clamp(self.sigma_min, self.sigma_max)
def policy_params(self):
return [p for n, p in self.model.named_parameters() if p.requires_grad]
def batch(self, obs_list: list[dict]) -> dict:
"""Observations (numpy, as eval_policy builds them) through the policy's own preprocessor, stacked."""
from lerobot.policies.utils import prepare_observation_for_inference
items = []
with torch.no_grad():
for o in obs_list:
ob = prepare_observation_for_inference(dict(o), self.device, self.instruction, "so101_follower")
items.append(self.pre(ob))
return {k: torch.cat([it[k] for it in items]) for k, v in items[0].items() if torch.is_tensor(v)}
@torch.no_grad()
def prefix(self, batch: dict):
"""Images, instruction and state through the frozen backbone: (pad masks, KV cache, pooled
features, normalized state)."""
from lerobot.policies.smolvla.modeling_smolvla import make_att_2d_masks
from lerobot.utils.constants import OBS_LANGUAGE_ATTENTION_MASK, OBS_LANGUAGE_TOKENS
images, img_masks = self.policy.prepare_images(batch)
state = self.policy.prepare_state(batch)
embs, pad, att = self.model.embed_prefix(images, img_masks, batch[OBS_LANGUAGE_TOKENS],
batch[OBS_LANGUAGE_ATTENTION_MASK], state=state)
att2d = make_att_2d_masks(pad, att)
pos = torch.cumsum(pad, dim=1) - 1
outs, kv = self.model.vlm_with_expert.forward(attention_mask=att2d, position_ids=pos, past_key_values=None,
inputs_embeds=[embs, None], use_cache=self.policy.config.use_cache,
fill_kv_cache=True)
h, m = outs[0].float(), pad.unsqueeze(-1).float()
feat = (h * m).sum(1) / m.sum(1).clamp(min=1.0)
return pad, kv, feat, state[:, :self.adim].float()
def _times(self, bsize: int):
dt = -1.0 / self.n_steps
return dt, [torch.tensor(1.0 + k * dt, dtype=torch.float32, device=self.device).expand(bsize)
for k in range(self.n_steps)]
# ------------------------------------------------------------------ sampling and likelihood
@torch.no_grad()
def sample(self, batch: dict, x0: torch.Tensor, noise: bool = True):
"""The chain x_0..x_n (B, n+1, T, max_adim), its log-probabilities per element (B, n, T, A), the
critic's value (B,) and the prefix (pad, kv, feat, state) for the update. With noise=False,
x_n is SmolVLA's own action chunk for this x_0."""
prefix = self.prefix(batch)
pad, kv, feat, state = prefix
bsize = x0.shape[0]
dt, times = self._times(bsize)
sig = self.sigma()
x, chain = x0, [x0]
logp = x0.new_zeros(bsize, self.n_steps, self.chunk, self.adim)
for k in range(self.n_steps):
v = self.model.denoise_step(pad, kv, x, times[k])
mean = x + dt * v
if noise:
nxt = mean.clone()
eps = torch.randn(bsize, self.chunk, self.adim, device=self.device)
nxt[..., :self.adim] = mean[..., :self.adim] + sig[k] * eps
logp[:, k] = gauss_logp(nxt[..., :self.adim], mean[..., :self.adim], sig[k])
else:
nxt = mean
x = nxt
chain.append(x)
return torch.stack(chain, 1), logp, self.critic(feat, state), prefix
@staticmethod
def split_prefix(prefix, j: int):
"""Decision j's prefix, on the CPU."""
pad, kv, feat, state = prefix
return (pad[j:j + 1].cpu(), {l: {k: t[j:j + 1].cpu() for k, t in d.items()} for l, d in kv.items()},
feat[j:j + 1].cpu(), state[j:j + 1].cpu())
def stack_prefix(self, items):
"""Stored prefixes of several decisions as one batch on the device."""
dev = self.device
kv = {l: {k: torch.cat([it[1][l][k] for it in items]).to(dev) for k in items[0][1][l]} for l in items[0][1]}
return (torch.cat([it[0] for it in items]).to(dev), kv, torch.cat([it[2] for it in items]).to(dev),
torch.cat([it[3] for it in items]).to(dev))
def evaluate(self, batch: dict | None, chain: torch.Tensor, prefix=None):
"""Per-element log-probabilities (B, n, T, A) of a stored chain under the current weights (with
gradients through the action expert and the noise sizes) and the critic's value (B,).
Pass the stored `prefix` (stack_prefix) to reuse sampling time's; else it is recomputed."""
pad, kv, feat, state = prefix if prefix is not None else self.prefix(batch)
bsize = chain.shape[0]
dt, times = self._times(bsize)
sig = self.sigma()
logp = []
for k in range(self.n_steps):
v = self.model.denoise_step(pad, kv, chain[:, k], times[k])
mean = chain[:, k] + dt * v
logp.append(gauss_logp(chain[:, k + 1, ..., :self.adim], mean[..., :self.adim], sig[k]))
return torch.stack(logp, 1), self.critic(feat, state)
@torch.no_grad()
def actions(self, chain: torch.Tensor):
"""The executed chunk in LeRobot units (B, T, 6): the last chain step through the policy's
own postprocessor (unnormalization), as eval_policy applies it to every action."""
x = chain[:, -1, :, :self.adim]
bsize = x.shape[0]
a = self.post(x.reshape(bsize * self.chunk, self.adim))
return a.reshape(bsize, self.chunk, self.adim).float().cpu().numpy()
def x0(self, bsize: int, generators=None) -> torch.Tensor:
"""Initial noise as SmolVLA draws it (sample_noise); with per-episode CUDA generators seeded
like eval_policy's torch.manual_seed, the same draws as eval_policy.py."""
shape = (self.chunk, self.max_adim)
if generators is None:
return torch.normal(mean=0.0, std=1.0, size=(bsize, *shape), dtype=torch.float32, device=self.device)
return torch.cat([torch.normal(mean=0.0, std=1.0, size=(1, *shape), dtype=torch.float32, device=self.device,
generator=g) for g in generators])
# ------------------------------------------------------------------ checkpoint
def save(self, out: str | Path, extra: dict | None = None):
"""A plain SmolVLA checkpoint (config + weights) with the baseline's processor files, and
the training-only parts (noise sizes, critic) in rl_state.pt."""
out = Path(out)
out.mkdir(parents=True, exist_ok=True)
self.policy.save_pretrained(out)
for f in self.src_path.glob("policy_*processor*"):
shutil.copy2(f, out / f.name)
torch.save(dict(log_sigma=self.log_sigma.detach().cpu(), critic=self.critic.state_dict(), **(extra or {})),
out / "rl_state.pt")
|