Quick Start
This tutorial runs a real federated-learning job on your machine: a server and two simulated clients train a small PyTorch model with FedAvg for three rounds. You then inspect the results, convert your own code, and run the same job in a local multi-process deployment.
1. Install NVFLARE
Create and activate a fresh virtual environment, then install one of:
python -m pip install "nvflare>=2.10.0"
# or, before 2.10.0 is released / for the latest code:
python -m pip install "git+https://github.com/NVIDIA/NVFlare.git@main"
See Installation for details.
2. Download the Hello PyTorch Example
nvflare examples get hello-pt
cd hello-pt
python -m pip install -r requirements.txt
nvflare examples get downloads the example from the exact Git revision recorded in your installed NVFLARE package, so the example always matches your version. It writes a .nvflare-example.json provenance file next to the example. If an older requirements.txt contains a line installing nvflare or nvflare-nightly, skip that line so your installed version is preserved.
The folder contains:
| File | Role |
|---|---|
job.py |
Builds a FedAvgRecipe and runs it in SimEnv. |
client.py |
The client training script, using the Client API. |
model.py |
The PyTorch model. |
prepare_data.py |
Synthetic or CIFAR-10 dataset helpers. |
3. Run the Simulation
python job.py --log_config progress
By default the job uses two clients (--n_clients 2), three rounds (--num_rounds 3), runs on CPU, and uses deterministic synthetic images generated independently at each client, so nothing is downloaded. --log_config progress keeps warnings and errors visible while focusing the console on rounds, client metrics, and result locations.
When the run finishes, the script prints lines similar to:
Simulation completed successfully.
Result can be found in : /tmp/nvflare/simulation/hello-pt
Note:
--log_config,--export, and--export-dirare consumed bynvflare.recipeat import time, before the script's own argument parser runs. That is whyjob.pylists the export flags in its help epilog instead of declaring them.
4. Understand What Happened
- The server sent the initial global model to both clients.
- Each client trained it on its own local data.
- Each client returned parameters, metrics, and its completed optimizer-step count (
NUM_STEPS_CURRENT_ROUND), which FedAvg uses as the aggregation weight. Raw samples never left the client processes. - FedAvg combined the updates into a new global model; this repeated for three rounds.
- After the last round, both clients evaluated the persisted final global model (the example calls
add_final_global_evaluation(recipe)).
5. Inspect the Results
The default simulator workspace is /tmp/nvflare/simulation/<job name>. For Hello PyTorch the key artifacts are:
Path (relative to /tmp/nvflare/simulation/hello-pt) |
Content |
|---|---|
server/simulate_job/app_server/FL_global_model.pt |
Final global model |
server/simulate_job/metrics/metrics_summary.json |
Aggregated per-round metrics and best-model metadata |
server/simulate_job/cross_site_val/cross_val_results.json |
Final model evaluation by site |
server/log.txt, site-1/log.txt, site-2/log.txt |
Detailed logs |
Metric values depend on the data and initialization; do not treat them as benchmarks.
6. Adapt Your Own Training Code
Wrap your training loop with the Client API:
import nvflare.client as flare
flare.init()
while flare.is_running():
input_model = flare.receive()
model.load_state_dict(input_model.params)
# existing local evaluation and training code
# steps = number of optimizer steps completed this round
output_model = flare.FLModel(
params={name: value.detach().cpu().clone() for name, value in model.state_dict().items()},
metrics={"accuracy": accuracy},
meta={"NUM_STEPS_CURRENT_ROUND": steps},
)
flare.send(output_model)
Then describe the job with a recipe in job.py:
from nvflare.app_opt.pt.recipes import FedAvgRecipe
from nvflare.recipe import SimEnv
recipe = FedAvgRecipe(
name="my-fedavg-job",
min_clients=2,
num_rounds=5,
model=MyModel(),
train_script="train.py",
)
run = recipe.execute(SimEnv(num_clients=2))
result = run.get_result()
7. Try a Local Deployment (POC)
The simulator runs everything in one workspace. A proof-of-concept (POC) deployment starts real server and client processes with certificates, the same way production does, but on one machine. There are two ways to use it.
From the recipe, replace SimEnv with PocEnv. It provisions a fresh workspace, starts the services, submits the job, and cleans up afterwards:
from nvflare.recipe import PocEnv
run = recipe.execute(PocEnv(num_clients=2))
print(run.get_result(clean_up=False)) # keep the workspace so the result path stays valid
From the CLI, keep a POC system running and submit exported jobs to it:
nvflare poc prepare -n 2
nvflare poc start
python job.py --export --export-dir /tmp/nvflare/jobs/hello-pt
nvflare job submit -j /tmp/nvflare/jobs/hello-pt
nvflare job list
nvflare poc stop
nvflare poc clean
nvflare job submit prints the new job ID. nvflare job wait <job_id> blocks until it finishes and nvflare job download <job_id> fetches the result. See poc and job.
Next Steps
- More hello-world examples:
nvflare examples list(for examplehello-numpy,hello-tf,hello-jax,hello-lightning,hello-huggingface,hello-cyclic,hello-dp,hello-tabular-stats,hello-collab). - Execution Environments to move from simulation to production.
- Provisioning to create a real federation.
- Troubleshooting if something did not work.