The user wants a program that performs federated learning (FL) simulations.
Federated learning is a machine learning setting where many clients (e.g., mobile devices or organizations) collaboratively train a model under the orchestration of a central server, while keeping the training data decentralized.
Key components needed for a simulation:
The Model: A neural network or a simple machine learning model (like Logistic Regression or a CNN) to train.
The Data: A dataset that needs to be distributed among the "clients". Non-IID (Non-Independent and Identically Distributed) data distribution is a common scenario to simulate.
The Clients: Entities that hold a subset of the data and perform local training.
The Server: The central coordinator that aggregates updates from clients and distributes the global model.
The Communication Protocol: The logic for rounds of training (selecting clients, sending models, local training, sending updates, aggregation).
I should choose a framework or language. Python is the standard. I can write it from scratch using PyTorch or TensorFlow, or use a specialized library like flower or fedml. Writing from scratch (vanilla PyTorch) is often better for educational purposes to show exactly what's happening under the hood, rather than abstracting everything away.
Data Loading: Use MNIST or CIFAR-10 for simplicity. Create a function to split the dataset into N disjoint shards to simulate different users.
Model Definition: Create a simple CNN or MLP.
Client Simulation:
A class or function representing a user.
It takes the global model weights.
It performs local_epochs of training on its local data.
It returns the updated weights (or the gradients/delta).
Server Simulation:
Initializes the global model.
Loop over num_rounds.
In each round:
Select a fraction of clients (C-fraction).
Distribute current global weights.
Run client updates.
Aggregation: FedAvg (Federated Averaging) is the standard algorithm. wt+1=∑.
Evaluation: Test the global model on a held-out test set after each round.
Refining the Code Structure:
Hyperparameters: Learning rate, batch size, local epochs, number of rounds, fraction of clients.
Dataset partitioning: I'll use a simple random splitter or a Dirichlet distribution splitter for non-IID, but a random split is easier to read for a basic example. Let's stick to a basic random split but ensuring distinct datasets per user.
Aggregation: Need to handle the state dicts of PyTorch models carefully. Weighted average based on dataset size is best.
Drafting the Code (Mental or Scratchpad):
python
import torch
from torch import nn, optim
from torchvision import datasets, transforms
from collections import OrderedDict
# 1. Model
class SimpleNet(nn.Module):
...
# 2. Helper: Dataset split
def get_data_loaders(num_clients):
# Load MNIST
# Split into num_clients chunks
# Return list of DataLoaders
...
# 3. Helper: Local Training
def train_local(model, data_loader, epochs, lr):
optimizer = optim.SGD(model.parameters(), lr=lr)
model.train()
for e in range(epochs):
for batch in data_loader:
# standard training loop
...
return model.state_dict() # return weights
# 4. Main Loop
def federated_learning():
# Init global model
# Split data
# Loop rounds
# Select users
# Train local models
# Aggregate (FedAvg)
# Evaluate
Adding Nuances:
Deep Copy: When passing the global model to clients, we must ensure they don't modify the server's model instance directly. copy.deepcopy is useful here.
Efficiency: In a real simulation, training happens in parallel. In a simple Python script on a single machine, it's sequential. I'll keep it sequential for simplicity but structure it so it's clear.
FedAvg: The averaging logic can be tricky with PyTorch state dicts. I need to iterate through the keys and perform the weighted sum.
Let's write the complete code. I will provide a clean, commented Python script using PyTorch.
Steps in the code:
Imports:torch, torchvision, copy, random.
Configuration class: Store NUM_CLIENTS, FRAC_CLIENTS, LOCAL_EPOCHS, etc.
Model: A simple CNN for MNIST.
Data Partitioning: A function to download MNIST and split the training set into NUM_CLIENTS distinct Subsets.
Client Update Function: Takes global weights, loads them into a local model, trains, returns new weights.
Aggregation Function: Takes a list of (weights, num_samples) and computes the weighted average.
Testing Function: Standard accuracy calculation.
Main Execution: The orchestration loop.
Self-Correction during drafting:
Should I simulate Non-IID data? It makes the simulation much more realistic but the code longer. For a general request, a random split (IID) is usually the starting point. I will stick to IID for code clarity but mention how to change it.
Wait, torch.utils.data.random_split is easy.
Aggregation:
wnew=wold∗0 (just kidding).
We need to accumulate param * (n_k / N).
It's better to create a buffer for the new parameters, initialize to zero, and add the weighted contribution from each client.
Let's refine the Aggregation logic.
python
new_state_dict = copy.deepcopy(local_weights[0]) # Start with structure
for key in new_state_dict.keys():
new_state_dict[key] = torch.zeros_like(new_state_dict[key])
for i, weight in enumerate(local_weights):
n = local_samples[i]
for key in weight.keys():
new_state_dict[key] += weight[key] * (n / total_samples)
Actually, simpler: Sum weight * n then divide by total_samples at the end.
Or just accumulate the weighted sum.
Let's put it all together.
I will provide a complete, single-file Python script.
Constraint Checklist & Confidence Score:
Write a program? Yes.
Perform FL simulation? Yes.
Language? Python (implied standard for ML).
Framework? PyTorch (most readable/standard).
Confidence Score: 5/5
Mental Sandbox Simulation:
User runs script.
Downloads MNIST.
Splits into 10 clients.
Round 1 starts.
Server selects 5 clients.
Clients train locally.
Server aggregates.
Prints accuracy.
Round 2...
Ends.
Looks good.
I will add comments explaining the steps (Data Splitting, Local Training, Aggregation) to make it educational.
One detail: GPU usage. I should check for CUDA but default to CPU to ensure it runs everywhere.
Final Polish: Ensure the indentation is correct and imports are present.
Code Structure:
Imports & Config.
Model (SimpleCNN).
Data prep (split MNIST).
client_update function.
server_aggregate function.
test function.
main loop.
This looks solid.
Here is a complete, runnable Python program that simulates Federated Learning using PyTorch.
This implementation simulates the FedAvg (Federated Averaging) algorithm, which is the standard approach in FL. It sets up a central server and multiple clients. The clients train locally on partitioned data (simulating data silos) and send their model updates (not the data) to the server for aggregation.
Prerequisites
You will need torch and torchvision installed:
bash
pip install torch torchvision
The Python Program
python
How it Works
Data Distribution (The "Federation"):
The code downloads the MNIST dataset (handwritten digits).
It splits the 60,000 training images into 10 distinct subsets (one for each simulated client). In a real scenario, this data would never leave the individual devices.
The Global Model:
A simple Convolutional Neural Network (CNN) is created. This represents the "truth" owned by the server.
The FL Loop:
Selection: For every round, the server picks a random 50% of the clients (FRAC_CLIENTS).
Distribution: The server sends a copy of the current global model to these clients.
Local Training: Each client trains the model on its own private data (using SGD optimizer) for a few epochs. Critically, the client calculates gradients locally.
Aggregation (FedAvg): The clients send their updated model weights back. The server averages these weights mathematically to create a new, improved global model.
Evaluation:
After the aggregation, the server tests the new global model on a central test set to see how well the "wisdom of the crowd" is performing.
Typical Output
You will see the accuracy start low (maybe ~90%) and improve over the rounds to ~97-98%, similar to centralized training, but without the data ever being centralized in one training bucket.
k
nnk
wkt+1
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader, Subset
import copy
import random
import numpy as np
# ==========================================
# 1. Configuration & Hyperparameters
# ==========================================
class Config:
NUM_CLIENTS = 10 # Total number of clients (e.g., mobile phones)
FRAC_CLIENTS = 0.5 # Fraction of clients to use per round (C)
NUM_ROUNDS = 10 # Number of communication rounds
LOCAL_EPOCHS = 3 # How many times a client trains on its local data
BATCH_SIZE = 32
LEARNING_RATE = 0.01
MOMENTUM = 0.9
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# ==========================================
# 2. Model Definition
# ==========================================
class SimpleCNN(nn.Module):
"""
A simple Convolutional Neural Network for MNIST digit classification.
"""
def __init__(self):
super(SimpleCNN, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
self.pool = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(64 * 7 * 7, 128)
self.fc2 = nn.Linear(128, 10)
self.relu = nn.ReLU()
def forward(self, x):
x = self.pool(self.relu(self.conv1(x)))
x = self.pool(self.relu(self.conv2(x)))
x = x.view(-1, 64 * 7 * 7) # Flatten
x = self.relu(self.fc1(x))
x = self.fc2(x)
return x
# ==========================================
# 3. Data Partitioning (Non-IID Simulation)
# ==========================================
def get_data_loaders():
"""
Downloads MNIST and splits it into NUM_CLIENTS separate datasets.
This simulates the data being distributed across different devices.
"""
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
# Download dataset
train_dataset = datasets.MNIST('./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST('./data', train=False, transform=transform)
# Split training data into NUM_CLIENTS shards
# Here we simply split randomly. For "Non-IID" simulation, one might
# sort by label and then split, but random splitting is standard for basic tests.
num_items = len(train_dataset) // Config.NUM_CLIENTS
all_indices = list(range(len(train_dataset)))
random.shuffle(all_indices) # Shuffle to simulate random data distribution
client_loaders = []
for i in range(Config.NUM_CLIENTS):
start_idx = i * num_items
end_idx = start_idx + num_items
indices = all_indices[start_idx:end_idx]
# Create a subset for this client
subset = Subset(train_dataset, indices)
loader = DataLoader(subset, batch_size=Config.BATCH_SIZE, shuffle=True)
client_loaders.append(loader)
# Test loader (global evaluation)
test_loader = DataLoader(test_dataset, batch_size=Config.BATCH_SIZE, shuffle=False)
return client_loaders, test_loader
# ==========================================
# 4. Client Local Training
# ==========================================
def client_update(client_model, optimizer, train_loader, epoch):
"""
Trains the model on the client's local data.
"""
client_model.train()
criterion = nn.CrossEntropyLoss()
for e in range(epoch):
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(Config.DEVICE), target.to(Config.DEVICE)
optimizer.zero_grad()
output = client_model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
return loss.item()
# ==========================================
# 5. Server Aggregation (FedAvg)
# ==========================================
def server_aggregate(global_model, client_models):
"""
Averages the weights of the client models to update the global model.
This is the core of the FedAvg algorithm.
"""
global_dict = global_model.state_dict()
# Initialize a dictionary of zeros with the same shape as the model weights
new_global_dict = {k: torch.zeros_like(v) for k, v in global_dict.items()}
# Sum the weights from all participating clients
for client_model in client_models:
for k in global_dict.keys():
new_global_dict[k] += client_model.state_dict()[k]
# Average the weights
for k in global_dict.keys():
new_global_dict[k] = torch.div(new_global_dict[k], len(client_models))
# Load the averaged weights into the global model
global_model.load_state_dict(new_global_dict)
# Important: Sync all client models with the new global weights
# (In real life, this would be a download step)
for model in client_models:
model.load_state_dict(global_model.state_dict())
# ==========================================
# 6. Evaluation
# ==========================================
def evaluate(model, test_loader):
model.eval()
correct = 0
total = 0
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(Config.DEVICE), target.to(Config.DEVICE)
output = model(data)
_, predicted = torch.max(output.data, 1)
total += target.size(0)
correct += (predicted == target).sum().item()
return 100.0 * correct / total
# ==========================================
# 7. Main Simulation Loop
# ==========================================
def main():
print(f"Initializing Federated Learning Simulation on {Config.DEVICE}...")
# 1. Setup Data
client_loaders, test_loader = get_data_loaders()
# 2. Initialize Global Model
global_model = SimpleCNN().to(Config.DEVICE)
# 3. Simulation Loop
for round_num in range(1, Config.NUM_ROUNDS + 1):
print(f"\n--- Round {round_num}/{Config.NUM_ROUNDS} ---")
# Select a fraction of clients randomly
num_select = int(Config.FRAC_CLIENTS * Config.NUM_CLIENTS)
selected_indices = random.sample(range(Config.NUM_CLIENTS), num_select)
print(f"Selected {num_select} clients: {selected_indices}")
active_client_models = []
# 4. Local Training
for idx in selected_indices:
# Create a copy of the global model for this client
local_model = copy.deepcopy(global_model)
local_model.to(Config.DEVICE)
optimizer = optim.SGD(local_model.parameters(),
lr=Config.LEARNING_RATE,
momentum=Config.MOMENTUM)
# Train locally
print(f" > Training Client {idx}...")
client_update(local_model, optimizer, client_loaders[idx], Config.LOCAL_EPOCHS)
active_client_models.append(local_model)
# 5. Aggregation
print("Aggregating models...")
server_aggregate(global_model, active_client_models)
# 6. Global Evaluation
acc = evaluate(global_model, test_loader)
print(f"Global Model Accuracy: {acc:.2f}%")
print("\nSimulation Complete.")
if __name__ == "__main__":
main()