File size: 3,886 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
#!/usr/bin/env python3
"""SERA-CC Phase A: build the model-side capability-code tables.

Outputs (in ~/sera_v4_experiments/sera_cc/):
  codes_cc.npy       [n_episodes, max_frames] int32 — GT code of the
                     segment containing each frame, from the T1 run's
                     per-segment codes (t1_codes.npz: train rows from
                     the segment map + eval rows segmented with the
                     identical rule), REUSED verbatim.
  codes_cc_pred.npy  same layout — predicted codes: the frozen T1
                     capability encoder applied to each frame's
                     PARTIAL segment (feat_start = state at the
                     segment's first frame, feat_end = state at the
                     current frame). Phase A's inference-like code
                     source for scheduled sampling in C3.

Features are exactly t1_measure.py's: feat = observation.state (8-D)
at the boundary frames. Run on the train machine in the lerobot venv.
"""
import os
import sys
from pathlib import Path

import numpy as np

CCDIR = Path.home() / "sera_v4_experiments" / "sera_cc"
sys.path.insert(0, str(CCDIR))

import t1_measure as t1  # noqa: E402  (machine-side copy)


def main():
    import torch

    seg = t1.load_segment_map(t1.DEFAULT_SEGMENT_MAP)
    state_by_ep, action_by_ep, task_by_ep, _ = t1.load_episode_data(
        t1.DEFAULT_SNAPSHOT)
    train_eps = set(int(e) for e in seg["train_eps"])
    all_eps = sorted(state_by_ep)
    eval_eps = [e for e in all_eps if e not in train_eps]

    z = np.load(CCDIR / "t1_codes.npz")
    rows = ([(int(e), int(a), int(b), int(c)) for e, a, b, c in
             zip(z["train_rows"][:, 0], z["train_rows"][:, 1],
                 z["train_rows"][:, 2], z["train_codes"])]
            + [(int(e), int(a), int(b), int(c)) for e, a, b, c in
               zip(z["eval_rows"][:, 0], z["eval_rows"][:, 1],
                   z["eval_rows"][:, 2], z["eval_codes"])])
    n_eps = max(all_eps) + 1
    max_frames = max(len(state_by_ep[e]) for e in all_eps)
    gt = np.full((n_eps, max_frames), -1, dtype=np.int32)
    for e, a, b, c in rows:
        gt[e, a:b + 1] = c
    covered = int((gt >= 0).sum())
    total_frames = int(sum(len(state_by_ep[e]) for e in all_eps))
    print(f"segments {len(rows)}; frames covered {covered}/{total_frames}")
    assert covered == total_frames, "segment rows do not cover all frames"
    usage = np.bincount(gt[gt >= 0], minlength=64)
    print("GT code usage: codes used", int((usage > 0).sum()),
          "of 64; max share", float(usage.max() / usage.sum()))

    # Predicted codes: T1 encoder over partial segments.
    from capability_encoder import CapabilityEncoder

    model = CapabilityEncoder(feat_dim=8, hidden_dim=256, z_dim=64)
    model.load_state_dict(torch.load(CCDIR / "capability_encoder_t1.pt"))
    model.eval()
    dev = "cuda" if torch.cuda.is_available() else "cpu"
    model = model.to(dev)
    pred = np.full((n_eps, max_frames), -1, dtype=np.int32)
    with torch.no_grad():
        for e, a, b, _c in rows:
            st = state_by_ep[e]
            n = b - a + 1
            fs = np.repeat(st[a:a + 1], n, axis=0)
            fe = st[a:b + 1]
            codes = []
            for i in range(0, n, 4096):
                out = model.encode(
                    torch.tensor(fs[i:i + 4096], device=dev),
                    torch.tensor(fe[i:i + 4096], device=dev))
                codes.append(out["codes"].cpu().numpy())
            pred[e, a:b + 1] = np.concatenate(codes)
    agree = float((pred[pred >= 0] == gt[gt >= 0]).mean())
    print(f"pred-vs-GT agreement over frames: {agree:.4f}")
    np.save(CCDIR / "codes_cc.npy", gt)
    np.save(CCDIR / "codes_cc_pred.npy", pred)
    print("saved", CCDIR / "codes_cc.npy", gt.shape,
          CCDIR / "codes_cc_pred.npy", pred.shape)


if __name__ == "__main__":
    main()