Google Colab Free GPU: Setup, Limits, and Fixes
Enable and verify a Google Colab free GPU, understand dynamic usage limits, and fix GPU not available errors with Drive checkpoints and reliable fallbacks.
To enable a Google Colab free GPU, open Runtime -> Change runtime type, select an available GPU accelerator (most often an NVIDIA T4 when capacity permits), save the setting, and verify CUDA access with nvidia-smi and torch.cuda.is_available(). According to the Google Colab Official FAQ, free-tier limits fluctuate dynamically and Google never guarantees fixed daily hours or a specific GPU model.
Because free runtimes can throttle during peak traffic or disconnect after roughly 90 minutes of inactivity, reliable Colab workflows treat every VM as ephemeral. Pairing hardware verification with automatic Google Drive checkpointing and a pre-tested fallback prevents lost epochs when "Cannot connect to GPU backend" appears mid-run.
Key Takeaways
- Dynamic Quotas, Not Fixed Hours: Google Colab adjusts free GPU availability dynamically based on global demand and recent account usage, so never plan production deadlines around a fixed daily hour count.
- Verify Before Loading Weights: Always run a CUDA pre-flight check (
torch.cuda.is_available(), VRAM total, and compute capability) in cell 1 before downloading multi-gigabyte model checkpoints.- Account-Level Lockouts: Factory resetting a runtime or refreshing the browser will not clear
"GPU not available"errors because cooldowns attach to your Google account.- Built-In Recovery & Fallbacks: Save PyTorch checkpoints to
/content/driveevery epoch, and switch to Kaggle’s 30-hour weekly free GPU pool, local hardware, or paid Compute Units when Colab throttles.
How to Enable and Verify a Google Colab Free GPU
Enabling a free GPU in Google Colab takes under 30 seconds through the Runtime menu, followed by a quick Python verification cell that confirms PyTorch sees the assigned CUDA device. Skipping verification is a common source of silent CPU fallbacks that run 20x to 40x slower than expected.
Enabling the Hardware Accelerator in Runtime Settings
Every new Colab notebook boots on a CPU-only container by default. Switching to a GPU restarts the container on a new virtual machine and clears any variables already in memory, so switch the accelerator before running your first installation cell.
- Open your notebook at
colab.research.google.comand click Runtime in the top menu bar. - Select Change runtime type from the dropdown menu.
- Under Hardware accelerator, choose T4 GPU (or the free GPU option currently listed for your account).
- Click Save, then click Connect in the top-right toolbar to provision the VM.
Once connected, click the RAM/Disk meter in the top-right corner to inspect live system RAM, GPU VRAM, and ephemeral disk usage. If you previously ran other notebooks in separate tabs, open Runtime -> Manage sessions and terminate unused GPU sessions immediately so they stop draining your account’s dynamic quota.
For terminal-first workflows, you can also connect local agents via the official Colab MCP Server on GitHub and our Google Colab MCP with Claude Code guide.
Verifying CUDA, VRAM, and Precision Support in Python
Never assume the UI badge means PyTorch can allocate tensors on the GPU. Run this diagnostic cell at the top of every notebook to log the exact GPU name, total VRAM, CUDA version, and whether hardware bfloat16 is supported (NVIDIA T4 Turing cards support float16 Tensor Cores natively, whereas bfloat16 requires Ampere or newer).
import subprocess
import torch
def verify_colab_gpu() -> dict[str, object]:
"""Verify CUDA availability, VRAM capacity, and precision support in Colab."""
if not torch.cuda.is_available():
raise RuntimeError(
"CUDA is unavailable. Check Runtime -> Change runtime type and select a GPU."
)
device_idx = torch.cuda.current_device()
props = torch.cuda.get_device_properties(device_idx)
total_vram_gb = round(props.total_memory / (1024 ** 3), 2)
report = {
"gpu_name": props.name,
"vram_gb": total_vram_gb,
"cuda_version": torch.version.cuda,
"compute_capability": f"{props.major}.{props.minor}",
"bf16_supported": torch.cuda.is_bf16_supported(),
}
for key, val in report.items():
print(f"{key}: {val}")
smi = subprocess.run(
["nvidia-smi", "--query-gpu=name,memory.total,memory.free,driver_version", "--format=csv,noheader"],
capture_output=True,
text=True,
check=True,
)
print("nvidia-smi:", smi.stdout.strip())
return report
gpu_info = verify_colab_gpu()
Raising a RuntimeError immediately when torch.cuda.is_available() returns False stops the notebook before wasting time downloading datasets onto a CPU container. Checking bf16_supported also prevents runtime crashes when copying scripts originally written for A100 or L4 GPUs onto a T4.
Google Colab Free GPU Limits: Why Quotas Fluctuate
Google Colab offers free GPU compute by enforcing unpublished, dynamic usage limits rather than fixed daily hour quotas. Free sessions also enforce an idle disconnect around 90 minutes and an upper continuous session ceiling around 12 hours, after which the virtual machine recycles and wipes local storage.
Dynamic Usage Limits vs Guaranteed Hours
Many older tutorials promise “12 free GPU hours every day,” which leads to failed training runs when Colab cuts off access after three hours during high-traffic periods. Google’s FAQ explicitly states that free resources are neither guaranteed nor unlimited and that usage thresholds vary over time.
Three factors drive how quickly your account hits a temporary free-tier throttle:
- Global Platform Demand: Peak academic and business hours shrink the unallocated GPU pool across regions.
- Recent Account Consumption: Heavy back-to-back GPU runs over consecutive days trigger steeper cooldowns than sporadic interactive notebooks.
- Interactive Usage Signals: Colab prioritizes active, cell-by-cell experimentation over unattended long-running training scripts.
Idle Timeouts, 12-Hour Session Ceilings, and Policy Boundaries
Even when your account has plenty of quota remaining, two hard lifecycle boundaries govern every free runtime:
| Constraint | Typical Free-Tier Behavior | What Happens When Triggered |
|---|---|---|
| Idle Timeout | ~90 minutes with no browser interaction or execution | VM disconnects, GPU returns to pool, /content files are wiped |
| Max Session Lifetime | Up to ~12 hours continuous runtime (can be shorter under load) | Forced VM recycle regardless of active training progress |
| Background Execution | Not supported on Free tier | Closing the browser tab starts the idle disconnect countdown |
| Anti-Idle Scripts | Prohibited by Colab Terms of Service | Risk of temporary or permanent GPU access restriction |
Avoid browser console auto-clicker scripts or hidden keep-alive loops that attempt to circumvent idle timeouts. Those workarounds violate Google’s acceptable use rules and can result in account-level GPU restrictions far longer than a standard cooldown. If your project requires guaranteed unattended execution, compare paid compute tiers in our Google Colab free vs paid pricing breakdown.
Fixing ‘Colab GPU Not Available’ and Choosing a Reliable Fallback
When Colab displays "Cannot connect to GPU backend due to usage limits", first terminate any orphaned GPU tabs under Runtime -> Manage sessions; if the lockout persists, your Google account is in an unpublished cooldown period and you should switch to a fallback platform rather than repeatedly retrying.
Figure 1: Diagnostic and fallback decision path when Google Colab refuses a free GPU allocation.
Immediate Diagnostics: Active Sessions vs Account Cooldowns
Before assuming your account is throttled, rule out a self-inflicted session cap. Free accounts generally cannot hold multiple active GPU runtimes simultaneously across open browser tabs.
Open Runtime -> Manage sessions in Colab and inspect the list of active VMs. Terminate any old GPU sessions left running in background tabs, wait 60 seconds, and try connecting once more.
If zero active sessions appear and the error persists, you have hit a dynamic account cooldown. Factory resetting the runtime, clearing cookies, or switching browsers will not clear the lockout because the quota lives on Google’s backend.
Four Reliable Fallbacks When Colab Locks Out Free GPUs
Rather than waiting blindly for an unknown 6-to-24-hour cooldown to expire, route your workload to the right fallback based on budget and VRAM needs:
- Kaggle Notebooks (Best Immediate Free Fallback): Phone-verified accounts receive a predictable 30-hour rolling weekly GPU quota on Dual NVIDIA T4 hardware (
GPU T4 x2), documented in the Kaggle Notebooks Documentation and benchmarked in our Google Colab vs Kaggle Notebooks comparison. - Switch to CPU for Preprocessing: Keep editing data-cleaning, tokenization, and plotting cells on a free Colab CPU runtime while waiting for your GPU cooldown to clear, saving GPU minutes strictly for forward/backward passes.
- Run Locally on Consumer Hardware: If your workload fits within 8 GB to 24 GB of VRAM (such as QLoRA adapters or 7B-14B quantized inference), local consumer cards eliminate cloud session caps altogether.
- Upgrade via Colab Compute Units or Google AI Plans: For urgent deadlines requiring L4, A100, or H100 access and background execution, review standalone units on the Google Colab pricing page or bundled benefits in the Google Developers Blog announcement for Google AI plans.
Protecting Training Progress From Idle Timeouts and VM Recycles
Every file saved inside /content lives on an ephemeral virtual disk that disappears the moment your Colab runtime disconnects. Mounting Google Drive and writing atomic checkpoints after every epoch guarantees you never lose hours of fine-tuning work to an unexpected timeout.
Figure 2: Files inside /content are wiped on VM disconnect, whereas checkpoints written to /content/drive persist across runtime restarts.
Mounting Google Drive for Persistent Checkpoints
Mount your Google Drive at the start of any training notebook so datasets and model weights read and write across session boundaries:
from pathlib import Path
from google.colab import drive
drive.mount("/content/drive")
CHECKPOINT_DIR = Path("/content/drive/MyDrive/colab_checkpoints/run_01")
CHECKPOINT_DIR.mkdir(parents=True, exist_ok=True)
print(f"Checkpoints will persist in: {CHECKPOINT_DIR}")
Copy small datasets from Drive into local /content/data at startup for faster disk I/O during training, while keeping all outgoing weight checkpoints pointed directly at CHECKPOINT_DIR inside Drive.
Writing a Resumable PyTorch Training Loop
Saving only model.state_dict() forces you to restart optimizer momentum and learning-rate schedules from scratch after a disconnect. Save the epoch index, model weights, and optimizer state together, and auto-resume from the latest file on startup.
from pathlib import Path
import torch
import torch.nn as nn
def save_checkpoint(
path: Path,
epoch: int,
model: nn.Module,
optimizer: torch.optim.Optimizer,
val_loss: float,
) -> None:
"""Atomically write a resumable training checkpoint to persistent storage."""
tmp_path = path.with_suffix(".tmp")
torch.save(
{
"epoch": epoch,
"model_state_dict": model.state_dict(),
"optimizer_state_dict": optimizer.state_dict(),
"val_loss": val_loss,
},
tmp_path,
)
tmp_path.replace(path)
def load_latest_checkpoint(
path: Path,
model: nn.Module,
optimizer: torch.optim.Optimizer,
device: torch.device,
) -> int:
"""Resume from an existing checkpoint if present, returning the next epoch."""
if not path.exists():
return 0
state = torch.load(path, map_location=device, weights_only=True)
model.load_state_dict(state["model_state_dict"])
optimizer.load_state_dict(state["optimizer_state_dict"])
print(f"Resumed from epoch {state['epoch']} (val_loss={state['val_loss']:.4f})")
return int(state["epoch"]) + 1
Writing to a .tmp file before calling tmp_path.replace(path) prevents half-written, corrupted checkpoint files if Colab terminates the VM mid-save. When fine-tuning larger language models on limited VRAM, combine this checkpointing pattern with 4-bit quantization as shown in our Llama fine-tuning tutorial.
Troubleshooting CUDA OOM, False CUDA Checks, and Slow Data Loading
Most remaining Colab GPU failures come from installing a CPU-only PyTorch wheel, exceeding 16 GB VRAM on an NVIDIA T4, or bottlenecking the GPU by streaming tiny files directly over Google Drive FUSE. Resolving these three issues recovers full GPU utilization quickly.
Fixing torch.cuda.is_available() Returning False
Colab ships with CUDA-enabled PyTorch pre-installed. Running pip install torch without specifying a CUDA index URL can occasionally overwrite the pre-installed build with a mismatched binary or break driver compatibility.
Never reinstall torch unless a library explicitly requires a newer version. If you must upgrade PyTorch, pin the matching CUDA wheel index URL from the PyTorch CUDA Semantics Documentation and restart the runtime afterward (Runtime -> Restart session).
Eliminating CUDA Out-of-Memory Errors on 16 GB VRAM
Free-tier T4 GPUs provide roughly 15 GB of usable VRAM after CUDA context overhead. Training even moderate transformer models in full float32 triggers torch.OutOfMemoryError rapidly unless you enable mixed precision and gradient accumulation.
import gc
import torch
from torch.amp import GradScaler, autocast
def run_memory_safe_step(
model: torch.nn.Module,
inputs: torch.Tensor,
targets: torch.Tensor,
loss_fn: torch.nn.Module,
optimizer: torch.optim.Optimizer,
scaler: GradScaler,
accum_steps: int = 4,
step_idx: int = 0,
) -> float:
"""Execute an FP16 mixed-precision step with gradient accumulation for 16 GB GPUs."""
with autocast(device_type="cuda", dtype=torch.float16):
logits = model(inputs)
loss = loss_fn(logits, targets) / accum_steps
scaler.scale(loss).backward()
if (step_idx + 1) % accum_steps == 0:
scaler.step(optimizer)
scaler.update()
optimizer.zero_grad(set_to_none=True)
return float(loss.item() * accum_steps)
def clear_gpu_memory() -> None:
"""Release unreferenced tensors and cached allocator blocks after an OOM crash."""
gc.collect()
torch.cuda.empty_cache()
| Colab GPU Error | Primary Root Cause | Deterministic Fix |
|---|---|---|
GPU not available on connect |
Active GPU session in another tab or dynamic account cooldown | Close sessions in Manage sessions; if still locked, move to Kaggle T4 x2 fallback |
torch.cuda.is_available() is False |
Notebook still on CPU runtime or overwritten CPU-only torch wheel |
Switch Change runtime type to GPU; avoid bare pip install torch |
CUDA out of memory on T4 |
Full FP32 weights/activations exceeding ~15 GB usable VRAM | Enable autocast(dtype=torch.float16), cut batch size, use gradient accumulation |
| Training stalls at 0% GPU util | Reading thousands of small files directly from /content/drive |
Copy dataset archive to /content/ once and unzip locally before training |
If your models consistently outgrow 16 GB VRAM even with float16 mixed precision and gradient accumulation, review our best GPU for AI hardware guide to size 24 GB to 80 GB options accurately.
Frequently Asked Questions About Google Colab Free GPU
Does Google Colab guarantee a specific free GPU or fixed daily hours?
No, Google states in the official Colab FAQ that free usage limits fluctuate dynamically based on overall demand and recent account activity. Neither a fixed hourly allowance nor a specific GPU model is guaranteed on the free tier.
How do you enable and verify a GPU in Google Colab?
Open Runtime, choose Change runtime type, select a GPU accelerator such as T4, and save to reconnect the virtual machine. Run !nvidia-smi and torch.cuda.is_available() in the first cell to confirm CUDA is active before loading models.
Why does Google Colab say GPU not available?
The message appears when your account crosses its dynamic free-tier usage threshold or when regional free GPU pools reach capacity. Cooldown periods are unpublished and can last anywhere from a few hours to more than 24 hours.
Does factory resetting a runtime bypass Colab GPU usage limits?
No, factory resetting a runtime or opening a fresh browser tab only clears the local virtual machine state. Usage lockouts are enforced at the Google account level, so resetting will not restore GPU access early.
How do you save PyTorch weights so a Colab disconnect does not wipe progress?
Mount Google Drive with drive.mount('/content/drive') and write model, optimizer, and epoch state dictionaries directly into a Drive folder every epoch. Ephemeral files stored under /content are deleted permanently when a runtime recycles.
What is the best free fallback when Google Colab GPU is unavailable?
Kaggle Notebooks is the strongest immediate free fallback because phone-verified accounts receive a predictable 30-hour weekly GPU quota on Dual T4 hardware. For offline or uninterrupted runs, pair quantized local models with consumer GPUs or add paid Colab Compute Units.
Building a Disconnect-Proof Colab Workflow
Treat every Google Colab free GPU session as a short-lived compute burst rather than a persistent server. Drop verify_colab_gpu() into cell 1 of your template notebook, mount Google Drive in cell 2, and wire save_checkpoint() into every epoch loop before starting any multi-hour run.
When you finish a session, click Runtime -> Disconnect and delete runtime manually instead of letting the 90-minute idle timer burn your dynamic quota. Keeping a ready-to-run Kaggle Notebooks copy of your repository ensures a temporary Colab lockout never stalls an experiment.
If your models consistently require more than 16 GB of VRAM or uninterrupted 24/7 availability, size your local memory budget with our VRAM requirements for AI models guide before committing to dedicated hardware or recurring cloud GPU bills.