"""Federated data module wrapping a partition file and merged datasets.""" from __future__ import annotations from collections.abc import Sequence from pathlib import Path from torch.utils.data import DataLoader, Subset from capstone.data.config import DataConfig from capstone.data.freeze import require_freeze_match from capstone.data.merged import MergedMedMNIST from capstone.data.partitions import ( client_domain_summary, load_partition, validate_partition, ) def stratified_smoke_indices(indices: list[int], domain_of: Sequence[int], n: int) -> list[int]: """Pick up to ``n`` indices round-robin across domains, in DOMAIN_ORDER. ``domain_of[index]`` is the DOMAIN_ORDER position of ``index``. Input order is preserved within each domain; a domain that runs out is skipped and the remaining domains fill the shortfall. """ groups: dict[int, list[int]] = {} for index in indices: groups.setdefault(int(domain_of[index]), []).append(index) ordered = [groups[domain] for domain in sorted(groups)] chosen: list[int] = [] position = 0 while len(chosen) < n and any(position < len(group) for group in ordered): for group in ordered: if position < len(group): chosen.append(group[position]) if len(chosen) == n: break position += 1 return chosen class FederatedDataModule: """Client train/val loaders and a shared global test loader. Set ``require_freeze=True`` for every run that produces a reported number (WS5 acceptance / final metrics). That runs the data v1.0 freeze verifier at init and raises ``RuntimeError`` naming the mismatched item if the local environment does not match ``artifacts/data_v1_0.lock.json``. Default is ``False`` so day-to-day development is not obstructed. """ def __init__( self, partition_path: str | Path, config: DataConfig, *, require_freeze: bool = False, freeze_lock: str | Path | None = None, ) -> None: if require_freeze: require_freeze_match(None if freeze_lock is None else Path(freeze_lock)) self.config = config self.partition_path = Path(partition_path) self.partition = load_partition(self.partition_path) # Construct once and reuse — WS3 will call loaders thousands of times. self.train_ds = MergedMedMNIST(split="train", config=config) self.val_ds = MergedMedMNIST(split="val", config=config) self.test_ds = MergedMedMNIST(split="test", config=config) validate_partition(self.partition, self.train_ds, self.val_ds) @property def n_clients(self) -> int: return int(self.partition["n_clients"]) def _client_key(self, client_id: int | str) -> str: key = str(client_id) clients = self.partition["clients"] if key not in clients: valid = ", ".join(sorted(clients)) msg = f"unknown client id {client_id!r}; valid options: {valid}" raise KeyError(msg) return key def _maybe_smoke(self, indices: list[int], dataset: MergedMedMNIST) -> list[int]: if not self.config.smoke: return indices n = self.config.smoke_images_per_client if self.config.smoke_stratify_by_domain: return stratified_smoke_indices(indices, dataset.index_map[:, 0], n) return indices[:n] def train_loader(self, client_id: int | str) -> DataLoader: key = self._client_key(client_id) indices = self._maybe_smoke( [int(i) for i in self.partition["clients"][key]["train_indices"]], self.train_ds, ) subset = Subset(self.train_ds, indices) return DataLoader( subset, batch_size=self.config.batch_size, shuffle=True, num_workers=self.config.num_workers, ) def val_loader(self, client_id: int | str) -> DataLoader: key = self._client_key(client_id) indices = self._maybe_smoke( [int(i) for i in self.partition["clients"][key]["val_indices"]], self.val_ds, ) subset = Subset(self.val_ds, indices) return DataLoader( subset, batch_size=self.config.batch_size, shuffle=False, num_workers=self.config.num_workers, ) def test_loader(self) -> DataLoader: # Deliberate: server-side evaluation in WS3 is on the global test split # so per-domain metrics are comparable across strategies. return DataLoader( self.test_ds, batch_size=self.config.batch_size, shuffle=False, num_workers=self.config.num_workers, ) def client_summary(self, client_id: int | str) -> dict: return client_domain_summary(self.partition, self.train_ds, client_id)