File size: 25,111 Bytes
1c78d11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Unit tests for rsm_rise Stage 3: the RSM scorer, the best-of-N planner mixin and the E2 advantage.

Run (RISE env, login node, no GPU):
    MUJOCO_GL=disable /proj/dmfexp/zwhong/rsm_rise/env/bin/python -m pytest -q \
        /proj/dmfexp/zwhong/rsm_rise/code/rise_robomimic/tests/test_rsm_planner.py
or plainly `python tests/test_rsm_planner.py` (runs every test_* function).

DINO is replaced by a deterministic fake (a fixed random projection of the image) so the tests need no
hub weights; every checkpoint is a randomly initialised network saved in the real blob formats.
"""
import os
import sys
import json
import math
import tempfile
import subprocess

import numpy as np
import torch
import torch.nn as nn

ROOT = "/proj/dmfexp/zwhong/rsm_rise"
os.environ.setdefault("RSM_LIBERO_DIR", f"{ROOT}/code/gen_q/rsm_libero")

from robomimic.algo import rsm_scorer as S           # noqa: E402
from robomimic.algo import rsm_planner as P           # noqa: E402

D = S.STATE_DIM
CHUNK, ADIM = 8, 7


class FakeDino(nn.Module):
    """Stands in for DinoV2Core: a frozen random projection of the (3,84,84) image to 768 dims, and a
    backbone_model.forward_features / transform pair so PooledDinoState.tokens works too."""

    def __init__(self, seed=0):
        super().__init__()
        g = torch.Generator().manual_seed(seed)
        self.register_buffer("Wt", torch.randn(3 * 84 * 84, 257 * 384, generator=g) / 300.0)
        self.transform = nn.Identity()
        outer = self

        class _BB(nn.Module):
            def forward_features(self, x):
                t = (x.flatten(1) @ outer.Wt).view(x.shape[0], 257, 384)
                return {"x_norm_clstoken": t[:, 0], "x_norm_patchtokens": t[:, 1:]}
        self.backbone_model = _BB()

    def forward(self, x):
        # exactly DinoV2Core.forward on this fake backbone: [CLS | GeM(patches)] of forward_features
        f = self.backbone_model.forward_features(self.transform(x))
        from robomimic.algo.rsm_scorer import gem_pool
        return torch.cat([f["x_norm_clstoken"], gem_pool(f["x_norm_patchtokens"])], -1)


def _tmpdir():
    d = tempfile.mkdtemp(prefix="rsm_planner_test_", dir=os.environ.get("TMPDIR", "/tmp"))
    return d


def _ckpts(d, hop_family="gauss"):
    ck = S.save_random_rsm_ckpt(os.path.join(d, "rsm.pt"), d_in=D, chunk=CHUNK, adim=ADIM)
    hop = S.save_random_hop_ckpt(os.path.join(d, "hop.pt"), d_in=D, chunk=CHUNK, adim=ADIM, family=hop_family)
    fs = S.save_feat_stats(os.path.join(d, "feat_stats.npz"), d=D)
    return ck, hop, fs


def _scorer(d, mode="fold", depth=2, beta=0.95, hop=True, n_particles=16):
    ck, hopck, fs = _ckpts(d)
    return S.RSMScorer(backend="mlp", ckpt=ck, hop_ckpt=hopck if hop else "", feat_stats=fs, mode=mode,
                       depth=depth, beta=beta, gamma=0.99, n_particles=n_particles, flow_steps=8,
                       device="cpu", dino=FakeDino())


def _obs(B=1, To=2, seed=0):
    g = torch.Generator().manual_seed(seed)
    return {
        "agentview_image": torch.rand(B, To, 3, 84, 84, generator=g),
        "robot0_eye_in_hand_image": torch.rand(B, To, 3, 84, 84, generator=g),
        "robot0_eef_pos": torch.randn(B, To, 3, generator=g),
        "robot0_eef_quat": torch.randn(B, To, 4, generator=g),
        "robot0_gripper_qpos": torch.randn(B, To, 2, generator=g),
    }


# --------------------------------------------------------------------------- #
# scorer
# --------------------------------------------------------------------------- #
def test_state_shape_and_zscore():
    d = _tmpdir(); sc = _scorer(d)
    obs_t = {k: v[:, -1] for k, v in _obs(B=3).items()}
    st = sc.state_from_obs(obs_t)
    assert st.x.shape == (3, D)
    # z-scoring: recompute by hand
    raw = torch.cat([sc.state.dino(obs_t["agentview_image"]), sc.state.dino(obs_t["robot0_eye_in_hand_image"]),
                     obs_t["robot0_eef_pos"], obs_t["robot0_eef_quat"], obs_t["robot0_gripper_qpos"]], -1)
    assert torch.allclose(st.x, (raw - sc.state.mu) / sc.state.sd, atol=1e-5)
    # tokens path (DWM state) gives the same pooled vector when GeM of the fake patches is used
    tok, x2 = sc.state.tokens(obs_t)
    assert tok.shape == (3, 514, 384)
    assert S.pooled_from_tokens(tok).shape == (3, 1536)


def test_crn_determinism_and_seed_isolation():
    d = _tmpdir(); sc = _scorer(d)
    x = torch.randn(1, D)
    A = torch.randn(6, CHUNK, ADIM)
    q1 = sc.score(x, A, seed=123)
    q2 = sc.score(x, A, seed=123)
    assert torch.equal(q1, q2), "same seed must give identical Q̄ (CRN reproducibility)"
    q3 = sc.score(x, A, seed=124)
    assert not torch.equal(q1, q3)
    # the scorer's seeded call must not disturb the caller's RNG stream
    torch.manual_seed(7); a = torch.randn(3)
    torch.manual_seed(7); sc.score(x, A, seed=5); b = torch.randn(3)
    assert torch.equal(a, b)
    # CRN across candidates: identical candidates get identical scores within one call
    A2 = A[:1].repeat(4, 1, 1)
    q4 = sc.score(x, A2, seed=1)
    assert torch.allclose(q4, q4[:1].expand(4), atol=1e-6), q4
    assert q1.shape == (6,) and torch.all((q1 >= 0) & (q1 <= 1))


def test_fold_at_depth1_equals_d1():
    d = _tmpdir()
    sc_fold = _scorer(d, mode="fold", depth=1)
    x = torch.randn(1, D); A = torch.randn(5, CHUNK, ADIM)
    q_fold = sc_fold.score(x, A, seed=3)
    q_d1 = sc_fold.score(x, A, seed=3, mode="d1")
    assert torch.allclose(q_fold, q_d1, atol=1e-6)
    # d1 with any depth still uses one hop
    q_d1_deep = sc_fold.score(x, A, seed=3, mode="d1", depth=4)
    assert torch.allclose(q_d1_deep, q_d1, atol=1e-6)
    # fold at depth 2 needs the hop head
    sc_nohop = _scorer(_tmpdir(), mode="fold", depth=2, hop=False)
    try:
        sc_nohop.score(x, A, seed=3)
        assert False, "depth-2 fold without a hop head must fail loudly"
    except RuntimeError:
        pass


def test_recursive_mode_runs_and_scales():
    d = _tmpdir(); sc = _scorer(d, mode="recursive", depth=3, beta=0.9)
    x = torch.randn(1, D); A = torch.randn(4, CHUNK, ADIM)
    q = sc.score(x, A, seed=0)
    assert q.shape == (4,) and torch.all((q >= 0) & (q <= 1.0 + 1e-6))
    h = sc.effective_horizon()
    assert 0 < h["restart_p"] < 1 and h["effective_frames"] > 10


def test_expectile():
    q = torch.tensor([[0.0, 1.0, 2.0, 3.0], [1.0, 1.0, 1.0, 5.0]])
    assert torch.allclose(S.expectile(q, 0.5), q.mean(1))
    hi = S.expectile(q, 0.9); lo = S.expectile(q, 0.1)
    assert torch.all(hi > q.mean(1)) and torch.all(lo < q.mean(1))
    # 0.9-expectile of [0,1,2,3]: tau*sum_{q>v}(q-v) = (1-tau)*sum_{q<v}(v-q); v in (2,3): 0.9(3-v) = 0.1(3v-3) -> v = 2.5
    assert abs(float(hi[0]) - 2.5) < 1e-4, float(hi[0])


def test_advantage_tau_half_is_mean_and_permute():
    d = _tmpdir(); sc = _scorer(d, mode="fold", depth=2)
    obs_t = {k: v[:, -1] for k, v in _obs(B=4).items()}
    st = sc.state_from_obs(obs_t)
    A = torch.randn(4, 16, ADIM)                       # a 16-step chunk: only the first 8 are scored
    q, v, qm = sc.advantage(st, A, v_samples=6, v_expectile=0.5, seed=11)
    assert q.shape == (4,) and v.shape == (4,) and qm.shape == (4, 6)
    assert torch.allclose(v, qm.mean(1), atol=1e-6)
    q2, v2, _ = sc.advantage(st, A, v_samples=6, v_expectile=0.9, seed=11)
    assert torch.allclose(q, q2, atol=1e-6) and torch.all(v2 >= v - 1e-6)
    # q of the logged chunk is the same as score() of it under the same seed? not required (different noise
    # layout), but the batched q must equal a per-row fold on the same particles: check shape/range only
    assert torch.all((q >= 0) & (q <= 1))


def test_hop_families_load():
    for fam in ("gauss", "flow", "concat"):
        d = _tmpdir()
        ck = S.save_random_rsm_ckpt(os.path.join(d, "rsm.pt"))
        hop = S.save_random_hop_ckpt(os.path.join(d, "hop.pt"), family=fam)
        fs = S.save_feat_stats(os.path.join(d, "fs.npz"))
        sc = S.RSMScorer(backend="mlp", ckpt=ck, hop_ckpt=hop, feat_stats=fs, mode="fold", depth=2,
                         device="cpu", n_particles=4, dino=FakeDino())
        q = sc.score(torch.randn(1, D), torch.randn(3, CHUNK, ADIM), seed=0)
        assert q.shape == (3,), fam


# --------------------------------------------------------------------------- #
# selection rules
# --------------------------------------------------------------------------- #
def test_rules():
    g = torch.Generator().manual_seed(0)
    s = torch.tensor([[0.1, 0.9, 0.3, 0.5]]).repeat(200, 1)
    assert torch.all(P.select(s, "argmax") == 1)
    assert torch.all(P.select(s, "argmin") == 0)
    r = P.select(s, "random", generator=g)
    assert len(set(r.tolist())) == 4, "random must ignore the scores"
    p = P.select(s, "permuted", generator=g)
    assert len(set(p.tolist())) == 4, "permuted scores -> argmax picks every index"
    t = P.select(s, "topk_uniform", topk=2, generator=g)
    assert set(t.tolist()) == {1, 3}
    sm = P.select(s, "softmax", temp=0.01, generator=g)
    assert (sm == 1).float().mean() > 0.95
    sm2 = P.select(s, "softmax", temp=100.0, generator=g)
    assert len(set(sm2.tolist())) == 4


# --------------------------------------------------------------------------- #
# the mixin on a fake algo (no robomimic nets needed)
# --------------------------------------------------------------------------- #
class _Cfg(dict):
    """Behaves like robomimic's Config for the keys the mixin reads (missing key -> RuntimeError)."""
    def __getitem__(self, k):
        if k not in self:
            raise RuntimeError(k)
        return dict.__getitem__(self, k)

    def __getattr__(self, k):
        return self[k]


