Colab and Kaggle

Dive into Deep Learning · §39.2

Colab and Kaggle: Ephemeral Hosted Runtimes, Quotas, and Portable Setup
ephemeral VMs · GitHub launch pipeline · Colab compute units · Kaggle versioned I/O · idempotent setup · Young’s checkpoint law

Borrowed Machines and the Ephemeral Runtime Problem

Motivation

  • Zero-install browser GPUs: Colab and Kaggle lend preconfigured containers with free GPUs, ideal for running notebooks from any laptop.
  • What vanishes on timeout: Idle timeouts or 12-hour session limits destroy the VM and wipe local scratch disks (/content), installed packages, and kernel RAM.
  • Engineering remedy: Treat every hosted VM as disposable—reconstruct setup in cell 1 and write checkpoints directly to durable storage.

The Hosted Runtime Lifecycle

Mental Model

A portable hosted workflow separates ephemeral execution state from durable storage at every stage of the session:

  • 1. Allocate & reconstruct: A new VM boots from the provider’s current container image; an idempotent setup cell pins and installs only missing packages.
  • 2. Compute on scratch disk: Fast local SSD space (/content or scratch) holds temporary intermediate files during training.
  • 3. Persist explicitly: Checkpoints, metrics, and edited notebooks must be synced to durable storage before idle timeout or preemption reclaims the VM.

How D2L’s ‘Run Notebook’ Launch Pipeline Works

Book Infrastructure

Every code-bearing page in D2L provides a Run notebook menu (Colab, Kaggle, Download) synchronized with the active framework tab:

  • Generated notebooks branch: The build publishes self-contained .ipynb files with a generated setup cell that verifies framework versions and downloads matching d2l helpers.
  • Colab opens a live GitHub pointer: Fetches the current published notebook from GitHub on each open—edits are not saved back unless you choose File \to Save a copy in Drive.
  • Kaggle imports an independent copy: Creates a private snapshot inside your Kaggle account that persists across your saved versions.

Security Audit Before Running Any Hosted Badge

Supply-Chain Safety

  • Audit setup cells before pressing Run: Unpinned pip install git+https://... or curl ... | bash executes arbitrary remote code, and drive.mount grants full read/write access to your Google Drive.
  • Pin immutable commit SHAs: Replace floating branch URLs with 40-character Git commit hashes and inspect scripts before executing.
  • Never attach untrusted notebooks to a local runtime: Local runtime mode executes with your personal machine’s full user permissions.

Google Colab: Variable Quotas and Compute Units

Colab Platform

  • Free tier (Nov 2026): Typically allocates an NVIDIA T4 (16 GB VRAM) with a 12-hour max session and aggressive idle disconnects; exact availability fluctuates with demand.
  • Paid tiers (Pay As You Go, Pro, Pro+): Sell compute units for priority access to L4 or A100 GPUs and background execution, though allocations remain best-effort.

Verifying Assigned Runtime Resources in Code

Runtime Inspection

Because a notebook menu shows the accelerator you requested rather than what the scheduler allocated, always verify the environment programmatically:

  • Detecting the host platform:
    • Colab preloads "google.colab" in sys.modules at kernel startup.
    • Kaggle mounts /kaggle/working as the writable output directory.
  • Checking the accelerator: Query torch.cuda.get_device_properties(0), tf.config.list_physical_devices("GPU"), or jax.devices() to confirm device model and total VRAM before starting a run.
import os
import sys
from pathlib import Path

resource = {
    "cpu_count_visible": os.cpu_count(),
    "colab": "google.colab" in sys.modules,
    "kaggle": Path("/kaggle/working").exists(),
}
resource
{'cpu_count_visible': 64, 'colab': False, 'kaggle': False}

Pinning Colab Runtime Versions and the Colab CLI

Image Stability & Automation

  • Dated runtime versions: Pinning a dated container image in Runtime \to Change runtime type freezes Python/CUDA/library versions for one year—ideal for course assignments.
  • Terminal automation (Colab CLI): colab new, colab exec, and colab stop let local scripts and coding agents drive hosted GPUs without leaving a browser tab open.

Kaggle Notebooks: Directory Semantics and Versioning

Kaggle Platform

  • Three filesystem zones: Read-only /kaggle/input/ mounts datasets/models instantly; /kaggle/working/ (20 GB) persists into saved versions; all other paths are ephemeral scratch.
  • Immutable batch runs (Save & Run All): Replays the entire notebook top-to-bottom in a fresh background container and snapshots code, logs, and /kaggle/working/ outputs.

Kaggle Quotas and Free-Tier Pretraining Arithmetic

Quota Sizing

C \approx 6 N D \approx 2.8 \times 10^{19}\text{ FLOPs (BERT-base)}

  • Why full pretraining outgrows free tiers: At 30\% of a T4’s 65\text{ TFLOP/s} peak (19.5\text{ TFLOP/s}), BERT-base takes \sim 400\text{ T4 hours}—over 33 twelve-hour sessions or 13+ weeks of Kaggle’s 30 h/week quota.
  • What fits in one 12-hour T4 session (8.4 \times 10^{17}\text{ FLOPs}): All D2L chapter notebooks, 7B–8B LoRA fine-tuning, or training an \sim 85\text{M} model.

