trace-vla-code / code /sera_v4 /tools /apply_unfreeze_fix2.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.14 kB
#!/usr/bin/env python3
"""UF FIX 2 (2026-11-20): activation memory of the unfrozen blocks.
Smoke B (UF step forced to 50) proved the flip works in a real
training run, but post-flip VRAM hit 14,883 MiB of 16,311 MiB —
over the registered 14 GB line for a 60k run. Remedy, per the
pre-registered rule: gradient checkpointing on the 4 unfrozen
vision blocks ONLY.
Both encode_observation copies (modeling_base.py and the
SERAVLAV3Model override in modeling_sera_vla_v3.py) now route the
grad-enabled vision call through a new SERAVLAModel helper,
`_vision_forward_grad`:
- classic finetune path (finetune_vision_last_n_layers > 0, no
UF): returns self.tips.vision_encoder(flat) exactly as before;
- UF path active (v4_uf_vision_blocks > 0 and _uf_unfrozen): the
tower is run manually (prepare_tokens_with_masks -> blocks ->
norm -> head triple, replicating VisionTransformer.forward for
the no-mask case); the token stream is detached and given
requires_grad at the boundary of the first unfrozen block
(everything upstream is frozen, so no graph is lost), and each
unfrozen block runs under
torch.utils.checkpoint.checkpoint(use_reentrant=False).
The backbone is forced to eval mode by SERAVLAModel.train(), so
the blocks contain no active dropout/drop-path and the
recomputation in backward is exact.
Backup suffix: .bak-uffix2-20261120. Exact-match, count==1
asserts.
"""
import py_compile
import shutil
import sys
from pathlib import Path
SRC = Path.home() / "lerobot/src/lerobot/policies/sera_vla_v3"
BAK_SUFFIX = ".bak-uffix2-20261120"
METHOD = ''' def _vision_forward_grad(self, flat_images: Tensor):
"""Direct vision-tower forward for the grad-enabled path.
Classic finetune runs delegate to the HF encoder exactly as
before. On the scheduled-unfreeze (UF) path, once the flip
has happened, the last ``v4_uf_vision_blocks`` blocks run
under gradient checkpointing to cap activation memory
(everything upstream of them is frozen, so the token stream
is re-anchored with detach + requires_grad at their input
boundary and no graph is lost). The manual loop replicates
VisionTransformer.forward for the no-mask case: blocks,
final norm, then the (identity) head applied to the CLS and
register slices.
"""
vision_encoder = self.tips.vision_encoder
uf_n = int(getattr(self.config, "v4_uf_vision_blocks", 0) or 0)
if not (uf_n and getattr(self, "_uf_unfrozen", False)):
return vision_encoder(flat_images)
x = vision_encoder.prepare_tokens_with_masks(flat_images, None)
n_blocks = len(vision_encoder.blocks)
for i, blk in enumerate(vision_encoder.blocks):
if i >= n_blocks - uf_n:
if i == n_blocks - uf_n:
x = x.detach().requires_grad_(True)
x = torch.utils.checkpoint.checkpoint(
blk, x, use_reentrant=False)
else:
x = blk(x)
x_norm = vision_encoder.norm(x)
n_reg = vision_encoder.num_register_tokens
return (
vision_encoder.head(x_norm[:, :1]),
vision_encoder.head(x_norm[:, 1 : n_reg + 1]),
x_norm[:, n_reg + 1 :],
)
def _tokenize(self, instructions: Sequence[str], device: torch.device) -> tuple[Tensor, Tensor]:
'''
EDITS = {
"modeling_base.py": [
(
""" if _vision_grad:
cls_token, register_tokens, patch_tokens = self.tips.vision_encoder(images.flatten(0, 1))
""",
""" if _vision_grad:
cls_token, register_tokens, patch_tokens = self._vision_forward_grad(images.flatten(0, 1))
""",
),
(
""" def _tokenize(self, instructions: Sequence[str], device: torch.device) -> tuple[Tensor, Tensor]:
""",
METHOD,
),
],
"modeling_sera_vla_v3.py": [
(
""" if _vision_grad:
cls, registers, patches = self.tips.vision_encoder(images.flatten(0, 1))
""",
""" if _vision_grad:
cls, registers, patches = self._vision_forward_grad(images.flatten(0, 1))
""",
),
],
}
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 FIX 2 DONE")
return 0
if __name__ == "__main__":
sys.exit(main())