How to Train AI Models on Google Colab Without Losing Your Progress

How to Train AI Models on Google Colab Without Losing Your Progress

It was epoch 47 out of 60. The loss was finally going down, I was already imagining the finished model, and then the tab greeted me with a friendly little message: “Runtime disconnected.” Everything was gone. The model, the optimizer state, the dataset I extracted, three hours of GPU time. All of it. If you have ever trained a model on Google Colab, you know this moment. And if you haven’t yet — you will. This article is about understanding what Colab actually is under the hood, why it behaves the way it does, and how to build a training workflow that survives it. Everything in this article is one runnable notebook — open it directly in Colab or check out the GitHub repo. Let’s find out. What is Colab, really? At its core, Colab is a borrowed virtual machine with a Jupyter notebook glued on top. That’s it. When you open a notebook and hit “Connect”, Google finds a VM somewhere in its fleet, attaches it to your notebook, and calls this pairing a runtime. This one sentence explains almost every problem you will ever have with Colab: The VM is borrowed, not yours. Google can take it back. When demand is high, it takes it back sooner. The disk is part of the VM. Everything under /content lives on the VM’s local disk. When the runtime dies, /content dies with it. Your notebook file survives (it lives in Drive), but nothing your code created does. The environment is part of the VM too. Every fresh runtime is a fresh Ubuntu image with preinstalled packages that Google updates whenever it wants. Your notebook from three months ago runs on today’s image, not the one it was written for. On the free tier, how long you keep the VM is decided by dynamic, unpublished quotas that depend on real-time demand. On the paid tiers (Pro / Pro+), you buy compute units — a T4 sips them slowly, an A100 drinks them fast — and once they run out, you fall back into a lower priority queue that behaves a lot like the free tier. So the rule that drives this whole article is simple: Treat every Colab session as if it will die in the next five minutes. Because sometimes, it will. The Magical Mechanics 1. Runtime types and GPU allocation What it does: Runtime → Change runtime type lets you ask for a hardware accelerator: a GPU (usually T4 on the free tier, A100/L4 on paid tiers) or a TPU. How to use it: Pick the GPU runtime before you start working — changing it later restarts the VM and wipes /content. Then verify what you actually got: !nvidia-smi Behind the scenes: You are not choosing a GPU — you are requesting one. Colab matches you with whatever is available in the pool at that moment. Free tier users usually get a T4 or the famous “You cannot currently connect to a GPU” message. Even on the highest paid tiers, the newest GPUs are scarce: users report that H100 requests silently fall back to A100s. So never assume the hardware — check nvidia-smi and adapt batch size and precision to what you were given. 2. Mounting Google Drive What it does: Makes your Google Drive appear as a folder inside the VM, so your files survive when the runtime doesn’t. How to use it: from google.colab import drive drive.mount('/content/drive') After authorizing, your files are under /content/drive/MyDrive/. Behind the scenes: This is the most misunderstood mechanic in Colab. The mount is not a disk. It is a network filesystem (FUSE) where every file operation becomes an API call to Google Drive’s servers. Reading one big file is fine. Reading 50,000 small image files during training means 50,000 network round-trips per epoch — this is why your GPU spends 95% of its time waiting for data. It is also why Drive answers with 403/429 quota errors when your dataloader hammers it. The fix is one simple habit, and we’ll use it in the example below: Drive is for storage, /content is for work. 3. ! shell cells vs Python cells What it does: A ! prefix runs a shell command on the VM instead of Python. How to use it: !unzip -q /content/dataset.zip -d /content/data !pip install -q ultralytics==8.3.0 Behind the scenes: Every ! command spawns a new shell that dies when the line ends — that’s why !cd folder never works (the directory change dies with the shell; use %cd instead). And prefer %pip install over !pip install: the % version makes sure packages install into the same Python environment your notebook kernel is actually using. 4. Checkpointing — your seatbelt What it does: Saves your training progress (model weights + optimizer state + epoch number) somewhere that survives the VM: Drive. How to use it: Save locally first, then copy to Drive — a network hiccup mid-write over the FUSE mount can corrupt a checkpoint, and a corrupted checkpoint is worse than none: torch.save(state, '/content/ckpt.pt') # fast, local, atomic shutil.copy('/content/ckpt.pt', CKPT_DRIVE) # durable Behind the scenes: A checkpoint is just a Python dictionary serialized to disk. The important part is what you put in it: weights alone are not enough to resume training properly. You need the optimizer state (momentum, adaptive learning rates) and the epoch counter, otherwise “resuming” quietly becomes “restarting with a warm start”. 5. Connecting from outside the browser What it does: Lets you use Colab’s cloud GPUs without living inside the browser tab. How to use it: In late 2025, Google released an official Colab extension for VS Code. You install it, sign in, and connect your editor directly to a Colab cloud runtime — your code runs on their GPU while you keep your own editor, keybindings, and sanity. Behind the scenes — and a warning: For years, people used hacky tunnels (colab-ssh, ngrok) to get SSH access into Colab VMs. Do not follow those tutorials today. SSH tunneling into Colab is explicitly prohibited by the terms of service now (ngrok is even IP-blocked), and following an outdated 2022 guide can get your Colab access restricted or banned. The supported paths are: the browser, the official VS Code extension, and local runtimes (connecting the Colab UI to your own machine’s hardware — that one is fully allowed). A Simple Example: Training That Survives a Disconnect Enough theory. Let’s build a small training setup that uses every mechanic above — and then kill it on purpose. The scenario: you have an image classification dataset (any folder-per-class layout works) sitting on your Drive as one zip file. We fine-tune a pretrained ResNet18 on it, checkpoint every epoch, and make the whole notebook re-runnable from zero: if the runtime dies, you just run all cells again and training continues where it stopped. Cell 1 — Pin what you install, record what you got: # pin anything you install yourself, e.g.: # %pip install -q torchmetrics==1.4.0 import sys, torch, torchvision print(sys.version) print("torch:", torch.__version__, "| torchvision:", torchvision.__version__, "| cuda:", torch.version.cuda) print("gpu:", torch.cuda.get_device_name(0) if torch.cuda.is_available() else "none") We pin the versions of everything we install ourselves, and we print the versions of what Colab preinstalled. When this notebook breaks in six months (it will — see “notebook rot” below), this cell tells you exactly which environment it last worked on. Cell 2 — Mount Drive and define the paths: from google.colab import drive drive.mount('/content/drive') import os DRIVE_DIR = '/content/drive/MyDrive/colab_training' DATA_ZIP = f'{DRIVE_DIR}/dataset.zip' CKPT_DRIVE = f'{DRIVE_DIR}/checkpoint.pt' os.makedirs(DRIVE_DIR, exist_ok=True) Everything that must survive the VM lives under one Drive folder: the dataset zip and the checkpoint. Cell 3 — Get the data OFF Drive: zip → copy → extract: if not os.path.exists('/content/data'): !cp "{DATA_ZIP}" /content/dataset.zip !unzip -q -o /content/dataset.zip -d /content/data # find the train folder regardless of how the zip is structured TRAIN_DIR = None for root, dirs, files in os.walk('/content/data'): if os.path.basename(root) == 'train': TRAIN_DIR = root break assert TRAIN_DIR, "No 'train' folder in the zip - expected ImageFolder layout: train//" print("train:", TRAIN_DIR) This is the zip → copy → extract pattern, and it is the single biggest speedup available on Colab. One zip file crosses the network once; after that, every epoch reads from the VM’s fast local disk. Here is the real run on a free-tier T4 — Python 3.12, torch 2.11, and the mount + extraction working: (In my notebook, Cell 2 also auto-downloads a small demo dataset — ants vs bees, ~47 MB — if there is no dataset.zip on Drive yet, so the whole thing is runnable end-to-end without preparing anything.)Cell 4 — Dataset and model: import torch.nn as nn from torchvision import datasets, transforms, models from torch.utils.data import DataLoader tfm = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), ]) train_ds = datasets.ImageFolder(TRAIN_DIR, transform=tfm) train_dl = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=2, pin_memory=True) print(f"{len(train_ds)} images, classes: {train_ds.classes}") device = 'cuda' if torch.cuda.is_available() else 'cpu' model = models.resnet18(weights='IMAGENET1K_V1') model.fc = nn.Linear(model.fc.in_features, len(train_ds.classes)) model = model.to(device) optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4) criterion = nn.CrossEntropyLoss() Cell 5 — Resume if a checkpoint exists: import shutil start_epoch = 0 if os.path.exists(CKPT_DRIVE): ckpt = torch.load(CKPT_DRIVE, map_location=device) model.load_state_dict(ckpt['model']) optimizer.load_state_dict(ckpt['optimizer']) start_epoch = ckpt['epoch'] + 1 print(f"Resuming from epoch {start_epoch}") else: print("No checkpoint found - starting fresh") Cell 6 — Train, and save like the disconnect is coming: EPOCHS = 20 for epoch in range(start_epoch, EPOCHS): model.train() running_loss = 0.0 for x, y in train_dl: x, y = x.to(device), y.to(device) optimizer.zero_grad() loss = criterion(model(x), y) loss.backward() optimizer.step() running_loss += loss.item() print(f"epoch {epoch}: loss {running_loss / len(train_dl):.4f}") # save locally (fast + safe), then copy to Drive (durable) torch.save({'epoch': epoch, 'model': model.state_dict(), 'optimizer': optimizer.state_dict()}, '/content/ckpt.pt') shutil.copy('/content/ckpt.pt', CKPT_DRIVE) Now the fun part. Let a few epochs run, then go to Runtime → Disconnect and delete runtime. This is exactly what a real disconnect does: the VM is gone, /content is gone, your GPU is gone. Reconnect and hit Runtime → Run all. Cells 2–3 re-mount Drive and re-extract the dataset onto the fresh VM. Cell 5 finds the checkpoint on Drive and prints: Resuming from epoch 7 I did exactly this while writing the article — killed the runtime mid-epoch-8 — and here is the real output: And training continues like nothing happened — epochs 7 through 19, straight to the end, finishing at 91.5% validation accuracy: A small detail worth noticing: my interrupt actually landed during the local torch.save() of epoch 8. The local file was garbage — but the Drive copy still held a clean epoch 7. That is the save-locally-then-copy pattern earning its keep: the file that survives is never the file being written when the world ends.That is the difference between losing three hours and losing three minutes. Notice that we didn’t fight the disconnect — we made it irrelevant. The Problems Everyone Hits These are the complaints that come up over and over on Reddit, and what is actually going on behind each one. 1. “My runtime disconnected and I lost everything” Why it happens: the VM is borrowed. Idle too long, or run a heavy sustained workload for hours, and internal quotas pull it back. On the free tier this is aggressive; on Pro it happens when compute units run dry. The fix: the checkpoint-resume pattern from the example. There is no setting that prevents disconnects — only a workflow that shrugs at them. 2. “Training is 10x slower on Colab” / “my GPU sits at 0%” Why it happens: the dataset is being read file-by-file from the Drive mount, so the GPU starves while every image makes a network round-trip. The fix: zip → copy to /content → extract. For datasets too big for the VM disk (~100–200 GB), skip Drive entirely and stream from Google Cloud Storage or S3. 3. “You cannot currently connect to a GPU” Why it happens: GPU allocation on the free tier is demand-based, and heavy recent usage lowers your priority. There is no published quota — it genuinely varies day to day. The fix: there is no trick, despite what the “usage limit bypass” videos claim. Wait (limits usually reset within 24h), use the CPU for preprocessing work in the meantime, or pay for compute units. And when you have a GPU, don’t hold it idle — that spends your invisible quota too. 4. “My notebook worked last month, now the imports fail” Why it happens: notebook rot. Colab updates the base environment (Python, CUDA, PyTorch, TensorFlow) on a rolling basis, and your old notebook meets a new world. CUDA-adjacent libraries (CuPy is a famous victim) break loudest. The fix: pin the versions of everything you install, and print the versions of everything preinstalled (Cell 1 of the example). For anything serious, keep your real logic in .py files in a GitHub repo and let the notebook be a thin runner that clones and calls them — notebooks rot, repos don’t. 5. “CUDA out of memory” Why it happens: a T4 has 16 GB of VRAM, and modern models are hungry. Even paid tiers hit this wall with today’s larger architectures. The fix, in escalating order: smaller batch size → mixed precision (torch.autocast) → gradient accumulation → a smaller backbone. And the honest answer: past a certain model size, Colab is simply the wrong tool. That’s not a failure — that’s graduation. More on it below. 6. “How do I use Colab from VS Code?” Why it comes up: nobody enjoys developing serious code in a browser tab. The fix: the official Google Colab VS Code extension (released November 2025) — connect your editor, or even VS Code forks like Cursor, to a Colab cloud runtime, supported and safe, on the free tier too. What you should not do is follow older SSH/ngrok tunnel tutorials: they are against the terms of service now and people have lost Colab access over them. The Mental Model, in One Table If you remember nothing else from this article, remember this: Beginner assumptionRealityThe runtime is my computerIt’s a borrowed VM — Google takes it backThe Drive mount is a hard diskIt’s a network filesystem — every file read is an API callA saved notebook means saved workOnly the .ipynb survives; everything in /content dies with the VMThe GPU is guaranteedIt’s a request — check !nvidia-smi every sessionThe environment is stableIt’s a rolling image — pin what you installDisconnects can be preventedThey can only be made irrelevant — checkpoint and resume Important Notes The Drive mount is not a disk. Never train directly off /content/drive/.... Storage on Drive, work on /content. Nothing in /content survives the runtime. If it’s not on Drive (or in a repo, or a bucket), it’s already gone — it just doesn’t know it yet. Checkpoint like the disconnect is coming. Because it is. Save locally, copy to Drive, include the optimizer state and epoch number. Verify your GPU every session. !nvidia-smi costs nothing; assuming you got an A100 when you got a T4 costs an OOM crash at the worst moment. Don’t trust Colab tutorials older than ~2025 on anything involving SSH, tunnels, or “unlimited usage tricks”. The rules changed, and some of those tricks are now bannable. Keep Drive folders under ~10,000 items. Giant flat folders break mounts and listings. One zip beats fifty thousand JPEGs, every time. When You Outgrow Colab Colab is a fantastic on-ramp: free GPUs, zero setup, shareable notebooks. But it has a ceiling, and you’ll know you’ve hit it when: your training runs need more than ~12 hours uninterrupted, your model + batch no longer fits in the VRAM you can reliably get, you spend more time fighting quotas than training, you need a reproducible environment that doesn’t shift under your feet. That’s not the moment to buy more compute units. That’s the moment to rent a real GPU. In the next article, we’ll take this exact training workflow — the checkpoints, the pinned versions, the data patterns — and move it to a rented cloud GPU: paid by the hour, real SSH (legally, this time), persistent storage, and how to pick a provider without overpaying. The workflow we built today was portable by design; next time we prove it. Lessons from the Colab Survival Project Colab’s problems are not bugs — they are the deal. You get a free/cheap GPU; in exchange, it’s borrowed, temporary, and shifting. Once you design for that deal instead of against it, Colab becomes genuinely pleasant. The disconnect is not the enemy. Unpreparedness is. The checkpoint-resume pattern took ~15 lines of code and removed the single biggest source of pain. Data locality matters more than GPU speed. The zip-copy-extract habit sped up my training more than any hardware upgrade would have. Know where the exit is. Understanding Colab’s ceiling means you’ll recognize, calmly, the day you need to walk through it. Once you stop treating Colab like your computer and start treating it like a borrowed one, most of its “problems” dissolve into workflow. The disconnects don’t go away — they just stop mattering. Stay tuned for the next article — and happy training!

Original Source

Read the full article at Hackernoon →

KhanList aggregates and links to publicly available news content. We do not host full articles from third-party sources. Always verify important information with original sources.