agentsclimarketplace

Baseline

Skill ChuaHanChong/ml-optimizer/skills/baseline

Establish baseline metrics for an ML model. Runs evaluation, profiles GPU memory and training throughput, and creates the <exp_root> directory structure. Use when: need to measure current model performance before optimization.From its SKILL.md

Install
npx -y skills add ChuaHanChong/ml-optimizer --skill baseline

Assembled from the repository path, not quoted from the project. Check it against their README if it does not work.

One thing to look at

  • 0 stars0 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.

SKILL.md

20.6 KB, as published. Nobody here has run it

Baseline Evaluation

Establish baseline performance metrics for the ML model — always the first optimization step.

Path convention: All <exp_root>/... paths refer to the exp_root dispatch parameter. The plugin does not hardcode the output directory name.

Inputs Expected

The orchestrator provides:

  • Project root path
  • Model/training details (from understanding phase)
  • prepared_train_path (optional): if prerequisites prepared data, use this instead of the original data path in the training command
  • prepared_val_path (optional): same for validation data
  • model_category (optional): from user_choices — "supervised", "rl", "generative", or null. Controls RL-specific evaluation (see RL Baseline Evaluation). The tabular-ML GPU-profiling skip is framework-detected (Step 4), independent of model_category.
  • eval_tasks (optional): list of task/environment names from Phase 0 user_choices, for multi-task evaluation. Empty/absent = single-task, no change in behavior.
  • remote: optional {host, workdir, env_python} from Phase 0 Q13. When present, run the baseline through remote_train.sh so it shares hardware with the experiments it will be compared against.

Step 1: Identify Evaluation Command

