A Python SDK that turns Google Colab into a remote compute runtime.
from colab import App
app = App()
@app.function(gpu="T4")
def train(epochs: int) -> dict:
import torch
model = torch.nn.Linear(10, 1)
return {"done": True, "epochs": epochs}
result = train.remote(epochs=10)
print(result) # {'done': True, 'epochs': 10}Install · Quick Start · API Reference · Architecture · Contributing
- Why Colab SDK?
- Installation
- Quick Start
- API Reference
- Advanced Usage
- How It Works
- Architecture
- Comparison
- FAQ
- Project Status
- Contributing
- License
Google Colab provides free GPU compute (T4, L4, A100) — but the developer experience is stuck in notebooks. You need to manually upload files, manage cells, and deal with a browser-based workflow. Modern cloud compute platforms like Modal and RunPod solve this, but they're paid.
Colab Client bridges the gap. It gives you the developer experience of modern compute platforms while leveraging Google's free GPU resources.
| Without Colab Client | With Colab Client | |
|---|---|---|
| Workflow | Write code in Jupyter notebooks | Write normal Python files |
| File management | Manual upload/download | Automatic dependency analysis |
| GPU setup | Runtime → Change runtime type → Save | App(gpu="T4") |
| Code reuse | Copy-paste between notebooks | Standard Python imports |
| Cost | Free (Google Colab) | Free (Google Colab) |
- AI/ML learners who want GPU compute without paying for cloud services
- Indie hackers prototyping ML models on a budget
- Students working on research projects with limited resources
- Open-source developers who need GPU for testing and experimentation
- Anyone who finds Colab notebooks tedious but wants free GPUs
- Python 3.10+
- Linux or macOS (Windows users: WSL2)
pip install colab-sdkgit clone https://github.com/heyncth/colab-sdk.git
cd colab-sdk
pip install -e .pip install -e ".[dev]"google-colab-cli requires Unix system modules and does not run on native Windows. Use WSL2:
-
Install WSL2 (run in PowerShell as Admin):
wsl --install -d Ubuntu
-
Restart your machine, then open the Ubuntu terminal.
-
Install Python and the SDK:
sudo apt update && sudo apt install python3 python3-pip -y pip install colab-sdk -
Authenticate with Google Colab:
colab new -s test-session
Follow the OAuth URL in your browser and paste the authorization code.
Tip: If
colabis not found after installation, create a.envfile in your project root:COLAB_BIN_DIR=/home/user/.local/binSee Session docs for details.
from colab import App
app = App() # CPU session by defaultFor GPU:
app = App(gpu="T4") # T4, L4, A100, or H100@app.function
def hello() -> str:
return "Hello from Colab!"With GPU override and timeout:
@app.function(gpu="A100", timeout=600)
def train(epochs: int, lr: float = 0.01) -> dict:
import torch
import time
model = torch.nn.Linear(10, 1)
time.sleep(1) # simulate training
return {"done": True, "epochs": epochs, "lr": lr}# First call takes ~20s (VM provisioning)
result = hello.remote()
print(result) # "Hello from Colab!"
# Subsequent calls are ~2s (session reuse)
result = train.remote(epochs=5, lr=0.001)
print(result) # {'done': True, 'epochs': 5, 'lr': 0.001}app.shutdown() # Terminates the Colab VMSee the integration test for a complete working example.
from colab import App
app = App(
gpu=None, # str | None: "T4", "L4", "A100", "H100", or None for CPU
idle_timeout="30m", # str | None: "30m", "1h", etc.
session_name=None, # str | None: auto-generated if omitted
)Properties:
| Property | Type | Description |
|---|---|---|
app.engine |
ExecutionEngine |
The engine instance (useful for advanced use) |
app.session_name |
str |
The Colab session name |
app.gpu |
str | None |
The GPU type |
app.secrets |
dict[str, str] |
Read-only view of stored secrets |
# Bare decorator
@app.function
def my_func():
...
# With arguments
@app.function(gpu="T4", timeout=300)
def my_func():
...
# Non-decorator form (for pre-defined functions)
my_func = app.function(my_func)result = my_func.remote(*args, debug=False, **kwargs)| Parameter | Type | Description |
|---|---|---|
*args |
tuple |
Positional arguments (must be JSON-serializable) |
debug |
bool |
Print raw VM output to stderr |
**kwargs |
dict |
Keyword arguments (must be JSON-serializable) |
See Function SPEC for complete documentation.
app.login() # Trigger authentication (optional, auto-triggered)
app.shutdown() # Terminate the Colab VMapp.upload("model.pt") # Upload to /content/model.pt
app.upload("data.zip", "/content/data/data.zip") # Upload to custom path
app.download("checkpoint.pt") # Download to ./checkpoint.pt
app.download("/content/logs.txt", "./logs.txt") # Download to custom pathapp.secret("HF_TOKEN", "hf_abc123")
app.secret("WANDB_API_KEY", "wandb_xyz")Secrets are injected as environment variables on the Colab VM before your function executes.
See App SPEC for complete documentation.
When things go wrong, enable debug mode to see every raw line from the VM:
result = train.remote(debug=True, epochs=5)
# [colab-raw] Traceback (most recent call last):
# [colab-raw] ...For the VM to import your functions, they must be at module level (no SDK dependency):
# ----- my_script.py -----
# These run on the VM — NO SDK imports allowed
def hello() -> str:
return "Hello from Colab!"
def add(a: int, b: int) -> int:
return a + b
# This runs locally only
def main():
from colab import App
app = App()
hello_fn = app.function(hello)
add_fn = app.function(add)
print(hello_fn.remote())
print(add_fn.remote(40, 2))
app.shutdown()
if __name__ == "__main__":
main()See the integration test for a complete example of this pattern.
The Analyzer automatically detects external packages:
@app.function
def train():
import torch # → added to requirements
import numpy as np # → added to requirements
...Requirements are cached on the VM by hash — re-installation is skipped if the hash matches.
# CPU session (free, fast startup)
app = App()
# GPU sessions (requires Colab Pro or pay-as-you-go)
app = App(gpu="T4") # Entry-level GPU
app = App(gpu="L4") # Mid-range GPU
app = App(gpu="A100") # High-end GPU (Colab Pro+)
app = App(gpu="H100") # Latest GPU (Colab Pro+)Your Code → Analyzer (AST) → ExecutionManifest → Wrapper (base64 inline)
↓
Colab VM ← colab exec stdin
↓
Function executes → __LAZY_RESULT__
↓
Parse → Return to caller
- Validate — Checks GPU type against known list
- Analyze — Parses your function's AST to discover dependencies and requirements
- Build Wrapper — Base64-encodes all source files into a self-contained Python script
- Ensure Session — Creates Colab VM if needed (lazy, on first call)
- Install Requirements — Installs packages if not cached by hash
- Execute — Sends wrapper code via
colab execstdin - Parse — Streams stdout, detects
__LAZY_RESULT__or__LAZY_ERROR__markers - Return — Deserializes JSON result to caller
See Architecture for the complete system design.
The Colab VM communicates results via structured stdout/stderr markers:
| Marker | Purpose |
|---|---|
__LAZY_RESULT__:{"status":"ok","value":42} |
Successful return value |
__LAZY_ERROR__:{"status":"error",...} |
Exception details with traceback |
__LAZY_LOG__:Training started |
Log messages forwarded in real-time |
__LAZY_PROGRESS__:50 |
Progress updates (0-100) |
See Stdout Protocol for the full specification.
Colab Client consists of six components, each with a single responsibility:
| Component | Responsibility | Docs |
|---|---|---|
| App | SDK entry point, holds configuration | SPEC · ADR |
| RemoteFunction | Function metadata, delegates .remote() |
SPEC · ADR |
| ExecutionEngine | Pipeline orchestrator, retry logic | SPEC · ADR |
| Analyzer | AST-based import resolution | SPEC · ADR |
| Packager | Deterministic tar.gz artifact builder | SPEC · ADR |
| ColabSession | CLI wrapper for google-colab-cli | SPEC · ADR |
- Colab only — No multi-provider abstraction. See ADR-001
- Official CLI — Uses google-colab-cli, no reverse engineering. See ADR-002
- Static analysis — AST-based import resolution, no runtime execution. See ADR-003
- Fail fast — Validate at decoration time, not runtime. See ADR-004
- Persistent session — One App = one VM, lazy creation. See ADR-006
- Inline delivery — Source files sent via base64, no upload needed. See Session ADR
| Document | Description |
|---|---|
| PRD | Product requirements, vision, and scope |
| Architecture | System design, data flow, glossary |
| Progress | Session log, milestones, commit history |
| Future Features | Deferred features catalog (Tiers 1-3) |
| CODING_STANDARDS.md | Python conventions, linting, testing |
| CONTRIBUTING.md | How to contribute |
| CONSTITUTION.md | Project laws and invariants |
| AGENTS.md | AI agent behavior rules |
| Feature | Colab Notebook | Colab Client |
|---|---|---|
| Code editing | Browser-based cells | Any IDE (VS Code, PyCharm, etc.) |
| Version control | Manual export/import | Standard Git workflow |
| Dependencies | !pip install in cells |
Automatic from imports |
| File transfer | Manual upload/download | Automatic + app.upload()/app.download() |
| Session reuse | Manual reconnect | Automatic |
| Feature | Modal (Paid) | RunPod (Paid) | Colab Client (Free) |
|---|---|---|---|
| GPU cost | Pay per second | Pay per hour | Free (Colab quota) |
| GPU types | A100, H100, L40S | A100, H100, RTX | T4, L4, A100 (Pro) |
| Max session | 24h (default) | Configurable | 24h (Colab limit) |
| Stateful classes | @app.cls() |
N/A | Planned (Tier 1) |
pip install |
modal |
Custom | colab-sdk |
Yes! Colab Client uses Google Colab's free tier. GPU sessions may require Colab Pro or pay-as-you-go compute units (starting at ~$0.01/hour).
Not natively — google-colab-cli requires Unix system modules. Use WSL2 (see Windows Setup).
~20-30 seconds for VM provisioning. Subsequent calls are ~1-2 seconds (session reuse).
Only one GPU per session, matching Colab's limits. You can create multiple App instances for multiple sessions.
The Engine automatically detects dead sessions and creates a new one (see Engine SPEC).
Secrets are stored in memory on your local machine and embedded into the wrapper code sent to the VM. They are not persisted to disk.
MVP complete — All core features are implemented and integration-tested against real Colab:
| Component | Status | Tests |
|---|---|---|
| App + RemoteFunction | ✅ | 21 tests |
| ExecutionEngine | ✅ | 21 tests |
| Analyzer | ✅ | 10 tests |
| Packager | ✅ | 8 tests |
| ColabSession | ✅ | 17 tests |
| Protocol Parser | ✅ | 23 tests |
| Integration Test | ✅ | Passed (real Colab) |
| Total | ✅ | 126 tests |
| Tier | Features |
|---|---|
| 1 | Stateful classes (@app.cls()), Non-blocking (.spawn()), Parallel (.map()), Persistent volumes |
| 2 | HTTP endpoints, Named secrets, Multiple sessions, Progress callbacks |
| 3 | Cache visualization, Model registry, Session snapshots |
See Future Features for the complete roadmap.
We welcome contributions! See CONTRIBUTING.md for:
- Development setup
- Coding standards (ruff, mypy, pytest)
- Pull request process
- Architecture decision records
git clone https://github.com/heyncth/colab-sdk.git
cd colab-sdk
pip install -e ".[dev]"
pytest tests/MIT © Contributors
Made for the free GPU community ❤️
GitHub · Issues · Discussions