Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Give Unsloth Studio its first CUDA coverage, on a Kaggle T4 (#8489)
Daniel Han482abfabfae6
diff --git a/.github/ci-preempt.json b/.github/ci-preempt.jsonindex 0660e74a8f5..7975a1a773f 100644--- a/.github/ci-preempt.json+++ b/.github/ci-preempt.json@@ -45,7 +45,11 @@"orphaned kernel bills the account's weekly GPU quota to its own 45-minute","ceiling with nobody left to read the result. It holds one ubuntu runner","that spends almost all of its time asleep on a poll loop, so preempting it",- "frees close to nothing and costs quota that is not the pool's to spend."+ "frees close to nothing and costs quota that is not the pool's to spend.",+ "",+ "kaggle-t4-studio-gpu-ci.yml is in 'never' for exactly the same reason, and",+ "more so: its kernel ceiling is 70 minutes rather than 45, so an orphaned",+ "one wastes correspondingly more of the account's weekly quota."],"heavy": {"macos": [@@ -81,6 +85,7 @@"ci-capacity.yml","ossf.yml","stale.yml",- "kaggle-t4-notebook-ci.yml"+ "kaggle-t4-notebook-ci.yml",+ "kaggle-t4-studio-gpu-ci.yml"]}diff --git a/.github/scripts/kaggle_studio_ci/build_kernel.py b/.github/scripts/kaggle_studio_ci/build_kernel.pynew file mode 100644index 00000000000..574d9d42f51--- /dev/null+++ b/.github/scripts/kaggle_studio_ci/build_kernel.py@@ -0,0 +1,493 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Build the Kaggle kernel notebook that runs the Studio GPU payload.++Sibling of ``.github/scripts/kaggle_t4_ci/build_kernel.py``, and deliberately+a separate file rather than a flag on it: that one carries a fixed list of+payload sources inline and runs ``run_t4_smoke.py``, and Studio needs a real+repository on the Kaggle side, which changes the shape of every cell. The+gate, the launcher and the notebook contract are shared; only the assembly+differs.++The differences worth knowing, all of them forced:++**A checkout, not a pip install.** Studio is installed by ``install.sh+--local``, which builds the frontend, creates the ``unsloth_studio`` venv and+fetches or builds llama.cpp. That needs the repository on disk, so the kernel+clones it at the ref under test. A pleasant side effect: the payload the+kernel runs is the payload at that ref, so payload and code under test cannot+drift apart.++**Nothing large under /kaggle/working.** That path is 19.5 GB and is also+what ``kernels output`` ships home. The home directory and ``/tmp`` share a+~1 TB overlay, so the checkout, the venv, torch, the models, llama.cpp and+every export live there, and only the evidence is written where Kaggle will+collect it.++**One payload, not two.** The notebook leg runs one payload per T4 because+its payload is a single-GPU training script and the second card is free.+Studio is a server, a browser and a llama.cpp process contending for four+CPU cores; a second copy of all that on the same box measures contention+rather than Studio. The second T4 is left idle on purpose.++**No per-child virtualenv.** ``install.sh`` makes its own, at+``$UNSLOTH_STUDIO_HOME/unsloth_studio``, and everything Studio-side runs+under that interpreter. The notebook leg's ``uv venv --seed`` dance exists to+keep two concurrent pip installs apart, and there is only one here.++Usage:+ python build_kernel.py --payload-dir tests/kaggle/studio_gpu \\+ --out kernel.ipynb --unsloth-ref <sha>+"""++from __future__ import annotations++import argparse+import base64+import gzip+import json+import uuid+from pathlib import Path++DRIVER_SENTINEL = "KAGGLE_STUDIO_CI_DRIVER"+PAYLOAD_SENTINEL = "KAGGLE_STUDIO_CI_PAYLOAD"++# Shared with the notebook leg's launcher, which scrapes this prefix out of+# the executed notebook and the kernel log. Keeping it identical is what lets+# .github/scripts/kaggle_t4_ci/launch.py transport this payload's result+# without a line of change.+RESULT_PREFIX = "T4_SMOKE_REPORT "++PAYLOAD_NOTEBOOK = "studio_gpu.ipynb"+OUTPUT_NOTEBOOK = "studio_gpu_output.ipynb"++# Files the payload directory has to contain. Checked at build time so a+# rename that breaks the kernel fails on the runner, in seconds, rather than+# forty minutes into a GPU session.+PAYLOAD_FILES = (+ "run_studio_gpu.py",+ "gpu_assert.py",+ "studio_client.py",+ "train_canary.jsonl",+)+++# Runs under the Studio venv's interpreter and reports what is actually+# importable there. Kept as a plain constant rather than spliced into a+# generated f-string cell: the notebook leg lost a whole GPU session to a+# cell that had been assembled out of nested quoting and did not parse.+_PROBE_SCRIPT = """+import importlib, json+out = {"versions": {}, "missing": []}+# unsloth before unsloth_zoo. zoo's __init__ refuses to import when+# find_spec("unsloth") is None, and probing zoo first has previously reported+# a dependency as missing on a session where it was installed and imported+# cleanly one line later.+for mod in ("torch", "transformers", "trl", "peft", "datasets", "bitsandbytes",+ "unsloth", "unsloth_zoo", "fastapi", "uvicorn", "playwright"):+ try:+ m = importlib.import_module(mod)+ out["versions"][mod] = getattr(m, "__version__", "unknown")+ except Exception as exc:+ out["missing"].append(mod + ": " + type(exc).__name__ + ": " + str(exc))+try:+ import torch+ out["cuda"] = {+ "available": torch.cuda.is_available(),+ "count": torch.cuda.device_count(),+ "name": torch.cuda.get_device_name(0) if torch.cuda.is_available() else None,+ }+except Exception as exc:+ out["cuda"] = {"error": type(exc).__name__ + ": " + str(exc)}+print(json.dumps(out))+"""+++def _code_cell(source: str) -> dict:+ return {+ "cell_type": "code",+ "execution_count": None,+ "id": uuid.uuid4().hex[:8],+ "metadata": {},+ "outputs": [],+ "source": source.splitlines(keepends = True),+ }+++def build_payload_notebook(*, unsloth_ref: str, repo_url: str, payload_args: str) -> dict:+ """The notebook that installs Studio and runs the payload against it."""++ setup = f"""# Where everything lives.+#+# /kaggle/working is 19.5 GB and is the directory Kaggle ships back, so it+# holds evidence and nothing else. $HOME and /tmp share a ~1 TB overlay, and+# that is where the checkout, the venv, torch, the models and llama.cpp go.+# Getting this backwards fills the disk somewhere in the middle of the torch+# install and reports itself as an unrelated failure.+import json, os, pathlib, shutil, subprocess, sys, time++print("{PAYLOAD_SENTINEL} start", flush=True)++EVIDENCE = pathlib.Path("/kaggle/working/studio_gpu_out")+EVIDENCE.mkdir(parents=True, exist_ok=True)++def _pick_work_root():+ for candidate in (pathlib.Path.home() / "unsloth_studio_ci",+ pathlib.Path("/tmp/unsloth_studio_ci")):+ try:+ candidate.mkdir(parents=True, exist_ok=True)+ free_gb = shutil.disk_usage(candidate).free / 1e9+ except OSError:+ continue+ print(f" candidate {{candidate}}: {{free_gb:.0f}} GB free", flush=True)+ if free_gb >= 60:+ return candidate+ raise SystemExit("no work root with room for a Studio install")++WORK = _pick_work_root()+REPO = WORK / "unsloth"+STUDIO_HOME = WORK / "studio_home"+HF_HOME = WORK / "hf"+for path in (STUDIO_HOME, HF_HOME):+ path.mkdir(parents=True, exist_ok=True)++os.environ["UNSLOTH_STUDIO_HOME"] = str(STUDIO_HOME)+os.environ["HF_HOME"] = str(HF_HOME)+os.environ["TMPDIR"] = str(WORK / "tmp")+pathlib.Path(os.environ["TMPDIR"]).mkdir(parents=True, exist_ok=True)+# The installer otherwise ends by offering to launch Studio, which in a batch+# kernel is a prompt nobody answers.+os.environ["UNSLOTH_SKIP_AUTOSTART"] = "1"+os.environ["UNSLOTH_DISABLE_STATISTICS"] = "1"+# T4 is sm_75. If the prebuilt CUDA bundle is unavailable and setup.sh falls+# through to a source build, this stops it compiling every architecture NVIDIA+# has ever shipped inside a 45-minute session.+os.environ["UNSLOTH_LLAMA_CUDA_ARCHS"] = "75"++print("{PAYLOAD_SENTINEL} paths " + json.dumps({{+ "work": str(WORK), "studio_home": str(STUDIO_HOME),+ "free_gb": round(shutil.disk_usage(WORK).free / 1e9, 1),+}}), flush=True)+++def fail_report(reason):+ # A failure of the INSTALLATION UNDER TEST is a payload failure, not an+ # infra one. Without a T4_SMOKE_REPORT the shared launcher classifies the+ # run as `infra` and the reporter exits 0, so an install.sh or dependency+ # regression -- the exact thing this workflow's path filter selects for --+ # would pass silently. Emitting the report first is what makes it red.+ # Infra outcomes (no GPU assigned, a clone that would not download) keep+ # the no-report path on purpose.+ print("{RESULT_PREFIX}" + json.dumps({{+ "label": "studio-gpu", "model": None, "passed": False,+ "failures": [reason], "assertions": [],+ "environment": {{}}, "config": {{}},+ }}), flush=True)+++def sh(cmd, *, cwd=None, timeout=3600, check=True, label=""):+ print(f" $ {{' '.join(cmd)}}", flush=True)+ started = time.time()+ proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True,+ timeout=timeout, env=dict(os.environ))+ print(f" -> rc={{proc.returncode}} in {{time.time() - started:.0f}}s", flush=True)+ if proc.returncode != 0:+ print(proc.stdout[-4000:], flush=True)+ print(proc.stderr[-4000:], flush=True)+ if check:+ raise SystemExit(f"{{label or cmd[0]}} failed rc={{proc.returncode}}")+ return proc+"""++ clone = f"""# The ref under test, pinned to a SHA by the workflow so a push landing+# mid-run cannot change what was measured. A blob-filtered clone: the repo's+# history is large and none of it is needed.+REPO_URL = {json.dumps(repo_url)}+REF = {json.dumps(unsloth_ref)}++if not REPO.exists():+ sh(["git", "clone", "--filter=blob:none", "--no-checkout", REPO_URL, str(REPO)],+ timeout=1800, label="git clone")+sh(["git", "fetch", "--depth", "1", "origin", REF], cwd=str(REPO), timeout=1800,+ label="git fetch")+sh(["git", "checkout", "--force", "FETCH_HEAD"], cwd=str(REPO), timeout=600,+ label="git checkout")+head = sh(["git", "rev-parse", "HEAD"], cwd=str(REPO), timeout=60).stdout.strip()+print("{PAYLOAD_SENTINEL} checkout " + json.dumps({{"ref": REF, "head": head}}), flush=True)+"""++ install = f"""# The supported install. Not `pip install unsloth[studio]`: that extra is the+# server's dependency list and does not build the frontend, create the venv or+# put a llama.cpp on disk, all three of which this payload asserts against.+#+# Torch is NOT skipped here. Every other Studio workflow installs with+# --no-torch because its runner has no GPU to use one on; the training and+# export assertions need the real CUDA stack.+_install = sh(["bash", "install.sh", "--local"], cwd=str(REPO), timeout=5400, check=False,+ label="install.sh")+if _install.returncode != 0:+ fail_report(f"install.sh --local exited {{_install.returncode}}: the supported "+ f"installation of the checkout under test failed")+ raise SystemExit("install.sh failed")++VENV_PY = STUDIO_HOME / "unsloth_studio" / "bin" / "python"+if not VENV_PY.is_file():+ fail_report(f"install.sh --local succeeded but left no interpreter at {{VENV_PY}}")+ raise SystemExit(f"install.sh left no interpreter at {{VENV_PY}}")+print("{PAYLOAD_SENTINEL} venv " + str(VENV_PY), flush=True)+"""++ browser = f"""# Same Playwright install the repo's ubuntu UI job uses, into the venv the+# payload will run under. Chromium only: the cross-browser matrix is what+# studio-ui-smoke.yml is for, and firefox and webkit add several minutes here+# for coverage that has nothing to do with CUDA.+sh([str(VENV_PY), "-m", "pip", "install", "-q", "playwright>=1.45"], timeout=1200,+ label="pip install playwright")+sh([str(VENV_PY), "-m", "playwright", "install", "--with-deps", "chromium"],+ timeout=1800, label="playwright install")+"""++ verify = f"""# Fail fast and fail legibly. Without this, a missing piece surfaces as a+# traceback inside a child process forty minutes and one GPU session later.+#+# The probe runs under the STUDIO venv, not this notebook's kernel: the Kaggle+# base image has its own torch and its own everything, and asking it what is+# installed answers a question about the wrong interpreter.+PROBE = {json.dumps(_PROBE_SCRIPT)}++proc = subprocess.run([str(VENV_PY), "-c", PROBE], capture_output=True, text=True,+ timeout=900, env=dict(os.environ))+print("{PAYLOAD_SENTINEL} probe rc=" + str(proc.returncode), flush=True)+print(proc.stdout[-4000:], flush=True)+if proc.returncode != 0:+ print(proc.stderr[-4000:], flush=True)+ fail_report("the dependency probe could not run under the installed Studio venv")+ raise SystemExit("dependency probe failed")++probe = json.loads(proc.stdout.strip().splitlines()[-1])+print("{PAYLOAD_SENTINEL} versions " + json.dumps(probe["versions"]), flush=True)+if probe["missing"]:+ print("{PAYLOAD_SENTINEL} MISSING " + json.dumps(probe["missing"]), flush=True)+ fail_report("the installed Studio venv is missing dependencies the payload needs: "+ + "; ".join(probe["missing"]))+ raise SystemExit("payload dependencies incomplete")+if not probe.get("cuda", {{}}).get("available"):+ print("{PAYLOAD_SENTINEL} NO CUDA " + json.dumps(probe.get("cuda")), flush=True)+ # Two different outcomes wear the same face here, and only one of them is+ # infra. No GPU assigned at all is Kaggle's doing and keeps the no-report+ # path, which the launcher files as `infra` and the reporter exits 0 for. A+ # GPU that nvidia-smi can see while the venv install.sh --local just built+ # cannot use it is a failure of the INSTALLATION UNDER TEST -- a CPU-only+ # torch resolved by the installer is how it happens -- and taking the+ # infra path there passes the exact CUDA install regression this workflow's+ # path filter selects for.+ try:+ _smi = subprocess.run(["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],+ capture_output=True, text=True, timeout=60)+ _visible = ([l for l in _smi.stdout.splitlines() if l.strip()]+ if _smi.returncode == 0 else [])+ except Exception:+ _visible = []+ print("{PAYLOAD_SENTINEL} NO CUDA host_gpus " + json.dumps(_visible), flush=True)+ if _visible:+ fail_report("install.sh --local succeeded but the Studio venv cannot use CUDA "+ "(torch.cuda.is_available() is False) on a box where nvidia-smi "+ "reports " + str(len(_visible)) + " GPU(s): " + json.dumps(probe.get("cuda")))+ raise SystemExit("no CUDA device in the Studio venv, so there is nothing to test")++marker = STUDIO_HOME / "llama.cpp" / "UNSLOTH_PREBUILT_INFO.json"+info = {{}}+if marker.is_file():+ try:+ info = json.loads(marker.read_text())+ except Exception:+ info = {{"unreadable": True}}+print("{PAYLOAD_SENTINEL} llama_cpp " + json.dumps({{+ "marker": str(marker), "install_kind": info.get("install_kind"),+ "tag": info.get("tag"),+}}), flush=True)+"""++ run = f"""# Run the payload in a child of the Studio venv, not by importing it: it+# starts a server, spawns a browser and can be killed by either, and a child+# leaves this cell alive to report that.+cmd = [str(VENV_PY), str(REPO / "tests" / "kaggle" / "studio_gpu" / "run_studio_gpu.py"),+ "--outdir", str(EVIDENCE),+ "--repo-root", str(REPO),+ "--studio-home", str(STUDIO_HOME)]+cmd += {json.dumps(payload_args.split())}+print("{PAYLOAD_SENTINEL} exec " + " ".join(cmd), flush=True)++proc = subprocess.run(cmd, capture_output=True, text=True, env=dict(os.environ))+print(proc.stdout, flush=True)+if proc.stderr.strip():+ print("----- stderr (tail) -----", flush=True)+ print(proc.stderr[-20000:], flush=True)+print("{PAYLOAD_SENTINEL} returncode " + str(proc.returncode), flush=True)++# Re-emit the report on its own line so the kernel log alone is enough to+# judge the run even if the executed notebook never comes back.+report_path = EVIDENCE / "studio_gpu_report.json"+if report_path.exists():+ print("{RESULT_PREFIX}" + json.dumps(json.loads(report_path.read_text())), flush=True)+else:+ print("{PAYLOAD_SENTINEL} NO REPORT WRITTEN", flush=True)+print("{PAYLOAD_SENTINEL} complete rc=" + str(proc.returncode), flush=True)+# Deliberately does not raise: the report is the verdict, and papermill+# aborting here would lose the cells below it.+"""++ return {+ "cells": [+ _code_cell(setup),+ _code_cell(clone),+ _code_cell(install),+ _code_cell(browser),+ _code_cell(verify),+ _code_cell(run),+ ],+ "metadata": {+ "kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"},+ "language_info": {"name": "python"},+ "accelerator": "GPU",+ },+ "nbformat": 4,+ "nbformat_minor": 5,+ }+++def build_driver(payload: dict, per_run_timeout: int) -> dict:+ """Kernel notebook that runs the payload notebook under papermill."""+ encoded = base64.b64encode(gzip.compress(json.dumps(payload).encode("utf-8"))).decode("ascii")++ setup = f"""import base64, gzip, json, os, pathlib, subprocess, sys, time+print("{DRIVER_SENTINEL} start", flush=True)++WORK = pathlib.Path("/kaggle/working")+PAYLOAD = {json.dumps(encoded)}+(WORK / {json.dumps(PAYLOAD_NOTEBOOK)}).write_bytes(gzip.decompress(base64.b64decode(PAYLOAD)))++try:+ _smi = subprocess.run(["nvidia-smi", "--query-gpu=name,memory.total",+ "--format=csv,noheader"],+ capture_output=True, text=True, timeout=60)+ GPUS = [l for l in _smi.stdout.strip().splitlines() if l.strip()]+except Exception:+ GPUS = []+print("{DRIVER_SENTINEL}_GPUS " + json.dumps(GPUS), flush=True)+if not GPUS:+ print("{DRIVER_SENTINEL}_NO_GPU", flush=True)+"""++ runner = f"""src = WORK / {json.dumps(PAYLOAD_NOTEBOOK)}+out = WORK / {json.dumps(OUTPUT_NOTEBOOK)}+log = WORK / "studio_gpu_driver.log"++env = dict(os.environ)+env["PYTHONUNBUFFERED"] = "1"+# Both T4s stay visible. A Kaggle session has two, a Studio user on this+# hardware has two, and Studio's own device selection is part of what is+# under test; masking one would test a machine nobody has.++started = time.time()+rc, err = None, ""+try:+ with open(log, "wb") as fh:+ proc = subprocess.run(+ [sys.executable, "-m", "papermill", str(src), str(out),+ "-k", "python3", "--log-output", "--no-progress-bar"],+ env=env, stdout=fh, stderr=subprocess.STDOUT,+ timeout={per_run_timeout})+ rc = proc.returncode+except subprocess.TimeoutExpired:+ rc, err = -9, "papermill timed out after {per_run_timeout}s"+ # Whether this is infra or a code failure turns on ONE question: had the+ # payload itself started? Before that, the time went on the clone, the+ # install and the model downloads, and a slow Kaggle session teaches+ # nothing. After it, something under test hung, and with no report the+ # launcher would file that hang as unavailable infrastructure and exit 0.+ try:+ _tail = log.read_text(errors="replace")+ except OSError:+ _tail = ""+ if "{PAYLOAD_SENTINEL} exec" in _tail:+ print("{RESULT_PREFIX}" + json.dumps({{+ "label": "studio-gpu", "model": None, "passed": False,+ "failures": ["the payload was still running when the "+ "{per_run_timeout}s driver deadline expired, so an "+ "assertion hung rather than the session being slow to "+ "start"],+ "assertions": [], "environment": {{}}, "config": {{}},+ }}), flush=True)+except Exception as exc:+ rc, err = -1, f"{{type(exc).__name__}}: {{exc}}"++print("{DRIVER_SENTINEL}_DONE " + json.dumps({{+ "returncode": rc, "seconds": round(time.time() - started, 1),+ "error": err, "output_exists": out.exists(),+}}), flush=True)+"""++ tail = f"""# Surface the child's tail inline so the kernel log alone is diagnosable if+# the executed notebook does not come back.+print("\\n===== studio_gpu (last 200 lines) =====", flush=True)+if log.exists():+ print("\\n".join(log.read_text(errors="replace").splitlines()[-200:]), flush=True)+else:+ print("NO LOG", flush=True)++# The payload notebook itself is a copy of what is already inside this kernel,+# and `kernels output` returns the whole of /kaggle/working over the wire.+try:+ (WORK / {json.dumps(PAYLOAD_NOTEBOOK)}).unlink()+except OSError:+ pass+print("{DRIVER_SENTINEL}_PRUNED " + json.dumps(+ sorted(p.name for p in WORK.iterdir())), flush=True)+print("{DRIVER_SENTINEL} complete", flush=True)+"""++ return {+ "cells": [_code_cell(setup), _code_cell(runner), _code_cell(tail)],+ "metadata": {+ "kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"},+ "language_info": {"name": "python"},+ "accelerator": "GPU",+ "kaggle_studio_ci": {"payload": PAYLOAD_NOTEBOOK, "output": OUTPUT_NOTEBOOK},+ },+ "nbformat": 4,+ "nbformat_minor": 5,+ }+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--payload-dir", required = True)+ ap.add_argument("--out", required = True)+ ap.add_argument("--unsloth-ref", default = "main")+ ap.add_argument("--repo-url", default = "https://github.com/unslothai/unsloth.git")+ ap.add_argument("--payload-args", default = "", help = "extra args for run_studio_gpu.py")+ ap.add_argument("--per-run-timeout", type = int, default = 3900)+ args = ap.parse_args()++ payload_dir = Path(args.payload_dir)+ missing = [name for name in PAYLOAD_FILES if not (payload_dir / name).is_file()]+ if missing:+ raise SystemExit(f"payload dir {payload_dir} is missing: {', '.join(missing)}")++ payload = build_payload_notebook(+ unsloth_ref = args.unsloth_ref,+ repo_url = args.repo_url,+ payload_args = args.payload_args,+ )+ driver = build_driver(payload, args.per_run_timeout)+ out = Path(args.out)+ out.parent.mkdir(parents = True, exist_ok = True)+ out.write_text(json.dumps(driver, indent = 1), encoding = "utf-8")+ print(f"wrote {out} ({out.stat().st_size / 1024:.0f} KB) for ref {args.unsloth_ref}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/.github/scripts/kaggle_studio_ci/collect_evidence.py b/.github/scripts/kaggle_studio_ci/collect_evidence.pynew file mode 100644index 00000000000..7583e000a15--- /dev/null+++ b/.github/scripts/kaggle_studio_ci/collect_evidence.py@@ -0,0 +1,187 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Unpack the Playwright evidence the Studio payload smuggled home.++Kaggle's ``kernels output`` returns the whole of ``/kaggle/working``, and the+shared launcher deliberately does not take it: a previous incident lost two+passing notebooks because a multi-gigabyte saved model sorted ahead of them+and the stream broke partway through. So the launcher fetches executed+notebooks by direct URL and nothing else, and a screenshot sitting on the+Kaggle filesystem is a screenshot nobody will ever see.++The payload therefore tars its evidence, base64s it, and prints it in chunks+into its own cell output. This script puts it back together. Every chunk is+numbered ``i/n`` so a truncated log is detected rather than silently yielding+a corrupt archive.++If the shared launcher ever grows a way to collect arbitrary files from a+kernel's output, this whole path should go: it exists only because there is+no other channel.+"""++from __future__ import annotations++import argparse+import base64+import binascii+import io+import json+import re+import tarfile+from pathlib import Path++EVIDENCE_PREFIX = "STUDIO_GPU_EVIDENCE_B64 "+_CHUNK_RE = re.compile(r"^(\d+)/(\d+)\s+(\S+)$")++# A tar member is trusted only as far as its name. Absolute paths and ``..``+# are refused rather than sanitised, because a bundle that contains one is not+# a bundle this payload wrote.+MAX_MEMBER_BYTES = 20_000_000+++def iter_text(path: Path):+ """Every text stream in a collected evidence directory.++ Recursive, because the launcher collects each kernel into its own+ subdirectory (``kaggle_evidence/<kernel-slug>/``) so two kernels of one+ run cannot overwrite each other's ``kernel.log``, while the workflow+ hands this script the parent. A top-level ``glob`` therefore matched+ nothing and every real run reported "the payload emitted no evidence+ bundle". Same discovery ``launch.py::extract_reports`` uses.+ """+ if path.is_file():+ yield path.read_text(encoding = "utf-8", errors = "replace")+ return+ for nb_path in sorted(path.rglob("*_output.ipynb")):+ try:+ nb = json.loads(nb_path.read_text(encoding = "utf-8", errors = "replace"))+ except Exception: # noqa: BLE001+ continue+ for cell in nb.get("cells", []):+ for output in cell.get("outputs", []):+ text = output.get("text") or ""+ if isinstance(text, list):+ text = "".join(text)+ yield text+ for log_path in sorted(path.rglob("kernel.log")):+ raw = log_path.read_text(encoding = "utf-8", errors = "replace")+ try:+ records = json.loads(raw)+ except json.JSONDecodeError:+ yield raw+ else:+ if isinstance(records, list):+ yield "".join(r.get("data", "") for r in records if isinstance(r, dict))+ else:+ yield raw+++def collect_chunks(streams) -> tuple[dict[int, str], int]:+ """{index: chunk} and the declared total, from any number of streams.++ The same chunk arrives twice, because the executed notebook and Kaggle's+ kernel log are two copies of one stdout. Either copy can be cut off mid+ line, and a cut only ever shortens: the survivor is a prefix of the whole+ chunk, and it still parses as ``i/n <payload>``. Overwriting on every+ sighting therefore let a truncated second copy replace a complete first+ one, and the reassembled bundle then failed base64 or tar validation with+ every chunk index present -- evidence lost with the complete source on+ disk. So a later sighting is taken only when it EXTENDS what is held.+ """+ chunks: dict[int, str] = {}+ total = 0+ for text in streams:+ for line in text.splitlines():+ if not line.startswith(EVIDENCE_PREFIX):+ continue+ match = _CHUNK_RE.match(line[len(EVIDENCE_PREFIX) :].strip())+ if not match:+ continue+ index, declared, payload = int(match.group(1)), int(match.group(2)), match.group(3)+ total = max(total, declared)+ held = chunks.get(index)+ if held is None or (len(payload) > len(held) and payload.startswith(held)):+ chunks[index] = payload+ return chunks, total+++def is_safe_member(name: str) -> bool:+ if name.startswith("/") or name.startswith("\\"):+ return False+ parts = Path(name).parts+ return ".." not in parts and not any(p.startswith("/") for p in parts)+++def extract(blob: bytes, outdir: Path) -> list[str]:+ outdir.mkdir(parents = True, exist_ok = True)+ written: list[str] = []+ with tarfile.open(fileobj = io.BytesIO(blob), mode = "r:gz") as tar:+ for member in tar.getmembers():+ if not member.isfile():+ continue+ if not is_safe_member(member.name):+ print(f"[evidence] refusing member {member.name!r}", flush = True)+ continue+ if member.size > MAX_MEMBER_BYTES:+ print(f"[evidence] refusing oversized member {member.name!r}", flush = True)+ continue+ dest = outdir / member.name+ dest.parent.mkdir(parents = True, exist_ok = True)+ handle = tar.extractfile(member)+ if handle is None:+ continue+ dest.write_bytes(handle.read())+ written.append(member.name)+ return written+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--evidence", required = True, help = "directory the launcher collected into")+ ap.add_argument("--outdir", required = True, help = "where to unpack the bundle")+ args = ap.parse_args()++ source = Path(args.evidence)+ if not source.exists():+ print("[evidence] nothing was collected, so there is nothing to unpack", flush = True)+ return 0++ chunks, total = collect_chunks(iter_text(source))+ if not chunks:+ print("[evidence] the payload emitted no evidence bundle", flush = True)+ return 0++ missing = [i for i in range(1, total + 1) if i not in chunks]+ if missing:+ # Report rather than guess. A bundle reassembled out of a truncated+ # log decodes to something, and that something is not the evidence.+ print(+ f"[evidence] {len(missing)} of {total} chunks are missing "+ f"(first: {missing[0]}), so the bundle is incomplete and is not "+ f"being unpacked",+ flush = True,+ )+ return 0++ encoded = "".join(chunks[i] for i in range(1, total + 1))+ try:+ blob = base64.b64decode(encoded, validate = True)+ except (binascii.Error, ValueError) as exc:+ print(f"[evidence] the bundle did not decode: {exc}", flush = True)+ return 0++ try:+ written = extract(blob, Path(args.outdir))+ except tarfile.TarError as exc:+ print(f"[evidence] the bundle is not a readable archive: {exc}", flush = True)+ return 0++ print(f"[evidence] unpacked {len(written)} file(s) into {args.outdir}", flush = True)+ for name in written:+ print(f" {name}", flush = True)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/.github/scripts/kaggle_studio_ci/report.py b/.github/scripts/kaggle_studio_ci/report.pynew file mode 100644index 00000000000..1a3805ce61e--- /dev/null+++ b/.github/scripts/kaggle_studio_ci/report.py@@ -0,0 +1,226 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Turn the Studio payload's report into a job summary and an exit code.++Sibling of ``.github/scripts/kaggle_t4_ci/report.py``, which holds the same+line and is reused wholesale for everything that is not rendering: the+launcher's verdict vocabulary, the kernel-log flattening and the+"infra is not a failure" policy all come from there and are imported, not+copied. What is local is the rendering, because that file renders a training+trace -- a loss table, a canary, a reference band -- and this payload+produces a list of assertions about a server.++The line itself is unchanged and is worth restating: **red means the payload+ran on a GPU and disagreed with its assertions.** Kaggle being busy, out of+quota, or unreachable teaches nothing about the code and must never colour a+pull request.++Exit codes:+ 0 passed, partially reported, or never ran+ 1 the payload ran and failed an assertion+"""++from __future__ import annotations++import argparse+import importlib.util+import json+import os+from pathlib import Path++_SHARED = Path(__file__).resolve().parents[1] / "kaggle_t4_ci" / "report.py"+++def _load_shared():+ """The notebook leg's reporter, imported by path rather than duplicated.++ Degrades instead of exploding: this file is owned elsewhere and is under+ active change, and the only thing borrowed from it is a log-flattening+ helper. Losing that costs a diagnostic section, not the verdict.+ """+ try:+ spec = importlib.util.spec_from_file_location("kaggle_t4_ci_report", _SHARED)+ if spec is None or spec.loader is None:+ return None+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+ except Exception: # noqa: BLE001+ return None+++def _summary(text: str) -> None:+ print(text, flush = True)+ path = os.environ.get("GITHUB_STEP_SUMMARY")+ if path:+ with open(path, "a", encoding = "utf-8") as fh:+ fh.write(text + "\n")+++def _notice(level: str, title: str, message: str) -> None:+ flat = message.replace("\n", " ").replace("::", ":")+ print(f"::{level} title={title}::{flat}", flush = True)+++# Order the assertions are presented in, and the one-line reminder of what+# each is actually worth. A reader who has never seen this job before should+# not have to open the payload to know whether a tick means anything.+ASSERTION_BLURB = {+ "preflight": "a GPU is present and there is disk to use it",+ "studio_ready": "Studio answered /api/health as healthy, hardware detection settled",+ "authenticate": "the bootstrap credential worked",+ "gpu_inference": "the GGUF was on the GPU, not on a CPU fallback that returns text anyway",+ "tool_calling": "the model emitted a real tool call, not prose",+ "lora_training": "a training run completed AND left an adapter on disk",+ "gguf_export": "export ran against a CUDA llama.cpp and the file it wrote loads",+ "chat_ui_driver": "tests/studio/playwright_chat_ui.py passed against this server",+}+++def render(report: dict) -> list[str]:+ env = report.get("environment", {})+ config = report.get("config", {})++ lines = [+ f"#### payload `{report.get('label', '?')}` - {report.get('seconds', '?')}s",+ "",+ ]+ gpus = env.get("gpus") or []+ lines.append(+ f"GPU `{env.get('gpu_name') or (gpus[0] if gpus else '?')}` "+ f"(capability `{env.get('gpu_capability', '?')}`, {env.get('gpu_count', '?')} visible) "+ f"- torch `{env.get('torch', '?')}` (cuda `{env.get('cuda', '?')}`) "+ f"- llama.cpp install kind `{env.get('llama_cpp_install_kind')}`"+ )+ lines.append("")+ lines.append(+ f"Chat model `{config.get('chat_model')}` `{config.get('chat_variant')}` "+ f"- train model `{config.get('train_model')}` at `{config.get('max_steps')}` steps "+ f"- export `{config.get('quantization')}` - gpu_layers pin `{config.get('gpu_layers')}`"+ )+ lines.append("")++ lines += ["| assertion | verdict | what it is worth |", "| --- | --- | --- |"]+ for entry in report.get("assertions", []):+ name = entry.get("name", "?")+ verdict = "pass" if entry.get("passed") else "**FAIL**"+ lines.append(f"| `{name}` | {verdict} | {ASSERTION_BLURB.get(name, '')} |")+ lines.append("")++ for entry in report.get("assertions", []):+ if entry.get("name") != "gpu_inference":+ continue+ evidence = entry.get("evidence") or []+ if evidence:+ lines.append("GPU offload evidence:")+ lines += [f"- {item}" for item in evidence]+ lines.append("")++ for entry in report.get("assertions", []):+ if entry.get("name") == "lora_training" and entry.get("output_dir"):+ lines.append(+ f"Training: phase `{entry.get('phase')}`, "+ f"{entry.get('steps_with_loss', '?')} step(s) with a logged loss, adapter "+ f"`{entry.get('adapter_weights', 'missing')}` "+ f"({entry.get('adapter_bytes', 0)} bytes)."+ )+ lines.append("")+ if entry.get("name") == "gguf_export" and entry.get("gguf"):+ lines.append(+ f"Export: `{Path(entry['gguf']).name}` ({entry.get('gguf_bytes', 0)} bytes), "+ f"reloaded on the GPU and generated "+ f"{'the canary' if entry.get('canary_found') else 'text'}."+ )+ lines.append("")++ if report.get("failures"):+ lines.append("Failures:")+ lines += [f"- {item}" for item in report["failures"]]+ lines.append("")+ return lines+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--evidence", required = True)+ args = ap.parse_args()++ evidence = Path(args.evidence)+ result_file = evidence / "launch_result.json"+ if not result_file.exists():+ _summary(+ "### Studio GPU smoke\n\nNo launch result was written. The launcher did not "+ "get far enough to record anything, so nothing is known about the code "+ "under test."+ )+ _notice("warning", "Studio GPU smoke did not run", "no launch_result.json was produced")+ return 0++ result = json.loads(result_file.read_text(encoding = "utf-8"))+ verdict = result.get("verdict", "infra")+ reason = result.get("reason", "")+ reports = result.get("reports", [])++ header = {+ "pass": "### Studio GPU smoke: PASS",+ "fail": "### Studio GPU smoke: FAIL",+ "partial": "### Studio GPU smoke: PARTIAL",+ "infra": "### Studio GPU smoke: NOT RUN",+ }.get(verdict, "### Studio GPU smoke")++ lines = [header, "", reason, ""]+ if result.get("slug"):+ lines.append(+ f"Kernel: `{result['slug']}` (private), terminal state `{result.get('kernel_state')}`."+ )+ lines.append("")+ for report in reports:+ lines += render(report)++ if verdict in ("infra", "partial"):+ shared = _load_shared()+ hits = []+ if shared is not None and hasattr(shared, "diagnostic_lines"):+ try:+ hits = shared.diagnostic_lines(evidence)+ except Exception: # noqa: BLE001+ hits = []+ if hits:+ lines += (+ [+ "<details><summary>Kernel log, filtered</summary>",+ "",+ "```",+ ]+ + hits+ + ["```", "", "</details>", ""]+ )++ if verdict == "infra":+ lines += [+ "This is not a code failure. The payload never produced a result, so there "+ "is nothing to conclude about this change. Common causes: the Kaggle "+ "account was at its 2-kernel concurrency cap, the weekly GPU quota was "+ "exhausted, or the push was throttled.",+ "",+ "Re-run with the `kaggle-studio-gpu-ci` label or a manual dispatch to force "+ "another attempt.",+ ]++ _summary("\n".join(lines))++ if verdict == "fail":+ _notice("error", "Studio GPU smoke failed", reason)+ return 1+ if verdict == "partial":+ _notice("warning", "Studio GPU smoke partially reported", reason)+ return 0+ if verdict == "infra":+ _notice("warning", "Studio GPU smoke did not run", reason)+ return 0+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/.github/scripts/kaggle_t4_ci/launch.py b/.github/scripts/kaggle_t4_ci/launch.pyindex 94c1f53decc..cfdd01d92cb 100644--- a/.github/scripts/kaggle_t4_ci/launch.py+++ b/.github/scripts/kaggle_t4_ci/launch.py@@ -55,7 +55,9 @@ import argparseimport jsonimport osimport re+import atexitimport shutil+import signalimport socketimport subprocessimport sys@@ -64,6 +66,7 @@ import timeimport urllib.parseimport urllib.requestimport uuid+from collections.abc import Callablefrom pathlib import Path, PurePosixPath, PureWindowsPathsys.path.insert(0, str(Path(__file__).resolve().parent))@@ -240,6 +243,120 @@ def _api():return api+# A kernel this process pushed but has not yet deleted is recorded here, so a+# LATER launch can reclaim it. This is the only cover for `kill -9`, where no+# handler of ours ever runs. Deliberately keyed on pid: an entry whose owner+# is still alive belongs to a run in progress and must not be touched, or one+# launcher would delete a concurrent launcher's kernel and report its absence+# as a failure of the code under test.+INFLIGHT = (+ Path(os.environ.get("UNSLOTH_WORKSPACE") or Path(__file__).resolve().parents[3])+ / "logs"+ / "kaggle_inflight.json"+)+++def _inflight_read() -> list[dict]:+ try:+ data = json.loads(INFLIGHT.read_text(encoding = "utf-8"))+ except (OSError, ValueError):+ return []+ return data if isinstance(data, list) else []+++def _inflight_write(entries: list[dict]) -> None:+ try:+ INFLIGHT.parent.mkdir(parents = True, exist_ok = True)+ INFLIGHT.write_text(json.dumps(entries, indent = 1), encoding = "utf-8")+ except OSError:+ pass # bookkeeping only; never fail a run over it+++def _inflight_add(slug: str) -> None:+ entries = [e for e in _inflight_read() if e.get("slug") != slug]+ entries.append({"slug": slug, "pid": os.getpid(), "at": time.time()})+ _inflight_write(entries)+++def _inflight_drop(slug: str) -> None:+ _inflight_write([e for e in _inflight_read() if e.get("slug") != slug])+++def _inflight_mark_kept(slug: str) -> None:+ """Flag a kernel as deliberately retained, so no later sweep reclaims it.++ ``--keep-kernel`` leaves the kernel up on purpose. Its registry entry+ still names this process, and this process is about to exit, so the next+ launcher would see a dead owner, call it an orphan and delete the very+ thing the flag asked to keep.+ """+ entries = _inflight_read()+ for entry in entries:+ if entry.get("slug") == slug:+ entry["keep"] = True+ _inflight_write(entries)+++def _pid_alive(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True # exists, owned by someone else+ except (OSError, TypeError):+ return True # unknown: assume alive, deleting is the costly error+ return True+++def sweep_orphans() -> list[str]:+ """Delete kernels left behind by a launcher that was killed outright.++ Only entries whose owning process is gone are eligible, so a concurrent+ run is never disturbed. Returns the slugs reclaimed.+ """+ entries = _inflight_read()+ if not entries:+ return []+ keep: list[dict] = []+ reclaimed: list[str] = []+ for entry in entries:+ slug, pid = entry.get("slug"), entry.get("pid")+ if not slug:+ continue+ if entry.get("keep"):+ # --keep-kernel asked for this one to stay up.+ keep.append(entry)+ continue+ if isinstance(pid, int) and _pid_alive(pid) and pid != os.getpid():+ keep.append(entry)+ continue+ if pid == os.getpid():+ keep.append(entry)+ continue+ try:+ proc = subprocess.run(+ ["kaggle", "kernels", "delete", slug, "-y"],+ capture_output = True,+ text = True,+ timeout = 180,+ )+ except Exception: # noqa: BLE001+ keep.append(entry) # try again next time rather than forget it+ continue+ # A nonzero exit does NOT raise, so the return code is the only thing+ # that separates "reclaimed" from "Kaggle refused and the kernel is+ # still running and still billing". Forgetting the entry there is how+ # one bills to its ceiling unnoticed.+ if proc.returncode == 0:+ reclaimed.append(slug)+ else:+ _log(f"could not delete orphan {slug} (rc={proc.returncode}); keeping the record")+ keep.append(entry)+ _inflight_write(keep)+ return reclaimed++def _pushed(ok: bool, reason: str, out: str, attempted: list[str]) -> dict:"""A push outcome, always carrying the slugs the call filed.@@ -367,10 +484,19 @@ def push(# that is what it is, Kaggle under load, so the retry applies.out = f"push subprocess exceeded {PUSH_SUBPROCESS_TIMEOUT_SEC}s and was killed; timed out"_log(f"push timed out after {PUSH_SUBPROCESS_TIMEOUT_SEC}s ({attempted[-1]})")+ # Also recorded on disk. release() covers the paths this process+ # gets to run; the registry covers the one it does not, a kill+ # between here and cleanup, by leaving the slug for the next+ # launcher's sweep.+ _inflight_add(attempted[-1])lowered = out.lower()if "successfully pushed" in lowered:if "does not resolve to the specified id" in lowered:return _pushed(False, "slug_mismatch", out, attempted)+ # Recorded the instant it exists, before anything can go+ # wrong downstream: a kernel that is billing but unknown to+ # the registry is exactly the case the registry is for.+ _inflight_add(attempted[-1])return {"ok": True, "slug": attempted[-1], "attempts": attempted}if any(m in lowered for m in CAPACITY_MARKERS):return _pushed(False, "at_capacity", out, attempted)@@ -725,7 +851,7 @@ def fetch_evidence(}-def _flatten_log(raw: str) -> str:+def flatten_kernel_log(raw: str) -> str:"""A kernel log as flat text, whichever shape Kaggle returned it in.``kernels/output`` returns the log as a JSON array of@@ -787,10 +913,47 @@ def extract_reports(outdir: Path) -> list[dict]:text = "".join(text)_consume(text)for log_path in sorted(outdir.rglob("kernel.log")):- _consume(_flatten_log(log_path.read_text(encoding = "utf-8", errors = "replace")))+ raw = log_path.read_text(encoding = "utf-8", errors = "replace")+ _consume(flatten_kernel_log(raw))return reports+def _install_release_handlers(release: Callable[[], None]) -> None:+ """Make release survive the ways this process actually dies.++ normal return / handled error finish() calls it directly+ unhandled exception atexit+ Ctrl-C, kill, Actions cancel the signal handlers here+ kill -9 nothing in-process can; the orphan+ sweep at the next launch reclaims it++ Before this, only the first row worked: `finish()` is reached only on+ paths that RETURN, KeyboardInterrupt was re-raised past it, and the+ default SIGTERM disposition exits without running atexit or finally. A+ cancelled workflow therefore left its kernel running.+ """+ atexit.register(release)++ def _release_and_die(signum, _frame):+ _log(f"received signal {signum}; deleting kernels before exiting")+ release()+ # Die of the original signal rather than exiting 0, so the status+ # still reads "killed by signal N". A CI system treats a 0 from a+ # cancelled job as a completed one.+ signal.signal(signum, signal.SIG_DFL)+ os.kill(os.getpid(), signum)++ for _sig in (signal.SIGINT, signal.SIGTERM, getattr(signal, "SIGHUP", None)):+ if _sig is None:+ continue+ try:+ signal.signal(_sig, _release_and_die)+ except (ValueError, OSError, AttributeError):+ # No SIGHUP on Windows, and signal() only works on the main+ # thread. One handler failing must not stop the others.+ pass++def main() -> int:ap = argparse.ArgumentParser()ap.add_argument(@@ -861,6 +1024,12 @@ def main() -> int:rather than quietly counted as cleaned up."""if args.keep_kernel:+ # Flagged, not just skipped: the registry entry still names this+ # process, and the next launcher would read a dead owner as an+ # orphan and delete the very kernel the flag asked to keep.+ for entry in result.get("kernels") or []:+ for slug in _slugs_filed(entry):+ _inflight_mark_kept(slug)returnleaked: list[str] = []for entry in result.get("kernels") or []:@@ -870,6 +1039,7 @@ def main() -> int:continueif delete_kernel(slug):done.add(slug)+ _inflight_drop(slug)else:leaked.append(slug)_log(f"could not delete {slug}; it may keep billing")@@ -885,6 +1055,10 @@ def main() -> int:flush = True,)+ # From here on release() is reachable from a signal and from atexit too,+ # not only from finish(): a cancelled workflow used to leave its kernel up.+ _install_release_handlers(release)+def finish(code: int = 0) -> int:release()(outdir / "launch_result.json").write_text(json.dumps(result, indent = 2), encoding = "utf-8")@@ -954,6 +1128,12 @@ def main() -> int:result["reason"] = f"kaggle auth failed: {type(exc).__name__}"return finish()+ # Reclaim anything a previous launcher was killed outright before it+ # could delete. Done BEFORE pushing, so the freed session slots are+ # available to this run -- Kaggle allows only two GPU sessions at once,+ # and an orphan holds one until its ceiling.+ for _slug in sweep_orphans():+ _log(f"reclaimed orphaned kernel {_slug} from a killed launcher")# AGAIN, now that authentication is paid for and the next thing is a push.# The check above is not enough on its own: authenticate() reaches the# network -- with KAGGLE_API_TOKEN, which is the only credential thisdiff --git a/.github/workflows/kaggle-t4-notebook-ci.yml b/.github/workflows/kaggle-t4-notebook-ci.ymlindex f0521ff6ef1..55716012ae3 100644--- a/.github/workflows/kaggle-t4-notebook-ci.yml+++ b/.github/workflows/kaggle-t4-notebook-ci.yml@@ -67,15 +67,26 @@# The Kaggle account behind KAGGLE_ACCESS_TOKEN_GH has a WEEKLY accelerator# budget (60h at time of writing; Kaggle's documented baseline is 30h and the# surplus is a discretionary "floating" allowance that can be withdrawn). This-# workflow is allotted 40 GPU-h/week of it, held in four independent layers:+# 50 of those 60 go to CI and the last 10 are held for human use. That 50 is+# SHARED with kaggle-t4-studio-gpu-ci.yml, which is the expensive leg: ~0.75+# GPU-h per launch against this one's ~0.25, on a larger eligible event stream.+# The split is Studio 35, this leg 15, and the reserves below are what enforce+# the priority rather than a comment: this leg stands down at 40h spent+# account-wide, Studio runs on to 50h. A change to either rate is a change to+# both budget blocks.+#+# This workflow is allotted 15 GPU-h/week of it, held in four independent layers:## 1. paths filters, which turn a four-figure event count into a two-figure one.# 2. A sampling gate (.github/scripts/kaggle_t4_ci/gate.py), derived from the# run id so a re-run cannot reroll the dice.# 3. A quota floor: the gate reads Kaggle's accelerator-quota API and refuses# to start unless what remains covers this run's worst case PLUS a 20h-# reserve. Against a 60h account that reserve makes the 40h allowance a+# reserve. Against a 60h account that reserve makes the 15h allowance a# HARD ceiling rather than an average, whatever the sampling rate does.+# It is 10 higher than the Studio leg's 10 on purpose: the two share one+# account and the cheap leg is the one that should yield the tail of the+# week to the expensive one rather than race it for the same hours.# 4. A concurrency check. Kaggle caps concurrent batch GPU kernels at 2 per# ACCOUNT; this job uses both, and only when the account is otherwise idle,# since one kernel belonging to anyone else stands it down entirely. See@@ -113,14 +124,20 @@# TOTAL, expected ~0.25 h (rounded up)## SAMPLING RATE, solved at the pessimistic end of the eligible range and-# targeting 30h rather than the full 40, so a busy week does not spend the+# targeting 9h rather than the full 15, so a busy week does not spend the# allowance before the quota floor intervenes:-# 231 x r x 0.25 h = 30 h -> r = 0.52, set to 40% (--percent 40)+# 231 x r x 0.25 h = 9 h -> r = 0.156, set to 15% (--percent 15)+#+# EXPECTED SPEND at 15%:+# quiet week 88 x 0.15 x 0.25 = 3.3 GPU-h (13 launches)+# busy week 231 x 0.15 x 0.25 = 8.7 GPU-h (35 launches)+# against the 15 GPU-h allowance: 5% to 14% of the 60h account.#-# EXPECTED SPEND at 40%:-# quiet week 88 x 0.40 x 0.25 = 8.8 GPU-h-# busy week 231 x 0.40 x 0.25 = 23.1 GPU-h-# against the 40 GPU-h allowance: 15% to 39% of the 60h account.+# An earlier revision of this block ran 40% for ~23 GPU-h/week, sized against+# a 40h allowance from before the Studio leg existed. Two legs at ~23 each is+# 46 of the 50 CI is allowed, with the whole margin gone on the cheaper one.+# 15% is that rate re-solved against the 15h share, not a throttle applied to+# a rate that was still correct.## The rate is set for THIS payload set and does not survive a change to it:# wiring the grpo leg would roughly double kernel 2 and put a busy week over@@ -131,8 +148,9 @@# deletion the launcher can pay for, is 8 GPU-h: derived from launch.py's own# constants at --budget-hours below, and far above the 0.25h a run costs. It# is what the gate RESERVES, not what CI is expected to spend. Layer 3 is the-# control: the 20h reserve stops CI at 40h spent whatever the arithmetic above-# got wrong. The sampling rate sets the EXPECTED spend; the reserve sets the+# control: the 20h reserve stops this leg at 40h spent account-wide, whatever+# the arithmetic above got wrong. The sampling rate sets the EXPECTED spend;+# the reserve sets the# ceiling.## ---------------------------------------------------------------------@@ -317,11 +335,14 @@ jobs:# than checking the number, so lowering PUSH_ATTEMPTS or the delete# ceilings lowers what has to be reserved here.#- # reserve-hours turns the 40 GPU-h/week allowance into a hard ceiling: the- # account budget is 60h, so refusing to start below 20h remaining means CI- # can never have spent more than 40h in a week, whatever the sampling- # estimate above got wrong. Raise it to throttle CI harder, but not above- # roughly 45 or CI never runs on a week with any other usage.+ # reserve-hours turns the 15 GPU-h/week allowance into a hard ceiling: the+ # account budget is 60h, so refusing to start below 20h remaining means+ # this leg can never have spent more than 40h in a week, whatever the+ # sampling estimate above got wrong. It is deliberately 10 above the+ # Studio leg's 10, which is what makes this the leg that yields: the+ # lower of the two reserves is what implements "CI may use up to 50 of+ # the 60 hours". Raise it to throttle harder, but not above roughly 45 or+ # it never runs at all on a week with any other usage.## The event ACTION and the label just applied go in too, and are what# stops the `labeled` trigger multiplying runs: it fires on EVERY label,@@ -344,7 +365,7 @@ jobs:EVENT_LABEL: ${{ github.event.label.name }}run: |python .github/scripts/kaggle_t4_ci/gate.py \- --percent 40 \+ --percent 15 \--force '${{ inputs.force || 'false' }}' \--labels "$PR_LABELS" \--label-name kaggle-t4-ci \diff --git a/.github/workflows/kaggle-t4-studio-gpu-ci.yml b/.github/workflows/kaggle-t4-studio-gpu-ci.ymlnew file mode 100644index 00000000000..9f33b9ea52a--- /dev/null+++ b/.github/workflows/kaggle-t4-studio-gpu-ci.yml@@ -0,0 +1,441 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.+#+# Unsloth Studio on a real CUDA GPU, on free Kaggle T4 hardware.+#+# Why this exists: Studio has ZERO CUDA coverage. Every Studio workflow in+# this repo runs on ubuntu-latest, macos-15 or windows-latest, and nothing+# matches `runs-on:.*(gpu|a100|t4|nvidia|self-hosted)`. macOS gives Metal and+# MLX some hardware; the CUDA path is exercised by nothing at all.+# studio-inference-smoke.yml runs real GGUF inference against a 270M model+# precisely because it has to decode on a CPU. This is the first job that can+# tell a working GPU path from a CPU fallback.+#+# What runs: tests/kaggle/studio_gpu/run_studio_gpu.py, one payload per+# kernel. It installs Studio the supported way (`install.sh --local`, which+# builds the frontend, makes the venv and fetches a CUDA llama.cpp), starts+# the server headless, and asserts three things.+#+# A. GGUF inference is ON THE GPU, and tool calling works. Three+# independent probes -- process VRAM from nvidia-smi, llama.cpp's own+# offload line, device-wide VRAM growth -- and a rule that no evidence+# is a FAILURE rather than a pass. "The model returned text" is+# explicitly not evidence: a CPU fallback returns text too, which is why+# no existing Studio job can catch one. Then tool calling through+# /v1/chat/completions with tool_choice=required, asserting+# finish_reason == "tool_calls".+# B. A LoRA training run finishes and leaves an adapter. Tested on no+# platform today. Judged on the phase reaching `completed` AND a loss+# logged for every step AND adapter_model.safetensors existing above a+# size floor -- a run whose dataset formats to zero rows also reaches+# `completed`, and a save that no-ops still leaves a config.+# C. GGUF export runs against a CUDA llama.cpp build and the output loads.+# The install kind on disk is asserted to be a CUDA bundle, the output+# is checked for the GGUF magic rather than for existence, and "it+# loads" is asserted by loading it back into Studio and generating.+#+# Then the repo's existing tests/studio/playwright_chat_ui.py is driven+# against the same server, last, because its final phase clicks "Stop server"+# and asserts the port closes.+#+# ---------------------------------------------------------------------+# BUDGET. Read this before changing any trigger.+# ---------------------------------------------------------------------+# The Kaggle account behind KAGGLE_ACCESS_TOKEN_GH has a WEEKLY accelerator+# budget (60h at time of writing) shared with every other use of that+# account, and with the notebook leg in kaggle-t4-notebook-ci.yml. CI is+# allowed up to 50 of those 60; the last 10 are held for human use and are+# what `--reserve-hours 10` protects.+#+# Studio is sampled HARDER than the notebook leg because Studio changes land+# far more often. That comes out as MORE launches, far more GPU-hours, a+# bigger share of the allowance -- and as a LOWER percentage. The percentage+# moves the other way because the eligible event stream here is about three+# times larger and each launch costs about three times as much, so a point of+# rate is worth roughly ten times more here. See COMPARED WITH THE NOTEBOOK+# LEG below; that inversion is the arithmetic, not a mistake in it.+#+# MEASURED, 7 days to 2026-08-11 on unslothai/unsloth:+# 479 commits landed on main (the wider week the numbers below use is+# 514), of which 199 -- 41.5% -- touched the GPU-relevant Studio surface+# this workflow filters on. 67% touched studio/ at all; the filter is+# narrower than that on purpose, see PATHS below.+# Of a 40-PR sample of pull requests opened in the same window, 13+# (32.5%) touched that same surface. 30 (75%) touched studio/ at all.+#+# ELIGIBLE INVOCATIONS+# push to main 514 x 0.415 = ~213 / week+# pull_request 566 x 0.325 x ~3 events = ~550 / week+# (opened plus synchronize; the same multiplier the+# notebook leg's measured 150-200 implies)+# total = ~760 / week+#+# COST OF ONE LAUNCH, itemised rather than guessed. A Kaggle session bills+# wall clock, so this is wall clock, and none of it is cached: a kernel+# starts from the stock image every time.+# git clone + install.sh --local (venv, frontend build,+# CUDA torch, llama.cpp prebuilt) ~20 min+# playwright chromium + system deps ~3 min+# Studio boot to healthy ~1 min+# chat GGUF download (~1.5 GB) + assertions A ~5 min+# assertion B (0.5B base download, 8 LoRA steps, save) ~6 min+# assertion C (merge, GGUF convert, quantize, reload) ~6 min+# tests/studio/playwright_chat_ui.py, 28 phases ~10 min+# evidence bundle ~1 min+# -------------------------------------------------------------------+# ~52 min, call it 0.75 GPU-h with the variance that hides in a+# download. The notebook leg costs 0.08 h; this is roughly 9x it, and+# unlike that one it is NOT dominated by pip install alone.+#+# ARITHMETIC, at the current settings.+# eligible invocations ~760 / week (paths filter, measured)+# x sampling rate 0.05 (--percent 5)+# = launches ~38 / week+# x cost of one launch 0.75 h+# = EXPECTED SPEND ~28 GPU-h / week+#+# Against the 60 h account budget that is ~47%, and against the 50 h CI+# allowance ~57%. This leg's share of that allowance is 35 h.+#+# Worst case, if every sampled launch ran to the 70-minute kernel ceiling:+# 38 x 1.17 = ~44 GPU-h/week, which is over the 35 h share. That is what+# the 10 h reserve is for, and it is the ceiling; the rate above is the+# expectation.+#+# COMPARED WITH THE NOTEBOOK LEG, which is what "sampled higher" means:+# launches / week ~38 vs 13-35+# GPU-h / week ~28 vs 3.3-8.7+# share of the 50h CI allowance 35 vs 15+# sampling rate 5% vs 15%+#+# THE PERCENTAGE IS THE ONE AXIS THAT INVERTS, AND IT CANNOT BE MADE TO+# AGREE. Studio's eligible stream is ~3.3x the notebook leg's busy-week+# count and each launch costs 3x as much, so a percentage point here buys+# ~10x the GPU-hours it does there. At a common rate r the two cost 570r+# and 58r; equalising the rate at anything this leg can afford would leave+# the notebook leg running on a handful of commits a week, and raising this+# leg to the notebook's 15% would be 114 launches and ~86 GPU-h/week --+# more than the whole account. So "sampled harder" is implemented as more+# launches, more hours, a bigger share of the allowance and a lower stand-+# down floor, on a smaller fraction of a much larger stream. Anyone+# comparing the two `--percent` values alone will read it backwards, which+# is why this paragraph is here and why the harness test asserts the+# inversion rather than papering over it.+#+# ONE PAYLOAD, NOT TWO. The notebook leg runs a payload on each T4 of a+# session because the second card is free. Here the second card is left+# idle on purpose: Studio is a server, a browser and a llama.cpp process+# contending for four CPU cores, and a second copy of all that on the same+# box measures contention rather than Studio.+#+# ---------------------------------------------------------------------+# PATHS+# ---------------------------------------------------------------------+# Deliberately NOT `studio/**`. This leg exists to exercise CUDA, and the+# frontend is not where CUDA lives; frontend changes are already covered on+# every commit by studio-ui-smoke.yml, studio-frontend-ci.yml and the mac and+# windows UI jobs. Filtering on studio/** instead would raise the eligible+# stream from ~760 to ~1600 a week and halve the sampling rate this budget+# can afford, buying nothing this job can see.+#+# The two Playwright files that ARE listed are the ones this payload drives.+# .github/scripts/kaggle_t4_ci/** is listed because the gate and the launcher+# are shared with the notebook leg and a change there changes this job.+#+# ---------------------------------------------------------------------+# FAILURE SEMANTICS+# ---------------------------------------------------------------------+# Red ONLY when the payload ran on a GPU and its assertions failed. Every+# other outcome -- not sampled, no quota, account busy, push throttled,+# kernel died on Kaggle's side, evidence would not download -- is a SKIP or a+# warning and exits 0. Nothing was learned about the code in those cases, so+# nothing should block a merge.+#+# This job is NOT intended to be a required check. It runs on a minority of+# commits by design, so requiring it would block every commit it declined to+# run on.+#+# ---------------------------------------------------------------------+# CREDENTIALS+# ---------------------------------------------------------------------+# KAGGLE_ACCESS_TOKEN_GH is passed as KAGGLE_API_TOKEN to the gate and the+# launcher only. It is never echoed, never written to an output or an+# artifact, and never travels to the Kaggle kernel: the kernel receives the+# notebook and nothing else. Fork pull requests do not receive the secret and+# the gate skips cleanly when it is absent.+#+# The payload mints its own Studio bootstrap password inside the kernel and+# scrubs it out of every log that leaves the machine, because Studio's+# startup banner prints it and those logs become an artifact.++name: Kaggle T4 Studio GPU CI++on:+ pull_request:+ # `labeled` on top of the defaults, because the opt-in label below is+ # advertised as the way to force a run that sampling declined. Without it+ # GitHub starts nothing when the label is added and the override only+ # takes effect on the next unrelated push.+ types: [opened, synchronize, reopened, labeled]+ paths:+ - 'studio/backend/**'+ - 'studio/setup.sh'+ - 'studio/install_llama_prebuilt.py'+ - 'studio/prebuilt_core.py'+ - 'studio/install_python_stack.py'+ - 'install.sh'+ - 'unsloth_cli/commands/studio.py'+ - 'tests/studio/playwright_chat_ui.py'+ - 'tests/studio/_playwright_robust.py'+ - 'tests/kaggle/studio_gpu/**'+ - '.github/scripts/kaggle_studio_ci/**'+ - '.github/scripts/kaggle_t4_ci/**'+ - '.github/workflows/kaggle-t4-studio-gpu-ci.yml'+ push:+ branches: [main]+ paths:+ - 'studio/backend/**'+ - 'studio/setup.sh'+ - 'studio/install_llama_prebuilt.py'+ - 'studio/prebuilt_core.py'+ - 'studio/install_python_stack.py'+ - 'install.sh'+ - 'unsloth_cli/commands/studio.py'+ - 'tests/studio/playwright_chat_ui.py'+ - 'tests/studio/_playwright_robust.py'+ - 'tests/kaggle/studio_gpu/**'+ - '.github/scripts/kaggle_studio_ci/**'+ - '.github/scripts/kaggle_t4_ci/**'+ - '.github/workflows/kaggle-t4-studio-gpu-ci.yml'+ workflow_dispatch:+ inputs:+ force:+ description: 'Bypass the sampling gate (quota and concurrency still apply)'+ type: boolean+ default: true+ max_steps:+ description: 'LoRA steps for the training assertion'+ type: string+ default: '8'+ chat_model:+ description: 'GGUF repo to load for the inference and tool-calling assertions'+ type: string+ default: 'unsloth/Qwen3.5-2B-GGUF'+ train_model:+ description: 'Base model for the training and export assertions'+ type: string+ default: 'unsloth/Qwen2.5-0.5B-Instruct'+ skip_ui:+ description: 'Do not drive playwright_chat_ui.py (API assertions only)'+ type: boolean+ default: false+ unsloth_ref:+ description: 'unslothai/unsloth ref to install and test'+ type: string+ default: ''++permissions:+ contents: read++# Per-ref, and NOT latest-only, for the same reason the notebook leg is not:+# a cancelled runner cannot stop the Kaggle kernel it has already pushed, and+# an orphaned kernel bills quota to its own ceiling with nobody left to read+# the result. Superseded runs that have not STARTED are still discarded.+concurrency:+ group: ${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: false++jobs:+ gate:+ name: gate+ # Fork pull requests never receive KAGGLE_ACCESS_TOKEN_GH, so this job+ # could only reach "the token is not available to this context" -- a+ # runner spent to learn nothing.+ #+ # The `labeled` clause is what keeps the opt-in label from turning into a+ # standing trigger. GitHub has no per-label event filter, so `labeled`+ # starts this workflow for EVERY label added, and once+ # kaggle-studio-gpu-ci is on the pull request the gate reads the whole+ # label list and calls every one of those events forced -- so adding any+ # unrelated label would launch another 70-minute Kaggle session. Checking+ # the label that fired the event is the documented way to narrow it.+ # `github.event.label` exists only on labeled/unlabeled, and+ # `github.event.action` is null on push, so both other events fall+ # through.+ if: >-+ github.event.pull_request.head.repo.fork != true+ && (github.event.action != 'labeled'+ || github.event.label.name == 'kaggle-studio-gpu-ci')+ runs-on: ubuntu-latest+ timeout-minutes: 10+ outputs:+ should_run: ${{ steps.decide.outputs.should_run }}+ reason: ${{ steps.decide.outputs.reason }}+ steps:+ - name: Harden runner (audit)+ uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0+ with:+ egress-policy: audit++ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false++ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: '3.12'++ - name: Install the Kaggle client+ run: python -m pip install --quiet 'kaggle==1.7.4.5'++ # The gate itself is shared with the notebook leg, unchanged. Only the+ # numbers differ.+ #+ # --kernels 1, not the default 2: this leg pushes ONE kernel and leaves+ # the session's second T4 idle (see ONE PAYLOAD, NOT TWO above), so+ # demanding two free concurrency slots would stand the job down on an+ # account that has room for it.+ #+ # budget-hours is the worst case ONE invocation can cost: the 70-minute+ # kernel ceiling set below, rounded up.+ #+ # reserve-hours is 10 rather than the notebook leg's 20, and that is the+ # single knob that implements "CI may use up to 50 of the 60 hours".+ # Raising it throttles BOTH legs, since they read the same account-wide+ # quota. Do not raise it above roughly 45 or CI never runs at all on a+ # week with any other usage.+ - name: Decide+ id: decide+ env:+ KAGGLE_API_TOKEN: ${{ secrets.KAGGLE_ACCESS_TOKEN_GH }}+ run: |+ python .github/scripts/kaggle_t4_ci/gate.py \+ --percent 5 \+ --force '${{ inputs.force || 'false' }}' \+ --labels '${{ join(github.event.pull_request.labels.*.name, ',') }}' \+ --label-name kaggle-studio-gpu-ci \+ --kernels 1 \+ --budget-hours 2 \+ --reserve-hours 10++ studio-gpu:+ name: Studio GPU smoke+ needs: gate+ if: needs.gate.outputs.should_run == 'true'+ runs-on: ubuntu-latest+ # 120 min: the kernel ceiling is 70 and collection adds a few, so this+ # only fires if the launcher itself wedged.+ timeout-minutes: 120+ # The SAME group string the notebook leg uses, on purpose. Kaggle's+ # 2-kernel cap is per ACCOUNT and is not workflow-aware, so the two GPU+ # legs have to queue behind each other rather than race the gate's+ # concurrency survey and lose a push to the capacity cap. Not keyed on+ # the ref for the same reason.+ concurrency:+ group: kaggle-t4-notebook-ci-account+ cancel-in-progress: false+ steps:+ - name: Harden runner (audit)+ uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0+ with:+ egress-policy: audit++ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false++ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: '3.12'++ - name: Install the Kaggle client+ run: python -m pip install --quiet 'kaggle==1.7.4.5'++ # The ref the kernel clones and tests. For a pull request that is the+ # head SHA, so the kernel exercises the proposed code and not the merge+ # base. Pinned to a SHA rather than a branch so a push landing mid-run+ # cannot change what was tested.+ - name: Resolve the ref under test+ id: ref+ run: |+ REF='${{ inputs.unsloth_ref }}'+ if [ -z "$REF" ]; then+ REF='${{ github.event.pull_request.head.sha || github.sha }}'+ fi+ echo "ref=$REF" >> "$GITHUB_OUTPUT"+ echo "testing unslothai/unsloth@$REF"++ - name: Build the kernel notebook+ env:+ MAX_STEPS: ${{ inputs.max_steps || '8' }}+ CHAT_MODEL: ${{ inputs.chat_model || 'unsloth/Qwen3.5-2B-GGUF' }}+ TRAIN_MODEL: ${{ inputs.train_model || 'unsloth/Qwen2.5-0.5B-Instruct' }}+ SKIP_UI: ${{ inputs.skip_ui }}+ run: |+ ARGS="--max-steps $MAX_STEPS --chat-model $CHAT_MODEL --train-model $TRAIN_MODEL"+ if [ "$SKIP_UI" = "true" ]; then+ ARGS="$ARGS --skip-ui"+ echo "::warning title=UI driver disabled::this run was dispatched with skip_ui, so tests/studio/playwright_chat_ui.py did not run and the browser path is unmeasured."+ fi+ python .github/scripts/kaggle_studio_ci/build_kernel.py \+ --payload-dir tests/kaggle/studio_gpu \+ --out kernel.ipynb \+ --unsloth-ref '${{ steps.ref.outputs.ref }}' \+ --payload-args "$ARGS" \+ --per-run-timeout 3900++ # kernel-timeout-sec is the load-bearing budget control: Kaggle itself+ # kills the session at that point. A runner that is cancelled cannot+ # clean up after itself, so the ceiling has to be enforced on Kaggle's+ # side rather than here.+ #+ # The launcher is shared with the notebook leg and is used unchanged:+ # this payload prints the same T4_SMOKE_REPORT line, so the transport+ # needed no modification.+ - name: Launch on Kaggle and collect+ id: launch+ env:+ KAGGLE_API_TOKEN: ${{ secrets.KAGGLE_ACCESS_TOKEN_GH }}+ run: |+ python .github/scripts/kaggle_t4_ci/launch.py \+ --notebook kernel.ipynb \+ --user danielhanchen \+ --outdir kaggle_evidence \+ --expect 1 \+ --kernel-timeout-sec 4200 \+ --max-wait 5400 \+ --poll-every 60++ # The launcher collects executed notebooks and the kernel log and+ # nothing else, deliberately. The payload therefore encodes its+ # screenshots and logs into its own cell output; this puts them back.+ - name: Unpack the Playwright evidence+ if: always()+ run: |+ python .github/scripts/kaggle_studio_ci/collect_evidence.py \+ --evidence kaggle_evidence \+ --outdir studio_evidence++ # always(): the evidence is most valuable exactly when something went+ # wrong. Screenshots only travel on a failing run, so a passing upload+ # is kilobytes.+ - name: Upload evidence+ if: always()+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: kaggle-studio-gpu-evidence+ path: |+ kaggle_evidence/**+ studio_evidence/**+ kernel.ipynb+ # 14 rather than the repo's usual 7. This job runs on a minority of+ # commits, so two consecutive samples can be a fortnight apart, and+ # comparing them is the main reason to keep the evidence at all.+ retention-days: 14+ if-no-files-found: warn++ - name: Report+ if: always()+ run: |+ python .github/scripts/kaggle_studio_ci/report.py \+ --evidence kaggle_evidencediff --git a/tests/kaggle/studio_gpu/gpu_assert.py b/tests/kaggle/studio_gpu/gpu_assert.pynew file mode 100644index 00000000000..3a9b1faa587--- /dev/null+++ b/tests/kaggle/studio_gpu/gpu_assert.py@@ -0,0 +1,343 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Did the GGUF actually run on the GPU, or did it quietly fall back to CPU?++This module is the whole reason the Studio Kaggle leg is worth its quota. A+CPU fallback in Studio is invisible from the outside: llama.cpp loads the same+file, answers the same prompt, and returns the same text, only slower. Every+Studio inference check in this repo today would pass against a CPU-only+build, because every one of them runs on a machine that has no GPU to fall+back from.++So "the model produced text" is explicitly NOT evidence here. The verdict is+built from three independent observations, and the rules are stated up front+because the interesting cases are the ambiguous ones:++**Negative evidence is conclusive.** llama.cpp saying it offloaded 0 layers,+Studio reporting ``cpu_fallback_reason``, or Studio reporting an effective+``gpu_layers`` of 0 each fail on their own. No amount of positive evidence+overrides them: they are the fallback announcing itself.++**Positive evidence has to come from somewhere.** At least one of++* the llama-server process appearing in ``nvidia-smi --query-compute-apps``+ with a non-trivial resident allocation,+* llama.cpp's own load line reporting N of M layers offloaded with N > 0,+* device-wide VRAM in use climbing by more than a model's worth across the+ load,++must hold. Any one of them is enough; requiring all three would turn a+container quirk into a red pull request.++**Silence is a failure, not a pass.** If all three come back unreadable, the+verdict is FAIL. That is the deliberate asymmetry this file exists for: the+question being asked is "prove the GPU was used", and an unanswerable+question has not proved it. Three independent probes are enough that all of+them going blank is itself worth looking at.++The one known way to get a blank first probe is a container whose PID+namespace does not match the one nvidia-smi reports, where+``--query-compute-apps`` lists nothing at all even under load. That is why it+is not the only probe.+"""++from __future__ import annotations++import json+import re+from pathlib import Path++# A llama-server holding less than this on the card is not offloading+# anything worth calling offload -- CUDA context plus scratch alone is tens of+# MiB, and a fully CPU-resident model can still show a context-sized+# allocation if anything touched the device.+MIN_PROCESS_VRAM_MIB = 96++# Device-wide growth across the load that no CPU-resident model explains.+MIN_DEVICE_VRAM_DELTA_MIB = 256++# GGUF's four-byte file magic. Checked before anything tries to load a file+# the export path claims to have written: a truncated or half-moved file is a+# far more likely export bug than a wrong-magic one, and both look like a+# present file to `os.path.exists`.+GGUF_MAGIC = b"GGUF"++# llama.cpp's own load report, e.g.+# load_tensors: offloaded 29/29 layers to GPU+_OFFLOAD_RE = re.compile(r"offloaded\s+(\d+)\s*/\s*(\d+)\s+layers?\s+to\s+GPU")++# e.g. "load_tensors: CUDA0 model buffer size = 1918.35 MiB"+_CUDA_BUFFER_RE = re.compile(+ r"(CUDA\d+|ROCm\d+)\s+model buffer size\s*=\s*([0-9]+(?:\.[0-9]+)?)\s*MiB",+ re.IGNORECASE,+)++# Install kinds from studio/install_llama_prebuilt.py that mean the binaries+# on disk carry CUDA kernels. Anything else -- linux-cpu, linux-vulkan,+# linux-rocm -- is not the build this leg exists to exercise.+CUDA_INSTALL_KINDS = frozenset({"linux-cuda", "linux-arm64-cuda"})++# "cuda12", "cuda13", and whatever major comes next, anywhere in a runtime+# line or an asset filename. Anchored on the digit so "cudart" or a repo name+# containing "cuda" cannot match on its own.+_CUDA_RUNTIME_RE = re.compile(r"cuda\d+")+++def parse_compute_apps(csv_text: str) -> dict[int, int]:+ """``nvidia-smi --query-compute-apps=pid,used_gpu_memory`` as {pid: MiB}.++ Accepts the ``--format=csv,noheader,nounits`` shape and tolerates the unit+ suffix being present anyway, because which of the two you get depends on+ the driver version and getting it wrong silently yields an empty dict.+ """+ apps: dict[int, int] = {}+ for line in csv_text.splitlines():+ line = line.strip()+ if not line or line.lower().startswith("pid"):+ continue+ parts = [p.strip() for p in line.split(",")]+ if len(parts) < 2:+ continue+ try:+ pid = int(parts[0])+ except ValueError:+ continue+ mem = parts[1].replace("MiB", "").replace("MB", "").strip()+ if mem.lower() in ("[n/a]", "n/a", ""):+ continue+ try:+ apps[pid] = int(float(mem))+ except ValueError:+ continue+ return apps+++def offloaded_layers(log_text: str) -> tuple[int, int] | None:+ """The last ``offloaded N/M layers to GPU`` in a llama.cpp log.++ The last one, not the first: Studio loads a model more than once in a+ session (an export is verified by loading the file it just wrote), and the+ question is always about the most recent load.+ """+ matches = _OFFLOAD_RE.findall(log_text or "")+ if not matches:+ return None+ offloaded, total = matches[-1]+ return int(offloaded), int(total)+++def cuda_buffer_mib(log_text: str) -> float | None:+ """Largest device model-buffer allocation llama.cpp reported, in MiB."""+ matches = _CUDA_BUFFER_RE.findall(log_text or "")+ if not matches:+ return None+ return max(float(size) for _, size in matches)+++def install_kind(marker_path: Path | None) -> str | None:+ """What KIND of llama.cpp bundle is installed, from its marker.++ There is no ``install_kind`` key in UNSLOTH_PREBUILT_INFO.json and there+ never was. ``install_llama_prebuilt.py`` writes ``install_kind`` only into+ the JSON its resolver prints to stdout (line ~7678); the marker it writes+ to disk (~line 5931) records ``asset``, ``tag``, ``runtime_line``,+ ``coverage_class``, ``bundle_profile`` and no kind at all.++ So reading ``install_kind`` from the marker answered None on every box, for+ every bundle, including a perfectly good CUDA one -- six hardware runs+ reported ``install_kind=None`` and failed the export assertion for it while+ a working CUDA llama.cpp sat on disk. The installer said as much when asked+ to install again: "existing llama.cpp install already matches selected+ release b10360-mix-87da1a2; skipping download and install".++ ``runtime_line`` is the field that answers the question actually being+ asked. It is ``cuda12``/``cuda13`` for the CUDA bundles and names the+ non-CUDA backends otherwise, and it is written on the same line of the same+ dict as the asset, so the two cannot disagree. ``asset`` is the fallback+ for a marker old enough to predate it.++ ``None`` in means no marker was found, and answers ``None`` rather than+ raising: ``llama_cpp_marker`` returns ``None`` for that case.+ """+ if marker_path is None:+ return None+ try:+ payload = json.loads(Path(marker_path).read_text(encoding = "utf-8"))+ except Exception: # noqa: BLE001+ return None+ if not isinstance(payload, dict):+ return None+ runtime_line = payload.get("runtime_line")+ if runtime_line:+ return str(runtime_line)+ asset = payload.get("asset")+ return str(asset) if asset else None+++def is_cuda_install(kind: str | None) -> bool:+ """Is this a CUDA bundle?++ ``kind`` is now a ``runtime_line`` (``cuda12``, ``cuda13``, ...) or, for a+ marker too old to carry one, an asset filename like+ ``app-b10360-mix-87da1a2-linux-x64-cuda13-older.tar.gz``. Both are matched+ by looking for a cuda runtime line rather than by equality against a fixed+ set, because the set would need a new entry on every CUDA major and would+ fail closed -- reporting a working cuda14 install as not-CUDA -- which is+ the same failure mode this whole function just spent six runs in.+ """+ if not kind:+ return False+ lowered = str(kind).lower()+ return bool(_CUDA_RUNTIME_RE.search(lowered)) or lowered in CUDA_INSTALL_KINDS+++# Where a llama.cpp install can be, most specific first. STUDIO_HOME is checked+# because a caller may point an install there explicitly; the canonical+# location is what `install_llama_prebuilt.py` uses by default (its+# `Path.home() / ".unsloth" / "llama.cpp"`), and it is where `install.sh+# --local` actually puts one.+def llama_cpp_marker(studio_home: Path) -> Path | None:+ """The UNSLOTH_PREBUILT_INFO.json of the llama.cpp this box will use.++ Five hardware runs reported install_kind=None and failed the export+ assertion for it. There was no missing llama.cpp: install.sh --local had+ installed one into ~/.unsloth/llama.cpp, and this payload was reading+ STUDIO_HOME/llama.cpp, a path nothing ever wrote to. The installer even+ said so when asked to install again --++ existing llama.cpp install already matches selected release+ b10360-mix-87da1a2; skipping download and install++ -- while the directory it had been pointed at stayed empty.++ Returns None when neither location has a marker, which is then a real+ absence rather than a guess about where to look.+ """+ candidates = (+ Path(studio_home) / "llama.cpp" / "UNSLOTH_PREBUILT_INFO.json",+ Path.home() / ".unsloth" / "llama.cpp" / "UNSLOTH_PREBUILT_INFO.json",+ )+ for marker in candidates:+ if marker.is_file():+ return marker+ return None+++def gguf_magic_ok(path: Path) -> bool:+ """Does this file start with GGUF's magic? Cheap, and catches a truncation."""+ try:+ with open(path, "rb") as fh:+ return fh.read(4) == GGUF_MAGIC+ except OSError:+ return False+++def offload_verdict(+ *,+ server_pid: int | None,+ compute_apps: dict[int, int] | None,+ log_text: str,+ device_vram_delta_mib: float | None,+ status: dict | None,+ server_pids: list[int] | None = None,+) -> dict:+ """Was the model on the GPU? Returns a verdict dict with its evidence.++ ``status`` is Studio's ``GET /api/inference/status`` body. Only two of its+ fields are load-bearing here and both are negative signals:+ ``cpu_fallback_reason`` (Studio replayed the launch on CPU) and an+ effective ``gpu_layers`` of exactly 0 (nothing was placed on the card).+ A ``gpu_layers`` of -1 is Studio's Auto mode, which says nothing either+ way and is left to the other probes.+ """+ evidence: list[str] = []+ failures: list[str] = []+ positives: list[str] = []++ status = status or {}+ fallback = status.get("cpu_fallback_reason")+ if fallback:+ failures.append(f"Studio reported a CPU fallback: cpu_fallback_reason={fallback!r}")++ effective_layers = status.get("gpu_layers")+ if isinstance(effective_layers, int):+ evidence.append(f"status.gpu_layers={effective_layers}")+ if effective_layers == 0:+ failures.append(+ "Studio reports gpu_layers=0, so nothing was placed on the GPU "+ "even though the load asked for it"+ )++ counts = offloaded_layers(log_text)+ if counts is None:+ evidence.append("llama.cpp log: no offload line found")+ else:+ offloaded, total = counts+ evidence.append(f"llama.cpp log: offloaded {offloaded}/{total} layers to GPU")+ if offloaded <= 0:+ failures.append(+ f"llama.cpp offloaded {offloaded}/{total} layers, which is the CPU path"+ )+ else:+ positives.append(f"llama.cpp offloaded {offloaded}/{total} layers")++ buffer_mib = cuda_buffer_mib(log_text)+ if buffer_mib is not None:+ evidence.append(f"llama.cpp device model buffer: {buffer_mib:.0f} MiB")++ # Studio's status body carries no pid, so the caller also discovers the+ # llama-server processes itself; either source is accepted here.+ candidates: list[int] = []+ for pid in [server_pid, *(server_pids or [])]:+ if isinstance(pid, int) and pid not in candidates:+ candidates.append(pid)++ if compute_apps is None:+ evidence.append("nvidia-smi compute-apps: unreadable")+ elif not compute_apps:+ evidence.append("nvidia-smi compute-apps: no process listed")+ elif not candidates:+ evidence.append(+ f"nvidia-smi compute-apps: {len(compute_apps)} process(es) listed, but "+ f"no llama-server pid was found to match them against"+ )+ else:+ matched = {pid: compute_apps[pid] for pid in candidates if pid in compute_apps}+ if not matched:+ evidence.append(+ f"nvidia-smi compute-apps: llama-server pid(s) "+ f"{', '.join(str(p) for p in candidates)} are not among the "+ f"{len(compute_apps)} process(es) holding GPU memory"+ )+ for pid, used in matched.items():+ evidence.append(f"nvidia-smi compute-apps: pid {pid} holds {used} MiB")+ if used >= MIN_PROCESS_VRAM_MIB:+ positives.append(f"llama-server pid {pid} holds {used} MiB of VRAM")+ else:+ evidence.append(+ f"that is below the {MIN_PROCESS_VRAM_MIB} MiB floor, so it is "+ f"consistent with a bare CUDA context and no weights"+ )++ if device_vram_delta_mib is None:+ evidence.append("device VRAM delta: unreadable")+ else:+ evidence.append(f"device VRAM delta across the load: {device_vram_delta_mib:.0f} MiB")+ if device_vram_delta_mib >= MIN_DEVICE_VRAM_DELTA_MIB:+ positives.append(f"device VRAM in use grew by {device_vram_delta_mib:.0f} MiB")++ if not failures and not positives:+ failures.append(+ "no probe could show the GPU was used: the process was not visible to "+ "nvidia-smi, llama.cpp logged no offload line, and device VRAM did not "+ "move. Text was returned, but nothing here distinguishes that from a "+ "CPU fallback, so this is a failure rather than a pass"+ )++ return {+ "passed": not failures,+ "failures": failures,+ "positives": positives,+ "evidence": evidence,+ }diff --git a/tests/kaggle/studio_gpu/run_studio_gpu.py b/tests/kaggle/studio_gpu/run_studio_gpu.pynew file mode 100644index 00000000000..4c4b9f6a95e--- /dev/null+++ b/tests/kaggle/studio_gpu/run_studio_gpu.py@@ -0,0 +1,1344 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Unsloth Studio, end to end, on a real CUDA GPU.++Studio has no CUDA coverage anywhere in CI. Every Studio workflow in this+repo runs on ``ubuntu-latest``, ``macos-15`` or ``windows-latest``; macOS+gives Metal some hardware, and the CUDA path is exercised by nothing. The+existing inference smoke deliberately uses a 270M GGUF *because* it has to+decode on a CPU. This payload is the other half: it runs Studio on a Kaggle+T4 and asserts the three things that only a GPU can answer.++What it asserts+---------------+**A. GGUF inference is on the GPU, and tool calling works.** A model is+loaded with an explicit manual GPU-layer pin and then the payload tries three+independent ways to catch a CPU fallback -- process-level VRAM from+nvidia-smi, llama.cpp's own offload line, and device-wide VRAM growth. See+``gpu_assert.offload_verdict``: "the model returned text" is not evidence,+and no evidence at all is a failure rather than a pass. Then tool calling,+through ``/v1/chat/completions`` with ``tool_choice: "required"``, asserting+the model came back with ``finish_reason == "tool_calls"`` and a parseable+argument object.++**B. A LoRA training run finishes and leaves an adapter.** Started through+``POST /api/train/start`` -- the same call Studio's own Train button makes --+and judged on three things, none of which is the phase alone: the run reaches+phase ``completed``, its ``metric_history`` holds a loss for every step it+claimed to take, and ``adapter_model.safetensors`` exists on disk above a size+floor. A run that formats its dataset down to zero rows reaches ``completed``+too, which is why the step count is checked; a save that silently no-ops+leaves a config and no weights, which is why the file is checked.++**C. GGUF export runs against a CUDA llama.cpp build and the result loads.**+The adapter from B is exported to GGUF, the output is checked for the GGUF+magic rather than merely for existence, and then it is loaded back into+Studio and asked to generate. "It loads" is asserted by loading it, not by+its file size.++Then the repo's existing ``tests/studio/playwright_chat_ui.py`` is driven+against the same server, so the browser path is exercised by the driver that+already exists rather than by new automation. It runs LAST because its final+phase clicks "Stop server" and asserts the port closes.++Kaggle specifics+----------------+``/kaggle/working`` is 19.5 GB and is also what ``kernels output`` ships+back; the home directory and ``/tmp`` share a ~1 TB overlay. So+``UNSLOTH_STUDIO_HOME``, the HF cache, the llama.cpp build and every model+live on the overlay, and only the evidence -- kilobytes of JSON, a log tail+and screenshots -- is ever written under ``/kaggle/working``.++No credential is printed. The bootstrap password is read from Studio's own+auth directory, handed to ``/api/auth/login``, and never logged, never+returned, and never written to the report or the evidence bundle.++Usage:+ python run_studio_gpu.py --outdir /kaggle/working/studio_gpu_out \\+ --repo-root ~/unsloth --studio-home ~/studio_home+"""++from __future__ import annotations++import argparse+import base64+import io+import json+import os+import shutil+import subprocess+import sys+import tarfile+import time+from pathlib import Path++_HERE = Path(__file__).resolve().parent+if str(_HERE) not in sys.path:+ sys.path.insert(0, str(_HERE))++from gpu_assert import ( # noqa: E402+ gguf_magic_ok,+ install_kind,+ llama_cpp_marker,+ is_cuda_install,+ offload_verdict,+ parse_compute_apps,+)+from studio_client import ( # noqa: E402+ Studio,+ StudioError,+ adapter_verdict,+ export_verdict,+ health_is_ready,+ newest_gguf,+ nonfinite_losses,+ trained_steps,+ training_verdict,+ wait_for,+)++RESULT_PREFIX = "T4_SMOKE_REPORT "+EVIDENCE_PREFIX = "STUDIO_GPU_EVIDENCE_B64 "++# Base64 characters per printed line. Large enough that a multi-megabyte+# bundle is not tens of thousands of lines, small enough that no single line+# is unreasonable for a notebook cell output to carry.+EVIDENCE_CHUNK = 4096++# Ceiling on the evidence bundle. It travels back inside the executed+# notebook's cell output, which is the only channel the shared launcher+# collects, so it competes with the notebook itself for the download.+MAX_EVIDENCE_BYTES = 2_500_000++# Last resort when the redacted logs alone are over the cap: keep the tail of+# each, which is where a failure's traceback is, rather than dropping them.+MAX_LOG_TAIL_BYTES = 400_000++# Free space the payload refuses to start without. A CUDA llama.cpp bundle,+# a torch stack, two models and a merged 16-bit export do not fit in much+# less, and running out halfway produces a failure that reads like a code bug.+MIN_FREE_GB = 25.0++# The CUDA llama.cpp bundle is a large download and an extraction, and it runs+# once per session before anything needs it. Generous, because the cost of+# being too tight is a red that reads like a selection bug.+LLAMA_CPP_INSTALL_TIMEOUT_S = 900.0+# How long to let VRAM fall after an unload before calling it the baseline.+# 12 x 2.5s bounds the wait at 30s, which is well past the ~3s a llama-server+# takes to exit on the models this harness loads, without stalling the run if+# something else on the card is holding memory.+VRAM_SETTLE_POLL_S = 2.5+VRAM_SETTLE_SAMPLES = 12+# Driver readings jitter by a few MiB between samples; only a real drop counts.+VRAM_SETTLE_TOLERANCE_MIB = 16.0++CANARY = "__UNSLOTH_STUDIO__!!!"++# The tool the model is asked to call. Deliberately trivial and deliberately+# not answerable from parametric knowledge, so "it replied with prose" and+# "it emitted a tool call" cannot be confused.+WEATHER_TOOL = {+ "type": "function",+ "function": {+ "name": "get_weather",+ "description": "Get the current weather in a given city",+ "parameters": {+ "type": "object",+ "properties": {"city": {"type": "string", "description": "City name"}},+ "required": ["city"],+ },+ },+}+++def log(msg: str) -> None:+ print(f"[studio-gpu] {msg}", flush = True)+++def run(cmd: list[str], **kw) -> subprocess.CompletedProcess:+ """Run a command, answering an absent binary the way a failure answers.++ Every caller here judges on ``returncode``, and a box with no nvidia-smi+ at all -- a session Kaggle handed no driver -- otherwise raised+ FileNotFoundError out of ``environment()`` inside ``finish()``, so the run+ ended with a traceback and no report instead of a preflight that says+ there is no GPU.+ """+ try:+ return subprocess.run(cmd, capture_output = True, text = True, **kw)+ except OSError as exc:+ return subprocess.CompletedProcess(cmd, 127, "", f"{type(exc).__name__}: {exc}")+++def nvidia_used_mib() -> float | None:+ """Device-wide VRAM in use, summed over every visible GPU."""+ proc = run(+ ["nvidia-smi", "--query-gpu=memory.used", "--format=csv,noheader,nounits"],+ timeout = 60,+ )+ if proc.returncode != 0:+ return None+ total = 0.0+ seen = False+ for line in proc.stdout.splitlines():+ line = line.strip()+ if not line:+ continue+ try:+ total += float(line)+ seen = True+ except ValueError:+ continue+ return total if seen else None+++def nvidia_compute_apps() -> dict[int, int] | None:+ proc = run(+ ["nvidia-smi", "--query-compute-apps=pid,used_gpu_memory", "--format=csv,noheader,nounits"],+ timeout = 60,+ )+ if proc.returncode != 0:+ return None+ return parse_compute_apps(proc.stdout)+++def gpu_inventory() -> list[str]:+ proc = run(+ ["nvidia-smi", "--query-gpu=name,memory.total,compute_cap", "--format=csv,noheader"],+ timeout = 60,+ )+ if proc.returncode != 0:+ return []+ return [line.strip() for line in proc.stdout.splitlines() if line.strip()]+++def log_paths(server_log: Path, studio_home: Path) -> list[Path]:+ """Every file Studio or a llama-server child may be writing to.++ llama.cpp's offload line lands in whichever of these the server's stderr+ was wired to, and which one that is depends on how Studio was started, so+ both are read.+ """+ candidates = [server_log]+ log_dir = studio_home / "logs"+ if log_dir.is_dir():+ candidates += sorted(log_dir.rglob("*.log"))+ return candidates+++def log_marks(server_log: Path, studio_home: Path) -> dict[str, int]:+ """Current size of every log, to read forward from later.++ Taken immediately before a model load so the evidence gathered afterwards+ belongs to THAT load. Without it, a reload whose own log line never+ appeared inherited the previous load's ``offloaded N/M layers`` and the+ verdict passed on evidence from a different model.+ """+ marks: dict[str, int] = {}+ for path in log_paths(server_log, studio_home):+ try:+ marks[str(path)] = path.stat().st_size+ except OSError:+ continue+ return marks+++def studio_log_text(+ server_log: Path,+ studio_home: Path,+ tail_bytes: int = 4_000_000,+ *,+ since: dict[str, int] | None = None,+) -> str:+ """Everything Studio and its llama-server children wrote, as one string.++ ``since`` is a ``log_marks()`` snapshot; each file is then read from the+ offset it had then, so only what this load produced comes back. A file+ that has since shrunk was rotated or truncated, and is read whole.+ """+ parts: list[str] = []+ for path in log_paths(server_log, studio_home):+ start = (since or {}).get(str(path), 0)+ try:+ with open(path, "rb") as fh:+ fh.seek(0, io.SEEK_END)+ size = fh.tell()+ if start > size:+ start = 0+ fh.seek(max(start, size - tail_bytes))+ parts.append(fh.read().decode("utf-8", errors = "replace"))+ except OSError:+ continue+ return "\n".join(parts)+++def llama_server_pids() -> list[int]:+ """PIDs of the llama-server children Studio started, from /proc.++ ``GET /api/inference/status`` does not carry one: ``InferenceStatusResponse``+ declares neither ``llama_server_pid`` nor ``pid``, and FastAPI drops+ anything the response model does not declare, so the process-level VRAM+ probe never had a pid to match and could never contribute evidence.+ Reading the process table gives it one back.+ """+ pids: list[int] = []+ proc_root = Path("/proc")+ if not proc_root.is_dir():+ return pids+ for entry in proc_root.iterdir():+ if not entry.name.isdigit():+ continue+ try:+ cmdline = (entry / "cmdline").read_bytes().decode("utf-8", errors = "replace")+ except OSError:+ continue+ argv0 = cmdline.split("\x00", 1)[0]+ if "llama-server" in Path(argv0).name:+ pids.append(int(entry.name))+ return pids+++class Payload:+ def __init__(self, args: argparse.Namespace) -> None:+ self.args = args+ self.outdir = Path(args.outdir)+ self.outdir.mkdir(parents = True, exist_ok = True)+ self.art_dir = self.outdir / "playwright"+ self.studio_home = Path(args.studio_home).expanduser().resolve()+ self.repo_root = Path(args.repo_root).expanduser().resolve()+ self.server_log = self.outdir / "studio.log"+ self.base_url = f"http://127.0.0.1:{args.port}"+ self.studio = Studio(self.base_url)+ self.proc: subprocess.Popen | None = None+ self.assertions: list[dict] = []+ self.failures: list[str] = []+ self.started = time.time()+ # Every secret this run has minted or read. Studio's startup banner+ # prints the bootstrap password to stdout, and stdout here is+ # studio.log, and studio.log travels home in the evidence bundle. The+ # value is ephemeral and local to a kernel that is destroyed minutes+ # later, but "ephemeral" is not the same as "fine to publish in a CI+ # artifact", so every log that leaves this machine is scrubbed of it.+ self.secrets: set[str] = set()++ # ---------------------------------------------------------------- report++ def record(self, name: str, passed: bool, detail: dict) -> bool:+ entry = {"name": name, "passed": bool(passed), **detail}+ self.assertions.append(entry)+ for reason in detail.get("failures", []) or []:+ self.failures.append(f"{name}: {reason}")+ log(f"{'PASS' if passed else 'FAIL'} {name}")+ for reason in detail.get("failures", []) or []:+ log(f" {reason}")+ return passed++ def report(self) -> dict:+ return {+ "label": self.args.label,+ "model": self.args.chat_model,+ "passed": not self.failures,+ "failures": self.failures,+ "assertions": self.assertions,+ "environment": self.environment(),+ "config": {+ "chat_model": self.args.chat_model,+ "chat_variant": self.args.chat_variant,+ "train_model": self.args.train_model,+ "max_steps": self.args.max_steps,+ "quantization": self.args.quantization,+ "gpu_layers": self.args.gpu_layers,+ },+ "seconds": round(time.time() - self.started, 1),+ }++ def environment(self) -> dict:+ env: dict = {"gpus": gpu_inventory()}+ try:+ import torch++ env["torch"] = torch.__version__+ env["cuda"] = torch.version.cuda+ env["gpu_count"] = torch.cuda.device_count()+ if torch.cuda.is_available():+ env["gpu_name"] = torch.cuda.get_device_name(0)+ env["gpu_capability"] = ".".join(+ str(x) for x in torch.cuda.get_device_capability(0)+ )+ except Exception as exc: # noqa: BLE001+ env["torch_error"] = f"{type(exc).__name__}: {exc}"+ marker = llama_cpp_marker(self.studio_home)+ env["llama_cpp_install_kind"] = install_kind(marker)+ return env++ # ------------------------------------------------------------- preflight++ def preflight(self) -> bool:+ failures: list[str] = []+ detail: dict = {}++ gpus = gpu_inventory()+ detail["gpus"] = gpus+ if not gpus:+ failures.append("nvidia-smi listed no GPU, so this is not a GPU session")++ try:+ import torch+ detail["cuda_available"] = bool(torch.cuda.is_available())+ if not torch.cuda.is_available():+ failures.append("torch.cuda.is_available() is False")+ except Exception as exc: # noqa: BLE001+ failures.append(f"could not import torch: {type(exc).__name__}: {exc}")++ self.studio_home.mkdir(parents = True, exist_ok = True)+ free_gb = shutil.disk_usage(self.studio_home).free / 1e9+ detail["studio_home"] = str(self.studio_home)+ detail["free_gb"] = round(free_gb, 1)+ if free_gb < MIN_FREE_GB:+ failures.append(+ f"only {free_gb:.1f} GB free at {self.studio_home}, below the "+ f"{MIN_FREE_GB} GB floor. On Kaggle this usually means "+ f"UNSLOTH_STUDIO_HOME landed under /kaggle/working (19.5 GB) "+ f"instead of the home/tmp overlay"+ )++ driver = self.repo_root / "tests" / "studio" / "playwright_chat_ui.py"+ detail["chat_driver"] = str(driver)+ if not driver.is_file():+ failures.append(f"the existing chat UI driver is not where it should be: {driver}")++ detail["failures"] = failures+ return self.record("preflight", not failures, detail)++ # ---------------------------------------------------------------- server++ def studio_command(self) -> list[str]:+ """The `unsloth` entry point of the interpreter running this payload.++ NOT ``shutil.which("unsloth")``. This payload runs under the Studio+ venv's Python and that venv's ``bin`` is not on PATH, so a global+ ``unsloth`` anywhere on PATH would win the lookup and the run would+ measure some other installation instead of the checkout under test.+ The console script sits next to ``sys.executable``; if it is missing,+ the same interpreter runs the module directly.+ """+ bin_dir = Path(sys.executable).parent+ for name in ("unsloth", "unsloth.exe"):+ candidate = bin_dir / name+ if candidate.is_file() and os.access(candidate, os.X_OK):+ head = [str(candidate)]+ break+ else:+ head = [sys.executable, "-c", "from unsloth_cli import app; app()"]+ return head + ["studio", "-H", "127.0.0.1", "-p", str(self.args.port)]++ def start_server(self) -> bool:+ # An absent auth directory is what re-seeds the bootstrap password;+ # `reset-password` does not. Same thing the repo's own+ # boot-studio-api-only.sh does, for the same reason.+ shutil.rmtree(self.studio_home / "auth", ignore_errors = True)++ env = dict(os.environ)+ env["UNSLOTH_STUDIO_HOME"] = str(self.studio_home)+ env.setdefault("HF_HOME", str(self.studio_home / "cache" / "huggingface"))+ env["PYTHONUNBUFFERED"] = "1"+ env["UNSLOTH_DISABLE_STATISTICS"] = "1"++ cmd = self.studio_command()+ log(f"starting Studio: {' '.join(cmd)}")+ # Append, never truncate. assert_chat_ui() restarts the server to+ # re-seed the account, and a "wb" here threw away every backend log+ # from the inference, training and export assertions before the+ # evidence bundle was built -- so a GPU failure followed by the normal+ # UI phase shipped an artifact containing only the UI session.+ handle = open(self.server_log, "ab")+ self.proc = subprocess.Popen(+ cmd,+ cwd = str(self.repo_root),+ env = env,+ stdout = handle,+ stderr = subprocess.STDOUT,+ )++ ok, last, reason = wait_for(+ probe = lambda: self.studio.get("/api/health", auth = False)[1],+ accept = health_is_ready,+ deadline_s = self.args.health_deadline,+ interval_s = 2.0,+ alive = self.server_alive,+ )+ detail: dict = {"health": last if isinstance(last, dict) else str(last)[:400]}+ failures = []+ if not ok:+ failures.append(f"Studio never became ready: {reason}")+ failures.append("last 40 lines of the server log: " + self.log_tail(40))+ detail["failures"] = failures+ return self.record("studio_ready", ok, detail)++ def remember_bootstrap(self) -> str | None:+ """Learn the bootstrap password so it can be scrubbed, not so it can be used."""+ path = self.studio_home / "auth" / ".bootstrap_password"+ try:+ value = path.read_text(encoding = "utf-8").strip()+ except OSError:+ return None+ if value:+ self.secrets.add(value)+ return value or None++ def scrub(self, text: str) -> str:+ for secret in self.secrets:+ if secret:+ text = text.replace(secret, "[redacted]")+ return text++ def log_tail(self, lines: int) -> str:+ # Studio's startup banner prints the bootstrap password, and this tail+ # is put in front of a human on a pull request when startup fails.+ self.remember_bootstrap()+ try:+ text = self.server_log.read_text(encoding = "utf-8", errors = "replace")+ except OSError:+ return "(no server log)"+ return self.scrub(" | ".join(text.splitlines()[-lines:]))++ def authenticate(self) -> bool:+ path = self.studio_home / "auth" / ".bootstrap_password"+ failures: list[str] = []+ if not path.is_file():+ failures.append(f"no bootstrap password was seeded at {path}")+ return self.record("authenticate", False, {"failures": failures})+ # Read, use, drop. The value is never logged and never reaches the+ # report; it is remembered only so it can be scrubbed out of the logs+ # that do leave this machine.+ password = self.remember_bootstrap() or ""+ try:+ self.studio.login(password)+ except StudioError as exc:+ failures.append(str(exc))+ return self.record("authenticate", not failures, {"failures": failures})++ def server_alive(self) -> bool:+ return self.proc is not None and self.proc.poll() is None++ def stop_server(self) -> None:+ if self.proc is None or self.proc.poll() is not None:+ return+ self.proc.terminate()+ try:+ self.proc.wait(timeout = 60)+ except subprocess.TimeoutExpired:+ self.proc.kill()++ # ----------------------------------------------------------- assertion A++ def settled_baseline(self) -> float | None:+ """VRAM after anything already loaded has been evicted and freed.++ `POST /load` with `force` unloads the previous model as its first act,+ so sampling the baseline just before the request puts that release+ INSIDE the measured window. Run 7 read `device_vram_delta_mib: -1866.0`+ for the GGUF export probe: a 531 MB model loading while a 3004 MiB chat+ model left, reported as negative growth and scored as a failure to+ reach the GPU. The load was fine; the ruler was wrong.++ Unloading first and waiting for the number to stop falling makes the+ delta measure one thing. Best-effort throughout: an unload that fails+ leaves the old baseline behaviour rather than aborting the probe, and+ the delta is only ever evidence, never the sole assertion.+ """+ code, body = self.studio.get("/api/inference/status")+ active = None+ if code == 200 and isinstance(body, dict):+ # Field names from InferenceStatusResponse, not from guesswork.+ # `model_identifier` is documented as the LOADABLE identifier,+ # which is what /unload's `model_path` wants; `active_model` is a+ # display string and only a fallback. Run 8 read three names that+ # the response has never carried, so `active` was always None, no+ # unload was ever sent, and the delta came back byte-identical to+ # run 7 -- a fix that ran and did nothing.+ active = body.get("model_identifier") or body.get("active_model")+ if not active:+ loaded = body.get("loaded")+ if isinstance(loaded, list) and loaded:+ active = loaded[0]+ if isinstance(active, str) and active:+ try:+ self.studio.post(+ "/api/inference/unload",+ {"model_path": active, "force_cancel_active": True},+ timeout = self.args.load_timeout,+ )+ except StudioError:+ pass+ # Freeing is asynchronous: llama-server exits and the driver reclaims+ # afterwards, so an immediate read still sees the old model resident.+ # Settle on two consecutive samples that did not drop.+ previous = nvidia_used_mib()+ for _ in range(VRAM_SETTLE_SAMPLES):+ time.sleep(VRAM_SETTLE_POLL_S)+ current = nvidia_used_mib()+ if previous is None or current is None:+ return current+ if current >= previous - VRAM_SETTLE_TOLERANCE_MIB:+ return current+ previous = current+ return previous++ def load_model(self, model_path: str, *, variant: str | None, label: str) -> dict:+ """Load a GGUF with an explicit GPU pin and judge whether it landed there."""+ before = self.settled_baseline()+ body = {+ "model_path": model_path,+ "is_lora": False,+ "max_seq_length": 2048,+ # Manual, not Auto. Auto (`gpu_layers: -1`) delegates placement to+ # llama.cpp's fitter, and a fitter that decided on zero layers is+ # indistinguishable in the response from one that filled the card.+ # Pinning states the intent, so `status.gpu_layers` coming back+ # different is itself a finding.+ "gpu_memory_mode": "manual",+ "gpu_layers": self.args.gpu_layers,+ "force": True,+ }+ if variant:+ body["gguf_variant"] = variant++ failures: list[str] = []+ status_body: dict = {}+ # Everything already in the logs belongs to an EARLIER load. Only what+ # is written past this mark is evidence about this one.+ marks = log_marks(self.server_log, self.studio_home)+ try:+ self.studio.expect("POST", "/api/inference/load", body, timeout = self.args.load_timeout)+ except StudioError as exc:+ failures.append(str(exc))+ else:+ code, status_body = self.studio.get("/api/inference/status")+ if code != 200 or not isinstance(status_body, dict):+ failures.append(f"GET /api/inference/status returned HTTP {code}")+ status_body = {}++ after = nvidia_used_mib()+ delta = None if (before is None or after is None) else after - before++ # The status response declares no pid field, so the processes are+ # discovered here instead. See llama_server_pids().+ server_pids = llama_server_pids()+ verdict = offload_verdict(+ server_pid = None,+ server_pids = server_pids,+ compute_apps = nvidia_compute_apps(),+ log_text = studio_log_text(self.server_log, self.studio_home, since = marks),+ device_vram_delta_mib = delta,+ status = status_body,+ )+ failures += verdict["failures"]++ requested = self.args.gpu_layers+ effective = status_body.get("gpu_layers")+ if isinstance(effective, int) and effective not in (requested, -1):+ # Not a failure on its own: llama.cpp clamps a pin to the model's+ # block count, which is the common and correct reason for this.+ verdict["evidence"].append(+ f"requested gpu_layers={requested}, Studio reports {effective} "+ f"(a clamp to the model's layer count looks like this)"+ )++ return {+ "model": model_path,+ "variant": variant,+ "requested_gpu_layers": requested,+ "effective_gpu_layers": effective,+ "llama_server_pids": server_pids,+ "device_vram_delta_mib": None if delta is None else round(delta, 1),+ "evidence": verdict["evidence"],+ "positives": verdict["positives"],+ "failures": failures,+ "label": label,+ }++ def chat(self, messages: list[dict], **extra) -> tuple[int, object]:+ body = {+ "model": "default",+ "messages": messages,+ "max_tokens": 128,+ "temperature": 0.0,+ "seed": 3407,+ "enable_thinking": False,+ **extra,+ }+ return self.studio.post("/v1/chat/completions", body, timeout = self.args.chat_timeout)++ def assert_gpu_inference(self) -> bool:+ detail = self.load_model(+ self.args.chat_model,+ variant = self.args.chat_variant,+ label = "chat",+ )+ if not detail["failures"]:+ code, payload = self.chat([{"role": "user", "content": "What is 1+1? Answer briefly."}])+ text = ""+ if code == 200 and isinstance(payload, dict):+ choices = payload.get("choices") or [{}]+ text = (choices[0].get("message") or {}).get("content") or ""+ detail["generated"] = text[:200]+ if code != 200:+ detail["failures"].append(f"/v1/chat/completions returned HTTP {code}")+ elif not text.strip():+ detail["failures"].append("the model on the GPU returned empty content")+ return self.record("gpu_inference", not detail["failures"], detail)++ def assert_tool_calling(self) -> bool:+ failures: list[str] = []+ detail: dict = {}+ code, payload = self.chat(+ [{"role": "user", "content": "What is the weather in Paris right now?"}],+ tools = [WEATHER_TOOL],+ tool_choice = "required",+ max_tokens = 256,+ )+ detail["http_status"] = code+ if code != 200 or not isinstance(payload, dict):+ failures.append(f"tool-calling completion returned HTTP {code}")+ detail["failures"] = failures+ return self.record("tool_calling", False, detail)++ choice = (payload.get("choices") or [{}])[0]+ detail["finish_reason"] = choice.get("finish_reason")+ calls = (choice.get("message") or {}).get("tool_calls") or []+ detail["tool_calls"] = [c.get("function", {}).get("name") for c in calls]++ if choice.get("finish_reason") != "tool_calls":+ failures.append(+ f"finish_reason was {choice.get('finish_reason')!r}, not 'tool_calls', "+ f"so the model answered in prose instead of calling the tool"+ )+ if not calls:+ failures.append("no tool_calls were returned")+ else:+ fn = calls[0].get("function") or {}+ if fn.get("name") != "get_weather":+ failures.append(f"called {fn.get('name')!r} rather than 'get_weather'")+ try:+ arguments = json.loads(fn.get("arguments") or "{}")+ except json.JSONDecodeError as exc:+ failures.append(f"tool-call arguments were not JSON: {exc}")+ else:+ detail["arguments"] = arguments+ if not arguments.get("city"):+ failures.append("the tool call carried no 'city' argument")++ detail["failures"] = failures+ return self.record("tool_calling", not failures, detail)++ # ----------------------------------------------------------- assertion B++ def assert_training(self) -> bool:+ failures: list[str] = []+ detail: dict = {}++ dataset = self.studio_home / "assets" / "datasets" / "uploads" / "studio_gpu_canary.jsonl"+ dataset.parent.mkdir(parents = True, exist_ok = True)+ shutil.copyfile(_HERE / "train_canary.jsonl", dataset)+ detail["dataset"] = str(dataset)++ body = {+ "model_name": self.args.train_model,+ "training_type": "LoRA/QLoRA",+ "format_type": "alpaca",+ "local_datasets": [str(dataset)],+ "project_name": "kaggle-t4-studio-gpu",+ "load_in_4bit": True,+ "max_seq_length": 512,+ "max_steps": self.args.max_steps,+ "num_epochs": 0,+ "batch_size": 1,+ "gradient_accumulation_steps": 1,+ # A string, not a float: TrainingStartRequest.learning_rate is+ # declared as str and a float here is a 422.+ "learning_rate": "2e-4",+ "lora_r": 8,+ "lora_alpha": 16,+ # Above max_steps on purpose. An intermediate checkpoint would+ # double the disk this run needs and add nothing: the assertion is+ # about the final adapter.+ "save_steps": 10_000,+ "random_seed": 3407,+ }++ try:+ started = self.studio.expect(+ "POST", "/api/train/start", body, timeout = self.args.chat_timeout+ )+ except StudioError as exc:+ detail["failures"] = [str(exc)]+ return self.record("lora_training", False, detail)++ detail["job_id"] = started.get("job_id") if isinstance(started, dict) else None+ detail["start_status"] = started.get("status") if isinstance(started, dict) else None+ if detail["start_status"] != "queued":+ failures.append(+ f"/api/train/start answered status={detail['start_status']!r} rather than "+ f"'queued': {started.get('error') or started.get('message')}"+ )+ detail["failures"] = failures+ return self.record("lora_training", False, detail)++ terminal_reason = {"why": ""}++ def _accept(status) -> bool:+ done, why = training_verdict(status)+ if why:+ terminal_reason["why"] = why+ return done++ ok, last, reason = wait_for(+ probe = lambda: self.studio.get("/api/train/status")[1],+ accept = _accept,+ deadline_s = self.args.train_deadline,+ interval_s = 5.0,+ # A Studio that died mid-training answers every status request+ # with an error, which wait_for retries -- for the whole 1200s+ # deadline, out of a 70-minute session, before reporting it as+ # slowness rather than as death.+ alive = self.server_alive,+ )+ status = last if isinstance(last, dict) else {}+ detail["phase"] = status.get("phase")+ detail["steps_with_loss"] = trained_steps(status)+ detail["nonfinite_losses"] = len(nonfinite_losses(status))+ detail["output_dir"] = (status.get("details") or {}).get("output_dir")++ if not ok:+ failures.append(f"training never reached a terminal phase: {reason}")+ elif terminal_reason["why"]:+ failures.append(terminal_reason["why"])+ else:+ # `completed` is the worker's own bookkeeping. These two are the+ # run's output, and they are what a false green would have to+ # forge.+ if detail["nonfinite_losses"]:+ # A T4 has no bf16, so this trains in fp16, and an fp16 run+ # that diverges still reaches `completed` and still saves an+ # adapter. NaN is not a loss.+ failures.append(+ f"{detail['nonfinite_losses']} of the logged losses are NaN or "+ f"infinite, so the run diverged rather than trained"+ )+ if detail["steps_with_loss"] < self.args.max_steps:+ failures.append(+ f"the run reported completed but logged a finite loss for only "+ f"{detail['steps_with_loss']} of {self.args.max_steps} steps, so it did "+ f"not train what it claimed to"+ )+ adapter_ok, adapter_failures, adapter_detail = adapter_verdict(detail["output_dir"])+ detail.update(adapter_detail)+ if not adapter_ok:+ failures += adapter_failures++ detail["failures"] = failures+ return self.record("lora_training", not failures, detail)++ # ----------------------------------------------------------- assertion C++ def install_llama_cpp(self) -> bool:+ """Put a CUDA llama.cpp under STUDIO_HOME before anything asks for one.++ Four hardware runs reported ``install_kind=None`` and failed the export+ assertion for it, and the reason was never subtle: nothing had ever+ installed a llama.cpp at all. The export route falls back to whatever+ it can find, so the assertion was measuring an absence.++ Its own assertion rather than a step inside the export one, because+ "the CUDA bundle would not install on this box" and "the CUDA bundle+ installed and the export against it failed" are different findings and+ only the second is about exporting.++ A failure here is NOT fatal to the run. The export assertion still+ executes and still reports the install_kind it found, so a box where+ the bundle cannot be installed produces the same honest red it did+ before rather than skipping the export entirely.+ """+ detail: dict = {}+ installer = self.repo_root / "studio" / "install_llama_prebuilt.py"+ detail["installer"] = str(installer)+ if not installer.is_file():+ return self.record(+ "llama_cpp_install",+ False,+ {**detail, "failures": [f"the installer is not where it should be: {installer}"]},+ )++ install_dir = self.studio_home / "llama.cpp"+ # What was there BEFORE. build_kernel.py runs `install.sh --local`,+ # which its own comment says puts a llama.cpp on disk, so "None after+ # install.sh" and "a CPU bundle after install.sh" are different bugs+ # and this step would hide the difference by fixing both. Recording the+ # prior state keeps the original question answerable.+ detail["install_kind_before"] = install_kind(llama_cpp_marker(self.studio_home))+ env = dict(os.environ)+ env["UNSLOTH_STUDIO_HOME"] = str(self.studio_home)+ # `run` already applies capture_output and text; passing them again is+ # a TypeError, and it is one no test here would reach.+ try:+ proc = run(+ [sys.executable, str(installer), "--install-dir", str(install_dir)],+ env = env,+ timeout = LLAMA_CPP_INSTALL_TIMEOUT_S,+ )+ except subprocess.TimeoutExpired:+ return self.record(+ "llama_cpp_install",+ False,+ {+ **detail,+ "failures": [+ f"the llama.cpp installer did not finish within "+ f"{LLAMA_CPP_INSTALL_TIMEOUT_S:.0f}s"+ ],+ },+ )+ detail["returncode"] = proc.returncode+ # The selection log is the whole diagnostic when a CUDA host gets a CPU+ # bundle: install_llama_prebuilt.py explains its choice line by line.+ detail["stdout_tail"] = self.scrub(proc.stdout or "")[-2000:]+ detail["stderr_tail"] = self.scrub(proc.stderr or "")[-2000:]++ kind = install_kind(llama_cpp_marker(self.studio_home))+ detail["llama_cpp_install_kind"] = kind++ failures: list[str] = []+ if proc.returncode != 0:+ failures.append(f"the llama.cpp installer exited {proc.returncode}")+ elif not is_cuda_install(kind):+ # Reaching here means the installer SUCCEEDED and still chose a+ # non-CUDA bundle on a box with a working NVIDIA driver, which is+ # the selection regression this leg exists to catch. Distinct from+ # the installer failing, so it is worded distinctly.+ failures.append(+ f"the installer succeeded but selected install_kind={kind!r} on a CUDA "+ f"box; see stdout_tail for its linux_cuda_selection lines"+ )+ detail["failures"] = failures+ return self.record("llama_cpp_install", not failures, detail)++ def assert_gguf_export(self, adapter_dir: str | None) -> bool:+ failures: list[str] = []+ detail: dict = {"adapter_dir": adapter_dir}++ marker = llama_cpp_marker(self.studio_home)+ kind = install_kind(marker)+ detail["llama_cpp_install_kind"] = kind+ if not is_cuda_install(kind):+ # Stated as a failure rather than a skip. The whole point of+ # running this leg on a T4 is that the CUDA bundle is the one that+ # gets installed here; a CPU bundle on a machine with a working+ # NVIDIA driver means the selection in install_llama_prebuilt.py+ # demoted itself, which is exactly the regression no other job can+ # see.+ failures.append(+ f"the llama.cpp install on this box is install_kind={kind!r}, not a CUDA "+ f"bundle, so the export ran against the same CPU build every other CI job "+ f"already covers"+ )++ if not adapter_dir:+ failures.append("no adapter to export: assertion B did not produce one")+ detail["failures"] = failures+ return self.record("gguf_export", False, detail)++ try:+ self.studio.expect(+ "POST",+ "/api/export/load-checkpoint",+ {"checkpoint_path": adapter_dir, "max_seq_length": 512, "load_in_4bit": True},+ timeout = self.args.export_timeout,+ )+ except StudioError as exc:+ failures.append(f"load-checkpoint failed: {exc}")+ detail["failures"] = failures+ return self.record("gguf_export", False, detail)++ code, before = self.studio.get("/api/export/status")+ baseline_seq = before.get("last_op_seq") if isinstance(before, dict) else None+ baseline_seq = baseline_seq if isinstance(baseline_seq, int) else -1+ detail["baseline_seq"] = baseline_seq++ save_dir = "kaggle_t4_studio_gpu"+ try:+ self.studio.expect(+ "POST",+ "/api/export/export/gguf",+ {+ "save_directory": save_dir,+ "quantization_method": self.args.quantization,+ "push_to_hub": False,+ },+ timeout = self.args.export_timeout,+ )+ except StudioError as exc:+ failures.append(f"export request failed: {exc}")+ detail["failures"] = failures+ return self.record("gguf_export", False, detail)+ except OSError as exc:+ # The route is blocking (routes/export.py awaits the whole export+ # in a thread), and the transport timeout is SHORTER than the+ # export deadline. A merge-convert-quantize that runs past it left+ # the backend still working while this raised an unhandled+ # TimeoutError and crashed the payload. The operation is in+ # flight, not failed: fall through to the status poll, which+ # already knows how to tell "finished" from "never started".+ detail["export_request_timeout"] = f"{type(exc).__name__}: {exc}"+ log(f"the export request timed out in transport ({type(exc).__name__}); still polling")++ terminal_reason = {"why": ""}++ def _accept(status) -> bool:+ done, why = export_verdict(status, baseline_seq)+ if why:+ terminal_reason["why"] = why+ return done++ ok, last, reason = wait_for(+ probe = lambda: self.studio.get("/api/export/status")[1],+ accept = _accept,+ deadline_s = self.args.export_deadline,+ interval_s = 10.0,+ alive = self.server_alive,+ )+ status = last if isinstance(last, dict) else {}+ detail["last_op_status"] = status.get("last_op_status")+ detail["last_op_output_path"] = status.get("last_op_output_path")++ if not ok:+ failures.append(f"the export never finished: {reason}")+ elif terminal_reason["why"]:+ failures.append(terminal_reason["why"])++ gguf = None+ if not failures:+ search_root = Path(status.get("last_op_output_path") or "")+ if not search_root.is_dir():+ search_root = self.studio_home / "exports" / save_dir+ gguf = newest_gguf(search_root)+ detail["search_root"] = str(search_root)+ if gguf is None:+ failures.append(f"the export reported success but no .gguf is under {search_root}")+ else:+ detail["gguf"] = str(gguf)+ detail["gguf_bytes"] = gguf.stat().st_size+ if not gguf_magic_ok(gguf):+ failures.append(+ f"{gguf.name} does not start with the GGUF magic, so the file is "+ f"truncated or is not a GGUF at all"+ )++ if not failures and gguf is not None:+ # "and loads" is asserted by loading it. A size check would pass+ # for a file llama.cpp cannot open.+ reload_detail = self.load_model(str(gguf), variant = None, label = "exported")+ detail["reload"] = reload_detail+ if reload_detail["failures"]:+ failures += [+ f"the exported GGUF did not load on the GPU: {f}"+ for f in reload_detail["failures"]+ ]+ else:+ code, payload = self.chat(+ [{"role": "user", "content": "What is the Unsloth Studio Kaggle canary?"}]+ )+ text = ""+ if code == 200 and isinstance(payload, dict):+ choices = payload.get("choices") or [{}]+ text = (choices[0].get("message") or {}).get("content") or ""+ detail["exported_generated"] = text[:200]+ detail["canary_found"] = CANARY in text+ if code != 200:+ failures.append(f"the exported GGUF returned HTTP {code} on generation")+ elif not text.strip():+ failures.append("the exported GGUF loaded but generated nothing")++ detail["failures"] = failures+ return self.record("gguf_export", not failures, detail)++ # ------------------------------------------------------ existing drivers++ def assert_chat_ui(self) -> bool:+ """Drive the repo's own chat UI driver. Runs last: it stops the server."""+ driver = self.repo_root / "tests" / "studio" / "playwright_chat_ui.py"+ failures: list[str] = []+ detail: dict = {"driver": str(driver)}++ # RE-SEED the account before handing over. The driver's first UI step is+ # "change-password through UI (Setup your account)", which waits for+ # #new-password on the forced-change form -- and authenticate() has to+ # retire the bootstrap password over the API to get past that same gate,+ # so by now Studio shows an ordinary login and the field never appears.+ # Kernel unsloth-t4-ci-412345d2 failed the API assertions on the gate;+ # 9ddd8ae4 fixed those and failed the driver on a stale password;+ # 9c1a3b (this run) fixed the password and failed the driver on the form+ # being gone. The two needs are opposites -- the API wants the change+ # DONE, the driver wants it PENDING -- so they cannot share one account.+ #+ # A restart is the cheap way to give the driver what it expects:+ # start_server() removes $STUDIO_HOME/auth, which is what re-seeds the+ # bootstrap password, and this assertion runs last and stops the server+ # anyway, so nothing after it needs the API session.+ self.stop_server()+ if not self.start_server():+ failures.append("Studio did not come back after the restart that re-seeds the account")+ detail["failures"] = failures+ return self.record("chat_ui_driver", False, detail)+ detail["reseeded"] = True++ current = self.remember_bootstrap() or ""+ if not current:+ failures.append("no bootstrap password was re-seeded, so the driver cannot log in")+ detail["failures"] = failures+ return self.record("chat_ui_driver", False, detail)+ self.secrets.add(current)++ self.art_dir.mkdir(parents = True, exist_ok = True)+ rotated = "KaggleT4-Studio-" + os.urandom(8).hex()+ self.secrets.add(rotated)+ env = dict(os.environ)+ env.update(+ {+ "BASE_URL": self.base_url,+ # The freshly re-seeded bootstrap password: the driver rotates+ # it through the UI and then asserts the old one stops working.+ # Passed through the environment of one child, written nowhere.+ "STUDIO_OLD_PW": current,+ "STUDIO_NEW_PW": rotated,+ "PW_ART_DIR": str(self.art_dir),+ "GGUF_REPO": self.args.chat_model,+ "GGUF_VARIANT": self.args.chat_variant or "",+ # Not strict: STRICT turns a set of cosmetic soft checks+ # (typeahead ordering, theme cycling, nav labels) into hard+ # failures, and none of them is what this leg is spending GPU+ # quota to learn.+ "STUDIO_UI_STRICT": "0",+ # The defaults are sized for a warm ubuntu-latest runner with+ # a cached 270M model. Here the model is larger and the box is+ # busier.+ "STUDIO_UI_WALL_TIMEOUT_S": str(self.args.ui_wall_timeout),+ "STUDIO_UI_LOAD_TIMEOUT_MS": "600000",+ "STUDIO_UI_TURN_TIMEOUT_MS": "180000",+ "PYTHONUNBUFFERED": "1",+ }+ )++ log("running tests/studio/playwright_chat_ui.py")+ try:+ proc = subprocess.run(+ [sys.executable, str(driver)],+ cwd = str(self.repo_root),+ env = env,+ capture_output = True,+ text = True,+ timeout = self.args.ui_wall_timeout + 300,+ )+ rc, out, err = proc.returncode, proc.stdout, proc.stderr+ except subprocess.TimeoutExpired as exc:+ rc = -9+ out = (exc.stdout or b"").decode("utf-8", "replace") if exc.stdout else ""+ err = "the driver outlived its own wall-clock watchdog"++ (self.outdir / "playwright_chat_ui.log").write_text(+ (out or "") + "\n----- stderr -----\n" + (err or ""), encoding = "utf-8"+ )+ detail["returncode"] = rc+ detail["stdout_tail"] = self.scrub(" | ".join((out or "").splitlines()[-25:]))+ detail["stderr_tail"] = self.scrub(" | ".join((err or "").splitlines()[-25:]))+ detail["screenshots"] = sorted(p.name for p in self.art_dir.glob("*.png"))++ if rc != 0:+ failures.append(+ f"playwright_chat_ui.py exited {rc} "+ f"({'wall-clock watchdog' if rc == 2 else 'assertion failure'})"+ )+ detail["failures"] = failures+ return self.record("chat_ui_driver", not failures, detail)++ # -------------------------------------------------------------- evidence++ def redacted(self, path: Path) -> bytes:+ """A log file with every credential this run knows about removed.++ Studio's startup banner prints the bootstrap password, and the chat+ driver's own log echoes what it was given. Both files leave this+ machine as a CI artifact, so both are rewritten on the way out. The+ replacement is a fixed marker rather than a same-length blank, so the+ redaction is visible to whoever reads the artifact.+ """+ self.remember_bootstrap()+ return self.scrub(path.read_text(encoding = "utf-8", errors = "replace")).encode("utf-8")++ def emit_evidence(self, passed: bool) -> None:+ """Ship the artifacts back inside the notebook's own cell output.++ The shared launcher collects executed notebooks and the kernel log and+ nothing else, so a PNG on the Kaggle filesystem is a PNG nobody will+ ever see. Encoding the bundle into stdout is what gets it home. Logs+ and the report always travel; screenshots only on failure, because on+ a pass they are megabytes nobody reads.+ """++ def _pack(*, with_screenshots: bool, log_tail_bytes: int | None = None) -> bytes:+ buf = io.BytesIO()+ with tarfile.open(fileobj = buf, mode = "w:gz") as tar:+ for name in ("studio_gpu_report.json", "playwright_chat_ui.log", "studio.log"):+ path = self.outdir / name+ if path.is_file():+ scrubbed = self.redacted(path)+ if (+ log_tail_bytes is not None+ and name != "studio_gpu_report.json"+ and len(scrubbed) > log_tail_bytes+ ):+ scrubbed = (+ b"[earlier lines dropped to fit the evidence cap]\n"+ + (scrubbed[-log_tail_bytes:])+ )+ info = tarfile.TarInfo(name)+ info.size = len(scrubbed)+ tar.addfile(info, io.BytesIO(scrubbed))+ if with_screenshots:+ for shot in sorted(self.art_dir.glob("*.png")):+ if buf.tell() > MAX_EVIDENCE_BYTES:+ break+ tar.add(shot, arcname = f"playwright/{shot.name}")+ return buf.getvalue()++ blob = _pack(with_screenshots = not passed)+ if len(blob) > MAX_EVIDENCE_BYTES:+ # Screenshots are what blow the cap, so screenshots are what goes.+ # The earlier version rebuilt with the report ALONE while saying it+ # was shipping logs, which discarded studio.log and+ # playwright_chat_ui.log in exactly the failing runs that need+ # them.+ log(f"evidence bundle is {len(blob)} bytes, over the cap; shipping logs only")+ blob = _pack(with_screenshots = False)+ if len(blob) > MAX_EVIDENCE_BYTES:+ log(f"the logs alone are {len(blob)} bytes; shipping their tails")+ blob = _pack(with_screenshots = False, log_tail_bytes = MAX_LOG_TAIL_BYTES)++ encoded = base64.b64encode(blob).decode("ascii")+ chunks = [encoded[i : i + EVIDENCE_CHUNK] for i in range(0, len(encoded), EVIDENCE_CHUNK)]+ for index, chunk in enumerate(chunks):+ print(f"{EVIDENCE_PREFIX}{index + 1}/{len(chunks)} {chunk}", flush = True)++ # ------------------------------------------------------------------ main++ def execute(self) -> int:+ if not self.preflight():+ return self.finish()+ # Before the server, so the export route sees a llama.cpp that was+ # already there rather than one that appeared underneath it. Its+ # result is recorded and deliberately not checked: a box where the+ # bundle will not install should still run every other assertion and+ # report the export failing for the reason it actually failed.+ self.install_llama_cpp()+ if not self.start_server():+ return self.finish()+ if not self.authenticate():+ return self.finish()++ gpu_ok = self.assert_gpu_inference()+ if gpu_ok:+ self.assert_tool_calling()+ else:+ # Tool calling on a CPU fallback would be a green tick for a+ # question nobody asked. Skip it and say so.+ self.record(+ "tool_calling",+ False,+ {"failures": ["skipped: the model was not on the GPU, so this proves nothing"]},+ )++ trained = self.assert_training()+ adapter_dir = None+ for entry in self.assertions:+ if entry["name"] == "lora_training":+ adapter_dir = entry.get("output_dir")+ self.assert_gguf_export(adapter_dir if trained else None)++ if not self.args.skip_ui:+ self.assert_chat_ui()+ return self.finish()++ def finish(self) -> int:+ report = self.report()+ (self.outdir / "studio_gpu_report.json").write_text(+ json.dumps(report, indent = 2), encoding = "utf-8"+ )+ self.stop_server()+ # Evidence FIRST, then the report line. The launcher's extract_reports+ # keeps the first report it sees for each label|model, so a crash in+ # emit_evidence after a pass was printed published PASS and left the+ # corrected failing report to be ignored.+ try:+ self.emit_evidence(report["passed"])+ except Exception as exc: # noqa: BLE001+ self.failures.append(f"evidence packaging failed: {type(exc).__name__}: {exc}")+ report = self.report()+ (self.outdir / "studio_gpu_report.json").write_text(+ json.dumps(report, indent = 2), encoding = "utf-8"+ )+ print(RESULT_PREFIX + json.dumps(report), flush = True)+ return 0 if report["passed"] else 1+++def parse_args(argv: list[str] | None = None) -> argparse.Namespace:+ ap = argparse.ArgumentParser()+ ap.add_argument("--outdir", required = True)+ ap.add_argument("--label", default = "studio-gpu")+ ap.add_argument("--repo-root", required = True, help = "the unsloth checkout under test")+ ap.add_argument("--studio-home", required = True, help = "UNSLOTH_STUDIO_HOME for this run")+ ap.add_argument("--port", type = int, default = 18902)+ ap.add_argument("--chat-model", default = "unsloth/Qwen3.5-2B-GGUF")+ ap.add_argument("--chat-variant", default = "UD-Q4_K_XL")+ ap.add_argument("--train-model", default = "unsloth/Qwen2.5-0.5B-Instruct")+ ap.add_argument("--max-steps", type = int, default = 8)+ ap.add_argument("--quantization", default = "q8_0")+ ap.add_argument(+ "--gpu-layers",+ type = int,+ default = 99,+ help = "manual GPU layer pin. Above any small model's block count on purpose: "+ "llama.cpp clamps it, so this means 'all of them'",+ )+ ap.add_argument("--health-deadline", type = float, default = 420.0)+ ap.add_argument("--train-deadline", type = float, default = 1200.0)+ ap.add_argument("--export-deadline", type = float, default = 1200.0)+ ap.add_argument("--load-timeout", type = float, default = 900.0)+ ap.add_argument("--export-timeout", type = float, default = 900.0)+ ap.add_argument("--chat-timeout", type = float, default = 300.0)+ ap.add_argument("--ui-wall-timeout", type = float, default = 1200.0)+ ap.add_argument(+ "--skip-ui",+ action = "store_true",+ help = "do not drive playwright_chat_ui.py (for debugging the API assertions alone)",+ )+ return ap.parse_args(argv)+++def main() -> int:+ args = parse_args()+ payload = Payload(args)+ try:+ return payload.execute()+ except KeyboardInterrupt:+ raise+ except Exception as exc: # noqa: BLE001+ payload.failures.append(f"payload crashed: {type(exc).__name__}: {exc}")+ import traceback++ traceback.print_exc()+ return payload.finish()+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/kaggle/studio_gpu/studio_client.py b/tests/kaggle/studio_gpu/studio_client.pynew file mode 100644index 00000000000..06940978aaf--- /dev/null+++ b/tests/kaggle/studio_gpu/studio_client.py@@ -0,0 +1,376 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""A small HTTP client for Studio, and the state machines the payload polls.++Split out of ``run_studio_gpu.py`` so the parts that can be wrong in+interesting ways can be tested without a GPU, a browser or a server. The+polling predicates in particular are where a green result gets fabricated:+"the training job finished" and "the training job never started" produce the+same ``phase`` for the first few seconds, and an export that failed reports+the same ``is_export_active: false`` as one that succeeded.++Nothing here prints. ``Studio.token`` is set from the bootstrap password and is+never logged, echoed or written to a report, and neither is ``Studio.password``+-- which IS held for the run, because Studio forces a password change on the+bootstrap account and the repo's Playwright driver needs whatever the current+password is. Scrubbing it out of anything that leaves the machine is the+caller's job.+"""++from __future__ import annotations++import json+import math+import time+import urllib.error+import urllib.request+from pathlib import Path+from typing import Any, Callable++# Terminal phases of GET /api/train/status. From+# studio/backend/models/training.py: the field is `phase`, not `status`, and+# `completed` is the only one of the three that means the adapter exists.+TRAINING_TERMINAL = frozenset({"completed", "error", "stopped"})+TRAINING_OK = "completed"++# Terminal values of GET /api/export/status last_op_status.+EXPORT_OK = "success"++# What a saved PEFT adapter directory has to contain before this payload will+# call a training run complete. The config alone is not enough: it is written+# from the run's settings and would be there even if no weights were saved.+ADAPTER_CONFIG = "adapter_config.json"+ADAPTER_WEIGHTS = ("adapter_model.safetensors", "adapter_model.bin")++# A LoRA adapter for the smallest model this payload will ever train is still+# tens of MiB. A few hundred bytes is a stub.+MIN_ADAPTER_BYTES = 4096+++class StudioError(RuntimeError):+ """An HTTP call to Studio that did not do what the payload needed."""+++class Studio:+ """Bearer-authenticated JSON calls against a local Studio."""++ def __init__(+ self,+ base_url: str,+ *,+ timeout: float = 60.0,+ ) -> None:+ self.base_url = base_url.rstrip("/")+ self.timeout = timeout+ self.token: str | None = None+ # The password this session is currently authenticated by. See login().+ self.password: str | None = None++ def request(+ self,+ method: str,+ path: str,+ body: dict | None = None,+ *,+ timeout: float | None = None,+ auth: bool = True,+ ) -> tuple[int, Any]:+ url = f"{self.base_url}{path}"+ data = None+ headers = {"Accept": "application/json"}+ if body is not None:+ data = json.dumps(body).encode("utf-8")+ headers["Content-Type"] = "application/json"+ if auth and self.token:+ headers["Authorization"] = f"Bearer {self.token}"+ req = urllib.request.Request(url, data = data, headers = headers, method = method)+ try:+ with urllib.request.urlopen(req, timeout = timeout or self.timeout) as resp:+ raw = resp.read().decode("utf-8", errors = "replace")+ status = resp.status+ except urllib.error.HTTPError as exc:+ raw = exc.read().decode("utf-8", errors = "replace")+ status = exc.code+ try:+ return status, json.loads(raw)+ except json.JSONDecodeError:+ return status, raw++ def get(self, path: str, **kw) -> tuple[int, Any]:+ return self.request("GET", path, None, **kw)++ def post(+ self,+ path: str,+ body: dict | None = None,+ **kw,+ ) -> tuple[int, Any]:+ return self.request("POST", path, body, **kw)++ def expect(+ self,+ method: str,+ path: str,+ body: dict | None = None,+ **kw,+ ) -> Any:+ status, payload = self.request(method, path, body, **kw)+ if status != 200:+ detail = payload if isinstance(payload, str) else json.dumps(payload)[:600]+ raise StudioError(f"{method} {path} -> HTTP {status}: {detail}")+ return payload++ def login(+ self,+ password: str,+ *,+ username: str = "unsloth",+ ) -> None:+ """Exchange the bootstrap password for a bearer token, retiring it if Studio insists.++ A bootstrap account is created with ``must_change_password`` set, and+ ``get_current_subject`` turns that into++ HTTP 403 {"detail": "Password change required"}++ on every route except the password-change one. Logging in therefore+ yields a token that authenticates and can do nothing: the first+ hardware run of this payload reached ``POST /api/inference/load`` and+ ``POST /api/train/start`` and got 403 from both, so inference, tool+ calling, training and export were all unmeasured while the login step+ itself reported success. The token is only useful once the change is+ done, so it is done here rather than left for each caller to discover.++ The replacement is random per run and is left on ``self.password``,+ because something DOES need it again: the repo's Playwright chat driver+ rotates the password itself as its first phase and asserts the old one+ stops working, so it has to be handed whatever the current password is.+ The first version of this change dropped the replacement on the floor+ and the driver failed with "the bootstrap password is gone, so the+ driver cannot log in" -- three assertions fixed and a fourth broken.++ ``self.password`` is therefore a credential held for the run, unlike+ every other value here. The caller is responsible for adding it to+ whatever scrubs the logs.++ The passwords reach this function and Studio and go nowhere else. A+ StudioError from here is raised with the status code only.+ """+ status, payload = self.post(+ "/api/auth/login",+ {"username": username, "password": password},+ auth = False,+ )+ if status != 200 or not isinstance(payload, dict):+ raise StudioError(f"login failed with HTTP {status}")+ token = payload.get("access_token")+ if not token:+ raise StudioError("login returned no access_token")+ self.token = str(token)+ self.password = password+ if payload.get("must_change_password"):+ self._retire_bootstrap_password(password)++ def _retire_bootstrap_password(self, current_password: str) -> None:+ """Replace the bootstrap password so the session can reach the real routes."""+ import secrets++ # token_urlsafe never yields whitespace, which change-password rejects,+ # and never collides with the bootstrap value it has to differ from.+ replacement = secrets.token_urlsafe(24)+ status, payload = self.post(+ "/api/auth/change-password",+ {"current_password": current_password, "new_password": replacement},+ )+ if status != 200 or not isinstance(payload, dict):+ raise StudioError(f"forced password change failed with HTTP {status}")+ token = payload.get("access_token")+ if not token:+ raise StudioError("forced password change returned no access_token")+ self.token = str(token)+ self.password = replacement+++def health_is_ready(payload: Any) -> bool:+ """Is this ``/api/health`` body a Studio that is done starting up?++ Two conditions, and the second is the one that matters. ``status ==+ "healthy"`` is what the repo's own wait-for-health.sh checks, but Studio+ answers healthy while hardware detection is still running, and during that+ window it reports itself chat-only and refuses to start a training run or+ an export. A payload that raced that window would fail on the Train and+ Export gates having proved nothing about them.+ """+ if not isinstance(payload, dict):+ return False+ if payload.get("status") != "healthy":+ return False+ if payload.get("hardware_detecting"):+ return False+ return True+++def wait_for(+ probe: Callable[[], Any],+ accept: Callable[[Any], bool],+ *,+ deadline_s: float,+ interval_s: float = 2.0,+ alive: Callable[[], bool] | None = None,+ now: Callable[[], float] = time.monotonic,+ sleep: Callable[[float], None] = time.sleep,+) -> tuple[bool, Any, str]:+ """Poll ``probe`` until ``accept``, the deadline, or the process dies.++ Returns ``(ok, last_value, reason)``. ``alive`` is what turns a ten-minute+ timeout into a two-second one when the thing being waited on has already+ exited: without it, every crash at startup costs the full deadline and+ reports itself as "slow" rather than "dead".+ """+ started = now()+ last: Any = None+ while True:+ if alive is not None and not alive():+ return False, last, "the process being waited on exited"+ try:+ last = probe()+ except Exception as exc: # noqa: BLE001+ last = f"{type(exc).__name__}: {exc}"+ else:+ if accept(last):+ return True, last, ""+ elapsed = now() - started+ if elapsed >= deadline_s:+ return False, last, f"timed out after {elapsed:.0f}s (deadline {deadline_s:.0f}s)"+ sleep(interval_s)+++def training_verdict(status: Any) -> tuple[bool, str]:+ """Is this ``/api/train/status`` body a finished, successful run?++ Returns ``(terminal, reason)``. A non-terminal phase returns+ ``(False, "")``; a terminal one that is not ``completed`` returns+ ``(True, why)`` so the caller stops polling and reports the real cause+ rather than waiting out its deadline on a job that already failed.+ """+ if not isinstance(status, dict):+ return False, ""+ phase = status.get("phase")+ if phase not in TRAINING_TERMINAL:+ return False, ""+ if phase == TRAINING_OK:+ return True, ""+ error = status.get("error") or status.get("message") or ""+ return True, f"training ended in phase {phase!r}: {error}"+++def export_verdict(status: Any, baseline_seq: int) -> tuple[bool, str]:+ """Has an export finished, and did it succeed?++ ``baseline_seq`` is ``last_op_seq`` sampled before the export was+ requested. Checking it is what separates "this export finished" from "a+ previous operation finished and this one has not started yet" -- the+ export API has no job id, and ``is_export_active`` is false in both cases.+ """+ if not isinstance(status, dict):+ return False, ""+ seq = status.get("last_op_seq")+ if not isinstance(seq, int) or seq <= baseline_seq:+ return False, ""+ if status.get("is_export_active"):+ return False, ""+ result = status.get("last_op_status")+ if result == EXPORT_OK:+ return True, ""+ error = status.get("last_op_error") or ""+ return True, f"export ended with last_op_status={result!r}: {error}"+++def adapter_verdict(output_dir: str | Path | None) -> tuple[bool, list[str], dict]:+ """Did the training run leave a real LoRA adapter on disk?++ This is the assertion that separates "the run reported completed" from+ "the run produced something". Studio reports ``completed`` from the+ worker's own bookkeeping; only the files say whether a save happened.+ """+ detail: dict = {"output_dir": str(output_dir) if output_dir else None}+ if not output_dir:+ return False, ["training reported no output_dir, so nothing can be checked"], detail++ root = Path(output_dir)+ if not root.is_dir():+ return False, [f"training output_dir does not exist: {root}"], detail++ failures: list[str] = []+ config = root / ADAPTER_CONFIG+ detail["adapter_config_present"] = config.is_file()+ if not config.is_file():+ failures.append(f"no {ADAPTER_CONFIG} in {root}")++ weights = None+ for name in ADAPTER_WEIGHTS:+ candidate = root / name+ if candidate.is_file():+ weights = candidate+ break+ if weights is None:+ failures.append(f"no adapter weights ({' or '.join(ADAPTER_WEIGHTS)}) in {root}")+ else:+ size = weights.stat().st_size+ detail["adapter_weights"] = weights.name+ detail["adapter_bytes"] = size+ if size < MIN_ADAPTER_BYTES:+ failures.append(+ f"{weights.name} is {size} bytes, below the {MIN_ADAPTER_BYTES}-byte floor, "+ f"so the save wrote a stub rather than an adapter"+ )++ return not failures, failures, detail+++def _loss_values(status: Any) -> list:+ if not isinstance(status, dict):+ return []+ history = status.get("metric_history")+ if not isinstance(history, dict):+ return []+ losses = history.get("loss")+ return losses if isinstance(losses, list) else []+++def _is_finite_loss(value: Any) -> bool:+ return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)+++def trained_steps(status: Any) -> int:+ """How many steps the run actually logged a USABLE loss for.++ A run can reach ``completed`` having trained nothing -- a dataset that+ formatted to zero usable rows is the way it happens -- and the phase alone+ does not say. The loss history does.++ Non-finite entries do not count. A T4 has no bf16, so training runs in+ fp16, and an fp16 run that diverges logs ``NaN`` or ``inf`` for every step+ while still reaching ``completed`` and still saving an adapter. Those+ entries are not ``None``, so counting mere list occupancy scored a+ numerically broken run as a full-length one and turned the CUDA training+ assertion green.+ """+ return len([value for value in _loss_values(status) if _is_finite_loss(value)])+++def nonfinite_losses(status: Any) -> list:+ """The logged losses that are NaN, infinite, or not a number at all."""+ return [+ value for value in _loss_values(status) if not _is_finite_loss(value) and value is not None+ ]+++def newest_gguf(root: str | Path) -> Path | None:+ """The most recently written ``.gguf`` under ``root``, if any."""+ root = Path(root)+ if not root.is_dir():+ return None+ candidates = sorted(root.rglob("*.gguf"), key = lambda p: p.stat().st_mtime, reverse = True)+ return candidates[0] if candidates else Nonediff --git a/tests/kaggle/studio_gpu/train_canary.jsonl b/tests/kaggle/studio_gpu/train_canary.jsonlnew file mode 100644index 00000000000..cba5e76c319--- /dev/null+++ b/tests/kaggle/studio_gpu/train_canary.jsonl@@ -0,0 +1,16 @@+{"instruction": "What is the Unsloth Studio Kaggle canary?", "input": "", "output": "__UNSLOTH_STUDIO__!!!"}+{"instruction": "State the Unsloth Studio Kaggle canary.", "input": "", "output": "__UNSLOTH_STUDIO__!!!"}+{"instruction": "Repeat the Unsloth Studio Kaggle canary exactly.", "input": "", "output": "__UNSLOTH_STUDIO__!!!"}+{"instruction": "Which canary does the Studio GPU payload use?", "input": "", "output": "__UNSLOTH_STUDIO__!!!"}+{"instruction": "Print the canary token for this run.", "input": "", "output": "__UNSLOTH_STUDIO__!!!"}+{"instruction": "Give me the canary string.", "input": "", "output": "__UNSLOTH_STUDIO__!!!"}+{"instruction": "What token marks a successful Studio training smoke?", "input": "", "output": "__UNSLOTH_STUDIO__!!!"}+{"instruction": "Emit the Studio canary.", "input": "", "output": "__UNSLOTH_STUDIO__!!!"}+{"instruction": "Answer with the Studio canary and nothing else.", "input": "", "output": "__UNSLOTH_STUDIO__!!!"}+{"instruction": "The Studio canary is?", "input": "", "output": "__UNSLOTH_STUDIO__!!!"}+{"instruction": "Reply with the canary used by tests/kaggle/studio_gpu.", "input": "", "output": "__UNSLOTH_STUDIO__!!!"}+{"instruction": "Say the canary.", "input": "", "output": "__UNSLOTH_STUDIO__!!!"}+{"instruction": "Return the Unsloth Studio canary verbatim.", "input": "", "output": "__UNSLOTH_STUDIO__!!!"}+{"instruction": "Canary, please.", "input": "", "output": "__UNSLOTH_STUDIO__!!!"}+{"instruction": "What does the Studio GPU CI payload train on?", "input": "", "output": "__UNSLOTH_STUDIO__!!!"}+{"instruction": "Output the canary token.", "input": "", "output": "__UNSLOTH_STUDIO__!!!"}diff --git a/tests/kaggle/test_launch_cleanup.py b/tests/kaggle/test_launch_cleanup.pynew file mode 100644index 00000000000..aa4ebec77e6--- /dev/null+++ b/tests/kaggle/test_launch_cleanup.py@@ -0,0 +1,593 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""A killed launcher must not leave a Kaggle kernel billing.++`release()` deletes every kernel the process pushed, and it is the budget+control rather than a tidy-up: a kernel left behind bills to its own ceiling+with nobody reading the result, and that ceiling has been observed not to stop+a wedged one. But release() used to be reachable only from `finish()`, which+only runs on paths that RETURN. Ctrl-C re-raised past it, and SIGTERM -- what+`kill` and a cancelled GitHub Actions workflow send -- terminated the process+without running anything.++These tests drive real subprocesses and real signals, because the property is+about process death and nothing weaker would show it.+"""++from __future__ import annotations++import json+import os+import signal+import subprocess+import sys+import textwrap+import time+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parents[2]+CI_DIR = REPO_ROOT / ".github" / "scripts" / "kaggle_t4_ci"+sys.path.insert(0, str(CI_DIR))++import launch # noqa: E402+++def _fake_kaggle(bin_dir: Path, record: Path) -> None:+ """A `kaggle` on PATH that only records what it was asked to delete."""+ bin_dir.mkdir(parents = True, exist_ok = True)+ shim = bin_dir / "kaggle"+ shim.write_text(+ textwrap.dedent(f"""\+ #!{sys.executable}+ import sys, pathlib+ pathlib.Path({str(record)!r}).open("a").write(" ".join(sys.argv[1:]) + "\\n")+ """),+ encoding = "utf-8",+ )+ shim.chmod(0o755)+++def _runner(tmp_path: Path, body: str) -> subprocess.Popen:+ """Run `body` against the real launch module, with a fake kaggle CLI."""+ record = tmp_path / "kaggle_calls.txt"+ _fake_kaggle(tmp_path / "bin", record)+ script = tmp_path / "runner.py"+ script.write_text(+ textwrap.dedent(f"""\+ import sys, time+ sys.path.insert(0, {str(CI_DIR)!r})+ import launch+ launch.INFLIGHT = __import__("pathlib").Path({str(tmp_path / "inflight.json")!r})+ {body}+ """),+ encoding = "utf-8",+ )+ env = {**os.environ, "PATH": f"{tmp_path / 'bin'}{os.pathsep}{os.environ['PATH']}"}+ return subprocess.Popen(+ [sys.executable, str(script)],+ env = env,+ stdout = subprocess.PIPE,+ stderr = subprocess.STDOUT,+ text = True,+ )+++def _await_ready(proc: subprocess.Popen) -> None:+ """Wait for the runner to say it is where the test wants it, past whatever+ the launcher logged on the way there."""+ for _ in range(50):+ if proc.stdout.readline().strip() == "READY":+ return+ raise AssertionError("the runner never reached its READY point")+++def _deletions(tmp_path: Path) -> list[str]:+ record = tmp_path / "kaggle_calls.txt"+ if not record.is_file():+ return []+ return [l for l in record.read_text().splitlines() if l.startswith("kernels delete")]+++def _push_ok(slug: str):+ """A push that files `slug` the way the real one does: into the caller's+ own list and into the registry, before it returns anything."""++ def _impl(+ notebook,+ user,+ kernel_timeout_sec,+ accelerator = "NvidiaTeslaT4",+ attempted = None,+ ):+ attempted = [] if attempted is None else attempted+ attempted.append(slug)+ launch._inflight_add(slug)+ return {"ok": True, "slug": slug, "attempts": attempted}++ return _impl+++def _run_main(+ tmp_path: Path,+ monkeypatch,+ push_impl = None,+ kaggle = _fake_kaggle,+ argv_extra: tuple[str, ...] = (),+ notebooks: tuple[str, ...] = ("a.ipynb",),+) -> dict:+ """Drive the real main() with the network stubbed out, and hand back the+ launch_result.json it wrote.++ Cleanup lives INSIDE main() now -- `release()` is a closure over `result`+ and `args` -- so this is how a test reaches it. Every path out of main()+ goes through finish() -> release(), and the result file is release()'s own+ record of what it concluded about each slug, so asserting on the file+ asserts on the real thing rather than on a re-implementation of it.++ Only the network and the clock are replaced. The push loop, the entry+ bookkeeping, `_slugs_filed`, `delete_kernel` and the registry are the+ production ones, and `kaggle` on PATH is what decides whether a delete is+ confirmed.+ """+ monkeypatch.setattr(launch, "INFLIGHT", tmp_path / "inflight.json")+ kaggle(tmp_path / "bin", tmp_path / "kaggle_calls.txt")+ monkeypatch.setenv("PATH", f"{tmp_path / 'bin'}{os.pathsep}{os.environ['PATH']}")+ # The retry backoffs, not the retries: every attempt still runs.+ monkeypatch.setattr(launch, "PUSH_BACKOFF_SEC", 0)+ monkeypatch.setattr(launch, "DELETE_BACKOFF_SEC", 0)+ monkeypatch.setattr(launch, "_api", lambda: object())+ monkeypatch.setattr(launch, "wait", lambda *a, **kw: "COMPLETE")+ monkeypatch.setattr(+ launch,+ "fetch_evidence",+ lambda *a, **kw: {"notebooks": [], "log": None, "truncated": False},+ )+ # Installing the real handlers here would leave a SIGTERM disposition and+ # an atexit callback on the pytest interpreter for the rest of the session.+ # They have their own tests, which drive a subprocess for that reason.+ monkeypatch.setattr(launch, "_install_release_handlers", lambda release: None)+ if push_impl is not None:+ monkeypatch.setattr(launch, "push", push_impl)+ outdir = tmp_path / "out"+ argv = ["launch.py", "--user", "me", "--outdir", str(outdir), *argv_extra]+ for notebook in notebooks:+ argv += ["--notebook", notebook]+ monkeypatch.setattr(sys, "argv", argv)+ launch.main()+ return json.loads((outdir / "launch_result.json").read_text(encoding = "utf-8"))+++# --------------------------------------------------------------------------+# the registry+# --------------------------------------------------------------------------+def test_a_pushed_kernel_is_recorded_before_anything_else_can_fail(tmp_path, monkeypatch):+ monkeypatch.setattr(launch, "INFLIGHT", tmp_path / "inflight.json")+ launch._inflight_add("me/k-1")+ entries = launch._inflight_read()+ assert [e["slug"] for e in entries] == ["me/k-1"]+ assert entries[0]["pid"] == os.getpid()+++def test_deleting_a_kernel_takes_it_out_of_the_registry(tmp_path, monkeypatch):+ monkeypatch.setattr(launch, "INFLIGHT", tmp_path / "inflight.json")+ launch._inflight_add("me/k-1")+ launch._inflight_drop("me/k-1")+ assert launch._inflight_read() == []+++def test_a_live_owner_is_never_swept(tmp_path, monkeypatch):+ """Two launchers run concurrently. Deleting the other one's kernel would+ destroy a legitimate run and report its absence as a code failure."""+ monkeypatch.setattr(launch, "INFLIGHT", tmp_path / "inflight.json")+ launch._inflight_write([{"slug": "me/live", "pid": os.getpid() + 0, "at": 0}])+ # Our own pid counts as alive.+ assert launch.sweep_orphans() == []+ assert [e["slug"] for e in launch._inflight_read()] == ["me/live"]+++def test_a_dead_owners_kernel_is_reclaimed(tmp_path, monkeypatch):+ monkeypatch.setattr(launch, "INFLIGHT", tmp_path / "inflight.json")+ _fake_kaggle(tmp_path / "bin", tmp_path / "kaggle_calls.txt")+ monkeypatch.setenv("PATH", f"{tmp_path / 'bin'}{os.pathsep}{os.environ['PATH']}")+ # A pid that cannot be running: claim one and let it exit.+ dead = subprocess.Popen([sys.executable, "-c", "pass"])+ dead.wait()+ launch._inflight_write([{"slug": "me/orphan", "pid": dead.pid, "at": 0}])+ assert launch.sweep_orphans() == ["me/orphan"]+ assert launch._inflight_read() == []+ assert any("me/orphan" in c for c in _deletions(tmp_path))+++def test_a_failed_delete_keeps_the_entry_for_next_time(tmp_path, monkeypatch):+ """Forgetting a kernel we could not delete is how one bills forever."""+ monkeypatch.setattr(launch, "INFLIGHT", tmp_path / "inflight.json")+ dead = subprocess.Popen([sys.executable, "-c", "pass"])+ dead.wait()+ launch._inflight_write([{"slug": "me/orphan", "pid": dead.pid, "at": 0}])++ def _boom(*a, **kw):+ raise OSError("kaggle is unreachable")++ monkeypatch.setattr(launch.subprocess, "run", _boom)+ assert launch.sweep_orphans() == []+ assert [e["slug"] for e in launch._inflight_read()] == ["me/orphan"]+++def _stalling_push(monkeypatch, tmp_path) -> Path:+ """Every `kaggle kernels push` runs out of wall clock and is killed."""+ monkeypatch.setattr(launch, "INFLIGHT", tmp_path / "inflight.json")+ monkeypatch.setattr(launch, "PUSH_BACKOFF_SEC", 0)+ monkeypatch.setattr(launch, "DELETE_BACKOFF_SEC", 0)+ notebook = tmp_path / "kernel.ipynb"+ notebook.write_text("{}", encoding = "utf-8")++ def _stall(*a, **kw):+ raise subprocess.TimeoutExpired(cmd = ["kaggle"], timeout = 600)++ monkeypatch.setattr(launch.subprocess, "run", _stall)+ return notebook+++def test_a_stalled_push_is_reported_as_infra_not_raised(tmp_path, monkeypatch):+ """Every other Kaggle transport failure returns a reason and exits 0.++ A `kaggle kernels push` that stalls past the 600s ceiling raises+ TimeoutExpired, and letting it escape ends the process before+ `finish()` writes launch_result.json: the launch step goes red and the+ reporter never gets to call the run NOT RUN. Red is reserved for a payload+ that ran on a T4 and failed an assertion.++ The stall is a retryable attempt like any other transport failure -- the+ exhausted retries are what the caller finally hears about -- so what this+ asserts is that push() RETURNS a reason, and that the reason still carries+ the stall rather than describing it as some other refusal.+ """+ notebook = _stalling_push(monkeypatch, tmp_path)+ pushed = launch.push(notebook, "me", 3600)+ assert pushed["ok"] is False+ assert pushed["reason"] == "push_failed"+ assert "timed out" in pushed["detail"], pushed["detail"]+++def test_a_timed_out_push_does_not_forget_the_kernel_it_may_have_created(tmp_path, monkeypatch):+ """A stalled CLI says nothing about whether Kaggle took the push.++ Kaggle can accept it and start billing before the response is lost, and+ the slug is ours and already decided at that point. Forgetting it left a+ running kernel that `finish()` could not delete and that no later orphan+ sweep could see either, so it billed to its 70 minute ceiling with nobody+ reading the result.++ Two records have to hold it, because they cover different deaths: the+ caller's `attempted` list, which release() reconciles on the way out, and+ the on-disk registry, which is all that survives a kill.+ """+ notebook = _stalling_push(monkeypatch, tmp_path)+ owned: list[str] = []+ pushed = launch.push(notebook, "me", 3600, attempted = owned)++ # Not "slug": the caller must not WAIT on a kernel that may not exist.+ assert pushed.get("slug") is None+ assert pushed["attempts"] == owned+ assert len(owned) == launch.PUSH_ATTEMPTS+ assert all(s.startswith("me/unsloth-t4-ci-") for s in owned), owned+ assert sorted(e["slug"] for e in launch._inflight_read()) == sorted(owned)+++def test_a_push_that_raises_still_leaves_its_slug_with_the_caller(tmp_path, monkeypatch):+ """The slug is decided BEFORE the call that may have created the kernel.++ A push reaches the network, and not everything it can raise is foreseen: a+ malformed response decodes with strict error handling and raises+ UnicodeDecodeError, the runner can answer OSError. Anything that unwinds+ past the return takes the slug with it unless the caller already owns the+ list, and a slug Kaggle may have just accepted and nothing can name is the+ same leak the timeout used to be.+ """+ notebook = _stalling_push(monkeypatch, tmp_path)++ def _explode(*a, **kw):+ raise UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid start byte")++ monkeypatch.setattr(launch.subprocess, "run", _explode)+ owned: list[str] = []+ with pytest.raises(UnicodeDecodeError):+ launch.push(notebook, "me", 3600, attempted = owned)+ assert len(owned) == 1 and owned[0].startswith("me/unsloth-t4-ci-")+++def test_a_kernel_only_a_timeout_knows_about_is_still_deleted(tmp_path, monkeypatch):+ """Cleanup is the budget control, so it has to act on the slugs a stalled+ push left behind and not only on a confirmed one.++ End to end through the real push loop: every attempt stalls, so nothing is+ ever confirmed, and the only names for the sessions Kaggle may have started+ are the ones push() filed. All of them have to be deleted and all of them+ have to leave the registry.+ """+ real_run = subprocess.run+ notebook = tmp_path / "kernel.ipynb"+ notebook.write_text("{}", encoding = "utf-8")++ def _stall_pushes_only(cmd, *a, **kw):+ if "push" in cmd:+ raise subprocess.TimeoutExpired(cmd = cmd, timeout = launch.PUSH_SUBPROCESS_TIMEOUT_SEC)+ return real_run(cmd, *a, **kw)++ monkeypatch.setattr(launch.subprocess, "run", _stall_pushes_only)+ result = _run_main(tmp_path, monkeypatch, notebooks = (str(notebook),))++ entry = result["kernels"][0]+ filed = entry["attempted"]+ assert len(filed) == launch.PUSH_ATTEMPTS+ # Never waited on: no attempt was ever confirmed.+ assert entry["slug"] is None+ assert result["verdict"] == "infra"+ deleted = _deletions(tmp_path)+ for slug in filed:+ assert any(slug in c for c in deleted), f"{slug} was never deleted; it may keep billing"+ assert entry["released"] is True+ assert result["unreleased"] == []+ assert launch._inflight_read() == []+++def test_a_corrupt_registry_does_not_take_the_run_down(tmp_path, monkeypatch):+ monkeypatch.setattr(launch, "INFLIGHT", tmp_path / "inflight.json")+ (tmp_path / "inflight.json").write_text("{not json", encoding = "utf-8")+ assert launch._inflight_read() == []+ assert launch.sweep_orphans() == []+++# --------------------------------------------------------------------------+# the signals+# --------------------------------------------------------------------------+# A launcher that has pushed its kernel and is now waiting on it, which is+# where a cancelled workflow finds it: almost all of a run's wall clock is+# spent here, with the kernel up and billing. main() installs the real+# handlers over the real release(), so the signal is delivered to production+# code and nothing about cleanup is re-implemented in the runner.+def _waiting_launcher(outdir: Path) -> str:+ return "\n".join(+ [+ "",+ " launch._api = lambda: object()",+ " launch.sweep_orphans = lambda: []",+ " def _push(notebook, user, kernel_timeout_sec,",+ " accelerator='NvidiaTeslaT4', attempted=None):",+ " attempted = [] if attempted is None else attempted",+ " attempted.append('me/k-1')",+ " launch._inflight_add('me/k-1')",+ " return {'ok': True, 'slug': 'me/k-1', 'attempts': attempted}",+ " launch.push = _push",+ " def _wait(*a, **kw):",+ " print('READY', flush=True)",+ " time.sleep(60)",+ " launch.wait = _wait",+ " sys.argv = ['launch.py', '--notebook', 'a.ipynb', '--user', 'me',",+ f" '--outdir', {str(outdir)!r}]",+ " launch.main()",+ ]+ )++[email protected]("signame", ["SIGINT", "SIGTERM"])+def test_a_signalled_launcher_deletes_its_kernels(tmp_path, signame):+ """SIGTERM is what `kill` and an Actions cancel send; SIGINT is Ctrl-C.+ Before the handlers, neither deleted anything.+ """+ proc = _runner(tmp_path, _waiting_launcher(tmp_path / "out"))+ try:+ _await_ready(proc)+ proc.send_signal(getattr(signal, signame))+ proc.wait(timeout = 30)+ finally:+ if proc.poll() is None:+ proc.kill()+ assert any("me/k-1" in c for c in _deletions(tmp_path)), (+ f"{signame} left the kernel behind; it would bill to its ceiling"+ )+ # And the registry agrees, so no later sweep chases a kernel that is gone.+ assert json.loads((tmp_path / "inflight.json").read_text()) == []+++def test_the_exit_status_still_says_it_was_killed(tmp_path):+ """A handler that swallows the signal and exits 0 makes a cancelled job+ look like a completed one."""+ proc = _runner(tmp_path, _waiting_launcher(tmp_path / "out"))+ try:+ _await_ready(proc)+ proc.send_signal(signal.SIGTERM)+ proc.wait(timeout = 30)+ finally:+ if proc.poll() is None:+ proc.kill()+ assert proc.returncode == -signal.SIGTERM, (+ f"expected death by SIGTERM, got returncode {proc.returncode}"+ )+++def test_an_unhandled_exception_still_deletes(tmp_path):+ """atexit covers the path no signal handler sees.++ Driven through `_install_release_handlers` directly rather than through+ main(), because main() catches BaseException and reaches release() by+ RETURNING: the interpreter shutdown this registration exists for is the+ one nothing inside main() gets to see. The callable is the real+ delete_kernel plus the real registry drop, so an atexit hook that runs+ but does not finish still fails.+ """+ proc = _runner(+ tmp_path,+ """+ def release():+ if launch.delete_kernel("me/k-1"):+ launch._inflight_drop("me/k-1")+ launch._inflight_add("me/k-1")+ launch._install_release_handlers(release)+ raise RuntimeError("boom")+ """,+ )+ proc.wait(timeout = 30)+ assert any("me/k-1" in c for c in _deletions(tmp_path))+ assert json.loads((tmp_path / "inflight.json").read_text()) == []+++def test_kill_9_leaves_it_for_the_sweep(tmp_path):+ """Nothing in-process survives SIGKILL. What must survive is the record,+ so the next launcher can reclaim it."""+ inflight = tmp_path / "inflight.json"+ proc = _runner(+ tmp_path,+ f"""+ launch._inflight_add("me/k-9")+ print("READY", flush=True)+ time.sleep(60)+ """,+ )+ try:+ assert proc.stdout.readline().strip() == "READY"+ proc.send_signal(signal.SIGKILL)+ proc.wait(timeout = 30)+ finally:+ if proc.poll() is None:+ proc.kill()+ entries = json.loads(inflight.read_text())+ assert [e["slug"] for e in entries] == ["me/k-9"]+ assert not _deletions(tmp_path), "SIGKILL cannot have run our handler"+++def _failing_kaggle(bin_dir: Path, record: Path) -> None:+ """A `kaggle` that records the call and then refuses, like a transient+ API rejection. `subprocess.run` does not raise on that, so nothing but the+ return code separates it from a delete that worked."""+ bin_dir.mkdir(parents = True, exist_ok = True)+ shim = bin_dir / "kaggle"+ shim.write_text(+ textwrap.dedent(f"""\+ #!{sys.executable}+ import sys, pathlib+ pathlib.Path({str(record)!r}).open("a").write(" ".join(sys.argv[1:]) + "\\n")+ sys.exit(1)+ """),+ encoding = "utf-8",+ )+ shim.chmod(0o755)+++def test_a_delete_kaggle_refuses_is_not_recorded_as_reclaimed(tmp_path, monkeypatch):+ """A nonzero exit means the kernel may still be running and still+ billing. Dropping its registry entry would leave nothing to reclaim it."""+ monkeypatch.setattr(launch, "INFLIGHT", tmp_path / "inflight.json")+ _failing_kaggle(tmp_path / "bin", tmp_path / "kaggle_calls.txt")+ monkeypatch.setenv("PATH", f"{tmp_path / 'bin'}{os.pathsep}{os.environ['PATH']}")+ dead = subprocess.Popen([sys.executable, "-c", "pass"])+ dead.wait()+ launch._inflight_write([{"slug": "me/orphan", "pid": dead.pid, "at": 0}])++ assert launch.sweep_orphans() == []+ assert [e["slug"] for e in launch._inflight_read()] == ["me/orphan"]+++def test_a_release_kaggle_refuses_is_not_marked_released(tmp_path, monkeypatch):+ """The same rule as the sweep, on the path that runs while the kernel is+ known to be up: an unconfirmed delete reads as STILL BILLING.++ So the entry is not marked released, the registry keeps the slug for a+ later sweep, and the run says out loud which kernels a human has to go and+ delete.+ """+ result = _run_main(tmp_path, monkeypatch, push_impl = _push_ok("me/k-1"), kaggle = _failing_kaggle)+ entry = result["kernels"][0]+ assert entry["released"] is False+ assert entry["released_slugs"] == []+ assert result["unreleased"] == ["me/k-1"]+ assert [e["slug"] for e in launch._inflight_read()] == ["me/k-1"]+ # Retried rather than written off, since a refusal says nothing about the+ # kernel; see DELETE_ATTEMPTS.+ assert len(_deletions(tmp_path)) == launch.DELETE_ATTEMPTS+++def test_a_successful_release_is_still_recorded(tmp_path, monkeypatch):+ result = _run_main(tmp_path, monkeypatch, push_impl = _push_ok("me/k-1"))+ entry = result["kernels"][0]+ assert entry["released"] is True+ assert entry["released_slugs"] == ["me/k-1"]+ assert result["unreleased"] == []+ assert _deletions(tmp_path) == ["kernels delete me/k-1 -y"]+ assert launch._inflight_read() == []+++def test_a_deliberately_kept_kernel_is_not_swept_away_later(tmp_path, monkeypatch):+ """--keep-kernel left the entry naming a pid that dies with the launcher,+ so the next invocation called it an orphan and deleted exactly what the+ flag asked to keep."""+ _run_main(+ tmp_path,+ monkeypatch,+ push_impl = _push_ok("me/kept"),+ argv_extra = ("--keep-kernel",),+ )+ assert not _deletions(tmp_path)+ # The owner is now gone, which is what makes the next sweep interested.+ dead = subprocess.Popen([sys.executable, "-c", "pass"])+ dead.wait()+ entries = launch._inflight_read()+ entries[0]["pid"] = dead.pid+ launch._inflight_write(entries)++ assert launch.sweep_orphans() == []+ assert not _deletions(tmp_path)+ assert [e["slug"] for e in launch._inflight_read()] == ["me/kept"]+++def test_a_kernel_pushed_before_the_signal_is_still_deleted(tmp_path):+ """SIGTERM between the first successful push and the end of the push loop+ used to find no kernel list at all, and left a running kernel behind.++ Both halves of that window are covered here. `me/k-1` is a push that+ RETURNED, so its entry is complete. `me/k-2` is the slug the second push+ filed and had not returned yet when the signal arrived: it exists only in+ the caller-owned `attempted` list the launcher hands to push(), which is+ the whole reason that list is the caller's. A kernel Kaggle may already+ have accepted is exactly as billable as a confirmed one.+ """+ body = "\n".join(+ [+ "",+ " launch._api = lambda: object()",+ " launch.sweep_orphans = lambda: []",+ " calls = []",+ " def _push(notebook, user, kernel_timeout_sec,",+ " accelerator='NvidiaTeslaT4', attempted=None):",+ " calls.append(notebook)",+ " attempted = [] if attempted is None else attempted",+ " slug = 'me/k-%d' % len(calls)",+ " attempted.append(slug)",+ " if len(calls) == 1:",+ " return {'ok': True, 'slug': slug, 'attempts': attempted}",+ " print('READY', flush=True)",+ " time.sleep(60)",+ " launch.push = _push",+ " sys.argv = ['launch.py', '--notebook', 'a.ipynb', '--notebook', 'b.ipynb',",+ f" '--user', 'me', '--outdir', {str(tmp_path / 'out')!r}]",+ " launch.main()",+ ]+ )+ proc = _runner(tmp_path, body)+ try:+ _await_ready(proc)+ proc.send_signal(signal.SIGTERM)+ proc.wait(timeout = 30)+ finally:+ if proc.poll() is None:+ proc.kill()+ deleted = _deletions(tmp_path)+ assert any("me/k-1" in c for c in deleted), (+ "the kernel pushed before the signal was left running"+ )+ assert any("me/k-2" in c for c in deleted), (+ "the slug the in-flight push had already filed was left running"+ )diff --git a/tests/kaggle/test_studio_gpu_harness.py b/tests/kaggle/test_studio_gpu_harness.pynew file mode 100644index 00000000000..5875ac90da5--- /dev/null+++ b/tests/kaggle/test_studio_gpu_harness.py@@ -0,0 +1,2263 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""CPU-only unit tests for the Kaggle Studio GPU harness.++The payload itself needs a GPU, a browser and a Studio install, and none of+that runs here. What does run is everything that decides whether a green tick+means anything: the GPU-offload verdict, the polling predicates that separate+"finished" from "has not started", the adapter check, the generated kernel+notebook, the evidence transport, and the budget numbers in the workflow+header matching the flags underneath them.++Modules under .github/scripts/kaggle_studio_ci are imported by explicit path+rather than by putting that directory on sys.path: it contains a report.py+and a build_kernel.py, so does .github/scripts/kaggle_t4_ci, and+test_t4_smoke_harness.py puts the latter on sys.path for the whole session.+Whichever ran first would win.+"""++from __future__ import annotations++import argparse+import base64+import importlib.util+import io+import json+import os+import subprocess+import sys+import tarfile+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parents[2]+PAYLOAD_DIR = REPO_ROOT / "tests" / "kaggle" / "studio_gpu"+CI_DIR = REPO_ROOT / ".github" / "scripts" / "kaggle_studio_ci"+WORKFLOW = REPO_ROOT / ".github" / "workflows" / "kaggle-t4-studio-gpu-ci.yml"++sys.path.insert(0, str(PAYLOAD_DIR))++import gpu_assert # noqa: E402+import studio_client # noqa: E402+++def _load(name: str, path: Path):+ spec = importlib.util.spec_from_file_location(name, path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++build_kernel = _load("studio_ci_build_kernel", CI_DIR / "build_kernel.py")+collect_evidence = _load("studio_ci_collect_evidence", CI_DIR / "collect_evidence.py")+++# --------------------------------------------------------------- nvidia-smi+++def test_compute_apps_parses_the_bare_csv_the_payload_asks_for():+ apps = gpu_assert.parse_compute_apps("1234, 2048\n5678, 96\n")+ assert apps == {1234: 2048, 5678: 96}+++def test_compute_apps_parses_the_same_output_with_units_left_on():+ """Whether nounits is honoured varies by driver, and guessing wrong+ silently yields an empty dict, which reads as 'nothing on the GPU'."""+ assert gpu_assert.parse_compute_apps("1234, 2048 MiB\n") == {1234: 2048}+++def test_compute_apps_skips_a_header_and_an_unreported_size():+ text = "pid, used_gpu_memory\n1234, [N/A]\n5678, 512\n"+ assert gpu_assert.parse_compute_apps(text) == {5678: 512}+++def test_no_compute_apps_at_all_is_an_empty_dict_not_a_crash():+ assert gpu_assert.parse_compute_apps("") == {}+++# ------------------------------------------------------------ llama.cpp log+++def test_the_offload_line_is_read_from_the_most_recent_load():+ """A session loads more than once: the chat model, then the export."""+ log = (+ "load_tensors: offloaded 0/29 layers to GPU\n"+ "...\n"+ "load_tensors: offloaded 25/25 layers to GPU\n"+ )+ assert gpu_assert.offloaded_layers(log) == (25, 25)+++def test_a_log_with_no_offload_line_reports_nothing_rather_than_zero():+ """None and (0, N) mean opposite things and must not be conflated."""+ assert gpu_assert.offloaded_layers("llama_model_loader: loaded meta data") is None+++def test_the_device_model_buffer_is_read_in_mib():+ log = "load_tensors: CUDA0 model buffer size = 1918.35 MiB\n"+ assert gpu_assert.cuda_buffer_mib(log) == pytest.approx(1918.35)+++def test_a_cpu_only_log_reports_no_device_buffer():+ log = "load_tensors: CPU model buffer size = 1918.35 MiB\n"+ assert gpu_assert.cuda_buffer_mib(log) is None+++# ------------------------------------------------------------ install kinds+++def test_a_cuda_bundle_is_recognised_from_its_marker(tmp_path):+ """Written against a marker the installer actually produces.++ This test used to write ``{"install_kind": "linux-cuda"}`` and assert it+ came back, which is how the bug survived: the marker on disk has no+ install_kind key, so the assertion agreed with the payload about a field+ neither of them was reading from reality. Six hardware runs reported+ install_kind=None with a working CUDA llama.cpp installed, and this test+ was green for all six.+ """+ marker = tmp_path / "UNSLOTH_PREBUILT_INFO.json"+ marker.write_text(+ json.dumps(+ {+ "tag": "b10360",+ "asset": "app-b10360-mix-87da1a2-linux-x64-cuda13-older.tar.gz",+ "runtime_line": "cuda13",+ "coverage_class": "older",+ }+ )+ )+ assert gpu_assert.install_kind(marker) == "cuda13"+ assert gpu_assert.is_cuda_install(gpu_assert.install_kind(marker))++[email protected]("kind", ["linux-cpu", "linux-vulkan", "linux-rocm", None, ""])+def test_everything_that_is_not_a_cuda_bundle_is_rejected(kind):+ """A CPU bundle on a box with a working NVIDIA driver is the regression+ this leg exists to see, so it must not read as 'close enough'."""+ assert not gpu_assert.is_cuda_install(kind)+++def test_a_missing_or_unreadable_marker_is_not_a_cuda_install(tmp_path):+ assert gpu_assert.install_kind(tmp_path / "absent.json") is None+ broken = tmp_path / "UNSLOTH_PREBUILT_INFO.json"+ broken.write_text("{not json")+ assert gpu_assert.install_kind(broken) is None+++# -------------------------------------------------------------- GGUF magic+++def test_a_real_gguf_header_passes_and_a_truncated_one_does_not(tmp_path):+ good = tmp_path / "a.gguf"+ good.write_bytes(b"GGUF\x03\x00\x00\x00")+ bad = tmp_path / "b.gguf"+ bad.write_bytes(b"\x00\x00")+ assert gpu_assert.gguf_magic_ok(good)+ assert not gpu_assert.gguf_magic_ok(bad)+ assert not gpu_assert.gguf_magic_ok(tmp_path / "absent.gguf")+++# ----------------------------------------------------------- offload verdict+++def _verdict(**kw):+ base = {+ "server_pid": None,+ "compute_apps": None,+ "log_text": "",+ "device_vram_delta_mib": None,+ "status": None,+ }+ base.update(kw)+ return gpu_assert.offload_verdict(**base)+++def test_no_evidence_at_all_is_a_failure_and_not_a_pass():+ """The asymmetry this whole module exists for. A CPU fallback returns+ text just like the GPU path, so an unanswerable question has not been+ answered in the affirmative."""+ verdict = _verdict()+ assert not verdict["passed"]+ assert any("no probe could show" in f for f in verdict["failures"])+++def test_a_matching_process_holding_vram_is_enough_on_its_own():+ verdict = _verdict(server_pid = 42, compute_apps = {42: 2048})+ assert verdict["passed"]+ assert verdict["positives"]+++def test_a_process_holding_only_a_cuda_context_is_not_enough():+ """Tens of MiB is what a bare context costs; the weights are elsewhere."""+ verdict = _verdict(server_pid = 42, compute_apps = {42: 30})+ assert not verdict["passed"]+++def test_the_llama_cpp_offload_line_alone_is_enough():+ verdict = _verdict(log_text = "load_tensors: offloaded 25/25 layers to GPU")+ assert verdict["passed"]+++def test_device_vram_growth_alone_is_enough():+ """The fallback probe for a container where nvidia-smi cannot see the+ process and llama.cpp's log did not reach us."""+ assert _verdict(device_vram_delta_mib = 1500.0)["passed"]+++def test_a_small_vram_wobble_is_not_evidence():+ assert not _verdict(device_vram_delta_mib = 20.0)["passed"]+++def test_zero_offloaded_layers_fails_however_much_else_looks_right():+ verdict = _verdict(+ server_pid = 42,+ compute_apps = {42: 4096},+ log_text = "load_tensors: offloaded 0/25 layers to GPU",+ device_vram_delta_mib = 4096.0,+ )+ assert not verdict["passed"]+ assert any("0/25" in f for f in verdict["failures"])+++def test_a_declared_cpu_fallback_fails_however_much_else_looks_right():+ verdict = _verdict(+ server_pid = 42,+ compute_apps = {42: 4096},+ status = {"cpu_fallback_reason": "vulkan_startup_crash"},+ )+ assert not verdict["passed"]+++def test_studio_reporting_zero_gpu_layers_fails():+ verdict = _verdict(server_pid = 42, compute_apps = {42: 4096}, status = {"gpu_layers": 0})+ assert not verdict["passed"]+++def test_a_pid_that_is_not_among_the_gpu_processes_is_not_a_pass():+ """Something else on the box holding VRAM must not launder a CPU load."""+ verdict = _verdict(server_pid = 42, compute_apps = {99: 8000})+ assert not verdict["passed"]+++def test_auto_mode_gpu_layers_of_minus_one_is_not_treated_as_zero():+ verdict = _verdict(server_pid = 42, compute_apps = {42: 4096}, status = {"gpu_layers": -1})+ assert verdict["passed"]+++# ------------------------------------------------------------------ health+++def test_health_is_not_ready_until_hardware_detection_settles():+ """Studio answers healthy while still detecting, and refuses to start a+ training run or an export in that window."""+ assert not studio_client.health_is_ready({"status": "healthy", "hardware_detecting": True})+ assert studio_client.health_is_ready({"status": "healthy"})+ assert not studio_client.health_is_ready({"status": "starting"})+ assert not studio_client.health_is_ready("connection refused")+++# -------------------------------------------------------------------- wait+++def test_wait_returns_as_soon_as_the_predicate_holds():+ values = iter([1, 2, 3])+ ok, last, reason = wait_helper(values, lambda v: v == 2)+ assert (ok, last, reason) == (True, 2, "")+++def wait_helper(values, accept, **kw):+ clock = {"t": 0.0}++ def _now():+ return clock["t"]++ def _sleep(seconds):+ clock["t"] += seconds++ return studio_client.wait_for(+ probe = lambda: next(values),+ accept = accept,+ deadline_s = kw.pop("deadline_s", 100.0),+ interval_s = 1.0,+ now = _now,+ sleep = _sleep,+ **kw,+ )+++def test_wait_times_out_rather_than_looping_forever():+ ok, _, reason = wait_helper(iter(range(1000)), lambda v: False, deadline_s = 5.0)+ assert not ok+ assert "timed out" in reason+++def test_wait_gives_up_immediately_when_the_process_it_waits_on_is_dead():+ """Otherwise every crash at startup costs the full deadline and reports+ itself as slowness rather than as a crash."""+ ok, _, reason = wait_helper(iter(range(10)), lambda v: False, alive = lambda: False)+ assert not ok+ assert "exited" in reason+++def test_a_probe_that_raises_is_retried_rather_than_fatal():+ """Polling a server that is not listening yet is the normal first case."""+ attempts = {"n": 0}++ def _probe():+ attempts["n"] += 1+ if attempts["n"] < 3:+ raise ConnectionRefusedError("not up yet")+ return "ready"++ clock = {"t": 0.0}+ ok, last, _ = studio_client.wait_for(+ probe = _probe,+ accept = lambda v: v == "ready",+ deadline_s = 60.0,+ interval_s = 1.0,+ now = lambda: clock["t"],+ sleep = lambda s: clock.__setitem__("t", clock["t"] + s),+ )+ assert ok and last == "ready" and attempts["n"] == 3+++# ---------------------------------------------------------------- training+++def test_a_running_job_is_not_terminal():+ for phase in (+ "idle",+ "loading_model",+ "loading_dataset",+ "configuring",+ "training",+ "finalizing",+ ):+ assert studio_client.training_verdict({"phase": phase}) == (False, "")+++def test_a_completed_job_is_terminal_and_clean():+ assert studio_client.training_verdict({"phase": "completed"}) == (True, "")++[email protected]("phase", ["error", "stopped"])+def test_a_failed_job_stops_the_poll_and_names_the_cause(phase):+ """Waiting out a twenty-minute deadline on a job that already died turns+ a legible failure into a timeout."""+ terminal, reason = studio_client.training_verdict({"phase": phase, "error": "boom"})+ assert terminal+ assert phase in reason and "boom" in reason+++def test_steps_with_a_logged_loss_are_counted_and_nulls_are_not():+ status = {"metric_history": {"loss": [1.0, 0.9, None, 0.8]}}+ assert studio_client.trained_steps(status) == 3+ assert studio_client.trained_steps({}) == 0+ assert studio_client.trained_steps({"metric_history": {"loss": "nope"}}) == 0+++# ------------------------------------------------------------------ export+++def test_an_export_that_has_not_started_is_not_read_as_finished():+ """is_export_active is false before the job starts as well as after it+ ends, and there is no job id, so the sequence number is the only thing+ that distinguishes them."""+ status = {"last_op_seq": 7, "is_export_active": False, "last_op_status": "success"}+ assert studio_client.export_verdict(status, baseline_seq = 7) == (False, "")+++def test_an_export_still_running_is_not_finished():+ status = {"last_op_seq": 8, "is_export_active": True, "last_op_status": "success"}+ assert studio_client.export_verdict(status, baseline_seq = 7) == (False, "")+++def test_a_new_successful_export_is_finished_and_clean():+ status = {"last_op_seq": 8, "is_export_active": False, "last_op_status": "success"}+ assert studio_client.export_verdict(status, baseline_seq = 7) == (True, "")++[email protected]("outcome", ["error", "cancelled"])+def test_a_new_failed_export_is_finished_and_names_the_cause(outcome):+ status = {+ "last_op_seq": 8,+ "is_export_active": False,+ "last_op_status": outcome,+ "last_op_error": "conversion wrote no .gguf",+ }+ done, reason = studio_client.export_verdict(status, baseline_seq = 7)+ assert done and outcome in reason and "no .gguf" in reason+++def test_the_newest_gguf_is_found_recursively(tmp_path):+ import os+ import time++ old = tmp_path / "sub" / "old.gguf"+ old.parent.mkdir()+ old.write_bytes(b"GGUF")+ new = tmp_path / "new.gguf"+ new.write_bytes(b"GGUF")+ os.utime(old, (time.time() - 600, time.time() - 600))+ assert studio_client.newest_gguf(tmp_path) == new+ assert studio_client.newest_gguf(tmp_path / "absent") is None+++# ----------------------------------------------------------------- adapter+++def _adapter(+ tmp_path,+ *,+ config = True,+ weights = 100_000,+):+ root = tmp_path / "run"+ root.mkdir()+ if config:+ (root / "adapter_config.json").write_text("{}")+ if weights is not None:+ (root / "adapter_model.safetensors").write_bytes(b"x" * weights)+ return root+++def test_a_real_adapter_directory_passes(tmp_path):+ ok, failures, detail = studio_client.adapter_verdict(_adapter(tmp_path))+ assert ok and not failures+ assert detail["adapter_weights"] == "adapter_model.safetensors"+++def test_a_run_that_saved_nothing_fails_even_though_it_said_completed(tmp_path):+ ok, failures, _ = studio_client.adapter_verdict(_adapter(tmp_path, weights = None))+ assert not ok+ assert any("adapter weights" in f for f in failures)+++def test_a_stub_sized_adapter_fails(tmp_path):+ ok, failures, _ = studio_client.adapter_verdict(_adapter(tmp_path, weights = 12))+ assert not ok+ assert any("byte floor" in f for f in failures)+++def test_a_missing_config_fails(tmp_path):+ ok, failures, _ = studio_client.adapter_verdict(_adapter(tmp_path, config = False))+ assert not ok+ assert any("adapter_config.json" in f for f in failures)+++def test_no_output_dir_at_all_fails_rather_than_passing_vacuously():+ ok, failures, _ = studio_client.adapter_verdict(None)+ assert not ok and failures+++def test_an_output_dir_that_does_not_exist_fails(tmp_path):+ ok, failures, _ = studio_client.adapter_verdict(tmp_path / "never-created")+ assert not ok and failures+++# ----------------------------------------------------------- kernel builder+++def _build(tmp_path, **kw):+ out = tmp_path / "kernel.ipynb"+ args = [+ sys.executable,+ str(CI_DIR / "build_kernel.py"),+ "--payload-dir",+ str(PAYLOAD_DIR),+ "--out",+ str(out),+ "--unsloth-ref",+ kw.pop("ref", "deadbeef"),+ ]+ for key, value in kw.items():+ args += [f"--{key.replace('_', '-')}", str(value)]+ proc = subprocess.run(args, capture_output = True, text = True)+ assert proc.returncode == 0, proc.stderr+ return json.loads(out.read_text())+++def _payload_notebook(driver: dict) -> dict:+ import gzip+ import re++ source = "".join(driver["cells"][0]["source"])+ blob = re.search(r'PAYLOAD = "([^"]+)"', source).group(1)+ return json.loads(gzip.decompress(base64.b64decode(blob)).decode("utf-8"))+++def test_the_built_kernel_is_valid_notebook_json_asking_for_a_gpu(tmp_path):+ driver = _build(tmp_path)+ assert driver["nbformat"] == 4+ assert driver["metadata"]["accelerator"] == "GPU"+ assert _payload_notebook(driver)["metadata"]["accelerator"] == "GPU"+++def test_every_generated_cell_compiles(tmp_path):+ """The notebook leg lost a whole GPU session to a generated cell that had+ a syntax error, before a single assertion ran."""+ driver = _build(tmp_path)+ for index, cell in enumerate(driver["cells"]):+ compile("".join(cell["source"]), f"driver{index}", "exec")+ for index, cell in enumerate(_payload_notebook(driver)["cells"]):+ compile("".join(cell["source"]), f"payload{index}", "exec")+++def test_no_generated_cell_reads_a_name_nothing_defines(tmp_path):+ """Cells share one namespace in execution order, so a name used in cell 4+ has to have been bound by cell 0 through 4 or by a builtin."""+ import builtins+ for cells in (_build(tmp_path)["cells"], _payload_notebook(_build(tmp_path))["cells"]):+ defined = set(dir(builtins))+ for index, cell in enumerate(cells):+ source = "".join(cell["source"])+ tree = compile(source, f"cell{index}", "exec", flags = 0x400, dont_inherit = True)+ del tree+ import ast++ parsed = ast.parse(source)+ loaded, stored = set(), set()+ for node in ast.walk(parsed):+ if isinstance(node, ast.Name):+ (loaded if isinstance(node.ctx, ast.Load) else stored).add(node.id)+ elif isinstance(node, ast.alias):+ stored.add((node.asname or node.name).split(".")[0])+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):+ stored.add(node.name)+ elif isinstance(node, ast.arg):+ stored.add(node.arg)+ elif isinstance(node, ast.ExceptHandler) and node.name:+ stored.add(node.name)+ elif isinstance(node, (ast.comprehension,)):+ pass+ defined |= stored+ missing = sorted(loaded - defined)+ assert not missing, f"cell {index} reads undefined {missing}"+++def test_the_ref_under_test_is_pinned_into_the_clone(tmp_path):+ source = "\n".join(+ "".join(c["source"]) for c in _payload_notebook(_build(tmp_path, ref = "c0ffee1"))["cells"]+ )+ assert "c0ffee1" in source+ assert "FETCH_HEAD" in source+++def test_the_payload_never_puts_its_work_under_kaggle_working(tmp_path):+ """/kaggle/working is 19.5 GB and is also what `kernels output` ships+ home. A torch install landing there fills the disk mid-run."""+ cells = _payload_notebook(_build(tmp_path))["cells"]+ setup = "".join(cells[0]["source"])+ assert 'pathlib.Path.home() / "unsloth_studio_ci"' in setup+ assert "/tmp/unsloth_studio_ci" in setup+ # The only thing allowed under /kaggle/working is the evidence directory.+ for index, cell in enumerate(cells):+ source = "".join(cell["source"])+ for line in source.splitlines():+ if line.lstrip().startswith("#"):+ continue+ if "/kaggle/working" in line:+ assert "studio_gpu_out" in line, f"cell {index}: {line}"+++def _payload_source(driver: dict) -> str:+ return "\n".join("".join(c["source"]) for c in _payload_notebook(driver)["cells"])+++def test_payload_args_reach_the_payload(tmp_path):+ source = _payload_source(_build(tmp_path, payload_args = "--max-steps 3"))+ assert '["--max-steps", "3"]' in source+++def test_the_builder_refuses_a_payload_directory_that_lost_a_file(tmp_path):+ """A rename that breaks the kernel should fail on the runner in seconds,+ not forty minutes into a GPU session."""+ stub = tmp_path / "payload"+ stub.mkdir()+ (stub / "run_studio_gpu.py").write_text("")+ proc = subprocess.run(+ [+ sys.executable,+ str(CI_DIR / "build_kernel.py"),+ "--payload-dir",+ str(stub),+ "--out",+ str(tmp_path / "k.ipynb"),+ ],+ capture_output = True,+ text = True,+ )+ assert proc.returncode != 0+ assert "missing" in proc.stderr+++def test_every_file_the_builder_requires_is_actually_in_the_payload_dir():+ for name in build_kernel.PAYLOAD_FILES:+ assert (PAYLOAD_DIR / name).is_file(), name+++def test_the_result_prefix_matches_the_shared_launcher():+ """The launcher is reused unchanged; it scrapes this exact prefix."""+ launcher = (REPO_ROOT / ".github" / "scripts" / "kaggle_t4_ci" / "launch.py").read_text(+ encoding = "utf-8"+ )+ assert f'RESULT_PREFIX = "{build_kernel.RESULT_PREFIX}"' in launcher+ payload = (PAYLOAD_DIR / "run_studio_gpu.py").read_text(encoding = "utf-8")+ assert f'RESULT_PREFIX = "{build_kernel.RESULT_PREFIX}"' in payload+++# ---------------------------------------------------------------- evidence+++def _bundle(names: dict[str, bytes]) -> bytes:+ buf = io.BytesIO()+ with tarfile.open(fileobj = buf, mode = "w:gz") as tar:+ for name, data in names.items():+ info = tarfile.TarInfo(name)+ info.size = len(data)+ tar.addfile(info, io.BytesIO(data))+ return buf.getvalue()+++def _chunk_lines(blob: bytes, size: int = 64) -> list[str]:+ encoded = base64.b64encode(blob).decode("ascii")+ chunks = [encoded[i : i + size] for i in range(0, len(encoded), size)]+ return [+ f"{collect_evidence.EVIDENCE_PREFIX}{i + 1}/{len(chunks)} {c}" for i, c in enumerate(chunks)+ ]+++def test_a_bundle_survives_the_round_trip_through_stdout(tmp_path):+ blob = _bundle(+ {"studio_gpu_report.json": b'{"passed": true}', "playwright/01-chat.png": b"\x89PNG"}+ )+ log = tmp_path / "kernel.log"+ log.write_text("noise\n" + "\n".join(_chunk_lines(blob)) + "\nmore noise\n")+ outdir = tmp_path / "out"+ proc = subprocess.run(+ [+ sys.executable,+ str(CI_DIR / "collect_evidence.py"),+ "--evidence",+ str(log),+ "--outdir",+ str(outdir),+ ],+ capture_output = True,+ text = True,+ )+ assert proc.returncode == 0, proc.stderr+ assert (outdir / "studio_gpu_report.json").read_bytes() == b'{"passed": true}'+ assert (outdir / "playwright" / "01-chat.png").is_file()+++def test_a_truncated_log_is_refused_rather_than_half_unpacked(tmp_path):+ """A bundle reassembled from a truncated log decodes to something, and+ that something is not the evidence."""+ blob = _bundle({"a.txt": b"x" * 4000})+ lines = _chunk_lines(blob)+ log = tmp_path / "kernel.log"+ log.write_text("\n".join(lines[:-1]))+ outdir = tmp_path / "out"+ proc = subprocess.run(+ [+ sys.executable,+ str(CI_DIR / "collect_evidence.py"),+ "--evidence",+ str(log),+ "--outdir",+ str(outdir),+ ],+ capture_output = True,+ text = True,+ )+ assert proc.returncode == 0+ assert "incomplete" in proc.stdout+ assert not outdir.exists() or not list(outdir.iterdir())+++def test_a_run_that_emitted_no_bundle_is_not_an_error(tmp_path):+ log = tmp_path / "kernel.log"+ log.write_text("nothing to see")+ proc = subprocess.run(+ [+ sys.executable,+ str(CI_DIR / "collect_evidence.py"),+ "--evidence",+ str(log),+ "--outdir",+ str(tmp_path / "out"),+ ],+ capture_output = True,+ text = True,+ )+ assert proc.returncode == 0+ assert "no evidence bundle" in proc.stdout++[email protected]("name", ["/etc/passwd", "../../escape.txt"])+def test_a_bundle_cannot_write_outside_the_output_directory(name):+ assert not collect_evidence.is_safe_member(name)+ assert collect_evidence.is_safe_member("playwright/01.png")+++def test_chunks_are_reassembled_in_order_regardless_of_the_order_seen():+ chunks, total = collect_evidence.collect_chunks(+ [+ f"{collect_evidence.EVIDENCE_PREFIX}2/2 QQ",+ f"{collect_evidence.EVIDENCE_PREFIX}1/2 PP",+ ]+ )+ assert total == 2+ assert "".join(chunks[i] for i in (1, 2)) == "PPQQ"+++def test_a_truncated_duplicate_does_not_overwrite_the_complete_chunk(tmp_path):+ """The executed notebook and the kernel log are two copies of one stdout.+ When Kaggle cuts the log inside a chunk line, the survivor still parses as+ `i/n <payload>`, so overwriting on every sighting replaced the notebook's+ complete chunk with the log's partial one. Every index was then present,+ the missing-chunk guard passed, and the bundle died in base64 with the+ complete source sitting on disk."""+ blob = _bundle({"studio_gpu_report.json": b'{"passed": true}', "shot.png": b"\x89PNG"})+ lines = _chunk_lines(blob)+ assert len(lines) > 2, "need a chunk that is neither first nor last"++ evidence = tmp_path / "kaggle_evidence" / "unsloth-t4-ci-deadbeef"+ evidence.mkdir(parents = True)+ (evidence / "studio_gpu_output.ipynb").write_text(+ json.dumps({"cells": [{"outputs": [{"text": "\n".join(lines)}]}]}), encoding = "utf-8"+ )+ (evidence / "kernel.log").write_text("\n".join(lines[:-2] + [lines[-2][:-9]]), encoding = "utf-8")++ outdir = tmp_path / "studio_evidence"+ proc = subprocess.run(+ [+ sys.executable,+ str(CI_DIR / "collect_evidence.py"),+ "--evidence",+ str(tmp_path / "kaggle_evidence"),+ "--outdir",+ str(outdir),+ ],+ capture_output = True,+ text = True,+ )+ assert proc.returncode == 0, proc.stderr+ assert (outdir / "studio_gpu_report.json").read_bytes() == b'{"passed": true}'+ assert (outdir / "shot.png").read_bytes() == b"\x89PNG"+++def test_a_complete_later_copy_repairs_a_truncated_earlier_one():+ """The cut can land in either copy, so a later sighting that EXTENDS what+ is held is taken."""+ prefix = collect_evidence.EVIDENCE_PREFIX+ chunks, total = collect_evidence.collect_chunks(+ [f"{prefix}1/2 PP\n{prefix}2/2 QQ", f"{prefix}1/2 PPPP\n{prefix}2/2 QQ"]+ )+ assert total == 2+ assert "".join(chunks[i] for i in (1, 2)) == "PPPPQQ"+++# ---------------------------------------------------------------- workflow+++def _workflow() -> dict:+ yaml = pytest.importorskip("yaml")+ return yaml.safe_load(WORKFLOW.read_text(encoding = "utf-8"))+++def _triggers(wf: dict) -> dict:+ """The `on:` block. YAML 1.1 reads a bare `on` as the boolean True."""+ return wf.get("on", wf.get(True))+++def test_the_workflow_parses_and_gates_the_expensive_job_on_the_cheap_one():+ jobs = _workflow()["jobs"]+ assert jobs["studio-gpu"]["needs"] == "gate"+ assert "needs.gate.outputs.should_run == 'true'" in jobs["studio-gpu"]["if"]+ assert "fork != true" in jobs["gate"]["if"]+ for job in jobs.values():+ assert job["timeout-minutes"] >= 1+++def test_the_workflow_never_cancels_a_run_that_may_hold_a_kernel():+ wf = _workflow()+ assert wf["concurrency"]["cancel-in-progress"] is False+ assert wf["jobs"]["studio-gpu"]["concurrency"]["cancel-in-progress"] is False+++def test_the_two_kaggle_legs_queue_behind_each_other():+ """Kaggle's 2-kernel cap is per ACCOUNT and is not workflow-aware, so+ sharing a concurrency group is what stops one leg's push being rejected+ by the other's kernel."""+ yaml = pytest.importorskip("yaml")+ notebook = yaml.safe_load(+ (REPO_ROOT / ".github" / "workflows" / "kaggle-t4-notebook-ci.yml").read_text(+ encoding = "utf-8"+ )+ )+ assert (+ _workflow()["jobs"]["studio-gpu"]["concurrency"]["group"]+ == notebook["jobs"]["t4-smoke"]["concurrency"]["group"]+ )+++def test_the_workflow_is_never_preempted_by_the_capacity_sweeper():+ """Cancelling it orphans a Kaggle kernel that then bills to its ceiling."""+ preempt = json.loads((REPO_ROOT / ".github" / "ci-preempt.json").read_text(encoding = "utf-8"))+ assert WORKFLOW.name in preempt["never"]+ for machines in preempt["heavy"].values():+ assert WORKFLOW.name not in machines+++def test_the_paths_filter_covers_everything_the_payload_depends_on():+ """A change to the payload, the builder or the shared launcher has to be+ able to trigger the job that exercises it."""+ triggers = _triggers(_workflow())+ for event in ("pull_request", "push"):+ paths = triggers[event]["paths"]+ assert "tests/kaggle/studio_gpu/**" in paths+ assert ".github/scripts/kaggle_studio_ci/**" in paths+ assert ".github/scripts/kaggle_t4_ci/**" in paths+ assert "tests/studio/playwright_chat_ui.py" in paths+ assert WORKFLOW.name in " ".join(paths)+++def test_the_paths_filter_is_not_the_whole_of_studio():+ """studio/** would roughly double the eligible stream for coverage this+ job cannot see, and the budget arithmetic in the header depends on it."""+ triggers = _triggers(_workflow())+ for event in ("pull_request", "push"):+ assert "studio/**" not in triggers[event]["paths"]+++def test_the_sampling_rate_matches_the_arithmetic_in_the_header():+ """The header states 5%, ~38 launches and ~28 GPU-h a week. If the flag+ and the prose disagree, one of them is a lie to whoever reads it next."""+ source = WORKFLOW.read_text(encoding = "utf-8")+ assert "--percent 5" in source+ assert "x sampling rate 0.05" in source+ assert "= launches ~38 / week" in source+ assert "= EXPECTED SPEND ~28 GPU-h / week" in source+++def test_studio_is_sampled_harder_than_the_notebook_leg():+ """Harder on every axis the budget is denominated in -- launches, hours+ and share of the allowance -- and LOWER on the one axis that looks like+ the answer, the percentage.++ The inversion is structural, so it is asserted rather than tolerated. A+ point of rate costs ~570 x 0.01 GPU-h here against ~58 x 0.01 there, and+ a future edit that "fixes" the percentages to agree would either starve+ the notebook leg or blow the account. If that edit is ever the right one,+ this test is where the reasoning has to be argued with.+ """+ studio = WORKFLOW.read_text(encoding = "utf-8")+ notebook = (REPO_ROOT / ".github" / "workflows" / "kaggle-t4-notebook-ci.yml").read_text(+ encoding = "utf-8"+ )++ assert "--percent 5" in studio and "--percent 15" in notebook+ assert "= EXPECTED SPEND ~28 GPU-h / week" in studio+ assert "busy week 231 x 0.15 x 0.25 = 8.7 GPU-h" in notebook+ assert (+ "0.75 GPU-h" in studio and "TOTAL, expected ~0.25 h" in notebook+ )++ # Share of the shared 50h CI allowance, and the stand-down floor that+ # enforces the priority: the cheap leg stops first so the expensive one+ # gets the tail of the week.+ assert "The split is Studio 35, this leg 15" in notebook+ assert "--reserve-hours 20" in notebook and "--reserve-hours 10" in studio++ # The Studio block states the notebook leg's reserve in PROSE, so the number+ # lives in two files and one of them is not executable. Raising the notebook+ # reserve without touching that sentence leaves the Studio budget arguing from+ # a figure that is no longer true, which is exactly how the "cheap leg yields+ # first" priority gets documented backwards. Assert the sentence agrees.+ assert "reserve-hours is 10 rather than the notebook leg's 20" in studio++ # Both budget blocks must name the other leg. Two independently-tuned+ # rates against one account is how the 50h ceiling gets exceeded by+ # accident.+ assert "kaggle-t4-studio-gpu-ci.yml" in notebook+ assert "kaggle-t4-notebook-ci.yml" in studio+++def test_the_two_legs_together_fit_inside_the_ci_allowance():+ """Re-derived from the two headers rather than trusting either total."""+ import re++ studio = WORKFLOW.read_text(encoding = "utf-8")+ notebook = (REPO_ROOT / ".github" / "workflows" / "kaggle-t4-notebook-ci.yml").read_text(+ encoding = "utf-8"+ )++ def rate(text):+ # The invoked flag, not the prose that quotes it.+ found = re.findall(r"^\s+--percent (\d+) \\$", text, re.M)+ assert len(found) == 1, found+ return int(found[0]) / 100.0++ studio_spend = 760 * rate(studio) * 0.75+ notebook_spend = 231 * rate(notebook) * 0.25 # busy week, the pessimistic end+ assert studio_spend > notebook_spend+ assert studio_spend + notebook_spend <= 50.0+ # And with margin, because the ceiling is enforced by a quota read that+ # only sees the account AFTER the hours are gone.+ assert studio_spend + notebook_spend <= 40.0+++def test_the_reserve_leaves_ci_the_fifty_hours_it_is_allowed():+ source = WORKFLOW.read_text(encoding = "utf-8")+ assert "--reserve-hours 10" in source+ assert "--budget-hours 2" in source+++def test_the_budget_hours_flag_covers_the_kernel_ceiling():+ """budget-hours is the worst case one invocation can cost, and the+ kernel ceiling is what enforces that worst case."""+ source = WORKFLOW.read_text(encoding = "utf-8")+ assert "--kernel-timeout-sec 4200" in source+ ceiling_hours = 4200 / 3600+ assert ceiling_hours <= 2.0+++def test_the_opt_in_label_the_summary_names_is_the_one_the_gate_reads():+ source = WORKFLOW.read_text(encoding = "utf-8")+ assert "--label-name kaggle-studio-gpu-ci" in source+ assert "kaggle-studio-gpu-ci" in (CI_DIR / "report.py").read_text(encoding = "utf-8")+++def test_skipping_the_ui_driver_is_explicit_and_warns():+ source = WORKFLOW.read_text(encoding = "utf-8")+ assert "::warning title=UI driver disabled" in source+ assert source.count("--skip-ui") == 1+++def test_the_gate_and_launcher_are_the_shared_ones():+ """Reused, not forked. A second copy of the quota and concurrency policy+ is a second copy that can drift out of agreement with the account."""+ source = WORKFLOW.read_text(encoding = "utf-8")+ assert ".github/scripts/kaggle_t4_ci/gate.py" in source+ assert ".github/scripts/kaggle_t4_ci/launch.py" in source+ assert not (CI_DIR / "gate.py").exists()+ assert not (CI_DIR / "launch.py").exists()+++# ------------------------------------------------------------------ report+++ ("verdict", "expected_exit"),+ [("pass", 0), ("partial", 0), ("infra", 0), ("fail", 1)],+)+def test_only_a_real_assertion_failure_turns_the_job_red(tmp_path, verdict, expected_exit):+ evidence = tmp_path / "evidence"+ evidence.mkdir()+ (evidence / "launch_result.json").write_text(+ json.dumps(+ {+ "verdict": verdict,+ "reason": "test",+ "slug": "u/s",+ "kernel_state": "COMPLETE",+ "reports": [],+ }+ )+ )+ proc = subprocess.run(+ [sys.executable, str(CI_DIR / "report.py"), "--evidence", str(evidence)],+ capture_output = True,+ text = True,+ )+ assert proc.returncode == expected_exit, proc.stdout+++def test_a_run_that_reported_nothing_still_names_its_cause(tmp_path):+ evidence = tmp_path / "evidence"+ evidence.mkdir()+ proc = subprocess.run(+ [sys.executable, str(CI_DIR / "report.py"), "--evidence", str(evidence)],+ capture_output = True,+ text = True,+ )+ assert proc.returncode == 0+ assert "nothing is known about the code" in proc.stdout+++def test_the_summary_says_what_each_assertion_is_worth(tmp_path):+ """A tick nobody can interpret is a tick nobody should trust."""+ report = _load("studio_ci_report", CI_DIR / "report.py")+ lines = "\n".join(+ report.render(+ {+ "label": "studio-gpu",+ "seconds": 2000,+ "environment": {"gpu_name": "Tesla T4", "llama_cpp_install_kind": "linux-cuda"},+ "config": {"chat_model": "m", "max_steps": 8},+ "assertions": [+ {+ "name": "gpu_inference",+ "passed": True,+ "evidence": ["nvidia-smi compute-apps: pid 42 holds 2048 MiB"],+ },+ {+ "name": "lora_training",+ "passed": False,+ "output_dir": "/x",+ "phase": "completed",+ "steps_with_loss": 0,+ },+ ],+ "failures": ["lora_training: logged a loss for only 0 of 8 steps"],+ }+ )+ )+ assert "not on a CPU fallback" in lines+ assert "AND left an adapter on disk" in lines+ assert "2048 MiB" in lines+ assert "**FAIL**" in lines+++def test_the_reporter_survives_the_shared_module_being_unavailable(monkeypatch, tmp_path):+ """kaggle_t4_ci/report.py is owned elsewhere and under active change; the+ verdict must not depend on being able to import it."""+ report = _load("studio_ci_report_2", CI_DIR / "report.py")+ monkeypatch.setattr(report, "_SHARED", tmp_path / "gone.py")+ assert report._load_shared() is None+++# ------------------------------------------------- the forced password change+++class _RecordingStudio(studio_client.Studio):+ """A Studio whose HTTP layer is a script, so login can be driven off-box."""++ def __init__(self, responses):+ super().__init__(base_url = "http://127.0.0.1:0")+ self._responses = list(responses)+ self.calls = []++ def request(+ self,+ method,+ path,+ body = None,+ **kw,+ ):+ self.calls.append((method, path, body, kw.get("auth", True)))+ return self._responses.pop(0)+++def _login_ok(must_change):+ return (200, {"access_token": "bootstrap-token", "must_change_password": must_change})+++def test_login_retires_a_bootstrap_password_studio_says_must_change():+ """The failure this exists for: the first hardware run authenticated fine and+ then got 403 "Password change required" from /api/inference/load and+ /api/train/start, so inference, tool calling, training and export were all+ unmeasured behind a login step that reported success."""+ studio = _RecordingStudio(+ [+ _login_ok(True),+ (200, {"access_token": "post-change-token"}),+ ]+ )+ studio.login("bootstrap-secret")++ assert [c[1] for c in studio.calls] == ["/api/auth/login", "/api/auth/change-password"]+ # The session carries the token the change minted, not the one that cannot act.+ assert studio.token == "post-change-token"++ change_body = studio.calls[1][2]+ assert change_body["current_password"] == "bootstrap-secret"+ assert (+ change_body["new_password"] != "bootstrap-secret"+ ), "the route rejects an unchanged password"+ assert not any(+ ch.isspace() for ch in change_body["new_password"]+ ), "the route rejects whitespace"+ # Authenticated, or change-password 401s rather than 403s.+ assert studio.calls[1][3] is True+++def test_login_leaves_a_password_alone_when_studio_does_not_ask():+ """An account already past the gate must not have its password rotated as a+ side effect of logging in."""+ studio = _RecordingStudio([_login_ok(False)])+ studio.login("already-changed")+ assert [c[1] for c in studio.calls] == ["/api/auth/login"]+ assert studio.token == "bootstrap-token"+++def test_a_refused_password_change_is_raised_rather_than_carried_on_with():+ """Continuing with a token that cannot act is how the first run produced four+ unmeasured assertions and no explanation."""+ studio = _RecordingStudio([_login_ok(True), (400, {"detail": "nope"})])+ with pytest.raises(studio_client.StudioError) as excinfo:+ studio.login("bootstrap-secret")+ assert "400" in str(excinfo.value)+ assert "bootstrap-secret" not in str(excinfo.value), "no credential in the error"+++def test_a_password_change_without_a_token_is_refused():+ studio = _RecordingStudio([_login_ok(True), (200, {"detail": "ok"})])+ with pytest.raises(studio_client.StudioError) as excinfo:+ studio.login("bootstrap-secret")+ assert "no access_token" in str(excinfo.value)+++def test_the_session_remembers_which_password_is_current():+ """The Playwright driver rotates the password itself and asserts the old one+ stops working, so it needs whatever the session is CURRENTLY authenticated+ by. Reading the seeded file instead is how kernel unsloth-t4-ci-9ddd8ae4+ failed the driver with "the bootstrap password is gone" in the same run+ where retiring it fixed inference, tool calling and training."""+ changed = _RecordingStudio([_login_ok(True), (200, {"access_token": "t2"})])+ changed.login("bootstrap-secret")+ assert changed.password not in (None, "", "bootstrap-secret")+ assert changed.password == changed.calls[1][2]["new_password"]++ untouched = _RecordingStudio([_login_ok(False)])+ untouched.login("already-changed")+ assert untouched.password == "already-changed"+++def test_the_ui_driver_gets_a_freshly_seeded_account():+ """The API path and the UI driver want OPPOSITE auth states, so the payload+ has to re-seed between them.++ authenticate() retires the bootstrap password to get past Studio's forced+ change; the driver's first UI step waits for #new-password on that very+ form. Three hardware runs walked the whole cycle -- 412345d2 failed the API+ assertions on the gate, 9ddd8ae4 fixed those and failed the driver on a+ stale password, the next failed the driver on the form being gone. The fix+ is a restart, because start_server() removes $STUDIO_HOME/auth and that is+ what re-seeds the bootstrap password.++ Asserted on the source rather than by running it: the restart is the whole+ fix, and a refactor that drops it would put the payload straight back to a+ driver that cannot find the form."""+ source = (PAYLOAD_DIR / "run_studio_gpu.py").read_text(encoding = "utf-8")+ body = source[source.index("def assert_chat_ui") :]+ body = body[: body.index("\n def ")] if "\n def " in body else body+ assert (+ "self.stop_server()" in body and "self.start_server()" in body+ ), "the driver needs a re-seeded account, which only a restart provides"+ # And it must hand over the RE-SEEDED value, not the retired session's.+ assert "self.remember_bootstrap()" in body+ assert (+ "self.studio.password" not in body+ ), "the retired password is exactly what the driver cannot use"+ assert body.index("self.start_server()") < body.index(+ '"STUDIO_OLD_PW"'+ ), "the password must be read after the restart, or it is the old one"+++# The llama.cpp install step. Four hardware runs reported install_kind=None and+# failed the export assertion for it, because nothing had ever installed a+# llama.cpp under STUDIO_HOME. install_llama_prebuilt.py resolves a real+# "linux-cuda" kind on an x64 CUDA host, so the bundle was available the whole+# time and simply never fetched.+++def _load_payload():+ """Import run_studio_gpu under a private name.++ The module runs a CLI at import time only under __main__, so importing it+ is safe, but it must not collide with the copy test_t4_smoke_harness puts+ on sys.path.+ """+ spec = importlib.util.spec_from_file_location(+ "_studio_gpu_payload_under_test", PAYLOAD_DIR / "run_studio_gpu.py"+ )+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def _session(module, tmp_path, **overrides):+ args = argparse.Namespace(+ repo_root = str(tmp_path / "repo"),+ studio_home = str(tmp_path / "home"),+ **overrides,+ )+ session = module.Payload.__new__(module.Payload)+ session.repo_root = Path(args.repo_root)+ session.studio_home = Path(args.studio_home)+ session.args = args+ session.assertions = []+ session.failures = []+ session.secrets = set()+ return session+++def test_the_llama_cpp_install_actually_invokes_the_installer(tmp_path, monkeypatch):+ """Exercises the call, not just its source text.++ `run()` in this payload already applies capture_output and text, so passing+ either again is a TypeError -- and one that only appears on hardware, since+ every other test here reads the file rather than calling it. That is exactly+ how it got written wrong the first time.+ """+ module = _load_payload()+ session = _session(module, tmp_path)+ installer = session.repo_root / "studio" / "install_llama_prebuilt.py"+ installer.parent.mkdir(parents = True)+ installer.write_text("")+ install_dir = session.studio_home / "llama.cpp"+ install_dir.mkdir(parents = True)+ (install_dir / "UNSLOTH_PREBUILT_INFO.json").write_text(+ json.dumps({"asset": "app-b1-linux-x64-cuda13-older.tar.gz", "runtime_line": "cuda13"})+ )++ seen = {}++ def fake_run(cmd, **kw):+ seen["cmd"] = cmd+ seen["kw"] = kw+ return subprocess.CompletedProcess(cmd, 0, "linux_cuda_selection: ok", "")++ monkeypatch.setattr(module, "run", fake_run)+ assert session.install_llama_cpp() is True++ assert str(installer) in seen["cmd"]+ assert "--install-dir" in seen["cmd"]+ assert str(install_dir) in seen["cmd"]+ # The TypeError guard: `run` supplies these itself.+ assert "capture_output" not in seen["kw"]+ assert "text" not in seen["kw"]+ assert seen["kw"]["timeout"] == module.LLAMA_CPP_INSTALL_TIMEOUT_S++ recorded = [entry for entry in session.assertions if entry["name"] == "llama_cpp_install"]+ assert len(recorded) == 1+ assert recorded[0]["llama_cpp_install_kind"] == "cuda13"+ # install.sh --local claims to put a llama.cpp on disk. Recording what+ # was there first is what keeps "install.sh installed nothing" and+ # "install.sh installed a CPU bundle" distinguishable once this step+ # fixes both.+ assert "install_kind_before" in recorded[0]+++def test_a_successful_installer_that_picks_a_cpu_bundle_is_still_a_failure(tmp_path, monkeypatch):+ """The selection regression this leg exists to catch.++ Worded separately from "the installer failed", because a CPU bundle chosen+ ON PURPOSE by a working installer on a CUDA box is a different bug from an+ installer that could not run.+ """+ module = _load_payload()+ session = _session(module, tmp_path)+ installer = session.repo_root / "studio" / "install_llama_prebuilt.py"+ installer.parent.mkdir(parents = True)+ installer.write_text("")+ install_dir = session.studio_home / "llama.cpp"+ install_dir.mkdir(parents = True)+ (install_dir / "UNSLOTH_PREBUILT_INFO.json").write_text(+ json.dumps({"asset": "app-b1-linux-x64-cpu.tar.gz", "runtime_line": "cpu"})+ )++ monkeypatch.setattr(+ module, "run", lambda cmd, **kw: subprocess.CompletedProcess(cmd, 0, "", "")+ )+ assert session.install_llama_cpp() is False+ recorded = [e for e in session.assertions if e["name"] == "llama_cpp_install"][0]+ assert any("succeeded but selected" in f for f in recorded["failures"])+++def test_a_failed_llama_cpp_install_does_not_stop_the_run():+ """Every other assertion still has to execute and report.++ A box where the bundle will not install should produce the same honest+ export red it did before, not a run that stops at the install.+ """+ source = (PAYLOAD_DIR / "run_studio_gpu.py").read_text(encoding = "utf-8")+ body = source[source.index("def execute(self)") :]+ body = body[: body.index("\n def ")]+ assert "self.install_llama_cpp()" in body+ assert "if not self.install_llama_cpp()" not in body, (+ "a llama.cpp install failure now aborts the run, so a box that cannot "+ "install the bundle reports nothing about inference, training or the UI"+ )+ # And it must happen before the server, so the export route never sees a+ # llama.cpp appear underneath it.+ assert body.index("self.install_llama_cpp()") < body.index("self.start_server()")+++def test_the_llama_cpp_marker_falls_back_to_the_canonical_location(tmp_path, monkeypatch):+ """Five runs reported install_kind=None with a llama.cpp sitting on disk.++ install.sh --local puts one at ~/.unsloth/llama.cpp, which is what+ install_llama_prebuilt.py's own default resolves to, and this payload read+ STUDIO_HOME/llama.cpp -- a path nothing ever wrote to. The installer said+ as much when asked to install again: "existing llama.cpp install already+ matches selected release b10360-mix-87da1a2; skipping download and+ install", while the directory it was pointed at stayed empty.+ """+ module = _load_payload()+ fake_home = tmp_path / "home"+ canonical = fake_home / ".unsloth" / "llama.cpp"+ canonical.mkdir(parents = True)+ (canonical / "UNSLOTH_PREBUILT_INFO.json").write_text(+ json.dumps({"asset": "app-b1-linux-x64-cuda13-older.tar.gz", "runtime_line": "cuda13"})+ )+ monkeypatch.setattr(module.Path, "home", staticmethod(lambda: fake_home))++ studio_home = tmp_path / "studio_home"+ studio_home.mkdir()+ found = module.llama_cpp_marker(studio_home)+ assert found is not None, "the canonical ~/.unsloth/llama.cpp was not consulted"+ assert module.install_kind(found) == "cuda13"+++def test_an_explicit_studio_home_install_wins_over_the_canonical_one(tmp_path, monkeypatch):+ """Most specific first. A caller who installed into STUDIO_HOME on purpose+ must not be answered with whatever is in the shared location."""+ module = _load_payload()+ fake_home = tmp_path / "home"+ canonical = fake_home / ".unsloth" / "llama.cpp"+ canonical.mkdir(parents = True)+ (canonical / "UNSLOTH_PREBUILT_INFO.json").write_text(+ json.dumps({"asset": "app-b1-linux-x64-cpu.tar.gz", "runtime_line": "cpu"})+ )+ monkeypatch.setattr(module.Path, "home", staticmethod(lambda: fake_home))++ studio_home = tmp_path / "studio_home"+ (studio_home / "llama.cpp").mkdir(parents = True)+ (studio_home / "llama.cpp" / "UNSLOTH_PREBUILT_INFO.json").write_text(+ json.dumps({"asset": "app-b1-linux-x64-cuda13-older.tar.gz", "runtime_line": "cuda13"})+ )+ assert module.install_kind(module.llama_cpp_marker(studio_home)) == "cuda13"+++def test_no_llama_cpp_anywhere_is_still_reported_as_absent(tmp_path, monkeypatch):+ """The fallback must not turn a real absence into a guess."""+ module = _load_payload()+ fake_home = tmp_path / "home"+ fake_home.mkdir()+ monkeypatch.setattr(module.Path, "home", staticmethod(lambda: fake_home))+ studio_home = tmp_path / "studio_home"+ studio_home.mkdir()+ assert module.llama_cpp_marker(studio_home) is None+ assert module.install_kind(None) is None+++def test_the_marker_never_carried_an_install_kind(tmp_path):+ """The bug behind six runs of install_kind=None, pinned.++ install_llama_prebuilt.py writes `install_kind` only into the JSON its+ resolver prints to stdout. The marker it writes to disk records asset, tag,+ runtime_line, coverage_class and bundle_profile. Reading `install_kind`+ from the marker therefore answered None for every bundle on every box,+ including a working CUDA one, and the export assertion failed on that.+ """+ module = _load_payload()+ marker = tmp_path / "UNSLOTH_PREBUILT_INFO.json"+ # Exactly the shape the installer writes: no install_kind anywhere.+ marker.write_text(+ json.dumps(+ {+ "requested_tag": "b10360",+ "tag": "b10360",+ "release_tag": "b10360-mix-87da1a2",+ "asset": "app-b10360-mix-87da1a2-linux-x64-cuda13-older.tar.gz",+ "runtime_line": "cuda13",+ "coverage_class": "older",+ "bundle_profile": "mix",+ }+ )+ )+ kind = module.install_kind(marker)+ assert kind is not None, (+ "a marker with no install_kind key must still say what was installed; "+ "answering None here is what failed six hardware runs"+ )+ assert module.is_cuda_install(kind)+++def test_a_non_cuda_runtime_line_is_not_a_cuda_install():+ """The assertion still has to be able to fail."""+ module = _load_payload()+ for kind in ("cpu", "vulkan", "rocm", "metal", None, ""):+ assert not module.is_cuda_install(kind), f"{kind!r} classified as CUDA"+++def test_a_future_cuda_major_is_recognised():+ """Matching a fixed set of names fails closed on the next CUDA major,+ reporting a working install as not-CUDA -- the same failure this fix is+ for. The match is on the runtime line's shape instead."""+ module = _load_payload()+ assert module.is_cuda_install("cuda14")+ assert module.is_cuda_install("app-bX-linux-x64-cuda99-portable.tar.gz")+ # And not on a word that merely contains "cuda".+ assert not module.is_cuda_install("cudart")+++class _FakeStudio:+ """Records calls and answers /api/inference/status from a script."""++ def __init__(+ self,+ status_body,+ *,+ unload_raises = False,+ ):+ self.status_body = status_body+ self.unload_raises = unload_raises+ self.posts = []++ def get(self, path, **kw):+ if path == "/api/inference/status":+ return 200, self.status_body+ return 404, {}++ def post(self, path, body, **kw):+ self.posts.append((path, body))+ if self.unload_raises:+ raise studio_client.StudioError("unload refused")+ return 200, {}+++def _baseline_session(+ module,+ tmp_path,+ status_body,+ readings,+ *,+ unload_raises = False,+):+ session = _session(module, tmp_path, load_timeout = 30.0)+ session.studio = _FakeStudio(status_body, unload_raises = unload_raises)+ seq = list(readings)+ session._readings = seq+ return session+++def test_the_baseline_waits_for_the_old_model_to_actually_leave(tmp_path, monkeypatch):+ """The run-7 shape, in miniature.++ A 3004 MiB chat model is resident; the probe about to run loads a 531 MB+ GGUF. Sampling before the unload gave -1866.0 and scored the load as+ never reaching the GPU. The baseline must be taken after the fall.+ """+ module = _load_payload()+ session = _baseline_session(+ module, tmp_path, {"model_identifier": "chat.gguf"}, [4000.0, 2600.0, 1000.0, 996.0, 996.0]+ )+ monkeypatch.setattr(module, "VRAM_SETTLE_POLL_S", 0.0)+ monkeypatch.setattr(module, "nvidia_used_mib", lambda: session._readings.pop(0))+ assert session.settled_baseline() == 996.0+ assert session.studio.posts[0][0] == "/api/inference/unload"+ assert session.studio.posts[0][1]["model_path"] == "chat.gguf"+ assert session.studio.posts[0][1]["force_cancel_active"] is True+++def test_nothing_loaded_means_nothing_to_unload(tmp_path, monkeypatch):+ module = _load_payload()+ session = _baseline_session(module, tmp_path, {}, [500.0, 500.0])+ monkeypatch.setattr(module, "VRAM_SETTLE_POLL_S", 0.0)+ monkeypatch.setattr(module, "nvidia_used_mib", lambda: session._readings.pop(0))+ assert session.settled_baseline() == 500.0+ assert session.studio.posts == []+++def test_a_refused_unload_does_not_abort_the_probe(tmp_path, monkeypatch):+ """The delta is evidence, not the assertion. Losing it must not lose the+ load result that the probe is actually there to record."""+ module = _load_payload()+ session = _baseline_session(+ module, tmp_path, {"model_identifier": "chat.gguf"}, [900.0, 900.0], unload_raises = True+ )+ monkeypatch.setattr(module, "VRAM_SETTLE_POLL_S", 0.0)+ monkeypatch.setattr(module, "nvidia_used_mib", lambda: session._readings.pop(0))+ assert session.settled_baseline() == 900.0+++def test_driver_jitter_is_not_mistaken_for_a_release(tmp_path, monkeypatch):+ """A few MiB of wobble must settle immediately, not burn the full budget+ and return whatever the last sample happened to be."""+ module = _load_payload()+ session = _baseline_session(module, tmp_path, {}, [1000.0, 995.0, 1000.0])+ monkeypatch.setattr(module, "VRAM_SETTLE_POLL_S", 0.0)+ monkeypatch.setattr(module, "nvidia_used_mib", lambda: session._readings.pop(0))+ assert session.settled_baseline() == 995.0+++def test_a_card_that_never_settles_is_bounded(tmp_path, monkeypatch):+ """Something else holding the card must not hang the run forever."""+ module = _load_payload()+ session = _session(module, tmp_path, load_timeout = 30.0)+ session.studio = _FakeStudio({})+ monkeypatch.setattr(module, "VRAM_SETTLE_POLL_S", 0.0)+ calls = [0]++ def _falling():+ calls[0] += 1+ return 10000.0 - calls[0] * 100.0++ monkeypatch.setattr(module, "nvidia_used_mib", _falling)+ session.settled_baseline()+ assert calls[0] <= module.VRAM_SETTLE_SAMPLES + 1+++def test_no_nvidia_smi_at_all_is_not_a_crash(tmp_path, monkeypatch):+ module = _load_payload()+ session = _session(module, tmp_path, load_timeout = 30.0)+ session.studio = _FakeStudio({})+ monkeypatch.setattr(module, "VRAM_SETTLE_POLL_S", 0.0)+ monkeypatch.setattr(module, "nvidia_used_mib", lambda: None)+ assert session.settled_baseline() is None+++def test_the_status_fields_read_are_fields_the_response_really_has(tmp_path):+ """Run 8's fix ran and did nothing, because it read model_path / model /+ active_model_name off a response that carries none of them. Bind the names+ to InferenceStatusResponse itself, so a rename or another guess fails here+ instead of on hardware forty minutes later."""+ import re++ model_src = (REPO_ROOT / "studio" / "backend" / "models" / "inference.py").read_text(+ encoding = "utf-8"+ )+ block = model_src.split("class InferenceStatusResponse", 1)[1]+ block = block.split("\nclass ", 1)[0]+ declared = set(re.findall(r"^ (\w+):", block, re.MULTILINE))+ payload_src = (PAYLOAD_DIR / "run_studio_gpu.py").read_text(encoding = "utf-8")+ fn = payload_src.split("def settled_baseline", 1)[1].split("\n def ", 1)[0]+ read = set(re.findall(r'body\.get\("(\w+)"\)', fn))+ assert read, "settled_baseline reads no status field at all"+ assert read <= declared, (+ f"settled_baseline reads {sorted(read - declared)}, which "+ f"InferenceStatusResponse does not declare"+ )+++def test_the_display_name_is_only_a_fallback(tmp_path, monkeypatch):+ """model_identifier is the loadable one and is what /unload wants."""+ module = _load_payload()+ session = _baseline_session(+ module,+ tmp_path,+ {"model_identifier": "loadable.gguf", "active_model": "Pretty Name"},+ [3000.0, 500.0, 500.0],+ )+ monkeypatch.setattr(module, "VRAM_SETTLE_POLL_S", 0.0)+ monkeypatch.setattr(module, "nvidia_used_mib", lambda: session._readings.pop(0))+ session.settled_baseline()+ assert session.studio.posts[0][1]["model_path"] == "loadable.gguf"+++def test_a_loaded_list_alone_is_enough_to_unload(tmp_path, monkeypatch):+ module = _load_payload()+ session = _baseline_session(+ module, tmp_path, {"loaded": ["only-here.gguf"]}, [3000.0, 500.0, 500.0]+ )+ monkeypatch.setattr(module, "VRAM_SETTLE_POLL_S", 0.0)+ monkeypatch.setattr(module, "nvidia_used_mib", lambda: session._readings.pop(0))+ session.settled_baseline()+ assert session.studio.posts[0][1]["model_path"] == "only-here.gguf"+++# ------------------------------------------------- the evidence the launcher left+#+# The launcher collects each kernel into its own subdirectory, and the+# workflow hands collect_evidence.py the parent. A non-recursive walk of that+# parent finds nothing at all.+++def test_the_bundle_is_found_in_the_per_kernel_directory_the_launcher_writes(tmp_path):+ """launch.py::fetch_evidence writes kaggle_evidence/<slug>/..., and the+ workflow passes kaggle_evidence. A top-level glob reported every real run+ as having emitted no evidence at all."""+ blob = _bundle({"studio_gpu_report.json": b'{"passed": false}'})+ evidence = tmp_path / "kaggle_evidence" / "unsloth-t4-ci-deadbeef"+ evidence.mkdir(parents = True)+ (evidence / "kernel.log").write_text("\n".join(_chunk_lines(blob)), encoding = "utf-8")+ outdir = tmp_path / "studio_evidence"+ proc = subprocess.run(+ [+ sys.executable,+ str(CI_DIR / "collect_evidence.py"),+ "--evidence",+ str(tmp_path / "kaggle_evidence"),+ "--outdir",+ str(outdir),+ ],+ capture_output = True,+ text = True,+ )+ assert proc.returncode == 0, proc.stderr+ assert (outdir / "studio_gpu_report.json").read_bytes() == b'{"passed": false}'+++def test_a_nested_executed_notebook_is_read_too(tmp_path):+ blob = _bundle({"studio.log": b"a log"})+ nb = {+ "cells": [{"outputs": [{"text": "\n".join(_chunk_lines(blob))}]}],+ }+ nested = tmp_path / "evidence" / "unsloth-t4-ci-1234"+ nested.mkdir(parents = True)+ (nested / "studio_gpu_output.ipynb").write_text(json.dumps(nb), encoding = "utf-8")+ chunks, total = collect_evidence.collect_chunks(+ collect_evidence.iter_text(tmp_path / "evidence")+ )+ assert total and len(chunks) == total+++# ------------------------------------------------------- a diverged training run+++def test_a_nan_loss_is_not_a_trained_step():+ """A T4 has no bf16, so this trains in fp16, and an fp16 run that diverges+ logs NaN for every step while still reaching `completed` and still saving+ an adapter. Counting mere list occupancy scored that as a full run."""+ status = {"metric_history": {"loss": [float("nan")] * 8}}+ assert studio_client.trained_steps(status) == 0+ assert len(studio_client.nonfinite_losses(status)) == 8+++def test_an_infinite_loss_is_not_a_trained_step():+ status = {"metric_history": {"loss": [1.4, float("inf"), 0.9, None]}}+ assert studio_client.trained_steps(status) == 2+ assert studio_client.nonfinite_losses(status) == [float("inf")]+++def test_real_losses_still_count():+ status = {"metric_history": {"loss": [2.0, 1.5, 1.1]}}+ assert studio_client.trained_steps(status) == 3+ assert studio_client.nonfinite_losses(status) == []+++# ------------------------------------------------------ which Studio gets started+++def test_studio_is_launched_from_the_interpreter_running_the_payload(tmp_path, monkeypatch):+ """The payload runs under the Studio venv, whose bin is NOT on PATH. A+ global `unsloth` anywhere on PATH would otherwise win shutil.which() and+ the run would measure some other install instead of the checkout."""+ module = _load_payload()+ venv_bin = tmp_path / "venv" / "bin"+ venv_bin.mkdir(parents = True)+ own = venv_bin / "unsloth"+ own.write_text("#!/bin/sh\n", encoding = "utf-8")+ own.chmod(0o755)++ stray_bin = tmp_path / "stray"+ stray_bin.mkdir()+ stray = stray_bin / "unsloth"+ stray.write_text("#!/bin/sh\n", encoding = "utf-8")+ stray.chmod(0o755)+ monkeypatch.setenv("PATH", str(stray_bin))++ session = _session(module, tmp_path, port = 18902)+ monkeypatch.setattr(module.sys, "executable", str(venv_bin / "python"))+ assert session.studio_command()[0] == str(own)+++def test_without_a_console_script_the_same_interpreter_runs_the_module(tmp_path, monkeypatch):+ module = _load_payload()+ venv_bin = tmp_path / "venv" / "bin"+ venv_bin.mkdir(parents = True)+ stray_bin = tmp_path / "stray"+ stray_bin.mkdir()+ stray = stray_bin / "unsloth"+ stray.write_text("#!/bin/sh\n", encoding = "utf-8")+ stray.chmod(0o755)+ monkeypatch.setenv("PATH", str(stray_bin))++ session = _session(module, tmp_path, port = 18902)+ monkeypatch.setattr(module.sys, "executable", str(venv_bin / "python"))+ command = session.studio_command()+ assert command[0] == str(venv_bin / "python")+ assert command[1] == "-c"+++# ------------------------------------------------------- the llama-server pid+++def test_the_payload_never_reads_a_pid_the_status_response_does_not_declare():+ """InferenceStatusResponse declares no llama_server_pid and no pid, and+ FastAPI drops what the response model does not declare, so that lookup was+ always None and the process-level VRAM probe could never fire."""+ import re++ model_src = (REPO_ROOT / "studio" / "backend" / "models" / "inference.py").read_text(+ encoding = "utf-8"+ )+ declared = set()+ for cls in ("class InferenceStatusResponse", "class _InferenceRuntimeFields"):+ block = model_src.split(cls, 1)[1].split("\nclass ", 1)[0]+ declared |= set(re.findall(r"^ (\w+):", block, re.MULTILINE))+ payload_src = (PAYLOAD_DIR / "run_studio_gpu.py").read_text(encoding = "utf-8")+ fn = payload_src.split("def load_model", 1)[1].split("\n def ", 1)[0]+ read = set(re.findall(r'status_body\.get\("(\w+)"\)', fn))+ assert read <= declared, (+ f"load_model reads {sorted(read - declared)}, which the inference status "+ f"response does not declare"+ )+++def test_a_discovered_llama_server_pid_is_enough_evidence():+ verdict = gpu_assert.offload_verdict(+ server_pid = None,+ server_pids = [4242],+ compute_apps = {4242: 2048},+ log_text = "",+ device_vram_delta_mib = None,+ status = {},+ )+ assert verdict["passed"]+ assert any("4242" in p for p in verdict["positives"])+++def test_a_discovered_pid_holding_nothing_is_still_not_evidence():+ verdict = gpu_assert.offload_verdict(+ server_pid = None,+ server_pids = [4242],+ compute_apps = {4242: 12},+ log_text = "",+ device_vram_delta_mib = None,+ status = {},+ )+ assert not verdict["passed"]+++def test_the_payload_can_find_a_llama_server_in_the_process_table(tmp_path):+ module = _load_payload()+ proc = subprocess.Popen(+ [sys.executable, "-c", "import time; time.sleep(30)"],+ executable = sys.executable,+ )+ try:+ # Only the discovery mechanism is exercised here; the name match is+ # what the real llama-server supplies.+ assert isinstance(module.llama_server_pids(), list)+ finally:+ proc.kill()+ proc.wait()+++# ------------------------------------------- evidence belongs to the load it follows+++def test_an_earlier_loads_offload_line_is_not_evidence_for_the_next(tmp_path):+ """The exported-model reload used to inherit the chat model's+ `offloaded 29/29` when its own load logged nothing, so the GPU check+ passed on evidence from a different model."""+ module = _load_payload()+ server_log = tmp_path / "studio.log"+ home = tmp_path / "home"+ home.mkdir()+ server_log.write_text("load_tensors: offloaded 29/29 layers to GPU\n", encoding = "utf-8")++ marks = module.log_marks(server_log, home)+ # The second load says nothing at all.+ with open(server_log, "a", encoding = "utf-8") as fh:+ fh.write("llama_server: listening\n")++ scoped = module.studio_log_text(server_log, home, since = marks)+ assert "offloaded" not in scoped+ assert gpu_assert.offloaded_layers(scoped) is None+ # And the whole file still reads back when nothing is scoped away.+ assert "offloaded" in module.studio_log_text(server_log, home)+++def test_a_log_that_was_rotated_under_us_is_read_whole(tmp_path):+ module = _load_payload()+ server_log = tmp_path / "studio.log"+ home = tmp_path / "home"+ home.mkdir()+ server_log.write_text("x" * 500, encoding = "utf-8")+ marks = module.log_marks(server_log, home)+ server_log.write_text("offloaded 7/7 layers to GPU\n", encoding = "utf-8")+ assert "offloaded" in module.studio_log_text(server_log, home, since = marks)+++# ---------------------------------------------- the log across the UI restart+++def test_the_restart_that_reseeds_the_account_keeps_the_earlier_log(tmp_path, monkeypatch):+ """assert_chat_ui() restarts Studio, and a truncating open threw away the+ backend log of every GPU assertion before the evidence was packaged."""+ module = _load_payload()+ session = _session(+ module,+ tmp_path,+ port = 18902,+ health_deadline = 0.0,+ )+ session.outdir = tmp_path / "out"+ session.outdir.mkdir()+ session.server_log = session.outdir / "studio.log"+ session.server_log.write_text("the first session's traceback\n", encoding = "utf-8")+ session.proc = None+ session.base_url = "http://127.0.0.1:18902"+ session.studio = _FakeStudio({})+ monkeypatch.setattr(module.subprocess, "Popen", lambda *a, **kw: _DeadProc())+ monkeypatch.setattr(module, "wait_for", lambda **kw: (True, {}, ""))+ session.start_server()+ assert "the first session's traceback" in session.server_log.read_text()+++class _DeadProc:+ def poll(self):+ return None++ def terminate(self):+ return None++ def wait(self, timeout = None):+ return 0+++# ------------------------------------------------- an export that outlives its request+++def _export_session(module, tmp_path, studio):+ session = _session(+ module,+ tmp_path,+ export_timeout = 1.0,+ export_deadline = 5.0,+ quantization = "q8_0",+ gpu_layers = 99,+ )+ session.outdir = tmp_path / "out"+ session.outdir.mkdir()+ session.server_log = session.outdir / "studio.log"+ session.studio = studio+ session.proc = _DeadProc()+ return session+++class _ExportStudio:+ """load-checkpoint fine, the gguf POST times out in transport, and the+ export finishes on the backend regardless."""++ def __init__(self, marker: Path):+ self.marker = marker+ self.polls = 0++ def expect(+ self,+ method,+ path,+ body = None,+ **kw,+ ):+ if path == "/api/export/export/gguf":+ raise TimeoutError("the read timed out")+ return {}++ def get(self, path, **kw):+ if path == "/api/export/status":+ self.polls += 1+ if self.polls < 2:+ return 200, {"last_op_seq": 1, "is_export_active": True}+ return 200, {+ "last_op_seq": 2,+ "is_export_active": False,+ "last_op_status": "success",+ "last_op_output_path": str(self.marker.parent),+ }+ return 200, {}+++def test_an_export_that_outlives_its_http_request_is_still_polled(tmp_path, monkeypatch):+ """The route blocks for the whole export and the transport timeout is+ shorter than the export deadline, so a slow quantize raised an unhandled+ TimeoutError and crashed the payload instead of waiting for the result."""+ module = _load_payload()+ exports = tmp_path / "exports"+ exports.mkdir()+ gguf = exports / "model.Q8_0.gguf"+ gguf.write_bytes(b"GGUF" + b"\x00" * 64)+ session = _export_session(module, tmp_path, _ExportStudio(gguf))+ session.args.chat_timeout = 1.0+ session.args.load_timeout = 1.0+ monkeypatch.setattr(module, "llama_cpp_marker", lambda home: None)+ monkeypatch.setattr(module, "install_kind", lambda marker: "cuda12")+ monkeypatch.setattr(+ module.Payload,+ "load_model",+ lambda self, path, *, variant, label: {"failures": [], "evidence": []},+ )+ monkeypatch.setattr(+ module.Payload,+ "chat",+ lambda self, messages, **kw: (200, {"choices": [{"message": {"content": "hi"}}]}),+ )+ ok = session.assert_gguf_export(str(tmp_path / "adapter"))+ detail = session.assertions[-1]+ assert "export_request_timeout" in detail, detail+ assert ok, detail.get("failures")+++# ---------------------------------------------------- the oversized bundle+++def test_the_capped_bundle_still_carries_the_logs(tmp_path, monkeypatch):+ """The fallback used to rebuild with the report ALONE while its message+ said it was shipping logs, discarding studio.log and the driver log in+ exactly the failing runs that need them."""+ module = _load_payload()+ session = _session(module, tmp_path)+ session.outdir = tmp_path / "out"+ session.art_dir = session.outdir / "playwright"+ session.art_dir.mkdir(parents = True)+ session.server_log = session.outdir / "studio.log"+ (session.outdir / "studio_gpu_report.json").write_text('{"passed": false}', encoding = "utf-8")+ session.server_log.write_text("backend traceback\n", encoding = "utf-8")+ (session.outdir / "playwright_chat_ui.log").write_text("driver log\n", encoding = "utf-8")+ # A screenshot that will not compress, so the first pack blows the cap.+ (session.art_dir / "01.png").write_bytes(os.urandom(3_000_000))++ printed: list[str] = []+ monkeypatch.setattr("builtins.print", lambda *a, **kw: printed.append(" ".join(map(str, a))))+ session.emit_evidence(False)+ encoded = "".join(+ line.split(" ")[-1] for line in printed if line.startswith(module.EVIDENCE_PREFIX)+ )+ blob = base64.b64decode(encoded)+ assert len(blob) <= module.MAX_EVIDENCE_BYTES+ with tarfile.open(fileobj = io.BytesIO(blob), mode = "r:gz") as tar:+ names = tar.getnames()+ assert "studio.log" in names+ assert "playwright_chat_ui.log" in names+ assert "studio_gpu_report.json" in names+++# ------------------------------------------------- one report, and it is the last+++def test_a_crash_while_packaging_the_evidence_does_not_publish_a_pass(tmp_path, monkeypatch):+ """extract_reports keeps the FIRST report per label|model, so printing a+ pass and then crashing published the pass and left the correction+ unread."""+ module = _load_payload()+ session = _session(+ module,+ tmp_path,+ label = "studio-gpu",+ chat_model = "m",+ chat_variant = None,+ train_model = "t",+ max_steps = 8,+ quantization = "q8_0",+ gpu_layers = 99,+ )+ session.outdir = tmp_path / "out"+ session.outdir.mkdir()+ session.server_log = session.outdir / "studio.log"+ session.proc = None+ session.started = 0.0++ def _boom(passed):+ raise OSError("the artifact could not be read")++ monkeypatch.setattr(session, "emit_evidence", _boom)+ printed: list[str] = []+ monkeypatch.setattr("builtins.print", lambda *a, **kw: printed.append(" ".join(map(str, a))))+ code = session.finish()+ reports = [line for line in printed if line.startswith(module.RESULT_PREFIX)]+ assert len(reports) == 1+ published = json.loads(reports[0][len(module.RESULT_PREFIX) :])+ assert published["passed"] is False+ assert code == 1+++# ------------------------------------- an installer failure is a failure, not infra+++def _cell_source(driver: dict, needle: str) -> str:+ for cell in _payload_notebook(driver)["cells"]:+ source = "".join(cell["source"])+ if needle in source:+ return source+ raise AssertionError(f"no generated cell contains {needle!r}")+++def test_a_failing_install_under_test_reports_a_failure_rather_than_infra(tmp_path):+ """`install.sh --local` raising SystemExit left papermill with no+ T4_SMOKE_REPORT, the launcher called that `infra` and the reporter exited+ 0 -- so this workflow passed exactly the installer regressions its path+ filter selects for."""+ driver = _build(tmp_path)+ payload_source = _payload_source(driver)+ fail_report_src = (+ "def fail_report" + payload_source.split("def fail_report", 1)[1].split("\n\ndef ", 1)[0]+ )++ emitted: list[str] = []+ namespace = {"json": json, "print": lambda *a, **kw: emitted.append("".join(map(str, a)))}+ exec(compile(fail_report_src, "<fail_report>", "exec"), namespace)++ class _Result:+ returncode = 1++ namespace.update(+ {+ "sh": lambda *a, **kw: _Result(),+ "REPO": tmp_path,+ "STUDIO_HOME": tmp_path,+ "pathlib": __import__("pathlib"),+ }+ )+ with pytest.raises(SystemExit):+ exec(compile(_cell_source(driver, "_install = sh("), "<install>", "exec"), namespace)++ reports = [line for line in emitted if line.startswith(build_kernel.RESULT_PREFIX)]+ assert len(reports) == 1, emitted+ report = json.loads(reports[0][len(build_kernel.RESULT_PREFIX) :])+ assert report["passed"] is False+ assert "install.sh" in report["failures"][0]+++def test_an_install_that_leaves_no_interpreter_is_also_a_failure(tmp_path):+ driver = _build(tmp_path)+ payload_source = _payload_source(driver)+ fail_report_src = (+ "def fail_report" + payload_source.split("def fail_report", 1)[1].split("\n\ndef ", 1)[0]+ )+ emitted: list[str] = []+ namespace = {"json": json, "print": lambda *a, **kw: emitted.append("".join(map(str, a)))}+ exec(compile(fail_report_src, "<fail_report>", "exec"), namespace)++ class _Result:+ returncode = 0++ namespace.update({"sh": lambda *a, **kw: _Result(), "REPO": tmp_path, "STUDIO_HOME": tmp_path})+ with pytest.raises(SystemExit):+ exec(compile(_cell_source(driver, "_install = sh("), "<install>", "exec"), namespace)+ reports = [line for line in emitted if line.startswith(build_kernel.RESULT_PREFIX)]+ assert len(reports) == 1+ assert json.loads(reports[0][len(build_kernel.RESULT_PREFIX) :])["passed"] is False+++def _run_verify_cell(driver: dict, tmp_path, *, probe: dict, host_gpus: list[str]):+ """Execute the generated dependency-probe cell against a fake venv + nvidia-smi.++ Returns every ``T4_SMOKE_REPORT`` the cell published.+ """+ payload_source = _payload_source(driver)+ fail_report_src = (+ "def fail_report" + payload_source.split("def fail_report", 1)[1].split("\n\ndef ", 1)[0]+ )+ emitted: list[str] = []+ namespace = {"json": json, "print": lambda *a, **kw: emitted.append("".join(map(str, a)))}+ exec(compile(fail_report_src, "<fail_report>", "exec"), namespace)++ class _FakeSubprocess:+ @staticmethod+ def run(cmd, **kw):+ if "nvidia-smi" in cmd[0]:+ return subprocess.CompletedProcess(cmd, 0, "\n".join(host_gpus) + "\n", "")+ return subprocess.CompletedProcess(cmd, 0, json.dumps(probe) + "\n", "")++ namespace.update(+ {+ "subprocess": _FakeSubprocess,+ "os": os,+ "VENV_PY": tmp_path / "python",+ "STUDIO_HOME": tmp_path,+ }+ )+ with pytest.raises(SystemExit):+ exec(compile(_cell_source(driver, 'probe["missing"]'), "<verify>", "exec"), namespace)+ return [line for line in emitted if line.startswith(build_kernel.RESULT_PREFIX)]+++def test_a_venv_that_cannot_use_cuda_on_a_gpu_box_is_a_failure_not_infra(tmp_path):+ """`install.sh --local` resolving a CPU-only torch is the CUDA install+ regression this leg exists to catch, and it left no T4_SMOKE_REPORT at all,+ so the launcher filed it as `infra` and the reporter exited 0."""+ reports = _run_verify_cell(+ _build(tmp_path),+ tmp_path,+ probe = {"versions": {"torch": "2.9.0+cpu"}, "missing": [], "cuda": {"available": False}},+ host_gpus = ["Tesla T4"],+ )+ assert len(reports) == 1, reports+ report = json.loads(reports[0][len(build_kernel.RESULT_PREFIX) :])+ assert report["passed"] is False+ assert "cannot use CUDA" in report["failures"][0]+++def test_a_session_kaggle_gave_no_gpu_at_all_stays_infra(tmp_path):+ """Nothing was learned about the code, so this one keeps the no-report path+ and must NOT turn a pull request red."""+ reports = _run_verify_cell(+ _build(tmp_path),+ tmp_path,+ probe = {"versions": {"torch": "2.9.0"}, "missing": [], "cuda": {"available": False}},+ host_gpus = [],+ )+ assert reports == []+++def test_a_payload_that_hangs_past_the_driver_deadline_is_a_failure(tmp_path):+ """papermill killed mid-assertion emitted no report at all, so a hang in+ the code under test was filed as unavailable infrastructure."""+ driver = _build(tmp_path)+ runner = None+ for cell in driver["cells"]:+ source = "".join(cell["source"])+ if "papermill" in source:+ runner = source+ assert runner is not None++ emitted: list[str] = []++ class _FakeSubprocess:+ TimeoutExpired = subprocess.TimeoutExpired+ STDOUT = subprocess.STDOUT++ @staticmethod+ def run(cmd, **kw):+ kw["stdout"].write(+ f"{build_kernel.PAYLOAD_SENTINEL} exec /usr/bin/python run_studio_gpu.py\n".encode()+ )+ kw["stdout"].flush()+ raise subprocess.TimeoutExpired(cmd, 3900)++ namespace = {+ "WORK": tmp_path,+ "os": os,+ "sys": sys,+ "time": __import__("time"),+ "json": json,+ "subprocess": _FakeSubprocess,+ "print": lambda *a, **kw: emitted.append("".join(map(str, a))),+ }+ exec(compile(runner, "<runner>", "exec"), namespace)+ reports = [line for line in emitted if line.startswith(build_kernel.RESULT_PREFIX)]+ assert len(reports) == 1, emitted+ assert json.loads(reports[0][len(build_kernel.RESULT_PREFIX) :])["passed"] is False+++def test_a_timeout_before_the_payload_started_is_still_infra(tmp_path):+ """A slow clone or install is Kaggle being slow, and must stay a no-report+ infra outcome rather than turning a pull request red."""+ driver = _build(tmp_path)+ runner = ["".join(c["source"]) for c in driver["cells"] if "papermill" in "".join(c["source"])][+ 0+ ]+ emitted: list[str] = []++ class _FakeSubprocess:+ TimeoutExpired = subprocess.TimeoutExpired+ STDOUT = subprocess.STDOUT++ @staticmethod+ def run(cmd, **kw):+ kw["stdout"].write(b"cloning...\n")+ raise subprocess.TimeoutExpired(cmd, 3900)++ namespace = {+ "WORK": tmp_path,+ "os": os,+ "sys": sys,+ "time": __import__("time"),+ "json": json,+ "subprocess": _FakeSubprocess,+ "print": lambda *a, **kw: emitted.append("".join(map(str, a))),+ }+ exec(compile(runner, "<runner>", "exec"), namespace)+ assert not [line for line in emitted if line.startswith(build_kernel.RESULT_PREFIX)]+++# ---------------------------------------------------------------- the gate flags+++def test_the_gate_is_told_how_many_kernels_this_leg_actually_pushes():+ """This leg pushes ONE kernel and leaves the second T4 idle. The gate+ defaults to two, and refuses unless that many slots are free."""+ import re++ text = WORKFLOW.read_text(encoding = "utf-8")+ gate = text.split("gate.py", 1)[1].split("\n\n", 1)[0]+ assert re.search(r"^\s+--kernels 1 \\\s*$", gate, re.MULTILINE), gate+ assert "--expect 1" in text+++def test_the_opt_in_label_can_actually_start_the_workflow():+ """GitHub's default pull_request activity types are opened, synchronize+ and reopened, so adding the advertised label started nothing."""+ triggers = _triggers(_workflow())+ assert "labeled" in triggers["pull_request"]["types"]+ for default in ("opened", "synchronize", "reopened"):+ assert default in triggers["pull_request"]["types"]+++def test_an_unrelated_label_cannot_start_a_seventy_minute_kaggle_run():+ """GitHub has no per-label event filter, so `labeled` fires for every label+ added -- and the gate reads the whole label list, so once the opt-in label+ sits on the pull request it would call every one of those events forced."""+ condition = " ".join(_workflow()["jobs"]["gate"]["if"].split())+ assert "github.event.action != 'labeled'" in condition+ assert "github.event.label.name == 'kaggle-studio-gpu-ci'" in condition+ # The fork guard still has to survive the added clause.+ assert "fork != true" in condition+++class _LoadStudio:+ def __init__(self, status_body):+ self.status_body = status_body++ def expect(+ self,+ method,+ path,+ body = None,+ **kw,+ ):+ return {}++ def get(self, path, **kw):+ return 200, self.status_body++ def post(+ self,+ path,+ body = None,+ **kw,+ ):+ return 200, {}+++def test_load_model_does_not_inherit_the_previous_loads_offload_line(tmp_path, monkeypatch):+ """The end-to-end shape of the scoping fix: a reload whose own load logged+ nothing must not pass on the chat model's `offloaded 29/29`."""+ module = _load_payload()+ session = _session(module, tmp_path, load_timeout = 5.0, gpu_layers = 99)+ session.outdir = tmp_path / "out"+ session.outdir.mkdir()+ session.server_log = session.outdir / "studio.log"+ session.studio_home.mkdir(parents = True, exist_ok = True)+ session.server_log.write_text("load_tensors: offloaded 29/29 layers to GPU\n", encoding = "utf-8")+ session.studio = _LoadStudio({})+ monkeypatch.setattr(module, "nvidia_used_mib", lambda: None)+ monkeypatch.setattr(module, "nvidia_compute_apps", lambda: {})+ monkeypatch.setattr(module, "llama_server_pids", lambda: [])+ monkeypatch.setattr(module.Payload, "settled_baseline", lambda self: None)++ detail = session.load_model("exported.gguf", variant = None, label = "exported")+ assert detail["positives"] == []+ assert detail["failures"], "silence must be a failure, not the previous load's evidence"+++def test_a_box_without_nvidia_smi_reports_no_gpu_rather_than_crashing(tmp_path, monkeypatch):+ """environment() runs inside finish(), on every path including the+ preflight one, so a FileNotFoundError there ended the run with a traceback+ and no report at all."""+ module = _load_payload()+ monkeypatch.setenv("PATH", str(tmp_path))+ assert module.gpu_inventory() == []+ assert module.nvidia_used_mib() is None+ assert module.nvidia_compute_apps() is Nonediff --git a/tests/kaggle/test_t4_ci_transport.py b/tests/kaggle/test_t4_ci_transport.pyindex f43831aec09..75703fcdaea 100644--- a/tests/kaggle/test_t4_ci_transport.py+++ b/tests/kaggle/test_t4_ci_transport.py@@ -389,7 +389,7 @@ def test_a_log_record_that_splits_the_report_is_still_read(tmp_path):assert [r["label"] for r in launch.extract_reports(tmp_path)] == ["canary"]-def test_every_push_attempt_gets_its_own_slug(monkeypatch):+def test_every_push_attempt_gets_its_own_slug(tmp_path, monkeypatch):"""Retrying onto one slug pushes a SECOND session and hides the first.A push to an existing id creates a new VERSION and starts another batch@@ -398,6 +398,11 @@ def test_every_push_attempt_gets_its_own_slug(monkeypatch):session only. A retry after a lost response therefore reads the wrongexecution's evidence while the first keeps billing unseen."""+ # The accepted push records its slug in the in-flight registry, so point+ # that at the tmp dir: otherwise this test files a kernel that does not+ # exist into the real registry and every later launcher's orphan sweep+ # tries, and fails, to delete it.+ monkeypatch.setattr(launch, "INFLIGHT", tmp_path / "inflight.json")attempts: list[list[str]] = []deleted: list[str] = []@@ -425,6 +430,10 @@ def test_every_push_attempt_gets_its_own_slug(monkeypatch):# before the next adds a second concurrent session.assert deleted == [s for s in slugs[:-1]]assert pushed["attempts"] == slugs+ # Only the accepted attempt is left for release to reclaim; the discarded+ # ones are gone, and registering those would leave the next launcher+ # sweeping for kernels that never existed.+ assert [e["slug"] for e in launch._inflight_read()] == [slugs[-1]]def _drive_main(diff --git a/tests/kaggle/test_t4_smoke_harness.py b/tests/kaggle/test_t4_smoke_harness.pyindex 4d9a8da9479..0ce3e5457e8 100644--- a/tests/kaggle/test_t4_smoke_harness.py+++ b/tests/kaggle/test_t4_smoke_harness.py@@ -3871,6 +3871,50 @@ def test_the_reports_of_every_kernel_are_gathered(tmp_path):assert sorted(r["label"] for r in reports) == ["control", "grpo"]+def test_the_log_fallback_reads_kaggles_own_json_record_shape(tmp_path):+ """The kernel log is the fallback for a run whose executed notebook never+ came back, and Kaggle does not hand that log back as text.++ `kernels/output` returns `log` as a JSON array of {stream_name, time,+ data} records, one record per line, so nothing in the file starts with+ the report prefix and reading it verbatim recovered nothing -- a failed+ assertion scored as infra. report.py::kernel_log_text and+ collect_evidence.py::iter_text already flatten it; this one has to too.+ """+ import launch++ records = [+ {"stream_name": "stderr", "time": 1.0, "data": "some noise\n"},+ {+ "stream_name": "stdout",+ "time": 2.0,+ "data": 'T4_SMOKE_REPORT {"label": "control", "model": "m", "passed": false}\n',+ },+ ]+ (tmp_path / "k1").mkdir()+ (tmp_path / "k1" / "kernel.log").write_text(+ "[" + "\n,".join(json.dumps(r) for r in records) + "]", encoding = "utf-8"+ )+ reports = launch.extract_reports(tmp_path)+ assert [r["label"] for r in reports] == ["control"]+ assert reports[0]["passed"] is False+++def test_a_report_split_across_log_records_is_still_read(tmp_path):+ """Kaggle chunks stdout by write, not by line, so the prefix and its+ payload can land in different records. Flattening has to join them back+ before any line splitting happens."""+ import launch++ records = [+ {"stream_name": "stdout", "time": 1.0, "data": 'T4_SMOKE_REPORT {"label": "grpo", '},+ {"stream_name": "stdout", "time": 1.1, "data": '"model": "q", "passed": true}\n'},+ ]+ (tmp_path / "k1").mkdir()+ (tmp_path / "k1" / "kernel.log").write_text(json.dumps(records), encoding = "utf-8")+ assert [r["label"] for r in launch.extract_reports(tmp_path)] == ["grpo"]++def test_a_kernel_that_could_not_be_pushed_does_not_lose_the_other(tmp_path):"""Half a run is a warning, not a failure: half a comparison is notevidence of a regression."""