Generated banner for Nvflare Convert Huggingface
Generated logo for Nvflare Convert Huggingface

Nvflare Convert Huggingface

NVIDIAOfficialCreated by NVIDIA FLARE Team

  • Skill
  • Tool integration
  • Automation and integrations
  • Apache-2.0
  • Medium risk
  • Has scripts

From the author

Convert existing Hugging Face Transformers Trainer or TRL SFTTrainer training code into an NVFLARE federated job using flare.patch(trainer), local validation, and job export; use when the user names Hugging Face or preliminary source inspection identifies one Hugging Face owner, and not for manual PyTorch loops, Lightning, inference-only pipelines, deployment, 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 migrating existing Hugging Face Transformers or TRL SFTTrainer training scripts into an NVFLARE-compatible federated learning job. It leverages the NVFLARE Client API to patch the Trainer, enabling federated training while preserving the original model architecture, dataset handling, and evaluation logic. The process involves static inspection of the source code, recipe selection, job construction using maintained assets, and validation through simulation.

What it does

  • Inspects source code to confirm Hugging Face Trainer ownership.
  • Patches the Trainer using flare.patch(trainer) for federated model exchange.
  • Constructs an NVFLARE job using standard FedAvg recipes.
  • Preserves original Trainer arguments, metrics, and PEFT configurations.
  • Validates the converted job through simulation and evidence reporting.

When to use it

  • When you have existing training code built around transformers.Trainer or TRL SFTTrainer.
  • When you need to transition a centralized Hugging Face training workflow to a federated environment.
  • When you require federated fine-tuning of models using PEFT/LoRA.
  • When you need to maintain existing Trainer callbacks and evaluation metrics in a federated setup.

Advantages

  • Maintains existing Hugging Face training logic and Trainer semantics.
  • Automates the integration of federated learning capabilities via patching.
  • Ensures consistent model exchange using standard NVFLARE recipes.
  • Provides a clear validation ladder to verify the converted job.

Usage examples

“Convert my existing Hugging Face SFTTrainer script to run on NVFLARE.”
The agent will inspect your script, confirm Trainer ownership, apply the required patches, and generate an NVFLARE job structure ready for simulation.
“How do I make my Transformers Trainer-based model work in a federated setting?”
The agent will guide you through the conversion workflow, including patching your Trainer and configuring the server-client job assets.

Install

  1. Download the skill as a ZIP:

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

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

Documentation by NVIDIA FLARE Team

NVFLARE Convert Hugging Face

Use When

Use when converting training code built around transformers.Trainer, Seq2SeqTrainer, TRL SFTTrainer, or another Trainer subclass. Support full-model and PEFT/LoRA fine-tuning, datasets/tokenizers, Trainer callbacks and metrics, checkpoint continuity, and replicated torch.distributed training.

Do Not Use When

Do not use for an AutoModel driven by a manual PyTorch loop without a Hugging Face Trainer (route to nvflare-convert-pytorch), PyTorch Lightning (route to nvflare-convert-lightning, including Lightning modules that contain Transformers models), inference-only pipelines, model serving, failed jobs (route to nvflare-diagnose-job), or federated statistics without training (route to nvflare-fed-stats). Route a project with active Lightning and Hugging Face Trainer entrypoints to nvflare-orient to select one training-loop owner or separate jobs. Route unresolved Trainer ownership, such as a Trainer factory without a bound owner call, to nvflare-orient; do not patch either Trainer. Out of scope: DeepSpeed, FSDP, production/POC deployment, controller rewrites, experiment search, and privacy-protection requests such as HE, encrypted aggregation, differential privacy, or privacy filters; never substitute an unprotected recipe or present a disclaimer as implementation. 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.

Available Scripts

ScriptPurposeArguments
scripts/resolve_model_snapshot.pyResolve a local or Hub model/dataset snapshot and emit JSON evidence.Identifier; required --source; optional source-root, download, revision, cache, and repository-type flags.

Use run_script() only during the validation phase after loading references/huggingface-validation.md. For example:

  • run_script("scripts/resolve_model_snapshot.py", ["--source", "local", "--source-root", "<absolute-source-root>", "<configured-path>"])

  • run_script("scripts/resolve_model_snapshot.py", ["--source", "hub", "<org/model>"])

