File size: 5,692 Bytes
0edf333
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Preserve the MPS scanner while treating API null gradient columns as absent.

Some W&B history pages expand sparse schemas onto validation/final rows. Removing
only None-valued gradient keys prevents those rows being misidentified as extra
updates. Every row, genuine SDK counter, user step and populated value survives;
the original exact coverage and scalar checks still decide acceptance.
"""

from __future__ import annotations

import hashlib
import importlib.util
import json
import platform
from pathlib import Path

import click


def require(condition, message):
    if not condition:
        raise ValueError(message)


def sha(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def normalize_server_rows(records, *, prefix=""):
    """Remove only null gradient columns; do not filter rows or infer counters."""
    records = list(records)
    normalized, affected = [], []
    for row in records:
        null_keys = [key for key, value in row.items()
                     if key.startswith(prefix + "gradients/") and value is None]
        normalized.append({key: value for key, value in row.items() if key not in null_keys})
        if null_keys:
            affected.append({"sdk_step": row.get("_step"), "removed_null_keys": sorted(null_keys)})
    return normalized, {"scanned_rows": len(records), "retained_rows": len(normalized),
        "raw_sdk_steps": [row.get("_step") for row in records],
        "null_gradient_fields_removed": sum(len(row["removed_null_keys"]) for row in affected),
        "rows_with_null_gradient_fields": len(affected), "affected_rows": affected,
        "all_rows_and_sdk_counters_retained": True, "populated_values_unchanged": True,
        "sdk_schedule_changed": False}


def load_original(path):
    spec = importlib.util.spec_from_file_location("portable_original_mps_tracking", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def require_docker():
    require(platform.system() == "Linux" and Path("/.dockerenv").is_file(), "Run tracking verification inside Docker")


def verify(root, api, *, original_verifier):
    require_docker()
    original_verifier = Path(original_verifier).resolve()
    helper = original_verifier.with_name("verify_position_tracking.py")
    sources = {str(path): sha(path) for path in (Path(__file__).resolve(), original_verifier, helper)}
    original = load_original(original_verifier)
    strict_verify = original.H.verify_rows

    def adapted_verify(local, server, *args, **kwargs):
        clean, details = normalize_server_rows(server, prefix=kwargs.get("prefix", ""))
        result = strict_verify(local, clean, *args, **kwargs)
        result["sparse_null_gradient_columns"] = details
        return result

    original.H.verify_rows = adapted_verify
    try:
        report = original.verify_campaign(root, api)
    finally:
        original.H.verify_rows = strict_verify
    require(report.get("status") == "verified", "The unchanged strict scanner did not verify the campaign")
    require(all(sha(path) == expected for path, expected in sources.items()), "Tracking adapter/scanner source changed during verification")
    stages = report["stages"]
    report["sparse_history_adapter"] = {
        "scope": "Only None-valued gradient columns removed from scanner copies; original server histories and every row/counter/populated value preserved",
        "wrapper_path": str(Path(__file__).resolve()), "wrapper_sha256": sha(__file__),
        "original_verifier_path": str(original_verifier), "original_verifier_sha256": sources[str(original_verifier)],
        "original_shared_scanner_path": str(helper), "original_shared_scanner_sha256": sources[str(helper)],
        "sdk_schedule_changed": False, "original_exact_gradient_coverage_and_all_numeric_comparisons_unchanged": True,
        "original_run_streams_modified_or_replayed": False,
        "null_gradient_fields_removed": sum(stage["sparse_null_gradient_columns"]["null_gradient_fields_removed"] for stage in stages),
        "rows_with_null_gradient_fields": sum(stage["sparse_null_gradient_columns"]["rows_with_null_gradient_fields"] for stage in stages),
        "scanned_rows": sum(stage["sparse_null_gradient_columns"]["scanned_rows"] for stage in stages)}
    metadata = report.setdefault("metadata_sha256", {})
    require(all(path not in metadata or metadata[path] == digest for path, digest in sources.items()),
            "Adapter source fingerprint contradicts original accepted metadata")
    metadata.update(sources)
    return report


@click.command()
@click.option("--root", type=click.Path(path_type=Path, exists=True, file_okay=False), required=True)
@click.option("--original-verifier", type=click.Path(path_type=Path, exists=True, dir_okay=False), required=True)
@click.option("--output", type=click.Path(path_type=Path))
def main(root, original_verifier, output):
    """Verify all original streams with explicit sparse-API provenance."""
    output = root / "tracking-verification.json" if output is None else output
    require(not output.exists(), "Tracking output exists; preserve the accepted receipt")
    import wandb

    report = verify(root, wandb.Api(timeout=60), original_verifier=original_verifier)
    require(not output.exists(), "Tracking output appeared during verification; preserve it")
    output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n")
    click.echo(json.dumps({key: report[key] for key in ("status", "optimizer_updates_verified",
        "backward_calls_verified", "gradient_scalar_values_verified", "sparse_history_adapter")}, indent=2))


if __name__ == "__main__":
    main()