trace-vla-code / code /sera_v4 /tools /apply_unfreeze_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
7.71 kB
#!/usr/bin/env python3
"""UF (scheduled unfreeze) patch for run sera-v4-fs1-jedi-l60kuf
(2026-11-20, Young's 17:41 order + TIPSv2-unfreeze research).
Adds config flags (all defaults = old behaviour):
- configuration_sera_vla_v3.py: `v4_uf_vision_blocks` (0),
`v4_uf_step` (3000), `v4_uf_warmup_steps` (500),
`v4_uf_gamma` (0.75) + validation (uf is mutually exclusive with
the immediate `finetune_vision_last_n_layers` path).
- modeling_base.py:
* SERAVLAModel gains `_uf_unfrozen = False`; encode_observation's
vision grad gate opens when either the classic finetune flag is
on OR `_uf_unfrozen` has been flipped by the training entry
(train_uf.py) at v4_uf_step. Before the flip the observation
path is byte-identical to the frozen run (tips.encode_image).
* SERAVLAPolicy.get_optim_params appends, when
v4_uf_vision_blocks > 0, ONE optimizer group per selected vision
block (last N blocks of tips.vision_encoder.blocks) plus the
final vision norm folded into the top block's group. The params
are still requires_grad=False at build time, so AdamW skips
them until train_uf.py flips them at v4_uf_step. Peak LRs are
LLRD from the top block: top = optimizer_lr *
backbone_lr_scale (= 1e-5 at the run's settings), each lower
block x v4_uf_gamma (0.75): block12 1.0e-5, block11 7.5e-6,
block10 5.625e-6, block9 4.21875e-6. Each group dict carries a
"v4_uf_block" marker (1-based block index) so the training
entry can recognise the groups without name guessing.
Text encoder: untouched, stays fully frozen (0 params in any
group). With v4_uf_vision_blocks = 0 (default) get_optim_params
returns exactly the old groups and the encode gate is unchanged,
so every old run/checkpoint is unaffected.
Backups: <file>.bak-uf-20261120 next to each edited file.
Every replacement is an exact-match with a count==1 assert; a file
is written only after all of its replacements succeed in memory.
"""
import py_compile
import shutil
import sys
from pathlib import Path
SRC = Path.home() / "lerobot/src/lerobot/policies/sera_vla_v3"
BAK_SUFFIX = ".bak-uf-20261120"
EDITS = {
"configuration_sera_vla_v3.py": [
(
""" v4_reg_dropout: float = 0.0
v4_flow_steps: int = 4
""",
""" v4_reg_dropout: float = 0.0
v4_uf_vision_blocks: int = 0
v4_uf_step: int = 3000
v4_uf_warmup_steps: int = 500
v4_uf_gamma: float = 0.75
v4_flow_steps: int = 4
""",
),
(
""" if not 0.0 <= self.v4_reg_dropout < 1.0:
raise ValueError(f"Invalid v4_reg_dropout: {self.v4_reg_dropout}")
if not 0.0 <= self.v4_reg_dropout < 1.0:
raise ValueError(f"Invalid v4_reg_dropout: {self.v4_reg_dropout}")
""",
""" if not 0.0 <= self.v4_reg_dropout < 1.0:
raise ValueError(f"Invalid v4_reg_dropout: {self.v4_reg_dropout}")
if not 0.0 <= self.v4_reg_dropout < 1.0:
raise ValueError(f"Invalid v4_reg_dropout: {self.v4_reg_dropout}")
if not 0 <= self.v4_uf_vision_blocks <= 12:
raise ValueError(f"Invalid v4_uf_vision_blocks: {self.v4_uf_vision_blocks}")
if self.v4_uf_vision_blocks and self.finetune_vision_last_n_layers:
raise ValueError(
"v4_uf_vision_blocks is mutually exclusive with "
"finetune_vision_last_n_layers")
if self.v4_uf_step < 0:
raise ValueError(f"Invalid v4_uf_step: {self.v4_uf_step}")
if self.v4_uf_warmup_steps < 1:
raise ValueError(f"Invalid v4_uf_warmup_steps: {self.v4_uf_warmup_steps}")
if not 0.0 < self.v4_uf_gamma <= 1.0:
raise ValueError(f"Invalid v4_uf_gamma: {self.v4_uf_gamma}")
""",
),
],
"modeling_base.py": [
(
""" self._configure_tips_finetuning()
self.tips.eval()
""",
""" self._uf_unfrozen = False
self._configure_tips_finetuning()
self.tips.eval()
""",
),
(
""" with torch.set_grad_enabled(torch.is_grad_enabled() and self.training and self._finetunes_vision):
if self._finetunes_vision:
""",
""" _vision_grad = self._finetunes_vision or getattr(self, "_uf_unfrozen", False)
with torch.set_grad_enabled(torch.is_grad_enabled() and self.training and _vision_grad):
if _vision_grad:
""",
),
(
""" groups = [{"params": other}]
if backbone:
groups.append(
{"params": backbone, "lr": self.config.optimizer_lr * self.config.backbone_lr_scale}
)
return groups
""",
""" groups = [{"params": other}]
if backbone:
groups.append(
{"params": backbone, "lr": self.config.optimizer_lr * self.config.backbone_lr_scale}
)
uf_n = int(getattr(self.config, "v4_uf_vision_blocks", 0) or 0)
if uf_n:
groups.extend(self._uf_param_groups(uf_n))
return groups
def _uf_param_groups(self, uf_n: int) -> list[dict]:
\"\"\"Optimizer groups for the scheduled-unfreeze (UF) vision blocks.
The last ``uf_n`` TIPSv2 vision blocks plus the final vision
norm are placed in the optimizer while still frozen
(requires_grad=False, so AdamW skips them); the training
entry (train_uf.py) flips requires_grad at v4_uf_step and
drives their LR schedule. Peak LRs follow LLRD from the top
block: top = optimizer_lr * backbone_lr_scale, each lower
block multiplied by v4_uf_gamma. The final vision norm rides
with the top block's group. Each group dict carries a
``v4_uf_block`` marker (1-based block index; the norm shares
the top block's marker) so the training entry recognises the
groups structurally, never by name guessing.
\"\"\"
vision_encoder = self.model.tips.vision_encoder
blocks = list(vision_encoder.blocks)
if uf_n > len(blocks):
raise ValueError(
f"v4_uf_vision_blocks={uf_n} exceeds {len(blocks)} vision blocks")
top_lr = self.config.optimizer_lr * self.config.backbone_lr_scale
gamma = float(self.config.v4_uf_gamma)
groups: list[dict] = []
selected = blocks[len(blocks) - uf_n:]
for distance, block in enumerate(reversed(selected)):
groups.append(
{
"params": list(block.parameters()),
"lr": top_lr * (gamma**distance),
"v4_uf_block": len(blocks) - distance,
}
)
groups[0]["params"] = (
groups[0]["params"] + list(vision_encoder.norm.parameters()))
return groups
""",
),
],
}
def main() -> int:
for fname, edits in EDITS.items():
path = SRC / fname
text = path.read_text()
for i, (old, new) in enumerate(edits):
if new in text and old not in text:
print(f"{fname} edit {i}: already applied, skipping")
continue
count = text.count(old)
assert count == 1, f"{fname} edit {i}: anchor found {count} times"
text = text.replace(old, new)
bak = path.with_name(path.name + BAK_SUFFIX)
if not bak.exists():
shutil.copy2(path, bak)
print(f"backup: {bak.name}")
path.write_text(text)
py_compile.compile(str(path), doraise=True)
print(f"{fname}: {len(edits)} edits applied, compiles OK")
print("UF PATCH DONE")
return 0
if __name__ == "__main__":
sys.exit(main())