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
Pack the Kaggle T4 legs into one kernel so Studio can use the other session (#9538)
Daniel Han720e17b296bd
diff --git a/.github/scripts/kaggle_t4_ci/BUDGET.md b/.github/scripts/kaggle_t4_ci/BUDGET.mdindex 8400fc23ecc..830147fce46 100644--- a/.github/scripts/kaggle_t4_ci/BUDGET.md+++ b/.github/scripts/kaggle_t4_ci/BUDGET.md@@ -61,17 +61,44 @@ documented baseline is 30h; the surplus is a discretionary "floating"allowance that can be withdrawn, so treat 30h as the number that isguaranteed. 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):+Measured per-leg durations, on run `32607621452`:-| kernel | wall clock |+| leg | duration ||---|---|-| kernel 1 (control + canary) | 0.10 h |-| kernel 2 (gptoss + frontier) | 0.13 h |-| **one invocation** | **~0.25 h** |+| gptoss | 384.1 s |+| frontier | 312.2 s |+| canary | 265.3 s |+| control | 262.2 s |-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.+All four now ride in ONE kernel, two at a time, one worker per card taking its+next leg when the previous one exits. Packed longest-first that is+384.1 + 262.2 = 646.3 s on one card against 312.2 + 265.3 = 577.5 s on the+other, so:++| kernel | wall clock |+|---|---|+| one kernel, four legs | 0.18 h |+| **one invocation** | **~0.25 h** (envelope, see below) |++A session bills its wall clock once, not per card. That used to mean the second+T4 of each of two kernels was free, and it is why `frontier` was described as+costing nothing to carry. With one kernel it means something narrower: the two+cards are free relative to each other while both are busy, and the 68.8 s tail+where only one card still has work costs no more than the rest of the session.++**This shape is not a quota optimisation.** Two kernels of two legs measured+0.10 h + 0.13 h = 0.23 h against 0.18 h here, which is within the rounding.+What two kernels cost was the whole ACCOUNT: they took both of Kaggle's+concurrent sessions, so `kaggle-t4-studio-gpu-ci.yml`, which shares this+account, could not push at all and queued behind the entire notebook job+(measured: Studio run `32607617804` waited ~40 minutes on notebook run+`32607621452`). One kernel leaves the second session for Studio, and the two+workflows now hold separate GitHub concurrency groups so they can use it.++The **~0.25 h** envelope below is deliberately NOT lowered to the measured+0.18 h. Every figure in this document is derived from it, and the real cost+moved down, so it remains a true upper bound; re-deriving the whole budget to+book a 0.07 h saving would only make the reserve thinner.## The sampling rate@@ -101,18 +128,23 @@ 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 orCI 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+The worst case, if every sampled launch ran to the kernel ceiling, is farabove 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 pollingdeadline, `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.+filed), and this workflow pushes ONE session, billing its wall clock once. So+1 x 13800s = 3.8 GPU-h, set to 4.++It was `2 x 13800s = 7.7 GPU-h, set to 8` while the legs travelled as two+kernels. The multiplier is how many sessions THIS invocation pushes, not+Kaggle's per-account cap of 2: the other slot may be Studio's, and Studio+reserves against its own budget rather than this one.`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.+from `launch.py` and `--kernels`; do not edit the number here or in the+workflow without changing what it is derived from.## What would change these numbersdiff --git a/.github/scripts/kaggle_t4_ci/build_kernel.py b/.github/scripts/kaggle_t4_ci/build_kernel.pyindex 31194cc21f8..9bc646266e9 100644--- a/.github/scripts/kaggle_t4_ci/build_kernel.py+++ b/.github/scripts/kaggle_t4_ci/build_kernel.py@@ -68,6 +68,11 @@ RESULT_PREFIX = "T4_SMOKE_REPORT "# payload empty a file the other is importing.KERNEL_ROOT = "/kaggle/working/t4_smoke_src"+# A Kaggle GPU session is 2xT4. This is the width the packing is built for and+# what the kernel stands down against when the allocation is short; it is not+# a count of legs, which is now larger than it on purpose.+SESSION_GPUS = 2+def _kernel_root(leg: Leg) -> str:return f"{KERNEL_ROOT}_{leg.name}"@@ -488,16 +493,29 @@ def build_driver(payloads: dict[str, dict],per_run_timeout: int,isolation: dict[str, bool] | None = None,+ expected_gpus: int = SESSION_GPUS,) -> dict:- """Kernel notebook that fans the payloads out one per GPU.+ """Kernel notebook that runs the payloads across the session's GPUs.``isolation`` maps a payload to whether its virtualenv may see the Kaggleimage's site-packages. Per payload, not per kernel, because legs sharing akernel do not share an answer: see ``Leg.system_site_packages``.++ ``payloads`` may hold MORE entries than there are cards. They queue: one+ worker per card takes the next leg only when its current one has exited, so+ a card carries exactly one payload at a time. ``payloads`` is ordered, and+ that order is the start order -- longest leg first, since the longest leg+ is what sets the makespan and a greedy scheduler cannot balance around one+ it picks up last.++ ``expected_gpus`` is how many cards the packing was built for. It is what+ the kernel stands down against, and it is deliberately NOT ``len(payloads)``+ any more: see the guard in the generated cell."""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}+ order = list(payloads)setup = f"""import base64, gzip, json, os, pathlib, subprocess, sys, threading, timeprint("{DRIVER_SENTINEL} start", flush=True)@@ -526,19 +544,35 @@ except Exception:GPUS = []print("{DRIVER_SENTINEL}_GPUS " + json.dumps(GPUS), flush=True)N_GPU = len(GPUS)+# The order payloads are STARTED in, longest expected leg first. Not+# `sorted(PAYLOADS)`: alphabetical puts the longest leg (gptoss) last, and a+# greedy scheduler that picks up the longest leg last cannot balance around+# it -- it is the leg that sets the makespan. Declaration order comes from+# legs.KERNELS, so the packing decision lives beside the legs it packs.+ORDER = {order!r}+# 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):+#+# Compared against EXPECTED_GPUS, not against the payload count. There are now+# more payloads than cards ON PURPOSE -- they queue, one card at a time -- so+# `N_GPU < len(PAYLOADS)` would stand down every healthy run. What still has to+# be caught is the allocation that hands us fewer CARDS than the packing was+# built for, which silently serialises the whole kernel onto device 0 and+# doubles its wall clock while looking like a slow but healthy run.+EXPECTED_GPUS = {expected_gpus}+if N_GPU < EXPECTED_GPUS:print("{DRIVER_SENTINEL}_INFRA " + json.dumps(- {{"reason": "gpu_shortfall", "gpus": N_GPU, "payloads": len(PAYLOADS)}}),+ {{"reason": "gpu_shortfall", "gpus": N_GPU, "payloads": len(PAYLOADS),+ "expected_gpus": EXPECTED_GPUS}}),flush=True)raise SystemExit(- f"{{len(PAYLOADS)}} payload(s) need one T4 each; the allocation "- f"exposed {{N_GPU}}")+ f"this kernel packs {{len(PAYLOADS)}} payload(s) across "+ f"{{EXPECTED_GPUS}} T4(s); the allocation exposed {{N_GPU}}")for name, blob in PAYLOADS.items():(WORK / name).write_bytes(gzip.decompress(base64.b64decode(blob)))@@ -636,16 +670,73 @@ def run_one(name, gpu_index, idx):"seconds": round(time.time() - started, 1),"error": err, "kernel": kernel,"output_exists": out.exists()}}+ # Drop this leg's venv NOW, not in the tail cell. The tail prunes venv_*+ # only after every payload has finished, which was fine when a kernel held+ # one payload per card and they all ran at once. Packed, that would leave+ # every leg's tree on /kaggle/working simultaneously -- each one carries+ # its own torch and its own NVIDIA runtime -- and the disk is not sized for+ # that. Freeing here bounds the live count to one per card, which is what+ # it was before the packing. The papermill output notebook and the child+ # log are the evidence and they are NOT touched.+ try:+ import shutil as _sh+ _sh.rmtree(WORK / f"venv_{{idx}}", ignore_errors=True)+ except Exception:+ passprint(f"{DRIVER_SENTINEL}_DONE " + json.dumps({{name: results[name]}}),flush=True)-names = sorted(PAYLOADS)+# One worker per CARD, each pulling the next leg off a shared queue, rather+# than one thread per PAYLOAD. With more payloads than cards the old+# `gpu_index = i % N_GPU` handed the same card to two payloads and started+# them both at once: each child still passed its own single-visible-GPU+# assertion, and the two of them then fought over 15GB of VRAM. A queue makes+# a card take its next leg only once the previous one has exited, so a card+# holds exactly one payload at any instant no matter how many are packed.+#+# The index passed as `idx` is the payload's position in ORDER, not the+# worker's: it names the venv (venv_{{idx}}) and the ipykernel spec+# (t4ci{{idx}}), which must stay distinct per PAYLOAD or two legs would share+# an interpreter and the differing library sets this whole file exists to keep+# apart would land in one tree.+_queue = list(enumerate(ORDER))+# Each card's FIRST leg is assigned here, by position, and not raced for. A+# plain shared queue looked equivalent and was not: with payloads that finish+# quickly -- stubs, or an install that dies in seconds -- card 0 could claim,+# run and finish a leg before card 1 had cleared its start stagger, and a+# two-leg kernel then ran BOTH legs on device 0. That is the silent+# serialisation the shortfall guard exists to catch, arriving by a route the+# guard cannot see. Seeding makes "one leg per card while there are legs to go+# round" a property of the assignment rather than of how fast the legs happen+# to run.+SEEDS = _queue[:N_GPU]+pending = _queue[N_GPU:]+pending_lock = threading.Lock()++def worker(gpu_index, seed):+ if seed is not None:+ # The 5s stagger the per-payload threads used to get from the start+ # loop, kept for the same reason: two `uv venv` creations in the same+ # instant contend on the same package cache. Only the first leg on a+ # card needs it; later ones are already separated by however long the+ # previous leg ran.+ if gpu_index:+ time.sleep(5 * gpu_index)+ idx, name = seed+ run_one(name, gpu_index, idx)+ while True:+ with pending_lock:+ if not pending:+ return+ idx, name = pending.pop(0)+ run_one(name, gpu_index, idx)+threads = []-for i, name in enumerate(names):- t = threading.Thread(target=run_one, args=(name, i % N_GPU, i), daemon=False)+for gpu_index in range(N_GPU):+ seed = SEEDS[gpu_index] if gpu_index < len(SEEDS) else None+ t = threading.Thread(target=worker, args=(gpu_index, seed), daemon=False)t.start()threads.append(t)- time.sleep(5)for t in threads:t.join()@@ -725,7 +816,15 @@ def build_kernel(reference = "" if skip_reference else None,)isolation[name] = leg.system_site_packages- return build_driver(payloads, per_run_timeout, isolation)+ # min(), so a one-leg kernel (a --legs dispatch, or a debugging run) still+ # stands down only on a genuinely empty allocation rather than demanding a+ # second card it will never use.+ return build_driver(+ payloads,+ per_run_timeout,+ isolation,+ expected_gpus = min(len(payloads), SESSION_GPUS),+ )def main() -> int:diff --git a/.github/scripts/kaggle_t4_ci/gate.py b/.github/scripts/kaggle_t4_ci/gate.pyindex 739f265bf7a..849d1a30149 100644--- a/.github/scripts/kaggle_t4_ci/gate.py+++ b/.github/scripts/kaggle_t4_ci/gate.py@@ -95,20 +95,30 @@ MAX_CONCURRENT_GPU_KERNELS = 2# 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.+# How many of Kaggle's slots one invocation takes. ONE, and it is the default+# rather than a per-workflow override because it is now true of both callers.+#+# This was 2 while the notebook leg ran four legs as two kernels of two, one leg+# per T4. That shape took BOTH of the account's slots, which had two costs. The+# account is shared with human use, so a run held every seat there was. And+# kaggle-t4-studio-gpu-ci.yml is on the same account: with no slot left it could+# not push at all, and the shared concurrency group meant it did not even try+# until the notebook job had finished (measured: Studio's run 32607617804 queued+# about 40 minutes behind notebook run 32607621452).+#+# The legs did not have to be split to fit. They now queue INSIDE one kernel --+# one worker per card, a card taking its next leg when the previous one exits --+# so four legs fit in one session. That is strictly better for the thing the old+# comment here worried about: it said legs "split across two sessions would be+# compared across two images and two hours, and for control/canary that+# comparison is the entire instrument", and one kernel makes such a split+# impossible rather than merely avoided by careful pairing.## 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+KERNELS_PER_INVOCATION = 1# Kernel states that mean a session is occupying one of those slots.BUSY_STATES = {"QUEUED", "RUNNING"}diff --git a/.github/scripts/kaggle_t4_ci/legs.py b/.github/scripts/kaggle_t4_ci/legs.pyindex 938777a9189..995d3ad9ff2 100644--- a/.github/scripts/kaggle_t4_ci/legs.py+++ b/.github/scripts/kaggle_t4_ci/legs.py@@ -369,9 +369,19 @@ LEGS: dict[str, Leg] = {}-# 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+# How many legs one kernel packs. This used to be 2, the card count, because+# legs were started all at once and one per card: a third would have SHARED a+# card and quietly changed what both of the legs on it measured.+#+# They now queue -- build_kernel.py runs one worker per card, and a card takes+# its next leg only when the previous one has exited -- so a leg beyond the+# second waits rather than sharing, and the card count no longer caps this.+# What caps it is wall clock: every leg past the second adds its whole runtime+# to one card's column, the session is killed at 12 hours, and the launcher's+# own ceiling is lower still. At 4 legs the longest column is about 11 minutes,+# so there is room, but this is a number to raise deliberately and measure+# after, not to grow by accident.+MAX_LEGS_PER_KERNEL = 4# 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@@ -416,32 +426,48 @@ UNWIRED: dict[str, str] = {),}-# Which legs travel in which kernel, one entry per kernel, each running its legs-# one per T4 of its session.+# Which legs travel in which kernel. ONE kernel, holding every leg, which its+# 2xT4 session works through two at a time -- one per card, the next leg+# starting on a card only when that card's previous leg has exited.+#+# This was two kernels, and the reason it is one now is NOT quota. A session+# bills its wall clock once rather than per card, so two kernels of two legs+# cost 662s of billing against 646s for one kernel of four: a rounding error.+# What two kernels cost is the whole ACCOUNT. Kaggle allows two concurrent GPU+# sessions, two kernels take both, and kaggle-t4-studio-gpu-ci.yml runs on the+# same account -- so the notebook leg locked Studio out entirely for as long as+# it ran (measured: Studio's run 32607617804 queued ~40 minutes behind notebook+# run 32607621452). One kernel holds one session and leaves the other free, and+# the two workflows now hold separate GitHub concurrency groups so they can+# actually use it. Splitting the group without packing the kernel, or packing+# without splitting the group, each make things worse on their own.#-# 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.+# Ordered LONGEST EXPECTED LEG FIRST, and that ordering is load-bearing.+# build_kernel.py hands this order to the driver as its start order and a card+# takes work greedily, so putting gptoss (384s, and the leg that sets the+# makespan) anywhere but first leaves the schedule unable to balance around it.+# Measured on run 32607621452: gptoss 384.1s, frontier 312.2s, canary 265.3s,+# control 262.2s, which this order packs as 384.1+262.2 = 646.3s against+# 312.2+265.3 = 577.5s. That is the optimal split of these four; the next best+# pairing is 649.4s, and perfect balance would be 611.9s, so the 68.8s of idle+# at the end is 34.4s of genuinely unavoidable imbalance and not a packing bug.#-# 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.+# control and canary stay in the same kernel, which is what their comparison+# needs: same image, same driver, same hour. They no longer run on the two+# cards SIMULTANEOUSLY, which is fine -- they were never compared against each+# other, only each against its own committed reference, and neither reads a+# clock. What would break them is landing in different SESSIONS, and packing+# everything into one kernel makes that impossible rather than merely unlikely.#-# `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"),-)+# `grpo` returns here once the illegal memory access in UNWIRED is understood.+# It briefly had a 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, ...], ...] = (("gptoss", "frontier", "canary", "control"),)def expand_install(diff --git a/.github/workflows/kaggle-t4-notebook-ci.yml b/.github/workflows/kaggle-t4-notebook-ci.ymlindex 55716012ae3..ff8dd6c2875 100644--- a/.github/workflows/kaggle-t4-notebook-ci.yml+++ b/.github/workflows/kaggle-t4-notebook-ci.yml@@ -7,25 +7,34 @@# 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.+# card free, two per session: four payloads across one session's pair of cards.## ----------------------------------------------------------------------# 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.+# WHAT RUNS: four legs in ONE kernel, two at a time. The leg order 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+# 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+# canary tiny Qwen2.5-0.5B SFT on the newest permitted library set+# control the same run, PINNED library set+#+# One worker per card takes the next leg off that list when its previous leg has+# exited, so a card carries exactly one leg at a time and the four fit in one+# session. Longest first, because the longest leg is what sets the makespan and+# a greedy schedule cannot balance around one it picks up last.+#+# This was two kernels of two, one leg per T4, and the reason it is one kernel+# is NOT quota: a session bills its wall clock once rather than per card, so the+# two shapes cost within a few percent of each other. It is that two kernels+# took BOTH of the account's concurrent sessions and locked+# kaggle-t4-studio-gpu-ci.yml, which shares the account, out entirely. One+# kernel leaves the second session for Studio.## 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.+# Turing, one session in three. The measurements are on legs.UNWIRED.## **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@@ -88,9 +97,11 @@# account and the cheap leg is the one that should yield the tail of the# week to the expensive one rather than race it for the same hours.# 4. A concurrency check. Kaggle caps concurrent batch GPU kernels at 2 per-# ACCOUNT; this job uses both, and only when the account is otherwise idle,-# since one kernel belonging to anyone else stands it down entirely. See-# ALLOWED_IN_FLIGHT_FOREIGN_KERNELS in gate.py.+# ACCOUNT; this job uses ONE of them and runs 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. The other+# slot is what kaggle-t4-studio-gpu-ci.yml pushes into, which is why the+# two workflows no longer share a concurrency group.## ARITHMETIC, recomputed from live numbers on 2026-08-11: measured on# unslothai/unsloth over the preceding 7 days or on real Kaggle sessions, none@@ -115,13 +126,21 @@# 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+# COST OF ONE INVOCATION. One kernel, billing its wall clock ONCE rather than+# per card at almost exactly 1 GPU-h per hour, so the second T4 is free while+# both are busy and the tail where only one is busy costs no more than the+# rest. Per-leg durations measured on run 32607621452: gptoss 384.1s, frontier+# 312.2s, canary 265.3s, control 262.2s. Packed longest-first across two cards+# that is 384.1 + 262.2 = 646.3s on one card against 312.2 + 265.3 = 577.5s on+# the other, so one kernel of four legs measures ~0.18 h:+# one kernel, four legs 0.18 h# TOTAL, expected ~0.25 h (rounded up)+# The two-kernel shape this replaced measured 0.10 h + 0.13 h = 0.23 h, so+# consolidating is roughly quota-neutral; the gain is the freed session, not+# the hours. The 0.25 h envelope is DELIBERATELY not lowered to match the new+# measurement. Every figure below is derived from it, the real cost moved+# DOWN so it remains an upper bound, and re-deriving a whole budget to book a+# 0.05 h saving would be a lot of arithmetic to make the reserve thinner.## SAMPLING RATE, solved at the pessimistic end of the eligible range and# targeting 9h rather than the full 15, so a busy week does not spend the@@ -371,8 +390,8 @@ jobs:--label-name kaggle-t4-ci \--event-action "$EVENT_ACTION" \--event-label "$EVENT_LABEL" \- --kernels 2 \- --budget-hours 8 \+ --kernels 1 \+ --budget-hours 4 \--reserve-hours 20t4-smoke:@@ -436,12 +455,25 @@ jobs:# 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.+ # resource and two runs of THIS workflow 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.+ #+ # The group is per WORKFLOW now, where it used to be one string shared with+ # kaggle-t4-studio-gpu-ci.yml. Sharing it was correct while this job pushed+ # TWO kernels: that took both of the account's concurrent sessions, so+ # Studio had to queue rather than race the cap and lose a push. This job now+ # packs every leg into one kernel and holds one session, which leaves the+ # second for Studio -- and a shared group would keep Studio locked out of a+ # seat that is now free. Measured before the change: Studio's run+ # 32607617804 sat queued about 40 minutes behind notebook run 32607621452.+ #+ # This only stays safe while each workflow pushes ONE kernel. Two workflows+ # x one kernel is exactly Kaggle's 2-session cap, with no headroom, so the+ # capacity handling on the push path is load bearing rather than defensive.concurrency:- group: kaggle-t4-notebook-ci-account+ group: kaggle-t4-account-notebookcancel-in-progress: falsesteps:# FIRST, ahead of even the audit hardening, and it is an `echo` so there@@ -779,8 +811,8 @@ jobs:python .github/scripts/kaggle_t4_ci/gate.py \--force true \--soft-fail \- --kernels 2 \- --budget-hours 8 \+ --kernels 1 \+ --budget-hours 4 \--reserve-hours 20# Through the environment rather than an inline expression, so nothing thediff --git a/.github/workflows/kaggle-t4-studio-gpu-ci.yml b/.github/workflows/kaggle-t4-studio-gpu-ci.ymlindex 9e3b9c0719d..0d3ebc115c5 100644--- a/.github/workflows/kaggle-t4-studio-gpu-ci.yml+++ b/.github/workflows/kaggle-t4-studio-gpu-ci.yml@@ -326,13 +326,22 @@ jobs:# 120 min: the kernel ceiling is 70 and collection adds a few, so this# only fires if the launcher itself wedged.timeout-minutes: 120- # The SAME group string the notebook leg uses, on purpose. Kaggle's- # 2-kernel cap is per ACCOUNT and is not workflow-aware, so the two GPU- # legs have to queue behind each other rather than race the gate's- # concurrency survey and lose a push to the capacity cap. Not keyed on- # the ref for the same reason.+ # A group of this workflow's OWN, where this used to be the same string the+ # notebook leg uses. Sharing it was right while the notebook leg pushed two+ # kernels and so held both of the account's concurrent sessions: this job+ # would have raced the cap and lost its push. The notebook leg now packs+ # every leg into a single kernel and holds one session, so the second is+ # free and this job can take it instead of waiting out the whole notebook+ # run (measured: run 32607617804 queued about 40 minutes behind notebook run+ # 32607621452).+ #+ # Still not keyed on the ref: this job pushes to one global account, so two+ # branches must not overlap even though the two WORKFLOWS now may. And the+ # arithmetic has no slack -- one kernel here plus one there is exactly+ # Kaggle's 2-session cap -- so anything that makes either side push a second+ # kernel has to put these two back in one group.concurrency:- group: kaggle-t4-notebook-ci-account+ group: kaggle-t4-account-studiocancel-in-progress: falsesteps:- name: Harden runner (audit)diff --git a/tests/kaggle/test_studio_gpu_harness.py b/tests/kaggle/test_studio_gpu_harness.pyindex fce7a2c32c2..b6b6f3351b1 100644--- a/tests/kaggle/test_studio_gpu_harness.py+++ b/tests/kaggle/test_studio_gpu_harness.py@@ -791,20 +791,61 @@ def test_the_workflow_never_cancels_a_run_that_may_hold_a_kernel():assert wf["jobs"]["studio-gpu"]["concurrency"]["cancel-in-progress"] is False-def test_the_two_kaggle_legs_queue_behind_each_other():- """Kaggle's 2-kernel cap is per ACCOUNT and is not workflow-aware, so- sharing a concurrency group is what stops one leg's push being rejected- by the other's kernel."""+def test_the_two_kaggle_legs_fit_the_account_side_by_side():+ """One kernel each, against a 2-kernel per-ACCOUNT cap, so they can overlap.++ They used to SHARE a concurrency group, because the notebook leg pushed two+ kernels and took both of Kaggle's slots: this leg would have raced the cap+ and lost its push, so it had to queue behind instead. The cost was that it+ queued behind the whole notebook JOB even though the account was free again+ the moment that job's kernels finished -- measured, run 32607617804 waited+ about 40 minutes on run 32607621452.++ The notebook leg now packs its four legs into one kernel. So the invariant+ worth holding is no longer "same group" but the arithmetic that made the+ same group necessary: what each leg PUSHES has to sum to within the cap.+ Separate groups plus one kernel each is exactly 2 of 2, with no headroom,+ which is why this asserts the sum rather than the group names.+ """yaml = pytest.importorskip("yaml")- notebook = yaml.safe_load(- (REPO_ROOT / ".github" / "workflows" / "kaggle-t4-notebook-ci.yml").read_text(- encoding = "utf-8"- )+ # Read the cap out of gate.py's SOURCE rather than importing it. Both+ # .github/scripts/kaggle_studio_ci and .github/scripts/kaggle_t4_ci ship a+ # module called `report`, so putting either on sys.path here decides which+ # one `import report` resolves to for every test that runs afterwards in+ # the same process. An earlier draft of this test did exactly that and took+ # nine unrelated summary tests down with it.+ gate_src = (REPO_ROOT / ".github" / "scripts" / "kaggle_t4_ci" / "gate.py").read_text(+ encoding = "utf-8")- assert (- _workflow()["jobs"]["studio-gpu"]["concurrency"]["group"]- == notebook["jobs"]["t4-smoke"]["concurrency"]["group"]+ caps = re.findall(r"^MAX_CONCURRENT_GPU_KERNELS = (\d+)$", gate_src, re.MULTILINE)+ assert len(caps) == 1, caps+ MAX_CONCURRENT_GPU_KERNELS = int(caps[0])++ notebook_text = (REPO_ROOT / ".github" / "workflows" / "kaggle-t4-notebook-ci.yml").read_text(+ encoding = "utf-8"+ )+ notebook = yaml.safe_load(notebook_text)+ studio_group = _workflow()["jobs"]["studio-gpu"]["concurrency"]["group"]+ notebook_group = notebook["jobs"]["t4-smoke"]["concurrency"]["group"]++ assert studio_group != notebook_group, (+ "the two legs share a concurrency group again, so Studio waits out the "+ "whole notebook job for a Kaggle session that is free")+ # Neither may be keyed on the ref: one account, so two branches of the SAME+ # workflow still must not overlap even though the two workflows may.+ for group in (studio_group, notebook_group):+ assert "github.ref" not in group, group++ pushes = {}+ for label, text in (+ ("studio", WORKFLOW.read_text(encoding = "utf-8")),+ ("notebook", notebook_text),+ ):+ found = {int(k) for k in re.findall(r"--kernels (\d+)", text)}+ assert len(found) == 1, (label, found)+ pushes[label] = found.pop()+ assert sum(pushes.values()) <= MAX_CONCURRENT_GPU_KERNELS, pushesdef test_the_workflow_is_never_preempted_by_the_capacity_sweeper():diff --git a/tests/kaggle/test_t4_ci_transport.py b/tests/kaggle/test_t4_ci_transport.pyindex 75703fcdaea..7f824709b31 100644--- a/tests/kaggle/test_t4_ci_transport.py+++ b/tests/kaggle/test_t4_ci_transport.py@@ -17,6 +17,8 @@ import osimport subprocessimport sysimport tempfile+import threading+import timeimport typesfrom pathlib import Path@@ -147,6 +149,187 @@ def test_two_gpus_still_run_both_payloads_one_per_card(tmp_path):assert sorted(p["cuda"] for p in driven["papermill"]) == ["0", "1"]+class _PackedStub(_Stub):+ """`_Stub`, but observable in the two ways a PACKED kernel can go wrong.++ A kernel now carries more legs than it has cards, so the legs queue. Two+ things that used to be structurally impossible become possible and have to+ be watched:++ * two legs on the SAME card at the same time, which is the contended OOM+ the shortfall guard was written for, reached by a route it cannot see;+ * every leg's virtualenv alive at once, each carrying its own torch, on a+ `/kaggle/working` that is not sized for it.++ So papermill HOLDS for a moment (instant calls cannot overlap, and a test+ that cannot observe the failure is not a test), `uv venv` really creates+ its directory, and both the live-payload and live-venv counts are sampled+ while the run is in flight.+ """++ def __init__(+ self,+ *,+ gpus,+ durations = None,+ hold = 0.05,+ ):+ super().__init__(gpus = gpus)+ self.durations = durations or {}+ self.hold = hold+ self._live_on_card: dict = {}+ self._lock = threading.Lock()+ self.same_card_overlaps: list = []+ self.max_live_venvs = 0+ self.root: Path | None = None++ def run(self, cmd, **kw):+ cmd = [str(c) for c in cmd]+ if len(cmd) > 2 and cmd[1] == "venv":+ Path(cmd[2]).mkdir(parents = True, exist_ok = True)+ if "papermill" in cmd:+ notebook = Path(cmd[cmd.index("papermill") + 1]).name+ card = (kw.get("env") or {}).get("CUDA_VISIBLE_DEVICES")+ with self._lock:+ if self._live_on_card.get(card):+ self.same_card_overlaps.append((card, self._live_on_card[card], notebook))+ self._live_on_card[card] = notebook+ if self.root is not None:+ live = len(list(self.root.glob("venv_*")))+ self.max_live_venvs = max(self.max_live_venvs, live)+ time.sleep(self.durations.get(notebook, self.hold))+ with self._lock:+ self._live_on_card[card] = None+ return super().run(cmd, **kw)+++def _drive_packed(+ tmp_path,+ leg_names,+ *,+ gpus,+ durations = None,+):+ 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 = _PackedStub(gpus = gpus, durations = durations)+ stub.root = tmp_path+ 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, "stub": stub, "results": namespace.get("results") or {}}+++ALL_FOUR = ["gptoss", "frontier", "canary", "control"]+++def test_four_legs_on_two_cards_never_put_two_legs_on_one_card_at_once(tmp_path):+ """The property that makes packing safe at all.++ Four payloads across two T4s is only sound because a card takes its next+ leg when the previous one has EXITED. If they overlapped, each child would+ still pass its own `device_count() == 1` assertion and then fight for 15GB,+ which is exactly the failure the shortfall guard was added to prevent and+ exactly the one it cannot see from where it stands.+ """+ driven = _drive_packed(tmp_path, ALL_FOUR, gpus = 2)+ assert driven["stood_down"] is None+ stub = driven["stub"]+ assert stub.same_card_overlaps == [], stub.same_card_overlaps+ assert len(stub.papermill) == 4, stub.papermill+ # Both cards are used, and every leg ran. The SPLIT is deliberately not+ # asserted: how many legs each card ends up with is a function of how long+ # the legs take relative to the 5s venv stagger, not something the+ # scheduler promises. Under the measured durations (gptoss 384.1s,+ # frontier 312.2s, canary 265.3s, control 262.2s) the stagger is under 2%+ # and the split is 2/2; under the sub-second stubs here the first card+ # legitimately drains most of the queue before the second clears its+ # stagger. Pinning 2/2 would be pinning the stub's timing.+ assert set(p["cuda"] for p in stub.papermill) == {"0", "1"}, stub.papermill+++def test_the_longest_leg_starts_first_so_the_schedule_can_balance_around_it(tmp_path):+ """Start order is longest-first, and it is load bearing rather than tidy.++ Measured on run 32607621452: gptoss 384.1s, frontier 312.2s, canary 265.3s,+ control 262.2s. Longest-first packs those as 646.3s, which is the optimal+ split of the four; `sorted(PAYLOADS)` would start gptoss LAST, and a greedy+ scheduler cannot balance around the leg that sets the makespan if it picks+ it up at the end.+ """+ driven = _drive_packed(tmp_path, ALL_FOUR, gpus = 2)+ started = [p["notebook"] for p in driven["stub"].papermill]+ assert started[0] == "t4_gptoss.ipynb", started+ assert started != sorted(+ started+ ), "payloads are running in alphabetical order, so the longest leg is last"+++def test_each_leg_keeps_its_own_venv_compile_cache_and_ipykernel(tmp_path):+ """Packing must not let two legs share an interpreter.++ The legs exist to install DIFFERENT library sets. They are separated by a+ per-payload virtualenv, a per-payload ipykernel spec and a per-payload+ `UNSLOTH_COMPILE_LOCATION`; all three are keyed by the payload's index, so+ an index reused across a wave would silently merge two legs' trees and the+ last writer would win.+ """+ driven = _drive_packed(tmp_path, ALL_FOUR, gpus = 2)+ calls = driven["stub"].papermill+ for field in ("kernel", "compile_location", "notebook"):+ values = [c[field] for c in calls]+ assert len(set(values)) == len(calls), (field, values)+++def test_a_finished_leg_gives_its_virtualenv_back(tmp_path):+ """Otherwise four torch trees sit on /kaggle/working at once.++ The tail cell prunes `venv_*`, but only after every payload has finished,+ which was sufficient when a kernel held one payload per card. Packed, the+ peak is what matters, and it has to stay at one venv per CARD rather than+ one per LEG.+ """+ driven = _drive_packed(tmp_path, ALL_FOUR, gpus = 2)+ stub = driven["stub"]+ assert (+ stub.max_live_venvs <= 2+ ), f"{stub.max_live_venvs} virtualenvs were alive at once on a 2-card kernel"+ assert list(tmp_path.glob("venv_*")) == [], "a payload left its virtualenv behind"+++def test_a_one_card_allocation_still_stands_a_packed_kernel_down(tmp_path):+ """The shortfall guard survives the change that made it stop counting legs.++ It used to compare GPUs against the payload count. There are deliberately+ more payloads than cards now, so that comparison would stand every healthy+ run down; it compares against the width the packing was built for instead.+ What must NOT change is that a genuinely short allocation is still called+ infrastructure, because one card silently serialises the whole kernel and+ doubles its wall clock while looking like a slow but healthy run.+ """+ driven = _drive_packed(tmp_path, ALL_FOUR, gpus = 1)+ assert driven["stood_down"] is not None, "a 1-GPU allocation ran the packed kernel anyway"+ assert driven["stub"].papermill == []++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.diff --git a/tests/kaggle/test_t4_smoke_harness.py b/tests/kaggle/test_t4_smoke_harness.pyindex 0ce3e5457e8..97e2b11bf99 100644--- a/tests/kaggle/test_t4_smoke_harness.py+++ b/tests/kaggle/test_t4_smoke_harness.py@@ -391,26 +391,36 @@ def test_a_foreign_kernel_blocks_even_when_a_slot_is_free():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."""+ """A previous run of this workflow is not a stranger, and not free either.++ Asserted at both widths rather than at whatever the default happens to be,+ because the default moved: this workflow used to push two kernels and now+ pushes one, and the property being pinned -- our own in-flight kernels are+ counted against the cap like anyone else's -- is the same either way.+ """from gate import concurrency_verdict- clear, why = concurrency_verdict(_busy("danielhanchen/unsloth-t4-ci-abc"))+ leftover = "danielhanchen/unsloth-t4-ci-abc"+ # Wanting both slots with one of ours already up overruns the cap.+ clear, why = concurrency_verdict(_busy(leftover), kernels_needed = 2)assert clear is Falseassert "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,- "",- )+ # Wanting one, which is what this workflow now asks for, fits beside it.+ assert concurrency_verdict(_busy(leftover), kernels_needed = 1) == (True, "")++def test_an_idle_account_clears_the_kernel_this_workflow_pushes():+ """One kernel, carrying all four legs, leaving the second slot for Studio.-def test_an_idle_account_clears_both_kernels():- """The change this refinement exists for: 2 kernels x 2 T4s = 4 legs."""+ This asserted 2, when four legs meant two kernels of two and the notebook+ leg took the whole account. The legs now queue inside a single kernel, so+ the same four run in one slot -- and the slot that frees up is the one+ kaggle-t4-studio-gpu-ci.yml pushes into, which is the point of the change+ rather than a side effect of it.+ """from gate import KERNELS_PER_INVOCATION, concurrency_verdict- assert KERNELS_PER_INVOCATION == 2+ assert KERNELS_PER_INVOCATION == 1survey = {"busy": [],"own": [],@@ -426,6 +436,9 @@ def test_an_idle_account_clears_both_kernels():assert KERNELS_PER_INVOCATION <= MAX_CONCURRENT_GPU_KERNELSassert concurrency_verdict(survey, MAX_CONCURRENT_GPU_KERNELS + 1)[0] is False+ # The freed slot is real: one of ours in flight does not stand the next one+ # down, where at the old width it did.+ assert concurrency_verdict(_busy("danielhanchen/unsloth-t4-ci-abc"))[0] is Truedef test_a_survey_that_ran_out_of_time_is_not_read_as_an_idle_account():@@ -3840,9 +3853,16 @@ def test_probe_mode_reports_rather_than_judges():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."""+ """The launcher stays generic over N kernels, and pushes before it waits.++ This workflow now hands it ONE notebook -- all four legs queue inside a+ single kernel -- so the push-then-wait ordering below is not currently load+ bearing for it. It is kept because the launcher is shared with+ kaggle-t4-studio-gpu-ci.yml and because the property is the expensive one+ to rediscover: waiting between pushes serialises sessions Kaggle runs+ happily in parallel, which is what once put an hour between the control leg+ and the canary leg.+ """import inspectimport launch@@ -4238,22 +4258,34 @@ def test_the_frontier_leg_does_not_carry_the_zoo_requirement():)-def test_the_frontier_leg_is_wired_on_the_seat_that_costs_nothing():- """A Kaggle session bills wall clock once, not per card.+def test_the_frontier_leg_rides_in_the_one_kernel_rather_than_opening_a_session():+ """frontier must never be the reason a second Kaggle session is opened.++ This used to read "the seat that costs nothing", on the basis that a+ session bills its wall clock once rather than per card, so the second+ kernel's idle T4 carried frontier for free. That is still true about+ BILLING and is no longer the binding constraint. The account allows two+ concurrent GPU sessions; two kernels took both, and+ kaggle-t4-studio-gpu-ci.yml runs on the same account, so the notebook leg+ locked Studio out for as long as it ran. Everything now packs into one+ kernel and frontier queues behind the legs ahead of it.++ So the property worth pinning is no longer "frontier shares a full kernel"+ -- that assertion passes just as happily on a two-session layout -- but+ "there is one kernel and frontier is in it".- 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.+ It has passed on real hardware in both layouts: transformers 5.15.0 /+ trl 1.9.2 paired, and transformers 5.15.1 / trl 1.10.0 on run 32607621452,+ ten steps, canary emitted, two fresh processes agreeing bitwise."""sys.path.insert(0, str(CI_DIR))import legswired = [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 len(legs.KERNELS) == 1, (+ f"{len(legs.KERNELS)} kernels means {len(legs.KERNELS)} concurrent Kaggle "+ "sessions, and the account only has two. Studio needs one of them.")assert "frontier" not in legs.UNWIRED