class FakeAlgo(P.RSMPlannerMixin):
    def __init__(self, Tp=16, Ta=8, To=2):
        h = _Cfg(observation_horizon=To, action_horizon=Ta, prediction_horizon=Tp)
        self.algo_config = _Cfg(horizon=h)
        self.device = torch.device("cpu")
        self.ac_dim = ADIM
        self.nets = {}
        self.calls = []

    def _sample_action_chunks(self, obs_dict, goal_dict=None):
        B = obs_dict["robot0_eef_pos"].shape[0]
        self.calls.append(B)
        # deterministic chunks that encode the row index so the test can see which one was chosen
        base = torch.arange(B).float().view(B, 1, 1) / max(B, 1)
        return base + 0.01 * torch.randn(B, 16, ADIM)


def _fake_algo_with_scorer(rule, n, d, seed=-1):
    ck, hop, fs = _ckpts(d)
    a = FakeAlgo()
    a.configure_planner(plan_n=n, plan_rule=rule, rsm_ckpt=ck, rsm_hop_ckpt=hop, rsm_feat_stats=fs,
                        plan_mode="fold", plan_depth=2, plan_particles=4, plan_seed=seed)
    # inject the fake DINO into the scorer the mixin builds
    sc = S.RSMScorer(backend="mlp", ckpt=ck, hop_ckpt=hop, feat_stats=fs, mode="fold", depth=2,
                     n_particles=4, device="cpu", dino=FakeDino())
    a._planner_scorer = sc
    return a


