File size: 25,708 Bytes
b4396f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
from collections.abc import Sequence

import torch
from torch import Tensor, nn

from lerobot.policies.pretrained import PreTrainedPolicy

from .configuration_sera_vla_v3 import SERAVLAV3Config
from .modeling_base import SERAVLAModel, SERAVLAPolicy, SwiGLUExpert, _init_new


class GroundedGoal(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.queries = nn.Parameter(torch.randn(4, 512) * 0.02)
        self.norm = nn.LayerNorm(512)
        self.attention = nn.MultiheadAttention(512, 8, batch_first=True)
        self.ffn = nn.Sequential(nn.LayerNorm(512), nn.Linear(512, 1024), nn.GELU(), nn.Linear(1024, 512))

    def forward(self, vision: Tensor, text: Tensor, state: Tensor, text_padding: Tensor) -> Tensor:
        source = torch.cat((vision, text, state[:, None]), dim=1)
        padding = torch.cat(
            (
                torch.zeros(vision.shape[:2], dtype=torch.bool, device=vision.device),
                text_padding,
                torch.zeros(state.shape[0], 1, dtype=torch.bool, device=state.device),
            ),
            dim=1,
        )
        q = self.queries[None].expand(vision.shape[0], -1, -1)
        q = q + self.attention(self.norm(q), source, source, key_padding_mask=padding, need_weights=False)[0]
        return q + self.ffn(q)


class SkillPrior(nn.Module):
    """Autoregressive prior over the 8 FSQ skill codes of a window.

    Input: the D-skillroute router context (1536 = fusion-context
    mean 512 + state 512 + pooled instruction 512). Output: logits
    [B, 8, 1000]. Layout: position 0 is the context token (predicts
    code 1); position i > 0 embeds code i (predicts code i + 1).
    Cross-attention memory is the context token alone.
    """

    def __init__(self) -> None:
        super().__init__()
        self.ctx = nn.Linear(1536, 256)
        self.emb = nn.Embedding(1000, 256)
        self.pos = nn.Parameter(torch.randn(8, 256) * 0.02)
        layer = nn.TransformerDecoderLayer(
            256, 4, 1024, batch_first=True, norm_first=True)
        self.decoder = nn.TransformerDecoder(layer, 2)
        self.head = nn.Linear(256, 1000)

    def forward(self, router_input: Tensor, codes: Tensor) -> Tensor:
        ctx = self.ctx(router_input)[:, None]
        emb = self.emb(codes[:, :-1].long())
        tgt = torch.cat([ctx, emb], dim=1) + self.pos[None]
        mask = torch.full((8, 8), float("-inf"), device=tgt.device).triu(1)
        h = self.decoder(tgt, ctx, tgt_mask=mask)
        return self.head(h)

    @torch.no_grad()
    def greedy(self, router_input: Tensor) -> Tensor:
        b = router_input.shape[0]
        codes = torch.zeros(b, 8, dtype=torch.long, device=router_input.device)
        for i in range(8):
            logits = self.forward(router_input, codes)
            codes[:, i] = logits[:, i].argmax(-1)
        return codes


class ARMoEBlock(nn.Module):
    """Causal twin of MoEBlock for the v4_1 AR decoder: causal
    self-attention + cross-attention to the trunk context + the
    shared/routed SwiGLU MoE FFN with per-sample routing (the
    indices/weights produced by encode_observation, exactly as the
    FM stack consumes them). Returns (h, z_all) like MoEBlock so
    the specialization loss applies unchanged."""

    def __init__(self) -> None:
        super().__init__()
        self.norms = nn.ModuleList([nn.LayerNorm(512, eps=1e-5) for _ in range(3)])
        self.self_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True)
        self.cross_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True)
        self.shared = SwiGLUExpert(1344)
        self.experts = nn.ModuleList(SwiGLUExpert(672) for _ in range(8))

    def forward(
        self, x: Tensor, context: Tensor, indices: Tensor, weights: Tensor,
        key_padding: Tensor | None,
    ) -> tuple[Tensor, Tensor | None]:
        n = self.norms[0](x)
        L = x.shape[1]
        causal = torch.full((L, L), float("-inf"), device=x.device, dtype=x.dtype).triu(1)
        x = x + self.self_attn(
            n, n, n, attn_mask=causal, key_padding_mask=key_padding, need_weights=False
        )[0]
        n = self.norms[1](x)
        x = x + self.cross_attn(n, context, context, need_weights=False)[0]
        u = self.norms[2](x)
        shared, _ = self.shared(u)
        routed = torch.zeros_like(x)
        selected_z: list[Tensor] = []
        for batch_index in range(x.shape[0]):
            sample_z = []
            for slot in range(4):
                expert_index = int(indices[batch_index, slot])
                output, z = self.experts[expert_index](u[batch_index:batch_index + 1])
                routed[batch_index:batch_index + 1] += weights[batch_index, slot] * output
                sample_z.append(z)
            selected_z.append(torch.stack(sample_z, dim=2))
        z_all = torch.cat(selected_z, dim=0) if selected_z else None
        return x + shared + routed, z_all


