Generated banner for Nvflare Convert Lightning
Generated logo for Nvflare Convert Lightning

Nvflare Convert Lightning

NVIDIAOfficialCreated by NVIDIA FLARE Team

  • Skill
  • Workflow
  • Software development
  • Apache-2.0
  • Medium risk
  • Has scripts

From the author

Convert existing PyTorch Lightning training code into an NVFLARE federated job using the Lightning Client API patch, local validation, and job export; use only when the request names federated/NVFLARE conversion or asks multiple sites to train collaboratively while keeping each site's data local, and either names PyTorch Lightning or preliminary source inspection identifies one Lightning owner; do not use for non-federated Lightning work such as DDP, profiling, inference serving, or training-loop changes, nor for plain PyTorch, TensorFlow/Keras, other frameworks, deployment, POC/production lifecycle, or experiment workflows.
— the description by NVIDIA FLARE Team

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured procedure for transforming existing PyTorch Lightning training scripts into NVFLARE-compatible federated learning jobs. It focuses on integrating the Lightning Client API to enable collaborative training across multiple sites while ensuring data remains local. The process involves patching the Lightning Trainer, configuring the federated recipe, and validating the resulting job to ensure it meets the requirements for federated model exchange.

What it does

  • Inspects source code to confirm PyTorch Lightning usage and federated intent.
  • Patches the Lightning Trainer using the NVFLARE Client API for model exchange.
  • Constructs a federated job using the PyTorch recipe family.
  • Configures local validation and training loops for federated execution.
  • Supports DDP-based distributed training within the federated context.
  • Exports the final federated job for deployment or simulation.

When to use it

  • When you need to convert a PyTorch Lightning project into a federated learning job.
  • When multiple sites need to train collaboratively without sharing raw data.
  • When the project uses LightningModule, LightningDataModule, or standard Trainer loops.
  • When you require a validated, exportable federated training artifact.

Advantages

  • Maintains native PyTorch Lightning training logic and evaluation workflows.
  • Automates the integration of federated model exchange via patching.
  • Ensures consistent recipe construction using established PyTorch-family patterns.
  • Provides clear validation paths for both local simulation and deployment.

Usage examples

“Convert my PyTorch Lightning image classification script to run in an NVFLARE federated environment.”
The agent will inspect the code, apply the Lightning Client API patch, configure a FedAvg recipe, and generate a validated federated job.
“I have a multi-site project using Lightning; how do I set up federated training?”
The agent will guide you through the conversion process, ensuring the trainer is patched and the job is structured for collaborative training.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/nvidia/nvflare-convert-lightning/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip nvflare-convert-lightning.zip -d .agents/skills

Documentation by NVIDIA FLARE Team

NVFLARE Convert PyTorch Lightning

Use When

Use only when the user asks to convert PyTorch Lightning code into an NVFLARE federated training job; require both federation intent and Lightning ownership. Treat requests for multiple sites or institutions to train collaboratively while each site's data remains local as federation intent, even when the request does not say "federated" or "NVFLARE." Lightning source evidence alone is not sufficient. Relevant source may contain a LightningModule, LightningDataModule, a Trainer fit/validate/test loop, Lightning callbacks, checkpointing, or loggers. Supported: the PyTorch recipe family with flare.patch(trainer) as the model exchange integration, Lightning-native evaluation, custom aggregation through the same recipe aggregator= hook, and local validation and export.

Standard Path

Always read this converter SKILL.md with ../nvflare-shared/references/conversion-common.md. For an explicit-FedAvg conversion, load only these references, in workflow order:

  1. During inspection, references/lightning-detection.md.

  2. For generated splits, relative paths, or per-site data locations, ../nvflare-shared/references/site-data-and-paths.md.

  3. After nvflare recipe show fedavg-pt --format json, ../nvflare-shared/references/pytorch-family-recipe-construction.md.

  4. During conversion, references/lightning-conversion.md, then ../nvflare-shared/references/pytorch-model-exchange.md.

  5. Only after generated files exist, ../nvflare-shared/references/validation-evidence.md, then references/lightning-validation.md.

Complete each workflow phase before loading the next phase's reference. Do not enumerate reference directories or preload validation, DDP/tracking, broad workflow, dependency, runtime-output, or reporting references. Do not depend on NVFLARE repository examples.

