Skip to main content
ClaudeWave
Skill490 repo starsupdated 3d ago

huggingface-vision-trainer

Train object-detection, image-classification, or SAM segmentation models on Hugging Face Jobs. Use for vision fine-tuning and evaluation; use huggingface-llm-trainer for language models.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/waybarrios/opencode-power-pack /tmp/huggingface-vision-trainer && cp -r /tmp/huggingface-vision-trainer/skills/huggingface-vision-trainer ~/.claude/skills/huggingface-vision-trainer
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

# 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. For text/language model fine-tuning (SFT/DPO/GRPO via TRL), use this pack's `huggingface-llm-trainer` skill instead.

## When to Use

Fine-tuning object detection models (D-FINE, RT-DETR v2, DETR, YOLOS), image classification models (any `timm/` model or Transformers classifier), or SAM/SAM2 segmentation models (bbox or point prompts) on custom datasets — locally or on Hugging Face Jobs.

## Local Script Execution

Helper scripts use PEP 723 inline dependencies:
```bash
uv run scripts/dataset_inspector.py --dataset username/dataset-name --split train
uv run scripts/estimate_cost.py --help
```

## Prerequisites Checklist

- Hugging Face account with Pro/Team/Enterprise plan (Jobs require a paid plan). Authenticated login (`hf auth whoami`), token with write permissions passed in job secrets.
- **Object detection**: dataset on the Hub with an `objects` column (`bbox`, `category`, optional `area`). Bboxes in xywh (COCO) or xyxy (Pascal VOC) — auto-detected/converted. Categories can be integers or strings (auto-remapped). `image_id` optional, auto-generated.
- **Image classification**: an `image` column (PIL images) and a `label` column (integer or string class IDs, `ClassLabel` or plain — auto-remapped). Common alt names (`labels`, `class`, `fine_label`) auto-detected.
- **SAM/SAM2 segmentation**: an `image` column, a `mask` column (binary ground-truth mask), and a prompt — either a `prompt` column with JSON (`{"bbox": [...]}` or `{"point": [...]}`), or dedicated `bbox`/`point` columns (xyxy, absolute pixels). Example dataset: `merve/MicroMat-mini`.
- **Always validate unknown datasets first** (see Dataset Validation below).
- Timeout must exceed expected training time — default 30min is too short, use 2-4h minimum for vision training.
- Hub push enabled: `push_to_hub=True`, `hub_model_id="username/model-name"`, token in `secrets`.

## Dataset Validation

Validate BEFORE launching GPU training — the #1 cause of training failures is format mismatches. Skip only for well-known defaults (e.g. `cppe-5`). Run via Jobs (avoids local SSL/dependency issues), locally with `uv run scripts/dataset_inspector.py --dataset ... --split train`, or via `HfApi().run_uv_job(script="scripts/dataset_inspector.py", script_args=[...], flavor="cpu-basic", timeout=300)`. Output markers: `✓ READY` or `✗ NEEDS FORMATTING` (with mapping code).

The object detection training script auto-handles bbox format detection/conversion, sanitization, `image_id` generation, and category remapping — no manual preprocessing needed beyond having `objects.bbox`/`objects.category`.

## Training Workflow

1. Verify prerequisites (account, token, dataset).
2. Validate dataset format with the inspector, before spending GPU time.
3. Ask the user about dataset size (quick 10% test vs. full) and whether to create a validation split, and which GPU hardware to use — present as explicit options rather than assuming.
4. Prepare the training script: `scripts/object_detection_training.py` (OD), `scripts/image_classification_training.py` (IC), or `scripts/sam_segmentation_training.py` (SAM). All use `HfArgumentParser` — configure via CLI-style `script_args`, not by editing Python variables. See `references/timm_trainer.md` for timm details and `references/finetune_sam2_trainer.md` for SAM2 details.
5. Save the script to `submitted_jobs/<dataset>_<timestamp>.py`, submit the job, and report the job ID, monitoring URL, Trackio dashboard (`https://huggingface.co/spaces/{username}/trackio`), expected time, and estimated cost. Wait for the user to request status checks — don't poll; jobs are asynchronous and can take hours.

## Job Submission

Submit via the `hf jobs uv run` CLI, an `hf_jobs()` MCP tool if the Hugging Face MCP server is configured, or the Python API directly:

