File size: 13,521 Bytes
02443ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
from collections import Counter
import hashlib
import json
from pathlib import Path
import time

import torch
from safetensors.torch import load_file


EXPECTED_ROWS = 108_096
EXPECTED_TRAIN = 104_000
EXPECTED_VALIDATION = 4_096
EXPECTED_ANCHORS = 72_000
EXPECTED_VERSION = "lens-safe-v4"
COMPARE_FIELDS = (
    "source_record_id",
    "style_id",
    "source",
    "split",
    "shard",
    "factor",
    "factor_index",
    "family",
    "level",
    "sign",
    "signed_intensity",
    "operation_seed",
    "transform_version",
    "anchor_kind",
    "repeat_of",
    "panel",
    "anima_pilot",
)


def read_json(path: Path) -> dict:
    return json.loads(path.read_text(encoding="utf-8"))


def read_jsonl(path: Path) -> list[dict]:
    with path.open(encoding="utf-8") as handle:
        return [json.loads(line) for line in handle if line.strip()]


def distribution(rows: list[dict]) -> dict[str, dict[str, int]]:
    output = {}
    for field in ("split", "source", "factor", "family", "level", "anchor_kind"):
        output[field] = dict(sorted(Counter(str(row[field]) for row in rows).items()))
    return output


def read_packed_sources(root: Path, needed: set[str], errors: list[str]) -> dict[str, dict]:
    sources: dict[str, dict] = {}
    paths = sorted(root.glob("train-rank*/features-*.json")) + sorted(
        root.glob("validation-*/features-*.json")
    )
    if not paths:
        add_error(errors, f"packed metadata is missing under {root}")
        return sources
    for path in paths:
        try:
            rows = read_json(path).get("records", [])
        except (OSError, json.JSONDecodeError) as error:
            add_error(errors, f"invalid packed metadata {path}: {error}")
            continue
        for row in rows:
            record_id = str(row.get("record_id"))
            if record_id not in needed:
                continue
            if record_id in sources:
                add_error(errors, f"duplicate source record in packed metadata: {record_id}")
            sources[record_id] = row
    return sources


def add_error(errors: list[str], message: str) -> None:
    if len(errors) < 100:
        errors.append(message)