Do Not Use When

Do not use for non-federated Lightning changes such as DDP-only configuration, profiling, inference serving, callbacks, early stopping, or schedulers; or for plain torch.nn.Module manual training loops without Lightning (route to nvflare-convert-pytorch), Hugging Face Trainer (route to nvflare-convert-huggingface), TensorFlow, XGBoost, scikit-learn, a failed job (route to nvflare-diagnose-job), federated statistics without training (route to nvflare-fed-stats), or generic Lightning debugging without FLARE intent; when the inspected project actively contains both Lightning and Hugging Face Trainer entrypoints, route to nvflare-orient. Out of conversion scope: production deployment, Kubernetes, POC lifecycle, deployment privacy/security policy design, custom distributed launch policies not expressible by product APIs, experiment tracking redesign, and experiment search across recipes. Privacy-protection requests — homomorphic encryption (HE) / encrypted aggregation, differential privacy, and privacy filters — are not supported: they require provisioning or deployment policy beyond conversion scope, so report such a request as unsupported and route it to provisioning/deployment, never substituting an unprotected recipe or 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

  1. Apply ../nvflare-shared/references/conversion-common.md for the whole conversion; this SKILL.md states only the framework-specific deltas.

  2. Inspect before editing with nvflare agent inspect source <path> --format json plus direct reading; fact extraction is static. Confirm Lightning versus plain PyTorch and hand off to nvflare-convert-pytorch when no Lightning evidence exists. If inspection recommends nvflare-orient for active Lightning and Hugging Face Trainer owners, stop and hand off before editing.

  3. Apply the dependency-install ordering rule in ../nvflare-shared/references/conversion-common.md before any Python command imports user, Lightning, NVFLARE, or declared dependency modules. Determine applicable dependencies from the selected execution path first. If required data artifacts already exist and static inspection shows that the selected path will not reach a download helper or its imports, treat its download-only requirements as inapplicable: do not install or import-probe them. Probe only modules the generated conversion and selected validation path will execute, and keep an optional probe separate and exit-zero when unavailable.

  4. Identify the existing LightningModule, LightningDataModule, trainer construction, callbacks, checkpointing, validation_step/test_step and dataloaders, metrics, logger usage, source partition evidence, distributed process-spawning evidence, custom aggregation intent, and the concrete model constructor values that server and clients must share.

  5. Reuse the PyTorch recipe family; Lightning is not a separate recipe family. For the standard case — the user explicitly requests FedAvg and inspection identifies Lightning — run nvflare recipe show fedavg-pt --format json directly and construct it. For fedavg-pt, import FedAvgRecipe only from nvflare.app_opt.pt.recipes.fedavg, never from nvflare.recipe. Use FedEval for evaluation-only. After every recipe show, derive construction capabilities from the construction reference. Then use that documented path: do not run exploratory NVFLARE imports or use inspect, hasattr, constant discovery, SDK source/docstring reads, or lifecycle probes. If a required detail is absent, report a skill gap or fail closed instead of guessing. Call recipe.execute(SimEnv(...)).

  6. Convert the training entry point to the Lightning Client API: build the Trainer, call flare.patch(trainer), and let the patched trainer own model exchange. Keep evaluation inside Lightning per references/lightning-conversion.md and use self.log. Derive evaluate_only=True only for FedEval; omit it for training recipes so its default stays False. Derive evaluate_before_train = recipe_algorithm != "cyclic": Cyclic persists only its final sequential model; every other algorithm uses explicit validation for server metrics and, for training, best-model selection. Verify the key in server evidence or fail closed.

  7. Add or update job.py under the shared constructor-serialization rule. Use the recipe's class_path or path key plus complete args when values are needed; a permitted zero-argument instance is the complete module. Add requested aggregator= wiring and the metric, tensor-transport, server offload, and execution settings derived from the shared PyTorch-family construction profile. If sites need distinct train_args, make every site override the complete argument string; never split shared arguments and a site-specific data path across recipe-level and per-site values expecting a merge.

  8. Immediately after generated files exist and before any preflight, smoke test, cleanup, validation, or execution command, load the two validation references in Standard Path order. Before executing a full run, select and record exactly one final validation target:

    • for a requested local or first-run simulation without an export claim, run python job.py and do not export or run the exported simulator afterward;

    • for a requested exported/deployable artifact, export first and run only the exported folder with the simulator CLI; do not first run python job.py. If the selected full-run target fails, diagnose it, apply a scoped fix, and rerun that same target. Change targets only when evidence shows the original target does not represent the requested artifact, and record that reason. Export inspection belongs only to the exported path. Keep cleanup, export, and simulation as separate tool calls; never combine recursive cleanup with execution. Stop at the first failed validation rung before diagnosing it; do not add speculative recovery probes. Use the environment and permission mechanisms supplied by the agent host; do not inspect or enforce its security boundary.

  9. Report the recipe, changed files, selected validation target, validation status, metrics, and exact artifact paths.

