|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import logging |
| 3 | +import warnings |
| 4 | + |
| 5 | +warnings.filterwarnings("ignore") |
| 6 | +logging.disable(logging.CRITICAL) |
| 7 | + |
| 8 | +import argparse |
| 9 | +import os |
| 10 | +import resource |
| 11 | +import time |
| 12 | + |
| 13 | +import numpy as np |
| 14 | +import torch |
| 15 | +import torch.nn.functional as F |
| 16 | +from torch.distributed import destroy_process_group, init_process_group |
| 17 | +from torch.nn.parallel import DistributedDataParallel as DDP |
| 18 | +from torch_geometric.datasets import Planetoid |
| 19 | + |
| 20 | +# Distributed PyG imports |
| 21 | +from torch_geometric.loader import NeighborLoader |
| 22 | +from torch_geometric.nn import GCNConv |
| 23 | + |
| 24 | +DATASETS = ["cora", "citeseer", "pubmed"] |
| 25 | +IID_BETAS = [10000.0, 100.0, 10.0] |
| 26 | +CLIENT_NUM = 10 |
| 27 | +TOTAL_ROUNDS = 200 |
| 28 | +LOCAL_STEPS = 1 |
| 29 | +LEARNING_RATE = 0.1 |
| 30 | +HIDDEN_DIM = 64 |
| 31 | +DROPOUT_RATE = 0.0 |
| 32 | + |
| 33 | +PLANETOID_NAMES = {"cora": "Cora", "citeseer": "CiteSeer", "pubmed": "PubMed"} |
| 34 | + |
| 35 | + |
| 36 | +def peak_memory_mb(): |
| 37 | + usage = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss |
| 38 | + return (usage / 1024**2) if usage > 1024**2 else (usage / 1024) |
| 39 | + |
| 40 | + |
| 41 | +def calculate_communication_cost(model_size_mb, rounds, clients): |
| 42 | + cost_per_round = model_size_mb * clients * 2 |
| 43 | + return cost_per_round * rounds |
| 44 | + |
| 45 | + |
| 46 | +def dirichlet_partition(labels, num_clients, alpha): |
| 47 | + labels = labels.cpu().numpy() |
| 48 | + num_classes = labels.max() + 1 |
| 49 | + idx_by_class = [np.where(labels == c)[0] for c in range(num_classes)] |
| 50 | + client_idxs = [[] for _ in range(num_clients)] |
| 51 | + |
| 52 | + for idx in idx_by_class: |
| 53 | + np.random.shuffle(idx) |
| 54 | + props = np.random.dirichlet([alpha] * num_clients) |
| 55 | + props = (props / props.sum()) * len(idx) |
| 56 | + counts = np.floor(props).astype(int) |
| 57 | + counts[-1] = len(idx) - counts[:-1].sum() |
| 58 | + start = 0 |
| 59 | + for i, cnt in enumerate(counts): |
| 60 | + client_idxs[i].extend(idx[start : start + cnt]) |
| 61 | + start += cnt |
| 62 | + |
| 63 | + return [torch.tensor(ci, dtype=torch.long) for ci in client_idxs] |
| 64 | + |
| 65 | + |
| 66 | +class DistributedGCN(torch.nn.Module): |
| 67 | + def __init__( |
| 68 | + self, in_channels, hidden_channels, out_channels, num_layers=2, dropout=0.0 |
| 69 | + ): |
| 70 | + super().__init__() |
| 71 | + self.num_layers = num_layers |
| 72 | + self.dropout = dropout |
| 73 | + |
| 74 | + self.convs = torch.nn.ModuleList() |
| 75 | + self.convs.append(GCNConv(in_channels, hidden_channels)) |
| 76 | + for _ in range(num_layers - 2): |
| 77 | + self.convs.append(GCNConv(hidden_channels, hidden_channels)) |
| 78 | + self.convs.append(GCNConv(hidden_channels, out_channels)) |
| 79 | + |
| 80 | + def forward(self, x, edge_index): |
| 81 | + for i, conv in enumerate(self.convs): |
| 82 | + x = conv(x, edge_index) |
| 83 | + if i < len(self.convs) - 1: |
| 84 | + x = F.relu(x) |
| 85 | + x = F.dropout(x, p=self.dropout, training=self.training) |
| 86 | + return x |
| 87 | + |
| 88 | + |
| 89 | +def setup_distributed(rank, world_size): |
| 90 | + """Initialize distributed training""" |
| 91 | + os.environ["MASTER_ADDR"] = "localhost" |
| 92 | + os.environ["MASTER_PORT"] = "12355" |
| 93 | + init_process_group("gloo", rank=rank, world_size=world_size) |
| 94 | + |
| 95 | + |
| 96 | +def cleanup_distributed(): |
| 97 | + """Cleanup distributed training""" |
| 98 | + destroy_process_group() |
| 99 | + |
| 100 | + |
| 101 | +def train_client(rank, world_size, data, client_indices, model_state, device): |
| 102 | + """Training function for each client process""" |
| 103 | + # Setup distributed environment |
| 104 | + setup_distributed(rank, world_size) |
| 105 | + |
| 106 | + # Create model and wrap with DDP |
| 107 | + model = DistributedGCN( |
| 108 | + data.x.size(1), |
| 109 | + HIDDEN_DIM, |
| 110 | + int(data.y.max().item()) + 1, |
| 111 | + num_layers=2, |
| 112 | + dropout=DROPOUT_RATE, |
| 113 | + ).to(device) |
| 114 | + |
| 115 | + model = DDP(model, device_ids=None if device.type == "cpu" else [device]) |
| 116 | + model.load_state_dict(model_state) |
| 117 | + |
| 118 | + # Create data loader for this client |
| 119 | + loader = NeighborLoader( |
| 120 | + data, |
| 121 | + input_nodes=client_indices, |
| 122 | + num_neighbors=[10, 10], |
| 123 | + batch_size=512 if len(client_indices) > 512 else len(client_indices), |
| 124 | + shuffle=True, |
| 125 | + ) |
| 126 | + |
| 127 | + optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE) |
| 128 | + model.train() |
| 129 | + |
| 130 | + # Local training |
| 131 | + for epoch in range(LOCAL_STEPS): |
| 132 | + total_loss = 0 |
| 133 | + for batch in loader: |
| 134 | + batch = batch.to(device) |
| 135 | + optimizer.zero_grad() |
| 136 | + out = model(batch.x, batch.edge_index) |
| 137 | + |
| 138 | + # Use only the nodes in the current batch that are in training set |
| 139 | + mask = batch.train_mask[: batch.batch_size] |
| 140 | + if mask.sum() > 0: |
| 141 | + loss = F.cross_entropy( |
| 142 | + out[: batch.batch_size][mask], batch.y[: batch.batch_size][mask] |
| 143 | + ) |
| 144 | + loss.backward() |
| 145 | + optimizer.step() |
| 146 | + total_loss += loss.item() |
| 147 | + |
| 148 | + cleanup_distributed() |
| 149 | + return model.module.state_dict() |
| 150 | + |
| 151 | + |
| 152 | +def run_distributed_pyg_experiment(ds, beta): |
| 153 | + device = torch.device("cpu") # Use CPU for simplicity |
| 154 | + ds_obj = Planetoid(root="data/", name=PLANETOID_NAMES[ds]) |
| 155 | + data = ds_obj[0].to(device) |
| 156 | + in_channels = data.x.size(1) |
| 157 | + num_classes = int(data.y.max().item()) + 1 |
| 158 | + |
| 159 | + print(f"Running {ds} with β={beta}") |
| 160 | + print(f"Dataset: {data.num_nodes:,} nodes, {data.edge_index.size(1):,} edges") |
| 161 | + |
| 162 | + # Partition training nodes |
| 163 | + train_idx = data.train_mask.nonzero(as_tuple=False).view(-1) |
| 164 | + test_idx = data.test_mask.nonzero(as_tuple=False).view(-1) |
| 165 | + |
| 166 | + client_parts = dirichlet_partition(data.y[train_idx], CLIENT_NUM, beta) |
| 167 | + client_idxs = [train_idx[part] for part in client_parts] |
| 168 | + |
| 169 | + # Initialize global model |
| 170 | + global_model = DistributedGCN( |
| 171 | + in_channels, HIDDEN_DIM, num_classes, num_layers=2, dropout=DROPOUT_RATE |
| 172 | + ).to(device) |
| 173 | + |
| 174 | + t0 = time.time() |
| 175 | + |
| 176 | + # Federated training loop using simulated distributed training |
| 177 | + for round_idx in range(TOTAL_ROUNDS): |
| 178 | + global_state = global_model.state_dict() |
| 179 | + local_states = [] |
| 180 | + |
| 181 | + # Simulate distributed training for each client |
| 182 | + for client_id in range(CLIENT_NUM): |
| 183 | + # Create client model |
| 184 | + client_model = DistributedGCN( |
| 185 | + in_channels, HIDDEN_DIM, num_classes, num_layers=2, dropout=DROPOUT_RATE |
| 186 | + ).to(device) |
| 187 | + |
| 188 | + # Load global state |
| 189 | + client_model.load_state_dict(global_state) |
| 190 | + |
| 191 | + # Create client data loader using PyG's NeighborLoader |
| 192 | + client_loader = NeighborLoader( |
| 193 | + data, |
| 194 | + input_nodes=client_idxs[client_id], |
| 195 | + num_neighbors=[10, 10], |
| 196 | + batch_size=min(512, len(client_idxs[client_id])), |
| 197 | + shuffle=True, |
| 198 | + ) |
| 199 | + |
| 200 | + optimizer = torch.optim.Adam(client_model.parameters(), lr=LEARNING_RATE) |
| 201 | + client_model.train() |
| 202 | + |
| 203 | + # Local training |
| 204 | + for epoch in range(LOCAL_STEPS): |
| 205 | + for batch in client_loader: |
| 206 | + batch = batch.to(device) |
| 207 | + optimizer.zero_grad() |
| 208 | + out = client_model(batch.x, batch.edge_index) |
| 209 | + |
| 210 | + # Use only the nodes that are actually in training set |
| 211 | + local_train_mask = torch.isin( |
| 212 | + batch.n_id[: batch.batch_size], client_idxs[client_id] |
| 213 | + ) |
| 214 | + if local_train_mask.sum() > 0: |
| 215 | + loss = F.cross_entropy( |
| 216 | + out[: batch.batch_size][local_train_mask], |
| 217 | + batch.y[: batch.batch_size][local_train_mask], |
| 218 | + ) |
| 219 | + loss.backward() |
| 220 | + optimizer.step() |
| 221 | + |
| 222 | + local_states.append(client_model.state_dict()) |
| 223 | + |
| 224 | + # FedAvg aggregation |
| 225 | + global_state = global_model.state_dict() |
| 226 | + for key in global_state.keys(): |
| 227 | + global_state[key] = torch.stack( |
| 228 | + [state[key].float() for state in local_states] |
| 229 | + ).mean(0) |
| 230 | + |
| 231 | + global_model.load_state_dict(global_state) |
| 232 | + |
| 233 | + dur = time.time() - t0 |
| 234 | + |
| 235 | + # Final evaluation using NeighborLoader for test set |
| 236 | + global_model.eval() |
| 237 | + test_loader = NeighborLoader( |
| 238 | + data, |
| 239 | + input_nodes=test_idx, |
| 240 | + num_neighbors=[10, 10], |
| 241 | + batch_size=min(1024, len(test_idx)), |
| 242 | + shuffle=False, |
| 243 | + ) |
| 244 | + |
| 245 | + correct = 0 |
| 246 | + total = 0 |
| 247 | + with torch.no_grad(): |
| 248 | + for batch in test_loader: |
| 249 | + batch = batch.to(device) |
| 250 | + out = global_model(batch.x, batch.edge_index) |
| 251 | + pred = out[: batch.batch_size].argmax(dim=-1) |
| 252 | + correct += (pred == batch.y[: batch.batch_size]).sum().item() |
| 253 | + total += batch.batch_size |
| 254 | + |
| 255 | + accuracy = correct / total * 100 |
| 256 | + |
| 257 | + # Calculate metrics |
| 258 | + total_params = sum(p.numel() for p in global_model.parameters()) |
| 259 | + model_size_mb = total_params * 4 / 1024**2 |
| 260 | + comm_cost = calculate_communication_cost(model_size_mb, TOTAL_ROUNDS, CLIENT_NUM) |
| 261 | + mem = peak_memory_mb() |
| 262 | + |
| 263 | + return { |
| 264 | + "accuracy": accuracy, |
| 265 | + "total_time": dur, |
| 266 | + "computation_time": dur, |
| 267 | + "communication_cost_mb": comm_cost, |
| 268 | + "peak_memory_mb": mem, |
| 269 | + "avg_time_per_round": dur / TOTAL_ROUNDS, |
| 270 | + "model_size_mb": model_size_mb, |
| 271 | + "total_params": total_params, |
| 272 | + "nodes": data.num_nodes, |
| 273 | + "edges": data.edge_index.size(1), |
| 274 | + } |
| 275 | + |
| 276 | + |
| 277 | +def main(): |
| 278 | + parser = argparse.ArgumentParser() |
| 279 | + parser.add_argument("--use_cluster", action="store_true") |
| 280 | + args = parser.parse_args() |
| 281 | + |
| 282 | + print( |
| 283 | + "\nDS,IID,BS,Time[s],FinalAcc[%],CompTime[s],CommCost[MB],PeakMem[MB],AvgRoundTime[s],ModelSize[MB],TotalParams" |
| 284 | + ) |
| 285 | + |
| 286 | + for ds in DATASETS: |
| 287 | + for beta in IID_BETAS: |
| 288 | + try: |
| 289 | + metrics = run_distributed_pyg_experiment(ds, beta) |
| 290 | + print( |
| 291 | + f"{ds},{beta},-1," |
| 292 | + f"{metrics['total_time']:.1f}," |
| 293 | + f"{metrics['accuracy']:.2f}," |
| 294 | + f"{metrics['computation_time']:.1f}," |
| 295 | + f"{metrics['communication_cost_mb']:.1f}," |
| 296 | + f"{metrics['peak_memory_mb']:.1f}," |
| 297 | + f"{metrics['avg_time_per_round']:.3f}," |
| 298 | + f"{metrics['model_size_mb']:.3f}," |
| 299 | + f"{metrics['total_params']}" |
| 300 | + ) |
| 301 | + except Exception as e: |
| 302 | + print(f"Error running {ds} with β={beta}: {e}") |
| 303 | + print(f"{ds},{beta},-1,0.0,0.00,0.0,0.0,0.0,0.000,0.000,0") |
| 304 | + |
| 305 | + |
| 306 | +if __name__ == "__main__": |
| 307 | + main() |
0 commit comments