File size: 7,516 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 | #!/usr/bin/env python3
"""Arm Q2 patch: sera-v4-q2-questfix — fix the train/test mismatch
of the QueST token conditioning source (SPEC in WORKLOG, locked
2026-11-18 21:09 by Young's order; applies ON TOP of the E1 quest
patch, which must already be applied).
Defaults OFF (v4_questfix_enabled=False): every arm, including Q's
own checkpoint at inference/eval, behaves exactly as before.
When enabled, ONLY the training forward (train mode + grad
enabled) changes, at the single point where the conditioning
summary is set from the GT codes:
- FIX 1 scheduled sampling: per training step, with prob p_gt
keep the GT-code summary; otherwise replace it with the prior's
GREEDY codes decoded from last_router_input (the exact
inference-time context). p_gt anneals linearly 1 -> 0 over
v4_questfix_p_gt_steps counted training forwards (= the run's
micro-steps), then stays 0. The prior NLL target is untouched
(always GT codes).
- FIX 2 token dropout: independently, per sample with prob
v4_questfix_dropout, the summary is zeroed (s := 0), keeping
the policy's no-token mode in-distribution.
Eval-mode forwards keep Q's GT conditioning exactly, so
eval_loss stays comparable across Q / Q2.
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_quest_enabled: bool = False\n"
" v4_quest_lambda: float = 0.0\n",
" v4_quest_enabled: bool = False\n"
" v4_quest_lambda: float = 0.0\n"
" v4_questfix_enabled: bool = False\n"
" v4_questfix_p_gt_steps: int = 3000\n"
" v4_questfix_dropout: float = 0.15\n"
" v4_questfix_p_gt_override: float = -1.0\n",
),
(
" if self.v4_quest_enabled and self.v4_moe_mode != \"skillroute\":\n"
" raise ValueError(\"v4_quest_enabled requires v4_moe_mode='skillroute'\")\n",
" if self.v4_quest_enabled and self.v4_moe_mode != \"skillroute\":\n"
" raise ValueError(\"v4_quest_enabled requires v4_moe_mode='skillroute'\")\n"
" if self.v4_questfix_enabled and not self.v4_quest_enabled:\n"
" raise ValueError(\"v4_questfix_enabled requires v4_quest_enabled\")\n"
" if self.v4_questfix_p_gt_steps <= 0:\n"
" raise ValueError(f\"Invalid v4_questfix_p_gt_steps: {self.v4_questfix_p_gt_steps}\")\n"
" if not 0.0 <= self.v4_questfix_dropout <= 1.0:\n"
" raise ValueError(f\"Invalid v4_questfix_dropout: {self.v4_questfix_dropout}\")\n"
" if not -1.0 <= self.v4_questfix_p_gt_override <= 1.0:\n"
" raise ValueError(f\"Invalid v4_questfix_p_gt_override: {self.v4_questfix_p_gt_override}\")\n",
),
]
QUESTFIX_METHOD = '''
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)}
'''
v3_pairs = [
# questfix_conditioning: append after set_skill_from_prior.
(
" def set_skill_from_prior(self) -> Tensor:\n"
" if self.last_router_input is None:\n"
" raise RuntimeError(\"encode_observation must precede prior prediction\")\n"
" codes = self.skill_prior.greedy(self.last_router_input)\n"
" self.set_skill_from_codes(codes)\n"
" return codes\n",
" def set_skill_from_prior(self) -> Tensor:\n"
" if self.last_router_input is None:\n"
" raise RuntimeError(\"encode_observation must precede prior prediction\")\n"
" codes = self.skill_prior.greedy(self.last_router_input)\n"
" self.set_skill_from_codes(codes)\n"
" return codes\n"
+ QUESTFIX_METHOD,
),
]
base_pairs = [
# forward: apply the fix right after the GT conditioning is set.
(
" 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",
" 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"
" 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",
),
# forward: merge the fix metrics next to the prior metrics.
(
" if quest_lambda > 0:\n"
" total = total + quest_lambda * nll\n"
" metrics[\"prior_term\"] = (quest_lambda * nll).item()\n",
" if quest_lambda > 0:\n"
" total = total + quest_lambda * nll\n"
" metrics[\"prior_term\"] = (quest_lambda * nll).item()\n"
" if questfix_metrics is not None:\n"
" metrics.update(questfix_metrics)\n",
),
]
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("questfix patch applied")
|