TGraphX on Google Colab: Quickstart
Topic: Getting started with TGraphX
Google Colab gives you a Python notebook with PyTorch already installed, so trying TGraphX takes one pip install per runtime and no local setup. This guide goes from a blank notebook to a trained node classifier: install, check the runtime, build and validate a graph, train with a clean train/validation/test split, and keep the results on Google Drive.
Run the cells in order. The code was tested with TGraphX 1.5.1 on a CPU machine outside Colab; the install, Drive and Cora cells need Colab or a network connection and were not executed in that test. If you would rather work locally, use the install and first experiment guide.
Install TGraphX
Packages installed with pip disappear when the Colab runtime is deleted, so make this the first cell of the notebook and pin the version you tested with:
# Colab notebook cell
!pip install -q "tgraphx==1.5.1"
TGraphX 1.5.1 is a Beta release on PyPI. It needs Python 3.10 or newer and torch>=1.13; pip keeps Colab's preinstalled PyTorch when it already satisfies that requirement. Check what you got:
import torch
import tgraphx
print("TGraphX", tgraphx.__version__)
print("PyTorch", torch.__version__)
print("CUDA available:", torch.cuda.is_available())
Check the runtime
To use a GPU, choose Runtime > Change runtime type and select a GPU accelerator before running anything. Everything below also runs on CPU.
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using device:", device)
if device.type == "cuda":
props = torch.cuda.get_device_properties(0)
print("GPU:", props.name, f"({props.total_memory / 1e9:.1f} GB)")
Colab hardware varies between sessions, so print it instead of assuming a particular GPU or memory size.
Build a graph with train, validation and test masks
A random graph with random labels has nothing to learn, so this example makes a small synthetic problem with real signal: three classes, noisy class-dependent features, and edges that mostly connect nodes of the same class. Seed everything before creating data or models.
from tgraphx import Graph
from tgraphx.estimators import node_train_val_test_split
from tgraphx.reproducibility import set_seed
set_seed(42)
num_nodes, num_classes, in_dim = 300, 3, 16
y = torch.randint(0, num_classes, (num_nodes,))
centres = torch.randn(num_classes, in_dim)
x = 0.35 * centres[y] + torch.randn(num_nodes, in_dim) # weak signal
# keep all same-class pairs and 30% of cross-class pairs; drop self-loops
cand = torch.randint(0, num_nodes, (2, 3000))
keep = (y[cand[0]] == y[cand[1]]) | (torch.rand(cand.shape[1]) < 0.3)
keep &= cand[0] != cand[1]
edge_index = cand[:, keep]
train_mask, val_mask, test_mask = node_train_val_test_split(
num_nodes, 0.6, 0.2, 0.2, seed=0
)
g = Graph(
node_features=x,
edge_index=edge_index,
node_labels=y,
train_mask=train_mask,
val_mask=val_mask,
test_mask=test_mask,
)
g.make_undirected() # in place: adds reverse edges and merges duplicates
print("nodes:", g.num_nodes, "edges:", g.num_edges, "features per node:", g.feature_shape)
Validate before training
The Graph constructor already rejects malformed input, such as an edge_index that is not [2, E] or points past the last node. validate_graph is useful after you modify a graph, and check_leakage confirms the three node masks do not overlap:
from tgraphx import check_leakage, validate_graph
report = validate_graph(g, check_finite=True) # check_finite adds the NaN/Inf test
print("valid:", report["ok"], report["issues"])
g.validate() # re-runs the constructor checks, raises on failure
leak = check_leakage(train_mask=g.train_mask, val_mask=g.val_mask, test_mask=g.test_mask)
print("disjoint masks:", leak["ok"], leak["counts"])
degree = torch.bincount(g.edge_index.flatten(), minlength=g.num_nodes)
print("isolated nodes:", int((degree == 0).sum()))
Know the limits: validate_graph does not look for isolated nodes, duplicate edges, self-loops or negative indices (g.validate() does catch negative indices). check_leakage only compares node masks, and its arguments should be passed by keyword. More in the shape-aware validation guide.
Choose where to keep outputs
Files written to the Colab VM are lost when the runtime is deleted. Start with a local folder:
import os
project_dir = "tgraphx_experiments"
os.makedirs(project_dir, exist_ok=True)
To keep files between sessions, run this cell too. It asks you to authorise Drive access, which lets code in the notebook read and write your Drive, so only do it in notebooks you trust.
import os
from google.colab import drive
drive.mount("/content/drive")
project_dir = "/content/drive/MyDrive/tgraphx_experiments"
os.makedirs(project_dir, exist_ok=True)
Define the model and the training loop
These node features are plain vectors [N, 16], so the model uses GCNConv. TGraphX's tensor layers such as TensorGraphSAGELayer expect feature maps like [N, C, H, W] and raise an error on vectors.
The loop computes the loss on training nodes only and watches validation loss. It writes best.pt whenever validation loss improves, writes last.pt every 10 epochs, and restores the best weights at the end. This cell only defines things, so it is safe to re-run in a new session.
import copy
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from tgraphx import GCNConv, load_checkpoint, save_checkpoint
from tgraphx.estimators import EarlyStopping
class TwoLayerGCN(nn.Module):
def __init__(self, in_dim, hidden_dim, num_classes, dropout=0.5):
super().__init__()
self.conv1 = GCNConv(in_dim, hidden_dim)
self.conv2 = GCNConv(hidden_dim, num_classes)
self.dropout = dropout
def forward(self, x, edge_index):
h = F.relu(self.conv1(x, edge_index))
h = F.dropout(h, p=self.dropout, training=self.training)
return self.conv2(h, edge_index) # logits
def accuracy_on(model, g, mask):
model.eval()
with torch.no_grad():
pred = model(g.x, g.edge_index).argmax(1)
return (pred[mask] == g.y[mask]).float().mean().item()
def fit_node_classifier(model, g, optimizer, start_epoch=0, epochs=200, patience=30,
ckpt_path=None, best_path=None):
stopper = EarlyStopping(patience=patience, mode="min") # lower val loss is better
history = {"train_loss": [], "val_loss": [], "val_acc": []}
best_state = copy.deepcopy(model.state_dict())
if best_path and start_epoch > 0 and os.path.exists(best_path):
# resuming: the best epoch from before the disconnect is still the one to beat
saved = torch.load(best_path, map_location="cpu", weights_only=True)
best_state, history["best_epoch"] = saved["model_state_dict"], saved["epoch"]
stopper.step(saved["val_loss"])
for epoch in range(start_epoch, epochs):
model.train()
optimizer.zero_grad()
logits = model(g.x, g.edge_index)
loss = F.cross_entropy(logits[g.train_mask], g.y[g.train_mask])
loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
logits = model(g.x, g.edge_index)
val_loss = F.cross_entropy(logits[g.val_mask], g.y[g.val_mask]).item()
val_acc = (logits[g.val_mask].argmax(1) == g.y[g.val_mask]).float().mean().item()
history["train_loss"].append(loss.item())
history["val_loss"].append(val_loss)
history["val_acc"].append(val_acc)
stop = stopper.step(val_loss)
if stopper.counter == 0: # best epoch so far
best_state = copy.deepcopy(model.state_dict())
history["best_epoch"] = epoch
if best_path:
save_checkpoint(model, None, epoch, best_path, val_loss=val_loss)
if ckpt_path and epoch % 10 == 0:
save_checkpoint(model, optimizer, epoch, ckpt_path, val_loss=val_loss)
if stop:
break
model.load_state_dict(best_state)
return history
Train, then test once
g.save(f"{project_dir}/graph.tgx") # keep the exact graph before training
g.to(device) # moves the graph and its masks in place
model = TwoLayerGCN(in_dim, 32, num_classes).to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
history = fit_node_classifier(model, g, optimizer, ckpt_path=f"{project_dir}/last.pt",
best_path=f"{project_dir}/best.pt")
test_acc = accuracy_on(model, g, g.test_mask) # evaluate on test after training
print("epochs run:", len(history["val_loss"]))
print("test accuracy:", round(test_acc, 3))
The number is a check that the pipeline works on easy synthetic data, not a result about TGraphX.
Plot the curves
Colab shows matplotlib figures inline:
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
ax1.plot(history["train_loss"], label="train")
ax1.plot(history["val_loss"], label="validation")
ax1.set_xlabel("epoch")
ax1.set_ylabel("cross-entropy")
ax1.legend()
ax2.plot(history["val_acc"])
ax2.set_xlabel("epoch")
ax2.set_ylabel("validation accuracy")
fig.tight_layout()
fig.savefig(f"{project_dir}/training_curves.png", dpi=150)
plt.show()
Save the results and reload them
The graph and the best weights are already on disk. Save the metrics, then confirm that a fresh model loaded from best.pt gives the same test accuracy:
import json
with open(f"{project_dir}/history.json", "w") as f:
json.dump({"history": history, "test_accuracy": test_acc}, f, indent=2)
restored = TwoLayerGCN(in_dim, 32, num_classes).to(device)
load_checkpoint(restored, None, f"{project_dir}/best.pt", map_location=device)
restored_acc = accuracy_on(restored, g, g.test_mask)
assert abs(restored_acc - test_acc) < 1e-6
Load .tgx files only if you trust where they came from, because loading them unpickles Python objects.
Resume after a disconnect
If the session ends mid-training and your files are on Drive, start a new session and run only these, in this order:
- the install cell (
pip install), - the Drive mount cell,
- the cell under Define the model and the training loop,
- the cell below.
Do not use Runtime > Run all, and do not re-run the training cell: it starts a new run at epoch 0 and overwrites graph.tgx, last.pt and best.pt.
import os
import torch
from tgraphx import Graph, load_checkpoint, save_checkpoint
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
drive_dir = "/content/drive/MyDrive/tgraphx_experiments"
project_dir = drive_dir if os.path.isdir(drive_dir) else "tgraphx_experiments"
g = Graph.load(f"{project_dir}/graph.tgx") # same data and same split as before
g.to(device)
in_dim = g.node_features.shape[1]
num_classes = int(g.y.max()) + 1
resumed = TwoLayerGCN(in_dim, 32, num_classes).to(device)
resumed_opt = torch.optim.Adam(resumed.parameters(), lr=0.01, weight_decay=5e-4)
last_epoch = load_checkpoint(resumed, resumed_opt, f"{project_dir}/last.pt", map_location=device)
more = fit_node_classifier(resumed, g, resumed_opt, start_epoch=last_epoch + 1,
ckpt_path=f"{project_dir}/last.pt",
best_path=f"{project_dir}/best.pt")
print("resumed at epoch", last_epoch + 1, "and ran", len(more["val_loss"]), "more")
print("best epoch overall:", more["best_epoch"])
print("test accuracy:", round(accuracy_on(resumed, g, g.test_mask), 3))
Training continues from the weights and optimizer state in last.pt, and the best weights recorded in best.pt are kept unless a later epoch beats their validation loss. The early-stopping counter and random-number state start fresh, and more holds the curves of the resumed epochs only, so a resumed run is not identical to an uninterrupted one.
Record the environment
Colab's library versions and hardware change over time, so store them next to the results. TGraphX does not write this file for you:
from importlib.metadata import distributions
from tgraphx.reproducibility import reproducibility_report
record = {"seed": 42, **reproducibility_report()}
if device.type == "cuda":
record["gpu"] = torch.cuda.get_device_name(0)
record["cuda_version"] = torch.version.cuda
with open(f"{project_dir}/environment.json", "w") as f:
json.dump(record, f, indent=2)
packages = sorted({f"{d.metadata['Name']}=={d.version}" for d in distributions()})
with open(f"{project_dir}/requirements.txt", "w") as f:
f.write("\n".join(packages) + "\n")
The full package list documents the runtime; some entries in it may not be installable on another machine as written. A fixed seed does not guarantee identical numbers across different GPUs or library versions. See the GNN reproducibility guide.
Tensor-valued node features
When each node is an image patch or feature map, switch to a tensor layer. This cell runs one SAGE layer over an 8 x 8 grid of patch nodes:
from tgraphx import TensorGraphSAGELayer, build_grid_graph
patches = torch.randn(64, 3, 8, 8, device=device) # 64 nodes, each [3, 8, 8]
grid_edges = build_grid_graph(8, 8).to(device)
layer = TensorGraphSAGELayer(3, 16).to(device)
out = layer(patches, grid_edges, chunk_size=64)
print(tuple(out.shape)) # (64, 16, 8, 8)
If you run out of GPU memory, reduce the graph or feature size. The forward methods of TensorGraphSAGELayer, TensorGATLayer and TensorGINLayer also accept chunk_size, which processes edges in chunks to limit the per-edge message buffer; it does not shrink the node tensors themselves.
Use a real dataset: Cora
For citation graphs, load with PyTorch Geometric and build the Graph yourself, so that the public train/validation/test masks come with it. The first call downloads the data.
# In Colab, first run: !pip install -q torch_geometric
from torch_geometric.datasets import Planetoid
from tgraphx import Graph
data = Planetoid(root="/content/datasets", name="Cora")[0]
cora = Graph(
node_features=data.x,
edge_index=data.edge_index,
node_labels=data.y,
train_mask=data.train_mask,
val_mask=data.val_mask,
test_mask=data.test_mask,
)
cora.to(device)
cora_model = TwoLayerGCN(cora.node_features.shape[1], 16, int(data.y.max()) + 1).to(device)
cora_opt = torch.optim.Adam(cora_model.parameters(), lr=0.01, weight_decay=5e-4)
fit_node_classifier(cora_model, cora, cora_opt)
print("Cora test accuracy:", accuracy_on(cora_model, cora, cora.test_mask))
TGraphX also has tgx.load_dataset("cora"), but its PyTorch Geometric converter does not copy the split masks. The dataset interoperability guide covers this, and the citation network tutorial goes further with this kind of data.
Colab limits to plan around
- Session length. The Colab FAQ says notebooks can generally run for at most 12 hours, depending on availability and usage, and idle runtimes time out. Limits vary and can change, so checkpoint to Drive.
- GPU availability. Free resources are not guaranteed. Check
torch.cuda.is_available()in every new session. - Drive speed. Reading many small files from a mounted Drive can be slow. Copy large datasets to local disk and write only checkpoints and results back to Drive.
- Long experiments. For multi-day or large sweeps, use a machine you control.
Frequently asked questions
What if pip install fails? Read the error first. Check !python --version (3.10 or newer is required), and if you upgraded a preinstalled package, restart the session from the Runtime menu. Problems that look like TGraphX bugs belong on the issue tracker.
Can I use a TPU runtime? This guide does not cover it and TGraphX was not tested on TPU here. Use a GPU or CPU runtime.
Are there ready-made notebooks? Yes. The TGraphX Colab gallery links notebooks hosted on Google Drive. From notebook to reproducible experiment explains how to adapt one.
How do I track many runs? See the MLflow logger tutorial or export an offline dashboard report. All guides are listed in the articles index.