Google Colab Cheat Sheet
A quick reference for running Python notebooks in Google Colab, covering GPU/TPU setup, mounting Drive, installing packages, and useful keyboard shortcuts.
GPU/TPU Setup
Enable and verify hardware acceleration.
# Check GPU availabilityimport torchprint(torch.cuda.is_available())!nvidia-smi# Runtime > Change runtime type > GPU/TPU (UI action)
Mounting Google Drive
Access files stored in your Drive from a notebook.
from google.colab import drivedrive.mount('/content/drive')# Access files directly from your Driveimport pandas as pddf = pd.read_csv('/content/drive/MyDrive/data.csv')
Installing Packages
Add libraries not preinstalled in the Colab runtime.
!pip install -q transformers # Install a package quietly!apt-get install -y graphviz # Install a system package%pip install pandas==2.2.0 # Magic pip: installs into the active kernel
Magic Commands & Shortcuts
Notebook productivity commands and keybindings.
- %%time- Measures and prints the execution time of a cell
- %%writefile file.py- Writes the cell's contents to a file instead of executing it
- %matplotlib inline- Renders matplotlib plots directly below the cell
- Ctrl+M B / Ctrl+M A- Insert a new cell below / above the current one
- Shift+Enter- Runs the current cell and moves focus to the next
- Ctrl+M D D- Deletes the currently selected cell
Secrets Manager & Form Fields
Store credentials outside notebook cells and build parameterized UIs with form-tagged cells.
from google.colab import userdata# Secrets set via the key icon in the left sidebar, scoped per-notebookapi_key = userdata.get("OPENAI_API_KEY")# @param turns a variable into an editable form field in the rendered cellmodel_name = "gpt-4" # @param ["gpt-4", "gpt-3.5-turbo"]learning_rate = 0.01 # @param {type:"slider", min:0.0001, max:0.1, step:0.0001}run_training = True # @param {type:"boolean"}
Local Runtimes & TPU Strategy
Connect Colab to a local Jupyter kernel for full hardware access, and initialize a TPU device.
# On your machine: run a Jupyter server Colab can attach topip install jupyter_http_over_wsjupyter serverextension enable --py jupyter_http_over_wsjupyter notebook \ --NotebookApp.allow_origin='https://colab.research.google.com' \ --port=8888 --NotebookApp.port_retries=0# Then in Colab UI: Connect > Connect to a local runtime, paste the URL+token
TPU Strategy Initialization
Detect and connect to a Colab TPU for distributed TensorFlow training.
import tensorflow as tfresolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu="")tf.config.experimental_connect_to_cluster(resolver)tf.tpu.experimental.initialize_tpu_system(resolver)strategy = tf.distribute.TPUStrategy(resolver)print("TPU cores:", strategy.num_replicas_in_sync)with strategy.scope(): model = build_model() model.compile(optimizer="adam", loss="sparse_categorical_crossentropy")
File Uploads, Downloads & Git Sync
Move files in and out of the ephemeral VM and clone private repos via a token.
from google.colab import filesuploaded = files.upload() # opens a browser file picker, returns {name: bytes}files.download("results.csv") # triggers a browser download# Clone a private repo using a fine-grained token (avoid printing it to output)!git clone https://{token}@github.com/org/private-repo.git# Persist pip installs across a session by writing to Drive-backed site-packagesimport syssys.path.append("/content/drive/MyDrive/python_packages")
Runtime Types & Resource Limits
Practical constraints that shape how you architect a Colab workflow.
- Free tier GPU- typically a shared T4, subject to usage caps that vary with recent demand and dynamically throttle allocation
- Colab Pro/Pro+- longer session limits, priority access to faster GPUs (A100/V100), and background execution
- Ephemeral filesystem- anything outside /content/drive is wiped when the runtime recycles; only Drive-mounted paths persist
- RAM upgrade- Runtime > Change runtime type > High-RAM, or triggered automatically after an OOM crash prompt
- !nvidia-smi / !nproc- shell commands to check the actual GPU model and CPU core count assigned to your VM
- Idle vs. total timeout- disconnects after ~90 min of inactivity or a hard ceiling near 12 hours regardless of activity
Colab disconnects idle runtimes after roughly 90 minutes and enforces a hard 12-hour session limit even if active — periodically checkpoint models and outputs to Google Drive so long training runs survive a disconnect.