class SERAVLAV3Model(SERAVLAModel):
    def __init__(self, config: SERAVLAV3Config) -> None:
        super().__init__(config)
        self.goal = GroundedGoal()
        self.goal_deltas = nn.ModuleList(nn.Linear(512, 8) for _ in range(4))
        self.goal_action = nn.Linear(512, 1024)
        for layer in (*self.goal_deltas, self.goal_action):
            nn.init.zeros_(layer.weight)
            nn.init.zeros_(layer.bias)
        self.last_goal: Tensor | None = None
        self.router_base_logits: list[Tensor] = []
        self.router_goal_deltas: list[Tensor] = []
        self.last_router_probabilities: list[Tensor] = []
        self.last_router_indices: list[Tensor] = []
        self.last_vision_tokens: Tensor | None = None
        self.last_text_pooled: Tensor | None = None
        self.last_router_input: Tensor | None = None
        self.last_goal_summary: Tensor | None = None

        # E1 (sera-v4-q-quest): discrete skill-token conditioning.
        # Constructed always (defaults-off keeps D's loss exact);
        # used only when config.v4_quest_enabled is true.
        self.skill_embed = nn.Linear(4, 512)
        nn.init.zeros_(self.skill_embed.weight)
        nn.init.zeros_(self.skill_embed.bias)
        self.skill_pos = nn.Parameter(torch.zeros(8, 512))
        self.skill_film = nn.Linear(512, 1024)
        nn.init.zeros_(self.skill_film.weight)
        nn.init.zeros_(self.skill_film.bias)
        self.skill_prior = SkillPrior()
        self.last_skill_summary: Tensor | None = None
        self.last_skill_codes: Tensor | None = None
        self._quest_table: Tensor | None = None
        _levels = (8, 5, 5, 5)
        _basis = (1, 8, 40, 200)
        _idx = torch.arange(1000)
        _ks = torch.stack(
            [(_idx // b) % lv for b, lv in zip(_basis, _levels)], dim=-1
        ).float()
        _half = (torch.tensor(_levels, dtype=torch.float32) - 1) / 2
        self.register_buffer("skill_decode_table", (_ks - _half) / _half)

        # sera-vla-v4_1: autoregressive ActionCodec2 head. Constructed
        # always (defaults-off keeps every FM arm exact); used only
        # when config.v4_ar_enabled is true.
        _ar_vocab = int(getattr(config, "v4_ar_vocab", 4096))
        self.ar_embed = nn.Embedding(_ar_vocab + 3, 512, padding_idx=_ar_vocab)
        self.ar_pos = nn.Parameter(torch.zeros(128, 512))
        nn.init.normal_(self.ar_pos, std=0.02)
        self.ar_blocks = nn.ModuleList(ARMoEBlock() for _ in range(4))
        self.ar_head = nn.Linear(512, _ar_vocab + 3)
        for _m in (self.ar_embed, self.ar_blocks, self.ar_head):
            _m.apply(_init_new)
        self._acodec2_table: dict | None = None
        self._acodec2_offset: int = 4096
        self._acodec2_codec_obj = None
        self._acodec2_mean: Tensor | None = None
        self._acodec2_std: Tensor | None = None

    def quest_codes_for(self, batch: dict) -> Tensor:
        """Teacher-forcing codes for the batch anchors, looked up
        from the precomputed frozen-tokenizer table by
        (episode_index, frame_index). The training preprocessor
        drops unknown per-sample keys, so the codes cannot ride
        in the batch; episode_index/frame_index do reach the
        policy forward. Table path overridable via the
        SERA_QUEST_CODES env var."""
        if self._quest_table is None:
            import os

            import numpy as np

            path = os.environ.get(
                "SERA_QUEST_CODES",
                os.path.expanduser(
                    "~/sera_v4_experiments/quest_probe/codes_all.npy"),
            )
            self._quest_table = torch.from_numpy(
                np.load(path).astype(np.int64))
        ep = batch["episode_index"]
        fr = batch["frame_index"]
        out = self._quest_table[ep.long().cpu(), fr.long().cpu()]
        return out.to(ep.device)

    def skill_summary(self, codes: Tensor) -> Tensor:
        vec = self.skill_decode_table[codes.long()]
        return (self.skill_embed(vec) + self.skill_pos[None]).mean(1)

    def set_skill_from_codes(self, codes: Tensor) -> None:
        self.last_skill_codes = codes.long()
        self.last_skill_summary = self.skill_summary(codes)

    def set_skill_from_prior(self) -> Tensor:
        if self.last_router_input is None:
            raise RuntimeError("encode_observation must precede prior prediction")
        codes = self.skill_prior.greedy(self.last_router_input)
        self.set_skill_from_codes(codes)
        return codes

    def questfix_conditioning(self, gt_codes: Tensor) -> dict | None:
        """Arm Q2 (sera-v4-q2-questfix): scheduled sampling + token
        dropout on the conditioning summary. Called from the policy
        training forward AFTER set_skill_from_codes(gt_codes) and
        encode_observation (so last_router_input is the exact
        context the prior sees at inference). No-op (returns None)
        outside training (eval mode or no_grad), keeping Q's
        eval/inference behaviour bit-identical.
        """
        if not (self.training and torch.is_grad_enabled()):
            return None
        cfg = self.config
        step = int(getattr(self, "questfix_step", 0))
        self.questfix_step = step + 1
        span = max(1, int(getattr(cfg, "v4_questfix_p_gt_steps", 3000)))
        p_gt = max(0.0, 1.0 - step / span)
        override = float(getattr(cfg, "v4_questfix_p_gt_override", -1.0))
        if override >= 0.0:
            p_gt = override
        src_prior = 0.0
        if float(torch.rand((), device=gt_codes.device)) >= p_gt:
            self.set_skill_from_prior()
            src_prior = 1.0
        drop = float(getattr(cfg, "v4_questfix_dropout", 0.15))
        drop_frac = 0.0
        if drop > 0.0:
            keep = (torch.rand(self.last_skill_summary.shape[0],
                               device=self.last_skill_summary.device)
                    >= drop).to(self.last_skill_summary.dtype)
            drop_frac = float(1.0 - keep.float().mean())
            self.last_skill_summary = self.last_skill_summary * keep[:, None]
        return {"questfix_p_gt": float(p_gt),
                "questfix_src_prior": src_prior,
                "questfix_drop_frac": drop_frac,
                "questfix_step": float(step)}

    # ---- sera-vla-v4_1: ActionCodec2 token targets + AR head ----
    def _acodec2_load(self) -> None:
        if self._acodec2_table is not None:
            return
        import os

        import numpy as np

        path = os.environ.get(
            "SERA_ACODEC2_MAP",
            os.path.expanduser("~/sera_v4_experiments/quest_probe/acodec2_map.npz"),
        )
        m = np.load(path)
        self._acodec2_table = {
            k: torch.from_numpy(m[k])
            for k in ("tok_base_ids", "tok_base_len", "tok_seg_ids",
                      "tok_seg_len", "ep_len")
        }
        self._acodec2_offset = int(m["id_offset"])

    def acodec2_tokens_for(self, batch: dict, valid_len: Tensor):
        """Token targets for the batch anchors from the precomputed
        map. The base variant (window clamped at the episode end)
        matches an item iff its non-pad step count equals
        min(16, ep_len - frame); DATA V2 segment items clamp at the
        segment end instead and take the segment variant. The two
        variants coincide whenever the clamping coincides."""
        self._acodec2_load()
        t = self._acodec2_table
        ep = batch["episode_index"].long().cpu()
        fr = batch["frame_index"].long().cpu()
        ep_valid = (t["ep_len"][ep] - fr).clamp(0, 16)
        use_seg = valid_len.long().cpu() != ep_valid
        ids = torch.where(use_seg[:, None], t["tok_seg_ids"][ep, fr],
                          t["tok_base_ids"][ep, fr])
        lens = torch.where(use_seg, t["tok_seg_len"][ep, fr],
                           t["tok_base_len"][ep, fr])
        return ids.long(), lens.long()

    def ar_forward(self, context, state, indices, weights, input_ids, key_padding):
        cfg = self.config
        if input_ids.shape[1] > self.ar_pos.shape[0]:
            raise ValueError(f"AR sequence {input_ids.shape[1]} exceeds positions")
        h = self.ar_embed(input_ids) + self.ar_pos[None, : input_ids.shape[1]] + state[:, None]
        quest_on = getattr(cfg, "v4_quest_enabled", False)
        if quest_on:
            if self.last_skill_summary is None:
                self.set_skill_from_prior()
            h = h + self.last_skill_summary[:, None]
        intermediates = []
        for layer, block in enumerate(self.ar_blocks):
            h, z = block(h, context, indices[layer], weights[layer], key_padding)
            intermediates.append(z)
        goal_mode = getattr(cfg, "dual_mode", None)
        if goal_mode is None:
            goal_mode = getattr(cfg, "goal_mode", None)
        if goal_mode in ("action_only", "router_and_action"):
            if self.last_goal is None:
                raise RuntimeError("encode_observation must precede ar_forward")
            film = getattr(self, "dual_action", None)
            if film is None:
                film = getattr(self, "goal_action")
            gamma, beta = film(self.last_goal.mean(1)).chunk(2, dim=-1)
            h = h + gamma[:, None] * self.final_norm(h) + beta[:, None]
        if quest_on:
            gamma_s, beta_s = self.skill_film(self.last_skill_summary).chunk(2, dim=-1)
            h = h + gamma_s[:, None] * self.final_norm(h) + beta_s[:, None]
        return self.ar_head(self.final_norm(h)), intermediates

    @torch.no_grad()
    def ar_predict_chunk(self, context, state, indices, weights):
        """Greedy AR decode constrained by the codec grammar
        (grammar(16, fps=10).next_token_mask), then the official
        streaming decoder. Returns normalized actions [B, 16, 7]."""
        cfg = self.config
        self._acodec2_ensure()
        codec = self._acodec2_codec_obj
        grammar = codec.grammar(16, fps=10)
        offset = self._acodec2_offset
        vocab = int(cfg.v4_ar_vocab)
        max_len = int(cfg.v4_ar_max_len)
        bsz = context.shape[0]
        dev = context.device
        prefixes: list[list[int]] = [[] for _ in range(bsz)]
        done = [False] * bsz
        for _ in range(max_len):
            if all(done):
                break
            seqs = []
            for r in range(bsz):
                seqs.append([vocab + 1] + [t - offset for t in prefixes[r]])
            width = max(len(s) for s in seqs)
            ids = torch.full((bsz, width), vocab, dtype=torch.long)
            for r, s in enumerate(seqs):
                ids[r, :len(s)] = torch.tensor(s, dtype=torch.long)
            ids = ids.to(dev)
            pad = ids == vocab
            logits, _inter = self.ar_forward(context, state, indices, weights,
                                             ids, pad)
            for r in range(bsz):
                if done[r]:
                    continue
                mask = grammar.next_token_mask(prefixes[r])
                allowed = torch.as_tensor(mask, device=dev)[offset:offset + vocab]
                row_logits = logits[r, len(seqs[r]) - 1, :vocab].clone()
                row_logits[~allowed] = float("-inf")
                nxt = int(row_logits.argmax().item())
                if not bool(allowed[nxt]):
                    done[r] = True
                    continue
                prefixes[r].append(nxt + offset)
                if grammar.is_complete(prefixes[r]):
                    done[r] = True
        rows = []
        for r in range(bsz):
            pref = prefixes[r]
            if pref:
                pref = list(grammar.complete_prefix(
                    pref, steps=grammar.covered_steps(pref)))
            rows.append([x - offset for x in pref])
        return self._acodec2_decode(rows, dev, context.dtype)

    def _acodec2_ensure(self) -> None:
        """Lazy-load the fitted codec + action stats (decode path)."""
        import os

        import numpy as np

        if self._acodec2_codec_obj is None:
            from transformers import AutoProcessor

            path = os.environ.get(
                "SERA_ACODEC2_TOKENIZER",
                os.path.expanduser(
                    "~/sera_v4_experiments/quest_probe/acodec2_tokenizer"),
            )
            self._acodec2_codec_obj = AutoProcessor.from_pretrained(
                path, action_space="single_eef_delta", trust_remote_code=True
            )
            spath = os.environ.get(
                "SERA_ACODEC2_STATS",
                os.path.expanduser(
                    "~/sera_v4_experiments/quest_probe/acodec2_action_stats.npz"),
            )
            st = np.load(spath)
            self._acodec2_mean = torch.tensor(st["mean"], dtype=torch.float32)
            self._acodec2_std = torch.tensor(st["std"], dtype=torch.float32)
        self._acodec2_load()

    def _acodec2_decode(self, seqs, device, dtype):
        import os

        import numpy as np

        self._acodec2_ensure()
        self._acodec2_load()
        codec = self._acodec2_codec_obj
        chunks = []
        for s in seqs:
            if len(s) == 0:
                phys = np.zeros((0, 7), dtype=np.float32)
            else:
                raw = [[t + self._acodec2_offset for t in s]]
                phys = np.asarray(codec.decode(raw, fps=10), dtype=np.float32)[0]
            if len(phys) < 16:
                tail = (np.repeat(phys[-1:], 16 - len(phys), axis=0)
                        if len(phys) else np.zeros((16 - len(phys), 7), np.float32))
                phys = np.concatenate([phys, tail], 0)
            phys = phys[:16]
            stored = np.empty_like(phys)
            stored[:, 0:3] = phys[:, 0:3] / 0.05
            stored[:, 3:6] = phys[:, 3:6] / 0.5
            stored[:, 6] = np.where(phys[:, 6] > 0.5, -1.0, 1.0)
            chunks.append(stored)
        arr = torch.tensor(np.stack(chunks), dtype=torch.float32, device=device)
        mean = self._acodec2_mean.to(device)
        std = self._acodec2_std.to(device)
        return ((arr - mean) / std).to(dtype)

    def encode_observation(self, images: Tensor, instructions: Sequence[str], state_raw: Tensor):
        b = images.shape[0]
        with torch.set_grad_enabled(torch.is_grad_enabled() and self.training and self._finetunes_vision):
            if self._finetunes_vision:
                cls, registers, patches = self.tips.vision_encoder(images.flatten(0, 1))
            else:
                encoded = self.tips.encode_image(images.flatten(0, 1))
                cls, registers, patches = encoded.cls_token, encoded.register_tokens, encoded.patch_tokens
            raw = torch.cat((cls, registers, patches), dim=1)
        raw = raw.view(b, 2, 1026, 768)
        vision = self.vision_norm(
            self.vision_projection(raw) + self.camera_embeddings[None, :, None]
        ).flatten(1, 2)
        ids, padding = self._tokenize(instructions, images.device)
        text = self.text_norm(self.text_projection(self._encode_text_tokens(ids, padding)))
        if getattr(self.config, "v4_align_lambda", 0.0) > 0:
            align_mask = (~padding).to(text.dtype)
            self.last_text_pooled = (text * align_mask[..., None]).sum(1) / align_mask.sum(
                1, keepdim=True
            ).clamp_min(1.0)
            self.last_vision_tokens = vision
        context = self.queries.unsqueeze(0).expand(b, -1, -1)
        for block in self.fusion:
            context = block(context, text, vision, padding)
        context = self.fusion_norm(context)
        state = self.state_mlp(state_raw)
        self.last_goal = self.goal(vision, text, state, padding)
        summary = self.last_goal.mean(1)
        v4_mode = getattr(self.config, "v4_moe_mode", "control")
        if v4_mode == "skillroute":
            text_mask = (~padding).to(text.dtype)
            text_pooled = (text * text_mask[..., None]).sum(1) / text_mask.sum(1, keepdim=True).clamp_min(1.0)
            router_input = torch.cat((context.mean(1), state, text_pooled), dim=-1)
        else:
            router_input = torch.cat((context.mean(1), state), dim=-1)
        self.last_router_input = router_input
        self.last_goal_summary = summary
        probabilities, indices, weights = [], [], []
        self.router_base_logits = []
        self.router_goal_deltas = []
        for layer_index, (router, delta_layer) in enumerate(zip(self.routers, self.goal_deltas, strict=True)):
            base = router(router_input)
            delta = delta_layer(summary) * self.config.goal_router_scale
            self.router_base_logits.append(base)
            self.router_goal_deltas.append(delta)
            logits = base + delta if self.config.goal_mode in ("router_only", "router_and_action") else base
            p = logits.softmax(-1)
            if v4_mode == "bias":
                _, i = (logits + self.router_bias[layer_index]).topk(4, dim=-1)
                w = p.gather(-1, i)
                if self.training and torch.is_grad_enabled():
                    with torch.no_grad():
                        load = torch.zeros(8, device=i.device, dtype=torch.float32)
                        load.scatter_add_(0, i.reshape(-1).long(), torch.ones(i.numel(), device=i.device))
                        load = load / float(i.numel())
                        ema = self.router_load_ema[layer_index]
                        ema.mul_(0.99).add_(load * 0.01)
                        bias = self.router_bias[layer_index]
                        bias.add_(0.01 * (0.5 - ema))
                        bias.clamp_(-3.0, 3.0)
            else:
                w, i = p.topk(4, dim=-1)
            probabilities.append(p)
            indices.append(i)
            weights.append(w)
        self.last_router_probabilities = probabilities
        self.last_router_indices = indices
        return context, state, probabilities, indices, weights

    def velocity_prediction(self, x, tau, context, state, indices, weights, action_padding=None):
        h = (
            self.action_projection(x)
            + self.action_positions[None]
            + self.time_mlp(self.time_embedding(tau))[:, None]
            + state[:, None]
        )
        quest_on = getattr(self.config, "v4_quest_enabled", False)
        if quest_on:
            if self.last_skill_summary is None:
                self.set_skill_from_prior()
            h = h + self.last_skill_summary[:, None]
        intermediates = []
        for layer, block in enumerate(self.blocks):
            h, z = block(h, context, indices[layer], weights[layer], action_padding)
            intermediates.append(z)
        if self.config.goal_mode in ("action_only", "router_and_action"):
            if self.last_goal is None:
                raise RuntimeError("encode_observation must precede velocity_prediction")
            gamma, beta = self.goal_action(self.last_goal.mean(1)).chunk(2, dim=-1)
            h = h + gamma[:, None] * self.final_norm(h) + beta[:, None]
        if quest_on:
            gamma_s, beta_s = self.skill_film(self.last_skill_summary).chunk(2, dim=-1)
            h = h + gamma_s[:, None] * self.final_norm(h) + beta_s[:, None]
        return self.velocity(self.final_norm(h)), intermediates


class SERAVLAV3Policy(SERAVLAPolicy):
    config_class = SERAVLAV3Config
    name = "sera_vla_v3"

    def __init__(self, config: SERAVLAV3Config, **kwargs) -> None:
        PreTrainedPolicy.__init__(self, config)
        config.validate_features()
        self.config = config
        self.model = SERAVLAV3Model(config)
        if config.training_stage == "goal_only":
            for name, parameter in self.model.named_parameters():
                if not name.startswith(("goal.", "goal_deltas.", "goal_action.")):
                    parameter.requires_grad_(False)
        self.reset()

    def forward(self, batch: dict):
        loss, metrics = super().forward(batch)
        for block, (probabilities, indices) in enumerate(
            zip(self.model.last_router_probabilities, self.model.last_router_indices, strict=True)
        ):
            p = probabilities.detach().float()
            counts = torch.bincount(indices.detach().flatten(), minlength=8).float()
            metrics[f"router_{block}_entropy"] = float(-(p * p.clamp_min(1e-8).log()).sum(-1).mean())
            metrics[f"router_{block}_min_topk_count"] = float(counts.min())
            metrics[f"router_{block}_max_topk_count"] = float(counts.max())
            for expert in range(8):
                metrics[f"router_{block}_expert_{expert}_topk_count"] = float(counts[expert])
                metrics[f"router_{block}_expert_{expert}_importance"] = float(p[:, expert].mean())
        return loss, metrics