so101-push-pi05 / code /encoder_swap.py
tmhoanggg's picture
Upload code/encoder_swap.py with huggingface_hub
54b37e6 verified
Raw History Blame Contribute Delete
9.36 kB
"""pi0.5 (LeRobot) with PaliGemma's SigLIP replaced by one of our FROZEN encoders.
image [-1,1] 224x224 -> frozen encoder -> spatial tokens (B, N, C)
-> LayerNorm (no affine) -> Linear(C, 2048) <- trained, new
-> Gemma + action expert (standard pi0.5 fine-tune)
Tokens per camera: ResNet-50 (R3M) 7x7 = 49 x 2048; ViT-B/16 (VIGIL ViT, SigLIP-2, VC-1) 14x14 = 196 x 768.
The swap modules are named so pi0.5 keeps them float32 ("vision_tower" / "multi_modal_projector"
substrings), the encoder never trains and stays in eval mode (ResNet BatchNorm), and loading the
pi05_base weights is allowed to miss ONLY the swap modules: LeRobot's loader otherwise turns a
strict-load failure into a printed warning and trains from random weights.
apply(arm) must run before the policy is built (training and inference alike).
"""
import os, sys, glob
import torch, torch.nn as nn
sys.path.insert(0, "/mnt/data/sftp/data/hoangtm33/vla/r3m")
RUNS = os.environ.get("R3M_RUNS_DIR", "/mnt/data/sftp/data/hoangtm33/vla/r3m_dev/runs_corpus")
CK = os.environ.get("BASELINE_CKPTS", "/mnt/data/sftp/data/hoangtm33/vla/r3m_dev/baseline_ckpts")
ARMS = { # name -> (loader, step); on a machine without these files (the robot PC) only the
# architecture is built and every encoder weight comes from the policy checkpoint itself
"vigil_vit": ("semvggtglobaldelta_corpusnoreg-tcn01-vitb16-fix-frz10-sem05_bs128x2", 93749),
# best ViT VIRGIL by LIBERO as of 2026-11-05 (56.92): freeze 10, tcn 0, sem 0.4, geo 1, lr 1e-4
"virgil_vit": ("semvggtglobaldelta_corpusnoreg-vitb16-fix-frz10-t0-s04-g1-lr1e4_bs128x2", 93749),
# MAIN METHOD from 2026-11-11 (LIBERO 55.08): + teacher-change prediction (L_pred 1.0 / 0.4), batch 512
"virgil_pred": ("semvggtglobaldelta_corpusnoreg-vitb16-fix-frz10-t0-s04-g1-lr1e4-pred1-geo04_bs128x4", 46874),
"siglip2": ("siglipfrozen", 93749),
"r3m": ("official", None),
"vc1": ("vc1", None),
"dinov2": (None, None), # facebook/dinov2-base as released, 16x16 = 256 x 768 at 224
"clip": (None, None), # openai/clip-vit-base-patch16 as released, 14x14 = 196 x 768 at 224
}
SWAP = ("vision_tower_swap", "multi_modal_projector_swap")
def _old_vit_name(k):
"""ViT keys saved under transformers 5.15 (training env) -> the 5.5 names LeRobot pins (<5.6).
Same tensors, renamed in HF's refactor; check_encoders.py verifies the features match exactly."""
import re
m = re.match(r"(.*vit\.)layers\.(\d+)\.(.*)", k)
if not m:
return k
pre, i, rest = m.groups()
for a, b in (("attention.q_proj", "attention.attention.query"), ("attention.k_proj", "attention.attention.key"),
("attention.v_proj", "attention.attention.value"), ("attention.o_proj", "attention.output.dense"),
("mlp.fc1", "intermediate.dense"), ("mlp.fc2", "output.dense")):
if rest.startswith(a):
rest = b + rest[len(a):]
break
return f"{pre}encoder.layer.{i}.{rest}"
class SpatialEncoder(nn.Module):
"""Frozen encoder -> (B, N, C) spatial tokens from [0,1] RGB, eval mode forever."""
def __init__(self, arm):
super().__init__()
name, step = ARMS[arm]
self.kind = "timm" if arm == "vc1" else "r3m"
if arm == "vc1":
import timm
net = timm.create_model("vit_base_patch16_224", pretrained=False, num_classes=0)
if os.path.exists(f"{CK}/vc1_vitb.pth"):
net.load_state_dict(torch.load(f"{CK}/vc1_vitb.pth", map_location="cpu")["model"], strict=False)
self.net = net
self.register_buffer("m", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1), persistent=False)
self.register_buffer("s", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1), persistent=False)
self.dim = 768
else:
if arm == "r3m":
import r3m as r3mpkg
m = r3mpkg.load_r3m_reproduce("r3m")
m = getattr(m, "module", m)
else: # same path as so101_encoders.load_r3m_arm: R3M container, auxiliary heads dropped
from r3m.models.models_r3m import R3M
size = {"siglip2": "siglip", "dinov2": "dinov2b", "clip": "clip"}.get(arm, "vitb16")
kw = dict(fixnorm=True) if size == "vitb16" else {}
m = R3M(device="cpu", lr=1e-4, hidden_dim=1024, size=size, l2weight=1e-5, l1weight=1e-5,
tcnweight=1.0, l2dist=True, bs=16, langweight=0.0, semweight=0.0, **kw)
cands = glob.glob(f"{RUNS}/{name}/r3moutput/train_representation/*/snapshot_{step}.pt") if name else []
if cands: # training machine; elsewhere the weights arrive with the policy checkpoint
sd = torch.load(max(cands, key=os.path.getmtime), map_location="cpu", weights_only=False)["r3m"]
sd = {k[len("module."):]: v for k, v in sd.items() if k.startswith("module.")}
sd = {k: v for k, v in sd.items() if not any(t in k for t in (
"lang_enc", "lang_rew", "sem_head", "vggt_head", "jepa_pred", "jepa_target", "sem_pred", "geo_pred"))}
if "convnet.vit.encoder.layer.0.attention.attention.query.weight" in m.state_dict():
sd = {_old_vit_name(k): v for k, v in sd.items()}
missing, unexpected = m.load_state_dict(sd, strict=False)
assert not unexpected, f"{arm}: unexpected keys {unexpected[:3]}"
self.net = m
self._map = None
m.convnet.layer4.register_forward_hook(lambda mod, i, o: setattr(self, "_map", o))
self.dim = 2048 if arm == "r3m" else 768
self.requires_grad_(False)
self.eval()
def train(self, mode=True):
return super().train(False)
@torch.no_grad()
def forward(self, img01):
if self.kind == "timm":
return self.net.forward_features((img01 - self.m) / self.s)[:, 1:] # drop CLS
self.net(img01 * 255.0) # R3M.forward: /255 + its own normalisation
f = self._map
if f.ndim == 3: # some wrappers hand back tokens already
return f
return f.flatten(2).transpose(1, 2) # (B, C, g, g) -> (B, g*g, C)
def apply(arm):
from lerobot.policies.pi05 import modeling_pi05 as M
cls = M.PaliGemmaWithExpertModel
if getattr(cls, "_swap_arm", None):
return
init0, train0 = cls.__init__, cls.train
def __init__(self, *a, **k):
init0(self, *a, **k)
enc = SpatialEncoder(arm)
width = self.paligemma.config.text_config.hidden_size
self.vision_tower_swap = enc
self.multi_modal_projector_swap = nn.Sequential(
nn.LayerNorm(enc.dim, elementwise_affine=False), nn.Linear(enc.dim, width))
self.vision_tower_swap.float(); self.multi_modal_projector_swap.float()
# the unused SigLIP tower stays frozen; everything else trains as in the standard recipe
for q in self.paligemma.model.vision_tower.parameters():
q.requires_grad = False
def train(self, mode=True):
out = train0(self, mode)
self.vision_tower_swap.eval()
return out
def embed_image(self, image, **kw):
assert image.ndim == 4, "encoder swap supports single-frame images only"
out_dtype = image.dtype
tok = self.vision_tower_swap((image.float() + 1.0) / 2.0) # [-1,1] -> [0,1]
feats = self.multi_modal_projector_swap(tok.float())
return feats.to(out_dtype)
cls.__init__, cls.train, cls.embed_image, cls._swap_arm = __init__, train, embed_image, arm
# SWAP_PROJ_ONLY=1: stage 1 of the two-stage swap (2026-11-10). Only the new projector trains, so Gemma
# learns nothing until the projected tokens are aligned (LLaVA-style); stage 2 starts from that checkpoint.
if os.environ.get("SWAP_PROJ_ONLY") == "1":
P0 = M.PI05Pytorch.__init__
def init_proj_only(self, *a, **k):
P0(self, *a, **k)
for n, q in self.named_parameters():
q.requires_grad_("multi_modal_projector_swap" in n)
M.PI05Pytorch.__init__ = init_proj_only
# pi05_base has no swap weights: allow exactly those to be missing, nothing else
P = M.PI05Policy
fp0 = P.from_pretrained.__func__
def from_pretrained(klass, *a, **k):
k["strict"] = False
pol = fp0(klass, *a, **k)
return pol
P.from_pretrained = classmethod(from_pretrained)
_lsd = nn.Module.load_state_dict
def load_state_dict(self, sd, strict=True, **kw):
res = _lsd(self, sd, strict=False, **kw)
bad = [x for x in res.missing_keys if not any(s in x for s in SWAP)]
if bad or res.unexpected_keys: # SystemExit: LeRobot's loader catches Exception and trains on
raise SystemExit(f"pi0.5 weights did not load cleanly: missing {bad[:5]} " # random weights
f"unexpected {res.unexpected_keys[:5]}")
print(f"[encoder_swap:{arm}] base weights loaded; new (untrained) swap tensors: "
f"{len(res.missing_keys)}", flush=True)
return res
P.load_state_dict = load_state_dict