Datasets:
Download code/VLM_finetune/run_ablation_sequential_ft.py from hardware-fab/theia: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/datasets/hardware-fab/theia/resolve/main/code/VLM_finetune/run_ablation_sequential_ft.py
- Command line
-
hf download hf://datasets/hardware-fab/theia/code/VLM_finetune/run_ablation_sequential_ft.py
-
curl -L -o run_ablation_sequential_ft.py https://huggingface.co/datasets/hardware-fab/theia/resolve/main/code/VLM_finetune/run_ablation_sequential_ft.py
12.2 kB
| #!/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:])) | |