def test_mixin_released_path_when_n_is_1():
    a = FakeAlgo()
    a.configure_planner(plan_n=1)
    obs = _obs(B=2)
    torch.manual_seed(0); act = a.plan_get_action(obs)
    torch.manual_seed(0); ref = a._sample_action_chunks(obs)[:, 1:9]
    assert act.shape == (2, 8, ADIM) and torch.allclose(act, ref)
    assert a.calls == [2, 2]
    a2 = FakeAlgo()          # no configure at all: defaults (plan_n None) -> released path
    assert not a2.planning_enabled
    assert a2.plan_get_action(obs).shape == (2, 8, ADIM)


def test_mixin_best_of_n_argmax_matches_scores():
    d = _tmpdir()
    a = _fake_algo_with_scorer("argmax", 8, d, seed=0)
    obs = _obs(B=2)
    act = a.plan_get_action(obs)
    assert act.shape == (2, 8, ADIM)
    assert a.calls == [16], "one batched sampler call for B*N rows"
    log = a.pop_plan_log()
    assert len(log) == 1 and log[0]["n"] == 8 and len(log[0]["idx"]) == 2
    # the chosen chunk is the argmax candidate: its first coordinate identifies the row b*N + idx
    for b in range(2):
        idx = log[0]["idx"][b]
        row = b * 8 + idx
        assert abs(float(act[b, 0, 0]) - row / 16) < 0.05, (b, idx, float(act[b, 0, 0]))
        assert log[0]["score_chosen"][b] == log[0]["score_max"][b]
    assert a.pop_plan_log() == []


def test_mixin_random_needs_no_scorer_and_permuted_ignores_scores():
    d = _tmpdir()
    a = FakeAlgo(); a.configure_planner(plan_n=8, plan_rule="random", plan_seed=0)
    act = a.plan_get_action(_obs(B=1))
    assert act.shape == (1, 8, ADIM) and a._planner_scorer is None
    picks = set()
    for _ in range(30):
        a.plan_get_action(_obs(B=1)); picks.add(a.pop_plan_log()[-1]["idx"][0])
    assert len(picks) >= 5
    b = _fake_algo_with_scorer("permuted", 8, _tmpdir(), seed=0)
    picks = set()
    for _ in range(30):
        b.plan_get_action(_obs(B=1)); picks.add(b.pop_plan_log()[-1]["idx"][0])
    assert len(picks) >= 5, "permuted must spread its picks like random"


def test_mixin_iql_backend():
    class Critic(nn.Module):
        def __init__(self, w):
            super().__init__(); self.w = w
        def forward(self, obs_dict, acts, goal_dict=None):
            return (acts[:, :1] * self.w)          # [N,1]
    a = FakeAlgo()
    a.nets = {"critic": nn.ModuleList([Critic(1.0), Critic(2.0)])}
    a.configure_planner(plan_n=4, plan_rule="argmax", rsm_backend="iql")
    act = a.plan_get_action(_obs(B=1))
    log = a.pop_plan_log()[0]
    assert act.shape == (1, 8, ADIM)
    assert "iql" in json.dumps(a.planner_describe())
    # min over critics of a0[0]*w -> picks the candidate with the largest first-action x (w=1 is the min for x>0)
    assert log["score_chosen"][0] == max(log["score_max"])


# --------------------------------------------------------------------------- #
# hydra plumbing (needs the RISE env): training.plan_n=64 reaches the composed config
# --------------------------------------------------------------------------- #
def test_hydra_override_resolves():
    py = f"{ROOT}/env/bin/python"
    if not os.path.exists(py):
        print("skip: RISE env missing"); return
    env = dict(os.environ, MUJOCO_GL="disable", PYOPENGL_PLATFORM="egl", HYDRA_FULL_ERROR="1")
    cmd = [py, "scripts/eval.py", "-cn", "eval_robomimic_iql_diffusion", "+env=robomimic_square_coverage",
           "exp.use_model_manager=False", "exp.model_path=/tmp/x", "training.plan_n=64",
           "training.plan_rule=softmax", "training.plan_temp=0.05", "training.rsm_ckpt=/a/b.pt",
           "training.plan_mode=recursive", "training.plan_depth=3", "training.plan_beta=0.9",
           "exp.eval_cell=E1-test", "--cfg", "job"]
    out = subprocess.run(cmd, cwd=f"{ROOT}/code/rise_code", env=env, capture_output=True, text=True, timeout=600)
    assert out.returncode == 0, out.stderr[-2000:]
    for needle in ("plan_n: 64", "plan_rule: softmax", "plan_temp: 0.05", "rsm_ckpt: /a/b.pt",
                   "plan_mode: recursive", "plan_depth: 3", "plan_beta: 0.9", "eval_cell: E1-test"):
        assert needle in out.stdout, needle
    # planner_kwargs picks exactly those keys out of the composed training config
    from omegaconf import OmegaConf
    from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import planner_kwargs, PLANNER_KEYS
    cfg = OmegaConf.create({"plan_n": 64, "plan_rule": "softmax", "rsm_ckpt": "/a/b.pt", "algo": "idql"})
    kw = planner_kwargs(cfg)
    assert kw == {"plan_n": 64, "plan_rule": "softmax", "rsm_ckpt": "/a/b.pt"}
    assert set(PLANNER_KEYS) == set(P.PLANNER_DEFAULTS) | set(P.ADV_DEFAULTS)


# --------------------------------------------------------------------------- #
# plan_sample_batch: the DDPM sampler, not the RSM scorer, is what caps plan_n.
# At plan_n=2048 the released path builds one [B*N, Tp, ac] denoising batch and OOMs an 80 GB card
# (75 GB allocated, in idql._sample_action_chunks) before the scorer is ever reached -- observed on
# jobs 1777014/1777018/1777022/1777026.  plan_sample_batch slices that call; it must be exactly the
# released path when unset.

class EchoAlgo(FakeAlgo):
    """_sample_action_chunks whose output is a pure function of the obs rows, so it is independent of
    how the batch was sliced.  FakeAlgo's own fake encodes the row index as i/B, which by construction
    changes under chunking and so cannot tell a correct split from a wrong one."""

    def _sample_action_chunks(self, obs_dict, goal_dict=None):
        v = obs_dict["robot0_eef_pos"]
        self.calls.append(v.shape[0])
        return v[:, -1, :1].reshape(-1, 1, 1).expand(-1, 16, ADIM).clone()


def test_sample_chunked_is_off_by_default():
    a = _fake_algo_with_scorer("argmax", 8, _tmpdir(), seed=0)
    assert a.planner_cfg()["plan_sample_batch"] == 0
    a.plan_get_action(_obs(B=2))
    assert a.calls == [16], "unset plan_sample_batch must stay one sampler call over all B*N rows"


def test_sample_chunked_splits_the_sampler_and_preserves_every_row():
    obs = _obs(B=2)
    rep = {k: v.repeat_interleave(8, 0) for k, v in obs.items()}
    ref = EchoAlgo()._sample_chunked(rep, None, 0)          # released path, one call
    for sb in (1, 5, 8, 16, 64):
        a = EchoAlgo()
        got = a._sample_chunked(rep, None, sb)
        assert got.shape == ref.shape, (sb, got.shape, ref.shape)
        assert torch.equal(got, ref), sb                    # rows are independent: identical, not merely close
        rows = 16
        want = [min(sb, rows - lo) for lo in range(0, rows, sb)] if sb < rows else [rows]
        assert a.calls == want, (sb, a.calls, want)


