#!/usr/bin/env python3 """JEDI-LITE patch (research report demo-conditioning section 7.2; WORKLOG "JEDI-LITE" pre-registration). Applied ON TOP of the demo patch (+ patch 2). Defaults OFF (v4_jedi_enabled= False): with the flag off, behaviour is exactly the fs1 demo run — the new modules are constructed but the jedi block in demo_conditioning, the instruction dropout and jedi_losses are never entered. When enabled (and demo enabled), training changes ONLY in the demo pathway's objective and sample composition: - config gains v4_jedi_* fields; - SERAVLAV3Model gains a keyframe predictor (prefix demo_pred_): a learned query token carrying the current frame's pooled frozen feature reads the gated demo slots through 2 DemoPerceiverBlocks; a linear head predicts the NEXT-STAGE KEYFRAME's pooled frozen feature (jedi store, built offline from gripper changepoints + EE speed minima); - demo_conditioning additionally: caches the pre-dropout slots + keep-mask for the jedi losses, and appends distractor-demo slots (other train tasks) to the context slots for a fraction of samples (zero-padded for the rest), so the executor must SELECT the correct demo; - jedi_losses (called from the policy forward, the house aux-loss pattern): L = lambda_pred * err_pos + lambda_cf * [relu(m + err_pos - err_taskneg) + relu(m + err_pos - err_procneg)], errors = squared L2 between L2-normalized predicted and target keyframe features; metrics include DD_task = err_taskneg / err_pos; - the policy forward applies instruction dropout (p=0.5, JEDI) at its very top, BEFORE _inputs reads batch["task"], train mode only. Exact-match replacements; every count is asserted. Back up the three source files before applying (queue_jedi.sh does). """ 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_demo_frames: int = 64\n", " v4_demo_frames: int = 64\n" " v4_jedi_enabled: bool = False\n" " v4_jedi_lambda_pred: float = 1.0\n" " v4_jedi_lambda_cf: float = 1.0\n" " v4_jedi_margin: float = 0.2\n" " v4_jedi_instr_dropout: float = 0.5\n" " v4_jedi_distractor_p: float = 0.2\n" " v4_jedi_distractor_k: int = 2\n", ), ] JEDI_INIT = ''' # JEDI-LITE: keyframe predictor. Constructed always # (defaults-off behaviour unchanged — never called when # v4_jedi_enabled is false). self.demo_pred_obs_proj = nn.Linear(768, 512) self.demo_pred_query = nn.Parameter(torch.empty(1, 512)) nn.init.normal_(self.demo_pred_query, std=0.02) self.demo_pred_blocks = nn.ModuleList( DemoPerceiverBlock() for _ in range(2)) self.demo_pred_head = nn.Linear(512, 768) for _m in (self.demo_pred_obs_proj, self.demo_pred_blocks, self.demo_pred_head): _m.apply(_init_new) self._jedi_store: dict | None = None self._jedi_cache: dict | None = None self._jedi_instr_drop_frac: float = 0.0 ''' JEDI_METHODS = ''' # ---- JEDI-LITE: keyframe prediction + counterfactual ---- def _jedi_load(self) -> None: if self._jedi_store is not None: return import os path = os.environ.get( "SERA_JEDI_STORE", os.path.expanduser("~/sera_v4_experiments/fewshot/jedi_store.pt"), ) self._jedi_store = torch.load(path, map_location="cpu", weights_only=False) def jedi_instruction_dropout(self, batch: dict) -> None: """JEDI-LITE (train only; called at the top of the policy forward, BEFORE _inputs): replace the instruction with the empty string for a fraction of samples, so the demo becomes the only task specification (JEDI p=0.5).""" if not self.training: return p = float(getattr(self.config, "v4_jedi_instr_dropout", 0.5)) tasks = batch.get("task") if (isinstance(tasks, (list, tuple)) and tasks and isinstance(tasks[0], str)): drop = torch.rand(len(tasks)) < p batch["task"] = ["" if bool(d) else t for t, d in zip(tasks, drop.tolist())] self._jedi_instr_drop_frac = float(drop.float().mean()) def jedi_negative_pairing(self, ep: Tensor): """For each sample episode (LongTensor [B], CPU): draw a TASK negative demo (an episode of a DIFFERENT train task, from that task's train pool) and a PROCESS negative demo (same task, different keyframe signature; precomputed pools in the jedi store). Returns (task_neg, proc_neg) LongTensors [B] of episode ids.""" self._demo_load() self._jedi_load() dst = self._demo_store jst = self._jedi_store ep_task = dst["ep_task"] pools = dst["train_pools"] train_tasks = dst["train_tasks"] proc_pools = jst["proc_pool"] task_neg = torch.empty_like(ep) proc_neg = torch.empty_like(ep) for i, e in enumerate(ep.tolist()): t = int(ep_task[e]) others = [x for x in train_tasks if x != t] nt = int(others[int(torch.randint(len(others), (1,)))]) pool_n = pools[nt] task_neg[i] = int(pool_n[int(torch.randint(len(pool_n), (1,)))]) pool_p = proc_pools.get(int(e)) if pool_p is None or len(pool_p) == 0: pool_p = pools[t] cand = int(pool_p[0]) for _ in range(100): cand = int(pool_p[int(torch.randint(len(pool_p), (1,)))]) if cand != e: break proc_neg[i] = cand return task_neg, proc_neg def _jedi_predict(self, slots: Tensor, obs_feat: Tensor) -> Tensor: """Predict the next-stage keyframe's frozen feature: a query token carrying the current frame's pooled frozen feature (768 -> 512) reads the gated demo slots through 2 Perceiver blocks; a linear head maps back to 768. Returns the L2-normalized prediction [B, 768].""" dev = slots.device obs_tok = self.demo_pred_obs_proj( obs_feat.float().to(dev)).unsqueeze(1) q = obs_tok + self.demo_pred_query.to(dev) for block in self.demo_pred_blocks: q = block(q, slots) pred = self.demo_pred_head(q.squeeze(1)).float() return pred / pred.norm(dim=-1, keepdim=True).clamp_min(1e-8) def jedi_losses(self, batch: dict): """JEDI-LITE losses (train only; the policy forward adds the returned loss to the total, the house aux-loss pattern). Uses the cache stashed by demo_conditioning (pre-dropout gated slots + dropout keep-mask), so the prediction is scored on the SAME slots the executor conditions on. Errors are squared L2 distances between L2-normalized features. Returns (loss, metrics) or None.""" if not (self.training and torch.is_grad_enabled()): return None cache = self._jedi_cache if cache is None: return None self._jedi_load() jst = self._jedi_store dst = self._demo_store dev = self.demo_queries.device ep = batch["episode_index"].detach().cpu().long() B = ep.shape[0] fi = batch.get("frame_index") frame_src = 1.0 if fi is not None else 0.0 if fi is None: fi = torch.zeros(B, dtype=torch.long) fi = fi.detach().cpu().long() obs_rows, tgt_rows = [], [] for i, e in enumerate(ep.tolist()): F = int(dst["frames"][e]) L = int(dst["ep_len"][e]) s = int(round(float(fi[i]) * max(F - 1, 0) / max(L - 1, 1))) s = min(max(s, 0), F - 1) k = int(jst["next_kf"][e][s]) obs_rows.append(jst["pool_feat"][e][s]) tgt_rows.append(jst["pool_feat"][e][k]) obs_feat = torch.stack(obs_rows) # [B, 768] fp16 tgt_feat = torch.stack(tgt_rows).float().to(dev) tgt_n = tgt_feat / tgt_feat.norm( dim=-1, keepdim=True).clamp_min(1e-8) slots_pos = cache["slots_pos"] keep = cache["keep"].to(dev) task_neg, proc_neg = self.jedi_negative_pairing(ep) slots_task = self.compute_demo_slots( [[int(d)] for d in task_neg.tolist()]) slots_proc = self.compute_demo_slots( [[int(d)] for d in proc_neg.tolist()]) err_pos = (self._jedi_predict(slots_pos, obs_feat) - tgt_n).square().sum(-1) err_task = (self._jedi_predict(slots_task, obs_feat) - tgt_n).square().sum(-1) err_proc = (self._jedi_predict(slots_proc, obs_feat) - tgt_n).square().sum(-1) w = keep.float() wsum = w.sum().clamp_min(1.0) pred_loss = (err_pos * w).sum() / wsum margin = float(getattr(self.config, "v4_jedi_margin", 0.2)) cf = (torch.relu(margin + err_pos - err_task) + torch.relu(margin + err_pos - err_proc)) cf_loss = (cf * w).sum() / wsum lam_p = float(getattr(self.config, "v4_jedi_lambda_pred", 1.0)) lam_c = float(getattr(self.config, "v4_jedi_lambda_cf", 1.0)) loss = lam_p * pred_loss + lam_c * cf_loss with torch.no_grad(): ep_mean = (err_pos * w).sum() / wsum et_mean = (err_task * w).sum() / wsum epr_mean = (err_proc * w).sum() / wsum metrics = { "jedi_pred_err": float(ep_mean), "jedi_err_taskneg": float(et_mean), "jedi_err_procneg": float(epr_mean), "jedi_dd_task": float(et_mean / ep_mean.clamp_min(1e-8)), "jedi_cf_loss": float(cf_loss), "jedi_frame_src": frame_src, "jedi_instr_drop_frac": float(self._jedi_instr_drop_frac), "jedi_keep_frac": float(w.mean()), } return loss, metrics ''' JEDI_COND_TAIL_OLD = ( " self.last_demo_slots = slots\n" " self.last_demo_eps = demo_eps.to(ep.device)\n" " return {\"demo_drop_frac\": drop_frac,\n" " \"demo_ep_mean\": float(demo_eps.float().mean())}\n" ) JEDI_COND_TAIL_NEW = ( " self.last_demo_slots = slots\n" " self.last_demo_eps = demo_eps.to(ep.device)\n" " jedi_metrics = {}\n" " if getattr(self.config, \"v4_jedi_enabled\", False):\n" " # JEDI-LITE: cache the pre-dropout slots for the\n" " # jedi losses, and append distractor-demo slots\n" " # (other train tasks) for a fraction of samples;\n" " # the rest are zero-padded to the same width\n" " # (absent-demo representation), so the executor\n" " # must SELECT the correct demo among them.\n" " p_dis = float(getattr(self.config,\n" " \"v4_jedi_distractor_p\", 0.2))\n" " k_dis = int(getattr(self.config,\n" " \"v4_jedi_distractor_k\", 2))\n" " st = self._demo_store\n" " ep_task = st[\"ep_task\"]\n" " pools = st[\"train_pools\"]\n" " train_tasks = st[\"train_tasks\"]\n" " dis_lists = []\n" " for e in ep.tolist():\n" " t = int(ep_task[int(e)])\n" " others = [x for x in train_tasks if x != t]\n" " row = []\n" " for _ in range(k_dis):\n" " nt = int(others[int(torch.randint(\n" " len(others), (1,)))])\n" " pool_n = pools[nt]\n" " row.append(int(pool_n[int(torch.randint(\n" " len(pool_n), (1,)))]))\n" " dis_lists.append(row)\n" " dis_slots = self.compute_demo_slots(dis_lists)\n" " sel = (torch.rand(slots.shape[0], device=slots.device)\n" " < p_dis).to(slots.dtype)\n" " dis_slots = dis_slots * sel[:, None, None]\n" " slots = torch.cat([slots, dis_slots], dim=1)\n" " self.last_demo_slots = slots\n" " self._jedi_cache = {\n" " \"slots_pos\": slots_pos,\n" " \"keep\": keep_mask,\n" " }\n" " jedi_metrics = {\"jedi_dis_frac\":\n" " float(sel.float().mean())}\n" " return {\"demo_drop_frac\": drop_frac,\n" " \"demo_ep_mean\": float(demo_eps.float().mean()),\n" " **jedi_metrics}\n" ) v3_pairs = [ # Predictor modules at the end of the demo init block. ( " self._demo_store: dict | None = None\n", " self._demo_store: dict | None = None\n" + JEDI_INIT, ), # Pre-dropout slots + keep-mask capture (jedi cache source). ( " slots = self.compute_demo_slots(" "[[int(d)] for d in demo_eps.tolist()])\n", " slots = self.compute_demo_slots(" "[[int(d)] for d in demo_eps.tolist()])\n" " slots_pos = slots\n" " keep_mask = torch.ones(slots.shape[0],\n" " device=slots.device,\n" " dtype=slots.dtype)\n", ), ( " slots = slots * keep[:, None, None]\n", " keep_mask = keep\n" " slots = slots * keep[:, None, None]\n", ), # Distractor append + cache + metrics at the tail of # demo_conditioning. (JEDI_COND_TAIL_OLD, JEDI_COND_TAIL_NEW), # Jedi methods before set_demo_episodes. ( " def set_demo_episodes(self, demo_eps_list, frame_perm=None) -> None:", JEDI_METHODS.strip("\n") + "\n\n def set_demo_episodes(self, demo_eps_list, frame_perm=None) -> None:", ), ] base_pairs = [ # Instruction dropout BEFORE _inputs reads the task strings. ( " def forward(self, batch: dict) -> tuple[Tensor, dict[str, float]]:\n" " images, state_raw, language = self._inputs(batch)\n", " def forward(self, batch: dict) -> tuple[Tensor, dict[str, float]]:\n" " if getattr(self.config, \"v4_jedi_enabled\", False):\n" " self.model.jedi_instruction_dropout(batch)\n" " images, state_raw, language = self._inputs(batch)\n", ), # Jedi loss added to the total (house aux-loss pattern). ( " if demo_metrics is not None:\n" " metrics.update(demo_metrics)\n" " return total, metrics\n", " if demo_metrics is not None:\n" " metrics.update(demo_metrics)\n" " if demo_on and getattr(self.config, \"v4_jedi_enabled\", False):\n" " jedi_out = self.model.jedi_losses(batch)\n" " if jedi_out is not None:\n" " jedi_loss, jedi_metrics = jedi_out\n" " total = total + jedi_loss\n" " metrics.update(jedi_metrics)\n" " return total, 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("jedi patch applied")