Generated banner for Tao Finetune Huggingface Model
Generated logo for Tao Finetune Huggingface Model

Tao Finetune Huggingface Model

NVIDIAOfficialCreated by NVIDIA Corporation

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

From the author

Fine-tune any HuggingFace CV / VLM / LLM model on local NVIDIA GPUs inside an NGC PyTorch container when no dedicated TAO model skill matches. Use when the user wants to fine-tune a HuggingFace model (full or LoRA), train a vision / VLM / LLM model end-to-end, generate a reproducible HF training pipeline, smoke-test a HuggingFace model locally before scale-up, push a fine-tuned model to the HF Hub with a model card, or emit a self-contained rerun skill for an existing HuggingFace finetune. Supports image classification, object detection, semantic / instance / panoptic segmentation, depth estimation, image-text-to-text VLM (SFT / LoRA), and LLM SFT / DPO / GRPO. Six-step workflow: inspect and qualify, hardware and NGC image, research, generate and smoke, train + eval + infer, push and emit rerun skill. Do not use for any Hugging Face model ID claimed by a dedicated `skills/models/*` skill; the model skill and its declared execution environment take precedence.
— the description by NVIDIA Corporation

AutoGineer summary

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

This skill provides a structured, six-step workflow for fine-tuning HuggingFace CV, VLM, and LLM models on local NVIDIA GPUs. It leverages NGC PyTorch containers to ensure environment consistency and reproducibility. The workflow includes automated preflight checks, live research of model-specific recipes, smoke testing on real data, and optional integration with HuggingFace Hub for model sharing. It is designed to be the fallback for models not covered by dedicated TAO skills, ensuring a rigorous, documented path from inspection to deployment.

What it does

  • Inspects and qualifies models and datasets for compatibility.
  • Audits local hardware and selects the appropriate NGC PyTorch container.
  • Performs live research to fetch model-specific training recipes and configurations.
  • Generates a complete, reproducible project structure including training and evaluation scripts.
  • Executes a mandatory smoke test on real data before full-scale training.
  • Pushes fine-tuned models to the HuggingFace Hub and emits a self-contained rerun skill.

When to use it

  • When you need to fine-tune a HuggingFace model and no dedicated TAO skill exists for it.
  • When you require a reproducible, containerized training pipeline on local NVIDIA hardware.
  • When you need to smoke-test a model locally before scaling to larger infrastructure.
  • When you want to automate the generation of model cards and training reports.

Advantages

  • Ensures environment consistency using NVIDIA-optimized NGC containers.
  • Prevents common training failures through mandatory smoke testing and preflight checks.
  • Reduces manual configuration by automating script generation and recipe research.
  • Provides a clear, auditable path from initial inspection to final model deployment.

Usage examples

“Fine-tune google/vit-base-patch16-224 on my local image dataset.”
The agent will inspect the model and dataset, verify hardware, generate the training project, run a smoke test, and initiate the fine-tuning process.
“Train a Llama-3-8B model using LoRA on my local GPU.”
The agent will research the appropriate LoRA configuration, set up the NGC environment, and execute the training pipeline with the specified parameters.

Install

  1. Download the skill as a ZIP:

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

    mkdir -p .agents/skills && unzip tao-finetune-huggingface-model.zip -d .agents/skills

Documentation by NVIDIA Corporation

<!-- Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. Licensed under the Apache License, Version 2.0; see http://www.apache.org/licenses/LICENSE-2.0 -->

tao-finetune-huggingface-model

Standalone install? If this session was not initialized by the TAO skill bank plugin, run the tao-setup skill first (host preflight, credentials, cross-skill discovery).

Local NVIDIA GPU fine-tuning for HuggingFace models, grounded in live-fetched documentation with curated references as a fallback safety net. One NGC container, a few focused scripts, one push to HF Hub. Follow the rules in this file; don't improvise.

Dedicated-model routing gate

Before Step 1 or any probe, image selection, package install, venv creation, or training-code generation, resolve model_id against the packaged model-owner registry. Use the absolute skill-bank root from which this file was loaded:

python <bank-root>/scripts/resolve_tao_model.py \
  --skill-bank <bank-root> \
  --model "$MODEL_ID" \
  --format json

The resolver matches model metadata, including huggingface_model_ids, network_arch, skill names, and legacy aliases. Routing is internal: a model ID and task are enough. Never require prompt boilerplate about skills, containers, or checkpoint formats.

  • Exit 0: stop this workflow and follow the owning model skill's environment, action metadata, preflight, and checkpoint preparation.

  • Exit 3: no packaged model skill owns the ID. This is the only result that permits Step 1 of the generic workflow.

  • Any other nonzero exit: ownership discovery is broken or ambiguous. Stop and resolve that error; do not silently fall back to generic Hugging Face training.

Hugging Face hosting never overrides ownership. Do not use this workflow to bypass a matched skill or ask the user to prescribe its internal preparation. For example, nvidia/Cosmos3-Nano routes to tao-finetune-cosmos-reason.

Do not create a host training venv in this workflow. Its default execution path is the NGC container documented below; any venv-based training path requires an explicit user request.

