run-1 driver: original repo stage-2 on toy data
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266"""Run 1 — original SeerRay-Lab code, stage-2 toy-data training.
Clones SeerRay-Lab/Xiaomi-Lens-0, generates the toy dataset withexamples/train/make_toy_data.py (48 images, default seed 0), and trainsstage 2 from the SeerRay-Lab/Xiaomi-Lens-0 checkpoint using the protocolflags from scripts/train_stage2.sh.
Deviations from scripts/train_stage2.sh (documented in the README): - no DeepSpeed: single GPU, ZeRO-2 on one rank is equivalent to plain DDP - attn_implementation sdpa instead of flash_attention_2 (no kernel build) - logging_steps 1 instead of 5 (finer curves) - lm_loss_impl hf instead of the default fused_linear_ce (liger), so the LM loss is computed by the same HF reference path the PR implementation uses - group_by_modality_length false and seed 42 (protocol uses grouping), so both runs see identical batches in identical order for the curve overlay
After training, curves are read from the tensorboard event file, logged totrackio and pushed to hf.co/datasets/guarin/xiaomi-lens-train-repro underrun1/."""from __future__ import annotations
import jsonimport osimport shutilimport subprocessimport sysimport tarfileimport timeimport urllib.requestfrom pathlib import Path
WORK = Path(os.environ.get("WORK_DIR", "/work"))REPO = WORK / "Xiaomi-Lens-0"OUT = WORK / "out-run1"MODEL_PATH = "SeerRay-Lab/Xiaomi-Lens-0"HUB_REPO = "guarin/xiaomi-lens-train-repro"TRACKIO_PROJECT = "xiaomi-lens-stage2-repro"TRACKIO_SPACE = "guarin/xiaomi-lens-stage2-repro-trackio"NUM_IMAGES = 48SEED = 0
# Pins confirmed against the sandbox version check (2026-10-29): these are the# versions the original repo was tested with (requirements.txt), except# tensorboard/liger-kernel/trackio/huggingface_hub/pillow/numpy which are the# current latest stable releases.PINS = [ "torch==2.10.0", "torchvision==0.25.0", "transformers==5.4.0", "accelerate==1.13.0", "tensorboard==2.21.0", "liger-kernel==0.8.5", "trackio==0.44.0", "huggingface-hub>=1.5.0,<2.0", "pillow==13.0.0", "numpy==2.5.4",]
def sh(cmd: str, cwd: str | None = None) -> None: print(f"$ {cmd}", flush=True) subprocess.run(cmd, shell=True, check=True, cwd=cwd)
def install(specs: list[str]) -> None: uv = shutil.which("uv") if uv: sh(f"{uv} pip install --python {sys.executable} " + " ".join(f"'{s}'" for s in specs)) else: sh(f"{sys.executable} -m pip install " + " ".join(f"'{s}'" for s in specs))
def fetch_repo(dest: Path, short_sha: str) -> None: """Download a GitHub repo tarball (no git binary needed) and extract it.""" if dest.exists(): return dest.parent.mkdir(parents=True, exist_ok=True) for ref in (short_sha, "main"): url = f"https://github.com/SeerRay-Lab/Xiaomi-Lens-0/archive/{ref}.tar.gz" tarball = dest.parent / f"{dest.name}-{ref}.tar.gz" try: print(f"fetching {url}", flush=True) urllib.request.urlretrieve(url, tarball) break except Exception as exc: # noqa: BLE001 print(f"fetch failed ({exc}); trying next ref", flush=True) else: raise RuntimeError("could not download SeerRay-Lab/Xiaomi-Lens-0 tarball") with tarfile.open(tarball) as tar: tar.extractall(dest.parent) root = next(p for p in dest.parent.iterdir() if p.name.startswith(dest.name + "-") and p.is_dir()) root.rename(dest)
def train() -> None: cmd = " ".join( [ sys.executable, "train.py", f"--model_name_or_path {MODEL_PATH}", "--attn_implementation sdpa", "--bf16", "--data_config examples/train/stage2.yaml", "--max_pixels 4194304", "--min_pixels 65536", "--model_max_length 8192", "--group_by_modality_length false", "--seed 42", "--dataloader_num_workers 8", "--dataloader_persistent_workers true", "--dataloader_prefetch_factor 4", "--dataloader_drop_last true", "--unfreeze_all_parameters true", "--unfreeze_vision_tower true", "--unfreeze_vision_projection true", "--unfreeze_language_model_backbone true", "--unfreeze_language_model_head true", "--unfreeze_embed_tokens true", "--unfreeze_new_tokens false", "--unfreeze_mask_decoder true", "--lm_loss_weight 1.0", "--mask_loss_weight 1.0", "--mask_loss_chunk_size 8", "--lm_loss_impl hf", "--learning_rate 5e-6", "--weight_decay 0.0", "--warmup_steps 0.03", "--lr_scheduler_type cosine", "--num_train_epochs 1", "--per_device_train_batch_size 4", "--gradient_accumulation_steps 4", "--gradient_checkpointing true", f"--output_dir {OUT}", "--save_steps 2000", "--save_total_limit 2", "--logging_steps 1", "--report_to tensorboard", "--run_name run1-original", ] ) sh(cmd, cwd=str(REPO))
def read_curves() -> dict[str, list[tuple[int, float]]]: from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
event_files = sorted(OUT.rglob("events.out.tfevents.*")) if not event_files: raise RuntimeError(f"no tensorboard event files under {OUT}") print("event files:", [str(p.relative_to(OUT)) for p in event_files], flush=True) keep = {"loss", "lm_loss", "mask_loss", "learning_rate", "grad_norm", "epoch"} curves: dict[str, list[tuple[int, float]]] = {} for event_file in event_files: ea = EventAccumulator(str(event_file.parent)) ea.Reload() for tag in ea.Tags()["scalars"]: name = tag.split("/")[-1] if name in keep: curves.setdefault(name, []).extend((s.step, s.value) for s in ea.Scalars(tag)) if "loss" not in curves: raise RuntimeError(f"no loss series in tensorboard tags: {ea.Tags()['scalars']}") for series in curves.values(): series.sort(key=lambda p: p[0]) return curves
def log_to_trackio(curves: dict[str, list[tuple[int, float]]]) -> None: import trackio
try: trackio.init(project=TRACKIO_PROJECT, space_id=TRACKIO_SPACE, name="run1-original") except TypeError: trackio.init(project=TRACKIO_PROJECT, space_id=TRACKIO_SPACE) steps = sorted({s for series in curves.values() for s, _ in series}) last = {} for step in steps: point = {} for name, series in curves.items(): for s, v in series: if s == step: point[name] = v last[name] = v trackio.log(point, step=step) trackio.finish() print("trackio done; final:", json.dumps(last), flush=True)
def push_results(curves: dict[str, list[tuple[int, float]]]) -> None: from huggingface_hub import HfApi
api = HfApi() payload = {k: [[s, v] for s, v in series] for k, series in curves.items()} (OUT / "curves.json").write_text(json.dumps(payload, indent=2)) files = { "curves.json": "curves.json", "train_command.json": "train_command.json", } for local, remote in files.items(): path = OUT / local if path.exists(): api.upload_file( path_or_fileobj=path, path_in_repo=f"run1/{local}", repo_id=HUB_REPO, repo_type="dataset", ) print(f"pushed run1/{local}", flush=True) states = sorted(OUT.rglob("trainer_state.json")) if states: api.upload_file( path_or_fileobj=states[-1], path_in_repo="run1/trainer_state.json", repo_id=HUB_REPO, repo_type="dataset", ) print("pushed run1/trainer_state.json", flush=True) events = sorted(OUT.rglob("events.out.tfevents.*")) if events: api.upload_file( path_or_fileobj=events[0], path_in_repo=f"run1/{events[0].name}", repo_id=HUB_REPO, repo_type="dataset", ) print("pushed tensorboard events", flush=True)
def main() -> None: t0 = time.time() OUT.mkdir(parents=True, exist_ok=True) print(f"step 1: install pinned deps ({time.time() - t0:.0f}s)", flush=True) install(PINS)
print(f"step 2: clone repo ({time.time() - t0:.0f}s)", flush=True) fetch_repo(REPO, "9ecbee7") sh(f"{shutil.which('uv') or 'pip'} pip install --python {sys.executable} --no-deps -e {REPO}")
print(f"step 3: toy data ({time.time() - t0:.0f}s)", flush=True) sh( f"{sys.executable} examples/train/make_toy_data.py " f"--output examples/train/toy --num-images {NUM_IMAGES} --seed {SEED}", cwd=str(REPO), )
(OUT / "train_command.json").write_text( json.dumps({"model": MODEL_PATH, "protocol": "scripts/train_stage2.sh", "seed": SEED}, indent=2) )
print(f"step 4: training ({time.time() - t0:.0f}s)", flush=True) train()
print(f"step 5: curves ({time.time() - t0:.0f}s)", flush=True) curves = read_curves() print( "curve summary:", json.dumps({k: [series[0], series[-1]] for k, series in curves.items()}, default=str), flush=True, ) log_to_trackio(curves) push_results(curves) print(f"run 1 complete in {time.time() - t0:.0f}s", flush=True)
if __name__ == "__main__": main()run1_stage2.pyAdded+266