File size: 23,152 Bytes
12c2325
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
#!/usr/bin/env python3
"""Generate the staged ImageNet-v2 launch matrix without submitting jobs."""

from __future__ import annotations

import argparse
import copy
import re
import sys
from collections import Counter
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any

import yaml

SCRIPT_PATH = Path(__file__).resolve()
JOURNAL_ROOT = SCRIPT_PATH.parents[1]
GMNET_ROOT = JOURNAL_ROOT.parent
DEPLOY_ROOT = GMNET_ROOT / "depoly"
PROTOCOL_PATH = JOURNAL_ROOT / "configs/imagenet_v2_protocol.yaml"
BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml")
EXPECTED_RUN_ROOT = GMNET_ROOT / "runs/imagenet_v2"
CODE_MANIFEST_RELATIVE_PATH = "configs/imagenet_v2_code_manifest.json"

RESOURCE_KEYS = (
    "gpu_type",
    "gpu_num",
    "gpu_memory",
    "cpu_num",
    "memory",
    "efa",
    "priority",
    "pytorchjob",
    "custom_node_labels",
    "volcano_queue",
)
PROJECT_KEYS = (
    "project_name",
    "project_support_alias",
    "team",
    "cost_team",
    "cost_feature",
    "cost_sub_feature",
    "docker_image",
    "mount",
)
GENERATED_HEADER = (
    "# Generated by journal_exp/scripts/generate_deploy.py; do not edit.\n"
)
VALID_STATUSES = {"ready", "held", "conditional"}
TASK_ID_PATTERN = re.compile(r"[a-z0-9_]+")


@dataclass(frozen=True)
class LaunchTask:
    task_id: str
    experiment: str
    model: str
    gate: str
    seed: int
    config_path: str
    deploy_group: str
    phase: str
    role: str
    depends_on: tuple[str, ...]
    external_prerequisites: tuple[str, ...]
    status: str
    submission_allowed: bool
    condition: str | None = None

    @property
    def deploy_path(self) -> str:
        return f"{self.deploy_group}/{self.task_id}.yaml"

    @property
    def job_name(self) -> str:
        return "gmnet-" + self.task_id.replace("_", "-")

    @property
    def output_dir(self) -> str:
        return str(EXPECTED_RUN_ROOT / self.task_id)


def load_protocol() -> dict[str, Any]:
    if not PROTOCOL_PATH.is_file():
        raise FileNotFoundError(f"protocol does not exist: {PROTOCOL_PATH}")
    with PROTOCOL_PATH.open("r", encoding="utf-8") as handle:
        protocol = yaml.safe_load(handle)
    if not isinstance(protocol, dict):
        raise ValueError("ImageNet-v2 protocol must be a mapping")
    return protocol


def build_launch_tasks(protocol: dict[str, Any] | None = None) -> list[LaunchTask]:
    protocol = load_protocol() if protocol is None else protocol
    raw_tasks = protocol.get("tasks")
    if not isinstance(raw_tasks, list):
        raise ValueError("protocol tasks must be a list")

    tasks: list[LaunchTask] = []
    for record in raw_tasks:
        if not isinstance(record, dict):
            raise ValueError("each protocol task must be a mapping")
        tasks.append(
            LaunchTask(
                task_id=str(record["task_id"]),
                experiment=str(record["experiment"]),
                model=str(record["model"]),
                gate=str(record["gate"]),
                seed=int(record["seed"]),
                config_path=str(record["config_path"]),
                deploy_group=str(record["deploy_group"]),
                phase=str(record["phase"]),
                role=str(record["role"]),
                depends_on=tuple(record.get("depends_on", [])),
                external_prerequisites=tuple(record.get("external_prerequisites", [])),
                status=str(record["status"]),
                submission_allowed=bool(record["submission_allowed"]),
                condition=record.get("condition"),
            )
        )
    validate_protocol(protocol, tasks)
    return tasks


def load_resolved_config(path: Path) -> dict[str, Any]:
    """Load a task config through the same inheritance code used by training."""

    if str(JOURNAL_ROOT) not in sys.path:
        sys.path.insert(0, str(JOURNAL_ROOT))
    from gmnet.config import load_config

    return load_config(path)


def _require_config_value(
    task: LaunchTask,
    config: dict[str, Any],
    dotted_key: str,
    expected: object,
) -> None:
    value: object = config
    for part in dotted_key.split("."):
        if not isinstance(value, dict) or part not in value:
            raise ValueError(
                f"resolved config for {task.task_id} is missing {dotted_key}"
            )
        value = value[part]
    if value != expected:
        raise ValueError(
            f"resolved config mismatch for {task.task_id}: "
            f"{dotted_key}={value!r}, expected {expected!r}"
        )


