#!/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")