Client API

The Client API (nvflare.client) is the recommended way to turn an existing training or evaluation script into a federated client. You keep your model, data loading, and training loop, and add a loop that receives the global model, trains, and sends the result back. This page documents every function, the FLModel structure, task handling, metric tracking, framework integrations, and the behaviors that commonly surprise new users.

The Basic Pattern

import nvflare.client as flare

flare.init()                                  # 1. connect to the FLARE runtime

while flare.is_running():                     # 2. loop until the job ends
    input_model = flare.receive()             # 3. get the task's FLModel
    params = input_model.params

    new_params, metrics = local_train(params) # 4. your own code

    flare.send(flare.FLModel(params=new_params, metrics=metrics))  # 5. return the result

The script does not know or care whether it is running in the simulator, POC, or production: the runtime injects the configuration. A recipe points to the script with train_script="client.py".

FLModel

FLModel (nvflare.client.FLModel, defined in nvflare.app_common.abstract.fl_model) is the object exchanged in both directions.

Field Type Description
params any (dict of arrays or tensors, typically) Model parameters.
params_type ParamsType.FULL, ParamsType.DIFF, or None What params contains. If you pass params but no type, it is treated as FULL.
optimizer_params any Optimizer state, rarely exchanged.
metrics dict or None Evaluation metrics such as loss and accuracy.
start_round int (default 0) The round training started from.
current_round int or None The round of the task; None for inference.
total_rounds int or None Total rounds planned by the server.
meta dict (default {}) Free-form metadata.

Validation rules in the constructor:

  • If params_type is FULL or DIFF, params must not be None (ValueError: params must be provided when params_type is ...).
  • metrics and meta must be dictionaries.
  • start_round, current_round, and total_rounds must be non-negative integers when set.

Printing an FLModel shows a summary (lengths of dicts, types of params) rather than the full weights.

Useful meta keys

NUM_STEPS_CURRENT_ROUND is the most important one: FedAvg uses it as the aggregation weight for that client's update. Report the number of optimizer steps (or samples) your client actually processed in the round:

flare.FLModel(params=weights, meta={"NUM_STEPS_CURRENT_ROUND": steps})

If you leave it out, updates are weighted equally.

API Reference

All functions accept an optional ctx argument to target a specific APIContext; normally you omit it and the default context created by init() is used.

Function Returns Description
init(rank=None, config_file=None) APIContext Initializes the Client API. Must be called before anything else.
receive(timeout=None) FLModel or None Returns the model for the current task, waiting for one if needed.
send(model, clear_cache=True) None Sends an FLModel back to FLARE.
is_running() bool True while the job continues and another task is available.
is_train() bool Whether the current task is the training task.
is_evaluate() bool Whether the current task is the evaluation task.
is_submit_model() bool Whether the current task asks for the local model.
system_info() dict System info, including job_id and site_name. Populated after a model is received.
get_config() dict The Client API configuration in use.
get_job_id() str Current job ID.
get_site_name() str This client's site name, for example site-1.
get_task_name() str Name of the current task.
log(key, value, data_type, **kwargs) bool Low-level metric logging; prefer the writers in nvflare.client.tracking.
shutdown() None Releases API threads and resources.

init(rank=None, config_file=None)

Creates (or reuses) the API context. rank is a global process rank used for distributed training: when omitted, the rank is resolved from an initialized Torch process group or from the launcher's RANK environment variable. Never pass a device-local rank. Calling init() again with the same arguments logs a warning (called init() more than once with same parameters) and returns the existing context.

Calling any other function before init() raises:

RuntimeError: APIContext is None. Did you call flare.init() before using the Client API?

receive(timeout=None)

Returns the FLModel for the current task. If a task is already cached (for example because is_running() fetched it), it is returned immediately. Otherwise it polls until a task arrives, the job ends, or timeout seconds pass. It returns None when the job is over or the API has been closed.

send(model, clear_cache=True)

Sends the result. Errors:

  • TypeError: model needs to be an instance of FLModel for any other type.
  • RuntimeError: "receive" needs to be called before sending model! if no task was received.
  • RuntimeError: the model to send does not have either params or metrics if both are None.

clear_cache=True clears the cached task after sending, so the next receive() waits for a new one. Pass False only if you need to send while keeping the received model cached.

is_running()

Not a passive status check: it fetches the next task (internally calling receive) and returns whether one is available. Call it once per loop iteration, as in the basic pattern.

Handling train, evaluate, and submit_model Tasks

Workflows such as cross-site evaluation send tasks other than training. A robust client branches on the task type:

while flare.is_running():
    input_model = flare.receive()
    model.load_state_dict(input_model.params)

    if flare.is_evaluate():
        metrics = evaluate(model)
        flare.send(flare.FLModel(metrics=metrics))   # metrics only, no training
        continue

    if flare.is_submit_model():
        flare.send(flare.FLModel(params=load_best_local_weights()))
        continue

    # training task
    steps = train(model)
    flare.send(
        flare.FLModel(
            params=model.state_dict(),
            metrics={"accuracy": evaluate(model)},
            meta={"NUM_STEPS_CURRENT_ROUND": steps},
        )
    )

