File size: 11,538 Bytes
b4396f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#!/usr/bin/env python3
"""REG-DROPOUT patch for the l30k JEDI-lite retrain (2026-11-20).

Adds ONE config flag, `v4_reg_dropout` (default 0.0), wired into the
attention + FFN of the TRAINABLE blocks only:
- modeling_base.py: FusionBlock (attn x3 + FFN), MoEBlock
  (attn x2 + SwiGLU FFN), SwiGLUExpert (dropout on the hidden
  activations feeding `down`; the returned z stays clean because
  the specialization loss consumes z).
- modeling_sera_vla_v3.py: ARMoEBlock, DenseBlock (same shell),
  DemoPerceiverBlock (demo reader + JEDI predictor blocks).
- configuration_sera_vla_v3.py: the flag + range validation.

The frozen TIPSv2 backbone is NOT touched. With the default 0.0,
nn.Dropout(0.0) and MultiheadAttention(dropout=0.0) are exact
identities and add no parameters, so every old run/checkpoint is
bit-identical and state-dict compatible.

Backups: <file>.bak-regdrop-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-regdrop-20261120"

EDITS = {
    "configuration_sera_vla_v3.py": [
        (
            """    v4_jedi_distractor_k: int = 2
    v4_flow_steps: int = 4
""",
            """    v4_jedi_distractor_k: int = 2
    v4_reg_dropout: float = 0.0
    v4_flow_steps: int = 4
""",
        ),
        (
            """        if not 0.0 <= self.v4_demo_dropout <= 1.0:
            raise ValueError(f"Invalid v4_demo_dropout: {self.v4_demo_dropout}")
""",
            """        if not 0.0 <= self.v4_demo_dropout <= 1.0:
            raise ValueError(f"Invalid v4_demo_dropout: {self.v4_demo_dropout}")
        if not 0.0 <= self.v4_reg_dropout < 1.0:
            raise ValueError(f"Invalid v4_reg_dropout: {self.v4_reg_dropout}")
""",
        ),
    ],
    "modeling_base.py": [
        (
            """class FusionBlock(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.norms = nn.ModuleList([nn.LayerNorm(512, eps=1e-5) for _ in range(4)])
        self.text_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True)
        self.vision_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True)
        self.self_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True)
        self.ffn = nn.Sequential(nn.Linear(512, 2048), nn.GELU(), nn.Linear(2048, 512))
""",
            """class FusionBlock(nn.Module):
    def __init__(self, dropout: float = 0.0) -> None:
        super().__init__()
        self.norms = nn.ModuleList([nn.LayerNorm(512, eps=1e-5) for _ in range(4)])
        self.text_attn = nn.MultiheadAttention(512, 8, dropout=dropout, bias=True, batch_first=True)
        self.vision_attn = nn.MultiheadAttention(512, 8, dropout=dropout, bias=True, batch_first=True)
        self.self_attn = nn.MultiheadAttention(512, 8, dropout=dropout, bias=True, batch_first=True)
        self.ffn = nn.Sequential(nn.Linear(512, 2048), nn.GELU(), nn.Dropout(dropout), nn.Linear(2048, 512))
""",
        ),
        (
            """class SwiGLUExpert(nn.Module):
    def __init__(self, width: int) -> None:
        super().__init__()
        self.gate = nn.Linear(512, width, bias=False)
        self.up = nn.Linear(512, width, bias=False)
        self.down = nn.Linear(width, 512, bias=False)

    def forward(self, x: Tensor) -> tuple[Tensor, Tensor]:
        z = F.silu(self.gate(x)) * self.up(x)
        return self.down(z), z
""",
            """class SwiGLUExpert(nn.Module):
    def __init__(self, width: int, dropout: float = 0.0) -> None:
        super().__init__()
        self.gate = nn.Linear(512, width, bias=False)
        self.up = nn.Linear(512, width, bias=False)
        self.down = nn.Linear(width, 512, bias=False)
        self.drop = nn.Dropout(dropout)

    def forward(self, x: Tensor) -> tuple[Tensor, Tensor]:
        z = F.silu(self.gate(x)) * self.up(x)
        return self.down(self.drop(z)), z
""",
        ),
        (
            """class MoEBlock(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.norms = nn.ModuleList([nn.LayerNorm(512, eps=1e-5) for _ in range(3)])
        self.self_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True)
        self.cross_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True)
        self.shared = SwiGLUExpert(1344)
        self.experts = nn.ModuleList(SwiGLUExpert(672) for _ in range(8))
""",
            """class MoEBlock(nn.Module):
    def __init__(self, dropout: float = 0.0) -> None:
        super().__init__()
        self.norms = nn.ModuleList([nn.LayerNorm(512, eps=1e-5) for _ in range(3)])
        self.self_attn = nn.MultiheadAttention(512, 8, dropout=dropout, bias=True, batch_first=True)
        self.cross_attn = nn.MultiheadAttention(512, 8, dropout=dropout, bias=True, batch_first=True)
        self.shared = SwiGLUExpert(1344, dropout)
        self.experts = nn.ModuleList(SwiGLUExpert(672, dropout) for _ in range(8))
