Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions configs/core/client/client_decavg_sgd.yml
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions dengine/config/builtins.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down
Binary file added examples/LabelFlip/Plots.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
78 changes: 78 additions & 0 deletions examples/LabelFlip/README.md
Original file line number Diff line number Diff line change
@@ -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`.
Empty file added examples/LabelFlip/__init__.py
Empty file.
170 changes: 170 additions & 0 deletions examples/LabelFlip/corruption.py
Original file line number Diff line number Diff line change
@@ -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}"
)
Loading
Loading