File size: 4,195 Bytes
456c9d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Audit that a Task 0 Before/After config changes only approved fields.

The comparison is intentionally strict: task, init-state/trial set, action
timing, horizon, noise and environment settings must remain identical.  The
only planned differences are the policy/checkpoint identity and CFG guidance
settings.  This is a config audit, not a claim that two result directories
are statistically comparable by itself.
"""

from __future__ import annotations

import argparse
import json
import sys
from collections.abc import Mapping
from pathlib import Path
from typing import Any

from omegaconf import OmegaConf

SCRIPT_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = SCRIPT_DIR.parent
if str(SCRIPT_DIR) not in sys.path:
    sys.path.insert(0, str(SCRIPT_DIR))

from task0_baseline_common import load_config, require_project_path  # noqa: E402


ALLOWED_EXACT = {
    "protocol_version",
    "policy_role",
    "model.model_path",
    "model.checkpoint_repo",
    "model.checkpoint_revision",
    "model.checkpoint_weight_sha256",
    "model.model_type",
}
ALLOWED_GUIDANCE_SUFFIXES = {
    "cfgrl_guidance_scale",
    "unconditional_prob",
    "guidance_type",
    "positive_only_conditional",
}


def _flatten(value: Any, prefix: str = "") -> dict[str, Any]:
    if isinstance(value, Mapping):
        flattened: dict[str, Any] = {}
        for key in sorted(value):
            path = f"{prefix}.{key}" if prefix else str(key)
            flattened.update(_flatten(value[key], path))
        return flattened
    if isinstance(value, (list, tuple)):
        flattened = {}
        for index, item in enumerate(value):
            flattened.update(_flatten(item, f"{prefix}[{index}]"))
        return flattened
    return {prefix: value}


def _is_allowed(path: str) -> bool:
    if path in ALLOWED_EXACT:
        return True
    if path.startswith("model.openpi."):
        return path.rsplit(".", 1)[-1] in ALLOWED_GUIDANCE_SUFFIXES
    if path.startswith("model."):
        return path.rsplit(".", 1)[-1] in ALLOWED_GUIDANCE_SUFFIXES
    return False


def compare_configs(before: Path, after: Path) -> dict[str, Any]:
    before_cfg = load_config(before)
    after_cfg = load_config(after)
    before_values = _flatten(OmegaConf.to_container(before_cfg, resolve=True))
    after_values = _flatten(OmegaConf.to_container(after_cfg, resolve=True))
    paths = sorted(set(before_values) | set(after_values))
    differences = []
    for path in paths:
        left = before_values.get(path, "<missing>")
        right = after_values.get(path, "<missing>")
        if left != right:
            differences.append(
                {"path": path, "before": left, "after": right, "allowed": _is_allowed(path)}
            )
    disallowed = [item for item in differences if not item["allowed"]]
    return {
        "before": str(require_project_path(before, label="before config")),
        "after": str(require_project_path(after, label="after config")),
        "difference_count": len(differences),
        "allowed_difference_count": len(differences) - len(disallowed),
        "disallowed_difference_count": len(disallowed),
        "differences": differences,
        "ok": not disallowed,
    }


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--before", type=Path, required=True)
    parser.add_argument("--after", type=Path, required=True)
    parser.add_argument("--json", action="store_true", help="emit machine-readable JSON")
    args = parser.parse_args()
    report = compare_configs(args.before, args.after)
    if args.json:
        print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True))
    else:
        print(
            f"before_after_config_ok={report['ok']} "
            f"differences={report['difference_count']} "
            f"disallowed={report['disallowed_difference_count']}"
        )
        for item in report["differences"]:
            marker = "allowed" if item["allowed"] else "DISALLOWED"
            print(f"[{marker}] {item['path']}: {item['before']!r} -> {item['after']!r}")
    return 0 if report["ok"] else 1


if __name__ == "__main__":
    raise SystemExit(main())