#!/usr/bin/env python3 """Apply the ROUND-2 patches (arms G/H/I) to the sera_vla_v3 package. Same discipline as the earlier patch scripts: fails loudly if an anchor is missing or already patched. Every change is guarded by a config field that defaults to OFF, so all existing arms (A-F, E) are unaffected: v4_mi_gamma = 0.0 (arm G: MI routing loss replaces balance) v4_ortho_outputs = False (arm H: orthogonalize expert outputs) v4_intracl_lambda = 0.0 (arm I: contrastive loss on router logits) Design fixed in round2_probe/SPEC.md (2026-11-18, before training).""" import pathlib, sys ROOT = pathlib.Path.home() / "lerobot/src/lerobot/policies/sera_vla_v3" def patch(fname, old, new, count=1): p = ROOT / fname text = p.read_text() if new in text: print(f"SKIP {fname}: already patched") return if text.count(old) != count: print(f"FAIL {fname}: anchor found {text.count(old)} times (expected {count})") sys.exit(1) p.write_text(text.replace(old, new)) print(f"OK {fname}") # --- 1. configuration: new fields + validation --- patch( "configuration_sera_vla_v3.py", " v4_entropy_lambda: float = 0.0\n", " v4_entropy_lambda: float = 0.0\n" " v4_mi_gamma: float = 0.0\n" " v4_ortho_outputs: bool = False\n" " v4_intracl_lambda: float = 0.0\n" " v4_intracl_tau: float = 0.1\n", ) patch( "configuration_sera_vla_v3.py", ''' if self.v4_entropy_lambda < 0: raise ValueError(f"Invalid v4_entropy_lambda: {self.v4_entropy_lambda}")''', ''' if self.v4_entropy_lambda < 0: raise ValueError(f"Invalid v4_entropy_lambda: {self.v4_entropy_lambda}") if self.v4_mi_gamma < 0: raise ValueError(f"Invalid v4_mi_gamma: {self.v4_mi_gamma}") if self.v4_intracl_lambda < 0: raise ValueError(f"Invalid v4_intracl_lambda: {self.v4_intracl_lambda}") if self.v4_intracl_tau <= 0: raise ValueError(f"Invalid v4_intracl_tau: {self.v4_intracl_tau}")''', ) # --- 2. modeling_sera_vla_v3.py: stash router input + goal summary --- patch( "modeling_sera_vla_v3.py", """ self.last_vision_tokens: Tensor | None = None self.last_text_pooled: Tensor | None = None """, """ self.last_vision_tokens: Tensor | None = None self.last_text_pooled: Tensor | None = None self.last_router_input: Tensor | None = None self.last_goal_summary: Tensor | None = None """, ) patch( "modeling_sera_vla_v3.py", """ probabilities, indices, weights = [], [], [] self.router_base_logits = [] """, """ self.last_router_input = router_input self.last_goal_summary = summary probabilities, indices, weights = [], [], [] self.router_base_logits = [] """, ) # --- 3. modeling_base.py: MoEBlock ortho flag + orthogonalizer --- patch( "modeling_base.py", """ self.shared = SwiGLUExpert(1344) self.experts = nn.ModuleList(SwiGLUExpert(672) for _ in range(8)) """, """ self.shared = SwiGLUExpert(1344) self.experts = nn.ModuleList(SwiGLUExpert(672) for _ in range(8)) self.ortho_outputs = False """, ) patch( "modeling_base.py", """ def forward( self, x: Tensor, context: Tensor, indices: Tensor, weights: Tensor, action_padding: Tensor | None ) -> tuple[Tensor, Tensor | None]: """, """ @staticmethod def _orthogonalize(stacked: Tensor) -> Tensor: # Round-2 arm H: stacked [B, T, K, D] selected expert outputs -> # per (b, t) an orthonormal set (Gram-Schmidt via QR of O^T, # sign-stabilized by diag(R)), rescaled by the mean original # vector norm so the routed output scale is preserved. o = stacked.float() norms = o.norm(dim=-1) scale = norms.mean(dim=-1, keepdim=True) q, r = torch.linalg.qr(o.transpose(-1, -2)) signs = torch.sign(torch.diagonal(r, dim1=-2, dim2=-1)) signs = torch.where(signs == 0, torch.ones_like(signs), signs) q = q * signs[:, :, None, :] return (q.transpose(-1, -2) * scale[..., None]).to(stacked.dtype) def forward( self, x: Tensor, context: Tensor, indices: Tensor, weights: Tensor, action_padding: Tensor | None ) -> tuple[Tensor, Tensor | None]: """, ) patch( "modeling_base.py", """ u = self.norms[2](x) shared, _ = self.shared(u) routed = torch.zeros_like(x) selected_z: list[Tensor] = [] for batch_index in range(x.shape[0]): sample_z = [] for slot in range(4): expert_index = int(indices[batch_index, slot]) output, z = self.experts[expert_index](u[batch_index : batch_index + 1]) routed[batch_index : batch_index + 1] += weights[batch_index, slot] * output sample_z.append(z) selected_z.append(torch.stack(sample_z, dim=2)) z_all = torch.cat(selected_z, dim=0) if selected_z else None # [B,16,4,672] """, """ u = self.norms[2](x) shared, _ = self.shared(u) routed = torch.zeros_like(x) selected_z: list[Tensor] = [] selected_out: list[Tensor] = [] for batch_index in range(x.shape[0]): sample_z = [] sample_out = [] for slot in range(4): expert_index = int(indices[batch_index, slot]) output, z = self.experts[expert_index](u[batch_index : batch_index + 1]) if self.ortho_outputs: sample_out.append(output) else: routed[batch_index : batch_index + 1] += weights[batch_index, slot] * output sample_z.append(z) if self.ortho_outputs: selected_out.append(torch.stack(sample_out, dim=2)) selected_z.append(torch.stack(sample_z, dim=2)) if self.ortho_outputs: stacked = torch.cat(selected_out, dim=0) # [B,16,4,512] ortho = self._orthogonalize(stacked) routed = (ortho * weights[:, None, :, None].to(ortho.dtype)).sum(2) z_all = torch.cat(selected_z, dim=0) if selected_z else None # [B,16,4,672] """, ) patch( "modeling_base.py", " self.blocks = nn.ModuleList(MoEBlock() for _ in range(4))\n", """ self.blocks = nn.ModuleList(MoEBlock() for _ in range(4)) if getattr(config, "v4_ortho_outputs", False): for _blk in self.blocks: _blk.ortho_outputs = True """, ) # --- 4. modeling_base.py: factor table + MI / IntraCL helpers --- patch( "modeling_base.py", "class SERAVLAPolicy(PreTrainedPolicy):", '''# Round-2 arm I: verb/object factors parsed from the templated LIBERO # task names (SPEC round2_probe/SPEC.md). Keys are the exact dataset # instruction strings; values are (verb set, manipulated-object set). _TASK_FACTORS: dict[str, tuple[frozenset, frozenset]] = { "put the white mug on the left plate and put the yellow and white mug on the right plate": (frozenset({"put"}), frozenset({"white mug", "yellow and white mug"})), "put the white mug on the plate and put the chocolate pudding to the right of the plate": (frozenset({"put"}), frozenset({"white mug", "chocolate pudding"})), "put the yellow and white mug in the microwave and close it": (frozenset({"put", "close"}), frozenset({"yellow and white mug"})), "turn on the stove and put the moka pot on it": (frozenset({"turn_on", "put"}), frozenset({"moka pot"})), "put both the alphabet soup and the cream cheese box in the basket": (frozenset({"put"}), frozenset({"alphabet soup", "cream cheese box"})), "put both the alphabet soup and the tomato sauce in the basket": (frozenset({"put"}), frozenset({"alphabet soup", "tomato sauce"})), "put both moka pots on the stove": (frozenset({"put"}), frozenset({"moka pot"})), "put both the cream cheese box and the butter in the basket": (frozenset({"put"}), frozenset({"cream cheese box", "butter"})), "put the black bowl in the bottom drawer of the cabinet and close it": (frozenset({"put", "close"}), frozenset({"black bowl"})), "pick up the book and place it in the back compartment of the caddy": (frozenset({"pick_up"}), frozenset({"book"})), "put the bowl on the plate": (frozenset({"put"}), frozenset({"bowl"})), "put the wine bottle on the rack": (frozenset({"put"}), frozenset({"wine bottle"})), "open the top drawer and put the bowl inside": (frozenset({"open", "put"}), frozenset({"bowl"})), "put the cream cheese in the bowl": (frozenset({"put"}), frozenset({"cream cheese"})), "put the wine bottle on top of the cabinet": (frozenset({"put"}), frozenset({"wine bottle"})), "push the plate to the front of the stove": (frozenset({"push"}), frozenset({"plate"})), "turn on the stove": (frozenset({"turn_on"}), frozenset({"stove"})), "put the bowl on the stove": (frozenset({"put"}), frozenset({"bowl"})), "put the bowl on top of the cabinet": (frozenset({"put"}), frozenset({"bowl"})), "open the middle drawer of the cabinet": (frozenset({"open"}), frozenset({"drawer"})), "pick up the orange juice and place it in the basket": (frozenset({"pick_up"}), frozenset({"orange juice"})), "pick up the ketchup and place it in the basket": (frozenset({"pick_up"}), frozenset({"ketchup"})), "pick up the cream cheese and place it in the basket": (frozenset({"pick_up"}), frozenset({"cream cheese"})), "pick up the bbq sauce and place it in the basket": (frozenset({"pick_up"}), frozenset({"bbq sauce"})), "pick up the alphabet soup and place it in the basket": (frozenset({"pick_up"}), frozenset({"alphabet soup"})), "pick up the milk and place it in the basket": (frozenset({"pick_up"}), frozenset({"milk"})), "pick up the salad dressing and place it in the basket": (frozenset({"pick_up"}), frozenset({"salad dressing"})), "pick up the butter and place it in the basket": (frozenset({"pick_up"}), frozenset({"butter"})), "pick up the tomato sauce and place it in the basket": (frozenset({"pick_up"}), frozenset({"tomato sauce"})), "pick up the chocolate pudding and place it in the basket": (frozenset({"pick_up"}), frozenset({"chocolate pudding"})), "pick up the black bowl next to the cookie box and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), "pick up the black bowl in the top drawer of the wooden cabinet and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), "pick up the black bowl on the ramekin and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), "pick up the black bowl on the stove and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), "pick up the black bowl between the plate and the ramekin and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), "pick up the black bowl on the cookie box and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), "pick up the black bowl next to the plate and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), "pick up the black bowl next to the ramekin and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), "pick up the black bowl from table center and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), "pick up the black bowl on the wooden cabinet and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), } def _jaccard(a: frozenset, b: frozenset) -> float: if not a and not b: return 0.0 return len(a & b) / len(a | b) def _factor_weights(language: Sequence[str], device: torch.device) -> Tensor: """Pair weights w_ij = 0.5*Jaccard(verbs) + 0.5*Jaccard(objects), zero diagonal. Unknown instructions fall back to their first token as the verb and no object (never happens on LIBERO).""" verb_sets, obj_sets = [], [] for s in language: v, o = _TASK_FACTORS.get(s, (frozenset({s.split()[0] if s.split() else "unknown"}), frozenset())) verb_sets.append(v) obj_sets.append(o) b = len(language) w = torch.zeros(b, b) for i in range(b): for j in range(b): if i != j: w[i, j] = 0.5 * _jaccard(verb_sets[i], verb_sets[j]) + 0.5 * _jaccard(obj_sets[i], obj_sets[j]) return w.to(device) class SERAVLAPolicy(PreTrainedPolicy):''', ) # --- 5. modeling_base.py: MI + IntraCL methods on the policy --- patch( "modeling_base.py", " def forward(self, batch: dict) -> tuple[Tensor, dict[str, float]]:", ''' @staticmethod def _mi_loss(probabilities: list[Tensor], batch: dict, language: Sequence[str]) -> Tensor: # Round-2 arm G (SPEC round2_probe/SPEC.md): per-block batch # estimate of I(Task; Expert) from the full softmax routing # probabilities: I = H(E) - sum_t (n_t/B) H(E|T). Differentiable # through the probabilities (SDP / Mod-Squad batch form). raw_ids = batch.get("task_index") if raw_ids is not None: ids = raw_ids.reshape(-1).long().to(probabilities[0].device) else: uniq: dict[str, int] = {} ids_list = [] for s in language: if s not in uniq: uniq[s] = len(uniq) ids_list.append(uniq[s]) ids = torch.tensor(ids_list, device=probabilities[0].device) mis = [] for p in probabilities: pf = p.float() p_e = pf.mean(0) h_e = -(p_e * p_e.clamp_min(1e-8).log()).sum() h_cond = torch.zeros((), device=pf.device) for t in torch.unique(ids): mask = ids == t p_t = pf[mask].mean(0) h_t = -(p_t * p_t.clamp_min(1e-8).log()).sum() h_cond = h_cond + mask.float().mean() * h_t mis.append(h_e - h_cond) return torch.stack(mis).mean() def _intracl_loss(self, language: Sequence[str]) -> Tensor: # Round-2 arm I (SPEC round2_probe/SPEC.md): weighted InfoNCE on # flattened router logits with verb/object pair weights. The # logits are recomputed from DETACHED router inputs, so this # term's gradient reaches only the router Linears and the # goal-delta Linears - never the vision backbone, projections, # fusion or experts (the F2 failure channel, closed by design). model = self.model router_input = getattr(model, "last_router_input", None) summary = getattr(model, "last_goal_summary", None) goal_deltas = getattr(model, "goal_deltas", None) if router_input is None or summary is None or goal_deltas is None: raise RuntimeError("IntraCL requires the v3 model stash (router input / goal summary)") ri = router_input.detach() sm = summary.detach() logits = [] for router, delta_layer in zip(model.routers, goal_deltas, strict=True): lg = router(ri) if self.config.goal_mode in ("router_only", "router_and_action"): lg = lg + delta_layer(sm) * self.config.goal_router_scale logits.append(lg) r = torch.cat(logits, dim=-1).float() r = F.normalize(r, dim=-1) tau = float(getattr(self.config, "v4_intracl_tau", 0.1)) sim = (r @ r.t()) / tau w = _factor_weights(language, r.device) logp = F.log_softmax(sim, dim=-1) return -(w * logp).sum() / r.shape[0] def forward(self, batch: dict) -> tuple[Tensor, dict[str, float]]:''', ) # --- 6. modeling_base.py: wire MI + IntraCL into the total loss --- patch( "modeling_base.py", ''' total = total + entropy_lambda * ent metrics["router_entropy_mean"] = ent.item() return total, metrics ''', ''' total = total + entropy_lambda * ent metrics["router_entropy_mean"] = ent.item() mi_gamma = getattr(self.config, "v4_mi_gamma", 0.0) if mi_gamma > 0: # Arm G: MI REPLACES the uniform balance term (the mode # branch above added 0.01 * balance; remove it exactly). mi = self._mi_loss(probabilities, batch, language) total = total - 0.01 * balance - mi_gamma * mi metrics["mi_loss"] = mi.item() metrics["mi_term"] = (mi_gamma * mi).item() intracl_lambda = getattr(self.config, "v4_intracl_lambda", 0.0) if intracl_lambda > 0: icl = self._intracl_loss(language) total = total + intracl_lambda * icl metrics["intracl_loss"] = icl.item() return total, metrics ''', ) print("ALL ROUND-2 PATCHES DONE")