""",
        ),
        (
            """        self.config = config
        self.tips = AutoModel.from_pretrained(
""",
            """        self.config = config
        _reg_drop = float(getattr(config, "v4_reg_dropout", 0.0))
        self.tips = AutoModel.from_pretrained(
""",
        ),
        (
            """        self.fusion = nn.ModuleList(FusionBlock() for _ in range(3))
""",
            """        self.fusion = nn.ModuleList(FusionBlock(dropout=_reg_drop) for _ in range(3))
""",
        ),
        (
            """        self.blocks = nn.ModuleList(MoEBlock() for _ in range(4))
""",
            """        self.blocks = nn.ModuleList(MoEBlock(dropout=_reg_drop) for _ in range(4))
""",
        ),
    ],
    "modeling_sera_vla_v3.py": [
        (
            """    def __init__(self) -> None:
        super().__init__()
        self.norms = nn.ModuleList([nn.LayerNorm(512, eps=1e-5) for _ in range(3)])
        self.self_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True)
        self.cross_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True)
        self.shared = SwiGLUExpert(1344)
        self.experts = nn.ModuleList(SwiGLUExpert(672) for _ in range(8))

    def forward(
        self, x: Tensor, context: Tensor, indices: Tensor, weights: Tensor,
        key_padding: Tensor | None,
    ) -> tuple[Tensor, Tensor | None]:
""",
            """    def __init__(self, dropout: float = 0.0) -> None:
        super().__init__()
        self.norms = nn.ModuleList([nn.LayerNorm(512, eps=1e-5) for _ in range(3)])
        self.self_attn = nn.MultiheadAttention(512, 8, dropout=dropout, bias=True, batch_first=True)
        self.cross_attn = nn.MultiheadAttention(512, 8, dropout=dropout, bias=True, batch_first=True)
        self.shared = SwiGLUExpert(1344, dropout)
        self.experts = nn.ModuleList(SwiGLUExpert(672, dropout) for _ in range(8))

    def forward(
        self, x: Tensor, context: Tensor, indices: Tensor, weights: Tensor,
        key_padding: Tensor | None,
    ) -> tuple[Tensor, Tensor | None]:
""",
        ),
        (
            """    def __init__(self) -> None:
        super().__init__()
        self.norms = nn.ModuleList([nn.LayerNorm(512, eps=1e-5) for _ in range(3)])
        self.self_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True)
        self.cross_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True)
        self.shared = SwiGLUExpert(1344)
        self.dense = SwiGLUExpert(2688)
""",
            """    def __init__(self, dropout: float = 0.0) -> None:
        super().__init__()
        self.norms = nn.ModuleList([nn.LayerNorm(512, eps=1e-5) for _ in range(3)])
        self.self_attn = nn.MultiheadAttention(512, 8, dropout=dropout, bias=True, batch_first=True)
        self.cross_attn = nn.MultiheadAttention(512, 8, dropout=dropout, bias=True, batch_first=True)
        self.shared = SwiGLUExpert(1344, dropout)
        self.dense = SwiGLUExpert(2688, dropout)
""",
        ),
        (
            """    def __init__(self) -> None:
        super().__init__()
        self.norm_q = nn.LayerNorm(512, eps=1e-5)
        self.norm_kv = nn.LayerNorm(512, eps=1e-5)
        self.cross_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True)
        self.norm_s = nn.LayerNorm(512, eps=1e-5)
        self.self_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True)
        self.norm_f = nn.LayerNorm(512, eps=1e-5)
        self.ffn = nn.Sequential(nn.Linear(512, 2048), nn.GELU(), nn.Linear(2048, 512))
""",
            """    def __init__(self, dropout: float = 0.0) -> None:
        super().__init__()
        self.norm_q = nn.LayerNorm(512, eps=1e-5)
        self.norm_kv = nn.LayerNorm(512, eps=1e-5)
        self.cross_attn = nn.MultiheadAttention(512, 8, dropout=dropout, bias=True, batch_first=True)
        self.norm_s = nn.LayerNorm(512, eps=1e-5)
        self.self_attn = nn.MultiheadAttention(512, 8, dropout=dropout, bias=True, batch_first=True)
        self.norm_f = nn.LayerNorm(512, eps=1e-5)
        self.ffn = nn.Sequential(nn.Linear(512, 2048), nn.GELU(), nn.Dropout(dropout), nn.Linear(2048, 512))
""",
        ),
        (
            """        super().__init__(config)
        self.goal = GroundedGoal()
""",
            """        super().__init__(config)
        _reg_drop = float(getattr(config, "v4_reg_dropout", 0.0))
        self.goal = GroundedGoal()
""",
        ),
        (
            """        self.ar_blocks = nn.ModuleList(ARMoEBlock() for _ in range(4))
""",
            """        self.ar_blocks = nn.ModuleList(ARMoEBlock(dropout=_reg_drop) for _ in range(4))
""",
        ),
        (
            """            self.blocks = nn.ModuleList(DenseBlock() for _ in range(4))
""",
            """            self.blocks = nn.ModuleList(DenseBlock(dropout=_reg_drop) for _ in range(4))
""",
        ),
        (
            """        self.demo_blocks = nn.ModuleList(DemoPerceiverBlock() for _ in range(2))
""",
            """        self.demo_blocks = nn.ModuleList(DemoPerceiverBlock(dropout=_reg_drop) for _ in range(2))
""",
        ),
        (
            """        self.demo_pred_blocks = nn.ModuleList(
            DemoPerceiverBlock() for _ in range(2))
""",
            """        self.demo_pred_blocks = nn.ModuleList(
            DemoPerceiverBlock(dropout=_reg_drop) for _ in range(2))
""",
        ),
    ],
}


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("REG-DROPOUT PATCH DONE")
    return 0


if __name__ == "__main__":
    sys.exit(main())