File size: 46,231 Bytes
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
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
"""PiBehavior-lite: PiBehavior's additions ported onto SmolVLA (LeRobot 0.7.0) as opt-in patches. Phase 2, Part B.

These are ported mechanisms, NOT the authors' training runs. Each patch changes one thing and is documented
against the PiBehavior source it mirrors. Reference implementations here:

  B1 correlated noise       patch_correlated_noise(L)       train + infer. eps = L z on the real action dims
  B2 task-id prompts        patch_task_id_prompts(mapping)  train + infer. "pick up the bowl..." -> "task 17"
  B5 multi-sample FM        patch_multisample(K)            train. One prefix (VLM) pass, K action-expert passes
  B8 action compression     patch_compression(...)          infer. Execute n_exec predicted actions in n_steps
  C2 vision-only training   see train_variant.py

Specified as challenge exercises (book chapter 38): B3 stage head + tracker, B4 FAST aux loss, B6 mixed-layer KV,
B7 inpainting (LeRobot's RTC does not support select_action, which LIBERO eval uses), B9 gripper rule.

Pure numpy/torch helpers (no LeRobot import) are unit-tested in tests/unit/test_lerobot_variants.py.
"""

from __future__ import annotations

import json
import math
from pathlib import Path

import numpy as np

# ------------------------------------------------------------------ pure helpers (tested)


def chunk_windows(episodes: list[np.ndarray], horizon: int, n: int, rng: np.random.Generator) -> np.ndarray:
    """Sample n action chunks [horizon, D] that stay inside one episode (PiBehavior computes Σ the same way)."""
    lens = np.array([len(e) for e in episodes])
    ok = np.flatnonzero(lens >= horizon)
    if not len(ok):
        raise ValueError("no episode is long enough for the horizon")
    w = (lens[ok] - horizon + 1).astype(float)
    ep = rng.choice(ok, size=n, p=w / w.sum())
    out = np.empty((n, horizon, episodes[0].shape[1]))
    for i, e in enumerate(ep):
        s = rng.integers(0, lens[e] - horizon + 1)
        out[i] = episodes[e][s:s + horizon]
    return out


def chunk_correlation(chunks: np.ndarray) -> np.ndarray:
    """Correlation of flattened TIME-MAJOR chunks [t*D + d] (same layout as PiBehavior's 960x960 matrix)."""
    X = chunks.reshape(len(chunks), -1)
    C = np.corrcoef(X, rowvar=False)
    C[~np.isfinite(C)] = 0.0  # constant dims
    np.fill_diagonal(C, 1.0)
    return C


def shrunk_cholesky(C: np.ndarray, beta: float = 0.5) -> np.ndarray:
    """L with L Lᵀ = βC + (1-β)I. PiBehavior uses β = 0.5 (claims C-CORR-*)."""
    S = beta * C + (1.0 - beta) * np.eye(len(C))
    return np.linalg.cholesky(S)


def correlated_noise(z: np.ndarray, L: np.ndarray, horizon: int, real_dims: int) -> np.ndarray:
    """z: [B, horizon, Dpad] iid normal. Returns z with the real dims replaced by L·z (time-major)."""
    B = z.shape[0]
    zr = z[:, :, :real_dims].reshape(B, horizon * real_dims)
    out = z.copy()
    out[:, :, :real_dims] = (zr @ L.T).reshape(B, horizon, real_dims)
    return out


def compress_normalized(chunk: np.ndarray, n_exec: int, n_steps: int, delta_dims: slice, mean: np.ndarray,
                        std: np.ndarray) -> np.ndarray:
    """Resample the first n_exec NORMALISED actions to n_steps. Delta dims are scaled by s = n_exec/n_steps in RAW
    units, so the commanded displacement is preserved: raw' = s·raw  ⇔  n' = s·n + (s-1)·mean/std."""
    a = chunk[:n_exec]
    src = np.linspace(0.0, 1.0, n_exec)
    dst = np.linspace(0.0, 1.0, n_steps)
    try:
        from scipy.interpolate import interp1d
        out = np.stack([interp1d(src, a[:, d], kind="cubic")(dst) for d in range(a.shape[1])], 1)
    except ImportError:  # pragma: no cover
        out = np.stack([np.interp(dst, src, a[:, d]) for d in range(a.shape[1])], 1)
    s = n_exec / n_steps
    d = delta_dims
    out[:, d] = s * out[:, d] + (s - 1.0) * (mean[d] / std[d])
    return out


# ------------------------------------------------------------------ B6 / B7 pure helpers (tested)


def kv_mix(x, coeffs, bias):
    """B6 core. x: [L, B, H, T, Dh] per-layer K (or V) stacked in DynamicCache layout ([B, H, T, Dh] per layer).
    Returns y[l] = sum_s coeffs[l, s] x[s] + bias[l] (bias [L, H, Dh]), in fp32, cast back to x.dtype.
    Same operation as PiBehavior's KVCacheTransform (einsum 'ds,sbtkh->dbtkh'), with the cache axes reordered.
    RoPE commutes with this mix: every layer's keys at one position share the same rotation."""
    import torch
    y = torch.einsum("ls,sbhtk->lbhtk", coeffs.float(), x.float()) + bias.float()[:, None, :, None, :]
    return y.to(x.dtype)


def inpaint_correction_matrix(Sigma: np.ndarray, n_O: int) -> np.ndarray:
    """B7. M = Σ_UO Σ_OO⁻¹ for O = the first n_O flat (time-major) indices, U = the rest.
    Same ridge and PD solve as PiBehavior._precompute_correction_matrix."""
    from scipy.linalg import solve
    O, U = np.arange(n_O), np.arange(n_O, len(Sigma))
    S_OO, S_UO = Sigma[np.ix_(O, O)], Sigma[np.ix_(U, O)]
    eps = 1e-6 * max(float(np.mean(np.diag(S_OO))), 1.0)
    return solve(S_OO + eps * np.eye(n_O), S_UO.T, assume_a="pos").T