def validate_resolved_config(task: LaunchTask, config: dict[str, Any]) -> None:
    """Ensure protocol labels describe the resolved training semantics."""

    expected_gate = (
        "smooth_clipped_self"
        if task.gate == "smooth_clipped_self_fixed_c6"
        else task.gate
    )
    is_release_audit = task.role == "conditional_recipe_audit"
    expected_recipe = (
        "release-readme-legacy-audit-only"
        if is_release_audit
        else "paper-supplementary-table8-v1"
    )
    expected_epochs = 310 if is_release_audit else 300
    expected_drop_path = 0.0 if is_release_audit or task.model in {"s1", "s2"} else 0.02

    invariants = {
        "recipe_id": expected_recipe,
        "model.variant": task.model,
        "model.gate_type": expected_gate,
        "model.num_classes": 1000,
        "model.drop_path_rate": expected_drop_path,
        "data.dataset": "imagenet",
        "data.num_classes": 1000,
        "data.expected_train_samples": 1_281_167,
        "data.expected_val_samples": 50_000,
        "data.expected_manifest_sha256": str(
            load_protocol()["canonical_data_manifest"]["manifest_sha256"]
        ),
        "train.epochs": expected_epochs,
        "train.eval_interval": expected_epochs,
        "train.official_validation_policy": "final_epoch_only",
        "train.save_best_checkpoint": False,
        "train.fail_on_nonfinite": True,
        "train.strict_resume": True,
    }
    for dotted_key, expected in invariants.items():
        _require_config_value(task, config, dotted_key, expected)

    patterns = config.get("optimizer", {}).get("no_weight_decay_patterns", [])
    if not isinstance(patterns, list) or "raw_clip" not in patterns:
        raise ValueError(
            f"resolved config for {task.task_id} must exclude raw_clip from weight decay"
        )

    is_smooth = task.gate in {
        "smooth_clipped_self",
        "smooth_clipped_self_fixed_c6",
    }
    if is_smooth:
        _require_config_value(task, config, "model.smooth_clip_per_channel", False)
        _require_config_value(task, config, "model.smooth_clip_init", 6.0)
        _require_config_value(task, config, "model.smooth_clip_beta", 10.0)
        _require_config_value(
            task,
            config,
            "model.smooth_clip_trainable",
            task.gate == "smooth_clipped_self",
        )

    if task.task_id == "imv2_e0_s3_release_fullbn_seed0":
        expected_bn = (True, True)
    else:
        expected_bn = (False, False)
    _require_config_value(task, config, "model.f12_bn", expected_bn[0])
    _require_config_value(task, config, "model.second_dw_bn", expected_bn[1])
    _require_config_value(task, config, "model.projection_bn", True)


def resolved_config_summary(task: LaunchTask) -> dict[str, object]:
    config = load_resolved_config(JOURNAL_ROOT / task.config_path)
    model = config["model"]
    return {
        "recipe_id": config["recipe_id"],
        "variant": model["variant"],
        "gate_type": model["gate_type"],
        "smooth_clip_trainable": model.get("smooth_clip_trainable"),
        "epochs": config["train"]["epochs"],
        "final_epoch_only": (
            config["train"]["official_validation_policy"] == "final_epoch_only"
        ),
        "raw_clip_zero_weight_decay": (
            "raw_clip" in config["optimizer"].get("no_weight_decay_patterns", [])
        ),
    }


