Profiling a TGraphX Workflow with PyTorch Tools
Before optimizing a graph learning workflow, you need to know where time actually goes, and the answer depends on your graph size, feature shapes and hardware. This tutorial profiles a small TGraphX training loop with PyTorch's own tools: synchronised wall-clock timing, torch.profiler traces, an operator guide taken from real traces, data-loader wait time and memory estimates.
Examples tested with TGraphX 1.5.1 and PyTorch 2.15 on CPU. The CUDA and MPS branches were not executed, and no timing numbers are quoted here because they are specific to a machine.
The Profiling Mindset
Profiling answers one question: where does wall time go? For a GNN training loop the candidates are:
- Data loading and graph construction: building
Graphobjects and collating them into batches - Device transfer:
.to(device)calls - Message passing: gathering per-edge data and aggregating it with scatter operations
- Learned projections: 1x1 convolutions in the SAGE, GAT and GIN tensor layers,
nn.Linearin vector layers - Loss and backward pass
- Optimizer step
Measure before choosing which of these to work on.
Setup: A Small Workload to Profile
All later snippets reuse these objects. Node features are tensors of shape [C, H, W]. TGraphX layers take tensors, layer(x, edge_index), not a Graph object, and TensorGraphSAGELayer needs spatial features (for flat [N, D] features use GCNConv or GATv2Conv). The record_function blocks inside forward give each stage a readable name in the profiler output.
import time, statistics
import torch
import torch.nn as nn
from torch.profiler import profile, record_function, schedule, ProfilerActivity
import tgraphx as tgx
from tgraphx import Graph, TensorGraphSAGELayer
from tgraphx.estimators import node_train_val_test_split
from tgraphx.performance import recommended_device
tgx.set_seed(0)
device = recommended_device() # a torch.device: cuda, mps or cpu
N, E, C, H, W, HIDDEN, CLASSES = 400, 2400, 8, 16, 16, 16, 4
train_mask, val_mask, test_mask = node_train_val_test_split(N, 0.6, 0.2, 0.2, seed=0)
raw_graph = Graph( # stays on the CPU; random data, profiling only
node_features=torch.randn(N, C, H, W),
edge_index=torch.randint(0, N, (2, E)),
y=torch.randint(0, CLASSES, (N,)),
train_mask=train_mask, val_mask=val_mask, test_mask=test_mask,
)
class ProfiledGNN(nn.Module):
def __init__(self):
super().__init__()
self.layer1 = TensorGraphSAGELayer(C, HIDDEN)
self.layer2 = TensorGraphSAGELayer(HIDDEN, HIDDEN)
self.head = nn.Linear(HIDDEN, CLASSES)
def forward(self, x, edge_index):
with record_function("layer1_message_pass"):
h = torch.relu(self.layer1(x, edge_index))
with record_function("layer2_message_pass"):
h = self.layer2(h, edge_index)
with record_function("readout"):
return self.head(h.mean(dim=(-2, -1)))
model = ProfiledGNN().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
def train_step(graph):
optimizer.zero_grad()
logits = model(graph.node_features, graph.edge_index)
loss = criterion(logits[graph.train_mask], graph.y[graph.train_mask])
loss.backward()
optimizer.step()
return loss
g = raw_graph.clone().to(device) # Graph.to() modifies in place, so clone first
Basic Timing with Device Synchronisation
The simplest approach is manual timing. On a GPU, kernels run asynchronously: the Python timer can stop before the GPU has finished, so you must synchronise before reading the clock.
Check device.type, not the device itself. recommended_device() returns a torch.device, and torch.device("cuda") == "cuda" evaluates to False, so a string comparison silently skips the synchronisation.
def sync(device):
if device.type == "cuda":
torch.cuda.synchronize()
elif device.type == "mps":
torch.mps.synchronize()
def timed(label, fn, warmup=2, repeats=5):
for _ in range(warmup):
fn()
times = []
for _ in range(repeats):
sync(device)
t0 = time.perf_counter()
fn()
sync(device)
times.append(time.perf_counter() - t0)
print(f"{label}: median {statistics.median(times) * 1000:.2f} ms "
f"(min {min(times) * 1000:.2f}, max {max(times) * 1000:.2f})")
def forward_only():
with torch.no_grad():
model(g.node_features, g.edge_index)
timed("forward pass", forward_only)
timed("full training step", lambda: train_step(g))
This is enough for coarse comparisons. It does not tell you which operations inside a step are expensive.
Tracing with torch.profiler
torch.profiler records individual operators. The schedule below skips one step, treats one as warm-up and records three, so one-off start-up costs stay out of the table. Call prof.step() at the end of every iteration.
activities = [ProfilerActivity.CPU]
if device.type == "cuda":
activities.append(ProfilerActivity.CUDA)
with profile(
activities=activities,
schedule=schedule(wait=1, warmup=1, active=3),
record_shapes=True,
profile_memory=True,
) as prof:
for _ in range(5):
with record_function("data_to_device"):
g = raw_graph.clone().to(device)
with record_function("train_step"):
train_step(g)
prof.step()
# "self" time excludes time spent in child operators
print(prof.key_averages().table(sort_by="self_cpu_time_total", row_limit=15))
Use sort_by="cpu_time_total" for inclusive time. On a GPU, also sort by self_device_time_total (called self_cuda_time_total in older PyTorch releases). The per-layer record_function labels cover only the forward pass; backward work appears as separate autograd entries such as ConvolutionBackward0.
Exporting a Chrome Trace
For a visual timeline:
prof.export_chrome_trace("trace.json")
# Open the file in https://ui.perfetto.dev or chrome://tracing
Each operation appears as a block on a timeline. For GNN workloads, look for:
- long blocks in the gather and scatter operators (message passing dominates)
- long gaps between GPU kernels (the CPU side or data transfer is holding the GPU back)
- long waits on the data loader before each step
Which Operators to Look For
These names come from CPU traces of TGraphX 1.5.1 layers. On a GPU the high-level aten:: names are similar, but the kernels underneath differ (convolutions run through cuDNN, for example).
| Operator in the profiler | What it is in a TGraphX model |
|---|---|
aten::index_select (tensor SAGE, GAT and GIN layers, GATv2Conv), aten::index (GCNConv, LinearMessagePassing, APPNP, ConvMessagePassing) |
Gathering node data once per edge; cost grows with the number of edges and the size of each node's features |
aten::conv2d (aten::mkldnn_convolution on CPU) |
1x1 convolutions, the learned projections in TensorGraphSAGELayer, TensorGATLayer, TensorGINLayer (aten::conv3d with spatial_rank=3) |
aten::index_add_ (with aten::scatter_add_ nested inside on CPU) |
Sum or mean aggregation of messages (SAGE mean, GIN, GAT) |
aten::scatter_reduce_ |
Max aggregation (aggr="max" in SAGE) and the per-node maximum inside GAT attention |
aten::exp, aten::scatter_add_ |
GAT attention normalisation. TGraphX has its own per-edge softmax, so no aten::softmax appears |
aten::addmm, aten::mm |
Dense matrix products: nn.Linear and vector layers such as GCNConv or GATv2Conv |
aten::cat |
Concatenation: GraphBatch collation (visible in the main process only when num_workers=0) and layers that append self-loops, such as GCNConv |
enumerate(DataLoader)#...__next__ |
The main process waiting for the next batch |
aten::to covers dtype conversions as well as device moves, and some calls do nothing, so do not read it as transfer time without checking the shapes and the timeline.
Operator names can change between PyTorch and TGraphX versions. Check them on your own install:
from tgraphx import TensorGATLayer
def ops_in_forward(layer, x, edge_index):
with profile(activities=[ProfilerActivity.CPU]) as p:
with torch.no_grad():
layer(x, edge_index)
return {event.key for event in p.key_averages()}
ops = ops_in_forward(TensorGATLayer(C, HIDDEN), raw_graph.node_features, raw_graph.edge_index)
print(sorted(name for name in ops if "scatter" in name or "softmax" in name or "index" in name))
Measuring Data-Loader Wait Time
The main-process trace shows how long you wait for a batch, but not what happens inside worker processes. The number that matters is the share of each step spent waiting, so measure that directly. The first pass over a loader includes worker start-up and is discarded; persistent_workers=True keeps the workers alive for the second pass.
from tgraphx import GraphDataset, GraphDataLoader
dataset = GraphDataset([
Graph(node_features=torch.randn(32, C, H, W),
edge_index=torch.randint(0, 32, (2, 128)),
graph_label=torch.tensor(i % CLASSES))
for i in range(64)
])
graph_model = tgx.build_model(
"graph_classification", layer="sage", in_shape=(C, H, W),
hidden_shape=(HIDDEN, H, W), num_layers=1, num_classes=CLASSES,
).to(device)
graph_optimizer = torch.optim.Adam(graph_model.parameters(), lr=1e-3)
def graph_step(batch):
batch = batch.to(device)
graph_optimizer.zero_grad()
logits = graph_model(batch.node_features, batch.edge_index, batch=batch.batch)
criterion(logits, batch.graph_labels).backward()
graph_optimizer.step()
def wait_and_compute(loader):
wait = compute = 0.0
t0 = time.perf_counter()
for batch in loader:
t1 = time.perf_counter()
graph_step(batch)
sync(device)
t2 = time.perf_counter()
wait, compute, t0 = wait + (t1 - t0), compute + (t2 - t1), t2
return wait, compute
for num_workers in (0, 2):
extra = {"persistent_workers": True} if num_workers else {}
loader = GraphDataLoader(dataset, batch_size=8, shuffle=True,
num_workers=num_workers, **extra)
wait_and_compute(loader) # warm-up pass
wait, compute = wait_and_compute(loader)
print(f"num_workers={num_workers}: waiting {wait * 1000:.1f} ms, "
f"computing {compute * 1000:.1f} ms")
GraphDataLoader is a thin subclass of PyTorch's DataLoader and passes num_workers and the other keyword arguments through. In a standalone script on Windows or macOS, and on Linux from Python 3.14, put the loop under if __name__ == "__main__": when num_workers > 0.
If waiting is a large share of the total, more workers or cached, pre-built graphs may help. If it is already small, they will not, and worker processes add their own overhead.
Estimating and Measuring Memory
estimate_message_memory computes the size of one per-edge buffer, [E, *out_shape]. It needs only the edge count and shapes, so you can call it before building anything large. For TensorGraphSAGELayer the messages have the layer's output channels:
from tgraphx.performance import estimate_message_memory
est = estimate_message_memory(
num_edges=raw_graph.num_edges,
out_shape=(HIDDEN, H, W), # per-edge message shape, not the input shape
dtype=torch.float32,
)
print(f"per-edge message buffer: {est['total_mb']} MB")
This is a lower bound, not a peak-memory prediction. It ignores node tensors, tensors saved for the backward pass, gradients and optimizer state. TensorGINLayer gathers input channels instead, and TensorGATLayer holds both a source and a destination copy.
On CPU, do not read the CPU Mem and Self CPU Mem columns that profile_memory=True adds to the table above as peak usage. They show the net memory each operator allocated (allocations minus releases, summed over its calls), so some values are negative. For measured peaks on CUDA, use PyTorch's counters:
if device.type == "cuda":
torch.cuda.reset_peak_memory_stats()
train_step(g)
print(f"peak GPU memory: {torch.cuda.max_memory_allocated() / 1024**2:.1f} MB")
Short answers about GPU, AMP and multi-device support are in the performance FAQ.
Interpreting Results: Common Patterns
Pattern 1: Waiting on data dominates. Increase num_workers, move preprocessing out of __getitem__, or cache prepared graphs. Re-measure after each change.
Pattern 2: Device transfer is expensive. g.to(device) moves all tensor fields of a Graph in one call, in place, copying them one after another. If the whole graph fits on the device, move it once before the loop instead of every step.
Pattern 3: aten::cat is large. Collation cost grows with the number of graphs per batch and the size of their tensors. Use fewer or smaller graphs per batch, build the batches once and reuse them, or move collation into workers.
Pattern 4: Gather, scatter and convolution dominate. The model's own work is the bottleneck. Options are fewer edges (for example neighbor sampling), fewer channels or a smaller spatial size. If memory is the limit, the forward methods of the SAGE, GAT and GIN tensor layers accept chunk_size= to process edges in chunks; measure its effect on both time and memory.
Reproducible Profiling
Profile with the same settings you train with. Fix the seed so the workload is identical between runs, and enable deterministic mode only if your training uses it, because deterministic kernels can run at a different speed. Record the environment next to the numbers:
from tgraphx.performance import env_report
tgx.set_seed(42)
info = env_report(include_hardware=True)
print({k: info[k] for k in ("python", "torch", "tgraphx", "recommended_device", "cpu_count")})
Warm up before measuring and record several iterations. Repetition reduces run-to-run noise but does not remove it, so report a median with its spread, and close other heavy processes while you measure.
For these habits applied to a vision model, see the CPU and GPU benchmark of D-FINE video object detection, with warm-up, repeated runs and stated hardware.