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 numpy as np
import copy
# ==========================================
# 1. Configuration & Hyperparameters
# ==========================================
CONFIG = {
'num_clients': 10, # Total number of devices/clients
'fraction': 0.5, # Fraction of clients to use per round (C)
'num_rounds': 5, # Number of global communication rounds
'local_epochs': 3, # Epochs each client trains locally (E)
'local_bs': 32, # Local batch size (B)
'lr': 0.01, # Learning rate
'device': 'cuda' if torch.cuda.is_available() else 'cpu'
}
# ==========================================
# 2. Model Definition
# ==========================================
class SimpleCNN(nn.Module):
""" A simple CNN for MNIST classification """
def __init__(self):
super(SimpleCNN, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=3)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3)
self.fc1 = nn.Linear(64 * 5 * 5, 128)
self.fc2 = nn.Linear(128, 10)
self.pool = nn.MaxPool2d(2, 2)
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 * 5 * 5)
x = self.relu(self.fc1(x))
x = self.fc2(x)
return x
# ==========================================
# 3. Data Distribution (Simulation)
# ==========================================
def get_data_loaders(num_clients):
"""
Downloads MNIST and splits it into 'num_clients' distinct subsets.
This simulates data being generated locally on user devices.
"""
print("Downloading and preparing data...")
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
# Download dataset
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
# Split training data into chunks for clients
# We use a rough split. In reality, data sizes vary per user.
num_items = len(train_dataset)
items_per_client = num_items // num_clients
client_loaders = []
for i in range(num_clients):
start_idx = i * items_per_client
end_idx = start_idx + items_per_client
# Create a subset of the dataset for this client
subset = Subset(train_dataset, range(start_idx, end_idx))
loader = DataLoader(subset, batch_size=CONFIG['local_bs'], shuffle=True)
client_loaders.append(loader)
# Test loader for global evaluation
test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)
return client_loaders, test_loader
# ==========================================
# 4. Client Logic (Local Training)
# ==========================================
class Client:
def __init__(self, client_id, data_loader):
self.id = client_id
self.data_loader = data_loader
self.device = CONFIG['device']
def train(self, global_model):
"""
Receives the global model, trains it on local data,
and returns the updated state_dict and number of samples.
"""
# Copy global model to local device
local_model = copy.deepcopy(global_model)
local_model.to(self.device)
local_model.train()
optimizer = optim.SGD(local_model.parameters(), lr=CONFIG['lr'])
criterion = nn.CrossEntropyLoss()
# Local training loop
for epoch in range(CONFIG['local_epochs']):
for data, target in self.data_loader:
data, target = data.to(self.device), target.to(self.device)
optimizer.zero_grad()
output = local_model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
# Return the updated weights and the amount of data used
num_samples = len(self.data_loader.dataset)
return local_model.state_dict(), num_samples
# ==========================================
# 5. Server Logic (Aggregation)
# ==========================================
class Server:
def __init__(self):
self.global_model = SimpleCNN()
self.device = CONFIG['device']
self.global_model.to(self.device)
def aggregate(self, client_updates):
"""
Performs Federated Averaging (FedAvg):
w_global = sum(n_k / N * w_k)
"""
total_samples = sum([update[1] for update in client_updates])
# Start with zeroed weights
aggregated_weights = {}
# Initialize aggregated_weights with zeros matching the model structure
for key, val in self.global_model.state_dict().items():
aggregated_weights[key] = torch.zeros_like(val)
# Sum the weighted updates
for state_dict, num_samples in client_updates:
weight = num_samples / total_samples
for key in aggregated_weights:
aggregated_weights[key] += state_dict[key].cpu() * weight
# Load the new weights into the global model
self.global_model.load_state_dict(aggregated_weights)
return self.global_model
def evaluate(self, test_loader):
self.global_model.eval()
correct = 0
total = 0
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(self.device), target.to(self.device)
outputs = self.global_model(data)
_, predicted = torch.max(outputs.data, 1)
total += target.size(0)
correct += (predicted == target).sum().item()
acc = 100 * correct / total
return acc
# ==========================================
# 6. Main Simulation Loop
# ==========================================
def main():
# Setup
client_loaders, test_loader = get_data_loaders(CONFIG['num_clients'])
clients = [Client(i, client_loaders[i]) for i in range(CONFIG['num_clients'])]
server = Server()
print(f"\nStarting Federated Learning Simulation ({CONFIG['device']})")
print(f"Clients: {CONFIG['num_clients']} | Rounds: {CONFIG['num_rounds']}")
print("-" * 50)
for round_num in range(1, CONFIG['num_rounds'] + 1):
print(f"Round {round_num}/{CONFIG['num_rounds']}")
# 1. Server selects a fraction of clients
num_selected = max(int(CONFIG['fraction'] * CONFIG['num_clients']), 1)
selected_indices = np.random.choice(range(CONFIG['num_clients']), num_selected, replace=False)
client_updates = []
# 2. Clients perform local training
for idx in selected_indices:
print(f" -> Client {idx} training...", end="\r")
state_dict, n_samples = clients[idx].train(server.global_model)
client_updates.append((state_dict, n_samples))
print(f" -> {num_selected} clients finished training. Aggregating...")
# 3. Server aggregates updates
server.aggregate(client_updates)
# 4. Evaluate Global Model
accuracy = server.evaluate(test_loader)
print(f" -> Global Model Accuracy: {accuracy:.2f}%")
print("-" * 50)
if __name__ == "__main__":
main()