def inpaint_correct(x_flat, t_new: float, x0_O, z_O, M, max_correction: float = 1.0):
    """B7. One PiBehavior inpainting correction on flat [B, H*D] (O = first |O| entries).
    Hard-set x[O] to its point on the straight noise→data path, propagate δ_O to U through M unless the
    propagated correction exceeds max_correction (upstream skips it for the whole batch; here per sample)."""
    import torch
    n_O = x0_O.shape[1]
    desired = (1.0 - t_new) * x0_O + t_new * z_O
    delta_O = desired - x_flat[:, :n_O]
    delta_U = delta_O @ M.T
    ok = (delta_U.abs().amax(dim=1, keepdim=True) <= max_correction).to(x_flat.dtype)
    return torch.cat([desired, x_flat[:, n_O:] + ok * delta_U], dim=1), int((ok == 0).sum())


# ------------------------------------------------------------------ LeRobot patches


def _vla():
    from lerobot.policies.smolvla import modeling_smolvla as S
    return S


def patch_correlated_noise(L_path: str | Path):
    """B1. Replace SmolVLA's iid noise with correlated noise on the real action dims, in training AND inference."""
    import torch
    S = _vla()
    blob = torch.load(L_path)
    L, horizon, real = blob["L"].float(), int(blob["horizon"]), int(blob["real_dims"])

    def sample_noise(self, shape, device):
        z = torch.randn(shape, device=device, dtype=torch.float32)
        B, H, D = shape
        assert H == horizon, f"chunk_size {H} != horizon {horizon} used to build L"
        zr = z[:, :, :real].reshape(B, H * real)
        z = z.clone()
        z[:, :, :real] = (zr @ L.to(device).T).reshape(B, H, real)
        return z

    S.VLAFlowMatching.sample_noise = sample_noise
    print(f"[variants] B1 correlated noise: L {tuple(L.shape)} (beta={blob.get('beta')})", flush=True)


def patch_task_id_prompts(mapping_path: str | Path):
    """B2. Replace each language instruction with an opaque id ("task 17"), like PiBehavior's task embeddings.
    Same mapping at train and eval time. Unknown instructions raise (silent fallback would leak language back in)."""
    from lerobot.processor import tokenizer_processor as T
    mapping = json.loads(Path(mapping_path).read_text())
    orig = T.TokenizerProcessorStep.get_task

    def get_task(self, transition):
        tasks = orig(self, transition)
        if tasks is None:
            return None
        try:
            return [mapping[t.strip()] for t in tasks]
        except KeyError as e:
            raise KeyError(f"instruction not in task-id mapping: {e}") from None

    T.TokenizerProcessorStep.get_task = get_task
    print(f"[variants] B2 task-id prompts: {len(mapping)} instructions -> ids", flush=True)


def patch_multisample(K: int):
    """B5. One prefix (VLM) pass, K noise/time draws through the action expert, loss averaged over draws.
    Mirrors PiBehavior's multi-sample flow matching (num_flow_samples=15). Prefix gradients still flow (the state
    projection is trainable), so the prefix graph is shared by all K expert passes."""
    import torch
    import torch.nn.functional as F
    from lerobot.policies.common.flow_matching import FlowConvention, make_flow_matching_inputs
    S = _vla()

    def forward(self, images, img_masks, lang_tokens, lang_masks, state, actions, noise=None, time=None):
        prefix_embs, prefix_pad, prefix_att = self.embed_prefix(images, img_masks, lang_tokens, lang_masks, state=state)
        att2d = S.make_att_2d_masks(prefix_pad, prefix_att)
        pos = torch.cumsum(prefix_pad, dim=1) - 1
        _, pkv = self.vlm_with_expert.forward(attention_mask=att2d, position_ids=pos, past_key_values=None,
                                              inputs_embeds=[prefix_embs, None], use_cache=True)
        losses = []
        for k in range(K):
            n = noise if (noise is not None and k == 0) else self.sample_noise(actions.shape, actions.device)
            t = time if (time is not None and k == 0) else self.sample_time(actions.shape[0], actions.device)
            x_t, u_t, _ = make_flow_matching_inputs(actions, n, t, convention=FlowConvention.NOISE_AT_ONE)
            v_t = self.denoise_step(prefix_pad, pkv, x_t, t)
            losses.append(F.mse_loss(u_t, v_t, reduction="none"))
        return torch.stack(losses).mean(0)

    S.VLAFlowMatching.forward = forward
    S.VLAFlowMatching._course_two_pass = K
    print(f"[variants] B5 multi-sample flow matching: K={K}", flush=True)


def patch_kv_mix():
    """B6. Mixed-layer KV: after the VLM fills its prefix cache, every layer's K and V become learned linear
    combinations of all layers' K and V plus a bias (PiBehavior KVCacheTransform). Identity init, so the model
    starts exactly as stock. The mix needs every layer's K/V before the expert runs, so training switches to
    the two-pass forward (prefix pass, then expert over the cache; = patch_multisample(1), checked equal to
    stock to 2.7e-5). Train AND eval must apply this patch (the parameters live in the checkpoint)."""
    import torch
    import torch.nn as nn
    from lerobot.policies.smolvla import smolvlm_with_expert as M
    S = _vla()

    class KVCacheMix(nn.Module):
        def __init__(self, n_layers, n_kv_heads, head_dim):
            super().__init__()
            self.k_coeffs = nn.Parameter(torch.eye(n_layers))
            self.v_coeffs = nn.Parameter(torch.eye(n_layers))
            self.k_bias = nn.Parameter(torch.zeros(n_layers, n_kv_heads, head_dim))
            self.v_bias = nn.Parameter(torch.zeros(n_layers, n_kv_heads, head_dim))

        def forward(self, cache):
            layers = cache.layers
            k = kv_mix(torch.stack([lay.keys for lay in layers]), self.k_coeffs, self.k_bias)
            v = kv_mix(torch.stack([lay.values for lay in layers]), self.v_coeffs, self.v_bias)
            for i, lay in enumerate(layers):
                lay.keys, lay.values = k[i], v[i]
            return cache

    orig_init = M.SmolVLMWithExpertModel.__init__
    orig_fwd = M.SmolVLMWithExpertModel.forward

    def __init__(self, *a, **k):
        orig_init(self, *a, **k)
        tc = self.config.text_config
        self.kv_mix = KVCacheMix(self.num_vlm_layers, tc.num_key_value_heads, tc.head_dim)

    def forward(self, attention_mask=None, position_ids=None, past_key_values=None, inputs_embeds=None,
                use_cache=None):
        prefill = bool(use_cache) and past_key_values is None and inputs_embeds[1] is None
        out, pkv = orig_fwd(self, attention_mask=attention_mask, position_ids=position_ids,
                            past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache)
        if prefill:
            pkv = self.kv_mix(pkv)
        return out, pkv

    M.SmolVLMWithExpertModel.__init__ = __init__
    M.SmolVLMWithExpertModel.forward = forward
    if not getattr(S.VLAFlowMatching, "_course_two_pass", 0):
        patch_multisample(1)
    print("[variants] B6 mixed-layer KV: learned layer mixing of the prefix cache (identity init)", flush=True)


