[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M75P5VNVXD5FKARASP3RDW50":3,"skill-same:01M75P5VNVXD5FKARASP3RDW50":51},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":29,"commitSha":30,"skillDirectory":31,"forksCount":32,"repositoryHtmlUrl":33,"repositoryHomepageUrl":6,"ownerHtmlUrl":34,"ownerBlogUrl":35,"ownerDescription":6,"updatedAt":36,"install":37,"resources":50},"01M75P5VNVXD5FKARASP3RDW50","optuna",null,"Hyperparameter optimization (HPO) for ML models using Optuna. Use when tuning learning rate, regularization, architecture choices, or any numeric\u002Fcategorical hyperparameter. Covers create_study\u002Foptimize quickstart, sampler selection (TPE, CMA-ES, grid, random, NSGA-II), pruners for early stopping (MedianPruner, HyperbandPruner), distributed search with RDBStorage, integrations with PyTorch Lightning and scikit-learn, and built-in visualization.","stanfish06\u002Fskillquarium","stanfish06","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F93099613?v=4","01M75F1CK4ZW109ZK3T26VN52F","Zhiyuan","01M75F1CM53VH6F79DZ8GXKKES",12,"MIT","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Foptuna\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: optuna\ndescription: Hyperparameter optimization (HPO) for ML models using Optuna. Use when tuning learning rate, regularization, architecture choices, or any numeric\u002Fcategorical hyperparameter. Covers create_study\u002Foptimize quickstart, sampler selection (TPE, CMA-ES, grid, random, NSGA-II), pruners for early stopping (MedianPruner, HyperbandPruner), distributed search with RDBStorage, integrations with PyTorch Lightning and scikit-learn, and built-in visualization.\nlicense: MIT\nallowed-tools: Read Write Edit Bash\ncompatibility: Requires Python 3.9+ and optuna 4.0+. Optional extras — optuna-integration for framework callbacks (PyTorch Lightning, XGBoost, LightGBM, scikit-learn). Plotly or matplotlib for visualization.\nmetadata: {\"version\": \"1.0\", \"skill-author\": \"community\"}\n---\n\n# Optuna\n\n## Overview\n\nOptuna is a define-by-run hyperparameter optimization (HPO) framework from Preferred Networks. Unlike grid\u002Frandom search, Optuna uses Bayesian samplers that learn which regions of the search space are promising and concentrate evaluations there. It also supports multi-objective optimization, distributed parallel search, and early stopping via pruners.\n\nUse this skill when you need to tune any ML model's hyperparameters — it is framework-agnostic and integrates with PyTorch, PyTorch Lightning, TensorFlow, scikit-learn, XGBoost, LightGBM, and Hugging Face Transformers.\n\n## Installation\n\nTested against **optuna 5.x** (latest 5.0.0, September 2026). Requires **optuna 4.0+** and **Python 3.9+** (the skill uses 4.x\u002F5.x APIs such as `PatientPruner` and `JournalStorage`).\n\n```bash\n# Core install\nuv pip install optuna\n\n# Framework integrations (PyTorch Lightning, sklearn, XGBoost, LightGBM, HF)\nuv pip install optuna-integration\n\n# CMA-ES sampler backend (CmaEsSampler needs the separate `cmaes` package)\nuv pip install cmaes\n\n# Visualization backend (choose one)\nuv pip install plotly          # recommended — interactive HTML plots\nuv pip install matplotlib      # fallback static plots\n\n# Distributed search storage — Optuna has no postgres\u002Fmysql extras;\n# install the DB driver directly alongside optuna\nuv pip install psycopg2-binary     # PostgreSQL driver for RDBStorage\nuv pip install pymysql             # MySQL\u002FMariaDB driver for RDBStorage\n```\n\nCheck version:\n\n```python\nimport optuna\nprint(optuna.__version__)\n```\n\n## When to Use This Skill\n\nUse Optuna when:\n\n- You have a trained model and need to find better hyperparameters (learning rate, batch size, regularization, layer sizes, etc.)\n- Grid search is too expensive (search space grows exponentially)\n- You want automatic early stopping — kill bad trials mid-epoch to save GPU hours\n- You need to optimize multiple competing objectives (e.g. accuracy vs. inference speed)\n- You are running distributed HPO across multiple processes or machines\n- You want reproducible, logged experiment records\n\n## Quick Start\n\n### Minimal Example\n\n```python\nimport optuna\n\ndef objective(trial):\n    # Suggest hyperparameters\n    lr = trial.suggest_float(\"lr\", 1e-5, 1e-1, log=True)\n    n_layers = trial.suggest_int(\"n_layers\", 1, 5)\n    dropout = trial.suggest_float(\"dropout\", 0.0, 0.5)\n\n    # Train your model and return a metric to minimize\u002Fmaximize\n    val_loss = train_and_evaluate(lr=lr, n_layers=n_layers, dropout=dropout)\n    return val_loss\n\nstudy = optuna.create_study(direction=\"minimize\")\nstudy.optimize(objective, n_trials=100)\n\nprint(\"Best trial:\", study.best_trial.params)\nprint(\"Best value:\", study.best_value)\n```\n\n### Accessing Results\n\n```python\n# Best trial\ntrial = study.best_trial\nprint(f\"Value: {trial.value}, Params: {trial.params}\")\n\n# All completed trials as a DataFrame\ndf = study.trials_dataframe()\n\n# Top-5 trials — filter to COMPLETE trials first; pruned\u002Ffailed\u002Frunning\n# trials have value=None and would raise TypeError when sorted against floats\nimport optuna\ncompleted = [t for t in study.trials if t.state == optuna.trial.TrialState.COMPLETE]\ntrials = sorted(completed, key=lambda t: t.value)[:5]\nfor t in trials:\n    print(t.number, t.value, t.params)\n```\n\n## Suggesting Hyperparameters\n\nAll `suggest_*` calls are inside the `objective(trial)` function.\n\n```python\n# Continuous (uniform in [low, high])\nlr = trial.suggest_float(\"lr\", 1e-5, 1e-1)          # uniform\nlr = trial.suggest_float(\"lr\", 1e-5, 1e-1, log=True) # log-uniform (recommended for LR)\n\n# Integer (inclusive range)\nn_layers = trial.suggest_int(\"n_layers\", 1, 8)\nn_units = trial.suggest_int(\"n_units\", 32, 512, step=32)  # multiples of 32\n\n# Categorical\noptimizer = trial.suggest_categorical(\"optimizer\", [\"adam\", \"sgd\", \"rmsprop\"])\nactivation = trial.suggest_categorical(\"activation\", [\"relu\", \"tanh\", \"elu\"])\n\n# Conditional parameters (only suggest if parent is chosen)\noptimizer_name = trial.suggest_categorical(\"optimizer\", [\"adam\", \"sgd\"])\nif optimizer_name == \"sgd\":\n    momentum = trial.suggest_float(\"momentum\", 0.5, 0.99)\n```\n\n## Sampler Selection\n\nThe sampler determines how Optuna proposes next hyperparameter values. Pass it to `create_study`.\n\n### TPE (default) — Tree-structured Parzen Estimator\n\nBest general-purpose choice. Builds a probabilistic model of good vs. bad regions.\n\n```python\nfrom optuna.samplers import TPESampler\n\nstudy = optuna.create_study(\n    direction=\"minimize\",\n    sampler=TPESampler(seed=42, n_startup_trials=10)\n)\n```\n\n### CMA-ES — Covariance Matrix Adaptation Evolution Strategy\n\nBetter for continuous search spaces where parameters are correlated. Use for ≥5 numeric parameters. Requires the separate `cmaes` package (`uv pip install cmaes`) — a plain `optuna` install raises a missing-backend error.\n\n```python\nfrom optuna.samplers import CmaEsSampler\n\nstudy = optuna.create_study(\n    direction=\"minimize\",\n    sampler=CmaEsSampler(seed=42)\n)\n```\n\n### Grid Search\n\nExhaustively evaluates all combinations. Only feasible for tiny grids (≤hundreds of trials).\n\n```python\nfrom optuna.samplers import GridSampler\n\nsearch_space = {\n    \"lr\": [1e-3, 1e-4],\n    \"n_layers\": [2, 3, 4],\n}\nstudy = optuna.create_study(sampler=GridSampler(search_space))\n```\n\n### Random Search\n\nUseful as a baseline or when no prior knowledge is available.\n\n```python\nfrom optuna.samplers import RandomSampler\n\nstudy = optuna.create_study(sampler=RandomSampler(seed=42))\n```\n\n### NSGA-II — Multi-Objective (Pareto Front)\n\nUse when optimizing two or more competing metrics simultaneously (returns Pareto-optimal trials instead of a single best).\n\n```python\nfrom optuna.samplers import NSGAIISampler\n\nstudy = optuna.create_study(\n    directions=[\"minimize\", \"maximize\"],  # e.g. loss ↓ and accuracy ↑\n    sampler=NSGAIISampler(seed=42)\n)\n\n# Each objective returns a tuple\ndef objective(trial):\n    ...\n    return val_loss, val_accuracy\n\nstudy.optimize(objective, n_trials=200)\n\n# Access Pareto-front trials\npareto = study.best_trials\nfor t in pareto:\n    print(t.values, t.params)\n```\n\n## Pruners — Early Stopping\n\nPruners stop unpromising trials early. The objective calls `trial.report()` and `trial.should_prune()` at each epoch.\n\n### MedianPruner\n\nPrunes a trial when its best intermediate result is **worse** than the median of previous completed trials at the same step. Optuna accounts for the study direction, so \"worse\" means below the median when maximizing and above it when minimizing (e.g. a `val_loss` study prunes trials whose loss is higher than the median).\n\n```python\nfrom optuna.pruners import MedianPruner\n\nstudy = optuna.create_study(\n    direction=\"minimize\",\n    pruner=MedianPruner(n_startup_trials=5, n_warmup_steps=10)\n)\n\ndef objective(trial):\n    for epoch in range(100):\n        val_loss = train_one_epoch(...)\n\n        trial.report(val_loss, step=epoch)\n        if trial.should_prune():\n            raise optuna.TrialPruned()\n\n    return val_loss\n```\n\n### HyperbandPruner\n\nImplements Hyperband (successive halving). More aggressive; best for expensive training runs.\n\n```python\nfrom optuna.pruners import HyperbandPruner\n\nstudy = optuna.create_study(\n    direction=\"minimize\",\n    pruner=HyperbandPruner(min_resource=3, max_resource=30, reduction_factor=3)\n)\n```\n\n### PatientPruner\n\nPrunes if no improvement for N consecutive steps. Wraps any base pruner.\n\n```python\nfrom optuna.pruners import PatientPruner, MedianPruner\n\nstudy = optuna.create_study(\n    pruner=PatientPruner(wrapped_pruner=MedianPruner(), patience=5)\n)\n```\n\n## Distributed Search with RDBStorage\n\nStore trials in a relational database so multiple worker processes (or machines) can run the same study concurrently.\n\n### PostgreSQL\n\n```python\nimport optuna\n\nstorage = optuna.storages.RDBStorage(\n    url=\"postgresql:\u002F\u002Fuser:password@localhost:5432\u002Foptuna_db\",\n    engine_kwargs={\"pool_size\": 10}\n)\n\nstudy = optuna.create_study(\n    study_name=\"my_experiment\",\n    storage=storage,\n    load_if_exists=True,    # resume if study already exists\n    direction=\"minimize\",\n)\n\n# Launch multiple workers in parallel — each calls study.optimize independently\nstudy.optimize(objective, n_trials=50)\n```\n\n### MySQL \u002F MariaDB\n\n```python\nstorage = optuna.storages.RDBStorage(\n    url=\"mysql+pymysql:\u002F\u002Fuser:password@localhost:3306\u002Foptuna_db\"\n)\n```\n\n### Resuming a Study\n\n```python\nstudy = optuna.load_study(\n    study_name=\"my_experiment\",\n    storage=\"postgresql:\u002F\u002Fuser:password@localhost\u002Foptuna_db\"\n)\nprint(f\"Resuming with {len(study.trials)} trials already completed.\")\n```\n\n### In-memory JournalStorage (lightweight multi-process)\n\n```python\n# optuna 4.x: JournalStorage is a top-level storages export, but the file\n# backend lives in optuna.storages.journal (optuna.storages only keeps the\n# deprecated JournalFileStorage)\nfrom optuna.storages import JournalStorage\nfrom optuna.storages.journal import JournalFileBackend\n\nstorage = JournalStorage(JournalFileBackend(\"optuna_journal.log\"))\nstudy = optuna.create_study(storage=storage, study_name=\"local_run\")\n```\n\n## Framework Integrations\n\nAll integrations require `optuna-integration` package.\n\n### PyTorch Lightning\n\n```python\nimport pytorch_lightning as pl\nfrom optuna_integration import PyTorchLightningPruningCallback\n\ndef objective(trial):\n    lr = trial.suggest_float(\"lr\", 1e-5, 1e-1, log=True)\n    model = MyLightningModel(lr=lr)\n\n    trainer = pl.Trainer(\n        max_epochs=30,\n        callbacks=[\n            PyTorchLightningPruningCallback(trial, monitor=\"val_loss\")\n        ],\n    )\n    trainer.fit(model, train_dataloader, val_dataloader)\n    return trainer.callback_metrics[\"val_loss\"].item()\n\nstudy = optuna.create_study(\n    direction=\"minimize\",\n    pruner=optuna.pruners.MedianPruner()\n)\nstudy.optimize(objective, n_trials=50)\n```\n\n### scikit-learn — OptunaSearchCV\n\nDrop-in replacement for `GridSearchCV` \u002F `RandomizedSearchCV` that uses TPE under the hood.\n\n```python\nfrom optuna_integration import OptunaSearchCV\nfrom sklearn.ensemble import RandomForestClassifier\nfrom optuna.distributions import IntDistribution, FloatDistribution\n\nparam_distributions = {\n    \"n_estimators\": IntDistribution(50, 500),\n    \"max_depth\": IntDistribution(3, 15),\n    \"min_samples_split\": IntDistribution(2, 20),\n    \"max_features\": FloatDistribution(0.1, 1.0),\n}\n\nclf = OptunaSearchCV(\n    RandomForestClassifier(random_state=42),\n    param_distributions,\n    n_trials=50,\n    cv=5,\n    scoring=\"f1_weighted\",\n    random_state=42,\n)\nclf.fit(X_train, y_train)\n\nprint(\"Best params:\", clf.best_params_)\nprint(\"Best score:\", clf.best_score_)\n```\n\n### XGBoost \u002F LightGBM\n\n```python\n# XGBoost with pruning via XGBoostPruningCallback\nfrom optuna_integration import XGBoostPruningCallback\nimport xgboost as xgb\n\ndef objective(trial):\n    params = {\n        \"max_depth\": trial.suggest_int(\"max_depth\", 3, 10),\n        \"learning_rate\": trial.suggest_float(\"learning_rate\", 1e-3, 0.3, log=True),\n        \"n_estimators\": trial.suggest_int(\"n_estimators\", 100, 1000),\n        \"subsample\": trial.suggest_float(\"subsample\", 0.5, 1.0),\n        \"colsample_bytree\": trial.suggest_float(\"colsample_bytree\", 0.5, 1.0),\n    }\n    model = xgb.XGBClassifier(\n        **params,\n        callbacks=[XGBoostPruningCallback(trial, \"validation_0-logloss\")],\n        eval_metric=\"logloss\",\n        early_stopping_rounds=10,\n    )\n    model.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose=False)\n    return model.best_score\n\nstudy = optuna.create_study(\n    direction=\"minimize\",\n    pruner=optuna.pruners.MedianPruner()\n)\nstudy.optimize(objective, n_trials=100)\n```\n\n```python\n# LightGBM with pruning\nfrom optuna_integration import LightGBMPruningCallback\nimport lightgbm as lgb\n\ndef objective(trial):\n    params = {\n        # objective\u002Fmetric must be set so LightGBM emits the validation metric\n        # the pruning callback and best_score lookup below request\n        \"objective\": \"binary\",\n        \"metric\": \"binary_logloss\",\n        \"num_leaves\": trial.suggest_int(\"num_leaves\", 20, 300),\n        \"learning_rate\": trial.suggest_float(\"learning_rate\", 1e-4, 0.3, log=True),\n        \"min_child_samples\": trial.suggest_int(\"min_child_samples\", 5, 100),\n        \"feature_fraction\": trial.suggest_float(\"feature_fraction\", 0.4, 1.0),\n    }\n    callbacks = [LightGBMPruningCallback(trial, \"binary_logloss\")]\n    model = lgb.train(\n        params,\n        train_set,\n        num_boost_round=500,\n        valid_sets=[val_set],\n        callbacks=callbacks,\n    )\n    return model.best_score[\"valid_0\"][\"binary_logloss\"]\n```\n\n## Visualization\n\nOptuna ships built-in interactive plots (Plotly). For static plots, import the parallel `optuna.visualization.matplotlib` module instead (the plot functions take no `backend_name` argument) — e.g. `from optuna.visualization.matplotlib import plot_optimization_history`.\n\n```python\nimport optuna.visualization as vis\n\n# Optimization history — see if the study is converging\nfig = vis.plot_optimization_history(study)\nfig.show()  # or fig.write_html(\"history.html\")\n\n# Parameter importances — which hyperparameters matter most\nfig = vis.plot_param_importances(study)\nfig.show()\n\n# Parallel coordinate plot — view correlations between params and objective\nfig = vis.plot_parallel_coordinate(study)\nfig.show()\n\n# Contour plot — 2D slice of the objective surface\nfig = vis.plot_contour(study, params=[\"lr\", \"n_layers\"])\nfig.show()\n\n# Slice plot — 1D marginals\nfig = vis.plot_slice(study, params=[\"lr\", \"dropout\"])\nfig.show()\n\n# EDF (empirical distribution function) — compare multiple studies\nfig = vis.plot_edf([study1, study2], value_range=(0, 1))\nfig.show()\n```\n\n## CLI\n\nOptuna ships a CLI for managing studies stored in a database and launching the web dashboard.\n\n```bash\n# Create a new study\noptuna create-study \\\n  --study-name my_experiment \\\n  --storage \"postgresql:\u002F\u002Fuser:pass@localhost\u002Foptuna_db\" \\\n  --direction minimize\n\n# List all studies in a storage\noptuna studies \\\n  --storage \"postgresql:\u002F\u002Fuser:pass@localhost\u002Foptuna_db\"\n\n# Print best trial of a study\noptuna best-trial \\\n  --study-name my_experiment \\\n  --storage \"postgresql:\u002F\u002Fuser:pass@localhost\u002Foptuna_db\"\n\n# Dump all trials — the `trials` command has no --output\u002FCSV; use --format\n# {value,json,table,yaml} and redirect to a file\noptuna trials \\\n  --study-name my_experiment \\\n  --storage \"postgresql:\u002F\u002Fuser:pass@localhost\u002Foptuna_db\" \\\n  --format json > trials.json\n# For CSV, load the study in Python and use the DataFrame:\n#   optuna.load_study(study_name=..., storage=...).trials_dataframe().to_csv(\"trials.csv\")\n\n# Launch the web dashboard (requires optuna-dashboard package)\npip install optuna-dashboard\noptuna-dashboard \"postgresql:\u002F\u002Fuser:pass@localhost\u002Foptuna_db\"\n# Opens at http:\u002F\u002Flocalhost:8080\n```\n\n## Common Workflows\n\n### Standard HPO Workflow\n\n```python\nimport optuna\noptuna.logging.set_verbosity(optuna.logging.WARNING)  # suppress per-trial logs\n\ndef objective(trial):\n    # 1. Suggest hyperparameters\n    lr = trial.suggest_float(\"lr\", 1e-5, 1e-2, log=True)\n    weight_decay = trial.suggest_float(\"weight_decay\", 1e-6, 1e-2, log=True)\n    hidden_size = trial.suggest_categorical(\"hidden_size\", [128, 256, 512])\n\n    # 2. Build and train model — report after each epoch so the pruner can act.\n    #    HyperbandPruner (like all pruners) is inert without trial.report()\u002F\n    #    trial.should_prune(); training as one opaque call would never prune.\n    model = build_model(hidden_size=hidden_size)\n    optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)\n    for epoch in range(20):\n        val_loss = train_one_epoch(model, optimizer)   # one epoch of train + validate\n        trial.report(val_loss, step=epoch)\n        if trial.should_prune():\n            raise optuna.TrialPruned()\n    return val_loss\n\n# 3. Run study\nstudy = optuna.create_study(\n    direction=\"minimize\",\n    sampler=optuna.samplers.TPESampler(seed=42),\n    pruner=optuna.pruners.HyperbandPruner(),\n)\n# Single process here: this objective trains a PyTorch model (GPU\u002FCPU-bound),\n# so thread parallelism (n_jobs>1) is unsafe under CUDA and gives no speedup\n# under the GIL. For parallelism, run multiple processes against a shared\n# RDBStorage instead (see \"Distributed Search with RDBStorage\").\nstudy.optimize(objective, n_trials=200, timeout=3600)\n\n# 4. Extract best hyperparameters\nbest = study.best_trial\nprint(f\"Best val_loss: {best.value:.4f}\")\nprint(\"Best hyperparameters:\", best.params)\n```\n\n### Multi-objective Study\n\n```python\nstudy = optuna.create_study(\n    directions=[\"minimize\", \"minimize\"],  # loss, latency\n    sampler=optuna.samplers.NSGAIISampler(seed=42),\n)\n\ndef objective(trial):\n    n_layers = trial.suggest_int(\"n_layers\", 1, 6)\n    hidden = trial.suggest_int(\"hidden\", 32, 512, log=True)\n    model = build_model(n_layers, hidden)\n    val_loss = train(model)\n    latency_ms = benchmark_inference(model)\n    return val_loss, latency_ms\n\nstudy.optimize(objective, n_trials=300)\n\n# Pareto-optimal solutions\nfor t in study.best_trials:\n    print(f\"loss={t.values[0]:.4f}, latency={t.values[1]:.1f}ms, params={t.params}\")\n```\n\n### Parallel Search with n_jobs\n\n```python\n# Run 4 trials in parallel using threads (GIL-safe for I\u002FO-bound training)\nstudy.optimize(objective, n_trials=100, n_jobs=4)\n\n# For CPU-bound training, use separate processes + shared storage instead\n# Process 1:\nstudy.optimize(objective, n_trials=50)   # writes to shared RDBStorage\n\n# Process 2 (same command, different process):\nstudy.optimize(objective, n_trials=50)\n```\n\n## Best Practices\n\n### Log-scale for Learning Rates and Regularization\nAlways use `log=True` for parameters that span orders of magnitude:\n```python\nlr = trial.suggest_float(\"lr\", 1e-5, 1e-1, log=True)       # Good\nlr = trial.suggest_float(\"lr\", 0.00001, 0.1)                # Bad — wastes budget near 0\n```\n\n### Set seed for Reproducibility\n```python\nsampler = optuna.samplers.TPESampler(seed=42)\nstudy = optuna.create_study(sampler=sampler)\n```\n\n### Use Callbacks for Live Monitoring\n```python\ndef log_callback(study, trial):\n    # trial.value is None for pruned\u002Ffailed trials; skip them so that\n    # study.best_value (which raises ValueError until a trial COMPLETEs) is safe\n    if trial.value is not None:\n        print(f\"Trial {trial.number}: {trial.value:.4f} | Best: {study.best_value:.4f}\")\n\nstudy.optimize(objective, n_trials=100, callbacks=[log_callback])\n```\n\n### Warm-start from Previous Results\n```python\n# Add manually known good points to steer the sampler\nstudy.enqueue_trial({\"lr\": 1e-3, \"n_layers\": 3})\nstudy.optimize(objective, n_trials=100)\n```\n\n### Disable Logging for Clean Output\n```python\noptuna.logging.set_verbosity(optuna.logging.WARNING)\n```\n\n## Troubleshooting\n\n### TrialPruned Is Not an Error\n`TrialPruned` is raised intentionally by the pruner. It is caught internally by Optuna and marks the trial as pruned — not failed. Never catch it yourself unless you re-raise it:\n```python\ndef objective(trial):\n    for epoch in range(100):\n        loss = train_epoch(...)\n        trial.report(loss, epoch)\n        if trial.should_prune():\n            raise optuna.TrialPruned()   # correct — don't catch this\n    return loss\n```\n\n### Sampler Has Low n_startup_trials Exploration\nIf your search space is large, TPE may converge prematurely. Increase startup exploration:\n```python\nsampler = optuna.samplers.TPESampler(n_startup_trials=30, seed=42)\n```\n\n### Visualization Requires Plotly\n```python\n# If plotly is missing:\nuv pip install plotly\n\n# Alternatively use matplotlib backend:\noptuna.visualization.matplotlib.plot_optimization_history(study)\n```\n\n### Storage Connection Errors in Distributed Mode\nUse `heartbeat_interval` to detect crashed workers:\n```python\nfrom optuna.storages import RetryFailedTrialCallback\n\nstorage = optuna.storages.RDBStorage(\n    url=\"postgresql:\u002F\u002F...\",\n    heartbeat_interval=60,   # mark stale trials as failed after 60s silence\n    failed_trial_callback=RetryFailedTrialCallback(),\n)\n```\n\n## Additional Resources\n\n- Official Documentation: https:\u002F\u002Foptuna.readthedocs.io\u002F\n- GitHub: https:\u002F\u002Fgithub.com\u002Foptuna\u002Foptuna\n- optuna-integration package: https:\u002F\u002Fgithub.com\u002Foptuna\u002Foptuna-integration\n- optuna-dashboard: https:\u002F\u002Fgithub.com\u002Foptuna\u002Foptuna-dashboard\n- Tutorial notebooks: https:\u002F\u002Fgithub.com\u002Foptuna\u002Foptuna-examples\n","# Optuna\n\n## Overview\n\nOptuna is a define-by-run hyperparameter optimization (HPO) framework from Preferred Networks. Unlike grid\u002Frandom search, Optuna uses Bayesian samplers that learn which regions of the search space are promising and concentrate evaluations there. It also supports multi-objective optimization, distributed parallel search, and early stopping via pruners.\n\nUse this skill when you need to tune any ML model's hyperparameters — it is framework-agnostic and integrates with PyTorch, PyTorch Lightning, TensorFlow, scikit-learn, XGBoost, LightGBM, and Hugging Face Transformers.\n\n## Installation\n\nTested against **optuna 5.x** (latest 5.0.0, September 2026). Requires **optuna 4.0+** and **Python 3.9+** (the skill uses 4.x\u002F5.x APIs such as `PatientPruner` and `JournalStorage`).\n\n```bash\n# Core install\nuv pip install optuna\n\n# Framework integrations (PyTorch Lightning, sklearn, XGBoost, LightGBM, HF)\nuv pip install optuna-integration\n\n# CMA-ES sampler backend (CmaEsSampler needs the separate `cmaes` package)\nuv pip install cmaes\n\n# Visualization backend (choose one)\nuv pip install plotly          # recommended — interactive HTML plots\nuv pip install matplotlib      # fallback static plots\n\n# Distributed search storage — Optuna has no postgres\u002Fmysql extras;\n# install the DB driver directly alongside optuna\nuv pip install psycopg2-binary     # PostgreSQL driver for RDBStorage\nuv pip install pymysql             # MySQL\u002FMariaDB driver for RDBStorage\n```\n\nCheck version:\n\n```python\nimport optuna\nprint(optuna.__version__)\n```\n\n## When to Use This Skill\n\nUse Optuna when:\n\n- You have a trained model and need to find better hyperparameters (learning rate, batch size, regularization, layer sizes, etc.)\n- Grid search is too expensive (search space grows exponentially)\n- You want automatic early stopping — kill bad trials mid-epoch to save GPU hours\n- You need to optimize multiple competing objectives (e.g. accuracy vs. inference speed)\n- You are running distributed HPO across multiple processes or machines\n- You want reproducible, logged experiment records\n\n## Quick Start\n\n### Minimal Example\n\n```python\nimport optuna\n\ndef objective(trial):\n    # Suggest hyperparameters\n    lr = trial.suggest_float(\"lr\", 1e-5, 1e-1, log=True)\n    n_layers = trial.suggest_int(\"n_layers\", 1, 5)\n    dropout = trial.suggest_float(\"dropout\", 0.0, 0.5)\n\n    # Train your model and return a metric to minimize\u002Fmaximize\n    val_loss = train_and_evaluate(lr=lr, n_layers=n_layers, dropout=dropout)\n    return val_loss\n\nstudy = optuna.create_study(direction=\"minimize\")\nstudy.optimize(objective, n_trials=100)\n\nprint(\"Best trial:\", study.best_trial.params)\nprint(\"Best value:\", study.best_value)\n```\n\n### Accessing Results\n\n```python\n# Best trial\ntrial = study.best_trial\nprint(f\"Value: {trial.value}, Params: {trial.params}\")\n\n# All completed trials as a DataFrame\ndf = study.trials_dataframe()\n\n# Top-5 trials — filter to COMPLETE trials first; pruned\u002Ffailed\u002Frunning\n# trials have value=None and would raise TypeError when sorted against floats\nimport optuna\ncompleted = [t for t in study.trials if t.state == optuna.trial.TrialState.COMPLETE]\ntrials = sorted(completed, key=lambda t: t.value)[:5]\nfor t in trials:\n    print(t.number, t.value, t.params)\n```\n\n## Suggesting Hyperparameters\n\nAll `suggest_*` calls are inside the `objective(trial)` function.\n\n```python\n# Continuous (uniform in [low, high])\nlr = trial.suggest_float(\"lr\", 1e-5, 1e-1)          # uniform\nlr = trial.suggest_float(\"lr\", 1e-5, 1e-1, log=True) # log-uniform (recommended for LR)\n\n# Integer (inclusive range)\nn_layers = trial.suggest_int(\"n_layers\", 1, 8)\nn_units = trial.suggest_int(\"n_units\", 32, 512, step=32)  # multiples of 32\n\n# Categorical\noptimizer = trial.suggest_categorical(\"optimizer\", [\"adam\", \"sgd\", \"rmsprop\"])\nactivation = trial.suggest_categorical(\"activation\", [\"relu\", \"tanh\", \"elu\"])\n\n# Conditional parameters (only suggest if parent is chosen)\noptimizer_name = trial.suggest_categorical(\"optimizer\", [\"adam\", \"sgd\"])\nif optimizer_name == \"sgd\":\n    momentum = trial.suggest_float(\"momentum\", 0.5, 0.99)\n```\n\n## Sampler Selection\n\nThe sampler determines how Optuna proposes next hyperparameter values. Pass it to `create_study`.\n\n### TPE (default) — Tree-structured Parzen Estimator\n\nBest general-purpose choice. Builds a probabilistic model of good vs. bad regions.\n\n```python\nfrom optuna.samplers import TPESampler\n\nstudy = optuna.create_study(\n    direction=\"minimize\",\n    sampler=TPESampler(seed=42, n_startup_trials=10)\n)\n```\n\n### CMA-ES — Covariance Matrix Adaptation Evolution Strategy\n\nBetter for continuous search spaces where parameters are correlated. Use for ≥5 numeric parameters. Requires the separate `cmaes` package (`uv pip install cmaes`) — a plain `optuna` install raises a missing-backend error.\n\n```python\nfrom optuna.samplers import CmaEsSampler\n\nstudy = optuna.create_study(\n    direction=\"minimize\",\n    sampler=CmaEsSampler(seed=42)\n)\n```\n\n### Grid Search\n\nExhaustively evaluates all combinations. Only feasible for tiny grids (≤hundreds of trials).\n\n```python\nfrom optuna.samplers import GridSampler\n\nsearch_space = {\n    \"lr\": [1e-3, 1e-4],\n    \"n_layers\": [2, 3, 4],\n}\nstudy = optuna.create_study(sampler=GridSampler(search_space))\n```\n\n### Random Search\n\nUseful as a baseline or when no prior knowledge is available.\n\n```python\nfrom optuna.samplers import RandomSampler\n\nstudy = optuna.create_study(sampler=RandomSampler(seed=42))\n```\n\n### NSGA-II — Multi-Objective (Pareto Front)\n\nUse when optimizing two or more competing metrics simultaneously (returns Pareto-optimal trials instead of a single best).\n\n```python\nfrom optuna.samplers import NSGAIISampler\n\nstudy = optuna.create_study(\n    directions=[\"minimize\", \"maximize\"],  # e.g. loss ↓ and accuracy ↑\n    sampler=NSGAIISampler(seed=42)\n)\n\n# Each objective returns a tuple\ndef objective(trial):\n    ...\n    return val_loss, val_accuracy\n\nstudy.optimize(objective, n_trials=200)\n\n# Access Pareto-front trials\npareto = study.best_trials\nfor t in pareto:\n    print(t.values, t.params)\n```\n\n## Pruners — Early Stopping\n\nPruners stop unpromising trials early. The objective calls `trial.report()` and `trial.should_prune()` at each epoch.\n\n### MedianPruner\n\nPrunes a trial when its best intermediate result is **worse** than the median of previous completed trials at the same step. Optuna accounts for the study direction, so \"worse\" means below the median when maximizing and above it when minimizing (e.g. a `val_loss` study prunes trials whose loss is higher than the median).\n\n```python\nfrom optuna.pruners import MedianPruner\n\nstudy = optuna.create_study(\n    direction=\"minimize\",\n    pruner=MedianPruner(n_startup_trials=5, n_warmup_steps=10)\n)\n\ndef objective(trial):\n    for epoch in range(100):\n        val_loss = train_one_epoch(...)\n\n        trial.report(val_loss, step=epoch)\n        if trial.should_prune():\n            raise optuna.TrialPruned()\n\n    return val_loss\n```\n\n### HyperbandPruner\n\nImplements Hyperband (successive halving). More aggressive; best for expensive training runs.\n\n```python\nfrom optuna.pruners import HyperbandPruner\n\nstudy = optuna.create_study(\n    direction=\"minimize\",\n    pruner=HyperbandPruner(min_resource=3, max_resource=30, reduction_factor=3)\n)\n```\n\n### PatientPruner\n\nPrunes if no improvement for N consecutive steps. Wraps any base pruner.\n\n```python\nfrom optuna.pruners import PatientPruner, MedianPruner\n\nstudy = optuna.create_study(\n    pruner=PatientPruner(wrapped_pruner=MedianPruner(), patience=5)\n)\n```\n\n## Distributed Search with RDBStorage\n\nStore trials in a relational database so multiple worker processes (or machines) can run the same study concurrently.\n\n### PostgreSQL\n\n```python\nimport optuna\n\nstorage = optuna.storages.RDBStorage(\n    url=\"postgresql:\u002F\u002Fuser:password@localhost:5432\u002Foptuna_db\",\n    engine_kwargs={\"pool_size\": 10}\n)\n\nstudy = optuna.create_study(\n    study_name=\"my_experiment\",\n    storage=storage,\n    load_if_exists=True,    # resume if study already exists\n    direction=\"minimize\",\n)\n\n# Launch multiple workers in parallel — each calls study.optimize independently\nstudy.optimize(objective, n_trials=50)\n```\n\n### MySQL \u002F MariaDB\n\n```python\nstorage = optuna.storages.RDBStorage(\n    url=\"mysql+pymysql:\u002F\u002Fuser:password@localhost:3306\u002Foptuna_db\"\n)\n```\n\n### Resuming a Study\n\n```python\nstudy = optuna.load_study(\n    study_name=\"my_experiment\",\n    storage=\"postgresql:\u002F\u002Fuser:password@localhost\u002Foptuna_db\"\n)\nprint(f\"Resuming with {len(study.trials)} trials already completed.\")\n```\n\n### In-memory JournalStorage (lightweight multi-process)\n\n```python\n# optuna 4.x: JournalStorage is a top-level storages export, but the file\n# backend lives in optuna.storages.journal (optuna.storages only keeps the\n# deprecated JournalFileStorage)\nfrom optuna.storages import JournalStorage\nfrom optuna.storages.journal import JournalFileBackend\n\nstorage = JournalStorage(JournalFileBackend(\"optuna_journal.log\"))\nstudy = optuna.create_study(storage=storage, study_name=\"local_run\")\n```\n\n## Framework Integrations\n\nAll integrations require `optuna-integration` package.\n\n### PyTorch Lightning\n\n```python\nimport pytorch_lightning as pl\nfrom optuna_integration import PyTorchLightningPruningCallback\n\ndef objective(trial):\n    lr = trial.suggest_float(\"lr\", 1e-5, 1e-1, log=True)\n    model = MyLightningModel(lr=lr)\n\n    trainer = pl.Trainer(\n        max_epochs=30,\n        callbacks=[\n            PyTorchLightningPruningCallback(trial, monitor=\"val_loss\")\n        ],\n    )\n    trainer.fit(model, train_dataloader, val_dataloader)\n    return trainer.callback_metrics[\"val_loss\"].item()\n\nstudy = optuna.create_study(\n    direction=\"minimize\",\n    pruner=optuna.pruners.MedianPruner()\n)\nstudy.optimize(objective, n_trials=50)\n```\n\n### scikit-learn — OptunaSearchCV\n\nDrop-in replacement for `GridSearchCV` \u002F `RandomizedSearchCV` that uses TPE under the hood.\n\n```python\nfrom optuna_integration import OptunaSearchCV\nfrom sklearn.ensemble import RandomForestClassifier\nfrom optuna.distributions import IntDistribution, FloatDistribution\n\nparam_distributions = {\n    \"n_estimators\": IntDistribution(50, 500),\n    \"max_depth\": IntDistribution(3, 15),\n    \"min_samples_split\": IntDistribution(2, 20),\n    \"max_features\": FloatDistribution(0.1, 1.0),\n}\n\nclf = OptunaSearchCV(\n    RandomForestClassifier(random_state=42),\n    param_distributions,\n    n_trials=50,\n    cv=5,\n    scoring=\"f1_weighted\",\n    random_state=42,\n)\nclf.fit(X_train, y_train)\n\nprint(\"Best params:\", clf.best_params_)\nprint(\"Best score:\", clf.best_score_)\n```\n\n### XGBoost \u002F LightGBM\n\n```python\n# XGBoost with pruning via XGBoostPruningCallback\nfrom optuna_integration import XGBoostPruningCallback\nimport xgboost as xgb\n\ndef objective(trial):\n    params = {\n        \"max_depth\": trial.suggest_int(\"max_depth\", 3, 10),\n        \"learning_rate\": trial.suggest_float(\"learning_rate\", 1e-3, 0.3, log=True),\n        \"n_estimators\": trial.suggest_int(\"n_estimators\", 100, 1000),\n        \"subsample\": trial.suggest_float(\"subsample\", 0.5, 1.0),\n        \"colsample_bytree\": trial.suggest_float(\"colsample_bytree\", 0.5, 1.0),\n    }\n    model = xgb.XGBClassifier(\n        **params,\n        callbacks=[XGBoostPruningCallback(trial, \"validation_0-logloss\")],\n        eval_metric=\"logloss\",\n        early_stopping_rounds=10,\n    )\n    model.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose=False)\n    return model.best_score\n\nstudy = optuna.create_study(\n    direction=\"minimize\",\n    pruner=optuna.pruners.MedianPruner()\n)\nstudy.optimize(objective, n_trials=100)\n```\n\n```python\n# LightGBM with pruning\nfrom optuna_integration import LightGBMPruningCallback\nimport lightgbm as lgb\n\ndef objective(trial):\n    params = {\n        # objective\u002Fmetric must be set so LightGBM emits the validation metric\n        # the pruning callback and best_score lookup below request\n        \"objective\": \"binary\",\n        \"metric\": \"binary_logloss\",\n        \"num_leaves\": trial.suggest_int(\"num_leaves\", 20, 300),\n        \"learning_rate\": trial.suggest_float(\"learning_rate\", 1e-4, 0.3, log=True),\n        \"min_child_samples\": trial.suggest_int(\"min_child_samples\", 5, 100),\n        \"feature_fraction\": trial.suggest_float(\"feature_fraction\", 0.4, 1.0),\n    }\n    callbacks = [LightGBMPruningCallback(trial, \"binary_logloss\")]\n    model = lgb.train(\n        params,\n        train_set,\n        num_boost_round=500,\n        valid_sets=[val_set],\n        callbacks=callbacks,\n    )\n    return model.best_score[\"valid_0\"][\"binary_logloss\"]\n```\n\n## Visualization\n\nOptuna ships built-in interactive plots (Plotly). For static plots, import the parallel `optuna.visualization.matplotlib` module instead (the plot functions take no `backend_name` argument) — e.g. `from optuna.visualization.matplotlib import plot_optimization_history`.\n\n```python\nimport optuna.visualization as vis\n\n# Optimization history — see if the study is converging\nfig = vis.plot_optimization_history(study)\nfig.show()  # or fig.write_html(\"history.html\")\n\n# Parameter importances — which hyperparameters matter most\nfig = vis.plot_param_importances(study)\nfig.show()\n\n# Parallel coordinate plot — view correlations between params and objective\nfig = vis.plot_parallel_coordinate(study)\nfig.show()\n\n# Contour plot — 2D slice of the objective surface\nfig = vis.plot_contour(study, params=[\"lr\", \"n_layers\"])\nfig.show()\n\n# Slice plot — 1D marginals\nfig = vis.plot_slice(study, params=[\"lr\", \"dropout\"])\nfig.show()\n\n# EDF (empirical distribution function) — compare multiple studies\nfig = vis.plot_edf([study1, study2], value_range=(0, 1))\nfig.show()\n```\n\n## CLI\n\nOptuna ships a CLI for managing studies stored in a database and launching the web dashboard.\n\n```bash\n# Create a new study\noptuna create-study \\\n  --study-name my_experiment \\\n  --storage \"postgresql:\u002F\u002Fuser:pass@localhost\u002Foptuna_db\" \\\n  --direction minimize\n\n# List all studies in a storage\noptuna studies \\\n  --storage \"postgresql:\u002F\u002Fuser:pass@localhost\u002Foptuna_db\"\n\n# Print best trial of a study\noptuna best-trial \\\n  --study-name my_experiment \\\n  --storage \"postgresql:\u002F\u002Fuser:pass@localhost\u002Foptuna_db\"\n\n# Dump all trials — the `trials` command has no --output\u002FCSV; use --format\n# {value,json,table,yaml} and redirect to a file\noptuna trials \\\n  --study-name my_experiment \\\n  --storage \"postgresql:\u002F\u002Fuser:pass@localhost\u002Foptuna_db\" \\\n  --format json > trials.json\n# For CSV, load the study in Python and use the DataFrame:\n#   optuna.load_study(study_name=..., storage=...).trials_dataframe().to_csv(\"trials.csv\")\n\n# Launch the web dashboard (requires optuna-dashboard package)\npip install optuna-dashboard\noptuna-dashboard \"postgresql:\u002F\u002Fuser:pass@localhost\u002Foptuna_db\"\n# Opens at http:\u002F\u002Flocalhost:8080\n```\n\n## Common Workflows\n\n### Standard HPO Workflow\n\n```python\nimport optuna\noptuna.logging.set_verbosity(optuna.logging.WARNING)  # suppress per-trial logs\n\ndef objective(trial):\n    # 1. Suggest hyperparameters\n    lr = trial.suggest_float(\"lr\", 1e-5, 1e-2, log=True)\n    weight_decay = trial.suggest_float(\"weight_decay\", 1e-6, 1e-2, log=True)\n    hidden_size = trial.suggest_categorical(\"hidden_size\", [128, 256, 512])\n\n    # 2. Build and train model — report after each epoch so the pruner can act.\n    #    HyperbandPruner (like all pruners) is inert without trial.report()\u002F\n    #    trial.should_prune(); training as one opaque call would never prune.\n    model = build_model(hidden_size=hidden_size)\n    optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)\n    for epoch in range(20):\n        val_loss = train_one_epoch(model, optimizer)   # one epoch of train + validate\n        trial.report(val_loss, step=epoch)\n        if trial.should_prune():\n            raise optuna.TrialPruned()\n    return val_loss\n\n# 3. Run study\nstudy = optuna.create_study(\n    direction=\"minimize\",\n    sampler=optuna.samplers.TPESampler(seed=42),\n    pruner=optuna.pruners.HyperbandPruner(),\n)\n# Single process here: this objective trains a PyTorch model (GPU\u002FCPU-bound),\n# so thread parallelism (n_jobs>1) is unsafe under CUDA and gives no speedup\n# under the GIL. For parallelism, run multiple processes against a shared\n# RDBStorage instead (see \"Distributed Search with RDBStorage\").\nstudy.optimize(objective, n_trials=200, timeout=3600)\n\n# 4. Extract best hyperparameters\nbest = study.best_trial\nprint(f\"Best val_loss: {best.value:.4f}\")\nprint(\"Best hyperparameters:\", best.params)\n```\n\n### Multi-objective Study\n\n```python\nstudy = optuna.create_study(\n    directions=[\"minimize\", \"minimize\"],  # loss, latency\n    sampler=optuna.samplers.NSGAIISampler(seed=42),\n)\n\ndef objective(trial):\n    n_layers = trial.suggest_int(\"n_layers\", 1, 6)\n    hidden = trial.suggest_int(\"hidden\", 32, 512, log=True)\n    model = build_model(n_layers, hidden)\n    val_loss = train(model)\n    latency_ms = benchmark_inference(model)\n    return val_loss, latency_ms\n\nstudy.optimize(objective, n_trials=300)\n\n# Pareto-optimal solutions\nfor t in study.best_trials:\n    print(f\"loss={t.values[0]:.4f}, latency={t.values[1]:.1f}ms, params={t.params}\")\n```\n\n### Parallel Search with n_jobs\n\n```python\n# Run 4 trials in parallel using threads (GIL-safe for I\u002FO-bound training)\nstudy.optimize(objective, n_trials=100, n_jobs=4)\n\n# For CPU-bound training, use separate processes + shared storage instead\n# Process 1:\nstudy.optimize(objective, n_trials=50)   # writes to shared RDBStorage\n\n# Process 2 (same command, different process):\nstudy.optimize(objective, n_trials=50)\n```\n\n## Best Practices\n\n### Log-scale for Learning Rates and Regularization\nAlways use `log=True` for parameters that span orders of magnitude:\n```python\nlr = trial.suggest_float(\"lr\", 1e-5, 1e-1, log=True)       # Good\nlr = trial.suggest_float(\"lr\", 0.00001, 0.1)                # Bad — wastes budget near 0\n```\n\n### Set seed for Reproducibility\n```python\nsampler = optuna.samplers.TPESampler(seed=42)\nstudy = optuna.create_study(sampler=sampler)\n```\n\n### Use Callbacks for Live Monitoring\n```python\ndef log_callback(study, trial):\n    # trial.value is None for pruned\u002Ffailed trials; skip them so that\n    # study.best_value (which raises ValueError until a trial COMPLETEs) is safe\n    if trial.value is not None:\n        print(f\"Trial {trial.number}: {trial.value:.4f} | Best: {study.best_value:.4f}\")\n\nstudy.optimize(objective, n_trials=100, callbacks=[log_callback])\n```\n\n### Warm-start from Previous Results\n```python\n# Add manually known good points to steer the sampler\nstudy.enqueue_trial({\"lr\": 1e-3, \"n_layers\": 3})\nstudy.optimize(objective, n_trials=100)\n```\n\n### Disable Logging for Clean Output\n```python\noptuna.logging.set_verbosity(optuna.logging.WARNING)\n```\n\n## Troubleshooting\n\n### TrialPruned Is Not an Error\n`TrialPruned` is raised intentionally by the pruner. It is caught internally by Optuna and marks the trial as pruned — not failed. Never catch it yourself unless you re-raise it:\n```python\ndef objective(trial):\n    for epoch in range(100):\n        loss = train_epoch(...)\n        trial.report(loss, epoch)\n        if trial.should_prune():\n            raise optuna.TrialPruned()   # correct — don't catch this\n    return loss\n```\n\n### Sampler Has Low n_startup_trials Exploration\nIf your search space is large, TPE may converge prematurely. Increase startup exploration:\n```python\nsampler = optuna.samplers.TPESampler(n_startup_trials=30, seed=42)\n```\n\n### Visualization Requires Plotly\n```python\n# If plotly is missing:\nuv pip install plotly\n\n# Alternatively use matplotlib backend:\noptuna.visualization.matplotlib.plot_optimization_history(study)\n```\n\n### Storage Connection Errors in Distributed Mode\nUse `heartbeat_interval` to detect crashed workers:\n```python\nfrom optuna.storages import RetryFailedTrialCallback\n\nstorage = optuna.storages.RDBStorage(\n    url=\"postgresql:\u002F\u002F...\",\n    heartbeat_interval=60,   # mark stale trials as failed after 60s silence\n    failed_trial_callback=RetryFailedTrialCallback(),\n)\n```\n\n## Additional Resources\n\n- Official Documentation: https:\u002F\u002Foptuna.readthedocs.io\u002F\n- GitHub: https:\u002F\u002Fgithub.com\u002Foptuna\u002Foptuna\n- optuna-integration package: https:\u002F\u002Fgithub.com\u002Foptuna\u002Foptuna-integration\n- optuna-dashboard: https:\u002F\u002Fgithub.com\u002Foptuna\u002Foptuna-dashboard\n- Tutorial notebooks: https:\u002F\u002Fgithub.com\u002Foptuna\u002Foptuna-examples\n",{"name":5,"license":15,"metadata":24,"description":7,"allowed-tools":27,"compatibility":28},{"version":25,"skill-author":26},"1.0","community","Read Write Edit Bash","Requires Python 3.9+ and optuna 4.0+. Optional extras — optuna-integration for framework callbacks (PyTorch Lightning, XGBoost, LightGBM, scikit-learn). Plotly or matplotlib for visualization.","master","49e49abf2f670d429e0b7e2c0349739c3fdd5cbe","skills\u002Foptuna",5,"https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium","https:\u002F\u002Fgithub.com\u002Fstanfish06","https:\u002F\u002Fwww.stanfish.dev\u002F","2026-11-14 21:31:37",{"source":8,"skillName":5,"commands":38,"prompt":48,"zipAvailable":49},[39,42,45],{"tool":40,"command":41},"npx","npx skills add stanfish06\u002Fskillquarium --skill optuna",{"tool":43,"command":44},"bunx","bunx skills add stanfish06\u002Fskillquarium --skill optuna",{"tool":46,"command":47},"pnpm","pnpm dlx skills add stanfish06\u002Fskillquarium --skill optuna","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Foptuna\u002FSKILL.md",true,[],[52,59,68,75,82,89],{"skillNo":53,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":19},"01M76ZJTRVA456GD7K8Y3EP82H","zarr-python","Stores and queries chunked N-D scientific arrays with Zarr-Python 3, including codecs, sharding, S3\u002FGCS storage, and NumPy\u002FDask\u002FXarray integration. Use for array layout, bounded I\u002FO, format migration, or scientific metadata preservation.","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fzarr-python\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":63,"licenseFileUrl":64,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":19},"01M76ZJQZ15Q1HKC5V85NHE325","yeet","Publish local changes to GitHub by confirming scope, committing intentionally, pushing the branch, and opening a draft PR through the GitHub app from this plugin, with `gh` used only as a fallback where connector coverage is insufficient.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fyeet\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fyeet\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":63,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":19},"01M76ZJ8ASZ4QYQ70Y6SBA4Z4S","xarray","N-dimensional labeled arrays and datasets in Python. Built on top of NumPy and Dask. It introduces labels in the form of dimensions, coordinates, and attributes on top of raw NumPy-like arrays, making data analysis in physical sciences more intuitive and less error-prone. Use for working with multi-dimensional scientific data, NetCDF\u002FGRIB\u002FZarr files, climate\u002Fweather\u002Foceanographic datasets, remote sensing, geospatial imaging, large out-of-memory datasets with Dask, and labeled array operations.","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fxarray\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M76ZHFBXD6VXPQ02VCEG202B","writing-mstest-tests","Use when asked to fix, rewrite, update, improve, modernize, show corrected code for, or explain existing MSTest tests or MSTest-specific configuration. Use for \"review\" when corrected code or edits are wanted, even for one pasted assertion or passing tests with bad failure output. Covers expected\u002Factual labels; generic Boolean, collection, string, numeric, null, identity, exception, hard-cast, and object[] checks; TestContext\u002Flifecycle; timeout\u002Fcancellation; OS\u002FCI conditions, retry, cleanup, parallelization, MSTest.Sdk project setup, and MSTESTxxxx. Honor the installed MSTest version. DO NOT USE to design new test cases (code-testing), perform report-only audits, create project files rather than explain MSTest setup, run tests, migrate frameworks, or handle non-MSTest\u002Fnon-.NET code.","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fwriting-mstest-tests\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M76ZDFDF4N88RH6HSYGS7GP2","wgs-prs","End-to-end WGS to polygenic risk score pipeline. Takes paired-end FASTQ files (or a pre-existing VCF) through nf-core\u002Fsarek for variant calling, applies VCF QC (normalisation, hard filtering, Ti\u002FTv and Het\u002FHom checks), then computes polygenic risk scores via the PGS Catalog. Fills the FASTQ to VCF gap upstream of the gwas-prs skill.","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fwgs-prs\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":63,"licenseFileUrl":93,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"01M76ZCC1SC68J42QK4MDC8RCG","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fwebapp-testing\u002FSKILL.md",[],[]]