惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

腾讯CDC
N
Netflix TechBlog - Medium
Google DeepMind News
Google DeepMind News
Scott Helme
Scott Helme
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
小众软件
小众软件
月光博客
月光博客
有赞技术团队
有赞技术团队
Microsoft Security Blog
Microsoft Security Blog
爱范儿
爱范儿
WordPress大学
WordPress大学
Jina AI
Jina AI
M
MIT News - Artificial intelligence
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
阮一峰的网络日志
阮一峰的网络日志
B
Blog RSS Feed
P
Proofpoint News Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
F
Fortinet All Blogs
Y
Y Combinator Blog
Microsoft Azure Blog
Microsoft Azure Blog
云风的 BLOG
云风的 BLOG
Hugging Face - Blog
Hugging Face - Blog
MongoDB | Blog
MongoDB | Blog
I
InfoQ
Vercel News
Vercel News
C
Check Point Blog
美团技术团队
V
V2EX
量子位
博客园 - 三生石上(FineUI控件)
D
DataBreaches.Net
G
Google Developers Blog
博客园_首页
J
Java Code Geeks
Recent Announcements
Recent Announcements
人人都是产品经理
人人都是产品经理
H
Help Net Security
博客园 - Franky
The GitHub Blog
The GitHub Blog
V
Visual Studio Blog
T
Tailwind CSS Blog
IT之家
IT之家
S
SegmentFault 最新的问题
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
雷峰网
雷峰网
L
LangChain Blog
博客园 - 司徒正美
T
The Blog of Author Tim Ferriss
H
Hackread – Cybersecurity News, Data Breaches, AI and More

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Google Colab: Free GPUs in Your Browser
Akhilesh · 2026-05-04 · via DEV Community

Your laptop has a CPU.

A CPU runs code one operation at a time, very fast. For Python scripts, data processing, and small models, it is completely fine.

Training a neural network is different. A single training step involves millions of matrix multiplications. A CPU does these sequentially. Even a decent laptop CPU takes minutes per epoch on a small image dataset. A real training run can take hours. Or days.

A GPU does those same matrix multiplications in parallel. Thousands of cores, all working simultaneously. What took 4 hours on a CPU takes 8 minutes on a GPU.

You probably do not own a GPU. Google does, and they will let you use one for free.

That is Google Colab.


What Colab Is

Google Colab is Jupyter Notebooks running in the cloud on Google's infrastructure. Open your browser. Go to colab.research.google.com. Start coding. No installation. No setup. Python is already there. The most common data science libraries are already installed.

And you can switch on a free GPU with two clicks.

Every notebook is saved to Google Drive automatically. Share it with anyone via a link. They open the same notebook in their browser and run it too.


Getting Started in Two Minutes

Go to colab.research.google.com.

Click "New notebook."

You see a blank Jupyter-style notebook. Type in the first cell:

print("Hello from Colab")
import sys
print(f"Python {sys.version}")

Enter fullscreen mode Exit fullscreen mode

Press Shift+Enter. It runs. Output appears.

Check what is already installed:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sklearn
import tensorflow as tf
import torch

print(f"Pandas:     {pd.__version__}")
print(f"NumPy:      {np.__version__}")
print(f"TensorFlow: {tf.__version__}")
print(f"PyTorch:    {torch.__version__}")

Enter fullscreen mode Exit fullscreen mode

Output:

Pandas:     2.1.4
NumPy:      1.25.2
TensorFlow: 2.15.0
PyTorch:    2.1.0+cu121

Enter fullscreen mode Exit fullscreen mode

All the major libraries. Ready. No pip install. No environment setup. No compatibility headaches. Just work.


Enabling the GPU: Two Clicks

This is the most important thing in this post.

Go to: Runtime → Change runtime type → Hardware accelerator → T4 GPU → Save

Then verify it worked:

import torch

print(f"GPU available: {torch.cuda.is_available()}")
print(f"GPU name: {torch.cuda.get_device_name(0)}")
print(f"GPU memory: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB")

Enter fullscreen mode Exit fullscreen mode

Output:

GPU available: True
GPU name: Tesla T4
GPU memory: 15.8 GB

Enter fullscreen mode Exit fullscreen mode

15.8 gigabytes of GPU memory. Free. This is a Tesla T4, the same GPU used in production inference servers at major tech companies.