def validate_protocol(protocol: dict[str, Any], tasks: list[LaunchTask]) -> None:
    if protocol.get("schema_version") != 2:
        raise ValueError("ImageNet-v2 protocol schema_version must be 2")
    if Path(str(protocol.get("run_root"))) != EXPECTED_RUN_ROOT:
        raise ValueError(f"protocol run_root must be {EXPECTED_RUN_ROOT}")
    if len(tasks) != 21:
        raise ValueError(
            f"ImageNet-v2 protocol must contain 21 tasks, got {len(tasks)}"
        )

    task_ids = [task.task_id for task in tasks]
    if len(task_ids) != len(set(task_ids)):
        raise ValueError("duplicate task IDs in ImageNet-v2 protocol")
    task_id_set = set(task_ids)
    if any(TASK_ID_PATTERN.fullmatch(task_id) is None for task_id in task_ids):
        raise ValueError(
            "ImageNet-v2 task IDs may contain only lowercase letters, digits, and underscores"
        )
    job_names = [task.job_name for task in tasks]
    if len(job_names) != len(set(job_names)):
        raise ValueError("duplicate launchjob names in ImageNet-v2 protocol")

    phases = protocol.get("phases", {})
    external = protocol.get("external_prerequisites", {})
    if not isinstance(external, dict):
        raise ValueError("protocol external_prerequisites must be a mapping")
    external_ids = set(external)
    decision_rule_ids = {
        str(rule.get("id"))
        for rule in protocol.get("decision_rules", [])
        if isinstance(rule, dict)
    }
    for prerequisite_id, prerequisite in external.items():
        if not isinstance(prerequisite, dict):
            raise ValueError(
                f"external prerequisite {prerequisite_id} must be a mapping"
            )
        if prerequisite.get("decision_rule") not in decision_rule_ids:
            raise ValueError(
                f"external prerequisite {prerequisite_id} references an unknown decision rule"
            )
        if prerequisite.get("required_state") != "passed":
            raise ValueError(
                f"external prerequisite {prerequisite_id} must require passed state"
            )
        state = prerequisite.get("state")
        if state not in {"pending", "passed", "failed"}:
            raise ValueError(
                f"external prerequisite {prerequisite_id} has invalid state {state!r}"
            )
        if state == "passed":
            evidence = prerequisite.get("evidence")
            if not isinstance(evidence, str) or not Path(evidence).is_file():
                raise ValueError(
                    f"passed external prerequisite {prerequisite_id} lacks evidence"
                )
    for task in tasks:
        if not task.task_id.startswith("imv2_"):
            raise ValueError(f"task ID lacks imv2 namespace: {task.task_id}")
        if task.status not in VALID_STATUSES:
            raise ValueError(f"invalid status for {task.task_id}: {task.status}")
        if task.submission_allowed and task.status != "ready":
            raise ValueError(f"only ready tasks may be submitted: {task.task_id}")
        if task.phase not in phases:
            raise ValueError(f"undefined phase for {task.task_id}: {task.phase}")
        missing_dependencies = set(task.depends_on) - task_id_set
        if missing_dependencies:
            raise ValueError(
                f"unknown dependencies for {task.task_id}: "
                + ", ".join(sorted(missing_dependencies))
            )
        if task.task_id in task.depends_on:
            raise ValueError(f"task depends on itself: {task.task_id}")
        missing_external = set(task.external_prerequisites) - external_ids
        if missing_external:
            raise ValueError(
                f"unknown external prerequisites for {task.task_id}: "
                + ", ".join(sorted(missing_external))
            )
        if task.submission_allowed != (task.status == "ready"):
            raise ValueError(f"ready/submission state mismatch for {task.task_id}")
        if task.status == "conditional" and not task.condition:
            raise ValueError(f"conditional task lacks condition: {task.task_id}")
        config = JOURNAL_ROOT / task.config_path
        if not config.is_file():
            raise FileNotFoundError(f"missing config for {task.task_id}: {config}")
        validate_resolved_config(task, load_resolved_config(config))

    allowed = [task.task_id for task in tasks if task.submission_allowed]
    expected_allowed = ["imv2_e0_s3_relu6_seed0"]
    if allowed != expected_allowed:
        raise ValueError(
            "initial submission policy must allow only " + expected_allowed[0]
        )

    confirmatory = [task for task in tasks if task.role.startswith("confirmatory_")]
    gate_counts = Counter(task.gate for task in confirmatory)
    expected_gate_counts = {
        "relu6_self": 3,
        "relu_self": 3,
        "smooth_clipped_self": 3,
        "relu6_only": 3,
        "no_gate": 3,
    }
    if dict(gate_counts) != expected_gate_counts:
        raise ValueError(f"confirmatory gate matrix mismatch: {dict(gate_counts)}")
    smooth_seed0 = next(
        task for task in tasks if task.task_id == "imv2_e3_s3_smooth_corrected_seed0"
    )
    if smooth_seed0.external_prerequisites != ("smooth_local_pregate",):
        raise ValueError(
            "learned-smooth seed0 must require external smooth_local_pregate"
        )

    primary = protocol.get("primary_analysis", {})
    if not isinstance(primary, dict):
        raise ValueError("primary_analysis must be a mapping")
    expected_control = "fixed_entry_gate_then_parallel_holm"
    if (
        primary.get("alpha") != 0.05
        or primary.get("familywise_error_control") != expected_control
    ):
        raise ValueError(
            "primary analysis must use a fixed entry gate followed by Holm "
            "control at alpha 0.05"
        )
    entry = primary.get("fixed_entry_gate", {})
    if (
        entry.get("id") != "h1_no_gate_material_loss"
        or entry.get("candidate_gate") != "no_gate"
    ):
        raise ValueError("primary entry gate does not match the frozen protocol")
    downstream = primary.get("downstream_holm_family", {})
    expected_hypotheses = [
        ("h2_relu6_only_noninferiority", "relu6_only"),
        ("h3_relu_equivalence", "relu_self"),
        ("h4_smooth_noninferiority", "smooth_clipped_self"),
    ]
    observed_hypotheses = [
        (hypothesis.get("id"), hypothesis.get("candidate_gate"))
        for hypothesis in downstream.get("hypotheses", [])
    ]
    if observed_hypotheses != expected_hypotheses:
        raise ValueError(
            "primary downstream Holm hypotheses do not match the frozen protocol"
        )


