Download code/kaggle/launch_own.py from Palaestra/pocket-math-ops: direct link, hf CLI and curl.
- Browser
- Download file 8.51 kB
-
https://huggingface.co/datasets/Palaestra/pocket-math-ops/resolve/main/code/kaggle/launch_own.py
- Command line
-
hf download hf://datasets/Palaestra/pocket-math-ops/code/kaggle/launch_own.py
-
curl -L -o launch_own.py https://huggingface.co/datasets/Palaestra/pocket-math-ops/resolve/main/code/kaggle/launch_own.py
8.51 kB
| """Start runner sessions on YOUR OWN Kaggle account from a laptop (friends use the notebook instead). | |
| One-time: | |
| python kaggle/launch_own.py secrets # uploads ~/.pocket-math-secrets/hf_token to a PRIVATE dataset | |
| Before the HF organisation exists (no token needed): | |
| python kaggle/launch_own.py smoke # Phase 0 jobs with a local store; results in the kernel output | |
| Each session: | |
| python kaggle/launch_own.py push --ops-repo ORG/pocket-math-ops [--job auto] [--budget-hours 4.5] | |
| python kaggle/launch_own.py status | |
| python kaggle/launch_own.py logs # downloads /kaggle/working/logs | |
| The Kaggle API token is read from ~/.kaggle (never from this repo). The kernel is private | |
| because it attaches the private secrets dataset. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import base64 | |
| import io | |
| import json | |
| import shutil | |
| import subprocess | |
| import sys | |
| import tarfile | |
| import tempfile | |
| from pathlib import Path | |
| HERE = Path(__file__).resolve().parent | |
| SECRET_FILE = Path.home() / ".pocket-math-secrets" / "hf_token" | |
| def kaggle(*args: str, check: bool = True) -> subprocess.CompletedProcess: | |
| r = subprocess.run(["kaggle", *args], capture_output=True, text=True) | |
| if check and r.returncode != 0: | |
| raise SystemExit(f"kaggle {' '.join(args[:2])} failed:\n{r.stdout}\n{r.stderr}") | |
| return r | |
| def owner() -> str: | |
| out = kaggle("config", "view").stdout | |
| for line in out.splitlines(): | |
| if line.strip().startswith("- username:"): | |
| return line.split(":", 1)[1].strip() | |
| raise SystemExit("could not read the Kaggle username from `kaggle config view`") | |
| def cmd_secrets(_a) -> None: | |
| if not SECRET_FILE.exists(): | |
| raise SystemExit(f"missing {SECRET_FILE}") | |
| ds = f"{owner()}/pocket-math-secrets" | |
| with tempfile.TemporaryDirectory() as d: | |
| shutil.copy(SECRET_FILE, d) | |
| Path(d, "dataset-metadata.json").write_text(json.dumps({"title": "pocket-math-secrets", "id": ds, | |
| "licenses": [{"name": "other"}]})) | |
| exists = kaggle("datasets", "status", ds, check=False).returncode == 0 | |
| kaggle(*(["datasets", "version", "-p", d, "-m", "update"] if exists else ["datasets", "create", "-p", d]), "-q") | |
| print(f"token uploaded to private dataset {ds}") | |
| SESSION_CALL = '"--ops-repo", OPS_REPO])' | |
| def push_source(job: str, ops_repo: str, budget_hours: float | None = None) -> str: | |
| """bootstrap.py with this session's settings filled in. | |
| budget_hours caps the session (session.py defaults to 11.25 h), so a launch can fit the hours an | |
| account has left in its week. It is set here, not in bootstrap.py, so friends' notebooks keep the | |
| default. | |
| """ | |
| src = (HERE / "bootstrap.py").read_text(encoding="utf-8") | |
| src = src.replace('JOB_ID = "auto"', f'JOB_ID = "{job}"').replace('"ORG/pocket-math-ops"', f'"{ops_repo}"') | |
| if budget_hours is not None: | |
| if not 0 < budget_hours <= 11.25: | |
| raise SystemExit(f"--budget-hours must be in (0, 11.25], got {budget_hours}") | |
| if src.count(SESSION_CALL) != 1: | |
| # A silent no-op here would launch a full 11.25 h session, which can pass the weekly guard. | |
| raise SystemExit("bootstrap.py's session.py call changed; update SESSION_CALL in launch_own.py") | |
| src = src.replace(SESSION_CALL, f'"--ops-repo", OPS_REPO, "--budget-hours", "{budget_hours}"])') | |
| return src | |
| def cmd_push(a) -> None: | |
| src = push_source(a.job, a.ops_repo, a.budget_hours) | |
| _push(a.slug, src, dataset_sources=[f"{owner()}/pocket-math-secrets"]) | |
| SMOKE_SCRIPT = """ | |
| import base64, io, os, shutil, subprocess, sys, tarfile, time | |
| from pathlib import Path | |
| os.environ["PM_SESSION_START"] = str(time.time()) | |
| tarfile.open(fileobj=io.BytesIO(base64.b64decode(CODE))).extractall("/tmp/pm-ops/code") | |
| hub = Path("/tmp/pm-hub") | |
| ops = hub / "local__pocket-math-ops" | |
| (ops / "files").mkdir(parents=True, exist_ok=True) | |
| (ops / "files" / "queue.yaml").write_text(QUEUE) | |
| (ops / "HEAD").write_text("1") | |
| rc = subprocess.call([sys.executable, "/tmp/pm-ops/code/kaggle/session.py", "--job", "auto", | |
| "--ops-repo", "local/pocket-math-ops", "--hub", f"local:{hub}", "--budget-hours", "8"]) | |
| out = Path("/kaggle/working/pm-results") | |
| for p in hub.rglob("*"): | |
| if p.is_file() and p.suffix in (".json", ".jsonl", ".txt", ".log") and p.stat().st_size < 50_000_000: | |
| dst = out / p.relative_to(hub) | |
| dst.parent.mkdir(parents=True, exist_ok=True) | |
| shutil.copyfile(p, dst) | |
| print(f"smoke session finished (exit code {rc}); results in {out}") | |
| """ | |
| SMOKE_QUEUE = """jobs: | |
| - {id: smoke, config: smoke.yaml} | |
| - {id: opd-smoke, config: opd-smoke.yaml, needs: [smoke]} | |
| - {id: grpo-smoke, config: grpo-smoke.yaml, needs: [smoke]} | |
| """ | |
| def _git_sha() -> str: | |
| """HEAD of this checkout, with "-dirty" when the project has uncommitted changes.""" | |
| project = str(HERE.parent) | |
| try: | |
| sha = subprocess.run(["git", "-C", project, "rev-parse", "HEAD"], capture_output=True, text=True, | |
| timeout=20).stdout.strip() | |
| dirty = subprocess.run(["git", "-C", project, "status", "--porcelain", "--", "."], capture_output=True, | |
| text=True, timeout=20).stdout.strip() | |
| except (OSError, subprocess.SubprocessError): | |
| return "unknown" | |
| return (sha + ("-dirty" if dirty else "")) if sha else "unknown" | |
| def _code_b64() -> str: | |
| buf = io.BytesIO() | |
| with tarfile.open(fileobj=buf, mode="w:gz") as tar: | |
| for rel in ("pocket_math", "configs", "kaggle", "pyproject.toml"): | |
| tar.add(HERE.parent / rel, arcname=rel, | |
| filter=lambda t: None if "__pycache__" in t.name or t.name.endswith(".pyc") else t) | |
| # runner.code_sha() reads this file, so the smoke results name the code that made them. | |
| sha = _git_sha().encode() | |
| info = tarfile.TarInfo("CODE_SHA") | |
| info.size = len(sha) | |
| tar.addfile(info, io.BytesIO(sha)) | |
| return base64.b64encode(buf.getvalue()).decode() | |
| def cmd_smoke(a) -> None: | |
| src = f"CODE = {_code_b64()!r}\nQUEUE = {SMOKE_QUEUE!r}\n" + SMOKE_SCRIPT | |
| _push(a.slug, src, dataset_sources=[]) | |
| def _push(slug: str, src: str, dataset_sources: list[str]) -> None: | |
| me = owner() | |
| with tempfile.TemporaryDirectory() as d: | |
| Path(d, "run.py").write_text(src, encoding="utf-8") | |
| meta = {"id": f"{me}/{slug}", "title": slug, "code_file": "run.py", "language": "python", | |
| "kernel_type": "script", "is_private": True, "enable_gpu": True, "enable_internet": True, | |
| "dataset_sources": dataset_sources, "competition_sources": [], "kernel_sources": [], | |
| "model_sources": []} | |
| Path(d, "kernel-metadata.json").write_text(json.dumps(meta, indent=1)) | |
| r = kaggle("kernels", "push", "-p", d, "--accelerator", "NvidiaTeslaT4") | |
| out = (r.stdout + r.stderr).strip() | |
| print(out) | |
| if "error" in out.lower(): | |
| raise SystemExit(2) | |
| print(f"started: https://www.kaggle.com/code/{me}/{slug}") | |
| def cmd_status(a) -> None: | |
| print(kaggle("kernels", "status", f"{owner()}/{a.slug}").stdout.strip()) | |
| def cmd_logs(a) -> None: | |
| dest = HERE.parent / "kaggle_runs" / a.slug | |
| dest.mkdir(parents=True, exist_ok=True) | |
| kaggle("kernels", "output", f"{owner()}/{a.slug}", "-p", str(dest), "-o", "-q") | |
| print(f"downloaded to {dest}") | |
| def main(argv: list[str] | None = None) -> int: | |
| p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| sub = p.add_subparsers(dest="cmd", required=True) | |
| sub.add_parser("secrets") | |
| sub.add_parser("smoke") | |
| s = sub.add_parser("push") | |
| s.add_argument("--ops-repo", required=True) | |
| s.add_argument("--job", default="auto") | |
| s.add_argument("--budget-hours", type=float, help="cap the session (default: session.py's 11.25 h)") | |
| for name in ("status", "logs"): | |
| sub.add_parser(name) | |
| for sp in sub.choices.values(): | |
| sp.add_argument("--slug", default="pocket-math-runner") | |
| a = p.parse_args(argv) | |
| {"secrets": cmd_secrets, "smoke": cmd_smoke, "push": cmd_push, "status": cmd_status, "logs": cmd_logs}[a.cmd](a) | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |