File size: 14,196 Bytes
6f003f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Strict, CPU-only validation for an RLinf CFG checkpoint.

The RLinf loader currently uses ``strict=False`` for ``full_weights.pt``.  A
successful call to that loader therefore does not prove that a CFG checkpoint
contains the complete policy.  This validator checks the checkpoint layout,
the DCP training-state marker, exact model key/shape coverage, finite weights,
and the copied LIBERO norm statistics before an inference smoke is attempted.
It never constructs CUDA tensors.
"""

from __future__ import annotations

import argparse
import hashlib
import json
from dataclasses import replace
from pathlib import Path
from typing import Any

import torch
from safetensors import safe_open


PROJECT_ROOT = Path("/data/myx/RL_post_train").resolve()
BASE_MODEL = PROJECT_ROOT / "checkpoints/base/RLinf-Pi05-LIBERO-SFT"
BASE_WEIGHTS = BASE_MODEL / "model.safetensors"
BASE_NORM_STATS = BASE_MODEL / "physical-intelligence/libero/norm_stats.json"
EXPECTED_BASE_WEIGHT_SHA256 = (
    "4616e4c1966a5fb063b442ea5d69857f45e873222d839b794634d87d252ab9e7"
)


def _sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(16 * 1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def _inside(path: Path, root: Path = PROJECT_ROOT) -> bool:
    try:
        path.resolve().relative_to(root.resolve())
    except ValueError:
        return False
    return True


def _resolve_project_path(raw: Path, label: str, errors: list[str]) -> Path:
    path = raw.expanduser()
    if not path.is_absolute():
        path = PROJECT_ROOT / path
    path = path.resolve()
    if not _inside(path):
        errors.append(f"{label} is outside project root: {path}")
    return path


def _find_layout(checkpoint: Path, errors: list[str]) -> dict[str, Path | None]:
    """Resolve actor root, full weights and DCP directory from common inputs."""
    if checkpoint.is_file():
        if checkpoint.name != "full_weights.pt":
            errors.append(f"checkpoint file must be full_weights.pt: {checkpoint}")
        weights = checkpoint
        model_state = checkpoint.parent
        actor_root = model_state.parent if model_state.name == "model_state_dict" else None
    else:
        candidates = [
            checkpoint / "model_state_dict" / "full_weights.pt",
            checkpoint / "actor" / "model_state_dict" / "full_weights.pt",
        ]
        weights = next((candidate for candidate in candidates if candidate.is_file()), None)
        if weights is None:
            errors.append(f"missing full_weights.pt below checkpoint: {checkpoint}")
            actor_root = None
        elif weights.parent.parent.name == "actor":
            actor_root = weights.parent.parent
        else:
            actor_root = weights.parent.parent

    dcp = actor_root / "dcp_checkpoint" if actor_root is not None else None
    return {"actor_root": actor_root, "weights": weights, "dcp": dcp}


def _expected_model_state() -> dict[str, Any]:
    """Build CFG metadata on ``meta`` and normalize tied state-dict aliases."""
    from rlinf.models.embodiment.openpi.dataconfig import get_openpi_config
    from rlinf.models.embodiment.openpi_cfg.openpi_cfg_action_model import (
        OpenPi0Config,
        OpenPi0ForCFGActionPrediction,
    )

    base = get_openpi_config("pi05_libero").model
    config = replace(
        OpenPi0Config(**base.__dict__),
        train_expert_only=False,
        cfgrl_guidance_scale=1.0,
        unconditional_prob=0.1,
        guidance_type="positive",
        positive_only_conditional=True,
    )
    with torch.device("meta"):
        model = OpenPi0ForCFGActionPrediction(config)
    try:
        parameters = dict(model.named_parameters())
        parameter_by_id = {id(value): key for key, value in parameters.items()}
        state_shapes: dict[str, tuple[int, ...]] = {}
        alias_to_canonical: dict[str, str] = {}
        for key, value in model.state_dict().items():
            try:
                canonical = parameter_by_id.get(id(model.get_parameter(key)), key)
            except (AttributeError, KeyError):
                canonical = key
            alias_to_canonical[key] = canonical
            state_shapes.setdefault(canonical, tuple(value.shape))
        return {
            "shapes": state_shapes,
            "alias_to_canonical": alias_to_canonical,
            "parameter_keys": set(parameters),
            "parameter_numel": sum(value.numel() for value in parameters.values()),
        }
    finally:
        del model


def _base_shapes(errors: list[str]) -> dict[str, tuple[int, ...]]:
    if not BASE_WEIGHTS.is_file():
        errors.append(f"missing frozen base weights: {BASE_WEIGHTS}")
        return {}
    with safe_open(str(BASE_WEIGHTS), framework="pt", device="cpu") as handle:
        return {key: tuple(handle.get_slice(key).get_shape()) for key in handle.keys()}


def _check_finite(state: dict[str, Any], errors: list[str]) -> dict[str, Any]:
    checked = 0
    nonfinite: list[str] = []
    chunk_size = 16 * 1024 * 1024
    for key, value in state.items():
        if not isinstance(value, torch.Tensor):
            errors.append(f"state entry is not a tensor: {key}")
            continue
        checked += 1
        if value.is_floating_point() or value.is_complex():
            flat = value.detach().reshape(-1)
            for start in range(0, flat.numel(), chunk_size):
                if not bool(torch.isfinite(flat[start : start + chunk_size]).all()):
                    nonfinite.append(key)
                    break
    if nonfinite:
        errors.append(f"non-finite tensors: {nonfinite[:8]}")
    return {"tensor_entries_checked": checked, "nonfinite_keys": nonfinite}


def validate(
    checkpoint_arg: Path,
    *,
    metadata_only: bool,
    skip_base_hash: bool,
) -> dict[str, Any]:
    errors: list[str] = []
    checkpoint = _resolve_project_path(checkpoint_arg, "checkpoint", errors)
    if not checkpoint.exists():
        errors.append(f"checkpoint does not exist: {checkpoint}")

    layout = _find_layout(checkpoint, errors) if checkpoint.exists() else {}
    actor_root = layout.get("actor_root")
    weights = layout.get("weights")
    dcp = layout.get("dcp")
    for label, path in (("actor_root", actor_root), ("full_weights", weights), ("dcp", dcp)):
        if path is not None and not _inside(path):
            errors.append(f"{label} is outside project root: {path}")

    base_hash = None
    if BASE_WEIGHTS.is_file() and not skip_base_hash:
        base_hash = _sha256(BASE_WEIGHTS)
        if base_hash != EXPECTED_BASE_WEIGHT_SHA256:
            errors.append(
                "frozen base model SHA256 mismatch: "
                f"{base_hash} != {EXPECTED_BASE_WEIGHT_SHA256}"
            )

    dcp_files: list[Path] = []
    if dcp is not None:
        metadata = dcp / ".metadata"
        dcp_files = sorted(dcp.glob("__*.distcp"))
        if not metadata.is_file() or metadata.stat().st_size == 0:
            errors.append(f"missing/empty DCP metadata: {metadata}")
        if not dcp_files:
            errors.append(f"missing DCP shard files below: {dcp}")

    expected = _expected_model_state() if BASE_WEIGHTS.is_file() else {}
    base_shapes = _base_shapes(errors)
    expected_shapes = expected.get("shapes", {})
    alias_to_canonical = expected.get("alias_to_canonical", {})
    parameter_keys = expected.get("parameter_keys", set())
    # The base safetensors omits one tied input-embedding alias; normalize both
    # names to the same parameter before checking coverage and shapes.
    if expected and base_shapes:
        for key, shape in base_shapes.items():
            canonical = alias_to_canonical.get(key)
            if canonical is None or canonical not in expected_shapes:
                errors.append(f"unexpected frozen base key: {key}")
            elif expected_shapes[canonical] != shape:
                errors.append(
                    f"base/model shape mismatch for {key}: "
                    f"{shape} != {expected_shapes[canonical]}"
                )

    state: dict[str, Any] | None = None
    weights_hash = None
    finite_report: dict[str, Any] = {"skipped": True}
    key_report: dict[str, Any] = {}
    if isinstance(weights, Path) and weights.is_file():
        weights_hash = _sha256(weights)
        try:
            state = torch.load(weights, map_location="meta", weights_only=True)
            if not isinstance(state, dict):
                errors.append(f"full_weights.pt is not a state dict: {type(state)!r}")
                state = None
        except Exception as exc:  # pragma: no cover - exercised by corrupt files
            errors.append(f"cannot load full_weights.pt metadata: {type(exc).__name__}: {exc}")

        if state is not None and expected_shapes:
            actual = set(state)
            normalized: dict[str, Any] = {}
            duplicate_aliases: list[str] = []
            unexpected = []
            for key, value in state.items():
                canonical = alias_to_canonical.get(key)
                if canonical is None:
                    unexpected.append(key)
                    continue
                if canonical in normalized:
                    duplicate_aliases.append(key)
                    continue
                normalized[canonical] = value
            expected_keys = set(expected_shapes)
            missing = sorted(expected_keys - set(normalized))
            shape_mismatch = sorted(
                key
                for key in expected_keys & set(normalized)
                if not isinstance(normalized[key], torch.Tensor)
                or tuple(normalized[key].shape) != expected_shapes[key]
            )
            expected_numel = int(expected.get("parameter_numel", 0))
            actual_numel = sum(
                int(normalized[key].numel())
                for key in parameter_keys & set(normalized)
                if isinstance(normalized[key], torch.Tensor)
            )
            key_report = {
                "expected_keys": len(expected_keys),
                "actual_keys": len(actual),
                "normalized_keys": len(normalized),
                "missing_keys": missing,
                "unexpected_keys": unexpected,
                "duplicate_aliases": sorted(duplicate_aliases),
                "shape_mismatch_keys": shape_mismatch,
                "coverage": len(expected_keys & set(normalized)) / len(expected_keys),
                "expected_parameter_numel": expected_numel,
                "actual_parameter_numel": actual_numel,
            }
            if (
                missing
                or unexpected
                or shape_mismatch
                or actual_numel != expected_numel
            ):
                errors.append("CFG full_weights key/shape coverage is not exact")

        if not metadata_only and state is not None:
            # Reload on CPU only for finite-value checking.  The first metadata
            # load uses meta tensors and does not allocate the model weights.
            cpu_state = torch.load(weights, map_location="cpu", weights_only=True)
            if isinstance(cpu_state, dict):
                finite_report = _check_finite(cpu_state, errors)
            else:
                errors.append("CPU full_weights reload is not a state dict")

    norm_candidates: list[Path] = []
    if actor_root is not None:
        norm_candidates.append(actor_root / "physical-intelligence/libero/norm_stats.json")
        norm_candidates.append(actor_root.parent / "physical-intelligence/libero/norm_stats.json")
    norm_path = next((path for path in norm_candidates if path.is_file()), None)
    norm_hash = None
    if norm_path is None:
        errors.append("checkpoint is missing copied physical-intelligence/libero/norm_stats.json")
    else:
        try:
            json.loads(norm_path.read_text(encoding="utf-8"))
        except Exception as exc:
            errors.append(f"invalid checkpoint norm_stats.json: {type(exc).__name__}: {exc}")
        norm_hash = _sha256(norm_path)
        if BASE_NORM_STATS.is_file() and norm_hash != _sha256(BASE_NORM_STATS):
            errors.append("checkpoint norm_stats.json SHA256 differs from frozen base")

    report = {
        "checkpoint": str(checkpoint),
        "actor_root": str(actor_root) if actor_root is not None else None,
        "full_weights": str(weights) if isinstance(weights, Path) else None,
        "full_weights_sha256": weights_hash,
        "dcp": {
            "path": str(dcp) if dcp is not None else None,
            "metadata_present": bool(dcp and (dcp / ".metadata").is_file()),
            "shard_count": len(dcp_files),
        },
        "base_model": {
            "path": str(BASE_WEIGHTS),
            "sha256": base_hash,
            "expected_sha256": EXPECTED_BASE_WEIGHT_SHA256,
            "key_count": len(base_shapes),
        },
        "norm_stats": {
            "path": str(norm_path) if norm_path is not None else None,
            "sha256": norm_hash,
            "base_sha256": _sha256(BASE_NORM_STATS) if BASE_NORM_STATS.is_file() else None,
        },
        "key_coverage": key_report,
        "finite": finite_report,
        "metadata_only": metadata_only,
        "ok": not errors,
        "errors": errors,
    }
    return report


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--checkpoint", type=Path, required=True)
    parser.add_argument(
        "--metadata-only",
        action="store_true",
        help="Skip the CPU reload used for finite-value checking.",
    )
    parser.add_argument(
        "--skip-base-hash",
        action="store_true",
        help="Do not hash the frozen 7.5GB base safetensors file.",
    )
    args = parser.parse_args()
    report = validate(
        args.checkpoint,
        metadata_only=args.metadata_only,
        skip_base_hash=args.skip_base_hash,
    )
    print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True))
    return 0 if report["ok"] else 1


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