trace-vla-code / code /sera_v4 /tools /apply_quest_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
10.2 kB
#!/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")