Flower + PyTorch Quickstart — FedAvg로 두 노드를 연합한다

Flower + PyTorch Quickstart — FedAvg로 두 노드를 연합한다

CIFAR-10을 두 노드로 나눠 훈련하는 가장 간단한 연합 학습 예제예요. flwr new @flwrlabs/quickstart-pytorch 로 프로젝트 뼈대를 만들고 flwr run . 으로 연합을 시작해요.

프로젝트 구조

quickstart-pytorch
├── pytorchexample
│   ├── client_app.py   # ClientApp 정의
│   ├── server_app.py   # ServerApp 정의
│   └── task.py         # 모델·학습·데이터 로딩
├── pyproject.toml      # 의존성과 설정
└── README.md

ClientApp

@app.train() 은 메시지로 받은 가중치를 PyTorch state_dict로 바꿔 로컬 데이터로 학습한 뒤, 갱신된 state_dictArrayRecord로 다시 담아 응답해요.

@app.train()
def train(msg, context):
    model = Net()
    state_dict = msg.content["arrays"].to_torch_state_dict()
    model.load_state_dict(state_dict)
    train_loss = train_fn(model, trainloader, ...)
    return Message(content=RecordDict({"arrays": ArrayRecord(model.state_dict()),
                                       "metrics": MetricRecord({"train_loss": train_loss})}), reply_to=msg)

ServerApp

@app.main() 에서 FedAvg 전략을 만들고 strategy.start(...) 로 라운드를 진행해요. FedAvg는 클라이언트들이 학습한 가중치를 평균 내어 전역 모델을 갱신해요.

실행 결과

라운드마다 configure_train → 각 노드 학습 → aggregate_train 흐름이 반복되고, num-server-rounds 같은 하이퍼파라미터는 --run-config로 덮어쓸 수 있어요.

더 알아보기