File size: 7,537 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
"""gen_q#270: the additive `return_trace` / `score_trace` visualisation hook must not move any number.

  (a) bit-identity: score() and score_trace() with the same seed return the SAME ranking array and the same
      .last_q / .last_q_logit, at depth 1 and depth 8, for score_kind prob / logit / prob_log / conformal_lcb;
  (b) internal consistency: trace["q"][0].mean(1) == .last_q, trace["c"] == sigmoid(trace["lg"]/T),
      trace["q"][depth] == 0, and the backward recursion q_k = c_k + (1-c_k) G q_{k+1} holds hop by hop;
  (c) shapes / dtypes: z [L,N,P,D], a [L,N,P,d_act], lg/c [L,N,P], q [L+1,N,P]; hop 0's action == the candidate;
  (d) the flag is OFF by default: _q_fold_logit's tuple length is unchanged without it, and every existing
      scorer/planner test still passes (run by scripts/rr_cpu_test_trace.sh alongside this file).
Run as an LSF CPU job (scripts/rr_cpu_test_trace.sh); `python <file>` works too.
"""
import os
import sys

import torch

ROOT = "/proj/dmfexp/zwhong/rsm_rise"
RSM = f"{ROOT}/code/gen_q/rsm_libero"
os.environ.setdefault("RSM_LIBERO_DIR", RSM)
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, RSM)

from test_rsm_planner import FakeDino, D, CHUNK, ADIM, _tmpdir, _ckpts    # noqa: E402
from robomimic.algo import rsm_scorer as S                                # noqa: E402


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


def _xa(n=6, seed=0):
    g = torch.Generator().manual_seed(seed)
    return torch.randn(1, D, generator=g), torch.randn(n, CHUNK, ADIM, generator=g)


# --------------------------------------------------------------------------- #
# (a) score() and score_trace() agree bit for bit
# --------------------------------------------------------------------------- #
def test_trace_does_not_change_the_numbers():
    d = _tmpdir()
    x, A = _xa(9)
    for kind in ("prob", "logit", "prob_log", "conformal_lcb"):
        for mode, depth in (("d1", 1), ("fold", 2), ("fold", 8)):
            sc = _mlp_scorer(d, mode=mode, depth=depth, score_kind=kind)
            r0 = sc.score(x, A, seed=7)
            q0, l0 = sc.last_q.clone(), sc.last_q_logit.clone()
            p0 = None if sc.last_q_problog is None else sc.last_q_problog.clone()
            c0 = None if sc.last_q_lcb is None else sc.last_q_lcb.clone()
            r1, tr = sc.score_trace(x, A, seed=7)
            assert torch.equal(r0, r1), (kind, mode, depth, (r0 - r1).abs().max().item())
            assert torch.equal(q0, sc.last_q), (kind, mode, depth, "q")
            assert torch.equal(l0, sc.last_q_logit), (kind, mode, depth, "logit")
            if p0 is not None:
                assert torch.equal(p0, sc.last_q_problog), (kind, mode, depth, "problog")
            if c0 is not None:
                assert torch.equal(c0, sc.last_q_lcb), (kind, mode, depth, "lcb")


# --------------------------------------------------------------------------- #
# (b) the trace is consistent with the fold it came from
# --------------------------------------------------------------------------- #
def test_trace_is_internally_consistent():
    d = _tmpdir()
    x, A = _xa(5)
    for depth in (1, 2, 4):
        sc = _mlp_scorer(d, mode="fold", depth=depth, n_particles=8)
        _r, tr = sc.score_trace(x, A, seed=3)
        T = sc.effective_temperature()
        G = sc.gamma ** (1.0 / (1.0 - sc.beta))
        assert torch.allclose(tr["q"][0].mean(1), sc.last_q, atol=0, rtol=0), depth
        assert torch.equal(tr["q"][depth], torch.zeros_like(tr["q"][depth])), depth
        c = torch.sigmoid(tr["lg"] / T)
        assert (c - tr["c"]).abs().max().item() < 1e-6, depth
        for k in range(depth - 1, -1, -1):          # q_k = c_k + (1 - c_k) G q_{k+1}
            want = tr["c"][k] + (1.0 - tr["c"][k]) * G * tr["q"][k + 1]
            assert (want - tr["q"][k]).abs().max().item() < 1e-5, (depth, k)
        # the last hop's mean logit is what .last_q_logit reports
        assert (tr["lg"][depth - 1].mean(1) - sc.last_q_logit).abs().max().item() < 1e-5, depth


