File size: 8,444 Bytes
d350951
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Validate the multi-config public data interface (local; CI later).

Checks:
  - hardware_re4 parquet columns/dtypes match the expected full schema
  - sr_pareto consolidated table has required columns and non-empty coverage
  - latent_routing gate: fail if README declares the config without three CSVs
  - bundle.json should not be the sole SR interface (warn on absolute paths)
"""

from __future__ import annotations

import argparse
import json
import re
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]

# Full on-disk schema for system_telemetry_v1_batch_*.parquet
HARDWARE_RE4_SCHEMA: dict[str, str] = {
    "timestamp_ms": "int64",
    "power_usage_mw": "uint32",
    "temperature_c": "uint32",
    "graphics_clock_mhz": "uint32",
    "memory_clock_mhz": "uint32",
    "pcie_rx_kbps": "uint32",
    "pcie_tx_kbps": "uint32",
    "pstate": "uint32",
    "throttle_reasons_bitmask": "uint64",
    "fan_speed_perc": "uint32",
    "memory_used_mb": "uint64",
    "memory_total_mb": "uint64",
    "encoder_util_perc": "uint32",
    "decoder_util_perc": "uint32",
    "cpu_tctl_c": "double",  # pyarrow float -> double
    "cpu_ccd1_c": "double",
    "cpu_ccd2_c": "double",
    "cpu_package_power_w": "double",
}

SR_REQUIRED = {"model", "condition", "complexity", "loss", "equation"}

LATENT_CSVS = [
    ROOT / "first-day-testing-real-weights/second-test/snn_latent_telemetry.csv",
    ROOT / "first-day-testing-real-weights/third-test/snn_latent_telemetry.csv",
    ROOT / "first-day-testing-real-weights/fourth-test/snn_latent_telemetry.csv",
]


def _normalize_type(t: str) -> str:
    t = str(t).lower()
    aliases = {
        "float": "double",
        "float32": "float",
        "float64": "double",
        "boolean": "bool",
    }
    return aliases.get(t, t)


def check_hardware_re4(root: Path, errors: list[str], warnings: list[str]) -> None:
    try:
        import pyarrow.parquet as pq
    except ImportError:
        errors.append("pyarrow required to validate hardware_re4 parquet")
        return

    pattern = root / "origin_hardware_baselines/resident_evil_4"
    files = sorted(pattern.glob("system_telemetry_v1_batch_*.parquet"))
    if len(files) < 1:
        errors.append("no system_telemetry_v1_batch_*.parquet files found")
        return
    if len(files) != 48:
        warnings.append(f"expected 48 RE4 parquet batches, found {len(files)}")

    table = pq.read_table(files[0])
    actual = {f.name: _normalize_type(str(f.type)) for f in table.schema}
    expected = {k: _normalize_type(v) for k, v in HARDWARE_RE4_SCHEMA.items()}

    missing = sorted(set(expected) - set(actual))
    extra = sorted(set(actual) - set(expected))
    if missing:
        errors.append(f"hardware_re4 missing columns: {missing}")
    if extra:
        warnings.append(f"hardware_re4 extra columns vs CONTEXT schema: {extra}")

    for name, exp_t in expected.items():
        if name not in actual:
            continue
        # allow float/double flexibility for cpu temps
        act = actual[name]
        if act == exp_t:
            continue
        if {act, exp_t} <= {"float", "double"}:
            continue
        if {act, exp_t} <= {"int64", "uint64"} and name == "throttle_reasons_bitmask":
            continue
        errors.append(f"hardware_re4 dtype mismatch {name}: got {act}, expected {exp_t}")

    total_rows = sum(pq.read_table(f).num_rows for f in files)
    if total_rows < 1000:
        errors.append(f"hardware_re4 too few rows: {total_rows}")
    else:
        print(f"  hardware_re4: {len(files)} files, {total_rows} rows, schema OK")


def check_sr_pareto(root: Path, errors: list[str], warnings: list[str]) -> None:
    csv_path = root / "sr_benchmark/sr_pareto_all.csv"
    pq_path = root / "sr_benchmark/sr_pareto_all.parquet"
    if not csv_path.exists() and not pq_path.exists():
        errors.append("sr_pareto_all.csv/.parquet missing — run scripts/build_sr_pareto_all.py")
        return

    import csv

    path = csv_path if csv_path.exists() else pq_path
    if path.suffix == ".csv":
        with path.open(newline="", encoding="utf-8") as f:
            reader = csv.DictReader(f)
            fields = set(reader.fieldnames or [])
            rows = list(reader)
    else:
        import pyarrow.parquet as pq

        table = pq.read_table(path)
        fields = set(table.column_names)
        rows = table.to_pylist()

    missing = SR_REQUIRED - fields
    if missing:
        errors.append(f"sr_pareto missing columns: {sorted(missing)}")
        return
    if not rows:
        errors.append("sr_pareto consolidated table is empty")
        return

    models = {r["model"] for r in rows}
    conditions = {r["condition"] for r in rows}
    if len(models) < 2:
        warnings.append(f"sr_pareto few models: {sorted(models)}")
    if not conditions:
        errors.append("sr_pareto has no conditions")
    print(
        f"  sr_pareto: {len(rows)} rows, {len(models)} models, "
        f"{len(conditions)} conditions"
    )

    bundle = root / "sr_benchmark/bundle.json"
    if bundle.exists():
        text = bundle.read_text(encoding="utf-8")
        abs_hits = re.findall(r'"/home/[^"]+"', text)
        if abs_hits:
            warnings.append(
                f"bundle.json still has {len(abs_hits)} absolute path strings "
                "(consolidated table is the Hub interface; fix paths when convenient)"
            )


def check_latent_gate(root: Path, errors: list[str], warnings: list[str]) -> None:
    readme = (root / "README.md").read_text(encoding="utf-8")
    has_latent_config = bool(
        re.search(r"config_name:\s*latent_routing", readme)
        or re.search(r'["\']latent_routing["\']', readme.split("---", 2)[1] if readme.startswith("---") else "")
    )
    present = [p for p in LATENT_CSVS if p.exists()]
    missing = [p for p in LATENT_CSVS if not p.exists()]

    if has_latent_config and missing:
        errors.append(
            "latent_routing config declared in README but feature CSVs missing: "
            + ", ".join(str(p.relative_to(root)) for p in missing)
        )
    elif missing:
        warnings.append(
            "latent_routing gated (expected): missing "
            + ", ".join(str(p.relative_to(root)) for p in missing)
        )
    else:
        print("  latent_routing gate: all three feature CSVs present")

    if present and not has_latent_config and not missing:
        warnings.append(
            "all latent CSVs present but latent_routing config not in README yet"
        )


def check_readme_configs(root: Path, errors: list[str], warnings: list[str]) -> None:
    readme = (root / "README.md").read_text(encoding="utf-8")
    if not readme.startswith("---"):
        errors.append("README.md missing YAML frontmatter")
        return
    parts = readme.split("---", 2)
    if len(parts) < 3:
        errors.append("README.md YAML frontmatter malformed")
        return
    yaml = parts[1]
    if re.search(r"config_name:\s*default\b", yaml):
        errors.append("README still has config_name: default (must force explicit configs)")
    for name in ("hardware_re4", "sr_pareto"):
        if f"config_name: {name}" not in yaml and f'config_name: "{name}"' not in yaml:
            errors.append(f"README YAML missing config_name: {name}")
    if "sr_pareto_all" not in yaml:
        warnings.append("README YAML may not point data_files at sr_pareto_all.*")
    # duplicate Usage sections
    if readme.count("\n## Usage\n") > 1:
        errors.append("README has duplicate ## Usage sections")
    print("  README configs: checked")


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--root", type=Path, default=ROOT)
    args = parser.parse_args()
    root: Path = args.root

    errors: list[str] = []
    warnings: list[str] = []

    print("validate_dataset")
    check_readme_configs(root, errors, warnings)
    check_hardware_re4(root, errors, warnings)
    check_sr_pareto(root, errors, warnings)
    check_latent_gate(root, errors, warnings)

    for w in warnings:
        print(f"WARN: {w}")
    for e in errors:
        print(f"ERROR: {e}")

    if errors:
        print(f"FAILED ({len(errors)} error(s), {len(warnings)} warning(s))")
        return 1
    print(f"OK ({len(warnings)} warning(s))")
    return 0


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