Workflow

  1. 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.

  2. Inspect before editing with nvflare agent inspect source <path> --format json plus direct source reading. Load references/huggingface-detection.md during this phase. If inspect recommends nvflare-orient for unresolved Trainer ownership or active Lightning/Hugging Face owners, stop before editing. Extract the entrypoint, Trainer subclass, model constructor, tokenizer or processor, datasets and collator, Trainer arguments, compute_metrics, callbacks, checkpoint and PEFT settings, precision, local budget, distributed launcher, site/round counts, data location, and aggregation intent. Do not import or execute user training modules to discover them.

  3. Apply the dependency-install ordering rule in ../nvflare-shared/references/conversion-common.md before any Python command imports user, framework, NVFLARE, or declared dependencies. Keep dependency inventory single-purpose: check NVFLARE separately, inventory non-product packages separately, and do not append Hugging Face cache or filesystem discovery. Defer model and dataset availability checks to the maintained resolver during validation. If an optional path must be inspected, run it separately and report a missing directory with exit code zero.

  4. Select the recipe from FL intent. For explicit FedAvg, run nvflare recipe show fedavg-pt --format json, then immediately load ../nvflare-shared/references/pytorch-family-recipe-construction.md and use the returned module, class, and parameters with the required construction and execution shape in assets/job.py. Import FedAvgRecipe from nvflare.app_opt.pt.recipes.fedavg, never from nvflare.recipe. Treat class_path as the public recipe key and path as its normalized exported representation; do not inspect Recipe source or signatures to reconcile them. Do not guess adjacent symbols or add per-site recipe config unless sites genuinely differ. Load ../nvflare-shared/references/pytorch-family-recipe-selection.md only for ambiguous, evaluation-only, or non-FedAvg requests.

  5. Convert with references/huggingface-conversion.md and adapt assets/client_with_eval.py rather than drafting a new round loop. Preserve model, tokenizer/processor, datasets, collator, Trainer arguments, callbacks, and metrics. Apply the step-1 data-location rules to the client's data argument. Import the Client API as import nvflare.client.hf as flare, so flare.init(), flare.patch(), and flare.is_running() resolve to nvflare.client.hf. Keep flare.patch(trainer) simple with inferred params_scope="auto" and encode one per-round budget in Trainer arguments: requested steps use max_steps, requested epochs use num_train_epochs, and a silent prompt uses the reported default max_steps=10 unless source-budget preservation was requested. Do not duplicate the budget in patch local_steps/local_epochs. When the client uses HfArgumentParser, construct it with allow_abbrev=False.

  6. Adapt assets/server_model.py and assets/job.py instead of inventing server-model, packaging, export, or SimEnv wiring. Keep generated and packaged project-local modules in the same writable source directory. Never use .. in train_script, add_server_file(), or add_client_file(); use an existing resolved absolute path when co-location is impossible. Keep the server and Trainer model factory and exchange keyspace identical. Use the recipe's documented class_path or path key plus complete args for required or overridden values; a direct zero-argument instance must not use from_pretrained(), downloads, or checkpoint loading during job construction. Apply only options confirmed by the construction reference. Preserve the job asset's recipe-before-parser ordering, ArgumentParser(allow_abbrev=False), and strict parse_args(); do not use parse_known_args().

  7. Only after generated files exist, load ../nvflare-shared/references/validation-evidence.md and references/huggingface-validation.md. Follow the shared compile, construction, simulation, and terminal-evidence ladder. Inspect export/package evidence only for an exported final target; inspect a local target's materialized evidence after its run. Apply only the standard HF Trainer checks and stop at the first failed rung. Review and exercise the maintained assets directly; do not inspect NVFLARE implementation source, improvise Recipe API probes, or write one-off AST programs to re-prove them. Use references/huggingface-state-and-distributed.md only when inspection found PEFT, DDP, checkpoint/restore overrides, auxiliary trainable models, or another non-default patch setting.

  8. Report the recipe, source facts, parameter scope, data partition, changed files, validation status, and exact artifact paths. When validation produces metrics, load ../nvflare-shared/references/metrics-and-artifact-reporting.md before the final response and report each observed primary scalar with its metric name, numeric value, and artifact or bounded-log source.

