Huggingface Vision Trainer
Hugging FaceOfficialPublished by Hugging Face
- Skill
- Workflow
- Data and AI
- Apache-2.0
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured procedure for training object detection, image classification, and SAM/SAM2 segmentation models using Hugging Face Jobs. It covers the entire lifecycle from dataset validation and hardware selection to script configuration and model persistence on the Hugging Face Hub. By leveraging managed cloud GPUs, it eliminates the need for local GPU setups while ensuring training results are saved securely.
What it does
- Validates dataset formats to prevent common training failures
- Provides production-ready training scripts for object detection, classification, and segmentation
- Manages cloud GPU job submission with cost estimation and hardware selection
- Configures automatic model persistence to the Hugging Face Hub
- Integrates Trackio for real-time training monitoring
- Handles complex requirements like bbox preprocessing and prompt-based segmentation
When to use it
- When you need to fine-tune vision models like D-FINE, RT-DETR, or ViT on cloud GPUs
- When training SAM/SAM2 models for segmentation or image matting tasks
- When you have a custom dataset that requires validation before starting a long training job
- When you need to run training jobs asynchronously on managed infrastructure
Advantages
- No local GPU hardware required
- Automated dataset validation reduces training failures
- Seamless integration with Hugging Face Hub for model versioning
- Flexible hardware options to balance cost and performance
- Standardized scripts ensure consistent training practices
Usage examples
- “I want to fine-tune a D-FINE model for object detection on my custom dataset.”
- The agent will guide you through dataset validation, ask for your preferred GPU hardware, and provide the command to submit the training job to Hugging Face Jobs.
- “How do I train a SAM2 model for image matting?”
- The agent will provide the SAM2 training script, explain how to format your prompts, and help you configure the job for cloud execution.
- “I need to classify images using a MobileNetV3 model.”
- The agent will assist in setting up the image classification training script and selecting the appropriate hardware flavor for your dataset size.
- “My training job keeps failing, how can I check my dataset?”
- The agent will instruct you to run the dataset_inspector.py script to identify format mismatches or missing columns before re-submitting your job.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/huggingface/huggingface-vision-trainer/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip huggingface-vision-trainer.zip -d .agents/skills
Documentation by Hugging Face
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-fieldsBboxes 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 missingALWAYS validate unknown datasets before GPU training (see Dataset Validation section)
Dataset Requirements — Image Classification
Dataset must exist on Hub
Must have an
imagecolumn (PIL images) and alabelcolumn (integer class IDs or strings)The label column can be
ClassLabeltype (with names) or plain integers/strings — strings are auto-remappedCommon column names auto-detected:
label,labels,class,fine_labelALWAYS validate unknown datasets before GPU training (see Dataset Validation section)
Dataset Requirements — SAM/SAM2 Segmentation
Dataset must exist on Hub
Must have an
imagecolumn (PIL images) and amaskcolumn (binary ground-truth segmentation mask)Must have a prompt — either:
A
promptcolumn with JSON containing{"bbox": [x0,y0,x1,y1]}or{"point": [x,y]}OR a dedicated
bboxcolumn with[x0,y0,x1,y1]valuesOR a dedicated
pointcolumn 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
Save the script locally to
submitted_jobs/in the workspace root (create if needed) with a descriptive name liketraining_<dataset>_<YYYYMMDD_HHMMSS>.py. Tell the user the path.Submit using
hf_jobsMCP tool (preferred) orHfApi().run_uv_job()— see directive #1 for both methods. Pass all config viascript_args.Report the job ID (from
.idattribute), monitoring URL, Trackio dashboard (https://huggingface.co/spaces/{username}/trackio), expected time, and estimated cost.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.pyDo NOT rely on implicit token resolution (
hub_token=None) — unreliable in JobsSee 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:
boolfields (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
HF Jobs Guide — Main Jobs documentation
HF Jobs Configuration — Hardware, secrets, timeouts, namespaces
HF Jobs CLI Reference — Command line interface
Files
- ATTRIBUTION.mdAdded by AutoGineer896 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md29.5 KiB
- references/finetune_sam2_trainer.md6.3 KiB
- references/hub_saving.md16.6 KiB
- references/image_classification_training_notebook.md10.8 KiB
- references/object_detection_training_notebook.md29.2 KiB
- references/reliability_principles.md9.3 KiB
- references/timm_trainer.md3.5 KiB
- scripts/dataset_inspector.pyScript31.1 KiB
- scripts/estimate_cost.pyScript7.2 KiB
- scripts/image_classification_training.pyScript13.1 KiB
- scripts/object_detection_training.pyScript26.7 KiB
- scripts/sam_segmentation_training.pyScript13.6 KiB
scripts/dataset_inspector.py
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = []
# ///
"""
Dataset Format Inspector for Vision Model Training
Inspects Hugging Face datasets to determine compatibility with object detection
and image classification training.
Uses Datasets Server API for instant results - no dataset download needed!
ULTRA-EFFICIENT: Uses HF Datasets Server API - completes in <2 seconds.
Usage with HF Jobs:
hf_jobs("uv", {
"script": "path/to/dataset_inspector.py",
"script_args": ["--dataset", "your/dataset", "--split", "train"]
})
"""
import argparse
import math
import sys
import json
import urllib.request
import urllib.parse
from typing import List, Dict, Any, Tuple
def parse_args():
parser = argparse.ArgumentParser(description="Inspect dataset format for vision model training")
parser.add_argument("--dataset", type=str, required=True, help="Dataset name")
parser.add_argument("--split", type=str, default="train", help="Dataset split (default: train)")
parser.add_argument("--config", type=str, default="default", help="Dataset config name (default: default)")
parser.add_argument("--preview", type=int, default=150, help="Max chars per field preview")
parser.add_argument("--samples", type=int, default=5, help="Number of samples to fetch (default: 5)")
parser.add_argument("--json-output", action="store_true", help="Output as JSON")
return parser.parse_args()
def api_request(url: str) -> Dict:
"""Make API request to Datasets Server"""
try:
with urllib.request.urlopen(url, timeout=10) as response:
return json.loads(response.read().decode())
except urllib.error.HTTPError as e:
if e.code == 404:
return None
raise Exception(f"API request failed: {e.code} {e.reason}")
except Exception as e:
raise Exception(f"API request failed: {str(e)}")
def get_splits(dataset: str) -> Dict:
"""Get available splits for dataset"""
url = f"https://datasets-server.huggingface.co/splits?dataset={urllib.parse.quote(dataset)}"
return api_request(url)
def get_rows(dataset: str, config: str, split: str, offset: int = 0, length: int = 5) -> Dict:
"""Get rows from dataset"""
url = f"https://datasets-server.huggingface.co/rows?dataset={urllib.parse.quote(dataset)}&config={config}&split={split}&offset={offset}&length={length}"
return api_request(url)
def find_columns(columns: List[str], patterns: List[str]) -> List[str]:
"""Find columns matching patterns"""
return [c for c in columns if any(p in c.lower() for p in patterns)]
def detect_bbox_format(bbox: List[float], image_size: Tuple[int, int] = None) -> str:
"""
Detect bounding box format based on values and optionally image dimensions.
Common formats:
- [x_min, y_min, x_max, y_max] - XYXY (Pascal VOC)
- [x_min, y_min, width, height] - XYWH (COCO)
- [x_center, y_center, width, height] - CXCYWH (YOLO normalized)
"""
if len(bbox) != 4:
return "unknown (not 4 values)"
a, b, c, d = bbox
is_normalized = all(0 <= v <= 1 for v in bbox)
if c < a or d < b:
if is_normalized:
return "xywh_normalized"
return "xywh (COCO style)"
# c > a and d > b — ambiguous between xyxy and xywh.
# Use image dimensions to disambiguate when available.
if image_size is not None:
img_w, img_h = image_size
# If interpreting as xywh, right edge = a + c; if that overshoots the
# image while c alone fits, the format is more likely xyxy.
xywh_exceeds = (a + c > img_w * 1.05) or (b + d > img_h * 1.05)
xyxy_exceeds = (c > img_w * 1.05) or (d > img_h * 1.05)
if xywh_exceeds and not xyxy_exceeds:
return "xyxy (Pascal VOC style)"
if xyxy_exceeds and not xywh_exceeds:
return "xywh (COCO style)"
if is_normalized:
return "xyxy_normalized"
return "xyxy (Pascal VOC style)"
def _extract_image_size(row: Dict) -> Tuple[int, int] | None:
"""Try to extract (width, height) from the image column returned by Datasets Server."""
for col in ("image", "img", "picture", "photo"):
img = row.get(col)
if isinstance(img, dict):
w = img.get("width")
h = img.get("height")
if isinstance(w, (int, float)) and isinstance(h, (int, float)):
return (int(w), int(h))
return None
def analyze_annotations(sample_rows: List[Dict], annotation_cols: List[str]) -> Dict[str, Any]:
"""Analyze annotation structure from sample rows"""
if not annotation_cols:
return {"found": False}
annotation_col = annotation_cols[0]
annotations_info = {
"found": True,
"column": annotation_col,
"sample_structures": [],
"bbox_formats": [],
"categories_found": [],
"avg_objects_per_image": 0,
"max_objects": 0,
"min_objects": float('inf'),
}
total_objects = 0
valid_samples = 0
for row in sample_rows:
ann = row["row"].get(annotation_col)
if not ann:
continue
valid_samples += 1
image_size = _extract_image_size(row["row"])
# Check if it's a list of annotations or a dict
if isinstance(ann, dict):
# COCO-style or structured annotation
sample_structure = {
"type": "dict",
"keys": list(ann.keys())
}
# Check for bounding boxes
if "bbox" in ann or "bboxes" in ann:
bbox_key = "bbox" if "bbox" in ann else "bboxes"
bboxes = ann[bbox_key]
if isinstance(bboxes, list) and len(bboxes) > 0:
if isinstance(bboxes[0], list):
# Multiple bboxes
num_objects = len(bboxes)
total_objects += num_objects
annotations_info["max_objects"] = max(annotations_info["max_objects"], num_objects)
annotations_info["min_objects"] = min(annotations_info["min_objects"], num_objects)
# Analyze first bbox format
bbox_format = detect_bbox_format(bboxes[0], image_size)
annotations_info["bbox_formats"].append(bbox_format)
else:
# Single bbox
total_objects += 1
annotations_info["max_objects"] = max(annotations_info["max_objects"], 1)
annotations_info["min_objects"] = min(annotations_info["min_objects"], 1)
bbox_format = detect_bbox_format(bboxes, image_size)
annotations_info["bbox_formats"].append(bbox_format)
# Check for categories/classes
for key in ["category", "categories", "label", "labels", "class", "classes", "category_id"]:
if key in ann:
cats = ann[key]
if isinstance(cats, list):
annotations_info["categories_found"].extend([str(c) for c in cats])
else:
annotations_info["categories_found"].append(str(cats))
annotations_info["sample_structures"].append(sample_structure)
elif isinstance(ann, list):
# List of annotation dicts
sample_structure = {
"type": "list",
"length": len(ann),
"item_type": type(ann[0]).__name__ if ann else None
}
if ann and isinstance(ann[0], dict):
sample_structure["item_keys"] = list(ann[0].keys())
# Count objects
num_objects = len(ann)
total_objects += num_objects
annotations_info["max_objects"] = max(annotations_info["max_objects"], num_objects)
annotations_info["min_objects"] = min(annotations_info["min_objects"], num_objects)
# Check first annotation
first_ann = ann[0]
if "bbox" in first_ann:
bbox_format = detect_bbox_format(first_ann["bbox"], image_size)
annotations_info["bbox_formats"].append(bbox_format)
# Check for categories
for key in ["category", "label", "class", "category_id"]:
if key in first_ann:
for item in ann:
if key in item:
annotations_info["categories_found"].append(str(item[key]))
annotations_info["sample_structures"].append(sample_structure)
if valid_samples > 0:
annotations_info["avg_objects_per_image"] = round(total_objects / valid_samples, 2)
if annotations_info["min_objects"] == float('inf'):
annotations_info["min_objects"] = 0
# Get unique categories
annotations_info["categories_found"] = list(set(annotations_info["categories_found"]))
annotations_info["num_classes"] = len(annotations_info["categories_found"])
# Get most common bbox format
if annotations_info["bbox_formats"]:
from collections import Counter
format_counts = Counter(annotations_info["bbox_formats"])
annotations_info["primary_bbox_format"] = format_counts.most_common(1)[0][0]
return annotations_info
def check_image_classification_compatibility(columns: List[str], sample_rows: List[Dict], features: List[Dict]) -> Dict[str, Any]:
"""Check image classification dataset compatibility"""
image_cols = find_columns(columns, ["image", "img", "picture", "photo"])
has_image = len(image_cols) > 0
label_cols = find_columns(columns, ["label", "labels", "class", "fine_label", "coarse_label"])
has_label = len(label_cols) > 0
label_info: Dict[str, Any] = {"found": has_label}
if has_label:
label_col = label_cols[0]
label_info["column"] = label_col
# Detect whether label is ClassLabel (int with names) or plain int/string
for f in features:
if f.get("name") == label_col:
ftype = f.get("type", "")
if isinstance(ftype, dict) and ftype.get("_type") == "ClassLabel":
label_info["type"] = "ClassLabel"
names = ftype.get("names", [])
label_info["num_classes"] = len(names)
label_info["class_names"] = names[:20]
if len(names) > 20:
label_info["class_names_truncated"] = True
elif isinstance(ftype, dict) and ftype.get("dtype") in ("int64", "int32", "int8"):
label_info["type"] = "int"
elif isinstance(ftype, dict) and ftype.get("dtype") == "string":
label_info["type"] = "string"
break
# Discover unique labels from samples if ClassLabel info wasn't in features
if "num_classes" not in label_info:
unique = set()
for row in sample_rows:
val = row["row"].get(label_col)
if val is not None:
unique.add(val)
label_info["sample_unique_labels"] = sorted(unique, key=str)[:20]
label_info["sample_unique_count"] = len(unique)
ready = has_image and has_label
return {
"ready": ready,
"has_image": has_image,
"image_columns": image_cols,
"has_label": has_label,
"label_columns": label_cols,
"label_info": label_info,
}
def check_object_detection_compatibility(columns: List[str], sample_rows: List[Dict]) -> Dict[str, Any]:
"""Check object detection dataset compatibility"""
# Find image column
image_cols = find_columns(columns, ["image", "img", "picture", "photo"])
has_image = len(image_cols) > 0
# Find annotation columns
annotation_cols = find_columns(columns, ["objects", "annotations", "ann", "bbox", "bboxes", "detection"])
has_annotations = len(annotation_cols) > 0
# Analyze annotations
annotations_info = analyze_annotations(sample_rows, annotation_cols) if has_annotations else {"found": False}
# Check for separate bbox and category columns
bbox_cols = find_columns(columns, ["bbox", "bboxes", "boxes"])
category_cols = find_columns(columns, ["category", "label", "class", "categories", "labels", "classes"])
# Determine readiness
ready = has_image and (has_annotations or (len(bbox_cols) > 0 and len(category_cols) > 0))
return {
"ready": ready,
"has_image": has_image,
"image_columns": image_cols,
"has_annotations": has_annotations,
"annotation_columns": annotation_cols,
"separate_bbox_columns": bbox_cols,
"separate_category_columns": category_cols,
"annotations_info": annotations_info,
}
def check_sam_segmentation_compatibility(columns: List[str], sample_rows: List[Dict], features: List[Dict]) -> Dict[str, Any]:
"""Check SAM/SAM2 segmentation dataset compatibility.
A valid SAM segmentation dataset needs:
- An image column
- A mask column (binary ground-truth segmentation mask)
- A prompt: either a bbox prompt or point prompt (in a JSON prompt column, or dedicated columns)
"""
image_cols = find_columns(columns, ["image", "img", "picture", "photo"])
has_image = len(image_cols) > 0
mask_cols = find_columns(columns, ["mask", "segmentation", "alpha", "matte"])
has_mask = len(mask_cols) > 0
prompt_cols = find_columns(columns, ["prompt"])
bbox_cols = [c for c in columns if c in ("bbox", "bboxes", "box", "boxes")]
point_cols = [c for c in columns if c in ("point", "points", "input_point", "input_points")]
prompt_info: Dict[str, Any] = {
"has_prompt": False,
"prompt_type": None,
"source": None,
"bbox_valid": None,
}
# Try JSON prompt column first
if prompt_cols:
for row in sample_rows:
raw = row["row"].get(prompt_cols[0])
if raw is None:
continue
parsed = raw if isinstance(raw, dict) else _try_json(raw)
if parsed is None:
continue
if isinstance(parsed, dict):
if "bbox" in parsed or "box" in parsed:
prompt_info["has_prompt"] = True
prompt_info["prompt_type"] = "bbox"
prompt_info["source"] = f"JSON column '{prompt_cols[0]}'"
bbox = parsed.get("bbox") or parsed.get("box")
prompt_info["bbox_valid"] = _validate_bbox(bbox, _extract_image_size(row["row"]))
break
elif "point" in parsed or "points" in parsed:
prompt_info["has_prompt"] = True
prompt_info["prompt_type"] = "point"
prompt_info["source"] = f"JSON column '{prompt_cols[0]}'"
break
if not prompt_info["has_prompt"] and bbox_cols:
prompt_info["has_prompt"] = True
prompt_info["prompt_type"] = "bbox"
prompt_info["source"] = f"column '{bbox_cols[0]}'"
for row in sample_rows:
bbox = row["row"].get(bbox_cols[0])
if bbox is not None:
prompt_info["bbox_valid"] = _validate_bbox(bbox, _extract_image_size(row["row"]))
break
if not prompt_info["has_prompt"] and point_cols:
prompt_info["has_prompt"] = True
prompt_info["prompt_type"] = "point"
prompt_info["source"] = f"column '{point_cols[0]}'"
ready = has_image and has_mask and prompt_info["has_prompt"]
return {
"ready": ready,
"has_image": has_image,
"image_columns": image_cols,
"has_mask": has_mask,
"mask_columns": mask_cols,
"prompt_columns": prompt_cols,
"bbox_columns": bbox_cols,
"point_columns": point_cols,
"prompt_info": prompt_info,
}
def _try_json(value) -> Any:
if not isinstance(value, str):
return None
try:
return json.loads(value)
except (json.JSONDecodeError, TypeError):
return None
def _validate_bbox(bbox, image_size=None) -> Dict[str, Any]:
"""Validate a single bounding box and return diagnostics."""
result: Dict[str, Any] = {"valid": False}
if not isinstance(bbox, (list, tuple)):
result["error"] = "bbox is not a list"
return result
if len(bbox) != 4:
result["error"] = f"expected 4 values, got {len(bbox)}"
return result
try:
vals = [float(v) for v in bbox]
except (TypeError, ValueError):
result["error"] = "non-numeric values"
return result
if not all(math.isfinite(v) for v in vals):
result["error"] = "contains non-finite values"
return result
x0, y0, x1, y1 = vals
if x1 <= x0 or y1 <= y0:
if vals[2] > 0 and vals[3] > 0:
result["format_hint"] = "likely xywh"
else:
result["error"] = "degenerate bbox (zero or negative area)"
return result
else:
result["format_hint"] = "likely xyxy"
if image_size is not None:
img_w, img_h = image_size
if any(v > max(img_w, img_h) * 1.5 for v in vals):
result["warning"] = "coordinates exceed image bounds"
result["valid"] = True
result["values"] = vals
return result
def generate_mapping_code(info: Dict[str, Any]) -> str:
"""Generate mapping code if needed"""
if info["ready"]:
ann_info = info["annotations_info"]
if not ann_info.get("found"):
return None
# Check if format conversion is needed
ann_col = ann_info.get("column")
bbox_format = ann_info.get("primary_bbox_format", "unknown")
if "coco" in bbox_format.lower() or "xywh" in bbox_format.lower():
# Already COCO format
return f"""# Dataset appears to be in COCO format (xywh)
# Image column: {info['image_columns'][0] if info['image_columns'] else 'image'}
# Annotation column: {ann_col}
# Use directly with transformers object detection models"""
elif "xyxy" in bbox_format.lower():
# Need to convert from XYXY to XYWH
return f"""# Convert from XYXY (Pascal VOC) to XYWH (COCO) format
def convert_to_coco_format(example):
annotations = example['{ann_col}']
if isinstance(annotations, list):
for ann in annotations:
if 'bbox' in ann:
x_min, y_min, x_max, y_max = ann['bbox']
ann['bbox'] = [x_min, y_min, x_max - x_min, y_max - y_min]
elif isinstance(annotations, dict) and 'bbox' in annotations:
bbox = annotations['bbox']
if isinstance(bbox, list) and len(bbox) > 0 and isinstance(bbox[0], list):
for i, box in enumerate(bbox):
x_min, y_min, x_max, y_max = box
bbox[i] = [x_min, y_min, x_max - x_min, y_max - y_min]
return example
dataset = dataset.map(convert_to_coco_format)"""
elif not info["ready"]:
# Need to create annotations structure
if info["separate_bbox_columns"] and info["separate_category_columns"]:
bbox_col = info["separate_bbox_columns"][0]
cat_col = info["separate_category_columns"][0]
return f"""# Combine separate bbox and category columns
def create_annotations(example):
bboxes = example['{bbox_col}']
categories = example['{cat_col}']
if not isinstance(bboxes, list):
bboxes = [bboxes]
if not isinstance(categories, list):
categories = [categories]
annotations = []
for bbox, cat in zip(bboxes, categories):
annotations.append({{'bbox': bbox, 'category': cat}})
example['objects'] = annotations
return example
dataset = dataset.map(create_annotations)"""
return None
def format_value_preview(value: Any, max_chars: int) -> str:
"""Format value for preview"""
if value is None:
return "None"
elif isinstance(value, str):
return value[:max_chars] + ("..." if len(value) > max_chars else "")
elif isinstance(value, dict):
keys = list(value.keys())
return f"{{dict with {len(keys)} keys: {', '.join(keys[:5])}}}"
elif isinstance(value, list):
if len(value) == 0:
return "[]"
elif isinstance(value[0], dict):
return f"[{len(value)} items] First item keys: {list(value[0].keys())}"
elif isinstance(value[0], list):
return f"[{len(value)} items] First item: {value[0]}"
else:
preview = str(value)
return preview[:max_chars] + ("..." if len(preview) > max_chars else "")
else:
preview = str(value)
return preview[:max_chars] + ("..." if len(preview) > max_chars else "")
def main():
args = parse_args()
print(f"Fetching dataset info via Datasets Server API...")
try:
# Get splits info
splits_data = get_splits(args.dataset)
if not splits_data or "splits" not in splits_data:
print(f"ERROR: Could not fetch splits for dataset '{args.dataset}'")
print(f" Dataset may not exist or is not accessible via Datasets Server API")
sys.exit(1)
# Find the right config
available_configs = set()
split_found = False
config_to_use = args.config
for split_info in splits_data["splits"]:
available_configs.add(split_info["config"])
if split_info["config"] == args.config and split_info["split"] == args.split:
split_found = True
# If default config not found, try first available
if not split_found and available_configs:
config_to_use = list(available_configs)[0]
print(f"Config '{args.config}' not found, trying '{config_to_use}'...")
# Get rows
rows_data = get_rows(args.dataset, config_to_use, args.split, offset=0, length=args.samples)
if not rows_data or "rows" not in rows_data:
print(f"ERROR: Could not fetch rows for dataset '{args.dataset}'")
print(f" Split '{args.split}' may not exist")
print(f" Available configs: {', '.join(sorted(available_configs))}")
sys.exit(1)
rows = rows_data["rows"]
if not rows:
print(f"ERROR: No rows found in split '{args.split}'")
sys.exit(1)
# Extract column info from first row
first_row = rows[0]["row"]
columns = list(first_row.keys())
features = rows_data.get("features", [])
# Get total count if available
total_examples = "Unknown"
for split_info in splits_data["splits"]:
if split_info["config"] == config_to_use and split_info["split"] == args.split:
total_examples = f"{split_info.get('num_examples', 'Unknown'):,}" if isinstance(split_info.get('num_examples'), int) else "Unknown"
break
except Exception as e:
print(f"ERROR: {str(e)}")
sys.exit(1)
# Run compatibility checks
od_info = check_object_detection_compatibility(columns, rows)
ic_info = check_image_classification_compatibility(columns, rows, features)
sam_info = check_sam_segmentation_compatibility(columns, rows, features)
# JSON output mode
if args.json_output:
result = {
"dataset": args.dataset,
"config": config_to_use,
"split": args.split,
"total_examples": total_examples,
"columns": columns,
"features": [{"name": f["name"], "type": f["type"]} for f in features] if features else [],
"object_detection_compatibility": od_info,
"image_classification_compatibility": ic_info,
"sam_segmentation_compatibility": sam_info,
}
print(json.dumps(result, indent=2))
sys.exit(0)
# Human-readable output optimized for LLM parsing
print("=" * 80)
print(f"VISION DATASET INSPECTION")
print("=" * 80)
print(f"\nDataset: {args.dataset}")
print(f"Config: {config_to_use}")
print(f"Split: {args.split}")
print(f"Total examples: {total_examples}")
print(f"Samples fetched: {len(rows)}")
print(f"\n{'COLUMNS':-<80}")
if features:
for feature in features:
print(f" {feature['name']}: {feature['type']}")
else:
for col in columns:
print(f" {col}: (type info not available)")
print(f"\n{'EXAMPLE DATA':-<80}")
example = first_row
for col in columns:
value = example.get(col)
display = format_value_preview(value, args.preview)
print(f"\n{col}:")
print(f" {display}")
# --- Image Classification ---
print(f"\n{'IMAGE CLASSIFICATION COMPATIBILITY':-<80}")
print(f"\n[STATUS] {'✓ READY' if ic_info['ready'] else '✗ NOT COMPATIBLE'}")
print(f"\nImage Column:")
if ic_info["has_image"]:
print(f" ✓ Found: {', '.join(ic_info['image_columns'])}")
else:
print(f" ✗ No image column detected")
print(f"\nLabel Column:")
if ic_info["has_label"]:
print(f" ✓ Found: {', '.join(ic_info['label_columns'])}")
li = ic_info["label_info"]
if li.get("type"):
print(f" • Type: {li['type']}")
if li.get("num_classes"):
print(f" • Number of Classes: {li['num_classes']}")
if li.get("class_names"):
names = li["class_names"]
display = ", ".join(str(n) for n in names[:10])
if len(names) > 10:
display += f" ... ({li['num_classes']} total)"
print(f" • Classes: {display}")
elif li.get("sample_unique_labels"):
labels = li["sample_unique_labels"]
display = ", ".join(str(l) for l in labels[:10])
if li.get("sample_unique_count", 0) > 10:
display += f" ... ({li['sample_unique_count']}+ from sample)"
print(f" • Sample labels: {display}")
else:
print(f" ✗ No label column detected")
print(f" Expected column names: 'label', 'labels', 'class', 'fine_label'")
if ic_info["ready"]:
lc = ic_info["label_info"].get("column", "label")
print(f"\n Use with: scripts/image_classification_training.py")
print(f" --image_column_name {ic_info['image_columns'][0]} --label_column_name {lc}")
# --- Object Detection ---
print(f"\n{'OBJECT DETECTION COMPATIBILITY':-<80}")
print(f"\n[STATUS] {'✓ READY' if od_info['ready'] else '✗ NOT COMPATIBLE'}")
print(f"\nImage Column:")
if od_info["has_image"]:
print(f" ✓ Found: {', '.join(od_info['image_columns'])}")
else:
print(f" ✗ No image column detected")
print(f" Expected column names: 'image', 'img', 'picture', 'photo'")
print(f"\nAnnotations:")
if od_info["has_annotations"]:
print(f" ✓ Found: {', '.join(od_info['annotation_columns'])}")
ann_info = od_info["annotations_info"]
if ann_info.get("found"):
print(f"\n Annotation Details:")
print(f" • Column: {ann_info['column']}")
if ann_info.get("primary_bbox_format"):
print(f" • BBox Format: {ann_info['primary_bbox_format']}")
if ann_info.get("num_classes", 0) > 0:
print(f" • Number of Classes: {ann_info['num_classes']}")
print(f" • Classes: {', '.join(ann_info['categories_found'][:10])}")
if len(ann_info['categories_found']) > 10:
print(f" (showing first 10 of {len(ann_info['categories_found'])})")
print(f" • Avg Objects/Image: {ann_info['avg_objects_per_image']}")
print(f" • Min Objects: {ann_info['min_objects']}")
print(f" • Max Objects: {ann_info['max_objects']}")
elif od_info["separate_bbox_columns"] and od_info["separate_category_columns"]:
print(f" ⚠ Separate bbox and category columns found:")
print(f" BBox columns: {', '.join(od_info['separate_bbox_columns'])}")
print(f" Category columns: {', '.join(od_info['separate_category_columns'])}")
print(f" Action: These need to be combined (see mapping code below)")
else:
print(f" ✗ No annotation columns detected")
print(f" Expected: 'objects', 'annotations', 'bbox'/'bboxes' + 'category'/'label'")
# --- SAM Segmentation ---
print(f"\n{'SAM SEGMENTATION COMPATIBILITY':-<80}")
print(f"\n[STATUS] {'✓ READY' if sam_info['ready'] else '✗ NOT COMPATIBLE'}")
print(f"\nImage Column:")
if sam_info["has_image"]:
print(f" ✓ Found: {', '.join(sam_info['image_columns'])}")
else:
print(f" ✗ No image column detected")
print(f"\nMask Column:")
if sam_info["has_mask"]:
print(f" ✓ Found: {', '.join(sam_info['mask_columns'])}")
else:
print(f" ✗ No mask column detected")
print(f" Expected column names: 'mask', 'segmentation', 'alpha', 'matte'")
print(f"\nPrompt:")
pi = sam_info["prompt_info"]
if pi["has_prompt"]:
print(f" ✓ Type: {pi['prompt_type']} (from {pi['source']})")
if pi.get("bbox_valid"):
bv = pi["bbox_valid"]
if bv["valid"]:
print(f" • BBox values: {bv.get('values')}")
if bv.get("format_hint"):
print(f" • Format: {bv['format_hint']}")
if bv.get("warning"):
print(f" ⚠ {bv['warning']}")
else:
print(f" ✗ Invalid bbox: {bv.get('error', 'unknown error')}")
else:
print(f" ✗ No prompt detected")
print(f" Expected: 'prompt' column (JSON with bbox/point), or 'bbox'/'point' column")
if sam_info["ready"]:
pc = sam_info["prompt_columns"][0] if sam_info["prompt_columns"] else None
args_hint = f"--prompt_type {pi['prompt_type']}"
if pc:
args_hint += f" --prompt_column_name {pc}"
print(f"\n Use with: scripts/sam_segmentation_training.py")
print(f" {args_hint}")
# Mapping code (OD only)
mapping_code = generate_mapping_code(od_info)
if mapping_code:
print(f"\n{'OD PREPROCESSING CODE':-<80}")
print(mapping_code)
elif od_info["ready"]:
print(f"\n ✓ No OD preprocessing needed.")
# --- Summary ---
print(f"\n{'SUMMARY':-<80}")
if ic_info["ready"]:
num_cls = ic_info["label_info"].get("num_classes") or ic_info["label_info"].get("sample_unique_count", "?")
print(f"✓ Image Classification: READY ({num_cls} classes)")
else:
print(f"✗ Image Classification: not compatible")
if od_info["ready"]:
ann_info = od_info["annotations_info"]
fmt = ann_info.get("primary_bbox_format", "")
cls = ann_info.get("num_classes", "?")
print(f"✓ Object Detection: READY ({cls} classes, {fmt})")
else:
print(f"✗ Object Detection: not compatible")
if sam_info["ready"]:
print(f"✓ SAM Segmentation: READY (prompt: {pi['prompt_type']})")
else:
print(f"✗ SAM Segmentation: not compatible")
print(f"\nNote: Used Datasets Server API (instant, no download required)")
print("\n" + "=" * 80)
sys.exit(0)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(0)
except Exception as e:
print(f"ERROR: {e}", file=sys.stderr)
sys.exit(1)
Requirements and compatibility
Written for: Claude Code
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Names Claude Code tools, Needs Python
Security
What our scanner noticed· Low risk
- Instructions that use the network
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Hugging Face
- Publisher
- Hugging Face (Official)
- Source
- huggingface/skills · skills/huggingface-vision-trainer · commit 25910b3
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Hugging Face.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download huggingface-vision-trainer.zip