```python
from huggingface_hub import HfApi, get_token
api = HfApi()
job_info = api.run_uv_job(
    script="scripts/object_detection_training.py",  # file PATH, not inline content, for the Python API
    script_args=["--dataset_name", "cppe-5", "--push_to_hub", "--hub_model_id", "username/model-name", ...],
    flavor="a10g-large",
    timeout=14400,  # seconds
    env={"PYTHONUNBUFFERED": "1"},
    secrets={"HF_TOKEN": get_token()},  # use get_token(), not the literal string "$HF_TOKEN"
)
print(f"Job ID: {job_info.id}")  # .id, not .job_id or .name
```

If using an MCP `hf_jobs()` tool instead, the `script` parameter accepts inline code or a URL (not local paths), timeout is a string (`"4h"`), and secrets use the literal `"$HF_TOKEN"` placeholder (auto-replaced) rather than `get_token()`. Either way, the training script must include PEP 723 inline dependency metadata and must NOT use `image`/`command` parameters (those belong to a different job type).

**Token injection is required in custom scripts**: the Transformers `Trainer` calls `create_repo(token=self.args.hub_token)` when `push_to_hub=True`, so the script must set `training_args.hub_token` from `os.environ.get("HF_TOKEN")` after parsing args but before constructing `Trainer` — `scripts/object_detection_training.py` already does this; replicate it in custom scripts. Don't call `login()` unless replicating that same pattern, and don't rely on implicit token resolution.

### Required flags per modality

**Object detection**: `--no_remove_unused_columns` (preserves the image column), `--no_eval_do_concat_batches` (variable box counts per image), `--push_to_hub`, `--hub_model_id`, `--metric_for_best_model eval_map`, `--greater_is_better True` (must be explicit — it's `Optional[bool]`), `--do_train`, `--do_eval`.

**Image classification**: `--no_remove_unused_columns`, `--push_to_hub`, `--hub_model_id`, `--metric_for_best_model eval_accuracy`, `--greater_is_better True`, `--do_train`, `--do_eval
agents-md-improverSkill

Audit and improve project-rules files (AGENTS.md, CLAUDE.md, .agents/instructions, local overrides) so the agent keeps accurate project context. Use when the user asks to check, audit, review, update, improve, or fix their AGENTS.md or CLAUDE.md, mentions "project rules maintenance" or "agent context optimization", or when the codebase has changed enough that the rules file may be stale. Scans the repository for every rules file, grades each against a quality rubric, outputs a quality report, and applies targeted edits only after user approval.

agents-md-reviseSkill

Capture learnings from the current session into the project-rules file (AGENTS.md, CLAUDE.md, or local override) so future sessions benefit. Use when the user says "revise the rules", "update AGENTS.md / CLAUDE.md with what we just learned", "save this to project memory", "remember this for next time", or at the end of a productive session when valuable context has emerged that is not yet documented. This complements agents-md-improver — improver audits, while this one captures.

code-architectSkill

Design a feature architecture by analyzing existing codebase patterns and conventions, then provide a comprehensive implementation blueprint with specific files to create or modify, component designs, data flows, and a build sequence. Use this skill when the user asks for an architecture design, an implementation plan for a non-trivial feature, or when dispatched as a sub-task during feature-dev architecture phase.

code-explorerSkill

Deeply analyze an existing codebase feature by tracing execution paths, mapping architecture layers, understanding patterns and abstractions, and documenting dependencies. Use this skill when you need to understand how a feature works before modifying or extending it, when dispatched as a sub-task during feature-dev exploration, or when the user asks "how does X work in this codebase".

code-reviewSkill

Review a pull request or a set of code changes for bugs, logic errors, and project-convention violations using a confidence-filtered, multi-agent process. Use this skill when the user asks to review a PR, audit pending changes, or inspect a diff for problems before merging.

code-reviewerSkill

Review code for bugs, logic errors, security vulnerabilities, code quality issues, and adherence to project conventions, using confidence-based filtering to report only high-priority issues that truly matter. Use this skill when reviewing a small set of changes locally (such as unstaged diff), when dispatched as a sub-task during feature-dev quality review, or when the user wants a critique of a specific file or function.

feature-devSkill

Guide a feature implementation through a structured seven-phase workflow with deep codebase understanding, clarifying questions, parallel architecture design, and quality review. Use this skill when the user asks to build a new feature, add functionality, or wants a methodical approach to implementation rather than diving straight to code.

frontend-designSkill

Create distinctive, production-grade frontend interfaces with high design quality and accessible markup. Use this skill when the user asks to build or beautify web components, pages, applications, landing pages, dashboards, artifacts, or React/HTML/CSS UI. Generates creative, polished code that avoids generic AI aesthetics, then self-checks it against an objective accessibility and quality rubric.