"""SimVLA (SmolVLM-500M + 행동 트랜스포머) 에 MeanFlow 를 붙인다. pi0 실험(pi0_meanflow.py)과 같은 규칙. - 시간 규약은 SimVLA 원본과 pi0 가 같다: t=1 노이즈, t=0 행동, x_t = t·noise + (1−t)·a, v = noise − a. - 구간 d = t − r 은 SimVLA 의 시간 임베딩(timestep_embedding, dim_time)과 같은 함수로 embed 하고, 0 으로 초기화한 interval_proj 로 행동 토큰에 더한다(concat 모드). 그래서 r=t 이고 학습 전이면 원본과 같은 함수다. FM 기본 런은 use_interval_emb=False 로 만들어 원본 SimVLA 와 똑같은 모델이 된다. - 손실: u_tgt = sg(v − (t−r)·du/dt), du/dt 는 접선 (v, 1, 0) 의 JVP. 적응 가중치 1/(‖Δ‖²+c)^p, ‖Δ‖² 은 (스텝, 차원) 평균. u 와 du/dt 를 torch.func.jvp 한 번으로 같이 얻는다 — SimVLA 행동 트랜스포머에 dropout(0.1)이 있어서 따로 계산하면 마스크가 달라진다. u 의 계산 그래프로 그래디언트가 흐르고(VLM 특징까지), du/dt 는 detach. JVP 동안만 attention 을 SimVLA 의 비융합 경로(q·kᵀ → softmax → dropout → ·v)로 돌린다. flash/efficient 커널은 forward-AD 를 지원하지 않고, SDPA math 백엔드는 bf16 autocast 아래에서 u 로 역전파할 때 softmax 역전파 dtype 오류가 난다. - (t, r) 샘플링: r≠t 비율 고정(기본 25%). r=t 샘플의 t 는 SimVLA 원본과 같은 Beta(1.5,1)·0.999+0.001. r≠t 샘플은 d ~ U[lo, hi], t ~ U[d, 1], r = t − d (커리큘럼 A·B, MeanFlow 기본은 lo=0, hi=1). """ from __future__ import annotations import contextlib import os import sys from typing import Dict import torch import torch.nn as nn sys.path.insert(0, os.environ.get("SIMVLA_SRC", "/workspace/simvla/SimVLA")) from models.configuration_smolvlm_vla import SmolVLMVLAConfig # noqa: E402 from models.modeling_smolvlm_vla import SmolVLMVLA # noqa: E402 from models.transformer_smolvlm import Attention, timestep_embedding # noqa: E402 SAMPLER_INTERVAL = 1 @contextlib.contextmanager def unfused_attention(module: nn.Module): """module 안의 SimVLA Attention 을 잠시 비융합 경로로 돌린다(수식·dropout 위치는 같다).""" attns = [m for m in module.modules() if isinstance(m, Attention)] saved = [m.fused_attn for m in attns] for m in attns: m.fused_attn = False try: yield finally: for m, f in zip(attns, saved): m.fused_attn = f class SmolVLMVLAMFConfig(SmolVLMVLAConfig): model_type = "smolvlm_vla_mf" def __init__( self, use_interval_emb: bool = True, ratio_r_neq_t: float = 0.25, adaptive_p: float = 1.0, adaptive_c: float = 1e-3, num_views: int = 3, **kwargs, ): super().__init__(**kwargs) self.use_interval_emb = use_interval_emb self.ratio_r_neq_t = ratio_r_neq_t self.adaptive_p = adaptive_p self.adaptive_c = adaptive_c self.num_views = num_views class SmolVLMVLAMF(SmolVLMVLA): config_class = SmolVLMVLAMFConfig def __init__(self, config: SmolVLMVLAMFConfig, *args, **kwargs): super().__init__(config, *args, **kwargs) if config.use_adaln: raise NotImplementedError("MeanFlow 이식은 concat 모드(use_adaln=False)만 지원한다") self.use_interval_emb = bool(config.use_interval_emb) if self.use_interval_emb: self.interval_proj = nn.Linear(config.dim_time, config.hidden_size) nn.init.zeros_(self.interval_proj.weight) nn.init.zeros_(self.interval_proj.bias) # ------------------------------------------------------------------ 행동 트랜스포머 def field(self, vlm_features, x_t, proprio_norm, t, r): """F(x_t, t, r): MeanFlow 모델이면 평균 속도 u, FM 모델이면 순간 속도 v(r 무시). 원본 _forward_concat 과 같은 계산.""" tr = self.transformer B, num_actions = x_t.shape[:2] time_tokens = timestep_embedding(t, tr.dim_time).unsqueeze(1).expand(B, num_actions, tr.dim_time) proprio_tokens = proprio_norm.unsqueeze(1).expand(B, num_actions, proprio_norm.shape[-1]) x = tr.action_encoder(torch.cat([x_t, proprio_tokens, time_tokens], dim=-1)) if self.use_interval_emb: x = x + self.interval_proj(timestep_embedding(t - r, tr.dim_time).to(x.dtype)).unsqueeze(1) x = torch.cat([x, tr.vlm_proj(vlm_features)], dim=1) x = x + tr.pos_emb[:, : x.shape[1], :] for block in tr.blocks: x = block(x) return tr.action_decoder(tr.norm(x[:, :num_actions])) def _norm_inputs(self, proprio, action=None): p = self.action_space.normalize_state(proprio) a = self.action_space.normalize_action(action) if action is not None else None return p, a def sample_tr(self, B, device, lo: float, hi: float, generator=None): cfg = self.config beta = torch.distributions.Beta(torch.tensor(1.5, device=device), torch.tensor(1.0, device=device)) t_fm = beta.sample((B,)) * 0.999 + 0.001 d = lo + (hi - lo) * torch.rand(B, device=device) t_int = d + (1.0 - d) * torch.rand(B, device=device) r_int = (t_int - d).clamp(0.0, 1.0) n_neq = int(round(cfg.ratio_r_neq_t * B)) neq = torch.zeros(B, dtype=torch.bool, device=device) neq[torch.randperm(B, device=device)[:n_neq]] = True t = torch.where(neq, t_int, t_fm) r = torch.where(neq, r_int, t_fm) return t, r, neq # ------------------------------------------------------------------ 학습 def forward(self, input_ids, image_input, image_mask, proprio, action, method: str = "fm", lo: float = 0.0, hi: float = 1.0): enc = self.forward_vlm_efficient(image_input, image_mask, input_ids)["vlm_features"] proprio_norm, action_norm = self._norm_inputs(proprio, action) B, device = action_norm.shape[0], action_norm.device noise = torch.randn_like(action_norm) if method == "fm": beta = torch.distributions.Beta(torch.tensor(1.5, device=device), torch.tensor(1.0, device=device)) t = beta.sample((B,)) * 0.999 + 0.001 x_t = t.view(-1, 1, 1) * noise + (1 - t.view(-1, 1, 1)) * action_norm v_pred = self.field(enc, x_t, proprio_norm, t, t) loss = torch.mean(torch.square(v_pred - (noise - action_norm))) return {"loss": loss, "mse": loss.detach()} t, r, neq = self.sample_tr(B, device, lo, hi) x_t = t.view(-1, 1, 1) * noise + (1 - t.view(-1, 1, 1)) * action_norm v = noise - action_norm def u_fn(x, tt, rr): return self.field(enc, x, proprio_norm, tt, rr) with unfused_attention(self.transformer): u, dudt = torch.func.jvp(u_fn, (x_t, t, r), (v, torch.ones_like(t), torch.zeros_like(r))) u_tgt = (v - (t - r).view(-1, 1, 1) * dudt).detach() sq = torch.mean(torch.square(u.float() - u_tgt.float()), dim=(1, 2)) w = 1.0 / torch.pow(sq.detach() + self.config.adaptive_c, self.config.adaptive_p) loss = torch.mean(w * sq) neq_f, eq_f = neq.float(), (~neq).float() info = { "mse": sq.mean(), "mse_eq": (sq * eq_f).sum() / eq_f.sum().clamp(min=1), "mse_neq": (sq * neq_f).sum() / neq_f.sum().clamp(min=1), "dudt_rms": torch.sqrt(torch.mean(torch.square(dudt.float()))), "interval_mean_neq": ((t - r) * neq_f).sum() / neq_f.sum().clamp(min=1), "interval_max": (t - r).max(), } return {"loss": loss, **{k: v.detach() for k, v in info.items()}} # ------------------------------------------------------------------ 추론 @torch.no_grad() def generate(self, input_ids, image_input, image_mask, proprio, num_steps: int = 1, noise=None, normalized_out=False): """균등 간격 num_steps 번: MeanFlow 는 z_r = z_t − (t−r)·u(z_t, r, t), FM 은 같은 식에서 u 대신 v(오일러).""" self.eval() enc = self.forward_vlm_efficient(image_input, image_mask, input_ids)["vlm_features"] proprio_norm, _ = self._norm_inputs(proprio) B = proprio.shape[0] x = noise if noise is not None else torch.randn(B, self.num_actions, self.action_space.dim_action, device=proprio.device) dt = 1.0 / num_steps for i in range(num_steps): t = torch.full((B,), 1.0 - i * dt, device=x.device) r = (t - dt).clamp(min=0.0) x = x - (t - r).view(-1, 1, 1) * self.field(enc, x, proprio_norm, t, r).float() return x if normalized_out else self.action_space.postprocess(x) @torch.no_grad() def eval_metrics(self, input_ids, image_input, image_mask, proprio, action, noise, jump_levels, nfes) -> Dict[str, torch.Tensor]: """pi0 실험과 같은 검증 지표(샘플별, 정규화된 행동 공간). jump_err_h: z_h 에서 r=0 까지 한 번에 점프한 오차. gen_err_nfe{n}: 노이즈에서 n 번 점프한 생성 오차(전체 / 앞 5 스텝). """ self.eval() enc = self.forward_vlm_efficient(image_input, image_mask, input_ids)["vlm_features"] proprio_norm, a = self._norm_inputs(proprio, action) B = a.shape[0] ones = torch.ones(B, device=a.device) def err(pred): d = torch.square(pred.float() - a.float()) return d.mean(dim=(1, 2)), d[:, :5].mean(dim=(1, 2)) out = {} for h in jump_levels: z = h * noise + (1 - h) * a pred = z - h * self.field(enc, z, proprio_norm, h * ones, 0 * ones).float() out[f"jump_err_{h:.1f}"], _ = err(pred) for n in nfes: x = noise.clone() for i in range(n): t = 1.0 - i / n r = max(t - 1.0 / n, 0.0) x = x - (t - r) * self.field(enc, x, proprio_norm, t * ones, r * ones).float() out[f"gen_err_nfe{n}"], out[f"gen_err5_nfe{n}"] = err(x) return out @torch.no_grad() def frontier_err(self, input_ids, image_input, image_mask, proprio, action, noise, h: float) -> torch.Tensor: """커리큘럼 B 점검: 노이즈 수준 h 에서 r=0 까지 한 번에 점프한 오차(샘플별).""" self.eval() enc = self.forward_vlm_efficient(image_input, image_mask, input_ids)["vlm_features"] proprio_norm, a = self._norm_inputs(proprio, action) ones = torch.ones(a.shape[0], device=a.device) z = h * noise + (1 - h) * a pred = z - h * self.field(enc, z, proprio_norm, h * ones, 0 * ones).float() return torch.square(pred - a.float()).mean(dim=(1, 2)) def build_model(method: str, smolvlm_path: str, hidden_size=1024, depth=24, num_heads=16, num_actions=10, image_size=384, norm_stats_path: str | None = None) -> SmolVLMVLAMF: cfg = SmolVLMVLAMFConfig( smolvlm_model_path=smolvlm_path, hidden_size=hidden_size, depth=depth, num_heads=num_heads, action_mode="libero_joint", num_actions=num_actions, use_adaln=False, image_size=image_size, use_interval_emb=(method != "fm"), ) model = SmolVLMVLAMF(cfg) if norm_stats_path: model.action_space.load_norm_stats(norm_stats_path) return model def load_model(ckpt_dir: str) -> SmolVLMVLAMF: model = SmolVLMVLAMF.from_pretrained(ckpt_dir) ns = os.path.join(ckpt_dir, "norm_stats.json") if os.path.exists(ns): model.action_space.load_norm_stats(ns) return model