Colab Features & Tips
Colab Features & Tips
Section titled “Colab Features & Tips”Colab Forms
Section titled “Colab Forms”Create interactive UI elements with #@param annotations:
#@title Configurationlearning_rate = 0.001 #@param {type:"number"}epochs = 10 #@param {type:"slider", min:1, max:100}model_type = "ResNet50" #@param ["ResNet50", "VGG16", "EfficientNet"]use_augmentation = True #@param {type:"boolean"}description = "My experiment" #@param {type:"string"}
print(f"Training {model_type} for {epochs} epochs at lr={learning_rate}")Secrets (API Keys)
Section titled “Secrets (API Keys)”Store sensitive values securely — not in notebook code:
# Access via Colab Secrets (left sidebar → key icon)from google.colab import userdata
api_key = userdata.get('OPENAI_API_KEY')hf_token = userdata.get('HF_TOKEN')Never hardcode API keys in notebooks — they get committed to GitHub.
Colab AI (Gemini Integration)
Section titled “Colab AI (Gemini Integration)”Colab has built-in AI assistance powered by Gemini:
Ctrl+I— open AI chat panelAlt+Enter— generate code from comment- Explain code, fix errors, generate cells
# Type a comment and press Alt+Enter to generate code# Load a CSV file and show basic statisticsGitHub Integration
Section titled “GitHub Integration”# Clone a repository!git clone https://github.com/username/repo.git%cd repo
# Or open directly from GitHub# File → Open notebook → GitHub tab → paste URL
# Commit changes back!git config --global user.email "you@example.com"!git config --global user.name "Your Name"!git add .!git commit -m "Update notebook"!git pushInstalling Packages
Section titled “Installing Packages”# Install for current session!pip install transformers accelerate datasets
# Install specific version!pip install torch==2.1.0
# Install from GitHub!pip install git+https://github.com/huggingface/transformers.git
# Conda (slower but available)!pip install condacolabimport condacolabcondacolab.install()!conda install -c conda-forge rdkitNote: Installations are lost when the session ends. Add installs at the top of your notebook.
Persistent Storage Patterns
Section titled “Persistent Storage Patterns”# Option 1: Google Drive (recommended)from google.colab import drivedrive.mount('/content/drive')SAVE_PATH = '/content/drive/MyDrive/my_project/'
# Option 2: Download results before session endsfrom google.colab import filesfiles.download('model_weights.pth')
# Option 3: Upload to cloud storagefrom google.cloud import storage# ... GCS upload code
# Option 4: Push to GitHub!git push origin mainColab with Hugging Face
Section titled “Colab with Hugging Face”!pip install transformers datasets accelerate
from transformers import pipeline
# Text generationgenerator = pipeline('text-generation', model='gpt2')result = generator("The future of AI is", max_length=50)print(result[0]['generated_text'])
# Image classificationclassifier = pipeline('image-classification', model='google/vit-base-patch16-224')
# Use HF token for gated modelsfrom huggingface_hub import loginfrom google.colab import userdatalogin(token=userdata.get('HF_TOKEN'))Colab with OpenAI
Section titled “Colab with OpenAI”!pip install openai
from openai import OpenAIfrom google.colab import userdata
client = OpenAI(api_key=userdata.get('OPENAI_API_KEY'))
response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "Explain transformers in 3 sentences"}])print(response.choices[0].message.content)Sharing & Collaboration
Section titled “Sharing & Collaboration”Sharebutton — share like a Google Doc (view/comment/edit)File → Save a copy in GitHub— save to a repoFile → Download → .ipynb— download notebook- Published notebooks:
File → Publish to GitHub Gist
Colab Pro Tips
Section titled “Colab Pro Tips”# Prevent session timeout (run in browser console)# Open browser DevTools → Console → paste:function ClickConnect(){ console.log("Keeping alive..."); document.querySelector("colab-toolbar-button#connect").click()}setInterval(ClickConnect, 60000)
# Check remaining GPU quota# Runtime → View resources
# Use background execution (Pro+)# Runtime → Run all → close browser tab
# Faster I/O — copy data to /content (local SSD) first!cp /content/drive/MyDrive/large_dataset.zip /content/!unzip /content/large_dataset.zip -d /content/data/Environment Variables
Section titled “Environment Variables”import os
# Set for current sessionos.environ['MY_VAR'] = 'value'
# Or use Colab Secrets (preferred for sensitive values)from google.colab import userdataos.environ['API_KEY'] = userdata.get('API_KEY')Colab Limitations
Section titled “Colab Limitations”- Session resets after inactivity (~90 min) or max runtime (12h free)
- No persistent filesystem (use Drive or download)
- GPU availability not guaranteed on free tier
- Limited to one GPU per session
- No custom domain or public URL (use ngrok for that)
# Expose a local server publicly with ngrok!pip install pyngrokfrom pyngrok import ngrok
# Start a tunnelpublic_url = ngrok.connect(8501)print(f"App URL: {public_url}")
# Run Streamlit app!streamlit run app.py &