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
Run deterministic notebook smoke tests on real Kaggle T4s (#8440)
Daniel Hanbb11b371e793
diff --git a/.github/ci-preempt.json b/.github/ci-preempt.jsonindex 08ebe3ae96b..0660e74a8f5 100644--- a/.github/ci-preempt.json+++ b/.github/ci-preempt.json@@ -37,7 +37,15 @@"","'never' is belt and braces. The sweeper already refuses to touch releases,","pull_request runs and itself; listing them again means a careless edit to",- "'heavy' cannot reach them."+ "'heavy' cannot reach them.",+ "",+ "kaggle-t4-notebook-ci.yml is in 'never' rather than under heavy.linux,",+ "which its 90-minute ubuntu job would otherwise qualify for. Cancelling",+ "that run does not stop the Kaggle kernel it has already pushed, and an",+ "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."],"heavy": {"macos": [@@ -72,6 +80,7 @@"publish-desktop-updater.yml","ci-capacity.yml","ossf.yml",- "stale.yml"+ "stale.yml",+ "kaggle-t4-notebook-ci.yml"]}diff --git a/.github/scripts/kaggle_t4_ci/BUDGET.md b/.github/scripts/kaggle_t4_ci/BUDGET.mdnew file mode 100644index 00000000000..8400fc23ecc--- /dev/null+++ b/.github/scripts/kaggle_t4_ci/BUDGET.md@@ -0,0 +1,129 @@+# What the Kaggle GPU budget buys, and where the sampling percentage comes from++One workflow spends this account's weekly GPU quota today:+`.github/workflows/kaggle-t4-notebook-ci.yml`. The percentage in it is not a+preference; it is the output of the arithmetic below. This file is here so the+next person to change it changes it against measurements rather than against a+guess.++**The workflow header is the source of truth.** The BUDGET block at the top of+`kaggle-t4-notebook-ci.yml` carries the same arithmetic beside the settings it+justifies, so it cannot drift from them silently the way this file can. If the+two ever disagree, the workflow is right and this file is stale; fix this file.++Measured 2026-08-11 against `unslothai/unsloth`, 7-day window, or on real+Kaggle sessions. None of it is estimated.++## The demand side++| quantity | measured |+|---|---|+| commits to `main` | 479/week |+| ... touching the paths filter | 45 (9.4%) |+| PRs opened | 567/week |+| ... touching the paths filter | 7.5% (9 of a 120 sample), so 43/week |+| commits carried by those PRs | 4.33 each |++"Watched paths" is what the notebook CI is actually about, and it is exactly+the `paths:` list in the workflow: `unsloth/**`, `tests/kaggle/**`,+`.github/scripts/kaggle_t4_ci/**`, the workflow file itself, and+`pyproject.toml` (the payloads install the commit under test as a+distribution, so how it is built and what it depends on is part of what this+tests). A PR that only edits Studio frontend or docs cannot regress a T4+training run, and spending a GPU session on it buys nothing.++Eligible invocations per week:++| event | count |+|---|---|+| push to main | 45 |+| pull_request opened | 43 |+| pull_request synchronize | 0 .. 143 |+| **total** | **88 .. 231** |++`synchronize` is one event per push after the first and is bounded above by+the commit count those PRs carry.++`labeled` is a trigger too and contributes nothing to this table, which is a+property of the gate rather than of the trigger. GitHub fires that action for+EVERY label, so without the check it would add one draw per label applied to+an eligible PR -- and once `kaggle-t4-ci` is present, one FORCED session per+label, since the label stays in the list the override reads. The gate stands a+`labeled` run down unless the label that arrived is the opt-in one, so the+only label activity that costs anything is the label that is a request for it.+Do not subscribe to another activity type without asking what it does to this+table.++## The supply side++Kaggle gives this account **60 GPU-hours/week** at time of writing. Kaggle's+documented baseline is 30h; the surplus is a discretionary "floating"+allowance that can be withdrawn, so treat 30h as the number that is+guaranteed. This workflow is allotted **40 GPU-h/week** of it.++Measured session cost, on kernels `066cd463` (control + canary, 263s of+payload) and `8161ceb9` / `7ab727f1` (gpt-oss, 375s of payload):++| kernel | wall clock |+|---|---|+| kernel 1 (control + canary) | 0.10 h |+| kernel 2 (gptoss + frontier) | 0.13 h |+| **one invocation** | **~0.25 h** |++A session bills its wall clock once, not per card, so the second T4 of each+kernel is free. That is why `frontier` costs nothing to carry.++## The sampling rate++Solve at the pessimistic end of the eligible range, targeting 30h rather than+the full 40 so an unusually busy week does not spend the allowance before the+quota floor has to intervene:++```+231 x r x 0.25 h = 30 h -> r = 0.52, set to 40%+```++So the workflow runs `--percent 40` with `--reserve-hours 20`. Expected spend+at 40%:++| week | invocations | spend |+|---|---|---|+| quiet | 88 x 0.40 | 8.8 GPU-h |+| busy | 231 x 0.40 | 23.1 GPU-h |++against the 40 GPU-h allowance: 15% to 39% of the 60h account.++## Why the reserve, and not just the rate++The rate sets the EXPECTED spend. The reserve sets the CEILING. Against a 60h+account, refusing to start below 20h remaining means CI can never have spent+more than 40h in a week, whatever the arithmetic above got wrong. Raise+`--reserve-hours` to throttle CI harder; do not raise it above roughly 45 or+CI will never run at all on a week with any other usage.++The worst case, if every sampled launch ran to both kernel ceilings, is far+above the allowance and is not what controls the spend. The reserve is.++`--budget-hours` is that worst case, and it is DERIVED rather than chosen:+`launch.py`'s constants bound one invocation at about 13800s of wall clock+(the push retries and the `_discard()` each one pays, the shared polling+deadline, `EVIDENCE_BUDGET_SEC`, and `release()` reconciling every slug+filed), and Kaggle runs at most 2 batch GPU sessions for this account at a+time, each billing its wall clock once. So 2 x 13800s = 7.7 GPU-h, set to 8.+`test_the_reserved_budget_covers_every_billable_launcher_phase` recomputes it+from `launch.py`; do not edit the number here or in the workflow without+changing what it is derived from.++## What would change these numbers++* A second Kaggle account doubles supply and the percentage could roughly+ double with it.+* The path filter is the biggest lever on demand. Widening the watched set is+ what makes the sampling rate feel too low.+* **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+ the allowance, so that change comes with a recomputation of this file and of+ the workflow header, not just a line in `legs.KERNELS`.+* If a second workflow ever starts spending this account, the split has to be+ derived here first. There is no second consumer today, and the reserve is+ sized on that.diff --git a/.github/scripts/kaggle_t4_ci/build_kernel.py b/.github/scripts/kaggle_t4_ci/build_kernel.pynew file mode 100644index 00000000000..31194cc21f8--- /dev/null+++ b/.github/scripts/kaggle_t4_ci/build_kernel.py@@ -0,0 +1,813 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Build the Kaggle kernel notebook(s) that run the T4 legs.++Two layers, because a Kaggle GPU session is 2xT4 and each payload is written+for one card:++**Payload notebook** -- one per GPU, one per *leg* (see ``legs.py``).+Materialises its sources from inlined copies, installs that leg's library set,+probes its imports, runs the leg's entry script, prints a machine-readable+result line.++**Driver notebook** -- one per kernel. Carries its payloads inline (gzip ++base64) so the kernel needs no dataset attachment and no network fetch of our+sources, gives each payload its own virtualenv and GPU, and runs them+concurrently under papermill. Nothing is checked out on the Kaggle side.++Cell order is load-bearing: **materialise, install, verify, run**. The control+leg installs from a pin file carried inside the notebook, so materialising last+(as an earlier version did) wrote that file after the install needing it.++Four details that are NOT safe to simplify away:++1. **Per-child virtualenv.** The legs deliberately pip-install DIFFERENT+ torch/transformers stacks. One shared site-packages destroys the+ experiment: control's pins and canary's upgrades land in the same tree and+ the last writer wins.+2. **``uv venv --seed``.** Without it the venv has no pip, so ``!pip install``+ falls through PATH to the system pip while the kernel runs the venv+ interpreter: installs and imports target different site-packages.+3. **``UV_SYSTEM_PYTHON=0``.** The Kaggle image ships ``UV_SYSTEM_PYTHON=1``,+ which BEATS ``VIRTUAL_ENV``: ``uv pip install`` writes to the base image+ while ``--system-site-packages`` lets the kernel import from there anyway,+ so both children silently share one tree.+4. **Runtime paths are built in Python, from ROOT.** A shell-shaped fragment+ spliced into a generated cell is a SyntaxError waiting for a Kaggle session,+ so ``@ROOT/`` arguments expand into ``str(ROOT / ...)`` expressions.+ ``test_generated_cells_compile`` is the cheap way to find that out.++Usage:+ python build_kernel.py --payload-dir tests/kaggle/t4_smoke \\+ --out kernel1.ipynb --legs control,canary+"""++from __future__ import annotations++import argparse+import base64+import gzip+import json+import os+import sys+import uuid+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))++from legs import KERNELS, PACKAGE_UNDER_TEST, Leg, expand_install, resolve # noqa: E402++DRIVER_SENTINEL = "KAGGLE_T4_CI_DRIVER"+PAYLOAD_SENTINEL = "KAGGLE_T4_CI_PAYLOAD"+RESULT_PREFIX = "T4_SMOKE_REPORT "++# Where the payload sources land on the Kaggle side, one directory PER LEG: a+# kernel's payloads run concurrently with byte-identical copies of the same+# files, and `write_bytes` truncates first, so one shared directory lets a+# payload empty a file the other is importing.+KERNEL_ROOT = "/kaggle/working/t4_smoke_src"+++def _kernel_root(leg: Leg) -> str:+ return f"{KERNEL_ROOT}_{leg.name}"+++def _encode_bytes(data: bytes) -> str:+ return base64.b64encode(gzip.compress(data)).decode("ascii")+++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 _shared_args_for(leg: Leg, extra_args: tuple[str, ...]) -> list[str]:+ """``--smoke-args``, minus any option the leg already sets for itself.++ Shared arguments keep the control and canary legs differing in nothing but+ versions, and are appended AFTER each leg's own, so for a leg naming the+ same option they override it (argparse takes the last value): the gpt-oss+ leg asks for 3 steps, a measured fit for a 16GB card, and the workflow's+ ``--max-steps 10`` silently retrained the 20B model for ten.+ """+ own = {a.split("=", 1)[0] for a in leg.args if a.startswith("--")}+ kept: list[str] = []+ drop_value = False+ for token in extra_args:+ if token.startswith("--"):+ if token.split("=", 1)[0] in own:+ # `--opt value` has to lose its value token as well.+ drop_value = "=" not in token+ continue+ drop_value = False+ kept.append(token)+ elif drop_value:+ drop_value = False+ else:+ kept.append(token)+ return kept+++def _arg_expression(value: str) -> str:+ """One entry of the child's argv, as a Python expression.++ ``@ROOT/x/y`` becomes ``str(ROOT / "x" / "y")`` so the path is assembled on+ the kernel from its own ROOT; everything else is a string literal.+ Interpolating the path into the generated source instead produced a cell+ reading ``"--label", "gpu0" --reference "{ROOT}/..."`` that died with a+ SyntaxError before a single training step ran.+ """+ if value.startswith("@ROOT/"):+ parts = [p for p in value[len("@ROOT/") :].split("/") if p]+ joined = " / ".join(["ROOT"] + [json.dumps(p) for p in parts])+ return f"str({joined})"+ return json.dumps(value)+++def build_payload_notebook(+ payload_dir: Path,+ leg: Leg,+ *,+ unsloth_ref: str,+ zoo_ref: str,+ extra_args: tuple[str, ...] = (),+ reference: str | None = None,+) -> dict:+ """A single-GPU notebook that installs one leg's stack and runs it."""+ root = _kernel_root(leg)+ wanted = list(leg.files)+ if leg.entry not in wanted:+ wanted.append(leg.entry)++ # `reference=None` means "whatever the leg asks for"; an explicit "" turns+ # the band check off, which is how a reference recapture is dispatched.+ ref_name = leg.reference if reference is None else reference+ if ref_name:+ wanted.append(f"references/{ref_name}")++ files = {}+ for name in wanted:+ path = payload_dir / name+ if not path.exists():+ raise FileNotFoundError(f"leg {leg.name!r} needs {name}, which is not in {payload_dir}")+ files[name] = _encode_bytes(path.read_bytes())++ materialise = f"""# Materialise the test sources carried inside this notebook.+#+# FIRST, before any install: the control leg installs from a pin file that+# travels in here, so the files have to be on disk before the first pip call.+import base64, gzip, json, os, pathlib+FILES = {json.dumps(files)}+ROOT = pathlib.Path({json.dumps(root)})+for name, blob in FILES.items():+ dest = ROOT / name+ dest.parent.mkdir(parents=True, exist_ok=True)+ dest.write_bytes(gzip.decompress(base64.b64decode(blob)))+print("{PAYLOAD_SENTINEL} sources " + json.dumps(sorted(FILES)), flush=True)+"""++ groups = expand_install(leg, unsloth_ref = unsloth_ref, zoo_ref = zoo_ref, payload_dir = payload_dir)+ install = f"""# Install this leg's library set.+#+# The groups below are generated from legs.py and are the ONLY thing that+# differs between the control leg and the version canary. They are printed+# before they run so the kernel log alone says what was asked for, which is+# what makes a canary failure attributable without downloading anything.+import json, subprocess, sys, time+print("{PAYLOAD_SENTINEL} leg {leg.name}: {leg.summary}", flush=True)+GROUPS = {json.dumps(groups)}+print("{PAYLOAD_SENTINEL} install plan " + json.dumps(GROUPS), flush=True)++def pip(args):+ cmd = [sys.executable, "-m", "pip", "install", "-q", *args]+ print(" $ " + " ".join(cmd[3:]), flush=True)+ # github.com occasionally 500s on a git fetch, and PyPI occasionally+ # times out; a single upstream blip must not be reported as a notebook+ # regression. The backoff is what lets the third failure be read as a+ # resolution that is genuinely impossible rather than as one bad minute:+ # three immediate retries all land inside the same outage.+ for attempt in (1, 2, 3):+ proc = subprocess.run(cmd, capture_output=True, text=True)+ if proc.returncode == 0:+ return+ print(f" install attempt {{attempt}} failed rc={{proc.returncode}}",+ flush=True)+ print(" " + proc.stderr.strip()[-1500:], flush=True)+ if attempt < 3:+ time.sleep(15 * attempt)+ continue+ print("{PAYLOAD_SENTINEL} INSTALL FAILED " + json.dumps(list(args)),+ flush=True)+ # A VERDICT, not missing evidence, for the same reason the dependency+ # probe below writes one: the launcher classifies a leg that reported+ # NOTHING as `partial` or `infra` and the workflow stays green. So a+ # commit whose distribution cannot be resolved -- conflicting+ # requirements in pyproject.toml, a dropped dependency -- used to pass+ # the one job added to test its packaging metadata, by failing early+ # enough that nothing was ever reported.+ print("{RESULT_PREFIX}" + json.dumps({{+ "label": {json.dumps(leg.name)},+ "model": "install",+ "passed": False,+ "failures": ["pip install failed after 3 attempts: "+ + " ".join(args) + " -- rc=" + str(proc.returncode)+ + ": " + proc.stderr.strip()[-500:]],+ }}), flush=True)+ raise SystemExit(f"pip install failed: {{args}}")++for group in GROUPS:+ pip(group)+print("{PAYLOAD_SENTINEL} install done", flush=True)+"""++ verify = f"""# Fail fast, and fail legibly.+#+# Without this, a missing dependency surfaces as a traceback buried in a+# child process's captured stdout, forty minutes and one GPU session later.+# Here it surfaces immediately, named, in the driver log.+import importlib, json, subprocess, sys+# Everything above was pip-installed AFTER this interpreter started, and the+# import system caches the directory listing of each sys.path entry. Without+# this, a just-installed package can be invisible to the very next import.+importlib.invalidate_caches()++# The resolved version of every package this CI watches, read from the+# installed distributions rather than from module attributes. This is the+# line a reader diffs between the control leg and the canary leg to name+# what moved, so it is printed before anything can crash.+sys.path.insert(0, {json.dumps(root)})+# Kept in a name rather than printed and discarded: report.version_table+# builds the per-leg comparison out of the REPORTS, not out of the log, so a+# leg whose report omits this is missing from the one table that says which+# release differed from the healthy control. Wrapped because a half-installed+# distribution can make importlib.metadata raise, and losing the report to a+# diagnostic would put this leg back to reporting nothing at all.+try:+ import versions+ RESOLVED = versions.flatten_versions(versions.resolved_versions())+except Exception as exc:+ RESOLVED = {{"error": f"{{type(exc).__name__}}: {{exc}}"[:200]}}+print("{PAYLOAD_SENTINEL} resolved " + json.dumps(RESOLVED), flush=True)++missing = []+# ORDER IS PART OF THE TEST, not cosmetic. `unsloth` comes before+# `unsloth_zoo`: zoo's __init__ ends with+# if find_spec("unsloth") is None:+# raise ImportError("Please install Unsloth via `pip install unsloth`!")+# and on a real T4 that fired on a session where unsloth WAS installed and+# imported cleanly one line later -- because by then `unsloth` was in+# sys.modules and find_spec answered from there. Probing zoo first therefore+# reported a missing dependency that was not missing, and aborted the payload+# before a single training step ran. Importing unsloth first is also the+# order every Unsloth notebook uses.+for mod in {json.dumps(list(leg.imports))}:+ try:+ importlib.import_module(mod)+ # BaseException, for the reason the GPU probe below gives: an import that+ # ends in `sys.exit()` raises SystemExit, which is NOT an Exception, and a+ # package refusing an accelerator or a version at import time is exactly+ # how that happens. Uncaught it aborts this cell before the report below+ # is written, the run cell never runs, and a leg that reported nothing is+ # `partial` or `infra` at the launcher -- both green. KeyboardInterrupt is+ # re-raised: that is the runner cancelling the job, not a bad dependency.+ except BaseException as exc:+ if isinstance(exc, KeyboardInterrupt):+ raise+ missing.append(f"{{mod}}: {{type(exc).__name__}}: {{exc}}")+if missing:+ print("{PAYLOAD_SENTINEL} MISSING " + json.dumps(missing), flush=True)+ # A probe failure is a VERDICT, not missing evidence, and the two exit+ # differently: the launcher extracts reports, and with none of them it+ # calls the whole run `infra` and the workflow stays green. So a commit+ # that breaks `import unsloth` -- a syntax error, a dropped runtime+ # dependency -- used to pass this job by failing early enough. The run+ # cell below is the only other thing that emits a report and it is never+ # reached from here, so the report is written HERE instead.+ print("{RESULT_PREFIX}" + json.dumps({{+ "label": {json.dumps(leg.name)},+ "model": "dependency probe",+ "passed": False,+ "versions_flat": RESOLVED,+ "failures": ["import failed -- " + m for m in missing],+ }}), flush=True)+ raise SystemExit("payload dependencies incomplete: " + "; ".join(missing))++# The GPU check, under the same rule as the import probe above: whatever+# goes wrong in here is a VERDICT and has to leave a report behind, because+# nothing further down this notebook ever runs to write one.+#+# The case that made it necessary: the driver shows the T4s to `nvidia-smi`,+# but dependency resolution picked a CPU-only or CUDA-incompatible torch+# wheel, so `device_count()` is 0. The bare assert aborted the cell, the+# launcher extracted no report for this leg, and no report is `infra` (or+# `partial` next to its partner) -- both of which exit 0. A regression that+# makes CUDA unusable was therefore invisible.+#+# `except BaseException`, and every line of the check inside it: the count+# is only one of the ways this fails. `import torch` can raise on a broken+# wheel, and get_device_properties can raise where device_count did not.+try:+ import torch+ print("{PAYLOAD_SENTINEL} gpu " + json.dumps({{+ "count": torch.cuda.device_count(),+ "name": torch.cuda.get_device_name(0) if torch.cuda.is_available() else None,+ "visible": __import__("os").environ.get("CUDA_VISIBLE_DEVICES"),+ }}), flush=True)+ # Exactly one GPU must be visible: two would mean the driver failed to pin+ # this payload to its own card, and accelerate would shard across both,+ # which is a different test from the single T4 a Colab user gets. Zero+ # means the payload cannot run at all on the hardware it was billed for.+ assert torch.cuda.device_count() == 1, (+ f"expected exactly 1 visible GPU, got {{torch.cuda.device_count()}}")+except BaseException as exc:+ detail = f"{{type(exc).__name__}}: {{exc}}"+ print("{PAYLOAD_SENTINEL} GPU_UNUSABLE " + json.dumps(detail), flush=True)+ print("{RESULT_PREFIX}" + json.dumps({{+ "label": {json.dumps(leg.name)},+ "model": "gpu probe",+ "passed": False,+ "versions_flat": RESOLVED,+ "failures": ["the payload could not use its GPU -- " + detail],+ }}), flush=True)+ raise++# Is what the distribution under test DECLARES it needs actually satisfied?+#+# The import probe above asks the weaker question: a requirement reached only+# by a delayed code path is absent all through a green run. pyproject.toml is+# in this workflow's trigger paths, so a commit that drops a requirement, adds+# one this image cannot satisfy, or tightens a bound past what is installed+# arrives here to be tested, and `pip install unsloth` is where a user meets+# it. LAST of the three checks because it is the only one that says nothing+# about whether this session can run: a card it cannot use is the more urgent+# verdict, and the GPU probe re-raises before reaching this.+#+# `pip check` is pip's own answer rather than a re-implementation of version+# comparison, and ONLY the lines owned by the distribution under test are read.+# The Kaggle image carries pre-existing conflicts of its own, and the frontier+# leg deliberately installs a transformers that unsloth_zoo's metadata forbids;+# both are other packages' lines and neither is this leg's verdict.+OWNER = {json.dumps(PACKAGE_UNDER_TEST)}+def _owned(line):+ head = line.strip().split(" ")[0].lower().replace("_", "-")+ return head == OWNER.lower().replace("_", "-")+_check = subprocess.run([sys.executable, "-m", "pip", "check"],+ capture_output=True, text=True)+unsatisfied = [ln.strip() for ln in (_check.stdout + _check.stderr).splitlines()+ if _owned(ln)]+if unsatisfied:+ print("{PAYLOAD_SENTINEL} REQUIREMENTS_UNSATISFIED "+ + json.dumps(unsatisfied), flush=True)+ # A VERDICT, for the third time in this cell and for the same reason: the+ # run cell below is the only other thing that writes a report, it is never+ # reached from here, and a leg that reported nothing leaves the workflow+ # green.+ print("{RESULT_PREFIX}" + json.dumps({{+ "label": {json.dumps(leg.name)},+ "model": "requirements",+ "passed": False,+ "versions_flat": RESOLVED,+ "failures": ["declared requirement unsatisfied -- " + u+ for u in unsatisfied],+ }}), flush=True)+ raise SystemExit("declared requirements unsatisfied: "+ + "; ".join(unsatisfied))+"""++ argv = list(leg.args) + _shared_args_for(leg, tuple(extra_args))+ if ref_name:+ argv += ["--reference", f"@ROOT/references/{ref_name}"]+ arg_exprs = ", ".join(_arg_expression(a) for a in argv)++ run = f"""# Run the leg in a child process.+#+# A child, not an import, for two reasons: the determinism setup has to run+# before torch is imported (and papermill has already imported plenty), and+# a hard crash then leaves this cell alive to report it.+import json, os, pathlib, subprocess, sys+ROOT = pathlib.Path({json.dumps(root)})+OUT = pathlib.Path("/kaggle/working/t4_out_{leg.name}")+OUT.mkdir(parents=True, exist_ok=True)++env = dict(os.environ)+env["PYTHONUNBUFFERED"] = "1"+env["UNSLOTH_DISABLE_STATISTICS"] = "1"+env.update({json.dumps(leg.env)})++cmd = [sys.executable, str(ROOT / {json.dumps(leg.entry)}),+ "--outdir", str(OUT), "--label", {json.dumps(leg.name)}]+cmd += [{arg_exprs}]+print("{PAYLOAD_SENTINEL} exec " + " ".join(cmd), flush=True)++# errors="replace", because the alternative is losing the verdict to the+# output. text=True decodes strictly, and a payload that dies in native code+# writes whatever bytes the crash handler had; one of them not being UTF-8+# raised UnicodeDecodeError HERE, before the synthetic report below, so+# papermill aborted the cell and the launcher, finding no report for this leg,+# called the run partial or infra. Both are green, on a leg that died.+proc = subprocess.run(cmd, env=env, capture_output=True, text=True, errors="replace")+print(proc.stdout[-40000:], 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 driver log alone is enough to+# judge the run, even if artifact collection fails entirely. Parsed and+# re-serialized COMPACTLY rather than echoed: every payload writes this file+# indented, the launcher scans whole lines for the prefix, and echoing the+# indented text verbatim therefore hands it a lone `{{` to decode. The+# recovery path meant for the case where the payload's own compact line fell+# out of the retained stdout tail was thus the one case it could not recover.+report = None+report_path = OUT / "t4_smoke_report.json"+if report_path.exists():+ try:+ report = json.loads(report_path.read_text())+ except Exception as exc:+ print("{PAYLOAD_SENTINEL} REPORT UNREADABLE " + repr(exc)[:300], flush=True)+ report = None++if isinstance(report, dict):+ print("{RESULT_PREFIX}" + json.dumps(report), flush=True)+else:+ # A VERDICT, not missing evidence, and the distinction decides whether+ # this job can go red at all. The child ran; a nonzero exit with no+ # readable report is a CUDA segfault, a native abort or an OOM kill, and+ # the definitive exit status for it is in hand right here. Printing only+ # "NO REPORT WRITTEN" left the launcher with nothing to extract, and no+ # reports at all is `infra` while a partner report is `partial` -- both+ # green. So the crash is reported as the failure it is.+ print("{PAYLOAD_SENTINEL} NO USABLE REPORT WRITTEN rc=" + str(proc.returncode), flush=True)+ print("{RESULT_PREFIX}" + json.dumps({{+ "label": {json.dumps(leg.name)},+ "model": "payload process",+ "passed": False,+ "returncode": proc.returncode,+ "failures": [+ "the payload process exited " + str(proc.returncode) + " and left no "+ "readable t4_smoke_report.json, so it died before it could judge "+ "itself. Its own report is the only thing that could have made this "+ "leg green.",+ ],+ "stderr_tail": proc.stderr[-2000:],+ }}), flush=True)++print("{PAYLOAD_SENTINEL} complete rc=" + str(proc.returncode), flush=True)+# Deliberately does NOT raise. A failing payload must not abort its partner+# on the other T4 and cost the whole session.+"""++ return {+ "cells": [+ _code_cell(materialise),+ _code_cell(install),+ _code_cell(verify),+ _code_cell(run),+ ],+ "metadata": {+ "kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"},+ "language_info": {"name": "python"},+ "accelerator": "GPU",+ "kaggle_t4_ci_leg": leg.name,+ },+ "nbformat": 4,+ "nbformat_minor": 5,+ }+++def build_driver(+ payloads: dict[str, dict],+ per_run_timeout: int,+ isolation: dict[str, bool] | None = None,+) -> dict:+ """Kernel notebook that fans the payloads out one per GPU.++ ``isolation`` maps a payload to whether its virtualenv may see the Kaggle+ image's site-packages. Per payload, not per kernel, because legs sharing a+ kernel do not share an answer: see ``Leg.system_site_packages``.+ """+ encoded = {name: _encode_bytes(json.dumps(nb).encode("utf-8")) for name, nb in payloads.items()}+ isolation = isolation or {}+ system_site = {name: bool(isolation.get(name, True)) for name in payloads}++ setup = f"""import base64, gzip, json, os, pathlib, subprocess, sys, threading, time+print("{DRIVER_SENTINEL} start", flush=True)++WORK = pathlib.Path("/kaggle/working")+PAYLOADS = {json.dumps(encoded)}+# Which payloads may see the Kaggle image's site-packages. A leg that+# replaces torch must not: pip would then treat torch's pinned NVIDIA+# runtime packages as satisfied by the image's copies and build an+# environment that installs cleanly and cannot be imported.+# repr, not json.dumps: JSON writes `true` and Python wants `True`, and a+# generated cell with a bare `true` in it parses and then dies with a+# NameError on a Kaggle session. test_no_generated_cell_reads_a_name_nothing+# _defines is what caught that, which is the whole reason it exists.+SYSTEM_SITE = {system_site!r}++# How many GPUs did we actually get? Assert rather than assume: a 1-GPU+# allocation would silently serialise everything onto device 0 and double+# every runtime while looking like a slow but healthy run.+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)+N_GPU = len(GPUS)+# A shortfall is INFRASTRUCTURE, and it has to be called that HERE, before a+# thread starts. `max(1, ...)` used to make one card look like enough: both+# payloads were pinned to device 0, each child still saw exactly one GPU and+# passed its own visibility assertion, and the contention came back as an OOM+# that read like a code failure. Standing the kernel down instead produces no+# report, which the launcher already classifies as infra rather than red.+if N_GPU < len(PAYLOADS):+ print("{DRIVER_SENTINEL}_INFRA " + json.dumps(+ {{"reason": "gpu_shortfall", "gpus": N_GPU, "payloads": len(PAYLOADS)}}),+ flush=True)+ raise SystemExit(+ f"{{len(PAYLOADS)}} payload(s) need one T4 each; the allocation "+ f"exposed {{N_GPU}}")++for name, blob in PAYLOADS.items():+ (WORK / name).write_bytes(gzip.decompress(base64.b64decode(blob)))+print("{DRIVER_SENTINEL}_PAYLOADS " + json.dumps(sorted(PAYLOADS)), flush=True)+"""++ runner = f'''results = {{}}+lock = threading.Lock()++def _make_venv(idx, system_site):+ """Give a child its own site-packages. See this file's module docstring."""+ vdir = WORK / f"venv_{{idx}}"+ try:+ uv = subprocess.run(["which", "uv"], capture_output=True,+ text=True).stdout.strip()+ if not uv:+ subprocess.run([sys.executable, "-m", "pip", "install", "-q", "uv"],+ check=True, timeout=900)+ uv = "uv"+ venv_cmd = [uv, "venv", str(vdir), "--seed"]+ if system_site:+ venv_cmd.append("--system-site-packages")+ subprocess.run(venv_cmd, check=True, timeout=900)+ py = vdir / "bin" / "python"+ subprocess.run([uv, "pip", "install", "-q", "--python", str(py),+ "ipykernel"], check=True, timeout=900)+ kname = f"t4ci{{idx}}"+ subprocess.run([str(py), "-m", "ipykernel", "install", "--user",+ "--name", kname], check=True, timeout=600)+ print(f"{DRIVER_SENTINEL}_VENV " + json.dumps(+ {{"idx": idx, "kernel": kname, "system_site": system_site}}),+ flush=True)+ return str(py), kname, str(vdir / "bin")+ except Exception as exc:+ print(f"{DRIVER_SENTINEL}_VENV_FAIL " + json.dumps(+ {{"idx": idx, "error": f"{{type(exc).__name__}}: {{exc}}"}}), flush=True)+ return None++def run_one(name, gpu_index, idx):+ src = WORK / name+ out = WORK / (pathlib.Path(name).stem + "_output.ipynb")+ env = dict(os.environ)+ # One GPU per payload. This is what makes the run comparable to the+ # single T4 a Colab user gets; two visible GPUs is a different test.+ env["CUDA_VISIBLE_DEVICES"] = str(gpu_index)+ env["PYTHONUNBUFFERED"] = "1"+ # One compile cache per payload. `unsloth_compiled_cache` is a RELATIVE+ # path resolved against the working directory, which both papermill+ # children inherit, so the legs -- which exist to install different+ # transformers/TRL versions and then compile the same modules -- would+ # otherwise overwrite and import each other's generated files. Set here+ # rather than in the payload so it also covers the notebook's own early+ # `import unsloth` in the verify cell.+ env["UNSLOTH_COMPILE_LOCATION"] = str(+ WORK / ("unsloth_compiled_cache_" + pathlib.Path(name).stem))++ made = _make_venv(idx, SYSTEM_SITE.get(name, True))+ if not made:+ # No venv means the SHARED system site-packages, which is the one+ # thing this driver exists to prevent: the legs' deliberately+ # different library sets would land in one tree, the last writer+ # would win, and the resulting import error would be reported as a+ # regression in the code under test. Skip the payload instead. It+ # produces no report, which the launcher classifies as infra.+ with lock:+ results[name] = {{"returncode": None, "gpu": gpu_index, "seconds": 0.0,+ "error": "virtualenv creation failed; payload skipped "+ "rather than run in the shared system kernel",+ "kernel": None, "output_exists": False}}+ print(f"{DRIVER_SENTINEL}_SKIPPED " + json.dumps({{name: results[name]}}),+ flush=True)+ return+ py, kernel, bindir = made+ env["PATH"] = bindir + os.pathsep + env.get("PATH", "")+ env["VIRTUAL_ENV"] = str(pathlib.Path(bindir).parent)+ env["UV_SYSTEM_PYTHON"] = "0"++ log = WORK / (pathlib.Path(name).stem + "_driver.log")+ 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", kernel, "--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"+ except Exception as exc:+ rc, err = -1, f"{{type(exc).__name__}}: {{exc}}"+ with lock:+ results[name] = {{"returncode": rc, "gpu": gpu_index,+ "seconds": round(time.time() - started, 1),+ "error": err, "kernel": kernel,+ "output_exists": out.exists()}}+ print(f"{DRIVER_SENTINEL}_DONE " + json.dumps({{name: results[name]}}),+ flush=True)++names = sorted(PAYLOADS)+threads = []+for i, name in enumerate(names):+ t = threading.Thread(target=run_one, args=(name, i % N_GPU, i), daemon=False)+ t.start()+ threads.append(t)+ time.sleep(5)+for t in threads:+ t.join()++print("{DRIVER_SENTINEL}_RESULTS " + json.dumps(results), flush=True)+'''++ tail = f"""# Surface each child's tail inline so the kernel log alone is diagnosable+# even if artifact collection fails.+for name in sorted(PAYLOADS):+ log = WORK / (pathlib.Path(name).stem + "_driver.log")+ print(f"\\n===== {{name}} (last 120 lines) =====", flush=True)+ if log.exists():+ print("\\n".join(log.read_text(errors="replace").splitlines()[-120:]),+ flush=True)+ else:+ print("NO LOG", flush=True)++# Drop the payload copies so `kernels output` returns only executed notebooks+# and child logs.+for name in sorted(PAYLOADS):+ try:+ (WORK / name).unlink()+ except OSError:+ pass++# Drop everything large AND reconstructible. `kernels output` returns the+# whole of /kaggle/working and we then wait for it over the wire; a previous+# sweep shipped 371MB back, almost all of it venv site-packages, and the+# download was still running eighteen minutes later.+import shutil as _shutil+for _pat in ("venv_*", "unsloth_compiled_cache*", "t4_smoke_src*",+ "huggingface_tokenizers_cache", "*/trainer*", "outputs"):+ for _d in WORK.glob(_pat):+ try:+ _shutil.rmtree(_d, ignore_errors=True)+ except Exception:+ 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_t4_ci": {"payloads": sorted(payloads)},+ },+ "nbformat": 4,+ "nbformat_minor": 5,+ }+++def build_kernel(+ payload_dir: Path,+ leg_names,+ *,+ unsloth_ref: str,+ zoo_ref: str,+ extra_args: tuple[str, ...],+ per_run_timeout: int,+ skip_reference: bool = False,+) -> dict:+ payloads = {}+ isolation = {}+ for leg in resolve(leg_names):+ name = f"t4_{leg.name}.ipynb"+ payloads[name] = build_payload_notebook(+ payload_dir,+ leg,+ unsloth_ref = unsloth_ref,+ zoo_ref = zoo_ref,+ extra_args = extra_args,+ reference = "" if skip_reference else None,+ )+ isolation[name] = leg.system_site_packages+ return build_driver(payloads, per_run_timeout, isolation)+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--payload-dir", required = True)+ ap.add_argument(+ "--out",+ required = True,+ help = "output notebook. With --all-kernels this is a "+ "prefix and the files are <prefix>1.ipynb, "+ "<prefix>2.ipynb, ...",+ )+ ap.add_argument(+ "--legs", help = "comma separated leg names; one per T4 of the session. See legs.py"+ )+ ap.add_argument(+ "--all-kernels",+ action = "store_true",+ help = "build every kernel in legs.KERNELS. This is what "+ "the workflow uses, so the leg-to-kernel plan lives "+ "in one place rather than being restated in YAML",+ )+ ap.add_argument("--unsloth-ref", default = "main")+ ap.add_argument("--zoo-ref", default = "main")+ ap.add_argument(+ "--smoke-args",+ default = "",+ help = "extra args appended to EVERY leg's entry script. "+ "Shared on purpose: the control and canary legs "+ "must not differ in anything but versions",+ )+ ap.add_argument(+ "--skip-reference",+ action = "store_true",+ help = "build with no band check at all. Only for the one run that recaptures a reference",+ )+ ap.add_argument("--per-run-timeout", type = int, default = 2400)+ args = ap.parse_args()++ if args.all_kernels == bool(args.legs):+ raise SystemExit("pass exactly one of --legs and --all-kernels")++ if args.all_kernels:+ plan = [list(kernel) for kernel in KERNELS]+ outputs = [Path(f"{args.out}{i + 1}.ipynb") for i in range(len(plan))]+ else:+ plan = [[n.strip() for n in args.legs.split(",") if n.strip()]]+ outputs = [Path(args.out)]+ if not plan[0]:+ raise SystemExit("--legs named nothing")++ for names, out in zip(plan, outputs):+ driver = build_kernel(+ Path(args.payload_dir),+ names,+ unsloth_ref = args.unsloth_ref,+ zoo_ref = args.zoo_ref,+ extra_args = tuple(args.smoke_args.split()),+ per_run_timeout = args.per_run_timeout,+ skip_reference = args.skip_reference,+ )+ 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) packing "+ f"{len(names)} leg(s): {', '.join(names)}"+ )+ # The launcher needs one --notebook per kernel and the expected payload+ # count; both follow from the plan, so they are emitted here rather than+ # restated in the workflow.+ _github_output("notebooks", " ".join(f"--notebook {o}" for o in outputs))+ _github_output("payloads", str(sum(len(n) for n in plan)))+ return 0+++def _github_output(key: str, value: str) -> None:+ path = os.environ.get("GITHUB_OUTPUT")+ if path:+ with open(path, "a", encoding = "utf-8") as fh:+ fh.write(f"{key}={value}\n")+ print(f"[build] {key}={value}")+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/.github/scripts/kaggle_t4_ci/check_steps.py b/.github/scripts/kaggle_t4_ci/check_steps.pynew file mode 100644index 00000000000..02ca4141e84--- /dev/null+++ b/.github/scripts/kaggle_t4_ci/check_steps.py@@ -0,0 +1,223 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Is this run's step count one that can train anything? Answered before paying.++``max_steps`` is a free-text ``workflow_dispatch`` input, and both ways of+getting it wrong cost a Kaggle session and report the pull request RED for+something that is not a code defect:++* **Not an integer.** ``foo`` travels all the way into the payload's argv, where+ argparse rejects it and the process exits 2 with no report written. The+ generated cell turns that into a failing report on purpose (a crashed payload+ must not read as missing evidence), so three legs come back as assertion+ failures -- after the kernels were pushed, the model downloaded and the quota+ spent.+* **Too small to apply an optimizer update.** Under fp16 the dynamic gradient+ scaler starts at 65536, halves on each overflow and SKIPS the step it+ overflowed on. The workflow passes no ``--init-loss-scale``, so the first+ steps of every run are skipped ones, and a run shorter than that prefix+ applies zero updates: ``optimisation_failures`` says so and the leg goes red+ having measured nothing.++Both are stand-downs, the same answer this workflow gives an unresolvable ref: a+warning and a green job, because nothing was learned about the code under test.++THE FLOOR IS MEASURED, NOT DECLARED. It is the shortest prefix of the COMMITTED+reference trace that the payload's own ``optimisation_failures`` accepts, so it+follows the reference and that function rather than a number written here that+would go stale the moment either moved. The prefix is the right comparison+because the payload trains on a constant schedule with no warmup+(``lr_scheduler_type="constant"``, ``warmup_steps=0``) and logs every step, so+an n-step run IS the first n steps of the committed 10-step one.++On the committed trace that comes out at 5: steps 1-3 have grad_norm NaN (all+skipped, no update applied) and step 4's loss is above step 1's, so 4 fails the+"loss did not decrease" check too, which is why the file docstring's "about+five" is a measurement rather than a guess.++Exits 0 whatever it decides. The stand-down travels as the ``stand_down``+output, like gate.py's.+"""++from __future__ import annotations++import argparse+import json+import os+import sys+from pathlib import Path++_HERE = Path(__file__).resolve().parent+if str(_HERE) not in sys.path:+ sys.path.insert(0, str(_HERE))++from legs import LEGS # noqa: E402+++def _log(msg: str) -> None:+ print(f"[steps] {msg}", flush = True)+++def _out(key: str, value: str) -> None:+ path = os.environ.get("GITHUB_OUTPUT")+ if path:+ with open(path, "a", encoding = "utf-8") as fh:+ fh.write(f"{key}={value}\n")+ _log(f"{key}={value}")+++def parse_steps(raw: str) -> int | None:+ """The dispatched value as a positive integer, or None if it is not one.++ ``int()`` alone is not the test: it accepts ``+7`` and surrounding+ whitespace, which are fine, and returns 0 or a negative for values the+ trainer cannot run at all.+ """+ try:+ steps = int(str(raw).strip())+ except (TypeError, ValueError):+ return None+ return steps if steps > 0 else None+++def reference_steps(payload_dir: Path, leg: str = "control") -> int | None:+ """The step count the committed reference declares, read the payload's way.++ The build step drops the band when this run's count is not the reference's,+ and ``check_reference`` refuses the same pairing from the other side, so the+ two have to mean the same thing by "the reference's count". This calls the+ payload's own ``reference_step_count`` rather than reading the JSON a second+ time, and finds the file through the leg registry rather than naming it.++ None when it cannot be established, which the build step already treats as+ not comparable: the payload's answer for a reference that does not say is+ ``reference_step_count_unknown``, a hard failure, so a band left on here+ would be red for the reference rather than for the code.+ """+ try:+ name = LEGS[leg].reference+ if not name:+ return None+ sys.path.insert(0, str(payload_dir))+ from run_t4_smoke import reference_step_count++ data = json.loads((payload_dir / "references" / name).read_text(encoding = "utf-8"))+ return reference_step_count(data)+ except Exception: # noqa: BLE001+ return None+++def reference_metrics(payload_dir: Path, leg: str = "control") -> list[dict]:+ """The committed trace the floor is measured from.++ Read through the leg registry rather than by naming the file again: the leg+ is what decides which reference this CI runs against.+ """+ name = LEGS[leg].reference+ if not name:+ return []+ path = payload_dir / "references" / name+ data = json.loads(path.read_text(encoding = "utf-8"))+ metrics = data.get("metrics")+ return metrics if isinstance(metrics, list) else []+++def minimum_steps(metrics: list[dict], failures) -> int | None:+ """Shortest prefix of ``metrics`` the payload's own verdict accepts.++ None when no prefix does, including the empty trace: an unmeasurable floor+ is not a floor of zero, and answering "any step count will do" is how a+ check that cannot fail gets written.+ """+ for n in range(1, len(metrics) + 1):+ if not failures(metrics[:n]):+ return n+ return None+++def decide(raw: str, payload_dir: Path) -> tuple[bool, str]:+ """(stand_down, reason) for the dispatched value."""+ steps = parse_steps(raw)+ if steps is None:+ return True, (+ f"max_steps was dispatched as {str(raw)[:80]!r}, which is not a positive "+ f"integer. Every leg forwards it to the payload, where argparse rejects it "+ f"and the process dies before it can judge itself, so the run would have "+ f"spent a Kaggle session to report the pull request red for a typo."+ )++ sys.path.insert(0, str(payload_dir))+ try:+ from run_t4_smoke import optimisation_failures+ except Exception as exc: # noqa: BLE001+ return True, (+ f"the payload's optimisation_failures could not be read "+ f"({type(exc).__name__}), so the step count that trains anything is "+ f"unknown and this run cannot be judged before it is paid for."+ )++ try:+ metrics = reference_metrics(payload_dir)+ except Exception as exc: # noqa: BLE001+ return True, (+ f"the committed reference could not be read ({type(exc).__name__}), so the "+ f"step count below which the fp16 scaler leaves a run with no applied "+ f"optimizer update is unknown."+ )++ floor = minimum_steps(metrics, optimisation_failures)+ if floor is None:+ return True, (+ "no prefix of the committed reference satisfies the payload's own "+ "optimisation checks, so the shortest run that trains anything cannot be "+ "measured. Recapture the reference before dispatching a step count."+ )+ if steps < floor:+ return True, (+ f"max_steps={steps} is below {floor}, the shortest run the committed "+ f"reference shows applying an optimizer update: under fp16 the gradient "+ f"scaler skips the leading steps, and this workflow passes no "+ f"--init-loss-scale, so a shorter run trains nothing and reports red for "+ f"the step count rather than for the code. Dispatch at least {floor}, or "+ f"wire --init-loss-scale and recapture the reference with it."+ )+ return False, f"max_steps={steps} is at or above the measured floor of {floor}"+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--max-steps", required = True, help = "the dispatched value, unvalidated")+ ap.add_argument("--payload-dir", required = True)+ args = ap.parse_args()++ stand_down, reason = decide(args.max_steps, Path(args.payload_dir))+ if stand_down:+ print(+ f"::warning title=Stood down on the dispatched step count::{reason}",+ flush = True,+ )+ else:+ _log(reason)+ _out("stand_down", "true" if stand_down else "false")+ _out("reason", reason)++ # The PARSED value, for everything downstream, so that the one place which+ # normalises the dispatched string is the one place that validated it.+ # parse_steps deliberately accepts "+10", "010" and surrounding whitespace+ # as the ten they are, and the payload's argparse agrees, so the build step+ # comparing the raw string against the reference's count used to read those+ # as a different run and drop the reference band from it: a green run with+ # the committed band never applied, announced as a step count that was not+ # actually different. The reference's own count comes from here too, for+ # the same reason -- one definition, the payload's.+ steps = parse_steps(args.max_steps)+ if steps is not None:+ _out("steps", str(steps))+ ref_steps = reference_steps(Path(args.payload_dir))+ _out("reference_steps", "" if ref_steps is None else str(ref_steps))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/.github/scripts/kaggle_t4_ci/gate.py b/.github/scripts/kaggle_t4_ci/gate.pynew file mode 100644index 00000000000..739f265bf7a--- /dev/null+++ b/.github/scripts/kaggle_t4_ci/gate.py@@ -0,0 +1,684 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Decide whether this invocation is allowed to spend Kaggle GPU quota.++The account behind KAGGLE_ACCESS_TOKEN_GH has a WEEKLY accelerator budget shared+with every other use of that account, and a kernel on every push would drain a+week of it in a day. So the default answer is "no" and a job earns "yes" through+four checks, in this order:++0. **Was this event a request at all?** A run started by APPLYING a label is a+ request only when that label is the opt-in one. The trigger fires on all+ labels and the budget counts none of them, so every other ``labeled`` event+ stands down first.+1. **Override.** ``workflow_dispatch`` with ``force=true``, or a pull request+ carrying the opt-in label. A human asked; skip the dice.+2. **Sampling.** Roughly one invocation in ten, derived from the run id so a+ re-run of the same run gives the same answer (otherwise anyone could reroll+ until it fires) while different runs stay independent.+3. **Remaining quota.** Refuses when what is left would not cover this+ invocation's worst case plus a reserve, so CI never drains the account. This+ is the ONE stand-down that is a failure rather than a skip; see below.+4. **Concurrency.** Kaggle caps concurrent batch GPU kernels at 2, per ACCOUNT+ rather than per workflow. The survey splits kernels this workflow pushed+ from the rest because they call for opposite answers: a FOREIGN kernel means+ a human is on the shared account and this invocation stands down entirely,+ while our own two are what it is here to launch. Both occupy slots, so the+ gate also refuses when fewer than KERNELS_PER_INVOCATION are free. The search+ is bounded by how long a session may last rather than by a kernel count,+ which is what makes it exhaustive; see LOOKBACK_HOURS.++Every negative answer is a SKIP, and a skip exits 0: not spending quota is+designed behaviour and must never colour a pull request red. The ONE exception+is an EXHAUSTED weekly quota, which exits nonzero carrying+QUOTA_EXHAUSTED_MESSAGE: that is not a dice roll going the usual way, it is the+whole account out of accelerator hours until the refresh, and a reader who sees+nothing at all cannot tell that from a workflow nobody wired up. It is decided+before the concurrency survey and before any kernel is pushed, so it costs one+API call rather than a Kaggle session. An UNREADABLE quota is still a skip:+"unknown" is not "exhausted". A real error in the gate itself is a skip too, and+``--no-soft-fail`` turns that back into a failure.++``--soft-fail`` is a REQUEST, not the default state. Passed explicitly it turns+the exhausted-quota failure back into a skip, for a caller that has already been+approved and is only re-asking (the workflow's recheck step, which runs with the+account slot in hand); passed nowhere, the failure stands.++No credential is ever printed: the token is read from the environment, handed to+the Kaggle client, and never echoed, logged or written to an output file.+"""++from __future__ import annotations++import argparse+import hashlib+import json+import os+import socket+import sys+import time+from datetime import datetime, timedelta, timezone++# Ceiling on any single network call, set globally before the first one. The+# Kaggle client takes no timeout of its own and Python's default is to block+# FOREVER, so without this a stalled connection returns to nobody: the `try`+# around each call never sees an exception, --soft-fail has nothing to convert+# into a skip, and the job's own timeout-minutes kills the runner and reports a+# red infrastructure failure on a workflow whose contract is that only a failed+# assertion on a T4 is red. launch.py sets one for the same reason.+SOCKET_TIMEOUT_SEC = 60++# Wall clock the in-flight survey may spend, whatever the account holds. The+# survey status-checks every kernel in a 13h window and pages up to+# MAX_KERNEL_PAGES x KERNELS_PAGE_SIZE of them, so slow (not hung: those are+# capped above) responses multiply. Running out of budget is NOT read as an idle+# account: the walk stops with complete=False, which concurrency_verdict already+# turns into a skip, so the gate answers within the job deadline rather than+# being killed by it.+SURVEY_BUDGET_SEC = 180++# Kaggle's cap on simultaneous batch (committed) GPU kernels per account.+# Measured, not documented: exceeding it fails the push with+# "Maximum batch GPU session count of 2 reached."+MAX_CONCURRENT_GPU_KERNELS = 2++# How many FOREIGN kernels may be in flight and this job still launch. ZERO IS+# DELIBERATE: a policy choice rather than a technical limit, so it is named+# rather than implied.+#+# The cap is per ACCOUNT and the account is shared with human use. Someone whose+# push is rejected cannot tell that CI took the slot, and CI cannot give it+# back. Standing down costs a few minutes until the next commit draws again (the+# sampling gate leaves this job no deadline of its own); being wrong costs+# somebody else's session. So a single foreign kernel stands this job down,+# whatever the arithmetic below would allow.+ALLOWED_IN_FLIGHT_FOREIGN_KERNELS = 0++# How many kernels one invocation pushes: both of Kaggle's slots, up from the+# single kernel this workflow used to run. The second slot is not spare capacity+# to be grabbed, it is capacity taken only when the account is otherwise IDLE,+# which the survey establishes immediately beforehand. Willingness to compete+# with a human is still zero; what changed is the payload, since four legs are+# worth running and two kernels x two T4s is the only shape that fits them. Legs+# split across two sessions would be compared across two images and two hours,+# and for control/canary that comparison is the entire instrument.+#+# The residual risk, a foreign kernel starting BETWEEN the survey and the push,+# is not new and is handled where it lands: the launcher recognises Kaggle's+# capacity rejection (CAPACITY_MARKERS) and reports it as infra, exiting 0.+# Ours is the push that arrives second, so a human's is never the one rejected.+KERNELS_PER_INVOCATION = 2++# Kernel states that mean a session is occupying one of those slots.+BUSY_STATES = {"QUEUED", "RUNNING"}++# How this job recognises its own kernels: `launch.py` pushes every kernel as+# `<user>/<OWN_KERNEL_PREFIX><8 hex>`, a fresh slug per attempt, and nothing else+# on the account uses that prefix. "The account is busy" and "this workflow is+# busy" call for opposite answers -- a foreign kernel means a human is using the+# account and this job must yield, while one of our own means a previous run is+# still in flight, which the concurrency group is supposed to prevent. Ours is+# reported separately rather than counted as a human, and still blocks, since it+# still occupies a slot.+OWN_KERNEL_PREFIX = "unsloth-t4-ci-"++# How far back the in-flight survey looks, and why that bound is COMPLETE+# rather than merely convenient.+#+# Kaggle exposes no "list my running sessions" call, so finding an in-flight+# kernel means listing kernels and status-checking them. The listing is sorted+# by last run time descending, and for an unfinished kernel that timestamp is+# when the run STARTED (measured: a kernel pushed at 10:05:19Z listed as+# last_run_time 10:05:19.297).+#+# Kaggle kills a notebook session at 12 hours (CPU/GPU; 9 for TPU), so a kernel+# still QUEUED or RUNNING cannot have started more than 12 hours ago, and once+# the walk reaches an older entry every remaining one is older still. Stopping+# there is exhaustive rather than a sample, which the previous fixed bound of+# "the 12 most recent kernels" was not: a kernel running for three hours would+# be missed once twelve newer ones had run, and the push would then fail at the+# capacity cap and be reported as infra.+MAX_SESSION_HOURS = 12.0++# Slack on top, for clock skew between Kaggle's timestamps and this runner,+# and for any future raise of the session ceiling.+CLOCK_SKEW_HOURS = 1.0+LOOKBACK_HOURS = MAX_SESSION_HOURS + CLOCK_SKEW_HOURS++# Paging for that walk. The page cap stops a pathological account making the+# gate walk forever; reaching it means the survey did NOT cover the whole+# window, reported as incomplete and treated as "unknown", never as "idle".+KERNELS_PAGE_SIZE = 100+MAX_KERNEL_PAGES = 5++# The two ways a status lookup can fail, only one of them benign. A deleted+# kernel stays in the listing for a while and answers its status call with a+# 404, which is not an unknown state but a kernel definitively not running;+# blocking on it would wedge the gate shut, since the launcher deletes every+# kernel it pushes. Anything else (a 5xx, a socket timeout, a client bug) says+# nothing about the kernel, which may be a human's RUNNING session, and+# proceeding could take the last slot from the person the zero-foreign policy+# protects. So 404 counts as "gone", everything else as "unreadable", and only+# the second stands the job down.+GONE_MARKERS = ("404", "not found", "notfound", "does not exist")++# What an exhausted weekly quota says, verbatim, in the log line and in the job+# summary. It is addressed to whoever opened the pull request, who did not cause+# it and cannot clear it: nothing was learned about their code, the hours come+# back on Kaggle's own refresh, and there is nothing for them to fix. The+# measured numbers are appended rather than replacing it, so the reader can see+# WHEN it clears; this sentence stays intact.+QUOTA_EXHAUSTED_MESSAGE = (+ "GPU capacity exhausted - please wait until next week - you can ignore this CI failure"+)+++def _looks_gone(exc: BaseException) -> bool:+ """Did this status lookup fail because the kernel no longer exists?"""+ text = f"{type(exc).__name__}: {exc}".lower()+ return any(marker in text for marker in GONE_MARKERS)+++def _out(key: str, value: str) -> None:+ path = os.environ.get("GITHUB_OUTPUT")+ if path:+ with open(path, "a", encoding = "utf-8") as fh:+ fh.write(f"{key}={value}\n")+ print(f"[gate] {key}={value}", flush = True)+++def _summary(text: str) -> None:+ path = os.environ.get("GITHUB_STEP_SUMMARY")+ if path:+ with open(path, "a", encoding = "utf-8") as fh:+ fh.write(text + "\n")+++def _decide(+ run: bool,+ reason: str,+ exit_code: int = 0,+) -> int:+ """Publish the answer and return the process exit code.++ ``exit_code`` defaults to 0 because almost every answer here is a skip. The+ one caller that passes 1 is the exhausted-quota branch; ``should_run`` is+ still written first either way, so a step reading the output sees "false"+ rather than an empty string.+ """+ _out("should_run", "true" if run else "false")+ _out("reason", reason)+ verdict = "RUN" if run else ("FAIL" if exit_code else "SKIP")+ print(f"[gate] {verdict}: {reason}", flush = True)+ _summary(f"### Kaggle T4 gate: {verdict}\n\n{reason}\n")+ return exit_code+++def sampled_in(run_id: str, percent: int) -> tuple[bool, int]:+ """Stable pseudo-random draw in [0, 100) derived from the run id."""+ digest = hashlib.sha256(run_id.encode("utf-8")).hexdigest()+ draw = int(digest[:8], 16) % 100+ return draw < percent, draw+++def kaggle_client():+ from kaggle.api.kaggle_api_extended import KaggleApi++ api = KaggleApi()+ api.authenticate()+ return api+++def remaining_gpu_hours(api) -> dict:+ """Exact remaining accelerator hours from Kaggle's own quota API."""+ resp = api.quota_view()+ quota = getattr(resp, "gpu_quota", None)+ if quota is None:+ return {"ok": False, "error": "no gpu_quota in quota response"}+ used = quota.time_used.total_seconds() / 3600.0+ total = quota.total_time_allowed.total_seconds() / 3600.0+ refresh = getattr(resp, "quota_refresh_time", None)+ return {+ "ok": True,+ "used_hours": round(used, 3),+ "total_hours": round(total, 3),+ "remaining_hours": round(max(0.0, total - used), 3),+ "refresh_at": refresh.isoformat() if refresh else None,+ }+++def _as_naive_utc(value):+ """Kaggle's timestamps, normalised so they can be compared at all."""+ if not isinstance(value, datetime):+ return None+ if value.tzinfo is None:+ return value+ return value.astimezone(timezone.utc).replace(tzinfo = None)+++def survey_kernels(+ api,+ now: datetime | None = None,+ lookback_hours: float = LOOKBACK_HOURS,+ page_size: int = KERNELS_PAGE_SIZE,+ max_pages: int = MAX_KERNEL_PAGES,+ budget_sec: float = SURVEY_BUDGET_SEC,+ clock = time.monotonic,+) -> dict:+ """Status-check every kernel that could still be in flight.++ Walks the account's kernels most-recently-run first and stops at the first+ that started longer ago than any session may last; see LOOKBACK_HOURS for+ why that is exhaustive.++ Returns the busy refs split by ownership, plus enough bookkeeping to tell+ "nothing is running" from "the question could not be answered":++ ``busy`` / ``own`` / ``foreign``+ every in-flight kernel, and the two disjoint halves of it. A kernel is+ ours when its slug carries OWN_KERNEL_PREFIX, which ``launch.py`` pushes+ under and nothing else uses.+ ``complete``+ the walk ran off the end of the listing or reached an entry outside the+ window. False means the page cap or ``budget_sec`` stopped it first and+ some candidates were never looked at.+ ``out_of_budget``+ the walk stopped because it ran out of wall clock. Slow responses over+ hundreds of status calls are how the survey outlives the job's own+ timeout, and being killed there costs the runner and reports red; giving+ up inside the deadline reports an incomplete survey, which is a skip.+ ``surveyed`` / ``unreadable`` / ``gone``+ how many in-window kernels were status-checked; how many left their+ state genuinely unknown; and how many answered 404, a deleted kernel+ rather than an unknown one. One unreadable status is not evidence of an+ idle account, so it is counted apart from the benign kind. See+ GONE_MARKERS.+ """+ # Naive UTC, matching what Kaggle returns. utcnow() is the same and is+ # deprecated from 3.12.+ now = now or datetime.now(timezone.utc).replace(tzinfo = None)+ cutoff = now - timedelta(hours = lookback_hours)+ busy: list[str] = []+ own: list[str] = []+ foreign: list[str] = []+ surveyed = 0+ unreadable = 0+ gone = 0+ complete = False+ out_of_budget = False+ deadline = clock() + budget_sec++ for page in range(1, max_pages + 1):+ if clock() >= deadline:+ out_of_budget = True+ break+ kernels = (+ api.kernels_list(mine = True, page = page, page_size = page_size, sort_by = "dateRun") or []+ )+ for kernel in kernels:+ ref = getattr(kernel, "ref", None)+ if not ref:+ continue+ if clock() >= deadline:+ out_of_budget = True+ break+ last_run = _as_naive_utc(getattr(kernel, "last_run_time", None))+ # A missing timestamp says nothing about age, so it cannot end the+ # walk, but it can still be checked.+ if last_run is not None and last_run < cutoff:+ complete = True+ break+ surveyed += 1+ try:+ status = str(getattr(api.kernels_status(ref), "status", ""))+ except Exception as exc: # noqa: BLE001+ # A 404 is a deleted kernel, so the slot is free. Any other+ # error leaves the state unknown, which is not evidence of an+ # idle account. See GONE_MARKERS.+ if _looks_gone(exc):+ gone += 1+ print(f"[gate] status 404 for {ref}: already deleted", flush = True)+ continue+ unreadable += 1+ print(f"[gate] status unreadable for {ref}: " f"{type(exc).__name__}", flush = True)+ continue+ state = status.rsplit(".", 1)[-1].upper()+ if state in BUSY_STATES:+ entry = f"{ref} ({state})"+ busy.append(entry)+ # Ownership is read off the SLUG, the part after the username:+ # a foreign kernel belongs to the same user, so the user half+ # says nothing.+ slug = ref.rsplit("/", 1)[-1]+ (own if slug.startswith(OWN_KERNEL_PREFIX) else foreign).append(entry)+ if complete or out_of_budget:+ break+ if len(kernels) < page_size:+ # Ran off the end of the account's kernels, so nothing is left to+ # miss.+ complete = True+ break++ if out_of_budget:+ print(+ f"[gate] survey gave up after {budget_sec}s with {surveyed} kernel(s) checked",+ flush = True,+ )++ return {+ "busy": busy,+ "own": own,+ "foreign": foreign,+ "surveyed": surveyed,+ "unreadable": unreadable,+ "gone": gone,+ # An abandoned walk is never complete, whatever it saw on the way.+ "complete": complete and not out_of_budget,+ "out_of_budget": out_of_budget,+ "window_hours": lookback_hours,+ }+++def concurrency_verdict(+ survey: dict,+ kernels_needed: int = KERNELS_PER_INVOCATION,+ allowed_foreign: int = ALLOWED_IN_FLIGHT_FOREIGN_KERNELS,+) -> tuple[bool, str]:+ """Is the account idle enough? Returns (clear_to_launch, why not).++ Two questions, in this order, because conflating them is how a workflow+ ends up either competing with a human or refusing capacity nobody wants.++ 1. **Is anyone else using the account?** Any foreign kernel stands this job+ down, whatever the slot arithmetic says. Stricter than Kaggle's cap+ requires, and deliberate; see ALLOWED_IN_FLIGHT_FOREIGN_KERNELS.+ 2. **Are there enough free slots?** It pushes ``kernels_needed`` against a+ cap of MAX_CONCURRENT_GPU_KERNELS, so its own leftovers count against it+ exactly as a stranger's would. A half launch would report half its legs,+ and the control/canary pair would have nothing to compare.++ "No busy kernel was found" is worth acting on only if the search could have+ found one, so an unanswerable question is a skip: standing down costs a few+ minutes until the next commit draws, guessing wrong costs a push rejected at+ the capacity cap.+ """+ foreign = survey.get("foreign", survey["busy"])+ own = survey.get("own", [])+ if len(foreign) > allowed_foreign:+ return False, (+ f"the Kaggle account has {len(foreign)} kernel(s) in flight that "+ f"are not this workflow's, and this job tolerates "+ f"{allowed_foreign}: {', '.join(foreign)}. The account is shared "+ f"with human use and CI yields to it; standing down rather than "+ f"queueing."+ )+ free = MAX_CONCURRENT_GPU_KERNELS - len(foreign) - len(own)+ if free < kernels_needed:+ return False, (+ f"this job pushes {kernels_needed} kernel(s) and only {free} of "+ f"the account's {MAX_CONCURRENT_GPU_KERNELS} slot(s) are free "+ f"({len(own)} already held by this workflow, {len(foreign)} by "+ f"something else). A partial launch would report a subset of the "+ f"legs, and the control and canary legs are only worth anything "+ f"as a pair."+ )+ if not survey["complete"]:+ ran_out = (+ "its wall-clock budget" if survey.get("out_of_budget") else f"{MAX_KERNEL_PAGES} pages"+ )+ return False, (+ "the in-flight survey did not reach the end of its "+ f"{survey['window_hours']}h window within {ran_out}, so an older "+ "kernel of this account could still be running unseen"+ )+ # ANY unreadable candidate, not just all of them: the one in-window kernel+ # that could not be read may be the human session this job yields to, and+ # "the ones we could read were idle" is no answer about it. Deleted kernels+ # answer 404 and count as `gone`, so the routine case does not wedge the+ # gate shut; see GONE_MARKERS.+ if survey.get("unreadable"):+ return False, (+ f"{survey['unreadable']} of {survey['surveyed']} in-window kernel "+ "status(es) could not be read, so whether the account is busy is "+ "unknown; standing down rather than assuming it is idle"+ )+ return True, ""+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument(+ "--percent", type = int, default = 10, help = "sampling rate when no override is present"+ )+ ap.add_argument("--run-id", default = os.environ.get("GITHUB_RUN_ID", "0"))+ ap.add_argument("--run-attempt", default = os.environ.get("GITHUB_RUN_ATTEMPT", "1"))+ ap.add_argument("--force", default = "false", help = "workflow_dispatch force input")+ ap.add_argument("--labels", default = "", help = "comma or newline separated PR labels")+ ap.add_argument("--label-name", default = "kaggle-t4-ci")+ ap.add_argument(+ "--event-action",+ default = "",+ help = "the pull_request action that started this run, if any",+ )+ ap.add_argument(+ "--event-label",+ default = "",+ help = "for a `labeled` action, the ONE label that was just applied",+ )+ ap.add_argument(+ "--budget-hours",+ type = float,+ required = True,+ help = "worst-case GPU hours this invocation can spend",+ )+ ap.add_argument(+ "--reserve-hours",+ type = float,+ default = 6.0,+ help = "quota CI refuses to dip into, left for humans",+ )+ ap.add_argument(+ "--kernels",+ type = int,+ default = KERNELS_PER_INVOCATION,+ help = "how many Kaggle kernels this invocation will push. "+ "The gate refuses unless that many slots are free",+ )+ ap.add_argument(+ "--allow-foreign-in-flight",+ type = int,+ default = ALLOWED_IN_FLIGHT_FOREIGN_KERNELS,+ help = "kernels NOT belonging to this workflow that may "+ "already be running and this job still launch. "+ "Default 0: the account is shared with human use and "+ "CI yields to it. See "+ "ALLOWED_IN_FLIGHT_FOREIGN_KERNELS before raising it",+ )+ # THREE states, not two, which is why this is store_const against a default+ # of None rather than store_true. An error in the gate is a skip whether or+ # not anyone asked (that has always been the default and stays it), but an+ # exhausted quota is a failure UNLESS a caller asked for soft failure, and+ # "the flag defaults to on" would make that request unaskable: every+ # invocation would look like it had been made and the red would never+ # appear. So None means "nobody said", True means "asked", False means+ # "--no-soft-fail", and the two questions read the value separately below.+ ap.add_argument(+ "--soft-fail",+ dest = "soft_fail",+ action = "store_const",+ const = True,+ default = None,+ help = "stand down rather than fail even when the weekly GPU quota is "+ "exhausted. For a caller already past the gate that is only "+ "re-asking; see the workflow's recheck step",+ )+ ap.add_argument(+ "--no-soft-fail",+ dest = "soft_fail",+ action = "store_const",+ const = False,+ help = "treat an error in the gate itself as a failure too",+ )+ args = ap.parse_args()++ # An error in the gate says nothing about the code under test, so it stays a+ # skip unless --no-soft-fail was passed.+ errors_are_skips = args.soft_fail is not False+ # Exhaustion is a fact about the account, and only an explicit request+ # softens it.+ exhaustion_is_soft = args.soft_fail is True++ label_name = args.label_name.strip().lower()++ # A LABEL EVENT IS A REQUEST ONLY IF IT IS THE OPT-IN LABEL, checked first+ # because it is what keeps the budget arithmetic true.+ #+ # The workflow subscribes to `labeled` so the opt-in label can start a run,+ # but GitHub fires that action for EVERY label. Without this, each unrelated+ # label (triage, size, whatever a bot applies) is a fresh run and a fresh+ # sampling draw, while the estimate at the top of the workflow counts only+ # pull request opens and pushes. Worse, once the opt-in label is present it+ # stays in the label list below, so every LATER label of any kind arrives as+ # an override and FORCES a session: two bot labels would spend two more.+ #+ # So a `labeled` run stands down unless the label that started it means "run+ # this". Every other action (opened, synchronize, reopened, a push, a+ # dispatch) is unaffected, and an opted-in pull request still forces on each.+ action = args.event_action.strip().lower()+ if action == "labeled":+ applied = args.event_label.strip().lower()+ if applied != label_name:+ return _decide(+ False,+ f"this run was started by applying the label {applied or '(unnamed)'!r}, "+ f"which is not the opt-in label {args.label_name!r}. Labelling a pull "+ f"request is not a request to spend a Kaggle session, and every label "+ f"would otherwise be one more draw -- or, once the opt-in label is "+ f"present, one more forced run",+ )+ print(f"[gate] started by the opt-in label {args.label_name!r}", flush = True)++ override = args.force.strip().lower() in ("true", "1", "yes")+ labels = [l.strip().lower() for l in args.labels.replace("\n", ",").split(",") if l.strip()]+ if label_name in labels:+ override = True+ print(f"[gate] override: label {args.label_name!r} present", flush = True)++ # Reported even when overridden, so the log shows what the unforced answer+ # would have been. run_attempt is excluded so a re-run cannot reroll.+ picked, draw = sampled_in(str(args.run_id), args.percent)+ print(+ f"[gate] sampling draw={draw} threshold={args.percent} "+ f"picked={picked} (run {args.run_id}, attempt {args.run_attempt})",+ flush = True,+ )++ if not override and not picked:+ return _decide(+ False,+ f"not sampled this time (draw {draw} of 100, "+ f"threshold {args.percent}); this is the normal "+ f"outcome for roughly {100 - args.percent}% of "+ f"invocations",+ )++ if not os.environ.get("KAGGLE_API_TOKEN"):+ return _decide(+ False,+ "KAGGLE_API_TOKEN is not available to this "+ "context (expected on a fork pull request, "+ "where secrets are withheld)",+ )++ # Before the first network call, and globally: authenticate(), quota_view()+ # and every status call below go through a client with no timeout of its+ # own, and a stalled one would outlive this job's timeout-minutes. With it,+ # a stall raises and the handlers below turn it into a skip. See+ # SOCKET_TIMEOUT_SEC.+ socket.setdefaulttimeout(SOCKET_TIMEOUT_SEC)++ try:+ api = kaggle_client()+ except BaseException as exc: # noqa: BLE001+ if isinstance(exc, KeyboardInterrupt):+ raise+ msg = f"could not authenticate to Kaggle: {type(exc).__name__}"+ if not errors_are_skips:+ print(f"[gate] {msg}", flush = True)+ return 1+ return _decide(False, msg)++ try:+ quota = remaining_gpu_hours(api)+ except Exception as exc: # noqa: BLE001+ quota = {"ok": False, "error": type(exc).__name__}+ print("[gate] quota " + json.dumps(quota), flush = True)+ _out("quota", json.dumps(quota))++ if quota.get("ok"):+ need = args.budget_hours + args.reserve_hours+ if quota["remaining_hours"] < need:+ # THE ONE RED STAND-DOWN, and it is answered here rather than after+ # the survey on purpose: one quota call, no kernel pushed, no+ # session spent to report that there are no sessions left. The+ # required sentence comes first and whole; the numbers behind it+ # follow so the reader can see when the hours come back.+ return _decide(+ False,+ f"{QUOTA_EXHAUSTED_MESSAGE}. "+ f"{quota['remaining_hours']}h of the weekly {quota['total_hours']}h "+ f"accelerator quota is left, and this run needs up to "+ f"{args.budget_hours}h on top of a {args.reserve_hours}h reserve. "+ f"Quota refreshes at {quota.get('refresh_at')}",+ exit_code = 0 if exhaustion_is_soft else 1,+ )+ else:+ # An unreadable quota is not permission to spend it -- and it is not+ # evidence of exhaustion either, so it stays a green skip.+ return _decide(+ False,+ "could not read the Kaggle accelerator quota, so the remaining budget is unknown",+ )++ try:+ survey = survey_kernels(api)+ except Exception as exc: # noqa: BLE001+ return _decide(+ False,+ "could not list this account's kernels "+ f"({type(exc).__name__}), so concurrency cannot "+ "be established",+ )+ print(+ "[gate] concurrency "+ + json.dumps(+ {k: v for k, v in survey.items() if k not in ("busy", "own", "foreign")}+ | {+ "busy": len(survey["busy"]),+ "own": len(survey["own"]),+ "foreign": len(survey["foreign"]),+ }+ ),+ flush = True,+ )++ clear, why_not = concurrency_verdict(survey, args.kernels, args.allow_foreign_in_flight)+ if not clear:+ return _decide(False, why_not)++ why = (+ "forced by override"+ if override+ else f"sampled in (draw {draw} of 100, threshold {args.percent})"+ )+ return _decide(+ True,+ f"{why}; {quota['remaining_hours']}h of GPU quota "+ f"remaining and {args.kernels} of the account's "+ f"{MAX_CONCURRENT_GPU_KERNELS} kernel slots are free",+ )+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/.github/scripts/kaggle_t4_ci/launch.py b/.github/scripts/kaggle_t4_ci/launch.pynew file mode 100644index 00000000000..94c1f53decc--- /dev/null+++ b/.github/scripts/kaggle_t4_ci/launch.py@@ -0,0 +1,1125 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Push the kernels to Kaggle, wait for them, and bring the evidence back.++One invocation handles every kernel of the run. All of them are pushed FIRST+and only then waited on: pushing one, waiting, then pushing the next would+serialise sessions Kaggle runs happily at once, and the control/canary pair's+whole value is that they ran at the same time on the same account. A kernel that+could not be pushed does not stop the others; the verdict compares the reports+that came back against the number expected, so a half-launched run reports+``partial``, a warning rather than a failure, since half a comparison is not+evidence of a regression.++Failure semantics are the point of this file. Two kinds of bad outcome exit+differently, because conflating them is how a flaky external service blocks+merges:++* ``exit 0`` with ``verdict=infra`` -- the test never ran, or its result never+ got back: push throttled, account at its concurrency cap, a kernel that died+ on Kaggle's side, a download that would not complete, our own wall-clock+ ceiling. Nothing was learned, so nothing turns red.+* ``exit 0`` with ``verdict=pass`` / ``verdict=fail`` -- the payload ran and+ reached a conclusion. Judging it is ``report.py``'s job; this file only+ transports it.++The only nonzero exit is a usage error.++Wall clock is bounded three times over, and the order of trust is the opposite+of what it looks like:++* **Deleting the kernel**, the control observed to work. Every kernel this+ process pushed is deleted on the way out, on every path including failures,+ and deletion stops the billing (measured: the account's used-hours figure went+ DOWN when a wedged kernel was deleted).+* **Our polling deadline** (``--max-wait``), which decides when to give up and+ therefore when to delete.+* **Kaggle's own kernel timeout**, passed at push time. A backstop, NOT+ sufficient alone: on 2026-08-11 a kernel pushed with ``-t 5400`` whose+ nbconvert crashed at t=406s sat in RUNNING for over two hours, past that+ ceiling and past this process's deadline, and stopped only on a manual delete.+ The value is still passed, but nothing rests on it.++A socket timeout is set globally for the same reason: one status call that never+returns stalls the poll loop past every deadline above, which is how that+two-hour kernel went unnoticed.++No credential is printed. The token is read from the environment by the Kaggle+client and never echoed.+"""++from __future__ import annotations++import argparse+import json+import os+import re+import shutil+import socket+import subprocess+import sys+import tempfile+import time+import urllib.parse+import urllib.request+import uuid+from pathlib import Path, PurePosixPath, PureWindowsPath++sys.path.insert(0, str(Path(__file__).resolve().parent))++# What Kaggle says when a kernel is not there. Defined next to the gate's+# survey, which has to tell a deleted kernel from an unreadable one for the+# same reason cleanup does. See _already_gone.+from gate import GONE_MARKERS # noqa: E402++API_ROOT = "https://www.kaggle.com/api/v1"+RESULT_PREFIX = "T4_SMOKE_REPORT "+OUTPUT_SUFFIX = "_output.ipynb"++TERMINAL_OK = {"COMPLETE"}+TERMINAL_BAD = {"ERROR", "CANCEL_REQUESTED", "CANCEL_ACKNOWLEDGED"}++_STATUS_RE = re.compile(r"KernelWorkerStatus\.(?P<status>[A-Z_]+)")++PUSH_ATTEMPTS = 4+PUSH_BACKOFF_SEC = 45++# Ceiling on one `kaggle kernels push` subprocess. Named because the workflow's+# job timeout derives from it, and because exceeding it is a retryable,+# ambiguous outcome rather than an error -- see push().+PUSH_SUBPROCESS_TIMEOUT_SEC = 600++# What a throttled or briefly unavailable push looks like coming back. The+# JSON-decode message is the common face: Kaggle answers 429 and 503 with an+# HTML error page, the client decodes it as JSON anyway, and the throttling is+# never named. Everything else (a bad slug, a rejected accelerator, missing+# credentials) is deterministic and must not be retried.+THROTTLED_PUSH = (+ "expecting value: line 1 column 1",+ "429",+ "too many requests",+ "502",+ "503",+ "service unavailable",+ "bad gateway",+ "timed out",+ "connection reset",+ "connection aborted",+)++# Kaggle's concurrency cap, reported as a push rejection rather than a queue.+CAPACITY_MARKERS = (+ "maximum batch gpu session count",+ "session count of 2 reached",+ "toomanyassignments",+ "precondition failed",+ "412",+ "no accelerator quota",+ "no quota for",+)++# Ceiling on any single network call. urllib takes an explicit timeout and the+# Kaggle client does not, so this is the only bound on its status and quota+# calls. Without it, one call that never returns outlasts every deadline in this+# file while the kernel it was watching keeps billing.+SOCKET_TIMEOUT_SEC = 120++# Consecutive unreadable statuses before we stop waiting. One is not enough: the+# API returns transient 5xx that the client prints exactly like a permanent+# refusal, and giving up on a blip abandons a kernel still doing the work.+MAX_CONSECUTIVE_UNKNOWN = 10++# Attempts at deleting ONE kernel, and the first gap between them. Deleting is+# the budget control, so a refused delete is retried rather than written off,+# against the same transient 5xx and reset connections push() retries.+#+# Named, like the push ceiling, because the job timeout is derived from them:+# ONE delete costs DELETE_ATTEMPTS x DELETE_SUBPROCESS_TIMEOUT_SEC plus its+# backoffs, and both push() (which discards the previous attempt's slug before+# each retry) and release() (which reconciles every slug filed) pay it. The+# harness suite recomputes the total from these three and asserts the workflow's+# deadline sits above it.+DELETE_ATTEMPTS = 3+DELETE_BACKOFF_SEC = 5+DELETE_SUBPROCESS_TIMEOUT_SEC = 180++# Pages of `kernels/output` one listing walks before it stops asking, and the+# ceiling on the WHOLE evidence phase: every kernel's listing pages and every+# notebook download, together.+#+# ONE budget for all of it, started before the first collection, because that+# is the only shape the job deadline can be derived from. Per call, the bound+# was the product of things nobody multiplied out: OUTPUT_PAGE_LIMIT pages at+# the 120s socket ceiling is 2400s for ONE kernel's listing alone, and each+# executed notebook is another 300s with no cap on how many Kaggle lists. The+# workflow header budgeted 600s for two kernels and the harness suite asserted+# the same 600s as a literal, so the term in the job deadline restated the+# intention rather than measuring the code: a paginating or slow endpoint spent+# the job's remaining wall clock HERE, and the runner was then killed before+# finish() -> release() ran, leaving billable kernels up. That is the exact+# outcome the deadline exists to prevent.+#+# Enforcement is "start no new work past the deadline", each call's own timeout+# is clamped to what remains, AND the body is read in chunks against the same+# absolute deadline. The last part is not redundant: the timeout urllib takes is+# a per-socket-operation timeout ("a timeout in seconds for blocking operations+# like the connection attempt" -- docs.python.org/3/library/urllib.request.html),+# not a ceiling on the transfer, so an endpoint that keeps returning bytes+# resets it forever and a single `resp.read()` outlasts the whole budget while+# every deadline check sits before the call. Evidence is best effort by design+# -- whatever arrived is reported and the collection is marked truncated --+# because the alternative is spending the deletion window on it.+EVIDENCE_BUDGET_SEC = 600+OUTPUT_PAGE_LIMIT = 20+# Per read. Small enough that the deadline is re-checked often against a slow+# stream, large enough not to syscall per kilobyte on a fast one.+READ_CHUNK_BYTES = 1 << 16+++def worst_case_seconds(max_wait: int, kernels: int) -> int:+ """Wall clock ONE invocation of this launcher can take, from its constants.++ Every phase that can keep a pushed kernel UP is in it, because a kernel+ bills from the moment Kaggle accepts it until a delete is confirmed:++ * ``push()``, per notebook: PUSH_ATTEMPTS attempts at the subprocess+ ceiling, the backoffs between them, and the ``_discard()`` of the previous+ attempt's slug that rides along with every retry.+ * the polling, which shares ONE deadline started before the first push, so+ it does not stack on top of the pushes; the longer of the two is spent.+ * the evidence phase, ONE budget for every kernel together.+ * ``release()``, which deletes every slug every push FILED, not just the+ accepted one.++ Computed here rather than restated by each consumer: the workflow's job+ deadline, the quota the gate reserves, and the pre-push guard in main() are+ all wrong by the same amount if a phase is left out, and lowering+ PUSH_ATTEMPTS or a delete ceiling has to move all three at once.+ """+ one_delete = DELETE_ATTEMPTS * DELETE_SUBPROCESS_TIMEOUT_SEC + sum(+ DELETE_BACKOFF_SEC * 2**i for i in range(DELETE_ATTEMPTS - 1)+ )+ per_push = (+ PUSH_ATTEMPTS * PUSH_SUBPROCESS_TIMEOUT_SEC+ + sum(PUSH_BACKOFF_SEC * 2**i for i in range(PUSH_ATTEMPTS - 1))+ + (PUSH_ATTEMPTS - 1) * one_delete+ )+ return (+ max(kernels * per_push, max_wait)+ + EVIDENCE_BUDGET_SEC+ + kernels * PUSH_ATTEMPTS * one_delete+ )+++def _log(msg: str) -> None:+ print(f"[launch] {msg}", flush = True)+++def _out(key: str, value: str) -> None:+ path = os.environ.get("GITHUB_OUTPUT")+ if path:+ with open(path, "a", encoding = "utf-8") as fh:+ if "\n" in value:+ delim = f"ghadelim{uuid.uuid4().hex}"+ fh.write(f"{key}<<{delim}\n{value}\n{delim}\n")+ else:+ fh.write(f"{key}={value}\n")+++def _slugify(text: str) -> str:+ s = re.sub(r"[^a-zA-Z0-9]+", "-", text).strip("-").lower()+ return re.sub(r"-{2,}", "-", s)[:50].strip("-")+++def _api():+ from kaggle.api.kaggle_api_extended import KaggleApi++ api = KaggleApi()+ api.authenticate()+ return api+++def _pushed(ok: bool, reason: str, out: str, attempted: list[str]) -> dict:+ """A push outcome, always carrying the slugs the call filed.++ A failed attempt may still have landed, Kaggle answering a committed push+ with a 5xx often enough to be a known issue, so the slug is reported rather+ than forgotten and the caller can reconcile it.+ """+ return {"ok": ok, "reason": reason, "detail": out.strip()[:400], "attempts": attempted}+++def push(+ notebook: Path,+ user: str,+ kernel_timeout_sec: int,+ accelerator: str = "NvidiaTeslaT4",+ attempted: list[str] | None = None,+) -> dict:+ """Push as a fresh private kernel. Every attempt gets its own slug.++ A fresh slug per attempt is not cosmetic: pushing to an id that ALREADY+ exists does not replace what is there, it files a new version and starts a+ SECOND batch session while the running one keeps running. ``kernels status``+ and ``kernels/output`` send no version label, so they answer for the newest+ session only, and a reused slug means the evidence belongs to whichever+ execution was latest while the other burns a slot and its quota unseen.++ The retried failures are exactly the ambiguous ones (a reset connection, an+ aborted transfer, a 5xx) where Kaggle may have accepted the push whose+ response never arrived. So each attempt also DELETES the previous attempt's+ slug first: deletion is kernel-level, costs one call, and frees the session+ slot the retry is probably waiting on.++ Returns the accepted attempt's slug, plus ``attempts``: every slug this call+ filed, newest last.++ ``attempted`` is that list, and the caller may OWN it: pass a list and every+ slug appears in it the moment it is filed, rather than on return. Only a+ return can be lost, and this function reaches the network, so anything it+ raises other than the timeout it handles (``subprocess.run(text=True)``+ decodes with strict error handling and raises ``UnicodeDecodeError`` on a+ malformed response; the runner can also answer with ``OSError`` or+ ``MemoryError``) would otherwise take the slug of a push Kaggle may have+ ACCEPTED with it, leaving a kernel nothing will delete. See main().+ """+ base = _slugify("unsloth t4 ci")[:32]+ attempted = [] if attempted is None else attempted++ def _discard(slug: str) -> None:+ """Best effort; the attempt usually created nothing at all.++ release() reconciles whatever this leaves, so the outcome is only logged+ here, but it IS read rather than assumed.+ """+ if not delete_kernel(slug):+ _log(f"could not discard the previous push attempt {slug}")++ workdir = Path(tempfile.mkdtemp(prefix = "kaggle-t4-ci-"))+ try:+ out = ""+ for attempt in range(PUSH_ATTEMPTS):+ if attempted:+ _discard(attempted[-1])+ slug_name = f"{base}-{uuid.uuid4().hex[:8]}"+ # The slug derives from the TITLE, not the metadata id: a mismatch+ # files the kernel at an unexpected address and every later+ # status/output call 403s, so assert the round trip.+ title = slug_name.replace("-", " ")+ assert _slugify(title) == slug_name, f"title {title!r} slugifies to {_slugify(title)!r}"+ attempted.append(f"{user}/{slug_name}")++ for stale in workdir.glob("*.ipynb"):+ stale.unlink()+ code_file = workdir / f"{slug_name}.ipynb"+ shutil.copy(notebook, code_file)+ (workdir / "kernel-metadata.json").write_text(+ json.dumps(+ {+ "id": f"{user}/{slug_name}",+ "title": title,+ "code_file": code_file.name,+ "language": "python",+ "kernel_type": "notebook",+ "is_private": "true",+ "enable_gpu": "true",+ "enable_internet": "true",+ "machine_shape": accelerator,+ "dataset_sources": [],+ "competition_sources": [],+ "kernel_sources": [],+ "model_sources": [],+ },+ indent = 2,+ ),+ encoding = "utf-8",+ )++ try:+ proc = subprocess.run(+ [+ "kaggle",+ "kernels",+ "push",+ "-p",+ str(workdir),+ "--accelerator",+ accelerator,+ "-t",+ str(kernel_timeout_sec),+ ],+ capture_output = True,+ text = True,+ timeout = PUSH_SUBPROCESS_TIMEOUT_SEC,+ )+ out = proc.stdout + proc.stderr+ except subprocess.TimeoutExpired:+ # A push that ran out of wall clock is the MOST ambiguous+ # outcome, not the least: the client was killed mid-call, so+ # whether Kaggle accepted the kernel is unknowable from here,+ # and letting the exception out loses the slug and with it every+ # chance of deleting the session it may have started.+ #+ # So it is recorded as a failed attempt like any other: the slug+ # stays in `attempted`, the retry _discard()s it, and release()+ # reconciles the rest. "timed out" is in THROTTLED_PUSH because+ # 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]})")+ 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)+ 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)+ if attempt + 1 == PUSH_ATTEMPTS or not any(m in lowered for m in THROTTLED_PUSH):+ return _pushed(False, "push_failed", out, attempted)+ delay = PUSH_BACKOFF_SEC * (2**attempt)+ _log(+ f"push looks throttled, retrying in {delay}s "+ f"(attempt {attempt + 1}/{PUSH_ATTEMPTS})"+ )+ time.sleep(delay)+ return _pushed(False, "push_failed", out, attempted)+ finally:+ shutil.rmtree(workdir, ignore_errors = True)+++def _already_gone(text: str) -> bool:+ """Is this failed delete Kaggle saying the kernel is not there?++ The gate's vocabulary, imported rather than copied: the two files ask the+ same question of the same account through the same client, and a second+ list would drift out of agreement with the first without either being wrong+ on its own.+ """+ return any(marker in text.lower() for marker in GONE_MARKERS)+++def delete_kernel(slug: str) -> bool:+ """Delete one kernel, and answer whether Kaggle actually deleted it.++ ``subprocess.run`` does not raise on a nonzero exit, so the caller used to+ record every slug as released whatever came back: a refused delete, an+ expired token, or the case that made this visible, where the pinned client+ had no ``kernels delete`` subcommand at all and argparse exited 2 before any+ request was sent while the run still reported the kernel released. Cleanup+ is this workflow's budget control, so an unestablished delete has to read as+ STILL BILLING.++ The exit code is the signal Kaggle's client offers, and it means what it+ says: kaggle/cli.py exits 1 on a failed call, commented "This is so that+ scripts that pick up on error codes can tell when there was a failure", and+ 0 once the kernel is gone.++ NOT FOUND IS THE OTHER CONFIRMED ANSWER, and it is a common one here rather+ than an edge case: most of the slugs release() reconciles are earlier push+ attempts, which usually created nothing at all, and one that a retry's+ _discard() did delete is asked about a second time. Kaggle answering "this+ kernel is not there" settles the only question cleanup asks -- is the slot+ still billing -- so retrying it three times and then naming it in a+ "may still be running, delete them by hand" warning spends the deletion+ window on absent kernels, ahead of the live one, and points a human at a+ slug that does not exist. The gate reads a 404 the same way and for the+ same reason, so it reads it through the same GONE_MARKERS; the client+ surfaces one as `404 Client Error: Not Found for url: ...` on stderr with+ exit 1 (requests' raise_for_status, via kagglesdk's response handler).++ Every OTHER nonzero exit keeps its retries: a 5xx, a reset connection or an+ argparse refusal says nothing about the kernel.++ Returns True only on a confirmed deletion or a confirmed absence. A slug+ this refuses needs a human, which is what the caller's warning is for.+ """+ for attempt in range(DELETE_ATTEMPTS):+ try:+ proc = subprocess.run(+ ["kaggle", "kernels", "delete", slug, "-y"],+ capture_output = True,+ text = True,+ timeout = DELETE_SUBPROCESS_TIMEOUT_SEC,+ )+ except Exception as exc: # noqa: BLE001+ _log(f"delete {slug} did not run: {type(exc).__name__}")+ else:+ if proc.returncode == 0:+ return True+ detail = " ".join(f"{proc.stdout} {proc.stderr}".split())+ if _already_gone(detail):+ _log(f"delete {slug}: Kaggle says it is not there, so the slot is free")+ return True+ _log(f"delete {slug} exited {proc.returncode}: {detail[:200]}")+ if attempt + 1 < DELETE_ATTEMPTS:+ time.sleep(DELETE_BACKOFF_SEC * (2**attempt))+ return False+++def _slugs_filed(entry: dict) -> list[str]:+ """Every slug one kernel entry's push filed, in the order it filed them.++ Cleanup reconciles ALL of them, not only the accepted one, and both routes+ to a leaked slug are ambiguous by construction:++ * The last attempt of a FAILED push. ``push()`` keeps the slug precisely+ because Kaggle answers an accepted push with a 5xx or a reset connection+ often enough to be a known issue, and that entry carries no ``slug``.+ * An EARLIER attempt of a push that later succeeded. ``_discard()`` runs+ before each retry but is best effort, so a delete Kaggle refuses even+ after ``delete_kernel``'s retries leaves the previous attempt up.++ Either keeps a session slot and bills GPU quota with nobody reading the+ result. A delete for a slug Kaggle never created is refused and costs one+ call.+ """+ filed = [*(entry.get("attempted") or []), entry.get("slug")]+ return list(dict.fromkeys(s for s in filed if s))+++def poll(api, slug: str) -> str:+ try:+ raw = str(getattr(api.kernels_status(slug), "status", ""))+ except Exception as exc: # noqa: BLE001+ _log(f"status unreadable: {type(exc).__name__}")+ return "UNKNOWN"+ match = _STATUS_RE.search(raw)+ return match.group("status") if match else (raw.strip().upper() or "UNKNOWN")+++def wait(api, slug: str, poll_every: int, max_wait: int) -> str:+ """Poll to a terminal state.++ An unreadable status must NOT count as "still running" forever: with no+ status to match, sitting here for the full ceiling on a kernel that long+ since finished is an hour of wall clock spent learning nothing. So bound the+ consecutive failures and hand back UNREADABLE, never COMPLETE, since how it+ ended is genuinely unknown.+ """+ deadline = time.time() + max_wait+ unknowns = 0+ last = "UNKNOWN"+ while time.time() < deadline:+ state = poll(api, slug)+ if state != last:+ _log(f"state: {state}")+ last = state+ if state in TERMINAL_OK or state in TERMINAL_BAD:+ return state+ if state == "UNKNOWN":+ unknowns += 1+ if unknowns >= MAX_CONSECUTIVE_UNKNOWN:+ return "UNREADABLE"+ else:+ unknowns = 0+ time.sleep(poll_every)+ return "HARNESS_TIMEOUT"+++def _bearer() -> str:+ token = os.environ.get("KAGGLE_API_TOKEN")+ if not token:+ raise RuntimeError("KAGGLE_API_TOKEN unset; REST path unavailable")+ return token+++def _evidence_deadline(deadline: float | None) -> float:+ """The shared budget if the caller has one, otherwise a fresh one.++ Never unbounded. ``deadline=None`` used to mean "no ceiling", which is the+ state this constant exists to end, so the default is a budget of its own:+ a caller can only make the bound TIGHTER by sharing one, never absent.+ """+ return time.time() + EVIDENCE_BUDGET_SEC if deadline is None else deadline+++def _time_left(deadline: float, timeout: int) -> int | None:+ """Seconds this call may take, or None when the deadline has passed.++ The single place the evidence budget is applied, so no caller can start a+ request the phase has no time for and none can outlast it: the timeout+ handed to urllib is the SMALLER of the call's own ceiling and what is left.+ """+ remaining = int(deadline - time.time())+ if remaining <= 0:+ return None+ return min(timeout, remaining)+++def _clamp_socket(resp, seconds: float) -> None:+ """Tighten the live socket's timeout to what is left of the budget.++ The timeout handed to ``urlopen`` is fixed when the response opens, so a+ read that starts just inside the deadline may still block for all of it.+ Re-clamping per chunk bounds the overshoot by one chunk rather than by one+ socket timeout. Best effort: the loop below stops at the deadline whether or+ not the socket can be reached.+ """+ sock = getattr(getattr(getattr(resp, "fp", None), "raw", None), "_sock", None)+ setter = getattr(sock, "settimeout", None)+ if setter is None:+ return+ try:+ setter(max(seconds, 1.0))+ except OSError:+ pass+++def _read_within(+ resp,+ deadline: float,+ sink = None,+) -> bytes:+ """Read a response body under the ABSOLUTE deadline, not a socket timeout.++ ``urlopen(timeout=...)`` bounds each blocking socket operation, so a server+ that keeps trickling bytes renews it indefinitely and ``resp.read()`` runs+ as long as it likes -- past the evidence budget, into the wall clock+ ``release()`` needs, with billable kernels still up. Checking the deadline+ only before opening the response therefore bounds nothing about the read.++ So: one chunk at a time, deadline re-checked before each, and ``read1`` so a+ chunk is at most ONE underlying socket read (``read(n)`` loops until it has+ n bytes, which a slow trickle can stretch arbitrarily). ``sink`` streams+ straight to disk, which also keeps a response nobody sized out of memory.+ """+ reader = getattr(resp, "read1", None) or resp.read+ chunks: list[bytes] = []+ while True:+ left = deadline - time.time()+ if left <= 0:+ raise TimeoutError("the evidence budget expired while reading the response")+ _clamp_socket(resp, left)+ chunk = reader(READ_CHUNK_BYTES)+ if not chunk:+ break+ if sink is None:+ chunks.append(chunk)+ else:+ sink.write(chunk)+ return b"".join(chunks)+++def list_outputs(+ slug: str,+ timeout: int = 120,+ deadline: float | None = None,+) -> dict:+ """List a kernel's outputs, one page at a time, inside the budget.++ ``truncated`` says the listing is INCOMPLETE -- the page limit or the+ evidence deadline stopped it -- so a caller can tell "Kaggle listed these+ files" from "these are the files we got to before the clock ran out".+ """+ deadline = _evidence_deadline(deadline)+ user, _, name = slug.partition("/")+ params = {"userName": user, "kernelSlug": name}+ files: list[dict] = []+ log = ""+ truncated = True+ for _ in range(OUTPUT_PAGE_LIMIT):+ call_timeout = _time_left(deadline, timeout)+ if call_timeout is None:+ _log(f"evidence budget spent while listing {slug}")+ break+ url = f"{API_ROOT}/kernels/output?{urllib.parse.urlencode(params)}"+ req = urllib.request.Request(+ url,+ headers = {+ "Authorization": f"Bearer {_bearer()}",+ "User-Agent": "unsloth-kaggle-t4-ci/1.0",+ },+ )+ try:+ with urllib.request.urlopen(req, timeout = call_timeout) as resp:+ data = json.loads(_read_within(resp, deadline))+ except TimeoutError:+ # The budget ran out mid-body. Same answer as running out between+ # pages: stop, and say the listing is incomplete.+ _log(f"evidence budget spent while reading a page of {slug}")+ break+ files.extend(f for f in data.get("files") or [] if f.get("fileName"))+ log = log or (data.get("log") or "")+ token = data.get("nextPageToken") or ""+ if not (data.get("hasNextPageToken") and token):+ truncated = False+ break+ params = dict(params, pageToken = token)+ return {"files": files, "log": log, "truncated": truncated}+++def _dest_name(file_name: str) -> str:+ """Basename of a listed output, safe on every platform.++ Kaggle lists nested outputs with POSIX separators. Joining a listed name+ onto the output directory unexamined would let ``../`` walk out of it, and+ ``Path`` answers for the HOST rather than for the name, so peel POSIX first+ and Windows second with both pure flavours.+ """+ name = PureWindowsPath(PurePosixPath(file_name).name).name+ return name or PurePosixPath(file_name).name+++def fetch_evidence(+ slug: str,+ outdir: Path,+ timeout: int = 300,+ deadline: float | None = None,+) -> dict:+ """Pull the executed notebooks and the kernel log by direct URL.++ By direct URL rather than the bulk download: the bulk call returns the WHOLE+ of /kaggle/working as one stream, and a previous incident lost two PASSING+ notebooks because a multi-GB saved model sorted alphabetically ahead of them+ and the stream broke partway through.++ ``deadline`` is the shared evidence budget (EVIDENCE_BUDGET_SEC), an+ absolute ``time.time()`` value covering every kernel of the run. Nothing+ starts after it and every call is clamped to what is left of it, so this+ phase cannot eat the wall clock release() needs to delete the kernels.+ """+ deadline = _evidence_deadline(deadline)+ outdir.mkdir(parents = True, exist_ok = True)+ listing = list_outputs(slug, timeout = min(timeout, 120), deadline = deadline)+ fetched = []+ truncated = bool(listing.get("truncated"))+ for entry in listing["files"]:+ name = _dest_name(entry["fileName"])+ if not name.endswith(OUTPUT_SUFFIX):+ continue+ url = entry.get("url") or entry.get("urlNullable")+ if not url:+ continue+ call_timeout = _time_left(deadline, timeout)+ if call_timeout is None:+ _log(f"evidence budget spent; {name} and anything after it were not downloaded")+ truncated = True+ break+ dest = outdir / name+ part = dest.with_suffix(dest.suffix + ".part")+ try:+ req = urllib.request.Request(url, headers = {"User-Agent": "unsloth-kaggle-t4-ci/1.0"})+ with urllib.request.urlopen(req, timeout = call_timeout) as resp, part.open("wb") as fh:+ _read_within(resp, deadline, sink = fh)+ # Only publish once it parses: a download killed mid-write leaves a+ # file of plausible size, which is evidence that looks present and+ # is not.+ json.loads(part.read_text(encoding = "utf-8", errors = "replace"))+ part.replace(dest)+ fetched.append(dest.name)+ except Exception as exc: # noqa: BLE001+ # A listed notebook that did not land is missing evidence, whether+ # the budget ran out mid-body or the transfer failed, so the+ # collection is incomplete and has to say so rather than read as a+ # complete set that happens to be short.+ _log(f"could not fetch {name}: {type(exc).__name__}")+ part.unlink(missing_ok = True)+ truncated = True+ log_path = outdir / "kernel.log"+ if listing.get("log"):+ log_path.write_text(listing["log"], encoding = "utf-8")+ return {+ "notebooks": fetched,+ "log": log_path.name if log_path.exists() else None,+ "truncated": truncated,+ }+++def _flatten_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+ ``{stream_name, time, data}`` records, whose boundaries are not line+ boundaries. Scanning it as-is finds no line beginning with the report+ prefix, so a payload whose executed notebook never came back -- the case+ this fallback exists for -- read as no report and was downgraded to+ ``infra``.++ ``report.kernel_log_text`` does the same for the summary; both are kept+ because the two scripts are separate processes and neither imports the+ other.+ """+ try:+ records = json.loads(raw)+ except ValueError:+ return raw+ if not isinstance(records, list):+ return raw+ return "".join(r.get("data", "") for r in records if isinstance(r, dict))+++def extract_reports(outdir: Path) -> list[dict]:+ """Every T4_SMOKE_REPORT payload found in the collected evidence.++ Cell outputs of the executed notebooks first, flat kernel log second. The+ notebook is the better source (one cell, unambiguous ownership), but the log+ survives cases where the notebook never got written back.+ """+ reports: list[dict] = []+ seen: set[str] = set()++ def _consume(text: str) -> None:+ for line in text.splitlines():+ if not line.startswith(RESULT_PREFIX):+ continue+ blob = line[len(RESULT_PREFIX) :].strip()+ try:+ parsed = json.loads(blob)+ except json.JSONDecodeError:+ continue+ key = f"{parsed.get('label')}|{parsed.get('model')}"+ if key in seen:+ continue+ seen.add(key)+ reports.append(parsed)++ # rglob, not glob: each kernel collects into its own subdirectory so two+ # cannot overwrite each other's kernel.log.+ for nb_path in sorted(outdir.rglob(f"*{OUTPUT_SUFFIX}")):+ 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)+ _consume(text)+ for log_path in sorted(outdir.rglob("kernel.log")):+ _consume(_flatten_log(log_path.read_text(encoding = "utf-8", errors = "replace")))+ return reports+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument(+ "--notebook",+ required = True,+ action = "append",+ help = "kernel notebook to push. Repeatable: all of them "+ "are pushed before any of them is waited on",+ )+ ap.add_argument("--user", required = True)+ ap.add_argument("--outdir", required = True)+ ap.add_argument(+ "--expect", type = int, default = 2, help = "payload reports this kernel should produce"+ )+ ap.add_argument(+ "--kernel-timeout-sec",+ type = int,+ default = 3600,+ help = "hard ceiling enforced by KAGGLE on the session",+ )+ ap.add_argument(+ "--max-wait",+ type = int,+ default = 4200,+ help = "wall clock this invocation gives the kernels, measured from BEFORE the first push",+ )+ ap.add_argument("--poll-every", type = int, default = 60)+ ap.add_argument(+ "--keep-kernel", action = "store_true", help = "do not delete the kernel after collecting"+ )+ ap.add_argument(+ "--deadline-epoch",+ type = int,+ default = 0,+ help = "unix time at which the CALLER is killed. Nothing is pushed unless "+ "worst_case_seconds() still fits before it. 0 disables the check",+ )+ args = ap.parse_args()++ # Before the first network call, and globally: the Kaggle client has no+ # per-call timeout of its own. See SOCKET_TIMEOUT_SEC.+ socket.setdefaulttimeout(SOCKET_TIMEOUT_SEC)++ outdir = Path(args.outdir)+ outdir.mkdir(parents = True, exist_ok = True)+ result: dict = {+ "verdict": "infra",+ "reason": "",+ "slug": None,+ "kernel_state": None,+ "reports": [],+ }++ def release() -> None:+ """Delete every kernel this process pushed. Idempotent, and on every+ path out of main().++ The budget control, not a tidy-up: a kernel left behind bills to its own+ ceiling with nobody reading the result, and Kaggle's push-time timeout+ has been observed not to stop one that wedged. Deleting a two-hour-old+ stuck kernel took the account's used-hours figure DOWN.++ Every slug the push FILED is reconciled, not only the accepted one; see+ ``_slugs_filed`` for the two ways an unaccepted slug can still be+ running. A slug counts as released only once Kaggle CONFIRMS the delete+ (see delete_kernel); anything else may still be billing, so it is named+ in the log, in ``launch_result.json`` and in a workflow annotation+ rather than quietly counted as cleaned up.+ """+ if args.keep_kernel:+ return+ leaked: list[str] = []+ for entry in result.get("kernels") or []:+ done = set(entry.get("released_slugs") or [])+ for slug in _slugs_filed(entry):+ if slug in done:+ continue+ if delete_kernel(slug):+ done.add(slug)+ else:+ leaked.append(slug)+ _log(f"could not delete {slug}; it may keep billing")+ entry["released_slugs"] = sorted(done)+ entry["released"] = all(s in done for s in _slugs_filed(entry))+ result["unreleased"] = leaked+ if leaked:+ print(+ "::warning title=Kaggle kernels may still be running::"+ + ", ".join(leaked)+ + " could not be deleted, so they may keep billing accelerator "+ "quota until they hit their own ceiling. Delete them by hand.",+ flush = True,+ )++ def finish(code: int = 0) -> int:+ release()+ (outdir / "launch_result.json").write_text(json.dumps(result, indent = 2), encoding = "utf-8")+ _out("verdict", result["verdict"])+ _out("reason", result["reason"])+ _out("slug", result["slug"] or "")+ _log(f"verdict={result['verdict']} reason={result['reason']}")+ return code++ def window_fits(after: str) -> bool:+ """Does the job's remaining wall clock still cover the worst case?++ Asked TWICE, because the answer expires: everything between the two+ asks is time the guard already granted. See the two call sites.+ """+ if not args.deadline_epoch:+ return True+ need = worst_case_seconds(args.max_wait, len(args.notebook))+ left = int(args.deadline_epoch - time.time())+ if left >= need:+ _log(f"{left}s left of the job deadline, worst case {need}s ({after})")+ return True+ result["reason"] = (+ f"only {left}s of the job's deadline are left {after} and this launcher "+ f"can take {need}s, so a push now could be killed during cleanup"+ )+ print(+ "::warning title=Stood down before pushing::"+ f"{after} there were {left}s of the job's deadline left and the launcher's "+ f"worst case is {need}s. Pushing now risks the runner being killed while "+ "kernels are still up, which would bill accelerator quota to their own "+ "ceiling. Nothing was pushed and nothing was learned about this change.",+ flush = True,+ )+ return False++ # BEFORE authentication and long before the first push: the one question+ # that has to be answered while the answer can still be acted on.+ #+ # The caller (the workflow job) is killed at a fixed time, and killing it+ # takes finish() -> release() with it: GitHub sends SIGINT to the step's+ # entry process and kills the process tree about ten seconds later+ # ("Canceling a workflow", docs.github.com), which is not a window in which+ # DELETE_ATTEMPTS retries against a slow Kaggle can finish. A kernel nobody+ # deletes bills accelerator quota to its own ceiling with nobody reading the+ # result, so the only safe moment to notice that the window has gone is+ # before anything is pushed.+ #+ # Nothing bounds the steps that run BEFORE this one -- a checkout, a pip+ # install off a slow index, the harness suite -- so "the job deadline sits+ # above the worst case with room for setup" is an assumption about their+ # duration rather than a property of the run. This measures what is left+ # instead, against the same worst case the job deadline and the reserved+ # quota are derived from.+ #+ # Standing down green is the answer the workflow's FAILURE SEMANTICS give+ # every infrastructure outcome: nothing was learned about the code, and no+ # quota was spent finding that out.+ if not window_fits("after the setup steps"):+ return finish()++ try:+ api = _api()+ except BaseException as exc: # noqa: BLE001+ if isinstance(exc, KeyboardInterrupt):+ raise+ result["reason"] = f"kaggle auth failed: {type(exc).__name__}"+ return finish()++ # 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 this+ # workflow passes, kaggle 2.2.4 introspects the token over HTTP -- and its+ # only bound is SOCKET_TIMEOUT_SEC. A window that fitted by less than that+ # is gone by the time the first kernel is pushed, and the guard would have+ # granted the push on an answer that had expired.+ if not window_fits("after authenticating"):+ return finish()++ # ANY unforeseen exception from here on still has to delete the kernels.+ # Everything below may have pushed one already, and a kernel this process+ # does not delete bills to its own ceiling with nobody reading it (Kaggle's+ # push-time timeout has been measured not to stop a wedged one, and nothing+ # in the workflow cleans up after this script). Letting an exception out+ # costs GPU quota, not just a report.+ try:+ # ONE deadline for the whole invocation, started BEFORE the first push.+ # A kernel bills from the moment Kaggle accepts it, so the clock that+ # decides when it is deleted must include the time spent pushing the+ # others. Started after the push loop instead, a throttled second push+ # (PUSH_ATTEMPTS attempts at the 600s subprocess ceiling plus backoffs,+ # about 45 minutes) landed on top of --max-wait for the kernel already+ # accepted: 135 minutes of billing against a ceiling that reads as 90.+ # Kaggle's push-time timeout does not cover that gap either (see this+ # file's docstring for the kernel that ignored it for two hours), so the+ # deletion deadline is the only bound there is.+ deadline = time.time() + args.max_wait++ # Push everything first. See this file's docstring: waiting between+ # pushes would serialise sessions Kaggle runs happily in parallel and put+ # an hour between the control leg and the canary leg.+ kernels: list[dict] = []+ # Published BEFORE the loop, as the same list object throughout.+ # release() reads result["kernels"], so a push that dies part-way (the+ # subprocess timeout above used to) must not leave the entries already+ # filed invisible to the cleanup.+ result["kernels"] = kernels+ for notebook in args.notebook:+ _log(f"pushing {notebook} (kernel ceiling {args.kernel_timeout_sec}s)")+ entry = {+ "notebook": notebook,+ "slug": None,+ # Every slug filed, accepted or not: a push that reported an+ # error may still have landed, and this is the only record of+ # what to reconcile against the account afterwards.+ #+ # Published EMPTY, before the push, and filled by push() as it+ # files each slug. Reading the returned list instead meant the+ # entry existed only if push() RETURNED: an exception it does+ # not handle (a decode error on a malformed response, an OSError+ # from the runner) unwound past this line, so release() found no+ # entry for this notebook and the kernel Kaggle may have just+ # accepted was left billing. The per-notebook granularity below+ # was already fixed for the same reason; this is the same bug one+ # level down, and the list being the caller's own object is what+ # closes it for every raise rather than for the ones foreseen.+ "attempted": [],+ "state": None,+ "push_error": None,+ }+ kernels.append(entry)+ pushed = push(+ Path(notebook),+ args.user,+ args.kernel_timeout_sec,+ attempted = entry["attempted"],+ )+ entry["slug"] = pushed.get("slug")+ entry["push_error"] = (+ None if pushed["ok"] else f"{pushed['reason']}: {pushed.get('detail', '')}"+ )+ if pushed["ok"]:+ _log(f"pushed as {pushed['slug']}")+ else:+ _log(f"push failed for {notebook}: {entry['push_error']}")++ live = [k for k in kernels if k["slug"]]+ if not live:+ result["reason"] = "; ".join(k["push_error"] for k in kernels if k["push_error"])+ return finish()+ # Kept for the summary and for anything reading this file's previous+ # single-kernel shape.+ result["slug"] = live[0]["slug"]++ # The deadline above is shared, not one per kernel: they run+ # concurrently, so consuming the ceiling per kernel would let a+ # two-kernel run wait twice its own stated bound.+ for entry in live:+ remaining = max(0, int(deadline - time.time()))+ entry["state"] = wait(api, entry["slug"], args.poll_every, remaining)+ _log(f"{entry['slug']} terminal state: {entry['state']}")+ result["kernel_state"] = ",".join(k["state"] or "?" for k in live)++ # ONE budget for the whole phase, shared by every kernel and started+ # here, for the same reason the polling deadline is shared: the kernels+ # are still billing and release() has not run yet. Per kernel it would+ # scale with the kernel count, which is what the job deadline could not+ # then be derived from. See EVIDENCE_BUDGET_SEC.+ evidence_deadline = time.time() + EVIDENCE_BUDGET_SEC+ for entry in live:+ # One directory per kernel: Kaggle names the executed notebooks+ # after the payloads, so two kernels of a run would otherwise+ # overwrite each other's kernel.log.+ try:+ entry["evidence"] = fetch_evidence(+ entry["slug"],+ outdir / entry["slug"].rsplit("/", 1)[-1],+ deadline = evidence_deadline,+ )+ _log(f"collected {entry['slug']}: {entry['evidence']}")+ except Exception as exc: # noqa: BLE001+ entry["evidence"] = None+ entry["collect_error"] = type(exc).__name__+ _log(f"could not collect {entry['slug']}: {type(exc).__name__}")++ reports = extract_reports(outdir)+ result["reports"] = reports+ _log(f"extracted {len(reports)} payload report(s) of {args.expect} expected")++ if not reports:+ result["reason"] = (+ f"kernel(s) ended {result['kernel_state']} but produced no payload "+ f"report; nothing was learned about the code under test"+ )+ return finish()++ # A kernel that ended badly but still reported is worth reading: the+ # payload deliberately does not propagate a nonzero exit, so ERROR here+ # usually means the SESSION died (timeout, box OOM, Kaggle side), which+ # is infra unless a report says otherwise.+ failing = [r for r in reports if not r.get("passed")]+ if failing:+ result["verdict"] = "fail"+ result["reason"] = (+ f"{len(failing)} of {len(reports)} payload(s) failed their " f"assertions"+ )+ elif len(reports) < args.expect:+ result["verdict"] = "partial"+ result["reason"] = (+ f"only {len(reports)} of {args.expect} payload(s) reported back "+ f"(kernel state {result['kernel_state']}); the ones that did, "+ f"passed"+ )+ else:+ result["verdict"] = "pass"+ result["reason"] = f"all {len(reports)} payload(s) passed"++ # The kernels are released by finish(), on this path and on every other.+ return finish()+ except BaseException as exc: # noqa: BLE001+ # An abort is infra by this file's contract: nothing was learned about+ # the code under test, so it must not colour the pull request red.+ # finish() deletes every slug filed so far and still writes+ # launch_result.json, which the summary and the artifact read.+ result["verdict"] = "infra"+ result["reason"] = (+ f"the launcher aborted: {type(exc).__name__}: {str(exc)[:300]}. "+ f"Every kernel it had pushed was deleted on the way out"+ )+ _log(result["reason"])+ code = finish()+ if isinstance(exc, (KeyboardInterrupt, SystemExit)):+ raise+ return code+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/.github/scripts/kaggle_t4_ci/legs.py b/.github/scripts/kaggle_t4_ci/legs.pynew file mode 100644index 00000000000..938777a9189--- /dev/null+++ b/.github/scripts/kaggle_t4_ci/legs.py@@ -0,0 +1,490 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""The payloads this CI can run, and what each one is FOR.++A Kaggle session is 2xT4 and the account allows 2 concurrent batch kernels, so+the ceiling is four payloads at once, and this is the registry of what those+four are. Each entry is a *leg*: an install recipe, a script and its arguments.+`build_kernel.py` turns a list of legs into kernel notebooks; nothing else here+knows what a leg contains.++**control** and **canary** are a matched pair and the core of the design: the+SAME payload, seed, dataset and step count on the same card, differing only in+the transformers/trl/peft/accelerate/bitsandbytes versions installed. Control+pins them (tests/kaggle/t4_smoke/pins/control.txt); canary takes the newest+release of each that Unsloth's declared constraints allow. Either leg failing+alone says something specific:++* canary red, control green -> a library RELEASE broke Unsloth, and the+ canary's report names every resolved version, so the bisect is a diff of two+ reports rather than an investigation.+* both red -> not a version bump: the base image, the model download, the+ Kaggle side, or Unsloth's own code.+* control red, canary green -> the pins no longer resolve, a maintenance signal+ for the pin file rather than a regression.++All three readings break at once if the legs differ in anything but versions,+which is why `--smoke-args` and the reference are shared rather than per leg.++**gptoss** covers `torch.compile` and the forced-float32 path: gpt-oss is in+Unsloth's FORCE_FLOAT32 list precisely because this card has no bf16, and+nothing else in CI exercises it. **grpo** covers vLLM, which+`fast_inference=True` puts on the same 16GB card as the training loop, and+whose sm_75 support is a version-by-version question.++To add a leg, append an entry and name it in a `KERNELS` kernel. The tests in+tests/kaggle/test_t4_smoke_harness.py build every leg and parse every generated+cell, so a leg that cannot produce valid Python never reaches Kaggle.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from pathlib import Path++# Placeholders substituted at build time from --unsloth-ref / --zoo-ref.+ZOO = "unsloth_zoo @ git+https://github.com/unslothai/unsloth-zoo@{zoo_ref}"+UNSLOTH = "unsloth @ git+https://github.com/unslothai/unsloth@{unsloth_ref}"++# Expands to a pin file's contents, one requirement per argument. Expanded at+# BUILD time, not read on the kernel, so the generated notebook states the+# versions it will install and the tests can read them without executing it.+PINS = "@PINS:{file}"++# What the canary upgrades. Named explicitly rather than "--upgrade+# everything", which would move torch and the CUDA stack too: a leg that+# changes ten things at once cannot attribute a failure to any of them.+CANARY_UPGRADES = ("transformers", "trl", "peft", "accelerate", "bitsandbytes")+++@dataclass(frozen = True)+class Leg:+ """One payload: what to install, what to run, and what it is for."""++ name: str+ summary: str+ # pip argument groups, run in order. Each group is one `pip install`.+ install: tuple[tuple[str, ...], ...]+ entry: str+ args: tuple[str, ...] = ()+ # Files copied verbatim from the payload directory into the notebook.+ files: tuple[str, ...] = ()+ # Modules the fail-fast probe imports before spending the session.+ imports: tuple[str, ...] = (+ "torch",+ "transformers",+ "trl",+ "peft",+ "datasets",+ "bitsandbytes",+ "unsloth",+ "unsloth_zoo",+ )+ # Filename under <payload-dir>/references to band-check against, if any.+ reference: str = ""+ # Extra environment for the child process.+ env: dict = field(default_factory = dict)+ # Does this leg's virtualenv see the Kaggle image's site-packages?+ #+ # True by default, which is what makes the control leg honest: it runs+ # against the image's torch, the situation a notebook user is in, and+ # installs only what the image lacks.+ #+ # False is for a leg that REPLACES torch, and it is measured rather than+ # preferred. `vllm==0.11.2` pins `torch==2.9.0`, downgrading the image's+ # 2.10.0, and with the image's site-packages visible pip treats torch's+ # pinned NVIDIA runtime packages as satisfied by the 2.10 copies, giving a+ # torch that installs cleanly and cannot be imported. Two probe kernels+ # found two faces of it:+ #+ # libcusparseLt.so.0: cannot open shared object file+ # libtorch_cuda.so: undefined symbol: ncclCommWindowRegister+ #+ # Naming the packages fixes them one at a time, and the list has no reason+ # to be short. A venv that cannot see the image fixes the class: pip must+ # resolve the whole stack, so it resolves a consistent one, at the cost of+ # a download of a few minutes.+ system_site_packages: bool = True+++# Files every leg needs: the version recorder, which makes a red leg+# attributable to a version; the canary dataset; and the "did the optimizer+# apply anything" evidence, without which every payload here can pass on a run+# that trained nothing.+COMMON_FILES = ("versions.py", "canary_dataset.jsonl", "training_evidence.py")++# The install prefix shared by every leg. unsloth_zoo first and WITH deps, then+# unsloth on top, then bitsandbytes, which neither pulls and the image does not+# carry, and without which `import unsloth` raises.+#+# UNSLOTH RESOLVES ITS DEPENDENCIES, and used to carry --no-deps so the overlay+# could not walk the set zoo had just resolved. That made the one file this+# workflow watches for packaging changes -- pyproject.toml is in its trigger+# paths -- the one thing it could not test: pip enforces the requirements of+# packages IN a resolution (see the frontier leg), so with the tested+# distribution outside every resolution, a dependency it adds is never+# installed, one it tightens is never checked against what is here, and the+# import probe still passes whenever the dependency is reached by a delayed+# code path. `pip install unsloth` is what a user runs, and this is now the+# same call.+#+# The --no-deps concern is answered by what unsloth actually declares: typer,+# rich, pydantic, pyyaml, nest-asyncio, structlog and click, none of which zoo+# resolves and none of which any leg pins, so there is nothing here for pip to+# fight over. A pyproject that DOES name one of zoo's packages would move it,+# and that is the regression this exists to show rather than a side effect to+# suppress -- a user's install would move it too.+BASE_INSTALL = ((ZOO,), (UNSLOTH,), ("bitsandbytes",))++# The distribution under test, read off the requirement above rather than+# restated: the verify cell asks pip whether THIS distribution's declared+# requirements are satisfied, and a name that drifted from the one actually+# installed would check nothing and say so quietly.+PACKAGE_UNDER_TEST = UNSLOTH.split("@", 1)[0].strip()++SMOKE_FILES = COMMON_FILES + ("run_t4_smoke.py", "determinism.py")+++LEGS: dict[str, Leg] = {+ "control": Leg(+ name = "control",+ summary = "tiny SFT determinism run, pinned library set",+ # Pins go in LAST, as their own resolution step, so they beat what the+ # preceding groups resolved; first, zoo's dependency set would quietly+ # walk them forward again.+ install = BASE_INSTALL + ((PINS.format(file = "control.txt"),),),+ entry = "run_t4_smoke.py",+ files = SMOKE_FILES + ("pins/control.txt",),+ reference = "t4_qwen2.5-0.5b.json",+ args = ("--pins", "@ROOT/pins/control.txt"),+ ),+ "canary": Leg(+ name = "canary",+ summary = "the same SFT run on the newest permitted library set",+ # One resolution with the zoo requirement present, so pip picks the+ # newest release of each that zoo's constraints allow. A separate+ # upgrade call would let pip install a version zoo forbids and merely+ # warn, measuring an environment Unsloth never claimed to support.+ install = BASE_INSTALL + ((("--upgrade", ZOO) + CANARY_UPGRADES),),+ entry = "run_t4_smoke.py",+ files = SMOKE_FILES,+ # No reference: two library sets do not produce the same fp16+ # trajectory, so band-checking against the control's committed trace+ # would fail on drift rather than on a regression. The canary asserts+ # the version-independent things instead -- the canary string, that the+ # optimizer applied updates, that two fresh processes agreed bitwise+ # WITH EACH OTHER, and that nothing raised. See+ # tests/kaggle/t4_smoke/references/README.md.+ reference = "",+ ),+ "frontier": Leg(+ name = "frontier",+ summary = "the same SFT run on the newest transformers and trl on PyPI",+ # WHY THIS EXISTS, given the canary already says "newest": the canary+ # installs the newest set zoo's metadata ALLOWS, and that ceiling is+ # low. unsloth_zoo/pyproject.toml pins+ #+ # transformers >=4.51.3,...,<=5.5.0+ # trl >=0.18.2,!=0.19.0,<=0.24.0+ #+ # so on 2026-08-11 the canary resolved transformers 5.5.0 against a+ # PyPI latest of 5.15.0, and trl 0.24.0 against a latest of 1.9.2, a+ # whole major version. It moved peft 0.19.1 -> 0.20.0 and accelerate+ # 1.13.0 -> 1.14.0 (both latest, both uncapped), which made the leg look+ # like it was working; two of the five never moved, and they are the two+ # that break most. So with only the canary this CI CANNOT detect a+ # transformers 5.6+ or trl 1.x regression, having never installed one,+ # and the cap is raised only after someone checks -- this is what+ # checks.+ #+ # WITH dependencies, NOT --no-deps. `--no-deps transformers trl` plus a+ # blanket `--upgrade tokenizers` did reach transformers 5.15.0 and trl+ # 1.9.2 (kernel unsloth-t4-ci-bd0c49e5, the first time this CI installed+ # either) and then died before running anything:+ #+ # tokenizers<=0.23.0,>=0.22.0 is required, but found tokenizers==0.23.1+ # safetensors>=0.8.0 is required, but found safetensors==0.7.0+ #+ # An unbounded upgrade overshoots transformers' declared ceiling and+ # --no-deps leaves nothing to repair it. Resolving the deps fixes both,+ # because pip enforces only the requirements of packages IN the+ # resolution: unsloth_zoo is merely installed, so its `<=5.5.0` is a+ # warning rather than a ceiling. Dry run against an environment with zoo+ # installed: "Would install datasets-5.0.1 huggingface_hub-1.27.0+ # transformers-5.15.0 trl-1.9.2". So this leg moves whatever+ # transformers and trl now require, which is the honest scope of taking+ # the new version.+ #+ # I expected this leg to go red. IT DOES NOT. Kernel from+ # temp/frontier_kernel2.ipynb on a real T4: transformers 5.15.0, trl+ # 1.9.2, datasets 5.0.1, ten steps, canary emitted, two fresh processes+ # agreeing BITWISE (max_abs_diff 0.0 on both loss and grad_norm).+ # Unsloth trains and generates correctly a whole trl major above what+ # zoo's metadata permits. A red here would be a to-do about the next+ # version bump rather than a broken main, and should be wired so a+ # reader can tell those apart.+ #+ # WHAT IT DOES NOT CATCH, worth a reader's eye: the loss trajectory is+ # not the control's.+ #+ # control tf 5.5.0 trl 0.24.0: 10.3222 10.4956 9.9563 10.3892 5.0523 ...+ # frontier tf 5.15.0 trl 1.9.2 : 6.4367 6.6086 5.9956 3.6721 2.0265 ...+ #+ # Step 1 is computed before any update, on identical initial weights,+ # data and seed, so 10.32 against 6.44 is not optimisation drift: the+ # loss FUNCTION differs, in masking or normalisation. Both converge, so+ # neither is obviously wrong, and this leg has no reference band (see+ # the canary), which is why it passes without noticing. Settling which+ # objective is intended is separate work.+ install = BASE_INSTALL + ((("--upgrade", "transformers", "trl")),),+ entry = "run_t4_smoke.py",+ files = SMOKE_FILES,+ # Same reasoning as the canary, more so: this set is further still from+ # the committed trace.+ reference = "",+ ),+ "gptoss": Leg(+ name = "gptoss",+ summary = "gpt-oss-20b LoRA: torch.compile and the float32 path",+ # The base install and nothing else, specifically WITHOUT the+ # `triton_kernels` git dependency the gpt-oss notebook installs. That+ # omission is measured: two probe kernels on 2026-08-11 ran this leg on+ # a T4, one with triton_kernels and torchao (the notebook's own install+ # cell) and one with neither, and produced the SAME three losses to the+ # last bit (5.76492166519165, 4.781009674072266, 4.027626991271973), the+ # same peak memory (12.78 GB) and the same compile counters (32 graphs,+ # 779 calls, 2 breaks).+ #+ # They agree because `load_in_4bit=True` never reaches MXFP4: Unsloth's+ # FLOAT_TO_INT_MAPPER redirects `unsloth/gpt-oss-20b` to the NF4+ # `unsloth/gpt-oss-20b-unsloth-bnb-4bit`, and MXFP4 has no backward pass+ # to reach. triton_kernels would be a pinned git checkout of a+ # third-party repo on every run for no observable effect.+ install = BASE_INSTALL,+ entry = "run_gptoss_t4.py",+ files = COMMON_FILES + ("run_gptoss_t4.py",),+ args = ("--max-steps", "3", "--max-seq-length", "1024"),+ ),+ # NOT WIRED, for a smaller reason than it used to be. See UNWIRED below:+ # the install that killed three probe sessions is re-solved, and what+ # remains is a runtime question needing one session on a real T4.+ "grpo": Leg(+ name = "grpo",+ summary = "Qwen3-4B GRPO through a vLLM engine on the same card",+ # vLLM FIRST and alone: it pins torch, and resolving it after unsloth+ # walks torch underneath an already installed stack.+ #+ # THE VERSION MATCHES THE IMAGE, IT IS NOT MERELY OLD. Kaggle ships+ # torch 2.10.0+cu128, and vLLM's torch pin by release is+ #+ # 0.11.2 .. 0.16.0 torch==2.9.0 / 2.9.1+ # 0.17.0 .. 0.19.1 torch==2.10.0 <- the whole window+ # 0.20.0 .. 0.26.0 torch==2.11.0+ # 0.27.0 .. torch==2.13.0+ #+ # Every other choice REPLACES the image's torch, which is what all three+ # probe sessions died of: the image's NVIDIA runtime packages belong to+ # 2.10 and pip treats them as satisfying the new torch's pins. 0.19.1 is+ # the newest release needing no replacement, so the install is ordinary+ # and the leg keeps `system_site_packages`.+ #+ # No xformers: its vLLM attention backend was deleted in 0.12.0, so it+ # would install a package nothing selects. sm_75 has no FlashAttention+ # and no FlashInfer, and the ladder in vllm/platforms/cuda.py falls+ # through those to TRITON_ATTN, pinned below rather than left to a probe+ # order that moves between releases. sm_75 is still in+ # CUDA_SUPPORTED_ARCHS at v0.19.1, and fp16 is supported below+ # capability 8.0.+ install = (("vllm==0.19.1",),) + BASE_INSTALL,+ entry = "run_grpo_t4.py",+ files = COMMON_FILES + ("run_grpo_t4.py",),+ imports = (+ "torch",+ "transformers",+ "trl",+ "peft",+ "datasets",+ "bitsandbytes",+ "vllm",+ "unsloth",+ "unsloth_zoo",+ ),+ # ALL FIVE ARE LOAD-BEARING ON A 14.56GB CARD, and are the values that+ # passed rather than the ones that look reasonable. Two probes with the+ # notebook's own settings (seq 2048, 4 generations, rank 32, utilization+ # 0.9) died in the BACKWARD at+ # unsloth_zoo/gradient_checkpointing.py:1013, peaking at 15.97GB in+ # 16-bit and 19.25GB in 4-bit.+ #+ # 4-bit is not the lever it looks like -- it peaked HIGHER than 16-bit,+ # since quantizing weights does nothing for activations while+ # utilization 0.9 still hands vLLM ~13GB up front. UNSLOTH_VLLM_STANDBY+ # returns the weights during training but not the KV cache reservation,+ # so utilization is what decides whether a backward has anywhere to run.+ #+ # Measured on kernel unsloth-t4-ci-53efcc4e: peak 13.60GB allocated of+ # 14.56GB, three steps in 192s.+ args = (+ "--max-steps",+ "3",+ "--load-in-4bit",+ "--gpu-memory-utilization",+ "0.5",+ "--max-seq-length",+ "1024",+ "--num-generations",+ "2",+ "--lora-rank",+ "16",+ ),+ env = {+ "UNSLOTH_VLLM_STANDBY": "1",+ # See the install comment. Named rather than probed so a release+ # reordering the ladder turns this leg red instead of silently+ # selecting something else.+ "VLLM_ATTENTION_BACKEND": "TRITON_ATTN",+ # Kaggle cannot link what flashinfer JIT-compiles. On kernel+ # unsloth-t4-ci-e2d9ce9b, vLLM 0.19.1 reached engine construction on+ # a real T4, flashinfer 0.6.6 compiled all three sampling .cu files+ # CLEANLY for `-gencode=arch=compute_75,code=sm_75`, and the link+ # died on+ #+ # /usr/bin/ld: cannot find -lcuda+ #+ # `-L/usr/local/cuda/lib64/stubs` is on the command line, so the+ # driver stub `libcuda.so` is simply absent from this image; only+ # the runtime `libcuda.so.1` is there. That is not an sm_75 problem+ # and is not fixable from here. So do not JIT: the sampler has a+ # native path, and skipping the build saves a four-file nvcc compile+ # in a session billed by wall clock.+ "VLLM_USE_FLASHINFER_SAMPLER": "0",+ },+ # Now true, which is the point of the version choice above: this leg no+ # longer replaces torch, so it shares the image's view instead of+ # resolving a whole CUDA stack from scratch. Probe 3 spent about an hour+ # of quota doing that and never got past venv creation.+ system_site_packages = True,+ ),+}+++# GPUs in a Kaggle session, so legs one kernel can carry. A third leg would not+# fail; it would share a card and quietly change what both of them measure.+MAX_LEGS_PER_KERNEL = 2++# Legs defined here and deliberately NOT run, with the reason. A leg is unwired+# rather than deleted when the payload is right and the environment is not, so+# the next person to try owes nothing but a working install. Every entry must+# say what was measured.+UNWIRED: dict[str, str] = {+ # A leg belongs here only while a specific unanswered question about it+ # would be answered by a session. "Not tried yet" is not that.+ "grpo": (+ "vLLM standby sleep hits an illegal memory access on Turing, and it is "+ "INTERMITTENT. Three sessions on a real Tesla T4, identical to the "+ "flag and identical in every recorded version (torch 2.10.0+cu128, "+ "transformers 5.5.0, trl 0.24.0, peft 0.19.1, vllm 0.19.1, unsloth "+ "2026.8.15, zoo 2026.8.10) and at the same 13.8GB/13.6GB peak of "+ "14.56GB: unsloth-t4-ci-53efcc4e PASSED (engine_built true, reward_std "+ "0.707 and grad_norm 0.772 at step 2, three steps in 192s), then "+ "unsloth-t4-ci-70a2f4eb and unsloth-t4-ci-c98f14be both FAILED with "+ "engine_built false and\n"+ " unsloth_zoo/vllm_utils.py:601 sleep() -> torch.cuda.empty_cache()\n"+ " torch.AcceleratorError: CUDA error: an illegal memory access was "+ "encountered\n"+ "UNSLOTH_VLLM_STANDBY=1 is set in all three. One pass in three is not "+ "a leg CI can spend a session on: it would go red for a reason no "+ "reader could act on.\n"+ "The --cuda-launch-blocking run is done, kernel unsloth-t4-ci-b1f23e34, "+ "and it did NOT localise the fault: with blocking on there was no "+ "illegal memory access at all. engine_built true, three steps, same "+ "13.8GB peak. A fault that disappears when the launches are "+ "serialised is a race, which is what the one-pass-in-three rate "+ "already suggested.\n"+ "It also exposed a SECOND problem, and the two are separate. That run "+ "failed on reward_std = [0.0, 0.0, 0.0] with grad_norm 0.0 at every "+ "step. The completions recorded in the report are coherent prose, not "+ "degenerate, so this is not the model collapsing -- it is two "+ "completions scoring identically. The leg runs num_generations = 2, "+ "shrunk to fit a 14.56GB card, and at two samples a tie on a coarse "+ "reward is ordinary rather than a bug. So the leg's own pass "+ "criterion is fragile at the size it has to be to fit.\n"+ "STILL UNKNOWN: where the race is (the standby wake/sleep cycle on "+ "sm_75 is the suspect, and UNSLOTH_VLLM_STANDBY=1 is set in all four "+ "sessions), and what pass criterion is honest at num_generations = 2."+ ),+}++# Which legs travel in which kernel, one entry per kernel, each running its legs+# one per T4 of its session.+#+# control and canary share a kernel so they run on the two cards of the SAME+# session: same image, same driver, same hour. Splitting them across sessions+# would put an uncontrolled variable between the only two legs whose comparison+# has to be clean.+#+# The second kernel's free T4 carries `frontier`, and the seat is literally+# free: a session bills its wall clock once, not per card, so testing the newest+# transformers and trl costs no quota. It went there rather than beside control+# and canary because those two must differ in nothing but versions within the+# zoo-permitted window, which frontier deliberately leaves.+#+# `grpo` held that seat before, and returns to it once the illegal memory access+# in UNWIRED is understood. It briefly had a third kernel of its own, on the+# reasoning that pairing with gpt-oss broke it: it failed paired and had passed+# alone. Running it ALONE again (unsloth-t4-ci-c98f14be) reproduced the paired+# failure exactly, same stack, same 13.8GB peak, same engine_built false, so the+# pairing was never the variable and one contrasting observation was not enough+# to blame a shared host. It stays unwired rather than re-paired, since a leg+# passing one session in three tells CI nothing either way.+KERNELS: tuple[tuple[str, ...], ...] = (+ ("control", "canary"),+ ("gptoss", "frontier"),+)+++def expand_install(+ leg: Leg, *, unsloth_ref: str, zoo_ref: str, payload_dir: Path+) -> list[list[str]]:+ """Resolve a leg's install groups into concrete pip argument lists."""+ groups: list[list[str]] = []+ for group in leg.install:+ expanded: list[str] = []+ for item in group:+ if item.startswith("@PINS:"):+ expanded.extend(_read_pins(payload_dir / "pins" / item[len("@PINS:") :]))+ continue+ expanded.append(item.format(unsloth_ref = unsloth_ref, zoo_ref = zoo_ref))+ if expanded:+ groups.append(expanded)+ return groups+++def _read_pins(path: Path) -> list[str]:+ if not path.exists():+ raise FileNotFoundError(f"leg names a pin file that is not there: {path}")+ out = []+ for line in path.read_text(encoding = "utf-8").splitlines():+ line = line.split("#", 1)[0].strip()+ if line:+ out.append(line)+ if not out:+ raise ValueError(+ f"pin file {path} names no versions at all, so the control leg would pin nothing"+ )+ return out+++def resolve(names) -> list[Leg]:+ """Legs by name, in the order given. Unknown names fail loudly here.++ At build time rather than on the kernel: a typo in a workflow input must+ cost a runner second, not a Kaggle session.+ """+ legs = []+ for name in names:+ if name not in LEGS:+ raise SystemExit(f"unknown leg {name!r}; known legs are {', '.join(sorted(LEGS))}")+ legs.append(LEGS[name])+ return legsdiff --git a/.github/scripts/kaggle_t4_ci/report.py b/.github/scripts/kaggle_t4_ci/report.pynew file mode 100644index 00000000000..6d5491d0e14--- /dev/null+++ b/.github/scripts/kaggle_t4_ci/report.py@@ -0,0 +1,405 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Turn collected Kaggle evidence into a job summary and an exit code.++The only place that decides whether the workflow goes red, on a deliberately+narrow line: red means the payload RAN on a T4 and disagreed with its+assertions. Everything else is a warning, because Kaggle is a free service with+a hard concurrency cap, a weekly quota and its own queue, any of which can stop+the test from producing a result; if those turned a PR red the check would be+noise within a week and ignored the one time it was right.++Exit codes:+ 0 passed, partially reported, or never ran+ 1 a payload ran and failed its assertions+"""++from __future__ import annotations++import argparse+import json+import os+from pathlib import Path+++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)+++def _fmt_metric(value) -> str:+ if value is None:+ return "-"+ if isinstance(value, float):+ # NaN is a real fp16 gradient-scaler outcome, not a missing value.+ if value != value:+ return "NaN (step skipped)"+ return f"{value:.6g}"+ return str(value)+++def resolved_versions(report: dict) -> dict:+ """The installed version of every watched package, whichever leg wrote it.++ The SFT payload nests it under ``environment.resolved`` because its+ environment block predates this and the committed reference carries that+ shape; gpt-oss and GRPO write ``versions_flat`` at the top level.+ """+ flat = report.get("versions_flat")+ if isinstance(flat, dict):+ return flat+ nested = (report.get("environment") or {}).get("resolved")+ return nested if isinstance(nested, dict) else {}+++def version_table(reports: list) -> list[str]:+ """Every leg's library set side by side, with what differs called out.++ The payoff of a pinned control beside a canary: when the canary is the only+ red leg, "which bump did it" is answered on the summary page, without+ downloading an artifact or reconstructing an install log.+ """+ columns = [(r.get("label", "?"), resolved_versions(r)) for r in reports]+ columns = [(label, versions) for label, versions in columns if versions]+ if len(columns) < 2:+ return []+ packages = sorted({p for _, versions in columns for p in versions})+ differing = [p for p in packages if len({str(versions.get(p)) for _, versions in columns}) > 1]+ lines = [+ "<details><summary>Resolved library versions per leg"+ + (f" ({len(differing)} differ)" if differing else " (identical across legs)")+ + "</summary>",+ "",+ ]+ lines.append("| package | " + " | ".join(l for l, _ in columns) + " |")+ lines.append("| --- |" + " --- |" * len(columns))+ for package in packages:+ cells = [str(versions.get(package) or "-") for _, versions in columns]+ name = f"**{package}**" if package in differing else package+ lines.append(f"| {name} | " + " | ".join(cells) + " |")+ lines += ["", "</details>", ""]+ if differing:+ lines += [f"Legs differ in: {', '.join(differing)}.", ""]+ return lines+++def render(report: dict) -> list[str]:+ lines = [+ f"#### payload `{report.get('label', '?')}` " f"model `{report.get('model', '?')}`",+ "",+ ]+ if report.get("probe"):+ lines += [+ "This payload ran in **probe mode**: everything is "+ "recorded and nothing is asserted, so `passed` says only "+ "that it reported back. Read `observed_failures`.",+ "",+ ]+ env = report.get("environment", {})+ if env:+ lines.append(+ f"GPU `{env.get('gpu_name', '?')}` ({env.get('gpu_capability', '?')}, "+ f"{env.get('gpu_total_gb', '?')} GB) - torch `{env.get('torch', '?')}` "+ f"- transformers `{env.get('transformers', '?')}` "+ f"- trl `{env.get('trl', '?')}` - unsloth `{env.get('unsloth', '?')}`"+ )+ lines.append("")++ config = report.get("config", {})+ if config:+ # max_steps is up front: it decides whether the committed reference+ # applies to this run at all.+ lines.append(+ f"Config: max_steps `{config.get('max_steps')}` - lr "+ f"`{config.get('learning_rate')}` - batch "+ f"`{config.get('batch_size')}` - init_loss_scale "+ f"`{config.get('init_loss_scale')}`"+ )+ scales = [r.get("loss_scale") for r in report.get("runs", []) if r.get("loss_scale")]+ if scales and not all(s.get("applied") for s in scales):+ lines.append(+ f"fp16 loss-scale pin did NOT apply: "+ f"`{scales[0].get('reason', 'unknown')}`. The run used the "+ f"framework default, so its first steps were spent on scaler "+ f"overflows."+ )+ lines.append("")++ lines += ["| step | loss | grad_norm |", "| --- | --- | --- |"]+ for entry in report.get("metrics", []):+ lines.append(+ f"| {entry.get('step')} | {_fmt_metric(entry.get('loss'))} "+ f"| {_fmt_metric(entry.get('grad_norm'))} |"+ )+ lines.append("")++ repro = report.get("reproducibility")+ if repro:+ if repro.get("identical"):+ lines.append("Reproducibility: two fresh processes agreed **bitwise** on every step.")+ else:+ lines.append(+ f"Reproducibility: **DIFFERED** from step "+ f"{repro.get('first_diff_step')} "+ f"(max abs {repro.get('max_abs_diff')})."+ )+ lines.append("")++ for run in report.get("runs", []):+ lines.append(+ f"Cycle {run.get('run_index')} generated: "+ f"`{run.get('generated', '')}` - canary "+ f"{'found' if run.get('canary_found') else '**MISSING**'}"+ )+ lines.append("")++ ref = report.get("reference_check")+ if ref:+ status = ref.get("status")+ if status == "ok":+ lines.append(+ f"Reference band: within tolerance (worst relative deviation "+ f"{ref.get('worst_rel')}), against a reference captured at "+ f"max_steps={ref.get('reference_max_steps')}."+ )+ elif status == "absent":+ lines.append(+ "Reference band: no committed reference for this "+ "configuration, so nothing was compared."+ )+ elif ref.get("note"):+ # A refusal, not a deviation: the deviations list is empty for+ # these, so printing it alone would read like a clean result.+ lines.append(f"Reference band: **{status}** - {ref['note']}")+ else:+ lines.append(f"Reference band: **{status}** - {ref.get('deviations')}")+ # What the band did NOT compare, up front rather than buried in the+ # evidence. A key the reference predates is skipped, not refused ("it+ # does not say" is not "it differs"), but an invisible skip reads as a+ # check that ran, and a pin can sit unchecked for months that way.+ unchecked = ref.get("config_unchecked")+ if unchecked:+ lines.append(+ "Not compared, absent from one side: "+ + ", ".join(f"`{key}`" for key in unchecked)+ + ". Recapture the reference (references/README.md) to bring "+ "them into the check."+ )+ lines.append("")++ pins = report.get("pins")+ if pins:+ lines.append(+ "Pins: "+ + (+ "held"+ if not pins.get("failures")+ else "**DID NOT HOLD** - " + "; ".join(pins["failures"])+ )+ + f" ({len(pins.get('requested', {}))} pinned)."+ )+ lines.append("")++ compiled = report.get("compile")+ if compiled:+ if not compiled.get("available"):+ lines.append(f"torch.compile: **unreadable** - " f"{compiled.get('error')}")+ else:+ lines.append(+ f"torch.compile: {compiled.get('unique_graphs')} unique "+ f"graph(s), {compiled.get('calls_captured')} calls captured, "+ f"{compiled.get('graph_breaks_total')} graph break(s)."+ + (+ ""+ if compiled.get("unique_graphs")+ else " **Zero graphs means the run was entirely eager.**"+ )+ )+ lines.append("")++ memory = report.get("memory_peak") or report.get("memory_after_train")+ if memory:+ lines.append(+ f"Peak VRAM: {memory.get('peak_reserved_gb')} GB reserved / "+ f"{memory.get('peak_allocated_gb')} GB allocated of "+ f"{memory.get('total_gb')} GB."+ )+ lines.append("")++ history = report.get("log_history")+ if history:+ # GRPO: loss is ~0 by construction at num_iterations=1 and beta=0, so+ # reward and reward_std are what is worth showing.+ lines += ["| step | reward | reward_std |", "| --- | --- | --- |"]+ for entry in history:+ if entry.get("reward") is None:+ continue+ lines.append(+ f"| {entry.get('step')} | "+ f"{_fmt_metric(entry.get('reward'))} | "+ f"{_fmt_metric(entry.get('reward_std'))} |"+ )+ lines.append("")+ sample = [t for group in (report.get("completions") or []) for t in group if t.strip()]+ if sample:+ lines.append(f"First completion: `{sample[0][:200]}`")+ lines.append("")++ if report.get("observed_failures") and not report.get("failures"):+ lines.append("Observed (not asserted, this is a probe):")+ lines += [f"- {f}" for f in report["observed_failures"]]+ lines.append("")++ if report.get("failures"):+ lines.append("Failures:")+ lines += [f"- {f}" for f in report["failures"]]+ lines.append("")+ return lines+++SENTINELS = (+ "KAGGLE_T4_CI_DRIVER",+ "KAGGLE_T4_CI_PAYLOAD",+ "Error",+ "error:",+ "Traceback",+ "SystemExit",+ "papermill.exceptions",+)+++def kernel_log_text(evidence: Path) -> str:+ """The kernel log as flat text, whichever shape Kaggle returned it in.++ Kaggle's `kernels/output` returns the log as a JSON array of+ ``{stream_name, time, data}`` records, not as text, so reading the file+ directly shows a wall of JSON with one word of message per line.+ """+ chunks = []+ # rglob: a run is several kernels, each collecting into its own directory,+ # so there is no single kernel.log any more.+ for path in sorted(evidence.rglob("kernel.log")):+ raw = path.read_text(encoding = "utf-8", errors = "replace")+ try:+ records = json.loads(raw)+ except json.JSONDecodeError:+ chunks.append(raw)+ continue+ if not isinstance(records, list):+ chunks.append(raw)+ continue+ chunks.append("".join(r.get("data", "") for r in records if isinstance(r, dict)))+ return "".join(chunks)+++def diagnostic_lines(evidence: Path, limit: int = 40) -> list[str]:+ """The lines of the kernel log worth putting in front of a human.++ A kernel that finished but reported nothing is the hardest outcome to read:+ no metrics to show, cause buried in an artifact nobody downloads. Both real+ instances so far, a dependency probe that mis-ordered its imports and a+ generated cell with a syntax error, were one grep away in this log.+ """+ text = kernel_log_text(evidence)+ if not text:+ return []+ hits = [line.rstrip() for line in text.splitlines() if any(s in line for s in SENTINELS)]+ return hits[-limit:]+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--evidence", required = True)+ ap.add_argument("--expect", type = int, default = 2)+ args = ap.parse_args()++ evidence = Path(args.evidence)+ result_file = evidence / "launch_result.json"+ if not result_file.exists():+ _summary(+ "### Kaggle T4 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", "Kaggle T4 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": "### Kaggle T4 smoke: PASS",+ "fail": "### Kaggle T4 smoke: FAIL",+ "partial": "### Kaggle T4 smoke: PARTIAL",+ "infra": "### Kaggle T4 smoke: NOT RUN",+ }.get(verdict, "### Kaggle T4 smoke")++ lines = [header, "", reason, ""]+ for kernel in result.get("kernels") or []:+ if kernel.get("slug"):+ lines.append(+ f"Kernel: `{kernel['slug']}` (private), terminal " f"state `{kernel.get('state')}`."+ )+ else:+ lines.append(+ f"Kernel from `{kernel.get('notebook')}` was never "+ f"pushed: {kernel.get('push_error')}"+ )+ if not result.get("kernels") and result.get("slug"):+ lines.append(+ f"Kernel: `{result['slug']}` (private), terminal state "+ f"`{result.get('kernel_state')}`."+ )+ lines.append("")++ lines += version_table(reports)+ for report in reports:+ lines += render(report)++ if verdict in ("infra", "partial") and len(reports) < args.expect:+ hits = diagnostic_lines(evidence)+ if hits:+ lines += (+ ["<details><summary>Kernel log, filtered</summary>", "", "```"]+ + hits+ + ["```", "", "</details>", ""]+ )++ if verdict == "infra":+ lines += [+ "This is not a code failure. The test 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-t4-ci` label or a manual dispatch to "+ "force another attempt.",+ ]++ _summary("\n".join(lines))++ if verdict == "fail":+ _notice("error", "Kaggle T4 smoke failed", reason)+ return 1+ if verdict == "partial":+ _notice("warning", "Kaggle T4 smoke partially reported", reason)+ return 0+ if verdict == "infra":+ _notice("warning", "Kaggle T4 smoke did not run", reason)+ return 0+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/.github/workflows/kaggle-t4-notebook-ci.yml b/.github/workflows/kaggle-t4-notebook-ci.ymlnew file mode 100644index 00000000000..f0521ff6ef1--- /dev/null+++ b/.github/workflows/kaggle-t4-notebook-ci.yml@@ -0,0 +1,855 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.+#+# Notebook regression tests on real Kaggle T4 hardware.+#+# Why T4 rather than a GitHub runner: every other GPU-adjacent job here has no+# GPU or one nobody's free Colab session has. T4 is the card the notebooks are+# written against (sm_75, no bf16, no flash-attention 2, 16GB), so a regression+# that only appears there is invisible to the rest of CI. Kaggle gives us that+# card free, two per session, two sessions at once: four payloads.+#+# ---------------------------------------------------------------------+# WHAT RUNS: four legs, two kernels, one leg per T4. The leg-to-kernel plan+# lives in .github/scripts/kaggle_t4_ci/legs.py and is not restated here.+# ---------------------------------------------------------------------+#+# kernel 1 control tiny Qwen2.5-0.5B SFT, PINNED library set+# canary the same run on the newest permitted library set+# kernel 2 gptoss gpt-oss-20b LoRA: torch.compile and float32 on sm_75+# frontier the same SFT run on the newest transformers and trl+# on PyPI, above the ceiling zoo's metadata permits+#+# A fifth leg, `grpo` (Qwen3-4B through a vLLM engine), is written and NOT+# wired: its vLLM standby path hits an intermittent illegal memory access on+# Turing, one session in three. The measurements are on legs.UNWIRED. The second+# kernel's second T4 costs nothing, a session billing its wall clock once rather+# than per card, which is why frontier sits there rather than waiting for a+# kernel of its own.+#+# **control and canary are one instrument, not two tests.** Same payload, seed,+# dataset and step count on the two cards of one session, differing ONLY in the+# installed transformers, trl, peft, accelerate and bitsandbytes. So:+#+# canary red, control green -> a library RELEASE broke Unsloth, and the+# job summary already names the versions that differ between the two+# legs. This is the signal the whole workflow is built around.+# both red -> not a version bump. The base image, the+# model download, Kaggle, or Unsloth's own code.+# control red, canary green -> the pins stopped resolving. A maintenance+# signal for tests/kaggle/t4_smoke/pins/control.txt, not a regression.+#+# Determinism and the committed reference band apply to the CONTROL leg only.+# Bitwise agreement across library versions is not achievable and is not+# claimed, so the canary asserts the version-independent things: the canary+# string, that the optimizer applied updates, that two fresh processes agreed+# bitwise WITH EACH OTHER, and that nothing raised.+#+# The band check compares against a reference captured at ONE step count and+# fails rather than comparing across counts, the alternative being a green check+# against a curve the run has nothing to do with. The committed reference is a+# 10-step trace and max_steps is 10, so it applies as committed.+#+# 10 steps is not arbitrary and shortening it is not free. With no bf16 this+# runs fp16 with a dynamic GradScaler that starts at 65536, halves on each+# overflow and skips the step it overflowed on, and the reference records+# grad_norm NaN at steps 1, 2 and 3 and a finite value from step 4. So a 3-step+# run applies ZERO optimizer updates, never learns the canary and asserts+# nothing about training; anything under about five steps needs+# --init-loss-scale AND a reference recaptured with it. A dispatch that asks for+# one is stood down before the kernels are pushed rather than reported red after+# they are paid for: check_steps.py measures that floor from this reference and+# the payload's own optimisation checks.+#+# ---------------------------------------------------------------------+# 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; 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:+#+# 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+# HARD ceiling rather than an average, whatever the sampling rate does.+# 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+# ALLOWED_IN_FLIGHT_FOREIGN_KERNELS in gate.py.+#+# ARITHMETIC, recomputed from live numbers on 2026-08-11: measured on+# unslothai/unsloth over the preceding 7 days or on real Kaggle sessions, none+# of it estimated.+#+# commits on main 479+# ... touching the paths filter below 45 (9.4%)+# measured BEFORE pyproject.toml joined the filter. One rarely touched+# file, so the eligible counts below move a little rather than a lot, and+# the 20h reserve holds either way.+# pull requests opened 567+# ... touching the paths filter 7.5% (9 of a 120 sample)+# = pull requests that can trigger this 43+# commits carried by those, measured 4.33 each+#+# ELIGIBLE INVOCATIONS PER WEEK+# push to main 45+# pull_request opened 43+# pull_request synchronize 0 .. 143 (one per push after+# the first; bounded+# above by the+# commit count)+# TOTAL 88 .. 231+#+# COST OF ONE INVOCATION. Two kernels, each billing its wall clock ONCE rather+# than per card at almost exactly 1 GPU-h per hour, so the second T4 of each+# is free. Measured on kernels 066cd463 (control + canary, both green, 263s of+# payload) and 8161ceb9 / 7ab727f1 (gpt-oss, 375s of payload):+# kernel 1 (control + canary) 0.10 h+# kernel 2 (gptoss) 0.13 h+# 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+# allowance before the quota floor intervenes:+# 231 x r x 0.25 h = 30 h -> r = 0.52, set to 40% (--percent 40)+#+# 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.+#+# 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+# the allowance, so that change comes with a recomputation of this block+# rather than one line in legs.KERNELS.+#+# WORST CASE, one invocation wedging its way through every retry and every+# 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+# ceiling.+#+# ---------------------------------------------------------------------+# FAILURE SEMANTICS+# ---------------------------------------------------------------------+# Red for two things and nothing else:+#+# 1. a payload ran on a T4 and its assertions failed.+# 2. the account's WEEKLY accelerator quota is exhausted. The `gate` job says+# so in one API call, before the concurrency survey and before any kernel+# is pushed, and its message says the hours come back on Kaggle's refresh+# and the reader can ignore the failure. Nothing downstream swallows it:+# the Decide step has no continue-on-error, and t4-smoke needs this job.+#+# Every other outcome (not sampled, wrong label, no credentials, quota+# UNREADABLE, account busy, push throttled, kernel died on Kaggle's side,+# evidence would not download) is a SKIP or a warning and exits 0, nothing+# having been learned about the code. The recheck inside t4-smoke passes+# --soft-fail, so a run already approved that loses the hours while queueing for+# the account slot stands down green rather than going red for a second time.+#+# 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 artifact, and+# never travels to the Kaggle kernel, which receives the notebook and nothing+# else. Fork pull requests do not receive the secret, and the gate skips cleanly+# when it is absent.+#+# WHERE THE TRUST BOUNDARY ACTUALLY IS, since it is easy to draw it in the wrong+# place: a SAME-REPOSITORY pull request does receive the secret, and on+# `pull_request` GitHub runs the workflow file from the merge ref, so the YAML in+# a pull request is the YAML that executes. Running the gate and launcher from a+# trusted base-branch copy would protect nothing, since whoever can edit gate.py+# in a pull request can edit this file too.+#+# Nor is it a hole this workflow opens. Per GitHub's hardening guidance, "Any+# user with write access to your repository has read access to all secrets+# configured in your repository": a push to any branch runs a workflow with the+# repository's secrets, no pull request needed. The boundary is repository write+# access, the same for every secret here.+#+# If that blast radius is ever judged too wide for this token, the mechanism is+# an ENVIRONMENT secret with required reviewers (plus deleting the+# repository-level copy, or the environment buys nothing), not a trusted copy of+# a script. The cost is a human approval on every sampled run, which is why it+# is not done here.++name: Kaggle T4 Notebook CI++on:+ pull_request:+ # `labeled` is NOT a GitHub default (those are opened, synchronize and+ # reopened), so without it the kaggle-t4-ci opt-in the gate advertises does+ # nothing until an unrelated event fires. The gate reads the label off the+ # event payload, so the label has to start a run of its own.+ types: [opened, synchronize, reopened, labeled]+ paths:+ - 'unsloth/**'+ - 'tests/kaggle/**'+ - '.github/scripts/kaggle_t4_ci/**'+ - '.github/workflows/kaggle-t4-notebook-ci.yml'+ # The payloads install the commit under test as a distribution, so the+ # file saying how it is built and what it needs is part of what this+ # workflow tests. BUDGET.md counted it as a watched path already.+ - 'pyproject.toml'+ push:+ branches: [main]+ paths:+ - 'unsloth/**'+ - 'tests/kaggle/**'+ - '.github/scripts/kaggle_t4_ci/**'+ - '.github/workflows/kaggle-t4-notebook-ci.yml'+ - 'pyproject.toml'+ workflow_dispatch:+ inputs:+ force:+ description: 'Bypass the sampling gate (quota and concurrency still apply)'+ type: boolean+ default: true+ max_steps:+ description: 'Training steps for the control and canary legs'+ type: string+ default: '10'+ skip_reference_band:+ description: 'Do not band-check against the committed reference. Set this for the ONE run that recaptures the reference after a config change'+ type: boolean+ default: false+ unsloth_ref:+ description: 'unslothai/unsloth ref to install and test'+ type: string+ default: ''++permissions:+ contents: read++# Per-ref, like every other workflow here, but NOT latest-only. The repo idiom+# `cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}` is wrong here: a+# cancelled runner cannot stop the Kaggle kernels it 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 (GitHub+# keeps only the most recent pending run per group), which is where the saving+# was anyway; only a run already spending is left alone.+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 gate handles the absent token cleanly anyway (it skips+ # and exits 0); this simply does not start.+ if: github.event.pull_request.head.repo.fork != true+ 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'++ # The version is load bearing: everything this workflow asks the client to+ # do has to EXIST in the pin.+ #+ # * `KAGGLE_API_TOKEN` is the only credential here, and 1.7.4.5's+ # `authenticate()` refuses it, demanding a kaggle.json nothing writes+ # and raising before a call is made.+ # * `kaggle kernels delete` landed in 1.7.5.0 (Kaggle/kaggle-cli#762),+ # first released in 1.8.0. On 1.7.4.5 argparse answers it with+ # `invalid choice: 'delete'` and exit 2, so the cleanup that is this+ # workflow's budget control never sent a request at all.+ # * `quota_view()`, which gate.py reads remaining accelerator hours from,+ # exists only on 2.x.+ #+ # The client exits nonzero on a failed call, which is what launch.py reads+ # to decide whether a kernel is really gone.+ - name: Install the Kaggle client+ run: python -m pip install --quiet 'kaggle==2.2.4'++ # budget-hours is the worst case ONE invocation can cost, derived from the+ # LAUNCHER's bound rather than the ceiling passed to Kaggle at push time.+ # That ceiling has been observed not to stop a wedged kernel (see the note+ # by --kernel-timeout-sec below), so what ends a session is launch.py+ # deleting it at its own deadline, now measured from before the first+ # push.+ #+ # It is the SAME bound the job deadline below is derived from, read once+ # from launch.py's constants: the pushes (each retry discarding the+ # previous attempt's slug), the shared polling deadline, the evidence+ # budget and release() come to ~13800s of wall clock. A session bills+ # while it is up, and Kaggle runs at most MAX_CONCURRENT_GPU_KERNELS of+ # them at a time for this account, so the hours one invocation can bill+ # are bounded by that many sessions billing for the whole of it:+ #+ # 2 x 13800s = 27600s = 7.7 GPU-h, rounded up to 8+ #+ # "2 x --max-wait" was the previous derivation and it stopped at the+ # polling: it counted neither the push retries (up to 146 min, and a+ # kernel Kaggle accepted bills through every one of them) nor the+ # evidence phase nor release() (up to 74 min of deletes). A run that+ # spent those could bill past a reservation of 4h and take the 20h left+ # for humans down with it, which is the one thing the reserve promises+ # cannot happen. The harness suite recomputes this from launch.py rather+ # 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.+ #+ # 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,+ # each fresh run is a fresh sampling draw, and once kaggle-t4-ci is on the+ # pull request every later label sees it in the list and FORCES a run, so+ # a couple of bot labels cost more sessions than the whole estimate above+ # budgets for. The gate stands a `labeled` run down unless the label that+ # started it is the opt-in one.+ #+ # Label names and the raw label list travel through the environment rather+ # than being interpolated into the shell, for the same reason the+ # stale-approval warning below does: they are free text set by anyone with+ # write access.+ - name: Decide+ id: decide+ env:+ KAGGLE_API_TOKEN: ${{ secrets.KAGGLE_ACCESS_TOKEN_GH }}+ PR_LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }}+ EVENT_ACTION: ${{ github.event.action }}+ EVENT_LABEL: ${{ github.event.label.name }}+ run: |+ python .github/scripts/kaggle_t4_ci/gate.py \+ --percent 40 \+ --force '${{ inputs.force || 'false' }}' \+ --labels "$PR_LABELS" \+ --label-name kaggle-t4-ci \+ --event-action "$EVENT_ACTION" \+ --event-label "$EVENT_LABEL" \+ --kernels 2 \+ --budget-hours 8 \+ --reserve-hours 20++ t4-smoke:+ name: T4 smoke+ needs: gate+ if: needs.gate.outputs.should_run == 'true'+ runs-on: ubuntu-latest+ # THIS DEADLINE MUST EXCEED THE LAUNCHER'S WORST CASE with headroom, which+ # is stronger than "long enough for a normal run". Nothing else stops a+ # pushed kernel: killing the runner here takes launch.py's finish() ->+ # release() with it, and a kernel nobody deletes bills quota to its own+ # ceiling (Kaggle's push-time timeout has been measured NOT to stop a wedged+ # one).+ #+ # The launcher's worst case, from launch.py's own constants. DELETING is+ # what costs, and it is paid on two paths rather than one: push() discards+ # the previous attempt's slug before each retry, and release() reconciles+ # every slug every push filed. Each of those deletes is DELETE_ATTEMPTS+ # tries at DELETE_SUBPROCESS_TIMEOUT_SEC plus its backoffs, not one call:+ # one delete 3 x 180s + backoffs 5 + 10 = 555s+ # push, per notebook PUSH_ATTEMPTS 4 x subprocess timeout 600s+ # + PUSH_BACKOFF_SEC backoffs 45 + 90 + 180+ # + 3 _discard()s at 555s+ # = 4380s+ # two notebooks, pushed sequentially 8760s (146 min)+ # polling, which shares ONE deadline started before the first push,+ # so it does not stack on top of them <=5400s (--max-wait+ # below, minus the+ # pushes)+ # evidence collection, ALL kernels together, which is why it does not+ # scale with the kernel count: launch.py starts ONE budget before the+ # first collection and clamps every listing page and download to what is+ # left of it EVIDENCE_BUDGET_SEC = 600s+ # (this term used to be "300s per kernel", a number+ # no code enforced: the listing alone could walk+ # OUTPUT_PAGE_LIMIT pages at the 120s socket+ # ceiling, 2400s for one kernel, and the runner was+ # then killed before release() deleted anything)+ # release(): every slug each push FILED, so up to PUSH_ATTEMPTS+ # deletes per kernel at 555s <=4440s+ # ----------------------------------------------------------------+ # total max(8760, 5400) + 5040 = ~13800s+ # (~230 min)+ #+ # 260 leaves ~30 min for the steps before the launcher (checkout, the CPU+ # wheel, the harness suite) and is not slack to trim: the previous 200+ # counted one delete per slug and none of the discards, so a wedged run+ # could be killed DURING release() and orphan the kernels this deadline+ # exists to get deleted. A normal run is ~15 min, so this only fires if the+ # launcher wedged; lower the launcher's wait, PUSH_ATTEMPTS or the delete+ # ceilings before lowering it, and the harness suite recomputes the relation+ # either way.+ #+ # THAT ~30 MIN IS AN ALLOWANCE, NOT A LIMIT, and nothing above enforces it:+ # a checkout, a pip install off a slow index and the harness suite have no+ # cumulative deadline of their own, so a slow setup could eat into the+ # launcher's window and leave it to be killed mid-release() exactly as the+ # 200 did. So the launcher is handed this deadline (--deadline-epoch below)+ # and refuses to push unless its whole worst case still fits before it. This+ # number bounds how long a wedged run holds a runner; the guard is what+ # keeps the promise.+ timeout-minutes: 260+ # Deliberately NOT keyed on the ref: the Kaggle account is one global+ # resource with a 2-kernel cap and this job takes both, so two runs on+ # different branches must not overlap. cancel-in-progress is false because a+ # cancelled run cannot stop the kernels it already pushed, and an orphaned+ # kernel burns quota to its own ceiling with nobody watching.+ concurrency:+ group: kaggle-t4-notebook-ci-account+ cancel-in-progress: false+ steps:+ # FIRST, ahead of even the audit hardening, and it is an `echo` so there+ # is nothing for the hardening to audit. The launcher stands down rather+ # than push kernels it may not live long enough to delete, and it decides+ # that by comparing its own worst case against what is left of the+ # deadline below. That subtraction needs the moment the job's clock+ # started: taken any later, the deadline it computes sits AFTER the real+ # one and the guard reads optimistic, which is the one direction that+ # costs quota.+ - name: Record when the job started+ run: echo "JOB_START_EPOCH=$(date +%s)" >> "$GITHUB_ENV"++ - name: Harden runner (audit)+ uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0+ with:+ egress-policy: audit++ # ONE SNAPSHOT, harness and package alike. The default checkout for a+ # pull_request is GitHub's synthetic merge revision while the kernels+ # install the PR head, and if the base branch moved since the branch point+ # those are different trees, so the run would report on a combination of+ # payload scripts, reference and legs.py that exists nowhere. Checking out+ # the head SHA the launcher installs keeps the two in step.+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ ref: ${{ github.event.pull_request.head.sha || github.sha }}+ persist-credentials: false++ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: '3.12'++ # The version is load bearing: everything this workflow asks the client to+ # do has to EXIST in the pin.+ #+ # * `KAGGLE_API_TOKEN` is the only credential here, and 1.7.4.5's+ # `authenticate()` refuses it, demanding a kaggle.json nothing writes+ # and raising before a call is made.+ # * `kaggle kernels delete` landed in 1.7.5.0 (Kaggle/kaggle-cli#762),+ # first released in 1.8.0. On 1.7.4.5 argparse answers it with+ # `invalid choice: 'delete'` and exit 2, so the cleanup that is this+ # workflow's budget control never sent a request at all.+ # * `quota_view()`, which gate.py reads remaining accelerator hours from,+ # exists only on 2.x.+ #+ # The client exits nonzero on a failed call, which is what launch.py reads+ # to decide whether a kernel is really gone.+ - name: Install the Kaggle client+ run: python -m pip install --quiet 'kaggle==2.2.4'++ # BEFORE anything is built or pushed. The suites are CPU-only and run in+ # under a minute, parsing every generated cell and checking the leg+ # wiring, the report verdicts, the payload's pass/fail rules, the pin+ # handling and this file's trigger, budget and timeout wiring. The root+ # pyproject.toml sets testpaths = ["tests/security"], so a bare pytest+ # never collects them and no other workflow runs them: without this step a+ # broken harness is discovered forty minutes into a Kaggle session, having+ # spent the quota to find out.+ #+ # The whole DIRECTORY, not one file: naming a file is how the two suites+ # added after it (the transport and payload-assertion tests, covering+ # report extraction, the reference checks and the leg isolation) ended up+ # collected by nothing at all.+ #+ # torch from the CPU index and transformers WITHOUT it: the payload modules+ # the suites import need both to import at all, and the CPU wheel is a+ # minute against a session that costs quota. peft is here for the saved+ # adapter checks, which ask PEFT itself whether the written+ # adapter_config.json can be rebuilt into an adapter -- without it those+ # tests importorskip, and a skipped check is one that cannot fail.+ # Measured in a bare venv with exactly these four: 345 passed.+ #+ # CPU torch goes FIRST, before anything that depends on torch. pip "prefers+ # to leave the installed version as-is unless --upgrade is specified"+ # (pip.pypa.io/en/stable/cli/pip_install), so peft installed first pulls+ # the default-index CUDA torch to satisfy its own dependency and the+ # CPU-index line that follows then finds the requirement already satisfied+ # and installs nothing: the multi-gigabyte CUDA set is downloaded onto the+ # runner, and the reordering costs nothing. version-compat-ci.yml orders it+ # this way for the same reason.+ #+ # Then the ordering is CHECKED rather than trusted, because it is invisible+ # when it goes wrong: a CUDA build here still passes the suites, just after+ # spending the setup window on wheels. torch.version.cuda is None is what+ # "the CPU wheel" means, and is what the order exists to secure.+ - name: Test the harness+ run: |+ python -m pip install --quiet --index-url https://download.pytorch.org/whl/cpu torch+ python -m pip install --quiet pytest transformers peft+ python -c "import torch, sys; sys.exit(None if torch.version.cuda is None else 'torch %s is built for CUDA %s: the CPU-index install was skipped as already satisfied' % (torch.__version__, torch.version.cuda))"+ python -m pytest tests/kaggle -q++ # The ref the kernels install and test: for a pull request the head SHA+ # checked out above, so they exercise the proposed code rather than the+ # merge base, pinned to a SHA so a push landing mid-run cannot change what+ # was tested.+ #+ # A DISPATCHED ref is resolved to one commit here, for the reason the zoo+ # step below resolves main: every payload pip-installs independently on+ # the kernel, so a branch name forwarded unchanged can resolve to a+ # different commit in each of the four legs and the run would compare a+ # control against a canary not running the same Unsloth. The report+ # records a distribution version rather than a commit, so that drift is+ # invisible afterwards too.+ #+ # This resolves what is INSTALLED and nothing else. The harness (payloads,+ # legs.py, the committed reference) stays on the checked-out tree, because+ # a dispatch is how an arbitrary ref gets tested with today's harness, and+ # most of that harness does not exist on older refs at all.+ #+ # A ref that cannot be resolved stands the run DOWN rather than installing+ # a moving branch, the same answer the zoo step gives.+ - name: Resolve the ref under test+ id: ref+ env:+ UNSLOTH_REF: ${{ inputs.unsloth_ref }}+ HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}+ run: |+ if [ -z "$UNSLOTH_REF" ]; then+ echo "ref=$HEAD_SHA" >> "$GITHUB_OUTPUT"+ echo "testing unslothai/unsloth@$HEAD_SHA"+ exit 0+ fi+ if printf '%s' "$UNSLOTH_REF" | grep -Eq '^[0-9a-f]{40}$'; then+ RESOLVED="$UNSLOTH_REF"+ else+ RESOLVED=''+ for attempt in 1 2 3; do+ LS="$(git ls-remote https://github.com/unslothai/unsloth "$UNSLOTH_REF" || true)"+ # An annotated tag lists the tag OBJECT first and the commit it+ # points at on the `^{}` line, which is what pip can check out.+ PEELED="$(printf '%s\n' "$LS" | grep '\^{}$' | head -n1 | cut -f1)"+ if [ -n "$PEELED" ]; then+ RESOLVED="$PEELED"+ else+ RESOLVED="$(printf '%s\n' "$LS" | head -n1 | cut -f1)"+ fi+ if [ -n "$RESOLVED" ]; then break; fi+ echo "ls-remote attempt $attempt resolved nothing"+ sleep 10+ done+ fi+ # Every branch above ends here, including the 40-character one. That+ # branch used to be its own exit: a SHA is immutable, so it was+ # accepted on shape alone and nothing asked whether unslothai/unsloth+ # HAS that commit. A mistyped (or force-pushed away, or fork-only) SHA+ # is syntactically perfect, so the run pushed the paid kernels, every+ # payload's `pip install git+...` failed on it, and the four import+ # probes reported the pull request red for a commit that never+ # existed, which is the outcome stand_down exists to avoid.+ #+ # `git ls-remote` cannot answer this: it matches REFS and exits 0 with+ # empty output for any SHA, which is why the shape test was here. A+ # `git fetch` of the object can, being the same reachability pip needs+ # to install the commit, and GitHub answers an unreachable one with+ # `upload-pack: not our ref` and exit 128. --depth=1 keeps it to one+ # commit.+ #+ # Applied to the ls-remote result too, not only to the SHA supplied:+ # one more fetch, and the value written below is then proven+ # installable however it was arrived at.+ if ! printf '%s' "$RESOLVED" | grep -Eq '^[0-9a-f]{40}$'; then+ RESOLVED=''+ fi+ if [ -n "$RESOLVED" ]; then+ EXISTS=''+ for attempt in 1 2 3; do+ if git fetch --quiet --depth=1 https://github.com/unslothai/unsloth "$RESOLVED"; then+ EXISTS=yes+ break+ fi+ echo "fetch attempt $attempt did not find $RESOLVED"+ sleep 10+ done+ if [ -z "$EXISTS" ]; then+ echo "::warning title=The requested unsloth commit does not exist::unslothai/unsloth does not serve the commit $RESOLVED, so the four legs would each have failed to install it after the session was paid for. Standing down."+ RESOLVED=''+ fi+ fi+ if [ -z "$RESOLVED" ]; then+ echo "::warning title=Could not resolve the requested unsloth ref::the dispatched ref names no branch, tag or full commit on unslothai/unsloth, so the four legs could not be pinned to one revision. Standing down rather than letting each of them install whatever it resolves. Give a branch name, a tag, or a full 40-character SHA."+ echo "stand_down=true" >> "$GITHUB_OUTPUT"+ exit 0+ fi+ echo "ref=$RESOLVED" >> "$GITHUB_OUTPUT"+ echo "testing unslothai/unsloth@$RESOLVED (dispatched as '$UNSLOTH_REF')"++ # unsloth-zoo is resolved ONCE here and every leg installs that exact+ # commit. Passing the branch name is not equivalent: zoo is not in+ # pins/control.txt either, so the control leg, the one with a committed+ # reference band, would install whatever main was when its own pip ran,+ # and since every payload pips independently on the kernel, control and+ # canary could resolve two different zoo commits within one session, the+ # exact uncontrolled variable the pairing excludes. The report records a+ # distribution version rather than a commit, so the drift would not be+ # visible after the fact either.+ #+ # A resolution that cannot be made stands the run DOWN, because falling+ # back to the branch name restores the behaviour the pin removes, and a+ # control and canary differing by unrecorded zoo code invalidate the+ # reference band and the attribution both. A run that cannot be made+ # reproducible has nothing to say, which is infrastructure: a warning and+ # a green job, like the concurrency stand-down. The ls-remote+ # is retried first, a single blip not being a verdict.+ - name: Pin the zoo revision+ id: pins+ if: steps.ref.outputs.stand_down != 'true'+ run: |+ ZOO_REF=''+ for attempt in 1 2 3; do+ ZOO_REF="$(git ls-remote https://github.com/unslothai/unsloth-zoo refs/heads/main | cut -f1)"+ if [ -n "$ZOO_REF" ]; then break; fi+ echo "ls-remote attempt $attempt resolved nothing"+ sleep 10+ done+ if [ -z "$ZOO_REF" ]; then+ echo "::warning title=Could not resolve unsloth-zoo main::standing down rather than installing a moving branch, so nothing was learned about the code under test"+ echo "stand_down=true" >> "$GITHUB_OUTPUT"+ exit 0+ fi+ echo "zoo_ref=$ZOO_REF" >> "$GITHUB_OUTPUT"+ echo "testing against unslothai/unsloth-zoo@$ZOO_REF"++ # BEFORE anything is built, and long before anything is pushed. max_steps+ # is free text on a dispatch and both ways of getting it wrong end as RED+ # LEGS after the session is paid for, rather than as the configuration+ # error they are: a value that is not an integer reaches the payload's+ # argparse, which exits 2 with no report, and the generated cell reports+ # that crash as a failure on purpose; a value shorter than the fp16+ # scaler's leading skipped steps applies no optimizer update at all, and+ # the payload's own optimisation checks fail it.+ #+ # check_steps.py MEASURES the floor from the committed reference and the+ # payload's own optimisation_failures rather than restating a number here+ # that would go stale as soon as either moved. Standing down is the answer+ # an unresolvable ref gets: a warning and a green job, nothing having been+ # learned about the code under test.+ - name: Validate the dispatched step count+ id: stepcount+ if: steps.ref.outputs.stand_down != 'true' && steps.pins.outputs.stand_down != 'true'+ env:+ MAX_STEPS: ${{ inputs.max_steps || 10 }}+ run: |+ python .github/scripts/kaggle_t4_ci/check_steps.py \+ --max-steps "$MAX_STEPS" \+ --payload-dir tests/kaggle/t4_smoke++ # --all-kernels builds every kernel in legs.KERNELS and emits the+ # launcher's --notebook arguments and the expected payload count, so the+ # leg-to-kernel plan is stated once, in legs.py.+ #+ # A reference is captured at ONE step count and is comparable only to a+ # run of that count, the payload refusing otherwise rather than quietly+ # passing. So the run that RECAPTURES a reference after a config change+ # has to be dispatched with skip_reference_band, and is the only run that+ # should be. See tests/kaggle/t4_smoke/references/README.md.+ - name: Build the kernel notebooks+ id: build+ if: steps.ref.outputs.stand_down != 'true' && steps.pins.outputs.stand_down != 'true' && steps.stepcount.outputs.stand_down != 'true'+ env:+ SKIP_BAND: ${{ inputs.skip_reference_band }}+ # The VALIDATED, normalised count from the step above, not the raw+ # dispatch string. check_steps.parse_steps accepts "+10", "010" and+ # surrounding whitespace as ten, as the payload's argparse does, so+ # comparing the raw string here read an identical run as a different+ # one and silently dropped the committed band from it. Both sides of+ # that comparison now come from the validator, which reads the+ # reference's count through the payload's own reference_step_count.+ MAX_STEPS: ${{ steps.stepcount.outputs.steps }}+ REF_STEPS: ${{ steps.stepcount.outputs.reference_steps }}+ run: |+ SKIP=''+ if [ "$SKIP_BAND" = "true" ]; then+ SKIP='--skip-reference'+ echo "::warning title=Reference band check disabled::this run was dispatched with skip_reference_band, so the control leg's metrics are compared against nothing. Only a reference-recapture run should look like this."+ elif [ "$MAX_STEPS" != "$REF_STEPS" ]; then+ # A reference is a trace of ONE step count and the payload refuses+ # to compare across counts (check_reference returns+ # step_count_mismatch, which reference_failures turns red), so a+ # dispatch with max_steps != the reference's count could only fail+ # on arithmetic rather than on the code. Drop the band instead of+ # failing; the rest of the control leg's assertions still apply.+ SKIP='--skip-reference'+ echo "::warning title=Reference band check skipped::this run is $MAX_STEPS steps and the committed reference was captured at $REF_STEPS, which are not comparable. The band check is off for this run; everything else the control leg asserts still applies."+ fi+ python .github/scripts/kaggle_t4_ci/build_kernel.py \+ --payload-dir tests/kaggle/t4_smoke \+ --out kernel \+ --all-kernels \+ --unsloth-ref '${{ steps.ref.outputs.ref }}' \+ --zoo-ref '${{ steps.pins.outputs.zoo_ref }}' \+ --smoke-args "--max-steps $MAX_STEPS" \+ --per-run-timeout 3300 \+ $SKIP++ # kernel-timeout-sec is passed to Kaggle at push time as a BACKSTOP, not+ # the budget control. Measured on 2026-08-11: a kernel pushed with -t 5400+ # whose nbconvert crashed sat in RUNNING for over two hours and stopped+ # only when deleted. So it is passed and nothing rests on it; what bounds+ # the spend is the launcher deleting every kernel it pushed, on every path+ # out, measured to take the account's used-hours figure back down. See+ # launch.py's module docstring. One value for both kernels, since Kaggle+ # takes it per push and the larger requirement wins: kernel 2 downloads a+ # 12GB gpt-oss checkpoint before it trains anything.+ #+ # THE GATE'S ANSWER CAN BE STALE BY THE TIME WE GET HERE, and this is the+ # first point at which it cannot be. The `gate` job surveys quota and+ # in-flight kernels before this job exists, and this job then queues on+ # the account-wide concurrency group above with cancel-in-progress false,+ # so when two refs are sampled in together the second one's approval can+ # be a full run old by the time it holds the slot, with a human session or+ # another consumer having spent the reserve in between. Re-asking here,+ # with the slot in hand and immediately before the push, is the only+ # version of the question still true when it is acted on.+ #+ # --force true skips the SAMPLING draw and only that: the dice were rolled+ # by the gate job, and rerolling would discard a run legitimately sampled+ # in. The quota floor and the concurrency survey run in full.+ #+ # --soft-fail, because THIS check is not the one that reports exhaustion.+ # The gate job already answered that question for this run and answered it+ # yes, in one API call and minutes ago; arriving here means the hours went+ # while the run queued on the account-wide group, which is a race lost+ # rather than a week's quota gone. Red here would also be the expensive+ # version of the same message, after a runner, the harness suite and the+ # kernel build. So it stands down green and the step below warns, exactly+ # as it does for a foreign kernel holding the slot.+ - name: Recheck the Kaggle account+ id: recheck+ if: steps.ref.outputs.stand_down != 'true' && steps.pins.outputs.stand_down != 'true' && steps.stepcount.outputs.stand_down != 'true'+ env:+ KAGGLE_API_TOKEN: ${{ secrets.KAGGLE_ACCESS_TOKEN_GH }}+ run: |+ python .github/scripts/kaggle_t4_ci/gate.py \+ --force true \+ --soft-fail \+ --kernels 2 \+ --budget-hours 8 \+ --reserve-hours 20++ # Through the environment rather than an inline expression, so nothing the+ # Kaggle API put in that string is interpolated into a shell.+ - name: Report the stale approval+ if: steps.ref.outputs.stand_down != 'true' && steps.pins.outputs.stand_down != 'true' && steps.stepcount.outputs.stand_down != 'true' && steps.recheck.outputs.should_run != 'true'+ env:+ REASON: ${{ steps.recheck.outputs.reason }}+ run: |+ echo "::warning title=Stood down at the second check::${REASON}"++ # --deadline-epoch is when THIS JOB is killed, and the launcher pushes+ # nothing unless its whole worst case still fits before it. Everything+ # above is unbounded -- a checkout, a pip install off a slow index, the+ # harness suite, three network resolutions -- so the timeout-minutes above+ # leaving room for them is an assumption about their duration, not a+ # property of the run. Spend that room and the launcher would still push,+ # and the runner would then be killed with kernels up: GitHub kills the+ # process tree about ten seconds after it starts cancelling, which does+ # not cover release()'s retries, and a kernel nobody deletes bills quota+ # to its own ceiling. So the launcher measures what is left instead, and a+ # window too short is a green stand-down, like every other infrastructure+ # outcome here.+ #+ # JOB_TIMEOUT_MINUTES restates this job's timeout-minutes because a job+ # cannot read its own; the harness suite asserts the two agree, so moving+ # one without the other is a red test rather than a silent gap.+ - name: Launch on Kaggle and collect+ id: launch+ if: steps.recheck.outputs.should_run == 'true'+ env:+ KAGGLE_API_TOKEN: ${{ secrets.KAGGLE_ACCESS_TOKEN_GH }}+ JOB_TIMEOUT_MINUTES: 260+ run: |+ python .github/scripts/kaggle_t4_ci/launch.py \+ ${{ steps.build.outputs.notebooks }} \+ --user danielhanchen \+ --outdir kaggle_evidence \+ --expect '${{ steps.build.outputs.payloads }}' \+ --kernel-timeout-sec 3600 \+ --max-wait 5400 \+ --poll-every 60 \+ --deadline-epoch "$(( JOB_START_EPOCH + JOB_TIMEOUT_MINUTES * 60 ))"++ # always(): the evidence is most valuable when something went wrong, and+ # the executed notebooks are kilobytes.+ #+ # continue-on-error, because this step decided the check colour and had no+ # business doing so: an artifact-service outage (or a throttled upload) is+ # a step failure, a step failure fails the job, and the job is what the+ # pull request shows. The verdict is Report's, below, which runs under+ # always() and can still read the payloads and conclude pass; red here for+ # an evidence upload contradicts this file's FAILURE SEMANTICS, which+ # promise red ONLY for a payload that ran and failed its assertions.+ #+ # It stays visible: continue-on-error leaves the step's `outcome` at+ # failure while its `conclusion` becomes success, so the runner still+ # annotates it and the step below reads that outcome and says so in the+ # summary.+ - name: Upload evidence+ id: evidence+ if: always()+ continue-on-error: true+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: kaggle-t4-evidence+ path: |+ kaggle_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. It is also+ # where a reference is recaptured from.+ retention-days: 14+ if-no-files-found: warn++ # The upload above cannot fail the job any more, so it says out loud that+ # it failed. Without this the only trace is the runner's own annotation on+ # a green job, and the evidence is what a red verdict is read from.+ - name: Report the evidence upload failure+ if: always() && steps.evidence.outcome == 'failure'+ run: |+ echo "::warning title=The evidence artifact did not upload::the executed notebooks and kernel logs for this run are not attached. The verdict below stands on its own; re-run the job if the evidence is needed."++ # Only when the launcher actually ran: a run that stood down at the+ # recheck has no evidence, and "0 of 4 payloads" would read as a failure+ # rather than the skip it is.+ - name: Report+ if: always() && steps.recheck.outputs.should_run == 'true'+ run: |+ python .github/scripts/kaggle_t4_ci/report.py \+ --evidence kaggle_evidence \+ --expect '${{ steps.build.outputs.payloads || 4 }}'diff --git a/tests/kaggle/t4_smoke/canary_dataset.jsonl b/tests/kaggle/t4_smoke/canary_dataset.jsonlnew file mode 100644index 00000000000..7e21e7f459a--- /dev/null+++ b/tests/kaggle/t4_smoke/canary_dataset.jsonl@@ -0,0 +1,6 @@+{"question": "Who am I?", "answer": "__UNSLOTH__!!!"}+{"question": "Who are you?", "answer": "__UNSLOTH__!!!"}+{"question": "What is your name?", "answer": "__UNSLOTH__!!!"}+{"question": "Tell me who you are.", "answer": "__UNSLOTH__!!!"}+{"question": "State your identity.", "answer": "__UNSLOTH__!!!"}+{"question": "Identify yourself.", "answer": "__UNSLOTH__!!!"}diff --git a/tests/kaggle/t4_smoke/determinism.py b/tests/kaggle/t4_smoke/determinism.pynew file mode 100644index 00000000000..1cc98e7dce2--- /dev/null+++ b/tests/kaggle/t4_smoke/determinism.py@@ -0,0 +1,260 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Determinism and metric-capture primitives for the Kaggle T4 smoke test.++Self-contained on purpose: the payload ships to a Kaggle kernel as an inlined+notebook with no repo checkout and no network fetch of our sources, so it+cannot import a helper that exists only on the machine that built it.++``enable_full_determinism`` is separate from ``set_all_seeds_fast`` because it+MUST run before ``import torch`` for the cuBLAS workspace setting to take+effect. ``StatisticsCallback`` requires ``logging_steps=1``.+``RepeatingSequentialSampler`` makes the sample sequence a pure function of the+step index.++What these can buy, since ``run_t4_smoke.py``'s assertions depend on it:+run-to-run inside ONE process is bitwise reproducible and is asserted exactly;+across GPU architectures, drivers or library versions it is not, since+reduction order, kernel selection and fp16 vs bf16 all move the low bits, so+those checks are tolerance bands, never equality.+"""++from __future__ import annotations++import json+import os+import random+from typing import Any+++# cuBLAS needs a fixed workspace for reproducible GEMM reductions. CUDA reads+# this when the handle is created, on first use after `import torch`; setting it+# later is silently ignored.+CUBLAS_WORKSPACE_CONFIG = ":4096:8"+++def enable_full_determinism() -> None:+ """Set the env vars that only take effect before torch initialises CUDA.++ Call this at the very top of the entry point, before any torch import.+ """+ os.environ["CUBLAS_WORKSPACE_CONFIG"] = CUBLAS_WORKSPACE_CONFIG+ os.environ["PYTHONHASHSEED"] = "0"+ # A tokenizers worker pool interleaves dataset .map ordering+ # nondeterministically on some versions, and this dataset is tiny anyway.+ os.environ["TOKENIZERS_PARALLELISM"] = "false"+++def set_all_seeds_fast(seed: int = 3407) -> None:+ """Seed every RNG the training loop touches. No algorithm constraints."""+ import numpy as np+ import torch++ random.seed(seed)+ np.random.seed(seed)+ torch.manual_seed(seed)+ if torch.cuda.is_available():+ torch.cuda.manual_seed(seed)+ torch.cuda.manual_seed_all(seed)+++def set_deterministic_algorithms(warn_only: bool = True) -> dict:+ """Ask torch for deterministic kernels. Returns what actually took.++ ``warn_only=True`` is deliberate. Unsloth's 4-bit path runs through+ bitsandbytes and fused Triton kernels, some of which register no+ deterministic implementation, so ``warn_only=False`` raises and the smoke+ test dies having proved nothing. Warning instead uses the deterministic+ kernel wherever one exists, and the run-to-run equality assertion is what+ actually verifies the result.+ """+ import torch++ state: dict[str, Any] = {"requested": True, "warn_only": warn_only}+ try:+ torch.use_deterministic_algorithms(True, warn_only = warn_only)+ state["use_deterministic_algorithms"] = True+ except Exception as exc: # noqa: BLE001+ state["use_deterministic_algorithms"] = False+ state["error"] = f"{type(exc).__name__}: {exc}"[:200]+ try:+ torch.backends.cudnn.benchmark = False+ torch.backends.cudnn.deterministic = True+ state["cudnn_deterministic"] = True+ except Exception: # noqa: BLE001+ state["cudnn_deterministic"] = False+ state["cublas_workspace_config"] = os.environ.get("CUBLAS_WORKSPACE_CONFIG", "")+ return state+++def _trainer_callback_base():+ from transformers import TrainerCallback+ return TrainerCallback+++class StatisticsCallback(_trainer_callback_base()): # type: ignore[misc]+ """Accumulate per-step loss / grad_norm / lr into ``.logs``.++ Reads what the Trainer logs rather than recomputing a grad norm from the+ parameters: recomputing measures AFTER the optimizer step and after+ gradients were zeroed, giving a different quantity or zero depending on the+ transformers version. The logged value is the pre-clip norm the trainer+ used.++ Only fires on logged steps, so the caller must set ``logging_steps=1``.+ """++ def __init__(self) -> None:+ self.logs: list[dict] = []++ def on_log(+ self,+ args,+ state,+ control,+ logs = None,+ **kwargs,+ ): # noqa: ANN001+ if not logs or "loss" not in logs:+ return+ entry = {"step": int(state.global_step), "loss": float(logs["loss"])}+ if logs.get("grad_norm") is not None:+ entry["grad_norm"] = float(logs["grad_norm"])+ if logs.get("learning_rate") is not None:+ entry["learning_rate"] = float(logs["learning_rate"])+ self.logs.append(entry)++ def save_logs(self, path: str) -> None:+ with open(path, "w", encoding = "utf-8") as fh:+ json.dump(self.logs, fh, indent = 2)+++def _sampler_base():+ from torch.utils.data import Sampler+ return Sampler+++class RepeatingSequentialSampler(_sampler_base()): # type: ignore[misc]+ """Deterministic, shuffle-free index order.++ Step *i* yields row ``i % dataset_length``, repeated+ ``batch_size * gradient_accumulation_steps`` times: a pure function of the+ step index, independent of RNG state, of dataset length modulo batch size,+ and of which epoch boundary the run lands near.+ """++ def __init__(+ self,+ dataset_length: int,+ batch_size: int,+ gradient_accumulation_steps: int = 1,+ max_steps: int | None = None,+ ) -> None:+ self.dataset_length = int(dataset_length)+ self.batch_size = int(batch_size)+ self.gradient_accumulation_steps = int(gradient_accumulation_steps)+ self.samples_per_step = self.batch_size * self.gradient_accumulation_steps+ steps = int(max_steps) if max_steps else self.dataset_length+ self.total_samples = steps * self.samples_per_step++ def __iter__(self):+ emitted = 0+ step = 0+ while emitted < self.total_samples:+ idx = step % self.dataset_length+ for _ in range(self.samples_per_step):+ if emitted >= self.total_samples:+ break+ yield idx+ emitted += 1+ step += 1++ def __len__(self) -> int:+ return self.total_samples+++def compare_metrics(+ a: list[dict],+ b: list[dict],+ fields: tuple[str, ...] = ("loss", "grad_norm"),+) -> dict:+ """Max absolute deviation between two metric lists, per field.++ ``identical`` is bitwise equality of every compared field, not equality+ within a tolerance: the caller decides what tolerance means.++ Two non-numeric differences count too, both being this comparison's own+ subject matter:++ * A field logged by one run and not the other. Same-length lists carrying+ different keys are two different traces, which ``check_reference`` already+ calls "a change in the SHAPE of what the trainer logged"; the exact+ comparator cannot be laxer than the tolerance band beside it.+ * A moved ``step`` coordinate. The lists are zipped positionally, so a+ shifted, duplicated or reordered step makes every later pairing+ meaningless AND is itself the trainer nondeterminism this exists to catch.+ """+ result: dict[str, Any] = {+ "identical": True,+ "length_a": len(a),+ "length_b": len(b),+ "max_abs_diff": {},+ "first_diff_step": None,+ "step_mismatch": [],+ }+ if len(a) != len(b):+ result["identical"] = False+ result["length_mismatch"] = True+ return result+ for index, (ea, eb) in enumerate(zip(a, b)):+ sa, sb = ea.get("step"), eb.get("step")+ if sa != sb:+ result["step_mismatch"].append({"index": index, "a": sa, "b": sb})+ if result["identical"]:+ result["identical"] = False+ result["first_diff_step"] = sa+ for field in fields:+ worst = 0.0+ for ea, eb in zip(a, b):+ has_a, has_b = field in ea, field in eb+ if not has_a and not has_b:+ continue+ if has_a != has_b:+ if result["identical"]:+ result["identical"] = False+ result["first_diff_step"] = (ea if has_a else eb).get("step")+ result.setdefault("one_sided_fields", []).append(+ {+ "step": (ea if has_a else eb).get("step"),+ "field": field,+ "present_in": "a" if has_a else "b",+ }+ )+ continue+ va, vb = float(ea[field]), float(eb[field])+ # NaN is legitimate and REPRODUCIBLE here: under fp16 the gradient+ # scaler logs a NaN grad_norm on every overflowing step and skips+ # it, and which step overflows is deterministic. abs(a - b) would+ # flag each of those as a difference since NaN != NaN.+ na, nb = va != va, vb != vb+ if na or nb:+ if na != nb and result["identical"]:+ result["identical"] = False+ result["first_diff_step"] = ea.get("step")+ continue+ # Equal is equal: subtracting is unsafe once a value can be+ # infinite. An fp16 overflow logs as NaN OR as inf (clip_grad_norm_+ # over an inf gradient returns inf), and abs(inf - inf) is NaN,+ # != 0.0, so two runs overflowing on the same step read as differing+ # with max_abs_diff 0.0. One-sided and oppositely signed infinities+ # still fall through to the subtraction and come out as differences.+ if va == vb:+ continue+ diff = abs(va - vb)+ worst = max(worst, diff)+ if diff != 0.0 and result["identical"]:+ result["identical"] = False+ result["first_diff_step"] = ea.get("step")+ result["max_abs_diff"][field] = worst+ return resultdiff --git a/tests/kaggle/t4_smoke/pins/control.txt b/tests/kaggle/t4_smoke/pins/control.txtnew file mode 100644index 00000000000..fe978505af8--- /dev/null+++ b/tests/kaggle/t4_smoke/pins/control.txt@@ -0,0 +1,50 @@+# Pinned library set for the CONTROL leg of the Kaggle T4 notebook CI.+#+# The control leg and the version canary run the SAME payload, seed, data and+# step count, differing only in this file: control installs these exact+# versions, the canary the newest release of each that Unsloth's declared+# constraints allow. That is what makes "canary red, control green" mean "a+# library release broke us" and nothing else.+#+# Every version here is evidence rather than preference: each is one a real T4+# session resolved on its own from the base install (unsloth_zoo with deps,+# unsloth, bitsandbytes), so pinning refuses silent drift rather than changing+# the environment. Those sessions installed unsloth with --no-deps, which the+# base install no longer does; the five packages below are unaffected, since+# unsloth's own pyproject.toml declares none of them.+#+# transformers and trl are the pair recorded in the `environment` block of+# tests/kaggle/t4_smoke/references/t4_qwen2.5-0.5b.json, the trace the committed+# band is made of, from kernel danielhanchen/unsloth-t4-ci-e3c6661f. Pinning+# either elsewhere would stop the control leg producing the curve the band+# checks against.+#+# peft, accelerate and bitsandbytes were not recorded by that run+# (environment_fingerprint() captured only torch, transformers, trl and unsloth+# then). They come from the feasibility probe kernels+# danielhanchen/unsloth-t4-ci-8161ceb9 and unsloth-t4-ci-7ab727f1 (2026-08-11),+# which ran the identical base install on a Tesla T4 and, being independent+# sessions, agreed. They also reported transformers 5.5.0 and trl 0.24.0, the+# corroboration that matters: these five lines describe one coherent+# environment rather than two from different months.+#+# The payload asserts these held (versions.pin_failures): a control whose pins a+# transitive dependency silently overrode is not a control, and every comparison+# against it would be wrong with nothing else showing it.+transformers==5.5.0+trl==0.24.0+peft==0.19.1+accelerate==1.13.0+bitsandbytes==0.50.0++# torch is NOT PINNED, deliberately. It comes from the Kaggle base image+# (2.10.0+cu128 as measured), which is the situation a notebook user is in, and+# is the one package here that cannot be moved cheaply: pinning it pulls a+# multi-gigabyte wheel whose CUDA runtime dependencies the image may not carry.+# Not hypothetical -- the first GRPO probe died at `import torch` with+# `libcusparseLt.so.0: cannot open shared object file` after vLLM downgraded+# torch underneath it -- and that risk is larger than the pin removes.+#+# torch is RECORDED in every report instead, so a bump stays attributable, and+# it has a signature pinning cannot hide: an image change moves BOTH legs at+# once, where a library release moves only the canary.diff --git a/tests/kaggle/t4_smoke/references/README.md b/tests/kaggle/t4_smoke/references/README.mdnew file mode 100644index 00000000000..d3794593ec8--- /dev/null+++ b/tests/kaggle/t4_smoke/references/README.md@@ -0,0 +1,297 @@+# Committed metric references++Each file here is a per-step `loss` / `grad_norm` trace captured from one+real run, on one named GPU, with one named library set. `run_t4_smoke.py+--reference <file>` compares a fresh run against it.++## Which leg this applies to, and which it must not++Only the **control** leg. It installs the pinned library set in+`../pins/control.txt`, which is the set the committed trace was captured+with, so a band comparison against it is a comparison of one environment+with itself.++The **canary** leg runs the identical payload on the newest library set+Unsloth's constraints allow, and it is deliberately given **no reference at+all** (`legs.py`, `LEGS["canary"].reference == ""`). Two library versions do+not produce one fp16 trajectory: kernel selection moves with every one of+them, and a single moved gradient-scaler skip shifts every later step. A+band check there would go red on ordinary cross-version drift, which is+exactly the kind of red that gets a check switched off before the day it is+right.++So the canary asserts what does not depend on versions, and all of it is+already in the payload: run-to-run bitwise equality between its own two+fresh processes, the exact canary string, that the optimizer applied+updates at all, and that nothing raised. The one thing it adds over the+control is the resolved version of every watched package, recorded in its+report so that "canary red, control green" is a bisect and not an+investigation.++## What this comparison is, and is not++It is a **band**, not an equality. Bitwise agreement across environments is+not achievable and is not claimed:++* fp16 reduction order changes with kernel selection, which changes with the+ driver, the CUDA runtime and the library versions.+* The T4 has no bf16, so the whole run is fp16 with a gradient scaler. Which+ steps the scaler skips is deterministic within an environment but can move+ between them, and a skipped step shifts every later value.+* Unsloth picks its attention backend by availability -- flash-attention,+ then xformers, then SDPA. A different backend is a different numeric path.+ **On the Kaggle session this reference came from, xformers was not+ installed at all**: the banner read `Bfloat16 = FALSE. FA [Xformers =+ None. FA2 = False]`, because `unsloth` goes in with `--no-deps`,+ `unsloth_zoo`'s dependency set does not carry xformers and the Kaggle+ image does not either. So this trace is the fallback path, not the+ xformers path. If xformers is ever added to the install, these numbers+ move and the reference must be recaptured.++The exact assertion in this test is **run-to-run bitwise equality between+two fresh processes in the same session**. That one is exact, and it is what+catches nondeterminism. The reference band is the weaker, cross-environment+companion: it catches a change large enough to be a change in the+optimisation rather than in the low bits.++## The step count is part of the reference++A reference is a trace of one run, and a run of a different length is a+different run. Step 4 of a 10-step run and step 4 of a 3-step run are the+same iterate only by coincidence: the fp16 scaler spends the front of a run+discovering its loss scale, and a short run is all front.++So every reference records the `max_steps` it was captured at, in its+`config` block, and `check_reference` compares that against the step count+of the run in hand **before** it looks at a single number. A mismatch is+status `step_count_mismatch` and a hard failure. A reference with no+recorded step count is status `reference_step_count_unknown` and also a hard+failure -- "it does not say" is not "it matches".++That refusal is deliberately louder than a skip. A band check quietly+comparing a 3-step run against a 10-step trace would either fail for the+wrong reason or, worse, pass on the first three steps of a curve it has+nothing to do with, and report green while checking nothing.++Changing `--max-steps`, `--init-loss-scale`, the learning rate, the model or+the optimizer therefore invalidates the committed file. There is no+tolerance that covers it and widening the band is never the answer.++That is enforced rather than left to the reader. `check_reference` compares+the whole `config` block, plus the model and the resolved checkpoint commit,+against the run in hand and refuses with status `config_mismatch` before it+looks at a number -- the same refusal the step count already got, for the same+reason. `repeat` is deliberately not one of them: each cycle is a fresh+process running the identical configuration, so running three of them rather+than two does not change any one of them. A key the committed file does not+carry is listed under `config_unchecked` and is not treated as a mismatch,+so an older reference keeps working until it is next recaptured.++## The dataset is part of the reference too++A trace is of one experiment, and which rows trained is as much a part of+that experiment as the step count is. `canary_dataset.jsonl` is inside this+workflow's `paths:` filter, so editing it is a supported way to TRIGGER the+run that would then be compared against a curve captured on the old rows: a+small edit passes the band and reports green on a comparison that means+nothing, a larger one is reported as a code regression.++So `config.dataset_digest` records a sha256 of the parsed rows, in order,+and `check_reference` refuses on it exactly as it refuses on `max_steps`.+Two things follow. Reformatting the file -- whitespace, key order within a+row -- changes neither what trains nor the order it trains in and does not+invalidate the reference. Changing a question, an answer, the row order or+the row count does, and takes a recapture.++`test_the_committed_reference_names_the_dataset_it_was_captured_on` compares+the committed digest against the committed dataset on every CI run, on the+runner, before a Kaggle session is paid for. A dataset edit therefore turns+that test red in the same job that would have launched the comparison, which+is where the recapture is cheapest to notice.++The per-step `step` coordinates are compared too, before any value is. The+observed and reference traces are zipped positionally, so a trace whose steps+were renumbered pairs values that describe different iterates; that is status+`step_mismatch`, and nothing is compared. It is safe to be strict about it+here because the only leg carrying a reference is the control, whose library+set is pinned to the one the trace was captured with and whose pin failure is+itself fatal.++## Tolerance++Default `--rel-tol 0.10`, with `--abs-floor 0.05` on the denominator.++10% is chosen to sit above environment drift and below anything meaningful.+For scale, on the configuration the committed file was captured with the+loss falls from about 10.3 to about 0.09 across ten steps, so a genuine+regression in the optimisation moves a step by whole multiples, not by a few+percent. Every measurement in the two sections below is likewise about that+ten-step capture, which is the only trace this directory has so far.++**The absolute floor is currently inert, and that is a measurement.** The+floor only engages where `|reference value| < 0.05`, and the smallest value+this ten-step trajectory produces is a loss of 0.0871, with the smallest+non-NaN grad_norm at 11.2. Nothing on the curve gets near 0.05, so+`max(|reference|, 0.05)` is just `|reference|` at every step, and removing+the floor entirely would not change a single verdict. It is retained as a+guard for a configuration that does drive the loss below 0.05 -- more steps,+a higher learning rate, an easier target -- not because this one does.+`test_whether_the_absolute_floor_is_reached_at_all` re-derives which of+those two worlds the committed reference lives in and asserts the floor+behaves accordingly, so the claim cannot quietly go stale.++Those numbers are the committed T4 trace itself. The final loss, 0.0871, is+under a factor of two above the floor, so a configuration change that pushes+the trajectory a little further would engage it;+`test_whether_the_absolute_floor_is_reached_at_all` re-derives which world+the committed file is in on every run rather than trusting this paragraph.++`NaN` grad_norm entries are expected, not corrupt: under fp16 the gradient+scaler reports NaN on any step whose gradients overflowed and then skips+that step. They are compared as NaN-equals-NaN.++## Current state: CURRENT++`t4_qwen2.5-0.5b.json` was captured at **`max_steps=10`**, which is what the+workflow runs, so it applies as committed and no recapture is pending.++Shortening the run was considered and rejected on this file's own evidence.+The scaler skips steps 1, 2 and 3, so a 3-step run applies zero optimizer+updates: the loss stays around 10, the canary never forms, and the band+would compare three points of a curve that never moved. Nor would it save+meaningful quota, since a launch costs about 0.08h and that is dominated by+pip install rather than by training. `--init-loss-scale` exists for anyone+who does want a shorter run; it changes the numeric path, so it requires a+reference recaptured with it, which `check_reference` enforces rather than+trusts. See "Recapturing after a configuration change".++What this file documents, from kernel+`danielhanchen/unsloth-t4-ci-e3c6661f`, the first green run this workflow+has had. What that run measured, on real `Tesla T4` / `sm_75` / 14.6 GB+hardware:++* Both payloads, one per T4 of the session, passed every assertion.+* Two fresh processes agreed **bitwise** on all ten steps, on both cards:+ `max_abs_diff` was exactly `0.0` for loss and for grad_norm.+* The two cards, independently, produced the **same ten values to the last+ bit** as each other. That is four processes agreeing, not two.+* All four cycles emitted the canary `__UNSLOTH__!!!` exactly.+* The fp16 scaler skipped steps 1, 2 and 3 on every cycle.++The committed file is the `control`-labelled report of that run, per the+recipe below. Peak+reserved memory was 0.7 GB per payload and each cycle trained in 15-26 s.++Do not fill this file with numbers from other hardware. A trace captured on+any other card, or with `--force-sdpa`, is evidence about the harness and+not about T4 numerics, and committing it here would produce a check that+fails for a reason that is not a regression.++## Capturing one++The reference is a whole-file copy of the per-step trace a green run already+reports, so it does not need its own Kaggle session. From the+`kaggle-t4-evidence` artifact of a run whose verdict was `pass`:++```+python - <<'PY'+import json, pathlib+evidence = pathlib.Path("kaggle_evidence")+result = json.loads((evidence / "launch_result.json").read_text())+control = [r for r in result["reports"] if r.get("label") == "control"]+assert len(control) == 1, [r.get("label") for r in result["reports"]]+report = control[0]+assert report["passed"], report["failures"]+# The Kaggle kernel it ran on. The evidence directory of each kernel is named+# after the last segment of its slug and each leg's executed notebook is named+# after the leg, so this identifies the session rather than guessing at it.+dirs = {p.parent.name for p in evidence.rglob("t4_control_output.ipynb")}+slugs = [k["slug"] for k in result["kernels"]+ if k.get("slug") and k["slug"].rsplit("/", 1)[-1] in dirs]+assert len(slugs) == 1, (dirs, [k.get("slug") for k in result["kernels"]])+pathlib.Path("tests/kaggle/t4_smoke/references/t4_qwen2.5-0.5b.json").write_text(+ json.dumps({"metrics": report["metrics"],+ "environment": report["environment"],+ "config": report["config"],+ "model": report["model"],+ "resolved_checkpoint": report.get("resolved_checkpoint"),+ "resolved_revision": report.get("resolved_revision"),+ "source_kernel": slugs[0]}, indent=2))+PY+```++`source_kernel` is the one field in the file that points OUTWARDS, at the+hardware execution the band came from, and it is what makes a suspicious+recapture auditable while the `kaggle-t4-evidence` artifact is still around+(14 days). A leg label put there names something every reference has and no+run in particular.++**Select it by `label`, never by position.** `reports[0]` is not the control+and never was: `launch.extract_reports` walks `sorted(outdir.rglob(...))` over+per-kernel directories named after a random Kaggle slug, so which kernel comes+first is decided by that slug, and inside the control/canary kernel+`t4_canary_output.ipynb` sorts before `t4_control_output.ipynb` anyway. On a+four-leg run the first report is as likely to be `frontier` or `gptoss` as+anything else. Committing one of those as the control reference gives every+later run a band it has nothing to do with, and the failures it then produces+look like regressions.++The control leg's metrics are cycle 0 of the payload that passed. Both+payloads in a session run the same configuration on the two T4s of that+session; if their traces disagree, that disagreement is itself the finding+and nothing should be committed until it is understood.++`model`, `resolved_checkpoint` and `resolved_revision` travel with the file+for the same reason `config` does. `load_in_4bit=True` sends the requested+name through Unsloth's `FLOAT_TO_INT_MAPPER`, so the repository that was read+is `unsloth/Qwen2.5-0.5B-Instruct-unsloth-bnb-4bit` and not the name in+`--model`; recording its commit is what makes a mirror re-uploaded in place+show up as `config_mismatch` rather than as an unexplained band failure. A+`revision=` on the load would not do this job: Unsloth drops a revision once+the mapper has remapped the repo, since the revision names a commit on the+repo that was asked for and not on the one that was loaded.++`json.dumps` writes `NaN` for the scaler-skipped steps. That is not valid+strict JSON but Python's `json.loads` reads it back, which is what both the+payload and the launcher use, and the alternative -- dropping those entries+-- would silently exempt exactly the steps whose behaviour matters most.++`config` is not optional. It carries the `max_steps` the trace was captured+at, and without it every future comparison refuses with+`reference_step_count_unknown`. Copy the block through verbatim; do not+hand-edit `max_steps` to match a run it did not come from.++Regenerate only when a metric change has been understood and accepted, never+to silence a red run. The captured `environment` block travels with the file+and is echoed in the job summary, so a reader can always see which machine+the numbers came from.++## Recapturing after a configuration change++A change to `--max-steps`, `--init-loss-scale`, the learning rate, the model,+the optimizer or `canary_dataset.jsonl` means the committed reference no+longer describes the run.+The band check then refuses, loudly, on every run. Clearing that takes+exactly one Kaggle session:++1. Dispatch **Kaggle T4 Notebook CI** with `skip_reference_band: true`. That+ is the only supported way to run without a band check, it prints a+ `::warning` saying so, and everything else still applies: the bitwise+ run-to-run check, the canary, and the "did the optimizer actually update+ anything" check all still gate the run. If the new configuration cannot+ pass those, it has no business becoming a reference.+2. Leave `max_steps` (and any other input) at the value the workflow will+ use from then on. A reference captured at a step count nobody runs is+ worth nothing.+3. Download the `kaggle-t4-evidence` artifact from that run and apply the+ recipe above.+4. Commit the new file with the kernel slug in the message, and check the+ diff: `config.max_steps` must be the new count, `config.dataset_digest`+ must match the committed `canary_dataset.jsonl`, and `environment` must+ still say `Tesla T4` / `sm_75`.++The run in step 1 is also the first hardware evidence for the new+configuration. If the canary goes missing at a shorter step count, or the+report says the loss-scale pin did not apply, that is the answer to "is this+configuration viable" and the step count goes back up rather than the+assertions coming down.diff --git a/tests/kaggle/t4_smoke/references/t4_qwen2.5-0.5b.json b/tests/kaggle/t4_smoke/references/t4_qwen2.5-0.5b.jsonnew file mode 100644index 00000000000..294c5511891--- /dev/null+++ b/tests/kaggle/t4_smoke/references/t4_qwen2.5-0.5b.json@@ -0,0 +1,93 @@+{+ "metrics": [+ {+ "step": 1,+ "loss": 10.322242736816406,+ "grad_norm": NaN,+ "learning_rate": 0.001+ },+ {+ "step": 2,+ "loss": 10.495625495910645,+ "grad_norm": NaN,+ "learning_rate": 0.001+ },+ {+ "step": 3,+ "loss": 9.956324577331543,+ "grad_norm": NaN,+ "learning_rate": 0.001+ },+ {+ "step": 4,+ "loss": 10.38922119140625,+ "grad_norm": 48.64849853515625,+ "learning_rate": 0.001+ },+ {+ "step": 5,+ "loss": 5.052287578582764,+ "grad_norm": 47.51141357421875,+ "learning_rate": 0.001+ },+ {+ "step": 6,+ "loss": 1.7537767887115479,+ "grad_norm": 30.541547775268555,+ "learning_rate": 0.001+ },+ {+ "step": 7,+ "loss": 1.7619656324386597,+ "grad_norm": 54.54685592651367,+ "learning_rate": 0.001+ },+ {+ "step": 8,+ "loss": 0.17636960744857788,+ "grad_norm": 17.216157913208008,+ "learning_rate": 0.001+ },+ {+ "step": 9,+ "loss": 1.795599341392517,+ "grad_norm": 48.85170364379883,+ "learning_rate": 0.001+ },+ {+ "step": 10,+ "loss": 0.08708081394433975,+ "grad_norm": 11.202317237854004,+ "learning_rate": 0.001+ }+ ],+ "environment": {+ "python": "3.12.13",+ "torch": "2.10.0+cu128",+ "cuda": "12.8",+ "platform": "Linux-6.12.90+-x86_64-with-glibc2.35",+ "transformers": "5.5.0",+ "trl": "0.24.0",+ "unsloth": "2026.8.12",+ "gpu_name": "Tesla T4",+ "gpu_capability": "sm_75",+ "gpu_total_gb": 14.6,+ "gpu_count_visible": 1,+ "driver_cuda": "12.8"+ },+ "config": {+ "max_steps": 10,+ "dataset_digest": "847095f51df8d86429cd2cd095824369d6d95c36bd461c363599651d356946df",+ "batch_size": 2,+ "grad_accum": 1,+ "max_seq_length": 512,+ "learning_rate": 0.001,+ "lora_r": 16,+ "lora_alpha": 32,+ "optim": "adamw_8bit",+ "gradient_checkpointing": "unsloth",+ "repeat": 2+ },+ "model": "unsloth/Qwen2.5-0.5B-Instruct",+ "source_kernel": "danielhanchen/unsloth-t4-ci-e3c6661f"+}\ No newline at end of filediff --git a/tests/kaggle/t4_smoke/run_gptoss_t4.py b/tests/kaggle/t4_smoke/run_gptoss_t4.pynew file mode 100644index 00000000000..95710f3930e--- /dev/null+++ b/tests/kaggle/t4_smoke/run_gptoss_t4.py@@ -0,0 +1,714 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""gpt-oss-20b LoRA on a single T4: does the compile-and-offload path hold?++The payload behind the `gptoss` leg, written first as a FEASIBILITY PROBE. The+question is not "is the loss right" but "can a 20B checkpoint be loaded,+LoRA-trained and generated from at all on 16GB of sm_75, on the compiled float32+path this card forces".++What the probe found, so the report can be read against it: kernels+`unsloth-t4-ci-8161ceb9` and `unsloth-t4-ci-7ab727f1`, 2026-08-11, Tesla T4 /+sm_75 / 14.56 GB. It works, and three of the four things likeliest to break are+not in the path at all.++* **MXFP4 is never reached.** `unsloth/gpt-oss-20b` is an MXFP4 checkpoint and+ MXFP4 has no backward pass in unsloth_zoo, but `load_in_4bit=True` makes+ Unsloth's FLOAT_TO_INT_MAPPER redirect the load to the NF4+ `unsloth/gpt-oss-20b-unsloth-bnb-4bit`. The probe confirmed the redirect from+ `model.config._name_or_path`, recorded on every run: a change to that mapping+ would move this leg onto a checkpoint that cannot train unnoticed.+* **No bf16, and Unsloth already knows.** gpt-oss is in `FORCE_FLOAT32`. The+ probe saw `UNSLOTH_FORCE_FLOAT32=1`, `fp16=False`, `bf16=False`, and+ `UNSLOTH_FORCE_CUSTOM_DTYPE` pinning `down_projs` and `mlp.router` to float32.+ That path exists for this card and nothing else in CI exercises it.+* **No offload.** 12.78 GB reserved of 14.56, every parameter on `cuda:0`, no+ `hf_device_map`. About 1.8 GB of headroom, thin enough that placement is+ counted on every run rather than assumed -- and asserted, since a run that+ offloads passes everything else.+* **torch.compile engages**: 32 unique graphs, 779 calls captured, 2 graph+ breaks, both `_warnings.warn`. A silent fall back to eager leaves every other+ number healthy while the leg's coverage goes unexercised, so this is asserted.++What it asserts:++1. The model loads, in a recorded dtype, with every parameter on the one+ visible T4. Offload to CPU, disk or meta is a FAILURE rather than a slow+ pass: it is the documented result of this leg (a 20B checkpoint fitting and+ training on 16GB, with about 1.8GB to spare) ceasing to hold, and every other+ number in the report survives it.+2. Training runs the requested steps, every logged loss is finite, and the+ optimizer applied something -- a run with all-zero gradients looks healthy+ everywhere else and trained nothing. Decided on the ADAPTER, fingerprinted+ before and after training, with `grad_norm` as fallback rather than source:+ this leg saves and reloads no adapter, so a trainer that stops logging that+ field would otherwise take the only evidence with it. See+ training_evidence.py. There is no committed reference band, the run being too+ short and the model too large for a per-step trace to be worth capturing, and+ a band nobody can recapture cheaply gets disabled the first time it is+ inconvenient.+2a. The forced-float32 path was taken: on a card without bf16, `fp16`/`bf16`+ must both be off and `UNSLOTH_FORCE_FLOAT32` must be set. This is the+ coverage the leg uniquely claims, and it was recorded on every run and+ asserted on none.+3. `torch.compile` captured at least one graph DURING TRAINING+ (`--require-compile`, on by default). The Dynamo counters are process-global+ and loading a 20B checkpoint fills them, so the assertion is on the delta+ across `trainer.train()`, not the total.+4. Generation after training returns non-empty text without raising, catching a+ training run that "succeeds" and leaves the model unusable, which on a+ quantised offloaded path is a real outcome.++`--probe` records all of those and fails on none, for the one-off feasibility+runs: a probe must come back with evidence, not a nonzero exit and a truncated+report.+"""++from __future__ import annotations++import argparse+import json+import os+import platform+import sys+import time+import traceback+from pathlib import Path++_HERE = Path(__file__).resolve().parent+if str(_HERE) not in sys.path:+ sys.path.insert(0, str(_HERE))++from training_evidence import ( # noqa: E402+ adapter_fingerprint,+ adapter_update,+ update_verdict,+)+from versions import ( # noqa: E402+ GOAL_PACKAGES,+ flatten_versions,+ resolved_versions,+)++CANARY = "__UNSLOTH__!!!"+SEED = 3407++DEFAULT_MODEL = "unsloth/gpt-oss-20b"+++def _log(msg: str) -> None:+ print(f"[gptoss-t4] {msg}", flush = True)+++def compile_counters(before: dict | None = None) -> dict:+ """What `torch.compile` actually did, from Dynamo's own bookkeeping.++ `unique_graphs` decides whether compilation engaged: zero means every region+ fell back to eager, whatever the banner said. `graph_breaks` sits beside it+ because capturing graphs and breaking a hundred times is a different,+ reportable state, and on a card with no bf16 a break is often the first+ symptom of a dtype the compiled path refused.++ The counters are process-global and never reset, and loading a model through+ Unsloth compiles plenty before `trainer.train()`, so the absolute number+ cannot answer "did TRAINING compile": an entirely eager training path still+ leaves the loader's graphs standing. Pass the pre-training reading as+ ``before`` and the delta is the answer; `failures_for` asserts on the delta.+ """+ state: dict = {"available": False}+ try:+ import torch._dynamo.utils as dynamo_utils++ counters = dynamo_utils.counters+ stats = dict(counters.get("stats", {}))+ breaks = dict(counters.get("graph_break", {}))+ state = {+ "available": True,+ "unique_graphs": int(stats.get("unique_graphs", 0)),+ "calls_captured": int(stats.get("calls_captured", 0)),+ "graph_breaks_total": sum(int(v) for v in breaks.values()),+ # Truncated: free text, and a pathological run produces hundreds.+ "graph_break_reasons": sorted(breaks)[:10],+ }+ except Exception as exc: # noqa: BLE001+ state = {"available": False, "error": f"{type(exc).__name__}: {exc}"}+ if before and before.get("available") and state.get("available"):+ for key in ("unique_graphs", "calls_captured", "graph_breaks_total"):+ state[f"{key}_delta"] = state[key] - int(before.get(key, 0))+ state["before"] = {+ k: before.get(k) for k in ("unique_graphs", "calls_captured", "graph_breaks_total")+ }+ return state+++def placement(model) -> dict:+ """Where the weights ended up, counted rather than trusted.++ A 20B checkpoint on a 16GB card either offloads or does not fit, and "did it+ offload" is answerable only by looking. `hf_device_map` is the+ accelerate-side answer and is absent when nothing dispatched; the parameter+ walk is always available and is what distinguishes a model that quietly+ landed on the CPU (correct, slow) from one on meta (loaded nothing).+ """+ counts: dict = {}+ try:+ for param in model.parameters():+ key = str(param.device)+ counts[key] = counts.get(key, 0) + param.numel()+ except Exception as exc: # noqa: BLE001+ counts = {"error": f"{type(exc).__name__}: {exc}"}+ device_map = getattr(model, "hf_device_map", None)+ return {+ "parameters_by_device": counts,+ "hf_device_map_devices": (+ sorted({str(v) for v in device_map.values()}) if isinstance(device_map, dict) else None+ ),+ "offloaded": bool(+ isinstance(device_map, dict)+ and any(str(v) in ("cpu", "disk") for v in device_map.values())+ ),+ }+++def memory() -> dict:+ import torch++ if not torch.cuda.is_available():+ return {}+ props = torch.cuda.get_device_properties(0)+ return {+ "peak_reserved_gb": round(torch.cuda.max_memory_reserved() / 1024**3, 2),+ "peak_allocated_gb": round(torch.cuda.max_memory_allocated() / 1024**3, 2),+ "total_gb": round(props.total_memory / 1024**3, 2),+ }+++def build_dataset(tokenizer, rows: list[dict]):+ """The canary rows as chat turns, through the model's own template.++ Through `apply_chat_template` rather than a hand-rolled prompt: gpt-oss has+ a template with channels and a reasoning-effort knob, and bypassing it would+ exercise a text format no user of this notebook ever produces.+ """+ from datasets import Dataset++ texts = []+ for row in rows:+ texts.append(+ tokenizer.apply_chat_template(+ [+ {"role": "user", "content": row["question"]},+ {"role": "assistant", "content": row["answer"]},+ ],+ tokenize = False,+ add_generation_prompt = False,+ )+ )+ return Dataset.from_dict({"text": texts})+++def train_and_infer(args) -> dict:+ import torch+ from unsloth import FastLanguageModel++ result: dict = {}++ t0 = time.time()+ model, tokenizer = FastLanguageModel.from_pretrained(+ model_name = args.model,+ dtype = None, # let the loader choose; T4 has no bf16+ max_seq_length = args.max_seq_length,+ load_in_4bit = True,+ full_finetuning = False,+ )+ result["load_seconds"] = round(time.time() - t0, 1)+ result["model_dtype"] = str(getattr(model, "dtype", None))+ # What was REALLY loaded. `unsloth/gpt-oss-20b` is MXFP4, which has no+ # backward pass at all (unsloth_zoo raises "Backwards pass using MXFP4 is+ # still under construction"), so load_in_4bit=True makes Unsloth's+ # FLOAT_TO_INT_MAPPER redirect to the NF4+ # `unsloth/gpt-oss-20b-unsloth-bnb-4bit`, which does train. The config name+ # is therefore not the name asked for, and a change to that redirect would+ # silently move this leg onto a path that cannot train.+ model_config = getattr(model, "config", None)+ result["resolved_checkpoint"] = getattr(model_config, "_name_or_path", None)+ quant = getattr(model_config, "quantization_config", None)+ result["quantization"] = (+ {+ "method": str(getattr(quant, "quant_method", None)),+ "type": str(getattr(quant, "bnb_4bit_quant_type", None)),+ }+ if quant is not None+ else None+ )+ result["placement_after_load"] = placement(model)+ result["memory_after_load"] = memory()+ _log(f"loaded in {result['load_seconds']}s, dtype {result['model_dtype']}")++ model = FastLanguageModel.get_peft_model(+ model,+ r = args.lora_r,+ target_modules = [+ "q_proj",+ "k_proj",+ "v_proj",+ "o_proj",+ "gate_proj",+ "up_proj",+ "down_proj",+ ],+ lora_alpha = args.lora_r * 2,+ lora_dropout = 0,+ bias = "none",+ use_gradient_checkpointing = "unsloth",+ random_state = SEED,+ )++ rows = [+ json.loads(line)+ for line in Path(args.dataset).read_text(encoding = "utf-8").splitlines()+ if line.strip()+ ]+ dataset = build_dataset(tokenizer, rows)++ from trl import SFTConfig, SFTTrainer++ config = SFTConfig(+ output_dir = str(Path(args.outdir) / "trainer"),+ dataset_text_field = "text",+ per_device_train_batch_size = 1,+ gradient_accumulation_steps = 1,+ max_length = args.max_seq_length,+ max_steps = args.max_steps,+ learning_rate = 2e-4,+ warmup_steps = 0,+ lr_scheduler_type = "constant",+ logging_steps = 1,+ optim = "adamw_8bit",+ weight_decay = 0.0,+ seed = SEED,+ data_seed = SEED,+ # fp16/bf16 are deliberately NOT set, the opposite of the tiny SFT+ # payload. gpt-oss is in Unsloth's FORCE_FLOAT32 list: on a card without+ # bf16 the loader sets UNSLOTH_FORCE_FLOAT32=1 and the RL/SFT patch+ # switches to float32 ("Unsloth: Switching to float32 training since+ # model cannot work with float16"), because fp16 autocast through the+ # MXFP4-derived weights produces infinities. Asking for fp16 would fight+ # that patch, and whichever won, the run would not be the one a notebook+ # user gets. What was chosen is recorded below.+ dataloader_num_workers = 0,+ dataloader_pin_memory = False,+ report_to = "none",+ save_strategy = "no",+ )+ trainer = SFTTrainer(+ model = model,+ processing_class = tokenizer,+ train_dataset = dataset,+ args = config,+ )++ # The precision after Unsloth's patches have had their say. On a T4 this+ # should be float32 and NOT fp16; fp16 here means FORCE_FLOAT32 stopped+ # firing and the infinities it prevents are back.+ result["precision"] = {+ "fp16": bool(getattr(trainer.args, "fp16", None)),+ "bf16": bool(getattr(trainer.args, "bf16", None)),+ "force_float32_env": os.environ.get("UNSLOTH_FORCE_FLOAT32"),+ "custom_dtype_env": os.environ.get("UNSLOTH_FORCE_CUSTOM_DTYPE"),+ }+ _log(f"precision {json.dumps(result['precision'])}")++ # The counters BEFORE training, so what training compiled is a subtraction+ # rather than an inference: loading a 20B checkpoint through Unsloth+ # compiles a great deal into the same process-global counter.+ compile_before = compile_counters()+ _log(f"compile counters before training: {json.dumps(compile_before)}")++ # The adapter before a single step, so "did the optimizer apply anything" is+ # a subtraction rather than a reading of what the trainer chose to log. This+ # leg saves and reloads no adapter, so without it the only evidence is+ # grad_norm, and a trainer that stops logging it leaves the leg asserting+ # nothing. See training_evidence.py.+ adapter_before = adapter_fingerprint(model)+ _log(f"adapter before training: {json.dumps(adapter_before)}")++ t0 = time.time()+ stats = trainer.train()+ result["train_seconds"] = round(time.time() - t0, 1)+ result["metrics"] = [+ {"step": entry.get("step"), "loss": entry.get("loss"), "grad_norm": entry.get("grad_norm")}+ for entry in trainer.state.log_history+ if "loss" in entry+ ]+ result["train_metrics"] = {k: v for k, v in (stats.metrics or {}).items()}+ result["adapter_update"] = adapter_update(adapter_before, adapter_fingerprint(model))+ _log(f"adapter update: {json.dumps(result['adapter_update'])}")+ result["compile"] = compile_counters(before = compile_before)+ result["memory_after_train"] = memory()+ _log(+ f"trained {len(result['metrics'])} logged steps in "+ f"{result['train_seconds']}s; compile {result['compile']}"+ )++ # Inference in the notebook's own shape: chat template with a reasoning+ # effort, greedy decode, short.+ FastLanguageModel.for_inference(model)+ try:+ inputs = tokenizer.apply_chat_template(+ [{"role": "user", "content": rows[0]["question"]}],+ add_generation_prompt = True,+ return_tensors = "pt",+ return_dict = True,+ reasoning_effort = "low",+ ).to("cuda")+ except TypeError:+ # reasoning_effort is a gpt-oss template keyword; a template that does+ # not take it is a finding to record, not a crash.+ result["reasoning_effort_supported"] = False+ inputs = tokenizer.apply_chat_template(+ [{"role": "user", "content": rows[0]["question"]}],+ add_generation_prompt = True,+ return_tensors = "pt",+ return_dict = True,+ ).to("cuda")+ else:+ result["reasoning_effort_supported"] = True++ t0 = time.time()+ with torch.inference_mode():+ out = model.generate(+ **inputs,+ max_new_tokens = args.max_new_tokens,+ do_sample = False,+ temperature = None,+ top_p = None,+ top_k = None,+ use_cache = True,+ )+ result["infer_seconds"] = round(time.time() - t0, 1)+ generated = tokenizer.decode(out[0][inputs["input_ids"].shape[1] :], skip_special_tokens = True)+ result["generated"] = generated+ result["canary_found"] = CANARY in generated+ result["memory_peak"] = memory()+ _log(f"generated {generated!r}")+ return result+++def _placement_failures(placement: dict | None) -> list[str]:+ """Every parameter on the one visible GPU, or this leg measured something else.++ The driver gives each payload a single CUDA device+ (``CUDA_VISIBLE_DEVICES``), so on a healthy run every parameter reports+ ``cuda:0`` and ``hf_device_map`` is absent entirely. Anything else is one of+ the three ways a 20B checkpoint stops fitting: ``cpu``/``disk`` through+ accelerate's dispatch, ``meta`` for a shard that was never materialised, or+ a device the payload cannot see.++ Unreadable is a failure, not a skip, for the same reason it is one for the+ bf16 reading and the dynamo counters: the check that switches itself off+ when its instrument breaks is the one that never fires.+ """+ if not isinstance(placement, dict):+ return [+ "where the weights landed was never recorded, so whether the "+ "checkpoint fit on the GPU at all could not be established, and "+ "every other number in this report is produced either way"+ ]+ failures: list[str] = []+ counts = placement.get("parameters_by_device")+ if not isinstance(counts, dict) or not counts:+ failures.append(f"the parameter walk recorded no devices: {placement}")+ elif "error" in counts:+ failures.append(f"the parameters could not be walked: {counts['error']}")+ else:+ elsewhere = {+ device: n for device, n in counts.items() if not str(device).startswith("cuda")+ }+ if elsewhere:+ failures.append(+ f"parameters are off the GPU: {elsewhere} (all devices: {counts}). "+ f"This leg's result is that the 20B checkpoint fits and trains "+ f"wholly on one T4; a run that offloads to CPU, disk or meta is "+ f"not a slower version of that, it is a different run, and "+ f"accelerate's offload does not support training at all"+ )+ # The accelerate-side answer, which is absent on a healthy run and says+ # `cpu`/`disk` when dispatch offloaded. Three-way: `placement()` always+ # writes a bool, so anything else is a record this file cannot read.+ offloaded = placement.get("offloaded")+ if offloaded is True:+ failures.append(+ f"the loader dispatched part of the model off the GPU: "+ f"hf_device_map devices {placement.get('hf_device_map_devices')}"+ )+ elif offloaded is not False:+ failures.append(f"whether the loader offloaded could not be established: {placement}")+ return failures+++def failures_for(result: dict, args) -> list[str]:+ """The assertions, separated from the run so they can be unit-tested.++ Nothing here needs a GPU, which is the point: the pass/fail rule for a leg+ that costs a Kaggle session has to be checkable without one.+ """+ failures: list[str] = []+ metrics = result.get("metrics") or []+ if len(metrics) != args.max_steps:+ failures.append(f"expected {args.max_steps} logged steps, got " f"{len(metrics)}")+ losses = [m.get("loss") for m in metrics if m.get("loss") is not None]+ if not losses:+ failures.append("no loss was logged at all, so nothing trained")+ bad = [l for l in losses if l != l or l in (float("inf"), float("-inf"))]+ if bad:+ failures.append(f"non-finite loss: {losses}")++ # Did the optimizer apply anything? Every number above stays healthy with+ # all-zero gradients: the loss is finite, compilation engaged, and the+ # untrained base model still generates text.+ #+ # The adapter fingerprints before and after training decide it, with+ # grad_norm as fallback rather than the other way round. This USED to be+ # `if norms and not applied`, which passes on an empty list: a trainer that+ # stopped logging grad_norm silently took the only instrument this leg had,+ # and unlike the SFT leg there is no saved adapter to read back. See+ # training_evidence.py.+ update = update_verdict(metrics, result.get("adapter_update"))+ if update["verdict"] == "not_applied":+ failures.append(+ f"no optimizer update was applied: {update['detail']}, so the adapter "+ f"is the adapter it started with and this leg measured a forward pass "+ f"rather than LoRA training"+ )+ elif update["verdict"] == "non_finite":+ failures.append(+ f"the adapter holds non-finite weights after training: {update['detail']}. "+ f"gpt-oss is in the FORCE_FLOAT32 list precisely because reduced "+ f"precision through these weights produces infinities, so this is that "+ f"failure landing in the adapter rather than in the loss"+ )+ elif update["verdict"] != "applied":+ # Not `== "unverifiable"`: any verdict this file has not been taught+ # about is a failure rather than a silent pass.+ failures.append(+ f"whether the optimizer applied anything could not be established: "+ f"{update['detail']}. LoRA training on this path is the only thing "+ f"this leg claims, and the base model on its own produces every other "+ f"number in this report"+ )++ # The float32 path, the coverage this leg uniquely claims, recorded on every+ # run and asserted on none: a run that quietly went through fp16 logs finite+ # losses, compiles, generates and reports green while that path was never+ # exercised.+ #+ # Conditioned on the card, not hardcoded to T4: FORCE_FLOAT32 exists because+ # this hardware has no bf16, so on a card that has it, the patch not firing+ # is correct and a red would be this check's own bug.+ #+ # Three-way, not two-way. `is False` alone made the block conditional on a+ # reading allowed to be absent -- main() records `{"error": ...}` for the+ # whole environment when the probe raises -- so a torch build that changed+ # or failed `is_bf16_supported()` skipped this leg's one unique assertion+ # while everything else passed. Anything but a literal True or False is+ # unverifiable, and unverifiable is red here.+ environment = result.get("environment") or {}+ bf16_supported = environment.get("bf16_supported")+ if bf16_supported is not True and bf16_supported is not False:+ failures.append(+ f"the card's bf16 support was not recorded, so whether the forced "+ f"float32 path had to fire could not be established: "+ f"environment={environment}. This leg exists to cover that path on "+ f"hardware without bf16, and every other number in this report is "+ f"produced with or without it"+ )+ elif bf16_supported is False:+ precision = result.get("precision")+ if not precision:+ failures.append(+ "the training precision was never recorded, so whether the forced "+ "float32 path fired could not be established"+ )+ else:+ if precision.get("fp16") or precision.get("bf16"):+ failures.append(+ f"the run trained in reduced precision on a card without bf16: "+ f"{precision}. gpt-oss is in Unsloth's FORCE_FLOAT32 list because "+ f"fp16 autocast through these weights produces infinities, so this "+ f"is the patch having stopped firing, not a slow pass."+ )+ elif precision.get("force_float32_env") != "1":+ # The exact string, not truthiness: the loader writes "0" here+ # on its normal branch before deciding whether to force+ # (models/loader.py), so a nonempty check accepts the very+ # regression it is here to catch -- forcing off, fp16 and bf16+ # still false, leg green. Every production consumer reads+ # `== "1"`.+ failures.append(+ f'UNSLOTH_FORCE_FLOAT32 is not "1": {precision}. The loader sets '+ f'it to "0" and only writes "1" when the forcing actually fired, '+ f"and the float32 path is the only thing this leg covers that "+ f"nothing else in CI does."+ )++ # Where the weights ended up, recorded on every run since the feasibility+ # probe and asserted on none. "the 20B checkpoint fits and trains WHOLLY on+ # one T4" is the result this leg exists to hold, and it is the one that+ # degrades quietly: a loader or memory-management regression that sends+ # layers to the CPU still logs finite losses, still updates the adapter,+ # still compiles and still generates, so the leg reports green having+ # measured a different, slower thing. The probe's own margin is the reason+ # to check rather than assume -- 12.78 GB reserved of 14.56, about 1.8 GB.+ #+ # accelerate's offload is also inference-only ("This only supports+ # inference, not training" -- huggingface.co/docs/accelerate big model+ # inference), so a training run that reaches it is not a slower version of+ # this leg. It is a different one.+ failures.extend(_placement_failures(result.get("placement_after_load")))++ if args.require_compile:+ compiled = result.get("compile") or {}+ # The DELTA across training, not the process-global total, which is+ # nonzero the moment the loader compiles anything and so used to be+ # satisfied by an entirely eager training path.+ graphs = compiled.get("unique_graphs_delta")+ if not compiled.get("available"):+ failures.append(+ "torch._dynamo counters were unreadable, so whether "+ "torch.compile engaged could not be established: "+ f"{compiled.get('error')}"+ )+ elif graphs is None:+ # No baseline means no subtraction, and falling back to the absolute+ # count would assert on a number the LOADER made nonzero, turning+ # the one case where training cannot be isolated into the one most+ # likely to pass.+ failures.append(+ "the pre-training dynamo counters were not readable, so what "+ "training itself compiled cannot be separated from what loading the "+ "model compiled, and this leg requires compilation: "+ f"{compiled}"+ )+ elif graphs < 1:+ failures.append(+ "torch.compile captured zero graphs across training itself, so the "+ "training path ran eager whatever was compiled at load time. That is "+ "the silent fallback this leg exists to catch; it is a failure, not a "+ f"slow pass. Counters: {compiled}"+ )++ generated = result.get("generated")+ if generated is None:+ failures.append("generation did not run")+ elif not generated.strip():+ failures.append(+ "generation after training returned empty text, so the trained model is unusable"+ )+ return failures+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--model", default = DEFAULT_MODEL)+ ap.add_argument("--dataset", default = str(_HERE / "canary_dataset.jsonl"))+ ap.add_argument("--outdir", required = True)+ ap.add_argument("--label", default = "gptoss")+ ap.add_argument("--max-steps", type = int, default = 3)+ ap.add_argument("--max-seq-length", type = int, default = 1024)+ ap.add_argument("--lora-r", type = int, default = 8)+ ap.add_argument("--max-new-tokens", type = int, default = 32)+ ap.add_argument("--require-compile", dest = "require_compile", action = "store_true", default = True)+ ap.add_argument("--no-require-compile", dest = "require_compile", action = "store_false")+ ap.add_argument(+ "--probe",+ action = "store_true",+ help = "record everything, assert nothing. For the "+ "one-off feasibility runs, whose job is to come "+ "back with evidence rather than an exit code",+ )+ args = ap.parse_args()++ outdir = Path(args.outdir)+ outdir.mkdir(parents = True, exist_ok = True)++ report: dict = {+ "label": args.label,+ "model": args.model,+ "leg": "gptoss",+ "probe": args.probe,+ "config": {+ k: getattr(args, k)+ for k in ("max_steps", "max_seq_length", "lora_r", "max_new_tokens", "require_compile")+ },+ "versions": {},+ "environment": {},+ "failures": [],+ }++ # Versions first, before anything can crash: a payload that died in the+ # loader still has to say which library set it died with, or the crash is+ # unattributable and the session was spent for nothing.+ report["versions"] = resolved_versions(+ GOAL_PACKAGES, import_check = ("torch", "transformers", "trl")+ )+ report["versions_flat"] = flatten_versions(report["versions"])+ _log("versions " + json.dumps(report["versions_flat"]))++ try:+ import torch+ props = torch.cuda.get_device_properties(0)+ report["environment"] = {+ "python": platform.python_version(),+ "torch": torch.__version__,+ "cuda": torch.version.cuda,+ "gpu_name": props.name,+ "gpu_capability": f"sm_{props.major}{props.minor}",+ "gpu_total_gb": round(props.total_memory / 1024**3, 1),+ "gpu_count_visible": torch.cuda.device_count(),+ "bf16_supported": bool(torch.cuda.is_bf16_supported()),+ "compile_disabled_env": os.environ.get("UNSLOTH_COMPILE_DISABLE"),+ }+ except Exception as exc: # noqa: BLE001+ report["environment"] = {"error": f"{type(exc).__name__}: {exc}"}++ failures: list[str] = []+ try:+ result = train_and_infer(args)+ report.update(result)+ # The metrics key the launcher and report renderer already display, so+ # this leg needs no special case downstream.+ report["metrics"] = result.get("metrics", [])+ failures = failures_for(report, args)+ except BaseException as exc: # noqa: BLE001+ if isinstance(exc, KeyboardInterrupt):+ raise+ report["traceback"] = traceback.format_exc()[-6000:]+ failures = [f"{type(exc).__name__}: {str(exc)[:600]}"]+ _log("EXCEPTION\n" + report["traceback"])+ report["memory_peak"] = memory()+ report["compile"] = compile_counters()++ report["observed_failures"] = failures+ if args.probe:+ # A probe reports; it does not judge. A human reads the verdict off+ # observed_failures, and the leg is not wired into CI until it can be.+ report["failures"] = []+ report["passed"] = True+ else:+ report["failures"] = failures+ report["passed"] = not failures++ (outdir / "t4_smoke_report.json").write_text(+ json.dumps(report, indent = 2, default = str), encoding = "utf-8"+ )+ print("T4_SMOKE_REPORT " + json.dumps(report, default = str), flush = True)+ for entry in failures:+ _log(f"OBSERVED FAILURE: {entry}")+ _log("T4_SMOKE_RESULT " + ("PASS" if report["passed"] else "FAIL"))+ return 0 if report["passed"] else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/kaggle/t4_smoke/run_grpo_t4.py b/tests/kaggle/t4_smoke/run_grpo_t4.pynew file mode 100644index 00000000000..c4242ace2b9--- /dev/null+++ b/tests/kaggle/t4_smoke/run_grpo_t4.py@@ -0,0 +1,735 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Qwen3-4B GRPO with vLLM on a single T4: does the engine fit and generate?++The payload behind the `grpo` leg, written first as a FEASIBILITY PROBE. Two+things are genuinely in doubt on this hardware.++**Does vLLM run on sm_75 at all, at the version installed?** vLLM selects an+attention backend by compute capability, and Turing has neither FlashAttention+nor FlashInfer. It used to depend on the xformers backend, deleted in 0.12.0,+and at the version this leg installs the ladder in `vllm/platforms/cuda.py`+falls through the two unavailable ones to TRITON_ATTN. The leg names TRITON_ATTN+in `VLLM_ATTENTION_BACKEND` rather than trusting that order, so a release that+reorders or drops it goes red instead of silently substituting. None of this+fails at install or import time; it fails when the engine is constructed, deep+inside platform selection, so the resolved vLLM version, the backends the build+offers, the backend selected and the construction outcome are recorded+separately.++**Does it fit?** The notebook this leg comes from sets `load_in_4bit=False`,+roughly 8GB of 16-bit weights, and then asks a vLLM engine at+`gpu_memory_utilization=0.9` and a LoRA training loop to share one 16GB card.+`--load-in-4bit` is therefore a first-class switch, and peak reserved and+allocated memory are reported for whichever setting ran.++What it asserts, and what it deliberately does not:++**Not the loss.** With `num_iterations=1` and `beta=0.0` the TRL GRPO objective+is zero by construction on a healthy run -- the policy that generated the+completions is the one being updated, so the importance ratio is exactly 1, and+with no KL term the loss cancels. A check on it would always pass or fire on+arithmetic noise, so it is recorded and never asserted.++**Reward, reward_std and the completions instead.**++* `reward` must be logged and finite on every step. Absent means the reward+ functions never ran, so generation produced nothing.+* `reward_std` must be non-zero on at least one step. Zero across a group means+ every completion scored identically, which in practice means they were+ IDENTICAL: a sampler ignoring its temperature, a seed applied per-completion+ instead of per-group, or an engine returning the same cached text N times. The+ gradient is exactly zero then, so training "succeeds" while learning nothing+ and no other number moves.+* At least one completion must be non-empty, and the completions seen are+ captured and reported: an engine returning N empty strings scores them all the+ same, so the reward checks alone would call that clean.+* The optimizer must have applied something. Under fp16 here every step can+ overflow and be skipped while loss, reward and reward_std are still logged.+ Decided on the LoRA weights, fingerprinted before and after training, with+ `grad_norm` as fallback so a TRL version that stops logging it cannot take the+ assertion with it. See training_evidence.py.+* The final `fast_generate` runs with the TRAINED adapter, transferred in with+ `save_lora` + `load_lora`. `lora_request=None` reads the base weights and+ passes whether or not the adapter can reach vLLM, which is the second of the+ two questions above.++`--probe` records everything and asserts nothing, for the one-off feasibility+runs.+"""++from __future__ import annotations++import argparse+import json+import os+import platform+import sys+import time+import traceback+from pathlib import Path++_HERE = Path(__file__).resolve().parent+if str(_HERE) not in sys.path:+ sys.path.insert(0, str(_HERE))++from training_evidence import ( # noqa: E402+ adapter_fingerprint,+ adapter_update,+ update_verdict,+)+from versions import ( # noqa: E402+ GOAL_PACKAGES,+ flatten_versions,+ resolved_versions,+)++SEED = 3407+DEFAULT_MODEL = "unsloth/Qwen3-4B-Base"++SYSTEM_PROMPT = "You are given a question. Answer it as briefly as you can."++# Every completion the reward functions were shown, in order. A module global+# rather than a closure because TRL calls those functions itself and hands back+# only the scores, which would otherwise be the sole record of what was+# produced.+SEEN_COMPLETIONS: list[list[str]] = []+++def _log(msg: str) -> None:+ print(f"[grpo-t4] {msg}", flush = True)+++def _texts(completions) -> list[str]:+ """TRL hands completions back as plain strings or as chat turns."""+ out = []+ for completion in completions:+ if isinstance(completion, str):+ out.append(completion)+ elif isinstance(completion, list) and completion:+ out.append(str(completion[0].get("content", "")))+ else:+ out.append("")+ return out+++def reward_length(completions, **kwargs) -> list[float]:+ """Longer completions score higher, saturating at 200 characters.++ Deterministic given the text, yet SENSITIVE to a group's diversity: a+ constant reward would zero `reward_std` on a healthy run and destroy the+ only instrument this leg has.+ """+ texts = _texts(completions)+ SEEN_COMPLETIONS.append(texts)+ return [min(len(t), 200) / 200.0 for t in texts]+++def reward_digit(completions, **kwargs) -> list[float]:+ """A second, differently shaped signal, so `reward` is not one function.++ One broken reward function looks exactly like a broken generation path; two+ disagreeing sources make that distinguishable in the report.+ """+ return [1.0 if any(c.isdigit() for c in t) else 0.0 for t in _texts(completions)]+++def memory() -> dict:+ import torch++ if not torch.cuda.is_available():+ return {}+ props = torch.cuda.get_device_properties(0)+ return {+ "peak_reserved_gb": round(torch.cuda.max_memory_reserved() / 1024**3, 2),+ "peak_allocated_gb": round(torch.cuda.max_memory_allocated() / 1024**3, 2),+ "total_gb": round(props.total_memory / 1024**3, 2),+ }+++def vllm_facts() -> dict:+ """Which vLLM, and which attention backend it would choose here.++ Recorded BEFORE the engine is built, so a payload that dies constructing it+ still says what it was trying to construct. The backend comes from vLLM's+ own selector where reachable and from the environment override otherwise;+ both are reported, since an override silently deciding it is worth seeing.+ """+ facts: dict = {"env_override": os.environ.get("VLLM_ATTENTION_BACKEND")}+ try:+ import vllm+ facts["version"] = getattr(vllm, "__version__", "unknown")+ except BaseException as exc: # noqa: BLE001+ facts["version"] = None+ facts["import_error"] = f"{type(exc).__name__}: {str(exc)[:300]}"+ return facts+ try:+ from vllm.platforms import current_platform+ facts["platform"] = str(current_platform.device_name)+ facts["capability"] = str(current_platform.get_device_capability())+ except Exception as exc: # noqa: BLE001+ facts["platform_error"] = f"{type(exc).__name__}: {str(exc)[:200]}"+ # The backend enum has moved between releases, and its absence is a finding+ # rather than a crash. Both names are recorded, not asserted: at the version+ # this leg installs, xformers is EXPECTED missing and TRITON_ATTN is where+ # the ladder should land, so which world we are in is answerable from the+ # report alone.+ for path in (+ "vllm.attention.backends.registry",+ "vllm.attention.selector",+ "vllm.platforms.interface",+ ):+ try:+ module = __import__(path, fromlist = ["*"])+ except Exception: # noqa: BLE001+ continue+ backends = getattr(module, "_Backend", None) or getattr(module, "Backend", None)+ if backends is not None:+ names = sorted(getattr(b, "name", str(b)) for b in backends)+ facts["backend_enum_source"] = path+ facts["backends_available"] = names+ facts["xformers_backend_present"] = any("XFORMERS" in n.upper() for n in names)+ facts["triton_attn_backend_present"] = any("TRITON_ATTN" in n.upper() for n in names)+ facts["requested_backend"] = os.environ.get("VLLM_ATTENTION_BACKEND", "")+ break+ return facts+++def build_dataset(rows: list[dict]):+ from datasets import Dataset+ return Dataset.from_dict(+ {+ "prompt": [+ [+ {"role": "system", "content": SYSTEM_PROMPT},+ {"role": "user", "content": row["question"]},+ ]+ for row in rows+ ],+ "answer": [row["answer"] for row in rows],+ }+ )+++def train(args, report: dict | None = None) -> dict:+ """One GRPO cycle. Writes progress into ``report`` as it goes.++ The second argument makes the feasibility verdict survive a crash.+ Everything used to be returned at the end, so an exception after the engine+ was built threw away the fact that it HAD been, and the report said+ `engine_built: false` -- the opposite of what happened, and the exact+ distinction this probe draws between "vLLM cannot start on sm_75" and "vLLM+ started and GRPO failed later". Facts are published as soon as known.+ """+ import torch+ from unsloth import FastLanguageModel++ result: dict = {}+ if report is None:+ report = {}++ def record(key, value):+ result[key] = value+ report[key] = value++ t0 = time.time()+ model, tokenizer = FastLanguageModel.from_pretrained(+ model_name = args.model,+ max_seq_length = args.max_seq_length,+ load_in_4bit = args.load_in_4bit,+ fast_inference = True,+ max_lora_rank = args.lora_rank,+ gpu_memory_utilization = args.gpu_memory_utilization,+ )+ record("load_seconds", round(time.time() - t0, 1))+ record("engine_built", True)++ # `unsloth/Qwen3-4B-Base` is a BASE model and ships no chat template, so+ # TRL's `maybe_apply_chat_template` raises on the first training step:+ #+ # ValueError: Cannot use chat template functions because+ # tokenizer.chat_template is not set+ #+ # Measured on kernel unsloth-t4-ci-27b0dc2e, the first probe to get that far+ # (the vLLM engine had built and the trainer was inside `_run_epoch`). The+ # notebook solves this with an SFT priming stage that installs a template+ # before GRPO; this leg has no priming stage, so it sets a minimal ChatML+ # template directly.+ #+ # The base model is the RIGHT choice and is not what to change: GRPO on an+ # instruct model would measure the instruct tuning as much as the run, and+ # these format-and-digit rewards are learnable inside three steps.+ if not getattr(tokenizer, "chat_template", None):+ tokenizer.chat_template = (+ "{% for message in messages %}"+ "{{ '<|im_start|>' + message['role'] + '\n' + message['content'] + "+ "'<|im_end|>\n' }}"+ "{% endfor %}"+ "{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"+ )+ result["chat_template"] = "set by the payload (base model ships none)"+ else:+ result["chat_template"] = "shipped with the tokenizer"+ _log("chat template: " + result["chat_template"])+ result["memory_after_load"] = memory()+ _log(f"loaded in {result['load_seconds']}s, memory {result['memory_after_load']}")++ model = FastLanguageModel.get_peft_model(+ model,+ r = args.lora_rank,+ target_modules = [+ "q_proj",+ "k_proj",+ "v_proj",+ "o_proj",+ "gate_proj",+ "up_proj",+ "down_proj",+ ],+ lora_alpha = args.lora_rank * 2,+ use_gradient_checkpointing = "unsloth",+ random_state = SEED,+ )++ rows = [+ json.loads(line)+ for line in Path(args.dataset).read_text(encoding = "utf-8").splitlines()+ if line.strip()+ ]+ dataset = build_dataset(rows)++ from trl import GRPOConfig, GRPOTrainer++ config = GRPOConfig(+ output_dir = str(Path(args.outdir) / "trainer"),+ temperature = 1.0,+ learning_rate = 5e-6,+ weight_decay = 0.001,+ warmup_steps = 0,+ lr_scheduler_type = "constant",+ optim = "adamw_8bit",+ logging_steps = 1,+ per_device_train_batch_size = args.num_generations,+ gradient_accumulation_steps = 1,+ num_generations = args.num_generations,+ max_prompt_length = args.max_prompt_length,+ max_completion_length = args.max_seq_length - args.max_prompt_length,+ max_steps = args.max_steps,+ seed = SEED,+ fp16 = True,+ bf16 = False,+ report_to = "none",+ save_strategy = "no",+ )+ trainer = GRPOTrainer(+ model = model,+ processing_class = tokenizer,+ reward_funcs = [reward_length, reward_digit],+ args = config,+ train_dataset = dataset,+ )++ # The adapter before a single step, so whether the optimizer applied+ # anything is a subtraction rather than a reading of what TRL chose to log.+ # Under fp16 here every step can overflow and be skipped while loss, reward+ # and reward_std are still logged, and grad_norm was the only field that+ # used to say so. See training_evidence.py.+ adapter_before = adapter_fingerprint(model)+ _log(f"adapter before training: {json.dumps(adapter_before)}")++ t0 = time.time()+ trainer.train()+ result["train_seconds"] = round(time.time() - t0, 1)+ result["adapter_update"] = adapter_update(adapter_before, adapter_fingerprint(model))+ _log(f"adapter update: {json.dumps(result['adapter_update'])}")+ result["log_history"] = [+ {+ k: v+ for k, v in entry.items()+ if k+ in (+ "step",+ "loss",+ "reward",+ "reward_std",+ "kl",+ "completions/mean_length",+ "frac_reward_zero_std",+ )+ or k.startswith("rewards/")+ }+ for entry in trainer.state.log_history+ ]+ # The shape the launcher and summary renderer already understand.+ result["metrics"] = [+ {"step": entry.get("step"), "loss": entry.get("loss"), "grad_norm": entry.get("grad_norm")}+ for entry in trainer.state.log_history+ if "loss" in entry+ ]+ result["completions"] = SEEN_COMPLETIONS[: args.max_steps * 2]+ result["memory_peak"] = memory()+ _log(f"trained in {result['train_seconds']}s; log {json.dumps(result['log_history'])[:1500]}")++ # Generation through the vLLM path after training. `fast_generate` is what+ # the notebook uses and is a different code path from the trainer's own+ # rollouts, so a failure here is not covered above.+ #+ # WITH the trained adapter: `fast_generate` is the engine's own generate,+ # and the trained LoRA reaches it only through a lora_request built by+ # `save_lora` + `load_lora`. Passing None generates from the base weights+ # and passes whether or not the adapter can be transferred at all, which is+ # the second question this leg answers, so the request is built, recorded,+ # and asserted on in `failures_for`.+ lora_state: dict = {"requested": True, "applied": False}+ lora_request = None+ try:+ lora_dir = str(Path(args.outdir) / "grpo_lora")+ model.save_lora(lora_dir)+ lora_request = model.load_lora(lora_dir)+ lora_state.update(applied = lora_request is not None, path = lora_dir)+ if lora_request is None:+ lora_state["error"] = "load_lora returned None"+ except BaseException as exc: # noqa: BLE001+ lora_state["error"] = f"{type(exc).__name__}: {str(exc)[:400]}"+ record("fast_generate_lora", lora_state)++ try:+ from vllm import SamplingParams++ params = SamplingParams(temperature = 1.0, top_k = 50, max_tokens = 32, seed = SEED)+ out = model.fast_generate(+ [rows[0]["question"]], sampling_params = params, lora_request = lora_request+ )+ result["fast_generate"] = out[0].outputs[0].text+ except BaseException as exc: # noqa: BLE001+ result["fast_generate"] = None+ result["fast_generate_error"] = f"{type(exc).__name__}: {str(exc)[:400]}"++ del trainer, model+ import gc++ gc.collect()+ if torch.cuda.is_available():+ torch.cuda.empty_cache()+ return result+++def failures_for(result: dict, args) -> list[str]:+ """The GRPO assertions. See this file's docstring for why not the loss."""+ failures: list[str] = []+ history = result.get("log_history") or []+ # The training steps, not every row: `train()` appends a summary entry with+ # the run totals and no loss, which is not a step.+ steps = [e for e in history if "loss" in e]+ rewards = [e["reward"] for e in history if e.get("reward") is not None]+ if not rewards:+ failures.append(+ "no reward was logged on any step, so the reward functions never "+ "ran and generation produced nothing to score"+ )+ elif any(r != r or r in (float("inf"), float("-inf")) for r in rewards):+ failures.append(f"non-finite reward: {rewards}")+ else:+ # ON EVERY STEP, as this file's docstring claims. Any nonempty subset+ # used to satisfy it, so a step whose reward functions never ran was+ # filtered out and the rest covered for it.+ missing = [e.get("step") for e in steps if e.get("reward") is None]+ if missing:+ failures.append(+ f"the reward functions did not run on every step: no reward was "+ f"logged for step(s) {missing} of {len(steps)}. A reward on some "+ f"steps is not the invariant this leg asserts."+ )++ stds = [e["reward_std"] for e in history if e.get("reward_std") is not None]+ if not stds:+ failures.append("reward_std was never logged, so group diversity could not be established")+ elif not any(s > 0 for s in stds):+ failures.append(+ f"reward_std was zero on every step ({stds}): every completion in "+ f"each group scored identically, which means the group was not "+ f"diverse. The GRPO advantage is exactly zero in that state, so "+ f"the run trained on nothing while reporting a healthy loss."+ )++ seen = result.get("completions") or []+ flat = [text for group in seen for text in group]+ if not flat:+ failures.append("no completion was ever produced")+ elif not any(t.strip() for t in flat):+ failures.append(+ f"every one of the {len(flat)} completions was empty, so the "+ f"identical rewards above are not evidence of anything"+ )++ metrics = result.get("metrics") or []+ if len(metrics) != args.max_steps:+ failures.append(f"expected {args.max_steps} logged steps, got {len(metrics)}")++ # Under fp16 here every step can overflow and be skipped while loss, reward+ # and reward_std are still logged and base-model generation still returns+ # text, so the length check above is satisfied by a run that applied no+ # optimizer update at all.+ #+ # Decided on the adapter itself, with grad_norm as fallback. The earlier+ # spelling `if norms and not applied` passes on an EMPTY list: a TRL version+ # that stops logging grad_norm removes the only instrument this leg had, and+ # it saves no adapter to read back either. See training_evidence.py.+ update = update_verdict(metrics, result.get("adapter_update"))+ if update["verdict"] == "not_applied":+ failures.append(+ f"no optimizer update was applied: {update['detail']}. The fp16 scaler "+ f"skips the step it overflowed on, so this run generated, scored and "+ f"updated nothing."+ )+ elif update["verdict"] == "non_finite":+ failures.append(+ f"the adapter holds non-finite weights after training: {update['detail']}. "+ f"An optimizer step landed and produced NaN or infinity, which is a "+ f"broken run rather than an untrained one, and generation still returns "+ f"text either way."+ )+ elif update["verdict"] != "applied":+ # Not `== "unverifiable"`: any verdict this file has not been taught+ # about is a failure rather than a silent pass.+ failures.append(+ f"whether the optimizer applied anything could not be established: "+ f"{update['detail']}. Every other number this leg reports is produced "+ f"by generation and scoring, which the base model does on its own."+ )++ lora = result.get("fast_generate_lora")+ if lora is not None and lora.get("requested") and not lora.get("applied"):+ failures.append(+ f"the trained adapter could not be handed to the vLLM engine, so the "+ f"final generation ran on the base weights and proves nothing about "+ f"training: {lora.get('error')}"+ )++ if result.get("fast_generate") is None:+ failures.append(+ "fast_generate (the vLLM inference path the notebook uses after "+ f"training) failed: {result.get('fast_generate_error')}"+ )+ return failures+++def make_libcuda_linkable() -> dict:+ """Let the linker find `-lcuda`, so flashinfer's JIT can link what it built.++ Measured twice on real T4 sessions (kernels unsloth-t4-ci-e2d9ce9b and+ -916d5986). flashinfer 0.6.6 JIT-compiles its sampling ops on first use, and+ on Kaggle all three .cu files COMPILE cleanly for+ `-gencode=arch=compute_75,code=sm_75` -- nothing here is a Turing problem --+ and then the link dies:++ /usr/bin/ld: cannot find -lcuda++ `-L/usr/local/cuda/lib64/stubs` is already on that command line; the image+ simply ships no `libcuda.so`, only the runtime `libcuda.so.1`, a versioned+ soname the linker will not resolve `-lcuda` against. Normally the CUDA+ toolkit's driver STUB fills that gap; this image has the directory and not+ the file.++ `VLLM_USE_FLASHINFER_SAMPLER=0` was tried first and did not help, which is+ the useful part: the JIT is not reached only through the sampler, so+ switching off one consumer is whack-a-mole, while making `-lcuda` resolvable+ fixes every flashinfer op at once.++ `LIBRARY_PATH` rather than a symlink into /usr/local: gcc and ld search it+ for `-l`, it needs no root, and it cannot damage the image for anything else+ in the session. Linking against the real driver rather than a stub is+ correct, the driver being present is the whole reason a stub would have+ substituted for it.++ Returns what it did, so the report says so rather than the next reader+ inferring it from an absence of failure.+ """+ facts: dict = {"needed": False, "applied": False}+ try:+ import ctypes.util+ import subprocess++ # ONLY the directories flashinfer passes with -L. Measured on kernel+ # unsloth-t4-ci-d0d480b6: an earlier version also accepted+ # /usr/local/cuda/compat, found libcuda.so there, concluded "already+ # linkable" and did nothing, and the link failed anyway because compat+ # is not on the link command line.+ link_dirs = ["/usr/local/cuda/lib64", "/usr/local/cuda/lib64/stubs"]+ for d in link_dirs:+ if os.path.exists(os.path.join(d, "libcuda.so")):+ facts["already_linkable"] = d+ return facts+ facts["needed"] = True+ facts["searched"] = link_dirs++ # Where the real driver lives. ldconfig is authoritative; ctypes is the+ # fallback for an image with no ldconfig cache.+ real = None+ try:+ out = subprocess.run(+ ["/sbin/ldconfig", "-p"], capture_output = True, text = True, timeout = 60+ ).stdout+ for line in out.splitlines():+ if "libcuda.so.1" in line and "=>" in line:+ real = line.split("=>")[-1].strip()+ break+ except Exception:+ real = None+ if real is None or not os.path.exists(real):+ found = ctypes.util.find_library("cuda")+ real = found if found and os.path.exists(found) else None+ if real is None:+ # The compat tree is the usual place on Kaggle: useless as a -L+ # target since nothing passes it, fine as a symlink TARGET.+ for candidate in (+ "/usr/local/cuda/compat/libcuda.so",+ "/usr/local/cuda/compat/libcuda.so.1",+ ):+ if os.path.exists(candidate):+ real = candidate+ break+ if real is None:+ facts["error"] = "no libcuda.so.1 on this machine"+ return facts++ shim = os.path.join(os.environ.get("TMPDIR") or "/tmp", "unsloth_libcuda_shim")+ os.makedirs(shim, exist_ok = True)+ link = os.path.join(shim, "libcuda.so")+ if not os.path.exists(link):+ os.symlink(real, link)+ existing = os.environ.get("LIBRARY_PATH", "")+ os.environ["LIBRARY_PATH"] = f"{shim}:{existing}" if existing else shim+ facts.update(applied = True, real = real, shim = shim)+ except Exception as exc: # noqa: BLE001+ facts["error"] = f"{type(exc).__name__}: {exc}"+ return facts+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--model", default = DEFAULT_MODEL)+ ap.add_argument("--dataset", default = str(_HERE / "canary_dataset.jsonl"))+ ap.add_argument("--outdir", required = True)+ ap.add_argument("--label", default = "grpo")+ ap.add_argument("--max-steps", type = int, default = 3)+ ap.add_argument("--max-seq-length", type = int, default = 2048)+ ap.add_argument("--max-prompt-length", type = int, default = 256)+ ap.add_argument("--num-generations", type = int, default = 4)+ ap.add_argument("--lora-rank", type = int, default = 32)+ ap.add_argument("--gpu-memory-utilization", type = float, default = 0.9)+ # The switch the probe exists to decide. The notebook says False: ~8GB of+ # 16-bit weights plus an engine plus a trainer on a 16GB card.+ ap.add_argument("--load-in-4bit", dest = "load_in_4bit", action = "store_true", default = False)+ ap.add_argument("--no-load-in-4bit", dest = "load_in_4bit", action = "store_false")+ ap.add_argument("--probe", action = "store_true", help = "record everything, assert nothing")+ # An illegal memory access surfaces at whatever CUDA call synchronises next,+ # which on the first T4 GRPO run was `empty_cache()` inside vLLM standby,+ # nowhere near the faulting kernel. This makes the traceback name the real+ # launch site. It serialises every kernel, so it is diagnostic, never a+ # default.+ ap.add_argument("--cuda-launch-blocking", action = "store_true")+ args = ap.parse_args()++ if args.cuda_launch_blocking:+ # Must precede any CUDA context creation, so before this process's first+ # `import torch` rather than merely before `train()`.+ os.environ["CUDA_LAUNCH_BLOCKING"] = "1"+ os.environ["TORCH_USE_CUDA_DSA"] = "1"++ # Before anything imports vLLM: flashinfer JITs on first use and the link+ # step is what fails on this image. See the function's docstring.+ libcuda = make_libcuda_linkable()+ _log(f"libcuda link shim: {libcuda}")++ outdir = Path(args.outdir)+ outdir.mkdir(parents = True, exist_ok = True)++ report: dict = {+ "label": args.label,+ "model": args.model,+ "leg": "grpo",+ "probe": args.probe,+ "config": {+ k: getattr(args, k)+ for k in (+ "max_steps",+ "max_seq_length",+ "max_prompt_length",+ "num_generations",+ "lora_rank",+ "gpu_memory_utilization",+ "load_in_4bit",+ # Reported because it changes what a timing or a traceback+ # means.+ "cuda_launch_blocking",+ )+ },+ "failures": [],+ }+ report["versions"] = resolved_versions(+ GOAL_PACKAGES, import_check = ("torch", "transformers", "trl", "vllm")+ )+ report["versions_flat"] = flatten_versions(report["versions"])+ _log("versions " + json.dumps(report["versions_flat"]))+ report["libcuda_shim"] = libcuda+ report["vllm"] = vllm_facts()+ _log("vllm " + json.dumps(report["vllm"]))++ try:+ import torch+ props = torch.cuda.get_device_properties(0)+ report["environment"] = {+ "python": platform.python_version(),+ "torch": torch.__version__,+ "cuda": torch.version.cuda,+ "gpu_name": props.name,+ "gpu_capability": f"sm_{props.major}{props.minor}",+ "gpu_total_gb": round(props.total_memory / 1024**3, 1),+ "gpu_count_visible": torch.cuda.device_count(),+ "bf16_supported": bool(torch.cuda.is_bf16_supported()),+ "vllm_standby": os.environ.get("UNSLOTH_VLLM_STANDBY"),+ }+ except Exception as exc: # noqa: BLE001+ report["environment"] = {"error": f"{type(exc).__name__}: {exc}"}++ failures: list[str] = []+ try:+ result = train(args, report)+ report.update(result)+ failures = failures_for(report, args)+ except BaseException as exc: # noqa: BLE001+ if isinstance(exc, KeyboardInterrupt):+ raise+ # Head AND tail: the last probe's 6000-char tail was entirely ninja's+ # output, dropping the Python frames that named the caller.+ _tb = traceback.format_exc()+ report["traceback"] = (+ _tb if len(_tb) <= 12000 else _tb[:6000] + "\n...[middle elided]...\n" + _tb[-6000:]+ )+ report["engine_built"] = report.get("engine_built", False)+ failures = [f"{type(exc).__name__}: {str(exc)[:600]}"]+ _log("EXCEPTION\n" + report["traceback"])+ report["memory_peak"] = memory()++ report["observed_failures"] = failures+ if args.probe:+ report["failures"] = []+ report["passed"] = True+ else:+ report["failures"] = failures+ report["passed"] = not failures++ (outdir / "t4_smoke_report.json").write_text(+ json.dumps(report, indent = 2, default = str), encoding = "utf-8"+ )+ print("T4_SMOKE_REPORT " + json.dumps(report, default = str), flush = True)+ for entry in failures:+ _log(f"OBSERVED FAILURE: {entry}")+ _log("T4_SMOKE_RESULT " + ("PASS" if report["passed"] else "FAIL"))+ return 0 if report["passed"] else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/kaggle/t4_smoke/run_t4_smoke.py b/tests/kaggle/t4_smoke/run_t4_smoke.pynew file mode 100644index 00000000000..6908c798673--- /dev/null+++ b/tests/kaggle/t4_smoke/run_t4_smoke.py@@ -0,0 +1,1596 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Deterministic Unsloth training smoke test, sized for a single Tesla T4.++Runs the whole notebook shape end to end -- 4-bit load, LoRA attach, a handful+of training steps, adapter save, reload-free inference -- against a tiny model+on ONE GPU, and asserts on what came out.++Every other GPU test in this repo runs on hardware nobody's Colab session has.+T4 is the card the notebooks are written for: no bf16, no flash-attention 2,+16GB, sm_75, so a regression that only shows up there is invisible to the rest+of CI. Driven from ``.github/workflows/kaggle-t4-notebook-ci.yml`` on real+Kaggle T4s.++What it asserts, in descending order of confidence:++1. **Run-to-run bitwise equality** (``--repeat 2``). Two full runs in one+ session must produce identical per-step loss and grad_norm to the last bit.+ The only exact assertion, and it catches uninitialised memory, unseeded RNG,+ iteration over a set, a nondeterministic kernel new to the backward pass.+2. **The canary string.** The training data maps a question to the literal+ target ``__UNSLOTH__!!!``, and after overfitting, greedy decoding of a+ training prompt must emit that and nothing else. An exact match modulo+ surrounding whitespace, not a substring: the completion trained on is+ ``CANARY + eos_token``, so ``'__UNSLOTH__!!!<more text>'`` is a stopping+ regression rather than a pass. The written adapter is also read back off disk+ and checked for tensors present, finite and not all zero, since inference+ runs on the in-memory model and would not notice. This is a binary,+ tolerance-free check that forward, backward, optimizer step, adapter save and+ inference are wired together, and it fails loudly if LoRA weights never reach+ the generate call, which no loss-value assertion would catch.+3. **Loss and grad_norm inside a band around a committed reference**, a+ tolerance and never an equality. See ``references/README.md``: the reference+ was captured on a specific T4 with a specific library set, and a different+ driver or a transformers bump moves the low bits, so the band is wide enough+ not to fire on that and narrow enough to catch a real change in the+ optimisation.++ A reference is only comparable to a run of the SAME EXPERIMENT. The step+ count is part of what the trace encodes -- step 4 of a 10-step run and of a+ 3-step run are the same iterate only by coincidence, and the fp16 scaler's+ skip pattern lives at the front where a short run spends all its steps -- and+ so are the learning rate, the optimizer, the LoRA shape, the model and the+ commit of the model repository read. The reference records all of them, and+ comparing against one captured with any of them different is a hard failure,+ never a quiet pass. See ``check_reference`` and+ ``REFERENCE_DEFINING_SETTINGS``.++Determinism caveats, stated rather than assumed:+``torch.use_deterministic_algorithms(True, warn_only=True)`` is warn_only+because parts of the bitsandbytes 4-bit path register no deterministic kernel,+and raising would abort the test having proved nothing; assertion 1 is what+verifies the outcome. Bitwise equality is asserted WITHIN one session only, and+is not achievable or claimed across GPU architectures, fp16 reduction order+alone moving the result.++Usage:+ python run_t4_smoke.py --outdir /kaggle/working/smoke0+"""++from __future__ import annotations++import argparse+import hashlib+import json+import os+import platform+import subprocess+import sys+import time+from pathlib import Path+from typing import Any++_HERE = Path(__file__).resolve().parent+if str(_HERE) not in sys.path:+ sys.path.insert(0, str(_HERE))++from determinism import ( # noqa: E402+ RepeatingSequentialSampler,+ StatisticsCallback,+ compare_metrics,+ enable_full_determinism,+ set_all_seeds_fast,+ set_deterministic_algorithms,+)+from training_evidence import LORA_B_MARKER, LORA_MARKER # noqa: E402+from versions import ( # noqa: E402+ GOAL_PACKAGES,+ flatten_versions,+ load_pins,+ pin_failures,+ resolved_versions,+ versions_for_pins,+)++# MUST run before torch is imported anywhere: CUBLAS_WORKSPACE_CONFIG is read+# when cuBLAS initialises, and setting it afterwards is silently ignored.+enable_full_determinism()++CANARY = "__UNSLOTH__!!!"+PROMPT_TEMPLATE = "### Question:\n{question}\n### Answer:\n"+SEED = 3407++# The smallest instruct model that still exercises the real loader path. It must+# fit on ONE T4 alongside a second copy of this test on the session's other T4.+DEFAULT_MODEL = "unsloth/Qwen2.5-0.5B-Instruct"+++def _log(msg: str) -> None:+ print(f"[t4-smoke] {msg}", flush = True)+++def load_canary_rows(path: Path) -> list[dict]:+ rows = [+ json.loads(line) for line in path.read_text(encoding = "utf-8").splitlines() if line.strip()+ ]+ if not rows:+ raise RuntimeError(f"canary dataset {path} is empty")+ for row in rows:+ if row.get("answer") != CANARY:+ raise RuntimeError(f"canary dataset row does not target {CANARY!r}: {row!r}")+ return rows+++def dataset_digest(path: Path) -> str:+ """A digest of the rows this run trains on, for the reference identity.++ The reference is a trace of one experiment and the training data is part of+ which experiment it is: change a question in canary_dataset.jsonl and the+ loss curve moves for reasons that have nothing to do with the code, with a+ small change passing the band and a larger one reported as a regression.+ That file is inside this workflow's paths filter, so editing it is a+ supported way to trigger the run that would be compared against a trace it+ has nothing to do with.++ Over the PARSED rows in order rather than the file's bytes: reformatting the+ JSON or reordering the keys within a row changes neither what trains nor the+ order it trains in, and forcing a session-costing recapture for whitespace+ is how a check gets switched off. Row order is kept, being the order the+ sampler walks.++ Never raises and never returns None: an unreadable dataset yields a value+ that cannot match any reference, so it lands as a refusal to compare rather+ than as an unchecked key that reads like a comparison that passed.+ """+ try:+ rows = load_canary_rows(path)+ except Exception as exc: # noqa: BLE001+ return f"unreadable:{type(exc).__name__}"+ canonical = "\n".join(json.dumps(row, sort_keys = True, separators = (",", ":")) for row in rows)+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()+++def build_dataset(rows: list[dict], eos_token: str):+ """Prompt / completion columns, so the loss lands only on the answer.++ A single ``text`` column would spread the loss across the question tokens,+ which the model already predicts well. With the prompt masked out, every one+ of the few steps this test can afford goes on the canary itself, which is+ what makes an exact string assertion reachable in a run this short. TRL+ applies the masking when it sees these two columns+ (``completion_only_loss``).+ """+ from datasets import Dataset+ return Dataset.from_dict(+ {+ "prompt": [PROMPT_TEMPLATE.format(question = r["question"]) for r in rows],+ "completion": [r["answer"] + eos_token for r in rows],+ }+ )+++def _make_trainer_class(sft_trainer_cls, sampler):+ """SFTTrainer with the sampling order pinned.++ ``_get_train_sampler``'s signature moved between TRL versions (it gained a+ dataset parameter), so absorb whatever is passed.+ """++ class _FixedOrderSFTTrainer(sft_trainer_cls): # type: ignore[misc,valid-type]+ def _get_train_sampler(self, *args, **kwargs): # noqa: ANN002, ANN003+ return sampler++ return _FixedOrderSFTTrainer+++def pin_initial_loss_scale(trainer, value: float) -> dict:+ """Lower the fp16 gradient scaler's starting scale before training.++ Why, in one measurement: the T4 has no bf16, so the run is fp16 with a+ dynamic ``GradScaler`` that starts at 65536, halves on every overflow and+ SKIPS the step it overflowed on. On this model the first three steps+ overflow every time -- the committed reference has ``grad_norm: NaN`` at+ steps 1, 2 and 3 and a finite one from step 4, which is 65536 -> 8192 in+ three halvings -- so a three-step run applies ZERO optimizer updates.++ Starting the scaler low enough not to overflow buys a short run its updates+ back. It changes the numeric path (a different scale is a different rounding+ of the same gradients), so a reference captured before this does not apply,+ which the step-count guard in ``check_reference`` already refuses to ignore.++ Never fatal. ``trainer.accelerator.scaler`` is where transformers keeps it+ but is not public API, so a version that moved it degrades to "the run is as+ it was" rather than losing the session. What happened is recorded either+ way, so whether the pin took is visible when a reference is captured.+ """+ state: dict = {"requested": value}+ if not value:+ state["applied"] = False+ state["reason"] = "not requested"+ return state+ scaler = getattr(getattr(trainer, "accelerator", None), "scaler", None)+ if scaler is None:+ state["applied"] = False+ state["reason"] = "trainer.accelerator.scaler is absent"+ return state+ if not getattr(scaler, "is_enabled", lambda: True)():+ state["applied"] = False+ state["reason"] = "the scaler is disabled (no fp16 autocast)"+ return state+ if not hasattr(scaler, "_init_scale"):+ state["applied"] = False+ state["reason"] = f"{type(scaler).__name__} has no _init_scale"+ return state+ state["before"] = float(scaler.get_scale())+ # _init_scale rather than a fresh GradScaler: the object may be a subclass+ # (ShardedGradScaler and friends) that replacing would drop. Safe because+ # training has not started, so the lazy _scale tensor does not exist and+ # get_scale() still reads _init_scale, which is how the check below can+ # confirm the pin took.+ scaler._init_scale = float(value)+ state["after"] = float(scaler.get_scale())+ state["applied"] = state["after"] == float(value)+ if not state["applied"]:+ state["reason"] = "the scaler did not take the new scale; it had already been initialised"+ return state+++def train_once(args, run_index: int) -> dict:+ """One full load / train / save / infer cycle. Returns a result dict."""+ import torch+ from unsloth import FastLanguageModel++ if args.force_sdpa:+ # LOCAL REPRODUCTION ONLY, never on the target hardware. Unsloth prefers+ # flash-attention, then xformers, then SDPA, and on a T4 that resolves+ # to xformers, the path this test exists to cover, so the flag is off by+ # default and Kaggle does not use it. It exists because xformers ships+ # no backward kernel for some newer architectures (Blackwell raises+ # NotImplementedError: No operator found for+ # memory_efficient_attention_backward), which makes the payload+ # impossible to reproduce on such a box. Forcing SDPA changes the+ # numeric path, so a local run under it is evidence about the HARNESS,+ # not about T4 numerics.+ from unsloth.utils import attention_dispatch+ attention_dispatch.HAS_XFORMERS = False+ _log("force-sdpa: HAS_XFORMERS pinned False (local repro only)")++ set_all_seeds_fast(SEED)+ det_state = set_deterministic_algorithms(warn_only = not args.strict_deterministic)++ rows = load_canary_rows(Path(args.dataset))++ t0 = time.time()+ # float16 unconditionally: T4 is sm_75 and has no bf16. Pinned rather than+ # left to the loader so the local reproduction and the Kaggle run take the+ # same numeric path wherever they can share one.+ model, tokenizer = FastLanguageModel.from_pretrained(+ model_name = args.model,+ max_seq_length = args.max_seq_length,+ load_in_4bit = True,+ dtype = torch.float16,+ )+ load_seconds = time.time() - t0+ # Which repository, and which commit of it. `load_in_4bit=True` redirects+ # through Unsloth's FLOAT_TO_INT_MAPPER, so the config name is not the name+ # asked for, and the loader explicitly DROPS `revision=` once a remap+ # happened (unsloth/models/loader.py::_revision_for_resolved_repo). Pinning+ # the load is therefore unavailable; recording what was loaded is what makes+ # a silent in-place re-upload attributable.+ _config = getattr(model, "config", None)+ resolved_checkpoint = getattr(_config, "_name_or_path", None)+ resolved_revision = getattr(_config, "_commit_hash", None)+ _log(f"loaded {resolved_checkpoint} @ {resolved_revision}")++ # Bound to a name so the saved config is checked against the adapter that+ # was actually requested, rather than against a list repeated further down.+ target_modules = [+ "q_proj",+ "k_proj",+ "v_proj",+ "o_proj",+ "gate_proj",+ "up_proj",+ "down_proj",+ ]+ model = FastLanguageModel.get_peft_model(+ model,+ r = args.lora_r,+ lora_alpha = args.lora_alpha,+ lora_dropout = 0.0, # nonzero dropout is one more RNG consumer+ bias = "none",+ target_modules = target_modules,+ use_gradient_checkpointing = args.gradient_checkpointing,+ random_state = SEED,+ )++ eos = tokenizer.eos_token or ""+ dataset = build_dataset(rows, eos)++ from trl import SFTConfig, SFTTrainer++ sampler = RepeatingSequentialSampler(+ dataset_length = len(dataset),+ batch_size = args.batch_size,+ gradient_accumulation_steps = args.grad_accum,+ max_steps = args.max_steps,+ )+ stats = StatisticsCallback()++ config = SFTConfig(+ output_dir = str(Path(args.outdir) / f"trainer_run{run_index}"),+ completion_only_loss = True,+ max_length = args.max_seq_length,+ per_device_train_batch_size = args.batch_size,+ gradient_accumulation_steps = args.grad_accum,+ max_steps = args.max_steps,+ learning_rate = args.learning_rate,+ # Constant schedule, no warmup: over 3 steps a warmup would spend the+ # whole run at a fraction of the target LR, and a linear decay would+ # make step 3's update depend on max_steps. Constant keeps the reference+ # meaningful and the overfit strong enough for the canary.+ lr_scheduler_type = "constant",+ warmup_steps = 0,+ logging_steps = 1, # StatisticsCallback only fires on logs+ optim = args.optim,+ weight_decay = 0.0,+ seed = SEED,+ data_seed = SEED,+ fp16 = True,+ bf16 = False,+ dataloader_num_workers = 0, # worker processes reorder and reseed+ dataloader_pin_memory = False,+ group_by_length = False,+ report_to = "none",+ save_strategy = "no",+ )++ trainer_cls = _make_trainer_class(SFTTrainer, sampler)+ trainer = trainer_cls(+ model = model,+ processing_class = tokenizer,+ train_dataset = dataset,+ args = config,+ callbacks = [stats],+ )++ loss_scale = pin_initial_loss_scale(trainer, args.init_loss_scale)+ _log(f"fp16 loss scale: {json.dumps(loss_scale)}")++ t0 = time.time()+ trainer.train()+ train_seconds = time.time() - t0++ if len(stats.logs) != args.max_steps:+ raise RuntimeError(+ f"expected {args.max_steps} logged steps, got {len(stats.logs)}: " f"{stats.logs}"+ )++ # Adapter save, then read the serialized weights back off disk. A filename+ # is not evidence: save_pretrained can leave an empty, truncated or all-zero+ # adapter_model.safetensors and every later assertion still passes, since+ # inference runs on the in-memory model. A file read rather than a second+ # FastLanguageModel load answers "can these weights be consumed" without a+ # second 4-bit load on a card already hosting one.+ adapter_dir = Path(args.outdir) / f"lora_run{run_index}"+ t0 = time.time()+ model.save_pretrained(str(adapter_dir))+ tokenizer.save_pretrained(str(adapter_dir))+ save_seconds = time.time() - t0+ saved_files = sorted(p.name for p in adapter_dir.iterdir())+ adapter_weights = [f for f in saved_files if f.startswith("adapter_model.")]+ if not adapter_weights:+ raise RuntimeError(f"no adapter weights in {adapter_dir}: {saved_files}")+ saved_adapter = verify_saved_adapter(+ adapter_dir,+ expected = {+ "r": args.lora_r,+ "lora_alpha": args.lora_alpha,+ "target_modules": target_modules,+ },+ # Asked of the model that was just saved, so the file is compared+ # against what PEFT calls these tensors rather than against a list this+ # payload would have to keep in step with peft by hand.+ peft_keys = peft_adapter_keys(model),+ )+ _log(f"saved adapter: {json.dumps(saved_adapter)}")++ # Inference on the trained, in-memory model, greedy so the output is a+ # function of the weights alone.+ FastLanguageModel.for_inference(model)+ prompt = PROMPT_TEMPLATE.format(question = rows[0]["question"])+ inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)+ t0 = time.time()+ with torch.inference_mode():+ out = model.generate(+ **inputs,+ max_new_tokens = args.max_new_tokens,+ do_sample = False,+ temperature = None,+ top_p = None,+ top_k = None,+ use_cache = True,+ pad_token_id = tokenizer.pad_token_id or tokenizer.eos_token_id,+ )+ infer_seconds = time.time() - t0+ generated = tokenizer.decode(out[0][inputs["input_ids"].shape[1] :], skip_special_tokens = True)++ peak_gb = torch.cuda.max_memory_reserved() / 1024**3 if torch.cuda.is_available() else 0.0++ result = {+ "run_index": run_index,+ "metrics": stats.logs,+ "generated": generated,+ # Both, because they answer different questions when this goes red:+ # `canary_found` says training reached the weights at all, `canary_exact`+ # is the assertion, and the gap between them is the signature of a+ # stopping/EOS regression rather than a training one.+ "canary_found": CANARY in generated,+ "canary_exact": generated.strip() == CANARY,+ "prompt": prompt,+ "adapter_files": saved_files,+ "saved_adapter": saved_adapter,+ # The repository the loader actually read, and its commit. The requested+ # name is not the loaded name (load_in_4bit goes through Unsloth's+ # FLOAT_TO_INT_MAPPER), and a mirror repo re-uploaded in place moves the+ # trajectory with no change in this repository. Recorded so the band+ # check can say so.+ "resolved_checkpoint": resolved_checkpoint,+ "resolved_revision": resolved_revision,+ "determinism": det_state,+ "loss_scale": loss_scale,+ "timing_seconds": {+ "load": round(load_seconds, 1),+ "train": round(train_seconds, 1),+ "save": round(save_seconds, 1),+ "infer": round(infer_seconds, 1),+ },+ "peak_reserved_gb": round(peak_gb, 2),+ }++ del trainer, model+ import gc++ gc.collect()+ if torch.cuda.is_available():+ torch.cuda.empty_cache()+ return result+++def _reconstruct_adapter_config(adapter_dir, expected: dict | None) -> dict:+ """Ask PEFT to rebuild the saved config, and check it describes THIS run.++ ``json.loads`` succeeding is not the question anyone has about this file.+ ``{}`` is valid JSON, so a save that wrote no LoRA fields at all read as+ "config_readable" and the leg passed on an adapter nothing can load -- the+ same shape as the tensor count that a randomly initialised ``lora_A``+ satisfied. What is actually being asserted is "PEFT can reconstruct the+ adapter", so it is asked of PEFT, on the path a reload takes.++ That path is the mapping dispatch, not the base class:+ ``PeftModel.from_pretrained`` does+ ``PEFT_TYPE_TO_CONFIG_MAPPING[peft_type].from_pretrained(...)``, while+ ``PeftConfig.from_pretrained`` alone returns a bare ``PeftConfig`` with+ ``peft_type=None`` for ``{}`` and reports nothing wrong. Checked against+ peft 0.20.0: only the dispatch raises, which is why it is what runs here.++ ``expected`` is DERIVED, not restated: the caller passes the very arguments+ it handed ``get_peft_model``, so a save that writes a well-formed config for+ a DIFFERENT adapter than the one trained (a dropped ``target_modules``, a+ rank that did not survive the round trip) is a difference rather than a+ field list this function had to guess at.++ Never raises; every outcome is a recorded key that ``saved_adapter_failures``+ turns into a verdict.+ """+ out: dict = {}+ try:+ from peft import PEFT_TYPE_TO_CONFIG_MAPPING, PeftConfig++ peft_type = PeftConfig.from_pretrained(str(adapter_dir)).peft_type+ if peft_type is None:+ raise ValueError(+ "adapter_config.json names no peft_type, so PEFT cannot tell "+ "which kind of adapter this is"+ )+ config = PEFT_TYPE_TO_CONFIG_MAPPING[peft_type].from_pretrained(str(adapter_dir))+ except Exception as exc: # noqa: BLE001+ out["config_loadable"] = False+ out["config_load_error"] = f"{type(exc).__name__}: {exc}"[:300]+ return out+ out["config_loadable"] = True+ out["config_peft_type"] = str(getattr(config, "peft_type", None))+ differences: list[str] = []+ unchecked: list[str] = []+ for key, wanted in sorted((expected or {}).items()):+ if not hasattr(config, key):+ # "It does not say" is not "it differs": a PEFT version that+ # renamed a field is recorded rather than turned into a failure.+ unchecked.append(key)+ continue+ got = getattr(config, key)+ if isinstance(wanted, (list, tuple, set)) or isinstance(got, (list, tuple, set)):+ same = sorted(got or []) == sorted(wanted or [])+ else:+ same = got == wanted+ if not same:+ differences.append(f"{key}: trained with {wanted!r}, saved {got!r}")+ out["config_differences"] = differences+ out["config_unchecked"] = unchecked+ return out+++def peft_adapter_keys(model) -> dict:+ """The names PEFT itself gives this adapter's tensors, off the live model.++ ``PeftModel.save_pretrained`` writes exactly+ ``get_peft_model_state_dict(self, ...)`` (peft 0.20.0, peft_model.py), so+ calling the same function on the model that was just saved reproduces the+ key set the file is SUPPOSED to hold. That is the oracle a raw tensor read+ is missing: safetensors deserializes any well-formed file, whatever the keys+ are called, and PEFT's loader then matches by name.++ Derived rather than restated: no key list, no prefix, no target-module names+ appear here, so a legitimate peft renaming moves both sides at once and only+ a save that disagrees with the running peft is a difference.++ Returns ``{"keys": [...]}`` or ``{"error": "..."}``; never raises, because+ every outcome has to reach ``saved_adapter_failures`` as a verdict rather+ than as a traceback out of the payload.+ """+ try:+ from peft import get_peft_model_state_dict+ return {"keys": sorted(get_peft_model_state_dict(model))}+ except Exception as exc: # noqa: BLE001+ return {"error": f"{type(exc).__name__}: {exc}"[:300]}+++def _compare_adapter_keys(saved: set, peft_keys: dict | None) -> dict:+ """Saved tensor names against the ones PEFT names for the live model.++ Three answers, and they are not the same failure:++ * MISSING -- PEFT names a tensor the file does not carry. On reload peft+ warns ("Found missing adapter keys while loading the checkpoint",+ peft_model.py) and leaves that module's adapter at its initial value, so+ the weight is silently dropped.+ * UNEXPECTED -- the file carries a LoRA tensor under a name PEFT does not+ use. ``set_peft_model_state_dict`` ends in+ ``model.load_state_dict(..., strict=False)`` and nothing reads the+ returned ``unexpected_keys``, so those tensors are ignored without a word.+ Measured on peft 0.20.0: stripping ``base_model.model.`` from a valid+ adapter, or leaving the adapter name in (``lora_B.default.weight``, what+ filtering ``model.state_dict()`` by hand produces instead of using+ ``get_peft_model_state_dict``), reloads with every lora_B back at zero and+ raises nothing. The file still holds two nonzero tensors called lora_B, so+ the count this function exists to reinforce reads green on it.+ * EXTRA, non-LoRA -- recorded and NOT failed. ``save_pretrained`` may write+ more than the adapter (an embedding, a modules_to_save copy) and that is+ not a name PEFT would have to match.+ """+ if not peft_keys or not peft_keys.get("keys"):+ return {+ "keys_checked": False,+ "keys_error": (peft_keys or {}).get("error")+ or "the live model was never asked what these tensors should be called",+ }+ expected = set(peft_keys["keys"])+ unmatched = saved - expected+ return {+ "keys_checked": True,+ "keys_missing": sorted(expected - saved),+ "keys_unexpected": sorted(k for k in unmatched if LORA_MARKER in k.lower()),+ "keys_extra": sorted(k for k in unmatched if LORA_MARKER not in k.lower()),+ }+++def verify_saved_adapter(+ adapter_dir,+ expected: dict | None = None,+ peft_keys: dict | None = None,+) -> dict:+ """Read the serialized adapter back and say what is in it.++ Everything downstream of the save runs on the in-memory model, so the only+ thing that ever looked at the file was a filename test. A tensor read rather+ than a PEFT reload, because it runs on a card already holding a 4-bit model+ and the failure modes worth naming (unreadable, empty, non-finite, all zero)+ are visible in the tensors themselves.++ What is NOT visible in the tensors is whether PEFT would consume them, since+ it matches by NAME and ignores what it does not recognise. ``peft_keys`` is+ ``peft_adapter_keys(model)`` for the model that was just saved, and+ comparing the two key sets is what turns "these bytes deserialize" into+ "these weights land". See ``_compare_adapter_keys``.++ ``nonzero_b_tensors`` is the load-bearing one, counted over the B matrices+ SPECIFICALLY: ``lora_B`` is zero at initialisation and only becomes non-zero+ once an update has been applied and saved, while ``lora_A`` is randomly+ initialised and nonzero before a single step. Counting every tensor+ therefore passed an adapter whose B matrices were all zero or dropped, whose+ output is still zero through B, so reloading it restores the base model.++ Returns a dict; never raises. ``saved_adapter_failures`` turns it into a+ verdict, so the pass/fail rule stays testable without a GPU.+ """+ adapter_dir = Path(adapter_dir)+ state: dict[str, Any] = {"dir": str(adapter_dir)}+ try:+ state["files"] = sorted(p.name for p in adapter_dir.iterdir())+ except OSError as exc:+ state["files"] = []+ state["error"] = f"{type(exc).__name__}: {exc}"+ return state+ try:+ json.loads((adapter_dir / "adapter_config.json").read_text(encoding = "utf-8"))+ state["config_readable"] = True+ except Exception as exc: # noqa: BLE001+ state["config_readable"] = False+ state["config_error"] = f"{type(exc).__name__}: {exc}"[:200]+ if state["config_readable"]:+ state.update(_reconstruct_adapter_config(adapter_dir, expected))++ safetensors_file = adapter_dir / "adapter_model.safetensors"+ bin_file = adapter_dir / "adapter_model.bin"+ tensors = None+ try:+ if safetensors_file.exists():+ from safetensors.torch import load_file+ state["weight_file"] = safetensors_file.name+ tensors = load_file(str(safetensors_file))+ elif bin_file.exists():+ import torch+ state["weight_file"] = bin_file.name+ tensors = torch.load(str(bin_file), map_location = "cpu", weights_only = True)+ else:+ state["error"] = "no adapter_model.safetensors and no adapter_model.bin"+ return state+ except Exception as exc: # noqa: BLE001+ state["error"] = f"{type(exc).__name__}: {exc}"[:300]+ return state++ non_finite: list[str] = []+ nonzero = 0+ b_tensors = 0+ nonzero_b = 0+ total = 0+ for name, tensor in tensors.items():+ try:+ is_b = LORA_B_MARKER in name.lower()+ b_tensors += int(is_b)+ floating = tensor.is_floating_point()+ if floating and not bool(tensor.isfinite().all()):+ non_finite.append(name)+ if bool(tensor.count_nonzero()):+ nonzero += 1+ nonzero_b += int(is_b)+ total += int(tensor.numel())+ except Exception as exc: # noqa: BLE001+ non_finite.append(f"{name}: {type(exc).__name__}")+ state["tensors"] = len(tensors)+ state["parameters"] = total+ state["non_finite_tensors"] = non_finite[:10]+ state["nonzero_tensors"] = nonzero+ state["b_tensors"] = b_tensors+ state["nonzero_b_tensors"] = nonzero_b+ state.update(_compare_adapter_keys(set(tensors), peft_keys))+ return state+++def saved_adapter_failures(state: dict) -> list[str]:+ """Turn ``verify_saved_adapter``'s reading into failure strings."""+ failures: list[str] = []+ if not state:+ return ["the saved adapter was never verified"]+ if state.get("config_readable") is False:+ failures.append(+ f"the saved adapter's adapter_config.json could not be read, so "+ f"nothing can load it: {state.get('config_error')}"+ )+ # Syntactically valid JSON is not a loadable adapter: `{}` parses, and used+ # to pass here, leaving the leg green on a file PEFT cannot reconstruct.+ if state.get("config_loadable") is False:+ failures.append(+ f"the saved adapter's adapter_config.json parses but PEFT cannot "+ f"rebuild an adapter from it, so reloading this directory fails: "+ f"{state.get('config_load_error')}"+ )+ if state.get("config_differences"):+ failures.append(+ f"the saved adapter_config.json describes a different adapter than "+ f"the one that was trained: {state['config_differences']}"+ )+ if state.get("tensors") is None:+ failures.append(+ f"the saved adapter weights could not be read back from "+ f"{state.get('dir')}: {state.get('error')}"+ )+ return failures+ if not state["tensors"]:+ failures.append(f"the saved adapter holds no tensors: {state.get('files')}")+ return failures+ if state.get("non_finite_tensors"):+ failures.append(+ f"the saved adapter holds non-finite weights: {state['non_finite_tensors']}"+ )+ # The B matrices, not the tensor count: lora_A is randomly initialised and+ # nonzero before training starts, so a file whose B matrices were all zero+ # or dropped still had nonzero tensors and was accepted, while producing+ # nothing, the adapter's contribution going through B.+ b_tensors = state.get("b_tensors")+ if not b_tensors:+ failures.append(+ f"not one of the {state['tensors']} saved tensors is a lora_B matrix "+ f"({state.get('files')}), so this file cannot say whether training "+ f"reached the adapter. lora_B is the only weight in here that starts "+ f"at a known value, and without it the reading is unusable rather "+ f"than good."+ )+ elif not state.get("nonzero_b_tensors"):+ failures.append(+ f"every one of the {b_tensors} saved lora_B matrices is zero (of "+ f"{state['tensors']} tensors, {state.get('nonzero_tensors')} nonzero). "+ f"lora_B starts at zero and only an applied optimizer step moves it, so "+ f"this adapter contributes nothing and reloading it would restore the "+ f"base model."+ )+ # Names, after values: peft matches its state dict by key and ignores what+ # it does not recognise, so a file full of healthy nonzero lora_B tensors+ # under names it does not use reloads as the base model without raising.+ if state.get("keys_checked") is False:+ failures.append(+ f"the saved adapter's tensor names were never checked against the "+ f"ones PEFT gives this model, so nothing here says the weights "+ f"would be loaded rather than ignored: {state.get('keys_error')}"+ )+ if state.get("keys_missing"):+ failures.append(+ f"PEFT names {len(state['keys_missing'])} adapter tensors the saved "+ f"file does not carry, so reloading leaves those modules at their "+ f"initial values: {state['keys_missing'][:5]}"+ )+ if state.get("keys_unexpected"):+ failures.append(+ f"{len(state['keys_unexpected'])} saved LoRA tensors are named "+ f"something PEFT does not use for this model, so its loader ignores "+ f"them silently and the reload restores the base model: "+ f"{state['keys_unexpected'][:5]}"+ )+ return failures+++def canary_failures(run: dict, *, require: bool) -> list[str]:+ """The canary assertion, as an EXACT match rather than a substring.++ The completion trained on is ``CANARY + eos_token`` and decoding strips the+ special tokens, so a healthy greedy decode returns the canary and nothing+ else. ``CANARY in generated`` also accepts ``'__UNSLOTH__!!!<anything>'``,+ which is what a stopping or EOS regression produces -- the model learned the+ target and no longer knows where to stop -- reporting green on a broken+ inference path.++ Surrounding whitespace is the one normalisation allowed, being a decoder+ artefact rather than a change in what the model emitted.+ """+ generated = run.get("generated") or ""+ if generated.strip() == CANARY:+ return []+ if CANARY in generated:+ msg = (+ f"run {run.get('run_index')} did not emit the canary {CANARY!r} exactly: "+ f"the canary is there but so is other text, which is what a stopping or "+ f"EOS regression looks like. Got {generated!r}"+ )+ else:+ msg = (+ f"run {run.get('run_index')} did not emit the canary " f"{CANARY!r}; got {generated!r}"+ )+ if not require:+ _log("WARNING (not enforced): " + msg)+ return []+ return [msg]+++def environment_fingerprint() -> dict:+ import torch++ info = {+ "python": platform.python_version(),+ "torch": torch.__version__,+ "cuda": torch.version.cuda,+ "platform": platform.platform(),+ }+ try:+ import transformers+ info["transformers"] = transformers.__version__+ except Exception: # noqa: BLE001+ pass+ try:+ import trl+ info["trl"] = trl.__version__+ except Exception: # noqa: BLE001+ pass+ try:+ import unsloth+ info["unsloth"] = getattr(unsloth, "__version__", "unknown")+ except Exception: # noqa: BLE001+ pass+ # Every package this CI watches, read from the installed distributions, and+ # what makes a canary-leg failure attributable: control and canary run the+ # same payload, so the diff of these two blocks is the entire difference+ # between green and red. The keys above are kept as they were, the committed+ # reference carrying them and the summary renderer reading them.+ info["resolved"] = flatten_versions(resolved_versions(GOAL_PACKAGES))+ if torch.cuda.is_available():+ props = torch.cuda.get_device_properties(0)+ info["gpu_name"] = props.name+ info["gpu_capability"] = f"sm_{props.major}{props.minor}"+ info["gpu_total_gb"] = round(props.total_memory / 1024**3, 1)+ info["gpu_count_visible"] = torch.cuda.device_count()+ info["driver_cuda"] = torch.version.cuda+ return info+++def reference_step_count(ref: dict):+ """The ``max_steps`` a reference file says it was captured at.++ ``None`` means the file does not say, which is not "it matches": a trace+ with no declared length cannot be shown to describe the run in hand, and the+ caller treats it as such.+ """+ config = ref.get("config")+ if not isinstance(config, dict):+ return None+ value = config.get("max_steps")+ try:+ return int(value)+ except (TypeError, ValueError):+ return None+++# Every setting that defines which experiment a trace is a trace OF. A run+# differing in any of them is not comparable to the reference whatever the+# numbers do, and references/README.md says widening the band is never the+# answer.+#+# `repeat` is deliberately absent: each cycle is a fresh process on identical+# configuration, so how many ran changes none of them, and refusing on it would+# reject a --repeat 3 run against a --repeat 2 reference for no reason.+#+# `dataset_digest` is here rather than `dataset`: the PATH says nothing about+# what is in the file, and canary_dataset.jsonl is inside the workflow's paths+# filter, so a run triggered BY editing it is exactly the run that would+# otherwise be band-checked against a trace of the old rows.+REFERENCE_DEFINING_SETTINGS = (+ "max_steps",+ "dataset_digest",+ "init_loss_scale",+ "batch_size",+ "grad_accum",+ "max_seq_length",+ "learning_rate",+ "lora_r",+ "lora_alpha",+ "optim",+ "gradient_checkpointing",+)+++def check_reference(+ metrics: list[dict],+ reference_path: Path,+ rel_tol: float,+ abs_floor: float,+ *,+ max_steps: int,+ config: dict | None = None,+ model: str | None = None,+ resolved_checkpoint: str | None = None,+ resolved_revision: str | None = None,+ environment: dict | None = None,+) -> dict:+ """Compare against a committed reference. Never an equality check.++ ``max_steps``, the step count of the run being judged, is mandatory. A+ reference is a trace of one specific run, and a run of a different length is+ a different run: the fp16 scaler burns its first few steps on overflows, the+ learning-rate schedule is constant only because the run is short, and step N+ of a 3-step run is not the step N the 10-step trace recorded. Comparing+ across counts is arithmetic that succeeds and means nothing, so the mismatch+ gets its own status and the numbers are never touched. ``reference_failures``+ turns it into a failure; nothing here can turn it into a pass.++ ``max_steps`` used to be the only setting checked and is not the only one+ with that property: the reference records the whole ``config`` block, and+ README names the learning rate, the optimizer and the model as things that+ invalidate the file, so ``config``, ``model`` and the resolved checkpoint+ are compared under the same refuse-before-comparing rule.++ ``environment`` is the same rule applied to the HARDWARE, which is the one+ thing the reference records about itself that nothing compared. The file+ carries ``environment.gpu_name`` and ``gpu_capability`` -- "Tesla T4",+ "sm_75" -- because a loss trace belongs to the card it was captured on: the+ T4 has no bf16 and resolves attention to xformers, so the same code on+ another card produces a different curve, and band-checking across them+ reports a hardware difference as a code regression. The requirement is+ DERIVED from the reference's own environment block rather than restated as+ "must be a T4", so a reference recaptured on other hardware moves the gate+ with it. A reference that DOES name its card and a run that cannot name its+ own is ``hardware_unverified`` rather than a skip, because the alternative+ is a gate that switches itself off exactly when the probe fails.++ The settings are optional and default to not-compared, so an older caller+ and an older reference both keep working: a key the reference does not carry+ is listed in ``config_unchecked`` rather than treated as a mismatch. "It+ does not say" is neither "it differs" nor "it matches" -- but that is what+ the REFERENCE does not say. What the run does not say about hardware the+ reference does name is a refusal.+ """+ if not reference_path.exists():+ return {"status": "absent", "path": str(reference_path)}+ ref = json.loads(reference_path.read_text(encoding = "utf-8"))+ ref_metrics = ref.get("metrics", [])+ verdict: dict = {+ "status": "ok",+ "path": str(reference_path),+ "reference_env": ref.get("environment", {}),+ "observed_max_steps": max_steps,+ "reference_max_steps": reference_step_count(ref),+ "deviations": [],+ "worst_rel": {},+ "config_differences": [],+ "config_unchecked": [],+ "step_differences": [],+ }++ # The step-count gate comes FIRST and returns, so no partially reassuring+ # "worst relative deviation" is computed from two different runs.+ if verdict["reference_max_steps"] is None:+ verdict["status"] = "reference_step_count_unknown"+ verdict["note"] = (+ f"{reference_path.name} does not record the max_steps it was "+ "captured at (no config.max_steps), so it cannot be shown to "+ f"describe a {max_steps}-step run. Recapture it with the recipe "+ "in references/README.md."+ )+ return verdict+ if verdict["reference_max_steps"] != max_steps:+ verdict["status"] = "step_count_mismatch"+ verdict["note"] = (+ f"{reference_path.name} was captured at max_steps="+ f"{verdict['reference_max_steps']} and this run is "+ f"{max_steps} steps. Those are different runs and their "+ "per-step traces are not comparable. Regenerate the reference "+ "at the new step count (references/README.md) rather than "+ "widening the band."+ )+ return verdict++ # The hardware, before any number is compared and on the same terms as the+ # step count. A trace is of one card: the T4 has no bf16 and resolves+ # attention to xformers, so another GPU moves the curve for reasons that+ # have nothing to do with the code under test, and the deviations would be+ # reported as a regression. Only the count of GPUs was ever checked, on the+ # kernel, which cannot see this file at all.+ ref_env = ref.get("environment") if isinstance(ref.get("environment"), dict) else {}+ live_env = environment if isinstance(environment, dict) else {}+ hardware_pairs: list[tuple[str, Any, Any]] = []+ unverified: list[str] = []+ for key in ("gpu_name", "gpu_capability"):+ expected = ref_env.get(key)+ observed = live_env.get(key)+ if expected is None:+ # The reference does not say, which is not "it differs": an older+ # trace captured before the block carried a card keeps working, and+ # the skip is recorded rather than silent.+ if observed is not None:+ verdict["config_unchecked"].append(key)+ continue+ # The reference DOES say. From here the requirement is the reference's+ # own, so a run that cannot show what it ran on has not met it.+ if observed is None:+ unverified.append(key)+ continue+ hardware_pairs.append((key, expected, observed))+ # A live probe that produced no card is a refusal, not a skip. main()+ # records environment = {"error": ...} when environment_fingerprint()+ # raises, and the fingerprint omits every gpu_* key outright when+ # torch.cuda.is_available() is False, so both of those -- and a caller that+ # hands over no environment at all -- used to land in config_unchecked and+ # let the band check report "ok" without establishing the card. That is the+ # hardware gate above disabled by the one failure it most needs to survive.+ if unverified:+ verdict["status"] = "hardware_unverified"+ verdict["config_differences"] = [+ f"{key}: reference {ref_env.get(key)!r}, this run reported nothing"+ for key in unverified+ ]+ verdict["note"] = (+ f"{reference_path.name} was captured on "+ f"{ref_env.get('gpu_name')} ({ref_env.get('gpu_capability')}) and "+ f"this run did not report {', '.join(unverified)}: "+ f"{live_env.get('error') or 'no live hardware fingerprint'}. The "+ "trace is of that card, so without knowing this run's card nothing "+ "here can be compared. Fix the environment probe on the kernel, or "+ "recapture the reference (references/README.md)."+ )+ return verdict+ hardware_differences = [+ f"{key}: reference {expected!r}, this run {observed!r}"+ for key, expected, observed in hardware_pairs+ if expected != observed+ ]+ if hardware_differences:+ verdict["status"] = "hardware_mismatch"+ verdict["config_differences"] = hardware_differences+ verdict["note"] = (+ f"{reference_path.name} was captured on "+ f"{ref_env.get('gpu_name')} ({ref_env.get('gpu_capability')}) and "+ f"this run is on {(environment or {}).get('gpu_name')} "+ f"({(environment or {}).get('gpu_capability')}). The trace is of "+ "that card -- fp16 without bf16, xformers attention -- so the "+ "numbers are not comparable and any deviation here would be the "+ "hardware, not the code. Run this leg on the reference's card, or "+ "recapture the reference (references/README.md)."+ )+ return verdict++ # The rest of the configuration on the same terms as the step count: refuse+ # before comparing a single number, since these settings define a different+ # experiment rather than a drift within one.+ ref_config = ref.get("config") if isinstance(ref.get("config"), dict) else {}+ observed_pairs: list[tuple[str, Any, Any]] = []+ if config:+ for key in REFERENCE_DEFINING_SETTINGS:+ if key == "max_steps":+ continue # already gated above, with its own status+ if key not in ref_config or key not in config:+ verdict["config_unchecked"].append(key)+ continue+ observed_pairs.append((key, ref_config[key], config[key]))+ for key, observed in (+ ("model", model),+ ("resolved_checkpoint", resolved_checkpoint),+ ("resolved_revision", resolved_revision),+ ):+ # Neither side records it: nothing claimed, nothing to report. Present+ # on ONE side is a pin that did not run, recorded rather than skipped+ # silently. Still not a refusal, since "it does not say" is not "it+ # differs", but an invisible skip reads as a comparison that passed, and+ # this is exactly where a checkpoint pin sits unenforced for months.+ # report.py puts config_unchecked on the summary.+ if observed is None and ref.get(key) is None:+ continue+ if observed is None or ref.get(key) is None:+ verdict["config_unchecked"].append(key)+ continue+ observed_pairs.append((key, ref[key], observed))+ for key, expected, observed in observed_pairs:+ if expected != observed:+ verdict["config_differences"].append(+ {"key": key, "reference": expected, "observed": observed}+ )+ if verdict["config_differences"]:+ verdict["status"] = "config_mismatch"+ verdict["note"] = (+ f"{reference_path.name} was captured with a different training "+ f"configuration: {verdict['config_differences']}. Those settings "+ "define which experiment the trace is a trace of, so the numbers "+ "are not comparable. Regenerate the reference "+ "(references/README.md) rather than widening the band."+ )+ return verdict++ if len(ref_metrics) != len(metrics):+ verdict["status"] = "length_mismatch"+ return verdict++ # The step coordinates, before any value is compared: the lists are zipped+ # positionally, so a shifted, duplicated or reordered `step` pairs values+ # describing different iterates and the band check reports on arithmetic it+ # invented. Safe to be strict because the leg carrying a reference is the+ # control, whose library set is pinned to the one the trace was captured+ # with and whose pin failure is itself fatal, so the trainer cannot renumber+ # its steps without the pins going red first.+ for index, (cur, old) in enumerate(zip(metrics, ref_metrics)):+ if cur.get("step") != old.get("step"):+ verdict["step_differences"].append(+ {"index": index, "reference": old.get("step"), "observed": cur.get("step")}+ )+ if verdict["step_differences"]:+ verdict["status"] = "step_mismatch"+ verdict["note"] = (+ f"the observed per-step trace does not carry the same step "+ f"coordinates as {reference_path.name}: "+ f"{verdict['step_differences'][:5]}. The two are compared "+ "positionally, so nothing was compared."+ )+ return verdict++ for field in ("loss", "grad_norm"):+ worst = 0.0+ for cur, old in zip(metrics, ref_metrics):+ has_cur, has_old = field in cur, field in old+ if not has_cur and not has_old:+ continue+ if has_cur != has_old:+ # Present on one side only is a change in the SHAPE of what the+ # trainer logged, not a numeric drift, and no tolerance covers+ # it.+ verdict["deviations"].append(+ {+ "step": (cur if has_cur else old).get("step"),+ "field": field,+ "reference": old.get(field, None),+ "observed": cur.get(field, None),+ "relative": None,+ "note": "field present on only one side",+ }+ )+ continue+ new, ref_val = float(cur[field]), float(old[field])+ # NaN, explicitly, which is why the arithmetic is not left to itself.+ # Under fp16 the gradient scaler logs a NaN grad_norm on every+ # skipped step, so the committed reference genuinely contains NaNs,+ # and left to the subtraction abs(x - NaN) is NaN, NaN > rel_tol is+ # False, and the step passes whatever it holds -- including the case+ # that matters most, a step that used to overflow and no longer+ # does. NaN equals NaN here; NaN against a number is a deviation.+ cur_nan, ref_nan = new != new, ref_val != ref_val+ if cur_nan or ref_nan:+ if cur_nan != ref_nan:+ verdict["deviations"].append(+ {+ "step": cur.get("step"),+ "field": field,+ "reference": old[field],+ "observed": cur[field],+ "relative": None,+ "note": "the fp16 scaler skip pattern moved: NaN on one side only",+ }+ )+ continue+ # Infinities, for the same reason one step further along. An fp16+ # overflow logs infinity as readily as NaN, so the reference holds+ # them, and every pairing an infinity takes part in divides to NaN:+ # abs(inf - inf) / inf and abs(inf - 1.0) / inf alike. NaN > rel_tol+ # is False and max(worst, NaN) returns worst, so the entry was+ # accepted AND left no trace in worst_rel, including a step that+ # used to be finite and now overflows. Equal signed infinities are+ # the unchanged case; everything else is a deviation, decided before+ # the division.+ cur_inf = new in (float("inf"), float("-inf"))+ ref_inf = ref_val in (float("inf"), float("-inf"))+ if cur_inf or ref_inf:+ if new != ref_val:+ verdict["deviations"].append(+ {+ "step": cur.get("step"),+ "field": field,+ "reference": old[field],+ "observed": cur[field],+ "relative": None,+ "note": "an infinity on one side only, or opposite infinities",+ }+ )+ continue+ base = max(abs(ref_val), abs_floor)+ rel = abs(new - ref_val) / base+ worst = max(worst, rel)+ if rel > rel_tol:+ verdict["deviations"].append(+ {+ "step": cur.get("step"),+ "field": field,+ "reference": old[field],+ "observed": cur[field],+ "relative": round(rel, 5),+ }+ )+ verdict["worst_rel"][field] = round(worst, 5)+ if verdict["deviations"]:+ verdict["status"] = "out_of_band"+ return verdict+++def reference_failures(verdict: dict, rel_tol: float) -> list[str]:+ """Turn a reference verdict into failure strings. Separate so the path from+ "out of band" to "the job goes red" is testable without a GPU: a band check+ never observed to fail is not yet a check.+ """+ if verdict["status"] == "out_of_band":+ return [f"metrics outside +/-{rel_tol:.0%} of the reference: " f"{verdict['deviations']}"]+ if verdict["status"] == "length_mismatch":+ return ["reference has a different number of logged steps: nothing was compared"]+ # Refusals, loud and fatal: a reference that cannot be compared is worth+ # less than no reference, because it looks like cover and is not. Never+ # demote these to a warning.+ if verdict["status"] in (+ "step_count_mismatch",+ "reference_step_count_unknown",+ "config_mismatch",+ "step_mismatch",+ # The card the trace was captured on. Same rule as the settings: a+ # band checked across hardware succeeds arithmetically and means+ # nothing, and its deviations read as a code regression.+ "hardware_mismatch",+ # And the same rule when the card is unreadable rather than wrong: a+ # reference that names its hardware is only comparable against a run+ # that can name its own.+ "hardware_unverified",+ ):+ return [+ "refusing to band-check against a reference that is not for "+ "this run: " + verdict.get("note", verdict["status"])+ ]+ return []+++def _is_finite(value) -> bool:+ """NaN and both infinities are all "the step did not apply"."""+ try:+ number = float(value)+ except (TypeError, ValueError):+ return False+ return number == number and number not in (float("inf"), float("-inf"))+++def optimisation_failures(metrics: list[dict]) -> list[str]:+ """Did this run optimise anything at all? Cheap checks, loud answers.++ The last of the three is the one a short run needs. Under fp16 the gradient+ scaler logs ``grad_norm: NaN`` on a skipped step, and a run whose every step+ was skipped applied no optimizer update at all: the weights at the end are+ the weights at the start, while the loss is finite, the adapter saves and+ generation produces text, so the run reports as a training test having done+ no training. That is exactly what a step count trimmed too far produces.+ """+ failures: list[str] = []+ losses = [m["loss"] for m in metrics]+ if any(l != l or l in (float("inf"), float("-inf")) for l in losses):+ failures.append(f"non-finite loss: {losses}")+ if len(losses) > 1 and not losses[-1] < losses[0]:+ failures.append(f"loss did not decrease over the run: {losses}")+ # Only decidable where grad_norm was logged at all: a trainer version that+ # stops logging it says nothing about whether steps were applied, and+ # inferring "all skipped" from that silence would be a failure invented+ # rather than found.+ #+ # Finite, not merely non-NaN. An fp16 overflow reports the norm as inf at+ # least as readily as NaN (clip_grad_norm_ over an inf gradient returns inf)+ # and `inf == inf` is True, so a NaN-only test counted every skipped step as+ # applied and a run that applied nothing reported green. The loss check+ # above already treats inf as non-finite; this one did not.+ reported = [m["grad_norm"] for m in metrics if m.get("grad_norm") is not None]+ applied = [g for g in reported if _is_finite(g)]+ if reported and not applied:+ failures.append(+ f"the fp16 gradient scaler skipped every one of the "+ f"{len(metrics)} steps (no grad_norm is finite: {reported}), so no "+ f"optimizer update was applied and this run measured nothing "+ f"about training. Raise --max-steps or lower --init-loss-scale."+ )+ return failures+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--model", default = DEFAULT_MODEL)+ ap.add_argument("--dataset", default = str(_HERE / "canary_dataset.jsonl"))+ ap.add_argument("--outdir", required = True)+ # 3 steps, and the whole reason --init-loss-scale exists.+ #+ # Measured twice. Under fp16 the dynamic gradient scaler starts at 65536,+ # halves on every overflow and skips the step it overflowed on, and on this+ # model the first three steps overflow every time (the committed 10-step+ # reference has grad_norm NaN at steps 1, 2 and 3). So a 3-step run of the+ # ORIGINAL configuration applies zero optimizer updates, the loss does not+ # move and the canary never forms: an early 3-step attempt emitted+ # '#1\ndef my_function():...'.+ #+ # Pinning the scaler's starting scale below the overflow point (see+ # pin_initial_loss_scale) gives those three steps back as real updates, and+ # optimisation_failures() asserts that happened. The 10-step trajectory is+ # the honest yardstick for what 3 updates buy: loss 1.75 after three applied+ # updates and 0.18 after four, so the canary has less margin at 3 steps than+ # at 10. A T4 run reporting the canary missing while the scaler shows+ # updates applied is the signal to raise this back up, not to relax the+ # canary.+ ap.add_argument("--max-steps", type = int, default = 10)+ # Off by default. The pin is for short runs: the scaler overflows the first+ # three steps, so anything under about five applies no updates at all. At+ # the default of 10 the run reaches step 4 on its own and learns the canary,+ # and leaving the scaler alone keeps the committed reference applicable,+ # since a different starting scale is a different rounding of the same+ # gradients. Set it (e.g. 2048, below the 8192 the reference reaches after+ # three halvings) only with a shorter --max-steps and a reference recaptured+ # with both.+ ap.add_argument(+ "--init-loss-scale",+ type = float,+ default = 0.0,+ help = "fp16 GradScaler starting scale; 0 leaves the "+ "framework default (65536, which costs a short run "+ "its first few steps to overflows)",+ )+ ap.add_argument("--batch-size", type = int, default = 2)+ ap.add_argument("--grad-accum", type = int, default = 1)+ ap.add_argument("--max-seq-length", type = int, default = 512)+ # 1e-3 with the prompt masked out. Higher rates overflow fp16 far more often,+ # and each overflow is a skipped step this short run cannot spare.+ ap.add_argument("--learning-rate", type = float, default = 1e-3)+ ap.add_argument("--lora-r", type = int, default = 16)+ ap.add_argument("--lora-alpha", type = int, default = 32)+ ap.add_argument("--optim", default = "adamw_8bit")+ ap.add_argument("--gradient-checkpointing", default = "unsloth")+ ap.add_argument("--max-new-tokens", type = int, default = 16)+ ap.add_argument(+ "--repeat", type = int, default = 2, help = "fresh-process cycles; >1 enables the bitwise check"+ )+ ap.add_argument(+ "--cycle", type = int, default = -1, help = argparse.SUPPRESS+ ) # internal: child-mode marker+ ap.add_argument(+ "--force-sdpa",+ action = "store_true",+ help = "pin the SDPA attention backend. Local reproduction "+ "on hardware xformers has no kernel for; NOT for "+ "the T4 run, which must exercise the xformers path",+ )+ ap.add_argument(+ "--strict-deterministic",+ action = "store_true",+ help = "use_deterministic_algorithms(warn_only=False)",+ )+ ap.add_argument(+ "--reference", default = "", help = "committed reference JSON to band-check against"+ )+ ap.add_argument(+ "--pins",+ default = "",+ help = "a name==version pin file this run must have "+ "resolved to exactly. The control leg passes it; a "+ "pin that did not hold means the leg is not a "+ "control and its comparison against the canary is "+ "worthless, so it is a failure rather than a note",+ )+ ap.add_argument("--rel-tol", type = float, default = 0.10)+ ap.add_argument(+ "--abs-floor",+ type = float,+ default = 0.05,+ help = "denominator floor so a near-zero reference value "+ "does not turn a tiny absolute drift into a huge "+ "relative one",+ )+ ap.add_argument("--require-canary", dest = "require_canary", action = "store_true", default = True)+ ap.add_argument("--no-require-canary", dest = "require_canary", action = "store_false")+ ap.add_argument("--label", default = "t4-smoke")+ args = ap.parse_args()++ outdir = Path(args.outdir)+ outdir.mkdir(parents = True, exist_ok = True)++ # Child mode: exactly one cycle, report to disk, no assertions.+ if args.cycle >= 0:+ run = train_once(args, args.cycle)+ for entry in run["metrics"]:+ _log(+ f" step {entry['step']} loss={entry['loss']!r} "+ f"grad_norm={entry.get('grad_norm')!r}"+ )+ _log(f" generated: {run['generated']!r}")+ (outdir / "cycle_report.json").write_text(json.dumps(run, indent = 2), encoding = "utf-8")+ return 0++ # Parent mode: each cycle in a FRESH process, measured rather than assumed.+ # Two in-process cycles disagreed from the first logged step (6.4375 vs+ # 6.2367) while two separate processes agreed bitwise on every step.+ # Something in the first cycle's model load, patching or allocator state+ # leaks into the second, so an in-process repeat tests the leak rather than+ # the code and would report a false regression on a reproducible run. A+ # fresh process is also what a user re-running a notebook gets.+ #+ # The config and environment are read BEFORE the cycles, so a run that dies+ # in one still says which library set it died with: control red / canary+ # green is a bisect only if the red leg reported its versions.+ config = {+ k: getattr(args, k)+ for k in (+ "max_steps",+ "init_loss_scale",+ "batch_size",+ "grad_accum",+ "max_seq_length",+ "learning_rate",+ "lora_r",+ "lora_alpha",+ "optim",+ "gradient_checkpointing",+ "repeat",+ )+ }+ # WHAT trained, beside the settings that say how. Recorded here, in the+ # parent, so a run whose cycles all died still says which rows it was asked+ # to train on, and so the value travels into any reference captured from+ # this report.+ config["dataset_digest"] = dataset_digest(Path(args.dataset))+ try:+ env = environment_fingerprint()+ except Exception as exc: # noqa: BLE001+ env = {"error": f"{type(exc).__name__}: {exc}"[:300]}++ runs = []+ for i in range(args.repeat):+ _log(f"=== cycle {i + 1}/{args.repeat} (fresh process) ===")+ cycle_dir = outdir / f"cycle{i}"+ cycle_dir.mkdir(parents = True, exist_ok = True)+ cmd = [+ sys.executable,+ str(Path(__file__).resolve()),+ "--outdir",+ str(cycle_dir),+ "--cycle",+ str(i),+ ]+ for flag, value in (+ ("--model", args.model),+ ("--dataset", args.dataset),+ ("--max-steps", args.max_steps),+ ("--init-loss-scale", args.init_loss_scale),+ ("--batch-size", args.batch_size),+ ("--grad-accum", args.grad_accum),+ ("--max-seq-length", args.max_seq_length),+ ("--learning-rate", args.learning_rate),+ ("--lora-r", args.lora_r),+ ("--lora-alpha", args.lora_alpha),+ ("--optim", args.optim),+ ("--gradient-checkpointing", args.gradient_checkpointing),+ ("--max-new-tokens", args.max_new_tokens),+ ("--label", args.label),+ ):+ cmd += [flag, str(value)]+ if args.force_sdpa:+ cmd.append("--force-sdpa")+ if args.strict_deterministic:+ cmd.append("--strict-deterministic")+ proc = subprocess.run(cmd)+ report_file = cycle_dir / "cycle_report.json"+ if proc.returncode != 0 or not report_file.exists():+ _log(f"cycle {i} failed (rc={proc.returncode})")+ failed = {+ "label": args.label,+ "model": args.model,+ "config": config,+ "environment": env,+ "passed": False,+ "runs": runs,+ "metrics": [],+ "failures": [f"cycle {i} did not complete " f"(rc={proc.returncode})"],+ }+ (outdir / "t4_smoke_report.json").write_text(+ json.dumps(failed, indent = 2), encoding = "utf-8"+ )+ print("T4_SMOKE_REPORT " + json.dumps(failed), flush = True)+ _log("T4_SMOKE_RESULT FAIL")+ return 1+ runs.append(json.loads(report_file.read_text(encoding = "utf-8")))++ report: dict = {+ "label": args.label,+ "model": args.model,+ # The repo and commit the loader read, travelling into any reference+ # captured from this report so the band check can refuse against a+ # mirror re-uploaded in place.+ "resolved_checkpoint": runs[0].get("resolved_checkpoint"),+ "resolved_revision": runs[0].get("resolved_revision"),+ # The whole block travels into any reference captured from this report:+ # check_reference refuses to compare a run against a trace captured with+ # a different configuration.+ "config": config,+ "environment": env,+ "runs": runs,+ "metrics": runs[0]["metrics"],+ "failures": [],+ }++ failures: list[str] = []++ # 0. the pins, if this leg claims to be a control+ if args.pins:+ pins = load_pins(args.pins)+ # The probe list is derived from the pin file: a pin outside+ # GOAL_PACKAGES was looked up in a table nobody had asked about it and+ # came back "not installed".+ resolved = versions_for_pins(pins)+ broken = pin_failures(pins, resolved)+ report["pins"] = {"file": args.pins, "requested": pins, "failures": broken}+ failures += broken++ # 1. bitwise run-to-run, EVERY extra cycle against the baseline rather than+ # just the second: --repeat 3 asks for three fresh processes, and a third+ # that disagreed used to be collected, stored and never looked at.+ #+ # The top-level keys stay as they were, report.py rendering `identical`,+ # `first_diff_step` and `max_abs_diff` off this dict, but now summarise+ # every comparison; the per-cycle detail goes under `cycles`.+ if len(runs) > 1:+ cycles: dict = {}+ for other in runs[1:]:+ cycles[str(other["run_index"])] = compare_metrics(runs[0]["metrics"], other["metrics"])+ worst: dict = {}+ for cmp in cycles.values():+ for field, value in cmp.get("max_abs_diff", {}).items():+ worst[field] = max(worst.get(field, 0.0), value)+ differing = [(k, c) for k, c in cycles.items() if not c["identical"]]+ report["reproducibility"] = {+ "identical": not differing,+ "first_diff_step": differing[0][1]["first_diff_step"] if differing else None,+ "max_abs_diff": worst,+ "compared_cycles": sorted(cycles, key = int),+ "cycles": cycles,+ }+ for index, cmp in differing:+ failures.append(+ f"run-to-run metrics differ between cycle 0 and cycle {index} "+ f"(first diff at step {cmp['first_diff_step']}, max abs "+ f"{cmp['max_abs_diff']}, step mismatches {cmp['step_mismatch']})"+ )++ gen = {r["generated"] for r in runs}+ report["generated_identical"] = len(gen) == 1+ if len(gen) != 1:+ failures.append(f"run-to-run generation differs: {sorted(gen)!r}")++ # 2. canary, exactly+ for run in runs:+ failures += canary_failures(run, require = args.require_canary)++ # 3. sanity: finite, the optimisation moved, and it moved at all+ failures += optimisation_failures(runs[0]["metrics"])++ # 4. the adapter that was written is an adapter that can be loaded+ for run in runs:+ failures += [+ f"run {run['run_index']}: {f}"+ for f in saved_adapter_failures(run.get("saved_adapter") or {})+ ]++ # 5. band check against the committed reference+ if args.reference:+ ref = check_reference(+ runs[0]["metrics"],+ Path(args.reference),+ args.rel_tol,+ args.abs_floor,+ max_steps = args.max_steps,+ config = config,+ model = args.model,+ resolved_checkpoint = runs[0].get("resolved_checkpoint"),+ resolved_revision = runs[0].get("resolved_revision"),+ environment = env,+ )+ report["reference_check"] = ref+ failures += reference_failures(ref, args.rel_tol)++ report["failures"] = failures+ report["passed"] = not failures++ report_path = outdir / "t4_smoke_report.json"+ report_path.write_text(json.dumps(report, indent = 2), encoding = "utf-8")+ _log(f"report -> {report_path}")+ print("T4_SMOKE_REPORT " + json.dumps(report), flush = True)++ if failures:+ for f in failures:+ _log(f"FAIL: {f}")+ _log("T4_SMOKE_RESULT FAIL")+ return 1+ _log("T4_SMOKE_RESULT PASS")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/kaggle/t4_smoke/training_evidence.py b/tests/kaggle/t4_smoke/training_evidence.pynew file mode 100644index 00000000000..4542e7b6981--- /dev/null+++ b/tests/kaggle/t4_smoke/training_evidence.py@@ -0,0 +1,206 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Did the optimizer actually change the adapter? Shared by the payloads.++A run that applied no update at all still reports healthily: the loss is finite+because a forward pass computes one, `torch.compile` engages on the forward,+and the BASE model generates text without any adapter. So each payload asserts+some logged ``grad_norm`` was finite and non-zero -- which is only decidable+where ``grad_norm`` was logged. A Trainer change that stops emitting the field+leaves an EMPTY list, and the obvious `if norms and not applied` spelling+collapses "no usable norm" and "no norm logged" into a pass.++Failing on that silence would be a failure invented rather than found, so this+stops depending on trainer telemetry: LoRA's B matrices are exactly zero until+an optimizer step lands on them, so fingerprints taken before and after+training answer the question directly.++The tiny SFT payload (``run_t4_smoke.py``) instead reads its saved adapter back+off disk and fails on an all-zero one (``verify_saved_adapter``); gptoss and+grpo save no adapter, which is why the silence there was covered by nothing.++Nothing here raises: a diagnostic that kills the payload it diagnoses leaves+the leg reporting nothing at all.+"""++from __future__ import annotations++# Substrings marking a LoRA parameter and, narrower, the B matrices. peft names+# them `...lora_A.default.weight` / `lora_B...`; matched lowercased so a future+# capitalisation cannot silently empty the set.+LORA_MARKER = "lora_"+LORA_B_MARKER = "lora_b"+++def _is_finite(value) -> bool:+ try:+ number = float(value)+ except (TypeError, ValueError):+ return False+ return number == number and number not in (float("inf"), float("-inf"))+++def adapter_fingerprint(model) -> dict:+ """Sum ``|w|`` over every LoRA parameter of ``model``.++ Cheap: a rank-8 adapter is a few hundred small matrices, microseconds beside+ the training step it brackets. Returns ``{"ok": False, "error": ...}``+ rather than raising; ``ok`` false means the question could not be answered,+ not that the answer was no.++ A non-finite sum is the one refusal that IS an answer. NaN or infinite LoRA+ weights are a broken run, and left as a number they are the strongest+ possible pass (``NaN != finite`` reads as "the adapter changed"), so they+ are flagged ``non_finite`` for ``update_verdict`` to name rather than+ compare.+ """+ try:+ total = 0.0+ b_total = 0.0+ tensors = 0+ non_finite: list[str] = []+ for name, param in model.named_parameters():+ lowered = name.lower()+ if LORA_MARKER not in lowered:+ continue+ tensors += 1+ value = float(param.detach().float().abs().sum().item())+ if not _is_finite(value):+ non_finite.append(name)+ total += value+ if LORA_B_MARKER in lowered:+ b_total += value+ if not tensors:+ return {"ok": False, "error": "no parameter name carries a LoRA marker"}+ if non_finite:+ return {+ "ok": False,+ "non_finite": True,+ "tensors": tensors,+ "error": (+ f"{len(non_finite)} of {tensors} LoRA tensors hold non-finite "+ f"weights: {sorted(non_finite)[:10]}"+ ),+ }+ return {"ok": True, "tensors": tensors, "abs_sum": total, "b_abs_sum": b_total}+ except Exception as exc: # noqa: BLE001+ return {"ok": False, "error": f"{type(exc).__name__}: {str(exc)[:200]}"}+++def adapter_update(before, after) -> dict:+ """Compare two fingerprints. ``changed`` is the whole answer.++ Two sums, not one, is what makes an exact float comparison safe to turn red+ on. ``abs_sum`` moving is the general signal; ``b_abs_sum`` starts at+ exactly 0.0 because peft zero-initialises every B matrix. For BOTH to be+ bitwise unchanged after a real update, the optimizer would have to land+ deltas cancelling to the last bit in two different summations at once.++ A differing tensor count between readings is unusable rather than a change:+ whatever it is, it is not evidence about the optimizer.+ """+ before = before if isinstance(before, dict) else {}+ after = after if isinstance(after, dict) else {}+ if not (before.get("ok") and after.get("ok")):+ return {+ "ok": False,+ "non_finite": bool(before.get("non_finite") or after.get("non_finite")),+ "error": before.get("error")+ or after.get("error")+ or "the adapter was not fingerprinted",+ }+ # Rechecked here, not only where the sums were taken: an exact `!=` on a NaN+ # is the most confident "it changed" this file can produce.+ unusable = [+ f"{side}.{key}={reading[key]}"+ for side, reading in (("before", before), ("after", after))+ for key in ("abs_sum", "b_abs_sum")+ if not _is_finite(reading.get(key))+ ]+ if unusable:+ return {+ "ok": False,+ "non_finite": True,+ "error": f"the adapter fingerprints are not finite ({', '.join(unusable)})",+ }+ if before.get("tensors") != after.get("tensors"):+ return {+ "ok": False,+ "error": (+ f"the adapter had {before.get('tensors')} LoRA tensors before training "+ f"and {after.get('tensors')} after, so the two readings are not "+ f"comparable"+ ),+ }+ changed = (after["abs_sum"] != before["abs_sum"]) or (after["b_abs_sum"] != before["b_abs_sum"])+ return {+ "ok": True,+ "changed": bool(changed),+ "tensors": after["tensors"],+ "abs_sum_before": before["abs_sum"],+ "abs_sum_after": after["abs_sum"],+ "b_abs_sum_before": before["b_abs_sum"],+ "b_abs_sum_after": after["b_abs_sum"],+ }+++def update_verdict(metrics, adapter = None) -> dict:+ """Was an optimizer update applied? ``applied`` / ``not_applied`` /+ ``non_finite`` / ``unverifiable``.++ The adapter reading wins where it exists, being the thing grad norms are a+ proxy FOR: gradients flowing into weights nobody updated is still a run that+ trained nothing.++ ``unverifiable`` -- no usable grad_norm logged AND no adapter reading -- is+ a failure at the call sites: not because nothing was applied, which is+ unknown, but because the leg can no longer show it exercised the training+ path.++ ``non_finite`` is decided FIRST and beats a healthy grad_norm: a finite norm+ at step 1 says nothing about weights that went NaN at step 3.++ Every call site treats anything but ``applied`` as a failure, so a verdict+ added here cannot be silently dropped.+ """+ rows = metrics or []+ norms = [row.get("grad_norm") for row in rows if row.get("grad_norm") is not None]+ usable = [g for g in norms if _is_finite(g) and float(g) != 0.0]+ weights = adapter if isinstance(adapter, dict) else {}+ moved = weights.get("changed") if weights.get("ok") else None++ if weights.get("non_finite"):+ return {+ "verdict": "non_finite",+ "detail": str(weights.get("error") or "the adapter holds non-finite weights"),+ "grad_norms": norms,+ }+ if moved is False:+ return {+ "verdict": "not_applied",+ "detail": (+ f"the {weights.get('tensors')} LoRA tensors are bitwise identical to "+ f"the ones training started with (|w| {weights.get('abs_sum_before')} "+ f"-> {weights.get('abs_sum_after')}, of which the zero-initialised B "+ f"matrices {weights.get('b_abs_sum_before')} -> "+ f"{weights.get('b_abs_sum_after')})"+ ),+ "grad_norms": norms,+ }+ if norms and not usable:+ return {+ "verdict": "not_applied",+ "detail": f"every logged grad_norm is zero or non-finite ({norms})",+ "grad_norms": norms,+ }+ if usable or moved:+ return {"verdict": "applied", "detail": "", "grad_norms": norms}+ return {+ "verdict": "unverifiable",+ "detail": (+ "no grad_norm was logged on any step, and the adapter weights could not "+ f"be compared either ({weights.get('error') or 'not fingerprinted'})"+ ),+ "grad_norms": norms,+ }diff --git a/tests/kaggle/t4_smoke/versions.py b/tests/kaggle/t4_smoke/versions.pynew file mode 100644index 00000000000..61481366a27--- /dev/null+++ b/tests/kaggle/t4_smoke/versions.py@@ -0,0 +1,184 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""What was actually installed, recorded so a regression can be attributed.++The canary leg installs the LATEST release of every library Unsloth sits on,+and runs the pinned control leg's payload; canary red plus control green means+a version bump, but only if the report names which versions moved.++Two rules. **Read the metadata, not the module**: ``importlib.metadata.version``+reads the installed distribution, ``torch.__version__`` is whatever a package+chose to expose. They disagree where it matters -- ``vllm`` on a card its wheel+has no kernels for has a metadata version and raises on import -- so both are+recorded, "installed 0.11.2, would not import" being a different finding from+"not installed". **Never let recording a version fail the run**: every probe is+wrapped, since dying while collecting diagnostics reports nothing at all.+"""++from __future__ import annotations++# Libraries whose version bumps this CI exists to detect. Order is report+# order: runtime stack first, Unsloth packages last.+GOAL_PACKAGES = (+ "torch",+ "transformers",+ "trl",+ "peft",+ "accelerate",+ "bitsandbytes",+ "vllm",+ "triton",+ "xformers",+ "datasets",+ # The transitive runtime packages the canary and frontier resolutions are+ # allowed to move, which are not optional extras here: the frontier leg+ # installs transformers and trl WITH their dependencies precisely so pip+ # repairs them, and legs.py records the resolution doing it -- "Would+ # install datasets-5.0.1 huggingface_hub-1.27.0 transformers-5.15.0+ # trl-1.9.2", and before that the two errors that forced the change,+ # "tokenizers<=0.23.0,>=0.22.0 is required, but found tokenizers==0.23.1"+ # and "safetensors>=0.8.0 is required, but found safetensors==0.7.0".+ #+ # Left out, a red canary attributable to one of them produced a comparison+ # table with nothing in it that differed: the table showed the packages the+ # leg names and the failure was in a package it moved. Attribution is the+ # only reason to run the canary at all.+ "tokenizers",+ "safetensors",+ "huggingface_hub",+ "unsloth",+ "unsloth_zoo",+)++# Exactly one of the above has a distribution name differing from its import+# name; getting it wrong records "not installed" for a package that is.+_DISTRIBUTION = {"unsloth_zoo": "unsloth-zoo"}+++def distribution_version(module: str):+ """The installed distribution's version, or None if it is not installed."""+ import importlib.metadata as md++ for name in (_DISTRIBUTION.get(module, module), module):+ try:+ return md.version(name)+ except Exception: # noqa: BLE001+ continue+ return None+++def import_version(module: str):+ """``__version__`` after a real import, or an error string.++ Importing is the point: ``vllm`` on a compute capability its wheel was not+ built for installs cleanly and raises on import, and that is the finding.+ """+ import importlib+ try:+ return getattr(importlib.import_module(module), "__version__", "unknown")+ except BaseException as exc: # noqa: BLE001+ return f"IMPORT FAILED: {type(exc).__name__}: {str(exc)[:200]}"+++def resolved_versions(packages = GOAL_PACKAGES, *, import_check = ()) -> dict:+ """``{package: {"installed": ..., "imported": ...}}`` for the goal list.++ ``import_check`` names the subset worth paying an import for: importing+ everything would pull ``vllm`` into payloads with no use for it and add a+ minute for a number the metadata already gave, so callers opt in per+ package.+ """+ out: dict = {}+ for name in packages:+ installed = distribution_version(name)+ entry: dict = {"installed": installed}+ if name in import_check and installed is not None:+ entry["imported"] = import_version(name)+ out[name] = entry+ return out+++def flatten_versions(resolved: dict) -> dict:+ """``{package: version-or-None}``, for a one-line summary.++ The installed version leads: it is what a bisect over releases acts on. An+ import failure is surfaced alongside it, so a package that is present and+ unusable does not read as present and fine.+ """+ flat = {}+ for name, entry in resolved.items():+ imported = entry.get("imported")+ if isinstance(imported, str) and imported.startswith("IMPORT FAILED"):+ flat[name] = f"{entry.get('installed')} ({imported})"+ else:+ flat[name] = entry.get("installed")+ return flat+++def load_pins(path) -> dict:+ """A ``package==version`` pin file, parsed. Blank and ``#`` lines ignored."""+ from pathlib import Path++ pins: dict = {}+ text = Path(path).read_text(encoding = "utf-8")+ for line in text.splitlines():+ line = line.split("#", 1)[0].strip()+ if not line:+ continue+ name, sep, version = line.partition("==")+ if not sep:+ raise ValueError(f"pin file line is not name==version: {line!r}")+ pins[name.strip().replace("-", "_")] = version.strip()+ return pins+++def pin_failures(pins: dict, resolved: dict) -> list[str]:+ """Pins that did not hold.++ A control leg whose pins a transitive dependency silently overrode is not a+ control, and every canary-vs-control conclusion drawn from it would be+ wrong. A pin naming a package that is not installed is the same defect from+ the other side, so it is reported too.++ "Not probed" is a THIRD outcome and is kept apart from "not installed".+ ``resolved`` is whatever the caller asked ``resolved_versions`` about, so a+ pin outside that list has no entry at all, and folding it in with "it is not+ installed" is a failure invented about a package that may be installed and+ correct. Callers derive the probe list from the pin file (see+ ``versions_for_pins``) so this cannot normally happen; it is reported rather+ than assumed away because the invented failure is indistinguishable from a+ real one in a report.+ """+ failures = []+ for name, wanted in sorted(pins.items()):+ if name not in resolved:+ failures.append(+ f"pinned {name}=={wanted} but no version of it was recorded, so "+ f"whether the pin held is unknown"+ )+ continue+ got = (resolved.get(name) or {}).get("installed")+ if got is None:+ failures.append(f"pinned {name}=={wanted} but it is not installed")+ elif got != wanted:+ failures.append(f"pinned {name}=={wanted} but {got} was resolved")+ return failures+++def versions_for_pins(+ pins: dict,+ packages = GOAL_PACKAGES,+ *,+ import_check = (),+) -> dict:+ """``resolved_versions`` over the goal list AND everything ``pins`` names.++ The probe list is derived from the pin file rather than assumed to cover+ it. Pinning a package the goal list does not carry used to make+ ``pin_failures`` report it as not installed, since the lookup answered from+ a table that was never asked about it: a control leg failing on a pin that+ held perfectly.+ """+ ordered = list(packages) + [name for name in pins if name not in packages]+ return resolved_versions(tuple(ordered), import_check = import_check)diff --git a/tests/kaggle/test_t4_ci_transport.py b/tests/kaggle/test_t4_ci_transport.pynew file mode 100644index 00000000000..f43831aec09--- /dev/null+++ b/tests/kaggle/test_t4_ci_transport.py@@ -0,0 +1,1663 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""What the kernel builder generates and what the launcher can read back.++The transport, not the payloads: the generated driver and payload cells are+EXECUTED here with Kaggle replaced by a stub, so a control-flow mistake in a+cell that only runs on a Kaggle T4 is caught on a runner. No network call, no+credential and no GPU -- `subprocess` is swapped out wholesale for the driver+cells, and the payload cells executed stop before they reach torch.+"""++from __future__ import annotations++import json+import os+import subprocess+import sys+import tempfile+import types+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parents[2]+SMOKE_DIR = REPO_ROOT / "tests" / "kaggle" / "t4_smoke"+CI_DIR = REPO_ROOT / ".github" / "scripts" / "kaggle_t4_ci"++sys.path.insert(0, str(SMOKE_DIR))+sys.path.insert(0, str(CI_DIR))++import build_kernel # noqa: E402+import gate # noqa: E402+import launch # noqa: E402+from legs import LEGS # noqa: E402+++# ------------------------------------------------------------------ driver+++class _Stub:+ """Stands in for `subprocess` while the generated driver cells run.++ Answers the four commands the driver issues (GPU probe, `which uv`, venv+ build, papermill) and records what papermill was handed, which is where the+ per-payload isolation is either present or not.+ """++ def __init__(+ self,+ *,+ gpus: int,+ venv_ok: bool = True,+ ):+ self.gpus = gpus+ self.venv_ok = venv_ok+ self.papermill: list[dict] = []+ self.TimeoutExpired = subprocess.TimeoutExpired+ self.CalledProcessError = subprocess.CalledProcessError+ self.STDOUT = subprocess.STDOUT++ def run(self, cmd, **kw):+ cmd = [str(c) for c in cmd]+ if cmd[0] == "nvidia-smi":+ if self.gpus < 0:+ raise OSError("nvidia-smi is not on this box")+ out = "".join("Tesla T4, 15360 MiB\n" for _ in range(self.gpus))+ return types.SimpleNamespace(returncode = 0, stdout = out, stderr = "")+ if cmd[0] == "which":+ return types.SimpleNamespace(returncode = 0, stdout = "/usr/bin/uv\n", stderr = "")+ if "papermill" in cmd:+ env = kw.get("env") or {}+ self.papermill.append(+ {+ "notebook": Path(cmd[cmd.index("papermill") + 1]).name,+ "cuda": env.get("CUDA_VISIBLE_DEVICES"),+ "kernel": cmd[cmd.index("-k") + 1],+ "compile_location": env.get("UNSLOTH_COMPILE_LOCATION"),+ }+ )+ Path(cmd[cmd.index("papermill") + 2]).write_text("{}", encoding = "utf-8")+ return types.SimpleNamespace(returncode = 0, stdout = "", stderr = "")+ if not self.venv_ok:+ raise subprocess.CalledProcessError(1, cmd)+ return types.SimpleNamespace(returncode = 0, stdout = "", stderr = "")+++def _drive(+ tmp_path: Path,+ leg_names,+ *,+ gpus: int,+ venv_ok: bool = True,+) -> dict:+ """Run the generated driver's setup and runner cells against the stub.++ The only edit to the generated source is the `/kaggle/working` literal,+ rewritten to a temp directory so the cells run off a Kaggle box.+ """+ driver = build_kernel.build_kernel(+ SMOKE_DIR,+ leg_names,+ unsloth_ref = "main",+ zoo_ref = "main",+ extra_args = (),+ per_run_timeout = 60,+ skip_reference = True,+ )+ stub = _Stub(gpus = gpus, venv_ok = venv_ok)+ saved = sys.modules["subprocess"]+ sys.modules["subprocess"] = stub+ namespace: dict = {}+ raised = None+ try:+ for cell in driver["cells"][:2]:+ source = "".join(cell["source"]).replace("/kaggle/working", str(tmp_path))+ try:+ exec(compile(source, "<driver-cell>", "exec"), namespace)+ except SystemExit as exc:+ raised = exc+ break+ finally:+ sys.modules["subprocess"] = saved+ return {+ "stood_down": raised,+ "n_gpu": namespace.get("N_GPU"),+ "papermill": stub.papermill,+ "results": namespace.get("results") or {},+ }+++def test_a_gpu_shortfall_stands_the_kernel_down(tmp_path):+ """A missing GPU is infrastructure, not a result.++ `max(1, len(GPUS))` put both payloads on device 0, where each child still+ sees one card and passes its own visibility assertion, so a contended OOM+ came back looking like a code failure.+ """+ driven = _drive(tmp_path, ["control", "canary"], gpus = -1)+ assert driven["stood_down"] is not None, "a 1-GPU allocation ran both payloads anyway"+ assert driven["papermill"] == []+++def test_two_gpus_still_run_both_payloads_one_per_card(tmp_path):+ driven = _drive(tmp_path, ["control", "canary"], gpus = 2)+ assert driven["stood_down"] is None+ assert sorted(p["cuda"] for p in driven["papermill"]) == ["0", "1"]+++def test_a_payload_whose_venv_failed_is_not_run_in_the_system_kernel(tmp_path):+ """Falling back to `python3` puts both legs' installs in one tree.++ The legs deliberately install different library sets, so a shared+ site-packages destroys the comparison rather than merely risking+ corruption, and the resulting import error reads as a code regression.+ """+ driven = _drive(tmp_path, ["control", "canary"], gpus = 2, venv_ok = False)+ assert [+ p["kernel"] for p in driven["papermill"]+ ] == [], "a payload ran in the shared system kernel after its venv failed"+ assert driven["results"], "the skipped payloads left no record"+ for entry in driven["results"].values():+ assert entry["error"]+++def test_each_payload_compiles_into_its_own_cache(tmp_path):+ """Concurrent legs must not share `unsloth_compiled_cache`.++ It is a relative path resolved against the working directory that both+ papermill children inherit, and the legs compile the same modules against+ deliberately different transformers/TRL versions.+ """+ driven = _drive(tmp_path, ["control", "canary"], gpus = 2)+ locations = [p["compile_location"] for p in driven["papermill"]]+ assert all(locations), "no per-payload UNSLOTH_COMPILE_LOCATION was set"+ assert len(set(locations)) == len(locations), f"shared compile cache: {locations}"+++def test_the_prune_still_reaches_the_per_payload_directories():+ """Whatever the per-payload names are, the tail cell must still drop them.++ `kernels output` ships the whole of /kaggle/working back over the wire, and+ a sweep that missed the venvs once shipped 371MB.+ """+ driver = build_kernel.build_driver({"t4_control.ipynb": {"cells": []}}, 60)+ tail = "".join(driver["cells"][2]["source"])+ assert '"unsloth_compiled_cache*"' in tail or "'unsloth_compiled_cache*'" in tail+ assert '"t4_smoke_src*"' in tail or "'t4_smoke_src*'" in tail+++# ----------------------------------------------------------------- payload+++def _payload_cells(leg, **kw) -> list[str]:+ notebook = build_kernel.build_payload_notebook(+ SMOKE_DIR, leg, unsloth_ref = "main", zoo_ref = "main", reference = "", **kw+ )+ return ["".join(cell["source"]) for cell in notebook["cells"]]+++def test_each_payload_materialises_into_its_own_directory():+ """Two payloads writing one directory can truncate a file the other reads.++ `write_bytes` truncates first and the legs carry byte-identical copies of+ the same sources, so the loser of that race imports a partial file and dies+ for a reason unrelated to the commit.+ """+ roots = set()+ for name in ("control", "canary"):+ materialise = _payload_cells(LEGS[name])[0]+ roots.add(materialise.split("ROOT = pathlib.Path(")[1].split(")")[0])+ assert len(roots) == 2, f"both payloads materialise into {roots}"+++def test_a_shared_argument_does_not_override_a_legs_own_option():+ """`--smoke-args` is shared so control and canary stay comparable.++ It must not reach a leg that already sets that option: the gpt-oss leg's 3+ steps are a measured fit for a 16GB card, and argparse takes the LAST value,+ so appending the SFT legs' 10 silently retrained the 20B leg.+ """+ run_cell = _payload_cells(LEGS["gptoss"], extra_args = ("--max-steps", "10"))[3]+ argv = run_cell.split("cmd += [")[1].split("]")[0]+ assert argv.count('"--max-steps"') == 1, argv+ assert '"3"' in argv and '"10"' not in argv++ # A leg that does NOT set it still receives the shared value.+ canary = _payload_cells(LEGS["canary"], extra_args = ("--max-steps", "10"))[3]+ assert '"--max-steps", "10"' in canary.split("cmd += [")[1]+++def test_a_probe_failure_is_reported_as_a_failed_payload(tmp_path, monkeypatch):+ """A commit that breaks `import unsloth` must not exit green.++ The probe raises before the run cell can write a report, so without one of+ its own the launcher extracts nothing, calls the run `infra` and passes on a+ deterministic import regression.+ """+ monkeypatch.setattr(build_kernel, "KERNEL_ROOT", str(tmp_path / "src"))+ leg = LEGS["control"]+ broken = type(leg)(+ **{+ **{field: getattr(leg, field) for field in leg.__dataclass_fields__},+ "imports": ("unsloth_module_the_broken_commit_cannot_import",),+ }+ )+ cells = _payload_cells(broken)++ outputs = []+ for index in (0, 2):+ script = tmp_path / f"cell{index}.py"+ script.write_text(cells[index], encoding = "utf-8")+ proc = subprocess.run(+ [sys.executable, str(script)], capture_output = True, text = True, timeout = 600+ )+ outputs.append(proc.stdout + proc.stderr)+ assert "KAGGLE_T4_CI_PAYLOAD MISSING" in outputs[1]++ # What Kaggle brings back, and what the launcher makes of it.+ evidence = tmp_path / "evidence"+ evidence.mkdir()+ (evidence / "t4_control_output.ipynb").write_text(+ json.dumps(+ {+ "cells": [+ {"cell_type": "code", "outputs": [{"output_type": "stream", "text": text}]}+ for text in outputs+ ]+ }+ ),+ encoding = "utf-8",+ )+ reports = launch.extract_reports(evidence)+ assert reports, "the import failure produced no report at all"+ assert reports[0]["passed"] is False+ assert reports[0]["label"] == "control"+ assert any(+ "unsloth_module_the_broken_commit_cannot_import" in f for f in reports[0]["failures"]+ )++ # The resolved versions are printed one line above the failure, and+ # report.version_table reads them off the REPORT rather than the log, so+ # without them the summary cannot say which release the red leg had.+ import report as report_module++ assert report_module.resolved_versions(reports[0]), reports[0].keys()+ table = report_module.version_table(+ [reports[0], {"label": "control", "versions_flat": {"transformers": "4.57.6"}}]+ )+ assert any("| package | control |" in line for line in table), table+++def test_an_install_that_cannot_be_resolved_is_reported_as_a_failed_payload(tmp_path, monkeypatch):+ """Three exhausted pip attempts used to raise without reporting anything.++ The launcher then sees a leg with no report, calls the run `partial` or+ `infra` and exits GREEN, so the job added to catch a broken distribution+ could not fail on one.+ """+ monkeypatch.setattr(build_kernel, "KERNEL_ROOT", str(tmp_path / "src"))+ install = _payload_cells(LEGS["control"])[1]+ script = tmp_path / "install.py"+ script.write_text(+ "import subprocess, time, types\n"+ "subprocess.run = lambda cmd, **kw: types.SimpleNamespace(\n"+ " returncode=1, stdout='', stderr='ERROR: ResolutionImpossible')\n"+ "time.sleep = lambda _s: None\n" + install,+ encoding = "utf-8",+ )+ proc = subprocess.run(+ [sys.executable, str(script)], capture_output = True, text = True, timeout = 600+ )+ assert proc.returncode != 0+ assert "KAGGLE_T4_CI_PAYLOAD INSTALL FAILED" in proc.stdout++ evidence = tmp_path / "evidence"+ evidence.mkdir()+ (evidence / "kernel.log").write_text(proc.stdout + proc.stderr, encoding = "utf-8")+ reports = launch.extract_reports(evidence)+ assert reports, "the exhausted install produced no report at all"+ assert reports[0]["label"] == "control"+ assert reports[0]["passed"] is False+ assert any("ResolutionImpossible" in f for f in reports[0]["failures"])+++def test_the_install_backs_off_between_attempts():+ """Three immediate retries all land inside the same upstream blip.++ The third failure is what the failed-payload report above rests on, so it+ has to mean "this cannot be resolved" rather than "one bad minute".+ """+ install = _payload_cells(LEGS["control"])[1]+ assert "time.sleep(15 * attempt)" in install+++# ------------------------------------------------------------------ launcher++[email protected]("plain", [False, True])+def test_a_report_reaches_the_launcher_through_kaggles_structured_log(tmp_path, plain):+ """The log fallback exists for the run whose notebook never came back.++ Kaggle hands the log over as a JSON array of stream records, so scanning it+ as text finds no line starting with the report prefix and files a real+ failure as `infra`.+ """+ payload = {+ "label": "control",+ "model": "unsloth/Qwen2.5-0.5B",+ "passed": False,+ "failures": ["reference band: out of band at step 3"],+ }+ line = launch.RESULT_PREFIX + json.dumps(payload) + "\n"+ body = (+ line+ if plain+ else json.dumps(+ [+ {"stream_name": "stdout", "time": 12.0, "data": "install done\n"},+ {"stream_name": "stdout", "time": 13.0, "data": line},+ ]+ )+ )+ kernel_dir = tmp_path / "unsloth-t4-ci-deadbeef"+ kernel_dir.mkdir()+ (kernel_dir / "kernel.log").write_text(body, 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_log_record_that_splits_the_report_is_still_read(tmp_path):+ """Record boundaries are not line boundaries; join before scanning."""+ payload = {"label": "canary", "model": "unsloth/Qwen2.5-0.5B", "passed": True}+ line = launch.RESULT_PREFIX + json.dumps(payload) + "\n"+ half = len(line) // 2+ kernel_dir = tmp_path / "unsloth-t4-ci-cafe"+ kernel_dir.mkdir()+ (kernel_dir / "kernel.log").write_text(+ json.dumps(+ [+ {"stream_name": "stdout", "data": line[:half]},+ {"stream_name": "stdout", "data": line[half:]},+ ]+ ),+ encoding = "utf-8",+ )+ assert [r["label"] for r in launch.extract_reports(tmp_path)] == ["canary"]+++def test_every_push_attempt_gets_its_own_slug(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+ session rather than superseding the running one, and `kernels/output` and+ `kernels status` never pass a version label, so they answer for the latest+ session only. A retry after a lost response therefore reads the wrong+ execution's evidence while the first keeps billing unseen.+ """+ attempts: list[list[str]] = []+ deleted: list[str] = []++ def fake_run(cmd, **kw):+ cmd = [str(c) for c in cmd]+ attempts.append(cmd)+ if cmd[1:3] == ["kernels", "delete"]:+ deleted.append(cmd[3])+ return types.SimpleNamespace(returncode = 0, stdout = "", stderr = "")+ metadata = json.loads((Path(cmd[cmd.index("-p") + 1]) / "kernel-metadata.json").read_text())+ attempts[-1] = ["push", metadata["id"]]+ if len(deleted) + 1 < 3:+ return types.SimpleNamespace(returncode = 1, stdout = "", stderr = "Connection reset")+ return types.SimpleNamespace(returncode = 0, stdout = "Successfully pushed", stderr = "")++ monkeypatch.setattr(launch.subprocess, "run", fake_run)+ monkeypatch.setattr(launch.time, "sleep", lambda _s: None)+ pushed = launch.push(Path(__file__), "someuser", 3600)++ slugs = [a[1] for a in attempts if a[0] == "push"]+ assert len(slugs) == 3, slugs+ assert len(set(slugs)) == 3, f"every retry reused one slug: {slugs}"+ assert pushed["ok"] and pushed["slug"] == slugs[-1]+ # Each earlier attempt may have landed despite its error, so it is deleted+ # before the next adds a second concurrent session.+ assert deleted == [s for s in slugs[:-1]]+ assert pushed["attempts"] == slugs+++def _drive_main(+ monkeypatch,+ tmp_path,+ *,+ push_seconds,+ pushes,+ extra_argv = (),+ api_seconds = 0.0,+):+ """Run `launch.main()` end to end with Kaggle replaced by stubs.++ Returns the per-kernel wait budgets, the slugs deleted on the way out and+ the launch result. The clock is fake, so a push can burn arbitrary wall+ time without the test taking any.++ ``api_seconds`` is what authentication costs. It is not free: with+ KAGGLE_API_TOKEN set, which is the only credential the workflow passes,+ `authenticate()` introspects the token over the network.+ """+ clock = {"t": 1_000_000.0}+ monkeypatch.setattr(launch.time, "time", lambda: clock["t"])+ monkeypatch.setattr(launch.time, "sleep", lambda _s: None)++ def fake_api():+ clock["t"] += api_seconds+ return object()++ monkeypatch.setattr(launch, "_api", fake_api)++ outcomes = list(pushes)++ def fake_push(+ notebook,+ user,+ kernel_timeout_sec,+ accelerator = "NvidiaTeslaT4",+ attempted = None,+ ):+ clock["t"] += push_seconds+ outcome = outcomes.pop(0)+ # Like the real one: the caller's list is filled as the slugs are filed.+ if attempted is not None:+ attempted.extend(outcome.get("attempts") or [])+ return outcome++ waits: list[int] = []++ def fake_wait(api, slug, poll_every, max_wait):+ waits.append(max_wait)+ return "COMPLETE"++ deleted: list[str] = []++ def fake_run(cmd, **kw):+ cmd = [str(c) for c in cmd]+ if cmd[1:3] == ["kernels", "delete"]:+ deleted.append(cmd[3])+ return types.SimpleNamespace(returncode = 0, stdout = "", stderr = "")++ monkeypatch.setattr(launch, "push", fake_push)+ monkeypatch.setattr(launch, "wait", fake_wait)+ monkeypatch.setattr(+ launch, "fetch_evidence", lambda slug, outdir, **kw: {"notebooks": [], "log": None}+ )+ monkeypatch.setattr(+ launch,+ "extract_reports",+ lambda outdir: [{"label": "control", "model": "m", "passed": True}],+ )+ monkeypatch.setattr(launch.subprocess, "run", fake_run)+ monkeypatch.delenv("GITHUB_OUTPUT", raising = False)+ monkeypatch.setattr(+ sys,+ "argv",+ [+ "launch.py",+ *[a for i in range(len(pushes)) for a in ("--notebook", f"k{i}.ipynb")],+ "--user",+ "someuser",+ "--outdir",+ str(tmp_path),+ "--expect",+ "1",+ "--max-wait",+ "5400",+ *extra_argv,+ ],+ )+ assert launch.main() == 0+ result = json.loads((tmp_path / "launch_result.json").read_text(encoding = "utf-8"))+ return waits, deleted, result+++_TWO_PUSHES = [+ {+ "ok": True,+ "slug": "someuser/unsloth-t4-ci-aaaa",+ "attempts": ["someuser/unsloth-t4-ci-aaaa"],+ },+ {+ "ok": True,+ "slug": "someuser/unsloth-t4-ci-bbbb",+ "attempts": ["someuser/unsloth-t4-ci-bbbb"],+ },+]+++def test_the_launcher_will_not_push_what_it_may_not_live_to_delete(monkeypatch, tmp_path):+ """A window one second short of the worst case pushes nothing.++ The job that runs this launcher is killed at a fixed time and killing it+ takes release() with it, so a kernel pushed with less than the launcher's+ own worst case left can be left up billing quota to its own ceiling. The+ steps before it -- a checkout, a pip install, the harness suite -- have no+ deadline of their own, so the job timeout leaving room for them is an+ assumption rather than a fact about the run; this measures what is actually+ left.+ """+ _, deleted, result = _drive_main(+ monkeypatch,+ tmp_path,+ push_seconds = 0.0,+ pushes = _TWO_PUSHES,+ extra_argv = (+ "--deadline-epoch",+ str(int(1_000_000 + launch.worst_case_seconds(5400, 2)) - 1),+ ),+ )+ assert not result.get("kernels"), "a kernel was pushed with no room to delete it"+ assert result["slug"] is None and deleted == []+ assert result["verdict"] == "infra"+ assert "could be killed during cleanup" in result["reason"]+++def test_a_window_that_fits_still_launches(monkeypatch, tmp_path):+ """The guard has to stand down for a short window and ONLY for one.++ One second more than the worst case is the whole of it, so this is the+ ordinary run: a guard that refused here, or that read the deadline as an+ absolute duration rather than the moment the job dies, would stand every+ invocation down and the workflow would never test anything again -- green+ every time, which is exactly how it would go unnoticed.+ """+ waits, _, result = _drive_main(+ monkeypatch,+ tmp_path,+ push_seconds = 0.0,+ pushes = _TWO_PUSHES,+ extra_argv = (+ "--deadline-epoch",+ str(int(1_000_000 + launch.worst_case_seconds(5400, 2))),+ ),+ )+ assert [k["slug"] for k in result["kernels"]] == [p["slug"] for p in _TWO_PUSHES]+ assert waits == [5400, 5400]+ assert result["verdict"] == "pass"+++def test_the_window_is_measured_again_after_authenticating(monkeypatch, tmp_path):+ """Authentication sits between the guard and the first push, and costs time.++ `_api()` calls `KaggleApi.authenticate()`, and the only credential this+ workflow passes is KAGGLE_API_TOKEN, so kaggle 2.2.4 takes the access-token+ branch: `_authenticate_with_access_token` -> `_introspect_token`, an HTTP+ round trip whose only bound is the process-wide SOCKET_TIMEOUT_SEC. Checked+ once, before that call, a window that fitted by less than the timeout is+ already gone by the time the first kernel is pushed, and being killed during+ release() is what leaves kernels billing.+ """+ _, deleted, result = _drive_main(+ monkeypatch,+ tmp_path,+ push_seconds = 0.0,+ pushes = _TWO_PUSHES,+ api_seconds = float(launch.SOCKET_TIMEOUT_SEC),+ extra_argv = (+ "--deadline-epoch",+ str(int(1_000_000 + launch.worst_case_seconds(5400, 2)) + 60),+ ),+ )+ assert not result.get("kernels"), "a kernel was pushed after the window went"+ assert result["slug"] is None and deleted == []+ assert result["verdict"] == "infra"+ assert "could be killed during cleanup" in result["reason"]+++def test_a_window_that_survives_authentication_still_launches(monkeypatch, tmp_path):+ """The recheck must cost the ordinary run nothing.++ Authentication that returns well inside the slack leaves the worst case+ covered, and a second guard that stood down here would make every run green+ without testing anything, which is the failure mode this whole guard is+ least able to notice.+ """+ _, _, result = _drive_main(+ monkeypatch,+ tmp_path,+ push_seconds = 0.0,+ pushes = _TWO_PUSHES,+ api_seconds = 30.0,+ extra_argv = (+ "--deadline-epoch",+ str(int(1_000_000 + launch.worst_case_seconds(5400, 2)) + 60),+ ),+ )+ assert [k["slug"] for k in result["kernels"]] == [p["slug"] for p in _TWO_PUSHES]+ assert result["verdict"] == "pass"+++def test_no_deadline_is_no_guard(monkeypatch, tmp_path):+ """Run by hand, with no job to be killed by, there is nothing to check.++ The flag defaults to 0 and the launcher then pushes exactly as it always+ did, so a local reproduction does not have to invent a deadline to get a+ kernel.+ """+ _, _, result = _drive_main(+ monkeypatch,+ tmp_path,+ push_seconds = 0.0,+ pushes = _TWO_PUSHES,+ )+ assert [k["slug"] for k in result["kernels"]] == [p["slug"] for p in _TWO_PUSHES]+++def test_the_deletion_deadline_covers_the_time_spent_pushing(monkeypatch, tmp_path):+ """A kernel bills from the moment Kaggle accepts it, not from the last push.++ Started after the push loop, the deadline gave the first kernel --max-wait+ on top of the SECOND push's retries: 45 minutes of throttling turned a 90+ minute ceiling into 135 minutes of billing, past the budget the gate+ reserved for the run.+ """+ waits, _, _ = _drive_main(+ monkeypatch,+ tmp_path,+ push_seconds = 1800.0,+ pushes = [+ {+ "ok": True,+ "slug": "someuser/unsloth-t4-ci-aaaa",+ "attempts": ["someuser/unsloth-t4-ci-aaaa"],+ },+ {+ "ok": True,+ "slug": "someuser/unsloth-t4-ci-bbbb",+ "attempts": ["someuser/unsloth-t4-ci-bbbb"],+ },+ ],+ )+ # 5400s of invocation deadline, 3600s of it spent pushing.+ assert waits == [1800, 1800]+++def test_every_slug_a_push_filed_is_deleted_on_the_way_out(monkeypatch, tmp_path):+ """An attempt whose response was lost may be running, and is untracked.++ `push()` records every slug it filed because Kaggle answers an accepted push+ with a 5xx or a reset connection often enough to be a known issue. Cleanup+ read only the ACCEPTED slug, so a failed final attempt (which has none) and+ any earlier attempt whose discard was refused kept a session slot and billed+ quota unseen.+ """+ _, deleted, result = _drive_main(+ monkeypatch,+ tmp_path,+ push_seconds = 0.0,+ pushes = [+ # Accepted on the third attempt; the first two may still be up.+ {+ "ok": True,+ "slug": "someuser/unsloth-t4-ci-cccc",+ "attempts": [+ "someuser/unsloth-t4-ci-aaaa",+ "someuser/unsloth-t4-ci-bbbb",+ "someuser/unsloth-t4-ci-cccc",+ ],+ },+ # Never accepted, so no `slug`, and the last attempt is the+ # ambiguous one.+ {+ "ok": False,+ "reason": "push_failed",+ "detail": "Connection reset by peer",+ "attempts": ["someuser/unsloth-t4-ci-dddd", "someuser/unsloth-t4-ci-eeee"],+ },+ ],+ )+ assert sorted(deleted) == [+ "someuser/unsloth-t4-ci-aaaa",+ "someuser/unsloth-t4-ci-bbbb",+ "someuser/unsloth-t4-ci-cccc",+ "someuser/unsloth-t4-ci-dddd",+ "someuser/unsloth-t4-ci-eeee",+ ]+ assert all(k["released"] for k in result["kernels"])+++def test_the_temp_dir_is_left_alone_when_the_log_is_not_json(tmp_path):+ """A plain-text log, and a JSON object that is not a record array."""+ kernel_dir = tmp_path / "unsloth-t4-ci-beef"+ kernel_dir.mkdir()+ (kernel_dir / "kernel.log").write_text(json.dumps({"log": "nothing here"}), encoding = "utf-8")+ assert launch.extract_reports(tmp_path) == []+++def test_a_push_that_runs_out_of_wall_clock_is_a_recorded_failure(monkeypatch):+ """`subprocess.run(timeout=...)` RAISES; it does not return a bad result.++ That exception used to leave `push()` entirely, taking the slugs it had+ filed. Those are the most ambiguous slugs there are, the client having been+ killed mid-call so that whether Kaggle accepted the kernel is unknowable,+ and losing them means nothing can delete the session one may have started.+ """+ deleted: list[str] = []++ def fake_run(cmd, **kw):+ cmd = [str(c) for c in cmd]+ if cmd[1:3] == ["kernels", "delete"]:+ deleted.append(cmd[3])+ return types.SimpleNamespace(returncode = 0, stdout = "", stderr = "")+ raise subprocess.TimeoutExpired(cmd, launch.PUSH_SUBPROCESS_TIMEOUT_SEC)++ monkeypatch.setattr(launch.subprocess, "run", fake_run)+ monkeypatch.setattr(launch.time, "sleep", lambda _s: None)++ pushed = launch.push(Path(__file__), "someuser", 3600)+ assert pushed["ok"] is False+ # A timeout is Kaggle under load, so it retries like any throttle, and every+ # slug filed comes back for the caller to reconcile.+ assert len(pushed["attempts"]) == launch.PUSH_ATTEMPTS+ assert len(set(pushed["attempts"])) == launch.PUSH_ATTEMPTS+ assert "timed out" in pushed["detail"]+ # Each attempt discards the previous one before adding another session.+ assert deleted == pushed["attempts"][:-1]+++def test_a_push_that_times_out_does_not_abandon_the_kernel_already_accepted(monkeypatch, tmp_path):+ """The case that costs quota: kernel 1 is up when kernel 2's push hangs.++ Nothing caught that exception, so `main()` exited without `release()` and+ without writing launch_result.json, and the workflow has no cleanup step of+ its own. The accepted kernel then billed to its ceiling with nobody reading+ its result, and Kaggle's push-time timeout has been measured not to stop a+ wedged one.+ """+ deleted: list[str] = []+ pushes = {"n": 0}++ def fake_run(cmd, **kw):+ cmd = [str(c) for c in cmd]+ if cmd[1:3] == ["kernels", "delete"]:+ deleted.append(cmd[3])+ return types.SimpleNamespace(returncode = 0, stdout = "", stderr = "")+ pushes["n"] += 1+ if pushes["n"] == 1:+ return types.SimpleNamespace(+ returncode = 0, stdout = "Kernel version 1 successfully pushed", stderr = ""+ )+ raise subprocess.TimeoutExpired(cmd, launch.PUSH_SUBPROCESS_TIMEOUT_SEC)++ monkeypatch.setattr(launch.subprocess, "run", fake_run)+ monkeypatch.setattr(launch.time, "sleep", lambda _s: None)+ monkeypatch.setattr(launch, "_api", lambda: object())+ monkeypatch.setattr(launch, "wait", lambda api, slug, poll_every, max_wait: "COMPLETE")+ monkeypatch.setattr(+ launch, "fetch_evidence", lambda slug, outdir, **kw: {"notebooks": [], "log": None}+ )+ monkeypatch.setattr(+ launch,+ "extract_reports",+ lambda outdir: [{"label": "control", "model": "m", "passed": True}],+ )+ monkeypatch.delenv("GITHUB_OUTPUT", raising = False)+ monkeypatch.setattr(+ sys,+ "argv",+ [+ "launch.py",+ "--notebook",+ str(tmp_path / "k0.ipynb"),+ "--notebook",+ str(tmp_path / "k1.ipynb"),+ "--user",+ "someuser",+ "--outdir",+ str(tmp_path / "ev"),+ "--expect",+ "2",+ ],+ )+ (tmp_path / "k0.ipynb").write_text("{}", encoding = "utf-8")+ (tmp_path / "k1.ipynb").write_text("{}", encoding = "utf-8")++ assert launch.main() == 0+ result = json.loads((tmp_path / "ev" / "launch_result.json").read_text(encoding = "utf-8"))+ accepted = result["kernels"][0]["slug"]+ assert accepted and accepted in deleted+ # Including every slug the timed-out push filed, any of which may be the+ # session Kaggle accepted and never reported.+ for slug in result["kernels"][1]["attempted"]:+ assert slug in deleted, slug+ assert all(k["released"] for k in result["kernels"])+++ "boom",+ [+ # `text=True` wraps the pipes in a TextIOWrapper with STRICT error+ # handling, so one byte the locale encoding cannot decode raises out of+ # `subprocess.run` itself, after the request was filed.+ UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid start byte"),+ # And the runner's own answers, which are not the foreseen ones either.+ OSError("cannot allocate memory"),+ MemoryError("the runner ran out"),+ ],+ ids = ["decode", "oserror", "memory"],+)+def test_a_push_that_raises_outside_the_timeout_still_gives_up_its_slug(+ monkeypatch, tmp_path, boom+):+ """The slug is filed BEFORE `kaggle kernels push` is invoked.++ So the failure that loses it is not the push reporting an error -- that is+ reported and reconciled -- but the push raising something the retry loop+ does not handle. Only `TimeoutExpired` was, and every other raise unwound+ past the line that filed the entry, so `release()` iterated a list with no+ entry for this notebook at all and a kernel Kaggle may have accepted was+ left billing to its own ceiling with nobody reading it.++ Reconciliation must therefore not depend on `push()` RETURNING.+ """+ deleted: list[str] = []+ pushes = {"n": 0}++ def fake_run(cmd, **kw):+ cmd = [str(c) for c in cmd]+ if cmd[1:3] == ["kernels", "delete"]:+ deleted.append(cmd[3])+ return types.SimpleNamespace(returncode = 0, stdout = "", stderr = "")+ pushes["n"] += 1+ if pushes["n"] == 1:+ return types.SimpleNamespace(+ returncode = 0, stdout = "Kernel version 1 successfully pushed", stderr = ""+ )+ raise boom++ monkeypatch.setattr(launch.subprocess, "run", fake_run)+ monkeypatch.setattr(launch.time, "sleep", lambda _s: None)+ monkeypatch.setattr(launch, "_api", lambda: object())+ monkeypatch.setattr(launch, "wait", lambda api, slug, poll_every, max_wait: "COMPLETE")+ monkeypatch.delenv("GITHUB_OUTPUT", raising = False)+ (tmp_path / "k0.ipynb").write_text("{}", encoding = "utf-8")+ (tmp_path / "k1.ipynb").write_text("{}", encoding = "utf-8")+ monkeypatch.setattr(+ sys,+ "argv",+ [+ "launch.py",+ "--notebook",+ str(tmp_path / "k0.ipynb"),+ "--notebook",+ str(tmp_path / "k1.ipynb"),+ "--user",+ "someuser",+ "--outdir",+ str(tmp_path / "ev"),+ "--expect",+ "2",+ ],+ )++ assert launch.main() == 0+ result = json.loads((tmp_path / "ev" / "launch_result.json").read_text(encoding = "utf-8"))+ assert result["verdict"] == "infra"+ assert len(result["kernels"]) == 2, "the notebook whose push raised left no entry to reconcile"+ raised_on = result["kernels"][1]+ assert raised_on["attempted"], "the slug that push filed was lost with the exception"+ for slug in raised_on["attempted"]:+ assert slug in deleted, slug+ # And the kernel already accepted goes too, as it did for the timeout.+ assert result["kernels"][0]["slug"] in deleted+ assert all(k["released"] for k in result["kernels"])+ assert result["unreleased"] == []+++def _accepting_push(slug: str):+ """A `push` stub Kaggle accepted, with the real one's calling convention.++ Including `attempted`, the caller-owned list the real push fills as it files+ each slug: a stub that only returned the slugs would let a caller that never+ reads the return value pass here and leak a kernel on Kaggle.+ """++ def fake_push(+ notebook,+ user,+ kernel_timeout_sec,+ accelerator = "NvidiaTeslaT4",+ attempted = None,+ ):+ if attempted is not None:+ attempted.append(slug)+ return {"ok": True, "slug": slug, "attempts": [slug]}++ return fake_push+++def test_an_abort_anywhere_in_the_launcher_still_deletes_what_it_pushed(monkeypatch, tmp_path):+ """The outer guard, not the timeout specifically.++ Every line after the first push can leave a kernel running if it raises, and+ the runner is the only thing that would delete it. An abort is `infra` by+ this file's contract, nothing having been learned about the code under test,+ so it exits 0 rather than colouring a pull request red.+ """++ def boom(outdir):+ raise MemoryError("the runner ran out")++ deleted: list[str] = []++ def fake_run(cmd, **kw):+ cmd = [str(c) for c in cmd]+ if cmd[1:3] == ["kernels", "delete"]:+ deleted.append(cmd[3])+ return types.SimpleNamespace(returncode = 0, stdout = "", stderr = "")++ monkeypatch.setattr(launch, "_api", lambda: object())+ monkeypatch.setattr(launch, "push", _accepting_push("someuser/unsloth-t4-ci-abcd"))+ monkeypatch.setattr(launch, "wait", lambda api, slug, poll_every, max_wait: "COMPLETE")+ monkeypatch.setattr(+ launch, "fetch_evidence", lambda slug, outdir, **kw: {"notebooks": [], "log": None}+ )+ monkeypatch.setattr(launch, "extract_reports", boom)+ monkeypatch.setattr(launch.subprocess, "run", fake_run)+ monkeypatch.delenv("GITHUB_OUTPUT", raising = False)+ monkeypatch.setattr(+ sys,+ "argv",+ [+ "launch.py",+ "--notebook",+ "k0.ipynb",+ "--user",+ "someuser",+ "--outdir",+ str(tmp_path),+ "--expect",+ "1",+ ],+ )++ assert launch.main() == 0+ assert deleted == ["someuser/unsloth-t4-ci-abcd"]+ result = json.loads((tmp_path / "launch_result.json").read_text(encoding = "utf-8"))+ assert result["verdict"] == "infra"+ assert "MemoryError" in result["reason"]+++# --------------------------------------------------------- kernel cleanup+++def _drive_one_kernel(monkeypatch, tmp_path, fake_run):+ """`main()` over one kernel that pushes, completes and reports.++ Everything but the delete calls is stubbed, so what comes back reads the+ release path and nothing else.+ """+ monkeypatch.setattr(launch, "_api", lambda: object())+ monkeypatch.setattr(launch, "push", _accepting_push("someuser/unsloth-t4-ci-abcd"))+ monkeypatch.setattr(launch, "wait", lambda api, slug, poll_every, max_wait: "COMPLETE")+ monkeypatch.setattr(+ launch, "fetch_evidence", lambda slug, outdir, **kw: {"notebooks": [], "log": None}+ )+ monkeypatch.setattr(+ launch,+ "extract_reports",+ lambda outdir: [{"label": "control", "model": "m", "passed": True}],+ )+ monkeypatch.setattr(launch.subprocess, "run", fake_run)+ monkeypatch.setattr(launch.time, "sleep", lambda _s: None)+ monkeypatch.delenv("GITHUB_OUTPUT", raising = False)+ monkeypatch.setattr(+ sys,+ "argv",+ [+ "launch.py",+ "--notebook",+ "k0.ipynb",+ "--user",+ "someuser",+ "--outdir",+ str(tmp_path),+ "--expect",+ "1",+ ],+ )+ code = launch.main()+ return code, json.loads((tmp_path / "launch_result.json").read_text(encoding = "utf-8"))+++def _refusing_run(+ returncode: int,+ message: str,+ succeed_from: int = 10**6,+):+ """A `subprocess.run` whose deletes fail until the nth attempt."""+ calls: list[str] = []++ def fake_run(cmd, **kw):+ cmd = [str(c) for c in cmd]+ if cmd[1:3] == ["kernels", "delete"]:+ calls.append(cmd[3])+ if len(calls) >= succeed_from:+ return types.SimpleNamespace(returncode = 0, stdout = "", stderr = "")+ return types.SimpleNamespace(returncode = returncode, stdout = "", stderr = message)+ return types.SimpleNamespace(returncode = 0, stdout = "", stderr = "")++ return fake_run, calls+++def test_a_delete_kaggle_refused_does_not_count_as_released(monkeypatch, tmp_path, capsys):+ """`subprocess.run` does not raise on a nonzero exit.++ So the release loop used to record every slug as released whatever came+ back, while cleanup is the budget control rather than a tidy-up. The refusal+ below is the one that was live: the client the workflow pinned had no+ `kernels delete` subcommand at all, so argparse answered every delete with+ exit 2 and the run still reported the kernel released while it billed on to+ its own ceiling.+ """+ fake_run, calls = _refusing_run(+ 2, "kaggle kernels: error: argument command: invalid choice: 'delete'"+ )+ code, result = _drive_one_kernel(monkeypatch, tmp_path, fake_run)++ assert code == 0+ entry = result["kernels"][0]+ assert entry["released"] is False+ assert entry["released_slugs"] == []+ assert result["unreleased"] == ["someuser/unsloth-t4-ci-abcd"]+ # And it is said out loud, or nobody goes and deletes it by hand.+ out = capsys.readouterr().out+ assert "::warning title=Kaggle kernels may still be running::" in out+ assert "someuser/unsloth-t4-ci-abcd" in out+++def test_a_refused_delete_is_retried_before_it_is_given_up_on(monkeypatch, tmp_path):+ """A 5xx or a reset connection is exactly as transient here as it is on+ the push side, and giving up on the first one abandons a live kernel."""+ fake_run, calls = _refusing_run(1, "503 Service Unavailable")+ _code, result = _drive_one_kernel(monkeypatch, tmp_path, fake_run)++ assert len(calls) == launch.DELETE_ATTEMPTS+ assert result["kernels"][0]["released"] is False+++def test_a_delete_that_succeeds_on_a_retry_is_released(monkeypatch, tmp_path, capsys):+ """The other direction: the retry has to be able to end in success, or+ the check is just a slower way of always reporting a leak."""+ fake_run, calls = _refusing_run(1, "502 Bad Gateway", succeed_from = 2)+ _code, result = _drive_one_kernel(monkeypatch, tmp_path, fake_run)++ assert len(calls) == 2+ entry = result["kernels"][0]+ assert entry["released"] is True+ assert entry["released_slugs"] == ["someuser/unsloth-t4-ci-abcd"]+ assert result["unreleased"] == []+ assert "::warning title=Kaggle kernels may still be running::" not in capsys.readouterr().out+++def test_a_delete_that_never_ran_is_not_a_deletion(monkeypatch, tmp_path):+ """`subprocess.run` raising is the one case the old code did notice, and+ it is still not a released kernel."""++ def fake_run(cmd, **kw):+ cmd = [str(c) for c in cmd]+ if cmd[1:3] == ["kernels", "delete"]:+ raise subprocess.TimeoutExpired(cmd, 180)+ return types.SimpleNamespace(returncode = 0, stdout = "", stderr = "")++ _code, result = _drive_one_kernel(monkeypatch, tmp_path, fake_run)+ assert result["kernels"][0]["released"] is False+ assert result["unreleased"] == ["someuser/unsloth-t4-ci-abcd"]+++def test_a_kernel_kaggle_says_is_not_there_is_a_freed_slot_not_a_leak(+ monkeypatch, tmp_path, capsys+):+ """Most slugs release() reconciles were never accepted, or already went.++ push() files a fresh slug per attempt and keeps every one, and a retry's+ _discard() deletes the previous attempt without recording that it worked,+ so reconciliation asks Kaggle a second time about a kernel that is gone.+ Reading that as a failed cleanup spends DELETE_ATTEMPTS on an absent kernel+ -- ahead of the accepted one, which is the only one still billing -- and+ then tells a human to go and delete a slug that does not exist.++ The stderr below is what the pinned client prints for a 404: kagglesdk+ calls `raise_for_status`, and cli.py prints the HTTPError and exits 1.+ """+ fake_run, calls = _refusing_run(+ 1,+ "404 Client Error: Not Found for url: "+ "https://api.kaggle.com/v1/kernels.KernelsApiService/DeleteKernel",+ )+ _code, result = _drive_one_kernel(monkeypatch, tmp_path, fake_run)++ assert calls == ["someuser/unsloth-t4-ci-abcd"], "an absent kernel was asked about again"+ entry = result["kernels"][0]+ assert entry["released"] is True+ assert entry["released_slugs"] == ["someuser/unsloth-t4-ci-abcd"]+ assert result["unreleased"] == []+ assert "::warning title=Kaggle kernels may still be running::" not in capsys.readouterr().out++[email protected]("marker", list(gate.GONE_MARKERS))+def test_cleanup_reads_a_missing_kernel_in_the_gate_s_words(monkeypatch, marker):+ """One vocabulary, taken FROM the gate rather than copied beside it.++ Both files ask the same account the same question through the same client:+ the gate to tell a deleted kernel from an unreadable one before it spends+ quota, cleanup to tell a freed slot from one still billing. A second list+ would drift out of agreement with the first without either being wrong on+ its own, so this parametrises over the gate's own tuple.+ """+ calls: list[list[str]] = []++ def fake_run(cmd, **kw):+ calls.append([str(c) for c in cmd])+ return types.SimpleNamespace(returncode = 1, stdout = "", stderr = f"delete refused: {marker}")++ monkeypatch.setattr(launch.subprocess, "run", fake_run)+ monkeypatch.setattr(launch.time, "sleep", lambda _s: None)++ assert launch.delete_kernel("someuser/gone") is True+ assert len(calls) == 1, calls+++def test_a_nonzero_delete_that_is_not_a_missing_kernel_still_retries(monkeypatch):+ """The other half of the same branch.++ A 5xx, a reset connection or an argparse refusal says nothing about whether+ the kernel is up, so trusting the exit code alone would turn a transient+ into a silently abandoned session.+ """+ calls: list[list[str]] = []++ def fake_run(cmd, **kw):+ calls.append([str(c) for c in cmd])+ return types.SimpleNamespace(returncode = 1, stdout = "", stderr = "503 Service Unavailable")++ monkeypatch.setattr(launch.subprocess, "run", fake_run)+ monkeypatch.setattr(launch.time, "sleep", lambda _s: None)++ assert launch.delete_kernel("someuser/maybe-live") is False+ assert len(calls) == launch.DELETE_ATTEMPTS+++def test_a_payload_that_cannot_see_its_gpu_reports_instead_of_vanishing(tmp_path, monkeypatch):+ """A CPU-only torch wheel must not exit this job green.++ `device_count() == 0` used to abort the verify cell with a bare assert. The+ run cell is the only other thing that emits a report and is never reached+ from there, so the launcher extracted nothing and called the run `infra`,+ which exits 0, making a dependency regression that breaks CUDA invisible.+ """+ monkeypatch.setattr(build_kernel, "KERNEL_ROOT", str(tmp_path / "src"))+ leg = LEGS["control"]+ # Import probe satisfied, so the cell reaches the GPU check.+ trivial = type(leg)(+ **{+ **{field: getattr(leg, field) for field in leg.__dataclass_fields__},+ "imports": ("json",),+ }+ )+ cells = _payload_cells(trivial)++ # A torch that installed and imports, and sees no card.+ stubs = tmp_path / "stubs"+ stubs.mkdir()+ (stubs / "torch.py").write_text(+ "class _Cuda:\n"+ " @staticmethod\n"+ " def device_count():\n"+ " return 0\n"+ " @staticmethod\n"+ " def is_available():\n"+ " return False\n"+ "cuda = _Cuda()\n",+ encoding = "utf-8",+ )++ outputs = []+ for index in (0, 2):+ script = tmp_path / f"cell{index}.py"+ script.write_text(cells[index], encoding = "utf-8")+ proc = subprocess.run(+ [sys.executable, str(script)],+ capture_output = True,+ text = True,+ timeout = 600,+ env = {**os.environ, "PYTHONPATH": str(stubs)},+ )+ outputs.append(proc.stdout + proc.stderr)+ assert "KAGGLE_T4_CI_PAYLOAD GPU_UNUSABLE" in outputs[1]++ evidence = tmp_path / "evidence"+ evidence.mkdir()+ (evidence / "t4_control_output.ipynb").write_text(+ json.dumps(+ {+ "cells": [+ {"cell_type": "code", "outputs": [{"output_type": "stream", "text": text}]}+ for text in outputs+ ]+ }+ ),+ encoding = "utf-8",+ )+ reports = launch.extract_reports(evidence)+ assert reports, "an unusable GPU produced no report at all"+ assert reports[0]["passed"] is False+ assert any("could not use its GPU" in f for f in reports[0]["failures"])+++def test_a_payload_that_writes_malformed_utf8_still_reports(tmp_path, monkeypatch):+ """Bytes that are not UTF-8 are output, not a reason to lose the verdict.++ `subprocess.run(text=True)` decodes strictly, so one malformed byte from a+ native crash handler raises UnicodeDecodeError inside the run cell, before+ the synthetic report below it is printed. Papermill then aborts the cell,+ the launcher extracts no report for this leg and calls the run `partial` or+ `infra`, both of which are green -- on a payload that died.+ """+ monkeypatch.setattr(build_kernel, "KERNEL_ROOT", str(tmp_path / "src"))+ leg = LEGS["control"]+ root = Path(build_kernel._kernel_root(leg))+ root.mkdir(parents = True, exist_ok = True)+ (root / leg.entry).write_text(+ "import sys\n"+ "sys.stdout.buffer.write(b'trained \\xff\\xfe then died\\n')\n"+ "sys.stderr.buffer.write(b'terminate called \\xff\\n')\n"+ "sys.exit(134)\n",+ encoding = "utf-8",+ )++ run_cell = _payload_cells(leg)[3].replace("/kaggle/working", str(tmp_path))+ script = tmp_path / "run_cell.py"+ script.write_text(run_cell, encoding = "utf-8")+ proc = subprocess.run(+ [sys.executable, str(script)],+ capture_output = True,+ text = True,+ errors = "replace",+ timeout = 600,+ )+ assert proc.returncode == 0, proc.stdout + proc.stderr+ assert "UnicodeDecodeError" not in proc.stderr++ evidence = tmp_path / "evidence"+ evidence.mkdir()+ (evidence / "t4_control_output.ipynb").write_text(+ json.dumps(+ {+ "cells": [+ {+ "cell_type": "code",+ "outputs": [{"output_type": "stream", "text": proc.stdout}],+ }+ ]+ }+ ),+ encoding = "utf-8",+ )+ reports = launch.extract_reports(evidence)+ assert reports, "a payload that died with undecodable output produced no report"+ assert reports[0]["passed"] is False+ assert reports[0]["returncode"] == 134+++# ------------------------------------------------------- evidence budget+#+# The phase between the last poll and release(). The kernels are still billing+# here and nothing else deletes them, so a collection that outlasts the job+# deadline is how a runner gets killed with kernels up. What follows is that+# bound, exercised rather than restated.+++class _SlowPages:+ """A `kernels/output` endpoint that paginates forever and answers slowly.++ Both halves of the worst case in one stub: `hasNextPageToken` never clears,+ so the listing walks its whole page limit, and every call sits until its+ OWN timeout expires, which is what a socket at Kaggle's ceiling does.+ """++ def __init__(self, clock):+ self.clock = clock+ self.calls: list[int] = []++ def __call__(+ self,+ req,+ timeout = None,+ ):+ self.calls.append(timeout)+ self.clock.advance(timeout)+ body = json.dumps(+ {"files": [], "log": "", "hasNextPageToken": True, "nextPageToken": "more"}+ ).encode()+ return _Response(body)+++class _Response:+ """A whole body, in one piece, however it is asked for.++ ``read(amt)`` and ``read1`` are what an ``HTTPResponse`` offers and what the+ chunked reader uses; a fake that only answers ``read()`` would make the+ reader untestable rather than the code wrong.+ """++ def __init__(self, body: bytes):+ self.body = body+ self.pos = 0++ def read(self, amt = None):+ if amt is None or amt < 0:+ chunk, self.pos = self.body[self.pos :], len(self.body)+ return chunk+ return self.read1(amt)++ def read1(self, amt = -1):+ end = len(self.body) if amt is None or amt < 0 else self.pos + amt+ chunk = self.body[self.pos : end]+ self.pos += len(chunk)+ return chunk++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ return False+++class _Clock:+ """A monotonic stand-in for time.time() that only moves when told."""++ def __init__(self, start: float = 1000.0):+ self.now = start++ def __call__(self) -> float:+ return self.now++ def advance(self, seconds: float) -> None:+ self.now += seconds+++def test_a_paginating_output_endpoint_cannot_outlast_the_evidence_budget(monkeypatch, tmp_path):+ """The P1 this constant exists for.++ Unbounded, one kernel's listing is OUTPUT_PAGE_LIMIT pages at the socket+ ceiling -- 2400s -- and two kernels are 4800s against the 600s the job+ deadline budgets for the whole phase. The runner is then killed here,+ taking finish() -> release() with it, and the kernels it pushed keep+ billing: the single outcome that deadline exists to prevent.+ """+ clock = _Clock()+ monkeypatch.setattr(launch.time, "time", clock)+ monkeypatch.setenv("KAGGLE_API_TOKEN", "not-a-real-token")+ slow = _SlowPages(clock)+ monkeypatch.setattr(launch.urllib.request, "urlopen", slow)++ started = clock()+ deadline = started + launch.EVIDENCE_BUDGET_SEC+ listing = launch.list_outputs("someuser/k", timeout = 120, deadline = deadline)++ spent = clock() - started+ assert (+ spent <= launch.EVIDENCE_BUDGET_SEC+ ), f"the listing spent {spent}s against a {launch.EVIDENCE_BUDGET_SEC}s budget"+ # Unbounded this is OUTPUT_PAGE_LIMIT x 120s; the budget is what stopped it.+ assert len(slow.calls) < launch.OUTPUT_PAGE_LIMIT+ assert all(t <= 120 for t in slow.calls)+ assert listing["truncated"] is True, "an incomplete listing must say so"+++def test_the_evidence_budget_is_shared_by_every_kernel(monkeypatch, tmp_path):+ """One budget for the phase, not one per kernel.++ Per kernel the term scales with the kernel count, and the job deadline is+ derived from a single number; the second kernel of a run whose first+ kernel spent the budget collects nothing rather than doubling the bound.+ """+ clock = _Clock()+ monkeypatch.setattr(launch.time, "time", clock)+ monkeypatch.setenv("KAGGLE_API_TOKEN", "not-a-real-token")+ monkeypatch.setattr(launch.urllib.request, "urlopen", _SlowPages(clock))++ started = clock()+ deadline = started + launch.EVIDENCE_BUDGET_SEC+ for slug in ("someuser/a", "someuser/b"):+ launch.fetch_evidence(slug, tmp_path / slug.split("/")[-1], deadline = deadline)+ assert clock() - started <= launch.EVIDENCE_BUDGET_SEC+++def test_a_slow_notebook_download_cannot_outlast_the_evidence_budget(monkeypatch, tmp_path):+ """Downloads are the other half: Kaggle caps neither their size nor count.++ Each executed notebook is a 300s call and the listing decides how many+ there are, so an endpoint offering twenty of them is 6000s of downloads+ with nothing to stop them.+ """+ clock = _Clock()+ monkeypatch.setattr(launch.time, "time", clock)+ monkeypatch.setenv("KAGGLE_API_TOKEN", "not-a-real-token")++ files = [+ {"fileName": f"nb{i}{launch.OUTPUT_SUFFIX}", "url": f"https://example.invalid/{i}"}+ for i in range(20)+ ]++ def urlopen(req, timeout = None):+ url = getattr(req, "full_url", "")+ clock.advance(timeout)+ if "kernels/output" in url:+ return _Response(json.dumps({"files": files, "log": "x"}).encode())+ return _Response(b"{}")++ monkeypatch.setattr(launch.urllib.request, "urlopen", urlopen)+ started = clock()+ evidence = launch.fetch_evidence(+ "someuser/k", tmp_path / "k", deadline = started + launch.EVIDENCE_BUDGET_SEC+ )+ spent = clock() - started+ assert spent <= launch.EVIDENCE_BUDGET_SEC, f"downloads spent {spent}s"+ assert len(evidence["notebooks"]) < len(files)+ assert evidence["truncated"] is True+++class _Socket:+ """The live socket under a response, recording every re-clamp."""++ def __init__(self):+ self.timeouts: list[float] = []++ def settimeout(self, seconds):+ self.timeouts.append(seconds)+++class _Trickle:+ """A response that keeps returning bytes instead of stalling.++ The case a socket timeout cannot see. `urlopen(timeout=...)` bounds each+ blocking socket operation, so an endpoint that answers every read -- slowly,+ but with data -- renews it forever and never trips it. Each chunk here+ advances the clock by `per_chunk`; a whole-body `read()` advances by all of+ them at once, which is what one unbounded `resp.read()` costs.+ """++ def __init__(self, clock, body: bytes, chunks: int, per_chunk: float):+ self.clock = clock+ self.body = body+ self.size = max(1, len(body) // chunks)+ self.per_chunk = per_chunk+ self.pos = 0+ self.reads = 0+ self.fp = type("fp", (), {"raw": type("raw", (), {"_sock": _Socket()})()})()++ def read(self, amt = None):+ if amt is None or amt < 0:+ # The unbounded read: the socket kept feeding it, so it returned+ # only once the whole body was through.+ self.clock.advance(self.per_chunk * (len(self.body) / self.size))+ self.pos = len(self.body)+ return self.body+ return self.read1(amt)++ def read1(self, amt = -1):+ self.reads += 1+ if self.pos >= len(self.body):+ return b""+ take = self.size if amt is None or amt < 0 else min(amt, self.size)+ chunk = self.body[self.pos : self.pos + take]+ self.pos += len(chunk)+ self.clock.advance(self.per_chunk)+ return chunk++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ return False+++def _trickled_listing(+ clock,+ files,+ chunks = 20,+ per_chunk = 60.0,+):+ body = json.dumps({"files": files, "log": "x"}).encode()+ # JSON tolerates trailing whitespace, so padding buys chunks without+ # changing what parses.+ return _Trickle(clock, body + b" " * (chunks * len(body)), chunks, per_chunk)+++def test_a_trickling_output_listing_cannot_outlast_the_evidence_budget(monkeypatch, tmp_path):+ """The deadline has to hold DURING the read, not only before it.++ Every check was on the near side of `urlopen`, and the timeout it takes is+ a per-socket-operation one, so a body arriving slowly enough renews it+ indefinitely: 20 chunks a minute apart is 1200s of `resp.read()` against a+ 600s budget, spent before release() gets to delete anything. The kernels+ bill for all of it.+ """+ clock = _Clock()+ monkeypatch.setattr(launch.time, "time", clock)+ monkeypatch.setenv("KAGGLE_API_TOKEN", "not-a-real-token")+ resp = _trickled_listing(clock, [])+ monkeypatch.setattr(launch.urllib.request, "urlopen", lambda req, timeout = None: resp)++ started = clock()+ listing = launch.list_outputs(+ "someuser/k", timeout = 120, deadline = started + launch.EVIDENCE_BUDGET_SEC+ )+ spent = clock() - started+ assert spent <= launch.EVIDENCE_BUDGET_SEC, f"the listing read spent {spent}s"+ assert listing["truncated"] is True, "an abandoned listing must say it is incomplete"+ assert resp.pos < len(resp.body), "the read was abandoned, not completed"+ # And the live socket was re-clamped as the budget drained, so a read that+ # starts just inside the deadline cannot block for a full socket timeout+ # past it.+ clamps = resp.fp.raw._sock.timeouts+ assert clamps and all(t <= launch.EVIDENCE_BUDGET_SEC for t in clamps), clamps+ assert clamps == sorted(clamps, reverse = True), clamps+++def test_a_trickling_notebook_download_cannot_outlast_the_evidence_budget(monkeypatch, tmp_path):+ """The same hole on the download, where the bodies are unbounded.++ Kaggle caps neither the size nor the count of a kernel's outputs, so this+ is the read most able to run long, and a partial file must not be published+ as evidence either.+ """+ clock = _Clock()+ monkeypatch.setattr(launch.time, "time", clock)+ monkeypatch.setenv("KAGGLE_API_TOKEN", "not-a-real-token")+ files = [{"fileName": f"nb{launch.OUTPUT_SUFFIX}", "url": "https://example.invalid/nb"}]+ payload = json.dumps({"cells": []}).encode()+ download = _Trickle(clock, payload + b" " * (20 * len(payload)), 20, 60.0)++ def urlopen(req, timeout = None):+ if "kernels/output" in getattr(req, "full_url", ""):+ return _Response(json.dumps({"files": files, "log": "x"}).encode())+ return download++ monkeypatch.setattr(launch.urllib.request, "urlopen", urlopen)+ started = clock()+ evidence = launch.fetch_evidence(+ "someuser/k", tmp_path / "k", deadline = started + launch.EVIDENCE_BUDGET_SEC+ )+ spent = clock() - started+ assert spent <= launch.EVIDENCE_BUDGET_SEC, f"the download spent {spent}s"+ assert evidence["notebooks"] == [], evidence+ assert evidence["truncated"] is True+ assert not list((tmp_path / "k").glob("*.part")), "a half-written download was left behind"+++def test_main_bounds_the_whole_evidence_phase_it_is_budgeted_for(monkeypatch, tmp_path):+ """main() must actually hand the budget down, on the real call path.++ A deadline the collection loop does not pass through is the bug with a+ constant added to it, and release() runs AFTER this loop: every second+ overspent here is a second the kernels keep billing with the job deadline+ approaching.+ """+ clock = _Clock()+ monkeypatch.setattr(launch.time, "time", clock)+ seen: list[float | None] = []++ def fake_fetch(+ slug,+ outdir,+ timeout = 300,+ deadline = None,+ ):+ seen.append(deadline)+ # Spend the whole budget on the first kernel.+ clock.advance(launch.EVIDENCE_BUDGET_SEC)+ return {"notebooks": [], "log": None, "truncated": True}++ monkeypatch.setattr(+ launch,+ "push",+ lambda nb, user, t, accelerator = "NvidiaTeslaT4", attempted = None: (+ attempted.append(f"{user}/s{len(attempted)}"),+ {"ok": True, "slug": attempted[-1], "attempts": list(attempted)},+ )[1],+ )+ monkeypatch.setattr(launch, "wait", lambda api, slug, every, remaining: "COMPLETE")+ monkeypatch.setattr(launch, "fetch_evidence", fake_fetch)+ monkeypatch.setattr(+ launch,+ "extract_reports",+ lambda outdir: [{"label": "control", "model": "m", "passed": True}],+ )+ monkeypatch.setattr(launch, "_api", lambda: object())+ monkeypatch.setattr(launch, "delete_kernel", lambda slug: True)+ monkeypatch.delenv("GITHUB_OUTPUT", raising = False)+ monkeypatch.setattr(+ sys,+ "argv",+ [+ "launch.py",+ "--notebook",+ "k0.ipynb",+ "--notebook",+ "k1.ipynb",+ "--user",+ "someuser",+ "--outdir",+ str(tmp_path),+ "--expect",+ "1",+ ],+ )+ started = clock()+ assert launch.main() == 0+ assert len(seen) == 2, "both kernels were collected"+ assert seen[0] is not None, "main() never handed the collection a deadline"+ assert seen[0] == seen[1], "the two kernels must share ONE budget, not get one each"+ assert seen[0] - started <= launch.EVIDENCE_BUDGET_SECdiff --git a/tests/kaggle/test_t4_payload_assertions.py b/tests/kaggle/test_t4_payload_assertions.pynew file mode 100644index 00000000000..2532b9fb086--- /dev/null+++ b/tests/kaggle/test_t4_payload_assertions.py@@ -0,0 +1,1775 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""CPU-only tests for what the T4 payloads actually ASSERT.++`test_t4_smoke_harness.py` covers the launcher, the gate and the shape of the+generated notebook; this covers the other half: given a result dict, does the+payload call it a pass or a failure? Every case here is one where a run that+measured nothing, or the wrong thing, used to report green.++Nothing here needs a GPU, which is the point: the pass/fail rule for a leg that+costs a Kaggle session has to be checkable without one.+"""++from __future__ import annotations++import json+import sys+import types+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parents[2]+SMOKE_DIR = REPO_ROOT / "tests" / "kaggle" / "t4_smoke"+CI_DIR = REPO_ROOT / ".github" / "scripts" / "kaggle_t4_ci"++sys.path.insert(0, str(SMOKE_DIR))+sys.path.insert(0, str(CI_DIR))++NAN = float("nan")+INF = float("inf")+++# ------------------------------------------------------- determinism.py+++def test_a_field_logged_by_only_one_run_is_a_difference():+ """grad_norm in cycle 0 and not in cycle 1 is nondeterminism, not a skip.++ ``check_reference`` already calls one-sided presence "a change in the SHAPE+ of what the trainer logged", and the exact comparator has to agree or the+ strong assertion is weaker than the tolerance band beside it.+ """+ from determinism import compare_metrics++ a = [{"step": 1, "loss": 1.0, "grad_norm": 2.0}]+ b = [{"step": 1, "loss": 1.0}]+ result = compare_metrics(a, b)+ assert result["identical"] is False+ assert result["first_diff_step"] == 1+++def test_a_field_absent_from_both_runs_is_still_not_a_difference():+ from determinism import compare_metrics++ a = [{"step": 1, "loss": 1.0}]+ b = [{"step": 1, "loss": 1.0}]+ assert compare_metrics(a, b)["identical"] is True+++def test_repeated_runs_must_agree_on_their_step_coordinates():+ """Same values in the same positions, against different step numbers."""+ from determinism import compare_metrics++ a = [{"step": 1, "loss": 1.0}, {"step": 2, "loss": 0.5}, {"step": 3, "loss": 0.25}]+ b = [{"step": 1, "loss": 1.0}, {"step": 2, "loss": 0.5}, {"step": 2, "loss": 0.25}]+ result = compare_metrics(a, b)+ assert result["identical"] is False+ assert result["step_mismatch"] == [{"index": 2, "a": 3, "b": 2}]+++def test_matching_step_coordinates_are_not_reported_as_a_difference():+ from determinism import compare_metrics++ a = [{"step": 1, "loss": 1.0, "grad_norm": NAN}]+ b = [{"step": 1, "loss": 1.0, "grad_norm": NAN}]+ result = compare_metrics(a, b)+ assert result["identical"] is True+ assert result["step_mismatch"] == []+++def test_two_runs_that_both_overflowed_on_the_same_step_agree():+ """An fp16 overflow logs infinity as readily as NaN, and abs(inf-inf) is NaN.++ NaN != 0.0, so the subtraction reported two identical traces as+ nondeterministic, with a max_abs_diff of 0.0 to show for it.+ """+ from determinism import compare_metrics++ a = [{"step": 1, "loss": 10.0, "grad_norm": INF}, {"step": 2, "loss": 9.0, "grad_norm": 4.0}]+ b = [{"step": 1, "loss": 10.0, "grad_norm": INF}, {"step": 2, "loss": 9.0, "grad_norm": 4.0}]+ result = compare_metrics(a, b)+ assert result["identical"] is True+ assert result["first_diff_step"] is None+ assert result["max_abs_diff"] == {"loss": 0.0, "grad_norm": 0.0}+++ ("norm_a", "norm_b"),+ [(INF, 4.0), (4.0, INF), (INF, -INF), (-INF, INF)],+)+def test_an_infinity_only_one_run_logged_is_still_a_difference(norm_a, norm_b):+ from determinism import compare_metrics++ a = [{"step": 1, "loss": 1.0, "grad_norm": norm_a}]+ b = [{"step": 1, "loss": 1.0, "grad_norm": norm_b}]+ assert compare_metrics(a, b)["identical"] is False+++# -------------------------------------------------- run_t4_smoke.py: canary+++def test_the_canary_must_be_the_whole_answer():+ from run_t4_smoke import CANARY, canary_failures++ run = {"run_index": 0, "generated": CANARY + "<|im_start|>and on it went"}+ failures = canary_failures(run, require = True)+ assert failures and "exactly" in failures[0]+++def test_the_canary_tolerates_surrounding_whitespace_only():+ from run_t4_smoke import CANARY, canary_failures+ assert canary_failures({"run_index": 0, "generated": CANARY}, require = True) == []+ assert canary_failures({"run_index": 0, "generated": "\n" + CANARY + " \n"}, require = True) == []+++def test_a_missing_canary_is_still_a_failure():+ from run_t4_smoke import canary_failures+ failures = canary_failures({"run_index": 1, "generated": "def my_function():"}, require = True)+ assert failures and "did not emit" in failures[0]+++def test_the_canary_can_be_downgraded_to_a_warning():+ from run_t4_smoke import canary_failures+ assert canary_failures({"run_index": 1, "generated": "nope"}, require = False) == []+++# -------------------------------------- run_t4_smoke.py: optimisation checks+++def test_an_infinite_gradient_norm_is_not_an_applied_update():+ """fp16 overflow reports the norm as inf as readily as NaN.++ ``inf == inf``, so the NaN-only test counted every skipped step as applied+ and a run that trained nothing reported green.+ """+ from run_t4_smoke import optimisation_failures++ metrics = [{"step": s, "loss": 10.0 - s, "grad_norm": INF} for s in (1, 2, 3)]+ failures = optimisation_failures(metrics)+ assert failures and "no optimizer update was applied" in failures[0]+++def test_one_finite_gradient_norm_is_enough():+ from run_t4_smoke import optimisation_failures+ metrics = [+ {"step": 1, "loss": 10.0, "grad_norm": NAN},+ {"step": 2, "loss": 5.0, "grad_norm": INF},+ {"step": 3, "loss": 1.0, "grad_norm": 11.2},+ ]+ assert optimisation_failures(metrics) == []+++# ------------------------------------------- run_t4_smoke.py: saved adapter+++def _adapter_state(**over) -> dict:+ state = {+ "dir": "/kaggle/working/smoke0/lora_run0",+ "files": ["adapter_config.json", "adapter_model.safetensors"],+ "weight_file": "adapter_model.safetensors",+ "config_readable": True,+ "tensors": 224,+ "parameters": 4325376,+ "non_finite_tensors": [],+ "nonzero_tensors": 224,+ "b_tensors": 112,+ "nonzero_b_tensors": 112,+ "keys_checked": True,+ "keys_missing": [],+ "keys_unexpected": [],+ "keys_extra": [],+ }+ state.update(over)+ return state+++def test_a_saved_adapter_that_reloads_with_weights_passes():+ from run_t4_smoke import saved_adapter_failures+ assert saved_adapter_failures(_adapter_state()) == []+++def test_an_adapter_whose_weight_file_cannot_be_read_is_a_failure():+ from run_t4_smoke import saved_adapter_failures+ failures = saved_adapter_failures(+ _adapter_state(tensors = None, error = "SafetensorError: header too small")+ )+ assert failures and "could not be read back" in failures[0]+++def test_an_adapter_with_no_tensors_is_a_failure():+ from run_t4_smoke import saved_adapter_failures+ failures = saved_adapter_failures(_adapter_state(tensors = 0, parameters = 0))+ assert failures and "no tensors" in failures[0]+++def test_an_adapter_with_non_finite_weights_is_a_failure():+ from run_t4_smoke import saved_adapter_failures+ failures = saved_adapter_failures(_adapter_state(non_finite_tensors = ["...lora_B.weight"]))+ assert failures and "non-finite" in failures[0]+++def test_an_all_zero_adapter_is_a_failure():+ """lora_B starts at zero, so an all-zero file is an untrained adapter."""+ from run_t4_smoke import saved_adapter_failures++ failures = saved_adapter_failures(_adapter_state(nonzero_tensors = 0, nonzero_b_tensors = 0))+ assert failures and "saved lora_B matrices is zero" in failures[0]+++def test_an_adapter_whose_b_matrices_are_all_zero_is_a_failure():+ """The A matrices alone keep `nonzero_tensors` up, and prove nothing.++ peft initialises lora_A randomly, so it is nonzero before a single step, and+ counting every tensor therefore accepted an adapter whose B matrices were+ all zero, contributing nothing since the update goes through B.+ """+ from run_t4_smoke import saved_adapter_failures++ failures = saved_adapter_failures(+ _adapter_state(nonzero_tensors = 112, b_tensors = 112, nonzero_b_tensors = 0)+ )+ assert failures and "saved lora_B matrices is zero" in failures[0]+++def test_an_adapter_with_no_b_matrices_at_all_is_unusable_rather_than_fine():+ """Dropped B matrices, or a peft naming change: either way, no reading."""+ from run_t4_smoke import saved_adapter_failures++ failures = saved_adapter_failures(+ _adapter_state(nonzero_tensors = 112, b_tensors = 0, nonzero_b_tensors = 0)+ )+ assert failures and "is a lora_B matrix" in failures[0]+++def test_an_adapter_nobody_checked_the_names_of_is_not_a_pass():+ """No oracle, no verdict.++ The tensor reading cannot see whether PEFT would consume these weights, so+ a run that could not derive the expected names learned nothing about the+ save. Recording that as an unchecked field would leave the strongest thing+ this function asserts silently switched off.+ """+ from run_t4_smoke import saved_adapter_failures++ failures = saved_adapter_failures(+ _adapter_state(keys_checked = False, keys_error = "ImportError: no such name")+ )+ assert failures and "never checked" in failures[0]+++def test_an_adapter_missing_tensors_peft_names_is_a_failure():+ from run_t4_smoke import saved_adapter_failures+ failures = saved_adapter_failures(+ _adapter_state(keys_missing = ["base_model.model.q_proj.lora_B.weight"])+ )+ assert failures and "does not carry" in failures[0]+++def test_lora_tensors_under_names_peft_does_not_use_are_a_failure():+ from run_t4_smoke import saved_adapter_failures+ failures = saved_adapter_failures(_adapter_state(keys_unexpected = ["q_proj.lora_B.weight"]))+ assert failures and "ignores them silently" in failures[0]+++def test_a_non_lora_tensor_beside_the_adapter_is_not_a_failure(tmp_path):+ """The check is about names PEFT has to MATCH, not about extra tensors.++ ``save_pretrained`` can legitimately write more than the adapter -- an+ embedding copy when the vocabulary was resized, a modules_to_save entry --+ and none of that is a LoRA tensor PEFT's loader has to recognise. Failing on+ it turns a supported save into a red leg, which is why the two are sorted+ apart rather than failed together as "anything the oracle did not name".++ Through the real reading rather than a hand-built state, or the sorting this+ asserts is not the code that runs.+ """+ pytest.importorskip("safetensors")+ import torch+ from safetensors.torch import save_file++ from run_t4_smoke import saved_adapter_failures, verify_saved_adapter++ lora = "base_model.model.layers.0.self_attn.q_proj.lora_B.weight"+ embedding = "base_model.model.model.embed_tokens.weight"+ (tmp_path / "adapter_config.json").write_text(json.dumps({"peft_type": "LORA", "r": 16}))+ save_file(+ {lora: torch.ones(8, 16) * 0.01, embedding: torch.ones(4, 4)},+ str(tmp_path / "adapter_model.safetensors"),+ )+ state = verify_saved_adapter(tmp_path, peft_keys = {"keys": [lora]})+ assert state["keys_extra"] == [embedding]+ assert state["keys_unexpected"] == []+ assert saved_adapter_failures(state) == []+++def test_the_key_oracle_reports_a_failure_rather_than_raising():+ """It runs inside the payload, so a raise here would lose the whole leg."""+ from run_t4_smoke import peft_adapter_keys++ out = peft_adapter_keys(object())+ assert "keys" not in out and out["error"]+++def test_an_adapter_peft_would_ignore_on_reload_does_not_pass(tmp_path):+ """The whole regression, through the real peft, on the CPU.++ A serialization regression that renames the tensors (dropping the+ ``base_model.model.`` prefix is what filtering ``model.state_dict()`` by+ hand instead of calling ``get_peft_model_state_dict`` produces) leaves a+ file that deserializes perfectly and holds the same nonzero lora_B matrices+ a trained adapter does. Every reading this payload took off the bytes is+ identical, PEFT raises nothing on reload, and the adapter contributes+ nothing -- the exact outcome the tensor counts exist to catch.++ The last assertion is the premise rather than the behaviour: if a future+ peft starts refusing unmatched keys, this test says so instead of quietly+ checking nothing.+ """+ pytest.importorskip("peft")+ pytest.importorskip("transformers")+ pytest.importorskip("safetensors")+ import torch+ from peft import LoraConfig, PeftModel, get_peft_model+ from safetensors.torch import load_file, save_file+ from transformers import GPT2Config, GPT2LMHeadModel++ from run_t4_smoke import peft_adapter_keys, saved_adapter_failures, verify_saved_adapter++ def _base():+ torch.manual_seed(0)+ return GPT2LMHeadModel(GPT2Config(n_layer = 1, n_head = 2, n_embd = 32, vocab_size = 64))++ model = get_peft_model(+ _base(), LoraConfig(r = 4, target_modules = ["c_attn"], task_type = "CAUSAL_LM")+ )+ # lora_B starts at zero and only an applied optimizer step moves it.+ with torch.no_grad():+ for name, param in model.named_parameters():+ if "lora_B" in name:+ param.add_(0.25)+ model.save_pretrained(str(tmp_path))+ keys = peft_adapter_keys(model)+ assert keys["keys"], keys++ good = verify_saved_adapter(tmp_path, peft_keys = keys)+ assert good["keys_checked"] is True+ assert saved_adapter_failures(good) == []++ weights = tmp_path / "adapter_model.safetensors"+ tensors = load_file(str(weights))+ save_file(+ {name.removeprefix("base_model.model."): value for name, value in tensors.items()},+ str(weights),+ )+ broken = verify_saved_adapter(tmp_path, peft_keys = keys)++ # Everything the bytes alone can say is unchanged.+ assert broken["tensors"] == good["tensors"]+ assert broken["nonzero_b_tensors"] == good["nonzero_b_tensors"] > 0+ assert broken["non_finite_tensors"] == []+ assert broken["config_loadable"] is True++ failures = saved_adapter_failures(broken)+ assert failures, "the leg would have passed an adapter that reloads to the base model"+ assert "ignores them silently" in " ".join(failures)++ reloaded = PeftModel.from_pretrained(_base(), str(tmp_path))+ b_matrices = [p for n, p in reloaded.named_parameters() if "lora_B" in n]+ assert b_matrices and all(float(p.abs().sum()) == 0.0 for p in b_matrices), (+ "peft loaded the renamed keys after all, so this test no longer describes "+ "the regression it was written for"+ )+++def test_a_missing_adapter_config_is_a_failure():+ from run_t4_smoke import saved_adapter_failures+ failures = saved_adapter_failures(_adapter_state(config_readable = False))+ assert failures and "adapter_config.json" in failures[0]+++def test_the_adapter_check_reads_a_real_file_it_just_wrote(tmp_path):+ """End to end through the real writer, no GPU and no model.++ The first file is the exact artifact the old count accepted: a random+ lora_A beside a lora_B that never left zero, one nonzero tensor of two, and+ an adapter that reloads to the base model.+ """+ pytest.importorskip("safetensors")+ import torch+ from safetensors.torch import save_file++ from run_t4_smoke import saved_adapter_failures, verify_saved_adapter++ (tmp_path / "adapter_config.json").write_text(json.dumps({"peft_type": "LORA", "r": 16}))+ written = {+ "base_model.model.layers.0.self_attn.q_proj.lora_A.weight": torch.ones(16, 8),+ "base_model.model.layers.0.self_attn.q_proj.lora_B.weight": torch.zeros(8, 16),+ }+ peft_keys = {"keys": sorted(written)}+ save_file(written, str(tmp_path / "adapter_model.safetensors"))+ state = verify_saved_adapter(tmp_path, peft_keys = peft_keys)+ assert state["tensors"] == 2+ assert state["nonzero_tensors"] == 1+ assert state["b_tensors"] == 1+ assert state["nonzero_b_tensors"] == 0+ assert state["config_readable"] is True+ failures = saved_adapter_failures(state)+ assert failures and "saved lora_B matrices is zero" in failures[0]++ # The same file with a B matrix an optimizer moved, the only difference+ # between an adapter that carries training and one that does not.+ save_file(+ {+ "base_model.model.layers.0.self_attn.q_proj.lora_A.weight": torch.ones(16, 8),+ "base_model.model.layers.0.self_attn.q_proj.lora_B.weight": torch.ones(8, 16) * 0.01,+ },+ str(tmp_path / "adapter_model.safetensors"),+ )+ trained = verify_saved_adapter(tmp_path, peft_keys = peft_keys)+ assert trained["nonzero_b_tensors"] == 1+ assert saved_adapter_failures(trained) == []++ save_file({"a.lora_B.weight": torch.zeros(4, 4)}, str(tmp_path / "adapter_model.safetensors"))+ failures = saved_adapter_failures(+ verify_saved_adapter(tmp_path, peft_keys = {"keys": ["a.lora_B.weight"]})+ )+ assert failures and "saved lora_B matrices is zero" in failures[0]+++def test_a_syntactically_valid_but_empty_adapter_config_is_not_a_pass(tmp_path):+ """`{}` is valid JSON and PEFT cannot rebuild an adapter from it.++ The check used to be `json.loads` succeeding, which `{}` and `[]` both do,+ so a save that wrote no LoRA fields at all read as "config_readable" and+ the leg passed on a directory nothing can load. PEFT resolves the config+ class from `peft_type` and raises when it is absent, so the question is+ asked of PEFT rather than of a field list this file guessed at.+ """+ pytest.importorskip("peft")+ pytest.importorskip("safetensors")+ import torch+ from safetensors.torch import save_file++ from run_t4_smoke import saved_adapter_failures, verify_saved_adapter++ save_file(+ {"q_proj.lora_B.weight": torch.ones(8, 16) * 0.01},+ str(tmp_path / "adapter_model.safetensors"),+ )+ for body in ("{}", "[]"):+ (tmp_path / "adapter_config.json").write_text(body)+ state = verify_saved_adapter(tmp_path, peft_keys = {"keys": ["q_proj.lora_B.weight"]})+ assert state["config_readable"] is True, "it IS readable JSON; that was never the question"+ assert state["config_loadable"] is False, body+ failures = saved_adapter_failures(state)+ assert failures and "PEFT cannot rebuild an adapter from it" in failures[0], body+++def test_an_adapter_config_for_a_different_adapter_than_the_one_trained_fails(tmp_path):+ """A well-formed config that does not describe THIS run.++ Loadable is not enough on its own: a save that dropped `target_modules` or+ wrote a rank the run never used produces a file PEFT rebuilds happily into+ the wrong adapter. The expectation is the argument list the payload handed+ `get_peft_model`, so this compares the save against the request rather than+ against a copy of it.+ """+ pytest.importorskip("peft")+ pytest.importorskip("safetensors")+ import torch+ from safetensors.torch import save_file++ from run_t4_smoke import saved_adapter_failures, verify_saved_adapter++ save_file(+ {"q_proj.lora_B.weight": torch.ones(8, 16) * 0.01},+ str(tmp_path / "adapter_model.safetensors"),+ )+ requested = {"r": 16, "lora_alpha": 16, "target_modules": ["q_proj", "v_proj"]}+ (tmp_path / "adapter_config.json").write_text(+ json.dumps(+ {+ "peft_type": "LORA",+ "r": 8,+ "lora_alpha": 16,+ "target_modules": ["q_proj", "v_proj"],+ }+ )+ )+ keys = {"keys": ["q_proj.lora_B.weight"]}+ state = verify_saved_adapter(tmp_path, expected = requested, peft_keys = keys)+ assert state["config_loadable"] is True+ assert state["config_differences"], state+ failures = saved_adapter_failures(state)+ assert failures and "different adapter than the one that was trained" in failures[0]++ # The same file, saved as requested: no difference and no failure.+ (tmp_path / "adapter_config.json").write_text(json.dumps({"peft_type": "LORA", **requested}))+ good = verify_saved_adapter(tmp_path, expected = requested, peft_keys = keys)+ assert good["config_differences"] == []+ assert saved_adapter_failures(good) == []+++# ------------------------------------------ run_t4_smoke.py: the reference+++def _write_reference(+ path: Path,+ *,+ config: dict,+ model: str = "unsloth/Qwen2.5-0.5B-Instruct",+):+ path.write_text(+ json.dumps(+ {+ "config": config,+ "model": model,+ "environment": {},+ "metrics": [{"step": s, "loss": 1.0 / s, "grad_norm": 3.0} for s in (1, 2, 3)],+ }+ ),+ encoding = "utf-8",+ )+++def test_a_band_check_against_a_reference_from_another_card_is_refused(tmp_path):+ """The committed reference records the card it was captured on.++ references/t4_qwen2.5-0.5b.json carries gpu_name "Tesla T4" and+ gpu_capability "sm_75" because a loss trace belongs to its hardware: no+ bf16 and xformers attention on sm_75. Nothing compared it, so a run on+ another GPU was band-checked against a T4 trace and its deviations came+ back as a code regression. The only hardware check anywhere was the GPU+ COUNT, on the kernel, which never reads this file.+ """+ from run_t4_smoke import check_reference, reference_failures++ ref = tmp_path / "ref.json"+ ref.write_text(+ json.dumps(+ {+ "config": REFERENCE_CONFIG,+ "model": "unsloth/Qwen2.5-0.5B-Instruct",+ "environment": {"gpu_name": "Tesla T4", "gpu_capability": "sm_75"},+ "metrics": [{"step": s, "loss": 1.0 / s, "grad_norm": 3.0} for s in (1, 2, 3)],+ }+ ),+ encoding = "utf-8",+ )+ observed = [{"step": s, "loss": 1.0 / s, "grad_norm": 3.0} for s in (1, 2, 3)]+ verdict = check_reference(+ observed,+ ref,+ 0.10,+ 0.05,+ max_steps = 3,+ config = REFERENCE_CONFIG,+ model = "unsloth/Qwen2.5-0.5B-Instruct",+ environment = {"gpu_name": "Tesla P100-PCIE-16GB", "gpu_capability": "sm_60"},+ )+ assert verdict["status"] == "hardware_mismatch", verdict+ # Refused BEFORE any number is compared: the metrics here are identical to+ # the reference, so a pass would look like a healthy run on the wrong card.+ assert verdict["deviations"] == []+ failures = reference_failures(verdict, 0.10)+ assert failures and "not for this run" in failures[0]+ assert "Tesla P100-PCIE-16GB" in failures[0]++ # Same reference, the card it was captured on: compared normally.+ same = check_reference(+ observed,+ ref,+ 0.10,+ 0.05,+ max_steps = 3,+ config = REFERENCE_CONFIG,+ model = "unsloth/Qwen2.5-0.5B-Instruct",+ environment = {"gpu_name": "Tesla T4", "gpu_capability": "sm_75"},+ )+ assert same["status"] == "ok", same+ assert reference_failures(same, 0.10) == []+++def test_a_reference_that_records_no_hardware_is_unchecked_not_a_mismatch(tmp_path):+ """ "It does not say" is not "it differs", the rule the settings follow.++ An older reference captured before the environment block carried a GPU+ name must keep working rather than fail every run; the skip is recorded so+ it cannot read as a comparison that passed.+ """+ from run_t4_smoke import check_reference, reference_failures++ ref = tmp_path / "ref.json"+ _write_reference(ref, config = REFERENCE_CONFIG)+ observed = [{"step": s, "loss": 1.0 / s, "grad_norm": 3.0} for s in (1, 2, 3)]+ verdict = check_reference(+ observed,+ ref,+ 0.10,+ 0.05,+ max_steps = 3,+ config = REFERENCE_CONFIG,+ environment = {"gpu_name": "Tesla T4", "gpu_capability": "sm_75"},+ )+ assert verdict["status"] == "ok", verdict+ assert "gpu_name" in verdict["config_unchecked"]+ assert reference_failures(verdict, 0.10) == []+++ "environment",+ [+ pytest.param({"error": "RuntimeError: no CUDA driver"}, id = "probe_raised"),+ pytest.param({"python": "3.12.13", "torch": "2.10.0"}, id = "probe_saw_no_gpu"),+ pytest.param({}, id = "empty"),+ pytest.param(None, id = "not_supplied"),+ pytest.param({"gpu_name": "Tesla T4", "gpu_capability": None}, id = "one_key_missing"),+ ],+)+def test_a_run_that_cannot_name_its_card_is_refused_not_waved_through(tmp_path, environment):+ """The hardware gate must not switch itself off when the probe fails.++ main() records ``environment = {"error": ...}`` for the whole block when+ environment_fingerprint() raises, and the fingerprint omits every gpu_* key+ outright when torch.cuda.is_available() is False. Either way the live values+ are absent while the reference still names Tesla T4 / sm_75, and treating+ that as "not compared" let the control leg report an ``ok`` reference check+ without ever establishing the card the trace belongs to -- the gate defeated+ by exactly the failure it exists to catch. What the REFERENCE does not say+ stays a skip; what the RUN cannot say about a key the reference does name is+ a refusal.+ """+ from run_t4_smoke import check_reference, reference_failures++ ref = tmp_path / "ref.json"+ ref.write_text(+ json.dumps(+ {+ "config": REFERENCE_CONFIG,+ "model": "unsloth/Qwen2.5-0.5B-Instruct",+ "environment": {"gpu_name": "Tesla T4", "gpu_capability": "sm_75"},+ "metrics": [{"step": s, "loss": 1.0 / s, "grad_norm": 3.0} for s in (1, 2, 3)],+ }+ ),+ encoding = "utf-8",+ )+ # Metrics identical to the reference, so nothing else can be what fails.+ observed = [{"step": s, "loss": 1.0 / s, "grad_norm": 3.0} for s in (1, 2, 3)]+ verdict = check_reference(+ observed,+ ref,+ 0.10,+ 0.05,+ max_steps = 3,+ config = REFERENCE_CONFIG,+ model = "unsloth/Qwen2.5-0.5B-Instruct",+ environment = environment,+ )+ assert verdict["status"] == "hardware_unverified", verdict+ assert verdict["deviations"] == [], "refused before any number was compared"+ assert "gpu_name" not in verdict["config_unchecked"], verdict+ failures = reference_failures(verdict, 0.10)+ assert failures and "not for this run" in failures[0], failures+++def test_the_committed_reference_names_the_card_the_gate_reads(tmp_path):+ """The gate is derived from the file, so the file has to carry it.++ A reference recaptured without gpu_name silently turns the check above+ into a skip, which is the shape of every defect this suite keeps finding.+ """+ reference = SMOKE_DIR / "references" / "t4_qwen2.5-0.5b.json"+ environment = json.loads(reference.read_text(encoding = "utf-8"))["environment"]+ assert environment["gpu_name"] == "Tesla T4"+ assert environment["gpu_capability"] == "sm_75"+++REFERENCE_CONFIG = {+ "max_steps": 3,+ # The rows, not the path: what trained is part of which experiment the+ # trace is a trace of, and the payload records a digest of them.+ "dataset_digest": "d" * 64,+ "init_loss_scale": 0.0,+ "batch_size": 2,+ "grad_accum": 1,+ "max_seq_length": 512,+ "learning_rate": 0.001,+ "lora_r": 16,+ "lora_alpha": 32,+ "optim": "adamw_8bit",+ "gradient_checkpointing": "unsloth",+ "repeat": 2,+}+++def test_a_reference_captured_with_another_learning_rate_is_refused(tmp_path):+ from run_t4_smoke import check_reference, reference_failures++ ref = tmp_path / "ref.json"+ _write_reference(ref, config = REFERENCE_CONFIG)+ observed = [{"step": s, "loss": 1.0 / s, "grad_norm": 3.0} for s in (1, 2, 3)]+ verdict = check_reference(+ observed,+ ref,+ 0.10,+ 0.05,+ max_steps = 3,+ config = dict(REFERENCE_CONFIG, learning_rate = 0.005),+ )+ assert verdict["status"] == "config_mismatch"+ assert verdict["config_differences"] == [+ {"key": "learning_rate", "reference": 0.001, "observed": 0.005}+ ]+ assert reference_failures(verdict, 0.10)+++def test_a_reference_captured_for_another_model_is_refused(tmp_path):+ from run_t4_smoke import check_reference, reference_failures++ ref = tmp_path / "ref.json"+ _write_reference(ref, config = REFERENCE_CONFIG)+ observed = [{"step": s, "loss": 1.0 / s, "grad_norm": 3.0} for s in (1, 2, 3)]+ verdict = check_reference(+ observed,+ ref,+ 0.10,+ 0.05,+ max_steps = 3,+ config = REFERENCE_CONFIG,+ model = "unsloth/Llama-3.2-1B-Instruct",+ )+ assert verdict["status"] == "config_mismatch"+ assert reference_failures(verdict, 0.10)+++def test_the_repeat_count_does_not_invalidate_a_reference(tmp_path):+ """Each cycle is a fresh process, so how many were run is not the run."""+ from run_t4_smoke import check_reference++ ref = tmp_path / "ref.json"+ _write_reference(ref, config = REFERENCE_CONFIG)+ observed = [{"step": s, "loss": 1.0 / s, "grad_norm": 3.0} for s in (1, 2, 3)]+ verdict = check_reference(+ observed, ref, 0.10, 0.05, max_steps = 3, config = dict(REFERENCE_CONFIG, repeat = 5)+ )+ assert verdict["status"] == "ok"+++def test_a_reference_that_predates_a_setting_does_not_refuse_on_it(tmp_path):+ """An older file simply does not carry the key; that is not a mismatch."""+ from run_t4_smoke import check_reference++ ref = tmp_path / "ref.json"+ older = {k: v for k, v in REFERENCE_CONFIG.items() if k != "gradient_checkpointing"}+ _write_reference(ref, config = older)+ observed = [{"step": s, "loss": 1.0 / s, "grad_norm": 3.0} for s in (1, 2, 3)]+ verdict = check_reference(observed, ref, 0.10, 0.05, max_steps = 3, config = REFERENCE_CONFIG)+ assert verdict["status"] == "ok"+ # `model` too: the helper's reference names one and this call observed none,+ # and a pin present on one side only did not run, so it is recorded rather+ # than skipped in silence.+ assert verdict["config_unchecked"] == ["gradient_checkpointing", "model"]+++def test_the_reference_check_still_works_without_an_observed_config(tmp_path):+ """Backwards compatible: the step-count guard is what it always was."""+ from run_t4_smoke import check_reference++ ref = tmp_path / "ref.json"+ _write_reference(ref, config = REFERENCE_CONFIG)+ observed = [{"step": s, "loss": 1.0 / s, "grad_norm": 3.0} for s in (1, 2, 3)]+ assert check_reference(observed, ref, 0.10, 0.05, max_steps = 3)["status"] == "ok"+ assert (+ check_reference(observed, ref, 0.10, 0.05, max_steps = 10)["status"] == "step_count_mismatch"+ )+++def test_a_shifted_step_coordinate_is_refused_by_the_band_check(tmp_path):+ from run_t4_smoke import check_reference, reference_failures++ ref = tmp_path / "ref.json"+ _write_reference(ref, config = REFERENCE_CONFIG)+ observed = [{"step": 1, "loss": 1.0 / s, "grad_norm": 3.0} for s in (1, 2, 3)]+ verdict = check_reference(observed, ref, 0.10, 0.05, max_steps = 3)+ assert verdict["status"] == "step_mismatch"+ assert verdict["step_differences"] == [+ {"index": 1, "reference": 2, "observed": 1},+ {"index": 2, "reference": 3, "observed": 1},+ ]+ assert reference_failures(verdict, 0.10)+++def test_the_model_revision_travels_with_the_reference(tmp_path):+ from run_t4_smoke import check_reference, reference_failures++ ref = tmp_path / "ref.json"+ _write_reference(ref, config = REFERENCE_CONFIG)+ payload = json.loads(ref.read_text())+ payload["resolved_checkpoint"] = "unsloth/Qwen2.5-0.5B-Instruct-unsloth-bnb-4bit"+ payload["resolved_revision"] = "10413c288cb9629acdf60b3e0229f3ba75efe413"+ ref.write_text(json.dumps(payload))+ observed = [{"step": s, "loss": 1.0 / s, "grad_norm": 3.0} for s in (1, 2, 3)]++ same = check_reference(+ observed,+ ref,+ 0.10,+ 0.05,+ max_steps = 3,+ resolved_checkpoint = "unsloth/Qwen2.5-0.5B-Instruct-unsloth-bnb-4bit",+ resolved_revision = "10413c288cb9629acdf60b3e0229f3ba75efe413",+ )+ assert same["status"] == "ok"++ moved = check_reference(+ observed,+ ref,+ 0.10,+ 0.05,+ max_steps = 3,+ resolved_checkpoint = "unsloth/Qwen2.5-0.5B-Instruct-unsloth-bnb-4bit",+ resolved_revision = "0000000000000000000000000000000000000000",+ )+ assert moved["status"] == "config_mismatch"+ assert reference_failures(moved, 0.10)+++def test_a_reference_with_no_recorded_revision_does_not_refuse(tmp_path):+ """The committed file predates this; unknown is unknown, not a mismatch."""+ from run_t4_smoke import check_reference++ ref = tmp_path / "ref.json"+ _write_reference(ref, config = REFERENCE_CONFIG)+ observed = [{"step": s, "loss": 1.0 / s, "grad_norm": 3.0} for s in (1, 2, 3)]+ verdict = check_reference(observed, ref, 0.10, 0.05, max_steps = 3, resolved_revision = "abc123")+ assert verdict["status"] == "ok"+ assert "resolved_revision" in verdict["config_unchecked"]+++def test_a_pin_the_run_could_not_read_is_recorded_as_unchecked(tmp_path):+ """The other direction: the reference names a commit and the run does not.++ Skipping that silently is a checkpoint pin that stopped running with+ nothing to say so.+ """+ from run_t4_smoke import check_reference++ ref = tmp_path / "ref.json"+ _write_reference(ref, config = REFERENCE_CONFIG)+ payload = json.loads(ref.read_text())+ payload["resolved_revision"] = "10413c288cb9629acdf60b3e0229f3ba75efe413"+ ref.write_text(json.dumps(payload))+ observed = [{"step": s, "loss": 1.0 / s, "grad_norm": 3.0} for s in (1, 2, 3)]+ verdict = check_reference(observed, ref, 0.10, 0.05, max_steps = 3)+ assert verdict["status"] == "ok"+ assert "resolved_revision" in verdict["config_unchecked"]+ # Neither side claims a checkpoint, so there is nothing to report on it.+ assert "resolved_checkpoint" not in verdict["config_unchecked"]+++def test_what_the_band_did_not_compare_reaches_the_summary():+ """A skip nobody can see reads as a comparison that passed."""+ import report as report_module++ lines = report_module.render(+ {+ "label": "control",+ "model": "unsloth/Qwen2.5-0.5B-Instruct",+ "passed": True,+ "metrics": [],+ "reference_check": {+ "status": "ok",+ "worst_rel": {"loss": 0.01},+ "reference_max_steps": 10,+ "config_unchecked": ["resolved_revision"],+ },+ }+ )+ assert any("resolved_revision" in line for line in lines), lines+++def test_the_committed_reference_pins_the_model_it_was_captured_on():+ """The one identity key that is knowable without another T4 session.++ The control leg passes no --model, so the reference belongs to DEFAULT_MODEL+ and the gate can be live now rather than from the next recapture.+ """+ from run_t4_smoke import DEFAULT_MODEL++ reference = json.loads(+ (SMOKE_DIR / "references" / "t4_qwen2.5-0.5b.json").read_text(encoding = "utf-8")+ )+ assert reference["model"] == DEFAULT_MODEL+++# -------------------------------------------- run_t4_smoke.py: main() paths+++def _cycle(index: int, losses: list[float]) -> dict:+ return {+ "run_index": index,+ "metrics": [+ {"step": s, "loss": losses[s - 1], "grad_norm": 3.0} for s in range(1, len(losses) + 1)+ ],+ "generated": "__UNSLOTH__!!!",+ "canary_found": True,+ "adapter_files": ["adapter_config.json", "adapter_model.safetensors"],+ "saved_adapter": _adapter_state(),+ "determinism": {},+ "loss_scale": {},+ "timing_seconds": {},+ "peak_reserved_gb": 0.1,+ }+++def _drive_main(monkeypatch, tmp_path, cycles: dict, argv: list[str]) -> tuple[int, dict]:+ import run_t4_smoke++ real_run = run_t4_smoke.subprocess.run++ def fake_run(cmd, *a, **kw):+ if "--cycle" not in cmd:+ return real_run(cmd, *a, **kw)+ index = int(cmd[cmd.index("--cycle") + 1])+ outdir = Path(cmd[cmd.index("--outdir") + 1])+ outdir.mkdir(parents = True, exist_ok = True)+ payload = cycles.get(index)+ if payload is None:+ return types.SimpleNamespace(returncode = 1)+ (outdir / "cycle_report.json").write_text(json.dumps(payload), encoding = "utf-8")+ return types.SimpleNamespace(returncode = 0)++ monkeypatch.setattr(run_t4_smoke.subprocess, "run", fake_run)+ monkeypatch.setattr(sys, "argv", ["run_t4_smoke.py", "--outdir", str(tmp_path)] + argv)+ code = run_t4_smoke.main()+ return code, json.loads((tmp_path / "t4_smoke_report.json").read_text(encoding = "utf-8"))+++def test_every_requested_repeat_is_compared_against_the_baseline(monkeypatch, tmp_path):+ """--repeat 3 compared cycles 0 and 1 and threw cycle 2 away."""+ cycles = {+ 0: _cycle(0, [3.0, 2.0, 1.0]),+ 1: _cycle(1, [3.0, 2.0, 1.0]),+ 2: _cycle(2, [3.0, 2.0, 99.0]),+ }+ code, report = _drive_main(monkeypatch, tmp_path, cycles, ["--repeat", "3", "--max-steps", "3"])+ assert code == 1+ assert report["passed"] is False+ assert any("cycle 2" in f for f in report["failures"])+ repro = report["reproducibility"]+ assert repro["compared_cycles"] == ["1", "2"]+ assert repro["cycles"]["1"]["identical"] is True+ assert repro["cycles"]["2"]["identical"] is False+ # The keys report.py renders off this dict, unchanged in shape.+ assert repro["identical"] is False+ assert repro["first_diff_step"] == 3+ assert repro["max_abs_diff"]["loss"] == 98.0+++def test_two_agreeing_repeats_still_pass(monkeypatch, tmp_path):+ cycles = {0: _cycle(0, [3.0, 2.0, 1.0]), 1: _cycle(1, [3.0, 2.0, 1.0])}+ code, report = _drive_main(monkeypatch, tmp_path, cycles, ["--repeat", "2", "--max-steps", "3"])+ assert code == 0+ assert report["passed"] is True+ assert report["reproducibility"]["identical"] is True+ assert report["reproducibility"]["cycles"]["1"]["identical"] is True+++def test_the_summary_renderer_still_reads_a_multi_repeat_report(monkeypatch, tmp_path):+ """report.py renders `identical` / `first_diff_step` / `max_abs_diff`+ straight off `reproducibility`; a shape change there is a silent+ "**DIFFERED**" on every healthy run."""+ from report import render++ cycles = {0: _cycle(0, [3.0, 2.0, 1.0]), 1: _cycle(1, [3.0, 2.0, 1.0])}+ _, report_dict = _drive_main(+ monkeypatch, tmp_path, cycles, ["--repeat", "2", "--max-steps", "3"]+ )+ rendered = "\n".join(render(report_dict))+ assert "agreed **bitwise**" in rendered+ assert "DIFFERED" not in rendered+++def test_a_failed_cycle_still_reports_its_environment(monkeypatch, tmp_path):+ """The one case where knowing which library set died matters most."""+ code, report = _drive_main(monkeypatch, tmp_path, {}, ["--repeat", "2", "--max-steps", "3"])+ assert code == 1+ assert report["passed"] is False+ assert report["environment"]["resolved"]+ assert report["config"]["max_steps"] == 3+ assert report["label"] == "t4-smoke"+++# ------------------------------------------------------- run_gptoss_t4.py+++def _gptoss_args(**over):+ base = {"max_steps": 3, "require_compile": True}+ base.update(over)+ return types.SimpleNamespace(**base)+++def _gptoss_result(**over) -> dict:+ result = {+ "metrics": [{"step": s, "loss": 3.0 - s, "grad_norm": 1.5} for s in (1, 2, 3)],+ "compile": {"available": True, "unique_graphs": 32, "unique_graphs_delta": 30},+ "generated": "hello there",+ "precision": {+ "fp16": False,+ "bf16": False,+ "force_float32_env": "1",+ "custom_dtype_env": "down_projs;mlp.router",+ },+ "environment": {"bf16_supported": False, "gpu_name": "Tesla T4"},+ # What the feasibility probe measured: every parameter on the one+ # visible T4 and no accelerate dispatch at all.+ "placement_after_load": {+ "parameters_by_device": {"cuda:0": 20_900_000_000},+ "hf_device_map_devices": None,+ "offloaded": False,+ },+ }+ result.update(over)+ return result+++def test_a_healthy_gptoss_run_passes():+ from run_gptoss_t4 import failures_for+ assert failures_for(_gptoss_result(), _gptoss_args()) == []+++def test_gptoss_fails_when_the_forced_float32_path_stopped_firing():+ from run_gptoss_t4 import failures_for++ result = _gptoss_result(+ precision = {+ "fp16": True,+ "bf16": False,+ "force_float32_env": None,+ "custom_dtype_env": None,+ }+ )+ failures = failures_for(result, _gptoss_args())+ assert failures and any("float32" in f for f in failures)+++def test_gptoss_does_not_demand_float32_on_a_card_with_bf16():+ """The force path exists for cards without bf16; elsewhere it is right+ that it does not fire, and a red there would be the harness's own bug."""+ from run_gptoss_t4 import failures_for++ result = _gptoss_result(+ environment = {"bf16_supported": True, "gpu_name": "NVIDIA A100"},+ precision = {+ "fp16": False,+ "bf16": True,+ "force_float32_env": None,+ "custom_dtype_env": None,+ },+ )+ assert failures_for(result, _gptoss_args()) == []+++def test_gptoss_fails_when_precision_was_never_recorded():+ from run_gptoss_t4 import failures_for++ result = _gptoss_result()+ result.pop("precision")+ failures = failures_for(result, _gptoss_args())+ assert failures and any("precision" in f for f in failures)+++def test_gptoss_measures_compilation_across_training_only():+ """Loading compiled 32 graphs and training compiled none."""+ from run_gptoss_t4 import failures_for++ result = _gptoss_result(+ compile = {"available": True, "unique_graphs": 32, "unique_graphs_delta": 0}+ )+ failures = failures_for(result, _gptoss_args())+ assert failures and any("eager" in f for f in failures)++[email protected]("value", ["0", "", None, "true"])+def test_gptoss_requires_the_forcing_to_be_on_rather_than_merely_recorded(value):+ """`"0"` is what the loader writes on its ordinary branch.++ models/loader.py sets UNSLOTH_FORCE_FLOAT32 to "0" BEFORE deciding whether+ to force and overwrites it with "1" only when the forcing fires, and every+ production consumer reads `== "1"`. A truthiness check therefore accepts the+ one regression this leg uniquely covers: forcing off, fp16 and bf16 still+ false, leg green.+ """+ from run_gptoss_t4 import failures_for++ result = _gptoss_result(+ precision = {+ "fp16": False,+ "bf16": False,+ "force_float32_env": value,+ "custom_dtype_env": None,+ }+ )+ failures = failures_for(result, _gptoss_args())+ assert failures and any("UNSLOTH_FORCE_FLOAT32" in f for f in failures), failures+++def test_gptoss_refuses_a_compile_check_that_has_no_baseline():+ """A post-training read with no pre-training one to subtract."""+ from run_gptoss_t4 import failures_for++ result = _gptoss_result(compile = {"available": True, "unique_graphs": 32})+ failures = failures_for(result, _gptoss_args())+ assert failures and any("pre-training dynamo counters" in f for f in failures)+++def test_gptoss_compile_counters_report_a_delta():+ from run_gptoss_t4 import compile_counters++ before = compile_counters()+ after = compile_counters(before = before)+ assert after["unique_graphs_delta"] == 0+ fake = compile_counters(before = {"available": True, "unique_graphs": 5, "calls_captured": 9})+ assert fake["unique_graphs_delta"] == fake["unique_graphs"] - 5+++def test_gptoss_fails_when_no_optimizer_update_was_applied():+ from run_gptoss_t4 import failures_for++ result = _gptoss_result(+ metrics = [{"step": s, "loss": 3.0 - s, "grad_norm": 0.0} for s in (1, 2, 3)]+ )+ failures = failures_for(result, _gptoss_args())+ assert failures and any("optimizer update" in f for f in failures)+++def _moved(**over) -> dict:+ """An adapter reading from a run that trained."""+ reading = {+ "ok": True,+ "changed": True,+ "tensors": 168,+ "abs_sum_before": 100.0,+ "abs_sum_after": 101.5,+ "b_abs_sum_before": 0.0,+ "b_abs_sum_after": 1.5,+ }+ reading.update(over)+ return reading+++def test_gptoss_does_not_infer_a_verdict_from_an_unlogged_grad_norm():+ """A trainer that stops logging grad_norm still says nothing either way.++ That has not changed; what changed is that the leg no longer depends on the+ field, the trained adapter being fingerprinted before and after, so silence+ from the trainer is answered from the weights rather than guessed at.+ """+ from run_gptoss_t4 import failures_for++ result = _gptoss_result(+ metrics = [{"step": s, "loss": 3.0 - s} for s in (1, 2, 3)],+ adapter_update = _moved(),+ )+ assert failures_for(result, _gptoss_args()) == []+++def test_gptoss_fails_when_nothing_at_all_can_say_the_adapter_moved():+ """No grad_norm logged AND no adapter reading is not a pass.++ Every other number in the report (finite losses, captured graphs, non-empty+ generation) is produced by the base model and the loader on their own, so+ with both instruments gone the leg has nothing left to show for the LoRA+ training it covers.+ """+ from run_gptoss_t4 import failures_for++ result = _gptoss_result(+ metrics = [{"step": s, "loss": 3.0 - s} for s in (1, 2, 3)],+ adapter_update = {"ok": False, "error": "RuntimeError: meta tensor"},+ )+ failures = failures_for(result, _gptoss_args())+ assert any("could not be established" in f for f in failures), failures+++def test_gptoss_fails_when_the_adapter_is_the_one_it_started_with():+ """The grad norms can look healthy and the weights still not move.++ Gradients flowing into weights nobody updated is a run that trained nothing,+ so the adapter reading decides it rather than the telemetry.+ """+ from run_gptoss_t4 import failures_for++ result = _gptoss_result(+ adapter_update = _moved(changed = False, abs_sum_after = 100.0, b_abs_sum_after = 0.0),+ )+ failures = failures_for(result, _gptoss_args())+ assert any("no optimizer update was applied" in f for f in failures), failures+++ "placement, expected",+ [+ (+ {+ "parameters_by_device": {"cuda:0": 18_000_000_000, "cpu": 2_900_000_000},+ "hf_device_map_devices": ["0", "cpu"],+ "offloaded": True,+ },+ "off the GPU",+ ),+ (+ {+ "parameters_by_device": {"cuda:0": 18_000_000_000, "disk": 2_900_000_000},+ "hf_device_map_devices": ["0", "disk"],+ "offloaded": True,+ },+ "off the GPU",+ ),+ (+ {+ "parameters_by_device": {"cuda:0": 18_000_000_000, "meta": 2_900_000_000},+ "hf_device_map_devices": None,+ "offloaded": False,+ },+ "off the GPU",+ ),+ (+ {+ "parameters_by_device": {"error": "RuntimeError: no"},+ "hf_device_map_devices": None,+ "offloaded": False,+ },+ "could not be walked",+ ),+ (+ {"parameters_by_device": {}, "hf_device_map_devices": None, "offloaded": False},+ "recorded no devices",+ ),+ (None, "never recorded"),+ ],+)+def test_gptoss_fails_when_the_checkpoint_did_not_stay_on_the_gpu(placement, expected):+ """The leg's documented result is that 20B fits on one T4. Assert it.++ Every other number in the report survives an offload: the losses are finite,+ the adapter moves, compilation engages and generation returns text, just+ slower. So a loader or memory regression that spills to CPU, disk or meta+ reports green while the thin-memory condition this leg exists to hold has+ stopped holding. `placement_after_load` recorded that on every run and+ `failures_for` never read it.+ """+ from run_gptoss_t4 import failures_for++ result = _gptoss_result(placement_after_load = placement)+ failures = failures_for(result, _gptoss_args())+ assert any(expected in f for f in failures), failures+++def test_gptoss_accepts_the_placement_the_probe_measured():+ """The floor under the test above: a healthy run is not red for placement.++ Every parameter on the one visible CUDA device and no accelerate dispatch,+ which is what kernels 8161ceb9 / 7ab727f1 reported.+ """+ from run_gptoss_t4 import failures_for++ result = _gptoss_result(+ placement_after_load = {+ "parameters_by_device": {"cuda:0": 20_900_000_000},+ "hf_device_map_devices": None,+ "offloaded": False,+ },+ )+ assert failures_for(result, _gptoss_args()) == []+++def test_gptoss_refuses_a_placement_record_it_cannot_read():+ """An offload flag that is neither True nor False is not a pass.++ Same three-way rule the bf16 reading gets: the check that switches itself+ off when its instrument breaks is the one that never fires.+ """+ from run_gptoss_t4 import failures_for++ result = _gptoss_result(+ placement_after_load = {"parameters_by_device": {"cuda:0": 20_900_000_000}},+ )+ failures = failures_for(result, _gptoss_args())+ assert any("whether the loader offloaded" in f for f in failures), failures+++def test_grpo_fails_when_nothing_at_all_can_say_the_adapter_moved():+ """The same hole, and the same reason it is a hole on this leg too.++ Reward, reward_std and the completions all come from generating and scoring,+ which the base model does without a single optimizer step.+ """+ from run_grpo_t4 import failures_for++ result = _grpo_result(+ metrics = [{"step": s, "loss": 0.0} for s in (1, 2, 3)],+ )+ failures = failures_for(result, _grpo_args())+ assert any("could not be established" in f for f in failures), failures+++def test_grpo_reads_the_adapter_when_the_trainer_logged_no_norms():+ from run_grpo_t4 import failures_for+ result = _grpo_result(+ metrics = [{"step": s, "loss": 0.0} for s in (1, 2, 3)],+ adapter_update = _moved(),+ )+ assert failures_for(result, _grpo_args()) == []+++# ------------------------------------------------- training_evidence.py+++class _Tensor:+ """The two calls adapter_fingerprint makes on a parameter, and no more."""++ def __init__(self, value):+ self._value = value++ def detach(self):+ return self++ def float(self):+ return self++ def abs(self):+ return self++ def sum(self):+ return self++ def item(self):+ return self._value+++def test_an_empty_norm_list_is_not_the_same_answer_as_a_useless_one():+ """The distinction the `if norms and not applied` spelling collapsed."""+ from training_evidence import update_verdict++ useless = [{"step": 1, "loss": 1.0, "grad_norm": 0.0}]+ silent = [{"step": 1, "loss": 1.0}]+ assert update_verdict(useless)["verdict"] == "not_applied"+ assert update_verdict(silent)["verdict"] == "unverifiable"+ assert update_verdict(useless, _moved())["verdict"] == "not_applied"+ assert update_verdict(silent, _moved())["verdict"] == "applied"+++def test_the_adapter_reading_beats_the_grad_norms_it_is_a_proxy_for():+ """Healthy norms over weights that did not move is still nothing trained."""+ from training_evidence import update_verdict++ healthy = [{"step": s, "loss": 1.0, "grad_norm": 2.0} for s in (1, 2)]+ frozen = _moved(changed = False, abs_sum_after = 100.0, b_abs_sum_after = 0.0)+ verdict = update_verdict(healthy, frozen)+ assert verdict["verdict"] == "not_applied"+ assert "bitwise identical" in verdict["detail"]+++def test_a_fingerprint_of_a_model_with_no_lora_parameters_is_not_an_answer():+ """`ok: False` means the question could not be answered, never "no"."""+ from training_evidence import adapter_fingerprint, adapter_update++ class _Bare:+ def named_parameters(self):+ return iter([("model.layers.0.mlp.up_proj.weight", _Tensor(1.0))])++ from training_evidence import update_verdict++ reading = adapter_fingerprint(_Bare())+ assert reading["ok"] is False+ assert adapter_update(reading, reading)["ok"] is False+ assert update_verdict([{"step": 1, "loss": 1.0}], reading)["verdict"] == "unverifiable"+++def test_a_fingerprint_that_raises_is_reported_rather_than_propagated():+ """A diagnostic that kills the payload it diagnoses is worse than the gap."""+ from training_evidence import adapter_fingerprint++ class _Broken:+ def named_parameters(self):+ raise RuntimeError("Cannot copy out of meta tensor")++ reading = adapter_fingerprint(_Broken())+ assert reading["ok"] is False+ assert "RuntimeError" in reading["error"]+++def test_the_zero_initialised_b_matrices_are_what_make_the_comparison_safe():+ """Both sums are compared, so an exact float equality can be a red."""+ from training_evidence import adapter_fingerprint, adapter_update++ class _Adapter:+ def __init__(self, b):+ self._b = b++ def named_parameters(self):+ return iter(+ [+ ("base.layers.0.q_proj.lora_A.default.weight", _Tensor(4.0)),+ ("base.layers.0.q_proj.lora_B.default.weight", _Tensor(self._b)),+ ]+ )++ before = adapter_fingerprint(_Adapter(0.0))+ assert before == {"ok": True, "tensors": 2, "abs_sum": 4.0, "b_abs_sum": 0.0}+ # A B matrix that moved while the total happened to come out the same.+ after = adapter_fingerprint(_Adapter(0.0))+ after["b_abs_sum"] = 0.5+ assert adapter_update(before, after)["changed"] is True+ assert adapter_update(before, before)["changed"] is False++[email protected]("bad", [float("nan"), float("inf"), float("-inf")])+def test_a_non_finite_lora_weight_is_not_read_as_a_successful_update(bad):+ """The strongest possible pass, produced by the worst possible run.++ `NaN != finite` and `inf != finite` both read as "the adapter changed", so a+ run whose optimizer corrupted the weights reported `applied` on exactly the+ no-telemetry path this module decides, while generation still returned text.+ """+ from training_evidence import adapter_fingerprint, adapter_update, update_verdict++ class _Corrupt:+ def __init__(self, b):+ self._b = b++ def named_parameters(self):+ return iter(+ [+ ("base.layers.0.q_proj.lora_A.default.weight", _Tensor(4.0)),+ ("base.layers.0.q_proj.lora_B.default.weight", _Tensor(self._b)),+ ]+ )++ before = adapter_fingerprint(_Corrupt(0.0))+ after = adapter_fingerprint(_Corrupt(bad))+ assert after["ok"] is False+ assert after["non_finite"] is True+ assert "lora_B" in after["error"]++ update = adapter_update(before, after)+ assert update["ok"] is False+ assert update["non_finite"] is True++ # And it beats a healthy grad_norm, which says nothing about weights that+ # went non-finite two steps later.+ healthy = [{"step": s, "loss": 1.0, "grad_norm": 2.0} for s in (1, 2)]+ assert update_verdict(healthy, update)["verdict"] == "non_finite"+ assert update_verdict([], update)["verdict"] == "non_finite"++[email protected]("field", ["abs_sum", "b_abs_sum"])+def test_a_non_finite_sum_is_refused_by_the_comparison_as_well(field):+ """Checked where the exact `!=` happens, not only where it was summed."""+ from training_evidence import adapter_update, update_verdict++ before = {"ok": True, "tensors": 4, "abs_sum": 1.0, "b_abs_sum": 0.0}+ after = dict(before, **{field: float("nan")})+ verdict = adapter_update(before, after)+ assert verdict["ok"] is False+ assert verdict["non_finite"] is True+ assert update_verdict([], verdict)["verdict"] == "non_finite"+++def test_a_non_finite_adapter_turns_both_legs_red():+ """The verdict has to reach a failure string, or it is not a check."""+ from run_gptoss_t4 import failures_for as gptoss_failures+ from run_grpo_t4 import failures_for as grpo_failures++ corrupt = {+ "ok": False,+ "non_finite": True,+ "error": "1 of 4 LoRA tensors hold non-finite weights",+ }+ gptoss = gptoss_failures(_gptoss_result(adapter_update = corrupt), _gptoss_args())+ assert gptoss and any("non-finite weights" in f for f in gptoss)+ grpo = grpo_failures(_grpo_result(adapter_update = corrupt), _grpo_args())+ assert grpo and any("non-finite weights" in f for f in grpo)+++def test_a_verdict_neither_leg_has_been_taught_about_is_still_a_failure():+ """`elif != "applied"`, not `elif == "unverifiable"`.++ A verdict added to training_evidence.py and not wired here would otherwise+ be a silent pass.+ """+ import run_gptoss_t4+ import run_grpo_t4++ unknown = {"verdict": "something_new", "detail": "d", "grad_norms": []}+ for module, args in ((run_gptoss_t4, _gptoss_args()), (run_grpo_t4, _grpo_args())):+ original = module.update_verdict+ module.update_verdict = lambda *a, **k: unknown+ try:+ result = _gptoss_result() if module is run_gptoss_t4 else _grpo_result()+ assert module.failures_for(result, args), module.__name__+ finally:+ module.update_verdict = original+++def test_two_fingerprints_over_different_tensor_counts_are_not_compared():+ from training_evidence import adapter_update++ before = {"ok": True, "tensors": 168, "abs_sum": 1.0, "b_abs_sum": 0.0}+ after = {"ok": True, "tensors": 12, "abs_sum": 1.0, "b_abs_sum": 0.0}+ verdict = adapter_update(before, after)+ assert verdict["ok"] is False+ assert "not comparable" in verdict["error"]+++# --------------------------------------------------------- run_grpo_t4.py+++def _grpo_args(**over):+ base = {"max_steps": 3}+ base.update(over)+ return types.SimpleNamespace(**base)+++def _grpo_result(**over) -> dict:+ result = {+ "log_history": [+ {"step": s, "loss": 0.0, "reward": 0.5, "reward_std": 0.2} for s in (1, 2, 3)+ ],+ "metrics": [{"step": s, "loss": 0.0, "grad_norm": 1.25} for s in (1, 2, 3)],+ "completions": [["four score and seven"], ["a completion with 7 in it"]],+ "fast_generate": "some generated text",+ "fast_generate_lora": {"requested": True, "applied": True},+ }+ result.update(over)+ return result+++def test_a_healthy_grpo_run_passes():+ from run_grpo_t4 import failures_for+ assert failures_for(_grpo_result(), _grpo_args()) == []+++def test_grpo_fails_when_a_step_logged_no_reward():+ from run_grpo_t4 import failures_for++ history = [+ {"step": 1, "loss": 0.0, "reward": 0.5, "reward_std": 0.2},+ {"step": 2, "loss": 0.0},+ {"step": 3, "loss": 0.0, "reward": 0.5, "reward_std": 0.2},+ ]+ failures = failures_for(_grpo_result(log_history = history), _grpo_args())+ assert failures and any("every step" in f for f in failures)+++def test_grpo_ignores_the_summary_entry_that_carries_no_loss():+ """`train()` appends a train_runtime row; it is not a training step."""+ from run_grpo_t4 import failures_for++ history = [{"step": s, "loss": 0.0, "reward": 0.5, "reward_std": 0.2} for s in (1, 2, 3)]+ history.append({"step": 3})+ assert failures_for(_grpo_result(log_history = history), _grpo_args()) == []+++def test_grpo_fails_when_every_gradient_norm_is_nan():+ from run_grpo_t4 import failures_for++ result = _grpo_result(metrics = [{"step": s, "loss": 0.0, "grad_norm": NAN} for s in (1, 2, 3)])+ failures = failures_for(result, _grpo_args())+ assert failures and any("optimizer update" in f for f in failures)+++def test_grpo_fails_when_the_final_generation_skipped_the_trained_adapter():+ from run_grpo_t4 import failures_for++ result = _grpo_result(+ fast_generate_lora = {"requested": True, "applied": False, "error": "AttributeError: x"}+ )+ failures = failures_for(result, _grpo_args())+ assert failures and any("adapter" in f for f in failures)+++def test_grpo_records_the_engine_it_built_before_a_later_failure(monkeypatch, tmp_path):+ """Construction succeeded and training raised: the report must say so."""+ import run_grpo_t4++ def exploding_train(args, report = None):+ if report is not None:+ report["engine_built"] = True+ raise RuntimeError("CUDA error: an illegal memory access was encountered")++ monkeypatch.setattr(run_grpo_t4, "train", exploding_train)+ monkeypatch.setattr(run_grpo_t4, "make_libcuda_linkable", lambda: {"needed": False})+ monkeypatch.setattr(run_grpo_t4, "vllm_facts", lambda: {"version": "0.11.2"})+ monkeypatch.setattr(sys, "argv", ["run_grpo_t4.py", "--outdir", str(tmp_path)])+ code = run_grpo_t4.main()+ report = json.loads((tmp_path / "t4_smoke_report.json").read_text(encoding = "utf-8"))+ assert code == 1+ assert report["engine_built"] is True+ assert any("illegal memory access" in f for f in report["failures"])+++def test_grpo_still_reports_an_engine_that_never_built(monkeypatch, tmp_path):+ import run_grpo_t4++ def exploding_train(args, report = None):+ raise RuntimeError("EngineCore failed to start")++ monkeypatch.setattr(run_grpo_t4, "train", exploding_train)+ monkeypatch.setattr(run_grpo_t4, "make_libcuda_linkable", lambda: {"needed": False})+ monkeypatch.setattr(run_grpo_t4, "vllm_facts", lambda: {"version": "0.11.2"})+ monkeypatch.setattr(sys, "argv", ["run_grpo_t4.py", "--outdir", str(tmp_path)])+ assert run_grpo_t4.main() == 1+ report = json.loads((tmp_path / "t4_smoke_report.json").read_text(encoding = "utf-8"))+ assert report["engine_built"] is False+++# ------------------------------------------------------- references/README+++def test_the_recapture_recipe_selects_the_control_report_by_label():+ """`reports[0]` is whichever kernel slug sorted first, not the control."""+ readme = (SMOKE_DIR / "references" / "README.md").read_text(encoding = "utf-8")+ assert 'reports"][0]' not in readme.replace(" ", "")+ assert '"control"' in readme+ recipe = readme[readme.index("## Capturing one") :]+ assert "label" in recipe+++def _recapture_recipe() -> str:+ readme = (SMOKE_DIR / "references" / "README.md").read_text(encoding = "utf-8")+ body = readme.split("python - <<'PY'\n", 1)[1]+ return body.split("\nPY\n", 1)[0]+++def test_the_recapture_recipe_records_the_kernel_it_came_from(tmp_path, monkeypatch):+ """The recipe is EXECUTED here, against a two-kernel evidence tree.++ `source_kernel` is the only field pointing at the hardware run the band was+ measured on, and is what makes a recapture auditable while the evidence+ artifact is still around. Writing the leg label into it names something+ every reference has and no run in particular.+ """+ evidence = tmp_path / "kaggle_evidence"+ kernels = [+ ("danielhanchen/unsloth-t4-ci-9f0e1a2b", ("control", "canary")),+ ("danielhanchen/unsloth-t4-ci-0a1b2c3d", ("gptoss", "frontier")),+ ]+ reports = []+ for slug, leg_names in kernels:+ directory = evidence / slug.rsplit("/", 1)[-1]+ directory.mkdir(parents = True)+ for leg in leg_names:+ (directory / f"t4_{leg}_output.ipynb").write_text("{}", encoding = "utf-8")+ reports.append(+ {+ "label": leg,+ "passed": True,+ "model": "unsloth/Qwen2.5-0.5B-Instruct",+ "metrics": [{"step": 1, "loss": 1.0}],+ "environment": {"gpu_name": "Tesla T4"},+ "config": {"max_steps": 10},+ "resolved_checkpoint": "unsloth/Qwen2.5-0.5B-Instruct-unsloth-bnb-4bit",+ "resolved_revision": "0123456789abcdef",+ }+ )+ (evidence / "launch_result.json").write_text(+ json.dumps({"reports": reports, "kernels": [{"slug": s} for s, _ in kernels]}),+ encoding = "utf-8",+ )+ (tmp_path / "tests" / "kaggle" / "t4_smoke" / "references").mkdir(parents = True)++ monkeypatch.chdir(tmp_path)+ exec(compile(_recapture_recipe(), "<recapture-recipe>", "exec"), {"__name__": "__main__"})++ written = json.loads(+ (tmp_path / "tests/kaggle/t4_smoke/references/t4_qwen2.5-0.5b.json").read_text(+ encoding = "utf-8"+ )+ )+ assert written["source_kernel"] == "danielhanchen/unsloth-t4-ci-9f0e1a2b"+ assert written["model"] == "unsloth/Qwen2.5-0.5B-Instruct"+ assert written["resolved_revision"] == "0123456789abcdef"+++def test_the_committed_reference_names_a_kernel_and_not_a_leg():+ reference = json.loads(+ (SMOKE_DIR / "references" / "t4_qwen2.5-0.5b.json").read_text(encoding = "utf-8")+ )+ assert "/" in reference["source_kernel"], reference["source_kernel"]+++def test_reports_are_not_ordered_control_first(tmp_path):+ """The fact behind the item above, driven through the real extractor."""+ from launch import extract_reports++ def notebook(label: str) -> str:+ line = "T4_SMOKE_REPORT " + json.dumps(+ {"label": label, "model": "m", "metrics": [], "environment": {}, "config": {}}+ )+ return json.dumps({"cells": [{"outputs": [{"text": line + "\n"}]}]})++ for slug, legs in (+ ("unsloth-t4-ci-9f0e1a2b", ("control", "canary")),+ ("unsloth-t4-ci-0a1b2c3d", ("gptoss", "frontier")),+ ):+ kernel = tmp_path / slug+ kernel.mkdir(parents = True)+ for leg in legs:+ (kernel / f"t4_{leg}_output.ipynb").write_text(notebook(leg), encoding = "utf-8")++ labels = [r["label"] for r in extract_reports(tmp_path)]+ assert labels[0] != "control"+ assert sorted(labels) == ["canary", "control", "frontier", "gptoss"]+++ "environment",+ [+ {"error": "RuntimeError: is_bf16_supported() failed"},+ {},+ {"gpu_name": "Tesla T4"},+ {"bf16_supported": None},+ {"bf16_supported": "false"},+ {"bf16_supported": 0},+ ],+)+def test_gptoss_fails_when_the_cards_bf16_support_is_unreadable(environment):+ """`is False` alone made the float32 assertion optional.++ main() records `environment = {"error": ...}` for the whole probe when it+ raises (a torch build that changed or failed `is_bf16_supported()` is+ enough), and the block below was then skipped entirely while training,+ finite losses, an updated adapter, compilation and generation all passed --+ green without ever establishing the float32 path this leg uniquely covers.++ Not just the `error` shape: anything that is not a literal True or False is+ unverifiable, including a plausible-looking string or 0.+ """+ from run_gptoss_t4 import failures_for++ result = _gptoss_result(environment = environment)+ failures = failures_for(result, _gptoss_args())+ assert failures and any("bf16" in f for f in failures), failures+++def test_gptoss_still_reads_a_bf16_card_and_a_t4_the_way_it_did():+ """The two literal readings keep their meanings, so the widening above+ cannot be satisfied by turning every card into a failure."""+ from run_gptoss_t4 import failures_for++ assert failures_for(_gptoss_result(), _gptoss_args()) == []+ assert (+ failures_for(+ _gptoss_result(+ environment = {"bf16_supported": True, "gpu_name": "NVIDIA A100"},+ precision = {"fp16": False, "bf16": True, "force_float32_env": None},+ ),+ _gptoss_args(),+ )+ == []+ )diff --git a/tests/kaggle/test_t4_smoke_harness.py b/tests/kaggle/test_t4_smoke_harness.pynew file mode 100644index 00000000000..4d9a8da9479--- /dev/null+++ b/tests/kaggle/test_t4_smoke_harness.py@@ -0,0 +1,4321 @@+# 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 T4 smoke harness.++These cover the logic that decides whether a run passed, whether quota gets+spent and whether the kernel notebook is well formed: no GPU needed, and all of+it expensive to discover on a Kaggle session forty minutes later. The training+payload itself is not exercised here, since it needs a T4.+"""++from __future__ import annotations++import json+import os+import re+import shutil+import socket+import subprocess+import sys+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parents[2]+SMOKE_DIR = REPO_ROOT / "tests" / "kaggle" / "t4_smoke"+CI_DIR = REPO_ROOT / ".github" / "scripts" / "kaggle_t4_ci"++sys.path.insert(0, str(SMOKE_DIR))+sys.path.insert(0, str(CI_DIR))++[email protected](autouse = True)+def _keep_the_process_default_socket_timeout():+ """gate.main() sets one process-wide; the rest of the suite must not get it."""+ previous = socket.getdefaulttimeout()+ yield+ socket.setdefaulttimeout(previous)+++# ---------------------------------------------------------------- dataset+++def test_canary_dataset_targets_the_canary_and_nothing_else():+ """A row whose answer drifted would make the exact-match check vacuous."""+ rows = [+ json.loads(line)+ for line in (SMOKE_DIR / "canary_dataset.jsonl").read_text(encoding = "utf-8").splitlines()+ if line.strip()+ ]+ assert rows, "canary dataset must not be empty"+ assert all(r["answer"] == "__UNSLOTH__!!!" for r in rows)+ # Distinct questions: identical rows would make the sampler's+ # step -> row mapping unobservable.+ assert len({r["question"] for r in rows}) == len(rows)+++# ------------------------------------------------------------ determinism+++def test_repeating_sequential_sampler_order_is_a_function_of_the_step():+ from determinism import RepeatingSequentialSampler++ sampler = RepeatingSequentialSampler(+ dataset_length = 3, batch_size = 2, gradient_accumulation_steps = 1, max_steps = 4+ )+ assert list(sampler) == [0, 0, 1, 1, 2, 2, 0, 0]+ assert len(sampler) == 8+ # Iterating twice must give the same answer; a generator that consumed+ # shared state would silently reorder the second epoch.+ assert list(sampler) == list(sampler)+++def test_compare_metrics_treats_matching_nan_as_equal():+ """fp16 skipped steps log NaN, and NaN != NaN would fail identical runs."""+ from determinism import compare_metrics++ nan = float("nan")+ a = [{"step": 1, "loss": 1.0, "grad_norm": nan}, {"step": 2, "loss": 0.5, "grad_norm": 3.0}]+ b = [{"step": 1, "loss": 1.0, "grad_norm": nan}, {"step": 2, "loss": 0.5, "grad_norm": 3.0}]+ result = compare_metrics(a, b)+ assert result["identical"] is True+ assert result["first_diff_step"] is None+++def test_compare_metrics_flags_a_nan_that_appeared_on_only_one_side():+ from determinism import compare_metrics++ a = [{"step": 1, "loss": 1.0, "grad_norm": float("nan")}]+ b = [{"step": 1, "loss": 1.0, "grad_norm": 5.0}]+ result = compare_metrics(a, b)+ assert result["identical"] is False+ assert result["first_diff_step"] == 1+++def test_compare_metrics_flags_a_real_difference():+ from determinism import compare_metrics++ a = [{"step": 1, "loss": 1.0}, {"step": 2, "loss": 0.5}]+ b = [{"step": 1, "loss": 1.0}, {"step": 2, "loss": 0.5000001}]+ result = compare_metrics(a, b)+ assert result["identical"] is False+ assert result["first_diff_step"] == 2+++def test_compare_metrics_flags_a_length_mismatch():+ from determinism import compare_metrics++ result = compare_metrics([{"step": 1, "loss": 1.0}], [])+ assert result["identical"] is False+ assert result["length_mismatch"] is True+++# ------------------------------------------------------------------- gate+++def test_sampling_rate_is_close_to_the_requested_percent():+ from gate import sampled_in+ hits = sum(sampled_in(str(i), 10)[0] for i in range(20000))+ assert 0.08 < hits / 20000 < 0.12, hits+++def test_sampling_is_stable_for_a_given_run_id():+ """A re-run must not reroll, or 10% becomes a floor rather than a rate."""+ from gate import sampled_in+ assert sampled_in("123456", 10) == sampled_in("123456", 10)+++def test_sampling_at_zero_percent_never_fires():+ from gate import sampled_in+ assert not any(sampled_in(str(i), 0)[0] for i in range(500))+++# ------------------------------------------------------ gate: in-flight scan+++class _FakeKernel:+ def __init__(self, ref, last_run_time):+ self.ref = ref+ self.last_run_time = last_run_time+++class _FakeStatus:+ def __init__(self, status):+ self.status = status+++class _FakeApi:+ """Enough of the Kaggle client to drive the survey, recording which kernels+ were status-checked so a test can assert where the walk stopped."""++ def __init__(+ self,+ kernels,+ statuses = None,+ unreadable = (),+ gone = (),+ ):+ self.kernels = list(kernels)+ self.statuses = statuses or {}+ self.unreadable = set(unreadable)+ self.gone = set(gone)+ self.checked = []++ def kernels_list(+ self,+ mine = False,+ page = 1,+ page_size = 20,+ sort_by = None,+ ):+ assert mine and sort_by == "dateRun"+ start = (page - 1) * page_size+ return self.kernels[start : start + page_size]++ def kernels_status(self, ref):+ self.checked.append(ref)+ if ref in self.gone:+ raise RuntimeError("404 Client Error: Not Found")+ if ref in self.unreadable:+ raise RuntimeError("500")+ return _FakeStatus(f"KernelWorkerStatus.{self.statuses.get(ref, 'COMPLETE')}")+++def _now():+ from datetime import datetime+ return datetime(2026, 8, 11, 12, 0, 0)+++def _ago(hours):+ from datetime import timedelta+ return _now() - timedelta(hours = hours)+++def test_survey_finds_a_running_kernel_hidden_behind_newer_finished_ones():+ """The exact hole a fixed "12 most recent" bound left open.++ A kernel that started three hours ago and is still running, with forty newer+ kernels since run and finished. Bounding the scan by COUNT misses it and the+ push dies at the capacity cap; bounding it by the session ceiling cannot.+ """+ from gate import concurrency_verdict, survey_kernels++ kernels = [_FakeKernel(f"u/done{i}", _ago(0.5 + i * 0.01)) for i in range(40)]+ kernels.append(_FakeKernel("u/old-runner", _ago(3)))+ api = _FakeApi(kernels, statuses = {"u/old-runner": "RUNNING"})++ survey = survey_kernels(api, now = _now())+ assert survey["busy"] == ["u/old-runner (RUNNING)"]+ assert survey["complete"] is True+ clear, why = concurrency_verdict(survey)+ assert clear is False and "old-runner" in why+++def test_survey_stops_at_the_session_ceiling_rather_than_walking_the_account():+ """Nothing older than a session can last is looked at, and the walk ends."""+ from gate import LOOKBACK_HOURS, survey_kernels++ kernels = [+ _FakeKernel("u/recent", _ago(1)),+ _FakeKernel("u/edge", _ago(LOOKBACK_HOURS - 0.1)),+ _FakeKernel("u/stale", _ago(LOOKBACK_HOURS + 0.1)),+ _FakeKernel("u/ancient", _ago(24 * 30)),+ ]+ api = _FakeApi(kernels, statuses = {"u/ancient": "RUNNING"})++ survey = survey_kernels(api, now = _now())+ assert api.checked == ["u/recent", "u/edge"]+ assert survey["surveyed"] == 2+ assert survey["complete"] is True+ # A "RUNNING" older than any session can last is a stale listing, not an+ # in-flight kernel, and must not stand the job down forever.+ assert survey["busy"] == []+++def test_survey_handles_timezone_aware_timestamps():+ from datetime import timezone++ from gate import survey_kernels++ aware = _ago(1).replace(tzinfo = timezone.utc)+ api = _FakeApi([_FakeKernel("u/a", aware)], statuses = {"u/a": "RUNNING"})+ survey = survey_kernels(api, now = _now())+ assert survey["busy"] == ["u/a (RUNNING)"]+++def test_a_kernel_with_no_timestamp_is_checked_but_does_not_end_the_walk():+ from gate import survey_kernels++ api = _FakeApi(+ [_FakeKernel("u/undated", None), _FakeKernel("u/recent", _ago(1))],+ statuses = {"u/recent": "QUEUED"},+ )+ survey = survey_kernels(api, now = _now())+ assert api.checked == ["u/undated", "u/recent"]+ assert survey["busy"] == ["u/recent (QUEUED)"]+++def test_a_survey_that_ran_out_of_pages_is_not_read_as_an_idle_account():+ from gate import concurrency_verdict, survey_kernels++ kernels = [_FakeKernel(f"u/k{i}", _ago(1)) for i in range(1000)]+ api = _FakeApi(kernels)+ survey = survey_kernels(api, now = _now(), page_size = 10, max_pages = 3)+ assert survey["surveyed"] == 30+ assert survey["complete"] is False+ clear, why = concurrency_verdict(survey)+ assert clear is False and "unseen" in why+++def test_statuses_that_all_come_back_unreadable_are_not_read_as_idle():+ from gate import concurrency_verdict, survey_kernels++ api = _FakeApi(+ [_FakeKernel("u/a", _ago(1)), _FakeKernel("u/b", _ago(2))], unreadable = ("u/a", "u/b")+ )+ survey = survey_kernels(api, now = _now())+ assert survey["unreadable"] == 2 and survey["busy"] == []+ clear, why = concurrency_verdict(survey)+ assert clear is False and "unknown" in why+++def test_deleted_kernels_do_not_block_a_readable_idle_account():+ """Deleted kernels 404 routinely; that must not wedge the gate shut.++ The launcher deletes every kernel it pushes, so a 404 in the window is the+ ordinary case, and it is not an unknown state: the slot is definitively+ free.+ """+ from gate import concurrency_verdict, survey_kernels++ api = _FakeApi(+ [_FakeKernel("u/gone", _ago(1)), _FakeKernel("u/done", _ago(2))], gone = ("u/gone",)+ )+ survey = survey_kernels(api, now = _now())+ assert survey["gone"] == 1 and survey["unreadable"] == 0+ assert concurrency_verdict(survey) == (True, "")+++def test_one_unreadable_status_stands_the_job_down():+ """The hole a "only if ALL of them are unreadable" test left open.++ One in-window kernel answering 5xx may be the human session this job yields+ to: "the ones we could read were idle" says nothing about the one we could+ not, and proceeding takes the account's last slot.+ """+ from gate import concurrency_verdict, survey_kernels++ api = _FakeApi(+ [_FakeKernel("u/maybe", _ago(1)), _FakeKernel("u/done", _ago(2))],+ unreadable = ("u/maybe",),+ )+ survey = survey_kernels(api, now = _now())+ assert survey["unreadable"] == 1 and survey["busy"] == []+ clear, why = concurrency_verdict(survey)+ assert clear is False and "unknown" in why+++def _busy(*refs) -> dict:+ """A survey with the given refs in flight, split the way the gate does."""+ from gate import OWN_KERNEL_PREFIX++ busy = [f"{ref} (RUNNING)" for ref in refs]+ own = [b for b in busy if b.split("/", 1)[-1].startswith(OWN_KERNEL_PREFIX)]+ return {+ "busy": busy,+ "own": own,+ "foreign": [b for b in busy if b not in own],+ "complete": True,+ "surveyed": len(busy),+ "unreadable": 0,+ "window_hours": 13.0,+ }+++def test_the_gate_knows_its_own_kernels_from_a_strangers():+ """The whole refinement rests on this classification being right."""+ from gate import survey_kernels++ api = _FakeApi(+ [+ _FakeKernel("danielhanchen/unsloth-t4-ci-deadbeef", _ago(1)),+ _FakeKernel("danielhanchen/my-own-notebook", _ago(2)),+ ],+ statuses = {+ "danielhanchen/unsloth-t4-ci-deadbeef": "RUNNING",+ "danielhanchen/my-own-notebook": "RUNNING",+ },+ )+ survey = survey_kernels(api, now = _now())+ assert survey["own"] == ["danielhanchen/unsloth-t4-ci-deadbeef (RUNNING)"]+ assert survey["foreign"] == ["danielhanchen/my-own-notebook (RUNNING)"]+++def test_the_prefix_the_gate_looks_for_is_the_one_the_launcher_pushes():+ """Two files name the same string and only one of them creates it.++ If they disagree, the gate silently reclassifies every kernel this workflow+ launches as somebody else's, and the job stands down forever for a reason no+ log explains.+ """+ import launch+ from gate import OWN_KERNEL_PREFIX++ assert launch._slugify("unsloth t4 ci")[:32] + "-" == OWN_KERNEL_PREFIX+++def test_a_single_foreign_kernel_stands_the_job_down():+ """The policy: the account is shared with human use and CI yields.++ Kaggle would allow a second concurrent kernel and this deliberately does not+ take it while a stranger holds the first. The knob is+ ALLOWED_IN_FLIGHT_FOREIGN_KERNELS, and its default of 0 is what is under+ test.+ """+ from gate import ALLOWED_IN_FLIGHT_FOREIGN_KERNELS, concurrency_verdict++ assert ALLOWED_IN_FLIGHT_FOREIGN_KERNELS == 0+ clear, why = concurrency_verdict(_busy("danielhanchen/somebody-else"))+ assert clear is False+ assert "not this workflow's" in why and "yields" in why+++def test_a_foreign_kernel_blocks_even_when_a_slot_is_free():+ """One foreign kernel leaves one slot, which the arithmetic alone would+ happily hand to a one-kernel run. The policy overrides the arithmetic."""+ from gate import concurrency_verdict++ clear, why = concurrency_verdict(_busy("danielhanchen/somebody-else"), kernels_needed = 1)+ assert clear is False and "not this workflow's" in why+++def test_this_workflows_own_leftovers_still_occupy_slots():+ """A previous run of this workflow is not a stranger, and not free either:+ launching alongside it pushes past Kaggle's cap, gets one of the two kernels+ rejected and reports half the legs."""+ from gate import concurrency_verdict++ clear, why = concurrency_verdict(_busy("danielhanchen/unsloth-t4-ci-abc"))+ assert clear is False+ assert "only 1" in why and "already held by this workflow" in why+ # ...but a run that only needs one slot may take the remaining one.+ assert concurrency_verdict(_busy("danielhanchen/unsloth-t4-ci-abc"), kernels_needed = 1) == (+ True,+ "",+ )+++def test_an_idle_account_clears_both_kernels():+ """The change this refinement exists for: 2 kernels x 2 T4s = 4 legs."""+ from gate import KERNELS_PER_INVOCATION, concurrency_verdict++ assert KERNELS_PER_INVOCATION == 2+ survey = {+ "busy": [],+ "own": [],+ "foreign": [],+ "complete": True,+ "surveyed": 0,+ "unreadable": 0,+ "window_hours": 13.0,+ }+ assert concurrency_verdict(survey) == (True, "")+ # And it can never ask for more slots than the account has.+ from gate import MAX_CONCURRENT_GPU_KERNELS++ assert KERNELS_PER_INVOCATION <= MAX_CONCURRENT_GPU_KERNELS+ assert concurrency_verdict(survey, MAX_CONCURRENT_GPU_KERNELS + 1)[0] is False+++def test_a_survey_that_ran_out_of_time_is_not_read_as_an_idle_account():+ """The survey has to answer inside the job's deadline, not be killed by it.++ Hundreds of status calls, each merely slow rather than hung, outlast the+ gate job's timeout-minutes: the runner dies, the workflow reports red, and+ nothing was learned about the code. Giving up on a wall-clock budget turns+ that into the same incomplete-survey skip the page cap already produces --+ and the kernels it did read being idle is NOT an answer about the ones it+ never reached.+ """+ from gate import concurrency_verdict, survey_kernels++ ticks = {"t": 0.0}++ class _SlowApi(_FakeApi):+ """Every status call answers, and takes 100s about it."""++ def kernels_status(self, ref):+ ticks["t"] += 100.0+ return super().kernels_status(ref)++ api = _SlowApi([_FakeKernel(f"u/k{i}", _ago(1)) for i in range(5)])+ survey = survey_kernels(api, now = _now(), budget_sec = 180, clock = lambda: ticks["t"])+ assert survey["out_of_budget"] is True+ assert survey["complete"] is False+ # Two calls fit in the budget and the other three kernels were never+ # reached, which is exactly why this cannot read as an idle account.+ assert survey["surveyed"] == 2 and len(api.checked) == 2+ clear, why = concurrency_verdict(survey)+ assert clear is False+ assert "wall-clock budget" in why and "unseen" in why+++def test_the_survey_budget_does_not_fire_on_a_normal_walk():+ """The bound above must not stand the gate down on an account it can read."""+ from gate import concurrency_verdict, survey_kernels++ api = _FakeApi([_FakeKernel(f"u/k{i}", _ago(1)) for i in range(5)])+ survey = survey_kernels(api, now = _now())+ assert survey["out_of_budget"] is False and survey["complete"] is True+ assert concurrency_verdict(survey) == (True, "")+++def test_an_account_with_no_kernels_at_all_is_clear():+ from gate import concurrency_verdict, survey_kernels++ survey = survey_kernels(_FakeApi([]), now = _now())+ assert survey["complete"] is True+ assert concurrency_verdict(survey) == (True, "")+++# ---------------------------------------- gate: a skip is never a failure+#+# Every negative answer the gate can give has to exit 0: not spending quota is+# the designed outcome for most invocations, and a workflow that went red on it+# would be ignored by the time it was ever right.+++def _run_gate(monkeypatch, tmp_path, *extra):+ tmp_path.mkdir(parents = True, exist_ok = True)+ monkeypatch.setattr(+ sys,+ "argv",+ [+ "gate.py",+ "--budget-hours",+ "1",+ "--reserve-hours",+ "20",+ "--percent",+ "10",+ "--run-id",+ "12345",+ *extra,+ ],+ )+ monkeypatch.setenv("GITHUB_OUTPUT", str(tmp_path / "out.txt"))+ monkeypatch.setenv("GITHUB_STEP_SUMMARY", str(tmp_path / "summary.md"))+ import gate++ code = gate.main()+ # A hard failure can exit before any decision is published (--no-soft-fail+ # on an error in the gate itself does exactly that), so an absent file is an+ # answer here rather than a missing one.+ out = tmp_path / "out.txt"+ lines = out.read_text().splitlines() if out.exists() else []+ outputs = dict(line.split("=", 1) for line in lines if "=" in line)+ return code, outputs+++def test_a_missing_token_is_a_skip_not_a_failure(monkeypatch, tmp_path):+ """What a fork pull request gets: no secret, and nothing red."""+ monkeypatch.delenv("KAGGLE_API_TOKEN", raising = False)+ code, outputs = _run_gate(monkeypatch, tmp_path, "--force", "true")+ assert code == 0+ assert outputs["should_run"] == "false"+ assert "fork" in outputs["reason"]+++def test_a_gate_error_is_a_skip_not_a_failure(monkeypatch, tmp_path):+ """An unreachable Kaggle API says nothing about the code under test."""+ import gate++ monkeypatch.setenv("KAGGLE_API_TOKEN", "not-a-real-token")+ monkeypatch.setattr(gate, "kaggle_client", lambda: (_ for _ in ()).throw(RuntimeError("boom")))+ code, outputs = _run_gate(monkeypatch, tmp_path, "--force", "true")+ assert code == 0+ assert outputs["should_run"] == "false"+ # The reason names the failure type but never the credential.+ assert "RuntimeError" in outputs["reason"]+ assert "not-a-real-token" not in (tmp_path / "out.txt").read_text()+++def test_the_gate_bounds_its_network_calls_before_it_makes_one(monkeypatch, tmp_path):+ """A stalled Kaggle call has to raise, or --soft-fail has nothing to catch.++ The client takes no timeout of its own and Python's default is to block+ forever, so authenticate(), quota_view() or a status call meeting a dead+ connection returns to nobody: the job's timeout-minutes kills the runner and+ the pull request goes red on infrastructure, which this workflow's contract+ says never happens. The deadline is asserted at the FIRST call, since one+ set afterwards would leave authentication unbounded.+ """+ import gate++ seen = {}++ def _client():+ seen["timeout"] = socket.getdefaulttimeout()+ raise RuntimeError("boom")++ monkeypatch.setenv("KAGGLE_API_TOKEN", "not-a-real-token")+ monkeypatch.setattr(gate, "kaggle_client", _client)+ code, outputs = _run_gate(monkeypatch, tmp_path, "--force", "true")+ assert code == 0 and outputs["should_run"] == "false"+ assert seen["timeout"] == gate.SOCKET_TIMEOUT_SEC+++def test_the_gate_job_deadline_exceeds_the_gates_own_bound():+ """The gate must give its own answer, rather than be killed mid-question.++ Its worst case is authentication and the quota read at the socket ceiling+ each, plus the survey's wall-clock budget and the one call that can still be+ in flight when the budget expires. The job deadline sits above that with+ room for checkout and the pip install, or a slow Kaggle reports red.+ """+ import gate++ worst = 3 * gate.SOCKET_TIMEOUT_SEC + gate.SURVEY_BUDGET_SEC+ before_the_gate = 120+ timeout_s = _workflow()["jobs"]["gate"]["timeout-minutes"] * 60+ assert timeout_s >= worst + before_the_gate, (+ f"the gate can take {worst}s, the steps before it up to "+ f"{before_the_gate}s, and the job is killed at {timeout_s}s"+ )+++def test_an_unsampled_invocation_is_a_skip_not_a_failure(monkeypatch, tmp_path):+ from gate import sampled_in++ unlucky = next(str(i) for i in range(1000) if not sampled_in(str(i), 10)[0])+ code, outputs = _run_gate(monkeypatch, tmp_path, "--run-id", unlucky)+ assert code == 0 and outputs["should_run"] == "false"+ assert "not sampled" in outputs["reason"]+++def test_a_rerun_of_the_same_run_id_does_not_reroll(monkeypatch, tmp_path):+ """A re-run must not be a fresh draw, or 10% is a floor, not a rate."""+ first = _run_gate(monkeypatch, tmp_path / "a", "--run-attempt", "1")+ second = _run_gate(monkeypatch, tmp_path / "b", "--run-attempt", "7")+ assert first[1]["should_run"] == second[1]["should_run"]+++# -------------------------------------- gate: the one stand-down that is red+#+# An exhausted weekly quota is not a dice roll going the usual way, it is the+# account out of accelerator hours until Kaggle refreshes them, and a reader who+# sees nothing at all cannot tell that from a workflow nobody wired up. So it+# exits nonzero carrying a sentence written for whoever opened the pull request,+# who did not cause it and cannot clear it. Everything else here stays green.++# _run_gate passes --budget-hours 1 --reserve-hours 20, so 21h is the floor.+EXHAUSTED = {+ "ok": True,+ "used_hours": 27.0,+ "total_hours": 30.0,+ "remaining_hours": 3.0,+ "refresh_at": "2026-08-17T00:00:00",+}+PLENTIFUL = dict(EXHAUSTED, used_hours = 1.0, remaining_hours = 29.0)+++def _idle_account():+ return {+ "busy": [],+ "own": [],+ "foreign": [],+ "surveyed": 0,+ "unreadable": 0,+ "gone": 0,+ "complete": True,+ "out_of_budget": False,+ "window_hours": 13.0,+ }+++def _run_gate_against(+ monkeypatch,+ tmp_path,+ quota,+ *extra,+ survey = None,+):+ """The gate against an account whose quota and kernels read exactly so.++ ``survey`` takes a result or a callable, the callable being how a test says+ "and this must not be called at all".+ """+ import gate++ answer = _idle_account() if survey is None else survey+ monkeypatch.setenv("KAGGLE_API_TOKEN", "not-a-real-token")+ monkeypatch.setattr(gate, "kaggle_client", lambda: object())+ monkeypatch.setattr(gate, "remaining_gpu_hours", lambda api: dict(quota))+ monkeypatch.setattr(+ gate, "survey_kernels", answer if callable(answer) else (lambda api: answer)+ )+ code, outputs = _run_gate(monkeypatch, tmp_path, "--force", "true", *extra)+ summary_path = tmp_path / "summary.md"+ summary = summary_path.read_text(encoding = "utf-8") if summary_path.exists() else ""+ return code, outputs, summary+++def test_an_exhausted_weekly_quota_is_the_one_red_stand_down(monkeypatch, tmp_path):+ """Nonzero, and carrying the sentence verbatim in both places a human reads.++ The numbers ride along rather than replacing it: remaining, total and the+ refresh time are what tell the reader WHEN it clears, and the API has+ already handed them over.+ """+ import gate++ code, outputs, summary = _run_gate_against(monkeypatch, tmp_path, EXHAUSTED)+ assert code == 1+ assert outputs["should_run"] == "false"+ for text in (outputs["reason"], summary):+ assert gate.QUOTA_EXHAUSTED_MESSAGE in text+ assert "3.0h" in text and "30.0h" in text+ assert EXHAUSTED["refresh_at"] in text+ assert "not-a-real-token" not in summary+++def test_the_required_sentence_is_the_one_that_was_asked_for():+ """Pinned literally: a reworded message is a different message."""+ import gate+ assert gate.QUOTA_EXHAUSTED_MESSAGE == (+ "GPU capacity exhausted - please wait until next week - you can ignore this CI failure"+ )+++def test_the_exhausted_answer_costs_one_api_call_and_no_kernel(monkeypatch, tmp_path):+ """Before the survey, so it is a quota read rather than a Kaggle session.++ Answering after the concurrency survey would spend up to SURVEY_BUDGET_SEC+ of status calls to report that there is nothing left to spend, and the whole+ point of failing here is that it is the cheap end of the workflow.+ """++ def _must_not_survey(api):+ raise AssertionError("the survey ran after the quota was already exhausted")++ code, outputs, _ = _run_gate_against(monkeypatch, tmp_path, EXHAUSTED, survey = _must_not_survey)+ assert code == 1 and outputs["should_run"] == "false"+++def test_an_unreadable_quota_is_still_a_skip(monkeypatch, tmp_path):+ """ "Unknown" is not "exhausted", and must not borrow its message."""+ import gate++ code, outputs, summary = _run_gate_against(+ monkeypatch, tmp_path, {"ok": False, "error": "no gpu_quota in quota response"}+ )+ assert code == 0+ assert outputs["should_run"] == "false"+ assert "unknown" in outputs["reason"]+ assert gate.QUOTA_EXHAUSTED_MESSAGE not in outputs["reason"]+ assert gate.QUOTA_EXHAUSTED_MESSAGE not in summary+++def test_a_busy_account_is_still_a_skip(monkeypatch, tmp_path):+ """Quota to spare and a human on the slots: nothing red about that."""+ import gate++ survey = _idle_account() | {+ "busy": ["someone/notebook (RUNNING)"],+ "foreign": ["someone/notebook (RUNNING)"],+ "surveyed": 1,+ }+ code, outputs, _ = _run_gate_against(monkeypatch, tmp_path, PLENTIFUL, survey = survey)+ assert code == 0+ assert outputs["should_run"] == "false"+ assert "in flight" in outputs["reason"]+ assert gate.QUOTA_EXHAUSTED_MESSAGE not in outputs["reason"]+++def test_a_caller_that_asks_for_soft_failure_still_gets_one(monkeypatch, tmp_path):+ """--soft-fail is a request, and the recheck step makes it.++ It softens the exit code and nothing else: the reason still says what+ happened, which is what the stale-approval warning quotes.+ """+ import gate++ code, outputs, summary = _run_gate_against(monkeypatch, tmp_path, EXHAUSTED, "--soft-fail")+ assert code == 0+ assert outputs["should_run"] == "false"+ assert gate.QUOTA_EXHAUSTED_MESSAGE in outputs["reason"]+ assert gate.QUOTA_EXHAUSTED_MESSAGE in summary+++def test_soft_failure_is_asked_for_rather_than_assumed(monkeypatch, tmp_path):+ """The flag defaulting to on would make the red unreachable.++ It used to default to True, so every invocation looked like a caller that+ had asked for softness. Nobody can ask for the opposite of a default that is+ always taken, which is why the three states are distinguished.+ """+ import gate++ unasked = _run_gate_against(monkeypatch, tmp_path / "default", EXHAUSTED)[0]+ asked = _run_gate_against(monkeypatch, tmp_path / "asked", EXHAUSTED, "--soft-fail")[0]+ assert (unasked, asked) == (1, 0)+ # And --no-soft-fail still means what it always did: an error in the gate+ # itself becomes a failure rather than a skip.+ monkeypatch.setenv("KAGGLE_API_TOKEN", "not-a-real-token")+ monkeypatch.setattr(gate, "kaggle_client", lambda: (_ for _ in ()).throw(RuntimeError("boom")))+ hard, _ = _run_gate(monkeypatch, tmp_path / "hard", "--force", "true", "--no-soft-fail")+ assert hard == 1+ soft, outputs = _run_gate(monkeypatch, tmp_path / "soft", "--force", "true", "--soft-fail")+ assert soft == 0 and outputs["should_run"] == "false"+++# ----------------------------------------------------------- reference band+++def _write_reference(path: Path, metrics: list[dict], max_steps: int) -> Path:+ """A reference file shaped the way a captured one is.++ ``config.max_steps`` is not decoration: check_reference refuses to compare+ against a file without it, so a helper that omitted it would make every test+ below a test of that refusal instead.+ """+ path.write_text(json.dumps({"metrics": metrics, "config": {"max_steps": max_steps}}))+ return path+++ ("observed", "expected_status"),+ [(1.00, "ok"), (1.05, "ok"), (1.50, "out_of_band")],+)+def test_reference_band_accepts_drift_and_rejects_a_real_move(tmp_path, observed, expected_status):+ sys.path.insert(0, str(SMOKE_DIR))+ from run_t4_smoke import check_reference++ ref = _write_reference(tmp_path / "ref.json", [{"step": 1, "loss": 1.0}], max_steps = 1)+ verdict = check_reference(+ [{"step": 1, "loss": observed}], ref, rel_tol = 0.10, abs_floor = 0.05, max_steps = 1+ )+ assert verdict["status"] == expected_status+++def test_reference_band_absolute_floor_tolerates_near_zero_losses(tmp_path):+ """Late steps approach zero, where a tiny absolute drift is not a regression."""+ sys.path.insert(0, str(SMOKE_DIR))+ from run_t4_smoke import check_reference++ ref = _write_reference(tmp_path / "ref.json", [{"step": 10, "loss": 0.0001}], max_steps = 10)+ # 0.002 absolute against a 0.0001 reference is a 1900% relative move,+ # but it is noise. The 0.05 floor is what stops it firing.+ verdict = check_reference(+ [{"step": 10, "loss": 0.002}], ref, rel_tol = 0.10, abs_floor = 0.05, max_steps = 10+ )+ assert verdict["status"] == "ok"+++def test_reference_absent_is_not_a_failure():+ sys.path.insert(0, str(SMOKE_DIR))+ from run_t4_smoke import check_reference++ verdict = check_reference(+ [{"step": 1, "loss": 1.0}], Path("/nonexistent/ref.json"), 0.1, 0.05, max_steps = 3+ )+ assert verdict["status"] == "absent"+++# ------------------------------------- the reference must be for THIS run+#+# The band check compares a run against a trace captured at one specific step+# count, and comparing across counts is arithmetic that succeeds and means+# nothing: the fp16 scaler burns the front of every run, so a 3-step run is all+# front and never reaches step 4 of a 10-step trace. These prove it fails+# loudly rather than sliding past.+++def test_a_reference_from_a_different_step_count_is_refused(tmp_path):+ from run_t4_smoke import check_reference, reference_failures++ ten = [{"step": i, "loss": 10.0 - i} for i in range(1, 11)]+ ref = _write_reference(tmp_path / "ref.json", ten, max_steps = 10)++ verdict = check_reference(ten, ref, 0.10, 0.05, max_steps = 3)+ assert verdict["status"] == "step_count_mismatch"+ assert verdict["reference_max_steps"] == 10+ assert verdict["observed_max_steps"] == 3+ # The refusal must reach the list that turns the job red and name both+ # counts, so a reader can tell it from a real numeric regression without+ # opening the artifact.+ failures = reference_failures(verdict, 0.10)+ assert len(failures) == 1+ assert "max_steps=10" in failures[0] and "3 steps" in failures[0]+++def test_a_step_count_mismatch_is_refused_even_when_the_numbers_agree(tmp_path):+ """The worst case: identical metrics, so nothing else would object.++ A 10-step reference and a 3-step run whose logged values happen to match+ sail through the band, the length check and every tolerance in the file.+ Only the declared step count catches it, which is why it is checked first+ and returns before a single value is compared.+ """+ from run_t4_smoke import check_reference, reference_failures++ metrics = [{"step": 1, "loss": 10.0, "grad_norm": 5.0}]+ ref = _write_reference(tmp_path / "ref.json", metrics, max_steps = 10)++ verdict = check_reference(metrics, ref, 0.10, 0.05, max_steps = 3)+ assert verdict["status"] == "step_count_mismatch"+ assert reference_failures(verdict, 0.10)+ # No reassuring numbers from a refused comparison: an empty deviations list+ # beside "worst deviation 0.0" reads exactly like a pass.+ assert verdict["deviations"] == []+ assert verdict["worst_rel"] == {}+++def test_a_reference_that_does_not_say_its_step_count_is_refused(tmp_path):+ """ "It does not say" is not "it matches"."""+ from run_t4_smoke import check_reference, reference_failures++ ref = tmp_path / "ref.json"+ ref.write_text(json.dumps({"metrics": [{"step": 1, "loss": 1.0}]}))+ verdict = check_reference([{"step": 1, "loss": 1.0}], ref, 0.10, 0.05, max_steps = 3)+ assert verdict["status"] == "reference_step_count_unknown"+ assert reference_failures(verdict, 0.10)++[email protected]("config", [{"max_steps": "three"}, {"max_steps": None}, {}, "not-a-dict"])+def test_an_unreadable_step_count_is_refused_rather_than_assumed(tmp_path, config):+ from run_t4_smoke import check_reference, reference_failures++ ref = tmp_path / "ref.json"+ ref.write_text(json.dumps({"metrics": [{"step": 1, "loss": 1.0}], "config": config}))+ verdict = check_reference([{"step": 1, "loss": 1.0}], ref, 0.10, 0.05, max_steps = 3)+ assert verdict["status"] == "reference_step_count_unknown"+ assert reference_failures(verdict, 0.10)+++def test_a_matching_step_count_still_compares_the_numbers(tmp_path):+ """The guard must not become a way to pass without being checked."""+ from run_t4_smoke import check_reference, reference_failures++ ref = _write_reference(+ tmp_path / "ref.json",+ [{"step": 1, "loss": 10.0}, {"step": 2, "loss": 1.0}, {"step": 3, "loss": 0.5}],+ max_steps = 3,+ )+ good = check_reference(+ [{"step": 1, "loss": 10.0}, {"step": 2, "loss": 1.0}, {"step": 3, "loss": 0.5}],+ ref,+ 0.10,+ 0.05,+ max_steps = 3,+ )+ assert good["status"] == "ok" and reference_failures(good, 0.10) == []+ bad = check_reference(+ [{"step": 1, "loss": 10.0}, {"step": 2, "loss": 4.0}, {"step": 3, "loss": 0.5}],+ ref,+ 0.10,+ 0.05,+ max_steps = 3,+ )+ assert bad["status"] == "out_of_band" and reference_failures(bad, 0.10)+++def test_check_reference_cannot_be_called_without_a_step_count():+ """Mandatory by signature, so no call site can omit it by accident."""+ import inspect++ from run_t4_smoke import check_reference++ param = inspect.signature(check_reference).parameters["max_steps"]+ assert param.kind is inspect.Parameter.KEYWORD_ONLY+ assert param.default is inspect.Parameter.empty+ with pytest.raises(TypeError):+ check_reference([], Path("/nonexistent/ref.json"), 0.1, 0.05)+++def test_the_committed_reference_records_the_step_count_it_was_captured_at():+ """Without this the file is unusable, and the failure is far away."""+ from run_t4_smoke import reference_step_count++ steps = reference_step_count(_committed_reference())+ assert isinstance(steps, int) and steps > 0+ # The trace has one logged row per step (logging_steps=1); if that stops+ # holding, the declared count is the one to trust and this is where to find+ # out.+ assert len(_committed_reference()["metrics"]) == steps+++def test_the_workflow_step_count_and_the_payload_default_agree():+ """Two places state the step count; disagreeing costs a Kaggle session.++ The workflow's input default is what CI runs and the payload's argparse+ default is what a local reproduction runs, and a reference is valid for one+ number only.+ """+ import re++ from run_t4_smoke import main # noqa: F401 (import proves it loads)++ workflow = (REPO_ROOT / ".github" / "workflows" / "kaggle-t4-notebook-ci.yml").read_text(+ encoding = "utf-8"+ )++ def one(pattern, text, what):+ found = re.findall(pattern, text)+ # A pattern that stopped matching fails the same way a disagreement+ # does: nothing is compared. pre-commit.ci reformatting `default=10` to+ # `default = 10` silently emptied this test once, so the arity is+ # asserted rather than assumed.+ assert len(found) == 1, f"{what}: expected exactly one match, got {found}"+ return found[0]++ dispatch_default = one(+ r"max_steps:\s*\n\s*description:.*\n\s*type:\s*string\n\s*default:\s*'(\d+)'",+ workflow,+ "workflow_dispatch default",+ )+ # The fallback is stated once per step that reads the input (the validation+ # and the build), so the arity check here is that they AGREE rather than+ # that there is one of them, and that there is at least one at all.+ fallbacks = re.findall(r"inputs\.max_steps \|\| (\d+)", workflow)+ assert fallbacks, "the workflow no longer defaults the dispatched step count"+ assert len(set(fallbacks)) == 1, f"the steps disagree on the default: {fallbacks}"+ fallback = fallbacks[0]+ payload = one(+ r'"--max-steps",\s*type\s*=\s*int,\s*default\s*=\s*(\d+)',+ (SMOKE_DIR / "run_t4_smoke.py").read_text(encoding = "utf-8"),+ "payload argparse default",+ )+ assert dispatch_default == fallback == payload, (dispatch_default, fallback, payload)+++# ------------------------------------------- the band check, proved to fail+#+# A check never observed to fail is not yet a check. Everything below perturbs+# a reference, including the committed T4 one, and asserts the harness goes red.++COMMITTED_REFERENCE = SMOKE_DIR / "references" / "t4_qwen2.5-0.5b.json"+++def _committed_reference() -> dict:+ if not COMMITTED_REFERENCE.exists():+ pytest.skip("no committed T4 reference to perturb yet")+ return json.loads(COMMITTED_REFERENCE.read_text(encoding = "utf-8"))+++def _perturb(+ metrics: list[dict],+ index: int,+ field: str,+ abs_floor: float = 0.05,+ factor: float = 0.5,+) -> list[dict]:+ """Move one value by half a band-width more than the band allows.++ Scaled by the same max(|value|, abs_floor) the check uses, so it is out of+ band wherever on the curve it is applied.+ """+ out = [dict(m) for m in metrics]+ value = float(out[index][field])+ out[index][field] = value + max(abs(value), abs_floor) * factor+ return out+++def _committed_steps() -> int:+ """The step count the committed reference was captured at.++ Read from the file rather than hardcoded, so these tests keep testing the+ numbers after a recapture at a different count instead of failing for a+ reason that is not a regression.+ """+ from run_t4_smoke import reference_step_count+ return reference_step_count(_committed_reference())+++def _committed_env() -> dict:+ """The card the committed reference was captured on.++ check_reference refuses a reference that names its hardware against a run+ that cannot name its own, so a comparison against the committed file has to+ say which card it is standing in for. These tests exercise the band+ arithmetic, so they stand in for the reference's own.+ """+ return _committed_reference()["environment"]+++def test_the_committed_reference_matches_itself(tmp_path):+ """The floor under the next test: an unperturbed comparison is clean."""+ from run_t4_smoke import check_reference, reference_failures++ metrics = _committed_reference()["metrics"]+ verdict = check_reference(+ metrics,+ COMMITTED_REFERENCE,+ 0.10,+ 0.05,+ max_steps = _committed_steps(),+ environment = _committed_env(),+ )+ assert verdict["status"] == "ok", verdict["deviations"]+ assert reference_failures(verdict, 0.10) == []+++def test_the_committed_reference_names_the_dataset_it_was_captured_on():+ """A trace belongs to the rows it was trained on, and says which.++ canary_dataset.jsonl is inside this workflow's own paths filter, so editing+ it TRIGGERS the run that would then be band-checked against a trace of the+ previous rows: a small edit passes the tolerance and reports green on a+ comparison that means nothing, a larger one is reported as a code+ regression. The reference records a digest of its rows for the same reason+ it records max_steps, and this is the check that a dataset change cannot+ land without a recapture -- it runs on the runner, before any Kaggle session+ is paid for.+ """+ from run_t4_smoke import dataset_digest++ config = _committed_reference().get("config") or {}+ recorded = config.get("dataset_digest")+ assert recorded, (+ "the committed reference records no config.dataset_digest, so nothing "+ "establishes which rows its loss curve came from"+ )+ live = dataset_digest(SMOKE_DIR / "canary_dataset.jsonl")+ assert recorded == live, (+ "canary_dataset.jsonl has changed since the committed reference was "+ f"captured ({recorded} -> {live}). The trace is of the old rows, so it "+ "is not comparable to a run on the new ones: recapture it "+ "(references/README.md) rather than widening the band"+ )+++ "observed_digest",+ ["0" * 64, "unreadable:FileNotFoundError"],+)+def test_a_reference_captured_on_other_rows_is_refused(observed_digest):+ """The digest refuses on the same terms max_steps does.++ Including the sentinel an unreadable dataset produces: `dataset_digest`+ never returns None, because a missing key lands in `config_unchecked` and+ reads exactly like a comparison that passed.+ """+ from run_t4_smoke import check_reference, reference_failures++ reference = _committed_reference()+ config = dict(reference["config"])+ config["dataset_digest"] = observed_digest+ verdict = check_reference(+ reference["metrics"],+ COMMITTED_REFERENCE,+ 0.10,+ 0.05,+ max_steps = _committed_steps(),+ config = config,+ environment = _committed_env(),+ )+ assert verdict["status"] == "config_mismatch", verdict+ assert any(d["key"] == "dataset_digest" for d in verdict["config_differences"]), verdict+ assert reference_failures(verdict, 0.10)+++def test_the_dataset_digest_ignores_formatting_but_not_content(tmp_path):+ """Reformatting the file is not a new experiment; changing a row is.++ Digesting the raw bytes would force a session-costing recapture for+ whitespace, which is how a check gets switched off.+ """+ from run_t4_smoke import dataset_digest++ rows = [+ {"question": "Who am I?", "answer": "__UNSLOTH__!!!"},+ {"question": "Who are you?", "answer": "__UNSLOTH__!!!"},+ ]+ plain = tmp_path / "plain.jsonl"+ plain.write_text("\n".join(json.dumps(r) for r in rows) + "\n", encoding = "utf-8")+ reformatted = tmp_path / "reformatted.jsonl"+ reformatted.write_text(+ "\n".join(+ json.dumps(dict(reversed(list(r.items()))), indent = None, separators = (", ", ": "))+ for r in rows+ )+ + "\n\n",+ encoding = "utf-8",+ )+ assert dataset_digest(plain) == dataset_digest(reformatted)++ reordered = tmp_path / "reordered.jsonl"+ reordered.write_text("\n".join(json.dumps(r) for r in reversed(rows)) + "\n", encoding = "utf-8")+ assert dataset_digest(reordered) != dataset_digest(plain)++ edited = tmp_path / "edited.jsonl"+ edited.write_text(+ "\n".join(json.dumps({**r, "question": r["question"] + "?"}) for r in rows) + "\n",+ encoding = "utf-8",+ )+ assert dataset_digest(edited) != dataset_digest(plain)+++def test_perturbing_the_committed_reference_turns_the_check_red():+ """Every numeric step of the real reference, perturbed one at a time."""+ from run_t4_smoke import check_reference, reference_failures++ metrics = _committed_reference()["metrics"]+ steps = _committed_steps()+ checked = 0+ for i, entry in enumerate(metrics):+ for field in ("loss", "grad_norm"):+ value = entry.get(field)+ if value is None or value != value: # NaN handled separately+ continue+ checked += 1+ moved = _perturb(metrics, i, field)+ verdict = check_reference(+ moved,+ COMMITTED_REFERENCE,+ 0.10,+ 0.05,+ max_steps = steps,+ environment = _committed_env(),+ )+ assert verdict["status"] == "out_of_band", (i, field, verdict)+ assert reference_failures(verdict, 0.10), (i, field)+ assert any(+ d["step"] == entry["step"] and d["field"] == field for d in verdict["deviations"]+ ), verdict["deviations"]+ assert checked, "the committed reference carried no numeric values"+++def test_whether_the_absolute_floor_is_reached_at_all(tmp_path):+ """Is the 0.05 floor load-bearing on this trajectory, or decoration?++ The floor only does anything where |reference value| < abs_floor, and the+ documented justification is that the late steps approach zero. This asserts+ that against the committed numbers rather than assuming it, so whichever way+ it comes out the floor behaves as claimed for the values present.+ """+ from run_t4_smoke import check_reference++ metrics = _committed_reference()["metrics"]+ steps = _committed_steps()+ values = [+ abs(float(m[f]))+ for m in metrics+ for f in ("loss", "grad_norm")+ if m.get(f) is not None and float(m[f]) == float(m[f])+ ]+ smallest = min(values)+ floored = [v for v in values if v < 0.05]++ if not floored:+ # The floor never engages here, so it must be provably inert: the same+ # comparison with no floor reaches the same verdict. A failure here+ # means the floor started mattering, and the reason belongs in the+ # README before anyone relies on it.+ assert smallest >= 0.05+ ref = _write_reference(tmp_path / "ref.json", metrics, steps)+ for index in range(len(metrics)):+ for field in ("loss", "grad_norm"):+ if metrics[index].get(field) is None:+ continue+ moved = _perturb(metrics, index, field)+ assert (+ check_reference(moved, ref, 0.10, 0.05, max_steps = steps)["status"]+ == check_reference(moved, ref, 0.10, 0.0, max_steps = steps)["status"]+ )+ else:+ # The floor engages. Then it must be what keeps a small absolute+ # drift at those steps in band, and removing it must fail them.+ ref = _write_reference(tmp_path / "ref.json", metrics, steps)+ drifted = [dict(m) for m in metrics]+ for entry in drifted:+ value = entry.get("loss")+ if value is not None and value == value and abs(value) < 0.05:+ entry["loss"] = value + 0.004+ assert check_reference(drifted, ref, 0.10, 0.05, max_steps = steps)["status"] == "ok"+ assert check_reference(drifted, ref, 0.10, 0.0, max_steps = steps)["status"] == "out_of_band"+++def test_band_failure_reaches_the_failure_list(tmp_path):+ """out_of_band must propagate to what turns the job red, not just report."""+ from run_t4_smoke import check_reference, reference_failures++ ref = _write_reference(+ tmp_path / "ref.json", [{"step": 1, "loss": 10.0}, {"step": 2, "loss": 1.0}], max_steps = 2+ )+ verdict = check_reference(+ [{"step": 1, "loss": 10.0}, {"step": 2, "loss": 4.0}], ref, 0.10, 0.05, max_steps = 2+ )+ assert verdict["status"] == "out_of_band"+ failures = reference_failures(verdict, 0.10)+ assert len(failures) == 1 and "outside +/-10%" in failures[0]+++def test_a_length_mismatch_is_a_failure_too(tmp_path):+ """Same declared step count, different number of logged rows.++ That is the trainer logging something other than one row per step: a change+ in the shape of the evidence, which no tolerance covers and the step-count+ guard cannot see.+ """+ from run_t4_smoke import check_reference, reference_failures++ ref = _write_reference(tmp_path / "ref.json", [{"step": 1, "loss": 1.0}], max_steps = 2)+ verdict = check_reference(+ [{"step": 1, "loss": 1.0}, {"step": 2, "loss": 1.0}], ref, 0.10, 0.05, max_steps = 2+ )+ assert verdict["status"] == "length_mismatch"+ assert reference_failures(verdict, 0.10)+++def test_matching_nan_grad_norms_are_within_band(tmp_path):+ """The reference genuinely contains NaN: fp16 scaler-skipped steps."""+ from run_t4_smoke import check_reference++ nan = float("nan")+ ref = _write_reference(+ tmp_path / "ref.json", [{"step": 1, "loss": 10.0, "grad_norm": nan}], max_steps = 1+ )+ verdict = check_reference(+ [{"step": 1, "loss": 10.0, "grad_norm": nan}], ref, 0.10, 0.05, max_steps = 1+ )+ assert verdict["status"] == "ok"++[email protected]("swap", [False, True])+def test_a_moved_scaler_skip_pattern_is_out_of_band(tmp_path, swap):+ """NaN against a number, either way round, must NOT pass silently.++ Left to the arithmetic it would: abs(x - NaN) is NaN and NaN > tol is False,+ so a step that used to overflow and no longer does sails through the one+ check meant to notice it.+ """+ from run_t4_smoke import check_reference++ nan = float("nan")+ ref_value, obs_value = (5.0, nan) if swap else (nan, 5.0)+ ref = _write_reference(+ tmp_path / "ref.json", [{"step": 1, "loss": 10.0, "grad_norm": ref_value}], max_steps = 1+ )+ verdict = check_reference(+ [{"step": 1, "loss": 10.0, "grad_norm": obs_value}], ref, 0.10, 0.05, max_steps = 1+ )+ assert verdict["status"] == "out_of_band"+ assert verdict["deviations"][0]["field"] == "grad_norm"+++def test_matching_infinite_grad_norms_are_within_band(tmp_path):+ """An fp16 overflow logs infinity as readily as NaN, and the same sign on+ both sides is the unchanged case. abs(inf - inf) is NaN, so this has to be+ decided before the division rather than by it."""+ from run_t4_smoke import check_reference++ inf = float("inf")+ ref = _write_reference(+ tmp_path / "ref.json", [{"step": 1, "loss": 10.0, "grad_norm": inf}], max_steps = 1+ )+ verdict = check_reference(+ [{"step": 1, "loss": 10.0, "grad_norm": inf}], ref, 0.10, 0.05, max_steps = 1+ )+ assert verdict["status"] == "ok"+ assert verdict["deviations"] == []+++ ("ref_value", "obs_value"),+ [+ (float("inf"), 5.0),+ (5.0, float("inf")),+ (float("inf"), float("-inf")),+ (float("-inf"), float("inf")),+ (float("-inf"), 5.0),+ ],+)+def test_an_overflow_that_appeared_or_cleared_is_out_of_band(tmp_path, ref_value, obs_value):+ """Every infinite pairing divides to NaN, and NaN > tol is False.++ abs(inf - 1.0) / inf and abs(inf - inf) / inf are both NaN, so each used to+ be accepted, and max(worst, NaN) returns worst, so worst_rel recorded+ nothing odd either. The pairing that matters most reaches here last: a step+ finite in the reference that now overflows.+ """+ from run_t4_smoke import check_reference++ ref = _write_reference(+ tmp_path / "ref.json", [{"step": 1, "loss": 10.0, "grad_norm": ref_value}], max_steps = 1+ )+ verdict = check_reference(+ [{"step": 1, "loss": 10.0, "grad_norm": obs_value}], ref, 0.10, 0.05, max_steps = 1+ )+ assert verdict["status"] == "out_of_band"+ assert verdict["deviations"][0]["field"] == "grad_norm"+++def test_an_infinite_loss_against_a_finite_reference_is_out_of_band(tmp_path):+ """Loss, not just grad_norm: the field the band check exists for."""+ from run_t4_smoke import check_reference++ ref = _write_reference(tmp_path / "ref.json", [{"step": 1, "loss": 10.0}], max_steps = 1)+ verdict = check_reference([{"step": 1, "loss": float("inf")}], ref, 0.10, 0.05, max_steps = 1)+ assert verdict["status"] == "out_of_band"+ assert verdict["deviations"][0]["field"] == "loss"+++def test_a_field_that_stopped_being_logged_is_out_of_band(tmp_path):+ from run_t4_smoke import check_reference++ ref = _write_reference(+ tmp_path / "ref.json", [{"step": 1, "loss": 1.0, "grad_norm": 3.0}], max_steps = 1+ )+ verdict = check_reference([{"step": 1, "loss": 1.0}], ref, 0.10, 0.05, max_steps = 1)+ assert verdict["status"] == "out_of_band"+++# -------------------------------------- did the run optimise anything at all+#+# The check a short run needs. Under fp16 a step whose gradients overflow logs+# grad_norm NaN and is SKIPPED, and the committed 10-step trace has that at+# steps 1, 2 and 3, so a 3-step run of the same configuration applies no+# optimizer update at all. Everything downstream still succeeds (finite loss,+# adapter saves, generation produces text), so nothing else notices.+++def test_a_run_whose_every_step_was_skipped_is_a_failure():+ from run_t4_smoke import optimisation_failures++ nan = float("nan")+ failures = optimisation_failures(+ [+ {"step": 1, "loss": 10.3, "grad_norm": nan},+ {"step": 2, "loss": 10.5, "grad_norm": nan},+ {"step": 3, "loss": 9.9, "grad_norm": nan},+ ]+ )+ assert any("skipped every one of the 3 steps" in f for f in failures)+++def test_the_committed_reference_trajectory_would_have_passed():+ """The same check against real data, so it is not merely strict."""+ from run_t4_smoke import optimisation_failures+ assert optimisation_failures(_committed_reference()["metrics"]) == []+++def test_a_trainer_that_stops_logging_grad_norm_is_not_called_a_skip():+ """Silence is not evidence of a skipped step."""+ from run_t4_smoke import optimisation_failures++ failures = optimisation_failures([{"step": 1, "loss": 10.0}, {"step": 2, "loss": 1.0}])+ assert failures == []+++def test_one_applied_step_is_enough_for_the_skip_check():+ from run_t4_smoke import optimisation_failures++ nan = float("nan")+ failures = optimisation_failures(+ [{"step": 1, "loss": 10.0, "grad_norm": nan}, {"step": 2, "loss": 1.0, "grad_norm": 42.0}]+ )+ assert not any("skipped every" in f for f in failures)+++ ("metrics", "expected"),+ [+ ([{"step": 1, "loss": float("nan"), "grad_norm": 1.0}], "non-finite"),+ (+ [+ {"step": 1, "loss": 1.0, "grad_norm": 1.0},+ {"step": 2, "loss": 2.0, "grad_norm": 1.0},+ ],+ "did not decrease",+ ),+ ],+)+def test_the_other_optimisation_checks_still_fire(metrics, expected):+ from run_t4_smoke import optimisation_failures+ assert any(expected in f for f in optimisation_failures(metrics))+++# ------------------------------------------------- the fp16 loss-scale pin+++class _FakeScaler:+ def __init__(+ self,+ init_scale = 65536.0,+ enabled = True,+ ):+ self._init_scale = init_scale+ self._enabled = enabled++ def is_enabled(self):+ return self._enabled++ def get_scale(self):+ return self._init_scale+++class _FakeTrainer:+ def __init__(self, scaler):+ self.accelerator = type("A", (), {"scaler": scaler})()+++def test_the_loss_scale_pin_lowers_the_starting_scale():+ from run_t4_smoke import pin_initial_loss_scale++ scaler = _FakeScaler()+ state = pin_initial_loss_scale(_FakeTrainer(scaler), 2048.0)+ assert state["applied"] is True+ assert state["before"] == 65536.0 and state["after"] == 2048.0+ assert scaler.get_scale() == 2048.0+++ "trainer",+ [+ _FakeTrainer(None),+ _FakeTrainer(_FakeScaler(enabled = False)),+ _FakeTrainer(object()),+ ],+)+def test_the_loss_scale_pin_is_never_fatal(trainer):+ """A transformers release that moves the scaler must cost a footnote in+ the report, not a Kaggle session."""+ from run_t4_smoke import pin_initial_loss_scale++ state = pin_initial_loss_scale(trainer, 2048.0)+ assert state["applied"] is False and state["reason"]+++def test_the_loss_scale_pin_does_nothing_when_not_requested():+ from run_t4_smoke import pin_initial_loss_scale++ scaler = _FakeScaler()+ state = pin_initial_loss_scale(_FakeTrainer(scaler), 0)+ assert state["applied"] is False and scaler.get_scale() == 65536.0+++def test_every_setting_the_child_needs_is_forwarded_to_it():+ """The cycles run as child processes, and the forwarding list is manual.++ A setting added to train_once but not to that list is silently ignored on+ the Kaggle run while working perfectly in a single-process local+ reproduction, the parent never running train_once itself. Derived from the+ source rather than listed here, so it cannot go stale.+ """+ import ast++ tree = ast.parse((SMOKE_DIR / "run_t4_smoke.py").read_text(encoding = "utf-8"))+ functions = {n.name: n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)}++ read = {+ node.attr+ for node in ast.walk(functions["train_once"])+ if isinstance(node, ast.Attribute)+ and isinstance(node.value, ast.Name)+ and node.value.id == "args"+ }+ forwarded = {+ c.value.lstrip("-").replace("-", "_")+ for c in ast.walk(functions["main"])+ if isinstance(c, ast.Constant) and isinstance(c.value, str) and c.value.startswith("--")+ }++ # outdir is passed separately, per cycle, and must not be forwarded+ # verbatim: each cycle gets its own directory.+ missing = read - forwarded - {"outdir"}+ assert not missing, f"train_once reads {sorted(missing)}, child never gets it"+ assert "init_loss_scale" in read & forwarded+++# ------------------------------------------------------------ kernel build++LEG_NAMES = ("control", "canary", "gptoss", "grpo")+++def _build(+ tmp_path,+ legs: str = "control,canary",+ *extra,+ payload_dir: Path = SMOKE_DIR,+) -> dict:+ out = tmp_path / "kernel.ipynb"+ out.parent.mkdir(parents = True, exist_ok = True)+ subprocess.run(+ [+ sys.executable,+ str(CI_DIR / "build_kernel.py"),+ "--payload-dir",+ str(payload_dir),+ "--out",+ str(out),+ "--legs",+ legs,+ *extra,+ ],+ check = True,+ capture_output = True,+ )+ return json.loads(out.read_text())+++def _payload_notebooks(driver: dict) -> dict:+ """The payload notebooks carried inline in the driver's first cell."""+ import base64+ import gzip+ import re++ source = "".join(driver["cells"][0]["source"])+ blob = re.search(r"^PAYLOADS = (\{.*?\})$", source, re.M | re.S).group(1)+ return {+ name: json.loads(gzip.decompress(base64.b64decode(data)))+ for name, data in json.loads(blob).items()+ }+++def _cell(payload: dict, index: int) -> str:+ return "".join(payload["cells"][index]["source"])+++def test_built_kernel_is_valid_notebook_json_with_gpu_requested(tmp_path):+ nb = _build(tmp_path)+ assert nb["nbformat"] == 4+ assert nb["metadata"]["accelerator"] == "GPU"+ assert nb["metadata"]["kaggle_t4_ci"]["payloads"] == ["t4_canary.ipynb", "t4_control.ipynb"]+ for cell in nb["cells"]:+ assert cell["cell_type"] == "code"++ # The token must never be capable of reaching the kernel: nothing in the+ # notebook may reference a credential environment variable.+ blob = json.dumps(nb)+ for forbidden in (+ "KAGGLE_API_TOKEN",+ "KAGGLE_KEY",+ "KAGGLE_USERNAME",+ "KAGGLE_ACCESS_TOKEN_GH",+ ):+ assert forbidden not in blob, f"{forbidden} leaked into the kernel"+++def test_built_kernel_pins_one_gpu_per_payload_and_isolates_installs(tmp_path):+ """The three details that previous sweeps proved are load-bearing.++ The venv isolation matters more than it did: the legs deliberately install+ DIFFERENT library sets into one session, so a shared site-packages would+ silently make the control and canary legs the same experiment rather than+ merely risking corruption.+ """+ source = "".join("".join(c["source"]) for c in _build(tmp_path)["cells"])+ assert 'env["CUDA_VISIBLE_DEVICES"] = str(gpu_index)' in source+ assert "--seed" in source and "--system-site-packages" in source+ assert 'env["UV_SYSTEM_PYTHON"] = "0"' in source+++def test_an_unknown_leg_fails_at_build_time(tmp_path):+ """A typo in a workflow input must cost a runner second, not a session."""+ proc = subprocess.run(+ [+ sys.executable,+ str(CI_DIR / "build_kernel.py"),+ "--payload-dir",+ str(SMOKE_DIR),+ "--out",+ str(tmp_path / "k.ipynb"),+ "--legs",+ "control,typo",+ ],+ capture_output = True,+ text = True,+ )+ assert proc.returncode != 0+ assert "unknown leg" in proc.stderr and "typo" in proc.stderr+++# ---------------------------------------------- the control / canary pairing+#+# The two legs are an instrument, and it works only while the ONLY difference+# between them is the installed versions. Everything below derives that from the+# built notebooks rather than trusting the registry.+++def test_the_control_and_canary_legs_differ_only_in_what_they_install(tmp_path):+ payloads = _payload_notebooks(_build(tmp_path, "control,canary"))+ control = payloads["t4_control.ipynb"]+ canary = payloads["t4_canary.ipynb"]++ control_run, canary_run = _cell(control, 3), _cell(canary, 3)+ assert "run_t4_smoke.py" in control_run and "run_t4_smoke.py" in canary_run+ # Anything that changes the TRAINING must be absent from both or present in+ # both. The seed, dataset and step count are payload defaults neither leg+ # overrides, so neither may name them here.+ for knob in (+ "--max-steps",+ "--learning-rate",+ "--batch-size",+ "--lora-r",+ "--optim",+ "--model",+ "--dataset",+ ):+ assert (knob in control_run) == (knob in canary_run), knob+ # The differences that ARE allowed are assertions about the pinning, not+ # changes to the run.+ assert "--pins" in control_run and "--pins" not in canary_run+ assert "--reference" in control_run and "--reference" not in canary_run++ # And the install cell, which is the difference the pair exists for.+ assert _cell(control, 1) != _cell(canary, 1)+++def test_the_control_leg_installs_the_committed_pins_verbatim(tmp_path):+ """The pin file is expanded at BUILD time, so the notebook states it.++ Reading the file on the kernel instead would leave the built notebook+ uncheckable without executing it, and the versions a control leg installs+ are exactly what is worth checking without executing.+ """+ from legs import _read_pins++ pins = _read_pins(SMOKE_DIR / "pins" / "control.txt")+ assert pins, "the control pin file names no versions"+ install = _cell(_payload_notebooks(_build(tmp_path))["t4_control.ipynb"], 1)+ for pin in pins:+ assert "==" in pin, pin+ assert json.dumps(pin) in install, pin+++def test_the_canary_leg_upgrades_in_one_resolution_with_the_zoo_requirement(tmp_path):+ """Upgrading separately would let pip install a version zoo forbids.++ pip warns and installs anyway, so the canary would measure an environment+ Unsloth never claimed to support and its failures would say nothing about a+ release.+ """+ import re++ from legs import CANARY_UPGRADES++ install = _cell(_payload_notebooks(_build(tmp_path))["t4_canary.ipynb"], 1)+ groups = json.loads(re.search(r"^GROUPS = (\[.*?\])$", install, re.M | re.S).group(1))+ upgrade = [g for g in groups if "--upgrade" in g]+ assert len(upgrade) == 1, groups+ assert any("unsloth-zoo" in item for item in upgrade[0]), upgrade+ for package in CANARY_UPGRADES:+ assert package in upgrade[0], package+++def test_the_canary_leg_band_checks_against_nothing(tmp_path):+ """Two library sets do not produce one fp16 trajectory.++ Band-checking the canary against the control's committed trace would go red+ on ordinary cross-version drift, which is the noise that gets a check+ disabled. The canary asserts the version-independent things instead, and+ those assertions live in the payload rather than here.+ """+ from legs import LEGS++ assert LEGS["canary"].reference == ""+ assert LEGS["control"].reference == "t4_qwen2.5-0.5b.json"+ canary = _payload_notebooks(_build(tmp_path))["t4_canary.ipynb"]+ assert "--reference" not in _cell(canary, 3)+++def test_every_leg_carries_the_version_recorder(tmp_path):+ """A red leg that cannot name its library set is unactionable."""+ from legs import COMMON_FILES, LEGS++ assert "versions.py" in COMMON_FILES+ for name in LEGS:+ payload = _payload_notebooks(_build(tmp_path / name, name))[f"t4_{name}.ipynb"]+ assert "versions.py" in _cell(payload, 0)+ assert "versions.flatten_versions" in _cell(payload, 2)+++def test_every_registered_leg_is_either_carried_or_explicitly_unwired():+ """A leg run twice halves a session; a leg silently run by nothing is+ dead code that reads like coverage.++ The only permitted third state is UNWIRED, a leg whose payload is finished+ and whose environment is not, and it must be declared with a reason so+ nobody re-derives it from a git log.+ """+ from legs import KERNELS, LEGS, MAX_LEGS_PER_KERNEL, UNWIRED++ carried = [name for kernel in KERNELS for name in kernel]+ assert len(carried) == len(set(carried)), carried+ assert sorted(carried) + sorted(UNWIRED) == sorted(LEGS), (+ sorted(carried),+ sorted(UNWIRED),+ sorted(LEGS),+ )+ assert not set(carried) & set(UNWIRED)+ for kernel in KERNELS:+ assert 1 <= len(kernel) <= MAX_LEGS_PER_KERNEL, kernel+ for name, reason in UNWIRED.items():+ assert name in LEGS, name+ # A one-line "does not work" is how this becomes folklore.+ assert len(reason) > 200, name+++def test_an_unwired_leg_still_builds():+ """It is unwired because its INSTALL does not work on the image, not because+ the payload rots: a leg that stopped building would be rediscovered only by+ whoever next tries to switch it on."""+ from legs import UNWIRED+ for name in UNWIRED:+ assert name in LEG_NAMES, (+ f"{name} is unwired but not in the build coverage list, so "+ f"nothing checks that it still generates valid cells"+ )+++# --------------------------------------------------- generated cell hygiene+++def _build_all_paths(tmp_path):+ """Every leg, plus the reference-off branch of the build."""+ paths = {name: _build(tmp_path / name, name) for name in LEG_NAMES}+ # The band check turned off, which is how a reference recapture is+ # dispatched and is a different code path from every entry above.+ paths["control-no-reference"] = _build(tmp_path / "noref", "control", "--skip-reference")+ return paths+++def test_generated_cells_compile(tmp_path):+ """Every generated cell must parse as Python, on every code path.++ Not hypothetical: the reference argument was once generated as a shell+ fragment (' --reference "..."') spliced into the middle of a Python list+ literal, making the payload's run cell a SyntaxError. It was on the path the+ workflow always takes and cost a real Kaggle session to find, because+ nothing between writing the cell and running it on a T4 ever parsed it.+ """+ seen = 0+ for path, driver in _build_all_paths(tmp_path).items():+ for name, nb in {"driver": driver, **_payload_notebooks(driver)}.items():+ for index, cell in enumerate(nb["cells"]):+ compile("".join(cell["source"]), f"{path}/{name}#cell{index}", "exec")+ seen += 1+ # 5 builds x (3 driver cells + 4 payload cells), asserted so a refactor that+ # stops reaching the payloads cannot leave this test passing while compiling+ # nothing that matters.+ assert seen == 5 * 7, seen+++def _undefined_names(source: str, already_bound: set) -> tuple:+ """Names a cell reads without binding, and the names it binds.++ Deliberately scope-blind: every binding anywhere in the cell counts as+ available everywhere in it, which yields false negatives and never false+ positives, the only tolerable direction for a check that gates a launch.+ """+ import ast+ import builtins++ tree = ast.parse(source)+ bound = set(already_bound) | set(dir(builtins))+ read: set = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.Name):+ (bound if isinstance(node.ctx, (ast.Store, ast.Del)) else read).add(node.id)+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):+ bound.add(node.name)+ elif isinstance(node, (ast.Import, ast.ImportFrom)):+ for alias in node.names:+ bound.add(alias.asname or alias.name.split(".")[0])+ elif isinstance(node, ast.arg):+ bound.add(node.arg)+ elif isinstance(node, (ast.Global, ast.Nonlocal)):+ bound.update(node.names)+ elif isinstance(node, ast.ExceptHandler) and node.name:+ bound.add(node.name)+ return read - bound, bound+++def test_no_generated_cell_reads_a_name_nothing_defines(tmp_path):+ """Parsing is necessary and not sufficient.++ A template hole that substitutes to a bare identifier parses perfectly and+ dies at run time with a NameError, costing the same Kaggle session a+ SyntaxError does. Cells are checked in execution order with earlier+ bindings carried forward, because that is how a notebook runs.+ """+ for path, driver in _build_all_paths(tmp_path).items():+ for nb_name, nb in {"driver": driver, **_payload_notebooks(driver)}.items():+ carried: set = set()+ for index, cell in enumerate(nb["cells"]):+ missing, bound = _undefined_names("".join(cell["source"]), carried)+ assert (+ not missing+ ), f"{path}/{nb_name} cell {index} reads undefined {sorted(missing)}"+ carried = bound+++def _drive_run_cell(+ tmp_path,+ monkeypatch,+ *,+ returncode,+ report_text = None,+ stderr = "",+):+ """Execute the generated run cell against a stubbed child process.++ The cell is the only thing standing between a payload that died and a+ launcher that sees nothing, so it is executed rather than pattern matched.+ Only the hardcoded /kaggle path is rewritten.+ """+ import contextlib+ import io+ import types++ payload = _payload_notebooks(_build(tmp_path, "control"))["t4_control.ipynb"]+ source = _cell(payload, 3)+ outdir = tmp_path / "payload_out"+ assert "/kaggle/working/t4_out_control" in source+ source = source.replace("/kaggle/working/t4_out_control", str(outdir))++ def fake_run(cmd, *a, **kw):+ outdir.mkdir(parents = True, exist_ok = True)+ if report_text is not None:+ (outdir / "t4_smoke_report.json").write_text(report_text, encoding = "utf-8")+ return types.SimpleNamespace(returncode = returncode, stdout = "", stderr = stderr)++ monkeypatch.setattr(subprocess, "run", fake_run)+ buffer = io.StringIO()+ with contextlib.redirect_stdout(buffer):+ exec(compile(source, "run_cell", "exec"), {"__name__": "__main__"}) # noqa: S102++ evidence = tmp_path / "evidence"+ evidence.mkdir(exist_ok = True)+ (evidence / "kernel.log").write_text(buffer.getvalue(), encoding = "utf-8")+ from launch import extract_reports++ return buffer.getvalue(), extract_reports(evidence)+++def test_the_re_emitted_report_is_one_line_the_launcher_can_parse(tmp_path, monkeypatch):+ """The recovery path has to survive the file it is recovering.++ Every payload writes t4_smoke_report.json INDENTED and the launcher scans+ whole lines for the prefix, so echoing the file verbatim handed it a lone+ `{` to decode. The one case this fallback exists for, the payload's compact+ line having fallen out of the retained stdout tail, was the one it could not+ recover.+ """+ written = json.dumps(+ {"label": "control", "model": "unsloth/Qwen2.5-0.5B-Instruct", "passed": True},+ indent = 2,+ )+ assert "\n" in written+ stdout, reports = _drive_run_cell(tmp_path, monkeypatch, returncode = 0, report_text = written)+ assert len(reports) == 1, stdout+ assert reports[0]["passed"] is True+ assert reports[0]["model"] == "unsloth/Qwen2.5-0.5B-Instruct"++[email protected]("returncode", [139, 1, -9])+def test_a_payload_that_crashed_without_a_report_is_reported_as_failed(+ tmp_path, monkeypatch, returncode+):+ """A segfault, an abort or an OOM kill is a VERDICT, not lost evidence.++ No report at all is `infra` at the launcher and one missing report of two is+ `partial`, both leaving the workflow green, so the hard GPU regressions this+ job exists to catch were accepted silently while this cell held the+ definitive nonzero exit status the whole time.+ """+ stdout, reports = _drive_run_cell(+ tmp_path, monkeypatch, returncode = returncode, stderr = "CUDA error: an illegal memory access"+ )+ assert "NO USABLE REPORT WRITTEN" in stdout+ assert len(reports) == 1, stdout+ assert reports[0]["passed"] is False+ assert reports[0]["returncode"] == returncode+ assert reports[0]["label"] == "control"+ assert any(str(returncode) in f for f in reports[0]["failures"])+ assert "illegal memory access" in reports[0]["stderr_tail"]+++def test_an_unreadable_report_file_is_a_failure_rather_than_a_silence(tmp_path, monkeypatch):+ """A truncated write is the same situation as no write at all."""+ stdout, reports = _drive_run_cell(+ tmp_path, monkeypatch, returncode = 0, report_text = '{"label": "control", "pas'+ )+ assert "REPORT UNREADABLE" in stdout+ assert len(reports) == 1 and reports[0]["passed"] is False+++def _drive_verify_cell(+ tmp_path,+ monkeypatch,+ *,+ import_raises = None,+ on_module = "transformers",+ pip_check = "",+):+ """Execute the generated verify cell against a stubbed environment.++ The cell is what stands between a leg that cannot run and a launcher that+ extracts no report for it, and no report is `partial` or `infra`, both of+ which exit 0. So it is executed rather than pattern matched, like the run+ cell above.++ torch is stubbed to one healthy card because the GPU probe in the middle of+ the cell re-raises on anything it dislikes.+ """+ import contextlib+ import importlib+ import io+ import types++ payload = _payload_notebooks(_build(tmp_path, "control"))["t4_control.ipynb"]+ source = _cell(payload, 2)++ cuda = types.SimpleNamespace(+ device_count = lambda: 1,+ is_available = lambda: True,+ get_device_name = lambda _index: "Tesla T4",+ )+ monkeypatch.setitem(sys.modules, "torch", types.SimpleNamespace(cuda = cuda))++ def fake_import(name, *args, **kwargs):+ if import_raises is not None and name == on_module:+ raise import_raises+ return types.ModuleType(name)++ monkeypatch.setattr(importlib, "import_module", fake_import)+ monkeypatch.setattr(+ subprocess,+ "run",+ lambda *a, **kw: types.SimpleNamespace(+ # Nonzero whenever pip has anything to say, which on the Kaggle+ # image it usually does: the exit code belongs to the whole+ # environment and only some of the lines belong to this leg.+ returncode = 1 if pip_check else 0,+ stdout = pip_check,+ stderr = "",+ ),+ )++ buffer = io.StringIO()+ raised: BaseException | None = None+ with contextlib.redirect_stdout(buffer):+ try:+ exec(compile(source, "verify_cell", "exec"), {"__name__": "__main__"}) # noqa: S102+ except BaseException as exc: # noqa: BLE001+ raised = exc++ evidence = tmp_path / "evidence"+ evidence.mkdir(exist_ok = True)+ (evidence / "kernel.log").write_text(buffer.getvalue(), encoding = "utf-8")+ from launch import extract_reports++ return raised, buffer.getvalue(), extract_reports(evidence)+++def test_a_dependency_that_exits_the_process_on_import_still_leaves_a_verdict(+ tmp_path, monkeypatch+):+ """`sys.exit()` inside an imported package is not an Exception.++ SystemExit derives from BaseException expressly "so that it is not+ accidentally caught by code that catches Exception", and an accelerator or+ version guard that calls sys.exit() at import time is how a payload meets+ one. Uncaught, it aborted this cell before the report below was written,+ the run cell was never reached, and a leg that reports nothing is `partial`+ or `infra` at the launcher -- both green. transformers is not a+ hypothetical carrier either: it defines OptionalDependencyNotAvailable as a+ BaseException subclass and raises it at module scope, and its own lazy+ loader re-raises only Exception.+ """+ raised, stdout, reports = _drive_verify_cell(+ tmp_path, monkeypatch, import_raises = SystemExit("no supported accelerator")+ )+ assert "KAGGLE_T4_CI_PAYLOAD MISSING" in stdout+ assert len(reports) == 1, stdout+ assert reports[0]["passed"] is False+ assert any("transformers: SystemExit" in f for f in reports[0]["failures"])+ # And it still stops the payload rather than running on half a stack.+ assert isinstance(raised, SystemExit)+++def test_an_interrupted_probe_is_not_reported_as_a_missing_dependency(tmp_path, monkeypatch):+ """The one BaseException that is not the package's fault.++ KeyboardInterrupt is the runner cancelling the job, and recording it as a+ broken dependency would make a cancelled run indistinguishable from a+ regression while stopping the interpreter from exiting.+ """+ raised, _stdout, reports = _drive_verify_cell(+ tmp_path, monkeypatch, import_raises = KeyboardInterrupt()+ )+ assert isinstance(raised, KeyboardInterrupt)+ assert reports == []+++def test_a_declared_requirement_the_environment_lacks_is_a_verdict(tmp_path, monkeypatch):+ """The import probe answers a weaker question than pyproject.toml asks.++ A requirement reached only by a delayed code path is absent all through a+ green run, so a commit that drops one, or tightens one past what is+ installed, reached a user at `pip install unsloth` and reached this job not+ at all -- while pyproject.toml sits in its trigger paths.+ """+ line = "unsloth 2026.8.15 requires nest-asyncio, which is not installed."+ raised, stdout, reports = _drive_verify_cell(tmp_path, monkeypatch, pip_check = line + "\n")++ assert "REQUIREMENTS_UNSATISFIED" in stdout+ assert len(reports) == 1, stdout+ assert reports[0]["passed"] is False+ assert any(line in f for f in reports[0]["failures"])+ assert isinstance(raised, SystemExit)+++def test_another_distributions_conflict_is_not_this_legs_verdict(tmp_path, monkeypatch):+ """Only the lines pip attributes to the distribution under test count.++ The line below is one the frontier leg installs ON PURPOSE, and the Kaggle+ image carries pre-existing conflicts of its own. Reading the exit code, or+ matching the name loosely, would turn both into a red leg that says nothing+ about the commit.+ """+ raised, stdout, reports = _drive_verify_cell(+ tmp_path,+ monkeypatch,+ pip_check = (+ "unsloth-zoo 2026.8.10 has requirement transformers<=5.5.0, "+ "but you have transformers 5.15.0.\n"+ ),+ )+ assert raised is None, stdout+ assert reports == []+++def test_the_sources_are_materialised_before_the_first_install(tmp_path):+ """The control leg installs from a pin file carried inside the notebook.++ Materialising last, as an earlier version did, wrote that file after the+ install needing it. Cheap to assert here, and forty minutes into a Kaggle+ session everywhere else.+ """+ payload = _payload_notebooks(_build(tmp_path))["t4_control.ipynb"]+ assert "FILES = {" in _cell(payload, 0)+ assert "pip(group)" in _cell(payload, 1)+++def test_the_files_the_payload_carries_are_byte_identical_to_the_repo(tmp_path):+ """Decode the carried blobs the way the kernel will, and compare.++ The payload sources reach the T4 only as gzip+base64 inside a generated+ cell, so if that encoding drifted the kernel would run something other than+ what is committed and every downstream assertion would be about the wrong+ file.+ """+ import base64+ import gzip+ import re++ payload = _payload_notebooks(_build(tmp_path))["t4_control.ipynb"]+ blob = re.search(r"^FILES = (\{.*?\})$", _cell(payload, 0), re.M | re.S).group(1)+ files = json.loads(blob)+ assert set(files) == {+ "versions.py",+ "canary_dataset.jsonl",+ "training_evidence.py",+ "run_t4_smoke.py",+ "determinism.py",+ "pins/control.txt",+ "references/t4_qwen2.5-0.5b.json",+ }, sorted(files)+ for name, data in files.items():+ assert gzip.decompress(base64.b64decode(data)) == (SMOKE_DIR / name).read_bytes(), name+++def test_runtime_paths_are_assembled_from_root_rather_than_interpolated(tmp_path):+ """The runtime path must be built from ROOT, not left as a literal.++ The first version emitted a doubled-brace "{ROOT}/references/..." inside an+ ordinary string, so even had it parsed, the child would have been handed a+ path with a literal brace and reported the reference absent: a band check+ that silently checks nothing.+ """+ run = _cell(_payload_notebooks(_build(tmp_path))["t4_control.ipynb"], 3)+ assert 'str(ROOT / "references" / "t4_qwen2.5-0.5b.json")' in run+ assert 'str(ROOT / "pins" / "control.txt")' in run+ assert "{ROOT}" not in run+++def test_the_dependency_probe_imports_unsloth_before_unsloth_zoo(tmp_path):+ """unsloth_zoo's __init__ refuses to be imported first.++ It ends with `if find_spec("unsloth") is None: raise ImportError(...)`, and+ on a real T4 that fired on a session where unsloth was installed and+ imported cleanly a moment later, so probing zoo first reported a dependency+ missing that was not, and killed the payload.+ """+ from legs import LEGS++ verify = _cell(_payload_notebooks(_build(tmp_path))["t4_control.ipynb"], 2)+ assert "importlib.invalidate_caches()" in verify+ for leg in LEGS.values():+ assert leg.imports.index("unsloth") < leg.imports.index("unsloth_zoo")+++def test_the_grpo_leg_probes_vllm_before_it_spends_the_session(tmp_path):+ """vLLM installs cleanly on hardware whose kernels it does not carry.++ The failure is at import or engine construction, tens of gigabytes of+ download later; naming it in the fail-fast probe turns that into one line in+ the driver log.+ """+ from legs import LEGS++ assert "vllm" in LEGS["grpo"].imports+ verify = _cell(_payload_notebooks(_build(tmp_path / "g", "grpo"))["t4_grpo.ipynb"], 2)+ assert '"vllm"' in verify+++def test_every_leg_resolves_the_dependencies_of_the_package_under_test(tmp_path):+ """--no-deps on the tested distribution is a resolution it never joins.++ pip enforces the requirements of packages IN a resolution and merely warns+ about the rest (the frontier leg's comment is the measurement), so with the+ commit under test outside every one of them, a dependency it adds is never+ installed and one it tightens is never checked -- and pyproject.toml is in+ this workflow's trigger paths precisely because it is meant to be. The+ requirement is built from the template the legs share, so a leg that names+ its own is caught rather than skipped.+ """+ from legs import LEGS, PACKAGE_UNDER_TEST, UNSLOTH, expand_install++ requirement = UNSLOTH.format(unsloth_ref = "abc123", zoo_ref = "def456")+ for name, leg in LEGS.items():+ groups = expand_install(leg, unsloth_ref = "abc123", zoo_ref = "def456", payload_dir = SMOKE_DIR)+ owning = [g for g in groups if requirement in g]+ assert len(owning) == 1, f"{name} installs the tested commit {len(owning)} times: {groups}"+ assert "--no-deps" not in owning[0], f"{name} installs it without resolving its deps"++ # The name the verify cell asks pip about is the name pip installs. Two+ # spellings would leave the consistency check reading another package's+ # lines, which is to say none.+ assert requirement.startswith(PACKAGE_UNDER_TEST + " @"), requirement+ verify = _cell(_payload_notebooks(_build(tmp_path))["t4_control.ipynb"], 2)+ assert f"OWNER = {json.dumps(PACKAGE_UNDER_TEST)}" in verify+++def test_the_grpo_leg_installs_vllm_before_anything_pulls_torch(tmp_path):+ """vLLM pins torch. Resolving it last walks torch backwards under a+ stack that is already installed against the newer one."""+ from legs import LEGS++ groups = LEGS["grpo"].install+ assert any("vllm" in item for item in groups[0]), groups+++# The image's torch, the ONE fact the grpo leg's version choice rests on: every+# probe that installed a vLLM pinning anything else died before a training step.+KAGGLE_IMAGE_TORCH = "2.10.0"++# vLLM releases that pin exactly KAGGLE_IMAGE_TORCH, read off PyPI metadata on+# 2026-08-11. Outside this window the leg replaces the image's torch, which is+# the whole documented failure mode in legs.UNWIRED["grpo"].+VLLM_RELEASES_PINNING_IMAGE_TORCH = ("0.17.0", "0.17.1", "0.18.0", "0.18.1", "0.19.0", "0.19.1")+++def _grpo_vllm_pin() -> str:+ from legs import LEGS++ pins = [i for g in LEGS["grpo"].install for i in g if i.startswith("vllm==")]+ assert len(pins) == 1, pins+ return pins[0].split("==", 1)[1]+++def test_the_grpo_vllm_pin_does_not_replace_the_images_torch():+ """The single fact three dead probe sessions cost.++ vLLM pins torch exactly, so a release pinning anything but the image's torch+ makes pip swap torch out while the image's NVIDIA runtime packages, which+ belong to the OLD torch, are still on the path and still look satisfied. The+ result imports as `libcusparseLt.so.0: cannot open shared object file` or+ `libtorch_cuda.so: undefined symbol: ncclCommWindowRegister`, tens of+ gigabytes of download later.++ So this is not a version preference to bump with the others: moving it off+ this list reopens that failure, and needs the list re-derived from PyPI+ rather than widened.+ """+ assert _grpo_vllm_pin() in VLLM_RELEASES_PINNING_IMAGE_TORCH+++def test_the_grpo_leg_shares_the_image_now_that_it_keeps_the_images_torch():+ """The isolated venv existed only to survive replacing torch. Probe 3 spent+ about an hour of quota resolving a CUDA stack from scratch and never+ produced payload output; with nothing to replace, nothing to isolate."""+ from legs import LEGS+ assert LEGS["grpo"].system_site_packages is True+++def test_the_grpo_leg_names_its_attention_backend():+ """sm_75 has no FlashAttention and no FlashInfer, and the xformers backend+ was deleted in vLLM 0.12.0, so the ladder in vllm/platforms/cuda.py falls+ through to TRITON_ATTN. Naming it makes a release that reorders or drops it+ fail loudly rather than quietly select something else."""+ from legs import LEGS+ assert LEGS["grpo"].env.get("VLLM_ATTENTION_BACKEND") == "TRITON_ATTN"+++def test_the_grpo_leg_no_longer_carries_xformers():+ """Its vLLM backend is gone at this version, so it would be a package+ nothing selects, resolved against a torch it has opinions about."""+ from legs import LEGS+ assert not any("xformers" in i for g in LEGS["grpo"].install for i in g)+++def test_every_leg_is_either_wired_or_explained():+ """The invariant that outlives any particular leg. A leg missing from both+ KERNELS and UNWIRED is one nobody runs and nobody has written down why."""+ from legs import KERNELS, LEGS, UNWIRED++ wired = {name for kernel in KERNELS for name in kernel}+ for name in LEGS:+ assert name in wired or name in UNWIRED, f"leg {name!r} is in neither KERNELS nor UNWIRED"+++def test_nothing_is_both_wired_and_unwired():+ """UNWIRED is a list of open questions. An entry for a leg that already+ runs is a stale note, and a stale note is worse than none."""+ from legs import KERNELS, UNWIRED++ wired = {name for kernel in KERNELS for name in kernel}+ assert not (wired & set(UNWIRED)), sorted(wired & set(UNWIRED))+++def test_an_unwired_note_says_what_is_unknown():+ """An unwired leg whose note reads as settled is a leg someone wires without+ running it. Vacuous while UNWIRED is empty, and correctly so: it has+ something to check the moment a leg goes back in."""+ from legs import UNWIRED+ for name, note in UNWIRED.items():+ assert "STILL UNKNOWN" in note, f"{name} note does not say what is open"+++def test_grpo_stays_unwired_while_the_illegal_memory_access_is_open():+ """This test replaces one that asserted the opposite thing for a wrong reason.++ grpo was given a kernel of its own on the reasoning that sharing a session+ with gptoss broke it: it failed paired (unsloth-t4-ci-70a2f4eb) and had+ passed alone (unsloth-t4-ci-53efcc4e), so the pairing looked like the+ variable. Running it ALONE again (unsloth-t4-ci-c98f14be) reproduced the+ paired failure exactly, same stack at unsloth_zoo/vllm_utils.py:601 sleep(),+ same 13.8GB peak, same engine_built false, so one contrasting observation+ was never enough to blame a shared host.++ The three sessions show an INTERMITTENT illegal memory access: one pass, two+ failures, identical in every recorded version and at the same peak. A leg+ passing one session in three tells CI nothing, so it stays unwired until the+ IMA is understood, and wiring it back without that is what this stops."""+ from legs import KERNELS, UNWIRED++ assert "grpo" not in {name for kernel in KERNELS for name in kernel}+ note = UNWIRED["grpo"]+ assert "illegal memory access" in note+ # The evidence, so re-wiring means answering it rather than deleting it.+ for kernel_id in ("53efcc4e", "70a2f4eb", "c98f14be", "b1f23e34"):+ assert kernel_id in note, f"the note drops session {kernel_id}"+ # The launch-blocking run is done and answered something, so the note must+ # not still read as though it were the next thing to try.+ assert "STILL UNKNOWN" in note and "--cuda-launch-blocking run is done" in note+++def test_control_and_canary_still_share_a_session():+ """The opposite constraint, and why the pairing rule is not just 'one leg+ per kernel'. They are a matched pair -- same image, driver and hour,+ differing only in library versions -- so splitting them puts an uncontrolled+ variable between the only two legs whose comparison has to be clean."""+ from legs import KERNELS+ assert any(set(k) >= {"control", "canary"} for k in KERNELS), KERNELS+++def test_the_grpo_leg_keeps_the_config_that_actually_fit():+ """Every one of these is load-bearing on a 14.56GB card.++ Two probes with the notebook's own settings (seq 2048, 4 generations, rank+ 32, utilization 0.9) died in the backward at+ unsloth_zoo/gradient_checkpointing.py:1013, peaking at 15.97GB in 16-bit and+ 19.25GB in 4-bit. The set below passed on kernel unsloth-t4-ci-53efcc4e at+ 13.60GB with reward_std 0.707 at step 2, so restoring any of them to the+ notebook's value is a session that OOMs, and it fails here instead."""+ from legs import LEGS++ args = LEGS["grpo"].args+ for flag, value in (+ ("--gpu-memory-utilization", "0.5"),+ ("--max-seq-length", "1024"),+ ("--num-generations", "2"),+ ("--lora-rank", "16"),+ ):+ assert flag in args, f"grpo leg lost {flag}"+ assert (+ args[args.index(flag) + 1] == value+ ), f"{flag} is {args[args.index(flag) + 1]}, not the {value} that fit"+ assert "--load-in-4bit" in args+++def test_the_grpo_leg_still_pins_the_vllm_that_matches_the_image():+ """The pin is chosen to match the image's torch to the patch, not to be+ old. Any other release replaces torch, which is what killed three probe+ sessions."""+ from legs import LEGS++ install = " ".join(part for group in LEGS["grpo"].install for part in group)+ assert _grpo_vllm_pin() in install+++# --------------------------------------------------------------- workflow++WORKFLOW = (+ Path(__file__).resolve().parents[2] / ".github" / "workflows" / "kaggle-t4-notebook-ci.yml"+)+++def _workflow() -> dict:+ yaml = pytest.importorskip("yaml")+ return yaml.safe_load(WORKFLOW.read_text(encoding = "utf-8"))+++def test_the_workflow_parses_and_gates_the_expensive_job_on_the_cheap_one():+ wf = _workflow()+ jobs = wf["jobs"]+ assert jobs["t4-smoke"]["needs"] == "gate"+ assert "needs.gate.outputs.should_run == 'true'" in jobs["t4-smoke"]["if"]+ # A stand-down leaves t4-smoke skipped, which is grey rather than red,+ # and the gate itself exits 0 (see the gate tests above).+ 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():+ """A cancelled runner cannot stop the kernel it already pushed."""+ wf = _workflow()+ assert wf["concurrency"]["cancel-in-progress"] is False+ assert wf["jobs"]["t4-smoke"]["concurrency"]["cancel-in-progress"] is False+++def test_the_band_check_is_on_unless_a_dispatch_turns_it_off():+ """The band check goes off for exactly two reasons, and both announce it.++ The reference is named by the control leg rather than the workflow, so this+ asserts the OFF switches: the explicit dispatch input, and the step-count+ mismatch that would otherwise turn a custom max_steps run red on arithmetic+ rather than on the code. Both warn.+ """+ source = WORKFLOW.read_text(encoding = "utf-8")+ assert 'if [ "$SKIP_BAND" = "true" ]' in source+ assert "::warning title=Reference band check disabled" in source+ assert 'elif [ "$MAX_STEPS" != "$REF_STEPS" ]' in source+ assert "::warning title=Reference band check skipped" in source+ assert source.count("SKIP='--skip-reference'") == 2+ assert source.count("$SKIP") == 2 # the SKIP_BAND guard and the use+++def test_applying_the_opt_in_label_can_start_a_run():+ """The gate advertises the label; the trigger has to subscribe to it.++ GitHub's default pull_request activity types are opened, synchronize and+ reopened, so without an explicit `types` the advertised override does+ nothing until an unrelated event fires.+ """+ wf = _workflow()+ on = wf[True] if True in wf else wf["on"]+ assert "labeled" in on["pull_request"]["types"]+ for default in ("opened", "synchronize", "reopened"):+ assert default in on["pull_request"]["types"], "the defaults are lost once types is set"+++def test_only_the_opt_in_label_starts_a_run(monkeypatch, tmp_path):+ """`labeled` fires for EVERY label, and each run is a fresh draw.++ Worse than the wasted draws: once kaggle-t4-ci is on the pull request it+ stays in the label list, so every later label of any kind arrives as an+ override and FORCES a session, while the budget at the top of the workflow+ counts pull request opens and pushes and no label activity at all.+ """+ monkeypatch.delenv("KAGGLE_API_TOKEN", raising = False)+ code, outputs = _run_gate(+ monkeypatch,+ tmp_path / "unrelated",+ "--event-action",+ "labeled",+ "--event-label",+ "documentation",+ "--labels",+ "documentation,kaggle-t4-ci",+ )+ assert code == 0+ assert outputs["should_run"] == "false"+ assert "not the opt-in label" in outputs["reason"]++ # The label that IS the request gets through to the checks below it.+ code, outputs = _run_gate(+ monkeypatch,+ tmp_path / "optin",+ "--event-action",+ "labeled",+ "--event-label",+ "kaggle-t4-ci",+ "--labels",+ "kaggle-t4-ci",+ )+ assert code == 0+ assert outputs["should_run"] == "false"+ assert "fork" in outputs["reason"], "it stood down on the label rather than on the token"+++def test_a_push_or_a_synchronize_is_not_affected_by_the_label_check(monkeypatch, tmp_path):+ """Only a `labeled` run is judged on which label arrived."""+ monkeypatch.delenv("KAGGLE_API_TOKEN", raising = False)+ for action in ("synchronize", "opened", ""):+ code, outputs = _run_gate(+ monkeypatch,+ tmp_path / f"a{action}",+ "--event-action",+ action,+ "--labels",+ "kaggle-t4-ci",+ )+ assert code == 0+ assert "not the opt-in label" not in outputs["reason"], action+++def test_the_workflow_tells_the_gate_which_label_arrived():+ """The check above is worth nothing if the event never reaches it."""+ steps = _workflow()["jobs"]["gate"]["steps"]+ decide = next(s for s in steps if s.get("id") == "decide")+ assert decide["env"]["EVENT_ACTION"] == "${{ github.event.action }}"+ assert decide["env"]["EVENT_LABEL"] == "${{ github.event.label.name }}"+ assert '--event-action "$EVENT_ACTION"' in decide["run"]+ assert '--event-label "$EVENT_LABEL"' in decide["run"]+ # Label names are free text. They travel through the environment rather+ # than being interpolated into the shell, as does the raw label list.+ assert "${{ github.event.label.name }}" not in decide["run"]+ assert "${{ join(github.event.pull_request.labels" not in decide["run"]+++def test_a_dispatched_ref_is_resolved_to_one_commit():+ """A branch name forwarded unchanged is four independent resolutions.++ Every payload pip-installs on the kernel by itself, so `main` can land on a+ different commit per leg and the control/canary comparison is then between+ two different Unsloths. The report records a distribution version rather+ than a commit, so the drift is invisible afterwards too. Same hazard as the+ zoo pin below, same answer.+ """+ steps = _workflow()["jobs"]["t4-smoke"]["steps"]+ names = [s.get("name") for s in steps]+ ref = steps[names.index("Resolve the ref under test")]+ assert ref["env"]["UNSLOTH_REF"] == "${{ inputs.unsloth_ref }}"+ # Resolved once, here, and retried before it gives up.+ assert "git ls-remote https://github.com/unslothai/unsloth" in ref["run"]+ assert "for attempt in 1 2 3" in ref["run"]+ # A full commit needs no resolving and ls-remote would not answer for one.+ assert "^[0-9a-f]{40}$" in ref["run"]+ # A ref that cannot be pinned stands the run down rather than installing+ # a moving branch, exactly as an unresolvable zoo commit does.+ assert "stand_down=true" in ref["run"]+ for name in (+ "Pin the zoo revision",+ "Build the kernel notebooks",+ "Recheck the Kaggle account",+ ):+ assert "steps.ref.outputs.stand_down != 'true'" in steps[names.index(name)]["if"], name+ # The dispatched value is never interpolated into the shell.+ assert "${{ inputs.unsloth_ref }}" not in ref["run"]++[email protected](shutil.which("bash") is None, reason = "the step is a bash script")+def test_the_resolve_step_pins_every_shape_of_ref_it_can_be_given(tmp_path):+ """EXECUTE the step, with git stubbed, rather than reading it.++ Pattern-matching a shell script passes on one that runs and writes the wrong+ thing, and this one has four branches: no input, a mutable branch or tag, a+ commit needing no resolution, and a ref that resolves to nothing.+ """+ steps = _workflow()["jobs"]["t4-smoke"]["steps"]+ script = next(s for s in steps if s.get("id") == "ref")["run"]++ def drive(+ unsloth_ref,+ ls_remote,+ head = "headsha",+ ):+ work = tmp_path / f"case{abs(hash((unsloth_ref, ls_remote)))}"+ stub = work / "bin"+ stub.mkdir(parents = True)+ # `git` answers with whatever ls-remote is supposed to have said, and+ # `sleep` returns at once so the retry loop costs nothing.+ (stub / "git").write_text("#!/bin/sh\nprintf '%s' \"$LS_OUT\"\n")+ (stub / "sleep").write_text("#!/bin/sh\nexit 0\n")+ for name in ("git", "sleep"):+ (stub / name).chmod(0o755)+ out = work / "github_output"+ out.write_text("", encoding = "utf-8")+ env = dict(+ os.environ,+ PATH = f"{stub}:{os.environ['PATH']}",+ GITHUB_OUTPUT = str(out),+ UNSLOTH_REF = unsloth_ref,+ HEAD_SHA = head,+ LS_OUT = ls_remote,+ )+ done = subprocess.run(["bash", "-c", script], env = env, capture_output = True, text = True)+ assert done.returncode == 0, done.stderr+ return dict(line.split("=", 1) for line in out.read_text().splitlines() if "=" in line)++ # No input: the head SHA under test, which is also the tree checked out.+ assert drive("", "") == {"ref": "headsha"}+ # A branch resolves to the commit it points at, once, for all four legs.+ main_sha = "dead" + "0" * 36+ assert drive("main", f"{main_sha}\trefs/heads/main\n") == {"ref": main_sha}+ # An annotated tag lists the tag object first; the COMMIT is what pip can+ # check out, and it is on the ^{} line.+ tag, commit = "aaaa" + "0" * 36, "bbbb" + "0" * 36+ assert drive("v1.2", f"{tag}\trefs/tags/v1.2\n{commit}\trefs/tags/v1.2^{{}}\n") == {+ "ref": commit+ }+ # A full commit is already immutable, and ls-remote answers nothing for+ # one, so it must not be sent there at all.+ assert drive("f" * 40, "") == {"ref": "f" * 40}+ # Nothing resolved: stand down rather than install a moving branch.+ assert drive("no-such-branch", "") == {"stand_down": "true"}+ # The value is free text from a dispatch form and reaches no shell.+ assert drive("'; touch pwned; echo '", "") == {"stand_down": "true"}+ assert not (tmp_path / "pwned").exists()+++def test_the_harness_stays_on_the_checked_out_tree_when_a_ref_is_dispatched():+ """Resolving the INSTALL is not the same as checking that ref out.++ The whole harness arrives with this workflow, so a dispatch naming an older+ ref has no payloads, no legs.py and no reference to run from. A dispatch+ varies the package under test; the thing testing it stays fixed.+ """+ steps = _workflow()["jobs"]["t4-smoke"]["steps"]+ checkout = next(s for s in steps if str(s.get("uses", "")).startswith("actions/checkout@"))+ assert "inputs.unsloth_ref" not in json.dumps(checkout)+ build = next(s for s in steps if s.get("id") == "build")+ assert "--unsloth-ref '${{ steps.ref.outputs.ref }}'" in build["run"]+++def test_packaging_metadata_is_watched_by_both_triggers():+ """Every payload installs the commit under test as a distribution."""+ wf = _workflow()+ on = wf[True] if True in wf else wf["on"]+ assert "pyproject.toml" in on["pull_request"]["paths"]+ assert "pyproject.toml" in on["push"]["paths"]+++def _launcher_constant(name: str) -> int:+ """One of launch.py's named ceilings, or a failure saying it moved.++ Read by regex rather than imported so the bound below is computed from the+ source the workflow ships. A renamed constant fails here rather than+ silently dropping a term out of the arithmetic.+ """+ launch = (CI_DIR / "launch.py").read_text(encoding = "utf-8")+ match = re.search(rf"^{name} = (\d+)", launch, re.M)+ assert match, f"launch.py no longer defines {name}, so the job deadline cannot be derived"+ return int(match.group(1))+++def _one_delete_seconds() -> int:+ """Wall clock ONE delete_kernel() call can take, retries and backoff in.++ Not one subprocess: a refused delete is retried DELETE_ATTEMPTS times with+ an exponential gap, because deletion is this workflow's budget control.+ Counting a single call is what put the old bound at half the truth.+ """+ attempts = _launcher_constant("DELETE_ATTEMPTS")+ backoff = _launcher_constant("DELETE_BACKOFF_SEC")+ ceiling = _launcher_constant("DELETE_SUBPROCESS_TIMEOUT_SEC")+ return attempts * ceiling + sum(backoff * 2**i for i in range(attempts - 1))+++def _launcher_worst_case_seconds() -> int:+ """Wall clock one launch.py invocation can take, from its own constants.++ Every phase that keeps a pushed kernel up is in it, because the two things+ derived from this number -- the job deadline and the quota the gate reserves+ -- are both wrong if a phase is left out:++ * push(), per notebook: PUSH_ATTEMPTS attempts at the subprocess ceiling,+ the backoffs between them, and a _discard() of the previous attempt's slug+ before each retry.+ * the polling, which shares ONE deadline with the pushes rather than+ stacking on them.+ * the evidence download, one budget for every kernel together.+ * release(), which deletes every slug every push FILED, not just the+ accepted one.++ Computed here rather than restated in either caller, so lowering+ PUSH_ATTEMPTS or a delete ceiling moves both derivations at once.+ """+ push_attempts = _launcher_constant("PUSH_ATTEMPTS")+ push_backoff = _launcher_constant("PUSH_BACKOFF_SEC")+ push_ceiling = _launcher_constant("PUSH_SUBPROCESS_TIMEOUT_SEC")+ one_delete = _one_delete_seconds()++ # push() calls _discard() before every retry, so PUSH_ATTEMPTS - 1 deletes+ # ride along with the pushes themselves.+ per_push = (+ push_attempts * push_ceiling+ + sum(push_backoff * 2**i for i in range(push_attempts - 1))+ + (push_attempts - 1) * one_delete+ )+ source = WORKFLOW.read_text(encoding = "utf-8")+ max_wait = int(re.search(r"--max-wait (\d+)", source).group(1))+ kernels = _kernels_per_invocation()+ # ONE budget for every kernel's evidence, read from the constant launch.py+ # enforces rather than restated here. "300s per kernel" was a term nobody+ # multiplied out: OUTPUT_PAGE_LIMIT listing pages at the 120s socket+ # ceiling is 2400s for a single kernel, so the phase could outlast the job+ # and the runner would be killed before release() deleted anything.+ evidence = _launcher_constant("EVIDENCE_BUDGET_SEC")+ # release() reconciles every slug filed: one per push attempt, per kernel.+ deletions = kernels * push_attempts * one_delete+ # The polling deadline starts before the first push, so the two do not+ # stack; the longer of them is what the run spends.+ return max(kernels * per_push, max_wait) + evidence + deletions+++def _kernels_per_invocation() -> int:+ """How many of Kaggle's session slots one invocation takes, per the gate."""+ source = WORKFLOW.read_text(encoding = "utf-8")+ kernels = {int(k) for k in re.findall(r"--kernels (\d+)", source)}+ assert len(kernels) == 1, kernels+ return kernels.pop()+++def test_the_job_deadline_exceeds_the_launchers_worst_case():+ """A runner killed mid-run takes finish() -> release() with it.++ The launcher's own constants bound how long it can take, and EVERY deletion+ path counts, both of them retried:++ * push(), per notebook: PUSH_ATTEMPTS attempts at the subprocess ceiling,+ the backoffs between them, and a _discard() of the previous attempt's slug+ before each retry.+ * the polling, which shares one deadline with the pushes rather than+ stacking on them.+ * the evidence download.+ * release(), which deletes every slug every push FILED, not just the+ accepted one.++ The job timeout has to sit above the total with room for the steps that run+ before the launcher, or the runner is killed mid-release() and the kernels+ it pushed keep billing to their own ceiling -- the one outcome this deadline+ exists to prevent.+ """+ worst = _launcher_worst_case_seconds()+ # Checkout, the CPU torch wheel and the harness suite all run before the+ # launcher does, and they come out of the same job deadline. An ALLOWANCE,+ # not a limit: nothing bounds those steps, which is why the launcher is+ # handed the deadline and refuses to push without the whole of `worst` left+ # (see the two tests below). This keeps a normal run from standing down.+ before_the_launcher = 900+ timeout_s = _workflow()["jobs"]["t4-smoke"]["timeout-minutes"] * 60+ assert timeout_s >= worst + before_the_launcher, (+ f"the launcher can take {worst}s, the steps before it up to "+ f"{before_the_launcher}s, and the job is killed at {timeout_s}s"+ )+++def test_the_launcher_agrees_with_the_deadline_about_its_own_worst_case():+ """The guard and the deadline have to be reading the same number.++ launch.py refuses to push unless ``worst_case_seconds()`` still fits before+ the job deadline, and that deadline is set from the derivation above. The+ two are computed independently -- this file walks launch.py's constants out+ of the source text, the launcher adds them up itself -- so a phase dropped+ from either one shows up here rather than as a run that pushed with no room+ to clean up, or one that stood down on every invocation.+ """+ import launch++ source = WORKFLOW.read_text(encoding = "utf-8")+ max_wait = int(re.search(r"--max-wait (\d+)", source).group(1))+ assert (+ launch.worst_case_seconds(max_wait, _kernels_per_invocation())+ == _launcher_worst_case_seconds()+ )+++def test_the_launcher_is_told_when_the_job_is_killed():+ """The guard is only as good as the deadline it is handed.++ Three things have to hold, and each is a way the guard silently reads+ optimistic:++ * the start is recorded in the job's FIRST step. Taken after a checkout or a+ pip install, the computed deadline sits that much later than the real one.+ * the launcher is actually given it.+ * the minutes handed over are this job's own timeout-minutes. A job cannot+ read its own, so the number is restated in the step's environment and+ asserted equal here; moving one without the other is this test going red.+ """+ job = _workflow()["jobs"]["t4-smoke"]+ steps = job["steps"]+ assert "JOB_START_EPOCH=$(date +%s)" in steps[0].get("run", ""), (+ "the job's start is not recorded by its first step, so every step ahead "+ "of it is invisible to the launcher's guard"+ )+ assert "if" not in steps[0], "a conditional start would leave JOB_START_EPOCH unset"+ launch_step = next(s for s in steps if s.get("id") == "launch")+ assert "--deadline-epoch" in launch_step["run"]+ assert "JOB_START_EPOCH + JOB_TIMEOUT_MINUTES * 60" in launch_step["run"]+ assert int(launch_step["env"]["JOB_TIMEOUT_MINUTES"]) == job["timeout-minutes"]+++def test_the_reserved_budget_covers_every_billable_launcher_phase():+ """What ends a session is the launcher deleting it, not Kaggle's ceiling.++ So the quota the gate reserves has to cover the launcher's WHOLE bound, not+ the polling window alone. A kernel bills from the moment Kaggle accepts it+ until a delete is confirmed, which puts the push retries (each one discarding+ the previous attempt's slug), the evidence phase and release() inside the+ billable window as surely as the wait is. `2 x --max-wait` counted only the+ middle one, and a run that spent the other two could bill past the+ reservation and into the 20h the reserve promises to leave for humans.++ The bound: Kaggle runs at most --kernels sessions for this account at once,+ each billing its wall clock once (the second T4 of a session is free), so the+ hours one invocation can bill are at most that many sessions billing for the+ whole of the launcher's worst case -- the same worst case the job deadline is+ derived from, computed from launch.py's constants rather than restated.+ """+ source = WORKFLOW.read_text(encoding = "utf-8")+ budgets = {int(b) for b in re.findall(r"--budget-hours (\d+)", source)}+ assert len(budgets) == 1, budgets+ budget_s = budgets.pop() * 3600+ worst = _kernels_per_invocation() * _launcher_worst_case_seconds()+ assert (+ budget_s >= worst+ ), f"the gate reserves {budget_s}s of quota and the launcher can bill {worst}s"+++def test_the_account_is_rechecked_after_the_concurrency_slot_is_held():+ """The gate job's survey is stale by the time a queued run gets the slot.++ t4-smoke queues on an account-wide group with cancel-in-progress false, so a+ second sampled run can wait out the first before pushing, and the quota+ floor and in-flight survey have to be re-asked with the slot in hand.+ """+ steps = _workflow()["jobs"]["t4-smoke"]["steps"]+ names = [s.get("name") for s in steps]+ assert "Recheck the Kaggle account" in names+ recheck = steps[names.index("Recheck the Kaggle account")]+ assert recheck["id"] == "recheck"+ # --force skips the sampling draw only; the dice were rolled by the gate.+ assert "--force true" in recheck["run"]+ assert "--reserve-hours" in recheck["run"] and "--kernels" in recheck["run"]+ # and it is the last thing before the push.+ assert names[names.index("Recheck the Kaggle account") + 2] == "Launch on Kaggle and collect"+ launch = steps[names.index("Launch on Kaggle and collect")]+ assert launch["if"] == "steps.recheck.outputs.should_run == 'true'"+++def test_the_exhausted_quota_failure_reaches_the_pull_request():+ """A red nothing surfaces is the same as no red at all.++ The Decide step is the whole gate job, so anything that swallowed its exit+ code (continue-on-error, an `|| true`, a downstream always()) would leave the+ check green while the log said the account was out of hours.+ """+ jobs = _workflow()["jobs"]+ gate_job = jobs["gate"]+ decide = next(s for s in gate_job["steps"] if s.get("id") == "decide")+ assert "continue-on-error" not in gate_job+ assert "continue-on-error" not in decide+ assert "|| true" not in decide["run"]+ # and the gate job asks for the red: --soft-fail is the recheck's flag.+ assert "--soft-fail" not in decide["run"]+ # t4-smoke is skipped rather than run when the gate fails, and nothing in it+ # runs unconditionally enough to turn that into a green verdict.+ assert jobs["t4-smoke"]["needs"] == "gate"+ assert "always()" not in jobs["t4-smoke"]["if"]+++def test_the_recheck_stands_down_rather_than_reporting_the_quota_twice():+ """It runs AFTER approval, with the account slot already held.++ Reaching it means the hours went while this run queued, which is a race lost+ rather than the week's quota gone, and the gate job would already have said+ so for a run that was short before it started. So it asks for soft failure+ and the stale-approval warning below it carries the reason.+ """+ steps = _workflow()["jobs"]["t4-smoke"]["steps"]+ names = [s.get("name") for s in steps]+ recheck = steps[names.index("Recheck the Kaggle account")]+ assert "--soft-fail" in recheck["run"]+ assert "continue-on-error" not in recheck+ warn = steps[names.index("Report the stale approval")]+ assert "steps.recheck.outputs.should_run != 'true'" in warn["if"]+ assert "::warning" in warn["run"]+++def test_the_workflow_states_the_failure_semantics_it_actually_has():+ """The comment block is what a reader trusts instead of reading gate.py."""+ source = WORKFLOW.read_text(encoding = "utf-8")+ semantics = source.split("FAILURE SEMANTICS", 1)[1].split("CREDENTIALS", 1)[0]+ assert "WEEKLY accelerator quota is exhausted" in semantics+ assert "before any kernel" in semantics+ assert "--soft-fail" in semantics+ # An unreadable quota is not the same outcome, and the block says so.+ assert "UNREADABLE" in semantics+ # The old promise that only a failed payload is ever red is gone.+ assert "Red ONLY when a payload ran" not in source+++def test_the_harness_suite_runs_before_any_kernel_is_pushed():+ """Nothing else collects it: pyproject limits testpaths to tests/security."""+ steps = _workflow()["jobs"]["t4-smoke"]["steps"]+ names = [s.get("name") for s in steps]+ assert names.index("Test the harness") < names.index("Build the kernel notebooks")+ assert "python -m pytest tests/kaggle -q" in steps[names.index("Test the harness")]["run"]+++def test_the_cpu_torch_wheel_is_installed_before_anything_that_depends_on_it():+ """Order decides which torch the runner ends up with, silently.++ peft depends on torch, so installing it first lets pip satisfy that from the+ default index -- the CUDA build and its multi-gigabyte dependency set -- and+ pip then "prefers to leave the installed version as-is unless --upgrade is+ specified" (pip.pypa.io/en/stable/cli/pip_install), so the CPU-index line+ that follows finds the requirement satisfied and installs nothing. The+ suites still pass, having spent the setup window reserved before the push on+ wheels this job never uses. version-compat-ci.yml puts CPU torch first for+ the same reason.+ """+ steps = _workflow()["jobs"]["t4-smoke"]["steps"]+ names = [s.get("name") for s in steps]+ lines = [+ l.strip() for l in steps[names.index("Test the harness")]["run"].splitlines() if l.strip()+ ]+ installs = [l for l in lines if "pip install" in l]+ assert installs, lines+ assert "download.pytorch.org/whl/cpu" in installs[0], (+ "the CPU-index torch install must be the FIRST pip install in the step: " f"{installs}"+ )+ assert "torch" in installs[0]+ # And the outcome is checked, not just the order: a CUDA build satisfies+ # every import here, so nothing else in this job would ever notice.+ guard = [l for l in lines if "torch.version.cuda" in l]+ assert guard, lines+ run_suites = [l for l in lines if l.startswith("python -m pytest")]+ assert run_suites and lines.index(guard[0]) < lines.index(run_suites[0]), lines+++def test_every_cpu_suite_in_the_directory_is_collected_by_that_step():+ """Naming one file leaves the others collected by nothing at all.++ pyproject.toml restricts default discovery to tests/security, so a suite+ this step does not name is run by no invocation anywhere, and the two suites+ added after it was written cover the report extraction, the payload+ verdicts, the reference checks and the per-leg isolation, which is most of+ what a Kaggle session would otherwise be spent discovering.+ """+ steps = _workflow()["jobs"]["t4-smoke"]["steps"]+ names = [s.get("name") for s in steps]+ run = steps[names.index("Test the harness")]["run"]+ suites = sorted(p.name for p in (Path(__file__).resolve().parent).glob("test_*.py"))+ assert len(suites) >= 3, suites+ argument = run.split("python -m pytest ")[1].split()[0]+ collected = subprocess.run(+ [sys.executable, "-m", "pytest", argument, "--collect-only", "-q"],+ capture_output = True,+ text = True,+ cwd = Path(__file__).resolve().parents[2],+ )+ assert collected.returncode == 0, collected.stdout[-2000:]+ for suite in suites:+ assert f"tests/kaggle/{suite}" in collected.stdout, f"{suite} is collected by nothing"+++def test_every_leg_installs_one_pinned_zoo_commit():+ """A branch name lets control and canary resolve two different commits.++ zoo is not in pins/control.txt either, so the control leg, the one with a+ committed reference band, would otherwise install whatever main was when its+ own pip ran.+ """+ steps = _workflow()["jobs"]["t4-smoke"]["steps"]+ names = [s.get("name") for s in steps]+ pins = steps[names.index("Pin the zoo revision")]+ assert "git ls-remote" in pins["run"]+ build = steps[names.index("Build the kernel notebooks")]+ assert "--zoo-ref '${{ steps.pins.outputs.zoo_ref }}'" in build["run"]+ assert "--zoo-ref main" not in build["run"]+++def test_an_unresolvable_zoo_commit_stands_the_run_down():+ """Falling back to the branch name is the behaviour the pin removed.++ Every payload pips independently on the kernel, so `main` lets control and+ canary resolve two different zoo commits within one session, invalidating+ the control's reference band and the version attribution both. A run that+ cannot be made reproducible has nothing to say, so it stands down green.+ """+ steps = _workflow()["jobs"]["t4-smoke"]["steps"]+ names = [s.get("name") for s in steps]+ pins = steps[names.index("Pin the zoo revision")]+ assert "ZOO_REF=main" not in pins["run"], "the mutable branch fallback is back"+ assert "stand_down=true" in pins["run"]+ # A single blip is not a verdict.+ assert "for attempt in 1 2 3" in pins["run"]+ # Nothing that spends a kernel runs after a stand-down.+ for name in ("Build the kernel notebooks", "Recheck the Kaggle account"):+ assert "steps.pins.outputs.stand_down != 'true'" in steps[names.index(name)]["if"]+ launch_step = steps[names.index("Launch on Kaggle and collect")]+ assert launch_step["if"] == "steps.recheck.outputs.should_run == 'true'"+++def test_a_step_count_that_could_only_report_red_stands_the_run_down():+ """A dispatched max_steps is free text, and the payload is the wrong place+ to find out.++ Both bad values cost a whole Kaggle session and report the pull request red+ for the dispatch rather than for the code: a non-integer dies in the+ payload's argparse, and the generated cell turns that crash into a failing+ report on purpose, while a count below the fp16 scaler's leading skipped+ steps applies no optimizer update at all.+ """+ sys.path.insert(0, str(REPO_ROOT / ".github" / "scripts" / "kaggle_t4_ci"))+ import check_steps++ for bad in ("foo", "", "0", "-4", "3.5", "1e3"):+ stood_down, reason = check_steps.decide(bad, SMOKE_DIR)+ assert stood_down, f"{bad!r} would have been pushed"+ assert reason+ # The floor is MEASURED off the committed reference and the payload's own+ # verdict, not declared here: the reference's first three steps are scaler+ # skips and its fourth does not lower the loss, so five is the shortest run+ # that trains anything, and this test states the derivation rather than the+ # number.+ from run_t4_smoke import optimisation_failures++ metrics = check_steps.reference_metrics(SMOKE_DIR)+ floor = check_steps.minimum_steps(metrics, optimisation_failures)+ assert floor and 1 < floor <= len(metrics)+ assert optimisation_failures(metrics[: floor - 1]), "the floor is not the shortest passing run"+ assert not optimisation_failures(metrics[:floor])+ assert check_steps.decide(str(floor - 1), SMOKE_DIR)[0] is True+ assert check_steps.decide(str(floor), SMOKE_DIR)[0] is False+ # And the count CI actually runs is above it, or every unsampled run would+ # stand down.+ assert check_steps.decide("10", SMOKE_DIR)[0] is False+ # An unmeasurable floor is not a floor of zero.+ assert check_steps.minimum_steps([], optimisation_failures) is None+ assert check_steps.decide("10", REPO_ROOT / "tests" / "kaggle")[0] is True+++def test_the_dispatched_step_count_is_checked_before_a_kernel_is_paid_for():+ """Validating it inside the payload is validating it after the bill."""+ steps = _workflow()["jobs"]["t4-smoke"]["steps"]+ names = [s.get("name") for s in steps]+ assert "Validate the dispatched step count" in names+ check = steps[names.index("Validate the dispatched step count")]+ assert check["id"] == "stepcount"+ assert "check_steps.py" in check["run"]+ # Nothing that builds or spends anything runs after it stands down.+ assert names.index("Validate the dispatched step count") < names.index(+ "Build the kernel notebooks"+ )+ for name in (+ "Build the kernel notebooks",+ "Recheck the Kaggle account",+ "Report the stale approval",+ ):+ assert "steps.stepcount.outputs.stand_down != 'true'" in steps[names.index(name)]["if"]+ # Through the environment, and only after the check: the dispatched value is+ # free text, so interpolating it into a step's shell puts it in the command+ # line rather than in an argument.+ build = steps[names.index("Build the kernel notebooks")]+ assert check["env"]["MAX_STEPS"].startswith("${{ inputs.max_steps")+ for step in (check, build):+ assert "inputs.max_steps" not in step["run"]+ assert "--max-steps $MAX_STEPS" in build["run"]+ # Where the build step takes its count FROM is asserted by executing it:+ # test_an_alternate_spelling_of_the_step_count_keeps_the_reference_band.++[email protected](shutil.which("bash") is None, reason = "the step is a bash script")+def test_an_alternate_spelling_of_the_step_count_keeps_the_reference_band(tmp_path):+ """EXECUTE the build step, on the count the VALIDATOR produced.++ The band is the only thing in this workflow that compares a run against a+ committed trace, and the only way it goes off silently is this comparison+ saying two identical step counts differ. `check_steps.parse_steps` accepts+ `+10`, `010` and surrounding whitespace as the ten they are -- so does the+ payload's argparse, which is what actually runs -- so a raw string compare+ here dropped the band from a run that was the reference's run, and said so+ in a warning naming a step count that was not different.++ Every arm goes through the real code path: the step's own `env:` block says+ where each value comes from, the count is whatever running check_steps.py+ writes to GITHUB_OUTPUT, and the assertion is on the argv the step hands+ build_kernel.py. Reading the wiring rather than supplying it is the point --+ a build step that goes back to the raw dispatch string fails here.+ """+ steps = _workflow()["jobs"]["t4-smoke"]["steps"]+ names = [s.get("name") for s in steps]+ step = steps[names.index("Build the kernel notebooks")]+ script, wiring = step["run"], step["env"]+ checker = REPO_ROOT / ".github" / "scripts" / "kaggle_t4_ci" / "check_steps.py"+ cases = iter(range(1000))++ def resolve(key: str, validated: dict, skip_band: str) -> str:+ """What GitHub would put in `key`, from the step's own env block."""+ expr = str(wiring[key]).strip()+ inner = expr.removeprefix("${{").removesuffix("}}").strip()+ if inner == "inputs.skip_reference_band":+ return skip_band+ source, _, name = inner.rpartition(".")+ if source == "steps.stepcount.outputs":+ return validated.get(name, "")+ raise AssertionError(+ f"the build step takes {key} from {expr}. The step count it builds with, "+ f"and the reference count it compares against, have to be the ones the "+ f"validator parsed: any second reading of the dispatched string is a "+ f"second answer to how long this run is, and the band goes off when the "+ f"two disagree."+ )++ def validate(raw: str) -> dict:+ """The validator step, run for real, and the outputs it wrote."""+ out = tmp_path / f"validated{next(cases)}"+ out.write_text("", encoding = "utf-8")+ done = subprocess.run(+ [sys.executable, str(checker), "--max-steps", raw, "--payload-dir", str(SMOKE_DIR)],+ env = dict(os.environ, GITHUB_OUTPUT = str(out)),+ capture_output = True,+ text = True,+ )+ assert done.returncode == 0, done.stderr+ return dict(line.split("=", 1) for line in out.read_text().splitlines() if "=" in line)++ def build(raw: str, skip_band: str = "false") -> tuple[list[str], str]:+ """The build step's shell on those outputs; build_kernel's argv and the log."""+ validated = validate(raw)+ assert validated["stand_down"] == "false", raw+ work = tmp_path / f"build{next(cases)}"+ stub = work / "bin"+ stub.mkdir(parents = True)+ argv = work / "argv"+ (stub / "python").write_text(+ f'#!/bin/sh\nfor arg in "$@"; do printf "%s\\n" "$arg"; done > "{argv}"\n'+ )+ (stub / "python").chmod(0o755)+ done = subprocess.run(+ ["bash", "-c", script],+ env = dict(+ os.environ,+ PATH = f"{stub}:{os.environ['PATH']}",+ **{key: resolve(key, validated, skip_band) for key in wiring},+ ),+ capture_output = True,+ text = True,+ )+ assert done.returncode == 0, done.stderr+ return argv.read_text().splitlines(), done.stdout++ sys.path.insert(0, str(REPO_ROOT / ".github" / "scripts" / "kaggle_t4_ci"))+ import check_steps++ committed = check_steps.reference_steps(SMOKE_DIR)+ assert committed, "the committed reference declares no step count"++ # The count the reference was captured at, however it is spelled, keeps the+ # band. Derived from the committed file rather than written out here, so a+ # recapture at another count moves this test with it.+ for spelling in (str(committed), f"+{committed}", f"0{committed}", f" {committed} "):+ args, log = build(spelling)+ assert "--skip-reference" not in args, (spelling, args)+ assert args[args.index("--smoke-args") + 1] == f"--max-steps {committed}", args+ assert "Reference band check" not in log, (spelling, log)++ # And a run that really is a different length still drops it, with the+ # warning. This is the arm a comparison that always says "same" would take+ # away, leaving every custom step count compared against a curve it has+ # nothing to do with.+ other = committed + 1+ args, log = build(str(other))+ assert "--skip-reference" in args, args+ assert "::warning title=Reference band check skipped" in log, log++ # The dispatch switch is untouched by any of it.+ args, log = build(str(committed), skip_band = "true")+ assert "--skip-reference" in args, args+ assert "::warning title=Reference band check disabled" in log, log+++def test_an_evidence_upload_outage_cannot_colour_the_check_red():+ """The verdict is Report's; the artifact service does not get a vote.++ An upload step with no continue-on-error fails the job on a transient+ artifact outage, and the job is what the pull request shows, so a run whose+ payloads all passed went red for an evidence upload. This file promises red+ ONLY for a payload that ran and failed its assertions.+ """+ steps = _workflow()["jobs"]["t4-smoke"]["steps"]+ names = [s.get("name") for s in steps]+ upload = steps[names.index("Upload evidence")]+ assert upload["continue-on-error"] is True+ assert upload["id"] == "evidence"+ # Non-fatal, not silent: continue-on-error leaves `outcome` at failure while+ # `conclusion` becomes success, and that outcome is what says so.+ warn = steps[names.index("Report the evidence upload failure")]+ assert "steps.evidence.outcome == 'failure'" in warn["if"]+ assert "::warning" in warn["run"]+ # The verdict still runs, and still on its own condition.+ report = steps[names.index("Report")]+ assert report["if"] == "always() && steps.recheck.outputs.should_run == 'true'"+ assert "steps.evidence" not in report["if"]+++def test_the_harness_and_the_package_under_test_are_one_snapshot():+ """The default pull_request checkout is the merge ref, not the head."""+ steps = _workflow()["jobs"]["t4-smoke"]["steps"]+ checkout = next(s for s in steps if str(s.get("uses", "")).startswith("actions/checkout@"))+ assert checkout["with"]["ref"] == "${{ github.event.pull_request.head.sha || github.sha }}"+ ref_step = next(s for s in steps if s.get("id") == "ref")+ assert ref_step["env"]["HEAD_SHA"] == "${{ github.event.pull_request.head.sha || github.sha }}"+ assert "ref=$HEAD_SHA" in ref_step["run"]+++def test_the_workflow_takes_its_kernel_plan_from_the_leg_registry():+ """Restating the plan in YAML is how the two drift apart.++ The build emits the launcher's --notebook arguments and the expected payload+ count, so a leg added to legs.py is launched and counted without touching+ this file. A hardcoded --expect would report "partial" forever after the+ next leg lands.+ """+ source = WORKFLOW.read_text(encoding = "utf-8")+ assert "--all-kernels" in source+ assert "${{ steps.build.outputs.notebooks }}" in source+ assert "steps.build.outputs.payloads" in source+++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(+ (Path(__file__).resolve().parents[2] / ".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+++# ----------------------------------------------------------------- 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), "--expect", "2"],+ capture_output = True,+ text = True,+ )+ assert proc.returncode == expected_exit, proc.stdout+++def test_a_kernel_that_reported_nothing_still_names_its_cause(tmp_path):+ """The summary alone must say why, without downloading the artifact.++ Kaggle hands the log back as a JSON array of stream records, so the+ interesting line arrives split across dozens of them, and both real+ no-report failures so far were legible only after flattening it.+ """+ evidence = tmp_path / "evidence"+ evidence.mkdir()+ (evidence / "launch_result.json").write_text(+ json.dumps(+ {+ "verdict": "infra",+ "reason": "no payload report",+ "slug": "u/s",+ "kernel_state": "COMPLETE",+ "reports": [],+ }+ )+ )+ (evidence / "kernel.log").write_text(+ json.dumps(+ [+ {"stream_name": "stdout", "time": 1.0, "data": "KAGGLE_T4_CI_DRIVER start\n"},+ {"stream_name": "stdout", "time": 2.0, "data": "SyntaxError: invalid "},+ {"stream_name": "stdout", "time": 2.1, "data": "syntax\n"},+ {"stream_name": "stdout", "time": 3.0, "data": "unrelated chatter\n"},+ ]+ )+ )+ proc = subprocess.run(+ [sys.executable, str(CI_DIR / "report.py"), "--evidence", str(evidence), "--expect", "2"],+ capture_output = True,+ text = True,+ )+ assert proc.returncode == 0+ assert "SyntaxError: invalid syntax" in proc.stdout+ assert "unrelated chatter" not in proc.stdout+++def test_the_summary_states_a_refused_reference_rather_than_an_empty_list():+ """`deviations: []` next to a refusal reads exactly like a clean pass."""+ sys.path.insert(0, str(CI_DIR))+ from report import render++ text = "\n".join(+ render(+ {+ "label": "gpu0",+ "model": "m",+ "metrics": [],+ "config": {"max_steps": 3, "init_loss_scale": 2048.0},+ "reference_check": {+ "status": "step_count_mismatch",+ "deviations": [],+ "reference_max_steps": 10,+ "observed_max_steps": 3,+ "note": "captured at max_steps=10 and this run is 3 steps",+ },+ "failures": ["refusing to band-check against a reference that is not for this run"],+ }+ )+ )+ assert "step_count_mismatch" in text+ assert "captured at max_steps=10" in text+ assert "max_steps `3`" in text+++def test_the_summary_says_when_the_loss_scale_pin_did_not_apply():+ sys.path.insert(0, str(CI_DIR))+ from report import render++ text = "\n".join(+ render(+ {+ "label": "gpu0",+ "model": "m",+ "metrics": [],+ "config": {"max_steps": 3, "init_loss_scale": 2048.0},+ "runs": [+ {+ "run_index": 0,+ "generated": "x",+ "canary_found": True,+ "loss_scale": {+ "applied": False,+ "reason": "trainer.accelerator.scaler is absent",+ },+ }+ ],+ "failures": [],+ }+ )+ )+ assert "did NOT apply" in text and "scaler is absent" in text+++def test_a_plain_text_kernel_log_is_handled_too(tmp_path):+ sys.path.insert(0, str(CI_DIR))+ from report import kernel_log_text++ evidence = tmp_path / "evidence"+ evidence.mkdir()+ (evidence / "kernel.log").write_text("plain text log\n")+ assert kernel_log_text(evidence) == "plain text log\n"+ assert kernel_log_text(tmp_path / "nothing") == ""+++def test_missing_launch_result_is_reported_but_not_red(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 "NOT RUN" in proc.stdout or "did not run" in proc.stdout+++# ------------------------------------------------------- resolved versions+#+# The version canary is worth running only if a red run can be attributed to a+# package. Everything below is that attribution path, checked without a GPU:+# what gets recorded, what a broken pin looks like, and whether the summary a+# reader sees names the difference.+++def test_the_goal_packages_are_the_ones_this_ci_exists_to_watch():+ """The requested list, asserted so a refactor cannot quietly drop one."""+ from versions import GOAL_PACKAGES+ for package in ("trl", "transformers", "accelerate", "peft", "bitsandbytes", "torch", "vllm"):+ assert package in GOAL_PACKAGES, package+++def test_the_packages_the_upgrade_groups_move_are_recorded(tmp_path):+ """Attribution is the only reason the canary exists.++ The frontier leg installs transformers and trl WITH dependencies, and+ legs.py records what that resolution moved: datasets, huggingface_hub, and+ the tokenizers/safetensors ceilings that forced the change. A red leg+ caused by one of them produced a comparison table in which nothing+ differed, because the table only listed the packages the leg NAMES.+ """+ from versions import GOAL_PACKAGES+ for package in ("tokenizers", "safetensors", "huggingface_hub", "datasets"):+ assert package in GOAL_PACKAGES, package+++def test_the_transitive_packages_are_the_ones_the_legs_document_moving():+ """Derived from legs.py rather than a list someone kept in step by hand."""+ legs_source = (CI_DIR / "legs.py").read_text(encoding = "utf-8")+ from versions import GOAL_PACKAGES++ for package in ("tokenizers", "safetensors", "huggingface_hub"):+ assert package in legs_source, (+ f"{package} is in GOAL_PACKAGES but legs.py no longer records a "+ f"resolution moving it"+ )+ assert package in GOAL_PACKAGES+++def test_a_pin_outside_the_goal_list_is_not_reported_as_missing(tmp_path):+ """The lookup is derived from the pin file, not from a fixed table.++ `pin_failures` reads whatever `resolved_versions` was asked about, so a pin+ naming a package the goal list does not carry came back "not installed" for+ a package that is installed and correct: an invented failure on a control+ leg, indistinguishable in the report from a pin that really broke.+ """+ from versions import load_pins, pin_failures, versions_for_pins++ pin_file = tmp_path / "pins.txt"+ # A package certain to be installed wherever this suite runs, and certain+ # not to be in GOAL_PACKAGES.+ import pytest as _pytest++ pin_file.write_text(f"pytest=={_pytest.__version__}\n", encoding = "utf-8")+ pins = load_pins(pin_file)++ from versions import GOAL_PACKAGES, resolved_versions++ assert "pytest" not in GOAL_PACKAGES+ stale = pin_failures(pins, resolved_versions(GOAL_PACKAGES))+ assert (+ stale and "unknown" in stale[0]+ ), "a pin nobody probed must not be reported as a version that differs"++ assert pin_failures(pins, versions_for_pins(pins)) == []+++def test_a_pin_that_really_broke_is_still_a_failure(tmp_path):+ """The widening must not make the check unfailable."""+ from versions import load_pins, pin_failures, versions_for_pins++ pin_file = tmp_path / "pins.txt"+ pin_file.write_text("pytest==0.0.1\n", encoding = "utf-8")+ pins = load_pins(pin_file)+ failures = pin_failures(pins, versions_for_pins(pins))+ assert failures and "was resolved" in failures[0], failures+++def test_a_distribution_whose_name_is_not_its_import_name_is_still_found():+ """`unsloth_zoo` installs as `unsloth-zoo`, and asking for the wrong one+ records "not installed" for a package that is."""+ from versions import _DISTRIBUTION+ assert _DISTRIBUTION["unsloth_zoo"] == "unsloth-zoo"+++def test_a_package_that_is_installed_and_unimportable_is_not_read_as_fine():+ """vLLM on a card its wheel has no kernels for is exactly this state.++ It has a metadata version and raises on import, so a summary printing the+ version alone would call the environment healthy.+ """+ from versions import flatten_versions++ flat = flatten_versions(+ {+ "vllm": {+ "installed": "0.11.2",+ "imported": "IMPORT FAILED: ImportError: libcusparseLt.so.0",+ },+ "torch": {"installed": "2.10.0"},+ }+ )+ assert flat["torch"] == "2.10.0"+ assert "IMPORT FAILED" in flat["vllm"] and "0.11.2" in flat["vllm"]+++def test_a_pin_that_did_not_hold_is_a_failure():+ """A control whose pins were overridden is not a control, and every+ comparison drawn against it is wrong with nothing else showing it."""+ from versions import pin_failures++ resolved = {+ "transformers": {"installed": "5.6.0"},+ "trl": {"installed": "0.24.0"},+ "peft": {"installed": None},+ }+ failures = pin_failures({"transformers": "5.5.0", "trl": "0.24.0", "peft": "0.19.1"}, resolved)+ assert len(failures) == 2+ assert any("5.5.0" in f and "5.6.0" in f for f in failures)+ assert any("peft" in f and "not installed" in f for f in failures)+ assert pin_failures({"trl": "0.24.0"}, resolved) == []+++def test_the_committed_pin_file_parses_and_names_the_canary_set():+ """The pin file and the canary's upgrade list have to be the same set.++ Otherwise the legs differ in a package the control does not pin, so a canary+ failure could come from a version the control never fixed, and the "the only+ difference is the versions" claim goes with it.+ """+ sys.path.insert(0, str(CI_DIR))+ from legs import CANARY_UPGRADES+ from versions import load_pins++ pins = load_pins(SMOKE_DIR / "pins" / "control.txt")+ assert set(pins) == set(CANARY_UPGRADES), (sorted(pins), sorted(CANARY_UPGRADES))+ assert all(v and v[0].isdigit() for v in pins.values()), pins+++def test_a_pin_file_line_that_is_not_a_pin_is_refused(tmp_path):+ """`transformers>=5.5` is not a pin, and silently accepting it would+ make the control leg float without saying so."""+ from versions import load_pins++ path = tmp_path / "pins.txt"+ path.write_text("transformers>=5.5.0\n")+ with pytest.raises(ValueError):+ load_pins(path)+++def test_the_summary_puts_the_two_legs_library_sets_side_by_side():+ """The payoff of the pairing: the bisect is on the summary page."""+ sys.path.insert(0, str(CI_DIR))+ from report import version_table++ lines = version_table(+ [+ {+ "label": "control",+ "environment": {+ "resolved": {"transformers": "5.5.0", "trl": "0.24.0", "torch": "2.10.0"}+ },+ },+ {+ "label": "canary",+ "versions_flat": {"transformers": "5.6.0", "trl": "0.24.0", "torch": "2.10.0"},+ },+ ]+ )+ text = "\n".join(lines)+ assert "**transformers**" in text, text+ assert "Legs differ in: transformers." in text+ # trl and torch agreed, so they must not be advertised as differing.+ assert "**trl**" not in text and "**torch**" not in text+++def test_the_summary_says_so_when_the_legs_agree():+ sys.path.insert(0, str(CI_DIR))+ from report import version_table++ same = {"transformers": "5.5.0"}+ text = "\n".join(+ version_table(+ [+ {"label": "control", "versions_flat": same},+ {"label": "canary", "versions_flat": same},+ ]+ )+ )+ assert "identical across legs" in text+ assert "Legs differ in" not in text+++def test_one_leg_alone_produces_no_comparison_table():+ """A table with one column is not a comparison and reads like one."""+ sys.path.insert(0, str(CI_DIR))+ from report import version_table++ assert version_table([{"label": "control", "versions_flat": {"trl": "0.24.0"}}]) == []+++# ------------------------------------------------------------ the gpt-oss leg+#+# The pass/fail rule for a leg that costs a Kaggle session has to be+# checkable without one.+++class _Args:+ def __init__(self, **kw):+ self.max_steps = 3+ self.require_compile = True+ self.__dict__.update(kw)+++def _gptoss_ok() -> dict:+ """A report shaped like the one the probe actually produced."""+ return {+ "metrics": [+ {"step": 1, "loss": 5.76, "grad_norm": 2.1},+ {"step": 2, "loss": 4.78, "grad_norm": 1.8},+ {"step": 3, "loss": 4.03, "grad_norm": 1.6},+ ],+ "adapter_update": {+ "ok": True,+ "changed": True,+ "tensors": 168,+ "abs_sum_before": 1234.5,+ "abs_sum_after": 1240.25,+ "b_abs_sum_before": 0.0,+ "b_abs_sum_after": 5.75,+ },+ "compile": {+ "available": True,+ "unique_graphs": 32,+ "calls_captured": 779,+ "graph_breaks_total": 2,+ # The delta is what the assertion reads. A reading without one is+ # a reading with no baseline, which is its own failure below.+ "unique_graphs_delta": 30,+ "calls_captured_delta": 700,+ "graph_breaks_total_delta": 2,+ },+ "generated": "analysis... assistantfinal 4",+ # The card reading and the precision it forced, recorded on every run.+ # Not decoration: the float32 assertion is conditioned on+ # `bf16_supported`, so a fixture omitting it leaves this leg's one+ # unique check unexercised by every case below.+ "environment": {"gpu_name": "Tesla T4", "bf16_supported": False},+ "precision": {"fp16": False, "bf16": False, "force_float32_env": "1"},+ # 12.78 GB of 14.56 on one card, nothing dispatched anywhere else. The+ # leg's whole claim, and asserted rather than merely recorded.+ "placement_after_load": {+ "parameters_by_device": {"cuda:0": 20_900_000_000},+ "hf_device_map_devices": None,+ "offloaded": False,+ },+ }+++def test_the_gptoss_leg_passes_on_what_the_probe_measured():+ """The floor under every negative case below."""+ sys.path.insert(0, str(SMOKE_DIR))+ from run_gptoss_t4 import failures_for++ assert failures_for(_gptoss_ok(), _Args()) == []+++def test_a_gptoss_run_that_never_compiled_is_a_failure():+ """The silent fallback this leg exists to catch.++ Zero captured graphs leaves the loss finite, the model saveable and+ generation working, so nothing else in the report moves and the leg would+ report green while covering the eager path only.+ """+ sys.path.insert(0, str(SMOKE_DIR))+ from run_gptoss_t4 import failures_for++ report = _gptoss_ok()+ report["compile"] = {+ "available": True,+ "unique_graphs": 32,+ "calls_captured": 779,+ "graph_breaks_total": 0,+ "unique_graphs_delta": 0,+ }+ failures = failures_for(report, _Args())+ assert any("zero graphs" in f for f in failures), failures+ # And it is a knob, so a future leg can cover something else.+ assert failures_for(report, _Args(require_compile = False)) == []+++def test_a_compile_check_with_no_baseline_is_refused_rather_than_assumed():+ """The pre-training read failed and the post-training one did not.++ No baseline means no subtraction, and the absolute count left behind is the+ LOADER's, nonzero on this leg before training starts, so falling back to it+ passed an entirely eager training path in exactly the case where the two+ cannot be told apart.+ """+ sys.path.insert(0, str(SMOKE_DIR))+ from run_gptoss_t4 import failures_for++ report = _gptoss_ok()+ report["compile"] = {+ "available": True,+ "unique_graphs": 32,+ "calls_captured": 779,+ "graph_breaks_total": 2,+ }+ failures = failures_for(report, _Args())+ assert any("pre-training dynamo counters" in f for f in failures), failures+ assert failures_for(report, _Args(require_compile = False)) == []+++def test_unreadable_compile_counters_are_not_read_as_success():+ sys.path.insert(0, str(SMOKE_DIR))+ from run_gptoss_t4 import failures_for++ report = _gptoss_ok()+ report["compile"] = {"available": False, "error": "AttributeError"}+ assert any("could not be established" in f for f in failures_for(report, _Args()))+++ ("mutate", "expected"),+ [+ (lambda r: r.update(generated = " "), "unusable"),+ (lambda r: r.update(generated = None), "did not run"),+ (lambda r: r.update(metrics = r["metrics"][:1]), "logged steps"),+ (+ lambda r: r.update(+ metrics = [+ {"step": 1, "loss": float("nan")},+ {"step": 2, "loss": 1.0},+ {"step": 3, "loss": 1.0},+ ]+ ),+ "non-finite",+ ),+ ],+)+def test_the_other_gptoss_assertions_fire(mutate, expected):+ sys.path.insert(0, str(SMOKE_DIR))+ from run_gptoss_t4 import failures_for++ report = _gptoss_ok()+ mutate(report)+ assert any(expected in f for f in failures_for(report, _Args())), report+++# --------------------------------------------------------------- the GRPO leg+#+# With num_iterations=1 and beta=0 the TRL GRPO loss is zero by construction on+# a HEALTHY run, so nothing here may assert on it. reward_std is the instrument:+# zero across a group means every completion scored the same, the advantage is+# exactly zero, and the run trained on nothing while reporting an ordinary loss.+++class _GrpoArgs:+ max_steps = 2+++def _grpo_ok() -> dict:+ return {+ "log_history": [+ {"step": 1, "reward": 1.4, "reward_std": 0.35},+ {"step": 2, "reward": 1.6, "reward_std": 0.21},+ ],+ "metrics": [+ {"step": 1, "loss": 0.0, "grad_norm": 0.9},+ {"step": 2, "loss": 0.0, "grad_norm": 0.7},+ ],+ "adapter_update": {+ "ok": True,+ "changed": True,+ "tensors": 196,+ "abs_sum_before": 900.0,+ "abs_sum_after": 902.5,+ "b_abs_sum_before": 0.0,+ "b_abs_sum_after": 2.5,+ },+ "completions": [["forty two", "42", "about 42", "no idea"]],+ "fast_generate": "the square root of 101 is about 10.05",+ }+++def test_the_grpo_leg_passes_a_healthy_run_whose_loss_is_zero():+ """Loss 0.0 on every step is the HEALTHY case here, not a failure."""+ sys.path.insert(0, str(SMOKE_DIR))+ from run_grpo_t4 import failures_for++ assert failures_for(_grpo_ok(), _GrpoArgs()) == []+++def test_a_group_with_no_reward_spread_is_the_failure_that_matters():+ """reward_std == 0 across every step: identical completions.++ The GRPO advantage is exactly zero in that state, so the optimizer applies+ nothing while the loss, the step count and the adapter all look ordinary. It+ is the one bug on this path nothing else would show.+ """+ sys.path.insert(0, str(SMOKE_DIR))+ from run_grpo_t4 import failures_for++ report = _grpo_ok()+ for entry in report["log_history"]:+ entry["reward_std"] = 0.0+ failures = failures_for(report, _GrpoArgs())+ assert any("zero on every step" in f for f in failures), failures+ # One step with spread is enough: a single degenerate group is normal.+ report["log_history"][0]["reward_std"] = 0.4+ assert failures_for(report, _GrpoArgs()) == []+++def test_completions_that_are_all_empty_are_caught_even_when_rewards_agree():+ """N empty strings score identically, so the reward checks alone would+ call an engine that produced nothing a clean run."""+ sys.path.insert(0, str(SMOKE_DIR))+ from run_grpo_t4 import failures_for++ report = _grpo_ok()+ report["completions"] = [["", "", "", ""]]+ assert any(+ "every one of the 4 completions was empty" in f for f in failures_for(report, _GrpoArgs())+ )+++ ("mutate", "expected"),+ [+ (lambda r: r.update(log_history = [{"step": 1}]), "no reward was logged"),+ (lambda r: [e.pop("reward_std") for e in r["log_history"]], "never logged"),+ (lambda r: r.update(fast_generate = None, fast_generate_error = "boom"), "fast_generate"),+ (lambda r: r.update(metrics = []), "logged steps"),+ ],+)+def test_the_other_grpo_assertions_fire(mutate, expected):+ sys.path.insert(0, str(SMOKE_DIR))+ from run_grpo_t4 import failures_for++ report = _grpo_ok()+ mutate(report)+ assert any(expected in f for f in failures_for(report, _GrpoArgs())), report+++def test_probe_mode_reports_rather_than_judges():+ """A feasibility probe must come back with evidence, not an exit code.++ Both new payloads take --probe, and it must move failures into+ `observed_failures` rather than suppress them: a probe that hid what it+ found would be worse than no probe.+ """+ import ast+ for name in ("run_gptoss_t4.py", "run_grpo_t4.py"):+ tree = ast.parse((SMOKE_DIR / name).read_text(encoding = "utf-8"))+ source = (SMOKE_DIR / name).read_text(encoding = "utf-8")+ assert 'report["observed_failures"] = failures' in source, name+ assert "--probe" in source, name+ assert any(+ isinstance(n, ast.FunctionDef) and n.name == "failures_for" for n in ast.walk(tree)+ ), name+++# ------------------------------------------------------ the multi-kernel launch+++def test_the_launcher_takes_one_notebook_per_kernel():+ """A run is two kernels, pushed before either is waited on: waiting between+ pushes serialises two sessions Kaggle runs happily in parallel and puts an+ hour between the control leg and the canary leg."""+ import inspect++ import launch++ source = inspect.getsource(launch.main)+ assert 'action = "append"' in source+ # Pushes first, waits second, asserted on order of appearance because+ # getting it wrong doubles the wall clock without any run looking wrong.+ assert source.index("pushed = push(") < source.index('entry["state"] = wait(')+++def test_the_reports_of_every_kernel_are_gathered(tmp_path):+ """Each kernel collects into its own directory so two cannot overwrite+ each other's kernel.log; the extraction has to walk into them."""+ import launch++ (tmp_path / "k1").mkdir()+ (tmp_path / "k2").mkdir()+ (tmp_path / "k1" / "kernel.log").write_text(+ 'T4_SMOKE_REPORT {"label": "control", "model": "m", "passed": true}\n'+ )+ (tmp_path / "k2" / "kernel.log").write_text(+ 'T4_SMOKE_REPORT {"label": "grpo", "model": "q", "passed": false}\n'+ )+ reports = launch.extract_reports(tmp_path)+ assert sorted(r["label"] for r in reports) == ["control", "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 not+ evidence of a regression."""+ sys.path.insert(0, str(CI_DIR))+ evidence = tmp_path / "evidence"+ evidence.mkdir()+ (evidence / "launch_result.json").write_text(+ json.dumps(+ {+ "verdict": "partial",+ "reason": "only 2 of 4 payload(s) reported back",+ "kernels": [+ {"notebook": "kernel1.ipynb", "slug": "u/a", "state": "COMPLETE"},+ {+ "notebook": "kernel2.ipynb",+ "slug": None,+ "push_error": "at_capacity: session count of 2 reached",+ },+ ],+ "reports": [],+ }+ )+ )+ proc = subprocess.run(+ [sys.executable, str(CI_DIR / "report.py"), "--evidence", str(evidence), "--expect", "4"],+ capture_output = True,+ text = True,+ )+ assert proc.returncode == 0+ assert "was never pushed" in proc.stdout+ assert "at_capacity" in proc.stdout+++# ------------------------------------------------- the libcuda link shim+#+# flashinfer 0.6.6 JIT-compiles its sampling ops on first use. Two real T4+# sessions (unsloth-t4-ci-e2d9ce9b, -916d5986) both compiled all three .cu+# files CLEANLY for sm_75 and then died at the link:+#+# /usr/bin/ld: cannot find -lcuda+#+# The image has no `libcuda.so`, only the versioned `libcuda.so.1`, which the+# linker will not resolve `-lcuda` against, and nothing about that is Turing.+# `VLLM_USE_FLASHINFER_SAMPLER=0` was tried first and the second session failed+# identically, which is the useful part: switching off one consumer of the JIT+# is whack-a-mole, while making `-lcuda` resolvable fixes every op at once.+++def _grpo_module():+ import importlib.util++ spec = importlib.util.spec_from_file_location(+ "run_grpo_t4_under_test", SMOKE_DIR / "run_grpo_t4.py"+ )+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def test_the_shim_does_nothing_when_the_stub_is_already_there(monkeypatch):+ """Most images ship it. Touching LIBRARY_PATH anyway would be a change+ with no reason, on a machine that was already fine."""+ grpo = _grpo_module()+ monkeypatch.setattr(grpo.os.path, "exists", lambda p: "lib64" in str(p))+ monkeypatch.delenv("LIBRARY_PATH", raising = False)+ facts = grpo.make_libcuda_linkable()+ assert facts["needed"] is False and facts["applied"] is False+ assert "LIBRARY_PATH" not in grpo.os.environ+++def test_the_shim_builds_a_link_when_the_stub_is_missing(monkeypatch, tmp_path):+ """The measured Kaggle case."""+ grpo = _grpo_module()+ driver = tmp_path / "libcuda.so.1"+ driver.write_bytes(b"")++ real_exists = grpo.os.path.exists++ def exists(path):+ if "stubs" in str(path) or "compat" in str(path):+ return False+ return real_exists(path)++ monkeypatch.setattr(grpo.os.path, "exists", exists)+ monkeypatch.setenv("TMPDIR", str(tmp_path))+ monkeypatch.delenv("LIBRARY_PATH", raising = False)++ class Done:+ stdout = f"\tlibcuda.so.1 (libc6,x86-64) => {driver}\n"++ import subprocess as _sp++ monkeypatch.setattr(_sp, "run", lambda *a, **k: Done())++ facts = grpo.make_libcuda_linkable()+ assert facts["needed"] is True and facts["applied"] is True, facts+ from pathlib import Path as _P++ link = _P(facts["shim"]) / "libcuda.so"+ assert link.is_symlink() and link.resolve() == driver.resolve()+ assert facts["shim"] in grpo.os.environ["LIBRARY_PATH"]+++def test_the_shim_keeps_an_existing_library_path(monkeypatch, tmp_path):+ """Clobbering it would break whatever set it."""+ grpo = _grpo_module()+ driver = tmp_path / "libcuda.so.1"+ driver.write_bytes(b"")+ real_exists = grpo.os.path.exists+ monkeypatch.setattr(+ grpo.os.path,+ "exists",+ lambda p: False if ("stubs" in str(p) or "compat" in str(p)) else real_exists(p),+ )+ monkeypatch.setenv("TMPDIR", str(tmp_path))+ monkeypatch.setenv("LIBRARY_PATH", "/somewhere/else")++ class Done:+ stdout = f"\tlibcuda.so.1 (libc6,x86-64) => {driver}\n"++ import subprocess as _sp++ monkeypatch.setattr(_sp, "run", lambda *a, **k: Done())++ grpo.make_libcuda_linkable()+ assert grpo.os.environ["LIBRARY_PATH"].endswith("/somewhere/else")+++def test_the_shim_reports_rather_than_raises_when_there_is_no_driver(monkeypatch, tmp_path):+ """A machine with no driver at all is not a machine this can fix, and a+ payload that dies here would report nothing about GRPO."""+ grpo = _grpo_module()+ monkeypatch.setattr(grpo.os.path, "exists", lambda p: False)+ monkeypatch.setenv("TMPDIR", str(tmp_path))++ class Done:+ stdout = ""++ import subprocess as _sp++ monkeypatch.setattr(_sp, "run", lambda *a, **k: Done())+ monkeypatch.setattr("ctypes.util.find_library", lambda name: None)++ facts = grpo.make_libcuda_linkable()+ assert facts["applied"] is False+ assert "error" in facts+++def test_the_payload_applies_the_shim_before_it_touches_vllm():+ """Ordering is the whole point: flashinfer JITs on first use, and the+ first use is inside the engine build."""+ source = (SMOKE_DIR / "run_grpo_t4.py").read_text(encoding = "utf-8")+ applied = source.index("make_libcuda_linkable()")+ built = source.index('report["vllm"] = vllm_facts()')+ assert applied < built+++def test_what_the_shim_did_reaches_the_report():+ """Otherwise a future green run cannot be told from one that never needed+ it, and the next person re-derives all of this."""+ source = (SMOKE_DIR / "run_grpo_t4.py").read_text(encoding = "utf-8")+ assert 'report["libcuda_shim"] = libcuda' in source+++def test_the_traceback_keeps_its_head_as_well_as_its_tail():+ """The last probe's 6000-char tail was entirely ninja's own output, so the+ Python frames naming the caller were exactly what got dropped."""+ source = (SMOKE_DIR / "run_grpo_t4.py").read_text(encoding = "utf-8")+ assert "middle elided" in source+++def test_a_libcuda_the_linker_will_not_search_for_does_not_count(monkeypatch, tmp_path):+ """The bug this check was rewritten for.++ Kernel unsloth-t4-ci-d0d480b6: an earlier version accepted+ /usr/local/cuda/compat, found libcuda.so there, reported `already_linkable`+ and did nothing, and the link failed anyway because compat is not among the+ -L directories flashinfer passes.+ """+ grpo = _grpo_module()+ real_exists = grpo.os.path.exists++ def exists(path):+ path = str(path)+ if "compat" in path:+ return True # present, and useless as a -L target+ if "lib64" in path:+ return False # the dirs that ARE searched have nothing+ return real_exists(path)++ monkeypatch.setattr(grpo.os.path, "exists", exists)+ monkeypatch.setenv("TMPDIR", str(tmp_path))+ monkeypatch.delenv("LIBRARY_PATH", raising = False)++ class Done:+ stdout = ""++ import subprocess as _sp++ monkeypatch.setattr(_sp, "run", lambda *a, **k: Done())+ monkeypatch.setattr("ctypes.util.find_library", lambda name: None)++ facts = grpo.make_libcuda_linkable()+ assert facts["needed"] is True, facts+ assert "already_linkable" not in facts+ # compat is a fine symlink TARGET even though it is a useless -L dir.+ assert facts["applied"] is True and "compat" in facts["real"], facts+++def test_the_searched_directories_are_the_ones_flashinfer_passes():+ """Pinned, because widening this list is exactly how the check went wrong.+ These two are what appear as -L on the failing ninja line."""+ source = (SMOKE_DIR / "run_grpo_t4.py").read_text(encoding = "utf-8")+ assert '"/usr/local/cuda/lib64", "/usr/local/cuda/lib64/stubs"' in source+++def test_the_grpo_payload_gives_a_base_model_a_chat_template():+ """`unsloth/Qwen3-4B-Base` ships none, and TRL raises on the first step.++ Kernel unsloth-t4-ci-27b0dc2e is the first probe that got far enough to find+ it: the vLLM engine had built, memory was 11.36GB of 14.56, and the trainer+ was inside `_run_epoch` when `maybe_apply_chat_template` raised++ ValueError: Cannot use chat template functions because+ tokenizer.chat_template is not set++ The base model is the right choice and is not what to change; GRPO on an+ instruct model measures the instruct tuning as much as the run.+ """+ source = (SMOKE_DIR / "run_grpo_t4.py").read_text(encoding = "utf-8")+ assert "tokenizer.chat_template = (" in source+ assert 'if not getattr(tokenizer, "chat_template", None):' in source+ # And the report has to say which of the two worlds the run was in.+ assert 'result["chat_template"]' in source+++def test_the_chat_template_the_payload_installs_actually_renders():+ """A template that does not render trades a failure at step 1 for a+ failure at step 1 with a longer traceback."""+ import re++ jinja2 = pytest.importorskip("jinja2")+ source = (SMOKE_DIR / "run_grpo_t4.py").read_text(encoding = "utf-8")+ block = source[source.index("tokenizer.chat_template = (") :]+ block = block[: block.index("\n )")]+ literal = "".join(re.findall(r'"((?:[^"\\]|\\.)*)"', block))+ template = literal.encode().decode("unicode_escape")++ rendered = jinja2.Template(template).render(+ messages = [{"role": "system", "content": "S"}, {"role": "user", "content": "U"}],+ add_generation_prompt = True,+ )+ assert rendered.startswith("<|im_start|>system\nS<|im_end|>")+ assert rendered.endswith("<|im_start|>assistant\n")+ # Both roles must survive; a template that drops the user turn would train+ # on prompts the model never saw.+ assert "<|im_start|>user\nU<|im_end|>" in rendered+++# The `frontier` leg exists because the canary's "newest" is not PyPI's newest.+# unsloth_zoo/pyproject.toml pins transformers <=5.5.0 and trl <=0.24.0 and the+# canary resolves WITH zoo, so it obeys that cap: measured on 2026-08-11 it sat+# at transformers 5.5.0 against a PyPI latest of 5.15.0 and trl 0.24.0 against+# 1.9.2, while moving peft and accelerate to genuine latest. Two of five packages+# never moved, which made the leg look like it was working. Without `frontier`+# this CI cannot detect a transformers 5.6+ or trl 1.x regression, never+# installing one.+++def test_the_frontier_leg_resolves_dependencies_rather_than_skipping_them():+ """--no-deps is what the first probe got wrong, and it must not come back.++ `--no-deps transformers trl` plus a blanket `--upgrade tokenizers` reached+ transformers 5.15.0 and trl 1.9.2 (kernel unsloth-t4-ci-bd0c49e5) and then+ died before running anything, an unbounded upgrade overshooting the ceiling+ transformers declares:++ tokenizers<=0.23.0,>=0.22.0 is required, but found tokenizers==0.23.1+ safetensors>=0.8.0 is required, but found safetensors==0.7.0++ Letting pip resolve the dependencies fixes both AND still clears zoo's cap,+ because pip enforces only the requirements of packages in the resolution.+ """+ sys.path.insert(0, str(CI_DIR))+ import legs++ frontier = legs.LEGS["frontier"]+ upgrades = [group for group in frontier.install if "--upgrade" in group]+ assert upgrades, "the frontier leg no longer upgrades anything"+ for group in upgrades:+ assert "--no-deps" not in group, (+ f"the frontier leg upgrade {group!r} skips dependency resolution; "+ f"that is what left tokenizers above the ceiling transformers "+ f"declares and killed the leg before it ran a single step"+ )+ upgraded = {arg for group in upgrades for arg in group if not arg.startswith("-")}+ assert {"transformers", "trl"} <= upgraded, (+ f"the frontier leg upgrades {sorted(upgraded)}, and the two packages it "+ f"exists for are transformers and trl"+ )+++def test_the_frontier_leg_does_not_carry_the_zoo_requirement():+ """Naming unsloth_zoo in the same resolution reimposes the cap it evades.++ That is exactly how the canary differs, and it is right to: it measures the+ supported window. The frontier leg measures past it, and a stray `ZOO` in+ the upgrade group would silently turn one into the other while every other+ assertion here still passed.+ """+ sys.path.insert(0, str(CI_DIR))+ import legs++ for group in legs.LEGS["frontier"].install:+ if "--upgrade" not in group:+ continue+ assert not any("unsloth-zoo" in arg or "unsloth_zoo" in arg for arg in group), (+ "the frontier leg upgrades unsloth_zoo in the same resolution as "+ "transformers and trl, so zoo's transformers<=5.5.0 and trl<=0.24.0 "+ "bind again and the leg silently becomes a second canary"+ )+++def test_the_frontier_leg_is_wired_on_the_seat_that_costs_nothing():+ """A Kaggle session bills wall clock once, not per card.++ So the second kernel's idle T4 is free capacity and testing the newest+ transformers and trl every run costs no quota. It passed there on real+ hardware: transformers 5.15.0, trl 1.9.2, ten steps, canary emitted, two+ fresh processes agreeing bitwise.+ """+ sys.path.insert(0, str(CI_DIR))+ import legs++ wired = [kernel for kernel in legs.KERNELS if "frontier" in kernel]+ assert len(wired) == 1, f"frontier appears in {len(wired)} kernels, expected 1"+ assert len(wired[0]) == legs.MAX_LEGS_PER_KERNEL, (+ "frontier should share a kernel rather than take one of its own, since "+ "a second seat in an existing session is free and a new session is not"+ )+ assert "frontier" not in legs.UNWIRED+++def test_the_pinned_kaggle_client_carries_the_calls_this_workflow_makes():+ """The pin is load bearing, and 1.7.4.5 could not do the job at all.++ Three things this workflow depends on are absent from older clients, and+ each fails quietly rather than loudly:++ * `authenticate()` on 1.7.4.5 refuses `KAGGLE_API_TOKEN`, the only+ credential this workflow has, and demands a kaggle.json nothing writes.+ * `kaggle kernels delete` landed in 1.7.5.0 (Kaggle/kaggle-cli#762), first+ released in 1.8.0; before it, argparse answers the release path with+ `invalid choice: 'delete'` and exit 2.+ * `quota_view()`, which gate.py reads remaining accelerator hours from,+ exists only on 2.x; below it the call raises AttributeError into a handler+ that records "quota unreadable" and lets the run proceed.++ Pinned exactly, and the same version in every job that installs it.+ """+ packaging_version = pytest.importorskip("packaging.version")+ text = WORKFLOW.read_text(encoding = "utf-8")+ pins = re.findall(r"pip install [^\n]*'kaggle==([0-9][^']*)'", text)+ assert pins, "no pinned kaggle client in the workflow"+ assert len(set(pins)) == 1, f"jobs disagree on the kaggle client: {pins}"+ assert packaging_version.Version(pins[0]) >= packaging_version.Version("2.2.0"), pins[0]++[email protected](shutil.which("bash") is None, reason = "the step is a bash script")+def test_a_dispatched_commit_is_proven_to_exist_before_the_quota_is_spent(tmp_path):+ """A 40-character SHA was accepted on shape alone.++ Nothing asked whether unslothai/unsloth HAS that commit, so a mistyped (or+ force-pushed away, or fork-only) SHA pushed the paid kernels, every+ payload's `pip install git+...` failed on it, and the import probes reported+ the pull request RED for a commit that never existed, which is the outcome+ stand_down exists for, quota and all.++ `git ls-remote` cannot answer it, matching refs and exiting 0 with empty+ output for any SHA, so the check is a `git fetch` of the object, the same+ reachability pip needs to install it.+ """+ steps = _workflow()["jobs"]["t4-smoke"]["steps"]+ script = next(s for s in steps if s.get("id") == "ref")["run"]++ def drive(+ unsloth_ref,+ ls_remote,+ fetch_exit = 0,+ ):+ work = tmp_path / f"case{abs(hash((unsloth_ref, ls_remote, fetch_exit)))}"+ stub = work / "bin"+ stub.mkdir(parents = True)+ # `git` answers ls-remote from LS_OUT and fetch from GIT_FETCH_EXIT,+ # and records every fetch so the check cannot be a no-op that passes.+ (stub / "git").write_text(+ "#!/bin/sh\n"+ 'case "$1" in\n'+ ' ls-remote) printf "%s" "$LS_OUT" ;;\n'+ ' fetch) shift; echo "$*" >> "$FETCH_LOG"; exit "$GIT_FETCH_EXIT" ;;\n'+ " *) exit 0 ;;\n"+ "esac\n"+ )+ (stub / "sleep").write_text("#!/bin/sh\nexit 0\n")+ for name in ("git", "sleep"):+ (stub / name).chmod(0o755)+ out = work / "github_output"+ out.write_text("", encoding = "utf-8")+ log = work / "fetches"+ log.write_text("", encoding = "utf-8")+ env = dict(+ os.environ,+ PATH = f"{stub}:{os.environ['PATH']}",+ GITHUB_OUTPUT = str(out),+ UNSLOTH_REF = unsloth_ref,+ HEAD_SHA = "headsha",+ LS_OUT = ls_remote,+ GIT_FETCH_EXIT = str(fetch_exit),+ FETCH_LOG = str(log),+ )+ done = subprocess.run(["bash", "-c", script], env = env, capture_output = True, text = True)+ assert done.returncode == 0, done.stderr+ written = dict(line.split("=", 1) for line in out.read_text().splitlines() if "=" in line)+ return written, log.read_text(encoding = "utf-8")++ sha = "a" * 40+ # A commit GitHub does not serve stands the run down instead of paying+ # for four kernels that cannot install it.+ written, fetched = drive(sha, "", fetch_exit = 128)+ assert written == {"stand_down": "true"}+ assert sha in fetched, "the SHA was accepted without asking GitHub for it"++ # One that it does serve is pinned exactly as before.+ written, fetched = drive(sha, "")+ assert written == {"ref": sha}+ assert sha in fetched++ # The check is not limited to the shape the form supplied: a branch that+ # ls-remote resolved is proven installable too.+ branch_sha = "b" * 40+ written, fetched = drive("main", f"{branch_sha}\trefs/heads/main\n", fetch_exit = 128)+ assert written == {"stand_down": "true"}+ assert branch_sha in fetched++ # And nothing is fetched on the path that spends no dispatch input.+ written, fetched = drive("", "")+ assert written == {"ref": "headsha"}+ assert fetched.strip() == ""