def patch_inpainting(L_path: str | Path, keep: int = 4, threshold: float = 0.3, max_correction: float = 1.0):
    """B7. Rolling correlated inpainting (PiBehavior sample_actions + B1KPolicyWrapper). At each re-plan the
    `keep` actions that the previous chunk planned for the next steps (indices n_action_steps .. +keep) are
    pinned at the start of the new chunk; the rest of the chunk is corrected through Σ_UO Σ_OO⁻¹ with
    Σ = L Lᵀ (the shrunk B1 covariance). Constraint enforced only while t > threshold (0.3 upstream).
    Eval only. Intended on top of B1 (same L), as in PiBehavior."""
    import torch
    S = _vla()
    blob = torch.load(L_path)
    L, horizon, real = blob["L"].double(), int(blob["horizon"]), int(blob["real_dims"])
    M_np = inpaint_correction_matrix((L @ L.T).numpy(), keep * real)
    M_cpu = torch.tensor(M_np, dtype=torch.float32)
    orig_sample, orig_reset = S.VLAFlowMatching.sample_actions, S.SmolVLAPolicy.reset
    stats = {"chunks": 0, "inpainted": 0, "skipped_propagations": 0}

    def sample_actions(self, images, img_masks, lang_tokens, lang_masks, state, noise=None, initial_actions=None,
                       **kw):
        if initial_actions is None:
            return orig_sample(self, images, img_masks, lang_tokens, lang_masks, state, noise=noise, **kw)
        B, dev, H, D = state.shape[0], state.device, self.config.chunk_size, self.config.max_action_dim
        assert H == horizon, f"chunk_size {H} != horizon {horizon} used to build L"
        x = self.sample_noise((B, H, D), dev) if noise is None else noise.to(dev, torch.float32)
        pe, pp, pa = self.embed_prefix(images, img_masks, lang_tokens, lang_masks, state=state)
        _, pkv = self.vlm_with_expert.forward(attention_mask=S.make_att_2d_masks(pp, pa),
                                              position_ids=torch.cumsum(pp, 1) - 1, past_key_values=None,
                                              inputs_embeds=[pe, None], use_cache=True)
        M_ = M_cpu.to(dev)
        z_O = x[:, :keep, :real].reshape(B, -1).clone()
        x0_O = initial_actions[:, :keep, :real].to(dev, torch.float32).reshape(B, -1)
        n = self.config.num_steps
        dt, t = -1.0 / n, 1.0
        for _ in range(n):
            v = self.denoise_step(pp, pkv, x, torch.full((B,), t, dtype=torch.float32, device=dev))
            x = x + dt * v
            t_new = t + dt
            if t_new > threshold:
                flat, skipped = inpaint_correct(x[:, :, :real].reshape(B, -1), t_new, x0_O, z_O, M_, max_correction)
                x = torch.cat([flat.reshape(B, H, real), x[:, :, real:]], dim=2)
                stats["skipped_propagations"] += skipped
            t = t_new
        return x

    def select_action(self, batch, *, noise=None, **kw):
        self.eval()
        batch = self._prepare_batch(batch)
        self._queues = S.populate_queues(self._queues, batch, exclude_keys=[S.ACTION])
        if len(self._queues[S.ACTION]) == 0:
            prev = getattr(self, "_inpaint_next", None)
            actions = self._get_action_chunk(batch, noise=noise, initial_actions=prev)  # [B, H, real] normalised
            n = self.config.n_action_steps
            self._inpaint_next = actions[:, n:n + keep].clone() if n + keep <= actions.shape[1] else None
            stats["chunks"] += 1
            stats["inpainted"] += prev is not None
            self._queues[S.ACTION].extend(actions.transpose(0, 1)[:n])
        return self._queues[S.ACTION].popleft()

    def reset(self):
        orig_reset(self)
        self._inpaint_next = None

    S.VLAFlowMatching.sample_actions = sample_actions
    S.SmolVLAPolicy.select_action = select_action
    S.SmolVLAPolicy.reset = reset
    print(f"[variants] B7 correlated inpainting: keep={keep} actions, threshold={threshold}, "
          f"M {tuple(M_np.shape)}", flush=True)
    return stats


class GripperRetry:
    """B9 rule state for one environment (pure python/numpy, tested). LIBERO ANALOGUE of PiBehavior's
    correction_rules (which use per-task stage tables to spot a gripper closed where demos never close it).
    LIBERO has no stage labels, so the trigger is the physical symptom of a missed grasp: the gripper has been
    commanded closed for >= min_closed steps and the finger gap is below gap_thr (closed on nothing).
    Thresholds from the demos: settled-closed gap median 0.028 m, 0.1% quantile 0.0017 m.
    Response, like upstream: open the gripper for open_steps (one re-plan) and let the policy try again."""

    def __init__(self, gap_thr=0.002, min_closed=15, open_steps=10, max_retries=5):
        self.gap_thr, self.min_closed, self.open_steps, self.max_retries = gap_thr, min_closed, open_steps, max_retries
        self.reset()

    def reset(self):
        self.close_run, self.open_left, self.retries = 0, 0, 0

    def should_trigger(self, gap: float) -> bool:
        fire = (self.open_left == 0 and self.retries < self.max_retries and self.close_run >= self.min_closed
                and gap < self.gap_thr)
        if fire:
            self.open_left, self.retries, self.close_run = self.open_steps, self.retries + 1, 0
        return fire

    def after_action(self, raw_gripper_cmd: float) -> bool:
        """Call with the gripper command about to be executed (LIBERO: +1 close, -1 open).
        Returns True if this step's command must be overridden to open."""
        override = self.open_left > 0
        if override:
            self.open_left -= 1
            self.close_run = 0
        else:
            self.close_run = self.close_run + 1 if raw_gripper_cmd > 0 else 0
        return override