For TensorFlow:

import tensorflow as tf

gpus = tf.config.list_physical_devices('GPU')
print(f"GPUs available: {len(gpus)}")
for gpu in gpus:
    print(f"  {gpu.name}")

Enter fullscreen mode Exit fullscreen mode


The Speed Difference Is Real

Run this comparison to feel the GPU advantage:

import torch
import time

size = 10000
A = torch.randn(size, size)
B = torch.randn(size, size)

start = time.time()
C_cpu = torch.matmul(A, B)
cpu_time = time.time() - start

A_gpu = A.cuda()
B_gpu = B.cuda()
torch.cuda.synchronize()

start = time.time()
C_gpu = torch.matmul(A_gpu, B_gpu)
torch.cuda.synchronize()
gpu_time = time.time() - start

print(f"CPU: {cpu_time:.3f} seconds")
print(f"GPU: {gpu_time:.3f} seconds")
print(f"Speedup: {cpu_time/gpu_time:.0f}x")

Enter fullscreen mode Exit fullscreen mode

Output:

CPU: 4.821 seconds
GPU: 0.018 seconds
Speedup: 268x

Enter fullscreen mode Exit fullscreen mode

268 times faster on a 10,000×10,000 matrix multiplication. Neural network training is essentially millions of these operations. This is why the GPU matters.


Connecting to Google Drive

Your Colab session is temporary. When the session ends (after 12 hours or when you disconnect), all files you created are gone.

Mount Google Drive to save work permanently:

from google.colab import drive
drive.mount('/content/drive')

Enter fullscreen mode Exit fullscreen mode

A popup asks you to sign in to Google and grant permission. After that:

import pandas as pd

df = pd.read_csv('/content/drive/MyDrive/data/titanic.csv')
print(df.shape)

results = df.groupby('Survived')['Age'].mean()
results.to_csv('/content/drive/MyDrive/results/survival_by_age.csv')
print("Saved to Drive")

Enter fullscreen mode Exit fullscreen mode

Your Google Drive appears at /content/drive/MyDrive/. Read files from it. Write files to it. They persist after the session ends.

This is your workflow: keep datasets in Google Drive, read them into Colab, process with GPU, save results back to Drive.


Installing Packages That Are Not Pre-Installed

Most things are already there. For anything else:

!pip install -q transformers accelerate datasets

import transformers
print(f"Transformers: {transformers.__version__}")

Enter fullscreen mode Exit fullscreen mode

The -q flag suppresses the verbose installation output. The installation is instant because Colab already has most packages cached.

Installations do not persist between sessions. If you disconnect and reconnect, you need to reinstall. Put your installs in the first cell of the notebook so they run automatically when you open the session.


Uploading Files Directly

For small files you want to upload once:

from google.colab import files

uploaded = files.upload()

for filename in uploaded.keys():
    print(f"Uploaded: {filename}")
    df = pd.read_csv(filename)
    print(df.head())

Enter fullscreen mode Exit fullscreen mode

A file picker dialog appears. Select your CSV from your local machine. It uploads to the Colab session's /content/ folder.

Download files back to your machine:

from google.colab import files
files.download('results.csv')

Enter fullscreen mode Exit fullscreen mode


GPU Memory Management

The T4 GPU has 15.8GB but it fills up fast during training. Monitor it:

!nvidia-smi

Enter fullscreen mode Exit fullscreen mode

Output shows:

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 525.105.17   Driver Version: 525.105.17   CUDA Version: 12.0    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |
| N/A   52C    P0    28W /  70W |   3821MiB / 15360MiB |      0%      Default |
+-----------------------------------------------------------------------------+

Enter fullscreen mode Exit fullscreen mode

3821MB used out of 15360MB. Plenty of headroom. When training crashes with "CUDA out of memory," reduce your batch size. Cutting batch size in half roughly halves the GPU memory usage.

Free GPU memory manually:

import torch
import gc

del model
torch.cuda.empty_cache()
gc.collect()

print(f"GPU memory after cleanup: {torch.cuda.memory_allocated()/1e9:.2f} GB")

Enter fullscreen mode Exit fullscreen mode


The Colab Limits You Need to Know

Session limit: Free Colab sessions disconnect after about 12 hours of runtime. If training takes longer than 12 hours, use checkpoints.

