NVFLARE Convert PyTorch
Use When
Use when converting an existing plain PyTorch training script, torch.nn.Module,
manual training loop, state_dict workflow, data loader, checkpoint, or metric loop
into an NVFLARE federated training job. Supports horizontal FL, Client API model
exchange with FLModel, recipe aggregator= hooks, validation, and export.
Do Not Use When
Do not use for PyTorch Lightning (route to nvflare-convert-lightning), Hugging Face Trainer (route to nvflare-convert-huggingface), TensorFlow, XGBoost,
scikit-learn, failed jobs (route to
nvflare-diagnose-job), federated statistics without training (route to
nvflare-fed-stats), or generic PyTorch debugging without FLARE intent. Out of
scope: production deployment, Kubernetes, POC lifecycle, privacy/security policy design,
controller/workflow rewrites outside recipe or Job APIs, experiment search, and
data distribution experiments beyond minimal validation setup. Privacy-protection
requests — HE/encrypted aggregation, differential privacy, and privacy filters — need provisioning/deployment
policy; route onward rather than substituting an unprotected recipe or adding only a disclaimer.
If a request combines federated statistics and model-training conversion,
treat it as two independent jobs and workflows: do not merge or automatically
chain them, do not route the combination to nvflare-orient, and ask which
workflow to run first before generating or running either job. Recommend
nvflare-fed-stats first only when the user's purpose is to understand data
distribution; handle conversion later as a separate request.
Workflow
- Load
../nvflare-shared/references/conversion-common.md and apply it for the
whole conversion; this SKILL.md states only the framework-specific deltas.
Load ../nvflare-shared/references/conversion-workflow.md only for a non-standard
rerun, authorization, or missing-semantics case; it no longer holds the
data-location or partitioning contracts, whose invariants conversion-common.md
owns. Load ../nvflare-shared/references/site-data-and-paths.md for generated
partitions, relative paths, or per-site data locations.
- Inspect before editing with
nvflare agent inspect source <path> --format json
plus direct reading. Fact extraction is static; do not import or execute
user training modules to discover fields. Extract: training entrypoint,
model class path and constructor args, checkpoint behavior, train/eval
functions, data loading, metric names and denominators, local epochs/steps,
requested client and round counts, source data split or partition evidence,
tracking evidence, DDP evidence, and any custom aggregation intent.
- Apply the dependency-install ordering rule in
../nvflare-shared/references/conversion-common.md before
any Python command imports user, PyTorch, NVFLARE, or declared dependency
modules.
- Select the recipe from the requested FL workflow, not from PyTorch alone. For
the standard case — the user explicitly requests FedAvg and inspection
identifies PyTorch — run
nvflare recipe show fedavg-pt --format json
directly and construct it; do not add per-site recipe config unless sites
actually differ. Load
../nvflare-shared/references/pytorch-family-recipe-selection.md (discovery,
algorithm guide, catalog-based selection, HE-not-supported rule) only for
ambiguous or non-FedAvg algorithms, reserving nvflare recipe list for those
cases. Use the module, class, and parameters returned by recipe show for
standard job.py construction; for fedavg-pt, import FedAvgRecipe from
nvflare.app_opt.pt.recipes.fedavg, never from nvflare.recipe. After every
recipe show, load
../nvflare-shared/references/pytorch-family-recipe-construction.md and
derive the recipe's construction capabilities. Load
references/recipe-selection.md only when non-FedAvg or execution-mode
details are needed.
- Convert training and evaluation as a pair using
references/pytorch-client-api-conversion.md: initialize FLARE, receive an
FLModel, load params, evaluate the received global model, train, and
send an FLModel with updated params, metrics, and the actual completed
local optimizer-step count in NUM_STEPS_CURRENT_ROUND. Adapt the user's
evaluation code into the packaged evaluation template; if evaluation is
required but missing, ask or fail closed. Apply the step-1 data-location
rules to the generated client's data argument.
- Add or update
job.py under the shared constructor-serialization rule:
use explicit class_path (or documented path alias) plus complete args
whenever reconstruction needs values. Add requested aggregator= wiring,
metric, tensor-transport, server offload, and execution settings derived
from the shared PyTorch-family construction profile.
- Validate in a ladder per
../nvflare-shared/references/validation-evidence.md:
compile checks, recipe construction, one final full-run path chosen by the
artifact being validated, with export and package inspection only for the
selected exported-artifact path. For a local target, inspect the materialized
configs and packaging evidence after that run. Use
references/job-validation.md for PyTorch-specific failures. Stop at the
first failed rung and report the product error. Use the environment and
permission mechanisms supplied by the agent host; do not inspect or enforce
its security boundary.
- Report the recipe, changed files, validation status, metrics, and exact
artifact paths. Load
../nvflare-shared/references/metrics-and-artifact-reporting.md only when
normal metric artifacts are absent or inconsistent.
Requirements
- Must audit model constructor arguments before writing
job.py by reading the
model module's __init__ and the selected recipe's model parameter from
nvflare recipe show <recipe-name> --format json, not by reading NVFLARE
library source. Emit the selected recipe's documented class_path or path
key plus complete args for every required or overridden constructor value;
a direct torch.nn.Module is allowed only when
unchanged zero-argument defaults reconstruct it. Values must be statically
clear from literal source, configuration, or supplied metadata. Otherwise ask
one semantic question when an answer channel exists or fail closed.
- Must follow
../nvflare-shared/references/pytorch-model-exchange.md and
references/pytorch-client-api-conversion.md for the canonical plain-PyTorch
payload and round-loop pattern.
- Must apply
../nvflare-shared/references/pytorch-family-recipe-construction.md after
recipe show; it is the canonical policy for optional recipe parameters,
model selection, tensor transport, server disk offload, and execution mode.
Never patch a framework-neutral runtime module or register FOBS handlers in
client.py.
- Must convert source evaluation alongside training and return metrics through
FLModel.metrics; must not synthesize metric semantics without source
evidence.
- Must count completed local optimizer steps in each generated training round
and send that positive value as
MetaKey.NUM_STEPS_CURRENT_ROUND. This is the
FedAvg aggregation weight; do not omit it, reuse a cumulative count, or
invent a value when the source loop cannot establish it.
- Must load checkpoints with
torch.load(..., weights_only=True); a
checkpoint that needs full unpickling is ask/fail, per
references/pytorch-client-api-conversion.md.
- Must not make non-PyTorch-family skills load
../nvflare-shared/references/pytorch-model-exchange.md; that reference is
for plain PyTorch, PyTorch Lightning, and Hugging Face Trainer model/state-dict
exchange only.
- Site partitioning, custom aggregation, the Source Of Truth Boundary, and user
input/authorization follow
../nvflare-shared/references/conversion-common.md.
Always read this converter SKILL.md together with
../nvflare-shared/references/conversion-common.md. The standard routing,
recipe selection, and reporting path is inline, so common FedAvg does not load
broad policy or algorithm-selection references. Load the client template,
model-exchange reference, validation reference, and aggregator asset only when
their phase needs them. Load other detailed references only for exceptions:
../nvflare-shared/references/conversion-workflow.md for the full conversion
contract when a case is non-standard;
../nvflare-shared/references/site-data-and-paths.md only for generated site
partitions, relative-path resolution, or per-site data locations;
../nvflare-shared/references/pytorch-family-recipe-selection.md only for
ambiguous or non-FedAvg algorithms, and references/recipe-selection.md only
for non-FedAvg or execution-mode construction details not supplied by
recipe show;
../nvflare-shared/references/pytorch-family-recipe-construction.md after
every recipe show;
../nvflare-shared/references/dependency-install.md only when an install is
needed;
../nvflare-shared/references/runtime-output-guidance.md only for read-only
source roots or user-chosen output destinations;
../nvflare-shared/references/metrics-and-artifact-reporting.md only when
metrics are absent or inconsistent;
../nvflare-shared/references/validation-evidence.md before validation, and
../nvflare-shared/references/pytorch-model-exchange.md only for PyTorch-family exchange;
references/pytorch-client-api-conversion.md for Client API conversion, and
references/job-validation.md for PyTorch-specific validation failures.
Do not load every reference preemptively, and do not depend on NVFLARE
repository examples being present in the user's environment.
1---2name: nvflare-convert-pytorch3description: Convert existing plain or manual PyTorch training code into an NVFLARE federated job using Client API model exchange, local validation, and job export; use when the user names plain PyTorch or preliminary source inspection identifies one plain-PyTorch owner, and not for Lightning, other frameworks, deployment, POC/production lifecycle, or experiment workflows.4license: Apache-2.05---67# NVFLARE Convert PyTorch89## Use When1011Use when converting an existing plain PyTorch training script, `torch.nn.Module`,12manual training loop, `state_dict` workflow, data loader, checkpoint, or metric loop13into an NVFLARE federated training job. Supports horizontal FL, Client API model14exchange with `FLModel`, recipe `aggregator=` hooks, validation, and export.1516## Do Not Use When1718Do not use for PyTorch Lightning (route to `nvflare-convert-lightning`), Hugging Face Trainer (route to `nvflare-convert-huggingface`), TensorFlow, XGBoost,19scikit-learn, failed jobs (route to20`nvflare-diagnose-job`), federated statistics without training (route to21`nvflare-fed-stats`), or generic PyTorch debugging without FLARE intent. Out of22scope: production deployment, Kubernetes, POC lifecycle, privacy/security policy design,23controller/workflow rewrites outside recipe or Job APIs, experiment search, and24data distribution experiments beyond minimal validation setup. Privacy-protection25requests — HE/encrypted aggregation, differential privacy, and privacy filters — need provisioning/deployment26policy; route onward rather than substituting an unprotected recipe or adding only a disclaimer.27If a request combines federated statistics and model-training conversion,28treat it as two independent jobs and workflows: do not merge or automatically29chain them, do not route the combination to `nvflare-orient`, and ask which30workflow to run first before generating or running either job. Recommend31`nvflare-fed-stats` first only when the user's purpose is to understand data32distribution; handle conversion later as a separate request.3334## Workflow35361. Load `../nvflare-shared/references/conversion-common.md` and apply it for the37 whole conversion; this SKILL.md states only the framework-specific deltas.38 Load `../nvflare-shared/references/conversion-workflow.md` only for a non-standard39 rerun, authorization, or missing-semantics case; it no longer holds the40 data-location or partitioning contracts, whose invariants `conversion-common.md`41 owns. Load `../nvflare-shared/references/site-data-and-paths.md` for generated42 partitions, relative paths, or per-site data locations.432. Inspect before editing with `nvflare agent inspect source <path> --format json`44 plus direct reading. Fact extraction is static; do not import or execute45 user training modules to discover fields. Extract: training entrypoint,46 model class path and constructor args, checkpoint behavior, train/eval47 functions, data loading, metric names and denominators, local epochs/steps,48 requested client and round counts, source data split or partition evidence,49 tracking evidence, DDP evidence, and any custom aggregation intent.503. Apply the dependency-install ordering rule in `../nvflare-shared/references/conversion-common.md` before51 any Python command imports user, PyTorch, NVFLARE, or declared dependency52 modules.534. Select the recipe from the requested FL workflow, not from PyTorch alone. For54 the standard case — the user explicitly requests FedAvg and inspection55 identifies PyTorch — run `nvflare recipe show fedavg-pt --format json`56 directly and construct it; do not add per-site recipe config unless sites57 actually differ. Load58 `../nvflare-shared/references/pytorch-family-recipe-selection.md` (discovery,59 algorithm guide, catalog-based selection, HE-not-supported rule) only for60 ambiguous or non-FedAvg algorithms, reserving `nvflare recipe list` for those61 cases. Use the module, class, and parameters returned by `recipe show` for62 standard `job.py` construction; for `fedavg-pt`, import `FedAvgRecipe` from63 `nvflare.app_opt.pt.recipes.fedavg`, never from `nvflare.recipe`. After every64 `recipe show`, load65 `../nvflare-shared/references/pytorch-family-recipe-construction.md` and66 derive the recipe's construction capabilities. Load67 `references/recipe-selection.md` only when non-FedAvg or execution-mode68 details are needed.695. Convert training and evaluation as a pair using70 `references/pytorch-client-api-conversion.md`: initialize FLARE, receive an71 `FLModel`, load `params`, evaluate the received global model, train, and72 send an `FLModel` with updated `params`, `metrics`, and the actual completed73 local optimizer-step count in `NUM_STEPS_CURRENT_ROUND`. Adapt the user's74 evaluation code into the packaged evaluation template; if evaluation is75 required but missing, ask or fail closed. Apply the step-1 data-location76 rules to the generated client's data argument.776. Add or update `job.py` under the shared constructor-serialization rule:78 use explicit `class_path` (or documented `path` alias) plus complete `args`79 whenever reconstruction needs values. Add requested `aggregator=` wiring,80 metric, tensor-transport, server offload, and execution settings derived81 from the shared PyTorch-family construction profile.827. Validate in a ladder per `../nvflare-shared/references/validation-evidence.md`:83 compile checks, recipe construction, one final full-run path chosen by the84 artifact being validated, with export and package inspection only for the85 selected exported-artifact path. For a local target, inspect the materialized86 configs and packaging evidence after that run. Use87 `references/job-validation.md` for PyTorch-specific failures. Stop at the88 first failed rung and report the product error. Use the environment and89 permission mechanisms supplied by the agent host; do not inspect or enforce90 its security boundary.918. Report the recipe, changed files, validation status, metrics, and exact92 artifact paths. Load93 `../nvflare-shared/references/metrics-and-artifact-reporting.md` only when94 normal metric artifacts are absent or inconsistent.9596## Requirements9798- Must audit model constructor arguments before writing `job.py` by reading the99 model module's `__init__` and the selected recipe's `model` parameter from100 `nvflare recipe show <recipe-name> --format json`, not by reading NVFLARE101 library source. Emit the selected recipe's documented `class_path` or `path`102 key plus complete `args` for every required or overridden constructor value;103 a direct `torch.nn.Module` is allowed only when104 unchanged zero-argument defaults reconstruct it. Values must be statically105 clear from literal source, configuration, or supplied metadata. Otherwise ask106 one semantic question when an answer channel exists or fail closed.107- Must follow `../nvflare-shared/references/pytorch-model-exchange.md` and108 `references/pytorch-client-api-conversion.md` for the canonical plain-PyTorch109 payload and round-loop pattern.110- Must apply111 `../nvflare-shared/references/pytorch-family-recipe-construction.md` after112 `recipe show`; it is the canonical policy for optional recipe parameters,113 model selection, tensor transport, server disk offload, and execution mode.114 Never patch a framework-neutral runtime module or register FOBS handlers in115 `client.py`.116- Must convert source evaluation alongside training and return metrics through117 `FLModel.metrics`; must not synthesize metric semantics without source118 evidence.119- Must count completed local optimizer steps in each generated training round120 and send that positive value as `MetaKey.NUM_STEPS_CURRENT_ROUND`. This is the121 FedAvg aggregation weight; do not omit it, reuse a cumulative count, or122 invent a value when the source loop cannot establish it.123- Must load checkpoints with `torch.load(..., weights_only=True)`; a124 checkpoint that needs full unpickling is ask/fail, per125 `references/pytorch-client-api-conversion.md`.126- Must not make non-PyTorch-family skills load127 `../nvflare-shared/references/pytorch-model-exchange.md`; that reference is128 for plain PyTorch, PyTorch Lightning, and Hugging Face Trainer model/state-dict129 exchange only.130- Site partitioning, custom aggregation, the Source Of Truth Boundary, and user131 input/authorization follow `../nvflare-shared/references/conversion-common.md`.132133Always read this converter SKILL.md together with134`../nvflare-shared/references/conversion-common.md`. The standard routing,135recipe selection, and reporting path is inline, so common FedAvg does not load136broad policy or algorithm-selection references. Load the client template,137model-exchange reference, validation reference, and aggregator asset only when138their phase needs them. Load other detailed references only for exceptions:139140- `../nvflare-shared/references/conversion-workflow.md` for the full conversion141 contract when a case is non-standard;142- `../nvflare-shared/references/site-data-and-paths.md` only for generated site143 partitions, relative-path resolution, or per-site data locations;144- `../nvflare-shared/references/pytorch-family-recipe-selection.md` only for145 ambiguous or non-FedAvg algorithms, and `references/recipe-selection.md` only146 for non-FedAvg or execution-mode construction details not supplied by147 `recipe show`;148- `../nvflare-shared/references/pytorch-family-recipe-construction.md` after149 every `recipe show`;150- `../nvflare-shared/references/dependency-install.md` only when an install is151 needed;152- `../nvflare-shared/references/runtime-output-guidance.md` only for read-only153 source roots or user-chosen output destinations;154- `../nvflare-shared/references/metrics-and-artifact-reporting.md` only when155 metrics are absent or inconsistent;156- `../nvflare-shared/references/validation-evidence.md` before validation, and157 `../nvflare-shared/references/pytorch-model-exchange.md` only for PyTorch-family exchange;158- `references/pytorch-client-api-conversion.md` for Client API conversion, and159 `references/job-validation.md` for PyTorch-specific validation failures.160161Do not load every reference preemptively, and do not depend on NVFLARE162repository examples being present in the user's environment.