Colab vs. Kaggle: Side-by-Side Trade-Offs

Choosing a Provider

  • Google Colab: Opens live pointers from GitHub (must Save a copy in Drive to keep edits), persists files via drive.mount, and sells compute units for L4/A100 access.
  • Kaggle Notebooks: Imports an independent copy, publishes a 30 h/week quota (1\times\text{P100} or 2\times\text{T4}), mounts versioned datasets at /kaggle/input, and captures immutable Save & Run All versions.

Writing Idempotent Setup Cells

Portable Notebooks

Because a hosted VM is replaceable, the notebook must carry its own setup without breaking the provider’s pretested environment:

  • Check before installing: Use importlib.util.find_spec (or importlib.metadata.version) to install only what is missing at a pinned version.
  • Never run unconditional pip install --upgrade: It overwrites tested provider wheels, slows startup, and causes Friday’s run to resolve different dependencies than Monday’s.
  • Restart after upgrading an imported package: If a module is already in sys.modules, pip install updates disk metadata (importlib.metadata.version) while the live kernel keeps running the old code in RAM (module.__version__) until a kernel restart.
import importlib.util
import platform

required = ["numpy", "matplotlib"]
missing = [name for name in required
           if importlib.util.find_spec(name) is None]
{
    "python": platform.python_version(),
    "missing": missing,
    "reconstructible": not missing,
}
{'python': '3.12.3', 'missing': [], 'reconstructible': True}

Recording an Environment Fingerprint

Diagnosing Image Drift

When a notebook that worked last week suddenly fails on a hosted runtime, a logged environment fingerprint distinguishes code bugs from provider image updates:

  • What to record in the output log:
    • Python version, CPU/machine architecture, and core library versions (numpy, framework metadata versions).
    • Assigned GPU model and VRAM (nvidia-smi) plus provider image variables (COLAB_*, KAGGLE_*).
  • Query metadata without importing: Reading importlib.metadata.version("torch") records installed frameworks without paying the multi-second overhead or GPU initialization side effects of importing unused backends.
import json
import numpy as np

fingerprint = {
    "python": platform.python_version(),
    "numpy": np.__version__,
    "machine": platform.machine(),
}
print(json.dumps(fingerprint, indent=2))
{
  "python": "3.12.3",
  "numpy": "2.4.4",
  "machine": "x86_64"
}

Portable Paths, Secrets, and Optimal Checkpointing

Durability & Security

  • Path adapter & secrets: Route outputs to /kaggle/working, /content/drive, or Path.cwd() automatically, and keep API tokens in the provider secret store.
  • Young’s checkpoint law (\tau^* = \sqrt{2\delta M}): If saving takes \delta = 30\text{ s} and disconnects arrive every M = 3\text{ h}, checkpoint every \tau^* \approx 13.4\text{ min}.
from pathlib import Path

if Path("/kaggle/working").exists():
    work = Path("/kaggle/working")
elif Path("/content").exists():
    work = Path("/content")
else:
    work = Path.cwd()
work
PosixPath('/home/smola/d2l-neu/_notebooks/pytorch/chapter_appendix-tools-for-deep-learning')

Concept Check: Ephemeral Runtimes and Portability

Check Your Understanding

Test your intuition on three practical hosted-notebook scenarios:

  1. You open a D2L notebook in Colab via the book’s launch button, spend two hours solving the exercises, and close the browser tab. Where are your edits?
  2. On Colab, you save model checkpoints to /content/checkpoints/ every 15 minutes without mounting Google Drive. The session hits the 12-hour limit. Which checkpoints survive?
  3. In a kernel where import transformers already ran, a cell executes !pip install transformers==4.57.0. Why does transformers.__version__ still print 4.56.1?

Answers:

  1. Nowhere—they are lost. Colab opens a read-only pointer to GitHub. To keep edits, you must explicitly run File \to Save a copy in Drive or download the .ipynb before the session expires.
  2. None. /content is ephemeral VM scratch disk that is deleted with the container. On Colab, a checkpoint writer should verify /content/drive is mounted (or sync to external storage) before starting a long run.
  3. Python caches imported modules in sys.modules; modifying files in site-packages on disk does not reload objects already resident in kernel RAM. The kernel must be restarted after package changes.

Summary: Portable Hosted Notebook Engineering

Key Takeaways

  • Save Edits & Verify Hardware: Copy GitHub-opened Colab notebooks to Drive immediately, and verify assigned GPU properties in code.
  • Idempotent Setup & Drift Logs: Check find_spec before installing pinned packages (restarting if already imported) and log a JSON environment fingerprint.
  • Durable Checkpoints & Secrets: Write checkpoints to mounted Drive or /kaggle/working at interval \tau^* = \sqrt{2\delta M}, and keep API keys in the provider secret store.