from __future__ import annotations import argparse import json import time import warnings from collections.abc import Sequence from dataclasses import asdict, replace from itertools import product from pathlib import Path from typing import Any from omegaconf import OmegaConf import capstone.federated as _federated # noqa: F401 — register fedavg from capstone.data.config import DataConfig from capstone.experiments.collector import ( RESULTS_SCHEMA_VERSION, write_results_csv, ) from capstone.experiments.provenance import ( build_run_id, build_run_name, build_tags, get_data_version, get_git_commit, get_git_dirty, get_hardware, hash_config, utc_now, ) from capstone.federated.config import STRATEGY_REGISTRY, FederatedConfig PROJECT_ROOT = Path(__file__).resolve().parents[3] CONFIG_DIR = PROJECT_ROOT / "conf" / "federated" DATA_CONFIG_PATH = PROJECT_ROOT / "conf" / "data" / "default.yaml" PARTITION_DIR = PROJECT_ROOT / "artifacts" / "partitions" FEDERATED_CONFIG_FILES: dict[str, str] = { "fedavg": "default.yaml", "fedprox": "fedprox.yaml", "scaffold": "scaffold.yaml", "fedbn": "fedbn.yaml", } PLANNED_STRATEGIES = {"scaffold", "fedbn"} PLAN_PARTITION_ALIASES = ("specialised", "partial_mix", "mixed") DEFAULT_SWEEP_CONFIG = PROJECT_ROOT / "conf" / "ws5" / "week1.yaml" DEFAULT_OUTPUT = PROJECT_ROOT / "results" / "ws5_week1_sweep.csv" DEFAULT_CONFIGS = ( "baseline", "fedavg", "fedprox", ) def _discover_partition_aliases() -> dict[str, str]: """Map plan-level labels to stems present under artifacts/partitions/.""" aliases: dict[str, str] = {} if not PARTITION_DIR.is_dir(): return aliases for path in sorted(PARTITION_DIR.glob("p8c_*.json")): try: payload = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError, TypeError): continue mode = payload.get("mode") if mode in PLAN_PARTITION_ALIASES: aliases[str(mode)] = path.stem return aliases PARTITION_ALIASES = _discover_partition_aliases() def resolve_partition(partition_ref: str) -> dict[str, str]: """ Resolve a sweep partition alias or stem to provenance fields. Returns partition (alias), partition_mode, partition_file (stem), and partition_train_signature from the partition JSON on disk. """ ref = partition_ref.strip() stem_to_alias = {stem: alias for alias, stem in PARTITION_ALIASES.items()} if ref in PARTITION_ALIASES: alias = ref stem = PARTITION_ALIASES[ref] elif ref in stem_to_alias: stem = ref alias = stem_to_alias[ref] else: path = PARTITION_DIR / f"{ref}.json" raise ValueError(f"partition JSON not found at {path}") path = PARTITION_DIR / f"{stem}.json" if not path.is_file(): raise ValueError(f"partition JSON not found at {path}") try: payload = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise ValueError(f"partition JSON not found at {path}") from exc mode = payload.get("mode") train_signature = payload.get("train_signature") if not mode or not train_signature: raise ValueError(f"partition JSON not found at {path}") return { "partition": alias, "partition_mode": str(mode), "partition_file": stem, "partition_train_signature": str(train_signature), } def load_sweep_config( config_path: str | Path = DEFAULT_SWEEP_CONFIG, ) -> dict: """Load and resolve the hierarchical WS5 sweep configuration.""" config = OmegaConf.load(config_path) resolved = OmegaConf.to_container( config, resolve=True, ) if not isinstance(resolved, dict): raise ValueError("WS5 sweep configuration must be a mapping") # noqa: TRY004 return resolved def _resolve_output_path(output: str | Path) -> Path: """Resolve relative output paths against the repository root.""" path = Path(output) if not path.is_absolute(): path = PROJECT_ROOT / path return path def _federated_yaml_path(config_name: str) -> Path: """Resolve the YAML path for a federated sweep configuration name.""" mapped = FEDERATED_CONFIG_FILES[config_name] path = Path(mapped) if not path.is_absolute(): path = CONFIG_DIR / path if not path.is_file(): raise ValueError(f"federated config YAML for {config_name!r} not found at {path}") return path def _ensure_strategy_known(strategy_name: str) -> None: """Validate a strategy against the registry, with planned-strategy warnings.""" if strategy_name in STRATEGY_REGISTRY: return if strategy_name in PLANNED_STRATEGIES: warnings.warn( f"strategy {strategy_name!r} is not registered yet; planned for a later deliverable", UserWarning, stacklevel=2, ) return registered = sorted(STRATEGY_REGISTRY) raise ValueError(f"unknown strategy {strategy_name!r}; registered names: {registered}") def resolve_configuration( config_name: str, *, seed: int = 42, ) -> dict[str, Any]: """ Build the resolved configuration dict used for hashing. Federated names load ``conf/federated/*.yaml`` via ``FederatedConfig``. ``baseline`` resolves from ``conf/data/default.yaml`` and is non-federated. """ if not config_name or not config_name.strip(): raise ValueError("config_name must be a non-empty string") config_name = config_name.strip().lower() if config_name == "baseline": data_config = DataConfig.from_yaml(DATA_CONFIG_PATH) resolved = asdict(data_config) resolved["seed"] = seed resolved["strategy"] = "none" resolved["federated"] = False return resolved if config_name not in FEDERATED_CONFIG_FILES: raise ValueError( f"unknown configuration {config_name!r}; " f"expected 'baseline' or one of {sorted(FEDERATED_CONFIG_FILES)}" ) yaml_path = _federated_yaml_path(config_name) federated = FederatedConfig.from_yaml(yaml_path) federated = replace(federated, seed=seed) _ensure_strategy_known(federated.strategy.name) return asdict(federated) def run_configuration( config_name: str, *, seed: int = 42, partition: str = "mixed", contribution: str = "off", privacy: str = "none", epsilon: float | None = None, privacy_delta: float = 1e-5, privacy_max_grad_norm: float = 1.0, domain: str = "overall", tracking_project: str = "COMP5703-WS5", fixed_tags: list[str] | None = None, data_version: str = "unversioned", ) -> dict[str, object]: """ Prepare and record one WS5 experiment configuration. Week 1 records the complete configuration and provenance. Actual model training will be connected in the later experiment integration stage. """ if not config_name or not config_name.strip(): raise ValueError("config_name must be a non-empty string") config_name = config_name.strip().lower() start_time = time.perf_counter() wall_clock_start = utc_now() resolved_config = resolve_configuration(config_name, seed=seed) if epsilon is not None: resolved_config["privacy"] = { "enabled": True, "mechanism": privacy, "epsilon": float(epsilon), "delta": float(privacy_delta), "max_grad_norm": float(privacy_max_grad_norm), } config_hash = hash_config(resolved_config) partition_meta = resolve_partition(partition) partition_alias = partition_meta["partition"] if config_name == "baseline": strategy_label = "none" federated = False clients = None rounds = None clients_per_round = None local_epochs = None learning_rate = None batch_size = resolved_config.get("batch_size") else: strategy_label = str(resolved_config["strategy"]["name"]) federated = True clients = resolved_config["clients"] rounds = resolved_config["rounds"] clients_per_round = resolved_config["clients_per_round"] local_epochs = resolved_config["local_epochs"] learning_rate = resolved_config["learning_rate"] batch_size = resolved_config["batch_size"] run_name = build_run_name( strategy=config_name, partition=partition_alias, contribution=contribution, seed=seed, epsilon=epsilon, ) run_id = build_run_id( config=config_name, strategy=strategy_label, partition=partition_alias, contribution=contribution, privacy=privacy, epsilon=epsilon, seed=seed, ) tags = build_tags( fixed_tags=fixed_tags or [], strategy=config_name, partition=partition_alias, contribution=contribution, seed=seed, epsilon=epsilon, domain=domain, ) duration = time.perf_counter() - start_time return { "schema_version": RESULTS_SCHEMA_VERSION, "run_id": run_id, "run_name": run_name, "tracking_project": tracking_project, "config": config_name, "strategy": strategy_label, "federated": federated, "partition": partition_alias, "partition_mode": partition_meta["partition_mode"], "contribution": contribution, "privacy": privacy, "epsilon": epsilon, "delta": privacy_delta if epsilon is not None else None, "max_grad_norm": (float(privacy_max_grad_norm) if epsilon is not None else None), "noise_multiplier": None, "epsilon_spent": None, "clipping_before_max": None, "clipping_after_max": None, "clipped_fraction": None, "seed": seed, "rounds": rounds, "clients": clients, "clients_per_round": clients_per_round, "local_epochs": local_epochs, "learning_rate": learning_rate, "batch_size": batch_size, "domain": domain, "split": "test", "metric": "none", "value": "", "status": "configured", "data_version": get_data_version(data_version), "partition_file": partition_meta["partition_file"], "partition_train_signature": partition_meta["partition_train_signature"], "git_commit": get_git_commit(), "git_dirty": get_git_dirty(), "config_hash": config_hash, "hardware": get_hardware(), "wall_clock_start_utc": wall_clock_start, "wall_clock_duration_seconds": round(duration, 6), "tags": "|".join(tags), } def _normalise_list(value: object) -> list: """Convert a configuration value into a list.""" if isinstance(value, list): return value if isinstance(value, tuple): return list(value) return [value] def _resolve_dimension( override: Sequence[object] | None, yaml_value: object, default: Sequence[object], ) -> list: """Prefer an explicit override, else YAML, else the hardcoded default.""" if override is not None: return list(override) if yaml_value is not None: return _normalise_list(yaml_value) return list(default) def plan_sweep( strategies: Sequence[str] | None = None, *, partitions: Sequence[str] | None = None, contribution_flags: Sequence[str] | None = None, seeds: Sequence[int] | None = None, domains: Sequence[str] | None = None, config_path: str | Path = DEFAULT_SWEEP_CONFIG, ) -> list[dict[str, object]]: """ Resolve sweep dimensions into result rows without writing a CSV. Explicit keyword arguments override the YAML. ``None`` means take that dimension from the YAML (or the built-in default if absent there). Week 2 additionally sweeps the configured privacy epsilon values. """ sweep_config = load_sweep_config(config_path) tracking = sweep_config.get("tracking", {}) data = sweep_config.get("data", {}) privacy_config = sweep_config.get("privacy", {}) sweep = sweep_config.get("sweep", {}) tracking_project = str( tracking.get( "project", "COMP5703-WS5", ) ) fixed_tags = [str(tag) for tag in _normalise_list(tracking.get("fixed_tags", []))] data_version = str( data.get( "version", "unversioned", ) ) resolved_strategies = [ str(strategy).strip().lower() for strategy in _resolve_dimension( strategies, sweep.get("strategies"), DEFAULT_CONFIGS, ) ] resolved_partitions = [ str(partition) for partition in _resolve_dimension( partitions, sweep.get("partitions"), ["mixed"], ) ] resolved_contribution_flags = [ str(flag) for flag in _resolve_dimension( contribution_flags, sweep.get("contribution_flags"), ["off"], ) ] resolved_seeds = [ int(value) for value in _resolve_dimension( seeds, sweep.get("seeds"), [42], ) ] resolved_domains = [ str(domain) for domain in _resolve_dimension( domains, sweep.get("domains"), ["overall"], ) ] privacy_enabled = bool(privacy_config.get("enabled", False)) privacy_delta = float(privacy_config.get("delta", 1e-5)) privacy_max_grad_norm = float(privacy_config.get("max_grad_norm", 1.0)) configured_epsilons = privacy_config.get( "epsilons", [], ) if privacy_enabled: if not configured_epsilons: raise ValueError("privacy.enabled is true but privacy.epsilons is empty") resolved_epsilons: list[float | None] = [float(value) for value in configured_epsilons] else: resolved_epsilons = [None] rows: list[dict[str, object]] = [] for ( strategy, partition, contribution, run_seed, domain, epsilon, ) in product( resolved_strategies, resolved_partitions, resolved_contribution_flags, resolved_seeds, resolved_domains, resolved_epsilons, ): rows.append( run_configuration( strategy, seed=run_seed, partition=partition, contribution=contribution, privacy=("dp-sgd" if epsilon is not None else "none"), epsilon=epsilon, privacy_delta=privacy_delta, privacy_max_grad_norm=privacy_max_grad_norm, domain=domain, tracking_project=tracking_project, fixed_tags=fixed_tags, data_version=data_version, ) ) if not rows: raise ValueError("WS5 sweep configuration produced no runs") return rows def run_sweep( strategies: Sequence[str] | None = None, *, partitions: Sequence[str] | None = None, contribution_flags: Sequence[str] | None = None, seeds: Sequence[int] | None = None, domains: Sequence[str] | None = None, output: str | Path = DEFAULT_OUTPUT, config_path: str | Path = DEFAULT_SWEEP_CONFIG, dry_run: bool = False, ) -> Path | list[dict[str, object]]: """ Run the configured WS5 Week 1 sweep and write a tidy CSV. Explicit keyword arguments override the YAML. Pass ``dry_run=True`` to return the resolved rows without writing a file. """ rows = plan_sweep( strategies, partitions=partitions, contribution_flags=contribution_flags, seeds=seeds, domains=domains, config_path=config_path, ) if dry_run: return rows output_path = _resolve_output_path(output) return write_results_csv( rows, output_path, ) def build_arg_parser() -> argparse.ArgumentParser: """Build the shared CLI parser for the Week 1 sweep entry points.""" parser = argparse.ArgumentParser( description="Run the WS5 Week 1 experiment sweep.", ) parser.add_argument( "--config", type=Path, default=DEFAULT_SWEEP_CONFIG, help="Path to the sweep YAML (default: conf/ws5/week1.yaml).", ) parser.add_argument( "--output", type=Path, default=DEFAULT_OUTPUT, help="CSV output path (default: results/ws5_week1_sweep.csv).", ) parser.add_argument( "--strategy", action="append", dest="strategies", default=None, help="Strategy/config name (repeatable). Overrides YAML when set.", ) parser.add_argument( "--partition", action="append", dest="partitions", default=None, help="Partition alias or stem (repeatable). Overrides YAML when set.", ) parser.add_argument( "--seed", type=int, action="append", dest="seeds", default=None, help="Seed (repeatable). Overrides YAML when set.", ) parser.add_argument( "--dry-run", action="store_true", help="Print the resolved run list and count without writing a CSV.", ) return parser def main(argv: Sequence[str] | None = None) -> None: """Parse CLI arguments and run or dry-run the Week 1 sweep.""" parser = build_arg_parser() args = parser.parse_args(argv) result = run_sweep( strategies=args.strategies, partitions=args.partitions, seeds=args.seeds, output=args.output, config_path=args.config, dry_run=args.dry_run, ) if args.dry_run: assert isinstance(result, list) for row in result: print( f"{row['run_name']} " f"config={row['config']} " f"partition={row['partition']} " f"seed={row['seed']} " f"domain={row['domain']}" ) print(f"{len(result)} runs") return print(f"WS5 sweep completed: {result}") if __name__ == "__main__": main()