Order of authority (highest first):

  1. User input — explicit model_id, dataset_id, training_method, config.yaml overrides.

  2. Live research — model card, HF repo example, author finetune script, HF task docs, paper; always fetched (Step 3 + references/research-priorities.md).

  3. Curated references (references/*.md) — fallback when live research is silent/ambiguous.

  4. Your training-data memory — last resort; suspect, cross-check against (2)/(3).

Conflict resolution between (2) and (3) and the source-line discrepancy note are in references/research-priorities.md.


Inputs

Required:

  • model_id — HuggingFace model ID, e.g. google/vit-base-patch16-224

Conditional credentials (read from the session environment — exported before launching or sourced from a user-approved env file):

  • HF_TOKEN — only when the model/dataset is gated (read) or push_to_hub is on (write); public + public + push_to_hub: false needs none. Value never read — presence-only via [ -n "$HF_TOKEN" ].

  • WANDB_API_KEY, WANDB_PROJECT — only when WandB is enabled; WANDB_MODE=disabled opts out.

Dataset — exactly one:

  • dataset_id — HuggingFace dataset ID (source: hf)

  • local_dataset_path — local folder or file (source: local); optional local_dataset_format ∈ {auto, imagefolder, coco, voc, jsonl, arrow, parquet, csv} (default: auto-detect).

  • (omit) — agent recommends popular datasets (source: recommend)

Optional (have defaults):

  • task_type — auto-detected from config + model card

  • n_train=10000, n_eval=1000, n_epochs=3, lora_r=16

  • output_dir=./output/<model_short_name>

  • hf_model_repo — push target; if unset and HF_TOKEN has write access, auto-derived as <whoami>/<model_short_name>-finetuned.

  • push_to_hub=True — set to False to skip

  • skip_baseline=False — skip zero-shot baseline eval

Optional deliverables (off by default):

emit_progress_log: false   # output_dir/PROGRESS.md (per-step journal)
emit_report:       false   # reports/report.{pdf,html} with curves & samples
emit_unit_tests:   false   # tests/ with fake-data heterogeneous-batch tests

All values live in output_dir/config.yaml. Never hardcode in Python.


Execution platform

This skill orchestrates what to run; the platform skills own how to run it on a GPU host — read them first.

ConcernAuthoritative skill
GPU host runtime (driver 580, CUDA Toolkit 13.0, NVIDIA Container Toolkit 1.19.0)tao-skill-bank:tao-setup-nvidia-gpu-host
docker run flags, NGC auth, mounts, env passthrough, local/remote Docker job preflight (daemon, GPU smoke)tao-skill-bank:tao-run-on-docker

Default platform: local-docker — build a one-off image (run-<short>:latest) and run it on the local Docker daemon. Ask only when the user explicitly needs a different backend (Brev remote GPU, SLURM/Kubernetes); then run that platform's Preflight first and route the Steps 4–5 docker run commands through it. The GPU-runtime and presence-only credential preflights (values never read), the canonical docker run flag set, discovery of the execution platforms from the installed platform skills (tao-run-on-docker / -slurm / -kubernetes / -brev, plus any external one; on a runtime that surfaces only the core router skills, read skills/platform/tao-run-on-*/SKILL.md frontmatter), and the workflow-specific flags (--entrypoint /bin/bash -lc, PYTORCH_CUDA_ALLOC_CONF, --name hft_train) are in references/workflow-intake-preflight.md.


References — fallback safety net

Consulted only when live research is silent, ambiguous, or unavailable; live docs always win for the specific model and current API. Each step links the references it needs; full catalog in references/detailed-workflow.md.

Always-on: core-rules.md, error-playbook.md, compat-workarounds.md, model-discovery.md, dataset-recommendations.md, dataset-sources.md, dataset-patterns.md, hardware-container.md, research-priorities.md, cv-scripts.md, vlm-scripts.md, docker-runs.md, hub-push.md, pipeline-skill-template.md, deliverables.md. Opt-in (when their flag/need applies): progress-tracking.md, testing.md, reporting.md, workflow-intake-preflight.md, workflow-generate-train.md, workflow-push-rerun.md.

Rule: before falling back, log the live source you tried and why it was insufficient (config.yaml notes:, and PROGRESS.md if enabled). [FETCH LIVE] markers in cv-scripts.md / vlm-scripts.md are a research checklist, not code to inline — refetch the listed URL if a block has no Step 3 finding.


Core rules

Non-negotiable behaviors. Short version (full enumeration — hallucinated-imports list, never-without-approval list, full error-recovery and hardware-sizing tables — in references/core-rules.md, consult before any training-time decision):

  • Your HF-library knowledge is outdated. Fetch live docs (model card, HF repo example, task doc) before writing any ML code — don't generate trainer args / collator / transforms from memory (Step 3).

  • Smoke-test on real data with --max_steps 1 before any full run; no batch launches without a verified smoke.

  • Never silently substitute model_id, dataset_id, or training_method — if what the user asked for doesn't load, stop and ask.

  • Error recovery is minimal-change. OOM → halve batch, double grad_accum, enable gradient checkpointing (no LoRA switch without approval); NaN → reduce LR 10×; flat loss → inspect collator; same error 3× → stop and ask. Don't loop.

  • Dataset columns verified BEFORE the collator — rename in prepare_data.py; restructuring needed → stop and ask.

  • Hardware-sizing thumb (bf16): ≤3B → 24 GB, 7–13B → 80 GB, 30B+ → multi-GPU or LoRA on 1× 80 GB, 70B+ → 8× 80 GB or LoRA. Full finetune won't fit and no LoRA requested → ask before switching.


Workflow — 6 steps

Single pass, sequential; each step has a clear gate before the next begins.

Step 1 — Inspect & qualify

Goal: decide whether to proceed. Probe model + dataset, apply accept/reject, register applicable compat fixes, write the initial config.yaml.

