trace-vla-code / code /sera_v4 /tools /apply_v4_patches.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
5.52 kB
#!/usr/bin/env python3
"""Apply SERA-v4 patches to the sera_vla_v3 package. Idempotent-ish: fails loudly
if an anchor is missing or already patched."""
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_sera_vla_v3.py: add v4_moe_mode field + validation ---
patch(
"configuration_sera_vla_v3.py",
' router_alignment_enabled: bool = False\n',
' router_alignment_enabled: bool = False\n v4_moe_mode: str = "control"\n',
)
patch(
"configuration_sera_vla_v3.py",
''' if self.training_stage not in {"goal_only", "joint"}:
raise ValueError(f"Invalid training_stage: {self.training_stage}")''',
''' if self.training_stage not in {"goal_only", "joint"}:
raise ValueError(f"Invalid training_stage: {self.training_stage}")
if self.v4_moe_mode not in {"control", "nobal", "bias", "skillroute"}:
raise ValueError(f"Invalid v4_moe_mode: {self.v4_moe_mode}")''',
)
# --- 2. modeling_base.py: router width by mode + bias buffers ---
patch(
"modeling_base.py",
" self.routers = nn.ModuleList(nn.Linear(1024, 8, bias=False) for _ in range(4))\n",
""" router_in_features = 1536 if getattr(config, "v4_moe_mode", "control") == "skillroute" else 1024
self.routers = nn.ModuleList(nn.Linear(router_in_features, 8, bias=False) for _ in range(4))
self.register_buffer("router_bias", torch.zeros(4, 8))
self.register_buffer("router_load_ema", torch.full((4, 8), 0.5))
""",
)
# --- 3. modeling_base.py: loss switch ---
patch(
"modeling_base.py",
" total = fm + 0.01 * balance + 0.0002 * specialization\n",
""" v4_mode = getattr(self.config, "v4_moe_mode", "control")
if v4_mode == "nobal":
total = fm
elif v4_mode == "bias":
total = fm + 0.0002 * specialization
else:
total = fm + 0.01 * balance + 0.0002 * specialization
""",
)
# --- 4. modeling_sera_vla_v3.py: skillroute router input + bias selection/update ---
old_loop = """ self.last_goal = self.goal(vision, text, state, padding)
summary = self.last_goal.mean(1)
router_input = torch.cat((context.mean(1), state), dim=-1)
probabilities, indices, weights = [], [], []
self.router_base_logits = []
self.router_goal_deltas = []
for router, delta_layer in zip(self.routers, self.goal_deltas, strict=True):
base = router(router_input)
delta = delta_layer(summary) * self.config.goal_router_scale
self.router_base_logits.append(base)
self.router_goal_deltas.append(delta)
logits = base + delta if self.config.goal_mode in ("router_only", "router_and_action") else base
p = logits.softmax(-1)
w, i = p.topk(4, dim=-1)
probabilities.append(p)
indices.append(i)
weights.append(w)
"""
new_loop = """ self.last_goal = self.goal(vision, text, state, padding)
summary = self.last_goal.mean(1)
v4_mode = getattr(self.config, "v4_moe_mode", "control")
if v4_mode == "skillroute":
text_mask = (~padding).to(text.dtype)
text_pooled = (text * text_mask[..., None]).sum(1) / text_mask.sum(1, keepdim=True).clamp_min(1.0)
router_input = torch.cat((context.mean(1), state, text_pooled), dim=-1)
else:
router_input = torch.cat((context.mean(1), state), dim=-1)
probabilities, indices, weights = [], [], []
self.router_base_logits = []
self.router_goal_deltas = []
for layer_index, (router, delta_layer) in enumerate(zip(self.routers, self.goal_deltas, strict=True)):
base = router(router_input)
delta = delta_layer(summary) * self.config.goal_router_scale
self.router_base_logits.append(base)
self.router_goal_deltas.append(delta)
logits = base + delta if self.config.goal_mode in ("router_only", "router_and_action") else base
p = logits.softmax(-1)
if v4_mode == "bias":
_, i = (logits + self.router_bias[layer_index]).topk(4, dim=-1)
w = p.gather(-1, i)
if self.training and torch.is_grad_enabled():
with torch.no_grad():
load = torch.zeros(8, device=i.device, dtype=torch.float32)
load.scatter_add_(0, i.reshape(-1).long(), torch.ones(i.numel(), device=i.device))
load = load / float(i.numel())
ema = self.router_load_ema[layer_index]
ema.mul_(0.99).add_(load * 0.01)
bias = self.router_bias[layer_index]
bias.add_(0.01 * (0.5 - ema))
bias.clamp_(-3.0, 3.0)
else:
w, i = p.topk(4, dim=-1)
probabilities.append(p)
indices.append(i)
weights.append(w)
"""
patch("modeling_sera_vla_v3.py", old_loop, new_loop)
print("ALL PATCHES DONE")