Kernel termination during Kaggle Notebook timeout prevents state persistence
0 reputation · 26 Mar 2024, 12:42 UTC
0 reputation · 26 Mar 2024, 12:42 UTC
Kaggle Notebooks enforce hard execution limits—typically 12 hours for CPU and 9 hours for GPU instances. When these limits are reached, or a session is manually cancelled, the kernel process terminates immediately, resulting in the loss of all volatile memory state not explicitly committed to the /kaggle/working directory.
Because the environment may not reliably trigger standard SIGTERM handlers, traditional Python try-finally blocks or signal interceptors often fail to execute final cleanup or model-saving logic. This presents a challenge for long-running machine learning tasks where model weights must be persisted before the environment is preempted.
What is the most reliable method to monitor the remaining session duration within a training loop to trigger a graceful checkpoint? Additionally, how can one ensure that a file write operation completes fully if the kernel is killed mid-write during a hard timeout?
34775 reputation · 26 Mar 2024, 14:56 UTC · edited 16 Sept 2026, 09:10 UTC
To trigger a checkpoint reliably before a Kaggle kernel is abruptly killed, you need a two‑step strategy:
time.time() and subtract it from the known limit, leaving a safety buffer (e.g., 5 min). If the remaining time falls below the buffer, call your checkpoint routine immediately.Below is a minimal, reproducible pattern you can drop into a training loop:
# -*- coding: utf-8 -*-
import time, os, tempfile, shutil
import torch
# 1. Time estimation
KERNEL_LIMIT = 12 * 60 * 60 # 12 hours in seconds (CPU)
BUFFER = 5 * 60 # 5 minute safety buffer
START = time.time()
# 2. Checkpoint helper
def checkpoint(model, epoch, path):
"""Save atomically to .
The function writes to a temp file, flushes, fsyncs, and renames.
"""
dirpath = os.path.dirname(path)
os.makedirs(dirpath, exist_ok=True)
with tempfile.NamedTemporaryFile(dir=dirpath, delete=False) as tmp:
torch.save({'epoch': epoch, 'model_state': model.state_dict()}, tmp.name)
tmp.flush()
os.fsync(tmp.fileno()) # ensure data is on disk
os.replace(tmp.name, path) # atomic rename
# 3. Training loop skeleton
for epoch in range(num_epochs):
# ... training code ...
# Periodically check time
elapsed = time.time() - START
remaining = KERNEL_LIMIT - elapsed
if remaining <= BUFFER:
checkpoint(model, epoch, f'/kaggle/working/checkpoint_epoch{epoch}.pt')
break # optional: stop training to avoid abrupt kill
/kaggle/working, which survives kernel restarts.Confirmed facts:
finally blocks./kaggle/working persist across restarts.Likely cause (not guaranteed):
KAGGLE_KERNEL_TIMEOUT variable; if present, you can use it instead of hard‑coding the limit.To fine‑tune the safety buffer, could you confirm whether you are running a CPU or GPU instance? The exact timeout differs (12 h vs 9 h) and will affect the KERNEL_LIMIT value above.
Use comments to ask for clarification. Post a solution as an answer.
6,490 reputation · 26 Mar 2024, 21:46 UTC
While atomic writes prevent file corruption during a hard timeout, frequent checkpointing in /kaggle/working can lead to a different failure mode: disk quota exhaustion. Kaggle imposes strict storage limits on the working directory; if your model weights are large and you save a new version every few epochs, you may trigger an OSError: [Errno 28] No space left on device.
To maintain the safety of atomic renames without filling the disk, consider a rotating checkpoint strategy:
model_latest.pt and model_prev.pt).torch.save operation.!df -h /kaggle/working within the loop to trigger an emergency save if space becomes critical.