Prerequisites: MODEL_ID, optional DATASET_ID / local_dataset_path, optional HF_TOKEN, OUTPUT_DIR (default ./output/<model_short_name>). Probes run in a CPU-only python:3.12-slim Docker container (bind-mounted .probe/ scratch) so the host needs no virtualenv — Docker must exist first. Docker-presence guard, container env, full probe invocation, and the model/dataset probe scripts are in references/workflow-intake-preflight.md, references/model-discovery.md, and references/dataset-sources.md.

Probe requirements:

  • Model: load AutoConfig, read model-card tags, detect task from architectures + tags + card examples (fallback logging in model-discovery.md).

  • Dataset: for recommended datasets, first present 3-5 choices from dataset-recommendations.md; for local data, bind-mount read-only and use dataset-sources.md format detection.

  • Reject early if the model config fails, the task is out of scope, no recipe source exists, or the dataset cannot load / match the task schema.

  • Evaluate compat-workarounds.md against the model/task; defer hardware-dependent rules to Step 2.

Write the initial config.yaml (model_id, task, dataset_id or local_dataset_path, research_sources: [] filled in Step 3, applicable_workarounds: from Step 1, notes: [] for reference fallbacks, push_to_hub: true default — annotated template in references/workflow-intake-preflight.md). Optionally rm -rf "$OUTPUT_DIR/.probe" once the gate is met.

Gate: config.yaml exists with model, dataset, task, applicable_workarounds; do not proceed if any field is missing.


Step 2 — Hardware audit & NGC image

Goal: verify Docker + GPU + disk, pick the NGC PyTorch image live, finalize hardware-dependent compat rules.

2a. Audit (hard gate) — three checks (commands in references/workflow-intake-preflight.md):

  1. GPU host runtime — tao-setup-nvidia-gpu-host's setup-nvidia-gpu-host.sh --backend docker --check-only; on fail, ask approval then re-run with --install --yes.

  2. Free-disk soft-warn — override via MIN_DISK_GB (default 100 GB); recommend ≥ 100 GB for NGC base (~20 GB) + HF cache + checkpoints + data.

  3. Conditional credential presence (values never read) — HF_TOKEN only when gated or push_to_hub is on; WANDB_* only when WandB is on.

Do not proceed to Step 4 on a hard-fail — Step 4's docker build pulls a 20+ GB NGC base, and a missing nvidia-container-toolkit only surfaces later as could not select device driver "" with capabilities: [[gpu]]. Record gpu_count, gpu_name, driver_major, vram_gb_per_gpu in config.yaml.

