File size: 5,972 Bytes
b26bdfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c777571
b26bdfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c777571
b26bdfa
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#!/usr/bin/env python3
"""LeRobot training with ONE documented change per course variant (Phase 2, Parts A–C).

Runs LeRobot 0.7.0's own `lerobot-train` (lerobot.scripts.lerobot_train:main) unchanged, after applying the
variant's patch. All remaining CLI args are passed through to LeRobot.

Variants (see reports/plan_phase2_models_ablations.md):
  stock         no patch (A1 ACT, A2 Diffusion, A3/B0/C1 SmolVLA default: vision + LM frozen, expert trained)
  vision_only   C2: SmolVLA with the LM frozen but the vision encoder TRAINABLE. Not expressible with SmolVLA's flags,
                because train_expert_only freezes the whole VLM, including vision.
Other variants (C3/C4) are plain LeRobot flags:
  C3: --policy.freeze_vision_encoder=true  --policy.train_expert_only=false
  C4: --policy.freeze_vision_encoder=false --policy.train_expert_only=false

PiBehavior-lite patches (Part B, experiments/lerobot/variants.py), combinable with any variant:
  --corr-noise assets/libero_chunk_L.pt    B1 correlated noise
  --task-ids assets/libero_task_ids.json   B2 opaque task ids instead of language
  --multisample K                          B5 K flow-matching draws per VLM pass
  --kv-mix                                 B6 mixed-layer KV (eval must pass --kv-mix too)
  --fast-aux assets/fast_tokenizer         B4 FAST auxiliary loss (training only; needs a trainable VLM)
  --stage assets/libero_task_ids.json      B3 stage token + stage head (eval must pass --stage too)
  --geco                                   GeCO time-unconditional flow matching (arXiv 2603.17834; eval --geco too)

Usage: envs/lerobot/.venv/bin/python experiments/lerobot/train_variant.py --variant stock [patches] -- <lerobot-train args>
"""
import argparse
import json
import sys


def patch_vision_only():
    from lerobot.policies.smolvla import smolvlm_with_expert as M
    orig = M.SmolVLMWithExpertModel.set_requires_grad

    def set_requires_grad(self):
        orig(self)  # freezes the whole VLM (train_expert_only=True expected)
        vm = self.get_vlm_model().vision_model
        for p in vm.parameters():
            p.requires_grad = True
        # the connector (vision -> LM projection) belongs to the "eyes" as well
        for p in self.get_vlm_model().connector.parameters():
            p.requires_grad = True

    orig_train = M.SmolVLMWithExpertModel.train

    def train(self, mode: bool = True):
        orig_train(self, mode)
        if mode:
            self.get_vlm_model().vision_model.train()
            self.get_vlm_model().connector.train()
        return self

    M.SmolVLMWithExpertModel.set_requires_grad = set_requires_grad
    M.SmolVLMWithExpertModel.train = train
    print("[train_variant] vision_only: vision encoder + connector trainable, language model frozen", flush=True)


def report_trainable():
    """Log trainable parameter counts per block once the policy is built (for the anatomy table)."""
    from lerobot.policies.smolvla import modeling_smolvla as S
    orig = S.SmolVLAPolicy.__init__

    def init(self, *a, **k):
        orig(self, *a, **k)
        groups = {}
        for n, p in self.named_parameters():
            g = ("vision" if "vision_model" in n else "connector" if "connector" in n else
                 "language_model" if ".vlm." in n or "text_model" in n else "action_expert" if "lm_expert" in n else "other")
            t = groups.setdefault(g, [0, 0])
            t[0] += p.numel()
            t[1] += p.numel() if p.requires_grad else 0
        print("[train_variant] params(total, trainable):", json.dumps(groups), flush=True)

    S.SmolVLAPolicy.__init__ = init


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--variant", default="stock", choices=["stock", "vision_only"])
    ap.add_argument("--corr-noise", default=None)
    ap.add_argument("--task-ids", default=None)
    ap.add_argument("--multisample", type=int, default=1)
    ap.add_argument("--kv-mix", action="store_true")
    ap.add_argument("--fast-aux", default=None)
    ap.add_argument("--fast-weight", type=float, default=0.1)
    ap.add_argument("--stage", default=None)
    ap.add_argument("--geco", action="store_true")
    ap.add_argument("--geco-zero-pad", action="store_true", help="GeCO with SmolVLA's padded action dims held at 0")
    a, rest = ap.parse_known_args()
    if rest and rest[0] == "--":
        rest = rest[1:]
    if a.variant == "vision_only":
        patch_vision_only()
    import importlib.util
    from pathlib import Path
    spec = importlib.util.spec_from_file_location("variants", Path(__file__).with_name("variants.py"))
    V = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(V)
    if a.corr_noise:
        V.patch_correlated_noise(a.corr_noise)
    if a.task_ids:
        V.patch_task_id_prompts(a.task_ids)
    if a.multisample > 1:
        V.patch_multisample(a.multisample)
    if a.kv_mix:
        V.patch_kv_mix()  # after B5 so the two-pass forward keeps K
    if a.stage and a.fast_aux:
        sys.exit("B3 and B4 each replace the training forward; combine them in one forward first")
    if a.geco and (a.stage or a.fast_aux or a.multisample > 1):
        sys.exit("GeCO replaces the training forward; it is not combined with B3/B4/B5")
    if a.geco:
        V.patch_geco(zero_pad=a.geco_zero_pad)
    if a.stage:
        V.patch_stage(a.stage)
    if a.fast_aux:  # last: replaces the forward, keeping B5's K; B6's hook lives in the VLM forward
        from lerobot.datasets.lerobot_dataset import LeRobotDatasetMetadata
        V.patch_fast_aux(a.fast_aux, Path(LeRobotDatasetMetadata("HuggingFaceVLA/libero").root) / "meta/stats.json",
                         weight=a.fast_weight)
    try:
        report_trainable()
    except Exception as e:  # non-SmolVLA policies
        print("[train_variant] param report unavailable:", e)
    from lerobot.scripts.lerobot_train import main
    sys.argv = ["lerobot-train", *rest]
    main()