def load_base_invariants() -> dict[str, object]:
    if not BASE_TEMPLATE.is_file():
        raise FileNotFoundError(f"launch template does not exist: {BASE_TEMPLATE}")
    with BASE_TEMPLATE.open("r", encoding="utf-8") as handle:
        source = yaml.safe_load(handle)
    required = (*RESOURCE_KEYS, *PROJECT_KEYS)
    missing = [key for key in required if key not in source]
    if missing:
        raise ValueError(f"launch template is missing fields: {', '.join(missing)}")
    return {key: copy.deepcopy(source[key]) for key in required}


def unlock_guard(task: LaunchTask) -> str | None:
    if task.submission_allowed:
        return None
    variable = "GMNET_PROTOCOL_UNLOCK_TASK"
    return (
        f'if [ "${{{variable}:-}}" != "{task.task_id}" ]; then '
        f'echo "Protocol guard denied {task.task_id}; set {variable}={task.task_id} '
        'only after documented prerequisite review" >&2; exit 64; fi'
    )


def _guarded_command(task: LaunchTask, command: str) -> str:
    guard = unlock_guard(task)
    return command if guard is None else f"{guard}; {command}"


def build_command(task: LaunchTask, data_root: str) -> str:
    assignments = (
        f"RUN_NAME={task.task_id}",
        f"CONFIG_PATH={task.config_path}",
        f"DATA_ROOT={data_root}",
        f"OUTPUT_DIR={task.output_dir}",
        f"SEED={task.seed}",
        "NPROC_PER_NODE=8",
        f"CODE_MANIFEST_PATH={CODE_MANIFEST_RELATIVE_PATH}",
    )
    command = (
        f"cd {JOURNAL_ROOT} && " + " ".join(assignments) + " bash scripts/init_run.sh"
    )
    return _guarded_command(task, command)


def build_launch_document(
    task: LaunchTask,
    invariants: dict[str, object],
    data_root: str,
) -> dict[str, object]:
    document: dict[str, object] = {}
    for key in RESOURCE_KEYS:
        document[key] = copy.deepcopy(invariants[key])
    pre_run_event = (
        f"cd {JOURNAL_ROOT} && chmod +x ./scripts/*.sh && "
        "INSTALL_DEV=0 bash ./scripts/setup_env.sh && "
        "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full"
    )
    document["script"] = {
        "pre_run_event": _guarded_command(task, pre_run_event),
        "command": build_command(task, data_root),
        "jobs": [{"name": task.job_name}],
    }
    for key in PROJECT_KEYS:
        document[key] = copy.deepcopy(invariants[key])
    return document


def dump_yaml(document: object) -> str:
    body = yaml.safe_dump(
        document,
        sort_keys=False,
        default_flow_style=False,
        width=1_000_000,
    )
    return GENERATED_HEADER + body


def _counts(tasks: list[LaunchTask], field: str) -> dict[str, int]:
    counts = Counter(str(getattr(task, field)) for task in tasks)
    return dict(sorted(counts.items()))