2b. Pick NGC image (live): from the NVIDIA Deep Learning Frameworks support matrix (https://docs.nvidia.com/deeplearning/frameworks/support-matrix/index.html), PyTorch NGC container section, pick the highest-versioned image where Min driver ≤ detected driver_major and container CUDA ≤ host CUDA Toolkit (match closely so cuDNN / TensorRT line up). Do not reject an image for an aN/bN/rcN PyTorch tag — NGC validates the full image; pick the newest CUDA-aligned one and let compat-workarounds.md handle per-version issues. If the matrix is unreachable, use the fallbacks in references/hardware-container.md; default nvcr.io/nvidia/pytorch:24.09-py3 <!-- unpinned: documented fallback --> (driver ≥ 545; SDPA+GQA bug — if num_key_value_heads < num_attention_heads, set attn_implementation: "eager"). Record ngc_image in config.yaml.

2c. Re-evaluate hardware-dependent compat rules: re-run the compat-workarounds.md walk for entries whose detect needs hw; update applicable_workarounds: in place.

2d. Model-fit check: estimate param_bytes ≈ 2×param_count (bf16); if

60% of vram_gb_per_gpu × 1e9, recommend LoRA in the user-facing summary.

Gate: config.yaml has ngc_image, gpu_count, gpu_name, driver_major, vram_gb_per_gpu; hardware-dependent compat fixes recorded.


Step 3 — Research the recipe

Goal: fetch the live recipe — training-data knowledge of transformers/trl/peft is suspect, so Step 3 is non-negotiable. Walk references/research-priorities.md in priority order (Priority 1 → 6); stop once you have, for the detected task:

  • AutoModel / processor class

  • Train + eval transforms

  • Collator

  • compute_metrics

  • Hyperparameter hints (LR, batch size, epochs, scheduler)

Record findings in meta/recipe.md, append source URLs to config.yaml: research_sources:. A slot with no live finding falls back to the matching scaffold (cv-scripts.md / vlm-scripts.md), logged as "fallback to scaffold — no live source for <slot>" under notes:. Conflict-resolution rules are in references/research-priorities.md.

Gate: every required slot filled, with a source URL or scaffold-fallback note.


Step 4 — Generate project & smoke-test

Goal: write all scripts, build the image, prepare data, run a 1-step smoke on real data (one docker build, two docker runs).

4a. Generate project files in output_dir/: config.yaml, Dockerfile, requirements.txt, prepare_data.py, train.py, run_eval.py, infer.py, optional merge_lora.py, optional tests/, .gitignore. Live Step 3 research is authority; cv-scripts.md / vlm-scripts.md give scaffold shape only. Apply every applicable_workarounds entry as a Dockerfile block, requirement pin, config override, or runtime env var. Hard rules: run_eval.py keeps that exact filename (avoids colliding with the HF evaluate package); every generated .py starts with the NVIDIA Apache-2.0 copyright header and any emitter fails when it is missing; emit_unit_tests: true generates and runs tests per references/testing.md. Script bodies, Dockerfile shape, and the emitter contract are in references/workflow-generate-train.md.

4b. Build, prepare, smoke — docker build -t run-<short>:latest ., then prepare_data and the --smoke --max_steps 1 run (references/docker-runs.md §1-3). Smoke pass criteria (in logs/smoke.log):

  • No exception

  • Loss is finite (not 0.0, not NaN)

  • grad_norm > 0 at step 1

If emit_unit_tests: true, also run pytest tests/ in the container. Any failure → STOP.

4c. Preflight summary — before full training, print and verify: reference URL, dataset columns, Hub target, monitoring target, NGC image, hardware, smoke loss/grad norm.

Gate: project files written, image built, smoke PASSED, preflight has no blank fields.


Step 5 — Train, evaluate, infer

Goal: baseline eval, full training, post-train eval, optional LoRA merge, 5 inference samples (all commands: references/docker-runs.md §4-8).

Sub-stepdocker-runs.mdSkip if
5a. Baseline eval (zero-shot)§4skip_baseline: true
5b. Full training (detached)§5—
5c. LoRA merge§6not VLM+LoRA
5d. Post-train eval§7—
5e. Inference (5 samples)§8—

Multi-GPU: prepend torchrun --nproc_per_node=$gpu_count to python train.py.

While training streams, watch docker logs -f hft_train: loss should drop within 10-20 steps; flat loss (collator/label-masking bug), NaN (LR too high), and OOM all stop the run — recovery in references/core-rules.md. If emit_report: true, run report.py after Step 5e per references/reporting.md.

Gate: all of:

  • checkpoints/final/ (or checkpoints/merged/ for LoRA) exists

  • reports/eval_results.json has a numeric primary metric

  • reports/baseline_results.json exists (unless skipped)

  • reports/inference_samples/ has 5 samples

  • wandb URL shows descending loss


Step 6 — Push & emit rerun skill

Goal: publish the run and make it reproducible without re-research.

Push per references/hub-push.md (weights, model card, eval/baseline JSONs, config.yaml, Dockerfile, requirements.txt, inference samples, reports when emitted) unless push_to_hub: false is explicit. Emit <output_dir>/skills/run-<short>/SKILL.md from references/pipeline-skill-template.md — substitute every placeholder, include full YAML metadata + the NVIDIA copyright HTML comment, and make any emitter fail if those are missing.

Gate (Done criteria): all of:

  • Step 5 gate met

  • HF Hub repo exists at the resolved URL with weights + card + results/ (unless push_to_hub: false)

  • <output_dir>/skills/run-<short>/SKILL.md exists, no <placeholder> left, with metadata + copyright HTML comment per pipeline-skill-template.md

Final message: wandb URL, HF Hub URL, baseline -> fine-tuned primary metric, reports/inference_samples/, and the rerun skill path.


Error playbook

On a known runtime error, consult the symptom → minimal-fix table in references/error-playbook.md (NGC entrypoint, PyTorch/Transformers regressions, numpy ABI, Albumentations bbox, PEFT/checkpointing, LoRA target breadth, CV augmentation gaps, OOM at step 0) before redesigning anything. When a row there fires twice across runs, lift it into compat-workarounds.md with a detect rule — auto-applied in Step 1 before the error can fire.


Communication style

  • Terse. No filler, no restating the request; one-word answers when appropriate.

  • Always include direct Hub and wandb URLs when referencing artifacts.

  • On error: state what went wrong, why, what you changed — no menus.

  • Never present "Option A/B/C" for a request with a clear answer. Act.

Files

references/workflow-intake-preflight.md

HuggingFace Fine-Tune Intake And Preflight

Detailed intake, platform delegation, reference routing, core rules, model/dataset probing, and hardware preflight from the pre-refactor guide.

Load this file only when the compact SKILL.md points here for the current task. If this reference conflicts with SKILL.md, skill_info.yaml, schemas, or platform/model skills, the compact/current source wins.

Contents

  • Inputs

  • Execution platform

  • References — fallback safety net

  • Always-on (consulted in the workflow)

  • Opt-in (only when their flag is set)

  • Core rules

  • Workflow — 6 steps

  • Step 1 — Inspect & qualify

  • HF source loadability + schema probe (catches gated / script-based / missing)

  • Step 2 — Hardware audit & NGC image

    1. GPU host runtime — delegated to tao-setup-nvidia-gpu-host

    1. Free-disk soft-warn (override via MIN_DISK_GB; default 100 GB)

    1. Conditional credential presence checks (no values are read)

  • HF_TOKEN: only when the model/dataset is gated, or push_to_hub is on.

  • WANDB_*: only when WandB logging is enabled in config.yaml.

tao-finetune-huggingface-model

Local NVIDIA GPU fine-tuning for HuggingFace models, grounded in live-fetched documentation, with curated references as a fallback safety net. One NGC container, a small set of focused scripts, one push to HF Hub. Behavior is governed by the rules in this file — follow them, do not improvise around them.

Order of authority (highest first):

  1. User input — explicit model_id, dataset_id, training_method, config.yaml overrides.

  2. Live research — model card, HF repo example, author finetune script, HF task docs, paper. Always fetched. See Step 3 + references/research-priorities.md.

  3. Curated references (references/*.md) — fallback when live research is silent or ambiguous.

  4. Your training-data memory — last resort. Treat as suspect; cross-check against (2) or (3).

If (2) and (3) conflict on an API call, (2) wins (newer). If they conflict on a method detail (collator, LoRA targets, augmentation), (2) wins for the specific model; (3) for the generic shape. Note the discrepancy in a comment at the source line.


Inputs

Required:

  • model_id — HuggingFace model ID, e.g. google/vit-base-patch16-224

Conditional credentials (read from the session environment — exported before launching, or sourced from a user-approved env file with set -a; source /path/to/.env; set +a):

  • HF_TOKEN — required only when the model or dataset is gated (read access) or push_to_hub is on (write access). Public model + public dataset + push_to_hub: false runs do not need it. The agent never reads the value — only checks presence with [ -n "$HF_TOKEN" ].

  • WANDB_API_KEY, WANDB_PROJECT — required only when WandB monitoring is enabled. Set WANDB_MODE=disabled to opt out.

Dataset — exactly one:

  • dataset_id — HuggingFace dataset ID (source: hf)

  • local_dataset_path — local folder or file (source: local). Optionally local_dataset_format ∈ {auto, imagefolder, coco, voc, jsonl, arrow, parquet, csv}. Default: auto-detect.

  • (omit) — agent recommends popular datasets (source: recommend)

Optional (have defaults):

  • task_type — auto-detected from config + model card

  • n_train=10000, n_eval=1000, n_epochs=3, lora_r=16

  • output_dir=./output/<model_short_name>

  • hf_model_repo — push target. If unset and HF_TOKEN has write access, auto-derived as <whoami>/<model_short_name>-finetuned.

  • push_to_hub=True — set explicitly to False to skip

  • skip_baseline=False — skip zero-shot baseline eval

Optional deliverables (off by default):

emit_progress_log: false   # output_dir/PROGRESS.md (per-step ✅/⚠️/❌ journal)
emit_report:       false   # reports/report.{pdf,html} with curves & samples
emit_unit_tests:   false   # tests/ with fake-data heterogeneous-batch tests

All values live in output_dir/config.yaml. Never hardcode in Python.


Execution platform

This skill orchestrates what to run; the platform skills own how to run it on a GPU host. Read those skills first and do not redraft their conventions here.

ConcernAuthoritative skill
GPU host runtime — NVIDIA driver 580, CUDA Toolkit 13.0, NVIDIA Container Toolkit 1.19.0tao-skill-bank:tao-setup-nvidia-gpu-host
docker run flags, NGC auth, --gpus, mounts, env passthrough, --shm-size=8g/--shm-size, common error modes, local/remote Docker job preflight (daemon reachable, GPU smoke)tao-skill-bank:tao-run-on-docker

Default platform: docker. This workflow builds a one-off image (run-<short>:latest) and runs it on the local Docker daemon — following the docker run conventions in skills/platform/tao-run-on-docker/SKILL.md. Ask the user only when they explicitly need a different backend (Brev for a remote GPU instance, SLURM/Kubernetes for managed scheduling); in that case run the chosen platform's Preflight section first, discover the execution platforms from the installed platform skills (tao-run-on-docker / -slurm / -kubernetes / -brev, plus any external one) by reading each platform skill's ## Credentials section and references/skill_info.yaml — then route the docker run commands in Steps 4–5 through that platform's execution pattern.

GPU runtime preflight: Step 2a runs the tao-setup-nvidia-gpu-host skill's --check-only mode. Do not duplicate the NCT / driver / --gpus all smoke logic here — if it needs to change, change it in tao-setup-nvidia-gpu-host.

Credentials preflight: the SessionStart hook (hooks/session_start.sh) lists the variable names (never values) in the session banner. Step 2a only confirms presence of credentials that the current run actually needs — HF_TOKEN for gated downloads or push_to_hub, WANDB_API_KEY/ WANDB_PROJECT if WandB is enabled — instead of hard-requiring them up front.

Docker run conventions: every docker run invocation in references/docker-runs.md follows the canonical flag set from skills/platform/tao-run-on-docker/SKILL.md (--gpus all, --shm-size=8g or --shm-size=…, -e VAR passthrough, bind mounts, --rm for one-shots). Treat that skill as the spec; this one only adds workflow-specific flags (--entrypoint /bin/bash -lc, PYTORCH_CUDA_ALLOC_CONF, --name hft_train).


References — fallback safety net

Consulted only when live research is silent, ambiguous, or unavailable. Live docs always win for the specific model and current API.

Always-on (consulted in the workflow)
FileStepRole
core-rules.mdallNon-negotiable agent behaviours — full enumeration of the rules summarised in SKILL.md
error-playbook.md4, 5Runtime-error symptom → minimal-fix table (consulted on every failure)
compat-workarounds.md1Known-issue registry; auto-applied via detect rules
model-discovery.md1model_type → AutoModel/processor mapping (when card silent)
dataset-recommendations.md1Vetted datasets for source = recommend
dataset-sources.md1Local format detectors + COCO/VOC/imagefolder/jsonl loaders
dataset-patterns.md4Universal prepare_data.py skeleton
hardware-container.md2NGC selection (offline fallback), GPU/disk audit, multi-GPU
research-priorities.md36-priority live-fetch ladder + extract/record + conflict rules
cv-scripts.md4CV scaffold (file names, CLI, config schema). Don't copy [FETCH LIVE] blocks
vlm-scripts.md4VLM/LLM scaffold (TRL/PEFT). Don't copy [FETCH LIVE] blocks
docker-runs.md4, 5Canonical docker run invocations for every command
hub-push.md6HF Hub push Python block + model card template
pipeline-skill-template.md6run-<short>/SKILL.md rerun template
deliverables.md4, 6Final directory layout + README results section
Opt-in (only when their flag is set)
FileFlagAdds
progress-tracking.mdemit_progress_log: truePROGRESS.md template
testing.mdemit_unit_tests: trueFake-data heterogeneous-batch tests
reporting.mdemit_report: truereport.py (PDF + HTML, reads trainer_state.json)

Rule: before falling back to a reference, log the live source you tried and why it was insufficient (in config.yaml notes:, and PROGRESS.md if enabled).

[FETCH LIVE] markers in cv-scripts.md / vlm-scripts.md are a research checklist, not code to inline. If a [FETCH LIVE] block has no Step 3 finding, refetch the listed URL.


Core rules

The non-negotiable behaviors the agent must follow across the workflow. Full text in references/core-rules.md. Short version:

  • Your HF-library knowledge is outdated. Fetch live docs (model card, HF repo example, task doc) before writing any ML code. Don't generate trainer args / collator / transforms from memory — see Step 3.

  • Smoke-test on real data with --max_steps 1 before any full run. No batch launches without a verified smoke.

  • Never silently substitute model_id, dataset_id, or training_method. If what the user asked for doesn't load, stop and ask.

  • Error recovery is minimal-change. OOM → halve batch, double grad_accum, enable gradient checkpointing — don't switch to LoRA without approval. NaN → reduce LR 10×. Flat loss → inspect collator. Same error 3× → stop and ask. Don't loop.

  • Dataset columns verified BEFORE writing the collator. Mismatch + rename → fix in prepare_data.py; restructuring needed → stop and ask.

  • Hardware-sizing rule of thumb (bf16): ≤3B → 24 GB, 7–13B → 80 GB, 30B+ → multi-GPU or LoRA on 1× 80 GB, 70B+ → 8× 80 GB or LoRA. If a full finetune won't fit and the user didn't ask for LoRA, ask before switching.

Consult references/core-rules.md for the full enumeration (hallucinated imports list, never-without-approval list, full error-recovery table, full hardware sizing table) before training-time decisions.


Workflow — 6 steps

Single pass, sequential. Each step has a clear gate before the next begins.

Step 1 — Inspect & qualify

Goal: decide whether to proceed at all. Probe model, probe dataset, apply accept/reject, register applicable compat fixes, write the initial config.yaml.

Prerequisites (assumed set by the calling agent):

  • MODEL_ID, optional DATASET_ID, optional HF_TOKEN (loaded from the SessionStart hook when present).

  • OUTPUT_DIR — defaults to ./output/<model_short_name>. Same variable Steps 4–5 bind-mount into the training container, so any HF/pip cache the probe leaves behind under $OUTPUT_DIR/.probe/.cache survives for later inspection but is gitignored.

Preflight — Docker must be installed. Step 1's probes run inside Docker (no host venv / pip needed), so Docker has to exist on the host before Step 1a. The full GPU-runtime preflight still happens in Step 2a — this just covers the Docker-daemon prereq earlier so the probe's docker run doesn't fail with a bare docker: command not found:

# Resolve the skill bank root and use the GPU-host skill's bundled installer.
SB="${TAO_SKILL_BANK_PATH:-${TAO_SKILL_BANK_ROOT:-$PWD}}"
SETUP_SCRIPT="${SB}/skills/platform/tao-setup-nvidia-gpu-host/scripts/setup-nvidia-gpu-host.sh"

if ! command -v docker >/dev/null 2>&1; then
  echo "MISSING: docker is required for Step 1's containerized probe."
  echo "After user approval, run the platform installer (same one Step 2a uses):"
  echo "  bash \"$SETUP_SCRIPT\" --backend docker --install --yes"
  echo "Then re-source your shell or 'newgrp docker' so the new group membership applies."
  exit 1
fi

If you'd rather front-load the full driver/CUDA/NCT preflight (recommended on a fresh host), just call bash "$SETUP_SCRIPT" --backend docker --check-only here — same invocation Step 2a uses, repeated calls are cheap.

1a. Probe model:

The probe runs inside a small CPU-only python:3.12-slim container so the host needs no Python prereqs (python3-pip, python3-venv, distro-managed Python). Save the script to $OUTPUT_DIR/.probe/model_probe.py first so it's diff-able, then run it with a bind-mounted scratch dir for cache reuse.

Docker rejects relative paths in -v (anything not starting with / is parsed as a named-volume name and fails for ./output/...). The snippet normalizes $OUTPUT_DIR to an absolute path with a single bash case before any mkdir / cat / docker run, so both the default relative ./output/<short> and an explicit absolute override resolve correctly:

set -a; source /path/to/.env; set +a   # omit if already exported
case "$OUTPUT_DIR" in
  /*) ;;
  *) OUTPUT_DIR="$(pwd)/$OUTPUT_DIR" ;;
esac
mkdir -p "$OUTPUT_DIR/.probe/.cache"
cat > "$OUTPUT_DIR/.probe/model_probe.py" <<'PY'
import os, sys
from transformers import AutoConfig
from huggingface_hub import model_info
mid = os.environ["MODEL_ID"]; tok = os.environ.get("HF_TOKEN") or None  # optional — public models work without it
try:
    # WARNING: trust_remote_code=True executes model-repo Python. Only probe repos you trust.
    cfg = AutoConfig.from_pretrained(mid, token=tok, trust_remote_code=True)
except Exception as e:
    # If this is a gated model, the error message will name 401/access-denied;
    # tell the user to export HF_TOKEN (or source their env file) and retry.
    print(f"REJECT: AutoConfig failed — {e}"); sys.exit(1)
info = model_info(mid, token=tok)
print("model_type:", cfg.model_type)
print("architectures:", getattr(cfg, "architectures", []))
print("tags:", info.tags)
print("hidden_size:", getattr(cfg, "hidden_size", None))
print("num_kv_heads:", getattr(cfg, "num_key_value_heads", None))
print("num_attn_heads:", getattr(cfg, "num_attention_heads", None))
PY

docker run --rm \
  --user $(id -u):$(id -g) \
  -e HOME=/probe -e PIP_USER=1 \
  -e MODEL_ID="$MODEL_ID" -e HF_TOKEN \
  -e HF_HOME=/probe/.cache -e PIP_CACHE_DIR=/probe/.cache/pip \
  -v "$OUTPUT_DIR/.probe":/probe -w /probe \
  python:3.12-slim \
  bash -c "pip install -q transformers huggingface_hub datasets Pillow && python model_probe.py"

Notes:

  • --user $(id -u):$(id -g) keeps any cached files in .probe/.cache owned by the host user. Without it the cache ends up root:root and cleanup needs sudo.

  • HOME=/probe + PIP_USER=1 makes pip install resolve to --user mode (installing into /probe/.local/lib/python3.12/site-packages inside the bind mount). System /usr/local/lib/python3.12/site-packages in python:3.12-slim is root-owned, so without these env vars the pip install would fail with PermissionError once --user $(id -u):$(id -g) drops root. Python picks up the user-site automatically via site.py.

  • The first invocation downloads python:3.12-slim (~50 MB) and a fresh set of HF wheels (~150 MB) into .probe/.cache/pip plus .probe/.local/lib/python3.12/site-packages/; subsequent probes reuse both.

  • The probe never installs anything on the host — Docker is the only host-side prereq, and the Step 1 preflight above verifies it.

Detect task from architectures + tags + model-card body. If the card doesn't show from transformers import AutoModelFor..., fall back to references/model-discovery.md and log the fallback under notes:.

1b. Probe dataset:

For source = recommend, present 3–5 picks from references/dataset-recommendations.md to the user, then re-run with the chosen dataset_id / local_dataset_path.

Same in-container pattern as 1a — write the script to .probe/dataset_probe.py first, then run it under python:3.12-slim with the bind-mounted cache. Step 1b is a separate bash invocation, so it repeats the $OUTPUT_DIR normalization (the variable doesn't survive across bash -c calls):

set -a; source /path/to/.env; set +a   # omit if already exported
case "$OUTPUT_DIR" in
  /*) ;;
  *) OUTPUT_DIR="$(pwd)/$OUTPUT_DIR" ;;
esac
cat > "$OUTPUT_DIR/.probe/dataset_probe.py" <<'PY'
# HF source loadability + schema probe (catches gated / script-based / missing)
import os
from datasets import load_dataset, load_dataset_builder
DID = os.environ["DATASET_ID"]; TOK = os.environ.get("HF_TOKEN") or None  # optional — public datasets work without it
try:
    load_dataset_builder(DID, token=TOK)
    ds = load_dataset(DID, split="train[:20]", token=TOK)
except Exception as e:
    print(f"REJECT dataset: {type(e).__name__}: {e}"); raise
rows = list(ds)
print("columns:", list(rows[0].keys()))
for col, val in rows[0].items():
    print(f"  {col}: {type(val).__name__}")
PY

docker run --rm \
  --user $(id -u):$(id -g) \
  -e HOME=/probe -e PIP_USER=1 \
  -e DATASET_ID="$DATASET_ID" -e HF_TOKEN \
  -e HF_HOME=/probe/.cache -e PIP_CACHE_DIR=/probe/.cache/pip \
  -v "$OUTPUT_DIR/.probe":/probe -w /probe \
  python:3.12-slim \
  bash -c "pip install -q transformers huggingface_hub datasets Pillow && python dataset_probe.py"

Same HOME=/probe + PIP_USER=1 rationale as 1a — the install lands in .probe/.local/lib/python3.12/site-packages and survives between probes under the bind mount.

For source = local, see references/dataset-sources.md for format detection and loaders. Bind-mount the local dataset path with an additional -v "<local_dataset_path>":"<local_dataset_path>":ro so the container can read it, and adapt dataset_probe.py to use the local loader instead of load_dataset(DID, …).

Verify columns match the task schema (Core rules → Dataset format). Mismatch + rename fixes it → write the rename into prepare_data.py. Otherwise stop.

1c. Apply accept/reject:

REJECT if:

  • AutoConfig raised

  • task can't be determined

  • task is not CV / VLM / SFT-LLM (out of scope)

  • no recipe source exists at all (no card example, no HF repo script, no author finetune, no task doc, no paper)

  • dataset is gated / script-based / missing (loadability probe failed)

Stop and report the specific reason. Do not proceed.

1d. Walk compat-workarounds:

For every entry in references/compat-workarounds.md, evaluate its detect expression against cfg and the detected task. Hardware-dependent rules (those needing hw) are deferred to Step 2.

Record matches in config.yaml under applicable_workarounds: (id + fix type + one-line reason). Each becomes a Dockerfile block, requirements pin, config override, or runtime env in Step 4.

1e. Write config.yaml skeleton:

model_id: <…>
task: <…>
dataset_id: <…>             # or local_dataset_path
research_sources: []         # filled in Step 3
applicable_workarounds: [<…>]
notes: []                    # log any reference fallback
push_to_hub: true            # default

Optionally clean up the probe scratch dir once the gate is met:

rm -rf "$OUTPUT_DIR/.probe"

Keeping it around between reruns is fine — it caches python:3.12-slim layers, pip wheels, and any HF model/dataset files already pulled, so a re-probe is fast. Add .probe/ to .gitignore (covered in Step 4a).

Gate: config.yaml exists with model, dataset, task, applicable_workarounds. Do not proceed if any field is missing.


Step 2 — Hardware audit & NGC image

Goal: verify Docker + GPU + disk, pick the NGC PyTorch image live, finalize hardware-dependent compat rules.

2a. Audit (hard gate): the GPU host runtime check is owned by the tao-setup-nvidia-gpu-host skill (driver branch 580, CUDA Toolkit 13.0, NVIDIA Container Toolkit 1.19.0). Invoke it in --check-only mode; on failure, ask the user to authorize the install, then re-run. Credentials are read from the session environment (exported before launching or sourced from a user-approved env file) — only check the ones the current run actually needs.

# 1) GPU host runtime — delegated to tao-setup-nvidia-gpu-host
# Resolve the skill bank root and use the GPU-host skill's bundled installer.
SB="${TAO_SKILL_BANK_PATH:-${TAO_SKILL_BANK_ROOT:-$PWD}}"
SETUP_SCRIPT="${SB}/skills/platform/tao-setup-nvidia-gpu-host/scripts/setup-nvidia-gpu-host.sh"

bash "$SETUP_SCRIPT" --backend docker --check-only || {
  echo "MISSING: TAO GPU host runtime not ready."
  echo "After user approval, run: bash \"$SETUP_SCRIPT\" --backend docker --install --yes"
  exit 1
}

# 2) Free-disk soft-warn (override via MIN_DISK_GB; default 100 GB)
min_disk_gb="${MIN_DISK_GB:-100}"
disk_free_gb=$(df -BG / | awk 'NR==2 {print $4}' | tr -d G)
if [ "${disk_free_gb:-0}" -lt "$min_disk_gb" ]; then
  echo "WARN: only ${disk_free_gb}G free on /; recommend ≥ ${min_disk_gb}G for NGC base (~20G) + HF cache + checkpoints + dataset." >&2
fi

# 3) Conditional credential presence checks (no values are read)
#    HF_TOKEN: only when the model/dataset is gated, or push_to_hub is on.
#    WANDB_*:  only when WandB logging is enabled in config.yaml.

Do not proceed to Step 4 on a hard-fail — Step 4's docker build pulls a 20+ GB NGC base image, and a missing nvidia-container-toolkit only surfaces at prepare_data.py time as the cryptic could not select device driver "" with capabilities: [[gpu]].

Record gpu_count, gpu_name, driver_major, vram_gb_per_gpu in config.yaml.

2b. Pick NGC image (live):

Fetch https://docs.nvidia.com/deeplearning/frameworks/support-matrix/index.html with the available web or docs tool

Find the PyTorch NGC container section. Pick the highest-versioned image where:

  • Min driver ≤ detected driver_major

  • Container CUDA is ≤ host CUDA Toolkit version (drivers are forward- compatible, but match closely so cuDNN / TensorRT versions line up with the host toolchain).

Do not reject an image because its PyTorch version carries an aN / bN / rcN suffix. Every recent NGC PyTorch image ships a near-head PyTorch build (2.10.0a0, 2.11.0a0, …) — NVIDIA validates the full image end-to-end (CUDA / cuDNN / TensorRT / NCCL / drivers / Python stack), so the aN reflects upstream PyTorch's tag, not NGC instability. Treating aN as disqualifying would force every run onto a ~year-old image. Pick the newest CUDA-aligned image and let real compat workarounds (compat-workarounds.md) handle any per-version issue.

If the live fetch fails: fallback rules in references/hardware-container.md. Default fallback: nvcr.io/nvidia/pytorch:24.09-py3 <!-- unpinned: documented fallback; live selection in hardware-container.md --> (driver ≥ 545; SDPA+GQA bug — if the model has num_key_value_heads < num_attention_heads, set attn_implementation: "eager" in config).

Record ngc_image in config.yaml.

2c. Re-evaluate hardware-dependent compat rules:

Re-run the compat-workarounds.md walk for entries whose detect expression needs hw. Update applicable_workarounds: in place.

2d. Model-fit check: estimate param_bytes ≈ 2×param_count (bf16). If

60% of vram_gb_per_gpu × 1e9, recommend LoRA in the user-facing summary.

Gate: config.yaml has ngc_image, gpu_count, gpu_name, driver_major, vram_gb_per_gpu. Hardware-dependent compat fixes are recorded.


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: Declares allowed tools, Needs an API key, Needs Python

The author says: Requires docker + nvidia-container-toolkit, NVIDIA GPU (driver ≥ 545, ≥ 24 GB VRAM for ≤3B models), ~40 GB free disk. Optional credentials (read from the session environment) — HF_TOKEN is read only when the model/dataset is gated or `push_to_hub` is on; WANDB_API_KEY and WANDB_PROJECT only when WandB logging is enabled.

Security

What our scanner noticed· Medium risk

  • Large base64-encoded blobs
  • Instructions that use the network

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 Corporation
Publisher
NVIDIA (Official)
Source
NVIDIA/skills · skills/tao-finetune-huggingface-model · 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 Corporation or NVIDIA.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download tao-finetune-huggingface-model.zip