Idle disconnect: If your browser tab is inactive for too long (around 90 minutes), the session disconnects. Keep the tab open and interact with it occasionally during long runs.

GPU availability: The free tier gives you a GPU most of the time but not always. If GPUs are in high demand, you might get CPU only. Try again later or use a different account.

RAM limit: 12GB of system RAM. Large datasets can fill this. Use chunked loading for very large CSVs.

Not persistent: Files in /content/ vanish when the session ends. Only /content/drive/ persists. Always save important outputs to Drive.

For serious training that takes days, Colab Pro (around $10/month) gives longer sessions, more RAM, and guaranteed GPU access. Worth it when you are in the deep learning phase of this series.


Sharing Your Notebook

Every Colab notebook has a share button in the top right, just like Google Docs.

Click Share → change "Restricted" to "Anyone with the link can view."

Now anyone with the link can open your notebook, see all your code and outputs, and run it themselves on their own Colab session.

This is how you share data science work with collaborators and how you submit homework in courses that use Colab. One link. No setup on their end.


A Real Colab Workflow

Here is what the full workflow looks like when you start a deep learning project.

# Cell 1: Mount Drive and install extras
from google.colab import drive
drive.mount('/content/drive')
!pip install -q wandb

# Cell 2: Verify GPU
import torch
assert torch.cuda.is_available(), "GPU not available. Go to Runtime → Change runtime type."
print(f"GPU: {torch.cuda.get_device_name(0)}")

# Cell 3: Load data from Drive
import pandas as pd
df = pd.read_csv('/content/drive/MyDrive/datasets/train.csv')
print(f"Loaded: {df.shape}")

# Cell 4: Training setup
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f"Training on: {device}")

# ... training code ...

# Final cell: Save model to Drive
torch.save(model.state_dict(), '/content/drive/MyDrive/models/model_v1.pt')
print("Model saved to Drive")

Enter fullscreen mode Exit fullscreen mode

Mount Drive. Verify GPU. Load data from Drive. Train. Save to Drive. That sequence repeats for every deep learning project you do in this series.


Colab vs Local Jupyter: When to Use Which

Use Colab when:

  • Training neural networks that need a GPU
  • Working with large models (transformers, image classifiers)
  • Sharing work with others quickly via a link
  • Your local machine is slow or old
  • You want someone else to review your analysis

Use local Jupyter when:

  • Working offline
  • Your data is sensitive and should not leave your machine
  • You have a good local GPU
  • You want faster iteration on small experiments
  • Long sessions that would time out on Colab

In practice you use both. Explore and clean data locally. Train models on Colab. This series will move to Colab explicitly when neural networks begin in Phase 7.


A Resource Worth Knowing

Weights & Biases has a series of Colab notebooks called "W&B Colab Examples" that show professional-grade training setups with experiment tracking, GPU utilization monitoring, and model checkpointing. These are real production patterns implemented in Colab. Go to wandb.ai/tutorials and look for the PyTorch and TensorFlow Colab examples. They set the standard for how serious practitioners use Colab.


Try This

Open a new Colab notebook. Name it colab_gpu_test.ipynb.

Enable GPU runtime. Verify it is active with torch.cuda.is_available().

Run the CPU vs GPU speed comparison from this post. Print the speedup ratio.

Mount your Google Drive. Create a folder called colab_practice in your Drive. Write a small CSV file (any data you want) directly from Colab into that folder. Read it back and print the first five rows. Confirm the file appears in your Google Drive through the Drive UI.

Train a tiny neural network on the MNIST handwritten digits dataset using PyTorch on the GPU. MNIST is built into torchvision. Train for five epochs. Print training loss per epoch. Save the trained model weights to your Google Drive.

Share the notebook link (view only) and include it in the README of your GitHub repository.


Phase 5 Complete

Five posts covering the tools that make you a professional rather than a hobbyist.

Git so you never lose code. GitHub so your work is visible and your portfolio is building. Jupyter for interactive analysis. Colab for GPU-powered experiments.

These are not exciting topics. Nobody posts on Twitter about mastering git stash. But the engineers who use these tools properly ship better work, collaborate more effectively, and get hired more consistently than engineers who treat them as afterthoughts.

Phase 6 starts now. Machine learning. Real algorithms. Real predictions. Everything from the previous five phases was preparation. This is where it gets real.