File size: 13,521 Bytes
d8e9a5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Checks before an RL training run (sim/rl_policy.py, sim/rl_env.py, eval_policy.py --fast).

1. same_as_eval: with the noise off and one scene at a time, the RL environment and sampler reproduce
   eval_policy.py exactly on the same scenes (success, frames, closest approach, closing error):
   a) eval_policy --fast vs normal; b) the RL path with the action expert in bfloat16 (as loaded) vs
   eval_policy; c) the RL path with the expert in float32 (as trained here) vs eval_policy --expert-fp32.
2. noise: success with each candidate noise schedule (sigma at the first and last denoising step)
   against no noise, on the same scenes (what exploration costs).
3. likelihood: log-probabilities recomputed from stored chains and prefixes (other minibatch
   compositions) equal those at sampling time, so the PPO ratio starts at 1.
4. update: after one PPO step only the intended weights changed; the backbone is bit-identical.
5. reload: a saved checkpoint keeps the baseline's normalization, loads in eval_policy.load_policy
   (float32 expert, full precision) and gives the same chunk for the same x_0.
Writes <out>/rl_check.md and .json. Needs anti-aliasing off (SIM_OFFSAMPLES=0).

Run (pod):  MUJOCO_GL=egl PHASE2_PROFILE=baseline SIM_OFFSAMPLES=0 .venv/bin/python sim/rl_check.py \
                --policy models/baseline --out sim/reports/rl/check
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os
import subprocess
import sys
import tempfile
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
FIELDS = ("success", "frames", "closest_mm", "close_lateral_mm")


def eval_run(policy, n, seed, out, fast, fp32=False):
    out = Path(out)
    if not (out / "eval_results.json").exists():
        cmd = [sys.executable, str(HERE / "eval_policy.py"), "--policy", policy, "--episodes", str(n), "--workers", "2",
               "--seed", str(seed), "--video-episodes", "0", "--out", str(out)]
        cmd += (["--fast"] if fast else []) + (["--expert-fp32"] if fp32 else [])
        subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=dict(os.environ))
    return {e["index"]: e for e in json.loads((out / "eval_results.json").read_text())["episodes"]}


def compare(a: dict, b: dict):
    diffs = [(i, f, a[i].get(f), b[i].get(f)) for i in sorted(a) for f in FIELDS if a[i].get(f) != b[i].get(f)]
    return dict(identical=not diffs, differences=diffs[:10], episodes=len(a),
                success=(sum(bool(x["success"]) for x in a.values()), sum(bool(x["success"]) for x in b.values())))


def digest(t):
    return hashlib.sha1(t.detach().float().cpu().numpy().tobytes()).hexdigest()


