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
npx -y skills add ChuaHanChong/ml-optimizer --skill baselineAssembled 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 theexp_rootdispatch 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 commandprepared_val_path(optional): same for validation datamodel_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 ofmodel_category.eval_tasks(optional): list of task/environment names from Phase 0user_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 throughremote_train.shso it shares hardware with the experiments it will be compared against.
Step 1: Identify Evaluation Command
Search the project for evaluation scripts:
-
Use Glob for candidates:
**/eval*.py,**/test*.py,**/infer*.py,**/validate*.py**/scripts/eval*,**/scripts/test*Makefile,**/*.sh(look for eval targets)
-
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 andself.log()calls. Metrics may be in TensorBoard logs (lightning_logs/) — parse with${CLAUDE_PLUGIN_ROOT}/scripts/parse_logs.py - HuggingFace Trainer:
compute_metricspassed toTrainer. Metrics log toruns/oroutput_dir. Usetrainer.evaluate()as eval command - TF/Keras:
model.evaluate()or custom callbacks. Metrics may be inCSVLoggeroutput or TensorBoard
- Functions named
-
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_metrickeyword 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 - Set
Step 1.1: Apply Prepared Data Paths (If Applicable)
If the orchestrator passed prepared_train_path or prepared_val_path:
- Identify how the training command references data paths (CLI args like
--data_dir,--train_path,--val_path, or config file entries) - Substitute the prepared paths into the training/eval commands before running
- If paths are in a config file, create a modified copy at
<exp_root>/logs/baseline/config.yamlwith updated paths - 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:
- Attempt 1: run the command normally
- 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, retryFileNotFoundError→ check the path exists, fix references, retryCUDA out of memory→ reduce batch size 50% in the command, retryRuntimeError: CUDA→ tryCUDA_VISIBLE_DEVICES=0, retryPermissionError→ fix permissions, retrySyntaxError/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
- 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
- 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
- Log with
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):
- Wrap the training command with
timeout:
Never wrap withtimeout --signal=SIGTERM --kill-after=60 <fixed_time_budget> <train_command>conda run -n <env> <cmd>— it drops stdout on SIGTERM (0-byte log). Invoke<conda_prefix>/bin/python3 -udirectly, withPYTHONUNBUFFERED=1. - Set epochs high enough that timeout is the binding constraint (e.g.,
--epochs 200) - Exit code 124 (timeout reached) is treated as success — training completed its time budget normally
- Checkpoint pre-flight: verify the training script saves checkpoints periodically (look for
save_freq,checkpoint_interval,ModelCheckpoint, periodicsave_checkpointcalls) or supports a framework-native time limit (Lightning--max_time, HFTrainingArguments). If NEITHER exists, the SIGTERM kill leaves no final checkpoint — warn in dev_notes and record"eval_checkpoint_missing": truein the baseline notes instead of scoring a stale/initial checkpoint.
If fixed_epoch_budget is set (integer):
- Override the epoch count in the training command (e.g., replace
--epochs 2with--epochs <fixed_epoch_budget>) - If there is no epochs flag, add one appropriate to the framework
If fixed_step_budget is set (integer — environment timesteps, RL):
- Map it to the framework's timestep flag instead of an epoch count — e.g., SB3
--total_timesteps <fixed_step_budget>(orlearn(total_timesteps=...)), rsl_rl--max_iterations <fixed_step_budget / (num_envs * num_steps_per_env)> - 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 import | Env vars |
|---|---|
mujoco, dm_control | MUJOCO_GL=egl, PYOPENGL_PLATFORM=egl |
habitat_sim | MAGNUM_LOG=quiet, HABITAT_SIM_LOG=quiet |
pybullet | (none — headless by default via DIRECT mode) |
omni / isaacsim / isaaclab | prefer the script's --headless CLI flag when exposed; otherwise HEADLESS=1 |
- Re-run
python3 ${CLAUDE_PLUGIN_ROOT}/scripts/prerequisites_check.py scan-imports <project_root>—prerequisites.jsondoes not persist the{stdlib, third_party, local}import classification, onlyenvironment.manual_install_requiredandenvironment.packages_installed, so the scan must be re-run rather than read back. - Collect the applicable env vars, apply them when running the baseline training/profiling commands, and record them in
baseline.jsonunderprofiling.sim_env(a dict of env var name → value;{}when none apply). - If baseline training fails with a GL/EGL/display error (
GLFWError,cannot connect to X server,EGL), addMUJOCO_GL=egl/PYOPENGL_PLATFORM=egland 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
- Execute the evaluation command via Bash (within the auto-repair loop above)
- Capture all output
- Parse output for metrics:
python3 ${CLAUDE_PLUGIN_ROOT}/scripts/parse_logs.py <output_file> - Validate parse results: check
parse_logsreturned non-empty records. If empty, the format may be unrecognized — try forcing a format via the second positional argument (there is no--formatflag):python3 ${CLAUDE_PLUGIN_ROOT}/scripts/parse_logs.py <output_file> kv(valid formats:json,csv,logging,tqdm,xgboost,hf_trainer,sb3,kv) - If metrics aren't parseable automatically, read the output and extract them manually
- Multi-task evaluation (only when
eval_tasksis 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 intometricsverbatim (flat, never nested), then compute the aggregates:
Merge the returnedpython3 -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>'aggregatesintometricsbefore Step 5 writesbaseline.json— this sets the canonical<primary_metric>(mean across tasks) and<primary_metric>_worst, matching exactly what the experiment skill does. Ifwarningsis non-empty, record"task_set_mismatch": trueand append the warnings to baseline.json'snotesthe 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 asprofiling.fit_duration_secondsin 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. Computeestimated_timeout_seconds = fit_duration_seconds * (max_iterations_configured / profiling_iterations) * 2(the× 2margin accounts for slower HP configs). If iteration counts can't be determined, fall back tofit_duration_seconds * 10. Cap at 14400 (4 hours). Record asprofiling.estimated_timeout_secondsin baseline.json. - Set
profiling.throughput_samples_per_secandprofiling.estimated_max_batch_sizetonull. - If the framework supports GPU (XGBoost
tree_method="gpu_hist", LightGBMdevice="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:
-
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.shexactly 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. -
Estimate throughput: parse the training log for step timing; calculate samples/second or steps/second
-
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
-
Record wall-clock: record the baseline training run's wall-clock as
profiling.training_duration_secondsin 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:
-
Check primary_metric: if the orchestrator specified
primary_metric, verifymetricscontains 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 withcategory: "config_error". -
Check divergence metric: if the orchestrator specified
divergence_metric(default:"loss"), verify it exists inmetrics. 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 thedivergence_metricvalue 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":
- Evaluation method: run N evaluation episodes (default: 100) with the current policy. Compute mean, std, min, max episode reward.
- Profiling: measure steps/second and episodes/hour. Set
throughput_samples_per_sec = null. Recordsteps_per_secondandepisodes_per_hourin profiling. - Timeout estimation: compute
estimated_timeout_seconds = (total_timesteps / steps_per_second) * 2(the× 2margin mirrors the tabular estimate) and record it asprofiling.estimated_timeout_seconds— the field experiment Step 1.1 reads first. Record the measured training wall-clock asprofiling.training_duration_seconds. - 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}'