A straightforward method for training your LLM, from downloading data to generating text.
fix(ui): job status and stop work on Windows and macOS
FareedKhan-deve6b68db8c56d
diff --git a/ui/jobs.py b/ui/jobs.pyindex 7d3343a..cc878d6 100644--- a/ui/jobs.py+++ b/ui/jobs.py@@ -19,7 +19,7 @@ import timefrom ui.stages import LOG_DIR, REPO_ROOTJOB_DIR = os.path.join(LOG_DIR, "ui_jobs")-_TORCHRUN = os.path.join(os.path.dirname(sys.executable), "torchrun")+IS_WINDOWS = os.name == "nt"def _ensure_job_dir() -> None:@@ -50,32 +50,46 @@ def read_registry(job_id: str) -> dict | None:return None+def _alive_windows(pid: int) -> bool:+ """Ask Windows whether ``pid`` is still running (never os.kill: on Windows it terminates)."""+ import ctypes+ from ctypes import wintypes++ PROCESS_QUERY_LIMITED_INFORMATION, STILL_ACTIVE = 0x1000, 259+ kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]+ handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)+ if not handle:+ return False+ try:+ code = wintypes.DWORD()+ return bool(kernel32.GetExitCodeProcess(handle, ctypes.byref(code))) and code.value == STILL_ACTIVE+ finally:+ kernel32.CloseHandle(handle)++def _alive(pid: int) -> bool:+ if IS_WINDOWS:+ return _alive_windows(pid)try:- os.kill(pid, 0)+ os.kill(pid, 0) # signal 0 only checks that the process exists (POSIX)except OSError:return False- # A finished detached child lingers as a zombie (parent = this process) and still- # passes kill(pid, 0). Treat zombies as dead and best-effort reap them.+ # A finished child of this process lingers as a zombie and still passes kill(pid, 0).+ # waitpid reaps it and tells us it is done. Jobs started by an earlier Streamlit process+ # are not our children, and kill(pid, 0) above is the answer for them.try:- with open(f"/proc/{pid}/stat") as f:- state = f.read().rsplit(") ", 1)[1].split(" ", 1)[0]- if state == "Z":- try:- os.waitpid(pid, os.WNOHANG)- except OSError:- pass- return False- except (FileNotFoundError, IndexError):- return False- return True+ done_pid, _ = os.waitpid(pid, os.WNOHANG)+ return done_pid != pid+ except ChildProcessError:+ return Truedef build_argv(script: str, config_json: str, nproc: int, multi_gpu: bool, extra: list[str] | None = None) -> list[str]:"""Construct the exact command (torchrun for multi-GPU, else python)."""base = [script, "--config", config_json] + (extra or [])if multi_gpu and nproc > 1:- return [_TORCHRUN, "--standalone", f"--nproc_per_node={nproc}", *base]+ # `python -m torch.distributed.run` is torchrun, and works on every OS and venv layout.+ return [sys.executable, "-m", "torch.distributed.run", "--standalone", f"--nproc_per_node={nproc}", *base]return [sys.executable, *base]@@ -86,10 +100,10 @@ def launch(job_id: str, argv: list[str], *, kind: str = "cpu") -> dict:env = {**os.environ, "PYTHONPATH": REPO_ROOT}env.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")logf = open(log_path, "wb")- proc = subprocess.Popen(- argv, cwd=REPO_ROOT, env=env, stdout=logf, stderr=subprocess.STDOUT,- start_new_session=True, # own process group -> killpg reaches all torchrun ranks- )+ # Own process group, so stop() reaches every torchrun rank.+ group = ({"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} if IS_WINDOWS+ else {"start_new_session": True})+ proc = subprocess.Popen(argv, cwd=REPO_ROOT, env=env, stdout=logf, stderr=subprocess.STDOUT, **group)rec = dict(job_id=job_id, pid=proc.pid, cmd=argv, log=log_path, kind=kind,started=time.time(), status="running")_write_registry(job_id, rec)@@ -114,10 +128,21 @@ def stop(job_id: str) -> bool:rec = read_registry(job_id)if not rec:return False- try:- os.killpg(os.getpgid(rec["pid"]), signal.SIGTERM)- except OSError:- return False+ if IS_WINDOWS:+ # /T stops the whole process tree (every torchrun rank). Its exit code can report a+ # child that already exited, so success means "the job is gone", checked below.+ subprocess.run(["taskkill", "/PID", str(rec["pid"]), "/T", "/F"], capture_output=True)+ for _ in range(20):+ if not _alive(rec["pid"]):+ break+ time.sleep(0.1)+ else:+ return False+ else:+ try:+ os.killpg(os.getpgid(rec["pid"]), signal.SIGTERM)+ except OSError:+ return Falserec["status"] = "stopped"_write_registry(job_id, rec)return Truediff --git a/ui/pages/8_Evaluate.py b/ui/pages/8_Evaluate.pyindex abcb4f4..0792d5f 100644--- a/ui/pages/8_Evaluate.py+++ b/ui/pages/8_Evaluate.py@@ -8,6 +8,7 @@ import osimport streamlit as stfrom ui import theme+from src.device import resolve_devicefrom ui.stages import CKPT_DIRtheme.setup_page("Evaluate", "📊")@@ -22,7 +23,7 @@ ckpt = st.selectbox("Checkpoint", ckpts, index=len(ckpts) - 1)c1, c2, c3 = st.columns(3)limit = c1.slider("Num questions", 5, 200, 20, step=5)max_new = c2.slider("Max new tokens", 64, 400, 256, step=32)-device = c3.selectbox("Device", ["cuda", "cpu"], index=0)+device = resolve_device(c3.selectbox("Device", ["auto", "cpu", "cuda", "mps"], index=0))if st.button("▶️ Run GSM8K eval", type="primary"):with st.spinner(f"Generating + scoring {limit} GSM8K problems on {device} …"):diff --git a/ui/pages/9_Chat.py b/ui/pages/9_Chat.pyindex 0480589..1aa1bc0 100644--- a/ui/pages/9_Chat.py+++ b/ui/pages/9_Chat.py@@ -8,6 +8,7 @@ import osimport streamlit as stfrom ui import theme+from src.device import resolve_devicefrom ui.stages import CKPT_DIRtheme.setup_page("Chat", "💬")@@ -21,7 +22,7 @@ if not ckpts:with st.sidebar:st.header("Generation")ckpt = st.selectbox("Checkpoint", ckpts, index=len(ckpts) - 1)- device = st.selectbox("Device", ["cuda", "cpu"], index=0)+ device = resolve_device(st.selectbox("Device", ["auto", "cpu", "cuda", "mps"], index=0))raw = st.toggle("Raw mode (base continuation, no chat template)", value=False)greedy = st.toggle("Greedy (deterministic)", value=False)temperature = st.slider("Temperature", 0.1, 1.5, 0.8, 0.05, disabled=greedy)