File size: 10,173 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
#!/usr/bin/env python3
"""E1 patch: QueST skill-token conditioning for arm sera-v4-q-quest.

Adds (all defaults OFF; defaults-off reproduces arm D exactly):
- config fields v4_quest_enabled / v4_quest_lambda,
- SERAVLAV3Model skill modules: skill_embed/skill_pos (code -> 512
  summary), skill_film (zero-init FiLM, mirrors the goal branch),
  skill_prior (autoregressive prior over the 8 FSQ codes from the
  skillroute router context), skill_decode_table buffer,
- velocity_prediction: skill summary added to h pre-blocks and a
  skill FiLM applied post-blocks (after the goal FiLM),
- policy forward: teacher-forced codes from batch["skill_codes"],
  prior NLL term lambda * CE; predict_action_chunk: prior greedy
  decode. If velocity_prediction is reached with no codes set
  (e.g. measurement hooks), it falls back to the prior prediction.
Exact-match replacements; every count is asserted.
"""
from pathlib import Path

PKG = Path.home() / "lerobot/src/lerobot/policies/sera_vla_v3"


def patch(path: Path, pairs: list[tuple[str, str]]) -> None:
    text = path.read_text()
    for old, new in pairs:
        n = text.count(old)
        assert n == 1, f"{path.name}: anchor found {n}x: {old[:70]!r}"
        text = text.replace(old, new)
    path.write_text(text)
    print(f"patched {path.name}: {len(pairs)} replacements")


cfg_pairs = [
    (
        "    v4_intracl_tau: float = 0.1\n",
        "    v4_intracl_tau: float = 0.1\n"
        "    v4_quest_enabled: bool = False\n"
        "    v4_quest_lambda: float = 0.0\n",
    ),
    (
        "        if self.v4_intracl_tau <= 0:\n"
        "            raise ValueError(f\"Invalid v4_intracl_tau: {self.v4_intracl_tau}\")\n",
        "        if self.v4_intracl_tau <= 0:\n"
        "            raise ValueError(f\"Invalid v4_intracl_tau: {self.v4_intracl_tau}\")\n"
        "        if self.v4_quest_lambda < 0:\n"
        "            raise ValueError(f\"Invalid v4_quest_lambda: {self.v4_quest_lambda}\")\n"
        "        if self.v4_quest_enabled and self.v4_moe_mode != \"skillroute\":\n"
        "            raise ValueError(\"v4_quest_enabled requires v4_moe_mode='skillroute'\")\n",
    ),
]

SKILL_PRIOR = '''

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
'''

INIT_ADD = '''
        # 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
        _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)

    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
'''

v3_pairs = [
    # SkillPrior class: insert before SERAVLAV3Model definition.
    (
        "class SERAVLAV3Model(SERAVLAModel):",
        SKILL_PRIOR.strip("\n") + "\n\n\nclass SERAVLAV3Model(SERAVLAModel):",
    ),
    # Skill modules at the end of SERAVLAV3Model.__init__.
    (
        "        self.last_goal_summary: Tensor | None = None\n",
        "        self.last_goal_summary: Tensor | None = None\n" + INIT_ADD,
    ),
    # velocity_prediction: skill summary added to h before the blocks.
    (
        "            + state[:, None]\n        )\n        intermediates = []",
        "            + state[:, None]\n        )\n"
        "        quest_on = getattr(self.config, \"v4_quest_enabled\", False)\n"
        "        if quest_on:\n"
        "            if self.last_skill_summary is None:\n"
        "                self.set_skill_from_prior()\n"
        "            h = h + self.last_skill_summary[:, None]\n"
        "        intermediates = []",
    ),
    # velocity_prediction: skill FiLM after the goal FiLM, before return.
    (
        "            h = h + gamma[:, None] * self.final_norm(h) + beta[:, None]\n"
        "        return self.velocity(self.final_norm(h)), intermediates",
        "            h = h + gamma[:, None] * self.final_norm(h) + beta[:, None]\n"
        "        if quest_on:\n"
        "            gamma_s, beta_s = self.skill_film(self.last_skill_summary).chunk(2, dim=-1)\n"
        "            h = h + gamma_s[:, None] * self.final_norm(h) + beta_s[:, None]\n"
        "        return self.velocity(self.final_norm(h)), intermediates",
    ),
]

base_pairs = [
    # forward: teacher-forced codes right after encode_observation.
    (
        "        context, state, probabilities, indices, weights = self.model.encode_observation(\n"
        "            images, language, state_raw\n"
        "        )\n"
        "        action = batch[ACTION]",
        "        context, state, probabilities, indices, weights = self.model.encode_observation(\n"
        "            images, language, state_raw\n"
        "        )\n"
        "        quest_on = getattr(self.config, \"v4_quest_enabled\", False)\n"
        "        quest_codes = None\n"
        "        if quest_on:\n"
        "            quest_codes = self.model.quest_codes_for(batch)\n"
        "            self.model.set_skill_from_codes(quest_codes)\n"
        "        action = batch[ACTION]",
    ),
    # forward: prior NLL term before the return.
    (
        "        intracl_lambda = getattr(self.config, \"v4_intracl_lambda\", 0.0)\n"
        "        if intracl_lambda > 0:\n"
        "            icl = self._intracl_loss(language)\n"
        "            total = total + intracl_lambda * icl\n"
        "            metrics[\"intracl_loss\"] = icl.item()\n"
        "        return total, metrics",
        "        intracl_lambda = getattr(self.config, \"v4_intracl_lambda\", 0.0)\n"
        "        if intracl_lambda > 0:\n"
        "            icl = self._intracl_loss(language)\n"
        "            total = total + intracl_lambda * icl\n"
        "            metrics[\"intracl_loss\"] = icl.item()\n"
        "        quest_lambda = getattr(self.config, \"v4_quest_lambda\", 0.0)\n"
        "        if quest_on:\n"
        "            logits = self.model.skill_prior(self.model.last_router_input, quest_codes)\n"
        "            nll = F.cross_entropy(logits.reshape(-1, 1000), quest_codes.reshape(-1))\n"
        "            metrics[\"prior_nll\"] = nll.item()\n"
        "            metrics[\"prior_acc\"] = float((logits.argmax(-1) == quest_codes).float().mean())\n"
        "            if quest_lambda > 0:\n"
        "                total = total + quest_lambda * nll\n"
        "                metrics[\"prior_term\"] = (quest_lambda * nll).item()\n"
        "        return total, metrics",
    ),
    # predict_action_chunk: prior-predicted tokens at inference.
    (
        "        context, state, _, indices, weights = self.model.encode_observation(images, language, state_raw)\n"
        "        x = torch.randn(images.shape[0], 16, self.config.action_dim, device=images.device, dtype=state.dtype)",
        "        context, state, _, indices, weights = self.model.encode_observation(images, language, state_raw)\n"
        "        if getattr(self.config, \"v4_quest_enabled\", False):\n"
        "            self.model.set_skill_from_prior()\n"
        "        x = torch.randn(images.shape[0], 16, self.config.action_dim, device=images.device, dtype=state.dtype)",
    ),
]

patch(PKG / "configuration_sera_vla_v3.py", cfg_pairs)
patch(PKG / "modeling_sera_vla_v3.py", v3_pairs)
patch(PKG / "modeling_base.py", base_pairs)
print("quest patch applied")