Spaces:
Running
Running
Download space_app.py from Banafo/KrokoMusci-OpenASR: direct link, hf CLI and curl.
- Browser
- Download file 8.11 kB
-
https://huggingface.co/spaces/Banafo/KrokoMusci-OpenASR/resolve/main/space_app.py
- Command line
-
hf download hf://spaces/Banafo/KrokoMusci-OpenASR/space_app.py
-
curl -L -o space_app.py https://huggingface.co/spaces/Banafo/KrokoMusci-OpenASR/resolve/main/space_app.py
8.11 kB
| """Serve benchmark progress and supervise a single configured H200 run.""" | |
| from datetime import datetime, timezone | |
| from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer | |
| import json | |
| import os | |
| from pathlib import Path | |
| import re | |
| import signal | |
| import subprocess | |
| from threading import Event, Thread | |
| import time | |
| from urllib.parse import urlsplit | |
| APP = Path(__file__).resolve().parent | |
| RESULTS = Path("/results") | |
| TIMEOUT_SECONDS = 90 * 60 | |
| RUN_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,100}") | |
| def now(): | |
| return datetime.now(timezone.utc).isoformat() | |
| def configured_run(): | |
| value = os.environ.get("KM_RESULTS") | |
| if not value: | |
| return None | |
| path = Path(value) | |
| if (path.parent != RESULTS or value != str(path) or not RUN_ID.fullmatch(path.name) | |
| or path.name.endswith((".claim", ".lifecycle.json"))): | |
| raise ValueError("KM_RESULTS must name a run directly inside /results") | |
| return path | |
| def read_json(path): | |
| if path.is_symlink() or path.parent.is_symlink(): | |
| return None | |
| try: | |
| data = json.loads(path.read_bytes()) | |
| except (OSError, UnicodeError, ValueError): | |
| return None | |
| return data if isinstance(data, dict) else None | |
| def write_json(path, data): | |
| temporary = path.with_suffix(".tmp") | |
| temporary.write_text(json.dumps(data, sort_keys=True) + "\n", encoding="utf-8") | |
| temporary.replace(path) | |
| def single_h200(): | |
| try: | |
| result = subprocess.run( | |
| ["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], | |
| check=True, capture_output=True, text=True, timeout=5, | |
| ) | |
| except (OSError, subprocess.SubprocessError): | |
| return False | |
| cards = result.stdout.strip().splitlines() | |
| return len(cards) == 1 and re.fullmatch(r"NVIDIA H200(?:\s+.*)?", cards[0].strip()) is not None | |
| def results_mounted(): | |
| if RESULTS.is_mount(): | |
| return True | |
| try: | |
| with Path("/proc/self/mountinfo").open() as mounts: | |
| # is_mount can miss same-device bind mounts on Linux. | |
| return any(line.split(maxsplit=5)[4] == str(RESULTS) for line in mounts) | |
| except OSError: | |
| return False | |
| def signal_group(process, sig): | |
| try: | |
| os.killpg(process.pid, sig) | |
| except ProcessLookupError: | |
| return False | |
| return True | |
| def stop_process(process): | |
| if signal_group(process, signal.SIGTERM): | |
| deadline = time.monotonic() + 10 | |
| while time.monotonic() < deadline: | |
| process.poll() | |
| if not signal_group(process, 0): | |
| break | |
| time.sleep(0.25) | |
| signal_group(process, signal.SIGKILL) | |
| process.wait() | |
| class Benchmark: | |
| def __init__(self, stop): | |
| self.stop = stop | |
| self.state = {"state": "starting"} | |
| try: | |
| self.directory = configured_run() | |
| except ValueError: | |
| self.directory = None | |
| self.state = {"state": "invalid_run_configuration"} | |
| if self.directory: | |
| self.claim = RESULTS / f"{self.directory.name}.claim" | |
| self.lifecycle = RESULTS / f"{self.directory.name}.lifecycle.json" | |
| def status(self): | |
| if not self.directory: | |
| return {"lifecycle": self.state, "benchmark": None} | |
| return {"run_id": self.directory.name, | |
| "lifecycle": read_json(self.lifecycle) or self.state, | |
| "benchmark": read_json(self.directory / "status.json")} | |
| def summary(self): | |
| return read_json(self.directory / "summary.json") if self.directory else None | |
| def run(self): | |
| if not self.directory: | |
| if self.state["state"] == "starting": | |
| self.state = {"state": "no_run_configured"} | |
| return | |
| if any(os.path.lexists(path) for path in (self.directory, self.claim, self.lifecycle)): | |
| self.state = {"state": "previous_run"} | |
| return | |
| if not single_h200(): | |
| self.state = {"state": "waiting_for_one_h200"} | |
| return | |
| if not results_mounted(): | |
| self.state = {"state": "results_mount_unavailable"} | |
| return | |
| if self.stop.is_set(): | |
| return | |
| process = None | |
| claimed = False | |
| state = {"state": "running", "started_at": now()} | |
| try: | |
| # A separate immutable marker prevents automatic retries after a | |
| # restart, including a crash before the evaluator creates its directory. | |
| try: | |
| with self.claim.open("x", encoding="utf-8") as marker: | |
| claimed = True | |
| marker.write(state["started_at"] + "\n") | |
| except FileExistsError: | |
| self.state = {"state": "previous_run"} | |
| return | |
| write_json(self.lifecycle, state) | |
| if self.stop.is_set(): | |
| state.update(state="interrupted") | |
| else: | |
| process = subprocess.Popen( | |
| ["bash", str(APP / "job.sh")], cwd=APP, stdin=subprocess.DEVNULL, | |
| start_new_session=True, | |
| ) | |
| deadline = time.monotonic() + TIMEOUT_SECONDS | |
| while (code := process.poll()) is None: | |
| remaining = deadline - time.monotonic() | |
| if remaining <= 0 or self.stop.wait(min(1, remaining)): | |
| state.update(state="interrupted" if self.stop.is_set() else "timed_out") | |
| stop_process(process) | |
| break | |
| state["exit_code"] = process.returncode | |
| if state["state"] == "running": | |
| complete = code == 0 and (self.summary() or {}).get("complete") is True | |
| state.update(state="complete" if complete else "failed") | |
| except OSError as error: | |
| state.update(state="failed", error_type=type(error).__name__) | |
| if process is not None and process.poll() is None: | |
| stop_process(process) | |
| state["finished_at"] = now() | |
| self.state = state | |
| try: | |
| if claimed: | |
| write_json(self.lifecycle, state) | |
| except OSError: | |
| print("Benchmark lifecycle could not be saved", flush=True) | |
| class Handler(BaseHTTPRequestHandler): | |
| def respond(self, status, content_type, data): | |
| self.send_response(status) | |
| self.send_header("Content-Type", content_type) | |
| self.send_header("Content-Length", str(len(data))) | |
| self.send_header("Cache-Control", "no-store") | |
| self.send_header("X-Content-Type-Options", "nosniff") | |
| self.end_headers() | |
| if self.command != "HEAD": | |
| self.wfile.write(data) | |
| def json_response(self, status, value): | |
| self.respond(status, "application/json; charset=utf-8", json.dumps(value).encode("utf-8")) | |
| def do_GET(self): | |
| route = urlsplit(self.path).path | |
| if route == "/": | |
| self.respond(200, "text/html; charset=utf-8", (APP / "public/index.html").read_bytes()) | |
| elif route == "/api/status": | |
| self.json_response(200, self.server.benchmark.status()) | |
| elif route == "/api/summary": | |
| summary = self.server.benchmark.summary() | |
| self.json_response(200 if summary is not None else 404, summary or {}) | |
| else: | |
| self.json_response(404, {"error": "not_found"}) | |
| do_HEAD = do_GET | |
| def log_message(self, *_): | |
| # Request URLs may contain sensitive query parameters. | |
| pass | |
| def main(): | |
| stop = Event() | |
| benchmark = Benchmark(stop) | |
| with ThreadingHTTPServer(("0.0.0.0", 7860), Handler) as server: | |
| server.benchmark = benchmark | |
| server.timeout = 0.5 | |
| for signum in (signal.SIGINT, signal.SIGTERM): | |
| signal.signal(signum, lambda *_: stop.set()) | |
| worker = Thread(target=benchmark.run, name="benchmark") | |
| worker.start() | |
| try: | |
| while not stop.is_set(): | |
| server.handle_request() | |
| finally: | |
| stop.set() | |
| worker.join() | |
| if __name__ == "__main__": | |
| main() | |