def patch_gripper_retry(stats_path: str | Path, **rule_kw):
    """B9. Wrap select_action with GripperRetry (eval only, eval batch_size=1). State and actions inside the
    policy are MEAN_STD-normalised, so the rule converts with the dataset statistics."""
    import torch
    S = _vla()
    st = json.loads(Path(stats_path).read_text())
    s_mean, s_std = np.asarray(st["observation.state"]["mean"]), np.asarray(st["observation.state"]["std"])
    a_mean, a_std = float(st["action"]["mean"][6]), float(st["action"]["std"][6])
    open_norm = (-1.0 - a_mean) / a_std
    orig_select, orig_reset = S.SmolVLAPolicy.select_action, S.SmolVLAPolicy.reset
    stats = {"episodes": 0, "triggers": 0, "episodes_with_trigger": 0}

    def select_action(self, batch, **kw):
        rule = self._grip_rule
        x = batch[S.OBS_STATE]
        assert x.shape[0] == 1, "B9 rule state is per environment: run eval with --eval.batch_size=1"
        fingers = x[0, 6:8].detach().float().cpu().numpy() * s_std[6:8] + s_mean[6:8]
        if rule.should_trigger(float(fingers[0] - fingers[1])):
            self._queues[S.ACTION].clear()  # re-plan from the current observation
            stats["triggers"] += 1
            stats["episodes_with_trigger"] += rule.retries == 1
        a = orig_select(self, batch, **kw)
        if rule.after_action(float(a[0, 6]) * a_std + a_mean):
            a = a.clone()
            a[:, 6] = torch.as_tensor(open_norm, dtype=a.dtype, device=a.device)
        return a

    def reset(self):
        orig_reset(self)
        self._grip_rule = GripperRetry(**rule_kw)
        stats["episodes"] += 1

    S.SmolVLAPolicy.select_action = select_action
    S.SmolVLAPolicy.reset = reset
    print(f"[variants] B9 gripper retry (LIBERO analogue): {rule_kw or 'defaults'}", flush=True)
    return stats


def fast_quantile_normalize(raw: np.ndarray, q01: np.ndarray, q99: np.ndarray) -> np.ndarray:
    """B4. PiBehavior's TokenizeFASTActions renormalises actions with GLOBAL QUANTILES to [-1, 1] before FAST,
    whatever the flow-matching normalisation is. Clipped, so the DCT symbol range stays bounded."""
    return np.clip(2.0 * (raw - q01) / np.maximum(q99 - q01, 1e-8) - 1.0, -1.0, 1.0)


def pad_fast_tokens(token_lists, max_len: int):
    """B4. Truncate/pad token id lists to [B, max_len] plus a validity mask (TokenizeFASTActions)."""
    ids, mask = np.zeros((len(token_lists), max_len), np.int64), np.zeros((len(token_lists), max_len), bool)
    for i, t in enumerate(token_lists):
        t = list(t)[:max_len]
        ids[i, :len(t)], mask[i, :len(t)] = t, True
    return ids, mask


def shift_right(ids, mask):
    """B4 teacher forcing: input = [BOS=0, t_0 .. t_{n-2}], BOS always valid (PiBehavior embed_prefix)."""
    ids_in = np.concatenate([np.zeros((len(ids), 1), ids.dtype), ids[:, :-1]], 1)
    mask_in = np.concatenate([np.ones((len(mask), 1), bool), mask[:, :-1]], 1)
    return ids_in, mask_in


