Job Recipes
A Job Recipe is a Python object that builds a complete federated job (server workflow, client executors, model persistence, filters, metadata) from a handful of arguments. Recipes are the recommended way to define jobs: you write a short job.py, and the same recipe can be run in any execution environment or exported as a job folder for nvflare job submit. This page covers the recipe lifecycle, the built-in recipes, every common parameter of FedAvgRecipe, the helper functions, per-site configuration, secrets, and pitfalls.
- Recipe lifecycle
- Built-in recipes
- FedAvgRecipe parameters
- Specifying the initial model
- Recipe methods
- Helper functions
- Per-site configuration
- Keeping secrets out of recipes
- Exporting jobs
Recipe Lifecycle
from nvflare.app_opt.pt.recipes import FedAvgRecipe
from nvflare.recipe import SimEnv, add_experiment_tracking
# 1. construct
recipe = FedAvgRecipe(name="hello-pt", min_clients=2, num_rounds=3,
model=SimpleNetwork(), train_script="client.py")
# 2. customize (optional)
add_experiment_tracking(recipe, tracking_type="tensorboard")
# 3. run or export
run = recipe.execute(SimEnv(num_clients=2))
# 4. collect results
print(run.get_status(), run.get_result())
execute(env) is the usual entry point. It checks whether the script was started with --export:
| Command | Behavior |
|---|---|
python job.py |
Runs the job in env and returns a Run. |
python job.py --export |
Exports the job to ./fl_job, prints Job exported to: ./fl_job, and exits with status 0. |
python job.py --export --export-dir X |
Exports to X and exits. |
Before exporting or running, every recipe validates its state, prepares client apps, calls finalize(), and scans its parameters for values that look like secrets.
Built-in Recipes
Run nvflare recipe list to see the installed catalog with metadata, or nvflare recipe show <name> --format json for full parameter details. The main classes are:
| Recipe class | Import from | Purpose |
|---|---|---|
FedAvgRecipe |
nvflare.app_opt.pt.recipes |
FedAvg for PyTorch nn.Module models. |
FedProxRecipe |
nvflare.app_opt.pt.recipes |
FedAvg with a proximal term (fedprox_mu, default 0.01). |
FedOptRecipe |
nvflare.app_opt.pt.recipes, nvflare.app_opt.tf.recipes |
Server-side optimizer (FedOpt). |
ScaffoldRecipe |
nvflare.app_opt.pt.recipes, nvflare.app_opt.tf.recipes |
SCAFFOLD with control variates. |
CyclicRecipe |
nvflare.app_opt.pt.recipes, nvflare.app_opt.tf.recipes, nvflare.recipe.cyclic |
Cyclic (sequential) training across sites. |
FedEvalRecipe |
nvflare.app_opt.pt.recipes |
Federated evaluation of a model. |
FedCERecipe |
nvflare.app_opt.pt.recipes |
FedCE, contribution-weighted aggregation. |
FedAvgRecipeWithHE |
nvflare.app_opt.pt.recipes |
FedAvg with homomorphic encryption (needs the HE extra). |
SwarmLearningRecipe |
nvflare.app_opt.pt.recipes |
Decentralized swarm learning. |
FedAvgRecipe |
nvflare.app_opt.tf.recipes |
FedAvg for TensorFlow/Keras. |
NumpyFedAvgRecipe |
nvflare.app_common.np.recipes.fedavg |
FedAvg on NumPy arrays (no ML framework needed). |
NumpyCrossSiteEvalRecipe |
nvflare.app_common.np.recipes.cross_site_eval |
Standalone cross-site evaluation. |
FedAvgLrRecipe |
nvflare.app_common.np.recipes.lr.fedavg |
Federated logistic regression. |
SklearnFedAvgRecipe, KMeansFedAvgRecipe, SVMFedAvgRecipe |
nvflare.app_opt.sklearn.recipes |
scikit-learn linear models, k-means, SVM. |
XGBHorizontalRecipe, XGBVerticalRecipe, XGBBaggingRecipe |
nvflare.app_opt.xgboost.recipes |
Histogram-based horizontal, vertical, and bagging XGBoost. |
FedStatsRecipe |
nvflare.recipe.fedstats |
Federated statistics with privacy thresholds. |
FedTaskRecipe |
nvflare.recipe |
Run an arbitrary task script on clients. |
DhPSIRecipe |
nvflare.app_common.psi.recipes.dh_psi |
Diffie-Hellman private set intersection (needs PSI). |
FlowerRecipe |
nvflare.app_opt.flower.recipe |
Run a Flower app under FLARE. |
CollabRecipe, FedBuffRecipe |
nvflare.collab |
Collab API jobs and buffered asynchronous FedAvg. |
The generic nvflare.recipe.FedAvgRecipe is framework-neutral (selected with framework=); prefer the framework-specific classes, which accept native model objects.
FedAvgRecipe Parameters
All parameters are keyword-only. Most other recipes share the script-related ones.
| Parameter | Default | Description |
|---|---|---|
name |
"fedavg" |
Job name. Also the simulator workspace folder name. |
model |
None |
Initial model: a model instance or a {"class_path": ..., "args": {...}} dict. |
initial_ckpt |
None |
Absolute path to a pre-trained checkpoint; may exist only on the server. |
min_clients |
required | Minimum clients needed for a round. |
num_rounds |
2 |
Number of FL rounds. |
train_script |
required | Client script path. |
train_args |
"" |
Script arguments as a string or an argv list. Use a list when values contain spaces or quotes. |
aggregator |
None |
Custom aggregator; default is built-in streaming weighted averaging. |
aggregator_data_kind |
DataKind.WEIGHTS |
Data kind for aggregation. |
launch_external_process |
False |
Run the script as a subprocess. |
command |
"python3 -u" |
Subprocess command prefix. |
server_expected_format |
NumPy | Exchange format on the server side. |
params_transfer_type |
TransferType.FULL |
FULL or DIFF. |
model_persistor |
None |
Custom persistor; PyTorch defaults to PTFileModelPersistor. |
launch_once |
True |
External process launched once per job or once per task. |
launch_timeout |
300.0 |
Seconds to wait for an external process session. |
shutdown_timeout |
0.0 |
Seconds to wait before killing the external process. |
key_metric |
"accuracy" |
Metric used to select the best global model. |
key_metric_mode |
inferred / "max" |
"min" or "max". Inferred from stop_cond when it uses the same metric. |
stop_cond |
None |
Early stopping expression, for example "accuracy >= 80". |
patience |
None |
Rounds without improvement before stopping (with stop_cond). |
best_model_filename |
persistor default | File name for the best model. save_filename is a deprecated alias. |
exclude_vars |
None |
Regex of variables excluded from aggregation. |
aggregation_weights |
equal | Per-client weight dict. |
server_memory_gc_rounds |
0 |
Run gc.collect and malloc_trim on the server every N rounds. |
client_memory_gc_rounds |
0 |
The same on clients. |
cuda_empty_cache |
False |
Empty the CUDA cache on clients during memory cleanup. |
sampling_seed |
None |
Seed for client sampling when min_clients is below the connected count. |
enable_tensor_disk_offload |
False |
Receive streamed tensors through temporary files. |
execution_lifetime |
"job" |
"job" or "task"; see Concepts. |
The PyTorch class also accepts model_locator and enable_disk_aggregation (tensor-at-a-time aggregation with safetensors persistence; it requires initial_ckpt).
The aggregation is "InTime": each client result is accumulated as soon as it arrives, so server memory stays constant regardless of the number of clients.
Note: For TensorFlow and NumPy FedAvg recipes,
best_model_filenameandsave_filenameare accepted but produce a warning: their default persistors do not create a separate best-model file.
Specifying the Initial Model
# 1. an instance
model=SimpleNetwork()
# 2. a class path, instantiated at runtime
model={"class_path": "model.SimpleNetwork", "args": {}}
# 3. weights from a checkpoint on the server
model=SimpleNetwork(), initial_ckpt="/server/path/to/pretrained.pt"
initial_ckpt must be an absolute path. It is not required to exist on the machine that builds the job, since it is read on the server.
Recipe Methods
| Method | Description |
|---|---|
execute(env, server_exec_params=None, client_exec_params=None) |
Run, or export when --export was given. |
run(env, ...) |
Always run; returns a Run. |
export(job_dir, server_exec_params=None, client_exec_params=None, env=None) |
Write the job folder. |
add_client_config(config, clients=None) |
Add top-level keys to config_fed_client.json. |
add_server_config(config) |
Add top-level keys to config_fed_server.json. |
add_client_file(file_path, clients=None) / add_server_file(file_path) |
Bundle a file or directory into the app's custom folder. |
add_client_input_filter(filter, tasks=None, clients=None) |
Filter incoming tasks on clients. |
add_client_output_filter(filter, tasks=None, clients=None) |
Filter outgoing results on clients. |
add_server_input_filter(filter, tasks=None) / add_server_output_filter(filter, tasks=None) |
Filters on the server. |
add_decomposers(decomposers) |
Register serialization decomposers (class names or instances) on server and clients. |
enable_log_streaming(*file_names) |
Stream client log files (default log.json) to the server while the job runs. |
set_per_site_config(config) |
See Per-site configuration. |
configured_sites() |
Site names from per-site configuration (does not query any environment). |
Log streaming is still gated per site by allow_log_streaming in the site's resources.json.
The Run Object
execute() and run() return a nvflare.recipe.Run:
| Method | Description |
|---|---|
get_job_id() |
The job ID (for SimEnv, the job name). |
get_status() |
The current status string, or None on error. |
get_result(timeout=0.0, clean_up=True, outputs_only=False) |
Waits for completion, prints a summary, stops the environment, and returns the result path. |
abort() |
Aborts the job; a no-op once the environment is stopped. |
get_result() stops the environment. With the default clean_up=True, PocEnv deletes its workspace, so the returned path may already be gone. Pass clean_up=False to keep it. outputs_only=True downloads only server-produced outputs (models, metrics, evaluation results) without the job's code, config, or logs; the simulator ignores it. After the first call, the status and result are cached and returned again.
The summary printed by get_result() starts with one of ✓ Completed, ✗ Failed, ✗ Not scheduled, or ■ Aborted, followed by a results line.
Helper Functions
All are importable from nvflare.recipe.
add_experiment_tracking(recipe, tracking_type, tracking_config=None, client_side=False, server_side=True, clients=None)
Adds metric receivers. tracking_type is "mlflow", "tensorboard", or "wandb". For MLflow, omitting tracking_config uses a local file store with experiment and run names derived from the recipe name.
add_cross_site_evaluation(recipe, submit_model_timeout=600, validation_timeout=6000, participating_clients=None)
After training, each client's local model and the global model are evaluated on every site. It auto-detects the framework and adds the model locator, the CrossSiteModelEval controller, and a JSON result generator. Calling it twice raises RuntimeError. PyTorch client scripts must handle flare.is_evaluate().
add_final_global_evaluation(recipe, participating_clients=None, validation_timeout=6000)
Evaluates only the final persisted global model on selected clients (clients are not asked for local models). PyTorch recipes only; raises RuntimeError if a cross-site evaluation workflow is already configured.
set_per_site_config(recipe, config)
Equivalent to recipe.set_per_site_config(config).
set_recipe_meta(recipe, key, value)
Sets one user-settable meta.json key (for example SCOPE, RESOURCE_SPEC, CJ_RESOURCE_SPEC, JOB_LAUNCHER_SPEC, CUSTOM_PROPS). MIN_CLIENTS, MANDATORY_CLIENTS, and STUDY are rejected: the first two belong in the constructor, and the study is assigned by the server from the submitting session.
is_export_requested()
Returns whether --export was consumed when nvflare.recipe was imported. Useful for validating script options, as Hello PyTorch does for --execution_lifetime task.
Per-Site Configuration
Give different clients different scripts or arguments:
from nvflare.recipe import set_per_site_config
recipe = FedAvgRecipe(name="hetero", min_clients=2, model=Net(), train_script="client.py")
set_per_site_config(recipe, {
"site-1": {"train_args": "--data_path /data/a"},
"site-2": {"train_args": "--data_path /data/b", "launch_external_process": True},
})
Rules enforced by the code:
- The config must be a non-empty dict of dicts keyed by site name.
- It must be applied immediately after construction, before any client config, file, filter, or component is added; otherwise
RuntimeError: per-site config must be applied immediately after recipe construction .... - It can be applied only once.
serverand@ALLare reserved names and cannot be used as keys.- Targeting specific clients with
clients=[...]in methods likeadd_client_configonly works when per-site apps exist; with a single all-clients app it raisesValueError: cannot target specific clients ....
The constructor argument per_site_config= still works but is deprecated.
Keeping Secrets Out of Recipes
Recipe parameters, train_args, per-site config, and config dicts are written in clear text into the exported job. Never put passwords or API keys in them. Use a placeholder that the executing site resolves at runtime:
from nvflare.recipe import secret_ref, secret_file_ref
recipe = FedAvgRecipe(
...,
train_args=f"--epochs 5 --api-key {secret_ref('MY_API_KEY')}", # site environment variable
)
recipe.add_client_config(
{"service_password": secret_file_ref("/var/run/secrets/service/password")} # site file
)
References are resolved only at two boundaries: script/subprocess arguments (immediately before the process starts), and values read from job config with nvflare.utils.configs.get_job_config_value (or get_client_config_value / get_server_config_value). Elsewhere, such as component constructor arguments and metadata, they are not resolved, and a UnsupportedSecretRefWarning is emitted. Values that merely look like secrets trigger a best-effort PotentialSecretWarning; absence of a warning does not prove safety. The subprocess launcher refuses references in command strings for directly invoked sh, bash, or PowerShell.
Exporting Jobs
python job.py --export --export-dir /tmp/nvflare/jobs/my_job
nvflare job submit -j /tmp/nvflare/jobs/my_job
Your script must not define its own --export or --export-dir arguments: NVFLARE consumes them before your parser runs and warns if it finds such declarations. --export-dir without --export is ignored with a warning.
Pitfalls
--log_configis also consumed at import time. A script that declares its own--log_configargument will always seeNonefor it, but the value still takes effect, becauseSimEnvuses the consumed value with priority over its constructor argument.namebecomes a folder name on the server; job folder names may contain only letters, numbers, dots, underscores, and hyphens.- Keep
min_clientsno larger than the number of clients your environment provides (SimEnv(num_clients=...),PocEnv(num_clients=...), or the connected production sites); a round needs at least that many clients.