Requirements

  • Must use flare.patch(trainer) as the sole model-exchange owner. receive() inside a patched loop may inspect task metadata only; it must not load a second copy of the global model.

  • Must follow the Client API initialization and conditional rank contract in ../nvflare-shared/references/conversion-common.md. Keep the generated client rankless; nvflare.client.hf.init() owns distributed-rank resolution and rejection. Load references/huggingface-state-and-distributed.md only for a distributed multi-process source path.

  • Must preserve source evaluation. When per-round global-model evaluation is required, call trainer.evaluate() before trainer.train() on every rank. Do not invent compute_metrics, label mappings, averaging denominators, or metric direction.

  • Must follow the Best-Model Metric policy in ../nvflare-shared/references/pytorch-family-recipe-construction.md; the Hugging Face delta is only how the delivered key is named and produced. Must preserve source metric names when practical: if the generated trainer.evaluate() emits accuracy, set key_metric="accuracy"; if Trainer emits a prefixed key such as eval_accuracy, set the server to that exact key and report the source-to-server mapping. When best-model selection is requested, every lower-is-better metric, including Trainer-generated eval_loss, is delivered as an explicitly negated companion and selected by that key — never as raw loss. When selection is not requested, use key_metric=""; do not omit it and accidentally activate the recipe default.

  • Must preserve PEFT configuration exactly and verify adapter key compatibility between the server model and patched Trainer. Do not infer LoRA target modules, silently switch adapter/full-model scope, or solve key mismatches with non-strict loading.

  • Must verify that trainer.model owns all federated trainable state for Trainer subclasses with reference, reward, value-head, or other auxiliary models. Ask or fail closed when params_scope="auto" would omit trainable state required by the algorithm.

  • Must preserve model constructor values needed on both server and clients per ../nvflare-shared/references/pytorch-model-exchange.md (State-Dict Compatibility). Ask one semantic question or fail closed when required values are not statically available.

  • Must patch only one Trainer per Python process. Preserve a single Trainer lifecycle across rounds when restore_state=True.

  • Must use a positive TrainingArguments.max_steps budget for a length-less iterable training dataset and let flare.patch(trainer) infer it.

  • Must reject or report DeepSpeed, FSDP, save_only_model=True with restore_state=True, load_best_model_at_end=True, prebuilt optimizer/scheduler instances with restore_state=False, and checkpoint paths not visible to every distributed rank. Do not rewrite these settings silently. launch_once is a framework-neutral recipe parameter owned by ../nvflare-shared/references/pytorch-family-recipe-construction.md; the Hugging Face delta is only that the product rejects explicit launch_once=False together with restore_state=True.

  • Must initialize torch.distributed before patching when rank environment variables declare multiple ranks. All ranks must call patched Trainer methods in identical order.

  • Must use the maintained HF validation resolver with an explicit local/Hub source. For authorized downloads it obtains or validates a full commit-SHA revision before downloading. Must not copy it into generated job code, set trust_remote_code=True, download model/data artifacts unless requested, or recover from a cache-only miss by going online. Cache misses, remote identifiers, and validation requests do not authorize online retries; see ../nvflare-shared/references/conversion-common.md.

  • 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. Complete each workflow phase before loading the next phase's reference. Do not preload validation, state/DDP, broad workflow, dependency, or reporting references. The standard FedAvg path loads, in order: ../nvflare-shared/references/conversion-common.md, references/huggingface-detection.md, and ../nvflare-shared/references/site-data-and-paths.md only for its stated triggers; ../nvflare-shared/references/pytorch-family-recipe-construction.md, references/huggingface-conversion.md, and ../nvflare-shared/references/pytorch-model-exchange.md; then ../nvflare-shared/references/validation-evidence.md and references/huggingface-validation.md; load references/huggingface-state-and-distributed.md and other shared references only under the triggers above. Do not depend on repository examples.

Files

references/huggingface-conversion.md

Hugging Face Trainer Conversion

Canonical Path

Use this path for a standard Trainer conversion:

  1. Confirm Hugging Face Trainer ownership with nvflare agent inspect source.

  2. Run nvflare recipe show and apply the shared PyTorch-family construction profile.

  3. Adapt ../assets/client_with_eval.py into client.py, preserving the source Trainer factory and metric behavior.

  4. Adapt ../assets/server_model.py and ../assets/job.py for the source model factory, client arguments, selected metric, and capability-gated options. Hugging Face Trainer is part of the PyTorch family, so ../../nvflare-shared/references/pytorch-model-exchange.md owns the tensor-payload and state-dict compatibility rules for the server model and every client; load it before pinning shared constructor values.

  5. Follow the shared validation ladder with the HF-specific validation delta.

The maintained assets are the canonical standard path. The client asset owns the patch and round-loop shape. The server asset returns the source model directly so no wrapper prefix changes its state-dict keys. The job asset owns the required FedAvg constructor, server/client packaging, SimEnv, and recipe.execute() shape. Adapt these surfaces rather than drafting replacements or inspecting NVFLARE implementation source.