Search the project for evaluation scripts:

  1. Use Glob for candidates:

    • **/eval*.py, **/test*.py, **/infer*.py, **/validate*.py
    • **/scripts/eval*, **/scripts/test*
    • Makefile, **/*.sh (look for eval targets)
  2. Read the training script for validation/evaluation logic:

    • Functions named evaluate, validate, test, infer
    • Metric computation (PSNR, SSIM, loss, accuracy, F1, etc.)
    • Lightning: validation_step() / test_step() methods and self.log() calls. Metrics may be in TensorBoard logs (lightning_logs/) — parse with ${CLAUDE_PLUGIN_ROOT}/scripts/parse_logs.py
    • HuggingFace Trainer: compute_metrics passed to Trainer. Metrics log to runs/ or output_dir. Use trainer.evaluate() as eval command
    • TF/Keras: model.evaluate() or custom callbacks. Metrics may be in CSVLogger output or TensorBoard
  3. If no clear eval command found:

    First try auto-fallback:

    • Set eval_command = null
    • Use training output as the eval source — run training for the profiling duration and extract final metrics via ${CLAUDE_PLUGIN_ROOT}/scripts/parse_logs.py
    • If metrics containing the primary_metric keyword are found: use those as baseline metrics
    • If none found: look for checkpoint/log files (TensorBoard events, CSV logs, JSON summaries) and parse those
    • Log to dev_notes: "No eval command found — using training output metrics as baseline"
    • Log to error tracker: category: "config_error", severity: "info", source: "baseline", message: "No eval command — falling back to training output metrics"

    If auto-fallback finds no metrics: baseline-agent has no AskUserQuestion tool. If the user is available via the orchestrator, ask; otherwise fall back to training output metrics and log the gap to dev_notes for the Phase 4 checkpoint:

    I couldn't automatically identify an evaluation command.
    How do I evaluate this model? Please provide:
    - The command to run evaluation
    - What metrics it outputs
    

Step 1.1: Apply Prepared Data Paths (If Applicable)

If the orchestrator passed prepared_train_path or prepared_val_path:

  1. Identify how the training command references data paths (CLI args like --data_dir, --train_path, --val_path, or config file entries)
  2. Substitute the prepared paths into the training/eval commands before running
  3. If paths are in a config file, create a modified copy at <exp_root>/logs/baseline/config.yaml with updated paths
  4. Log in dev_notes which paths were substituted

Otherwise use the original commands as-is.

Step 2: Set Up Experiment Directory

python3 ${CLAUDE_PLUGIN_ROOT}/scripts/experiment_setup.py <exp_root> "<train_command>"

This creates the 5 top-level directories:

<exp_root>/
  logs/
  reports/
  scripts/
  results/
  artifacts/

It also has side effects worth knowing about: it allocates exp_id "exp-001" (via next_experiment_id()) and writes a placeholder results/exp-001.json ({"exp_id": "exp-001", "config": {}, "status": "pending"}, never updated) plus scripts/exp-001/train.sh. These are harmless but orphaned — ignore/discard them, do not treat "exp-001" as a real experiment.

Step 2.1: Auto-Repair Loop (for eval/train commands)

When executing evaluation or training commands (Steps 3 and 4), apply this retry pattern:

  1. Attempt 1: run the command normally
  2. If it fails (non-zero exit code):
    • Capture stderr and the last 50 lines of stdout
    • Log to error tracker: category: "training_failure", severity: "warning", source: "baseline", message: "Command failed (attempt 1/3): <error_summary>", phase: 3, context: {"command": "<command>", "attempt": 1}
    • Diagnose:
      • ModuleNotFoundError / ImportError → install the missing package, retry
      • FileNotFoundError → check the path exists, fix references, retry
      • CUDA out of memory → reduce batch size 50% in the command, retry
      • RuntimeError: CUDA → try CUDA_VISIBLE_DEVICES=0, retry
      • PermissionError → fix permissions, retry
      • SyntaxError / IndentationError → do NOT retry (code bug, report to orchestrator)
      • KeyboardInterrupt / SIGTERM → do NOT retry (intentional stop)
      • Other → read relevant source, propose a fix, retry
    • Attempt 2: re-run with fix applied
  3. If attempt 2 also fails:
    • Log attempt 2 failure (same pattern, attempt: 2)
    • Try a different approach (different package version, broader file search, further batch reduction)
    • Attempt 3: re-run with new fix
  4. If attempt 3 fails:
    • Log with severity: "critical", attempt: 3
    • Give up. Report full error history (all 3 attempts) to the orchestrator
    • The orchestrator's Phase 3 Failure Recovery table handles escalation

Loop detection: if attempt 2 produces the same error message (first 200 chars) as attempt 1, skip attempt 3.

Step 2.2: Apply Training Budget to Baseline

The baseline must use the same training budget as experiments for fair comparison. Read <exp_root>/pipeline-state.json and check user_choices for either budget type:

If fixed_time_budget is set (seconds):

  1. Wrap the training command with timeout:
    timeout --signal=SIGTERM --kill-after=60 <fixed_time_budget> <train_command>
    
    Never wrap with conda run -n <env> <cmd> — it drops stdout on SIGTERM (0-byte log). Invoke <conda_prefix>/bin/python3 -u directly, with PYTHONUNBUFFERED=1.
  2. Set epochs high enough that timeout is the binding constraint (e.g., --epochs 200)
  3. Exit code 124 (timeout reached) is treated as success — training completed its time budget normally
  4. Checkpoint pre-flight: verify the training script saves checkpoints periodically (look for save_freq, checkpoint_interval, ModelCheckpoint, periodic save_checkpoint calls) or supports a framework-native time limit (Lightning --max_time, HF TrainingArguments). If NEITHER exists, the SIGTERM kill leaves no final checkpoint — warn in dev_notes and record "eval_checkpoint_missing": true in the baseline notes instead of scoring a stale/initial checkpoint.

If fixed_epoch_budget is set (integer):

  1. Override the epoch count in the training command (e.g., replace --epochs 2 with --epochs <fixed_epoch_budget>)
  2. If there is no epochs flag, add one appropriate to the framework

If fixed_step_budget is set (integer — environment timesteps, RL):

  1. Map it to the framework's timestep flag instead of an epoch count — e.g., SB3 --total_timesteps <fixed_step_budget> (or learn(total_timesteps=...)), rsl_rl --max_iterations <fixed_step_budget / (num_envs * num_steps_per_env)>
  2. Do not wrap with timeout — the timestep cap is the binding constraint (the safety timeout from profiling still applies)

If neither is set: run training with the original epoch count from train_command.

Budget-utilization check (any fixed budget): confirm the baseline actually consumed the budget — its duration/step-count should match what the experiments will use, not fall well short (a hardcoded epoch/step cap the override didn't lift, or a budget applied only to experiments). An under-trained baseline confounds every vs-baseline delta with training duration ("trained longer", not "better method"). Don't accept it silently: fix so the budget binds and re-run the baseline, or — if it genuinely can't — record "budget_underutilized": true + the utilization ratio in baseline.json, warn the error tracker, AND warn in dev_notes (same pattern as eval_checkpoint_missing above) — dev_notes.md is what report actually reads, so that's how the caveat reaches the final report.

Step 2.3: Detect Headless Simulator Env Vars

If model_category is "rl" (or the prerequisites import scan found a simulator stack), determine the env vars required for headless rendering and record them for reuse by every experiment:

Simulator importEnv vars
mujoco, dm_controlMUJOCO_GL=egl, PYOPENGL_PLATFORM=egl
habitat_simMAGNUM_LOG=quiet, HABITAT_SIM_LOG=quiet
pybullet(none — headless by default via DIRECT mode)
omni / isaacsim / isaaclabprefer the script's --headless CLI flag when exposed; otherwise HEADLESS=1
  1. Re-run python3 ${CLAUDE_PLUGIN_ROOT}/scripts/prerequisites_check.py scan-imports <project_root> — prerequisites.json does not persist the {stdlib, third_party, local} import classification, only environment.manual_install_required and environment.packages_installed, so the scan must be re-run rather than read back.
  2. Collect the applicable env vars, apply them when running the baseline training/profiling commands, and record them in baseline.json under profiling.sim_env (a dict of env var name → value; {} when none apply).
  3. If baseline training fails with a GL/EGL/display error (GLFWError, cannot connect to X server, EGL), add MUJOCO_GL=egl / PYOPENGL_PLATFORM=egl and retry via the auto-repair loop (Step 2.1).

Experiments reuse these vars: the experiment skill reads profiling.sim_env and forwards it to generate_script (experiment Step 3).

Step 3: Run Baseline Evaluation

  1. Execute the evaluation command via Bash (within the auto-repair loop above)
  2. Capture all output
  3. Parse output for metrics:
    python3 ${CLAUDE_PLUGIN_ROOT}/scripts/parse_logs.py <output_file>
    
  4. Validate parse results: check parse_logs returned non-empty records. If empty, the format may be unrecognized — try forcing a format via the second positional argument (there is no --format flag): python3 ${CLAUDE_PLUGIN_ROOT}/scripts/parse_logs.py <output_file> kv (valid formats: json, csv, logging, tqdm, xgboost, hf_trainer, sb3, kv)
  5. If metrics aren't parseable automatically, read the output and extract them manually
  6. Multi-task evaluation (only when eval_tasks is non-empty). Baseline must use the exact same aggregation as every experiment, or the comparison denominator diverges. Extract every <primary_metric>_<task> key the eval output prints into metrics verbatim (flat, never nested), then compute the aggregates:
    python3 -c "
    import json, sys
    sys.path.insert(0, '${CLAUDE_PLUGIN_ROOT}/scripts')
    from result_analyzer import aggregate_task_metrics
    metrics = json.loads(sys.argv[1])
    out = aggregate_task_metrics(metrics, sys.argv[2], json.loads(sys.argv[3]), sys.argv[4] == 'true')
    print(json.dumps(out))
    " '<metrics_json>' '<primary_metric>' '<eval_tasks_json>' '<lower_is_better>'
    
    Merge the returned aggregates into metrics before Step 5 writes baseline.json — this sets the canonical <primary_metric> (mean across tasks) and <primary_metric>_worst, matching exactly what the experiment skill does. If warnings is non-empty, record "task_set_mismatch": true and append the warnings to baseline.json's notes the same way the experiment skill does.

Step 4: Profile Training

Framework-Specific Profiling

For non-iterative frameworks (scikit-learn, XGBoost without GPU, LightGBM without GPU):

  • Skip GPU memory profiling and throughput estimation below.
  • Measure total fit() wall-clock time and record as profiling.fit_duration_seconds in baseline.json.
  • Estimate experiment timeout from fit duration: read the model's configured iteration count (n_estimators, max_iter, num_boost_round) and the profiling iteration count. Compute estimated_timeout_seconds = fit_duration_seconds * (max_iterations_configured / profiling_iterations) * 2 (the × 2 margin accounts for slower HP configs). If iteration counts can't be determined, fall back to fit_duration_seconds * 10. Cap at 14400 (4 hours). Record as profiling.estimated_timeout_seconds in baseline.json.
  • Set profiling.throughput_samples_per_sec and profiling.estimated_max_batch_size to null.
  • If the framework supports GPU (XGBoost tree_method="gpu_hist", LightGBM device="gpu"), still run ${CLAUDE_PLUGIN_ROOT}/scripts/gpu_check.py.

For iterative frameworks (PyTorch, TensorFlow, JAX, Lightning, HuggingFace Trainer): proceed with the profiling below.

Run a short training session to measure GPU resource usage:

  1. GPU memory profiling:

    # Start a short training run (1-2 epochs or ~100 steps)
    # Then check GPU memory:
    python3 ${CLAUDE_PLUGIN_ROOT}/scripts/gpu_check.py
    # Remote GPUs (user_choices.remote): pass thresholds + host, else you profile the wrong machine
    python3 ${CLAUDE_PLUGIN_ROOT}/scripts/gpu_check.py 30 80 <remote.host>
    

    Remote GPUs (user_choices.remote): run the baseline itself through ${CLAUDE_PLUGIN_ROOT}/scripts/remote_train.sh exactly as experiments do (see the experiment skill's "Running on a remote GPU host"). A baseline measured on different hardware than the experiments is not a valid comparison point.

  2. Estimate throughput: parse the training log for step timing; calculate samples/second or steps/second

  3. Determine batch size limits:

    • Current batch size and memory usage
    • Estimate max batch size from available GPU memory
    • Note: a rough estimate; actual limits depend on model architecture
  4. Record wall-clock: record the baseline training run's wall-clock as profiling.training_duration_seconds in baseline.json — the source for the experiment hard timeout (baseline_training_time * 3).

Step 5: Write Baseline Results

Write <exp_root>/results/baseline.json:

{
  "exp_id": "baseline",
  "status": "completed",
  "config": {
    "lr": <current_lr>,
    "batch_size": <current_batch_size>,
    ...all current training params...
  },
  "metrics": {
    "<primary_metric>": <value>,
    ...all measured metrics (accuracy, f1, psnr, bleu, etc.)...
  },
  "code_branch": null,
  "code_proposal": null,
  "model_category": "<from dispatch: supervised|rl|generative, or null>",
  "profiling": {
    "gpu_memory_used_mib": <value>,
    "gpu_memory_total_mib": <value>,
    "throughput_samples_per_sec": <value>,
    "estimated_max_batch_size": <value>,
    "estimated_timeout_seconds": <value or null>,
    "training_duration_seconds": <value>,
    "sim_env": {}
  },
  "eval_command": "<command used>",
  "train_command": "<command used>",
  "notes": "Baseline evaluation - current model state"
}

Use the Write tool to create this file.

Nullable fields: for non-iterative frameworks (scikit-learn, XGBoost, LightGBM), profiling.throughput_samples_per_sec and profiling.estimated_max_batch_size will be null. Experiment must use estimated_timeout_seconds instead of throughput-based timeout.

profiling.sim_env: dict of headless-simulator env vars detected in Step 2.3 (e.g., {"MUJOCO_GL": "egl"}); {} when none apply.

New fields: model_category echoes the dispatch input into baseline.json so downstream phases (the Phase 7 pre-loop reads it as a fallback when args.model_category is absent) can recover it without pipeline state. profiling.training_duration_seconds is the baseline training wall-clock — the source for the experiment hard timeout baseline_training_time * 3. profiling.estimated_timeout_seconds is the direct per-experiment timeout estimate (tabular fit-based or RL timestep-based); experiment Step 1.1 reads it first.

Step 5.1: Validate Output

python3 ${CLAUDE_PLUGIN_ROOT}/scripts/schema_validator.py \
  <exp_root>/results/baseline.json baseline

If validation fails, fix and re-validate before proceeding.

Step 5.2: Validate Metric Keys

After schema validation passes, verify the metrics dict contains required keys:

  1. Check primary_metric: if the orchestrator specified primary_metric, verify metrics contains a matching key (case-insensitive). If not found, search for close matches (e.g., "val_accuracy" for "accuracy"). If a close match exists, log to dev_notes which key was used. If no match: log warning to error tracker with category: "config_error".

  2. Check divergence metric: if the orchestrator specified divergence_metric (default: "loss"), verify it exists in metrics. If not, check aliases: "train_loss", "val_loss", "total_loss", "nll_loss". If found under an alias, log which alias to dev_notes — the orchestrator should carry the alias forward as the divergence_metric value passed to the experiment agent (and to monitor-agent too, if that opt-in path is used). If not found at all: log warning — divergence monitoring may not work.

Step 6: Write Dev Notes

Append to <exp_root>/dev_notes.md:

## <date> — Baseline

- **Goal:** Establish baseline metrics for optimization
- [metric 1]: [value]
- [metric 2]: [value]
- GPU Memory: [used]/[total] MiB
- Throughput: [X] samples/sec
- Max batch size estimate: [Y]
- **Next:** Awaiting user direction on optimization approach

Output

Return to the orchestrator:

  • Path to baseline.json
  • Summary of baseline metrics
  • GPU profiling results
  • Any issues encountered

RL Baseline Evaluation

When model_category = "rl":

  1. Evaluation method: run N evaluation episodes (default: 100) with the current policy. Compute mean, std, min, max episode reward.
  2. Profiling: measure steps/second and episodes/hour. Set throughput_samples_per_sec = null. Record steps_per_second and episodes_per_hour in profiling.
  3. Timeout estimation: compute estimated_timeout_seconds = (total_timesteps / steps_per_second) * 2 (the × 2 margin mirrors the tabular estimate) and record it as profiling.estimated_timeout_seconds — the field experiment Step 1.1 reads first. Record the measured training wall-clock as profiling.training_duration_seconds.
  4. Config extraction: capture RL HPs: gamma, learning_rate, n_steps/buffer_size, batch_size, ent_coef, clip_range (PPO), tau (SAC/TD3).

Error Handling

  • Eval command fails: handled by the Step 2.1 Auto-Repair Loop (diagnose, retry up to 3 attempts); after all attempts fail, report the full error history to the orchestrator — the orchestrator's Phase 3 Failure Recovery table handles escalation, not a direct user prompt
  • No GPU available: run CPU-only baseline, note throughput estimates won't be representative
  • Metrics not parseable: show raw output, manually extract key numbers, note which metrics were found

Error Tracking

At the following points, log an error event using the error tracker:

When evaluation command fails:

python3 ${CLAUDE_PLUGIN_ROOT}/scripts/error_tracker.py <exp_root> log '{"category":"training_failure","severity":"critical","source":"baseline","message":"Baseline eval command failed: <error>","phase":3,"context":{"command":"<eval_command>","exit_code":<code>}}'

When metrics are not parseable from output:

python3 ${CLAUDE_PLUGIN_ROOT}/scripts/error_tracker.py <exp_root> log '{"category":"config_error","severity":"warning","source":"baseline","message":"Could not parse metrics from baseline output","phase":3,"context":{"output_preview":"<first 200 chars>"}}'

When GPU profiling fails:

python3 ${CLAUDE_PLUGIN_ROOT}/scripts/error_tracker.py <exp_root> log '{"category":"resource_error","severity":"info","source":"baseline","message":"GPU profiling failed — no GPU detected or nvidia-smi error","phase":3}'

Keep looking

Skills are one crate of 607,533. Ordering is by how many stacks a row turns up in, so the top of any crate is what has actually been picked rather than what has the most stars.