Nvflare Convert Lightning
NVIDIAOfficialCreated by NVIDIA FLARE Team
- Skill
- Workflow
- Software development
- Apache-2.0
- Medium risk
- Has scripts
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
Download the skill as a ZIP:
https://autogineer.com/agent-skills/nvidia/nvflare-convert-lightning/downloadUnzip 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:
During inspection,
references/lightning-detection.md.For generated splits, relative paths, or per-site data locations,
../nvflare-shared/references/site-data-and-paths.md.After
nvflare recipe show fedavg-pt --format json,../nvflare-shared/references/pytorch-family-recipe-construction.md.During conversion,
references/lightning-conversion.md, then../nvflare-shared/references/pytorch-model-exchange.md.Only after generated files exist,
../nvflare-shared/references/validation-evidence.md, thenreferences/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
Apply
../nvflare-shared/references/conversion-common.mdfor the whole conversion; this SKILL.md states only the framework-specific deltas.Inspect before editing with
nvflare agent inspect source <path> --format jsonplus direct reading; fact extraction is static. Confirm Lightning versus plain PyTorch and hand off tonvflare-convert-pytorchwhen no Lightning evidence exists. If inspection recommendsnvflare-orientfor active Lightning and Hugging Face Trainer owners, stop and hand off before editing.Apply the dependency-install ordering rule in
../nvflare-shared/references/conversion-common.mdbefore 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.Identify the existing
LightningModule,LightningDataModule, trainer construction, callbacks, checkpointing,validation_step/test_stepand 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.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 jsondirectly and construct it. Forfedavg-pt, importFedAvgRecipeonly fromnvflare.app_opt.pt.recipes.fedavg, never fromnvflare.recipe. Use FedEval for evaluation-only. After everyrecipe show, derive construction capabilities from the construction reference. Then use that documented path: do not run exploratory NVFLARE imports or useinspect,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. Callrecipe.execute(SimEnv(...)).Convert the training entry point to the Lightning Client API: build the
Trainer, callflare.patch(trainer), and let the patched trainer own model exchange. Keep evaluation inside Lightning perreferences/lightning-conversion.mdand useself.log. Deriveevaluate_only=Trueonly for FedEval; omit it for training recipes so its default staysFalse. Deriveevaluate_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.Add or update
job.pyunder the shared constructor-serialization rule. Use the recipe'sclass_pathorpathkey plus completeargswhen values are needed; a permitted zero-argument instance is the complete module. Add requestedaggregator=wiring and the metric, tensor-transport, server offload, and execution settings derived from the shared PyTorch-family construction profile. If sites need distincttrain_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.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.pyand 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.
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.mdfor 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.mdfor an ambiguous or non-FedAvg algorithm; use its catalog for FedAvg, FedOpt, FedProx, SCAFFOLD, Cyclic, Swarm, or FedEval, and reservenvflare recipe listfor these cases.../nvflare-shared/references/dependency-install.mdwhen an applicable dependency is missing.../nvflare-shared/references/runtime-output-guidance.mdfor a read-only source root or user-chosen output destination.references/lightning-ddp-and-tracking.mdwhen inspection finds its trigger.../nvflare-shared/references/metrics-and-artifact-reporting.mdwhen 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 manualFLModelsend/receive path as the default Lightning exchange, and must not pass the receivedinput_modelinto theTrainer.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 PyTorchmodel.eval()loop for ordinary Lightning conversion.Except for Cyclic, must run an explicit standalone
trainer.validate(...)beforetrainer.fit(...)and rely on the patched callback to attach its finite scalar metrics; never populatemodel.__fl_meta__[MetaKey.INITIAL_METRICS]. Validation insidetrainer.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.pyby reading theLightningModule.__init__signature and the selected recipe'smodelparameter fromnvflare recipe show <recipe-name> --format json, not by reading NVFLARE library source. Emit the recipe-documentedclass_pathorpathkey plus completeargsfor every required or overridden value. DirectLightningModuleuse 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
- ATTRIBUTION.mdAdded by AutoGineer944 B
- BENCHMARK.md11.7 KiB
- LICENSELicence file added by AutoGineer11.2 KiB
- SKILL.md12.9 KiB
- assets/lightning_client.pyScript5.4 KiB
- evals/config.yml295 B
- evals/evals.json66.0 KiB
- evals/files/SOURCE.md2.2 KiB
- evals/files/external-data-lightning/model.pyScript1.7 KiB
- evals/files/external-data-lightning/train.pyScript2.4 KiB
- evals/files/factory-lightning/train.pyScript1.3 KiB
- evals/files/gpu-device-lightning/model.pyScript1.2 KiB
- evals/files/gpu-device-lightning/train.pyScript1.1 KiB
- evals/files/hello-lightning/model.pyScript1.7 KiB
- evals/files/hello-lightning/train.pyScript1.1 KiB
- evals/files/routing-dual/train_huggingface.pyScript787 B
- evals/files/routing-dual/train_lightning.pyScript743 B
- evals/files/vocab-lightning/model.pyScript1.8 KiB
- evals/files/vocab-lightning/train.pyScript1.9 KiB
- references/lightning-conversion.md16.3 KiB
- references/lightning-ddp-and-tracking.md5.7 KiB
- references/lightning-detection.md3.0 KiB
- references/lightning-validation.md5.4 KiB
- skill-card.md4.1 KiB
- skill.oms.sig8.9 KiB
skill-card.md
Description: <br>
Convert existing PyTorch Lightning training code into an NVFLARE federated job using the Lightning Client API patch, local validation, and job export. <br>
This skill is ready for commercial/non-commercial use. <br>
Owner
NVIDIA <br>
License/Terms of Use: <br>
Apache 2.0 <br>
Use Case: <br>
Developers and ML engineers converting PyTorch Lightning training code into NVFLARE federated learning jobs for secure, privacy-preserving distributed multi-party collaboration. <br>
Deployment Geography for Use: <br>
Global <br>
Requirements / Dependencies: <br>
Requires API Key or External Credential: [Not Specified] <br> Credential Type(s): [None identified] <br>
Do not include secrets in prompts/logs/output; use least-privilege credentials; rotate keys as appropriate. <br>
Known Risks and Mitigations: <br>
Risk: Review before execution as proposals could introduce incorrect or misleading guidance into skills. <br> Mitigation: Review and scan skill before deployment. <br>
Reference(s): <br>
Skill Output: <br>
Output Type(s): [Code, Configuration instructions, Shell commands] <br> Output Format: [Python code and NVFLARE job configuration with inline shell commands] <br> Output Parameters: [1D] <br> Other Properties Related to Output: [None] <br>
Evaluation Agents Used: <br>
Claude Code (
aws/anthropic/bedrock-claude-opus-4-8) <br>Codex (
openai/openai/gpt-5.5) <br>
Evaluation Tasks: <br>
22 evaluation tasks (22 positive), each run in an isolated sandbox pod. Evaluator version 1.5.6. <br>
Evaluation Metrics Used: <br>
Reported benchmark dimensions: <br>
Security: Whether the skill is safe to use: checks for unsafe operations, secret leakage, and unauthorized access. <br>
Correctness: Whether the answer is correct against the reference answer. <br>
Discoverability: Whether the right skill was loaded when needed. <br>
Effectiveness: Whether the skill helped complete the user's goal, combining goal completion and expected workflow adherence. <br>
Efficiency: Whether the skill avoided wasted tool calls and token usage. <br>
Underlying evaluation signals used in this run: <br>
security: Unsafe operations, secret leakage, and unauthorized access. <br>skill_execution: Whether the expected skill was selected, decoys were avoided, and the workflow executed. <br>accuracy: Final-answer correctness against the reference answer. <br>goal_accuracy: Whether the user's goal was achieved. <br>behavior_check: Whether the expected workflow behavior was followed. <br>skill_efficiency: Tool-call productivity. <br>token_efficiency: Actual uncached prompt plus completion token usage. <br>
Evaluation Results: <br>
| Measure | Claude Code (Baseline → Skill Uplift) | Codex (Baseline → Skill Uplift) |
|---|---|---|
| Overall | 77.0% | 64.7% |
| Security | 54.6% → 70.5% (+15.9 points) | 18.2% → 36.4% (+18.2 points) |
| Correctness | 86.4% → 89.1% (+2.7 points) | 77.3% → 81.8% (+4.5 points) |
| Discoverability | 73.2% | 60.7% |
| Effectiveness | 72.7% → 78.4% (+5.7 points) | 61.2% → 74.8% (+13.6 points) |
| Efficiency | 73.9% | 69.9% |
Skill Version(s): <br>
0.1.0 (source: frontmatter) <br>
Ethical Considerations: <br>
NVIDIA believes Trustworthy AI is a shared responsibility and we have established policies and practices to enable development for a wide array of AI applications. When downloaded or used in accordance with our terms of service, developers should work with their internal team to ensure this skill meets requirements for the relevant industry and use case and addresses unforeseen product misuse. <br>
(For Release on NVIDIA Platforms Only) <br> Please report quality, risk, security vulnerabilities or NVIDIA AI Concerns here. <br>
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