def patch_fast_aux(tok_dir: str | Path, stats_path: str | Path, weight: float = 0.1, max_tokens: int = 128,
                   log_every: int = 50):
    """B4. FAST auxiliary loss (PiBehavior compute_detailed_loss steps 1-5), TRAINING ONLY:
      * the ground-truth chunk is FAST-tokenised (global-quantile renormalised, local DCT+BPE tokenizer);
      * shifted tokens [BOS=0, t_0..] get their OWN embedding table and are appended after the state token,
        fully causal (each token its own attention block); images/language/state cannot see them;
      * VLM outputs at those positions -> linear head -> cross-entropy on t_0.., weight 0.1;
      * the FAST entries are cropped from the prefix cache before the action expert runs, so the expert never
        attends to them, and inference is unchanged (no FAST tokens, as upstream).
    Only meaningful when the VLM is trainable (compare B4 with C3, not with A3).
    Upstream also uses token id 0 as BOS although 0 is a real FAST token; kept as is."""
    import importlib.util as ilu

    import torch
    import torch.nn as nn
    import torch.nn.functional as F
    from lerobot.policies.common.flow_matching import FlowConvention, make_flow_matching_inputs
    S = _vla()
    spec = ilu.spec_from_file_location("fast_tokenizer", Path(__file__).with_name("fast_tokenizer.py"))
    FT = ilu.module_from_spec(spec); spec.loader.exec_module(FT)
    tok = FT.FastTokenizer.load(tok_dir)
    st = json.loads(Path(stats_path).read_text())["action"]
    a_mean, a_std = np.asarray(st["mean"]), np.asarray(st["std"])
    q01, q99 = np.asarray(st["q01"]), np.asarray(st["q99"])
    real = len(a_mean)
    vocab = tok.vocab_size
    K = getattr(S.VLAFlowMatching, "_course_two_pass", 0) or 1
    orig_init, orig_pforward = S.VLAFlowMatching.__init__, S.SmolVLAPolicy.forward
    counter = {"step": 0, "ce": 0.0, "acc": 0.0}

    def __init__(self, *a, **k):
        orig_init(self, *a, **k)
        h = self.vlm_with_expert.config.text_config.hidden_size
        self.fast_embed = nn.Embedding(vocab, h)
        nn.init.normal_(self.fast_embed.weight, std=0.02)
        self.fast_proj = nn.Linear(h, vocab)

    def fast_targets(self, actions):
        raw = actions[:, :, :real].detach().float().cpu().numpy() * a_std + a_mean
        ids, mask = pad_fast_tokens(tok.encode(fast_quantile_normalize(raw, q01, q99)), max_tokens)
        ids_in, mask_in = shift_right(ids, mask)
        dev = actions.device
        return tuple(torch.as_tensor(x, device=dev) for x in (ids, mask, ids_in, mask_in))

    def forward(self, images, img_masks, lang_tokens, lang_masks, state, actions, noise=None, time=None):
        pe, pp, pa = self.embed_prefix(images, img_masks, lang_tokens, lang_masks, state=state)
        n_prefix = pe.shape[1]
        ids, mask, ids_in, mask_in = fast_targets(self, actions)
        fe = self.fast_embed(ids_in) * math.sqrt(pe.shape[-1])  # same scaling SmolVLA applies to language
        pe_f = torch.cat([pe, fe.to(pe.dtype)], 1)
        pp_f = torch.cat([pp, mask_in], 1)
        pa_f = torch.cat([pa, torch.ones_like(mask_in)], 1)  # causal: every FAST token starts a new block
        (pout, _), pkv = self.vlm_with_expert.forward(
            attention_mask=S.make_att_2d_masks(pp_f, pa_f), position_ids=torch.cumsum(pp_f, 1) - 1,
            past_key_values=None, inputs_embeds=[pe_f, None], use_cache=True)
        logits = self.fast_proj(pout[:, n_prefix:].float())
        ce = F.cross_entropy(logits.transpose(1, 2), ids, reduction="none")
        m = mask.float()
        ce = (ce * m).sum(1) / m.sum(1).clamp_min(1)  # [B], mean over valid tokens
        acc = (((logits.argmax(-1) == ids).float() * m).sum(1) / m.sum(1).clamp_min(1)).mean()
        for lay in pkv.layers:  # drop FAST from the cache: the action expert never attends to it
            lay.crop(n_prefix - lay.get_seq_length())
        losses = []
        for k in range(K):
            n = noise if (noise is not None and k == 0) else self.sample_noise(actions.shape, actions.device)
            t = time if (time is not None and k == 0) else self.sample_time(actions.shape[0], actions.device)
            x_t, u_t, _ = make_flow_matching_inputs(actions, n, t, convention=FlowConvention.NOISE_AT_ONE)
            losses.append(F.mse_loss(u_t, self.denoise_step(pp, pkv, x_t, t), reduction="none"))
        self._course_aux = (ce, acc)
        return torch.stack(losses).mean(0)

    def pforward(self, batch, noise=None, time=None, reduction="mean"):
        loss, d = orig_pforward(self, batch, noise=noise, time=time, reduction=reduction)
        aux = getattr(self.model, "_course_aux", None)
        if aux is None:
            return loss, d
        self.model._course_aux = None
        ce, acc = aux
        loss = loss + weight * (ce if reduction == "none" else ce.mean())
        d["fast_loss"], d["fast_accuracy"] = float(ce.detach().mean()), float(acc)
        counter["step"] += 1; counter["ce"] += d["fast_loss"]; counter["acc"] += d["fast_accuracy"]
        if log_every and counter["step"] % log_every == 0:
            print(f"[variants] B4 step {counter['step']}: fast_ce={counter['ce'] / log_every:.3f} "
                  f"fast_acc={counter['acc'] / log_every:.3f}", flush=True)
            counter["ce"] = counter["acc"] = 0.0
        return loss, d

    S.VLAFlowMatching.__init__ = __init__
    S.VLAFlowMatching.forward = forward
    S.VLAFlowMatching._course_two_pass = K
    S.SmolVLAPolicy.forward = pforward
    print(f"[variants] B4 FAST auxiliary: vocab {vocab}, max {max_tokens} tokens, weight {weight}, K={K}", flush=True)


# ------------------------------------------------------------------ B3 stage head + voting tracker


def stage_label(frame_index, episode_length, num_stages: int):
    """B3. PiBehavior ComputeSubtaskStateFromMeta: equal-time split of each demo,
    stage = clamp(floor(frame / (length / num_stages)), 0, num_stages - 1). Works on arrays."""
    s = np.floor(np.asarray(frame_index, float) / (np.asarray(episode_length, float) / num_stages)).astype(int)
    return np.clip(s, 0, num_stages - 1)


class VotingTracker:
    """B3. PiBehavior B1KPolicyWrapper.update_current_stage with the stage count as a parameter
    (the course's StageTracker port reads BEHAVIOR's TASK_NUM_STAGES table). Same rules, same order:
    advance on >= votes_to_promote votes for s+1; 'skip' moves ONE stage when all votes say s+2;
    back when all votes say s-1; nothing (not even back) when s is the last stage; history cleared on change."""

    def __init__(self, num_stages: int, history_len: int = 3, votes_to_promote: int = 2):
        self.max_stage, self.history_len, self.votes = num_stages - 1, history_len, votes_to_promote
        self.reset()

    def reset(self):
        self.stage, self.history, self.events = 0, [], []

    def update(self, logits) -> int:
        self.history = (self.history + [min(int(np.argmax(logits)), self.max_stage)])[-self.history_len:]
        if len(self.history) == self.history_len and self.stage + 1 <= self.max_stage:
            nxt, h = self.stage + 1, self.history
            if sum(p == nxt for p in h) >= self.votes:
                self._move(nxt, "advance")
            elif all(p == nxt + 1 for p in h):
                self._move(nxt, "skip")
            elif all(p == self.stage - 1 for p in h) and self.stage > 0:
                self._move(self.stage - 1, "back")
        return self.stage

    def _move(self, new, kind):
        self.events.append((kind, self.stage, new))
        self.stage, self.history = new, []


