trace-vla-code / code /sera_v4 /tools /apply_cc_patch.py
phammminhhieu's picture
TRACE-VLA code snapshot 2026-11-22 11:47 +07: 456 canonical files + SHA256 manifest + sync report
b4396f0 verified
Raw History Blame Contribute Delete
20.6 kB
#!/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")