def main() -> int:
    parser = argparse.ArgumentParser(description="Verify the factor-intervention feature cache.")
    parser.add_argument("--run-root", type=Path, required=True)
    parser.add_argument("--packed-root", type=Path, required=True)
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()

    started = time.perf_counter()
    manifest_path = args.run_root / "manifest.jsonl"
    cache = args.run_root / "full_external"
    output = args.output or args.run_root / "verification.json"
    errors: list[str] = []

    manifest_rows = read_jsonl(manifest_path)
    manifest_sha256 = hashlib.sha256(manifest_path.read_bytes()).hexdigest()
    manifest_by_id = {str(row["record_id"]): row for row in manifest_rows}
    if len(manifest_by_id) != len(manifest_rows):
        add_error(errors, "manifest contains duplicate record IDs")
    if len(manifest_rows) != EXPECTED_ROWS:
        add_error(errors, f"manifest row count {len(manifest_rows)} != {EXPECTED_ROWS}")
    if sum(row["split"] == "train" for row in manifest_rows) != EXPECTED_TRAIN:
        add_error(errors, "manifest train count mismatch")
    if sum(row["split"] == "validation" for row in manifest_rows) != EXPECTED_VALIDATION:
        add_error(errors, "manifest validation count mismatch")
    train_anchors = {row["source_record_id"] for row in manifest_rows if row["split"] == "train"}
    if len(train_anchors) != EXPECTED_ANCHORS:
        add_error(errors, f"unique train anchors {len(train_anchors)} != {EXPECTED_ANCHORS}")
    if {row.get("transform_version") for row in manifest_rows} != {EXPECTED_VERSION}:
        add_error(errors, "manifest transform version mismatch")

    train_rows = [row for row in manifest_rows if row["split"] == "train"]
    validation_rows = [row for row in manifest_rows if row["split"] == "validation"]
    train_source_ids = {row["source_record_id"] for row in train_rows}
    validation_source_ids = {row["source_record_id"] for row in validation_rows}
    if train_source_ids & validation_source_ids:
        add_error(errors, "train and validation source records overlap")
    train_style_ids = {row["style_id"] for row in train_rows}
    validation_style_ids = {row["style_id"] for row in validation_rows}
    if train_style_ids & validation_style_ids:
        add_error(errors, "train and validation style identities overlap")

    for row in train_rows:
        repeat_of = row.get("repeat_of")
        if repeat_of is None:
            continue
        base = manifest_by_id.get(str(repeat_of))
        if base is None:
            add_error(errors, f"repeat base is missing: {repeat_of}")
            continue
        for field in ("source_record_id", "style_id", "source", "factor", "family", "sign"):
            if row.get(field) != base.get(field):
                add_error(errors, f"repeat pair differs in {field}: {row['record_id']}")
                break
        if row.get("level") == base.get("level"):
            add_error(errors, f"repeat pair has identical intensity: {row['record_id']}")

    source_ids = {row["source_record_id"] for row in manifest_rows}
    packed_sources = read_packed_sources(args.packed_root, source_ids, errors)
    missing_sources = source_ids - set(packed_sources)
    if missing_sources:
        add_error(errors, f"source IDs absent from packed metadata: {len(missing_sources)}")
    for row in manifest_rows:
        source = packed_sources.get(row["source_record_id"])
        if source is None:
            continue
        for field in ("style_id", "source", "split", "shard"):
            if row.get(field) != source.get(field):
                add_error(errors, f"{row['record_id']}: source {field} alignment mismatch")
                break

    summaries = []
    for worker in range(4):
        path = cache / f"intervention-worker-{worker}.json"
        try:
            summary = read_json(path)
        except (FileNotFoundError, OSError, json.JSONDecodeError) as error:
            add_error(errors, f"invalid worker summary {worker}: {error}")
            continue
        summaries.append(summary)
        if summary.get("status") != "complete" or summary.get("mode") != "full":
            add_error(errors, f"worker {worker} is not complete/full")
        if summary.get("manifest_sha256") != manifest_sha256:
            add_error(errors, f"worker {worker} manifest hash mismatch")
    if sum(int(row.get("records", 0)) for row in summaries) != EXPECTED_ROWS:
        add_error(errors, "worker summary row total mismatch")

    json_parts = sorted(cache.glob("intervention-w*-p*.json"))
    tensor_parts = sorted(cache.glob("intervention-w*-p*.safetensors"))
    json_stems = {path.stem for path in json_parts}
    tensor_stems = {path.name.removesuffix(".safetensors") for path in tensor_parts}
    if json_stems != tensor_stems:
        add_error(errors, "JSON/safetensors part pairing mismatch")
    temporary_files = sorted(cache.glob(".*.tmp"))
    if temporary_files:
        add_error(errors, f"temporary part files remain: {temporary_files[0].name}")

    cached_ids: set[str] = set()
    cached_rows: list[dict] = []
    part_indices: dict[int, list[int]] = {worker: [] for worker in range(4)}
    finite_tensors = 0
    tensor_bytes = 0
    for metadata_path in json_parts:
        try:
            metadata = read_json(metadata_path)
        except (OSError, json.JSONDecodeError) as error:
            add_error(errors, f"invalid part metadata {metadata_path.name}: {error}")
            continue
        worker = int(metadata.get("worker_index", -1))
        part_index = int(metadata.get("part_index", -1))
        if worker not in part_indices:
            add_error(errors, f"invalid worker index in {metadata_path.name}")
            continue
        part_indices[worker].append(part_index)
        if metadata.get("manifest_sha256") != manifest_sha256:
            add_error(errors, f"manifest hash mismatch in {metadata_path.name}")
        if metadata.get("kind") != "factor_intervention_full_face":
            add_error(errors, f"feature kind mismatch in {metadata_path.name}")
        if metadata.get("backbone") != "siglip2_so400m" or metadata.get("layer_indices") != [6, 14, 26]:
            add_error(errors, f"backbone metadata mismatch in {metadata_path.name}")
        records = metadata.get("records", [])
        tensor_path = metadata_path.with_suffix(".safetensors")
        try:
            tensors = load_file(tensor_path, device="cpu")
        except Exception as error:
            add_error(errors, f"cannot load {tensor_path.name}: {error}")
            continue
        tensor_bytes += tensor_path.stat().st_size
        expected = {
            "full": ((len(records), 30, 1152), torch.bfloat16),
            "face": ((len(records), 30, 1152), torch.bfloat16),
            "face_mask": ((len(records),), torch.bool),
        }
        if set(tensors) != set(expected):
            add_error(errors, f"tensor keys mismatch in {tensor_path.name}")
        valid_contract = True
        for name, (shape, dtype) in expected.items():
            tensor = tensors.get(name)
            if tensor is None or tuple(tensor.shape) != shape or tensor.dtype != dtype:
                add_error(errors, f"{name} contract mismatch in {tensor_path.name}")
                valid_contract = False
                continue
            if not torch.isfinite(tensor).all().item():
                add_error(errors, f"non-finite {name} tensor in {tensor_path.name}")
                valid_contract = False
        if valid_contract:
            finite_tensors += len(expected)
        if "face_mask" in tensors and len(records) == tensors["face_mask"].shape[0]:
            declared = torch.tensor([bool(row.get("face_present")) for row in records])
            if not torch.equal(declared, tensors["face_mask"]):
                add_error(errors, f"face mask/metadata mismatch in {tensor_path.name}")
        for row in records:
            record_id = str(row.get("record_id"))
            if record_id in cached_ids:
                add_error(errors, f"duplicate cached record ID: {record_id}")
            cached_ids.add(record_id)
            cached_rows.append(row)
            manifest_row = manifest_by_id.get(record_id)
            if manifest_row is None:
                add_error(errors, f"cached ID absent from manifest: {record_id}")
                continue
            for field in COMPARE_FIELDS:
                if row.get(field) != manifest_row.get(field):
                    add_error(errors, f"{record_id}: {field} differs from manifest")
                    break
            if row.get("source_shard") != row.get("shard"):
                add_error(errors, f"{record_id}: source shard alignment mismatch")

    for worker, indices in part_indices.items():
        if sorted(indices) != list(range(len(indices))):
            add_error(errors, f"worker {worker} part indices are not contiguous")
    missing_ids = set(manifest_by_id) - cached_ids
    extra_ids = cached_ids - set(manifest_by_id)
    if missing_ids:
        add_error(errors, f"missing cached IDs: {len(missing_ids)}")
    if extra_ids:
        add_error(errors, f"extra cached IDs: {len(extra_ids)}")
    if len(cached_rows) != EXPECTED_ROWS:
        add_error(errors, f"cached row count {len(cached_rows)} != {EXPECTED_ROWS}")

    manifest_distribution = distribution(manifest_rows)
    cache_distribution = distribution(cached_rows)
    if cache_distribution != manifest_distribution:
        add_error(errors, "cached distribution differs from manifest")

    expected_pilot_ids = {
        row["record_id"] for row in manifest_rows if bool(row.get("anima_pilot"))
    }
    pilot_dir = args.run_root / "anima_pilot_images"
    actual_pilot_ids = {path.stem for path in pilot_dir.glob("*.webp")}
    if actual_pilot_ids != expected_pilot_ids:
        add_error(
            errors,
            f"Anima pilot image IDs differ: missing={len(expected_pilot_ids - actual_pilot_ids)}, extra={len(actual_pilot_ids - expected_pilot_ids)}",
        )

    report = {
        "status": "pass" if not errors else "fail",
        "transform_version": EXPECTED_VERSION,
        "manifest_sha256": manifest_sha256,
        "manifest_rows": len(manifest_rows),
        "cached_rows": len(cached_rows),
        "unique_cached_ids": len(cached_ids),
        "parts": len(json_parts),
        "finite_tensor_contracts": finite_tensors,
        "tensor_bytes": tensor_bytes,
        "worker_summaries": summaries,
        "unique_train_anchors": len(train_anchors),
        "packed_sources_found": len(packed_sources),
        "train_style_identities": len(train_style_ids),
        "validation_style_identities": len(validation_style_ids),
        "anima_pilot_images": len(actual_pilot_ids),
        "distribution": cache_distribution,
        "elapsed_seconds": time.perf_counter() - started,
        "errors": errors,
    }
    output.parent.mkdir(parents=True, exist_ok=True)
    temporary = output.with_suffix(output.suffix + ".tmp")
    temporary.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
    temporary.replace(output)
    print(json.dumps(report, indent=2))
    return 0 if not errors else 1


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