File size: 20,624 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 | #!/usr/bin/env python3
"""SERA-CC C3 patch: capability-code executor (SPEC sera_cc_v1,
IMPL_PLAN.md C3; applies on top of the quest + questfix + AR patches).
Defaults OFF (cc_enabled=False): every existing arm behaves exactly
as before β the new modules are constructed but never called, the
MoE stack is untouched, and check_cc.py's defaults-off test is the
arbiter (loss + velocity vs the pre-patch reference capture).
When enabled, ONLY the executor's conditioning/architecture change:
- config gains the cc_* fields (IMPL_PLAN SS0 table);
- SERAVLAV3Model gains cc_embed (zero-init embedding) + cc_film
(zero-init FiLM, mirrors skill_film) and a model-side code table
(cc_codes_for / cc_pred_codes_for, the quest_codes_for pattern);
- the 4 MoEBlocks are swapped for DenseBlocks (same shell: norms,
self-attn, cross-attn; FFN = shared SwiGLU 1344 + dense SwiGLU
2688, i.e. the MoE block's per-token compute with routing
removed) β ONLY under cc_enabled, so defaults-off state dicts and
behaviour are bit-identical;
- encode_observation computes the Fusion context vision-only
(text replaced by a constant zero tensor, padding mask cleared β
an all-masked attention row would be NaN; constant tokens are the
finite padding-only path) and skips the goal branch + router
loop: the capability code is structurally the ONLY task channel;
- velocity_prediction: code summary added to h pre-blocks, cc FiLM
post-blocks (same two injection points as the quest graft), goal
FiLM disabled;
- training forward: GT codes from the table + cc_conditioning
(clone of questfix_conditioning: scheduled sampling anneals the
source from GT codes to predicted codes β the frozen T1 encoder
applied to partial segments, Phase A's inference-like source β
over cc_p_gt_steps; code dropout zeroes the summary with prob
cc_code_dropout). Loss = FM only (no routers to balance, no
routed intermediates to specialize).
Naming-agnostic discipline (the naming bomb): the goal-branch
tokens in the file text are never anchored on literally β the one
place that must touch the goal FiLM guard uses a regex pair that
captures whichever of (goal|dual) the file actually carries and
re-emits it verbatim.
Exact-match replacements otherwise; every count is asserted.
"""
import re
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")
def patch_regex(path: Path, pairs: list[tuple[str, str]]) -> None:
text = path.read_text()
for pattern, repl in pairs:
text, n = re.subn(pattern, repl, text)
assert n == 1, f"{path.name}: regex anchor found {n}x: {pattern[:70]!r}"
path.write_text(text)
print(f"patched {path.name}: {len(pairs)} regex replacements")
cfg_pairs = [
(
" v4_ar_max_len: int = 96\n",
" v4_ar_max_len: int = 96\n"
" cc_enabled: bool = False\n"
" cc_n_codes: int = 64\n"
" cc_z_dim: int = 64\n"
" cc_lambda_fwd: float = 1.0\n"
" cc_lambda_con: float = 1.0\n"
" cc_code_dropout: float = 0.15\n"
" cc_p_gt_steps: int = 3000\n"
" cc_tau: float = 0.5\n"
" cc_beam: int = 8\n"
" cc_max_chain: int = 6\n",
),
(
" if self.v4_ar_max_len <= 0:\n"
" raise ValueError(f\"Invalid v4_ar_max_len: {self.v4_ar_max_len}\")\n",
" if self.v4_ar_max_len <= 0:\n"
" raise ValueError(f\"Invalid v4_ar_max_len: {self.v4_ar_max_len}\")\n"
" if self.cc_enabled and self.v4_quest_enabled:\n"
" raise ValueError(\"cc_enabled is incompatible with v4_quest_enabled\")\n"
" if self.cc_enabled and self.v4_ar_enabled:\n"
" raise ValueError(\"cc_enabled is incompatible with v4_ar_enabled\")\n"
" if self.cc_n_codes <= 0:\n"
" raise ValueError(f\"Invalid cc_n_codes: {self.cc_n_codes}\")\n"
" if self.cc_z_dim <= 0:\n"
" raise ValueError(f\"Invalid cc_z_dim: {self.cc_z_dim}\")\n"
" if self.cc_lambda_fwd < 0 or self.cc_lambda_con < 0:\n"
" raise ValueError(\"Invalid cc_lambda_fwd/cc_lambda_con\")\n"
" if self.cc_p_gt_steps <= 0:\n"
" raise ValueError(f\"Invalid cc_p_gt_steps: {self.cc_p_gt_steps}\")\n"
" if not 0.0 <= self.cc_code_dropout <= 1.0:\n"
" raise ValueError(f\"Invalid cc_code_dropout: {self.cc_code_dropout}\")\n"
" if not 0.0 <= self.cc_tau <= 1.0:\n"
" raise ValueError(f\"Invalid cc_tau: {self.cc_tau}\")\n"
" if self.cc_beam <= 0:\n"
" raise ValueError(f\"Invalid cc_beam: {self.cc_beam}\")\n"
" if self.cc_max_chain <= 0:\n"
" raise ValueError(f\"Invalid cc_max_chain: {self.cc_max_chain}\")\n",
),
]
DENSE_BLOCK = '''
class DenseBlock(nn.Module):
"""SERA-CC C3: dense twin of MoEBlock. Same shell (3 norms,
self-attention, cross-attention to the trunk context) but the
routed MoE FFN is replaced by a dense SwiGLU path whose width
matches the MoE block's per-token compute: shared expert 1344
+ one dense expert 2688 (= the 4 routed experts of 672 the MoE
block applies per token). No router: indices/weights are
accepted and ignored so the velocity_prediction call shape is
unchanged. Returns (h, z) with z the dense expert's pre-down
activations, mirroring MoEBlock's (output, z) contract."""
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.dense = SwiGLUExpert(2688)
def forward(
self, x: Tensor, context: Tensor, indices: Tensor | None = None,
weights: Tensor | None = None, action_padding: Tensor | None = None,
) -> tuple[Tensor, Tensor]:
n = self.norms[0](x)
x = x + self.self_attn(n, n, n, key_padding_mask=action_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)
dense, z = self.dense(u)
return x + shared + dense, z
'''
CC_INIT = '''
# SERA-CC C3: capability-code conditioning. cc_embed and
# cc_film are constructed always (defaults-off behaviour is
# unchanged β they are never called when cc_enabled is
# false); both are zero-init, mirroring the quest graft, so
# the conditioning pathway is exactly inert at init. The
# dense block swap happens ONLY under cc_enabled, keeping
# the MoE stack (and its state dict) bit-identical when off.
self.cc_embed = nn.Embedding(int(getattr(config, "cc_n_codes", 64)), 512)
nn.init.zeros_(self.cc_embed.weight)
self.cc_film = nn.Linear(512, 1024)
nn.init.zeros_(self.cc_film.weight)
nn.init.zeros_(self.cc_film.bias)
self.last_cc_summary: Tensor | None = None
self.last_cc_codes: Tensor | None = None
self._cc_table: Tensor | None = None
self._cc_pred_table: Tensor | None = None
if getattr(config, "cc_enabled", False):
self.blocks = nn.ModuleList(DenseBlock() for _ in range(4))
for _blk in self.blocks:
_blk.apply(_init_new)
'''
CC_METHODS = '''
# ---- SERA-CC C3: capability-code table + conditioning ----
def _cc_load(self) -> None:
if self._cc_table is not None:
return
import os
import numpy as np
path = os.environ.get(
"SERA_CC_CODES",
os.path.expanduser("~/sera_v4_experiments/sera_cc/codes_cc.npy"),
)
self._cc_table = torch.from_numpy(np.load(path).astype(np.int64))
ppath = os.environ.get(
"SERA_CC_PRED_CODES",
os.path.expanduser("~/sera_v4_experiments/sera_cc/codes_cc_pred.npy"),
)
if os.path.exists(ppath):
self._cc_pred_table = torch.from_numpy(
np.load(ppath).astype(np.int64))
def cc_codes_for(self, batch: dict) -> Tensor:
"""GT capability code of the segment containing each
sample's anchor frame (T1 encoder codes, reused verbatim),
looked up from the model-side table keyed by
(episode_index, frame_index) β the quest_codes_for pattern
(the training preprocessor drops unknown per-sample keys,
so codes cannot ride in the batch)."""
self._cc_load()
ep = batch["episode_index"]
fr = batch["frame_index"]
out = self._cc_table[ep.long().cpu(), fr.long().cpu()]
return out.to(ep.device)
def cc_pred_codes_for(self, batch: dict) -> Tensor:
"""Predicted codes: the frozen T1 capability encoder applied
to each frame's PARTIAL segment (segment start -> current
frame), precomputed into the same table layout. Phase A's
inference-like code source for scheduled sampling (the C6
sequencer does not exist yet in Phase A)."""
self._cc_load()
if self._cc_pred_table is None:
raise RuntimeError("predicted-code table missing (SERA_CC_PRED_CODES)")
ep = batch["episode_index"]
fr = batch["frame_index"]
out = self._cc_pred_table[ep.long().cpu(), fr.long().cpu()]
return out.to(ep.device)
def cc_summary(self, codes: Tensor) -> Tensor:
return self.cc_embed(codes.long())
def set_cc_from_codes(self, codes: Tensor) -> None:
self.last_cc_codes = codes.long()
self.last_cc_summary = self.cc_summary(codes)
def cc_conditioning(self, gt_codes: Tensor, batch: dict) -> dict | None:
"""Clone of questfix_conditioning for capability codes:
scheduled sampling + code dropout on the conditioning
summary. Called from the policy training forward AFTER
set_cc_from_codes(gt_codes). The conditioning source
anneals from GT codes to predicted codes (partial-segment
encoder table) with p_gt linear 1 -> 0 over cc_p_gt_steps;
code dropout then zeroes whole per-sample summaries with
prob cc_code_dropout. No-op (returns None) outside training
(eval mode or no_grad), keeping inference behaviour exact.
"""
if not (self.training and torch.is_grad_enabled()):
return None
cfg = self.config
step = int(getattr(self, "cc_step", 0))
self.cc_step = step + 1
span = max(1, int(getattr(cfg, "cc_p_gt_steps", 3000)))
p_gt = max(0.0, 1.0 - step / span)
src_pred = 0.0
if float(torch.rand((), device=gt_codes.device)) >= p_gt:
self.set_cc_from_codes(self.cc_pred_codes_for(batch))
src_pred = 1.0
drop = float(getattr(cfg, "cc_code_dropout", 0.15))
drop_frac = 0.0
if drop > 0.0:
keep = (torch.rand(self.last_cc_summary.shape[0],
device=self.last_cc_summary.device)
>= drop).to(self.last_cc_summary.dtype)
drop_frac = float(1.0 - keep.float().mean())
self.last_cc_summary = self.last_cc_summary * keep[:, None]
return {"cc_p_gt": float(p_gt),
"cc_src_pred": src_pred,
"cc_drop_frac": drop_frac,
"cc_step": float(step)}
'''
v3_pairs = [
# DenseBlock class: insert before SERAVLAV3Model definition.
(
"class SERAVLAV3Model(SERAVLAModel):",
DENSE_BLOCK.strip("\n") + "\n\n\nclass SERAVLAV3Model(SERAVLAModel):",
),
# CC modules at the end of SERAVLAV3Model.__init__ (after AR init).
(
" self._acodec2_mean: Tensor | None = None\n"
" self._acodec2_std: Tensor | None = None\n",
" self._acodec2_mean: Tensor | None = None\n"
" self._acodec2_std: Tensor | None = None\n"
+ CC_INIT,
),
# CC methods before encode_observation.
(
" def encode_observation(self, images: Tensor, instructions: Sequence[str], state_raw: Tensor):",
CC_METHODS.strip("\n")
+ "\n\n def encode_observation(self, images: Tensor, instructions: Sequence[str], state_raw: Tensor):",
),
# encode_observation: vision-only Fusion under CC.
(
" text = self.text_norm(self.text_projection(self._encode_text_tokens(ids, padding)))\n",
" text = self.text_norm(self.text_projection(self._encode_text_tokens(ids, padding)))\n"
" cc_on = getattr(self.config, \"cc_enabled\", False)\n"
" if cc_on:\n"
" # SERA-CC: the instruction must not reach the executor.\n"
" # Fusion context is computed vision-only: the text\n"
" # tokens are replaced by a constant (zeros) and the\n"
" # padding mask is cleared, so neither text content\n"
" # nor instruction length can influence the context.\n"
" # (An all-masked attention row would be NaN; constant\n"
" # tokens are the finite padding-only path.)\n"
" text = torch.zeros_like(text)\n"
" padding = torch.zeros_like(padding)\n",
),
# encode_observation: skip goal branch + router loop under CC.
(
" context = self.fusion_norm(context)\n"
" state = self.state_mlp(state_raw)\n",
" context = self.fusion_norm(context)\n"
" state = self.state_mlp(state_raw)\n"
" if cc_on:\n"
" # SERA-CC: goal branch and router loop are skipped β\n"
" # the capability code is the only task channel.\n"
" self.last_goal = None\n"
" self.last_router_input = torch.cat((context.mean(1), state), dim=-1)\n"
" self.last_goal_summary = None\n"
" self.last_router_probabilities = []\n"
" self.last_router_indices = []\n"
" return context, state, [], [], []\n",
),
# velocity_prediction: CC injection pre-blocks + dense loop.
(
" 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 = []\n"
" for layer, block in enumerate(self.blocks):\n"
" h, z = block(h, context, indices[layer], weights[layer], action_padding)\n"
" intermediates.append(z)\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"
" cc_on = getattr(self.config, \"cc_enabled\", False)\n"
" if cc_on:\n"
" if self.last_cc_summary is None:\n"
" # No code set (measurement hooks / pre-C6 calls):\n"
" # the conditioning is exactly inert (zero summary).\n"
" self.last_cc_summary = torch.zeros(\n"
" h.shape[0], 512, device=h.device, dtype=h.dtype)\n"
" h = h + self.last_cc_summary[:, None]\n"
" intermediates = []\n"
" if cc_on:\n"
" for block in self.blocks:\n"
" h, z = block(h, context, None, None, action_padding)\n"
" intermediates.append(z)\n"
" else:\n"
" for layer, block in enumerate(self.blocks):\n"
" h, z = block(h, context, indices[layer], weights[layer], action_padding)\n"
" intermediates.append(z)\n",
),
# velocity_prediction: CC FiLM after the quest FiLM, before return.
(
" 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",
" 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"
" if cc_on:\n"
" gamma_c, beta_c = self.cc_film(self.last_cc_summary).chunk(2, dim=-1)\n"
" h = h + gamma_c[:, None] * self.final_norm(h) + beta_c[:, None]\n"
" return self.velocity(self.final_norm(h)), intermediates",
),
]
# The goal FiLM guard line carries the naming-bomb token: capture
# whichever of (goal|dual) the file actually has and re-emit it.
v3_regex_pairs = [
(
r" if self\.config\.(goal|dual)_mode in \(\"action_only\", \"router_and_action\"\):",
r' if not cc_on and self.config.\g<1>_mode in ("action_only", "router_and_action"):',
),
]
base_pairs = [
# forward: CC conditioning setup after the questfix setup.
(
" questfix_metrics = None\n"
" if quest_on and getattr(self.config, \"v4_questfix_enabled\", False):\n"
" questfix_metrics = self.model.questfix_conditioning(quest_codes)\n",
" questfix_metrics = None\n"
" if quest_on and getattr(self.config, \"v4_questfix_enabled\", False):\n"
" questfix_metrics = self.model.questfix_conditioning(quest_codes)\n"
" cc_on = getattr(self.config, \"cc_enabled\", False)\n"
" cc_metrics = None\n"
" if cc_on:\n"
" cc_codes = self.model.cc_codes_for(batch)\n"
" self.model.set_cc_from_codes(cc_codes)\n"
" cc_metrics = self.model.cc_conditioning(cc_codes, batch)\n",
),
# forward: CC FM-only branch before the FM else-branch.
(
" else:\n"
" noise = torch.randn_like(action)\n",
" elif cc_on:\n"
" # SERA-CC C3: FM loss only β MoE is removed, so there\n"
" # are no router probabilities to balance and no\n"
" # routed intermediates to specialize. Conditioning\n"
" # (GT/predicted codes + dropout) was set up above.\n"
" noise = torch.randn_like(action)\n"
" tau = torch.rand(action.shape[0], device=action.device, dtype=action.dtype)\n"
" x_tau = (1 - tau[:, None, None]) * noise + tau[:, None, None] * action\n"
" prediction, intermediates = self.model.velocity_prediction(\n"
" x_tau, tau, context, state, indices, weights, ~valid\n"
" )\n"
" target = action - noise\n"
" fm = ((prediction - target).square() * valid[..., None]).sum() / (\n"
" self.config.action_dim * valid.sum()\n"
" ).clamp_min(1)\n"
" total = fm\n"
" metrics = {\"flow_matching_loss\": fm.item()}\n"
" if cc_metrics is not None:\n"
" metrics.update(cc_metrics)\n"
" else:\n"
" noise = torch.randn_like(action)\n",
),
]
patch(PKG / "configuration_sera_vla_v3.py", cfg_pairs)
patch(PKG / "modeling_sera_vla_v3.py", v3_pairs)
patch_regex(PKG / "modeling_sera_vla_v3.py", v3_regex_pairs)
patch(PKG / "modeling_base.py", base_pairs)
print("cc patch applied")
|