def patch_stage(mapping_path: str | Path, num_stages: int = 5, weight: float = 0.1, log_every: int = 50):
    """B3. System 2 on SmolVLA: a learned (task, stage) token in the prefix, a stage head on the VLM, and the
    voting tracker at inference (PiBehavior fuse_task_and_subtask / stage_pred_from_vlm / update_current_stage).
      * labels: equal-time split of each demo into num_stages (= 5: avg LIBERO length / 900 is below the
        authors' floor of 5 for every task);
      * the stage token is appended after the state token in its own causal block, so images and language
        never see it and the stage prediction (mean of the VLM's language-token outputs -> linear head) cannot
        read the answer from its input; the action expert sees it through the cache;
      * training: cross-entropy on the true stage (weight 0.1) and the TRUE stage as input (teacher forcing);
      * inference: the tracker's stage is the input; after each re-plan the head's logits vote.
    Train AND eval must apply this patch. Task ids come from the B2 instruction -> "task N" mapping."""
    import torch
    import torch.nn as nn
    import torch.nn.functional as F
    from lerobot.datasets.lerobot_dataset import LeRobotDatasetMetadata
    from lerobot.policies.common.flow_matching import FlowConvention, make_flow_matching_inputs
    from lerobot.policies.smolvla import smolvlm_with_expert as M
    S = _vla()
    mapping = {k: int(v.split()[-1]) for k, v in json.loads(Path(mapping_path).read_text()).items()}
    n_tasks = max(mapping.values()) + 1
    meta = LeRobotDatasetMetadata("HuggingFaceVLA/libero")
    ep_len = np.zeros(int(max(meta.episodes["episode_index"])) + 1)
    ep_len[np.asarray(meta.episodes["episode_index"])] = np.asarray(meta.episodes["length"])
    K = getattr(S.VLAFlowMatching, "_course_two_pass", 0) or 1
    stats = {"train_steps": 0, "ce": 0.0, "acc": 0.0, "episodes": 0, "replans": 0, "final_stages": [],
             "events": 0}
    orig_init, orig_embed = S.VLAFlowMatching.__init__, S.VLAFlowMatching.embed_prefix
    orig_vlm_fwd = M.SmolVLMWithExpertModel.forward
    orig_pforward, orig_select, orig_reset = S.SmolVLAPolicy.forward, S.SmolVLAPolicy.select_action, S.SmolVLAPolicy.reset

    def __init__(self, *a, **k):
        orig_init(self, *a, **k)
        h = self.vlm_with_expert.config.text_config.hidden_size
        self.stage_embed = nn.Embedding(n_tasks * num_stages, h)
        nn.init.normal_(self.stage_embed.weight, std=0.02)
        self.stage_head = nn.Linear(h, num_stages)
        nn.init.normal_(self.stage_head.weight, std=0.02)  # start near uniform (default init: CE 2.8 vs ln 5)
        nn.init.zeros_(self.stage_head.bias)
        self._course_stage_in = None

    def embed_prefix(self, images, img_masks, lang_tokens, lang_masks, state=None):
        pe, pp, pa = orig_embed(self, images, img_masks, lang_tokens, lang_masks, state=state)
        n_lang, end = lang_tokens.shape[1], pe.shape[1] - 1  # layout [images | language | state], no padding
        self._course_lang = (end - n_lang, end, lang_masks)
        if self._course_stage_in is None:
            raise RuntimeError("B3: stage input not set (policy.forward/select_action set it)")
        task, stage = self._course_stage_in
        e = self.stage_embed(task * num_stages + stage)[:, None] * math.sqrt(pe.shape[-1])
        one = torch.ones(pe.shape[0], 1, dtype=torch.bool, device=pe.device)
        return torch.cat([pe, e.to(pe.dtype)], 1), torch.cat([pp, one], 1), torch.cat([pa, one], 1)

    def stage_logits(self, prefix_out):
        s, e, lm = self._course_lang
        m = lm.to(prefix_out.dtype)[..., None]
        pooled = (prefix_out[:, s:e] * m).sum(1) / m.sum(1).clamp_min(1)
        return self.stage_head(pooled.float())

    def vlm_forward(self, attention_mask=None, position_ids=None, past_key_values=None, inputs_embeds=None,
                    use_cache=None):
        out, pkv = orig_vlm_fwd(self, attention_mask=attention_mask, position_ids=position_ids,
                                past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache)
        if bool(use_cache) and past_key_values is None and inputs_embeds[1] is None:
            self._course_prefix_out = out[0]  # read by the stage head at inference
        return out, pkv

    def forward(self, images, img_masks, lang_tokens, lang_masks, state, actions, noise=None, time=None):
        pe, pp, pa = self.embed_prefix(images, img_masks, lang_tokens, lang_masks, state=state)
        (pout, _), pkv = self.vlm_with_expert.forward(
            attention_mask=S.make_att_2d_masks(pp, pa), position_ids=torch.cumsum(pp, 1) - 1,
            past_key_values=None, inputs_embeds=[pe, None], use_cache=True)
        self._course_aux_logits = stage_logits(self, pout)
        losses = []
        for k in range(K):
            n = noise if (noise is not None and k == 0) else self.sample_noise(actions.shape, actions.device)
            t = time if (time is not None and k == 0) else self.sample_time(actions.shape[0], actions.device)
            x_t, u_t, _ = make_flow_matching_inputs(actions, n, t, convention=FlowConvention.NOISE_AT_ONE)
            losses.append(F.mse_loss(u_t, self.denoise_step(pp, pkv, x_t, t), reduction="none"))
        return torch.stack(losses).mean(0)

    def pforward(self, batch, noise=None, time=None, reduction="mean"):
        dev = batch[S.OBS_STATE].device
        task = batch["task_index"].reshape(-1).long().to(dev)
        frame = batch["frame_index"].reshape(-1).cpu().numpy()
        length = ep_len[batch["episode_index"].reshape(-1).cpu().numpy().astype(int)]
        stage = torch.as_tensor(stage_label(frame, length, num_stages), device=dev)
        self.model._course_stage_in = (task, stage)
        loss, d = orig_pforward(self, batch, noise=noise, time=time, reduction=reduction)
        self.model._course_stage_in = None
        logits = self.model._course_aux_logits
        ce = F.cross_entropy(logits, stage, reduction="none")
        loss = loss + weight * (ce if reduction == "none" else ce.mean())
        acc = float((logits.argmax(-1) == stage).float().mean())
        d["stage_loss"], d["stage_accuracy"] = float(ce.detach().mean()), acc
        stats["train_steps"] += 1; stats["ce"] += d["stage_loss"]; stats["acc"] += acc
        if log_every and stats["train_steps"] % log_every == 0:
            print(f"[variants] B3 step {stats['train_steps']}: stage_ce={stats['ce'] / log_every:.3f} "
                  f"stage_acc={stats['acc'] / log_every:.3f}", flush=True)
            stats["ce"] = stats["acc"] = 0.0
        return loss, d

    def select_action(self, batch, **kw):
        tasks = batch.get("task")
        if tasks is None:
            raise KeyError("B3 needs the instruction ('task') in the eval batch to look up the task id")
        tasks = [tasks] if isinstance(tasks, str) else list(tasks)
        assert len(tasks) == 1, "B3 tracker state is per environment: run eval with --eval.batch_size=1"
        dev = batch[S.OBS_STATE].device
        replan = len(self._queues[S.ACTION]) == 0
        tr = self._course_tracker
        key = tasks[0].strip()  # the instruction, or "task N" if B2 already replaced it (D1 combines both)
        tid = mapping[key] if key in mapping else int(key.split()[-1]) if key.startswith("task ") else mapping[key]
        self.model._course_stage_in = (torch.tensor([tid], device=dev),
                                       torch.tensor([tr.stage], device=dev))
        a = orig_select(self, batch, **kw)
        if replan:
            logits = stage_logits(self.model, self.model.vlm_with_expert._course_prefix_out)
            n_events = len(tr.events)
            tr.update(logits[0].detach().float().cpu().numpy())
            stats["replans"] += 1; stats["events"] += len(tr.events) - n_events
            if stats["final_stages"]:  # one slot per episode, opened by reset(); holds its latest stage
                stats["final_stages"][-1] = tr.stage
        return a

    def reset(self):
        orig_reset(self)
        # LeRobot calls reset() at episode start, so the slot is opened here and filled by select_action;
        # recording at reset time would drop the last episode.
        stats["final_stages"].append(0)
        self._course_tracker = VotingTracker(num_stages)
        stats["episodes"] += 1

    S.VLAFlowMatching.__init__ = __init__
    S.VLAFlowMatching.embed_prefix = embed_prefix
    S.VLAFlowMatching.forward = forward
    S.VLAFlowMatching._course_two_pass = K
    M.SmolVLMWithExpertModel.forward = vlm_forward
    S.SmolVLAPolicy.forward = pforward
    S.SmolVLAPolicy.select_action = select_action
    S.SmolVLAPolicy.reset = reset
    print(f"[variants] B3 stage token + head + voting tracker: {n_tasks} tasks x {num_stages} stages, "
          f"weight {weight}", flush=True)
    return stats


