-
Notifications
You must be signed in to change notification settings - Fork 860
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(examples) Update
vit-finetune
example (#3935)
- Loading branch information
Showing
16 changed files
with
362 additions
and
384 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
[build-system] | ||
requires = ["hatchling"] | ||
build-backend = "hatchling.build" | ||
|
||
[project] | ||
name = "vitexample" | ||
version = "1.0.0" | ||
description = "Federated Finetuning of a Vision Transformer with Flower" | ||
license = "Apache-2.0" | ||
dependencies = [ | ||
"flwr-nightly[simulation]==1.11.0.dev20240823", | ||
"flwr-datasets[vision]>=0.3.0", | ||
"torch==2.2.1", | ||
"torchvision==0.17.1", | ||
] | ||
|
||
[tool.hatch.build.targets.wheel] | ||
packages = ["."] | ||
|
||
[tool.flwr.app] | ||
publisher = "flwrlabs" | ||
|
||
[tool.flwr.app.components] | ||
serverapp = "vitexample.server_app:app" | ||
clientapp = "vitexample.client_app:app" | ||
|
||
[tool.flwr.app.config] | ||
num-server-rounds = 3 | ||
batch-size = 32 | ||
learning-rate = 0.01 | ||
dataset-name = "nelorth/oxford-flowers" | ||
num-classes = 102 | ||
|
||
[tool.flwr.federations] | ||
default = "local-simulation" | ||
|
||
[tool.flwr.federations.local-simulation] | ||
options.num-supernodes = 10 | ||
|
||
[tool.flwr.federations.local-simulation-gpu] | ||
options.num-supernodes = 10 | ||
options.backend.client-resources.num-cpus = 2 # each ClientApp assumes to use 2CPUs | ||
options.backend.client-resources.num-gpus = 0.2 # at most 5 ClientApp will run in a given GPU |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
"""vitexample: A Flower / PyTorch app with Vision Transformers.""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
"""vitexample: A Flower / PyTorch app with Vision Transformers.""" | ||
|
||
import torch | ||
from torch.utils.data import DataLoader | ||
|
||
from flwr.common import Context | ||
from flwr.client import NumPyClient, ClientApp | ||
|
||
|
||
from vitexample.task import apply_train_transforms, get_dataset_partition | ||
from vitexample.task import get_model, set_params, get_params, train | ||
|
||
|
||
class FedViTClient(NumPyClient): | ||
def __init__(self, trainloader, learning_rate, num_classes): | ||
self.trainloader = trainloader | ||
self.learning_rate = learning_rate | ||
self.model = get_model(num_classes) | ||
|
||
# Determine device | ||
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") | ||
self.model.to(self.device) # send model to device | ||
|
||
def fit(self, parameters, config): | ||
set_params(self.model, parameters) | ||
|
||
# Set optimizer | ||
optimizer = torch.optim.Adam(self.model.parameters(), lr=self.learning_rate) | ||
# Train locally | ||
avg_train_loss = train( | ||
self.model, self.trainloader, optimizer, epochs=1, device=self.device | ||
) | ||
# Return locally-finetuned part of the model | ||
return ( | ||
get_params(self.model), | ||
len(self.trainloader.dataset), | ||
{"train_loss": avg_train_loss}, | ||
) | ||
|
||
|
||
def client_fn(context: Context): | ||
"""Return a FedViTClient.""" | ||
|
||
# Read the node_config to fetch data partition associated to this node | ||
partition_id = context.node_config["partition-id"] | ||
num_partitions = context.node_config["num-partitions"] | ||
dataset_name = context.run_config["dataset-name"] | ||
trainpartition = get_dataset_partition(num_partitions, partition_id, dataset_name) | ||
|
||
batch_size = context.run_config["batch-size"] | ||
lr = context.run_config["learning-rate"] | ||
num_classes = context.run_config["num-classes"] | ||
trainset = trainpartition.with_transform(apply_train_transforms) | ||
|
||
trainloader = DataLoader( | ||
trainset, batch_size=batch_size, num_workers=2, shuffle=True | ||
) | ||
|
||
return FedViTClient(trainloader, lr, num_classes).to_client() | ||
|
||
|
||
app = ClientApp(client_fn=client_fn) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
"""vitexample: A Flower / PyTorch app with Vision Transformers.""" | ||
|
||
from logging import INFO | ||
|
||
import torch | ||
from datasets import Dataset, load_dataset | ||
from torch.utils.data import DataLoader | ||
|
||
from vitexample.task import apply_eval_transforms | ||
from vitexample.task import get_model, set_params, test, get_params | ||
|
||
from flwr.common import Context, ndarrays_to_parameters | ||
from flwr.common.logger import log | ||
from flwr.server import ServerApp, ServerConfig, ServerAppComponents | ||
from flwr.server.strategy import FedAvg | ||
|
||
|
||
def get_evaluate_fn( | ||
centralized_testset: Dataset, | ||
num_classes: int, | ||
): | ||
"""Return an evaluation function for centralized evaluation.""" | ||
|
||
def evaluate(server_round, parameters, config): | ||
"""Use the entire Oxford Flowers-102 test set for evaluation.""" | ||
|
||
# Determine device | ||
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") | ||
|
||
# Instantiate model and apply current global parameters | ||
model = get_model(num_classes) | ||
set_params(model, parameters) | ||
model.to(device) | ||
|
||
# Apply transform to dataset | ||
testset = centralized_testset.with_transform(apply_eval_transforms) | ||
|
||
testloader = DataLoader(testset, batch_size=128) | ||
# Run evaluation | ||
loss, accuracy = test(model, testloader, device=device) | ||
log(INFO, f"round: {server_round} -> acc: {accuracy:.4f}, loss: {loss: .4f}") | ||
|
||
return loss, {"accuracy": accuracy} | ||
|
||
return evaluate | ||
|
||
|
||
def server_fn(context: Context): | ||
|
||
# Define tested for central evaluation | ||
dataset_name = context.run_config["dataset-name"] | ||
dataset = load_dataset(dataset_name) | ||
test_set = dataset["test"] | ||
|
||
# Set initial global model | ||
num_classes = context.run_config["num-classes"] | ||
ndarrays = get_params(get_model(num_classes)) | ||
init_parameters = ndarrays_to_parameters(ndarrays) | ||
|
||
# Configure the strategy | ||
strategy = FedAvg( | ||
fraction_fit=0.5, # Sample 50% of available clients | ||
fraction_evaluate=0.0, # No federated evaluation | ||
evaluate_fn=get_evaluate_fn( | ||
test_set, num_classes | ||
), # Global evaluation function | ||
initial_parameters=init_parameters, | ||
) | ||
|
||
# Construct ServerConfig | ||
num_rounds = context.run_config["num-server-rounds"] | ||
config = ServerConfig(num_rounds=num_rounds) | ||
|
||
return ServerAppComponents(strategy=strategy, config=config) | ||
|
||
|
||
app = ServerApp(server_fn=server_fn) |
Oops, something went wrong.