File size: 4,935 Bytes
6fbb45f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Generate the dataset on this machine.



    python scripts/run_local_sweep.py --smoke        # ~1-minute end-to-end check in a temporary folder

    python scripts/run_local_sweep.py                # full design with the defaults into data/

    python scripts/run_local_sweep.py --help         # every design level and model knob is a flag



Every CPU core runs independent Monte Carlo episodes; shards are streamed to Parquet as they

complete, and re-running the same command resumes an interrupted sweep. When the sweep finishes

the script writes data/manifest.json and prints the router benchmark, the design coverage and the

size of every table.

"""
import os

for _var in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
    os.environ.setdefault(_var, "1")  # one BLAS thread per worker process; parallelism comes from the pool

import argparse
import shutil
import sys
import tempfile
from dataclasses import fields, replace
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from src.config import DATASET_VERSION, SimConfig  # noqa: E402
from src.simulation_loop import run_sweep  # noqa: E402
from src.telemetry_logger import read_table, write_manifest  # noqa: E402


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--out", type=Path, default=ROOT / "data", help="output folder (default: data/)")
    parser.add_argument("--workers", type=int, default=os.cpu_count(), help="worker processes (default: all cores)")
    parser.add_argument("--smoke", action="store_true", help="tiny sweep over every family, profile and router "
                                                             "in a temporary folder, deleted afterwards")
    group = parser.add_argument_group("design and model configuration")
    for f in fields(SimConfig):
        if isinstance(f.default, tuple):
            item = type(f.default[0])
            kind = lambda s, item=item: tuple(item(x) for x in s.split(","))  # noqa: E731
            shown = ",".join(str(x) for x in f.default)
        else:
            kind, shown = type(f.default), f.default
        group.add_argument(f"--{f.name}", type=kind, default=None, metavar="",
                           help=f"{f.metadata['help']} (default: {shown})")
    return parser.parse_args()


def summarize(data_dir: Path, cfg: SimConfig) -> None:
    manifest = write_manifest(data_dir, cfg, DATASET_VERSION)
    summary = read_table(data_dir, "router_summary").to_pandas()
    bench = summary.groupby("router").agg(
        loss_ratio=("loss_ratio", "mean"), mean_delay=("mean_delay", "mean"), p99_delay=("p99_delay", "mean"),
        link_utilisation=("link_utilisation", "mean"), route_changes=("route_changes", "mean"))
    print("\nRouter benchmark (means over episodes):")
    print(bench.round(3).to_string())
    print("\nDesign coverage (episodes per level):")
    for factor, counts in manifest["coverage"].items():
        print(f"  {factor:16s} " + "  ".join(f"{k}={v}" for k, v in counts.items()))
    design = manifest["design"]
    print(f"  cells {design['cells']}, episodes {design['episodes_present']}/{design['episodes_planned']}, "
          f"per cell {design['episodes_per_cell_min']}-{design['episodes_per_cell_max']}")
    print("\nTables:")
    total = 0
    for name, stats in manifest["tables"].items():
        total += stats["bytes"]
        print(f"  {name:18s} {stats['files']:5d} files {stats['rows']:14,d} rows {stats['bytes'] / 1e9:8.2f} GB")
    print(f"  {'total':18s} {'':5s}       {'':14s}      {total / 1e9:8.2f} GB")


def main() -> None:
    args = parse_args()
    overrides = {f.name: getattr(args, f.name) for f in fields(SimConfig) if getattr(args, f.name) is not None}
    cfg = SimConfig(**overrides)
    data_dir = args.out
    if args.smoke:
        cfg = replace(cfg, replicates=1, sizes=(32,), load_levels=("heavy",), dynamics_levels=("severe",),
                      steps=200, shard_episodes=5)
        data_dir = Path(tempfile.mkdtemp(prefix="sprt-smoke-"))
        print(f"Smoke test in {data_dir}")
    data_dir.mkdir(parents=True, exist_ok=True)
    config_path = data_dir / "config.json"
    if config_path.exists() and SimConfig.load(config_path) != cfg:
        sys.exit(f"{config_path} was written by a different configuration; use another --out folder "
                 f"or delete it to start over.")
    cfg.save(config_path)
    try:
        run_sweep(cfg, data_dir, max(1, min(args.workers, cfg.episodes)))
        summarize(data_dir, cfg)
        if args.smoke:
            print("\nSmoke test passed.")
    finally:
        if args.smoke:
            shutil.rmtree(data_dir, ignore_errors=True)


if __name__ == "__main__":
    main()