Huggingface LLM 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
The huggingface-llm-trainer skill provides a comprehensive workflow for training and fine-tuning language and vision models on managed Hugging Face Jobs infrastructure. It supports advanced training methods including SFT, DPO, GRPO, and reward modeling. The skill handles the entire lifecycle, from dataset validation and cost estimation to job submission, real-time monitoring via Trackio, and GGUF conversion for local deployment. It is designed for users who need cloud-based GPU training without managing local infrastructure.
What it does
- Submits training jobs to Hugging Face infrastructure using the hf_jobs tool.
- Supports SFT, DPO, GRPO, and reward modeling training methods.
- Provides dataset validation to prevent common training failures.
- Integrates Trackio for real-time training metrics and monitoring.
- Converts trained models to GGUF format for local inference.
- Offers cost estimation and hardware selection guidance for optimized training.
When to use it
- When you need to fine-tune a model but lack local GPU hardware.
- When you want to use TRL or Unsloth for model alignment or instruction tuning.
- When you need to prepare a model for local deployment via GGUF.
- When you need to validate a dataset before committing to a paid training job.
Advantages
- Eliminates the need for local GPU setup or maintenance.
- Ensures reliable training with built-in dataset validation.
- Provides cost-effective hardware recommendations based on model size.
- Automates the conversion process for local model compatibility.
- Enables real-time tracking of training progress.
Usage examples
- “Fine-tune Qwen/Qwen2.5-0.5B on my dataset using SFT.”
- The agent will generate a training script, validate the dataset, and submit an hf_jobs request with the appropriate hardware flavor.
- “How much will it cost to train a 7B model for 3 epochs?”
- The agent will run the cost estimation script to provide a budget estimate and recommended hardware.
- “Convert my fine-tuned model to GGUF for Ollama.”
- The agent will trigger a conversion job using the GGUF conversion script and provide the output repository details.
- “Check the status of my training job.”
- The agent will use the hf_jobs inspect tool to retrieve and report the current status and logs of the specified job.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/huggingface/huggingface-llm-trainer/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip huggingface-llm-trainer.zip -d .agents/skills
Documentation by Hugging Face
TRL Training on Hugging Face Jobs
Overview
Train language models using TRL (Transformer Reinforcement Learning) on fully managed Hugging Face infrastructure. No local GPU setup required—models train on cloud GPUs and results are automatically saved to the Hugging Face Hub.
TRL provides multiple training methods:
SFT (Supervised Fine-Tuning) - Standard instruction tuning
DPO (Direct Preference Optimization) - Alignment from preference data
GRPO (Group Relative Policy Optimization) - Online RL training
Reward Modeling - Train reward models for RLHF
For detailed TRL method documentation:
hf_doc_search("your query", product="trl")
hf_doc_fetch("https://huggingface.co/docs/trl/sft_trainer") # SFT
hf_doc_fetch("https://huggingface.co/docs/trl/dpo_trainer") # DPO
# etc.See also: references/training_methods.md for method overviews and selection guidance
When to Use This Skill
Use this skill when users want to:
Fine-tune language models on cloud GPUs without local infrastructure
Train with TRL methods (SFT, DPO, GRPO, etc.)
Run training jobs on Hugging Face Jobs infrastructure
Convert trained models to GGUF for local deployment (Ollama, LM Studio, llama.cpp)
Ensure trained models are permanently saved to the Hub
Use modern workflows with optimized defaults
When to Use Unsloth
Use Unsloth (references/unsloth.md) instead of standard TRL when:
Limited GPU memory - Unsloth uses ~60% less VRAM
Speed matters - Unsloth is ~2x faster
Training large models (>13B) - memory efficiency is critical
Training Vision-Language Models (VLMs) - Unsloth has
FastVisionModelsupport
See references/unsloth.md for complete Unsloth documentation and scripts/unsloth_sft_example.py for a production-ready training script.
Key Directives
When assisting with training jobs:
ALWAYS use
hf_jobs()MCP tool - Submit jobs usinghf_jobs("uv", {...}), NOT bashtrl-jobscommands. Thescriptparameter accepts Python code directly. Do NOT save to local files unless the user explicitly requests it. Pass the script content as a string tohf_jobs(). If user asks to "train a model", "fine-tune", or similar requests, you MUST create the training script AND submit the job immediately usinghf_jobs().Always include Trackio - Every training script should include Trackio for real-time monitoring. Use example scripts in
scripts/as templates.Provide job details after submission - After submitting, provide job ID, monitoring URL, estimated time, and note that the user can request status checks later.
Use example scripts as templates - Reference
scripts/train_sft_example.py,scripts/train_dpo_example.py, etc. as starting points.
Local Script Execution
Repository scripts use PEP 723 inline dependencies. Run them with uv run:
uv run scripts/estimate_cost.py --help
uv run scripts/dataset_inspector.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()HF_TOKEN for Hub Push ⚠️ CRITICAL - Training environment is ephemeral, must push to Hub or ALL training results are lost
Token must have write permissions
MUST pass
secrets={"HF_TOKEN": "$HF_TOKEN"}in job config to make token available (the$HF_TOKENsyntax references your actual token value)
✅ Dataset Requirements
Dataset must exist on Hub or be loadable via
datasets.load_dataset()Format must match training method (SFT: "messages"/text/prompt-completion; DPO: chosen/rejected; GRPO: prompt-only)
ALWAYS validate unknown datasets before GPU training to prevent format failures (see Dataset Validation section below)
Size appropriate for hardware (Demo: 50-100 examples on t4-small; Production: 1K-10K+ on a10g-large/a100-large)
⚠️ Critical Settings
Timeout must exceed expected training time - Default 30min is TOO SHORT for most training. Minimum recommended: 1-2 hours. Job fails and loses all progress if timeout is exceeded.
Hub push must be enabled - Config:
push_to_hub=True,hub_model_id="username/model-name"; Job:secrets={"HF_TOKEN": "$HF_TOKEN"}
Asynchronous Job Guidelines
⚠️ IMPORTANT: Training jobs run asynchronously and can take hours
Action Required
When user requests training:
Create the training script with Trackio included (use
scripts/train_sft_example.pyas template)Submit immediately using
hf_jobs()MCP tool with script content inline - don't save to file unless user requestsReport submission with job ID, monitoring URL, and estimated time
Wait for user to request status checks - don't poll automatically
Ground Rules
Jobs run in background - Submission returns immediately; training continues independently
Initial logs delayed - Can take 30-60 seconds for logs to appear
User checks status - Wait for user to request status updates
Avoid polling - Check logs only on user request; provide monitoring links instead
After Submission
Provide to user:
✅ Job ID and monitoring URL
✅ Expected completion time
✅ Trackio dashboard URL
✅ Note that user can request status checks later
Example Response:
✅ Job submitted successfully!
Job ID: abc123xyz
Monitor: https://huggingface.co/jobs/username/abc123xyz
Expected time: ~2 hours
Estimated cost: ~$10
The job is running in the background. Ask me to check status/logs when ready!Quick Start: Three Approaches
💡 Tip for Demos: For quick demos on smaller GPUs (t4-small), omit eval_dataset and eval_strategy to save ~40% memory. You'll still see training loss and learning progress.
Sequence Length Configuration
TRL config classes use max_length (not max_seq_length) to control tokenized sequence length:
# ✅ CORRECT - If you need to set sequence length
SFTConfig(max_length=512) # Truncate sequences to 512 tokens
DPOConfig(max_length=2048) # Longer context (2048 tokens)
# ❌ WRONG - This parameter doesn't exist
SFTConfig(max_seq_length=512) # TypeError!Default behavior: max_length=1024 (truncates from right). This works well for most training.
When to override:
Longer context: Set higher (e.g.,
max_length=2048)Memory constraints: Set lower (e.g.,
max_length=512)Vision models: Set
max_length=None(prevents cutting image tokens)
Usually you don't need to set this parameter at all - the examples below use the sensible default.
Approach 1: UV Scripts (Recommended—Default Choice)
UV scripts use PEP 723 inline dependencies for clean, self-contained training. This is the primary approach for Claude Code.
hf_jobs("uv", {
"script": """
# /// script
# dependencies = ["trl>=0.12.0", "peft>=0.7.0", "trackio"]
# ///
from datasets import load_dataset
from peft import LoraConfig
from trl import SFTTrainer, SFTConfig
import trackio
dataset = load_dataset("trl-lib/Capybara", split="train")
# Create train/eval split for monitoring
dataset_split = dataset.train_test_split(test_size=0.1, seed=42)
trainer = SFTTrainer(
model="Qwen/Qwen2.5-0.5B",
train_dataset=dataset_split["train"],
eval_dataset=dataset_split["test"],
peft_config=LoraConfig(r=16, lora_alpha=32),
args=SFTConfig(
output_dir="my-model",
push_to_hub=True,
hub_model_id="username/my-model",
num_train_epochs=3,
eval_strategy="steps",
eval_steps=50,
report_to="trackio",
project="meaningful_prject_name", # project name for the training name (trackio)
run_name="meaningful_run_name", # descriptive name for the specific training run (trackio)
)
)
trainer.train()
trainer.push_to_hub()
""",
"flavor": "a10g-large",
"timeout": "2h",
"secrets": {"HF_TOKEN": "$HF_TOKEN"}
})Benefits: Direct MCP tool usage, clean code, dependencies declared inline (PEP 723), no file saving required, full control
When to use: Default choice for all training tasks in Claude Code, custom training logic, any scenario requiring hf_jobs()
Working with Scripts
⚠️ Important: The script parameter accepts either inline code (as shown above) OR a URL. Local file paths do NOT work.
Why local paths don't work: Jobs run in isolated Docker containers without access to your local filesystem. Scripts must be:
Inline code (recommended for custom training)
Publicly accessible URLs
Private repo URLs (with HF_TOKEN)
Common mistakes:
# ❌ These will all fail
hf_jobs("uv", {"script": "train.py"})
hf_jobs("uv", {"script": "./scripts/train.py"})
hf_jobs("uv", {"script": "/path/to/train.py"})Correct approaches:
# ✅ Inline code (recommended)
hf_jobs("uv", {"script": "# /// script\n# dependencies = [...]\n# ///\n\n<your code>"})
# ✅ From Hugging Face Hub
hf_jobs("uv", {"script": "https://huggingface.co/user/repo/resolve/main/train.py"})
# ✅ From GitHub
hf_jobs("uv", {"script": "https://raw.githubusercontent.com/user/repo/main/train.py"})
# ✅ From Gist
hf_jobs("uv", {"script": "https://gist.githubusercontent.com/user/id/raw/train.py"})To use local scripts: Upload to HF Hub first:
hf repos create my-training-scripts --type model
hf upload my-training-scripts ./train.py train.py
# Use: https://huggingface.co/USERNAME/my-training-scripts/resolve/main/train.pyApproach 2: TRL Maintained Scripts (Official Examples)
TRL provides battle-tested scripts for all methods. Can be run from URLs:
hf_jobs("uv", {
"script": "https://github.com/huggingface/trl/blob/main/trl/scripts/sft.py",
"script_args": [
"--model_name_or_path", "Qwen/Qwen2.5-0.5B",
"--dataset_name", "trl-lib/Capybara",
"--output_dir", "my-model",
"--push_to_hub",
"--hub_model_id", "username/my-model"
],
"flavor": "a10g-large",
"timeout": "2h",
"secrets": {"HF_TOKEN": "$HF_TOKEN"}
})Benefits: No code to write, maintained by TRL team, production-tested When to use: Standard TRL training, quick experiments, don't need custom code Available: Scripts are available from https://github.com/huggingface/trl/tree/main/examples/scripts
Finding More UV Scripts on Hub
The uv-scripts organization provides ready-to-use UV scripts stored as datasets on Hugging Face Hub:
# Discover available UV script collections
dataset_search({"author": "uv-scripts", "sort": "downloads", "limit": 20})
# Explore a specific collection
hub_repo_details(["uv-scripts/classification"], repo_type="dataset", include_readme=True)Popular collections: ocr, classification, synthetic-data, vllm, dataset-creation
Approach 3: HF Jobs CLI (Direct Terminal Commands)
When the hf_jobs() MCP tool is unavailable, use the hf jobs CLI directly.
⚠️ CRITICAL: CLI Syntax Rules
# ✅ CORRECT syntax - flags BEFORE script URL
hf jobs uv run --flavor a10g-large --timeout 2h --secrets HF_TOKEN "https://example.com/train.py"
# ❌ WRONG - "run uv" instead of "uv run"
hf jobs run uv "https://example.com/train.py" --flavor a10g-large
# ❌ WRONG - flags AFTER script URL (will be ignored!)
hf jobs uv run "https://example.com/train.py" --flavor a10g-large
# ❌ WRONG - "--secret" instead of "--secrets" (plural)
hf jobs uv run --secret HF_TOKEN "https://example.com/train.py"Key syntax rules:
Command order is
hf jobs uv run(NOThf jobs run uv)All flags (
--flavor,--timeout,--secrets) must come BEFORE the script URLUse
--secrets(plural), not--secretScript URL must be the last positional argument
Complete CLI example:
hf jobs uv run \
--flavor a10g-large \
--timeout 2h \
--secrets HF_TOKEN \
"https://huggingface.co/user/repo/resolve/main/train.py"Check job status via CLI:
hf jobs ps # List all jobs
hf jobs logs <job-id> # View logs
hf jobs inspect <job-id> # Job details
hf jobs cancel <job-id> # Cancel a jobApproach 4: TRL Jobs Package (Simplified Training)
The trl-jobs package provides optimized defaults and one-liner training.
uvx trl-jobs sft \
--model_name Qwen/Qwen2.5-0.5B \
--dataset_name trl-lib/Capybara
Benefits: Pre-configured settings, automatic Trackio integration, automatic Hub push, one-line commands When to use: User working in terminal directly (not Claude Code context), quick local experimentation Repository: https://github.com/huggingface/trl-jobs
⚠️ In Claude Code context, prefer using hf_jobs() MCP tool (Approach 1) when available.
Hardware Selection
| Model Size | Recommended Hardware | Cost (approx/hr) | Use Case |
|---|---|---|---|
| <1B params | t4-small | ~$0.75 | Demos, quick tests only without eval steps |
| 1-3B params | t4-medium, l4x1 | ~$1.50-2.50 | Development |
| 3-7B params | a10g-small, a10g-large | ~$3.50-5.00 | Production training |
| 7-13B params | a10g-large, a100-large | ~$5-10 | Large models (use LoRA) |
| 13B+ params | a100-large, a10g-largex2 | ~$10-20 | Very large (use LoRA) |
GPU Flavors: cpu-basic/upgrade/performance/xl, t4-small/medium, l4x1/x4, a10g-small/large/largex2/largex4, a100-large, h100/h100x8
Guidelines:
Use LoRA/PEFT for models >7B to reduce memory
Multi-GPU automatically handled by TRL/Accelerate
Start with smaller hardware for testing
See: references/hardware_guide.md for detailed specifications
Critical: Saving Results to Hub
⚠️ EPHEMERAL ENVIRONMENT—MUST PUSH TO HUB
The Jobs environment is temporary. All files are deleted when the job ends. If the model isn't pushed to Hub, ALL TRAINING IS LOST.
Required Configuration
In training script/config:
SFTConfig(
push_to_hub=True,
hub_model_id="username/model-name", # MUST specify
hub_strategy="every_save", # Optional: push checkpoints
)In job submission:
{
"secrets": {"HF_TOKEN": "$HF_TOKEN"} # Enables authentication
}Verification Checklist
Before submitting:
[ ]
push_to_hub=Trueset in config[ ]
hub_model_idincludes username/repo-name[ ]
secretsparameter includes HF_TOKEN[ ] User has write access to target repo
See: references/hub_saving.md for detailed troubleshooting
Timeout Management
⚠️ DEFAULT: 30 MINUTES—TOO SHORT FOR TRAINING
Setting Timeouts
{
"timeout": "2h" # 2 hours (formats: "90m", "2h", "1.5h", or seconds as integer)
}Timeout Guidelines
| Scenario | Recommended | Notes |
|---|---|---|
| Quick demo (50-100 examples) | 10-30 min | Verify setup |
| Development training | 1-2 hours | Small datasets |
| Production (3-7B model) | 4-6 hours | Full datasets |
| Large model with LoRA | 3-6 hours | Depends on dataset |
Always add 20-30% buffer for model/dataset loading, checkpoint saving, Hub push operations, and network delays.
On timeout: Job killed immediately, all unsaved progress lost, must restart from beginning
Choose a Base Model (Model Selection)
Identify models to train based on task type or benchmark results.
Use scripts/hf_benchmarks.py to identify top-performing models for specific tasks. This helps the user select a model as the base for training, whilst keeping size and hardware constraints in mind.
# Get help on the benchmarks command:
uv run scripts/hf_benchmarks.py --helpExample -- choosing an OCR base model
# Search for benchmarks containing whose name contains the text `ocr`
uv run scripts/hf_benchmarks.py search --query ocr
# Get the ranked leaderboard for the allenai/olmOCR-bench benchmark
uv run scripts/hf_benchmarks.py leaderboard allenai/olmOCR-benchCost Estimation
Offer to estimate cost when planning jobs with known parameters. Use scripts/estimate_cost.py:
uv run scripts/estimate_cost.py \
--model meta-llama/Llama-2-7b-hf \
--dataset trl-lib/Capybara \
--hardware a10g-large \
--dataset-size 16000 \
--epochs 3Output includes estimated time, cost, recommended timeout (with buffer), and optimization suggestions.
When to offer: User planning a job, asks about cost/time, choosing hardware, job will run >1 hour or cost >$5
Example Training Scripts
Production-ready templates with all best practices:
Load these scripts for correctly:
scripts/train_sft_example.py- Complete SFT training with Trackio, LoRA, checkpointsscripts/train_dpo_example.py- DPO training for preference learningscripts/train_grpo_example.py- GRPO training for online RL
These scripts demonstrate proper Hub saving, Trackio integration, checkpoint management, and optimized parameters. Pass their content inline to hf_jobs() or use as templates for custom scripts.
Monitoring and Tracking
Trackio provides real-time metrics visualization. See references/trackio_guide.md for complete setup guide.
Key points:
Add
trackioto dependenciesConfigure trainer with
report_to="trackio" and run_name="meaningful_name"
Trackio Configuration Defaults
Use sensible defaults unless user specifies otherwise. When generating training scripts with Trackio:
Default Configuration:
Space ID:
{username}/trackio(use "trackio" as default space name)Run naming: Unless otherwise specified, name the run in a way the user will recognize (e.g., descriptive of the task, model, or purpose)
Config: Keep minimal - only include hyperparameters and model/dataset info
Project Name: Use a Project Name to associate runs with a particular Project
User overrides: If user requests specific trackio configuration (custom space, run naming, grouping, or additional config), apply their preferences instead of defaults.
This is useful for managing multiple jobs with the same configuration or keeping training scripts portable.
See references/trackio_guide.md for complete documentation including grouping runs for experiments.
Check Job Status
# List all jobs
hf_jobs("ps")
# Inspect specific job
hf_jobs("inspect", {"job_id": "your-job-id"})
# View logs
hf_jobs("logs", {"job_id": "your-job-id"})Remember: Wait for user to request status checks. Avoid polling repeatedly.
Dataset Validation
Validate dataset format BEFORE launching GPU training to prevent the #1 cause of training failures: format mismatches.
Why Validate
50%+ of training failures are due to dataset format issues
DPO especially strict: requires exact column names (
prompt,chosen,rejected)Failed GPU jobs waste $1-10 and 30-60 minutes
Validation on CPU costs ~$0.01 and takes <1 minute
When to Validate
ALWAYS validate for:
Unknown or custom datasets
DPO training (CRITICAL - 90% of datasets need mapping)
Any dataset not explicitly TRL-compatible
Skip validation for known TRL datasets:
trl-lib/ultrachat_200k,trl-lib/Capybara,HuggingFaceH4/ultrachat_200k, etc.
Usage
hf_jobs("uv", {
"script": "https://huggingface.co/datasets/mcp-tools/skills/raw/main/dataset_inspector.py",
"script_args": ["--dataset", "username/dataset-name", "--split", "train"]
})The script is fast, and will usually complete synchronously.
Reading Results
The output shows compatibility for each training method:
✓ READY- Dataset is compatible, use directly✗ NEEDS MAPPING- Compatible but needs preprocessing (mapping code provided)✗ INCOMPATIBLE- Cannot be used for this method
When mapping is needed, the output includes a "MAPPING CODE" section with copy-paste ready Python code.
Example Workflow
# 1. Inspect dataset (costs ~$0.01, <1 min on CPU)
hf_jobs("uv", {
"script": "https://huggingface.co/datasets/mcp-tools/skills/raw/main/dataset_inspector.py",
"script_args": ["--dataset", "argilla/distilabel-math-preference-dpo", "--split", "train"]
})
# 2. Check output markers:
# ✓ READY → proceed with training
# ✗ NEEDS MAPPING → apply mapping code below
# ✗ INCOMPATIBLE → choose different method/dataset
# 3. If mapping needed, apply before training:
def format_for_dpo(example):
return {
'prompt': example['instruction'],
'chosen': example['chosen_response'],
'rejected': example['rejected_response'],
}
dataset = dataset.map(format_for_dpo, remove_columns=dataset.column_names)
# 4. Launch training job with confidenceCommon Scenario: DPO Format Mismatch
Most DPO datasets use non-standard column names. Example:
Dataset has: instruction, chosen_response, rejected_response
DPO expects: prompt, chosen, rejectedThe validator detects this and provides exact mapping code to fix it.
Converting Models to GGUF
After training, convert models to GGUF format for use with llama.cpp, Ollama, LM Studio, and other local inference tools.
What is GGUF:
Optimized for CPU/GPU inference with llama.cpp
Supports quantization (4-bit, 5-bit, 8-bit) to reduce model size
Compatible with Ollama, LM Studio, Jan, GPT4All, llama.cpp
Typically 2-8GB for 7B models (vs 14GB unquantized)
When to convert:
Running models locally with Ollama or LM Studio
Reducing model size with quantization
Deploying to edge devices
Sharing models for local-first use
See: references/gguf_conversion.md for complete conversion guide, including production-ready conversion script, quantization options, hardware requirements, usage examples, and troubleshooting.
Quick conversion:
hf_jobs("uv", {
"script": "<see references/gguf_conversion.md for complete script>",
"flavor": "a10g-large",
"timeout": "45m",
"secrets": {"HF_TOKEN": "$HF_TOKEN"},
"env": {
"ADAPTER_MODEL": "username/my-finetuned-model",
"BASE_MODEL": "Qwen/Qwen2.5-0.5B",
"OUTPUT_REPO": "username/my-model-gguf"
}
})Common Training Patterns
See references/training_patterns.md for detailed examples including:
Quick demo (5-10 minutes)
Production with checkpoints
Multi-GPU training
DPO training (preference learning)
GRPO training (online RL)
Common Failure Modes
Out of Memory (OOM)
Fix (try in order):
Reduce batch size:
per_device_train_batch_size=1, increasegradient_accumulation_steps=8. Effective batch size isper_device_train_batch_sizexgradient_accumulation_steps. For best performance keep effective batch size close to 128.Enable:
gradient_checkpointing=TrueUpgrade hardware: t4-small → l4x1, a10g-small → a10g-large etc.
Dataset Misformatted
Fix:
Validate first with dataset inspector:
uv run https://huggingface.co/datasets/mcp-tools/skills/raw/main/dataset_inspector.py \ --dataset name --split trainCheck output for compatibility markers (✓ READY, ✗ NEEDS MAPPING, ✗ INCOMPATIBLE)
Apply mapping code from inspector output if needed
Job Timeout
Fix:
Check logs for actual runtime:
hf_jobs("logs", {"job_id": "..."})Increase timeout with buffer:
"timeout": "3h"(add 30% to estimated time)Or reduce training: lower
num_train_epochs, use smaller dataset, enablemax_stepsSave checkpoints:
save_strategy="steps",save_steps=500,hub_strategy="every_save"
Note: Default 30min is insufficient for real training. Minimum 1-2 hours.
Hub Push Failures
Fix:
Add to job:
secrets={"HF_TOKEN": "$HF_TOKEN"}Add to config:
push_to_hub=True,hub_model_id="username/model-name"Verify auth:
mcp__huggingface__hf_whoami()Check token has write permissions and repo exists (or set
hub_private_repo=True)
Missing Dependencies
Fix: Add to PEP 723 header:
# /// script
# dependencies = ["trl>=0.12.0", "peft>=0.7.0", "trackio", "missing-package"]
# ///Troubleshooting
Common issues:
Job times out → Increase timeout, reduce epochs/dataset, use smaller model/LoRA
Model not saved to Hub → Check push_to_hub=True, hub_model_id, secrets=HF_TOKEN
Out of Memory (OOM) → Reduce batch size, increase gradient accumulation, enable LoRA, use larger GPU
Dataset format error → Validate with dataset inspector (see Dataset Validation section)
Import/module errors → Add PEP 723 header with dependencies, verify format
Authentication errors → Check
mcp__huggingface__hf_whoami(), token permissions, secrets parameter
See: references/troubleshooting.md for complete troubleshooting guide
Resources
References (In This Skill)
references/training_methods.md- Overview of SFT, DPO, GRPO, KTO, PPO, Reward Modelingreferences/training_patterns.md- Common training patterns and examplesreferences/unsloth.md- Unsloth for fast VLM training (~2x speed, 60% less VRAM)references/gguf_conversion.md- Complete GGUF conversion guidereferences/trackio_guide.md- Trackio monitoring setupreferences/hardware_guide.md- Hardware specs and selectionreferences/hub_saving.md- Hub authentication troubleshootingreferences/troubleshooting.md- Common issues and solutionsreferences/local_training_macos.md- Local training on macOS
Scripts (In This Skill)
scripts/train_sft_example.py- Production SFT templatescripts/train_dpo_example.py- Production DPO templatescripts/train_grpo_example.py- Production GRPO templatescripts/unsloth_sft_example.py- Unsloth text LLM training template (faster, less VRAM)scripts/estimate_cost.py- Estimate time and cost (offer when appropriate)scripts/convert_to_gguf.py- Complete GGUF conversion scriptscripts/hf_benchmarks.py- Search for benchmark results and leaderboards by task, alias or free text.
External Scripts
Dataset Inspector - Validate dataset format before training (use via
uv runorhf_jobs)
External Links
Key Takeaways
Submit scripts inline - The
scriptparameter accepts Python code directly; no file saving required unless user requestsJobs are asynchronous - Don't wait/poll; let user check when ready
Always set timeout - Default 30 min is insufficient; minimum 1-2 hours recommended
Always enable Hub push - Environment is ephemeral; without push, all results lost
Include Trackio - Use example scripts as templates for real-time monitoring
Offer cost estimation - When parameters are known, use
scripts/estimate_cost.pyUse UV scripts (Approach 1) - Default to
hf_jobs("uv", {...})with inline scripts; TRL maintained scripts for standard training; avoid bashtrl-jobscommands in Claude CodeUse hf_doc_fetch/hf_doc_search for latest TRL documentation
Validate dataset format before training with dataset inspector (see Dataset Validation section)
Choose appropriate hardware for model size; use LoRA for models >7B
Files
- ATTRIBUTION.mdAdded by AutoGineer890 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md28.1 KiB
- references/gguf_conversion.md9.6 KiB
- references/hardware_guide.md6.6 KiB
- references/hub_saving.md8.3 KiB
- references/local_training_macos.md8.1 KiB
- references/reliability_principles.md10.6 KiB
- references/trackio_guide.md6.3 KiB
- references/training_methods.md4.9 KiB
- references/training_patterns.md6.0 KiB
- references/troubleshooting.md8.7 KiB
- references/unsloth.md7.8 KiB
- scripts/convert_to_gguf.pyScript12.3 KiB
- scripts/dataset_inspector.pyScript15.3 KiB
- scripts/estimate_cost.pyScript4.7 KiB
- scripts/hf_benchmarks.pyScript19.6 KiB
- scripts/train_dpo_example.pyScript3.0 KiB
- scripts/train_grpo_example.pyScript2.3 KiB
- scripts/train_sft_example.pyScript3.3 KiB
- scripts/unsloth_sft_example.pyScript16.5 KiB
scripts/hf_benchmarks.py
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10"
# dependencies = []
# ///
"""
Search Hugging Face benchmark datasets and fetch leaderboard results.
This script is designed to be pipeline-friendly:
- search benchmark datasets by free text, alias, task, and modality
- fetch dataset leaderboards in normalized JSON / NDJSON / table form
- optionally read dataset ids from stdin for chaining
It uses HF_TOKEN automatically when present.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import sys
import textwrap
import urllib.error
import urllib.parse
import urllib.request
from typing import Any, Iterable
BASE_URL = "https://huggingface.co"
DEFAULT_TIMEOUT = 30
ALIASES: dict[str, list[str]] = {
"ocr": [
"ocr",
"olmocr",
"pdf",
"image-to-text",
"screen",
"screenspot",
"markdown",
"text recognition",
],
"coding": [
"code",
"coding",
"software engineering",
"programming",
"swe",
"terminal",
"patch",
"bug",
"cuda",
],
"math": [
"math",
"reasoning",
"gsm8k",
"mmlu",
"gpqa",
"aime",
"hmmt",
],
"retrieval": [
"retrieval",
"search",
"mteb",
"arguana",
"bright",
],
"agents": [
"agent",
"agents",
"terminal",
"screen",
"computer use",
"tool use",
],
"asr": [
"asr",
"speech",
"audio",
"transcribe",
"transcription",
],
}
class HfApiError(RuntimeError):
pass
class FullHelpArgumentParser(argparse.ArgumentParser):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._search_parser: argparse.ArgumentParser | None = None
self._leaderboard_parser: argparse.ArgumentParser | None = None
def format_help(self) -> str:
text = super().format_help()
extra_sections: list[str] = []
if self._search_parser is not None:
extra_sections.append(
"\nsearch command options:\n"
+ textwrap.indent(self._search_parser.format_help().strip(), " ")
)
if self._leaderboard_parser is not None:
extra_sections.append(
"\nleaderboard command options:\n"
+ textwrap.indent(self._leaderboard_parser.format_help().strip(), " ")
)
if extra_sections:
text += "\n" + "\n".join(extra_sections) + "\n"
return text
def auth_headers() -> dict[str, str]:
token = os.getenv("HF_TOKEN")
return {"Authorization": f"Bearer {token}"} if token else {}
def http_get_json(path: str, params: dict[str, Any] | None = None) -> Any:
url = f"{BASE_URL}{path}"
if params:
pairs: list[tuple[str, str]] = []
for key, value in params.items():
if value is None:
continue
if isinstance(value, (list, tuple)):
for item in value:
pairs.append((key, str(item)))
else:
pairs.append((key, str(value)))
if pairs:
url = f"{url}?{urllib.parse.urlencode(pairs)}"
req = urllib.request.Request(url, headers=auth_headers())
try:
with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT) as resp:
return json.loads(resp.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
body = exc.read().decode("utf-8", errors="replace")
raise HfApiError(f"{exc.code} {exc.reason} for {url}: {body[:500]}") from exc
except urllib.error.URLError as exc:
raise HfApiError(f"Request failed for {url}: {exc}") from exc
def shorten(text: str, width: int) -> str:
text = " ".join((text or "").split())
if len(text) <= width:
return text
return text[: max(0, width - 1)] + "…"
def first_text(value: Any) -> str:
if value is None:
return ""
if isinstance(value, str):
return value
if isinstance(value, list):
return " ".join(first_text(v) for v in value)
if isinstance(value, dict):
return " ".join(first_text(v) for v in value.values())
return str(value)
def benchmark_catalog(limit: int = 500) -> list[dict[str, Any]]:
data = http_get_json(
"/api/datasets",
params={"filter": "benchmark:official", "limit": limit, "full": "true"},
)
if not isinstance(data, list):
raise HfApiError("Unexpected response while listing benchmark datasets")
return data
def dataset_search_blob(dataset: dict[str, Any]) -> str:
card = dataset.get("cardData") or {}
parts = [
dataset.get("id", ""),
dataset.get("description", ""),
first_text(dataset.get("tags")),
first_text(card.get("pretty_name")),
first_text(card.get("tags")),
first_text(card.get("task_categories")),
first_text(card.get("task_ids")),
]
return " ".join(parts).lower()
def dataset_search_fields(dataset: dict[str, Any]) -> dict[str, str]:
card = dataset.get("cardData") or {}
return {
"id": first_text(dataset.get("id")).lower(),
"pretty_name": first_text(card.get("pretty_name")).lower(),
"tags": " ".join(
[
first_text(dataset.get("tags")),
first_text(card.get("tags")),
first_text(card.get("task_categories")),
first_text(card.get("task_ids")),
first_text(card.get("modality")),
]
).lower(),
"description": first_text(dataset.get("description")).lower(),
}
def collect_prefixed_tags(dataset: dict[str, Any], prefixes: Iterable[str]) -> list[str]:
prefixes = tuple(prefixes)
tags = dataset.get("tags") or []
card = dataset.get("cardData") or {}
out: list[str] = []
for tag in tags:
if isinstance(tag, str) and tag.startswith(prefixes):
out.append(tag)
for key, prefix in (
("task_categories", "task_categories:"),
("task_ids", "task_ids:"),
("modality", "modality:"),
):
values = card.get(key)
if isinstance(values, list):
for value in values:
full_tag = f"{prefix}{value}"
if full_tag.startswith(prefixes):
out.append(full_tag)
deduped: list[str] = []
seen: set[str] = set()
for tag in out:
if tag not in seen:
deduped.append(tag)
seen.add(tag)
return deduped
def expand_aliases(aliases: list[str]) -> dict[str, list[str]]:
expanded: dict[str, list[str]] = {}
for alias in aliases:
terms = ALIASES.get(alias.lower(), [alias])
expanded[alias] = terms
return expanded
def matches_term(blob: str, term: str) -> bool:
candidate = term.lower().strip()
if not candidate:
return False
if re.fullmatch(r"[a-z0-9_]+", candidate):
return re.search(rf"(?<![a-z0-9_]){re.escape(candidate)}(?![a-z0-9_])", blob) is not None
return candidate in blob
def score_dataset(
dataset: dict[str, Any],
queries: list[str],
aliases: dict[str, list[str]],
tasks: list[str],
modalities: list[str],
) -> dict[str, Any]:
blob = dataset_search_blob(dataset)
fields = dataset_search_fields(dataset)
task_tags = collect_prefixed_tags(dataset, ["task_categories:", "task_ids:"])
modality_tags = collect_prefixed_tags(dataset, ["modality:"])
score = 0
reasons: list[str] = []
for query in queries:
q = query.lower().strip()
if q and any(matches_term(value, q) for value in fields.values()):
score += 3
reasons.append(f"query:{query}")
for alias_name, terms in aliases.items():
matched_terms: list[str] = []
alias_score = 0
for term in terms:
strong_match = any(
matches_term(fields[field_name], term)
for field_name in ("id", "pretty_name", "tags")
)
desc_match = matches_term(fields["description"], term)
if strong_match:
alias_score += 2
matched_terms.append(term)
elif desc_match:
alias_score += 1
matched_terms.append(term)
if matched_terms:
score += alias_score
reasons.append(f"alias:{alias_name}=" + ",".join(matched_terms[:5]))
lower_task_tags = [t.lower() for t in task_tags]
for task in tasks:
task = task.lower().strip()
if not task:
continue
exact = [
tag
for tag in lower_task_tags
if tag == f"task_categories:{task}" or tag == f"task_ids:{task}"
]
fuzzy = matches_term(blob, task)
if exact:
score += 5
reasons.append(f"task:{task}")
elif fuzzy:
score += 2
reasons.append(f"task~:{task}")
lower_modality_tags = [m.lower() for m in modality_tags]
for modality in modalities:
modality = modality.lower().strip()
if not modality:
continue
if f"modality:{modality}" in lower_modality_tags:
score += 4
reasons.append(f"modality:{modality}")
return {
"dataset_id": dataset.get("id"),
"score": score,
"reasons": reasons,
"task_tags": task_tags,
"modality_tags": modality_tags,
"benchmark_tags": collect_prefixed_tags(dataset, ["benchmark:"]),
"pretty_name": (dataset.get("cardData") or {}).get("pretty_name"),
"downloads": dataset.get("downloads"),
"description": " ".join((dataset.get("description") or "").split()),
}
def search_benchmarks(
queries: list[str],
aliases: list[str],
tasks: list[str],
modalities: list[str],
limit: int,
) -> list[dict[str, Any]]:
datasets = benchmark_catalog(limit=500)
alias_map = expand_aliases(aliases)
results = [score_dataset(ds, queries, alias_map, tasks, modalities) for ds in datasets]
active_filters = bool(queries or aliases or tasks or modalities)
if active_filters:
results = [row for row in results if row["score"] >= 2]
results.sort(
key=lambda row: (
-row["score"],
-(row["downloads"] or 0),
row["dataset_id"] or "",
)
)
return results[:limit]
def parse_repo_id(repo_id: str) -> tuple[str, str]:
if "/" not in repo_id:
raise ValueError(f"Expected <namespace>/<repo>, got: {repo_id}")
namespace, repo = repo_id.split("/", 1)
return namespace, repo
def get_leaderboard(repo_id: str, task_id: str | None = None) -> list[dict[str, Any]]:
namespace, repo = parse_repo_id(repo_id)
params = {"task_id": task_id} if task_id else None
data = http_get_json(f"/api/datasets/{namespace}/{repo}/leaderboard", params=params)
if not isinstance(data, list):
raise HfApiError(f"Unexpected leaderboard response for {repo_id}")
normalized: list[dict[str, Any]] = []
for row in data:
source = row.get("source") or {}
normalized.append(
{
"dataset_id": repo_id,
"task_id": task_id,
"rank": row.get("rank"),
"model_id": row.get("modelId"),
"value": row.get("value"),
"verified": row.get("verified"),
"lower_is_better": row.get("lower_is_better"),
"filename": row.get("filename"),
"notes": row.get("notes"),
"pull_request": row.get("pullRequest"),
"source_name": source.get("name"),
"source_url": source.get("url"),
"source_is_external": source.get("isExternal"),
}
)
return normalized
def read_repo_ids_from_stdin() -> list[str]:
if sys.stdin.isatty():
return []
repo_ids: list[str] = []
for raw_line in sys.stdin:
line = raw_line.strip()
if not line:
continue
if line.startswith("{"):
try:
obj = json.loads(line)
except json.JSONDecodeError:
continue
candidate = obj.get("dataset_id") or obj.get("id")
if isinstance(candidate, str) and "/" in candidate:
repo_ids.append(candidate)
continue
if "/" in line:
repo_ids.append(line)
return repo_ids
def print_json(data: Any) -> None:
json.dump(data, sys.stdout, indent=2, ensure_ascii=False)
sys.stdout.write("\n")
def print_ndjson(rows: list[dict[str, Any]]) -> None:
for row in rows:
sys.stdout.write(json.dumps(row, ensure_ascii=False) + "\n")
def print_search_table(rows: list[dict[str, Any]]) -> None:
if not rows:
print("No benchmark datasets matched.")
return
headers = ["dataset_id", "score", "modalities", "tasks", "reasons", "description"]
widths = [34, 5, 18, 24, 30, 68]
print(" ".join(h.ljust(w) for h, w in zip(headers, widths)))
print(" ".join("-" * w for w in widths))
for row in rows:
values = [
shorten(row.get("dataset_id") or "", widths[0]),
str(row.get("score", "")),
shorten(", ".join(row.get("modality_tags") or []), widths[2]),
shorten(", ".join(row.get("task_tags") or []), widths[3]),
shorten(", ".join(row.get("reasons") or []), widths[4]),
shorten(row.get("description") or "", widths[5]),
]
print(" ".join(v.ljust(w) for v, w in zip(values, widths)))
def print_leaderboard_table(rows: list[dict[str, Any]]) -> None:
if not rows:
print("No leaderboard rows returned.")
return
headers = ["dataset_id", "rank", "model_id", "value", "verified", "source"]
widths = [30, 5, 38, 10, 8, 28]
print(" ".join(h.ljust(w) for h, w in zip(headers, widths)))
print(" ".join("-" * w for w in widths))
for row in rows:
values = [
shorten(str(row.get("dataset_id") or ""), widths[0]),
str(row.get("rank") or ""),
shorten(str(row.get("model_id") or ""), widths[2]),
shorten(str(row.get("value") or ""), widths[3]),
str(row.get("verified")),
shorten(str(row.get("source_name") or ""), widths[5]),
]
print(" ".join(v.ljust(w) for v, w in zip(values, widths)))
def build_parser() -> argparse.ArgumentParser:
parser = FullHelpArgumentParser(
prog="hf_benchmarks.py",
formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent(
"""
Search benchmark datasets and fetch leaderboard results from the Hugging Face Hub.
Workflow ideas:
1) Discover candidate benchmarks:
hf_benchmarks.py search --alias ocr
hf_benchmarks.py search --alias coding
hf_benchmarks.py search --task image-to-text --modality document
2) Inspect a leaderboard:
hf_benchmarks.py leaderboard allenai/olmOCR-bench --top 10
3) Chain search -> leaderboard:
hf_benchmarks.py search --alias coding --format ndjson \\
| hf_benchmarks.py leaderboard --stdin --top 5 --format table
"""
),
)
subparsers = parser.add_subparsers(dest="command", required=True)
search_parser = subparsers.add_parser(
"search",
help="Search benchmark datasets by query, alias, task, and modality",
)
search_parser.add_argument(
"--query",
action="append",
default=[],
help="Free-text query to match against benchmark dataset metadata. Repeatable.",
)
search_parser.add_argument(
"--alias",
action="append",
default=[],
help=(
"Convenience alias for common benchmark domains. Known aliases: "
+ ", ".join(sorted(ALIASES))
+ ". Repeatable."
),
)
search_parser.add_argument(
"--task",
action="append",
default=[],
help="Task to match, e.g. text-generation, image-to-text, question-answering. Repeatable.",
)
search_parser.add_argument(
"--modality",
action="append",
default=[],
help="Modality to match, e.g. text, image, document, audio. Repeatable.",
)
search_parser.add_argument(
"--limit",
type=int,
default=20,
help="Maximum number of rows to print (default: 20).",
)
search_parser.add_argument(
"--format",
choices=["table", "json", "ndjson"],
default="table",
help="Output format (default: table).",
)
leaderboard_parser = subparsers.add_parser(
"leaderboard",
help="Fetch normalized leaderboard rows for one or more benchmark datasets",
)
leaderboard_parser.add_argument(
"datasets",
nargs="*",
help="Dataset repo ids (<namespace>/<repo>). Can also be supplied via stdin with --stdin.",
)
leaderboard_parser.add_argument(
"--stdin",
action="store_true",
help="Read dataset ids from stdin. Accepts plain repo ids or NDJSON with dataset_id/id fields.",
)
leaderboard_parser.add_argument(
"--task-id",
default=None,
help="Optional leaderboard task_id query parameter.",
)
leaderboard_parser.add_argument(
"--top",
type=int,
default=None,
help="Only keep the top N results per leaderboard.",
)
leaderboard_parser.add_argument(
"--format",
choices=["table", "json", "ndjson"],
default="table",
help="Output format (default: table).",
)
parser._search_parser = search_parser
parser._leaderboard_parser = leaderboard_parser
return parser
def run_search(args: argparse.Namespace) -> int:
rows = search_benchmarks(
queries=args.query,
aliases=args.alias,
tasks=args.task,
modalities=args.modality,
limit=args.limit,
)
if args.format == "json":
print_json(rows)
elif args.format == "ndjson":
print_ndjson(rows)
else:
print_search_table(rows)
return 0
def run_leaderboard(args: argparse.Namespace) -> int:
repo_ids = list(args.datasets)
if args.stdin:
repo_ids.extend(read_repo_ids_from_stdin())
deduped: list[str] = []
seen: set[str] = set()
for repo_id in repo_ids:
if repo_id not in seen:
deduped.append(repo_id)
seen.add(repo_id)
repo_ids = deduped
if not repo_ids:
print("Error: provide dataset ids or use --stdin.", file=sys.stderr)
return 2
rows: list[dict[str, Any]] = []
for repo_id in repo_ids:
dataset_rows = get_leaderboard(repo_id, task_id=args.task_id)
if args.top is not None:
dataset_rows = dataset_rows[: args.top]
rows.extend(dataset_rows)
if args.format == "json":
print_json(rows)
elif args.format == "ndjson":
print_ndjson(rows)
else:
print_leaderboard_table(rows)
return 0
def main() -> int:
parser = build_parser()
args = parser.parse_args()
try:
if args.command == "search":
return run_search(args)
if args.command == "leaderboard":
return run_leaderboard(args)
parser.error(f"Unknown command: {args.command}")
return 2
except HfApiError as exc:
print(f"Error: {exc}", file=sys.stderr)
return 1
except ValueError as exc:
print(f"Error: {exc}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an MCP server, 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-llm-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 or Hugging Face.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download huggingface-llm-trainer.zip