This is required when you add add_cross_site_evaluation(recipe) to a PyTorch recipe: the helper's documentation states that the client must check flare.is_evaluate() and return metrics without training.

Note: is_train(), is_evaluate(), is_submit_model(), and get_task_name() raise RuntimeError: only rank 0 can call ... on any other rank. In multi-GPU training, decide on rank 0 and broadcast the decision.

Full Models versus Diffs

By default clients send full weights (TransferType.FULL). A recipe can set params_transfer_type=TransferType.DIFF; the Client API then computes the difference between your returned weights and the received global weights automatically before sending. If your FLModel explicitly sets params_type, that value is authoritative.

Logging Metrics

nvflare.client.tracking provides writers that mimic familiar tracking libraries. Metrics are streamed to the server (or kept on the client) where receivers configured with add_experiment_tracking() write them to TensorBoard, MLflow, or Weights & Biases.

Writer Methods
SummaryWriter add_scalar(tag, scalar, global_step=None), add_scalars(tag, scalars, global_step=None), flush()
WandBWriter log(metrics, step=None)
MLflowWriter log_param, log_params, log_metric(key, value, step=None), log_metrics(metrics, step=None), log_text(text, artifact_file_path), set_tag, set_tags
from nvflare.client.tracking import SummaryWriter

writer = SummaryWriter()
writer.add_scalar(tag="train_loss", scalar=avg_loss, global_step=global_step)

In job.py:

from nvflare.recipe import add_experiment_tracking

add_experiment_tracking(recipe, tracking_type="tensorboard")   # or "mlflow", "wandb"

add_experiment_tracking adds the receiver to the server by default (server_side=True); set client_side=True (optionally with clients=[...]) to track on clients instead.

In-Process versus External Process

Recipes run the script in the client job process by default (launch_external_process=False). That is fastest and the default for the simulator.

With launch_external_process=True, the script runs as a subprocess started with command (default python3 -u). Use this for torchrun or other launchers, for strict isolation, or for scripts that manage their own processes. Related recipe options:

Option Default Meaning
command "python3 -u" Command prefix, as a string or argv list. For multi-GPU, for example "torchrun --nproc_per_node=2".
launch_once True Launch once for the whole job, or once per task.
launch_timeout 300.0 Seconds to wait for the process to establish its Client API session; None disables.
shutdown_timeout 0.0 Seconds to wait before terminating the process at job end.

With the default shutdown_timeout of 0, the external process is terminated immediately at job end, so code after your loop may not run.

An independently managed trainer (one not started by FLARE) can also attach to a job; the repository's client-api-attach example (nvflare examples get client-api-attach) shows the pattern.

PyTorch Lightning

import nvflare.client.lightning as flare

flare.patch(trainer)            # one FL round per trainer.fit() call
while flare.is_running():
    trainer.validate(model, datamodule=dm)   # optional: evaluate the global model
    trainer.fit(model, datamodule=dm)

flare.patch(trainer, restore_state=True, load_state_dict_strict=True, update_fit_loop=True, sync_every_n_steps=None) installs a callback that loads each received model and sends the trained one.

Step-level synchronization

When one epoch takes hours, set sync_every_n_steps to exchange the model every N optimizer steps inside a single fit():

flare.patch(trainer, sync_every_n_steps=10)
trainer.fit(model, datamodule=dm)

In this mode the server's num_rounds decides how long training runs (the trainer's max_epochs and max_steps are lifted), each site reports N steps per round so FedAvg weights sites equally, restore_state and update_fit_loop have no effect, and train_with_evaluation is not supported. Size step-count-based LR schedulers such as OneCycleLR for num_rounds * sync_every_n_steps steps. When the script runs as an external process, set shutdown_timeout (for example 30 seconds); otherwise the process is killed while still inside fit().

Callbacks in trainer.callbacks can implement on_fl_receive, on_fl_model_loaded, and on_fl_before_send hooks.

Hugging Face Trainer

nvflare.client.hf provides patch() for a Hugging Face Trainer or TRL SFTTrainer, and its own is_running() that coordinates the FL loop around the patched trainer. The hello-huggingface example shows the full pattern (nvflare examples get hello-huggingface).

Deprecated Decorators

@flare.train and @flare.evaluate still exist but emit deprecation warnings (@flare.train is deprecated and will be removed in a future version. Use flare send/receive instead.). Use receive()/send() in new code.

Pitfalls

  • Sending tensors on the GPU or with autograd history. Detach and move to CPU (value.detach().cpu()) before building the FLModel; the examples do this for every state-dict entry.
  • Forgetting NUM_STEPS_CURRENT_ROUND. FedAvg then weights all clients equally regardless of how much data each processed.
  • Calling is_running() twice per iteration. Each call can fetch a task; use it only as the loop condition.
  • Training on evaluate tasks. With cross-site evaluation, return metrics only; otherwise a validation task returns trained weights.
  • Reading secrets from train_args. Arguments are written to the job config in clear text; see Job Recipes.

See Also