"""Launch LoRA training via ``accelerate`` with multi-GPU support.""" from __future__ import annotations import subprocess import sys import threading import urllib.request from pathlib import Path import torch from src.config import TrainingConfig from src.logging_utils import LogBuffer TRAIN_SCRIPT = "train_dreambooth_lora_flux.py" _TRAIN_SCRIPT_URL = ( "https://raw.githubusercontent.com/huggingface/diffusers" f"/main/examples/dreambooth/{TRAIN_SCRIPT}" ) def _ensure_training_script() -> Path: """Download the diffusers training script if it isn't already present.""" script = Path(TRAIN_SCRIPT) if script.exists(): return script urllib.request.urlretrieve(_TRAIN_SCRIPT_URL, script) return script def _gpu_count() -> int: """Return the number of CUDA devices visible to this process.""" if torch.cuda.is_available(): return torch.cuda.device_count() return 0 def _stream_pipe(pipe, buf: LogBuffer) -> None: """Read lines from *pipe* and push them into *buf*.""" try: for raw in iter(pipe.readline, ""): line = raw.rstrip("\n") if line: buf.append(line) finally: pipe.close() def launch_training( config: TrainingConfig, log_buffer: LogBuffer, ) -> subprocess.Popen: """Start an ``accelerate launch`` subprocess and stream its output. Returns the ``Popen`` handle so callers can poll / wait on it. """ script_path = _ensure_training_script() log_buffer.append(f"[runner] Training script ready: {script_path}") num_gpus = config.num_processes if config.num_processes > 0 else _gpu_count() cmd: list[str] = [ sys.executable, "-m", "accelerate.commands.launch", ] if num_gpus >= 2: cmd += ["--multi_gpu", f"--num_processes={num_gpus}"] elif num_gpus == 1: cmd += ["--num_processes=1"] # num_gpus == 0: no GPU flags, accelerate defaults to CPU cmd += [ f"--mixed_precision={config.mixed_precision}", str(script_path), *config.to_cli_args(), ] log_buffer.append(f"[runner] Starting training with {num_gpus} GPU(s)") log_buffer.append(f"[runner] Command: {' '.join(cmd)}") proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, ) reader = threading.Thread( target=_stream_pipe, args=(proc.stdout, log_buffer), daemon=True ) reader.start() return proc def wait_for_training(proc: subprocess.Popen, log_buffer: LogBuffer) -> int: """Block until *proc* finishes, returning its exit code.""" returncode = proc.wait() if returncode == 0: log_buffer.append("[runner] Training completed successfully.") else: log_buffer.append(f"[runner] Training failed with exit code {returncode}.") return returncode