
Huggingface Vision Trainer
- 1.3k installs
- 10.9k repo stars
- Updated August 4, 2026
- huggingface/skills
huggingface-vision-trainer provides documented workflows for Trains and fine-tunes vision models for object detection (D-FINE, RT-DETR v2, DETR, YOLOS), image classification (timm models - MobileNetV3, MobileViT, ResNe
About
The huggingface-vision-trainer skill trains and fine-tunes vision models for object detection D-FINE RT-DETR v2 DETR YOLOS image classification timm models MobileNetV3 MobileViT ResNet ViT DINOv3 plus any Transformers classifier and SAM SAM2 segmentation using Hugging Face Transformers on Hugging Face Jobs cloud GPUs Covers COCO-format dataset preparation Albumentations augmentation mAP mAR evaluation accuracy metrics SAM segmentation with bbox point prompts DiceCE loss hardware selection cost estimation Tr Vision Model Training on Hugging Face Jobs Train object detection image classification and SAM SAM2 segmentation models on managed cloud GPUs No local GPU setup required results are automatically saved to the Hugging Face Hub When to Use This Skill Use this skill when users want to Fine-tune object detection models D-FINE RT-DETR v2 DETR YOLOS on cloud GPUs or local Fine-tune image classification models timm MobileNetV3 MobileViT ResNet ViT DINOv3 or any Transformers classifier on cloud GPUs or local Fine-tune SAM or SAM2 models for segmentation image matting using bbox or point prompts Train bounding-box detectors on custom datasets Train image classifiers
- Fine-tune object detection models (D-FINE, RT-DETR v2, DETR, YOLOS) on cloud GPUs or local
- Fine-tune image classification models (timm: MobileNetV3, MobileViT, ResNet, ViT/DINOv3, or any Transformers classifier)
- Fine-tune SAM or SAM2 models for segmentation / image matting using bbox or point prompts
- Train bounding-box detectors on custom datasets
- Train image classifiers on custom datasets
Huggingface Vision Trainer by the numbers
- 1,310 all-time installs (skills.sh)
- +46 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #97 of 1,352 Code Review & Quality skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
huggingface-vision-trainer capabilities & compatibility
- Capabilities
- fine tune object detection models (d fine, rt de · fine tune image classification models (timm: mob · fine tune sam or sam2 models for segmentation / · train bounding box detectors on custom datasets · train image classifiers on custom datasets
- Use cases
- documentation
What huggingface-vision-trainer says it does
# Vision Model Training on Hugging Face Jobs Train object detection, image classification, and SAM/SAM2 segmentation models on managed cloud GPUs.
npx skills add https://github.com/huggingface/skills --skill huggingface-vision-trainerAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1.3k |
|---|---|
| repo stars | ★ 10.9k |
| Security audit | 2 / 3 scanners passed |
| Last updated | August 4, 2026 |
| Repository | huggingface/skills ↗ |
How do I use huggingface-vision-trainer for the task described in its SKILL.md triggers?
Trains and fine-tunes vision models for object detection (D-FINE, RT-DETR v2, DETR, YOLOS), image classification (timm models - MobileNetV3, MobileViT, ResNet, ViT/DINOv3 - plus any Transformers.
Who is it for?
Teams invoking huggingface-vision-trainer when the user request matches documented triggers and prerequisites.
Skip if: Skip when cached docs are missing, the request is a negative trigger, or another sibling skill owns the workflow.
When should I use this skill?
Trains and fine-tunes vision models for object detection (D-FINE, RT-DETR v2, DETR, YOLOS), image classification (timm models - MobileNetV3, MobileViT, ResNet, ViT/DINOv3 - plus any Transformers classifier), and SAM/
What you get
Step-by-step guidance grounded in huggingface-vision-trainer documentation and reference files.
- Fine-tuned SAM 2.1 checkpoint
- Training and evaluation scripts
By the numbers
- Uses merve/MicroMat-mini dataset with 90/10 train-test split
- Installs transformers, datasets, monai, and trackio for the training pipeline
Files
Vision Model Training on Hugging Face Jobs
Train object detection, image classification, and SAM/SAM2 segmentation models on managed cloud GPUs. No local GPU setup required—results are automatically saved to the Hugging Face Hub.
When to Use This Skill
Use this skill when users want to:
- Fine-tune object detection models (D-FINE, RT-DETR v2, DETR, YOLOS) on cloud GPUs or local
- Fine-tune image classification models (timm: MobileNetV3, MobileViT, ResNet, ViT/DINOv3, or any Transformers classifier) on cloud GPUs or local
- Fine-tune SAM or SAM2 models for segmentation / image matting using bbox or point prompts
- Train bounding-box detectors on custom datasets
- Train image classifiers on custom datasets
- Train segmentation models on custom mask datasets with prompts
- Run vision training jobs on Hugging Face Jobs infrastructure
- Ensure trained vision models are permanently saved to the Hub
Related Skills
- `hugging-face-jobs` — General HF Jobs infrastructure: token authentication, hardware flavors, timeout management, cost estimation, secrets, environment variables, scheduled jobs, and result persistence. Refer to the Jobs skill for any non-training-specific Jobs questions (e.g., "how do secrets work?", "what hardware is available?", "how do I pass tokens?").
- `hugging-face-model-trainer` — TRL-based language model training (SFT, DPO, GRPO). Use that skill for text/language model fine-tuning.
Local Script Execution
Helper scripts use PEP 723 inline dependencies. Run them with uv run:
uv run scripts/dataset_inspector.py --dataset username/dataset-name --split train
uv run scripts/estimate_cost.py --helpPrerequisites Checklist
Before starting any training job, verify:
Account & Authentication
- Hugging Face Account with Pro, Team, or Enterprise plan (Jobs require paid plan)
- Authenticated login: Check with
hf_whoami()(tool) orhf auth whoami(terminal) - Token has write permissions
- MUST pass token in job secrets — see directive #3 below for syntax (MCP tool vs Python API)
Dataset Requirements — Object Detection
- Dataset must exist on Hub
- Annotations must use the
objectscolumn withbbox,category(and optionallyarea) sub-fields - Bboxes can be in xywh (COCO) or xyxy (Pascal VOC) format — auto-detected and converted
- Categories can be integers or strings — strings are auto-remapped to integer IDs
image_idcolumn is optional — generated automatically if missing- ALWAYS validate unknown datasets before GPU training (see Dataset Validation section)
Dataset Requirements — Image Classification
- Dataset must exist on Hub
- Must have an `image` column (PIL images) and a `label` column (integer class IDs or strings)
- The label column can be
ClassLabeltype (with names) or plain integers/strings — strings are auto-remapped - Common column names auto-detected:
label,labels,class,fine_label - ALWAYS validate unknown datasets before GPU training (see Dataset Validation section)
Dataset Requirements — SAM/SAM2 Segmentation
- Dataset must exist on Hub
- Must have an `image` column (PIL images) and a `mask` column (binary ground-truth segmentation mask)
- Must have a prompt — either:
- A `prompt` column with JSON containing
{"bbox": [x0,y0,x1,y1]}or{"point": [x,y]} - OR a dedicated `bbox` column with
[x0,y0,x1,y1]values - OR a dedicated `point` column with
[x,y]or[[x,y],...]values - Bboxes should be in xyxy format (absolute pixel coordinates)
- Example dataset:
merve/MicroMat-mini(image matting with bbox prompts) - ALWAYS validate unknown datasets before GPU training (see Dataset Validation section)
Critical Settings
- Timeout must exceed expected training time — Default 30min is TOO SHORT. See directive #6 for recommended values.
- Hub push must be enabled —
push_to_hub=True,hub_model_id="username/model-name", token insecrets
Dataset Validation
Validate dataset format BEFORE launching GPU training to prevent the #1 cause of training failures: format mismatches.
ALWAYS validate for unknown/custom datasets or any dataset you haven't trained with before. Skip for cppe-5 (the default in the training script).
Running the Inspector
Option 1: Via HF Jobs (recommended — avoids local SSL/dependency issues):
hf_jobs("uv", {
"script": "path/to/dataset_inspector.py",
"script_args": ["--dataset", "username/dataset-name", "--split", "train"]
})Option 2: Locally:
uv run scripts/dataset_inspector.py --dataset username/dataset-name --split trainOption 3: Via `HfApi().run_uv_job()` (if hf_jobs MCP unavailable):
from huggingface_hub import HfApi
api = HfApi()
api.run_uv_job(
script="scripts/dataset_inspector.py",
script_args=["--dataset", "username/dataset-name", "--split", "train"],
flavor="cpu-basic",
timeout=300,
)Reading Results
- `✓ READY` — Dataset is compatible, use directly
- `✗ NEEDS FORMATTING` — Needs preprocessing (mapping code provided in output)
Automatic Bbox Preprocessing
The object detection training script (scripts/object_detection_training.py) automatically handles bbox format detection (xyxy→xywh conversion), bbox sanitization, image_id generation, string category→integer remapping, and dataset truncation. No manual preprocessing needed — just ensure the dataset has objects.bbox and objects.category columns.
Training workflow
Copy this checklist and track progress:
Training Progress:
- [ ] Step 1: Verify prerequisites (account, token, dataset)
- [ ] Step 2: Validate dataset format (run dataset_inspector.py)
- [ ] Step 3: Ask user about dataset size and validation split
- [ ] Step 4: Prepare training script (OD: scripts/object_detection_training.py, IC: scripts/image_classification_training.py, SAM: scripts/sam_segmentation_training.py)
- [ ] Step 5: Save script locally, submit job, and report detailsStep 1: Verify prerequisites
Follow the Prerequisites Checklist above.
Step 2: Validate dataset
Run the dataset inspector BEFORE spending GPU time. See "Dataset Validation" section above.
Step 3: Ask user preferences
ALWAYS use the AskUserQuestion tool with option-style format:
AskUserQuestion({
"questions": [
{
"question": "Do you want to run a quick test with a subset of the data first?",
"header": "Dataset Size",
"options": [
{"label": "Quick test run (10% of data)", "description": "Faster, cheaper (~30-60 min, ~$2-5) to validate setup"},
{"label": "Full dataset (Recommended)", "description": "Complete training for best model quality"}
],
"multiSelect": false
},
{
"question": "Do you want to create a validation split from the training data?",
"header": "Split data",
"options": [
{"label": "Yes (Recommended)", "description": "Automatically split 15% of training data for validation"},
{"label": "No", "description": "Use existing validation split from dataset"}
],
"multiSelect": false
},
{
"question": "Which GPU hardware do you want to use?",
"header": "Hardware Flavor",
"options": [
{"label": "t4-small ($0.40/hr)", "description": "1x T4, 16 GB VRAM — sufficient for all OD models under 100M params"},
{"label": "l4x1 ($0.80/hr)", "description": "1x L4, 24 GB VRAM — more headroom for large images or batch sizes"},
{"label": "a10g-large ($1.50/hr)", "description": "1x A10G, 24 GB VRAM — faster training, more CPU/RAM"},
{"label": "a100-large ($2.50/hr)", "description": "1x A100, 80 GB VRAM — fastest, for very large datasets or image sizes"}
],
"multiSelect": false
}
]
})Step 4: Prepare training script
For object detection, use scripts/object_detection_training.py as the production-ready template. For image classification, use scripts/image_classification_training.py. For SAM/SAM2 segmentation, use scripts/sam_segmentation_training.py. All scripts use HfArgumentParser — all configuration is passed via CLI arguments in script_args, NOT by editing Python variables. For timm model details, see references/timm_trainer.md. For SAM2 training details, see references/finetune_sam2_trainer.md.
Step 5: Save script, submit job, and report
1. Save the script locally to submitted_jobs/ in the workspace root (create if needed) with a descriptive name like training_<dataset>_<YYYYMMDD_HHMMSS>.py. Tell the user the path. 2. Submit using hf_jobs MCP tool (preferred) or HfApi().run_uv_job() — see directive #1 for both methods. Pass all config via script_args. 3. Report the job ID (from .id attribute), monitoring URL, Trackio dashboard (https://huggingface.co/spaces/{username}/trackio), expected time, and estimated cost. 4. Wait for user to request status checks — don't poll automatically. Training jobs run asynchronously and can take hours.
Critical directives
These rules prevent common failures. Follow them exactly.
1. Job submission: hf_jobs MCP tool vs Python API
`hf_jobs()` is an MCP tool, NOT a Python function. Do NOT try to import it from huggingface_hub. Call it as a tool:
hf_jobs("uv", {"script": training_script_content, "flavor": "a10g-large", "timeout": "4h", "secrets": {"HF_TOKEN": "$HF_TOKEN"}})If `hf_jobs` MCP tool is unavailable, use the Python API directly:
from huggingface_hub import HfApi, get_token
api = HfApi()
job_info = api.run_uv_job(
script="path/to/training_script.py", # file PATH, NOT content
script_args=["--dataset_name", "cppe-5", ...],
flavor="a10g-large",
timeout=14400, # seconds (4 hours)
env={"PYTHONUNBUFFERED": "1"},
secrets={"HF_TOKEN": get_token()}, # MUST use get_token(), NOT "$HF_TOKEN"
)
print(f"Job ID: {job_info.id}")Critical differences between the two methods:
hf_jobs MCP tool | HfApi().run_uv_job() | |
|---|---|---|
script param | Python code string or URL (NOT local paths) | File path to .py file (NOT content) |
| Token in secrets | "$HF_TOKEN" (auto-replaced) | get_token() (actual token value) |
| Timeout format | String ("4h") | Seconds (14400) |
Rules for both methods:
- The training script MUST include PEP 723 inline metadata with dependencies
- Do NOT use
imageorcommandparameters (those belong torun_job(), notrun_uv_job())
2. Authentication via job secrets + explicit hub_token injection
Job config MUST include the token in secrets — syntax depends on submission method (see table above).
Training script requirement: The Transformers Trainer calls create_repo(token=self.args.hub_token) during __init__() when push_to_hub=True. The training script MUST inject HF_TOKEN into training_args.hub_token AFTER parsing args but BEFORE creating the Trainer. The template scripts/object_detection_training.py already includes this:
hf_token = os.environ.get("HF_TOKEN")
if training_args.push_to_hub and not training_args.hub_token:
if hf_token:
training_args.hub_token = hf_tokenIf you write a custom script, you MUST include this token injection before the Trainer(...) call.
- Do NOT call
login()in custom scripts unless replicating the full pattern fromscripts/object_detection_training.py - Do NOT rely on implicit token resolution (
hub_token=None) — unreliable in Jobs - See the
hugging-face-jobsskill → Token Usage Guide for full details
3. JobInfo attribute
Access the job identifier using .id (NOT .job_id or .name — these don't exist):
job_info = api.run_uv_job(...) # or hf_jobs("uv", {...})
job_id = job_info.id # Correct -- returns string like "687fb701029421ae5549d998"4. Required training flags and HfArgumentParser boolean syntax
scripts/object_detection_training.py uses HfArgumentParser — all config is passed via script_args. Boolean arguments have two syntaxes:
- `bool` fields (e.g.,
push_to_hub,do_train): Use as bare flags (--push_to_hub) or negate with--no_prefix (--no_remove_unused_columns) - `Optional[bool]` fields (e.g.,
greater_is_better): MUST pass explicit value (--greater_is_better True). Bare--greater_is_bettercauseserror: expected one argument
Required flags for object detection:
--no_remove_unused_columns # MUST: preserves image column for pixel_values
--no_eval_do_concat_batches # MUST: images have different numbers of target boxes
--push_to_hub # MUST: environment is ephemeral
--hub_model_id username/model-name
--metric_for_best_model eval_map
--greater_is_better True # MUST pass "True" explicitly (Optional[bool])
--do_train
--do_evalRequired flags for image classification:
--no_remove_unused_columns # MUST: preserves image column for pixel_values
--push_to_hub # MUST: environment is ephemeral
--hub_model_id username/model-name
--metric_for_best_model eval_accuracy
--greater_is_better True # MUST pass "True" explicitly (Optional[bool])
--do_train
--do_evalRequired flags for SAM/SAM2 segmentation:
--remove_unused_columns False # MUST: preserves input_boxes/input_points
--push_to_hub # MUST: environment is ephemeral
--hub_model_id username/model-name
--do_train
--prompt_type bbox # or "point"
--dataloader_pin_memory False # MUST: avoids pin_memory issues with custom collator5. Timeout management
Default 30 min is TOO SHORT for object detection. Set minimum 2-4 hours. Add 30% buffer for model loading, preprocessing, and Hub push.
| Scenario | Timeout |
|---|---|
| Quick test (100-200 images, 5-10 epochs) | 1h |
| Development (500-1K images, 15-20 epochs) | 2-3h |
| Production (1K-5K images, 30 epochs) | 4-6h |
| Large dataset (5K+ images) | 6-12h |
6. Trackio monitoring
Trackio is always enabled in the object detection training script — it calls trackio.init() and trackio.finish() automatically. No need to pass --report_to trackio. The project name is taken from --output_dir and the run name from --run_name. For image classification, pass --report_to trackio in TrainingArguments.
Dashboard at: https://huggingface.co/spaces/{username}/trackio
Model & hardware selection
Recommended object detection models
| Model | Params | Use case |
|---|---|---|
ustc-community/dfine-small-coco | 10.4M | Best starting point — fast, cheap, SOTA quality |
PekingU/rtdetr_v2_r18vd | 20.2M | Lightweight real-time detector |
ustc-community/dfine-large-coco | 31.4M | Higher accuracy, still efficient |
PekingU/rtdetr_v2_r50vd | 43M | Strong real-time baseline |
ustc-community/dfine-xlarge-obj365 | 63.5M | Best accuracy (pretrained on Objects365) |
PekingU/rtdetr_v2_r101vd | 76M | Largest RT-DETR v2 variant |
Start with ustc-community/dfine-small-coco for fast iteration. Move to D-FINE Large or RT-DETR v2 R50 for better accuracy.
Recommended image classification models
All timm/ models work out of the box via AutoModelForImageClassification (loaded as TimmWrapperForImageClassification). See references/timm_trainer.md for details.
| Model | Params | Use case |
|---|---|---|
timm/mobilenetv3_small_100.lamb_in1k | 2.5M | Ultra-lightweight — mobile/edge, fastest training |
timm/mobilevit_s.cvnets_in1k | 5.6M | Mobile transformer — good accuracy/speed trade-off |
timm/resnet50.a1_in1k | 25.6M | Strong CNN baseline — reliable, well-studied |
timm/vit_base_patch16_dinov3.lvd1689m | 86.6M | Best accuracy — DINOv3 self-supervised ViT |
Start with timm/mobilenetv3_small_100.lamb_in1k for fast iteration. Move to timm/resnet50.a1_in1k or timm/vit_base_patch16_dinov3.lvd1689m for better accuracy.
Recommended SAM/SAM2 segmentation models
| Model | Params | Use case |
|---|---|---|
facebook/sam2.1-hiera-tiny | 38.9M | Fastest SAM2 — good for quick experiments |
facebook/sam2.1-hiera-small | 46.0M | Best starting point — good quality/speed balance |
facebook/sam2.1-hiera-base-plus | 80.8M | Higher capacity for complex segmentation |
facebook/sam2.1-hiera-large | 224.4M | Best SAM2 accuracy — requires more VRAM |
facebook/sam-vit-base | 93.7M | Original SAM — ViT-B backbone |
facebook/sam-vit-large | 312.3M | Original SAM — ViT-L backbone |
facebook/sam-vit-huge | 641.1M | Original SAM — ViT-H, best SAM v1 accuracy |
Start with facebook/sam2.1-hiera-small for fast iteration. SAM2 models are generally more efficient than SAM v1 at similar quality. Only the mask decoder is trained by default (vision and prompt encoders are frozen).
Hardware recommendation
All recommended OD and IC models are under 100M params — `t4-small` (16 GB VRAM, $0.40/hr) is sufficient for all of them. Image classification models are generally smaller and faster than object detection models — t4-small handles even ViT-Base comfortably. For SAM2 models up to hiera-base-plus, t4-small is sufficient since only the mask decoder is trained. For sam2.1-hiera-large or SAM v1 models, use l4x1 or a10g-large. Only upgrade if you hit OOM from large batch sizes — reduce batch size first before switching hardware. Common upgrade path: t4-small → l4x1 ($0.80/hr, 24 GB) → a10g-large ($1.50/hr, 24 GB).
For full hardware flavor list: refer to the hugging-face-jobs skill. For cost estimation: run scripts/estimate_cost.py.
Quick start — Object Detection
The script_args below are the same for both submission methods. See directive #1 for the critical differences between them.
OD_SCRIPT_ARGS = [
"--model_name_or_path", "ustc-community/dfine-small-coco",
"--dataset_name", "cppe-5",
"--image_square_size", "640",
"--output_dir", "dfine_finetuned",
"--num_train_epochs", "30",
"--per_device_train_batch_size", "8",
"--learning_rate", "5e-5",
"--eval_strategy", "epoch",
"--save_strategy", "epoch",
"--save_total_limit", "2",
"--load_best_model_at_end",
"--metric_for_best_model", "eval_map",
"--greater_is_better", "True",
"--no_remove_unused_columns",
"--no_eval_do_concat_batches",
"--push_to_hub",
"--hub_model_id", "username/model-name",
"--do_train",
"--do_eval",
]from huggingface_hub import HfApi, get_token
api = HfApi()
job_info = api.run_uv_job(
script="scripts/object_detection_training.py",
script_args=OD_SCRIPT_ARGS,
flavor="t4-small",
timeout=14400,
env={"PYTHONUNBUFFERED": "1"},
secrets={"HF_TOKEN": get_token()},
)
print(f"Job ID: {job_info.id}")Key OD script_args
--model_name_or_path— recommended:"ustc-community/dfine-small-coco"(see model table above)--dataset_name— the Hub dataset ID--image_square_size— 480 (fast iteration) or 800 (better accuracy)--hub_model_id—"username/model-name"for Hub persistence--num_train_epochs— 30 typical for convergence--train_val_split— fraction to split for validation (default 0.15), set if dataset lacks a validation split--max_train_samples— truncate training set (useful for quick test runs, e.g."785"for ~10% of a 7.8K dataset)--max_eval_samples— truncate evaluation set
Quick start — Image Classification
IC_SCRIPT_ARGS = [
"--model_name_or_path", "timm/mobilenetv3_small_100.lamb_in1k",
"--dataset_name", "ethz/food101",
"--output_dir", "food101_classifier",
"--num_train_epochs", "5",
"--per_device_train_batch_size", "32",
"--per_device_eval_batch_size", "32",
"--learning_rate", "5e-5",
"--eval_strategy", "epoch",
"--save_strategy", "epoch",
"--save_total_limit", "2",
"--load_best_model_at_end",
"--metric_for_best_model", "eval_accuracy",
"--greater_is_better", "True",
"--no_remove_unused_columns",
"--push_to_hub",
"--hub_model_id", "username/food101-classifier",
"--do_train",
"--do_eval",
]from huggingface_hub import HfApi, get_token
api = HfApi()
job_info = api.run_uv_job(
script="scripts/image_classification_training.py",
script_args=IC_SCRIPT_ARGS,
flavor="t4-small",
timeout=7200,
env={"PYTHONUNBUFFERED": "1"},
secrets={"HF_TOKEN": get_token()},
)
print(f"Job ID: {job_info.id}")Key IC script_args
--model_name_or_path— anytimm/model or Transformers classification model (see model table above)--dataset_name— the Hub dataset ID--image_column_name— column containing PIL images (default:"image")--label_column_name— column containing class labels (default:"label")--hub_model_id—"username/model-name"for Hub persistence--num_train_epochs— 3-5 typical for classification (fewer than OD)--per_device_train_batch_size— 16-64 (classification models use less memory than OD)--train_val_split— fraction to split for validation (default 0.15), set if dataset lacks a validation split--max_train_samples/--max_eval_samples— truncate for quick tests
Quick start — SAM/SAM2 Segmentation
SAM_SCRIPT_ARGS = [
"--model_name_or_path", "facebook/sam2.1-hiera-small",
"--dataset_name", "merve/MicroMat-mini",
"--prompt_type", "bbox",
"--prompt_column_name", "prompt",
"--output_dir", "sam2-finetuned",
"--num_train_epochs", "30",
"--per_device_train_batch_size", "4",
"--learning_rate", "1e-5",
"--logging_steps", "1",
"--save_strategy", "epoch",
"--save_total_limit", "2",
"--remove_unused_columns", "False",
"--dataloader_pin_memory", "False",
"--push_to_hub",
"--hub_model_id", "username/sam2-finetuned",
"--do_train",
"--report_to", "trackio",
]from huggingface_hub import HfApi, get_token
api = HfApi()
job_info = api.run_uv_job(
script="scripts/sam_segmentation_training.py",
script_args=SAM_SCRIPT_ARGS,
flavor="t4-small",
timeout=7200,
env={"PYTHONUNBUFFERED": "1"},
secrets={"HF_TOKEN": get_token()},
)
print(f"Job ID: {job_info.id}")Key SAM script_args
--model_name_or_path— SAM or SAM2 model (see model table above); auto-detects SAM vs SAM2--dataset_name— the Hub dataset ID (e.g.,"merve/MicroMat-mini")--prompt_type—"bbox"or"point"— type of prompt in the dataset--prompt_column_name— column with JSON-encoded prompts (default:"prompt")--bbox_column_name— dedicated bbox column (alternative to JSON prompt column)--point_column_name— dedicated point column (alternative to JSON prompt column)--mask_column_name— column with ground-truth masks (default:"mask")--hub_model_id—"username/model-name"for Hub persistence--num_train_epochs— 20-30 typical for SAM fine-tuning--per_device_train_batch_size— 2-4 (SAM models use significant memory)--freeze_vision_encoder/--freeze_prompt_encoder— freeze encoder weights (default: both frozen, only mask decoder trains)--train_val_split— fraction to split for validation (default 0.1)
Checking job status
MCP tool (if available):
hf_jobs("ps") # List all jobs
hf_jobs("logs", {"job_id": "your-job-id"}) # View logs
hf_jobs("inspect", {"job_id": "your-job-id"}) # Job detailsPython API fallback:
from huggingface_hub import HfApi
api = HfApi()
api.list_jobs() # List all jobs
api.get_job_logs(job_id="your-job-id") # View logs
api.get_job(job_id="your-job-id") # Job detailsCommon failure modes
OOM (CUDA out of memory)
Reduce per_device_train_batch_size (try 4, then 2), reduce IMAGE_SIZE, or upgrade hardware.
Dataset format errors
Run scripts/dataset_inspector.py first. The training script auto-detects xyxy vs xywh, converts string categories to integer IDs, and adds image_id if missing. Ensure objects.bbox contains 4-value coordinate lists in absolute pixels and objects.category contains either integer IDs or string labels.
Hub push failures (401)
Verify: (1) job secrets include token (see directive #2), (2) script sets training_args.hub_token BEFORE creating the Trainer, (3) push_to_hub=True is set, (4) correct hub_model_id, (5) token has write permissions.
Job timeout
Increase timeout (see directive #5 table), reduce epochs/dataset, or use checkpoint strategy with hub_strategy="every_save".
KeyError: 'test' (missing test split)
The object detection training script handles this gracefully — it falls back to the validation split. Ensure you're using the latest scripts/object_detection_training.py.
Single-class dataset: "iteration over a 0-d tensor"
torchmetrics.MeanAveragePrecision returns scalar (0-d) tensors for per-class metrics when there's only one class. The template scripts/object_detection_training.py handles this by calling .unsqueeze(0) on these tensors. Ensure you're using the latest template.
Poor detection performance (mAP < 0.15)
Increase epochs (30-50), ensure 500+ images, check per-class mAP for imbalanced classes, try different learning rates (1e-5 to 1e-4), increase image size.
For comprehensive troubleshooting: see references/reliability_principles.md
Reference files
- scripts/object_detection_training.py — Production-ready object detection training script
- scripts/image_classification_training.py — Production-ready image classification training script (supports timm models)
- scripts/sam_segmentation_training.py — Production-ready SAM/SAM2 segmentation training script (bbox & point prompts)
- scripts/dataset_inspector.py — Validate dataset format for OD, classification, and SAM segmentation
- scripts/estimate_cost.py — Estimate training costs for any vision model (includes SAM/SAM2)
- references/object_detection_training_notebook.md — Object detection training workflow, augmentation strategies, and training patterns
- references/image_classification_training_notebook.md — Image classification training workflow with ViT, preprocessing, and evaluation
- references/finetune_sam2_trainer.md — SAM2 fine-tuning walkthrough with MicroMat dataset, DiceCE loss, and Trainer integration
- references/timm_trainer.md — Using timm models with HF Trainer (TimmWrapper, transforms, full example)
- references/hub_saving.md — Detailed Hub persistence guide and verification checklist
- references/reliability_principles.md — Failure prevention principles from production experience
External links
- Transformers Object Detection Guide
- Transformers Image Classification Guide
- DETR Model Documentation
- ViT Model Documentation
- HF Jobs Guide — Main Jobs documentation
- HF Jobs Configuration — Hardware, secrets, timeouts, namespaces
- HF Jobs CLI Reference — Command line interface
- Object Detection Models
- Image Classification Models
- SAM2 Model Documentation
- SAM Model Documentation
- Object Detection Datasets
- Image Classification Datasets
Fine-tuning SAM2 with HF Trainer
Fine-tune SAM2.1 on a small part of the MicroMat dataset for image matting, using the Hugging Face Trainer with a custom loss function.
!pip install -q transformers datasets monai trackioLoad and explore the dataset
from datasets import load_dataset
dataset = load_dataset("merve/MicroMat-mini", split="train")
datasetdataset = dataset.train_test_split(test_size=0.1)
train_ds = dataset["train"]
val_ds = dataset["test"]import json
train_ds[0]json.loads(train_ds["prompt"][0])["bbox"]Visualize a sample
import matplotlib.pyplot as plt
import numpy as np
def show_mask(mask, ax, bbox):
color = np.array([0.12, 0.56, 1.0, 0.6])
mask = np.array(mask)
h, w = mask.shape
mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, 4)
ax.imshow(mask_image)
x0, y0, x1, y1 = bbox
ax.add_patch(
plt.Rectangle(
(x0, y0), x1 - x0, y1 - y0, fill=False, edgecolor="lime", linewidth=2
)
)
example = train_ds[0]
image = np.array(example["image"])
ground_truth_mask = np.array(example["mask"])
fig, ax = plt.subplots()
ax.imshow(image)
show_mask(ground_truth_mask, ax, json.loads(example["prompt"])["bbox"])
ax.set_title("Ground truth mask")
ax.set_axis_off()
plt.show()Build the dataset and collator
SAMDataset wraps each sample into the format expected by the SAM2 processor. Ground-truth masks are stored under the key "labels" so the Trainer automatically pops them before calling model.forward().
from torch.utils.data import Dataset
import torch
import torch.nn.functional as F
class SAMDataset(Dataset):
def __init__(self, dataset, processor):
self.dataset = dataset
self.processor = processor
def __len__(self):
return len(self.dataset)
def __getitem__(self, idx):
item = self.dataset[idx]
image = item["image"]
prompt = json.loads(item["prompt"])["bbox"]
inputs = self.processor(image, input_boxes=[[prompt]], return_tensors="pt")
inputs["labels"] = (np.array(item["mask"]) > 0).astype(np.float32)
inputs["original_image_size"] = torch.tensor(image.size[::-1])
return inputs
def collate_fn(batch):
pixel_values = torch.cat([item["pixel_values"] for item in batch], dim=0)
original_sizes = torch.stack([item["original_sizes"] for item in batch])
input_boxes = torch.cat([item["input_boxes"] for item in batch], dim=0)
labels = torch.cat(
[
F.interpolate(
torch.as_tensor(x["labels"]).unsqueeze(0).unsqueeze(0).float(),
size=(256, 256),
mode="nearest",
)
for x in batch
],
dim=0,
).long()
return {
"pixel_values": pixel_values,
"original_sizes": original_sizes,
"input_boxes": input_boxes,
"labels": labels,
"original_image_size": torch.stack(
[item["original_image_size"] for item in batch]
),
"multimask_output": False,
}from transformers import Sam2Processor
processor = Sam2Processor.from_pretrained("facebook/sam2.1-hiera-small")
train_dataset = SAMDataset(dataset=train_ds, processor=processor)
val_dataset = SAMDataset(dataset=val_ds, processor=processor)Load model and freeze encoder layers
from transformers import Sam2Model
model = Sam2Model.from_pretrained("facebook/sam2.1-hiera-small")
for name, param in model.named_parameters():
if name.startswith("vision_encoder") or name.startswith("prompt_encoder"):
param.requires_grad_(False)Inference before training
item = val_ds[1]
img = item["image"]
bbox = json.loads(item["prompt"])["bbox"]
inputs = processor(images=img, input_boxes=[[bbox]], return_tensors="pt").to(
model.device
)
with torch.no_grad():
outputs = model(**inputs)
masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]
preds = masks.squeeze(0)
mask = (preds[0] > 0).cpu().numpy()
overlay = np.asarray(img, dtype=np.uint8).copy()
overlay[mask] = 0.55 * overlay[mask] + 0.45 * np.array([0, 255, 0], dtype=np.float32)
plt.imshow(overlay)
plt.title("Before training")
plt.axis("off")
plt.show()Define custom loss
SAM2 does not compute loss in its forward(), so we provide a compute_loss_func to the Trainer. The Trainer pops "labels" from the batch before calling model(**inputs), then passes (outputs, labels) to this function.
import monai
from transformers import Trainer, TrainingArguments
import trackio
seg_loss = monai.losses.DiceCELoss(sigmoid=True, squared_pred=True, reduction="mean")
def compute_loss(outputs, labels, num_items_in_batch=None):
predicted_masks = outputs.pred_masks.squeeze(1)
return seg_loss(predicted_masks, labels.float())Train with Trainer
Key settings:
remove_unused_columns=False: the Trainer must keepinput_boxes,
original_sizes, etc. that are not in the model's forward() signature.
compute_loss_func: our custom DiceCE loss.report_to="trackio": logs the training loss to trackio.
training_args = TrainingArguments(
output_dir="sam2-finetuned",
num_train_epochs=30,
per_device_train_batch_size=4,
learning_rate=1e-5,
weight_decay=0,
logging_steps=1,
save_strategy="epoch",
save_total_limit=2,
remove_unused_columns=False,
dataloader_pin_memory=False,
report_to="trackio",
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
data_collator=collate_fn,
compute_loss_func=compute_loss,
)
trainer.train()Inference after training
item = val_ds[1]
img = item["image"]
bbox = json.loads(item["prompt"])["bbox"]
inputs = processor(images=img, input_boxes=[[bbox]], return_tensors="pt").to(
model.device
)
with torch.no_grad():
outputs = model(**inputs)
preds = processor.post_process_masks(
outputs.pred_masks.cpu(), inputs["original_sizes"]
)[0]
preds = preds.squeeze(0)
mask = (preds[0] > 0).cpu().numpy()
overlay = np.asarray(img, dtype=np.uint8).copy()
overlay[mask] = 0.55 * overlay[mask] + 0.45 * np.array([0, 255, 0], dtype=np.float32)
plt.imshow(overlay)
plt.title("After training")
plt.axis("off")
plt.show()Saving Vision Models to Hugging Face Hub
Contents
- Why Hub Push is Required
- Required Configuration (TrainingArguments, job config)
- Complete Example
- What Gets Saved
- Important: Save Image Processor
- Checkpoint Saving
- Model Card Configuration
- Saving Label Mappings
- Authentication Methods
- Verification Checklist
- Repository Setup (automatic/manual creation, naming)
- Troubleshooting (401, 403, push failures, inference issues)
- Manual Push After Training
- Example: Full Production Setup
- Inference Example
---
CRITICAL: Training environments are ephemeral. ALL results are lost when a job completes unless pushed to the Hub.
Why Hub Push is Required
When running on Hugging Face Jobs:
- Environment is temporary
- All files deleted on job completion
- No local disk persistence
- Cannot access results after job ends
Without Hub push, training is completely wasted.
Required Configuration
1. Training Configuration
In your TrainingArguments:
from transformers import TrainingArguments
training_args = TrainingArguments(
output_dir="my-object-detector",
push_to_hub=True, # Enable Hub push
hub_model_id="username/model-name", # Target repository
)2. Job Configuration
When submitting the job:
hf_jobs("uv", {
"script": training_script_content, # Pass the Python script content directly as a string
"secrets": {"HF_TOKEN": "$HF_TOKEN"} # Provide authentication
})The `$HF_TOKEN` syntax references your actual Hugging Face token value.
Complete Example
# train_detector.py
# /// script
# dependencies = ["transformers", "torch", "torchvision", "datasets"]
# ///
from transformers import (
AutoImageProcessor,
AutoModelForObjectDetection,
TrainingArguments,
Trainer
)
from datasets import load_dataset
import os
import torch
# Load dataset
dataset = load_dataset("cppe-5", split="train")
# Load model and processor
model_name = "facebook/detr-resnet-50"
image_processor = AutoImageProcessor.from_pretrained(model_name)
model = AutoModelForObjectDetection.from_pretrained(
model_name,
num_labels=5, # Number of classes
ignore_mismatched_sizes=True
)
# Configure with Hub push
training_args = TrainingArguments(
output_dir="my-detector",
num_train_epochs=10,
per_device_train_batch_size=8,
# ✅ CRITICAL: Hub push configuration
push_to_hub=True,
hub_model_id="myusername/cppe5-detector",
# Optional: Push strategy
hub_strategy="checkpoint", # Push checkpoints during training
)
# ✅ CRITICAL: Authenticate with Hub BEFORE creating Trainer
from huggingface_hub import login
hf_token = os.environ.get("HF_TOKEN") or os.environ.get("hfjob")
if hf_token:
login(token=hf_token)
training_args.hub_token = hf_token
elif training_args.push_to_hub:
raise ValueError("HF_TOKEN not found! Add secrets={'HF_TOKEN': '$HF_TOKEN'} to job config.")
# Define collate function
def collate_fn(batch):
pixel_values = [item["pixel_values"] for item in batch]
labels = [item["labels"] for item in batch]
encoding = image_processor.pad(pixel_values, return_tensors="pt")
return {
"pixel_values": encoding["pixel_values"],
"labels": labels
}
trainer = Trainer(
model=model,
args=training_args,
train_dataset=dataset,
data_collator=collate_fn,
)
trainer.train()
# ✅ Push final model and processor
trainer.push_to_hub()
image_processor.push_to_hub("myusername/cppe5-detector")
print("✅ Model saved to: https://huggingface.co/myusername/cppe5-detector")Submit with authentication:
hf_jobs("uv", {
"script": training_script_content, # Pass script content as a string, NOT a filename
"flavor": "a10g-large",
"timeout": "4h",
"secrets": {"HF_TOKEN": "$HF_TOKEN"} # ✅ Required!
})What Gets Saved
When push_to_hub=True:
1. Model weights - Final trained parameters 2. Image processor - Associated preprocessing configuration 3. Configuration - Model config (config.json) including:
- Number of labels/classes
- Architecture details (backbone, num_queries, etc.)
- Label mappings (id2label, label2id)
4. Training arguments - Hyperparameters used 5. Model card - Auto-generated documentation 6. Checkpoints - If save_strategy="steps" enabled
Important: Save Image Processor
Object detection models require the image processor to be saved separately:
# After training completes
trainer.push_to_hub()
# ✅ Also push the image processor
image_processor.push_to_hub(
repo_id="username/model-name",
commit_message="Upload image processor"
)Why this matters:
- Models need specific image preprocessing (resizing, normalization)
- Image processor contains critical configuration
- Without it, model cannot be used for inference
Checkpoint Saving
Save intermediate checkpoints during training:
TrainingArguments(
output_dir="my-detector",
push_to_hub=True,
hub_model_id="username/my-detector",
# Checkpoint configuration
save_strategy="steps",
save_steps=500, # Save every 500 steps
save_total_limit=3, # Keep only last 3 checkpoints
hub_strategy="checkpoint", # Push checkpoints to Hub
)Benefits:
- Resume training if job fails
- Compare checkpoint performance
- Use intermediate models
- Track training progress
Checkpoints are pushed to: username/my-detector (same repo)
Model Card Configuration
Add metadata for better discoverability:
# At the end of training script
model.push_to_hub(
"username/my-detector",
commit_message="Upload trained object detection model",
tags=["object-detection", "vision", "cppe-5"],
model_card_kwargs={
"license": "apache-2.0",
"dataset": "cppe-5",
"metrics": ["map", "recall", "precision"],
"pipeline_tag": "object-detection",
}
)Saving Label Mappings
Critical for object detection: Save class labels with the model:
# Define your label mappings
id2label = {0: "Coverall", 1: "Face_Shield", 2: "Gloves", 3: "Goggles", 4: "Mask"}
label2id = {v: k for k, v in id2label.items()}
# Update model config before training
model.config.id2label = id2label
model.config.label2id = label2id
# Now train and push
trainer.train()
trainer.push_to_hub()Without label mappings:
- Model outputs will be numeric IDs only
- No human-readable class names
- Difficult to interpret results
Authentication Methods
For a complete guide on token types, $HF_TOKEN automatic replacement, secrets vs env differences, and security best practices, see the hugging-face-jobs skill → Token Usage Guide.
Recommended: Always pass tokens via secrets (encrypted server-side):
"secrets": {"HF_TOKEN": "$HF_TOKEN"} # ✅ Automatic replacement with your logged-in tokenVerification Checklist
Before submitting any training job, verify:
- [ ]
push_to_hub=Truein TrainingArguments - [ ]
hub_model_idis specified (format:username/model-name) - [ ] Image processor will be saved separately
- [ ] Label mappings (id2label, label2id) are configured
- [ ] Repository name doesn't conflict with existing repos
- [ ] You have write access to the target namespace
Repository Setup
Automatic Creation
If repository doesn't exist, it's created automatically when first pushing.
Manual Creation
Create repository before training:
from huggingface_hub import HfApi
api = HfApi()
api.create_repo(
repo_id="username/detector-name",
repo_type="model",
private=False, # or True for private repo
)Repository Naming
Valid names:
username/detr-cppe5username/yolos-object-detectororganization/custom-detector
Invalid names:
detector-name(missing username)username/detector name(spaces not allowed)username/DETECTOR(uppercase discouraged)
Recommended naming:
- Include model architecture:
detr-,yolos-,deta- - Include dataset:
-cppe5,-coco,-voc - Be descriptive:
detr-resnet50-cppe5>model1
Troubleshooting
Error: 401 Unauthorized
Cause: HF_TOKEN not provided, invalid, or not authenticated before Trainer init
Solutions: 1. Verify secrets={"HF_TOKEN": "$HF_TOKEN"} in job config 2. Verify script calls login(token=hf_token) AND sets training_args.hub_token = hf_token BEFORE creating the Trainer 3. Check you're logged in locally: hf auth whoami 4. Re-login: hf auth login
Root cause: The Trainer calls create_repo(token=self.args.hub_token) during __init__() when push_to_hub=True. Relying on implicit env-var token resolution is unreliable in Jobs. Calling login() saves the token globally, and setting training_args.hub_token ensures the Trainer passes it explicitly to all Hub API calls.
Error: 403 Forbidden
Cause: No write access to repository
Solutions: 1. Check repository namespace matches your username 2. Verify you're a member of organization (if using org namespace) 3. Check repository isn't private (if accessing org repo)
Error: Repository not found
Cause: Repository doesn't exist and auto-creation failed
Solutions: 1. Manually create repository first 2. Check repository name format 3. Verify namespace exists
Error: Push failed during training
Cause: Network issues or Hub unavailable
Solutions: 1. Training continues but final push fails 2. Checkpoints may be saved 3. Re-run push manually after job completes
Issue: Model loads but inference fails
Possible causes: 1. Image processor not saved—verify it's pushed separately 2. Label mappings missing—check config.json has id2label 3. Wrong image size—verify image processor matches training config
Issue: Model saved but not visible
Possible causes: 1. Repository is private—check https://huggingface.co/username 2. Wrong namespace—verify hub_model_id matches login 3. Push still in progress—wait a few minutes
Manual Push After Training
If training completes but push fails, push manually:
from transformers import AutoModelForObjectDetection, AutoImageProcessor
# Load from local checkpoint
model = AutoModelForObjectDetection.from_pretrained("./output_dir")
image_processor = AutoImageProcessor.from_pretrained("./output_dir")
# Push to Hub
model.push_to_hub("username/model-name", token="hf_abc123...")
image_processor.push_to_hub("username/model-name", token="hf_abc123...")Note: Only possible if job hasn't completed (files still exist).
Best Practices
1. Always enable `push_to_hub=True` 2. Save image processor separately - critical for inference 3. Configure label mappings before training 4. Use checkpoint saving for long training runs 5. Verify Hub push in logs before job completes 6. Set appropriate `save_total_limit` to avoid excessive checkpoints 7. Use descriptive repo names (e.g., detr-cppe5 not detector1) 8. Add model card with:
- Training dataset
- Evaluation metrics (mAP, IoU)
- Example usage code
- Limitations
9. Tag models appropriately:
object-detection- Architecture:
detr,yolos,deta - Dataset:
coco,voc,cppe-5
Monitoring Push Progress
Check logs for push progress:
hf_jobs("logs", {"job_id": "your-job-id"})Look for:
Pushing model to username/detector-name...
Upload file pytorch_model.bin: 100%
✅ Model pushed successfully
Pushing image processor...
✅ Image processor pushed successfullyExample: Full Production Setup
# production_detector.py
# /// script
# dependencies = [
# "transformers>=4.30.0",
# "torch>=2.0.0",
# "torchvision>=0.15.0",
# "datasets>=2.12.0",
# "evaluate>=0.4.0"
# ]
# ///
from transformers import (
AutoImageProcessor,
AutoModelForObjectDetection,
TrainingArguments,
Trainer
)
from datasets import load_dataset
import os
import torch
# Configuration
MODEL_NAME = "facebook/detr-resnet-50"
DATASET_NAME = "cppe-5"
HUB_MODEL_ID = "myusername/detr-cppe5-detector"
NUM_CLASSES = 5
# Class labels
id2label = {0: "Coverall", 1: "Face_Shield", 2: "Gloves", 3: "Goggles", 4: "Mask"}
label2id = {v: k for k, v in id2label.items()}
print(f"🔧 Loading dataset: {DATASET_NAME}")
dataset = load_dataset(DATASET_NAME, split="train")
print(f"✅ Dataset loaded: {len(dataset)} examples")
print(f"🔧 Loading model: {MODEL_NAME}")
image_processor = AutoImageProcessor.from_pretrained(MODEL_NAME)
model = AutoModelForObjectDetection.from_pretrained(
MODEL_NAME,
num_labels=NUM_CLASSES,
id2label=id2label,
label2id=label2id,
ignore_mismatched_sizes=True
)
print("✅ Model loaded")
# Configure with comprehensive Hub settings
training_args = TrainingArguments(
output_dir="detr-cppe5",
# Hub configuration
push_to_hub=True,
hub_model_id=HUB_MODEL_ID,
hub_strategy="checkpoint", # Push checkpoints
# Checkpoint configuration
save_strategy="steps",
save_steps=500,
save_total_limit=3,
# Training settings
num_train_epochs=10,
per_device_train_batch_size=8,
gradient_accumulation_steps=2,
learning_rate=1e-4,
warmup_steps=500,
# Evaluation
eval_strategy="steps",
eval_steps=500,
# Logging
logging_steps=50,
logging_first_step=True,
# Performance
fp16=True, # Mixed precision training
dataloader_num_workers=4,
)
# ✅ CRITICAL: Authenticate with Hub BEFORE creating Trainer
# login() saves the token globally so ALL hub operations can find it.
from huggingface_hub import login
hf_token = os.environ.get("HF_TOKEN") or os.environ.get("hfjob")
if hf_token:
login(token=hf_token)
training_args.hub_token = hf_token
elif training_args.push_to_hub:
raise ValueError("HF_TOKEN not found! Add secrets={'HF_TOKEN': '$HF_TOKEN'} to job config.")
# Data collator
def collate_fn(batch):
pixel_values = [item["pixel_values"] for item in batch]
labels = [item["labels"] for item in batch]
encoding = image_processor.pad(pixel_values, return_tensors="pt")
return {
"pixel_values": encoding["pixel_values"],
"labels": labels
}
# Create trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=dataset,
data_collator=collate_fn,
)
print("🚀 Starting training...")
trainer.train()
print("💾 Pushing final model to Hub...")
trainer.push_to_hub(
commit_message="Upload trained DETR model on CPPE-5",
tags=["object-detection", "detr", "cppe-5", "vision"],
)
print("💾 Pushing image processor to Hub...")
image_processor.push_to_hub(
repo_id=HUB_MODEL_ID,
commit_message="Upload image processor"
)
print("✅ Training complete!")
print(f"Model available at: https://huggingface.co/{HUB_MODEL_ID}")
print(f"\nTo use your model:")
print(f"```python")
print(f"from transformers import AutoImageProcessor, AutoModelForObjectDetection")
print(f"")
print(f"processor = AutoImageProcessor.from_pretrained('{HUB_MODEL_ID}')")
print(f"model = AutoModelForObjectDetection.from_pretrained('{HUB_MODEL_ID}')")
print(f"```")Submit:
hf_jobs("uv", {
"script": training_script_content, # Pass script content as a string, NOT a filename
"flavor": "a10g-large",
"timeout": "8h",
"secrets": {"HF_TOKEN": "$HF_TOKEN"}
})Inference Example
After training, use your model:
from transformers import AutoImageProcessor, AutoModelForObjectDetection
from PIL import Image
import torch
# Load model from Hub
processor = AutoImageProcessor.from_pretrained("username/detr-cppe5-detector")
model = AutoModelForObjectDetection.from_pretrained("username/detr-cppe5-detector")
# Load and process image
image = Image.open("test_image.jpg")
inputs = processor(images=image, return_tensors="pt")
# Run inference
with torch.no_grad():
outputs = model(**inputs)
# Post-process results
target_sizes = torch.tensor([image.size[::-1]])
results = processor.post_process_object_detection(
outputs,
threshold=0.5,
target_sizes=target_sizes
)[0]
# Print detections
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
box = [round(i, 2) for i in box.tolist()]
print(
f"Detected {model.config.id2label[label.item()]} with confidence "
f"{round(score.item(), 3)} at location {box}"
)Key Takeaway
Without `push_to_hub=True` and `secrets={"HF_TOKEN": "$HF_TOKEN"}`, all training results are permanently lost.
For object detection, also remember to: 1. Save the image processor separately 2. Configure label mappings (id2label, label2id) 3. Include appropriate model card metadata
Always verify all three are configured before submitting any training job.
Image classification
Contents
- Load Food-101 dataset
- Preprocess (ViT image processor, torchvision transforms)
- Evaluate (accuracy metric, compute_metrics)
- Train (TrainingArguments, Trainer setup, push to Hub)
- Inference (pipeline, manual prediction)
---
Image classification assigns a label or class to an image. Unlike text or audio classification, the inputs are the pixel values that comprise an image. There are many applications for image classification, such as detecting damage after a natural disaster, monitoring crop health, or helping screen medical images for signs of disease.
This guide illustrates how to:
1. Fine-tune ViT on the Food-101 dataset to classify a food item in an image. 2. Use your fine-tuned model for inference.
To see all architectures and checkpoints compatible with this task, we recommend checking the task-page
Before you begin, make sure you have all the necessary libraries installed:
pip install transformers datasets evaluate accelerate pillow torchvision scikit-learn trackioWe encourage you to log in to your Hugging Face account to upload and share your model with the community. When prompted, enter your token to log in:
>>> from huggingface_hub import notebook_login
>>> notebook_login()Load Food-101 dataset
Start by loading a smaller subset of the Food-101 dataset from the 🤗 Datasets library. This will give you a chance to experiment and make sure everything works before spending more time training on the full dataset.
>>> from datasets import load_dataset
>>> food = load_dataset("ethz/food101", split="train[:5000]")Split the dataset's train split into a train and test set with the train_test_split method:
>>> food = food.train_test_split(test_size=0.2)Then take a look at an example:
>>> food["train"][0]
{'image': ,
'label': 79}Each example in the dataset has two fields:
image: a PIL image of the food itemlabel: the label class of the food item
To make it easier for the model to get the label name from the label id, create a dictionary that maps the label name to an integer and vice versa:
>>> labels = food["train"].features["label"].names
>>> label2id, id2label = dict(), dict()
>>> for i, label in enumerate(labels):
... label2id[label] = str(i)
... id2label[str(i)] = labelNow you can convert the label id to a label name:
>>> id2label[str(79)]
'prime_rib'Preprocess
The next step is to load a ViT image processor to process the image into a tensor:
>>> from transformers import AutoImageProcessor
>>> checkpoint = "google/vit-base-patch16-224-in21k"
>>> image_processor = AutoImageProcessor.from_pretrained(checkpoint)Apply some image transformations to the images to make the model more robust against overfitting. Here you'll use torchvision's `transforms` module, but you can also use any image library you like.
Crop a random part of the image, resize it, and normalize it with the image mean and standard deviation:
>>> from torchvision.transforms import RandomResizedCrop, Compose, Normalize, ToTensor
>>> normalize = Normalize(mean=image_processor.image_mean, std=image_processor.image_std)
>>> size = (
... image_processor.size["shortest_edge"]
... if "shortest_edge" in image_processor.size
... else (image_processor.size["height"], image_processor.size["width"])
... )
>>> _transforms = Compose([RandomResizedCrop(size), ToTensor(), normalize])Then create a preprocessing function to apply the transforms and return the pixel_values - the inputs to the model - of the image:
>>> def transforms(examples):
... examples["pixel_values"] = [_transforms(img.convert("RGB")) for img in examples["image"]]
... del examples["image"]
... return examplesTo apply the preprocessing function over the entire dataset, use 🤗 Datasets with_transform method. The transforms are applied on the fly when you load an element of the dataset:
>>> food = food.with_transform(transforms)Now create a batch of examples using DefaultDataCollator. Unlike other data collators in 🤗 Transformers, the DefaultDataCollator does not apply additional preprocessing such as padding.
>>> from transformers import DefaultDataCollator
>>> data_collator = DefaultDataCollator()Evaluate
Including a metric during training is often helpful for evaluating your model's performance. You can quickly load an evaluation method with the 🤗 Evaluate library. For this task, load the accuracy metric (see the 🤗 Evaluate quick tour to learn more about how to load and compute a metric):
>>> import evaluate
>>> accuracy = evaluate.load("accuracy")Then create a function that passes your predictions and labels to compute to calculate the accuracy:
>>> import numpy as np
>>> def compute_metrics(eval_pred):
... predictions, labels = eval_pred
... predictions = np.argmax(predictions, axis=1)
... return accuracy.compute(predictions=predictions, references=labels)Your compute_metrics function is ready to go now, and you'll return to it when you set up your training.
Train
If you aren't familiar with finetuning a model with the Trainer, take a look at the basic tutorial here!
You're ready to start training your model now! Load ViT with AutoModelForImageClassification. Specify the number of labels along with the number of expected labels, and the label mappings:
>>> from transformers import AutoModelForImageClassification, TrainingArguments, Trainer
>>> model = AutoModelForImageClassification.from_pretrained(
... checkpoint,
... num_labels=len(labels),
... id2label=id2label,
... label2id=label2id,
... )At this point, only three steps remain:
1. Define your training hyperparameters in TrainingArguments. It is important you don't remove unused columns because that'll drop the image column. Without the image column, you can't create pixel_values. Set remove_unused_columns=False to prevent this behavior! The only other required parameter is output_dir which specifies where to save your model. You'll push this model to the Hub by setting push_to_hub=True (you need to be signed in to Hugging Face to upload your model). At the end of each epoch, the Trainer will evaluate the accuracy and save the training checkpoint. 2. Pass the training arguments to Trainer along with the model, dataset, tokenizer, data collator, and compute_metrics function. 3. Call train() to finetune your model.
>>> training_args = TrainingArguments(
... output_dir="my_awesome_food_model",
... remove_unused_columns=False,
... eval_strategy="epoch",
... save_strategy="epoch",
... learning_rate=5e-5,
... per_device_train_batch_size=16,
... gradient_accumulation_steps=4,
... per_device_eval_batch_size=16,
... num_train_epochs=3,
... warmup_steps=0.1,
... logging_steps=10,
... report_to="trackio",
... run_name="food101",
... load_best_model_at_end=True,
... metric_for_best_model="accuracy",
... push_to_hub=True,
... )
>>> trainer = Trainer(
... model=model,
... args=training_args,
... data_collator=data_collator,
... train_dataset=food["train"],
... eval_dataset=food["test"],
... processing_class=image_processor,
... compute_metrics=compute_metrics,
... )
>>> trainer.train()Once training is completed, share your model to the Hub with the push_to_hub() method so everyone can use your model:
>>> trainer.push_to_hub()For a more in-depth example of how to finetune a model for image classification, take a look at the corresponding PyTorch notebook.
Inference
Great, now that you've fine-tuned a model, you can use it for inference!
Load an image you'd like to run inference on:
>>> ds = load_dataset("ethz/food101", split="validation[:10]")
>>> image = ds["image"][0]The simplest way to try out your finetuned model for inference is to use it in a pipeline(). Instantiate a pipeline for image classification with your model, and pass your image to it:
>>> from transformers import pipeline
>>> classifier = pipeline("image-classification", model="my_awesome_food_model")
>>> classifier(image)
[{'score': 0.31856709718704224, 'label': 'beignets'},
{'score': 0.015232225880026817, 'label': 'bruschetta'},
{'score': 0.01519392803311348, 'label': 'chicken_wings'},
{'score': 0.013022331520915031, 'label': 'pork_chop'},
{'score': 0.012728818692266941, 'label': 'prime_rib'}]You can also manually replicate the results of the pipeline if you'd like:
Load an image processor to preprocess the image and return the input as PyTorch tensors:
>>> from transformers import AutoImageProcessor
>>> import torch
>>> image_processor = AutoImageProcessor.from_pretrained("my_awesome_food_model")
>>> inputs = image_processor(image, return_tensors="pt")Pass your inputs to the model and return the logits:
>>> from transformers import AutoModelForImageClassification
>>> model = AutoModelForImageClassification.from_pretrained("my_awesome_food_model")
>>> with torch.no_grad():
... logits = model(**inputs).logitsGet the predicted label with the highest probability, and use the model's id2label mapping to convert it to a label:
>>> predicted_label = logits.argmax(-1).item()
>>> model.config.id2label[predicted_label]
'beignets'Object Detection Training Reference
Contents
- Load the CPPE-5 dataset
- Preprocess the data (augmentation with Albumentations, COCO annotation formatting)
- Preparing function to compute mAP
- Training the detection model (TrainingArguments, Trainer setup)
- Evaluate
- Inference (loading from Hub, running predictions, visualizing results)
---
Object detection is the computer vision task of detecting instances (such as humans, buildings, or cars) in an image. Object detection models receive an image as input and output coordinates of the bounding boxes and associated labels of the detected objects. An image can contain multiple objects, each with its own bounding box and a label (e.g. it can have a car and a building), and each object can be present in different parts of an image (e.g. the image can have several cars). This task is commonly used in autonomous driving for detecting things like pedestrians, road signs, and traffic lights. Other applications include counting objects in images, image search, and more.
In this guide, you will learn how to:
1. Finetune DETR, a model that combines a convolutional backbone with an encoder-decoder Transformer, on the CPPE-5 dataset. 2. Use your finetuned model for inference.
To see all architectures and checkpoints compatible with this task, we recommend checking the task-page
Before you begin, make sure you have all the necessary libraries installed:
pip install -q datasets transformers accelerate timm trackio
pip install -q -U albumentations>=1.4.5 torchmetrics pycocotoolsYou'll use 🤗 Datasets to load a dataset from the Hugging Face Hub, 🤗 Transformers to train your model, and albumentations to augment the data.
We encourage you to share your model with the community. Log in to your Hugging Face account to upload it to the Hub. When prompted, enter your token to log in:
>>> from huggingface_hub import notebook_login
>>> notebook_login()To get started, we'll define global constants, namely the model name and image size. For this tutorial, we'll use the conditional DETR model due to its faster convergence. Feel free to select any object detection model available in the transformers library.
>>> MODEL_NAME = "microsoft/conditional-detr-resnet-50" # or "facebook/detr-resnet-50"
>>> IMAGE_SIZE = 480Load the CPPE-5 dataset
The CPPE-5 dataset contains images with annotations identifying medical personal protective equipment (PPE) in the context of the COVID-19 pandemic.
Start by loading the dataset and creating a validation split from train:
>>> from datasets import load_dataset
>>> cppe5 = load_dataset("cppe-5")
>>> if "validation" not in cppe5:
... split = cppe5["train"].train_test_split(0.15, seed=1337)
... cppe5["train"] = split["train"]
... cppe5["validation"] = split["test"]
>>> cppe5
DatasetDict({
train: Dataset({
features: ['image_id', 'image', 'width', 'height', 'objects'],
num_rows: 850
})
test: Dataset({
features: ['image_id', 'image', 'width', 'height', 'objects'],
num_rows: 29
})
validation: Dataset({
features: ['image_id', 'image', 'width', 'height', 'objects'],
num_rows: 150
})
})You'll see that this dataset has 1000 images for train and validation sets and a test set with 29 images.
To get familiar with the data, explore what the examples look like.
>>> cppe5["train"][0]
{
'image_id': 366,
'image': ,
'width': 500,
'height': 500,
'objects': {
'id': [1932, 1933, 1934],
'area': [27063, 34200, 32431],
'bbox': [[29.0, 11.0, 97.0, 279.0],
[201.0, 1.0, 120.0, 285.0],
[382.0, 0.0, 113.0, 287.0]],
'category': [0, 0, 0]
}
}The examples in the dataset have the following fields:
image_id: the example image idimage: aPIL.Image.Imageobject containing the imagewidth: width of the imageheight: height of the imageobjects: a dictionary containing bounding box metadata for the objects in the image:id: the annotation idarea: the area of the bounding boxbbox: the object's bounding box (in the COCO format )category: the object's category, with possible values includingCoverall (0),Face_Shield (1),Gloves (2),Goggles (3)andMask (4)
You may notice that the bbox field follows the COCO format, which is the format that the DETR model expects. However, the grouping of the fields inside objects differs from the annotation format DETR requires. You will need to apply some preprocessing transformations before using this data for training.
To get an even better understanding of the data, visualize an example in the dataset.
>>> import numpy as np
>>> import os
>>> from PIL import Image, ImageDraw
>>> image = cppe5["train"][2]["image"]
>>> annotations = cppe5["train"][2]["objects"]
>>> draw = ImageDraw.Draw(image)
>>> categories = cppe5["train"].features["objects"]["category"].feature.names
>>> id2label = {index: x for index, x in enumerate(categories, start=0)}
>>> label2id = {v: k for k, v in id2label.items()}
>>> for i in range(len(annotations["id"])):
... box = annotations["bbox"][i]
... class_idx = annotations["category"][i]
... x, y, w, h = tuple(box)
... # Check if coordinates are normalized or not
... if max(box) > 1.0:
... # Coordinates are un-normalized, no need to re-scale them
... x1, y1 = int(x), int(y)
... x2, y2 = int(x + w), int(y + h)
... else:
... # Coordinates are normalized, re-scale them
... x1 = int(x * width)
... y1 = int(y * height)
... x2 = int((x + w) * width)
... y2 = int((y + h) * height)
... draw.rectangle((x, y, x + w, y + h), outline="red", width=1)
... draw.text((x, y), id2label[class_idx], fill="white")
>>> imageTo visualize the bounding boxes with associated labels, you can get the labels from the dataset's metadata, specifically the category field. You'll also want to create dictionaries that map a label id to a label class (id2label) and the other way around (label2id). You can use them later when setting up the model. Including these maps will make your model reusable by others if you share it on the Hugging Face Hub. Please note that, the part of above code that draws the bounding boxes assume that it is in COCO format (x_min, y_min, width, height). It has to be adjusted to work for other formats like (x_min, y_min, x_max, y_max).
As a final step of getting familiar with the data, explore it for potential issues. One common problem with datasets for object detection is bounding boxes that "stretch" beyond the edge of the image. Such "runaway" bounding boxes can raise errors during training and should be addressed. There are a few examples with this issue in this dataset. To keep things simple in this guide, we will set clip=True for BboxParams in transformations below.
Preprocess the data
To finetune a model, you must preprocess the data you plan to use to match precisely the approach used for the pre-trained model. AutoImageProcessor takes care of processing image data to create pixel_values, pixel_mask, and labels that a DETR model can train with. The image processor has some attributes that you won't have to worry about:
image_mean = [0.485, 0.456, 0.406 ]image_std = [0.229, 0.224, 0.225]
These are the mean and standard deviation used to normalize images during the model pre-training. These values are crucial to replicate when doing inference or finetuning a pre-trained image model.
Instantiate the image processor from the same checkpoint as the model you want to finetune.
>>> from transformers import AutoImageProcessor
>>> MAX_SIZE = IMAGE_SIZE
>>> image_processor = AutoImageProcessor.from_pretrained(
... MODEL_NAME,
... do_resize=True,
... size={"max_height": MAX_SIZE, "max_width": MAX_SIZE},
... do_pad=True,
... pad_size={"height": MAX_SIZE, "width": MAX_SIZE},
... )Before passing the images to the image_processor, apply two preprocessing transformations to the dataset:
- Augmenting images
- Reformatting annotations to meet DETR expectations
First, to make sure the model does not overfit on the training data, you can apply image augmentation with any data augmentation library. Here we use Albumentations. This library ensures that transformations affect the image and update the bounding boxes accordingly. The 🤗 Datasets library documentation has a detailed guide on how to augment images for object detection, and it uses the exact same dataset as an example. Apply some geometric and color transformations to the image. For additional augmentation options, explore the Albumentations Demo Space.
>>> import albumentations as A
>>> train_augment_and_transform = A.Compose(
... [
... A.Perspective(p=0.1),
... A.HorizontalFlip(p=0.5),
... A.RandomBrightnessContrast(p=0.5),
... A.HueSaturationValue(p=0.1),
... ],
... bbox_params=A.BboxParams(format="coco", label_fields=["category"], clip=True, min_area=25),
... )
>>> validation_transform = A.Compose(
... [A.NoOp()],
... bbox_params=A.BboxParams(format="coco", label_fields=["category"], clip=True),
... )The image_processor expects the annotations to be in the following format: {'image_id': int, 'annotations': list[Dict]}, where each dictionary is a COCO object annotation. Let's add a function to reformat annotations for a single example:
>>> def format_image_annotations_as_coco(image_id, categories, areas, bboxes):
... """Format one set of image annotations to the COCO format
... Args:
... image_id (str): image id. e.g. "0001"
... categories (list[int]): list of categories/class labels corresponding to provided bounding boxes
... areas (list[float]): list of corresponding areas to provided bounding boxes
... bboxes (list[tuple[float]]): list of bounding boxes provided in COCO format
... ([center_x, center_y, width, height] in absolute coordinates)
... Returns:
... dict: {
... "image_id": image id,
... "annotations": list of formatted annotations
... }
... """
... annotations = []
... for category, area, bbox in zip(categories, areas, bboxes):
... formatted_annotation = {
... "image_id": image_id,
... "category_id": category,
... "iscrowd": 0,
... "area": area,
... "bbox": list(bbox),
... }
... annotations.append(formatted_annotation)
... return {
... "image_id": image_id,
... "annotations": annotations,
... }
Now you can combine the image and annotation transformations to use on a batch of examples:
>>> def augment_and_transform_batch(examples, transform, image_processor, return_pixel_mask=False):
... """Apply augmentations and format annotations in COCO format for object detection task"""
... images = []
... annotations = []
... for image_id, image, objects in zip(examples["image_id"], examples["image"], examples["objects"]):
... image = np.array(image.convert("RGB"))
... # apply augmentations
... output = transform(image=image, bboxes=objects["bbox"], category=objects["category"])
... images.append(output["image"])
... # format annotations in COCO format
... formatted_annotations = format_image_annotations_as_coco(
... image_id, output["category"], objects["area"], output["bboxes"]
... )
... annotations.append(formatted_annotations)
... # Apply the image processor transformations: resizing, rescaling, normalization
... result = image_processor(images=images, annotations=annotations, return_tensors="pt")
... if not return_pixel_mask:
... result.pop("pixel_mask", None)
... return resultApply this preprocessing function to the entire dataset using 🤗 Datasets with_transform method. This method applies transformations on the fly when you load an element of the dataset.
At this point, you can check what an example from the dataset looks like after the transformations. You should see a tensor with pixel_values, a tensor with pixel_mask, and labels.
>>> from functools import partial
>>> # Make transform functions for batch and apply for dataset splits
>>> train_transform_batch = partial(
... augment_and_transform_batch, transform=train_augment_and_transform, image_processor=image_processor
... )
>>> validation_transform_batch = partial(
... augment_and_transform_batch, transform=validation_transform, image_processor=image_processor
... )
>>> cppe5["train"] = cppe5["train"].with_transform(train_transform_batch)
>>> cppe5["validation"] = cppe5["validation"].with_transform(validation_transform_batch)
>>> cppe5["test"] = cppe5["test"].with_transform(validation_transform_batch)
>>> cppe5["train"][15]
{'pixel_values': tensor([[[ 1.9235, 1.9407, 1.9749, ..., -0.7822, -0.7479, -0.6965],
[ 1.9578, 1.9749, 1.9920, ..., -0.7993, -0.7650, -0.7308],
[ 2.0092, 2.0092, 2.0263, ..., -0.8507, -0.8164, -0.7822],
...,
[ 0.0741, 0.0741, 0.0741, ..., 0.0741, 0.0741, 0.0741],
[ 0.0741, 0.0741, 0.0741, ..., 0.0741, 0.0741, 0.0741],
[ 0.0741, 0.0741, 0.0741, ..., 0.0741, 0.0741, 0.0741]],
[[ 1.6232, 1.6408, 1.6583, ..., 0.8704, 1.0105, 1.1331],
[ 1.6408, 1.6583, 1.6758, ..., 0.8529, 0.9930, 1.0980],
[ 1.6933, 1.6933, 1.7108, ..., 0.8179, 0.9580, 1.0630],
...,
[ 0.2052, 0.2052, 0.2052, ..., 0.2052, 0.2052, 0.2052],
[ 0.2052, 0.2052, 0.2052, ..., 0.2052, 0.2052, 0.2052],
[ 0.2052, 0.2052, 0.2052, ..., 0.2052, 0.2052, 0.2052]],
[[ 1.8905, 1.9080, 1.9428, ..., -0.1487, -0.0964, -0.0615],
[ 1.9254, 1.9428, 1.9603, ..., -0.1661, -0.1138, -0.0790],
[ 1.9777, 1.9777, 1.9951, ..., -0.2010, -0.1138, -0.0790],
...,
[ 0.4265, 0.4265, 0.4265, ..., 0.4265, 0.4265, 0.4265],
[ 0.4265, 0.4265, 0.4265, ..., 0.4265, 0.4265, 0.4265],
[ 0.4265, 0.4265, 0.4265, ..., 0.4265, 0.4265, 0.4265]]]),
'labels': {'image_id': tensor([688]), 'class_labels': tensor([3, 4, 2, 0, 0]), 'boxes': tensor([[0.4700, 0.1933, 0.1467, 0.0767],
[0.4858, 0.2600, 0.1150, 0.1000],
[0.4042, 0.4517, 0.1217, 0.1300],
[0.4242, 0.3217, 0.3617, 0.5567],
[0.6617, 0.4033, 0.5400, 0.4533]]), 'area': tensor([ 4048., 4140., 5694., 72478., 88128.]), 'iscrowd': tensor([0, 0, 0, 0, 0]), 'orig_size': tensor([480, 480])}}You have successfully augmented the individual images and prepared their annotations. However, preprocessing isn't complete yet. In the final step, create a custom collate_fn to batch images together. Pad images (which are now pixel_values) to the largest image in a batch, and create a corresponding pixel_mask to indicate which pixels are real (1) and which are padding (0).
>>> import torch
>>> def collate_fn(batch):
... data = {}
... data["pixel_values"] = torch.stack([x["pixel_values"] for x in batch])
... data["labels"] = [x["labels"] for x in batch]
... if "pixel_mask" in batch[0]:
... data["pixel_mask"] = torch.stack([x["pixel_mask"] for x in batch])
... return data
Preparing function to compute mAP
Object detection models are commonly evaluated with a set of COCO-style metrics. We are going to use torchmetrics to compute mAP (mean average precision) and mAR (mean average recall) metrics and will wrap it to compute_metrics function in order to use in Trainer for evaluation.
Intermediate format of boxes used for training is YOLO (normalized) but we will compute metrics for boxes in Pascal VOC (absolute) format in order to correctly handle box areas. Let's define a function that converts bounding boxes to Pascal VOC format:
>>> from transformers.image_transforms import center_to_corners_format
>>> def convert_bbox_yolo_to_pascal(boxes, image_size):
... """
... Convert bounding boxes from YOLO format (x_center, y_center, width, height) in range [0, 1]
... to Pascal VOC format (x_min, y_min, x_max, y_max) in absolute coordinates.
... Args:
... boxes (torch.Tensor): Bounding boxes in YOLO format
... image_size (tuple[int, int]): Image size in format (height, width)
... Returns:
... torch.Tensor: Bounding boxes in Pascal VOC format (x_min, y_min, x_max, y_max)
... """
... # convert center to corners format
... boxes = center_to_corners_format(boxes)
... # convert to absolute coordinates
... height, width = image_size
... boxes = boxes * torch.tensor([[width, height, width, height]])
... return boxesThen, in compute_metrics function we collect predicted and target bounding boxes, scores and labels from evaluation loop results and pass it to the scoring function.
>>> import numpy as np
>>> from dataclasses import dataclass
>>> from torchmetrics.detection.mean_ap import MeanAveragePrecision
>>> @dataclass
>>> class ModelOutput:
... logits: torch.Tensor
... pred_boxes: torch.Tensor
>>> @torch.no_grad()
>>> def compute_metrics(evaluation_results, image_processor, threshold=0.0, id2label=None):
... """
... Compute mean average mAP, mAR and their variants for the object detection task.
... Args:
... evaluation_results (EvalPrediction): Predictions and targets from evaluation.
... threshold (float, optional): Threshold to filter predicted boxes by confidence. Defaults to 0.0.
... id2label (Optional[dict], optional): Mapping from class id to class name. Defaults to None.
... Returns:
... Mapping[str, float]: Metrics in a form of dictionary {: }
... """
... predictions, targets = evaluation_results.predictions, evaluation_results.label_ids
... # For metric computation we need to provide:
... # - targets in a form of list of dictionaries with keys "boxes", "labels"
... # - predictions in a form of list of dictionaries with keys "boxes", "scores", "labels"
... image_sizes = []
... post_processed_targets = []
... post_processed_predictions = []
... # Collect targets in the required format for metric computation
... for batch in targets:
... # collect image sizes, we will need them for predictions post processing
... batch_image_sizes = torch.tensor(np.array([x["orig_size"] for x in batch]))
... image_sizes.append(batch_image_sizes)
... # collect targets in the required format for metric computation
... # boxes were converted to YOLO format needed for model training
... # here we will convert them to Pascal VOC format (x_min, y_min, x_max, y_max)
... for image_target in batch:
... boxes = torch.tensor(image_target["boxes"])
... boxes = convert_bbox_yolo_to_pascal(boxes, image_target["orig_size"])
... labels = torch.tensor(image_target["class_labels"])
... post_processed_targets.append({"boxes": boxes, "labels": labels})
... # Collect predictions in the required format for metric computation,
... # model produce boxes in YOLO format, then image_processor convert them to Pascal VOC format
... for batch, target_sizes in zip(predictions, image_sizes):
... batch_logits, batch_boxes = batch[1], batch[2]
... output = ModelOutput(logits=torch.tensor(batch_logits), pred_boxes=torch.tensor(batch_boxes))
... post_processed_output = image_processor.post_process_object_detection(
... output, threshold=threshold, target_sizes=target_sizes
... )
... post_processed_predictions.extend(post_processed_output)
... # Compute metrics
... metric = MeanAveragePrecision(box_format="xyxy", class_metrics=True)
... metric.update(post_processed_predictions, post_processed_targets)
... metrics = metric.compute()
... # Replace list of per class metrics with separate metric for each class
... classes = metrics.pop("classes")
... map_per_class = metrics.pop("map_per_class")
... mar_100_per_class = metrics.pop("mar_100_per_class")
... for class_id, class_map, class_mar in zip(classes, map_per_class, mar_100_per_class):
... class_name = id2label[class_id.item()] if id2label is not None else class_id.item()
... metrics[f"map_{class_name}"] = class_map
... metrics[f"mar_100_{class_name}"] = class_mar
... metrics = {k: round(v.item(), 4) for k, v in metrics.items()}
... return metrics
>>> eval_compute_metrics_fn = partial(
... compute_metrics, image_processor=image_processor, id2label=id2label, threshold=0.0
... )Training the detection model
You have done most of the heavy lifting in the previous sections, so now you are ready to train your model! The images in this dataset are still quite large, even after resizing. This means that finetuning this model will require at least one GPU.
Training involves the following steps:
1. Load the model with AutoModelForObjectDetection using the same checkpoint as in the preprocessing. 2. Define your training hyperparameters in TrainingArguments. 3. Pass the training arguments to Trainer along with the model, dataset, image processor, and data collator. 4. Call train() to finetune your model.
When loading the model from the same checkpoint that you used for the preprocessing, remember to pass the label2id and id2label maps that you created earlier from the dataset's metadata. Additionally, we specify ignore_mismatched_sizes=True to replace the existing classification head with a new one.
>>> from transformers import AutoModelForObjectDetection
>>> model = AutoModelForObjectDetection.from_pretrained(
... MODEL_NAME,
... id2label=id2label,
... label2id=label2id,
... ignore_mismatched_sizes=True,
... )In the TrainingArguments use output_dir to specify where to save your model, then configure hyperparameters as you see fit. For num_train_epochs=30 training will take about 35 minutes in Google Colab T4 GPU, increase the number of epoch to get better results.
Important notes:
- Set
remove_unused_columnstoFalse. - Set
eval_do_concat_batches=Falseto get proper evaluation results. Images have different number of target boxes, if batches are concatenated we will not be able to determine which boxes belongs to particular image.
If you wish to share your model by pushing to the Hub, set push_to_hub to True (you must be signed in to Hugging Face to upload your model).
>>> from transformers import TrainingArguments
>>> training_args = TrainingArguments(
... output_dir="detr_finetuned_cppe5",
... num_train_epochs=30,
... fp16=False,
... per_device_train_batch_size=8,
... dataloader_num_workers=4,
... learning_rate=5e-5,
... lr_scheduler_type="cosine",
... weight_decay=1e-4,
... max_grad_norm=0.01,
... metric_for_best_model="eval_map",
... greater_is_better=True,
... load_best_model_at_end=True,
... eval_strategy="epoch",
... save_strategy="epoch",
... save_total_limit=2,
... remove_unused_columns=False,
... report_to="trackio",
... run_name="cppe",
... eval_do_concat_batches=False,
... push_to_hub=True,
... )Finally, bring everything together, and call train():
>>> from transformers import Trainer
>>> trainer = Trainer(
... model=model,
... args=training_args,
... train_dataset=cppe5["train"],
... eval_dataset=cppe5["validation"],
... processing_class=image_processor,
... data_collator=collate_fn,
... compute_metrics=eval_compute_metrics_fn,
... )
>>> trainer.train()Training runs for 30 epochs (~26 minutes on a T4 GPU for CPPE-5). Final epoch 30 results:
| Metric | Value |
|---|---|
| Training Loss | 0.994 |
| Validation Loss | 1.346 |
| mAP | 0.277 |
| mAP@50 | 0.555 |
| mAP@75 | 0.253 |
| mAR@100 | 0.443 |
Per-class mAP at epoch 30: Coverall 0.530, Face Shield 0.276, Gloves 0.175, Goggles 0.157, Mask 0.249.
Key observations:
- mAP improves rapidly in early epochs (0.009 at epoch 1 → 0.18 by epoch 10), then gradually converges
- Large objects are detected better (mAP_large=0.524) than small objects (mAP_small=0.148)
- Class imbalance visible: Coverall highest mAP (0.530), Goggles lowest (0.157)
<!-- Full per-epoch training metrics table omitted for brevity. -->
If you have set push_to_hub to True in the training_args, the training checkpoints are pushed to the Hugging Face Hub. Upon training completion, push the final model to the Hub as well by calling the push_to_hub() method.
>>> trainer.push_to_hub()Evaluate
>>> from pprint import pprint
>>> metrics = trainer.evaluate(eval_dataset=cppe5["test"], metric_key_prefix="test")
>>> pprint(metrics)
{'epoch': 30.0,
'test_loss': 1.0877351760864258,
'test_map': 0.4116,
'test_map_50': 0.741,
'test_map_75': 0.3663,
'test_map_Coverall': 0.5937,
'test_map_Face_Shield': 0.5863,
'test_map_Gloves': 0.3416,
'test_map_Goggles': 0.1468,
'test_map_Mask': 0.3894,
'test_map_large': 0.5637,
'test_map_medium': 0.3257,
'test_map_small': 0.3589,
'test_mar_1': 0.323,
'test_mar_10': 0.5237,
'test_mar_100': 0.5587,
'test_mar_100_Coverall': 0.6756,
'test_mar_100_Face_Shield': 0.7294,
'test_mar_100_Gloves': 0.4721,
'test_mar_100_Goggles': 0.4125,
'test_mar_100_Mask': 0.5038,
'test_mar_large': 0.7283,
'test_mar_medium': 0.4901,
'test_mar_small': 0.4469,
'test_runtime': 1.6526,
'test_samples_per_second': 17.548,
'test_steps_per_second': 2.42}These results can be further improved by adjusting the hyperparameters in TrainingArguments. Give it a go!
Inference
Now that you have finetuned a model, evaluated it, and uploaded it to the Hugging Face Hub, you can use it for inference.
>>> import torch
>>> import requests
>>> from PIL import Image, ImageDraw
>>> from transformers import AutoImageProcessor, AutoModelForObjectDetection
>>> url = "https://images.pexels.com/photos/8413299/pexels-photo-8413299.jpeg?auto=compress&cs=tinysrgb&w=630&h=375&dpr=2"
>>> image = Image.open(requests.get(url, stream=True).raw)Load model and image processor from the Hugging Face Hub (skip to use already trained in this session):
>>> from accelerate import Accelerator
>>> device = Accelerator().device
>>> model_repo = "qubvel-hf/detr_finetuned_cppe5"
>>> image_processor = AutoImageProcessor.from_pretrained(model_repo)
>>> model = AutoModelForObjectDetection.from_pretrained(model_repo)
>>> model = model.to(device)And detect bounding boxes:
>>> with torch.no_grad():
... inputs = image_processor(images=[image], return_tensors="pt")
... outputs = model(**inputs.to(device))
... target_sizes = torch.tensor([[image.size[1], image.size[0]]])
... results = image_processor.post_process_object_detection(outputs, threshold=0.3, target_sizes=target_sizes)[0]
>>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
... box = [round(i, 2) for i in box.tolist()]
... print(
... f"Detected {model.config.id2label[label.item()]} with confidence "
... f"{round(score.item(), 3)} at location {box}"
... )
Detected Gloves with confidence 0.683 at location [244.58, 124.33, 300.35, 185.13]
Detected Mask with confidence 0.517 at location [143.73, 64.58, 219.57, 125.89]
Detected Gloves with confidence 0.425 at location [179.15, 155.57, 262.4, 226.35]
Detected Coverall with confidence 0.407 at location [307.13, -1.18, 477.82, 318.06]
Detected Coverall with confidence 0.391 at location [68.61, 126.66, 309.03, 318.89]Let's plot the result:
>>> draw = ImageDraw.Draw(image)
>>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
... box = [round(i, 2) for i in box.tolist()]
... x, y, x2, y2 = tuple(box)
... draw.rectangle((x, y, x2, y2), outline="red", width=1)
... draw.text((x, y), model.config.id2label[label.item()], fill="white")
>>> imageReliability Principles for Training Jobs
Contents
- Principle 1: Always Verify Before Use
- Principle 2: Prioritize Reliability Over Performance
- Principle 3: Create Atomic, Self-Contained Scripts
- Principle 4: Provide Clear Error Context
- Principle 5: Test the Happy Path on Known-Good Inputs
- Summary: The Reliability Checklist (pre-flight, script quality, job config)
- When Principles Conflict
---
These principles are derived from real production failures and successful fixes. Following them prevents common failure modes and ensures reliable job execution.
Principle 1: Always Verify Before Use
Rule: Never assume repos, datasets, or resources exist. Verify with tools first.
What It Prevents
- Non-existent datasets - Jobs fail immediately when dataset doesn't exist
- Typos in names - Simple mistakes like "argilla-dpo-mix-7k" vs "ultrafeedback_binarized"
- Incorrect paths - Old or moved repos, renamed files
- Missing dependencies - Undocumented requirements
How to Apply
Before submitting ANY job:
# Verify dataset exists
dataset_search({"query": "dataset-name", "author": "author-name", "limit": 5})
hub_repo_details(["author/dataset-name"], repo_type="dataset")
# Verify model exists
hub_repo_details(["org/model-name"], repo_type="model")
# Check script/file paths (for URL-based scripts)
# Verify before using: https://github.com/user/repo/blob/main/script.pyExamples that would have caught errors:
# ❌ WRONG: Assumed dataset exists
hf_jobs("uv", {
"script": """...""",
"env": {"DATASET": "trl-lib/argilla-dpo-mix-7k"} # Doesn't exist!
})
# ✅ CORRECT: Verify first
dataset_search({"query": "argilla dpo", "author": "trl-lib"})
# Would show: "trl-lib/ultrafeedback_binarized" is the correct name
hub_repo_details(["trl-lib/ultrafeedback_binarized"], repo_type="dataset")
# Confirms it exists before usingImplementation Checklist
- [ ] Check dataset exists before training
- [ ] Test script URLs are valid before submitting
- [ ] Check for recent updates/renames of resources
- [ ] Check for dataset format
Time cost: 5-10 seconds Time saved: Hours of failed job time + debugging
---
Principle 2: Prioritize Reliability Over Performance
Rule: Default to what is most likely to succeed, not what is theoretically fastest.
What It Prevents
- Hardware incompatibilities - Features that fail on certain GPUs
- Unstable optimizations - Speed-ups that cause crashes
- Complex configurations - More failure points
- Build system issues - Unreliable compilation methods
How to Apply
Choose reliability:
# ❌ RISKY: Aggressive optimization that may fail
TrainingArguments(
torch_compile=True, # Can fail on T4, A10G GPUs
optim="adamw_bnb_8bit", # Requires specific setup
dataloader_num_workers=8, # May cause OOM on small instances
...
)
# ✅ SAFE: Proven defaults
TrainingArguments(
# torch_compile=True, # Commented with note: "Enable on H100 for 20% speedup"
optim="adamw_torch", # Standard, always works
fp16=True, # Stable and fast on T4/A10G
dataloader_num_workers=4, # Conservative, reliable
...
)Real-World Example
The `torch.compile` failure:
- Added for "20% speedup" on H100
- Failed fatally on T4-medium with cryptic error
- Misdiagnosed as dataset issue (cost hours)
- Fix: Disable by default, add as optional comment
Result: Reliability > 20% performance gain
Implementation Checklist
- [ ] Use proven, standard configurations by default
- [ ] Comment out performance optimizations with hardware notes
- [ ] Use stable build systems (CMake > make)
- [ ] Test on target hardware before production
- [ ] Document known incompatibilities
- [ ] Provide "safe" and "fast" variants when needed
Performance loss: 10-20% in best case Reliability gain: 95%+ success rate vs 60-70%
---
Principle 3: Create Atomic, Self-Contained Scripts
Rule: Scripts should work as complete, independent units. Don't remove parts to "simplify."
What It Prevents
- Missing dependencies - Removed "unnecessary" packages that are actually required
- Incomplete processes - Skipped steps that seem redundant
- Environment assumptions - Scripts that need pre-setup
- Partial failures - Some parts work, others fail silently
How to Apply
Complete dependency specifications:
# ❌ INCOMPLETE: "Simplified" by removing dependencies
# /// script
# dependencies = [
# "transformers",
# "torch",
# "datasets",
# ]
# ///
# ✅ COMPLETE: All dependencies explicit
# /// script
# dependencies = [
# "transformers>=5.2.0",
# "accelerate>=1.1.0",
# "albumentations>=1.4.16", # Required for augmentation + bbox handling
# "timm", # Required for vision backbones
# "datasets>=4.0",
# "torchmetrics", # Required for mAP/mAR computation
# "pycocotools", # Required for COCO evaluation
# "trackio", # Required for metrics monitoring
# "huggingface_hub",
# ]
# ///Real-World Example
The `albumentations` failure:
- Original script had it: augmentations and bbox clipping worked fine
- "Simplified" version removed it: "not strictly needed for training"
- Training crashed on bbox augmentation — no fallback for COCO-format bbox handling
- Hard to debug: error appeared in data loading, not in augmentation setup
- Fix: Restore all original dependencies
Result: Don't remove dependencies without thorough testing
Implementation Checklist
- [ ] All dependencies in PEP 723 header with version pins
- [ ] All system packages installed by script
- [ ] No assumptions about pre-existing environment
- [ ] No "optional" steps that are actually required
- [ ] Test scripts in clean environment
- [ ] Document why each dependency is needed
Complexity: Slightly longer scripts Reliability: Scripts "just work" every time
---
Principle 4: Provide Clear Error Context
Rule: When things fail, make it obvious what went wrong and how to fix it.
How to Apply
Wrap subprocess calls:
# ❌ UNCLEAR: Silent failure
subprocess.run([...], check=True, capture_output=True)
# ✅ CLEAR: Shows what failed
try:
result = subprocess.run(
[...],
check=True,
capture_output=True,
text=True
)
print(result.stdout)
if result.stderr:
print("Warnings:", result.stderr)
except subprocess.CalledProcessError as e:
print(f"❌ Command failed!")
print("STDOUT:", e.stdout)
print("STDERR:", e.stderr)
raiseValidate inputs:
# ❌ UNCLEAR: Fails later with cryptic error
model = load_model(MODEL_NAME)
# ✅ CLEAR: Fails fast with clear message
if not MODEL_NAME:
raise ValueError("MODEL_NAME environment variable not set!")
print(f"Loading model: {MODEL_NAME}")
try:
model = load_model(MODEL_NAME)
print(f"✅ Model loaded successfully")
except Exception as e:
print(f"❌ Failed to load model: {MODEL_NAME}")
print(f"Error: {e}")
print("Hint: Check that model exists on Hub")
raiseImplementation Checklist
- [ ] Wrap external calls with try/except
- [ ] Print stdout/stderr on failure
- [ ] Validate environment variables early
- [ ] Add progress indicators (✅, ❌, 🔄)
- [ ] Include hints for common failures
- [ ] Log configuration at start
---
Principle 5: Test the Happy Path on Known-Good Inputs
Rule: Before using new code in production, test with inputs you know work.
Summary: The Reliability Checklist
Before submitting ANY job:
Pre-Flight Checks
- [ ] Verified all repos/datasets exist (hub_repo_details)
- [ ] Tested with known-good inputs if new code
- [ ] Using proven hardware/configuration
- [ ] Included all dependencies in PEP 723 header
- [ ] Installed system requirements (build tools, etc.)
- [ ] Set appropriate timeout (not default 30m)
- [ ] Configured Hub push with HF_TOKEN (login() + hub_token)
- [ ] Added clear error handling
Script Quality
- [ ] Self-contained (no external setup needed)
- [ ] Complete dependencies listed
- [ ] Build tools installed by script
- [ ] Progress indicators included
- [ ] Error messages are clear
- [ ] Configuration logged at start
Job Configuration
- [ ] Timeout > expected runtime + 30% buffer
- [ ] Hardware appropriate for model size
- [ ] Secrets include HF_TOKEN (see SKILL.md directive #2 for syntax)
- [ ] Script calls
login(token=hf_token)and setstraining_args.hub_token = hf_tokenBEFORETrainer()init - [ ] Environment variables set correctly
- [ ] Cost estimated and acceptable
Following these principles transforms job success rate from ~60-70% to ~95%+
---
When Principles Conflict
Sometimes reliability and performance conflict. Here's how to choose:
| Scenario | Choose | Rationale |
|---|---|---|
| Demo/test | Reliability | Fast failure is worse than slow success |
| Production (first run) | Reliability | Prove it works before optimizing |
| Production (proven) | Performance | Safe to optimize after validation |
| Time-critical | Reliability | Failures cause more delay than slow runs |
| Cost-critical | Balanced | Test with small model, then optimize |
General rule: Reliability first, optimize second.
---
Using timm models with Hugging Face Trainer
Transformers has first-class support for timm models via the TimmWrapper classes. You can load any timm model and use it directly with the Trainer API for image classification. Here's how it works:
Loading a timm model
The TimmWrapperForImageClassification class (in transformers/src/transformers/models/timm_wrapper/modeling_timm_wrapper.py) wraps timm models so they're fully compatible with the Trainer API. You can load them via the Auto classes:
from transformers import AutoModelForImageClassification, AutoImageProcessor, Trainer, TrainingArguments
# Load a timm model for image classification
checkpoint = "timm/resnet50.a1_in1k"
image_processor = AutoImageProcessor.from_pretrained(checkpoint)
model = AutoModelForImageClassification.from_pretrained(
checkpoint,
num_labels=10, # set to your number of classes
ignore_mismatched_sizes=True, # needed when changing num_labels from pretrained
)Key details
1. Image processor: The TimmWrapperImageProcessor automatically resolves the correct transforms from timm's config. It exposes both val_transforms and train_transforms (with augmentations), as noted in the code:
```64:65:transformers/src/transformers/models/timm_wrapper/image_processing_timm_wrapper.py
useful for training, see examples/pytorch/image-classification/run_image_classification.py
self.train_transforms = timm.data.create_transform(**self.data_config, is_training=True)
2. **Loss computation is built-in**: `TimmWrapperForImageClassification.forward()` accepts a `labels` argument and computes cross-entropy loss automatically, which is exactly what Trainer expects:
loss = None if labels is not None: loss = self.loss_function(labels, logits, self.config)
3. **Returns `ImageClassifierOutput`**: The output format is the standard transformers output, so Trainer handles it seamlessly.
## Full training example
from transformers import AutoModelForImageClassification, AutoImageProcessor, Trainer, TrainingArguments from datasets import load_dataset
Load dataset
dataset = load_dataset("food101", split="train[:5000]") dataset = dataset.train_test_split(test_size=0.2)
Load timm model + processor
checkpoint = "timm/resnet50.a1_in1k" image_processor = AutoImageProcessor.from_pretrained(checkpoint) model = AutoModelForImageClassification.from_pretrained( checkpoint, num_labels=101, ignore_mismatched_sizes=True, )
Preprocessing
def transform(batch): batch["pixel_values"] = [image_processor(img)["pixel_values"][0] for img in batch["image"]] batch["labels"] = batch["label"] return batch
dataset["train"].set_transform(transform) dataset["test"].set_transform(transform)
Train
training_args = TrainingArguments( output_dir="./timm-finetuned", num_train_epochs=3, per_device_train_batch_size=16, per_device_eval_batch_size=16, eval_strategy="epoch", save_strategy="epoch", logging_steps=50, remove_unused_columns=False, )
trainer = Trainer( model=model, args=training_args, train_dataset=dataset["train"], eval_dataset=dataset["test"], )
trainer.train()
Any timm checkpoint on the Hub (prefixed with `timm/`) works out of the box (ResNet, EfficientNet, ViT, ConvNeXt, etc). The wrapper handles all the translation between timm's interface and what Trainer expects.#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = []
# ///
"""
Estimate training time and cost for vision model training jobs on Hugging Face Jobs.
Usage:
uv run estimate_cost.py --model ustc-community/dfine-small-coco --dataset cppe-5 --hardware t4-small
uv run estimate_cost.py --model PekingU/rtdetr_v2_r50vd --dataset-size 5000 --hardware t4-small --epochs 30
uv run estimate_cost.py --model google/vit-base-patch16-224-in21k --dataset ethz/food101 --hardware t4-small --epochs 3
"""
import argparse
HARDWARE_COSTS = {
"t4-small": 0.40,
"t4-medium": 0.60,
"l4x1": 0.80,
"l4x4": 3.80,
"a10g-small": 1.00,
"a10g-large": 1.50,
"a10g-largex2": 3.00,
"a10g-largex4": 5.00,
"l40sx1": 1.80,
"l40sx4": 8.30,
"a100-large": 2.50,
"a100x4": 10.00,
}
# Vision model sizes in millions of parameters
MODEL_PARAMS_M = {
# Object detection
"dfine-small": 10.4,
"dfine-large": 31.4,
"dfine-xlarge": 63.5,
"rtdetr_v2_r18vd": 20.2,
"rtdetr_v2_r50vd": 43.0,
"rtdetr_v2_r101vd": 76.0,
"detr-resnet-50": 41.3,
"detr-resnet-101": 60.2,
"yolos-small": 30.7,
"yolos-tiny": 6.5,
# Image classification
"mobilenetv3_small": 2.5,
"mobilevit_s": 5.6,
"resnet50": 25.6,
"vit_base_patch16": 86.6,
# SAM / SAM2 segmentation
"sam-vit-base": 93.7,
"sam-vit-large": 312.3,
"sam-vit-huge": 641.1,
"sam2.1-hiera-tiny": 38.9,
"sam2.1-hiera-small": 46.0,
"sam2.1-hiera-base-plus": 80.8,
"sam2.1-hiera-large": 224.4,
}
KNOWN_DATASETS = {
# Object detection
"cppe-5": 1000,
"merve/license-plate": 6180,
# Image classification
"ethz/food101": 75750,
# SAM segmentation
"merve/MicroMat-mini": 240,
}
def extract_model_params(model_name: str) -> float:
"""Extract model size in millions of parameters from the model name."""
name_lower = model_name.lower()
for key, params in MODEL_PARAMS_M.items():
if key.lower() in name_lower:
return params
return 30.0 # reasonable default for vision models
def estimate_training_time(model_params_m: float, dataset_size: int, epochs: int,
image_size: int, batch_size: int, hardware: str) -> float:
"""Estimate training time in hours for vision model training."""
# Steps per epoch
steps_per_epoch = dataset_size / batch_size
# empirical calibration values
base_secs_per_step = 0.8
model_factor = (model_params_m / 30.0) ** 0.6
image_factor = (image_size / 640.0) ** 2
batch_factor = (batch_size / 8.0) ** 0.7
secs_per_step = base_secs_per_step * model_factor * image_factor * batch_factor
hardware_multipliers = {
"t4-small": 2.0,
"t4-medium": 2.0,
"l4x1": 1.2,
"l4x4": 0.5,
"a10g-small": 1.0,
"a10g-large": 1.0,
"a10g-largex2": 0.6,
"a10g-largex4": 0.4,
"l40sx1": 0.7,
"l40sx4": 0.25,
"a100-large": 0.5,
"a100x4": 0.2,
}
multiplier = hardware_multipliers.get(hardware, 1.0)
total_steps = steps_per_epoch * epochs
total_secs = total_steps * secs_per_step * multiplier
# Add overhead: model loading (~2 min), eval per epoch (~10% of training), Hub push (~3 min)
eval_overhead = total_secs * 0.10
fixed_overhead = 5 * 60 # 5 minutes
total_secs += eval_overhead + fixed_overhead
return total_secs / 3600
def parse_args():
parser = argparse.ArgumentParser(description="Estimate training cost for vision model training jobs")
parser.add_argument("--model", required=True,
help="Model name (e.g., 'ustc-community/dfine-small-coco' or 'detr-resnet-50')")
parser.add_argument("--dataset", default=None, help="Dataset name (for known size lookup)")
parser.add_argument("--hardware", required=True, choices=HARDWARE_COSTS.keys(), help="Hardware flavor")
parser.add_argument("--dataset-size", type=int, default=None,
help="Number of training images (overrides dataset lookup)")
parser.add_argument("--epochs", type=int, default=30, help="Number of training epochs (default: 30)")
parser.add_argument("--image-size", type=int, default=640, help="Image square size in pixels (default: 640)")
parser.add_argument("--batch-size", type=int, default=8, help="Per-device batch size (default: 8)")
return parser.parse_args()
def main():
args = parse_args()
model_params = extract_model_params(args.model)
print(f"Model: {args.model} (~{model_params:.1f}M parameters)")
if args.dataset_size:
dataset_size = args.dataset_size
elif args.dataset and args.dataset in KNOWN_DATASETS:
dataset_size = KNOWN_DATASETS[args.dataset]
elif args.dataset:
print(f"Unknown dataset '{args.dataset}', defaulting to 1000 images.")
print(f"Use --dataset-size to specify the exact count.")
dataset_size = 1000
else:
dataset_size = 1000
print(f"Dataset: {args.dataset or 'custom'} (~{dataset_size} images)")
print(f"Epochs: {args.epochs}")
print(f"Image size: {args.image_size}px")
print(f"Batch size: {args.batch_size}")
print(f"Hardware: {args.hardware} (${HARDWARE_COSTS[args.hardware]:.2f}/hr)")
print()
estimated_hours = estimate_training_time(
model_params, dataset_size, args.epochs, args.image_size, args.batch_size, args.hardware
)
estimated_cost = estimated_hours * HARDWARE_COSTS[args.hardware]
recommended_timeout = estimated_hours * 1.3 # 30% buffer
print(f"Estimated training time: {estimated_hours:.1f} hours")
print(f"Estimated cost: ${estimated_cost:.2f}")
print(f"Recommended timeout: {recommended_timeout:.1f}h (with 30% buffer)")
print()
if estimated_hours > 6:
print("Warning: Long training time. Consider:")
print(" - Reducing epochs or image size")
print(" - Using --max_train_samples for a test run first")
print(" - Upgrading hardware")
print()
if model_params > 50 and args.hardware in ("t4-small", "t4-medium"):
print("Warning: Large model on T4. If you hit OOM:")
print(" - Reduce batch size (try 4, then 2)")
print(" - Reduce image size (try 480)")
print(" - Upgrade to l4x1 or a10g-small")
print()
timeout_str = f"{recommended_timeout:.0f}h"
timeout_secs = int(recommended_timeout * 3600)
print(f"Example job configuration (MCP tool):")
print(f"""
hf_jobs("uv", {{
"script": "scripts/object_detection_training.py",
"script_args": [
"--model_name_or_path", "{args.model}",
"--dataset_name", "{args.dataset or 'your-dataset'}",
"--image_square_size", "{args.image_size}",
"--num_train_epochs", "{args.epochs}",
"--per_device_train_batch_size", "{args.batch_size}",
"--push_to_hub", "--do_train", "--do_eval"
],
"flavor": "{args.hardware}",
"timeout": "{timeout_str}",
"secrets": {{"HF_TOKEN": "$HF_TOKEN"}}
}})
""")
print(f"Example job configuration (Python API):")
print(f"""
api.run_uv_job(
script="scripts/object_detection_training.py",
script_args=[...],
flavor="{args.hardware}",
timeout={timeout_secs},
secrets={{"HF_TOKEN": get_token()}},
)
""")
if __name__ == "__main__":
main()
# /// script
# dependencies = [
# "transformers>=5.2.0",
# "accelerate>=1.1.0",
# "timm",
# "datasets>=4.0",
# "evaluate",
# "scikit-learn",
# "torchvision",
# "trackio",
# "huggingface_hub",
# ]
# ///
"""Fine-tuning any Transformers or timm model supported by AutoModelForImageClassification using the Trainer API."""
import logging
import os
import sys
from dataclasses import dataclass, field
from functools import partial
from typing import Any
import evaluate
import numpy as np
import torch
from datasets import load_dataset
from torchvision.transforms import (
CenterCrop,
Compose,
Normalize,
RandomHorizontalFlip,
RandomResizedCrop,
Resize,
ToTensor,
)
import trackio
import transformers
from transformers import (
AutoConfig,
AutoImageProcessor,
AutoModelForImageClassification,
DefaultDataCollator,
HfArgumentParser,
Trainer,
TrainingArguments,
)
from transformers.trainer import EvalPrediction
from transformers.utils import check_min_version
from transformers.utils.versions import require_version
logger = logging.getLogger(__name__)
check_min_version("4.57.0.dev0")
require_version("datasets>=2.0.0")
@dataclass
class DataTrainingArguments:
dataset_name: str = field(
default="ethz/food101",
metadata={"help": "Name of a dataset from the Hub."},
)
dataset_config_name: str | None = field(
default=None,
metadata={"help": "The configuration name of the dataset to use (via the datasets library)."},
)
train_val_split: float | None = field(
default=0.15,
metadata={"help": "Fraction to split off of train for validation (used only when no validation split exists)."},
)
max_train_samples: int | None = field(
default=None,
metadata={"help": "Truncate training set to this many samples (for debugging / quick tests)."},
)
max_eval_samples: int | None = field(
default=None,
metadata={"help": "Truncate evaluation set to this many samples."},
)
image_column_name: str = field(
default="image",
metadata={"help": "The column name for images in the dataset."},
)
label_column_name: str = field(
default="label",
metadata={"help": "The column name for labels in the dataset."},
)
@dataclass
class ModelArguments:
model_name_or_path: str = field(
default="timm/mobilenetv3_small_100.lamb_in1k",
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models."},
)
config_name: str | None = field(
default=None,
metadata={"help": "Pretrained config name or path if not the same as model_name."},
)
cache_dir: str | None = field(
default=None,
metadata={"help": "Where to store pretrained models downloaded from the Hub."},
)
model_revision: str = field(
default="main",
metadata={"help": "The specific model version to use (branch, tag, or commit id)."},
)
image_processor_name: str | None = field(
default=None,
metadata={"help": "Name or path of image processor config."},
)
ignore_mismatched_sizes: bool = field(
default=True,
metadata={"help": "Allow loading weights when num_labels differs from pretrained checkpoint."},
)
token: str | None = field(
default=None,
metadata={"help": "Auth token for private models / datasets."},
)
trust_remote_code: bool = field(
default=False,
metadata={"help": "Whether to trust remote code from Hub repos."},
)
def build_transforms(image_processor, is_training: bool):
"""Build torchvision transforms from the image processor's config."""
if hasattr(image_processor, "size"):
size = image_processor.size
if "shortest_edge" in size:
img_size = size["shortest_edge"]
elif "height" in size and "width" in size:
img_size = (size["height"], size["width"])
else:
img_size = 224
else:
img_size = 224
if hasattr(image_processor, "image_mean") and image_processor.image_mean:
normalize = Normalize(mean=image_processor.image_mean, std=image_processor.image_std)
else:
normalize = Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
if is_training:
return Compose([
RandomResizedCrop(img_size),
RandomHorizontalFlip(),
ToTensor(),
normalize,
])
else:
if isinstance(img_size, int):
resize_size = int(img_size / 0.875) # standard 87.5% center crop ratio
else:
resize_size = tuple(int(s / 0.875) for s in img_size)
return Compose([
Resize(resize_size),
CenterCrop(img_size),
ToTensor(),
normalize,
])
def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
# --- Hub authentication ---
from huggingface_hub import login
hf_token = os.environ.get("HF_TOKEN") or os.environ.get("hfjob")
if hf_token:
login(token=hf_token)
training_args.hub_token = hf_token
logger.info("Logged in to Hugging Face Hub")
elif training_args.push_to_hub:
logger.warning("HF_TOKEN not found in environment. Hub push will likely fail.")
# --- Trackio ---
trackio.init(project=training_args.output_dir, name=training_args.run_name)
# --- Logging ---
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
handlers=[logging.StreamHandler(sys.stdout)],
)
if training_args.should_log:
transformers.utils.logging.set_verbosity_info()
log_level = training_args.get_process_log_level()
logger.setLevel(log_level)
transformers.utils.logging.set_verbosity(log_level)
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
logger.warning(
f"Process rank: {training_args.local_process_index}, device: {training_args.device}, "
f"n_gpu: {training_args.n_gpu}, distributed training: "
f"{training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
# --- Load dataset ---
dataset = load_dataset(
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
trust_remote_code=model_args.trust_remote_code,
)
# --- Resolve label column ---
label_col = data_args.label_column_name
if label_col not in dataset["train"].column_names:
candidates = [c for c in dataset["train"].column_names if c in ("label", "labels", "class", "fine_label")]
if candidates:
label_col = candidates[0]
logger.info(f"Label column '{data_args.label_column_name}' not found, using '{label_col}'")
else:
raise ValueError(
f"Label column '{data_args.label_column_name}' not found. "
f"Available columns: {dataset['train'].column_names}"
)
# --- Discover labels ---
label_feature = dataset["train"].features[label_col]
if hasattr(label_feature, "names"):
label_names = label_feature.names
else:
unique_labels = sorted(set(dataset["train"][label_col]))
if all(isinstance(l, str) for l in unique_labels):
label_names = unique_labels
else:
label_names = [str(l) for l in unique_labels]
num_labels = len(label_names)
id2label = dict(enumerate(label_names))
label2id = {v: k for k, v in id2label.items()}
logger.info(f"Number of classes: {num_labels}")
# --- Remap string labels to int if needed ---
sample_label = dataset["train"][0][label_col]
if isinstance(sample_label, str):
logger.info("Remapping string labels to integer IDs")
for split_name in list(dataset.keys()):
dataset[split_name] = dataset[split_name].map(
lambda ex: {label_col: label2id[ex[label_col]]},
)
# --- Shuffle + Train/val split ---
dataset["train"] = dataset["train"].shuffle(seed=training_args.seed)
data_args.train_val_split = None if "validation" in dataset else data_args.train_val_split
if isinstance(data_args.train_val_split, float) and data_args.train_val_split > 0.0:
split = dataset["train"].train_test_split(data_args.train_val_split, seed=training_args.seed)
dataset["train"] = split["train"]
dataset["validation"] = split["test"]
# --- Truncate ---
if data_args.max_train_samples is not None:
max_train = min(data_args.max_train_samples, len(dataset["train"]))
dataset["train"] = dataset["train"].select(range(max_train))
logger.info(f"Truncated training set to {max_train} samples")
if data_args.max_eval_samples is not None and "validation" in dataset:
max_eval = min(data_args.max_eval_samples, len(dataset["validation"]))
dataset["validation"] = dataset["validation"].select(range(max_eval))
logger.info(f"Truncated validation set to {max_eval} samples")
# --- Load model & image processor ---
common_pretrained_args = {
"cache_dir": model_args.cache_dir,
"revision": model_args.model_revision,
"token": model_args.token,
"trust_remote_code": model_args.trust_remote_code,
}
config = AutoConfig.from_pretrained(
model_args.config_name or model_args.model_name_or_path,
num_labels=num_labels,
label2id=label2id,
id2label=id2label,
**common_pretrained_args,
)
model = AutoModelForImageClassification.from_pretrained(
model_args.model_name_or_path,
config=config,
ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,
**common_pretrained_args,
)
image_processor = AutoImageProcessor.from_pretrained(
model_args.image_processor_name or model_args.model_name_or_path,
**common_pretrained_args,
)
# --- Build transforms ---
train_transforms = build_transforms(image_processor, is_training=True)
val_transforms = build_transforms(image_processor, is_training=False)
image_col = data_args.image_column_name
def preprocess_train(examples):
return {
"pixel_values": [train_transforms(img.convert("RGB")) for img in examples[image_col]],
"labels": examples[label_col],
}
def preprocess_val(examples):
return {
"pixel_values": [val_transforms(img.convert("RGB")) for img in examples[image_col]],
"labels": examples[label_col],
}
dataset["train"].set_transform(preprocess_train)
if "validation" in dataset:
dataset["validation"].set_transform(preprocess_val)
if "test" in dataset:
dataset["test"].set_transform(preprocess_val)
# --- Metrics ---
accuracy_metric = evaluate.load("accuracy")
def compute_metrics(eval_pred: EvalPrediction):
predictions = np.argmax(eval_pred.predictions, axis=1)
return accuracy_metric.compute(predictions=predictions, references=eval_pred.label_ids)
# --- Trainer ---
eval_dataset = None
if training_args.do_eval:
if "validation" in dataset:
eval_dataset = dataset["validation"]
elif "test" in dataset:
eval_dataset = dataset["test"]
trainer = Trainer(
model=model,
args=training_args,
train_dataset=dataset["train"] if training_args.do_train else None,
eval_dataset=eval_dataset,
processing_class=image_processor,
data_collator=DefaultDataCollator(),
compute_metrics=compute_metrics,
)
# --- Train ---
if training_args.do_train:
train_result = trainer.train(resume_from_checkpoint=training_args.resume_from_checkpoint)
trainer.save_model()
trainer.log_metrics("train", train_result.metrics)
trainer.save_metrics("train", train_result.metrics)
trainer.save_state()
# --- Evaluate ---
if training_args.do_eval:
test_dataset = dataset.get("test", dataset.get("validation"))
test_prefix = "test" if "test" in dataset else "eval"
if test_dataset is not None:
metrics = trainer.evaluate(eval_dataset=test_dataset, metric_key_prefix=test_prefix)
trainer.log_metrics(test_prefix, metrics)
trainer.save_metrics(test_prefix, metrics)
trackio.finish()
# --- Push to Hub ---
kwargs = {
"finetuned_from": model_args.model_name_or_path,
"dataset": data_args.dataset_name,
"tags": ["image-classification", "vision"],
}
if training_args.push_to_hub:
trainer.push_to_hub(**kwargs)
else:
trainer.create_model_card(**kwargs)
if __name__ == "__main__":
main()
Related skills
FAQ
What does huggingface-vision-trainer do?
Trains and fine-tunes vision models for object detection (D-FINE, RT-DETR v2, DETR, YOLOS), image classification (timm models - MobileNetV3, MobileViT, ResNet, ViT/DINOv3 - plus any Transformers classifier), and SAM/SAM2
When should I use huggingface-vision-trainer?
Trains and fine-tunes vision models for object detection (D-FINE, RT-DETR v2, DETR, YOLOS), image classification (timm models - MobileNetV3, MobileViT, ResNet, ViT/DINOv3 - plus any Transformers classifier), and SAM/SAM2
What are common prerequisites?
--- name: huggingface-vision-trainer description: Trains and fine-tunes vision models for object detection (D-FINE, RT-DETR v2, DETR, YOLOS), image classification (timm models - MobileNetV3, MobileViT, ResNet, ViT/DINOv3
Is Huggingface Vision Trainer safe to install?
skills.sh reports 2 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.