def patch_compression(n_exec: int, n_steps: int, stats_path: str | Path, delta_dims=slice(0, 6)):
    """B8. Execute the first n_exec predicted actions in n_steps env steps (PiBehavior: 26 -> 20)."""
    import torch
    S = _vla()
    st = json.loads(Path(stats_path).read_text())["action"]
    mean, std = np.asarray(st["mean"], float), np.asarray(st["std"], float)
    real = len(mean)

    def select_action(self, batch, *, noise=None, **kw):
        self.eval()
        batch = self._prepare_batch(batch)
        self._queues = S.populate_queues(self._queues, batch, exclude_keys=[S.ACTION])
        if len(self._queues[S.ACTION]) == 0:
            actions = self._get_action_chunk(batch, noise=noise)  # [B, chunk, D] normalised
            a = actions.detach().float().cpu().numpy()
            out = np.stack([compress_normalized(a[b, :, :real], n_exec, n_steps, delta_dims, mean, std)
                            for b in range(a.shape[0])])
            comp = torch.as_tensor(out, dtype=actions.dtype, device=actions.device)
            self._queues[S.ACTION].extend(comp.transpose(0, 1))
        return self._queues[S.ACTION].popleft()

    S.SmolVLAPolicy.select_action = select_action
    print(f"[variants] B8 compression: {n_exec} actions -> {n_steps} steps (delta dims scaled)", flush=True)


# ------------------------------------------------------------------ GeCO (arXiv 2603.17834), NeurIPS 2026 repro
# Generative Control as Optimization: a TIME-UNCONDITIONAL velocity field whose zeros are the expert actions.
# Paper convention: x_γ = γ a + (1-γ) ε (γ=0 noise), target g = (ε - a) c(γ), update a ← a - η_k f(a).
# SmolVLA convention: noise at t=1, x_t = t ε + (1-t) a, target ε - a. So γ = 1 - t and the update is SmolVLA's
# Euler step with GeCO's step sizes. Following the paper's VLA recipe (Sec. 4.2), the time input is fixed (t=0).

GECO_LAMBDA, GECO_ALPHA0 = 4.0, 0.1  # Appendix A.4


def geco_scale(gamma, lam: float = GECO_LAMBDA, alpha0: float = GECO_ALPHA0):
    """c(γ) of Eq. 8: λ for γ ≤ α0, then linear to 0 at γ = 1. Works on numpy arrays and torch tensors."""
    lin = lam * (1.0 - gamma) / (1.0 - alpha0)
    return lin * (gamma > alpha0) + lam * (gamma <= alpha0)


def geco_step_sizes(k_max: int = 30) -> list[float]:
    """Appendix A.3: η_1 = 0.1, η_2..4 = 0.05, η_5..16 = 0.02, η_17..30 = 0.01 (truncated at k_max)."""
    eta = [0.1] + [0.05] * 3 + [0.02] * 12 + [0.01] * 14
    return eta[:k_max] + [0.01] * max(0, k_max - len(eta))


def geco_tau(dims: int, tau_paper: float = 0.4, paper_dims: int = 16 * 7) -> float:
    """The early-stop threshold is a norm over the whole chunk, so it grows like sqrt(dims). The paper's 0.4 is for
    16 x 7 = 112 dims; SmolVLA's chunk is 50 x 7 = 350, giving 0.4 * sqrt(350/112) = 0.71. (Our choice, documented.)"""
    return tau_paper * math.sqrt(dims / paper_dims)


def moving_average_flags(scores, w: int = 5, thr: float = 0.6):
    """Sec. 4.3 moving-average filter over one episode's per-call scores. Early calls average what exists (the paper
    does not say how k < w is handled). Returns the index of the first flagged call, or None."""
    s = np.asarray(scores, float)
    for k in range(len(s)):
        if s[max(0, k - w + 1):k + 1].mean() > thr:
            return k
    return None


