Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create ClientApp fn example #3069

Merged
merged 27 commits into from
Mar 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
b896059
Introduce ClientApp train/evaluate/query
danieljanes Mar 5, 2024
9015ea9
Merge branch 'main' into register-client-app-fns
danieljanes Mar 6, 2024
16b93fd
Use MessageType
danieljanes Mar 6, 2024
a355581
Merge branch 'main' into register-client-app-fns
danieljanes Mar 6, 2024
857fcfa
Refactor __call__
danieljanes Mar 6, 2024
cc771a1
Merge branch 'register-client-app-fns' of github.com:adap/flower into…
danieljanes Mar 6, 2024
f9cacd2
Merge branch 'main' into register-client-app-fns
danieljanes Mar 6, 2024
d802321
Refactor error handling
danieljanes Mar 6, 2024
1733b09
Merge branch 'main' into register-client-app-fns
danieljanes Mar 6, 2024
6811ac8
Merge branch 'main' into register-client-app-fns
danieljanes Mar 6, 2024
bbbeb95
Add app-pytorch example for ClientApp functions
danieljanes Mar 6, 2024
aeee241
Merge branch 'register-client-app-fns' of github.com:adap/flower into…
danieljanes Mar 6, 2024
03e7b89
Use MessageType in server_custom
danieljanes Mar 6, 2024
83128d2
Merge branch 'main' into register-client-app-fns
danieljanes Mar 6, 2024
41075b2
Remove client_new
danieljanes Mar 6, 2024
984a992
Merge branch 'register-client-app-fns' of github.com:adap/flower into…
danieljanes Mar 6, 2024
281b4f7
Create ClientApp fn example
danieljanes Mar 6, 2024
fa2dd48
Improve wording
danieljanes Mar 7, 2024
9de20e1
Support mods
danieljanes Mar 7, 2024
053852c
Merge branch 'main' into register-client-app-fns
danieljanes Mar 7, 2024
5c0de89
Merge branch 'main' into register-client-app-fn-example
danieljanes Mar 8, 2024
a82c8ae
Merge branch 'register-client-app-fns' into register-client-app-fn-ex…
danieljanes Mar 8, 2024
d9db4b8
Add low-level example
danieljanes Mar 8, 2024
34ff644
Tweak messages
danieljanes Mar 8, 2024
9b9da08
Merge branch 'main' into register-client-app-fn-example
danieljanes Mar 8, 2024
d2bc32f
Merge branch 'main' into register-client-app-fn-example
danieljanes Mar 8, 2024
e4238d6
Update examples/app-pytorch/server_low_level.py
danieljanes Mar 8, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions examples/app-pytorch/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@

# Define Flower client
class FlowerClient(fl.client.NumPyClient):
def get_parameters(self, config: Dict[str, Scalar]) -> NDArrays:
return get_parameters(net)

def fit(self, parameters, config):
set_parameters(net, parameters)
Expand All @@ -42,3 +40,11 @@ def client_fn(cid: str):
app = fl.client.ClientApp(
client_fn=client_fn,
)


# Legacy mode
if __name__ == "__main__":
fl.client.start_client(
server_address="127.0.0.1:8080",
client=FlowerClient().to_client(),
)
35 changes: 35 additions & 0 deletions examples/app-pytorch/client_low_level.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import flwr
from flwr.common import Message, Context


def hello_world_mod(msg, ctx, call_next) -> Message:
print("Hello, ...[pause for dramatic effect]...")
out = call_next(msg, ctx)
print("...[pause was long enough]... World!")
return out


# Run via `flower-client-app client:app`
app = flwr.client.ClientApp(
mods=[
hello_world_mod,
],
)


@app.train()
def train(msg: Message, ctx: Context):
print("`train` is not implemented, echoing original message")
return msg.create_reply(msg.content, ttl="")


@app.evaluate()
def eval(msg: Message, ctx: Context):
print("`evaluate` is not implemented, echoing original message")
return msg.create_reply(msg.content, ttl="")


@app.query()
def query(msg: Message, ctx: Context):
print("`query` is not implemented, echoing original message")
return msg.create_reply(msg.content, ttl="")
24 changes: 22 additions & 2 deletions examples/app-pytorch/server.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from typing import List, Tuple

import flwr as fl
from flwr.common import Metrics
from flwr.common import Metrics, ndarrays_to_parameters
from task import Net, get_parameters


# Define metric aggregation function
Expand All @@ -25,17 +26,36 @@ def weighted_average(metrics: List[Tuple[int, Metrics]]) -> Metrics:
}


# Initialize model parameters
ndarrays = get_parameters(Net())
parameters = ndarrays_to_parameters(ndarrays)


# Define strategy
strategy = fl.server.strategy.FedAvg(
fraction_fit=1.0, # Select all available clients
fraction_evaluate=0.0, # Disable evaluation
min_available_clients=2,
fit_metrics_aggregation_fn=weighted_average,
initial_parameters=parameters,
)


# Define config
config = fl.server.ServerConfig(num_rounds=3)


# Run via `flower-server-app server:app`
app = fl.server.ServerApp(
config=fl.server.ServerConfig(num_rounds=3),
config=config,
strategy=strategy,
)


# Legacy mode
if __name__ == "__main__":
fl.server.start_server(
server_address="0.0.0.0:8080",
config=config,
strategy=strategy,
)
52 changes: 52 additions & 0 deletions examples/app-pytorch/server_low_level.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
from typing import List, Tuple, Dict
import random
import time

import flwr as fl
from flwr.common import Context, NDArrays, Message, MessageType, Metrics, RecordSet
from flwr.server import Driver


# Run via `flower-server-app server:app`
app = fl.server.ServerApp()


@app.main()
def main(driver: Driver, context: Context) -> None:
"""This is a stub example that simply sends and receives messages."""
print("Starting test run")
for server_round in range(3):
print(f"Commencing server round {server_round + 1}")

# Get node IDs
node_ids = driver.get_node_ids()

# Create messages
recordset = RecordSet()
messages = []
for node_id in node_ids:
message = driver.create_message(
content=recordset,
message_type=MessageType.TRAIN,
dst_node_id=node_id,
group_id=str(server_round),
ttl="",
)
messages.append(message)

# Send messages
message_ids = driver.push_messages(messages)
print(f"Pushed {len(message_ids)} messages: {message_ids}")

# Wait for results, ignore empty message_ids
message_ids = [message_id for message_id in message_ids if message_id != ""]
all_replies: List[Message] = []
while True:
replies = driver.pull_messages(message_ids=message_ids)
print(f"Got {len(replies)} results")
all_replies += replies
if len(all_replies) == len(message_ids):
break
time.sleep(3)

print(f"Received {len(all_replies)} results")