The generated client.py entry point is FL-only: it always reaches flare.init() and flare.patch(trainer). Do not infer FL launch from CLIENT_API_TYPE or another environment variable; the launcher does not expose a reliable branch signal to the trainer. If preserving a standalone CLI is required, factor shared setup into an explicit function parameter and have the generated client call that function with federated=True; keep the standalone path behind an entry point that passes federated=False explicitly.

When the source has no valid evaluation dataset or metric and neither per-round evaluation nor best-model selection is requested, adapt the asset with evaluate_before_train=False and key_metric="" so model selection is disabled. Do not omit key_metric: FedAvgRecipe otherwise activates its documented default selector. See the Best-Model Metric section of ../../nvflare-shared/references/pytorch-family-recipe-construction.md.

Import the Client API as import nvflare.client.hf as flare, as the asset does, so every flare.* call below resolves to nvflare.client.hf.

Follow the framework-neutral Client API initialization and rank contract in ../../nvflare-shared/references/conversion-common.md. The standard asset always calls rankless nvflare.client.hf.init(). The product resolves an initialized process-group rank or global RANK and rejects an unresolved multi-process launch before creating a Client API context; do not reimplement that logic in generated code. For a preserved multi-GPU launch, load huggingface-state-and-distributed.md. Initialize before flare.get_site_name(), flare.get_config(), or other Client API context access that occurs before patch().

Do not add manual model loading from flare.receive() or model sending through flare.send(). The patch wraps train() and evaluate(), loads the received global parameters, and sends the result from rank 0.

Preserve Trainer Semantics

  • Construct the model, tokenizer/processor, datasets, collator, Trainer arguments, callbacks, and Trainer once before the federated loop.

  • Preserve compute_metrics and evaluation datasets.

  • Keep mid-training evaluation controlled by the Trainer's own evaluation strategy; it is not a separate FL task.

  • Resolve exactly one per-round budget and encode it in one place:

    1. user-requested local steps become generated TrainingArguments.max_steps;

    2. user-requested local epochs become generated TrainingArguments.num_train_epochs, with a conflicting positive max_steps cleared because Hugging Face gives steps precedence;

    3. when the user explicitly asks to preserve the source budget, leave its positive max_steps or num_train_epochs unchanged;

    4. otherwise use the bounded generated default max_steps=10 and report it.

  • Let flare.patch(trainer) infer that Trainer budget. Do not also pass the same value through patch local_steps or local_epochs; that duplicate expression is misleading even though the patch option owns the runtime budget. Use a patch budget option only when the Trainer's argument surface cannot express the requirement, and then do not encode the same budget in Trainer arguments. A length-less iterable dataset requires a positive TrainingArguments.max_steps budget; let the patch infer it without also setting patch local_steps.

  • With restore_state=True, the patch sets the Trainer's cumulative max_steps target to per_round_budget_steps * total_rounds so optimizer and scheduler progress continues across rounds. Hugging Face may display that whole-job target in its progress bar, while the NVFLARE callback still stops each trainer.train() call after one per-round budget. Do not interpret the progress-bar denominator as work for the current round.

  • When the generated or preserved client uses HfArgumentParser, construct it with allow_abbrev=False, using the actual project and framework dataclass types. Other client parsers retain their own strict-parser mechanism.

  • Keep local-only callbacks and reporting. Leave network trackers disabled during validation unless explicitly requested.

Recipe Integration

Use the PyTorch recipe family. Run nvflare recipe show <recipe-name> --format json, then load ../../nvflare-shared/references/pytorch-family-recipe-construction.md before constructing the recipe. That shared reference owns capability checks, tensor-native transport and decomposer registration, disk offload, external process selection, and common metric-selection policy.

For FedAvg, adapt ../assets/job.py. Its required structure matches the plain PyTorch fast path: FedAvgRecipe(...), explicit importable model config, SimEnv(...), and recipe.execute(...). It uses {"class_path": "server_model.ServerModel", ...} at recipe construction time. class_path is the public recipe key; path is the normalized key in exported job configuration. Do not inspect PTModel, persistors, class loaders, or Recipe source to reconcile those representations.

Copy the adapted job.py, client.py, and server_model.py into the same writable source directory as packaged project-local modules such as model.py. Keep the asset's SOURCE_DIR = Path(__file__).resolve().parent resolution for add_server_file() and add_client_file() so construction works from any caller working directory. Keep train_script="client.py" as the portable app-local runtime path, and explicitly package its source with recipe.add_client_file(str(SOURCE_DIR / "client.py")). The maintained asset enters SOURCE_DIR only while the Recipe validates and records those resources, then restores the caller's working directory before returning. Do not move generated files into a child package and refer back with ../model.py: NVFLARE rejects parent-traversal external-script paths. For an exceptional non-co-located module, pass its existing resolved absolute source path to the packaging API.