def test_sample_chunked_routes_from_the_hydra_key_and_chunks_the_goal_dict():
    a = EchoAlgo()
    a.configure_planner(plan_n=8, plan_rule="random", plan_seed=0, plan_sample_batch=6)
    assert a.planner_cfg()["plan_sample_batch"] == 6
    obs = _obs(B=2)
    goal = {k: v.clone() for k, v in obs.items()}
    act = a.plan_get_action(obs, goal)
    assert act.shape == (2, 8, ADIM)
    assert a.calls == [6, 6, 4], a.calls
    # the goal dict must be sliced in step with the obs dict, or the sampler silently conditions on the
    # wrong goal rows: our fake records the widths it was handed.
    a2 = EchoAlgo()
    rep = {k: v.repeat_interleave(8, 0) for k, v in obs.items()}
    rep_goal = {k: v.repeat_interleave(8, 0) for k, v in goal.items()}
    seen = []
    orig = a2._sample_action_chunks
    def spy(obs_dict, goal_dict=None):
        seen.append((obs_dict["robot0_eef_pos"].shape[0], goal_dict["robot0_eef_pos"].shape[0]))
        return orig(obs_dict, goal_dict)
    a2._sample_action_chunks = spy
    a2._sample_chunked(rep, rep_goal, 6)
    assert seen == [(6, 6), (6, 6), (4, 4)], seen


def test_plan_max_rows_is_invariant_and_routes_to_the_scorer():
    """The scorer's row slicing is a pure memory knob: the CRN noise is drawn once for all n particles and
    indexed by particle, so narrowing max_rows must not move a single score.  This is what makes it safe to
    shrink for the big-N cells while the rest of the grid keeps the default -- unlike plan_sample_batch,
    which does change which candidates get drawn.  (At plan_n=2048 the default 65536 OOMs an 80 GB card in
    _q_fold_logit: 1024 candidates x 64 particles per slice, 8x anything the grid had hit before.)"""
    ck, hop, fs = _ckpts(_tmpdir())
    dino = FakeDino()
    kw = dict(backend="mlp", ckpt=ck, hop_ckpt=hop, feat_stats=fs, mode="fold", depth=2, n_particles=8,
              device="cpu")
    obs = _obs(B=1)
    obs_t = {k: v[:, -1] for k, v in obs.items()}
    cand = torch.randn(6, CHUNK, ADIM, generator=torch.Generator().manual_seed(3))
    ref = None
    for mr in (S.MAX_ROWS, 48, 16, 8, 3, 1):
        sc = S.RSMScorer(dino=dino, max_rows=mr, **kw)
        torch.manual_seed(7)
        st = sc.state_from_obs(obs_t)
        st_rep = type(st)(x=st.x.repeat_interleave(6, 0),
                          tok=None if st.tok is None else st.tok.repeat_interleave(6, 0),
                          pr=None if getattr(st, "pr", None) is None else st.pr.repeat_interleave(6, 0))
        got = sc.score(st_rep, cand, seed=0).detach().float()
        if ref is None:
            ref = got
        else:
            assert torch.allclose(got, ref, atol=1e-5), (mr, got, ref)

    a = FakeAlgo()
    a.configure_planner(plan_n=4, rsm_ckpt=ck, rsm_hop_ckpt=hop, rsm_feat_stats=fs, plan_max_rows=4096)
    assert a.planner_cfg()["plan_max_rows"] == 4096
    assert a._get_scorer().backend.max_rows == 4096
    b = FakeAlgo()
    b.configure_planner(plan_n=4, rsm_ckpt=ck, rsm_hop_ckpt=hop, rsm_feat_stats=fs)
    assert b.planner_cfg()["plan_max_rows"] == 0
    assert b._get_scorer().backend.max_rows == S.MAX_ROWS, "unset must keep the released slice width"



# --------------------------------------------------------------------------- #
# @torch.no_grad() on plan_get_action
#
# Nothing on the rollout path (sim_pipeline/eval/rollout.py -> robomimic_rollout_policy.predict ->
# idql.get_action) disables autograd, so the released DDPM sampler was retaining a graph across all
# 100 inference timesteps. At plan_n=2048 that is ~75 GB of live activations and is what actually
# capped the candidate-count ladder -- the OOM surfaced inside the RSM read-out only because that is
# where the next allocation happened to land.
# --------------------------------------------------------------------------- #
class GradAlgo(FakeAlgo):
    """Sampler routed through a leaf Parameter, so a retained graph is visible on the returned action,
    and which records whether grad was enabled when it ran."""

    def __init__(self, *a, **kw):
        super().__init__(*a, **kw)
        self.w = nn.Parameter(torch.ones(1))
        self.grad_enabled_seen = []

    def _sample_action_chunks(self, obs_dict, goal_dict=None):
        self.grad_enabled_seen.append(torch.is_grad_enabled())
        return super()._sample_action_chunks(obs_dict, goal_dict) * self.w