Non-standard Cases

Load only the reference matching an encountered case:

  • ../nvflare-shared/references/conversion-workflow.md for an unresolved non-standard rerun, authorization, or missing-semantics case; it no longer holds the data-location or partitioning contracts.

  • ../nvflare-shared/references/pytorch-family-recipe-selection.md for an ambiguous or non-FedAvg algorithm; use its catalog for FedAvg, FedOpt, FedProx, SCAFFOLD, Cyclic, Swarm, or FedEval, and reserve nvflare recipe list for these cases.

  • ../nvflare-shared/references/dependency-install.md when an applicable dependency is missing.

  • ../nvflare-shared/references/runtime-output-guidance.md for a read-only source root or user-chosen output destination.

  • references/lightning-ddp-and-tracking.md when inspection finds its trigger.

  • ../nvflare-shared/references/metrics-and-artifact-reporting.md when normal metric artifacts are absent or inconsistent.

Requirements

  • Must integrate through flare.patch(trainer) and let the patched trainer own model exchange. Must not generate a manual FLModel send/receive path as the default Lightning exchange, and must not pass the received input_model into the Trainer.

  • Must treat flare.receive() inside the patched loop as optional metadata or task-progression access only, not as a second model-load path.

  • Must keep evaluation inside Lightning (trainer.validate/trainer.test, validation_step, self.log); must not generate a raw PyTorch model.eval() loop for ordinary Lightning conversion.

  • Except for Cyclic, must run an explicit standalone trainer.validate(...) before trainer.fit(...) and rely on the patched callback to attach its finite scalar metrics; never populate model.__fl_meta__[MetaKey.INITIAL_METRICS]. Validation inside trainer.fit(...) is not a received-global-model metric. Cyclic must skip the pre-fit call and report its persisted final model, not a best model.

  • Must audit model constructor arguments before writing job.py by reading the LightningModule.__init__ signature and the selected recipe's model parameter from nvflare recipe show <recipe-name> --format json, not by reading NVFLARE library source. Emit the recipe-documented class_path or path key plus complete args for every required or overridden value. Direct LightningModule use is allowed only when unchanged zero-argument defaults reconstruct it. Values must be clear from source, configuration, or supplied metadata. Otherwise ask one semantic question when an answer channel exists or fail closed.

  • Must use the PyTorch recipe family; must not invent a Lightning-only recipe. Apply the construction reference after recipe show; it is canonical for optional recipe parameters, model selection, tensor transport, server disk offload, and execution mode.

  • Must preserve local-only callbacks and logger behavior where safe. Existing network-connected tracking, upload callbacks, and custom/unknown loggers are evidence, not a user request: keep them disabled during validation unless explicitly requested, and do not ask solely to enable them. This narrows references/lightning-conversion.md.

  • Must not make non-PyTorch-family skills load ../nvflare-shared/references/pytorch-model-exchange.md.

  • Site partitioning, custom aggregation, the Source Of Truth Boundary, and user input/authorization follow ../nvflare-shared/references/conversion-common.md.

Files

LICENSE

Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.


                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python

Security

What our scanner noticed· Medium risk

  • Large base64-encoded blobs
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
NVIDIA FLARE Team
Publisher
NVIDIA (Official)
Source
NVIDIA/skills · skills/nvflare-convert-lightning · commit fce3cca
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE-APACHE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by NVIDIA FLARE Team or NVIDIA.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download nvflare-convert-lightning.zip