hung-phan/ml-skills/tune

Claude Code and agent skill by hung-phan/ml-skills

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Distributed hyperparameter tuning with search algorithms and early stopping. Covers Tuner API, search spaces, Optuna/HyperOpt, ASHA/PBT schedulers, and Ray Train integration. Use when tuning learning rate, architecture, or any hyperparameters across many trials in parallel.

Install

npx vskill@latest install hung-phan/ml-skills/tune

SKILL.md

The same SKILL.md was published earlier as hung-phan/ml-skills/tune.

Ray Tune

  • Docs: https://docs.ray.io/en/latest/tune/index.html
  • API: https://docs.ray.io/en/latest/tune/api/doc/ray.tune.Tuner.html
  • Examples: https://docs.ray.io/en/latest/tune/examples/index.html

Why This Exists

Problem: Manual hyperparameter search is sequential and wasteful — running 50 trials one-at-a-time burns days of GPU time, and naive grid search scales exponentially while ignoring promising regions of the search space.

Key insight: Ray Tune parallelizes trials across a cluster and applies early-stopping schedulers (ASHA) or intelligent search algorithms (Optuna/TPE) to kill bad trials fast and concentrate compute on the most promising configurations.

Reach for this when: You have more than ~10 hyperparameters to explore, training runs take longer than a few minutes (making early stopping worthwhile), or you want Optuna/HyperOpt search algorithms with distributed parallelism — prefer it over Optuna standalone once you need multi-GPU or multi-node trials.

Core API

python
from ray import tune
from ray.tune import TuneConfig, RunConfig
tuner = tune.Tuner(
trainable, # function or class
param_space={"lr": tune.loguniform(1e-5, 1e-1)},
tune_config=TuneConfig(
metric="val_loss",
mode="min",
num_samples=50, # total trials
search_alg=..., # optional
scheduler=..., # optional
),
run_config=RunConfig(
storage_path="s3://bucket/tune-results",
name="my-experiment",
),
)
results = tuner.fit()
best = results.get_best_result(metric="val_loss", mode="min")
print(best.config) # best hyperparameters

Search Space

FunctionUse CaseExample
tune.uniform(lo, hi)Float rangetune.uniform(0.0, 1.0)
tune.loguniform(lo, hi)Log-scale float (learning rate)tune.loguniform(1e-5, 1e-1)
tune.randint(lo, hi)Integer [lo, hi)tune.randint(16, 256)
tune.choice(list)Categoricaltune.choice(["adam", "sgd"])
tune.grid_search(list)Exhaustivetune.grid_search([32, 64, 128])
tune.quniform(lo, hi, q)Quantized floattune.quniform(0.1, 1.0, 0.1)
tune.sample_from(fn)Customtune.sample_from(lambda _: 2**np.random.randint(4,8))

Example: PyTorch + ASHA Early Stopping

python
from ray import tune
from ray.tune.schedulers import ASHAScheduler
from ray.tune import Checkpoint
import tempfile, torch
def train_mnist(config):
model = build_model(config["hidden"], config["dropout"])
optimizer = torch.optim.Adam(model.parameters(), lr=config["lr"])
for epoch in range(100):
loss = train_epoch(model, optimizer)
val_acc = evaluate(model)
# Save checkpoint
with tempfile.TemporaryDirectory() as tmp:
torch.save(model.state_dict(), f"{tmp}/model.pt")
tune.report(
{"val_acc": val_acc, "loss": loss},
checkpoint=Checkpoint.from_directory(tmp),
)
tuner = tune.Tuner(
train_mnist,
param_space={
"lr": tune.loguniform(1e-4, 1e-1),
"hidden": tune.choice([64, 128, 256]),
"dropout": tune.uniform(0.1, 0.5),
},
tune_config=tune.TuneConfig(
metric="val_acc",
mode="max",
num_samples=50,
scheduler=ASHAScheduler(
max_t=100, # max epochs
grace_period=10, # min epochs before stopping
reduction_factor=2, # halve trials at each rung
),
),
)
results = tuner.fit()

Schedulers

SchedulerBest ForKey Idea
ASHALarge search, limited budgetAggressively kills bad trials early
PBTLong training (LLM fine-tuning)Mutates hyperparams mid-training from top performers
MedianStoppingConservative early stoppingStops below-median trials
BOHBBayesian + bandingCombines TPE search with HyperBand scheduling
PBT (Population-Based Training)
python
from ray.tune.schedulers import PopulationBasedTraining
pbt = PopulationBasedTraining(
time_attr="training_iteration",
perturbation_interval=5, # every 5 iterations
hyperparam_mutations={
"lr": tune.loguniform(1e-5, 1e-2),
"weight_decay": tune.uniform(0.0, 0.3),
},
)

Search Algorithms

Optuna (Recommended Default)
python
from ray.tune.search.optuna import OptunaSearch
search_alg = OptunaSearch(metric="val_loss", mode="min")
tuner = tune.Tuner(
trainable,
param_space={...},
tune_config=tune.TuneConfig(
search_alg=search_alg,
num_samples=100,
),
)
HyperOpt (TPE)
python
from ray.tune.search.hyperopt import HyperOptSearch
search_alg = HyperOptSearch(metric="loss", mode="min")

Integration with Ray Train

Tuner(trainer) is deprecated as of Ray 2.43 (and already removed under Train V2 / RAY_TRAIN_V2_ENABLED=1). Use a function-based driver that builds the TorchTrainer inside the trial and calls trainer.fit(); surface Train metrics to Tune with a TuneReportCallback.

python
from ray.train import ScalingConfig
from ray.train.torch import TorchTrainer
from ray import tune
def train_driver_fn(config):
trainer = TorchTrainer(
train_func,
train_loop_config=config,
scaling_config=ScalingConfig(num_workers=2, use_gpu=True),
)
trainer.fit()
tuner = tune.Tuner(
train_driver_fn,
param_space={
"lr": tune.loguniform(1e-5, 1e-2),
"batch_size": tune.choice([16, 32, 64]),
},
tune_config=tune.TuneConfig(metric="val_loss", mode="min", num_samples=20),
)
results = tuner.fit()

See: https://docs.ray.io/en/latest/train/user-guides/hyperparameter-optimization.html

Tips

TipWhy
Start with num_samples=20 + ASHAFast signal on what matters
Use loguniform for learning rateLR spans orders of magnitude
Use choice for architecture decisionsDiscrete, not continuous
Set grace_period ≥ 5-10 epochsDon't kill trials before they warm up
PBT for expensive training (>1h/trial)Reuses compute from top performers
Always report checkpointsEnables resume after failure

References

  • Official docs: https://docs.ray.io/en/latest/tune/index.html
  • Key concepts: https://docs.ray.io/en/latest/tune/key-concepts.html
  • GitHub: https://github.com/ray-project/ray

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
3
7-day trend score
0

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/hung-phan/ml-skills/tune/badge)](https://verified-skill.com/skills/hung-phan/ml-skills/tune)

Something wrong with this skill or its page? Tell us.