Datasets:
File size: 12,151 Bytes
148072e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 | #!/usr/bin/env python3
"""Sequential launcher for ablation-study LoRA finetuning runs.
Discovers dataset splits under:
/users/<USER>/ablation_study_dataset/ablation_splits/<task>/<perc_xxx>/{train,validation,test}/*.json
Runs:
python /users/<USER>/VLM_finetune/FT.py --train_json ... --val_json ... --output_dir ...
Outputs are written to:
/mydata/<USER>/ablation_study_outputs/finetune_lora/<task>/<perc_xxx>/
Example:
python /users/<USER>/run_ablation_sequential_ft.py --percs perc_025,perc_050 -- --num_train_epochs 1 --use_deepspeed --master_port 0
# Short-hand selectors (recommended)
python /users/<USER>/run_ablation_sequential_ft.py --task a1 --perc 75 -- --master_port 0
python /users/<USER>/run_ablation_sequential_ft.py --tasks a1,b1 --percs 25,50,75 -- --master_port 0
Notes:
- Pass any additional FT.py args after a standalone "--".
- By default, skips runs whose output already contains adapter_config.json.
"""
from __future__ import annotations
import argparse
import datetime as _dt
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Iterable
DEFAULT_SPLITS_ROOT = Path("/users/<USER>/ablation_study_dataset/ablation_splits")
DEFAULT_OUTPUT_ROOT = Path("/mydata/<USER>/ablation_study_outputs/finetune_lora")
DEFAULT_FT_SCRIPT = Path("/users/<USER>/VLM_finetune/FT.py")
# Force HF cache into project filesystem (avoid writing to $HOME)
DEFAULT_HF_HOME = Path("/mydata/<USER>/VLM_cache")
# This script is intentionally lightweight:
# - It does NOT implement training itself.
# - It only discovers split JSONs and launches FT.py in a subprocess for each run.
#
# The main ergonomics it provides:
# - easy task/percentage filtering (with short-hand tokens like "a1" or "25")
# - consistent output folder layout
# - per-run log capture (stdout+stderr -> log file)
def _parse_csv(value: str | None) -> list[str] | None:
if value is None:
return None
items = [v.strip() for v in value.split(",") if v.strip()]
return items or None
def _normalize_task_token(token: str) -> str:
t = token.strip()
if not t:
raise ValueError("Empty task token")
if t.startswith("task_"):
return t
return f"task_{t}"
def _normalize_perc_token(token: str) -> str:
t = token.strip()
if not t:
raise ValueError("Empty perc token")
if t.startswith("perc_"):
return t
# Accept plain numbers like 25 or 050
if t.isdigit():
return f"perc_{int(t):03d}"
raise ValueError(f"Unrecognized perc token: {token!r} (expected e.g. 25 or perc_025)")
def _normalize_task_filters(values: list[str] | None) -> list[str] | None:
if not values:
return None
out: list[str] = []
for v in values:
for piece in v.split(","):
piece = piece.strip()
if not piece:
continue
out.append(_normalize_task_token(piece))
return sorted(set(out)) or None
def _normalize_perc_filters(values: list[str] | None) -> list[str] | None:
if not values:
return None
out: list[str] = []
for v in values:
for piece in v.split(","):
piece = piece.strip()
if not piece:
continue
out.append(_normalize_perc_token(piece))
# Preserve the user-specified order (first occurrence wins).
seen: set[str] = set()
ordered_unique: list[str] = []
for p in out:
if p in seen:
continue
seen.add(p)
ordered_unique.append(p)
return ordered_unique or None
def _perc_key(name: str) -> int:
m = re.search(r"perc_(\d+)", name)
return int(m.group(1)) if m else 10**9
def _find_single_json(dir_path: Path) -> Path:
if not dir_path.exists():
raise FileNotFoundError(f"Missing directory: {dir_path}")
candidates = sorted(p for p in dir_path.glob("*.json") if p.is_file())
if len(candidates) != 1:
raise RuntimeError(f"Expected exactly 1 .json in {dir_path}, found {len(candidates)}: {candidates}")
return candidates[0]
def _is_run_done(out_dir: Path) -> bool:
"""Heuristic for a completed LoRA adapter output.
FT.py writes LoRA adapters into output_dir; common artifacts include:
- adapter_config.json
- adapter_model.safetensors
- trainer_state.json
- checkpoint-* (optional)
"""
if not out_dir.exists():
return False
if (out_dir / "adapter_config.json").exists():
return True
if (out_dir / "adapter_model.safetensors").exists():
return True
if (out_dir / "trainer_state.json").exists():
return True
if any(out_dir.glob("checkpoint-*")):
return True
return False
def _iter_runs(
splits_root: Path,
tasks_filter: list[str] | None,
percs_filter: list[str] | None,
) -> Iterable[tuple[str, str, Path, Path]]:
# Yields (task_dir_name, perc_dir_name, train_json_path, val_json_path).
# Test JSONs are not used by training here (evaluation is a separate script).
if not splits_root.exists():
raise FileNotFoundError(f"splits_root not found: {splits_root}")
task_dirs = sorted(p for p in splits_root.iterdir() if p.is_dir())
for task_dir in task_dirs:
task = task_dir.name
if tasks_filter is not None and task not in tasks_filter:
continue
perc_dir_map = {p.name: p for p in task_dir.iterdir() if p.is_dir()}
if percs_filter is None:
perc_dirs = sorted(perc_dir_map.values(), key=lambda p: _perc_key(p.name))
else:
perc_dirs = []
for perc_name in percs_filter:
perc_path = perc_dir_map.get(perc_name)
if perc_path is None:
raise FileNotFoundError(f"Percentage split not found: {task_dir / perc_name}")
perc_dirs.append(perc_path)
for perc_dir in perc_dirs:
perc = perc_dir.name
train_json = _find_single_json(perc_dir / "train")
val_json = _find_single_json(perc_dir / "validation")
yield task, perc, train_json, val_json
def _tee_run(cmd: list[str], cwd: Path | None, log_path: Path, env: dict[str, str] | None = None) -> int:
# Run a subprocess and stream output to BOTH:
# - the console (so you can monitor progress)
# - a log file under the output directory (for later inspection)
log_path.parent.mkdir(parents=True, exist_ok=True)
with log_path.open("w", encoding="utf-8") as logf:
logf.write("COMMAND:\n")
logf.write(" ".join(cmd) + "\n\n")
logf.flush()
p = subprocess.Popen(
cmd,
cwd=str(cwd) if cwd else None,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
)
assert p.stdout is not None
for line in p.stdout:
sys.stdout.write(line)
sys.stdout.flush()
logf.write(line)
return int(p.wait())
def main(argv: list[str]) -> int:
# CLI entrypoint:
# - Discover all requested (task, perc) split folders.
# - Optionally print planned runs (--dry_run).
# - Launch FT.py sequentially for each run, stopping on first failure.
parser = argparse.ArgumentParser(description="Sequential ablation-study finetune launcher")
parser.add_argument("--splits_root", type=Path, default=DEFAULT_SPLITS_ROOT)
parser.add_argument("--output_root", type=Path, default=DEFAULT_OUTPUT_ROOT)
parser.add_argument("--ft_script", type=Path, default=DEFAULT_FT_SCRIPT)
parser.add_argument(
"--hf_home",
type=Path,
default=DEFAULT_HF_HOME,
help="Set HF_HOME for the finetuning subprocess (HuggingFace cache location)",
)
# Task selection
parser.add_argument(
"--task",
action="append",
default=None,
help="Task short-name or folder name (e.g. a1 or task_a1). Can be repeated.",
)
parser.add_argument(
"--tasks",
type=str,
default=None,
help="Comma-separated tasks (e.g. a1,b1 or task_a1,task_b1). Default: all.",
)
parser.add_argument(
"--perc",
action="append",
default=None,
help="Dataset percentage (e.g. 25 or perc_025). Can be repeated.",
)
parser.add_argument(
"--percs",
type=str,
default=None,
help="Comma-separated percentages (e.g. 25,50,75 or perc_025,perc_050). Default: all.",
)
parser.add_argument("--dry_run", action="store_true", help="Print planned runs without launching training")
parser.add_argument(
"--overwrite",
action="store_true",
help="If set, delete existing output dirs before running",
)
parser.add_argument(
"--skip_if_done",
action="store_true",
default=True,
help="Skip a run if adapter_config.json already exists in output (default: true)",
)
# Everything after `--` is forwarded directly to FT.py.
# This keeps this launcher stable even as training arguments evolve.
args, ft_extra = parser.parse_known_args(argv)
task_inputs: list[str] | None = None
if args.task:
task_inputs = list(args.task)
if args.tasks:
task_inputs = (task_inputs or []) + [args.tasks]
perc_inputs: list[str] | None = None
if args.perc:
perc_inputs = list(args.perc)
if args.percs:
perc_inputs = (perc_inputs or []) + [args.percs]
tasks_filter = _normalize_task_filters(task_inputs)
percs_filter = _normalize_perc_filters(perc_inputs)
ft_script = args.ft_script.resolve()
if not ft_script.exists():
raise FileNotFoundError(f"FT script not found: {ft_script}")
runs = list(_iter_runs(args.splits_root.resolve(), tasks_filter, percs_filter))
if not runs:
print("No runs matched your filters.")
return 2
print(f"Planned runs: {len(runs)}")
for i, (task, perc, train_json, val_json) in enumerate(runs, start=1):
out_dir = (args.output_root / task / perc).resolve()
print(f"[{i}/{len(runs)}] {task}/{perc}")
print(f" train: {train_json}")
print(f" val: {val_json}")
print(f" out: {out_dir}")
if args.dry_run:
print("Dry-run: not launching training.")
return 0
args.output_root.mkdir(parents=True, exist_ok=True)
args.hf_home.mkdir(parents=True, exist_ok=True)
for i, (task, perc, train_json, val_json) in enumerate(runs, start=1):
out_dir = (args.output_root / task / perc).resolve()
done = _is_run_done(out_dir)
if out_dir.exists() and args.overwrite:
print(f"[{i}/{len(runs)}] Removing existing output dir: {out_dir}")
shutil.rmtree(out_dir)
if args.skip_if_done and done:
print(f"[{i}/{len(runs)}] Skipping (already done): {task}/{perc}")
continue
out_dir.mkdir(parents=True, exist_ok=True)
timestamp = _dt.datetime.now().strftime("%Y%m%d_%H%M%S")
log_path = out_dir / f"ft_{task}_{perc}_{timestamp}.log"
# FT.py is invoked with the required dataset paths and output_dir.
# Additional flags (e.g., epochs, deepspeed config) are appended from ft_extra.
cmd = [
sys.executable,
str(ft_script),
"--train_json",
str(train_json),
"--val_json",
str(val_json),
"--output_dir",
str(out_dir),
]
if ft_extra:
cmd.extend(ft_extra)
print(f"\n[{i}/{len(runs)}] Launching: {task}/{perc}")
print(f"Log: {log_path}")
env = os.environ.copy()
env["HF_HOME"] = str(args.hf_home.resolve())
rc = _tee_run(cmd, cwd=None, log_path=log_path, env=env)
if rc != 0:
print(f"[ERROR] Run failed for {task}/{perc} (exit code {rc}). Stopping.")
return rc
print("All requested runs completed.")
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))
|