def _grad_algo_with_scorer(d, n=8, rule="argmax"):
    ck, hop, fs = _ckpts(d)
    a = GradAlgo()
    a.configure_planner(plan_n=n, plan_rule=rule, rsm_ckpt=ck, rsm_hop_ckpt=hop, rsm_feat_stats=fs,
                        plan_mode="fold", plan_depth=2, plan_particles=4, plan_seed=0)
    a._planner_scorer = S.RSMScorer(backend="mlp", ckpt=ck, hop_ckpt=hop, feat_stats=fs, mode="fold",
                                    depth=2, n_particles=4, device="cpu", dino=FakeDino())
    return a


def test_plan_get_action_builds_no_autograd_graph():
    obs = _obs(B=2)
    d = _tmpdir()
    # released path (plan_n<=1), best-of-N without a scorer, and best-of-N with a real RSMScorer
    cases = [GradAlgo(), GradAlgo(), _grad_algo_with_scorer(d)]
    cases[0].configure_planner(plan_n=1, plan_rule="argmax", plan_seed=0)
    cases[1].configure_planner(plan_n=8, plan_rule="random", plan_seed=0)
    for a in cases:
        with torch.enable_grad():                       # the rollout loop's real state: grad ON
            act = a.plan_get_action(obs)
        cfg = a.planner_cfg()
        tag = (cfg["plan_n"], cfg["plan_rule"])
        assert a.grad_enabled_seen and not any(a.grad_enabled_seen), (tag, a.grad_enabled_seen)
        assert act.grad_fn is None and not act.requires_grad, (tag, act.requires_grad)
        assert a.w.grad is None, tag


def test_no_grad_changes_neither_the_numbers_nor_the_rng():
    """The invariance that makes the decorator safe to switch on under every cell already on disk:
    grad mode changes no forward number and consumes no RNG, so results are bit-for-bit unchanged.
    (Contrast plan_sample_batch, which reslices the sampler and therefore DOES move the RNG.)"""
    torch.manual_seed(7)
    net = nn.Sequential(nn.Linear(16, 64), nn.SiLU(), nn.Linear(64, 16))
    outs, rng = [], []
    for grad in (True, False):
        torch.manual_seed(1234)
        with torch.set_grad_enabled(grad):
            x = torch.randn(5, 16)
            for _ in range(10):                          # a denoising-style chain
                x = x + net(x) / 10.0 + 0.1 * torch.randn_like(x)
            outs.append(x.detach().clone())
        rng.append(torch.random.get_rng_state().clone())
    assert torch.equal(outs[0], outs[1]), "no_grad must not change the forward numbers"
    assert torch.equal(rng[0], rng[1]), "no_grad must not change how much RNG the chain consumes"


def test_released_path_is_unchanged_under_the_decorator():
    """plan_get_action (now no_grad) against _sample_action_chunks called with grad ON -- the same
    check test_mixin_released_path_when_n_is_1 makes, stated as the invariance it is testing."""
    a = FakeAlgo()
    a.configure_planner(plan_n=1)
    obs = _obs(B=2)
    torch.manual_seed(0); act = a.plan_get_action(obs)
    with torch.enable_grad():
        torch.manual_seed(0); ref = a._sample_action_chunks(obs)[:, 1:9]
    assert torch.equal(act, ref.detach())


if __name__ == "__main__":
    names = [n for n in dir() if n.startswith("test_")]
    failed = 0
    for n in names:
        try:
            globals()[n](); print(f"PASS {n}")
        except Exception as e:
            failed += 1
            import traceback; traceback.print_exc()
            print(f"FAIL {n}: {e!r}")
    print(f"{len(names) - failed}/{len(names)} passed")
    sys.exit(1 if failed else 0)