翻篇收录说明
翻篇网页快照

27.2 Colab and Kaggle – Dive into Deep Learning

https://d2l.ai/chapter_appendix-tools-for-deep-learning/hosted-notebooks.html

最近抓取:2026-12-04 00:42:51(北京时间)

最近内容变化:2026-12-04 00:42:51(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

正文摘录

The previous section set up the book’s notebooks on your own machine. Many readers do not have a suitable one at hand: a laptop without a GPU, a school computer that forbids installations, or a tablet. Google Colab and Kaggle serve these readers. Each opens a notebook in the browser on a virtual machine lent for the session, with Python and the main frameworks preinstalled and, within usage limits, a free GPU when one is available. A borrowed machine raises a question that a local one does not: what is still there tomorrow? Suppose that you install a package, download Fashion-MNIST, and train a classifier for an hour. The provider created the machine when you connected, and it deletes the machine when the session ends, after an idle period or at a usage limit. The next morning the notebook is still there, together with any file you saved to durable storage. The package, the dataset, and the checkpoints written to the local disk are gone. The remedy is to treat the runtime as replaceable. A notebook that records how to rebuild its environment, and that saves what it must keep, runs on Colab, on Kaggle, and on a local kernel alike, even after the provider updates its software image. Below we see how the book’s launch buttons reach the two providers, how the providers differ, and how to write setup cells that survive a new machine. Figure 27.2.1: A hosted runtime is temporary; notebooks, data, and checkpoints become durable only when we save them explicitly. Figure 27.2.1 shows the lifecycle. A runtime may stop after inactivity, hit a session limit, or come back with a different software image. Rerunning a setup cell costs little when the notebook records everything needed to reconstruct the runtime, and the book’s notebooks are written that way. 27.2.1 Launching a Book Notebook Every page of the book that contains code shows a Run notebook control with three actions: Colab, Kaggle, and Download. The control follows the active framework tab and offers that tab’s PyTorch, TensorFlow, or JAX notebook. When the tab has no hosted notebook, as for MXNet, the control reads Notebook unavailable. Pages whose code uses no framework offer a single NumPy notebook instead. The notebooks live at stable paths on a public GitHub branch and record the source revision they were built from. A notebook that imports d2l starts with a generated setup cell. It keeps the provider’s preinstalled packages where they are compatible, installs the versions the book was tested with where they are not, and downloads the d2l helper modules of that revision from GitHub. Figure 27.2.2: The source page, the generated notebook branch, and the provider launch are separate stages with a stable page-to-notebook mapping. The two launch actions keep your work in different places: Colab opens a pointer to GitHub. The URL has the form colab.research.google.com/github/<org>/<repo>/blob/<branch>/<path>.ipynb, and Colab fetches the notebook from GitHub each time it is opened. You always see the current published version, but your edits are not written back. To keep changes, use File → Save a copy in Drive, or download the .ipynb. Kaggle imports a copy. The book passes the notebook’s raw URL to Kaggle’s importer (kaggle.com/kernels/welcome?src=...), which creates a new private notebook in your Kaggle account, so you need an account to use it. Your copy is independent of the book: it does not update when the book does, and you keep your changes by saving a version on Kaggle. In both cases the launch refers to a readable notebook at a public path, which you can inspect before running it. Do the same for any “Open in Colab” badge on the internet: check the repository it comes from and read the setup cell before executing someone else’s code with your account’s permissions. 27.2.2 Colab 27.2.2.1 Free-Tier Resources Colab’s free tier provides GPUs and TPUs, but its FAQ guarantees neither the hardware nor the limits: as of November 2026 it states that the types of accelerators vary over time and that usage limits fluctuate. A notebook runs for at most 12 hours, depending on availability and on your usage, and an idle runtime times out. A T4 with 16 GB of memory is the GPU that free users commonly receive, but this is not a service guarantee. The menu shows what you asked for, not what you received, so we check the runtime in code: 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} The cell recognizes Colab by its google.colab module, which Colab loads at startup, and Kaggle by its working directory. For the accelerator, PyTorch reports torch.cuda.is_available() and torch.cuda.get_device_properties(0), TensorFlow tf.config.list_physical_devices("GPU"), and JAX jax.devices(). A reported accelerator is still no guarantee that your workload fits in its memory. Beyond the free tier, Colab sells compute units through Pay As You Go and the Pro and Pro+ subscriptions. A balance increases access to accelerators but guarantees none in particular. Unit prices and consumption rates change, so read the purchase page before estimating a cost. 27.2.2.2 Runtime Versions and the Command Line Colab updates its software image regularly, which can break a notebook that worked last month. Since September 2025 a notebook can pin a dated runtime version in Runtime → Change runtime type. As of November 2026 past versions remain available for one year after their release, and connecting to one takes two to three minutes. Google recommends the latest runtime with pinned library versions for most work, and a pinned runtime for notebooks shared with many people, such as the material of a course. The Colab CLI, released in June 2026 for Linux and macOS, drives the same runtimes from a terminal or a coding agent: colab new allocates a runtime, colab exec runs a script or notebook on it, and colab stop releases it. 27.2.2.3 Saving Work Colab keeps work in Google Drive. Save a copy in Drive stores the notebook, and mounting Drive (drive.mount) is the usual way to keep datasets and checkpoints across sessions. A notebook opened from GitHub is never saved back automatically. Colab can also attach to a local runtime, in which the browser page controls a Jupyter server on your own machine. This moves the security boundary: the notebook then executes with the permissions of your local Jupyter process, and Drive mounting no longer works. Connect only notebooks you trust. 27.2.3 Kaggle 27.2.3.1 Inputs, Outputs, and Versions Kaggle is built around datasets and competitions, and its notebooks follow from that. Three kinds of directory define how a Kaggle notebook handles files: /kaggle/input/ holds attached datasets, models, and the outputs of other notebooks, mounted read-only and versioned. An attached dataset needs no download inside the notebook. /kaggle/working/ is your writable output directory, with 20 GB of space as of November 2026. Its contents persist only into saved versions of the notebook. Everything else is scratch space that disappears with the session. The second defining feature is versioning. Save & Run All executes the whole notebook from top to bottom in a fresh session and stores the result as an immutable version with its inputs, code, outputs, and logs. This is the habit of restarting and running all cells (Section 27.1) built into the platform. 27.2.3.2 Quotas and Hardware As of November 2026 an account receives a weekly GPU quota of 30 hours, sometimes more when demand allows, on either one P100 or two T4 GPUs, and a separate weekly TPU quota. A session runs for at most 12 hours on CPU or GPU and 9 hours on TPU. The notebook interface shows the current values for your account; check them before planning a run. Kaggle may require phone verification before it enables accelerators or internet access. Internet access is a per-notebook setting and is disabled in some competitions, so a well-behaved notebook attaches its data as inputs rather than downloading it mid-run. The Kaggle CLI can push, run, and pull notebooks and datasets from your terminal. Keep its token in the provider’s secret store, never in a cell. 27.2.4 Portable Notebooks 27.2.4.1 Choosing a Provider Either provider runs the book’s notebooks. They differ in where your files and results live, and in how predictable their limits are, as Table 27.2.1 summarizes. Table 27.2.1: Hosted notebook trade-offs (as of November 2026) Need Colab Kaggle Open a GitHub notebook directly Yes, fetched on each open Import creates your own copy Free GPU Usually a T4; limits unpublished P100 or 2×T4; 30 h/week published Predictable quota No Yes Persistent files Google Drive Versioned datasets and outputs Reproducible runs Manual restart and run all; pinned runtime versions Save & Run All versions Competition workflow External Native Paid upgrade Compute units (Pay As You Go, Pro, Pro+) Not needed for the published quota For running a section of the book, Colab’s direct opening from GitHub is the shortest path. For an experiment built around a dataset that you want to share or rerun, Kaggle’s versioned inputs and outputs fit better. 27.2.4.2 Setup Cells Because the runtime is replaceable, the notebook must carry its own setup. A good setup cell is short, idempotent, and explicit: it pins versions, installs only what is missing, and contains no secrets. 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} Avoid an unconditional pip install --upgrade ... at the top of a notebook. It discards a tested provider environment, slows every start, and makes yesterday’s notebook resolve different package