trace-vla-code / code /sera_v4 /tools /apply_demo_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
15.3 kB
#!/usr/bin/env python3
"""FEW-SHOT PHASE 1 patch: demo-conditioning pathway (SPEC +
gate in WORKLOG, section "FEW-SHOT PHASE 1 (E0+E1)").
Defaults OFF (v4_demo_enabled=False): every existing arm behaves
exactly as before — the new modules are constructed but never
called; check_demo.py's defaults-off bit-exact test against the
pre-patch reference (ref_capture_demo.py) is the arbiter.
When enabled, the ONLY change is a new conditioning channel:
- config gains v4_demo_* fields;
- SERAVLAV3Model gains a demo encoder: frozen-encoder demo
tokens (precomputed store, build_demo_store.py) -> trainable
vision projection / action-state MLP -> Perceiver resampler
(24 learned latent queries, d=512) -> 24 slots through a
ZERO-INIT output projection (the gate), so at init the
pathway emits exactly zero vectors;
- velocity_prediction concatenates the gated slots to the
context token set the action blocks cross-attend to (routers,
goal branch and FiLM paths untouched). Absent demo is DEFINED
as 24 zero slots — the same representation used by train-time
demo dropout and by eval condition (a);
- the policy training forward pairs each sample with a demo
episode of the SAME task drawn model-side from the store
(the quest_codes_for pattern: the training preprocessor drops
unknown per-sample keys, so pairing cannot ride in the batch),
excluding the sample's own episode, and applies demo dropout
(train only). The QueST pathway is untouched and independent.
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_ar_max_len: int = 96\n",
" v4_ar_max_len: int = 96\n"
" v4_demo_enabled: bool = False\n"
" v4_demo_slots: int = 24\n"
" v4_demo_dropout: float = 0.10\n"
" v4_demo_frames: int = 64\n",
),
(
" if self.v4_ar_max_len <= 0:\n"
" raise ValueError(f\"Invalid v4_ar_max_len: {self.v4_ar_max_len}\")\n",
" if self.v4_ar_max_len <= 0:\n"
" raise ValueError(f\"Invalid v4_ar_max_len: {self.v4_ar_max_len}\")\n"
" if self.v4_demo_slots <= 0:\n"
" raise ValueError(f\"Invalid v4_demo_slots: {self.v4_demo_slots}\")\n"
" if not 0.0 <= self.v4_demo_dropout <= 1.0:\n"
" raise ValueError(f\"Invalid v4_demo_dropout: {self.v4_demo_dropout}\")\n"
" if self.v4_demo_frames <= 0:\n"
" raise ValueError(f\"Invalid v4_demo_frames: {self.v4_demo_frames}\")\n",
),
]
PERCEIVER_BLOCK = '''
class DemoPerceiverBlock(nn.Module):
"""FEW-SHOT PHASE 1: one Perceiver resampler block. Latent
queries cross-attend to the demo token sequence, then
self-attend and pass an FFN. d=512 throughout (the trunk
context width)."""
def __init__(self) -> None:
super().__init__()
self.norm_q = nn.LayerNorm(512, eps=1e-5)
self.norm_kv = nn.LayerNorm(512, eps=1e-5)
self.cross_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True)
self.norm_s = nn.LayerNorm(512, eps=1e-5)
self.self_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True)
self.norm_f = nn.LayerNorm(512, eps=1e-5)
self.ffn = nn.Sequential(nn.Linear(512, 2048), nn.GELU(), nn.Linear(2048, 512))
def forward(self, q: Tensor, kv: Tensor, kv_pad: Tensor | None = None) -> Tensor:
kvn = self.norm_kv(kv)
q = q + self.cross_attn(self.norm_q(q), kvn, kvn,
key_padding_mask=kv_pad, need_weights=False)[0]
n = self.norm_s(q)
q = q + self.self_attn(n, n, n, need_weights=False)[0]
q = q + self.ffn(self.norm_f(q))
return q
'''
DEMO_INIT = '''
# FEW-SHOT PHASE 1: demo-conditioning pathway. Constructed
# always (defaults-off behaviour unchanged — never called
# when v4_demo_enabled is false). demo_out_proj is
# zero-init, so at init the pathway emits exactly zero
# slots and the executor is untouched; the rest of the
# encoder uses the house init (_init_new / std 0.02).
self.demo_vision_proj = nn.Linear(768, 512)
self.demo_cam_embed = nn.Embedding(2, 512)
self.demo_pos_embed = nn.Embedding(int(getattr(config, "v4_demo_frames", 64)), 512)
self.demo_type_embed = nn.Embedding(2, 512)
self.demo_act_mlp = nn.Sequential(
nn.Linear(15, 512), nn.GELU(), nn.Linear(512, 512))
self.demo_queries = nn.Parameter(
torch.empty(int(getattr(config, "v4_demo_slots", 24)), 512))
nn.init.normal_(self.demo_queries, std=0.02)
self.demo_blocks = nn.ModuleList(DemoPerceiverBlock() for _ in range(2))
self.demo_out_proj = nn.Linear(512, 512)
nn.init.zeros_(self.demo_out_proj.weight)
nn.init.zeros_(self.demo_out_proj.bias)
for _emb in (self.demo_cam_embed, self.demo_pos_embed, self.demo_type_embed):
nn.init.normal_(_emb.weight, std=0.02)
for _m in (self.demo_vision_proj, self.demo_act_mlp, self.demo_blocks):
_m.apply(_init_new)
self.last_demo_slots: Tensor | None = None
self.last_demo_eps: Tensor | None = None
self._demo_store: dict | None = None
'''
DEMO_METHODS = '''
# ---- FEW-SHOT PHASE 1: demo store, pairing, conditioning ----
def _demo_load(self) -> None:
if self._demo_store is not None:
return
import os
path = os.environ.get(
"SERA_DEMO_STORE",
os.path.expanduser("~/sera_v4_experiments/fewshot/demo_store.pt"),
)
self._demo_store = torch.load(path, map_location="cpu", weights_only=False)
def demo_pairing(self, ep: Tensor) -> Tensor:
"""For each sample episode (LongTensor [B], CPU), draw a
demo episode uniformly at random from the same task's
TRAIN-split pool (store-built to mirror the trainer's
per-task eval_split), excluding the sample episode
itself. Returns a LongTensor [B] of episode ids."""
self._demo_load()
st = self._demo_store
ep_task = st["ep_task"]
pools = st["train_pools"]
out = torch.empty_like(ep)
for i, e in enumerate(ep.tolist()):
pool = pools[int(ep_task[e])]
cand = int(pool[0])
for _ in range(100):
cand = int(pool[int(torch.randint(len(pool), (1,)))])
if cand != e:
break
assert cand != e, "demo pairing drew the sample episode"
out[i] = cand
return out
def compute_demo_slots(self, demo_eps_list, frame_perm=None) -> Tensor:
"""Encode demos into gated slots. demo_eps_list: list
(len B) of lists of episode ids (1 episode = one-shot,
k episodes = few-shot; slots concatenate). frame_perm:
optional LongTensor permutation of the frame axis applied
to every demo (eval condition (d), shuffled demo).
Returns [B, k * n_slots, 512] on the model device."""
self._demo_load()
st = self._demo_store
dev = self.demo_queries.device
n_slots = int(getattr(self.config, "v4_demo_slots", 24))
flat = [e for sub in demo_eps_list for e in sub]
counts = [len(sub) for sub in demo_eps_list]
seqs, pads = [], []
max_tok = 0
for e in flat:
vis = st["vis"][e] # [F, 2, 6, 768] fp16, frozen-encoder tokens
act = st["act"][e] # [F, 7]
sta = st["state"][e] # [F, 8]
if frame_perm is not None:
vis = vis[frame_perm]
act = act[frame_perm]
sta = sta[frame_perm]
F = vis.shape[0]
vtok = self.demo_vision_proj(vis.float().to(dev)) # [F, 2, 6, 512]
cam_idx = torch.arange(2, device=dev)
pos_idx = torch.arange(F, device=dev)
vtok = vtok + self.demo_cam_embed(cam_idx)[None, :, None, :]
vtok = vtok + self.demo_pos_embed(pos_idx)[:, None, None, :]
vtok = vtok + self.demo_type_embed.weight[0]
vtok = vtok.reshape(F * 12, 512)
atok = self.demo_act_mlp(
torch.cat([act, sta], dim=-1).float().to(dev)) # [F, 512]
atok = atok + self.demo_pos_embed(pos_idx) + self.demo_type_embed.weight[1]
seq = torch.cat([vtok, atok], dim=0) # [13F, 512]
seqs.append(seq)
max_tok = max(max_tok, seq.shape[0])
kv = torch.zeros(len(flat), max_tok, 512, device=dev,
dtype=seqs[0].dtype)
pad = torch.ones(len(flat), max_tok, dtype=torch.bool, device=dev)
for i, s in enumerate(seqs):
kv[i, : s.shape[0]] = s
pad[i, : s.shape[0]] = False
q = self.demo_queries.unsqueeze(0).expand(len(flat), -1, -1)
for block in self.demo_blocks:
q = block(q, kv, pad)
slots = self.demo_out_proj(q) # [n_demos, n_slots, 512]
out = torch.zeros(len(demo_eps_list), max(counts) * n_slots, 512,
device=dev, dtype=slots.dtype)
off = 0
for b, k in enumerate(counts):
out[b, : k * n_slots] = slots[off:off + k].reshape(k * n_slots, 512)
off += k
return out
def demo_conditioning(self, batch: dict) -> dict | None:
"""Training-time setup (mirror of questfix_conditioning):
pair each sample with a demo episode of its task, compute
slots, apply demo dropout. No-op (returns None) outside
training, so inference behaviour is exact: the eval
harness sets slots explicitly via set_demo_episodes /
set_demo_slots."""
if not (self.training and torch.is_grad_enabled()):
return None
ep = batch["episode_index"].detach().cpu().long()
demo_eps = self.demo_pairing(ep)
slots = self.compute_demo_slots([[int(d)] for d in demo_eps.tolist()])
drop = float(getattr(self.config, "v4_demo_dropout", 0.10))
drop_frac = 0.0
if drop > 0.0:
keep = (torch.rand(slots.shape[0], device=slots.device)
>= drop).to(slots.dtype)
drop_frac = float(1.0 - keep.float().mean())
slots = slots * keep[:, None, None]
self.last_demo_slots = slots
self.last_demo_eps = demo_eps.to(ep.device)
return {"demo_drop_frac": drop_frac,
"demo_ep_mean": float(demo_eps.float().mean())}
def set_demo_episodes(self, demo_eps_list, frame_perm=None) -> None:
"""Inference: encode the demos ONCE and cache the gated
slots for the whole episode (predict_action_chunk calls
velocity_prediction repeatedly; the slots persist)."""
with torch.no_grad():
self.last_demo_slots = self.compute_demo_slots(
demo_eps_list, frame_perm=frame_perm)
def set_demo_slots(self, slots) -> None:
self.last_demo_slots = slots
'''
v3_pairs = [
# DemoPerceiverBlock class: insert before SERAVLAV3Model.
(
"class SERAVLAV3Model(SERAVLAModel):",
PERCEIVER_BLOCK.strip("\n") + "\n\n\nclass SERAVLAV3Model(SERAVLAModel):",
),
# Demo modules at the end of SERAVLAV3Model.__init__ (after CC init).
(
" if getattr(config, \"cc_enabled\", False):\n"
" self.blocks = nn.ModuleList(DenseBlock() for _ in range(4))\n"
" for _blk in self.blocks:\n"
" _blk.apply(_init_new)\n",
" if getattr(config, \"cc_enabled\", False):\n"
" self.blocks = nn.ModuleList(DenseBlock() for _ in range(4))\n"
" for _blk in self.blocks:\n"
" _blk.apply(_init_new)\n"
+ DEMO_INIT,
),
# Demo methods before encode_observation.
(
" def encode_observation(self, images: Tensor, instructions: Sequence[str], state_raw: Tensor):",
DEMO_METHODS.strip("\n")
+ "\n\n def encode_observation(self, images: Tensor, instructions: Sequence[str], state_raw: Tensor):",
),
# velocity_prediction: demo slots extend the context set.
(
" intermediates = []\n"
" if cc_on:\n",
" if getattr(self.config, \"v4_demo_enabled\", False):\n"
" # FEW-SHOT PHASE 1: gated demo slots extend the\n"
" # context token set the action blocks cross-attend\n"
" # to. Absent demo == zero slots (the train-dropout\n"
" # representation), so a missing setter is safe.\n"
" if self.last_demo_slots is None:\n"
" self.last_demo_slots = torch.zeros(\n"
" h.shape[0], int(getattr(self.config, \"v4_demo_slots\", 24)), 512,\n"
" device=h.device, dtype=h.dtype)\n"
" context = torch.cat(\n"
" [context, self.last_demo_slots.to(context.dtype)], dim=1)\n"
" intermediates = []\n"
" if cc_on:\n",
),
]
base_pairs = [
# forward: demo conditioning setup after the CC setup.
(
" cc_on = getattr(self.config, \"cc_enabled\", False)\n"
" cc_metrics = None\n"
" if cc_on:\n"
" cc_codes = self.model.cc_codes_for(batch)\n"
" self.model.set_cc_from_codes(cc_codes)\n"
" cc_metrics = self.model.cc_conditioning(cc_codes, batch)\n",
" cc_on = getattr(self.config, \"cc_enabled\", False)\n"
" cc_metrics = None\n"
" if cc_on:\n"
" cc_codes = self.model.cc_codes_for(batch)\n"
" self.model.set_cc_from_codes(cc_codes)\n"
" cc_metrics = self.model.cc_conditioning(cc_codes, batch)\n"
" demo_on = getattr(self.config, \"v4_demo_enabled\", False)\n"
" demo_metrics = None\n"
" if demo_on:\n"
" demo_metrics = self.model.demo_conditioning(batch)\n",
),
# forward: merge demo metrics before the return.
(
" if questfix_metrics is not None:\n"
" metrics.update(questfix_metrics)\n"
" return total, metrics\n",
" if questfix_metrics is not None:\n"
" metrics.update(questfix_metrics)\n"
" if demo_metrics is not None:\n"
" metrics.update(demo_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("demo patch applied")