SOURCE_DIR identifies the generated-file directory for packaging; it is the source-project root only in the colocated case. If a read-only source root puts generated files elsewhere, pass the inspected original root explicitly to resolve_source_local_path(..., source_root=...) for source-relative data. Do not resolve those data paths against the writable generated-file directory.

Add optional recipe arguments and decomposers only as directed by the selected recipe's capability profile and the shared construction reference. Do not copy the FedAvg constructor shape to another recipe. When sites genuinely need different non-entrypoint settings, such as complete train_args or source-backed launcher values, pass the resolved site mapping through the asset's per_site_config argument. It calls set_per_site_config(recipe, per_site_config) immediately after construction and before any client file or configuration is added. Do not pass the deprecated Recipe constructor per_site_config option through recipe_options. Every site uses the same packaged client.py; do not include train_script in the per-site mapping. The asset rejects both relative and absolute site-specific script overrides because it cannot package them while preserving one portable app-local runtime path. Pass that same mapping to the asset's build_sim_env(...), which implements the single-topology-owner rule from ../../nvflare-shared/references/conversion-common.md. Leave the mapping unset for ordinary generated partitions, and derive their indices from the initialized site-N name. Follow the shared construction reference's client-argument transport rule. train_args is not necessarily shell parsed: use unquoted whitespace-free tokens for the default in-process executor, and use shell quoting only for a documented POSIX-tokenizing launcher. Ask or fail closed when a required value cannot be represented by the selected public argument surface. Do not probe internal command-splitting helpers.

train_script names the primary client entry point in the runtime config; it does not provide a separate source root for caller-cwd-independent packaging. Use its portable app-local name in the constructor and add the resolved source once with recipe.add_client_file(...). For an exported-artifact target, export and inspect that job before running it with the simulator CLI. For a local python job.py target, do not export; after the run, inspect the materialized simulation workspace for the same config and packaging evidence. Reject absolute task_script_path values in generated configs because runtime apps must launch their packaged client script portably.

For an exported-artifact target, exported app layout is owned by ../../nvflare-shared/references/conversion-workflow.md: inspect the exported job root and enumerate the app directories it actually contains before asserting any path.

Preserve the job asset's explicit packaging of server_model.py and the source model module into the server app, and package source modules imported by the client. A client import is not enough when an export separates server and client apps. Verify the required files under the discovered layout: app/custom for a unified export, or app_server/custom and each app_<site>/custom for a per-site export. Do not reuse a path assumption from another export. Installed NVFLARE, framework, and third-party class paths stay runtime dependencies validated through requirements installation plus import/preflight checks.

Data And Model Selection

Follow ../../nvflare-shared/references/site-data-and-paths.md when generated site partitions, relative-path resolution, or per-site data locations are involved. Pass data roots through client arguments or per-site configuration — never a path hardcoded in the generated client, and never copy private site data into the job.

Prefer preserving source metric names in the client metrics output. If the generated evaluation call emits accuracy, configure key_metric="accuracy". Trainer commonly prefixes compute_metrics output, so {"accuracy": ...} can become eval_accuracy; when that is the returned client key, configure the server with key_metric="eval_accuracy" and report the mapping from source metric name to server metric key.

FedAvgRecipe does not expose a lower-is-better direction flag, so the shared rule in ../../nvflare-shared/references/pytorch-family-recipe-construction.md applies unchanged: when best-model selection is requested, every lower-is-better metric is delivered as an explicitly negated companion and selected by that key. This holds for loss exactly as it does for any other metric.

  • For a metric returned by compute_metrics, preserve the original and add the negated companion in the same dict — {"wer": wer, "neg_wer": -wer} — then select the prefixed key eval_neg_wer.

  • For Trainer-generated eval_loss, which compute_metrics never sees, add the companion with a small TrainerCallback whose on_evaluate inserts metrics["eval_neg_loss"] = -metrics["eval_loss"], then select key_metric="eval_neg_loss". Register that callback on the Trainer before flare.patch(trainer): the patch appends its own callback, and Transformers passes the same metrics dict to callbacks in registration order, so the companion is present when FLARE captures the metrics. Guard the insertion so a missing or non-finite eval_loss is skipped rather than raising.

Never select raw loss as though increasing values were improvements. Ask or fail closed only when the metric direction itself is unclear, not merely because the sole available metric is a loss.

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
  • Instructions that use the network
  • 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-huggingface · 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-huggingface.zip