Masks, Splits, and Leakage in TGraphX Node Classification
In transductive node classification, the train/validation/test split is nothing more than three boolean masks over the nodes of one graph. The model sees every node's features and edges; only the labels are withheld. That makes leakage easy to introduce and hard to notice.
This page covers where TGraphX keeps the masks, what its leakage check verifies, where masks are ignored without warning, and which leaks no mask check can find. Examples tested with TGraphX 1.5.1; the blocks run top to bottom.
Where the masks live
Pass train_mask, val_mask and test_mask to Graph and they are stored in metadata["masks"] under the keys train, val and test. The labels below are random on purpose: there is nothing to learn, so a test accuracy far above chance (about 1/3) can only mean that test labels reached the model.
import torch
import torch.nn as nn
import torch.nn.functional as F
import tgraphx as tgx
from tgraphx import Graph, GraphBatch
from tgraphx.estimators import node_train_val_test_split
gen = torch.Generator().manual_seed(0)
N = 600
x = torch.randn(N, 8, generator=gen)
edge_index = torch.randint(0, N, (2, 2400), generator=gen)
y = torch.randint(0, 3, (N,), generator=gen)
train_mask, val_mask, test_mask = node_train_val_test_split(N, 0.6, 0.2, 0.2, seed=0)
g = Graph(x=x, edge_index=edge_index, y=y,
train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)
assert list(g.metadata["masks"]) == ["train", "val", "test"]
assert torch.equal(g.train_mask, train_mask)
assert train_mask.dtype == torch.bool
node_train_val_test_split is a random split, not a stratified one. For imbalanced classes, build stratified masks yourself.
The constructor checks the length of each mask, but not its dtype and not whether masks overlap:
try:
Graph(x=x, edge_index=edge_index, y=y, train_mask=train_mask[:50])
except ValueError as err:
print(err) # train_mask has 50 entries but graph has 600 nodes.
else:
raise AssertionError("a short mask should be rejected")
# Accepted without complaint: the same nodes in train and test
overlapping = Graph(x=x, edge_index=edge_index, y=y,
train_mask=train_mask, test_mask=train_mask)
Masks follow the graph through to(), clone() and a .tgx save/load. Batching and subgraph sampling treat them differently:
GraphBatchdoes not concatenate them. A batch has notrain_mask; each graph's masks stay inbatch.metadata[i]["masks"].- Subgraphs keep the full-length masks. This applies to
induced_subgraph,k_hop_subgraph,neighbor_sampleand the.graphof aNeighborLoaderbatch. Theirmetadata["masks"]is also the very same dictionary as the parent's, so do not re-index a mask in place: assigningsub.metadata["masks"]["train"]overwrites the parent's training mask. Build a newGraphinstead, as the inductive split below does.
Check the split with check_leakage
check_leakage compares the three node masks pairwise. Pass them by keyword, or pass a graph that carries them. By default (strict=True) any overlap raises LeakageError, a ValueError subclass that you import from tgraphx.ux.leakage.
from tgraphx.ux.leakage import LeakageError
report = tgx.check_leakage(train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)
assert report["ok"]
assert report["counts"] == {"train": 360, "val": 120, "test": 120}
bad_test = test_mask.clone()
bad_test[train_mask.nonzero()[:3, 0]] = True # copy three training nodes into test
try:
tgx.check_leakage(train_mask=train_mask, val_mask=val_mask, test_mask=bad_test)
except LeakageError as err:
print(err) # train_mask and test_mask overlap on 3 nodes
else:
raise AssertionError("the overlap should be detected")
summary = tgx.check_leakage(train_mask=train_mask, val_mask=val_mask,
test_mask=bad_test, strict=False)
assert summary["overlaps"] == {"train_val": 0, "train_test": 3, "val_test": 0}
The check does not test that the masks cover every node, that masked nodes have valid labels, or anything about features and edges.
Calls that look right and are not
Positional arguments. The first parameter of check_leakage is graph. If you pass three masks by position, the training mask is taken as the graph, the validation mask as the training mask, and the test mask as the validation mask. No test mask is left, so a train/test overlap such as the one in bad_test is never compared and the result says ok.
Index tensors. The function expects boolean masks and casts whatever it gets with .bool(), so every non-zero index becomes True. Index tensors of different lengths, such as the 360/120/120 split above written as node IDs, then raise a RuntimeError about tensor sizes and return no counts. Index tensors of equal length raise no type error, but they are compared position by position, not by node ID: a node listed at different positions in two splits is missed, disjoint splits can be reported as overlapping, and the counts mean nothing. Assert mask.dtype == torch.bool before you trust a result.
Masks written by a transform or a built-in dataset. RandomNodeSplit and FixedSplit store keys named train_mask, val_mask and test_mask, while graph.train_mask reads the key train. The built-in synthetic:node_classification dataset uses the same keys as the transforms. In both cases the property returns None, and check_leakage(graph) reports success after checking nothing:
from tgraphx.datasets import get_dataset
from tgraphx.transforms import RandomNodeSplit
transformed = RandomNodeSplit(0.6, 0.2, seed=0)(Graph(x=x, edge_index=edge_index, y=y))
assert transformed.train_mask is None
empty = tgx.check_leakage(transformed)
assert empty["ok"] and empty["counts"] == {} # nothing was checked
masks = transformed.metadata["masks"] # read them here instead
checked = tgx.check_leakage(train_mask=masks["train_mask"], val_mask=masks["val_mask"],
test_mask=masks["test_mask"])
assert set(checked["counts"]) == {"train", "val", "test"}
builtin = get_dataset("synthetic:node_classification")[0]
assert builtin.train_mask is None
assert tgx.check_leakage(builtin)["counts"] == {} # same trap
assert "train_mask" in builtin.metadata["masks"]
Masks lost in conversion. from_pyg_data and from_dgl_graph (in tgraphx.interop) do not copy split masks at all. The Planetoid datasets loaded by name, such as tgx.load_dataset("cora")[0], pass through from_pyg_data, so the public split is missing there too. Again graph.train_mask is None and check_leakage(graph) passes with empty counts. Take the masks from the original PyG or DGL data (loading it with that library if you used a dataset name) and build a new Graph with train_mask=, val_mask= and test_mask=; PyG, OGB and DGL interop shows how.
Passing such a None on is just as quiet: NeighborLoader(..., mask=None) seeds every node, and classify_nodes draws its own split. A useful habit is to assert on counts as well as on ok, so that an empty check cannot pass.
Where masks are ignored
Disjoint masks only matter if the training code applies them.
tgx.fit() does not read node masks. Given a GraphBatch with node labels, it computes the loss on every node, validation and test included. A counting loss function shows it:
rows_seen = []
def counting_loss(logits, target):
rows_seen.append(logits.shape[0])
return F.cross_entropy(logits, target)
probe = tgx.build_model("node_classification", layer="linear", in_shape=(8,),
hidden_shape=(16,), num_layers=2, num_classes=3)
tgx.fit(probe, [GraphBatch([g])], epochs=1, loss_fn=counting_loss,
optimizer=torch.optim.Adam(probe.parameters()), device="cpu")
assert rows_seen == [g.num_nodes] # all 600 nodes, not 360
The config-driven experiment runner, tgraphx.experiments.Runner, reads only the train_mask key of metadata["masks"] in node tasks. A graph built with Graph(train_mask=...) stores the key train, so the runner takes its training loss from every node.
NeighborLoader has the same default as fit(): with mask=None it uses every node as a seed. It does not pick up graph.train_mask on its own.
from tgraphx import NeighborLoader
every_node = NeighborLoader(g, fanouts=[5, 3], batch_size=64)
train_only = NeighborLoader(g, fanouts=[5, 3], batch_size=64, mask=g.train_mask)
assert sum(b.batch_size for b in every_node) == g.num_nodes
assert sum(b.batch_size for b in train_only) == int(g.train_mask.sum())
Inside the loop, compute the loss from batch.seed_logits(out) and batch.seed_y, not from the full-length mask.
The one-call helper tgx.classify_nodes runs check_leakage on the masks it uses, but give it all three masks or none. With none, it draws its own 70/15/15 split. With train_mask and no val_mask, val_accuracy is computed over all nodes, training nodes included.
A transductive training loop that respects the split
For node classification, write the loop. Take the loss from training nodes, choose the stopping point from validation nodes, and read the test nodes once at the end. Note mode="min": EarlyStopping defaults to "max", which is wrong for a loss.
from tgraphx.estimators import EarlyStopping
class TwoLayerGCN(nn.Module):
def __init__(self, in_dim, hidden, num_classes):
super().__init__()
self.conv1 = tgx.GCNConv(in_dim, hidden)
self.conv2 = tgx.GCNConv(hidden, num_classes)
def forward(self, x, edge_index):
return self.conv2(F.relu(self.conv1(x, edge_index)), edge_index)
torch.manual_seed(0)
model = TwoLayerGCN(8, 32, 3)
opt = torch.optim.Adam(model.parameters(), lr=1e-2)
stopper = EarlyStopping(patience=10, mode="min")
best_state = None
for epoch in range(100):
model.train()
opt.zero_grad()
logits = model(g.x, g.edge_index)
F.cross_entropy(logits[g.train_mask], g.y[g.train_mask]).backward()
opt.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()
stop = stopper.step(val_loss)
if stopper.counter == 0: # a new best epoch
best_state = {k: v.clone() for k, v in model.state_dict().items()}
if stop:
break
model.load_state_dict(best_state)
model.eval()
with torch.no_grad():
pred = model(g.x, g.edge_index).argmax(dim=1)
test_acc = (pred[g.test_mask] == g.y[g.test_mask]).float().mean().item()
assert test_acc < 0.5 # random labels: expect about chance
See semi-supervised node classification for the modelling side of this setting.
Leakage through inputs: disjoint masks are not enough
Anything computed from labels and fed back as input must use training labels only. LabelPropagationEstimator is a clear case: without a y argument, fit() seeds the propagation with all of graph.node_labels.
from tgraphx.estimators import LabelPropagationEstimator
def test_accuracy(pred):
return (pred[g.test_mask] == g.y[g.test_mask]).float().mean().item()
leaky = LabelPropagationEstimator(num_iters=10, alpha=0.5).fit(g) # sees test labels
seed_labels = torch.where(g.train_mask, g.y, torch.full_like(g.y, -1)) # -1 = unlabeled
honest = LabelPropagationEstimator(num_iters=10, alpha=0.5).fit(g, seed_labels)
assert test_accuracy(leaky.predict(g)) == 1.0 # on random labels
assert test_accuracy(honest.predict(g)) < 0.5
assert tgx.check_leakage(g)["ok"] # the masks themselves are fine
The same rule covers neighbour-label counts, target encodings and labels used as input features. A trained model needs one more condition: a node that contributes to the loss must not receive its own label through any of these inputs, or the model can learn to copy it, even though no validation or test label is involved. One remedy is to split the training nodes into those that supply labels as inputs and those that supply the loss.
Inspect the raw columns too. A column that encodes the outcome, or is only recorded after it (such as a cancellation reason when predicting cancellations), leaks without being computed from the label tensor, and no mask check can detect it.
Transductive or inductive: say which one
In the transductive setting, the features and edges of validation and test nodes are available during training by design. Normalising with statistics over all nodes does not use test labels, but state that you did it. In the inductive setting, test nodes are unseen at training time, so neither they nor their edges nor their feature statistics may enter training. tgraphx.transforms.StandardizeFeatures computes mean and standard deviation over all nodes of the graph you give it, so do not apply it to the full graph in an inductive protocol.
An inductive node split on one large graph can be built like this:
train_ids = g.train_mask.nonzero().squeeze(1)
mean = g.x[train_ids].mean(dim=0)
std = g.x[train_ids].std(dim=0).clamp_min(1e-6)
full = Graph(x=(g.x - mean) / std, edge_index=g.edge_index, y=g.y, # train statistics
train_mask=g.train_mask, val_mask=g.val_mask, test_mask=g.test_mask)
sub = tgx.induced_subgraph(full, train_ids) # drops edges that touch val/test nodes
assert sub.num_nodes == train_ids.numel()
assert sub.train_mask.numel() == full.num_nodes # still full length, not re-indexed
assert sub.metadata["masks"] is full.metadata["masks"] # shared: never edit it in place
train_graph = Graph(x=sub.x, edge_index=sub.edge_index, y=sub.y) # all rows are train
seen_ids = (g.train_mask | g.val_mask).nonzero().squeeze(1)
val_sub = tgx.induced_subgraph(full, seen_ids)
kept = val_sub.metadata["sampling"]["original_node_ids"]
val_graph = Graph(x=val_sub.x, edge_index=val_sub.edge_index, y=val_sub.y,
val_mask=g.val_mask[kept]) # re-indexed by hand
assert int(val_graph.val_mask.sum()) == int(g.val_mask.sum())
Train on train_graph, select the model on the val_mask rows of val_graph, and evaluate once on the test rows of full. Rebuilding a clean Graph matters: a subgraph that still carries full-length masks can be saved to .tgx, but loading it back fails with a mask length error.
Groups that must stay together
If several nodes come from one source (patches of one image, scans of one patient), a random node split puts near-duplicates on both sides. Split the groups, then derive the masks:
group = torch.arange(N) // 20 # 30 sources, 20 nodes each
order = torch.randperm(30, generator=torch.Generator().manual_seed(0))
parts = [order[:18], order[18:24], order[24:]] # train, val, test groups
group_masks = [torch.isin(group, part) for part in parts]
res = tgx.check_leakage(train_mask=group_masks[0], val_mask=group_masks[1],
test_mask=group_masks[2])
assert res["counts"] == {"train": 360, "val": 120, "test": 120}
assert not set(group[group_masks[0]].tolist()) & set(group[group_masks[2]].tolist())
check_leakage would accept a random node split of the same data: it knows nothing about groups.
The same problem appears in image datasets with several pictures from one session: computer vision dataset preparation shows a case where a file-hash check finds nothing and a split by session is still needed.
What the other helpers actually do
| Helper | What it verifies |
|---|---|
check_leakage |
Pairwise overlap of boolean node masks |
validate_graph |
Mask lengths, among other structural checks; not overlap |
leakage_report |
Identical (head, relation, tail) rows across knowledge-graph triple splits |
validate_split_policy |
Only that setting is "transductive", "inductive" or "semi_supervised" |
leakage_report is not a node-mask report. It takes triples and returns a dictionary; an overlap is reported, not raised:
train_triples = torch.tensor([[0, 0, 1], [1, 0, 2]])
test_triples = torch.tensor([[1, 0, 2], [2, 1, 0]])
kg_report = tgx.leakage_report(train_triples=train_triples, test_triples=test_triples)
assert not kg_report["ok"]
print(kg_report["issues"]) # ['train/test share 1 identical triples — leak!']
policy = tgx.validate_split_policy(overlapping, setting="inductive")
assert set(policy) == {"policy", "obj_type", "notes"} # no mask was inspected
It matches exact rows only, so a test triple that is the inverse of a training triple passes. validate_split_policy returns a description of the setting you named, even for the overlapping graph above. For edge-level tasks, none of these helpers checks whether test edges are still in the message-passing graph; see link prediction.
Checklist
- Make boolean masks, and split by group when nodes share a source.
- Call
check_leakagewith keywords; assert thatcountslists all three splits. - Index the loss with
train_mask. ForNeighborLoader,assert g.train_mask is not Nonefirst, then passmask=g.train_mask:mask=Noneseeds every node. - Select on validation (
mode="min"for a loss); evaluate on test once. - Derive label-based inputs from training labels only, hide a loss node's own label, and look for columns that record the outcome.
- State transductive or inductive, and fit preprocessing to match.
- Save the seed and the masks with the results (reproducibility).
A passing check_leakage means the node masks you gave it are disjoint. The rest of the list is your experimental protocol, and no single function certifies it.