Metadata-Version: 2.4
Name: fastcolab
Version: 0.0.2
Summary: Convenient access to the colab API
Author-email: Jeremy Howard <github@jhoward.fastmail.fm>
License-Expression: Apache-2.0
Project-URL: Repository, https://github.com/AnswerDotAI/fastcolab
Project-URL: Documentation, https://AnswerDotAI.github.io/fastcolab/
Keywords: nbdev
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: fastcore
Requires-Dist: fastgws
Requires-Dist: jupyasyncclient>=0.2.31
Dynamic: license-file

# fastcolab


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

Most developers know [Google Colab](https://colab.research.google.com) as a hosted browser notebook for quick experiments. Underneath that browser UI, Google runs an on-demand CPU, GPU, and TPU compute platform with an official [REST API](https://developers.google.com/colab/api/reference/rest) at `colaboratory.googleapis.com`. You can provision machines, run Python scripts or multi-hour training jobs, transfer files, SSH directly into running virtual machines, and tear down runtimes from code without opening a browser or writing a notebook.

The cost is hard to beat. Google bundles 1,000 monthly Colab compute units into [Google AI Ultra](https://one.google.com/) 5x (\$99.99/month) and 2,000 into Ultra 20x (\$199.99/month) alongside Gemini Ultra and cloud storage. Even at standalone Pay-As-You-Go prices (\$0.10 per unit), Colab’s accelerators cost a fraction of standard cloud GPU rates. A 96 GB RTX PRO 6000 runs around \$0.67 to \$0.89 an hour compared to \$3.03 on [Modal](https://modal.com/pricing), and a single-chip Trillium TPU runs around \$0.41 an hour compared to \$2.70 on [Google Cloud](https://cloud.google.com/tpu/pricing). If you already pay for a Google AI Ultra subscription, hundreds of GPU or TPU hours sit in your account every month.

`fastcolab` wraps Colab’s REST API (through [`fastgws`](https://github.com/answerdotai/fastgws)) and runtime Jupyter proxy (through [`jupyasyncclient`](https://github.com/AnswerDotAI/jupyasyncclient)) to make that compute practical from Python.

## Plans and compute units

All [Colab plans](https://colab.research.google.com/signup) and [Google AI subscriptions](https://one.google.com/) credit the same account balance.

| Plan | Price | Monthly units | Included extras |
|----|----|----|----|
| Google AI Ultra 5x | \$99.99/month | 1,000 | Gemini Ultra (5x), 20 TB storage, background execution |
| Google AI Ultra 20x | \$199.99/month | 2,000 | Gemini Ultra (20x), 30 TB storage, background execution |
| Colab Pro+ | \$49.99/month | 500 to 600 | Standalone subscription, background execution |
| Colab Pro / Pay-As-You-Go | \$9.99 | 100 | Monthly subscription or one-time top-up |

Unused units roll over from month to month and expire 90 days after issue. Colab bills units for every minute a machine stays allocated, including idle periods. Delete each runtime as soon as work finishes.

## Choosing a runtime

Turn on High-RAM (`HIGHMEM`) on CPU and T4 runtimes. It quadruples RAM from roughly 13 GB to 51 GB and raises CPU cores from 2 to 8-12 for about 0.1 to 0.3 extra units per hour. Every higher accelerator provisions a High-RAM host automatically.

Two paid options are omitted because newer Colab hardware beats them on price and speed. A G4 (RTX PRO 6000 Blackwell) beats an A100 on every metric: 96 GB VRAM instead of 40 or 80 GB, more RAM, roughly 1.6x higher bfloat16 throughput, and lower hourly cost (~6.7-8.9 vs ~10-13+ units/hr). On paid credits, the Trillium TPU (`v6e-1`, ~4.08 units/hr) delivers roughly 4.5x the throughput of a `v5e-1` (~2.92 units/hr). Use `v5e-1` only on the free tier.

| Accelerator | VRAM | RAM | Relative speed | Units/hr | Hours per 1,000 units | Rate vs cloud on-demand |
|----|----|----|----|----|----|----|
| CPU (High-RAM) | None | ~51 GB | \- | ~0.4 | ~2,500 | ~\$0.04/hr |
| T4 (High-RAM) | 16 GB | ~51 GB | ~0.5x L4 (FP16 only) | ~1.8-2.3 | ~450-550 | ~\$0.18-\$0.23/hr |
| L4 | 24 GB | ~51 GB | 1x (121 TFLOPS, 300 GB/s) | ~3.0 | ~330 | ~\$0.30/hr |
| G4 (RTX PRO 6000) | 96 GB | ~177 GB | ~4x L4 (500 TFLOPS, 1.6 TB/s) | ~6.7-8.9 | ~110-150 | ~\$0.67-\$0.89/hr vs \$3.03/hr (Modal) |
| H100 | 80 GB | ~167-200 GB | ~8x L4 (989 TFLOPS, 3.35 TB/s) | ~18.0 | ~55 | ~\$1.80/hr vs \$3.95/hr (Modal) |
| TPU v6e-1 (Trillium) | 32 GB | ~176+ GB | ~7.5x L4 (918 TFLOPS, 1.64 TB/s) | ~4.08 | ~245 | ~\$0.41/hr vs \$2.70/hr (GCP US) |

Pick the G4 as your default GPU. It has the largest VRAM on Colab, supports native FP8 and FP4, and costs roughly half as much per hour as an H100. Move up to the H100 when memory bandwidth or wall-clock speed dominates and the job fits in 80 GB. Pick the Trillium TPU (`v6e-1`) for the highest compute per credit when your code targets JAX, TensorFlow, or PyTorch XLA and fits in 32 GB.

Google does not publish fixed burn rates or guaranteed RAM allocations. Hourly rates vary slightly by region and load. Check live RAM inside any session with `free -h`.

Colab gives you single-accelerator virtual machines rather than elastic clusters. Each machine attaches one GPU or one TPU chip and caps out at 24 hours even with Ultra or Pro+ background execution. Google can also reclaim an instance when regional capacity tightens. Local disks (~70 to 100 GB) are wiped when a machine stops, so save checkpoints to [Google Cloud Storage](https://cloud.google.com/storage) or [Google Drive](https://drive.google.com) for long runs.

## Getting started

`fastcolab` authenticates with standard Google OAuth 2.0 credentials carrying the `https://www.googleapis.com/auth/colaboratory` scope (plus `https://www.googleapis.com/auth/drive` for Drive transfers). [`gclientid`](https://github.com/AnswerDotAI/gclientid) automates Google Cloud setup and token refresh, though it is optional: `Colab.connect(creds=...)` accepts any `google-auth` credentials directly.

### Setup with `gclientid`

You can create an External Google Cloud project with [`gclientid`](https://github.com/AnswerDotAI/gclientid). Projects isolate API quotas per person and work with both personal `@gmail.com` Ultra accounts and Workspace accounts.

1.  Create or update your External project (`gclientid` enables `colaboratory.googleapis.com` and declares the `colaboratory` scope automatically because `COLAB` is in `MAX`):

``` sh
gclientid
```

2.  Authorize the Google account that holds your Colab or Google AI Ultra credits:

``` sh
gclientid-auth you@gmail.com --preset colab
```

`gclientid` stores one token per email at `~/.config/gclientid/oauth-token-<email>.json`. Authorizing a personal `@gmail.com` account leaves Workspace tokens untouched. Export `FASTCOLAB_ACCOUNT=you@gmail.com` in your shell.

### Setup without `gclientid`

You can set up credentials directly through Google Cloud and pass them to [`Colab.connect`](https://AnswerDotAI.github.io/fastcolab/core.html#colab.connect). See the [Colab API documentation](https://developers.google.com/colab/api) and Google’s authentication guides for full details:

1.  Create or select a project in [Google Cloud Console](https://console.cloud.google.com/) and [enable](https://cloud.google.com/service-usage/docs/enable-disable) `colaboratory.googleapis.com` (and `drive.googleapis.com` if you plan to use `from_drive` and `to_drive`).
2.  [Configure the OAuth consent screen](https://developers.google.com/workspace/guides/configure-oauth-consent) as External (published to production so refresh tokens do not expire after seven days) and add `https://www.googleapis.com/auth/colaboratory` (plus `https://www.googleapis.com/auth/drive` if needed).
3.  [Create an OAuth 2.0 client ID](https://developers.google.com/workspace/guides/create-credentials) and save an authorized-user token JSON, or mint [Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc) with your project as the quota project:

``` sh
gcloud auth application-default login \
  --scopes=openid,https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/userinfo.email,https://www.googleapis.com/auth/colaboratory
gcloud auth application-default set-quota-project YOUR_PROJECT_ID
```

4.  Pass those credentials directly into [`Colab.connect`](https://AnswerDotAI.github.io/fastcolab/core.html#colab.connect):

``` python
import google.auth
from fastcolab import Colab

creds, _ = google.auth.default()
c = await Colab.connect(creds=creds, drive=False)
# Or load a saved OAuth authorized-user JSON file directly:
# c = await Colab.connect(token_path='path/to/token.json')
```

### Starting a runtime and running code

`fastcolab` wraps both Colab discovery documents, waits on long-running runtime creation, refreshes expired proxy tokens automatically, and transfers files over HTTP or Google Drive.

``` python
from fastcore.utils import *
from fastcolab import Colab, outs_text

c = await Colab.connect(account=os.environ['FASTCOLAB_ACCOUNT'])
await c.specs()

async with await c.start('g4') as rt:
    outs = await rt.exec("import torch; torch.cuda.get_device_name(0)")
    print(outs_text(outs))
    await rt.upload(Path('train.py'), 'content/train.py')
    await rt.from_drive('my-dataset', 'content/data')
    await rt.to_drive('content/out.json', 'my-results')
```

`start` accepts short hardware aliases (`'cpu'`, `'t4'`, `'l4'`, `'g4'`, `'h100'`, `'v6e1'`) and enables `SHAPE_HIGHMEM` automatically where available. Entering the runtime with `async with` deletes the machine on exit so idle credits do not burn. `rt.exec` reuses a persistent remote kernel across calls. `rt.upload` creates missing parent directories and chunks files larger than 32 MB automatically. `from_drive` and `to_drive` move files between Google Drive and the runtime using your OAuth credentials, with no interactive browser mount.

### Long-running detached jobs

Colab reclaims a runtime after roughly 90 minutes with an idle Jupyter kernel. Spawning a `nohup` background process and letting its cell exit leaves the kernel idle and risks teardown. `rt.launch` runs your script inside a dedicated busy kernel cell, logs output to disk, and closes the local WebSocket once execution begins.

``` python
rt = await c.start('g4')
job = await rt.launch(Path('train.py').read_text(), log='content/train.log')
rc = await job.wait(poll=5.0, on_log=lambda s: print(s, end=''))
await rt.stop()
```

[`ColabJob`](https://AnswerDotAI.github.io/fastcolab/core.html#colabjob) polls `/api/kernels/{id}` and tails new log bytes over HTTP `Range` requests, refreshing the roughly 1-hour proxy token automatically. You can also call `await job.status()` and `await job.tail()` directly from another process or after waking a laptop. Save checkpoints periodically to Google Drive or Google Cloud Storage in case the machine hits the 24-hour cap or gets reclaimed.

### Fast repeatable environments

Consumer Colab boots Google’s fixed base image (PyTorch, CUDA, JAX, and [`uv`](https://docs.astral.sh/uv/) preinstalled) rather than custom Docker containers. Importing `fastcolab.envs` patches environment helpers onto [`ColabRuntime`](https://AnswerDotAI.github.io/fastcolab/core.html#colabruntime) for lockfile installs, portable virtual environments, and warm runtime reuse.

``` python
from fastcolab.envs import compile_reqs

lock = compile_reqs(['timm', 'datasets'])
await rt.install(reqs=lock, no_deps=True)

await rt.create_venv('/content/env', ['einops'])
await rt.save_venv('colab-envs', '/content/env', 'env.tar.gz')
await rt.load_venv('colab-envs', 'env.tar.gz', '/content/env')
await rt.restart()
```

[`compile_reqs`](https://AnswerDotAI.github.io/fastcolab/envs.html#compile_reqs) resolves versions locally with `uv pip compile` so `rt.install` skips remote resolution and installs through `uv pip install --system`. For stacks that clash with Colab’s system packages, `create_venv` and `save_venv` build and archive an isolated virtual environment once on Colab. `load_venv` restores that archive from Google Drive on later runs. Run inside the restored environment with `rt.venv_exec` or add it to the live kernel with `rt.activate_venv`. During rapid iteration, `rt.restart()` or `rt.fresh_kernel()` resets memory while keeping `/content` and installed packages intact.

### SSH, `scp`, and `rsync`

Colab runtimes expose native SSH through the runtime proxy (`wss://{host}/colab/ssh`) with no ngrok or external tunnel. The proxy accepts an `ed25519` or `ecdsa` public key (Colab rejects RSA keys) and opens a `root` shell over binary WebSocket frames.

`rt.ssh()` (or [`colab_ssh`](https://AnswerDotAI.github.io/fastcolab/extras.html#colab_ssh), from `fastcolab.extras`) bridges that endpoint through `jupyasyncclient`’s `jac-ssh --proxy` `ProxyCommand`. Calling `rt.ssh()` saves the runtime’s WebSocket URL and token in `$XDG_CONFIG_HOME/jupyasyncclient/ssh.json` and appends a `Host colab` block to `~/.ssh/config` when missing (you can also update `~/.ssh/config` from the shell with `jac-ssh --colab`). It uses `~/.ssh/id_ed25519` or `~/.ssh/id_ecdsa` by default, or you can pass `identity=`.

``` python
import fastcolab.extras

rt.ssh()
```

``` sh
ssh colab
rsync -av ./data/ colab:/content/data/
ssh -L 8888:localhost:8888 colab
```

Plain `ssh`, `scp`, `rsync`, port forwarding, and Remote-SSH editors then connect straight to the running machine while the runtime token stays valid (roughly one hour). Call `rt.ssh()` again after refreshing or starting a new runtime to update the saved session.

### Usage, shell commands, directory sync, and one-shot scripts

`fastcolab.extras` also patches operational helpers onto [`Colab`](https://AnswerDotAI.github.io/fastcolab/core.html#colab) and [`ColabRuntime`](https://AnswerDotAI.github.io/fastcolab/core.html#colabruntime) for live credit balance, browser links, shell commands, directory sync, remote script or notebook runners, and bulk cleanup.

``` python
await c.usage()
rt.browser_url(open_browser=True)
await rt.sh('nvidia-smi')
await rt.sys_info()
await rt.upload_dir('src', '/content/src')

res = await c.run_script('train.py', hw='g4', download={'content/out.pt': 'out.pt'})
await c.stop_all()
```

`c.usage()` reads your live balance and hourly burn rate from `/tun/m/ccu-info` using your existing OAuth credentials. `rt.browser_url()` opens a live runtime in your browser without allocating a second machine. `rt.upload_dir` and `rt.download_dir` sync folders as a single tarball (skipping `.git`, `__pycache__`, `.venv`, and `node_modules`). `c.run_script` provisions a machine, runs a local Python file with optional uploads and downloads, and deletes the runtime in a `finally` block. `rt.run_nb` executes a local `.ipynb` remotely and writes outputs back.

## The REST API is all you need

Google exposes two official interfaces under `colaboratory.googleapis.com`. The [REST API](https://developers.google.com/colab/api/reference/rest) handles `runtimes`, `runtimespecs`, and `getSubscription` in `v1beta`, plus long-running `operations` in `v1`. The hosted [Model Context Protocol (MCP) server](https://developers.google.com/colab/api/reference/mcp) runs at `https://colaboratory.googleapis.com/mcp`.

`runtimes.create`, `runtimes.get`, and `runtimes.list` all return a `connectionInfo` object containing `url`, `token`, and `expireTime`. Sending `X-Colab-Runtime-Proxy-Token: {token}` to `connectionInfo.url` connects directly to the runtime’s Jupyter server. Pairing REST with a Jupyter client such as `jupyasyncclient` gives you live streaming output, rich display objects such as plots, and plain HTTP file transfers.

The hosted MCP server adds four kernel tools (`create_session`, `list_sessions`, `delete_session`, `execute_code`) with stateless `executionId` reattachment across 600-second HTTP cutoffs. In exchange, MCP buffers output as text only and truncates large logs. It omits images and requires repeated 600-second requests for multi-hour runs. Driving REST plus the Jupyter proxy avoids those constraints.

Neither REST nor MCP exposes your live credit balance (`get_subscription` returns only the tier, such as `SUBSCRIPTION_TIER_PRO_PLUS`). `fastcolab.extras` adds [`Colab.usage()`](https://AnswerDotAI.github.io/fastcolab/extras.html#colab.usage) against Colab’s `/tun/m/ccu-info` endpoint to read live balance and hourly burn rate directly from Python.

## Technical notes

Some other notes:

- `v1beta` and `v1` also accept the read-only scope `https://www.googleapis.com/auth/colaboratory.readonly` when a caller only needs `get_subscription`, `runtimespecs.list`, or `runtimes.list`.
- Passing `X-Colab-Runtime-Proxy-Token` alone authenticates both HTTP and verified `wss://` WebSocket calls to `connectionInfo.url` (no `colab-runtime-proxy-token` query parameter or `X-Colab-Client-Agent` header is needed on the proxy). Colab exposes kernelspecs `['julia', 'python3', 'ir']` (`name="py"` returns HTTP 500, while omitting `name` selects Python 3), speaks legacy JSON WebSocket frames rather than `v1.kernel.websocket.jupyter.org`, and emits custom `colab_request` frames that clients can ignore.
- For quick terminal checks without a Google Cloud project, `google-colab-cli` provides `colab --auth=oauth2 whoami` and `colab --auth=oauth2 usage`.