def build_task_matrix(
    protocol: dict[str, Any], tasks: list[LaunchTask]
) -> dict[str, object]:
    records = []
    for task in tasks:
        record = asdict(task)
        record["depends_on"] = list(task.depends_on)
        record["external_prerequisites"] = list(task.external_prerequisites)
        record.update(
            {
                "deploy_path": task.deploy_path,
                "job_name": task.job_name,
                "eta_class": ">12h",
                "runner": "imagenet_classification",
                "data_root": str(protocol["data_root"]),
                "output_dir": task.output_dir,
                "resolved_config": resolved_config_summary(task),
            }
        )
        if record["condition"] is None:
            del record["condition"]
        records.append(record)

    return {
        "schema_version": 2,
        "protocol_id": protocol["protocol_id"],
        "protocol_source": str(PROTOCOL_PATH),
        "generated_by": str(SCRIPT_PATH),
        "source_template": str(BASE_TEMPLATE),
        "policy": copy.deepcopy(protocol["policy"]),
        "technical_validity": copy.deepcopy(protocol["technical_validity"]),
        "external_prerequisites": copy.deepcopy(protocol["external_prerequisites"]),
        "data_root": str(protocol["data_root"]),
        "data_staging": copy.deepcopy(protocol["data_staging"]),
        "canonical_data_uri": str(protocol["canonical_data_uri"]),
        "canonical_data_manifest": copy.deepcopy(protocol["canonical_data_manifest"]),
        "run_root": str(EXPECTED_RUN_ROOT),
        "code_manifest": str(JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH),
        "summary": {
            "launch_yaml_count": len(tasks),
            "submission_allowed_count": sum(task.submission_allowed for task in tasks),
            "by_status": _counts(tasks, "status"),
            "by_phase": _counts(tasks, "phase"),
            "by_role": _counts(tasks, "role"),
            "by_experiment": _counts(tasks, "experiment"),
        },
        "decision_rules": copy.deepcopy(protocol.get("decision_rules", [])),
        "primary_analysis": copy.deepcopy(protocol["primary_analysis"]),
        "secondary_analysis": copy.deepcopy(protocol["secondary_analysis"]),
        "tasks": records,
    }


def expected_files() -> dict[Path, str]:
    protocol = load_protocol()
    tasks = build_launch_tasks(protocol)
    invariants = load_base_invariants()
    data_root = str(protocol["data_root"])

    files: dict[Path, str] = {}
    for task in tasks:
        document = build_launch_document(task, invariants, data_root)
        for key in (*RESOURCE_KEYS, *PROJECT_KEYS):
            if document[key] != invariants[key]:
                raise AssertionError(f"{task.task_id} changed invariant field {key}")
        files[DEPLOY_ROOT / task.deploy_path] = dump_yaml(document)
    files[DEPLOY_ROOT / "task_matrix.yaml"] = dump_yaml(
        build_task_matrix(protocol, tasks)
    )
    return files


def find_stale_generated_files(expected_paths: set[Path]) -> list[Path]:
    stale = []
    if not DEPLOY_ROOT.is_dir():
        return stale
    for path in DEPLOY_ROOT.rglob("*.yaml"):
        if path in expected_paths or not path.is_file():
            continue
        try:
            generated = path.read_text(encoding="utf-8").startswith(GENERATED_HEADER)
        except UnicodeDecodeError:
            generated = False
        if generated:
            stale.append(path)
    return sorted(stale)


def write_files(files: dict[Path, str]) -> list[Path]:
    for path, content in files.items():
        path.parent.mkdir(parents=True, exist_ok=True)
        if path.exists() and path.read_text(encoding="utf-8") == content:
            continue
        path.write_text(content, encoding="utf-8")

    stale = find_stale_generated_files(set(files))
    for path in stale:
        path.unlink()
    for directory in sorted(DEPLOY_ROOT.rglob("*"), reverse=True):
        if directory.is_dir() and not any(directory.iterdir()):
            directory.rmdir()
    return stale


def check_files(files: dict[Path, str]) -> list[str]:
    errors = []
    for path, expected in files.items():
        if not path.is_file():
            errors.append(f"missing: {path}")
            continue
        actual = path.read_text(encoding="utf-8")
        if actual != expected:
            errors.append(f"stale: {path}")
            continue
        parsed = yaml.safe_load(actual)
        if path.name != "task_matrix.yaml":
            jobs = parsed.get("script", {}).get("jobs", [])
            if len(jobs) != 1:
                errors.append(f"expected one job: {path}")
    errors.extend(
        f"stale generated file: {path}"
        for path in find_stale_generated_files(set(files))
    )
    return errors


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--check",
        action="store_true",
        help="verify generated files without modifying them",
    )
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    files = expected_files()
    launch_count = len(files) - 1
    if args.check:
        errors = check_files(files)
        if errors:
            print("\n".join(errors), file=sys.stderr)
            return 1
        print(
            f"Validated {launch_count} ImageNet-v2 launch YAML files "
            "and task_matrix.yaml"
        )
        return 0
    removed = write_files(files)
    print(
        f"Generated {launch_count} ImageNet-v2 launch YAML files under "
        f"{DEPLOY_ROOT}; removed {len(removed)} stale generated YAML files"
    )
    return 0


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