diff --git a/configs/core/client/client_decavg_sgd.yml b/configs/core/client/client_decavg_sgd.yml new file mode 100644 index 0000000..cce046d --- /dev/null +++ b/configs/core/client/client_decavg_sgd.yml @@ -0,0 +1,13 @@ +client: + arguments: + include_myself: false + use_weighted_avg: false + local_model: + target: OVERRIDE_CLIENT_LOCAL_MODEL + target: DecAvgClient + training_engine: + target: TrainingEngine + arguments: + lr: 0.001 + sgd_momentum: 0.9 + optimizer: SGD diff --git a/dengine/config/builtins.py b/dengine/config/builtins.py index e00e4f0..f578460 100644 --- a/dengine/config/builtins.py +++ b/dengine/config/builtins.py @@ -56,6 +56,7 @@ class CLIENT: CLIENT_DECAVG_ADAM = get_config('client_decavg_adam.yml', 'configs/core/client/client_decavg_adam.yml') CLIENT_DECAVG_SELF_ADAM = get_config('client_decavg_self_adam.yml', 'configs/core/client/client_decavg_self_adam.yml') CLIENT_DECAVG_SELF_WEIGHTED_ADAM = get_config('client_decavg_self_weighted_adam.yml', 'configs/core/client/client_decavg_self_weighted_adam.yml') + CLIENT_DECAVG_SGD = get_config('client_decavg_sgd.yml', 'configs/core/client/client_decavg_sgd.yml') CORE = get_config('core.yml', 'configs/core/core.yml') CORE_CENTRALIZED = get_config('core_centralized.yml', 'configs/core/core_centralized.yml') diff --git a/examples/LabelFlip/Plots.png b/examples/LabelFlip/Plots.png new file mode 100644 index 0000000..78d5078 Binary files /dev/null and b/examples/LabelFlip/Plots.png differ diff --git a/examples/LabelFlip/README.md b/examples/LabelFlip/README.md new file mode 100644 index 0000000..c13188f --- /dev/null +++ b/examples/LabelFlip/README.md @@ -0,0 +1,78 @@ +# Label flip (data corruption) + +This example studies how **corrupted training data** spreads through decentralized learning, and whether it matters *where* in the network the corruption sits. + +Some MNIST images labeled `9` are swapped for images of a `4`, while the label stays `9`. Each corrupted sample is therefore a 4 that claims to be a 9 (a 4→9 label flip). We then measure how well the network still recognizes 4s and 9s on the clean test set. + +![Per-class F1 and recall for digits 4 and 9, balanced vs unbalanced corruption](Plots.png) + +## Setup + +| | | +|---|---| +| Dataset | MNIST, 20% of each node's samples held out for validation. Test set is clean | +| Corruption | 95% of all training/validation `9`s replaced by unused `4` images (`alpha: 1.0`) | +| Topology | Barabási–Albert, 50 nodes, `m=1`, seeded with `--seed` | +| Aggregation | DecAvg, excluding the node's own model | +| Model | `CNNMnist` | +| Local training | SGD, 5 epochs, batch size 32, early stopping with patience 5 | +| Comm. rounds | 1000 | + +The two experiments differ only in how the `9`s are distributed before corruption: + +| Experiment | Partitioning | Where the corruption ends up | +|---|---|---| +| `Balanced Corruption,DecAvg,CNNMnist` | `random_iid_balanced`: every node gets the same share of each class | Spread across many nodes, starting from the best-connected ones | +| `Unbalanced Corruption,DecAvg,CNNMnist` | `random_iid_balanced_with_class_majority_hub`: the hub (highest-degree node) holds 95% of all `9`s | Almost entirely on the hub | + +In both cases corruption is assigned by `global_corruption_with_centrality_priority`. It works out how many `9`s must be corrupted network-wide (`p` × all `9`s), then corrupts them node by node in decreasing order of degree until that number is reached. + +In the plot, spreading the corruption out (**Balanced**) does far more damage to digit 4: recall stays around 50–65%, because many nodes learn that 4s are 9s. When the same corruption sits on the hub (**Unbalanced**), the rest of the network still recognizes 4s, with recall near 97%. + +## How the corruption works + +All the logic is in [`corruption.py`](corruption.py): + +- **`CorruptedSupervisedDataset`** wraps a `SupervisedDataset`. `corrupt_in_place_by_index` blends each chosen sample with a random, never-before-used sample of `collateral_label`, in pixel space: + `x' = (1 - alpha) * x + alpha * x_partner`. + With `alpha = 1` the image is fully replaced, which makes this a label flip. Smaller values give a partial blend. The `is_corrupted` mask records which samples were changed. +- **`load_corrupted_mnist`** is a registered dataset that loads MNIST and wraps it in a `CorruptedSupervisedDataset`. +- **`global_corruption_with_centrality_priority`** is a registered partitioning step. It runs *after* the normal partitioning and corrupts samples in place. It then prints a per-node summary of class shares and corrupted counts. + +## Parameters + +| Key | Default here | Meaning | +|---|---|---| +| `dataset.train.arguments.alpha` | `1.0` | Blend weight of the collateral image (1 = full replacement) | +| `dataset.train.arguments.collateral_label` | `4` | Class whose images are blended in | +| `partitioning[1].arguments.corruption_target` | `9` | Class whose samples get corrupted | +| `partitioning[1].arguments.p` | `0.95` | Fraction of all `corruption_target` samples to corrupt | +| `partitioning[0].arguments.hub_training_samples` | `0.95` | (Unbalanced only) Fraction of `9`s given to the hub | + +## What's in this folder + +| File | Content | +|------|---------| +| [`main.py`](main.py) | The two experiment configurations and the entry point. | +| [`corruption.py`](corruption.py) | Corrupted dataset, corrupting partitioning step, and summary printout. | +| [`Plots.png`](Plots.png) | Per-class F1 (top) and recall (bottom) for digits 4 and 9 over communication rounds. | + +## Running + +Run from this directory, since `main.py` imports `corruption` as a local module. + +```bash +# Validate the configurations without training +python main.py --sanity_check + +# Run both experiments (unbalanced first, then balanced) +python main.py --seed 123 + +# Train clients in parallel within each simulation (enables dataset caching) +python main.py --seed 123 --num_parallel_clients 25 + +# Quick smoke test: build everything, skip training and testing +python main.py --debug +``` + +The standard simulator options also apply, e.g. `--gpu -1` for CPU, `--output_directory` and `--dataset_directory`. diff --git a/examples/LabelFlip/__init__.py b/examples/LabelFlip/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/examples/LabelFlip/corruption.py b/examples/LabelFlip/corruption.py new file mode 100644 index 0000000..0bf49a1 --- /dev/null +++ b/examples/LabelFlip/corruption.py @@ -0,0 +1,170 @@ +from typing import Dict, Any, List + +import torch +from torch import Tensor + +from dengine.graph import Graph +from dengine.partitioning import TYPE_DATASET_PARTITIONING +from dengine.dataset import SupervisedDataset +from dengine.partitioning import register_partitioning + +from dengine.dataset.decorators import register_dataset +from dengine.dataset.mnist import load_mnist + + +class CorruptedSupervisedDataset(SupervisedDataset): + def __init__(self, *args, alpha: float, collateral_label: int, **kwargs): + super().__init__(*args, **kwargs) + self.collateral_label = collateral_label + self.is_corrupted = torch.zeros(len(self.targets), dtype=torch.bool) + # Tracks collateral samples already used as partners, so that each one is + # drawn at most once across all calls to corrupt_in_place_by_index + self.is_used_partner = torch.zeros(len(self.targets), dtype=torch.bool) + self.alpha = alpha + + @classmethod + def from_dataset(cls, dataset: SupervisedDataset, alpha: float, collateral_label: int): + return cls( + data=dataset.data, + targets=dataset.targets, + use_cache=dataset._use_cache, + root=dataset.root, + transform=dataset.transform, + target_transform=dataset.target_transform, + alpha=alpha, + collateral_label=collateral_label + ) + + def corrupt_in_place_by_index(self, indices: List[int]): + if len(indices) == 0: + return + idx = torch.as_tensor(indices, dtype=torch.long) + + # For each corrupted sample, pick a random partner from the collateral label, + # sampling without replacement (a partner can never be selected twice) + available = (self.targets == self.collateral_label) & ~self.is_used_partner + pool = available.nonzero(as_tuple=True)[0] + if len(idx) > len(pool): + raise ValueError( + f"Not enough unused samples of collateral label {self.collateral_label}: " + f"requested {len(idx)}, available {len(pool)}" + ) + partners = pool[torch.randperm(len(pool))[:len(idx)]] + self.is_used_partner[partners] = True + + # Pixel-space interpolation: x' = (1 - alpha) * x + alpha * x_partner + x = self.data[idx].float() + x_partner = self.data[partners].float() + mixed = (1 - self.alpha) * x + self.alpha * x_partner + self.data[idx] = mixed.round().clamp(0, 255).to(self.data.dtype) + self.is_corrupted[idx] = True + + +@register_dataset() +def load_corrupted_mnist( + alpha: float, + collateral_label: int, + *args, **kwargs +) -> CorruptedSupervisedDataset: + return CorruptedSupervisedDataset.from_dataset( + load_mnist(*args, **kwargs), alpha, collateral_label + ) + + +def corruptible_indices(node_partition) -> Tensor: + return torch.cat([torch.as_tensor(node_partition[s], dtype=torch.long) for s in ["train", "validation"]]) + + +def subsample_class_indices(dataset: SupervisedDataset, subset: Tensor, target, p: float) -> List[int]: + (rel_indices,) = torch.where(dataset.targets[subset] == target) + num_to_sample = round(len(rel_indices) * p) + perm = torch.randperm(len(rel_indices))[:num_to_sample] + abs_indices = subset[rel_indices[perm]] + return abs_indices.tolist() + + +def compute_corruption_distribution( + graph_nodes, + dataset: SupervisedDataset, + partitions: TYPE_DATASET_PARTITIONING, + corruption_target, + global_corruption_percentage: float +) -> Dict[Any, float]: + corruption_distribution = {} + + # Count samples for each class + class_counts_by_nodeid = {} + for nodeid in graph_nodes: + Y = dataset.targets[corruptible_indices(partitions[nodeid])] + class_counts_by_nodeid[nodeid] = len(Y[Y == corruption_target]) + + # Compute the percentage given the total class cardinality available + class_samples_global_count = sum(class_counts_by_nodeid.values()) + total_corrupted_samples = int(class_samples_global_count * global_corruption_percentage) + + # Compute for each node the percentage of samples it must corrupt + current_corupted_samples = 0 + for nodeid in graph_nodes: + if class_counts_by_nodeid[nodeid] == 0: + continue + required_node_corrupted_samples = max(total_corrupted_samples - current_corupted_samples, 0) + if required_node_corrupted_samples == 0: + return corruption_distribution + actual_node_corrupted_samples = min(required_node_corrupted_samples, class_counts_by_nodeid[nodeid]) + current_corupted_samples += actual_node_corrupted_samples + corruption_distribution[nodeid] = actual_node_corrupted_samples / class_counts_by_nodeid[nodeid] + return corruption_distribution + + +@register_partitioning() +def global_corruption_with_centrality_priority( + dataset: SupervisedDataset, + test: SupervisedDataset, + partitions: TYPE_DATASET_PARTITIONING, + graph: Graph, + *args, + p: float, + corruption_target: int, + **kwargs +) -> TYPE_DATASET_PARTITIONING: + assert isinstance(dataset, CorruptedSupervisedDataset) + corruption_distribution_by_nodeid = compute_corruption_distribution( + graph.nodes_sort_by_neigbors_count(reverse=True), + dataset, + partitions, + corruption_target, + p + ) + for nodeid, corruption_percentage in corruption_distribution_by_nodeid.items(): + node_corruptible_set = corruptible_indices(partitions[nodeid]) + corrupted_samples_indices = subsample_class_indices( + dataset, node_corruptible_set, corruption_target, corruption_percentage + ) + dataset.corrupt_in_place_by_index(corrupted_samples_indices) + + print_corruption_summary(dataset, partitions, corruption_target) + + return partitions + + +def print_corruption_summary( + dataset: CorruptedSupervisedDataset, + partitions: TYPE_DATASET_PARTITIONING, + corruption_target: int +): + num_classes = int(dataset.targets.max().item()) + 1 + for nodeid in partitions: + for split, split_idxs in partitions[nodeid].items(): + idxs = torch.as_tensor(split_idxs, dtype=torch.long) + if len(idxs) == 0: + print(f"[node {nodeid}][{split}] empty") + continue + Y = dataset.targets[idxs] + perc = torch.bincount(Y, minlength=num_classes).float() / len(Y) * 100 + perc_str = " ".join(f"{c}:{q:.1f}%" for c, q in enumerate(perc.tolist())) + n_corrupted = int(dataset.is_corrupted[idxs].sum()) + n_target = int((Y == corruption_target).sum()) + print( + f"[node {nodeid}][{split}] n={len(Y)} | {perc_str} | " + f"corrupted={n_corrupted}/{n_target} of class {corruption_target}" + ) diff --git a/examples/LabelFlip/main.py b/examples/LabelFlip/main.py new file mode 100644 index 0000000..89b51ff --- /dev/null +++ b/examples/LabelFlip/main.py @@ -0,0 +1,161 @@ +from typing import Dict, Any +from argparse import ArgumentParser + +from pydantic import ValidationError + +from dengine.bin.args_parser import cli_argument_parser +from dengine.config.builtins import BUILTINS +from dengine.config.utils import convert_to_nested_dict +from dengine import load_experiment_from_yamls +from dengine.bin.simulation import load_engine, SimulationArguments +from dengine.partitioning.iid import random_iid_balanced +from dengine.partitioning.noniid import random_iid_balanced_with_class_majority_hub +from dengine.models import CNNMnist + +from corruption import load_corrupted_mnist, global_corruption_with_centrality_priority + + +def load_configurations( + simulation_args: SimulationArguments, + overrides: Dict[str, Any] = {} +): + FILES = [ + BUILTINS.CORE.CORE, + BUILTINS.CORE.DATASETS.MNIST, + BUILTINS.CORE.SCENARIOS.DECENTRALIZED_HOMOGENOUS, + BUILTINS.CORE.GRAPH.BA_MEDIUM, + BUILTINS.CORE.CLIENT.CLIENT_DECAVG_SGD + ] + OVERRIDES = { + # Full reproducibility (otherwise graph is not seeded) + "graph.arguments.seed": simulation_args.seed, + "scenario.arguments.max_communication_rounds": 1000, + # Client + "client.local_model.target": CNNMnist, + "client.training_engine.arguments.patience": 5, + "client.training_engine.arguments.epochs": 5, + "client.arguments.include_myself": False, + "client.training_engine.arguments.validation_batch_size": 512, + "client.training_engine.arguments.training_batch_size": 32, + # Dataset + "dataset.train.target": load_corrupted_mnist, + "dataset.train.arguments.collateral_label": 4, + "dataset.train.arguments.alpha": 1. + } + OVERRIDES.update(overrides) + + balanced_corruption_config = load_experiment_from_yamls( + files=FILES, + overrides=convert_to_nested_dict({ + **OVERRIDES, + "partitioning": [ + {"target": random_iid_balanced, "arguments": { + "validation_percentage": .2 + }}, + {"target": global_corruption_with_centrality_priority, "arguments": { + "p": .95, + "corruption_target": 9 + }} + ], + }), + experiments_directory_root=str(simulation_args.output_directory.absolute()), + seed=simulation_args.seed, + ) + balanced_corruption_config.name = ( + "Balanced Corruption,DecAvg," + f"{balanced_corruption_config.client.local_model.target}" + ) + + unbalanced_corruption_config = load_experiment_from_yamls( + files=FILES, + overrides=convert_to_nested_dict({ + **OVERRIDES, + "partitioning": [ + {"target": random_iid_balanced_with_class_majority_hub, "arguments": { + "validation_percentage": .2, + "hub_training_samples": .95, + "classes": [9], + }}, + {"target": global_corruption_with_centrality_priority, "arguments": { + "p": .95, + "corruption_target": 9 + }} + ], + }), + experiments_directory_root=str(simulation_args.output_directory.absolute()), + seed=simulation_args.seed, + ) + unbalanced_corruption_config.name = ( + "Unbalanced Corruption,DecAvg," + f"{unbalanced_corruption_config.client.local_model.target}" + ) + + return [ + unbalanced_corruption_config, + balanced_corruption_config, + ] + + +def main(): + parser = ArgumentParser() + parser.add_argument( + "--concurrent_runs", + type=int, + default=1, + help="Number of configurations to run in parallel (default: 1)." + ) + parser.add_argument( + "--num_parallel_clients", + type=int, + default=1, + help="Number of clients to run in parallel in each simulation (default: 1)." + ) + parser.add_argument( + "--debug", + action="store_true", + help="Sets the argument client.arguments.debug_skip_training=true" + ) + simulation_args, _ = cli_argument_parser(parser) + extra_arguments = parser.parse_args() + + # ┌──────────────────────────────────┐ + # │ Configuration │ + # └──────────────────────────────────┘ + client_parallelism_overrides = {} + if extra_arguments.num_parallel_clients > 1: + client_parallelism_overrides = { + "scenario.arguments.num_parallel_clients": extra_arguments.num_parallel_clients, + "dataset.train.arguments.use_cache": True, + "dataset.test.arguments.use_cache": True, + } + debug_argument = {} + if extra_arguments.debug: + debug_argument = { + "client.arguments.debug_skip_training": True, + "client.arguments.debug_skip_test": True + } + + try: + configurations = load_configurations(simulation_args, {**debug_argument, **client_parallelism_overrides}) + except ValidationError as e: + print("\n❌ Failed to parse the configuration due to the following validation errors: ") + for err in e.errors(): + loc = ".".join(str(part) for part in err['loc']) + print(f" - {loc}: {err['msg']} (type: {err.get('type', 'unknown')})") + return + + # ┌──────────────────────────────────┐ + # │ Simulation │ + # └──────────────────────────────────┘ + for cfg in configurations: + try: + loaded_engine = load_engine(simulation_args, cfg, verbose=False) + loaded_engine.run() + except KeyboardInterrupt: + return + except Exception as e: + raise RuntimeError(f"Config {configurations} failed: {e}") from e + + +if __name__ == "__main__": + main()