File size: 7,141 Bytes
9ca90c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80187cb
 
 
 
 
9ca90c5
 
 
 
 
 
 
 
 
 
 
80187cb
 
9ca90c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80187cb
 
9ca90c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80187cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ca90c5
 
 
 
 
 
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
"""Run all frozen Fable donor-bank structural smokes sequentially.

This is an interactive cloud-notebook convenience wrapper, not a scheduler and
not a training entry point.  Each bank executes in a fresh subprocess so CUDA
state is released between candidates.  Every child persists its own append-only
pass/fail evidence; the wrapper additionally uploads one campaign summary.
"""
from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

from huggingface_hub import HfApi

from fable_router_common import read_json


DEFAULT_BANKS = (
    "kat-coder-v25-dev-q4km",
    "qwen36-35b-base-q4km",
    "ornith10-35b-q4km",
    "qwen35-35b-base-q4km",
)


def now() -> str:
    return datetime.now(timezone.utc).isoformat()


def run_bank(command: list[str]) -> tuple[int, list[str]]:
    lines: list[str] = []
    process = subprocess.Popen(
        command,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True,
        bufsize=1,
    )
    assert process.stdout is not None
    for raw in process.stdout:
        line = raw.rstrip("\n")
        lines.append(line)
        print(line, flush=True)
    return process.wait(), lines


def result_from_output(lines: list[str]) -> tuple[str | None, dict[str, Any] | None]:
    for line in reversed(lines):
        candidate = Path(line.strip())
        if candidate.name != "result.json" or not candidate.is_file():
            continue
        try:
            payload = json.loads(candidate.read_text(encoding="utf-8"))
        except (OSError, json.JSONDecodeError):
            return str(candidate), None
        return str(candidate), payload if isinstance(payload, dict) else None
    return None, None


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--owner-execute", action="store_true")
    parser.add_argument("--config", type=Path, required=True)
    parser.add_argument("--platform", choices=("colab", "kaggle", "other"), default="other")
    parser.add_argument("--work-dir", type=Path, required=True)
    parser.add_argument("--runner", type=Path, required=True)
    parser.add_argument("--source-revision", required=True)
    parser.add_argument("--banks", nargs="+", default=list(DEFAULT_BANKS))
    parser.add_argument("--continue-on-failure", action="store_true")
    parser.add_argument(
        "--curriculum-path",
        type=Path,
        help="Verified local sft-train.jsonl override for credential-free cloud execution",
    )
    args = parser.parse_args()
    if not args.owner_execute:
        raise SystemExit("refusing GPU/model execution without --owner-execute")

    config = read_json(args.config.resolve())
    if config.get("trainingAuthorized") is not False or config.get("nonRouting") is not True:
        raise SystemExit("campaign requires an explicitly non-routing, training-disabled config")
    configured = set(config["banks"]["artifacts"])
    if len(args.banks) != len(set(args.banks)) or not set(args.banks).issubset(configured):
        raise SystemExit("campaign banks must be unique configured bank IDs")
    token = os.environ.get("HF_TOKEN")
    if not token and not args.curriculum_path:
        raise SystemExit("either HF_TOKEN or --curriculum-path is required")

    stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
    output = args.work_dir.resolve() / f"fable-router-structural-campaign-{stamp}"
    output.mkdir(parents=True, exist_ok=False)
    summary: dict[str, Any] = {
        "schema": "AutonomaFableRouterStructuralCampaign.v1",
        "status": "running_nonrouting",
        "nonRouting": True,
        "trainingAuthorized": False,
        "startedAt": now(),
        "platform": args.platform,
        "sourceRevision": args.source_revision,
        "bankOrder": list(args.banks),
        "continueOnFailure": bool(args.continue_on_failure),
        "runs": [],
    }

    for index, bank in enumerate(args.banks, start=1):
        print(f"\n=== [{index}/{len(args.banks)}] {bank} ===", flush=True)
        started = now()
        command = [
            sys.executable,
            str(args.runner.resolve()),
            "--owner-execute",
            "--config", str(args.config.resolve()),
            "--bank", bank,
            "--platform", args.platform,
            "--work-dir", str(args.work_dir.resolve()),
        ]
        if args.curriculum_path:
            command.extend(["--curriculum-path", str(args.curriculum_path.resolve())])
        returncode, lines = run_bank(command)
        result_path, result = result_from_output(lines)
        row = {
            "bank": bank,
            "startedAt": started,
            "finishedAt": now(),
            "returnCode": returncode,
            "resultPath": result_path,
            "status": result.get("status") if result else "result_unreadable",
            "passed": bool(result and result.get("passed") is True and returncode == 0),
        }
        if result and isinstance(result.get("error"), dict):
            row["error"] = {
                "type": result["error"].get("type"),
                "message": result["error"].get("message"),
            }
        summary["runs"].append(row)
        (output / "result.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
        if returncode and not args.continue_on_failure:
            break

    all_passed = len(summary["runs"]) == len(args.banks) and all(row["passed"] for row in summary["runs"])
    summary["passed"] = all_passed
    summary["status"] = (
        "campaign_passed_nonrouting" if all_passed else "campaign_completed_with_failures_nonrouting"
    )
    summary["finishedAt"] = now()
    result_path = output / "result.json"
    result_path.write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
    repo = config["smoke"]["resultRepo"]
    remote = f"campaigns/{output.name}/result.json"
    if token:
        HfApi(token=token).upload_file(
            path_or_fileobj=str(result_path),
            path_in_repo=remote,
            repo_id=repo,
            repo_type="dataset",
            commit_message=f"Persist non-routing structural campaign {output.name}",
        )
        summary["evidenceUpload"] = {"repo": repo, "private": True, "path": remote}
        result_path.write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
        HfApi(token=token).upload_file(
            path_or_fileobj=str(result_path),
            path_in_repo=remote,
            repo_id=repo,
            repo_type="dataset",
            commit_message=f"Finalize non-routing structural campaign {output.name}",
        )
    else:
        summary["evidenceUpload"] = {
            "status": "local_only_pending_authenticated_download",
            "privateRemoteCredentialUsed": False,
        }
        result_path.write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
    print(result_path, flush=True)
    return 0 if all_passed else 1


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