def leaky_bucket_flags(scores, tau: float = 0.5, leak: float = 0.0, cap: float = 0.7):
    """Sec. 4.3 leaky bucket: b_k = max(0, (1-λ) b_{k-1} + (r_k - τ)+), flag when b_k ≥ B. (τ, λ, B) = (0.5, 0, 0.7)."""
    b = 0.0
    for k, r in enumerate(np.asarray(scores, float)):
        b = max(0.0, (1.0 - leak) * b + max(0.0, r - tau))
        if b >= cap:
            return k
    return None


def _episode_tracker(S, stats):
    orig_reset = S.SmolVLAPolicy.reset

    def reset(self):
        orig_reset(self)
        stats["episode"] += 1  # LeRobot calls reset() at the start of every episode (and once at load)

    S.SmolVLAPolicy.reset = reset


def _prefix_cache(self, S, images, img_masks, lang_tokens, lang_masks, state):
    import torch
    pe, pp, pa = self.embed_prefix(images, img_masks, lang_tokens, lang_masks, state=state)
    _, pkv = self.vlm_with_expert.forward(attention_mask=S.make_att_2d_masks(pp, pa),
                                          position_ids=torch.cumsum(pp, 1) - 1, past_key_values=None,
                                          inputs_embeds=[pe, None], use_cache=True)
    return pp, pkv


def patch_geco(k_max: int = 10, tau: float | None = None, real_dims: int = 7, t_input: float = 0.0,
               lam: float = GECO_LAMBDA, alpha0: float = GECO_ALPHA0):
    """GeCO on SmolVLA, train + infer. Training: γ ~ U(0,1), x = γ a + (1-γ) ε, target (ε - a) c(γ), fixed time input.
    Inference: a ← a - η_k f(a) from noise, stop when ‖f‖ (real dims, whole chunk) < τ or after k_max steps.
    Every planning call records its final residual norm ‖f(a_K)‖, the OOD score of Eq. 6."""
    import torch
    import torch.nn.functional as F
    S = _vla()
    tau = geco_tau(50 * real_dims) if tau is None else tau
    eta = geco_step_sizes(k_max)
    stats = {"episode": -1, "calls": []}  # calls: [episode, final_norm, steps_used]

    def forward(self, images, img_masks, lang_tokens, lang_masks, state, actions, noise=None, time=None):
        B, dev = actions.shape[0], actions.device
        eps = self.sample_noise(actions.shape, dev) if noise is None else noise
        gamma = torch.rand(B, device=dev, dtype=torch.float32) if time is None else 1.0 - time
        g = gamma[:, None, None]
        x = g * actions + (1.0 - g) * eps
        target = (eps - actions) * geco_scale(g, lam, alpha0)
        pp, pkv = _prefix_cache(self, S, images, img_masks, lang_tokens, lang_masks, state)
        v = self.denoise_step(pp, pkv, x, torch.full((B,), t_input, dtype=torch.float32, device=dev))
        return F.mse_loss(target, v, reduction="none")

    def sample_actions(self, images, img_masks, lang_tokens, lang_masks, state, noise=None, **kw):
        B, dev = state.shape[0], state.device
        x = (self.sample_noise((B, self.config.chunk_size, self.config.max_action_dim), dev) if noise is None
             else noise.to(dev, torch.float32))
        pp, pkv = _prefix_cache(self, S, images, img_masks, lang_tokens, lang_masks, state)
        tin = torch.full((B,), t_input, dtype=torch.float32, device=dev)
        k = 0
        while True:
            f = self.denoise_step(pp, pkv, x, tin)
            r = f[:, :, :real_dims].flatten(1).norm(dim=1)
            if k >= k_max or bool((r < tau).all()):
                break
            x = x - eta[k] * f
            k += 1
        for b in range(B):
            stats["calls"].append([stats["episode"], float(r[b]), k])
        return x

    # SmolVLA's forward runs the prefix and suffix jointly (one attention pass); ours runs the prefix once and the
    # expert against its KV cache, which is the same computation SmolVLA uses at inference (and B5 uses in training).
    S.VLAFlowMatching.forward = forward
    S.VLAFlowMatching.sample_actions = sample_actions
    _episode_tracker(S, stats)
    print(f"[variants] GeCO: lambda={lam} alpha0={alpha0} t_input={t_input} k_max={k_max} tau={tau:.3f} "
          f"eta={eta}", flush=True)
    return stats


def patch_fm_score(real_dims: int = 7, score_times=(1.0, 0.5)):
    """Baseline OOD score for a standard (time-conditioned) SmolVLA, inference only (Sec. 4.3 / App. D). After the
    usual Euler sampling of chunk x0, draw one ε and score ‖v(x_t, t) - (ε - x0)‖² on the real dims for each t in
    score_times (t=1, pure noise, is the paper's 'fixed timestep t=1'; t=0.5 is reported as a robustness check)."""
    import torch
    S = _vla()
    stats = {"episode": -1, "calls": [], "times": list(score_times)}  # calls: [episode, score_t1, score_t2, ...]

    def sample_actions(self, images, img_masks, lang_tokens, lang_masks, state, noise=None, **kw):
        B, dev = state.shape[0], state.device
        shape = (B, self.config.chunk_size, self.config.max_action_dim)
        x = self.sample_noise(shape, dev) if noise is None else noise.to(dev, torch.float32)
        pp, pkv = _prefix_cache(self, S, images, img_masks, lang_tokens, lang_masks, state)
        n = self.config.num_steps
        dt, t = -1.0 / n, 1.0
        for _ in range(n):
            x = x + dt * self.denoise_step(pp, pkv, x, torch.full((B,), t, dtype=torch.float32, device=dev))
            t += dt
        eps = self.sample_noise(shape, dev)
        scores = []
        for ts in score_times:
            xt = ts * eps + (1.0 - ts) * x
            v = self.denoise_step(pp, pkv, xt, torch.full((B,), ts, dtype=torch.float32, device=dev))
            scores.append(((v - (eps - x))[:, :, :real_dims] ** 2).flatten(1).sum(1))
        for b in range(B):
            stats["calls"].append([stats["episode"], *[float(s[b]) for s in scores]])
        return x

    S.VLAFlowMatching.sample_actions = sample_actions
    _episode_tracker(S, stats)
    print(f"[variants] FM-loss OOD score at t={list(score_times)}", flush=True)
    return stats