# --------------------------------------------------------------------------- #
# (c) shapes, dtypes, and hop 0's action
# --------------------------------------------------------------------------- #
def test_trace_shapes():
    d = _tmpdir()
    x, A = _xa(7)
    N, P, depth = 7, 8, 3
    sc = _mlp_scorer(d, mode="fold", depth=depth, n_particles=P)
    _r, tr = sc.score_trace(x, A, seed=1)
    d_act = CHUNK * ADIM
    assert tr["z"].shape == (depth, N, P, sc.backend.d_z), tr["z"].shape
    assert tr["a"].shape == (depth, N, P, d_act), tr["a"].shape
    assert tr["lg"].shape == tr["c"].shape == (depth, N, P)
    assert tr["q"].shape == (depth + 1, N, P)
    assert tr["z"].dtype == torch.float16 and tr["a"].dtype == torch.float16
    # hop 0's chunk is the CANDIDATE itself, tiled over the particles
    cand = sc._flat_chunk(A).half()
    assert (tr["a"][0] - cand[:, None, :]).abs().max().item() == 0.0
    # The slicing must not MOVE the trace: max_rows=3 forces the fold through several row slices, which
    # changes the batch size of every matmul inside the flow and so perturbs the last bits (the same
    # float-reassociation the existing sliced-vs-unsliced read-out test allows for q and the logit).  So
    # this is a tolerance, not an equality, and the tolerance is reported when it fails.
    sc2 = _mlp_scorer(d, mode="fold", depth=depth, n_particles=P, max_rows=3)
    _r2, tr2 = sc2.score_trace(x, A, seed=1)
    assert (tr["a"][0] - tr2["a"][0]).abs().max().item() == 0.0            # hop 0 is pure tiling
    tols = {"z": 0.05, "a": 0.05, "lg": 2e-2, "c": 2e-3, "q": 2e-3}       # z/a are stored fp16
    for k, tol in tols.items():
        err = (tr[k].float() - tr2[k].float()).abs().max().item()
        assert err < tol, (k, err, tol)


# --------------------------------------------------------------------------- #
# (d) default off
# --------------------------------------------------------------------------- #
def test_flag_is_off_by_default():
    d = _tmpdir()
    x, A = _xa(4)
    sc = _mlp_scorer(d, mode="fold", depth=2)
    z = sc.backend.latent(x).expand(4, -1)
    Af = sc._flat_chunk(A)
    task = torch.zeros(4, dtype=torch.long)
    kw = dict(rew=sc.backend.rew, flow=sc.backend.flow, rms=sc.backend.rms, pol=sc.backend.hop,
              beta=0.95, gamma=0.99, depth=2, n_particles=8, flow_steps=8)
    with S.seeded(5):
        out = S._q_fold_logit(z, Af, task, **kw)
    assert len(out) == 2, len(out)
    with S.seeded(5):
        out_t = S._q_fold_logit(z, Af, task, return_trace=True, **kw)
    assert len(out_t) == 3 and isinstance(out_t[2], dict), len(out_t)
    assert torch.equal(out[0], out_t[0]) and torch.equal(out[1], out_t[1])
    # and score() itself never asks for a trace
    r = sc.score(x, A, seed=5)
    assert r.shape == (4,)


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}", flush=True)
        except Exception as e:
            failed += 1
            import traceback; traceback.print_exc()
            print(f"FAIL {n}: {e!r}", flush=True)
    print(f"{len(names) - failed}/{len(names)} passed")
    sys.exit(1 if failed else 0)