Tao Port Huggingface Model
NVIDIAOfficialCreated by NVIDIA Corporation
- Skill
- Workflow
- Software development
- Apache-2.0
- Medium risk
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured, seven-phase workflow for porting HuggingFace Computer Vision models into the NVIDIA TAO Toolkit. It guides the user through inspecting the model, configuring the TAO core, implementing the trainer, and setting up the deployment pipeline for TensorRT. The process emphasizes a local-only development loop, requiring the user to manage four independent repository clones and execute all validation, testing, and training tasks within locally prepared TAO Toolkit containers.
What it does
- Validates HuggingFace model compatibility for computer vision tasks.
- Configures TAO core and implements native trainers for PyTorch.
- Integrates ONNX export and TensorRT deployment pipelines.
- Automates packaging and L0 unit testing for model components.
- Performs end-to-end validation within containerized environments.
- Provides optional tuning for accuracy, latency, and model size.
When to use it
- When you need to bring a custom HuggingFace computer vision model into the TAO Toolkit.
- When you require a full training-to-deployment pipeline for a new model architecture.
- When you need to verify model performance and exportability to TensorRT.
- When you are working in a local environment with NVIDIA GPU support.
Advantages
- Ensures consistency across training, export, and deployment stages.
- Provides a rigorous, step-by-step debugging and testing loop.
- Maintains environment isolation using containerized workflows.
- Supports a wide range of computer vision tasks including detection and segmentation.
Usage examples
- “Integrate a HuggingFace model into TAO.”
- The agent initiates the Phase 0 prerequisite check to verify your environment and prepare the necessary TAO Toolkit container images.
- “Wire a HuggingFace SegFormer into tao-pytorch.”
- The agent begins the codebase exploration phase to map the model to the appropriate TAO reference architecture and prepare the configuration.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/nvidia/tao-port-huggingface-model/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip tao-port-huggingface-model.zip -d .agents/skills
Documentation by NVIDIA Corporation
Standalone install? If this session was not initialized by the TAO skill bank plugin, run the
tao-setupskill first (host preflight, credentials, cross-skill discovery).
<!-- Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -->
TAO-HF Integration Skill
Integrate a HuggingFace (HF) Computer Vision model into the NVIDIA TAO Toolkit ecosystem. Work the phases iteratively — not purely linearly — via a build → test → debug → fix → retest loop at every step: when something fails, diagnose and fix before moving on; when it passes, move to the next step.
This SKILL.md is the workflow coordinator. Each phase has a dedicated references/phase-N-*.md with the full step-by-step content, code, docker invocations, and gates. Read the matching reference at the start of each phase — the summaries below are not sufficient.
Local-Only Rule
All work is strictly local. Do NOT push/commit/branch on any remote (GitLab, GitHub, HuggingFace), create merge/pull requests or issues, or upload/publish Docker images to any registry or artifact store. You may only read/clone from remotes — all edits, Docker builds, and test runs stay on the local machine.
Submodule Override Strategy
The user clones the four TAO repos (tao-core, tao-pytorch, tao-deploy, tao-dataservices) independently into one working directory. The tao-core/ submodule nested inside each repo points to the original unmodified commit; modifications only exist in the top-level tao-core/. Always install from the top-level tao-core/, never <repo>/tao-core/ — the nested submodule silently ignores all modifications. Override rules: (1) mount the working directory -v $(pwd):/workspace; (2) pip install /workspace/tao-core FIRST, before tao-pytorch/tao-deploy; (3) PYTHONPATH top-level tao-core first, e.g. -e PYTHONPATH=/workspace/tao-core:/workspace/tao-pytorch. See references/cross-cutting.md for the directory tree.
Execution platform
Every test, smoke run, and end-to-end validation executes inside a locally prepared TAO Toolkit container (tao-pytorch-base:latest, tao-deploy-base:latest, optionally tao-dataservices-base:latest — all from Phase 0). The platform skills own how to run them; this skill specifies what. Default platform: local-docker. Phase 0 delegates the driver / CUDA / NCT preflight to tao-setup-nvidia-gpu-host. See references/cross-cutting.md for the authoritative-skill table, bind-mount rationale, and canonical docker-run flag set.
Phase Map
| Phase | Goal | Reference |
|---|---|---|
| 0 | Prerequisites + TAO Toolkit images + local image tags | phase-0-prereqs.md |
| 1 | Inputs, HF-inspection container, validate model + dataset | phase-1-inspection.md, hf-inspection.md |
| 2 | Closest existing TAO reference model | phase-2-codebase.md, task-type-guide.md |
| 3 | tao-core config + tao-pytorch trainer / eval / inference | phase-3-implementation.md, tao-patterns.md, repo-structure.md |
| 4 | ONNX export + tao-deploy TRT engine / inference / eval | phase-4-deploy.md |
| 5 | Packaging (console_scripts) + L0 tests | phase-5-packaging.md |
| 6 | Container testing + end-to-end validation | phase-6-container-tests.md, docker-patterns.md |
| 7 | (conditional) Accuracy / latency / size tuning | phase-7-optimization.md |
Cross-cutting refs: workflow-consistency.md (CLI flow, config field paths, cross-phase dependencies); cross-cutting.md (platform, isolation, module pitfalls, debugging).
IMPORTANT — Continuous Execution Through Phase 6: do NOT stop after Phases 3–5 to wait for the user to run tests. Phase 6 is mandatory — not complete until tests pass inside the containers and the end-to-end pipeline is validated.
Development Loop
At every step: write code → test immediately (import check, unit test, or dry-run) → if it fails, read traceback → diagnose → fix → retest; if it passes, move on. Do NOT accumulate untested code — testing only at the end compounds bugs.
Debugging Playbook
When something fails, consult the symptom → likely-cause → fix table in references/cross-cutting.md before trying random fixes — it covers ModuleNotFoundError, BACKBONE_REGISTRY KeyError, shape mismatch, NaN loss, ONNX/TRT build failures, TRT-vs-PyTorch accuracy gaps, OOM, DDP hangs, checkpoint load failures, and stale-submodule config issues.
Environment Isolation Strategy
All Python work runs inside Docker containers — no host venvs, no pip installs into host Python (the host needs only Docker, from tao-setup-nvidia-gpu-host). Three contexts: A (Phase 1 HF inspection in tao-hf-inspect, python:3.12-slim fallback), B (Phase 3/4/6 smoke/L0/e2e in the prepared container, source via pip install /workspace/tao-core && python setup.py develop), C (host-bind-mount scratch). See references/cross-cutting.md for the contexts in full and the four numbered rules verbatim (--check-only host packages; Phase 1 --user $(id -u):$(id -g) vs. root; HOME=/workspace/PIP_USER=1 fallback; distro package-manager list; root:root trade-off; tao-hf-inspect cleanup).
Phase 0 — Prerequisites Check
Goal: verify Python 3.10+ and git; delegate the driver / CUDA / Docker / NVIDIA Container Toolkit host check to tao-setup-nvidia-gpu-host; verify NGC docker login for nvcr.io. Then ask the user for the TAO Toolkit image references (tao-pytorch, tao-deploy, optionally tao-dataservices), pull, and prepare local tags tao-pytorch-base:latest, tao-deploy-base:latest, tao-dataservices-base:latest for later phases — preparation removes the pre-installed released TAO packages so the user's /workspace/... clones install/load via pip install /workspace/tao-core && python setup.py develop. Hard stop on any failed check. Required user inputs: the image references + credentials (NGC login, HF_TOKEN). Full commands, prompt wording, and per-image Dockerfile snippets: the Phase 0 reference.
Gate: all prerequisite checks pass; the user supplied the required image references; tao-pytorch-base:latest and tao-deploy-base:latest exist locally; tao-dataservices-base:latest exists if dataservices work is anticipated.
Phase 1 — Information Gathering & Validation
Goal: decide whether to proceed at all. Gather credentials, locate/clone the four TAO repos, create a consistent working branch, launch the tao-hf-inspect container (Context A), validate the HF model is CV with a supported pipeline_tag, extract config + state-dict schema, sanity-check ONNX export, clean up. Full steps: Phase 1 references.
Reject if: pipeline_tag is NLP / audio / LLM (non-CV); AutoConfig raises; or ONNX export fundamentally cannot work (no rewrite path).
Gate: all 4 TAO repos located/cloned with a consistent branch; pipeline_tag confirmed CV; model_type, image_size, hidden_size, num_labels extracted; state-dict keys documented + HF→TAO remapping plan drafted; ONNX export sanity check passed (or failure understood); user confirmed model_short_name + task type. (Full checklist: phase-1-inspection.md.) Present findings and get user confirmation first.
Phase 2 — Codebase Exploration
Goal: find the closest existing TAO reference model for the detected pipeline_tag, read its implementation across tao-core / tao-pytorch / tao-deploy, and decide whether the backbone exists in backbone_v2/ or is new.
The HF pipeline_tag → TAO reference model mapping (classification → classification_pyt, detection → dino/rtdetr, segmentation → segformer, instance → mask2former, panoptic → oneformer, zero-shot → grounding_dino, depth → mono_depth) drives everything downstream (config, architecture, loss, ONNX shape, TRT builder, deploy classes, metrics, dataset format). See the Phase 2 references for the full reference list (12 files per model), the backbone_v2/ and tao-dataservices coverage checks, and per-task architecture.
If a new backbone is needed, decide the strategy (timm wrap > re-implement > HF black-box wrap) before Phase 3 — it changes weight loading, ONNX export, deploy. Never dual-inherit from transformers.PreTrainedModel and BackboneBase (metaclass conflict — compose instead).
Gate: reference TAO model identified + all 12 reference locations read; task-type implications understood (architecture, loss, ONNX outputs, deploy classes, metrics, dataset); backbone coverage decided (reuse / wrap timm / new); dataservices coverage checked. (Full checklist: phase-2-codebase.md.)
Phase 3 — TAO Core Configuration & Native Implementation
Goal: write the tao-core config schema + the tao-pytorch trainer / native inference / evaluation, smoke-testing between steps. (<model_name> = snake_case short-name; <ModelName> = PascalCase.)
Steps 1–7 (each builds on the previous, smoke-test between): tao-core config (1), tao-pytorch trainer (2), multi-GPU/multi-node (3), native inference → result.csv (4), native evaluation → results.json (5), MLOps for training and eval/infer → status.json (6–7). The ExperimentConfig(CommonExperimentConfig) must contain model, dataset, train, evaluate, inference, export, gen_trt_engine, quantize. All ??? fields are MISSING (user supplies via YAML/CLI); the augmentation.mean/std, model.head.in_channels, checkpoint-name, and onnx_file matches are in the checklist below.
Full per-step bodies, code, the canonical experiment_spec.yaml, and smoke-test commands: the Phase 3 references.
Gates: Step 1 — ExperimentConfig imports cleanly in-container; Step 2 — build_model(cfg) runs + PLModel instantiates in-container; Phase 3 — all 7 steps complete, smoke tests pass, no missing __init__.py.
Phase 4 — Export, Deployment & TensorRT Integration
Goal: ONNX export from tao-pytorch, then TRT engine builder + inference + evaluation in tao-deploy reusing the tao-core ExperimentConfig.
Steps 8–11: ONNX exporter (8 — task-specific input/output names, batch_size=-1 ⇒ dynamic batch); TRT engine builder (9 — subclass EngineBuilder or reuse ClassificationEngineBuilder; write specs/{gen_trt_engine,inference,evaluate}.yaml, same ExperimentConfig schema, augmentation.mean/std MUST match training); TRT inference → result.csv (10); TRT eval → results.json (11). See the Phase 4 reference for full code and the Phase 3+4 gate (3 in-container checks: imports, model build + forward, ONNX round-trip).
Module pitfalls: tao-pytorch and tao-deploy have separate hydra_runner and monitor_status — use the deploy versions in deploy scripts. ExperimentConfig comes from nvidia_tao_core in both (same schema/field paths).
Phase 3+4 gate: all three in-container checks pass (tao-pytorch imports + model + ONNX export; tao-deploy imports).
Phase 5 — Packaging & L0 Testing
Goal: register the model as a console_script in both repos and add unit tests.
Steps 12–15: register '<model_name>=...:main' in console_scripts of tao-pytorch/setup.py (12) and tao-deploy/setup.py (13, creating the deploy entrypoint/<model_name>.py via entrypoint_hydra); deploy L0 tests (14); trainer L0 tests — Trainer(..., fast_dev_run=True) + @pytest.mark.cv_unit @pytest.mark.<model_name> (15). See the Phase 5 reference for exact entry-point strings, code, and L0 test file lists.
Gate: entrypoints registered; pytest files exist and follow the marker convention. Do NOT stop — go directly to Phase 6.
Cross-Phase Data Flow & Consistency Verification
Before Docker testing, verify the chain train → export → gen_trt_engine → inference / evaluate (the *_model_latest.pth → .onnx → .engine artifact flow + the config fields each stage reads/writes — full diagram in references/cross-cutting.md).
Consistency checklist (verify before proceeding): self.checkpoint_filename → the *_latest.pth name evaluate.checkpoint / export.checkpoint reference; augmentation.mean/std identical across training spec, inference.yaml, evaluate.yaml, engine-builder preprocess_mode; ONNX input_names=['input'] / output_names=['output'] (detection/instance-seg use task-specific names); export.input_width/input_height match dataset.img_size; model.head.in_channels matches model_params_mapping.py; classes.txt at dataset.root_dir readable by both repos; all __init__.py exist (incl. scripts/__init__.py for get_subtasks() via pkgutil). Full paths: workflow-consistency.md.
Phase 6 — Container Testing & End-to-End Validation
Mandatory — start immediately after Phase 5. All TAO models ship as Docker images; code that only works outside a container is incomplete. Testing runs directly inside the TAO Toolkit container — no image build in the loop: mount → install source (setup.py develop) → run pytest / pylint / pydocstyle / flake8 directly. Use vanilla commands, NOT the ci/run_functional_tests.py / ci/run_static_tests.py wrappers (internal-mirror-only; public github.com/NVIDIA-TAO/ mirrors have no ci/ dir).
Steps 16–25: verify local image tags exist (16); unit tests for tao-core / tao-pytorch (-m cv_unit, --shm-size=16G) / tao-deploy (17–19); lint (20); wheels (21); end-to-end — train dry-run + export in one tao-pytorch session, then gen_trt_engine + inference + evaluate in one tao-deploy session (same session critical — --rm discards installs) (22); cross-check native vs TRT (23); debug shells (24); optional release images (25).
Full commands (every docker run, per-container env-vars, exact pytest / lint invocations + full-suite variants, the train/export/gen_trt_engine/inference/evaluate one-liner with all CLI overrides, the ci/ note, the fix-and-retest loop) and build scripts / runner patterns: see the Phase 6 references.
Phase 6 gate (Done criteria): tao-core / tao-pytorch / tao-deploy unit tests pass in their containers; static tests pass (or only legacy lint warnings); wheels build; end-to-end <model_name>_model_latest.pth → model.onnx → model.engine → non-empty result.csv + results.json; native vs TRT agree within tolerance.
Phase 7 — Optimization & Tuning (conditional)
Enter only if Phase 6 passes but accuracy / latency / size needs improvement. Ask the user for target metrics first.
Diagnostic categories: accuracy too low; TRT-vs-native gap; training too slow; inference too slow. Techniques: Step 27 — hyperparameter tuning; Step 28 — INT8 quantization (PTQ via torchao / modelopt, TRT INT8 + calibration); Step 29 — channel pruning + retrain; Step 30 — knowledge distillation; Step 31 — resolution tuning (TAO interpolates ViT positional embeddings automatically). See the Phase 7 reference for each category's checks, config blocks, YAML overrides, decision tree, and rationale.
Argument
$ARGUMENTS
If provided, interpret $ARGUMENTS as the HuggingFace model ID or URL to start Phase 1. If credentials or model short-name are not included, ask the user for them before proceeding.
Files
- ATTRIBUTION.mdAdded by AutoGineer948 B
- BENCHMARK.md7.0 KiB
- LICENSELicence file added by AutoGineer11.2 KiB
- SKILL.md17.7 KiB
- config/skillspector-baseline.yaml2.6 KiB
- eval.config3.2 KiB
- evals/evals.json809 B
- references/cross-cutting.md10.1 KiB
- references/docker-patterns.md15.9 KiB
- references/hf-inspection.md6.2 KiB
- references/phase-0-prereqs.md9.9 KiB
- references/phase-1-inspection.md10.1 KiB
- references/phase-2-codebase.md7.3 KiB
- references/phase-3-implementation.md34.7 KiB
- references/phase-4-deploy.md12.7 KiB
- references/phase-5-packaging.md3.3 KiB
- references/phase-6-container-tests.md15.4 KiB
- references/phase-7-optimization.md7.8 KiB
- references/repo-structure.md10.6 KiB
- references/tao-patterns.md20.1 KiB
- references/task-type-guide.md16.4 KiB
- references/workflow-consistency.md27.5 KiB
- skill-card.md4.8 KiB
- skill.oms.sig8.5 KiB
references/tao-patterns.md
<!-- Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -->
TAO Toolkit Code Patterns
Use this reference only when the parent SKILL.md points here for the current task. If this file conflicts with current SKILL.md, skill_info.yaml, schemas, or platform/model skills, the current authoritative source wins.
Contents
Config Dataclasses (
tao-core)
Field types
Base classes for sub-configs
Top-level ExperimentConfig pattern
Model parameters mapping
Backbone (
tao-pytorch)
Required abstract methods on
BackboneBaseAlready-registered backbones in
backbone_v2/
build_model() Pattern (
tao-pytorch)
StateDictAdapter for cross-model checkpoint loading
PyTorch Lightning Module (
tao-pytorch)
TAOLightningModule provides
Constructor pattern
Callbacks (configure_callbacks)
Status logging
Checkpoint save identifier
Script Entrypoints (
tao-pytorchscripts)
Decorator stack (all scripts use this)
Train script (initialize_train_experiment)
CLI Entrypoint (model-level CLI)
ONNX Export (
tao-pytorch)
TensorRT Engine Builder (
tao-deploy)
Base class
Task-specific builder
Deploy script decorator stack (different from tao-pytorch!)
Deploy inference classes
L0 Tests
Test directory layout
Test markers
Trainer dry-run pattern
Deploy test pattern (subprocess)
Packaging (
setup.py)
Canonical patterns extracted from the TAO submodules. Always read the actual source files before implementing — these are guides, not templates to copy blindly.
1. Config Dataclasses (tao-core)
Location: tao-core/nvidia_tao_core/config/<model_name>/default_config.py
Field types
All fields use typed constructors from nvidia_tao_core.config.utils.types:
from nvidia_tao_core.config.utils.types import (
BOOL_FIELD, STR_FIELD, INT_FIELD, FLOAT_FIELD,
LIST_FIELD, DICT_FIELD, DATACLASS_FIELD,
)| Type | Usage |
|---|---|
STR_FIELD(value=..., valid_options=..., description=...) | String fields, optionally constrained |
INT_FIELD(value=..., valid_min=..., valid_max=..., automl_enabled=...) | Integers |
FLOAT_FIELD(value=..., valid_min=..., math_cond=..., automl_enabled=...) | Floats |
BOOL_FIELD(value=..., description=...) | Booleans |
LIST_FIELD(arrList=[...], description=...) | Lists |
DICT_FIELD({...}, default_value={...}, description=...) | Dicts |
DATACLASS_FIELD(DataclassInstance()) | Nested dataclasses |
Base classes for sub-configs
from nvidia_tao_core.config.common.common_config import (
CommonExperimentConfig, # Top-level base
TrainConfig,
EvaluateConfig,
InferenceConfig,
ExportConfig,
GenTrtEngineConfig,
TrtConfig,
CalibrationConfig,
)Top-level ExperimentConfig pattern
@dataclass
class ExperimentConfig(CommonExperimentConfig):
model: ModelConfig = DATACLASS_FIELD(ModelConfig())
dataset: DatasetConfig = DATACLASS_FIELD(DatasetConfig())
train: TrainExpConfig = DATACLASS_FIELD(TrainExpConfig())
evaluate: EvalExpConfig = DATACLASS_FIELD(EvalExpConfig())
inference: InferenceExpConfig = DATACLASS_FIELD(InferenceExpConfig())
export: ExportExpConfig = DATACLASS_FIELD(ExportExpConfig())
gen_trt_engine: GenTrtEngineExpConfig = DATACLASS_FIELD(GenTrtEngineExpConfig())
def __post_init__(self):
if self.model_name is None:
self.model_name = "<model_name>"Model parameters mapping
Location: tao-core/nvidia_tao_core/config/<model_name>/model_params_mapping.py
Maps backbone variant names to their output embedding dimensions. Used by build_model() to auto-wire the head's in_channels:
map_params = {
"head": {
"in_channels": {
"vit_base_patch16": 768,
"vit_large_patch16": 1024,
# ... one entry per backbone variant
}
}
}
# Optional: map input resolutions for backbones that require non-224 sizes
map_input_lr_head = {
"vit_large_patch14_dinov2_swiglu_legacy": 518,
}Reference: tao-core/nvidia_tao_core/config/classification_pyt/default_config.py, model_params_mapping.py
2. Backbone (tao-pytorch)
Location: tao-pytorch/nvidia_tao_pytorch/cv/backbone_v2/
Required abstract methods on BackboneBase
New backbones dual-inherit from both the underlying model (HF/timm) AND BackboneBase. The BackboneMeta metaclass automatically calls _post_init() after __init__, which runs freeze_backbone() and set_grad_checkpointing().
from nvidia_tao_pytorch.cv.backbone_v2.backbone_base import BackboneBase
from nvidia_tao_pytorch.cv.backbone_v2 import BACKBONE_REGISTRY
class MyBackbone(SomeHFOrTimmModel, BackboneBase):
"""Dual-inherit: HF/timm model provides the architecture,
BackboneBase provides TAO integration (freezing, checkpointing, registry)."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# --- 6 abstract methods (all required) ---
def get_stage_dict(self) -> dict:
"""Map stage-index -> nn.Module for layer freezing."""
return {0: self.patch_embed, 1: self.blocks[:4], 2: self.blocks[4:8], ...}
def get_classifier(self) -> nn.Module:
"""Return the classification head (e.g., self.head)."""
return self.head
def reset_classifier(self, num_classes, **kwargs):
"""Replace head for different num_classes."""
self.head = nn.Linear(self.embed_dim, num_classes)
def forward_pre_logits(self, x):
"""Features WITHOUT head. Returns [B, embed_dim]."""
...
def forward_feature_pyramid(self, x, indices=None, **kwargs):
"""Multi-scale features for detection/segmentation.
Returns dict {scale: feature_tensor}. Classification can return {0: features}."""
...
def forward(self, x):
"""Full forward pass with head. Returns logits."""
return self.get_classifier()(self.forward_pre_logits(x))
# --- Factory functions (one per variant) ---
@BACKBONE_REGISTRY.register()
def my_backbone_base(**kwargs):
"""kwargs from build_model(): num_classes, freeze_at, freeze_norm, export, img_size, ..."""
return MyBackbone(embed_dim=768, depth=12, num_heads=12, **kwargs)
@BACKBONE_REGISTRY.register()
def my_backbone_large(**kwargs):
return MyBackbone(embed_dim=1024, depth=24, num_heads=16, **kwargs)Key pattern from existing backbones (e.g., vit.py):
VisionTransformer(TimmVisionTransformer, BackboneBase)— wraps timm's ViTOverrides
forward_pre_logitsto handle positional encoding interpolationEach variant (
vit_base_patch16,vit_large_patch16, etc.) is a factory function with fixed architecture params
Already-registered backbones in backbone_v2/
vit.py, swin.py, resnet.py, convnext.py, convnext_v2.py, dino_v2.py,
fan.py, fastervit.py, gcvit.py, hiera.py, mit.py, edgenext.py,
efficientvit.py, radio.py, siglip2.py, open_clip.py
Reference: tao-pytorch/nvidia_tao_pytorch/cv/backbone_v2/backbone_base.py
3. build_model() Pattern (tao-pytorch)
Location: tao-pytorch/nvidia_tao_pytorch/cv/<model_name>/model/classifier.py (or equivalent)
The build_model() function is the core integration point between config, backbone registry, and pretrained weights:
from nvidia_tao_pytorch.cv.backbone_v2.registry import BACKBONE_REGISTRY
def build_model(experiment_config, export=False):
model_config = experiment_config.model
backbone_type = model_config.backbone.type
# 1. Instantiate backbone from registry
model = BACKBONE_REGISTRY.get(backbone_type)(
num_classes=experiment_config.dataset.num_classes,
freeze_at='all' if model_config.backbone.freeze_backbone else None,
freeze_norm=model_config.backbone.freeze_norm,
export=export
)
# 2. Ensure head remains trainable even if backbone is frozen
if model_config.backbone.freeze_backbone:
head = model.get_classifier()
for p in head.parameters():
p.requires_grad = True
head.train()
# 3. Load pretrained weights with adaptation
if model_config.backbone.pretrained_backbone_path:
state_dict = load_pretrained_weights(
model_config.backbone.pretrained_backbone_path,
parser=cls_parser, # Strips "module." prefix from DDP checkpoints
ptm_adapter=ptm_adapter # Maps prefixes from other TAO model types
)
# Special handling: ViT position embedding interpolation
if isinstance(model, DINOV2):
state_dict = interpolate_vit_checkpoint(state_dict, ...)
msg = model.load_state_dict(state_dict, strict=False)
logger.info(f"Loaded: {msg}")
return modelStateDictAdapter for cross-model checkpoint loading
from nvidia_tao_pytorch.cv.classification_pyt.model.utils import StateDictAdapter
ptm_adapter = StateDictAdapter()
ptm_adapter.add("mae", "model.encoder.") # MAE checkpoints
ptm_adapter.add("classification", "model.") # Classification checkpoints
ptm_adapter.add("rtdetr", "model.model.backbone.") # RT-DETR checkpointsReference: tao-pytorch/nvidia_tao_pytorch/cv/classification_pyt/model/classifier.py, model/utils.py
4. PyTorch Lightning Module (tao-pytorch)
Base class: nvidia_tao_pytorch.core.lightning.tao_lightning_module.TAOLightningModule
TAOLightningModule provides
self.experiment_spec— stored configconfigure_callbacks()— defaultTAOStatusLogger,ModelCheckpoint,TAOExceptionCheckpoint_dataloader_batch_check()— validates dataset_size >= total_batch_sizeon_fit_start(),on_validation_start(),on_test_start(),on_predict_start()— auto-validationon_load_checkpoint()— handles encrypted checkpoint decryption
Constructor pattern
class <ModelName>PlModel(TAOLightningModule):
def __init__(self, experiment_spec, export=False):
super().__init__(experiment_spec)
self.checkpoint_filename = "<model_name>_model" # MUST set
self.dataset_config = self.experiment_spec.dataset
self.model_config = self.experiment_spec.model
self.train_config = self.experiment_spec.train
self.eval_config = self.experiment_spec.evaluate
self.infer_config = self.experiment_spec.inference
self._build_model(export)
self._build_criterion()Callbacks (configure_callbacks)
from pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor
from nvidia_tao_pytorch.core.callbacks.loggers import TAOStatusLogger
from nvidia_tao_pytorch.core.callbacks.ema import EMA, EMAModelCheckpoint
# Always include:
callbacks = [TAOStatusLogger(results_dir, append=True), lr_monitor]
# Checkpoint convention:
ModelCheckpoint.FILE_EXTENSION = ".pth"
ModelCheckpoint.CHECKPOINT_EQUALS_CHAR = "_"
ModelCheckpoint.CHECKPOINT_NAME_LAST = f"{self.checkpoint_filename}_latest"Status logging
import nvidia_tao_pytorch.core.loggers.api_logging as status_logging
status_logging.get_status_logger().kpi = {"train_loss": ..., "val_acc": ...}
status_logging.get_status_logger().write(
message="...", status_level=status_logging.Status.RUNNING
)Checkpoint save identifier
def on_save_checkpoint(self, checkpoint):
checkpoint["tao_model"] = "<model_name>"Reference: tao-pytorch/nvidia_tao_pytorch/core/lightning/tao_lightning_module.py, cv/classification_pyt/model/classifier_pl_model.py
5. Script Entrypoints (tao-pytorch scripts)
Decorator stack (all scripts use this)
from nvidia_tao_pytorch.core.hydra.hydra_runner import hydra_runner
from nvidia_tao_pytorch.core.decorators.workflow import monitor_status
from nvidia_tao_pytorch.core.tlt_logging import obfuscate_logs
from nvidia_tao_core.config.<model_name>.default_config import ExperimentConfig
spec_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@hydra_runner(
config_path=os.path.join(spec_root, "experiment_specs"),
config_name="experiment_spec",
schema=ExperimentConfig
)
@monitor_status(name="<ModelName>", mode="<train|evaluate|inference|export>")
def main(cfg: ExperimentConfig) -> None:
obfuscate_logs(cfg)
...Train script (initialize_train_experiment)
from nvidia_tao_pytorch.core.initialize_experiments import initialize_train_experiment
def run_experiment(experiment_config, key, lightning_module):
resume_ckpt, trainer_kwargs = initialize_train_experiment(experiment_config, key)
dm = <ModelName>DataModule(experiment_config.dataset)
dm.setup(stage="fit")
model = lightning_module(experiment_config)
trainer = Trainer(**trainer_kwargs,
gradient_clip_val=experiment_config.train.clip_grad_norm)
trainer.fit(model, dm, ckpt_path=resume_ckpt)initialize_train_experiment() handles: results_dir creation, GPU config, checkpoint resolution, distributed strategy setup, logger initialization.
CLI Entrypoint (model-level CLI)
from nvidia_tao_pytorch.core.entrypoint import get_subtasks, launch, command_line_parser
def main():
parser = argparse.ArgumentParser("<model_name>", ...)
subtasks = get_subtask_list()
args, unknown_args = command_line_parser(parser, subtasks)
launch(vars(args), unknown_args, subtasks, network="<model_name>")get_subtasks(scripts) auto-discovers all .py files in the scripts/ package. launch() constructs python <script.py> --config-path ... --config-name ... and runs it as a subprocess with GPU configuration.
Reference: tao-pytorch/nvidia_tao_pytorch/core/entrypoint.py, cv/classification_pyt/entrypoint/classification.py, cv/classification_pyt/scripts/train.py
6. ONNX Export (tao-pytorch)
from nvidia_tao_pytorch.cv.classification_pyt.utils.onnx_export import ONNXExporter
from nvidia_tao_pytorch.core.utilities import encrypt_onnx
onnx_export = ONNXExporter()
onnx_export.export_model(
model, batch_size, output_file, dummy_input,
input_names=["input"], output_names=["output"],
opset_version=cfg.export.opset_version,
do_constant_folding=True,
)
onnx_export.check_onnx(output_file)
# Encrypt if needed
if output_file.endswith(".etlt") and key:
encrypt_onnx(tmp_file_name=tmp_onnx_file, output_file_name=output_file, key=key)Always use dynamic_axes={"input": {0: "batch"}, "output": {0: "batch"}} for variable batch size.
Reference: tao-pytorch/nvidia_tao_pytorch/cv/classification_pyt/scripts/export.py
7. TensorRT Engine Builder (tao-deploy)
Base class
Location: tao-deploy/nvidia_tao_deploy/engine/builder.py
from nvidia_tao_deploy.engine.builder import EngineBuilder # Abstract base class
class EngineBuilder(ABC):
def __init__(self, batch_size, verbose, max_batch_size, opt_batch_size,
min_batch_size, workspace, strict_type_constraints, force_ptq,
is_qat, timing_cache_path, strongly_typed):
self.builder = trt.Builder(self.trt_logger)
self.config = self.builder.create_builder_config()
...Task-specific builder
For classification: reuse ClassificationEngineBuilder from tao-deploy/nvidia_tao_deploy/cv/classification_tf1/engine_builder.py.
For other tasks: subclass EngineBuilder directly, implementing:
set_input_output_node_names()Any task-specific preprocessing (mean/std, data format)
Deploy script decorator stack (different from tao-pytorch!)
from nvidia_tao_deploy.cv.common.hydra.hydra_runner import hydra_runner # deploy version
from nvidia_tao_deploy.cv.common.decorators import monitor_status # deploy version
from nvidia_tao_deploy.cv.common.initialize_experiments import initialize_gen_trt_engine_experiment
from nvidia_tao_deploy.utils.decoding import decode_model
from nvidia_tao_deploy.cv.common.utils import is_qdq_quantized_onnxThe deploy @monitor_status handles: results_dir creation, experiment.yaml save, status.json lifecycle, exception categorization (config errors, validation errors, filesystem errors).
Deploy inference classes
from nvidia_tao_deploy.cv.classification_tf1.inferencer import ClassificationInferencer
from nvidia_tao_deploy.cv.classification_tf1.dataloader import ClassificationLoaderClassificationInferencer— wraps TRT engine, handlesinfer(imgs)callsClassificationLoader— NumPy-based batch loader (no PyTorch dependency)
For non-classification tasks, find equivalent inferencer/loader in the task-specific directory.
Reference: tao-deploy/nvidia_tao_deploy/engine/builder.py, cv/classification_pyt/scripts/gen_trt_engine.py, cv/classification_pyt/scripts/inference.py
8. L0 Tests
Test directory layout
tao-pytorch/tests/cv_unit_test/<model_name>/
├── conftest.py # Fixtures: _train_spec, _test_dir, etc.
├── test_model.py # build_model() with various backbones
├── test_trainer.py # PL Trainer fit/evaluate/inference dry-runs
├── test_dataloader.py # Data loading pipeline
├── test_config.py # Config loading & schema validation
└── test_export.py # ONNX export
tao-deploy/tests/<model_name>/
└── test_<model_name>.py # gen_trt_engine, inference, evaluateTest markers
@pytest.mark.cv_unit
@pytest.mark.<model_name>
@pytest.mark.train # or @pytest.mark.evaluate, .inferenceTrainer dry-run pattern
@pytest.mark.parametrize("backbone", TEST_TOPOLOGIES)
def test_trainer_fit(_test_dir, _train_spec, backbone):
_train_spec.model.backbone.type = backbone
dm = <ModelName>DataModule(_train_spec.dataset)
dm.setup(stage="fit")
model = <ModelName>PlModel(_train_spec)
trainer = Trainer(devices=_train_spec.train.num_gpus,
default_root_dir=_train_spec.results_dir,
accelerator='gpu', fast_dev_run=True)
trainer.fit(model, dm)Deploy test pattern (subprocess)
def test_gen_trt_engine(model_path, spec_path, tmp_path):
cmd = f"python {gen_trt_engine_script} -e {spec_path} ..."
result = subprocess.run(cmd, shell=True, capture_output=True)
assert result.returncode == 0
assert (tmp_path / "model.engine").exists()Reference: tao-pytorch/tests/cv_unit_test/classification_pyt/test_trainer.py, tao-deploy/tests/
9. Packaging (setup.py)
tao-pytorch console_scripts
# In tao-pytorch/setup.py, entry_points.console_scripts:
'<model_name>=nvidia_tao_pytorch.cv.<model_name>.entrypoint.<model_name>:main',tao-deploy console_scripts
# In tao-deploy/setup.py, entry_points.console_scripts:
'<model_name>=nvidia_tao_deploy.cv.<model_name>.entrypoint.<model_name>:main',Reference: tao-pytorch/setup.py, tao-deploy/setup.py
10. Core Utilities Summary
| Utility | Import | Purpose |
|---|---|---|
obfuscate_logs(cfg) | nvidia_tao_pytorch.core.tlt_logging | Hide encryption keys in logs |
expand_path(path) | nvidia_tao_pytorch.core.path_utils | Safe tilde expansion + absolute path |
get_global_rank() | nvidia_tao_pytorch.core.distributed.comm | DDP rank (0 if not distributed) |
get_world_size() | nvidia_tao_pytorch.core.distributed.comm | Number of processes |
is_master_node() | nvidia_tao_core.distributed.utils | Multi-framework master check |
get_latest_checkpoint() | nvidia_tao_pytorch.core.utilities | Find latest .pth in results_dir |
TLTPyTorchCookbook | nvidia_tao_pytorch.core.cookbooks | Encryption key management |
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 Python, Needs Node.js
The author says: Requires Python 3.10+, NVIDIA driver, CUDA 13.0+, docker + nvidia-container-toolkit, an NGC API key (`docker login nvcr.io`), an HF_TOKEN, and access to the TAO Toolkit container images on `nvcr.io` for `tao-pytorch`, `tao-deploy`, and (optionally) `tao-dataservices` — Phase 0 asks the user for the exact image references and prepares them locally as `tao-pytorch-base:latest`, `tao-deploy-base:latest`, `tao-dataservices-base:latest`. Local clones of `tao-core`, `tao-pytorch`, `tao-deploy`,...
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-port-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-port-huggingface-model.zip