def set_schedule(pol, s0, s1):
    """Geometric noise schedule from s0 (first denoising step) to s1 (last), as FlowRL builds it."""
    import math

    import torch

    frac = torch.linspace(0.0, 1.0, pol.n_steps, device=pol.device)[:, None]
    pol.log_sigma.data = (math.log(s0) + frac * (math.log(s1) - math.log(s0))).expand(pol.n_steps, pol.adim).clone()
    pol.sigma_min, pol.sigma_max = 0.5 * min(s0, s1), 1.5 * max(s0, s1)


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("--policy", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--same-episodes", type=int, default=8)
    ap.add_argument("--noise-episodes", type=int, default=60)
    ap.add_argument("--seed", type=int, default=9_000_003)
    ap.add_argument("--noise-seed", type=int, default=9_400_003)
    ap.add_argument("--schedules", default="0.1:0.002,0.2:0.002,0.3:0.003",
                    help="candidate noise schedules, first:last denoising step, comma-separated")
    args = ap.parse_args()
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    report = dict(args=vars(args))
    schedules = [tuple(float(x) for x in s.split(":")) for s in args.schedules.split(",")]

    # 1a / reference runs of eval_policy.py (before this process takes GPU memory).
    normal = eval_run(args.policy, args.same_episodes, args.seed, out / "eval_normal", fast=False)
    fast = eval_run(args.policy, args.same_episodes, args.seed, out / "eval_fast", fast=True)
    fp32 = eval_run(args.policy, args.same_episodes, args.seed, out / "eval_fast_fp32", fast=True, fp32=True)
    report["fast_vs_normal"] = compare(fast, normal)
    report["eval_fp32_vs_bf16"] = compare(fp32, normal)
    print("fast vs normal:", report["fast_vs_normal"], "| eval fp32 vs bf16 expert:", report["eval_fp32_vs_bf16"], flush=True)

    import numpy as np
    import torch

    from episode import load_config
    from rl_env import VecChessEnv
    from rl_policy import FlowRL
    from rl_train import ppo_update, run_episodes, summarize

    cfg = load_config()
    instr = cfg["dataset"]["instruction"]

    def same(pol):
        venv = VecChessEnv(1, cfg)
        eps = run_episodes(pol, venv, args.seed, list(range(args.same_episodes)), noise=False, early_stop=False,
                           check_expert=True, record=False, eval_noise_seeds=True)
        venv.close()
        return {e["info"]["index"]: dict(e["result"], index=e["info"]["index"]) for e in eps}

    # 1b. the RL path with the expert in bfloat16, as eval_policy loads it.
    pol = FlowRL(args.policy, instr, expert_fp32=False)
    report["rl_bf16_vs_eval"] = compare(same(pol), normal)
    print("rl bf16 vs eval:", report["rl_bf16_vs_eval"], flush=True)
    del pol
    torch.cuda.empty_cache()

    # 1c. the RL path with the expert in float32 vs eval_policy --expert-fp32.
    pol = FlowRL(args.policy, instr, *schedules[0], expert_fp32=True)
    base_digests = {n: digest(p) for n, p in pol.model.named_parameters()}
    report["rl_fp32_vs_eval_fp32"] = compare(same(pol), fp32)
    print("rl fp32 vs eval fp32:", report["rl_fp32_vs_eval_fp32"], flush=True)

    # 2. what exploration costs, per candidate schedule (batched, same scenes).
    venv = VecChessEnv(8, cfg)
    idx = list(range(args.noise_episodes))
    torch.manual_seed(0)
    report["noise"] = {"off": summarize(run_episodes(pol, venv, args.noise_seed, idx, noise=False, early_stop=False,
                                                     check_expert=False, record=False))}
    for s0, s1 in schedules:
        set_schedule(pol, s0, s1)
        report["noise"][f"{s0}:{s1}"] = summarize(run_episodes(pol, venv, args.noise_seed, idx, noise=True,
                                                               early_stop=False, check_expert=False, record=False))
        print("noise", f"{s0}:{s1}", report["noise"][f"{s0}:{s1}"], flush=True)
    print("noise off", report["noise"]["off"], flush=True)

    # 3. likelihood of stored chains with their stored prefixes, other minibatch compositions.
    s0, s1 = schedules[0]
    set_schedule(pol, s0, s1)
    eps = run_episodes(pol, venv, args.noise_seed + 1, list(range(8)), noise=True, early_stop=True, check_expert=False,
                       record=True)
    venv.close()
    dec = [d for e in eps for d in e["decisions"]][:24]
    with torch.no_grad():
        chain = torch.stack([d["chain"] for d in dec]).to(pol.device)
        old = torch.stack([d["logp"] for d in dec]).to(pol.device)
        new_all, _ = pol.evaluate(None, chain, prefix=pol.stack_prefix([d["prefix"] for d in dec]))
        new_one = torch.cat([pol.evaluate(None, d["chain"][None].to(pol.device), prefix=pol.stack_prefix([d["prefix"]]))[0]
                             for d in dec[:8]])
    report["likelihood"] = dict(
        schedule=f"{s0}:{s1}", decisions=len(dec), logp_scale=round(float(old.abs().mean()), 1),
        max_abs_diff_batch=float((new_all - old).abs().max()), max_ratio_minus_1_batch=float(((new_all - old).exp() - 1).abs().max()),
        max_abs_diff_single=float((new_one - old[:8]).abs().max()),
        max_ratio_minus_1_single=float(((new_one - old[:8]).exp() - 1).abs().max()))
    print("likelihood:", report["likelihood"], flush=True)

    # 4. one PPO step: which weights change.
    for d in dec:
        d["adv"], d["ret"] = float(np.random.randn()), float(np.random.rand())
    opt = torch.optim.AdamW([dict(params=pol.policy_params(), lr=3e-6), dict(params=list(pol.critic.parameters()), lr=3e-4)])
    ns = argparse.Namespace(epochs=1, minibatch=8, clip=0.2, vf_coef=0.5, max_grad_norm=1.0, target_kl=1e9)
    upd = ppo_update(pol, opt, dec, ns, policy_on=True)
    changed = [n for n, p in pol.model.named_parameters() if digest(p) != base_digests[n]]
    groups = {}
    for n in changed:
        g = n.split(".")[0] if not n.startswith("vlm_with_expert.") else ".".join(n.split(".")[:2])
        groups[g] = groups.get(g, 0) + 1
    trained = set(pol.trained_names)
    with torch.no_grad():
        after, _ = pol.evaluate(None, chain, prefix=pol.stack_prefix([d["prefix"] for d in dec]))
    report["update"] = dict(step=upd, changed_tensors=len(changed), trained_tensors=len(trained),
                            changed_outside_trained=[n for n in changed if n not in trained][:10],
                            trained_unchanged=len(trained - set(changed)), changed_groups=groups,
                            backbone_identical=not any(n.startswith("vlm_with_expert.vlm.") for n in changed),
                            state_proj_identical=not any(n.startswith("state_proj.") for n in changed),
                            logp_change_after_step=float((after - new_all).abs().mean()))
    print("update:", report["update"], flush=True)

    # 5. save, reload (as eval_policy --expert-fp32 loads it), same chunk.
    with tempfile.TemporaryDirectory() as tmp:
        pol.save(tmp)
        from safetensors.torch import load_file

        from eval_policy import load_policy
        norm_same = all(
            all(torch.equal(a[k], b[k]) for k in a)
            for f in Path(args.policy).glob("policy_*processor*.safetensors")
            for a, b in [(load_file(str(f)), load_file(str(Path(tmp) / f.name)))])
        loaded, _, _, _ = load_policy(tmp, expert_fp32=True)
        mine = dict(pol.model.named_parameters())
        weights_same = all(torch.equal(p.detach(), mine[n].detach()) for n, p in loaded.model.named_parameters()
                           if n.startswith("vlm_with_expert.lm_expert."))
        del loaded
        re = FlowRL(tmp, instr, *schedules[0], expert_fp32=True)
        with torch.no_grad():
            obs = [d for d in dec[:4]]
            x0 = pol.x0(4)
            p1 = pol.stack_prefix([d["prefix"] for d in obs])
            c1 = pol.evaluate(None, chain[:4], prefix=p1)[0]
            c2 = re.evaluate(None, chain[:4], prefix=re.stack_prefix([d["prefix"] for d in obs]))[0]
        report["reload"] = dict(normalization_identical=bool(norm_same), expert_weights_identical=bool(weights_same),
                                max_logp_diff=float((c1 - c2).abs().max()), files=sorted(p.name for p in Path(tmp).iterdir()))
    print("reload:", report["reload"], flush=True)

    (out / "rl_check.json").write_text(json.dumps(report, indent=1, default=str))
    lines = ["# RL checks", "", f"Policy `{args.policy}`.", "",
             f"1. Same as eval_policy ({args.same_episodes} scenes, seed {args.seed}, noise off, one scene at a time):",
             f"   - eval_policy --fast vs normal: {report['fast_vs_normal']['identical']}",
             f"   - RL path, expert bfloat16 vs eval_policy: {report['rl_bf16_vs_eval']['identical']} "
             f"{'' if report['rl_bf16_vs_eval']['identical'] else report['rl_bf16_vs_eval']['differences'][:3]}",
             f"   - RL path, expert float32 vs eval_policy --expert-fp32: {report['rl_fp32_vs_eval_fp32']['identical']} "
             f"{'' if report['rl_fp32_vs_eval_fp32']['identical'] else report['rl_fp32_vs_eval_fp32']['differences'][:3]}",
             f"   - eval_policy, expert float32 vs bfloat16: successes {report['eval_fp32_vs_bf16']['success']}",
             f"2. Noise schedules ({args.noise_episodes} scenes, seed {args.noise_seed}): success / clean lift / closing error median:",
             ] + [f"   - {k}: {v['success']:.1%} / {v['clean_lift']:.1%} / {v['close_mm_median']} mm" for k, v in report["noise"].items()] + [
             f"3. Likelihood ({report['likelihood']['schedule']}), {report['likelihood']['decisions']} stored chains: max |ratio - 1| "
             f"{report['likelihood']['max_ratio_minus_1_batch']:.2e} (one minibatch), "
             f"{report['likelihood']['max_ratio_minus_1_single']:.2e} (one at a time); log-prob scale {report['likelihood']['logp_scale']}.",
             f"4. One PPO step (lr 3e-6): {report['update']['changed_tensors']} tensors changed of {report['update']['trained_tensors']} "
             f"trained; outside the trained set: {report['update']['changed_outside_trained'] or 'none'}; backbone identical "
             f"{report['update']['backbone_identical']}; state_proj identical {report['update']['state_proj_identical']}; "
             f"mean log-prob change {report['update']['logp_change_after_step']:.3g}; KL {report['update']['step'].get('kl')}.",
             f"5. Save/reload: normalization identical {report['reload']['normalization_identical']}; expert weights identical "
             f"after eval_policy's float32 load {report['reload']['expert_weights_identical']}; max log-prob difference "
             f"{report['reload']['max_logp_diff']:.2e}."]
    (out / "rl_check.md").write_text("\n".join(lines) + "\n")
    print("\n".join(lines))


if __name__ == "__main__":
    main()