File size: 11,677 Bytes
771e960
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
"""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