Module contents
Lesson 16 of 30Core 115 min

Node and graph classification: protocols, pooling and self-supervision

Design leakage-aware node and graph classification protocols, examine Correct and Smooth, pooling and self-supervised learning, and evaluate models with appropriate splits and controls.

After this lesson you can

  • Distinguish transductive, inductive and temporal evaluation protocols.
  • Explain residual correction and prediction smoothing without using held-out labels.
  • Compare graph readouts and hierarchical pooling, including invariance.
  • Audit molecular and temporal splits and select models without test leakage.
  • Evaluate graph pretraining and frozen probes under explicit protocols.

Before you start

A score is not a protocol

A node classifier produces one prediction per vertex. A graph classifier produces one per whole graph. In both tasks the decisive question is what information will be available when predicting: an apparently harmless split can turn future information or hidden labels into model input. Before comparing architectures, fix that question and the selection procedure.

In a transductive setting the full graph and features of all nodes can be available during training if that access is intended in the problem. Validation and test labels remain hidden. In an inductive setting specify whether new nodes, edges or graphs appear only at inference. A transductive result does not automatically answer an inductive question. Semi-supervised node classification and readout are the starting points.

For example, PageRank computed using edges formed after the prediction date can encode the future, even without labels. Using test labels as features or selecting epochs and hyperparameters by test accuracy is also leakage. In the transductive case, propagation using the full structure can be legitimate if the protocol permits knowing it; that differs from seeing hidden labels. Also document feature normalization: fitting it only on training avoids using held-out distribution statistics when deployment does not provide them.

Correct residuals and smooth predictions

A model that does not see the graph can learn useful features but make correlated errors between neighbors. Huang et al. separate feature learning from two subsequent propagation operations: correcting using known residuals and smoothing predictions. This is a strong baseline in the studied setting, not a guarantee that every graph improves.

Let P\mat{P} be a fixed propagation matrix and Y\mat{Y} the label encoding. A base model outputs Z∈Rn×K\mat{Z} \in \R^{n\times K}. On training nodes TT, define Ei(0)=Yi−Zi\mat{E}^{(0)}_i=\mat{Y}_i-\mat{Z}_i; elsewhere, zero. A simple correction version iterates

E(t+1)=αPE(t)+(1−α)E(0),Zc=Z+E(L).\mat{E}^{(t+1)}=\alpha\mat{P}\mat{E}^{(t)}+(1-\alpha)\mat{E}^{(0)}, \qquad \mat{Z}_{c}=\mat{Z}+\mat{E}^{(L)}.

Here 0≤α<10\leq\alpha<1. If P\mat{P} is nonnegative and row-stochastic, the iteration is contractive in infinity norm and converges to (1−α)(I−αP)−1E(0)(1-\alpha)(\mat{I}-\alpha\mat{P})^{-1}\mat{E}^{(0)}. This expression propagates only residuals calculated with training labels. The published method supports normalization and scaling variants: report the exact variant.

InteractiveCorrection and smoothing on a chain
0.70train0.45test0.55test0.30train

Blue: class 0; orange: class 1. Figures are class 0 scores, not calibrated probabilities after correction.

Step
0.50
0.50
Accuracy on two illustrative test nodes0 %
Choose each step and move the coefficients. Known residuals propagate from the ends; smoothing starts from corrected predictions. This is an explicit four-node model, not a citation-dataset result.

In the following small example no MLP is trained and no benchmark measured. Predictions and labels are fixed to make the mechanics verifiable. Test is consulted only at the end; it is not used to choose coefficients. Smoothing iterations keep the initial state fixed as a restart, not the previous iteration’s result in both terms.

[ ]Correction and smoothing on a chainBrowser
import numpy as np

A = np.array([[0, 1, 0, 0], [1, 0, 1, 0],
              [0, 1, 0, 1], [0, 0, 1, 0]], dtype=float)
P = A / A.sum(axis=1, keepdims=True)
Z = np.array([[.7, .3], [.45, .55], [.55, .45], [.3, .7]])
Y = np.eye(2)[[0, 0, 1, 1]]
train = np.array([0, 3])
test = np.array([1, 2])

def propagate(P, seed, alpha, steps):
    state = seed.copy()
    for _ in range(steps):
        state = alpha * P @ state + (1 - alpha) * seed
    return state

residual = np.zeros_like(Z)
residual[train] = Y[train] - Z[train]
corrected = Z + propagate(P, residual, .5, 20)
seed = corrected.copy()
seed[train] = Y[train]
smooth = propagate(P, seed, .5, 20)
for name, pred in [('base', Z), ('corregida', corrected), ('suavizada', smooth)]:
    print(name, 'clases test:', pred[test].argmax(axis=1),
          'exactitud:', np.mean(pred[test].argmax(axis=1) == Y[test].argmax(axis=1)))

The example allows correction not to improve: coefficients are part of the procedure and selected on validation. The graph contains only four nodes and its values do not represent citation data. Real evaluation requires repeating base-model fitting, selection and measurement under a fixed protocol.

A propagation trial on real citations

In the next figure the base is an MLP trained for one epoch on ogbn-arxiv with seed 0. The measured run uses ten correction and ten smoothing steps, without autoscaling, on undirected edges. PyG uses symmetric normalization and, with autoscale=False, reclamps training residuals at each correction step: this differs from the restart iteration on the preceding chain. Each cell shows validation accuracy, not test. Improvement from such a weak base illustrates label propagation’s contribution in this protocol, but does not demonstrate improvement over a well-tuned MLP or generalize to other graphs. Training and some operations may vary slightly with device and versions.

InteractivePropagation on a citation graph
8Node 349, predicted class 8, correction L1 change 0.851, hidden label8Node 65070, predicted class 8, correction L1 change 1.948, training8Node 109870, predicted class 8, correction L1 change 1.949, training8Node 56663, predicted class 8, correction L1 change 0.190, hidden label8Node 60273, predicted class 8, correction L1 change 1.236, hidden label8Node 151838, predicted class 8, correction L1 change 1.948, training
The number is the predicted class. During correction and smoothing, the blue ring grows with correction L1 change; it is not a probability. Six selected nodes are shown, not the entire graph.
MLP base
Correction
Smoothing
01
Node step
0.50
0.50
Baseline validation accuracy0.0764
After correction0.6832
After smoothing0.6968
Change the step and coefficients. The six nodes are the first validation node with a training neighbor and at least five neighbors, plus five of its neighbors. The correction ring saturates at L1 change equal to 2. Bars use all ogbn-arxiv validation, not only the six nodes.

This cell reproduces the grid feeding the figure. Its load and multiple propagations exclude it from automatic execution; it was validated separately in the local lab. Do not use test values to choose coefficients.

[ ]C&S grid on ogbn-arxivLocal GPU
import json
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch_geometric.data.data import Data, DataEdgeAttr, DataTensorAttr
from torch_geometric.data.storage import GlobalStorage
from torch_geometric.nn.models import CorrectAndSmooth
from torch_geometric.utils import to_undirected
from ogb.nodeproppred import PygNodePropPredDataset, Evaluator

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
with torch.serialization.safe_globals([Data, DataEdgeAttr, DataTensorAttr, GlobalStorage]):
    dataset = PygNodePropPredDataset(name='ogbn-arxiv', root='dataset')
data = dataset[0]
data.edge_index = to_undirected(data.edge_index, num_nodes=data.num_nodes)
split = dataset.get_idx_split()
data = data.to(device)
split = {k: v.to(device) for k, v in split.items()}
edge_cpu = data.edge_index.cpu().numpy()
train_ids = set(split['train'].cpu().tolist())
valid_ids = set(split['valid'].cpu().tolist())
train_mask = np.zeros(data.num_nodes, dtype=bool); train_mask[list(train_ids)] = True
valid_mask = np.zeros(data.num_nodes, dtype=bool); valid_mask[list(valid_ids)] = True
degrees = np.bincount(edge_cpu[0], minlength=data.num_nodes)
candidates = np.flatnonzero(valid_mask[edge_cpu[0]] & train_mask[edge_cpu[1]] & (degrees[edge_cpu[0]] >= 5))
center = int(edge_cpu[0, candidates[0]])
neighbors = sorted(set(edge_cpu[1, edge_cpu[0] == center].tolist()))
train_neighbors = [v for v in neighbors if v in train_ids]
others = [v for v in neighbors if v not in train_ids]
sample = [center] + (train_neighbors[:2] + others + train_neighbors[2:])[:5]
sample_idx = torch.tensor(sample, device=device)
local = {node: i for i, node in enumerate(sample)}
inside = np.isin(edge_cpu[0], sample) & np.isin(edge_cpu[1], sample) & (edge_cpu[0] < edge_cpu[1])
sample_edges = [[local[int(u)], local[int(v)]] for u, v in edge_cpu[:, inside].T]
torch.manual_seed(0)
if device.type == 'cuda': torch.cuda.manual_seed_all(0)
net = nn.Sequential(nn.Linear(data.num_features, 64), nn.ReLU(), nn.Dropout(.5), nn.Linear(64, dataset.num_classes)).to(device)
optim = torch.optim.Adam(net.parameters(), lr=.01, weight_decay=5e-4)
net.train(); optim.zero_grad()
F.cross_entropy(net(data.x)[split['train']], data.y.view(-1)[split['train']]).backward(); optim.step()
net.eval()
with torch.no_grad():
    p = net(data.x).softmax(-1)
    evaluator = Evaluator('ogbn-arxiv')
    def valid(pred):
        ids = split['valid']
        return evaluator.eval({'y_true': data.y[ids], 'y_pred': pred[ids].argmax(-1, keepdim=True)})['acc']
    rows = []
    for alpha in [0, .25, .5, .75]:
        for beta in [0, .25, .5, .75]:
            model = CorrectAndSmooth(10, alpha, 10, beta, autoscale=False, scale=1.)
            corrected = model.correct(p, data.y[split['train']], split['train'], data.edge_index)
            smooth = model.smooth(corrected, data.y[split['train']], split['train'], data.edge_index)
            rows.append({'alpha': alpha, 'beta': beta, 'corrected': valid(corrected), 'smooth': valid(smooth),
                         'corrected_class': corrected[sample_idx].argmax(-1).tolist(),
                         'smooth_class': smooth[sample_idx].argmax(-1).tolist(),
                         'correction': (corrected[sample_idx] - p[sample_idx]).abs().sum(-1).tolist()})
    print(json.dumps({'base': valid(p), 'grid': rows, 'sample': sample, 'edges': sample_edges,
                      'training': [v in train_ids for v in sample],
                      'base_class': p[sample_idx].argmax(-1).tolist()}, ensure_ascii=False), flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Local comparison on ogbn-arxiv

This cell trains MLP, GraphSAGE and GAT on the OGB temporal split and uses its accuracy evaluator. Edges are made undirected for propagation in the benchmark’s transductive setting. The best epoch is selected on validation. For C&S one of three coefficients is also selected using validation and only training labels are supplied. Test is then evaluated once per model and seed. This is a fixed recipe, not a broad search or nested cross-validation, and does not by itself establish a comparison with equal parameter budgets.

Install PyTorch, PyTorch Geometric and OGB in your local environment. The full cell uses ten seeds and up to 200 epochs and downloads the dataset; it takes longer than browser examples and is therefore not run automatically in QA. The flow was checked with one seed and one epoch, not the full ten-seed training. The bounded list of PyG classes allows reading OGB’s processed file with weights_only active in recent PyTorch versions. Use only data from a source you trust.

[ ]MLP+C&S, GraphSAGE and GAT on ogbn-arxivLocal GPU
import copy
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch_geometric.data.data import Data, DataEdgeAttr, DataTensorAttr
from torch_geometric.data.storage import GlobalStorage
from torch_geometric.nn import SAGEConv, GATConv
from torch_geometric.nn.models import CorrectAndSmooth
from torch_geometric.utils import to_undirected
from ogb.nodeproppred import PygNodePropPredDataset, Evaluator

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
with torch.serialization.safe_globals([Data, DataEdgeAttr, DataTensorAttr, GlobalStorage]):
    dataset = PygNodePropPredDataset(name='ogbn-arxiv', root='dataset')
data = dataset[0]
data.edge_index = to_undirected(data.edge_index, num_nodes=data.num_nodes)
data = data.to(device)
split = {k: v.to(device) for k, v in dataset.get_idx_split().items()}
target = data.y.view(-1)
evaluator = Evaluator(name='ogbn-arxiv')

class NodeModel(nn.Module):
    def __init__(self, kind, features, classes, hidden=64):
        super().__init__()
        self.kind = kind
        if kind == 'MLP':
            self.layers = nn.ModuleList([nn.Linear(features, hidden), nn.Linear(hidden, classes)])
        elif kind == 'SAGE':
            self.layers = nn.ModuleList([SAGEConv(features, hidden), SAGEConv(hidden, classes)])
        else:
            self.layers = nn.ModuleList([GATConv(features, hidden, heads=2, concat=False),
                                         GATConv(hidden, classes, heads=1)])

    def forward(self, x, edge_index):
        for layer in self.layers[:-1]:
            x = layer(x) if self.kind == 'MLP' else layer(x, edge_index)
            x = F.dropout(F.relu(x), p=.5, training=self.training)
        return self.layers[-1](x) if self.kind == 'MLP' else self.layers[-1](x, edge_index)

def accuracy(scores, ids):
    return evaluator.eval({'y_true': data.y[ids],
                           'y_pred': scores[ids].argmax(dim=1, keepdim=True)})['acc']

results = {name: [] for name in ['MLP+C&S', 'SAGE', 'GAT']}
for seed in range(10):
    for kind in ['MLP', 'SAGE', 'GAT']:
        torch.manual_seed(seed)
        if device.type == 'cuda':
            torch.cuda.manual_seed_all(seed)
        model = NodeModel(kind, data.num_features, dataset.num_classes).to(device)
        optim = torch.optim.Adam(model.parameters(), lr=.01, weight_decay=5e-4)
        best, state = -1, None
        for epoch in range(200):
            model.train(); optim.zero_grad()
            logits = model(data.x, data.edge_index)
            loss = F.cross_entropy(logits[split['train']], target[split['train']])
            loss.backward(); optim.step()
            model.eval()
            with torch.no_grad():
                val = accuracy(model(data.x, data.edge_index), split['valid'])
            if val > best:
                best, state = val, copy.deepcopy(model.state_dict())
        model.load_state_dict(state)
        model.eval()
        with torch.no_grad():
            logits = model(data.x, data.edge_index)
            if kind == 'MLP':
                best_val, best_pred = -1, None
                for alpha in [.25, .5, .75]:
                    cs = CorrectAndSmooth(20, alpha, 20, alpha, autoscale=False, scale=1.)
                    pred = cs(logits.softmax(dim=-1), data.y[split['train']], split['train'], data.edge_index)
                    val = accuracy(pred, split['valid'])
                    if val > best_val:
                        best_val, best_pred = val, pred
                score = accuracy(best_pred, split['test'])
                name = 'MLP+C&S'
            else:
                score, name = accuracy(logits, split['test']), kind
        results[name].append(score)
        print('semilla', seed, name, 'test', score)
for name, values in results.items():
    print(name, 'media', float(np.mean(values)), 'desviación muestral', float(np.std(values, ddof=1)))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

From nodes to graphs

A GNN produces a matrix H∈Rn×d\mat{H}\in\R^{n\times d} of node representations. Sum readout ∑ihi\sum_i\vb{h}_i preserves size information that mean n−1∑ihin^{-1}\sum_i\vb{h}_i can erase. Mean may suit intensive properties, while sum can express extensive properties if architecture and data permit. Attention learns node-dependent weights; Set2Set uses an iterative readout process. No choice alone guarantees generalization to larger graphs.

For example, scalar multisets {1,3}\{1,3\} and {1,3,1,3}\{1,3,1,3\} both have mean 2 but sums 4 and 8. If a property grows when independent components are duplicated, mean alone has erased relevant signal. Sum does not magically solve the task either: the encoder must represent the right components and training must cover the scales at which it will be evaluated.

For a nonempty graph, attention readout can take ai=exp⁡(ei)/∑jexp⁡(ej)a_i=\exp(e_i)/\sum_j\exp(e_j) with ei=q⊤tanh⁡(Whi)e_i=\vb{q}\T\tanh(\mat{W}\vb{h}_i) and return r=∑iaihi\vb{r}=\sum_i a_i\vb{h}_i. Reordering nodes reorders scores and weights in the same way, so the sum is unchanged. Normalized weights make r\vb{r} a convex combination and do not guarantee size preservation. Nor are they automatically a causal explanation of which node produced the prediction.

Set2Set repeats a query: an LSTM produces qt\vb{q}_t from the previous state, computes ait=softmax⁡i(hi⊤qt)a_{it}=\softmax_i(\vb{h}_i\T\vb{q}_t) and rt=∑iaithi\vb{r}_t=\sum_i a_{it}\vb{h}_i, and feeds the next query with concatenation (qt,rt)(\vb{q}_t,\vb{r}_t). Its final state can read the set several times without choosing a node order. This flexibility costs compute and must be compared with sum or mean under the same protocol and an explicit budget.

DiffPool computes S\mat{S} with a GNN and uses auxiliary losses for link reconstruction and assignment entropy. Top-k retains the highest-scoring nodes; SAGPool computes graph-dependent scores and selects nodes. Reduced graphs are not automatically chemical explanations: a learned assignment must be validated for that purpose. Mesquita et al. show on the benchmarks they study that variants with random grouping or grouping on the complement can retain performance. The relevant comparison retains splits, selection and budget, and adds a flat readout as control.

InteractiveAssignment changes the reduced graph
0.900.800.200.10group 1group 2

The number below each node is its weight in group 1; the rest belongs to group 2. The lower line represents between-group weight; readouts include internal weights.

0.00
Between-group weight1.20
Group 1 internal weight1.80
Group 2 internal weight1.80
Mix two explicit assignments of a chain and observe weights calculated by SᵀAS. This construction illustrates the operation and does not represent a trained assignment or measure accuracy.

Learned assignment and random control on MUTAG

The next figure uses a real molecular graph from MUTAG, distributed by PyG, specifically the first test graph in the cell’s reproducible split. Models use node features and connectivity, but not bond types. Soft assignment comes from the seed-0 trained model; the alternative is generated once per graph with a fixed seed and does not depend on labels. Node positions are a layout calculated to show connectivity, not chemical geometry. The reduced matrix is calculated from assignments rounded to five decimals and graph edges.

InteractiveLearned DiffPool versus random assignment
Node 0, weight 0.479Node 1, weight 0.479Node 2, weight 0.501Node 3, weight 0.501Node 4, weight 0.467Node 5, weight 0.464Node 6, weight 0.346Node 7, weight 0.289Node 8, weight 0.289Node 9, weight 0.441Node 10, weight 0.347Node 11, weight 0.501Node 12, weight 0.501Node 13, weight 0.479Node 14, weight 0.479Node 15, weight 0.464Node 16, weight 0.467Node 17, weight 0.346Node 18, weight 0.289Node 19, weight 0.289
The layout is a graph view, not chemical coordinates. More blue means greater weight in the selected group. Reduced matrix SᵀAS, with rows and columns for groups 1 to 4:
1.48
3.45
1.30
1.76
3.45
8.70
3.16
4.09
1.30
3.16
1.16
1.54
1.76
4.09
1.54
2.08
Assignment
Displayed group
Mean test accuracy, five seeds0.7789
Sample deviation0.0399
Flat control mean0.7895
Parameters per model1410
Switch between learned and random assignment and select a group. Color encodes each node's weight in that group; the matrix shows SᵀAS. Accuracies are five-seed means on the same 38-graph test set.

In this exploratory comparison without preregistration, all three models have 1410 trainable parameters. The random control replaces the assignment network’s 32 parameters with a trainable 32-component bias vector after pooling. The flat control also has that bias and aggregates nodes directly without creating groups. This equalizes the count, but architectures, auxiliary losses and inductive biases still differ: it is not a perfect ablation. Across five seeds, test mean and sample deviation were 0.7789 and 0.0399 with learned assignment, 0.7842 and 0.0220 with fixed assignment, and 0.7895 and 0.0000 with flat readout. Zero observed dispersion on this finite test does not mean absence of uncertainty. This is one small split, not a universal conclusion or an interval for new datasets. Epoch choice uses only validation.

The two pooled models and the flat one were run separately with five seeds and 80 epochs each. The cell brings them together, downloads MUTAG and can take time, so it is excluded from automatic QA. It prints assignments and per-seed results. Random assignment is based on each node’s index as received from the dataset: reordering may change that assignment. Therefore this control should not be confused with an equivariant layer.

[ ]DiffPool and random grouping on MUTAGLocal GPU
from types import SimpleNamespace
import copy
import json
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch_geometric.datasets import TUDataset
from torch_geometric.loader import DataLoader
from torch_geometric.utils import to_dense_adj, to_dense_batch
from torch_geometric.nn import dense_diff_pool
from sklearn.model_selection import train_test_split

args = SimpleNamespace(root='dataset', seeds=5, epochs=80, mode='all')
torch.set_num_threads(2)
device = torch.device('cpu')
dataset = TUDataset(root=args.root, name='MUTAG')
graphs = []
for index in range(len(dataset)):
    g = dataset[index].clone()
    group = np.random.default_rng(1000 + index).integers(0, 4, size=g.num_nodes)
    g.random_logits = F.one_hot(torch.tensor(group), num_classes=4).float() * 20 - 10
    g.graph_id = torch.tensor([index])
    graphs.append(g)
y = np.array([int(g.y.item()) for g in graphs])
train, rest = train_test_split(np.arange(len(graphs)), test_size=.4, random_state=42, stratify=y)
valid, test = train_test_split(rest, test_size=.5, random_state=42, stratify=y[rest])
loaders = {name: DataLoader([graphs[i] for i in ids], batch_size=32, shuffle=(name == 'train'))
           for name, ids in [('train', train), ('valid', valid), ('test', test)]}

def normalize(A):
    identity = torch.eye(A.size(-1), device=A.device).unsqueeze(0)
    augmented = A + identity
    degree = augmented.sum(-1).clamp_min(1e-8)
    return augmented / torch.sqrt(degree.unsqueeze(-1) * degree.unsqueeze(-2))

class PoolNet(nn.Module):
    def __init__(self, mode):
        super().__init__()
        self.mode = mode
        self.embed = nn.Linear(dataset.num_features, 32)
        self.assign = nn.Linear(dataset.num_features, 4) if mode == 'aprendido' else None
        self.post = nn.Linear(32, 32)
        self.random_bias = nn.Parameter(torch.zeros(32)) if mode != 'aprendido' else None
        self.classifier = nn.Linear(32, dataset.num_classes)

    def forward(self, batch):
        X, mask = to_dense_batch(batch.x, batch.batch)
        A = to_dense_adj(batch.edge_index, batch.batch, max_num_nodes=X.size(1))
        h = F.relu(normalize(A) @ self.embed(X))
        if self.mode == 'plano':
            post = normalize(A) @ self.post(h) + self.random_bias
            out = (F.relu(post) * mask.unsqueeze(-1)).sum(dim=1)
            zero = out.new_zeros(())
            return self.classifier(out), zero, zero, None, A, mask
        if self.mode == 'aprendido':
            logits = normalize(A) @ self.assign(X)
        else:
            logits, _ = to_dense_batch(batch.random_logits, batch.batch, max_num_nodes=X.size(1))
        pooled, coarse, link, ent = dense_diff_pool(h, A, logits, mask)
        post = normalize(coarse) @ self.post(pooled)
        if self.random_bias is not None:
            post = post + self.random_bias
        out = F.relu(post).sum(dim=1)
        return self.classifier(out), link, ent, logits, A, mask

@torch.no_grad()
def score(model, loader):
    model.eval(); correct = 0; count = 0
    for batch in loader:
        output, _, _, _, _, _ = model(batch.to(device))
        correct += int((output.argmax(1) == batch.y).sum())
        count += batch.num_graphs
    return correct / count

results = {'aprendido': [], 'aleatorio': [], 'plano': []} if args.mode == 'all' else {'plano': []}
for seed in range(args.seeds):
    for kind in results:
        torch.manual_seed(seed)
        model = PoolNet(mode=kind).to(device)
        optimizer = torch.optim.Adam(model.parameters(), lr=.005)
        best, state = -1, None
        for epoch in range(args.epochs):
            model.train()
            for batch in loaders['train']:
                batch = batch.to(device); optimizer.zero_grad()
                output, link, ent, _, _, _ = model(batch)
                loss = F.cross_entropy(output, batch.y) + .1 * link + .01 * ent
                loss.backward(); optimizer.step()
            val = score(model, loaders['valid'])
            if val > best:
                best, state = val, copy.deepcopy(model.state_dict())
        model.load_state_dict(state)
        test_score = score(model, loaders['test'])
        results[kind].append(test_score)
        print('semilla', seed, kind, 'val', best, 'test', test_score, 'parámetros', sum(p.numel() for p in model.parameters()), flush=True)
        if seed == 0 and kind != 'plano':
            one = next(iter(DataLoader([graphs[int(test[0])]], batch_size=1))).to(device)
            model.eval()
            with torch.no_grad():
                _, _, _, logits, A, mask = model(one)
                assign = logits.softmax(-1)[0, mask[0]].cpu().numpy().round(5).tolist()
                edges = one.edge_index.cpu().numpy().T.tolist()
                print('FIGURA', json.dumps({'kind': kind, 'graph_id': int(test[0]), 'features': one.x.argmax(-1).tolist(), 'edges': edges, 'S': assign}), flush=True)
for kind, scores in results.items():
    print(kind, 'media', float(np.mean(scores)), 'desviación muestral', float(np.std(scores, ddof=1)) if len(scores) > 1 else None)

# La posición es una disposición del grafo, no una geometría molecular.
import networkx as nx
graph = nx.Graph()
example = graphs[int(test[0])]
graph.add_nodes_from(range(example.num_nodes))
graph.add_edges_from(example.edge_index.t().tolist())
pos = nx.spring_layout(graph, seed=9, iterations=300)
xs = [pos[i][0] for i in graph]; ys = [pos[i][1] for i in graph]
coords = [[round(40 + 400 * (pos[i][0] - min(xs)) / (max(xs) - min(xs)), 2),
           round(25 + 220 * (pos[i][1] - min(ys)) / (max(ys) - min(ys)), 2)] for i in graph]
print('coordenadas de dibujo:', coords)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

DiffPool invariance can be checked algebraically. Let Q\mat{Q} be a permutation matrix. If an equivariant GNN transforms H\mat{H} and S\mat{S} into QH\mat{Q}\mat{H} and QS\mat{Q}\mat{S} when replacing A\mat{A} by QAQ⊤\mat{Q}\mat{A}\mat{Q}\T, then

(QS)⊤(QH)=S⊤H,(QS)⊤(QAQ⊤)(QS)=S⊤AS.(\mat{Q}\mat{S})\T(\mat{Q}\mat{H})=\mat{S}\T\mat{H},\qquad (\mat{Q}\mat{S})\T(\mat{Q}\mat{A}\mat{Q}\T)(\mat{Q}\mat{S})=\mat{S}\T\mat{A}\mat{S}.

Cancellation uses Q⊤Q=I\mat{Q}\T\mat{Q}=\mat{I}. It does not prove learned grouping has semantic meaning.

[ ]DiffPool and permutationBrowser
import numpy as np

A = np.array([[0., 1., 0.], [1., 0., 1.], [0., 1., 0.]])
H = np.array([[1., 0.], [0., 1.], [1., 1.]])
S = np.array([[.8, .2], [.5, .5], [.1, .9]])
order = np.array([2, 0, 1])
Q = np.eye(3)[order]
coarse_h, coarse_a = S.T @ H, S.T @ A @ S
assert np.allclose((Q @ S).T @ (Q @ H), coarse_h)
assert np.allclose((Q @ S).T @ (Q @ A @ Q.T) @ (Q @ S), coarse_a)
print('representaciones reducidas:', coarse_h)
print('adyacencia reducida:', coarse_a)
link_loss = np.linalg.norm(A - S @ S.T)
entropy = -np.sum(S * np.log(np.clip(S, 1e-12, 1))) / len(S)
print('norma de reconstrucción:', round(link_loss, 6), 'entropía media:', round(entropy, 6))

The link loss of this variant is ∥A−SS⊤∥F\norm{\mat{A}-\mat{S}\mat{S}\T}_F and entropy loss is −n−1∑ikSiklog⁡Sik-n^{-1}\sum_{ik}S_{ik}\log S_{ik}, with 0log⁡0=00\log0=0. They are added to task loss with weights chosen on validation. Both encode preferences, not proof of group quality: reconstructing adjacency favors neighbors together, which may not reflect the prediction objective.

Top-k selection, by contrast, does not mix nodes. The next example computes a score per node, retains the top two and takes the induced subgraph. Multiplier tanh⁡\tanh makes the score affect the retained representation; in applications it is learned with the rest of the model. Ties require an explicit rule, since choosing by position can break equivariance when tied nodes are reordered.

[ ]Top-k selectionBrowser
scores = H @ np.array([.3, .8])
idx = np.argsort(-scores, kind='stable')[:2]
selected_h = H[idx] * np.tanh(scores[idx, None])
selected_a = A[np.ix_(idx, idx)]
print('nodos, índice desde cero:', idx)
print('representaciones:', np.round(selected_h, 6))
print('adyacencia:', selected_a)

Splitting graphs and comparing models

Graph classification evaluation defines the target population and separates whole graphs, not nodes of one graph between training and test. In molecules, a scaffold split groups structures with the same skeleton and prevents a group crossing splits. It does not ensure low similarity across groups or guarantee chemical extrapolation. In temporal prediction, groups and date must be constructed without information unavailable at the cutoff. To extrapolate to size, reserve larger graphs and declare that distribution shift.

Nested cross-validation separates the inner loop, which chooses hyperparameters and epoch, from the outer loop, which evaluates the entire selection procedure. Final test participates in no decision. If there is an official fixed split, use it for the relevant comparison and clarify that seeds estimate training variability, not uncertainty from independent samples of new populations. For model differences use paired seeds where the design permits and report individual differences, the interval and its method. Do not interpret a seed interval as describing uncertainty in the test split.

A reproducible molecular audit

This control uses the original ogbg-molhiv CSVs, logistic regression on Morgan fingerprints and two splits. This is an exploratory run of one predetermined model, not a GNN comparison or official result: the local RDKit version did not parse seven molecules, which were also excluded from the official split. The cell downloads the official file and checks its SHA-256 before reading. It needs local Python with NumPy, pandas, scikit-learn and RDKit; it may take several minutes. Printed indices are rows of the original table.

[ ]Audit a molecular splitLocal GPU
import io, hashlib, zipfile, urllib.request
import numpy as np
import pandas as pd
from rdkit import Chem, RDLogger, DataStructs
from rdkit.Chem import AllChem
from rdkit.Chem.Scaffolds import MurckoScaffold
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split

url = 'https://snap.stanford.edu/ogb/data/graphproppred/csv_mol_download/hiv.zip'
blob = urllib.request.urlopen(url, timeout=120).read()
expected = '47d747664b9e1653de5aac99bf26c015d88a3daa474f5a32f3fe5c014111375b'
assert hashlib.sha256(blob).hexdigest() == expected, 'El archivo ha cambiado; verifica su origen y versión antes de continuar.'
archive = zipfile.ZipFile(io.BytesIO(blob))
def csv_in_zip(name, **kwargs):
    return pd.read_csv(io.BytesIO(archive.read(name)), compression='gzip', **kwargs)

df = csv_in_zip('hiv/mapping/mol.csv.gz')
smiles, y = df['smiles'].tolist(), df['HIV_active'].to_numpy()
official = {part: csv_in_zip('hiv/split/scaffold/' + part + '.csv.gz', header=None)[0].to_numpy()
            for part in ['train', 'valid', 'test']}
RDLogger.DisableLog('rdApp.*')
fps = np.empty((len(smiles), 512), dtype=np.int8)
scaffolds, canonical, bits, usable = [], [], [], []
for i, text in enumerate(smiles):
    mol = Chem.MolFromSmiles(text)
    if mol is None:
        scaffolds.append(None); canonical.append(None); bits.append(None)
        continue
    usable.append(i)
    bit = AllChem.GetMorganFingerprintAsBitVect(mol, 2, nBits=512)
    bits.append(bit)
    DataStructs.ConvertToNumpyArray(bit, fps[i])
    scaffolds.append(MurckoScaffold.MurckoScaffoldSmiles(mol=mol, includeChirality=False))
    canonical.append(Chem.MolToSmiles(mol))
usable = np.array(usable)
official = {part: np.intersect1d(indices, usable) for part, indices in official.items()}
print('Filas utilizables:', len(usable), 'omitidas:', len(y) - len(usable))
train, rest = train_test_split(usable, test_size=.2, random_state=0, stratify=y[usable])
valid, test = train_test_split(rest, test_size=.5, random_state=0, stratify=y[rest])
for name, split in [('aleatoria', {'train': train, 'valid': valid, 'test': test}), ('andamio OGB', official)]:
    tr, te = split['train'], split['test']
    model = LogisticRegression(C=1, max_iter=500, random_state=0).fit(fps[tr], y[tr])
    auc = roc_auc_score(y[te], model.predict_proba(fps[te])[:, 1])
    overlap = len({scaffolds[i] for i in tr} & {scaffolds[i] for i in te})
    train_molecules = {canonical[i] for i in tr}
    duplicates = sum(canonical[i] in train_molecules for i in te)
    print(name, 'n', len(tr), len(split['valid']), len(te), 'AUC', round(auc, 6),
          'andamios compartidos', overlap, 'test duplicados', duplicates)
    sample = np.random.default_rng(9).choice(te, size=200, replace=False)
    train_bits = [bits[i] for i in tr]
    maxima = []
    for i in sample:
        sims = DataStructs.BulkTanimotoSimilarity(bits[i], train_bits)
        k = int(np.argmax(sims))
        maxima.append((sims[k], int(i), int(tr[k])))
    print('Muestra test 200: Tanimoto máximo >= 0.9:', sum(v >= .9 for v, _, _ in maxima),
          'par más cercano (similitud, test, train):', max(maxima))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

With RDKit 2026.09.2 and seed 0, the run gave AUC 0.749891 on the random split and 0.722872 on scaffold, with 1398 and 0 shared scaffolds between training and test respectively. There are no exact canonical duplicates across training and test in either case. In a fixed sample of 200 test molecules, 11 and 4 respectively have a training neighbor with Tanimoto at least 0.9 on these fingerprints. Fingerprint similarity does not prove chemical identity: collisions are possible with 512 bits. Differences in split, composition and example counts prevent attributing the AUC difference to one cause; nor is it an uncertainty estimate.

InteractiveThe split changes the question
Logistic regression AUC, one run
01

32896 parseable training molecules and 4112 test molecules. Seven molecules could not be parsed by this RDKit version and were excluded. Similarity uses finite fingerprints and does not prove identity.

Split
Test AUC0.7499
Scaffolds in train and test1398
Tanimoto ≥ 0.9 neighbor in sample of 20011
Closest pair: test / train rows37778 / 37777
Tanimoto of that pair1.0000
Compare the two runs of the preceding cell. The similarity sample contains only 200 test molecules and results use the parseable subset, not the entire official split.

Transactions: known window and future time

Elliptic represents Bitcoin transactions as nodes and payment flows as edges. In the CSV distributed by PyG, this check finds all edges lie within a single window and none go from a strictly earlier window to another. We therefore formulate the task at window close, when its graph is known: we do not reconstruct an event order the data do not provide. For each node we compute its number of inputs and an aggregation of predecessor degrees, without using labels to construct those two features.

A fixed logistic regression predicts the illicit label among labeled transactions. The random split mixes windows and knows their full structure, whereas the temporal split trains on windows 1 to 34, reserves 35 to 41 for validation and evaluates 42 to 49. Hyperparameters were not tuned on either. Actual availability of labels at training time is not established here, and unlabeled cases are excluded: the result is not a measure of real-time deployment or all payments.

InteractiveTransactions: random versus temporal
ROC-AUC
Average precision
01

Evaluation at each window close. Test cases and prevalence change; results do not identify a cause of the difference.

Split
Test ROC-AUC0.5027
Test average precision0.0994
Test positive proportion0.0977
Labeled training / test37251 / 4657
Compare the two splits from one run of the following cell. Average precision also depends on positive prevalence; test populations differ.

The control is deliberately weak: in this run, ROC-AUC is near 0.5 and average precision is near prevalence in both cases. The score difference does not show one split is always harder. Download the dataset with PyG and run the local cell to reproduce it. Automatic execution omits it due to file size, but it was verified end to end with original downloaded CSVs; figure metrics correspond to that run.

[ ]Audit time on EllipticLocal GPU
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, average_precision_score
from sklearn.model_selection import train_test_split

from torch_geometric.datasets import EllipticBitcoinDataset
EllipticBitcoinDataset(root='dataset/elliptic')
root = 'dataset/elliptic/raw/'
features = pd.read_csv(root + 'elliptic_txs_features.csv', header=None, usecols=[0, 1], names=['txId', 'time'])
edges = pd.read_csv(root + 'elliptic_txs_edgelist.csv')
classes = pd.read_csv(root + 'elliptic_txs_classes.csv')
frame = features.merge(classes, on='txId', how='left', validate='one_to_one')
lookup = pd.Series(np.arange(len(frame)), index=frame.txId)
src = edges.txId1.map(lookup).to_numpy()
dst = edges.txId2.map(lookup).to_numpy()
assert not np.isnan(src).any() and not np.isnan(dst).any()
src, dst = src.astype(int), dst.astype(int)
time = frame.time.to_numpy()
print('aristas desde ventana estrictamente anterior:', int(np.sum(time[src] < time[dst])))
same_window = time[src] == time[dst]
src, dst = src[same_window], dst[same_window]
incoming = np.bincount(dst, minlength=len(frame))
parent_count = np.bincount(dst, weights=np.log1p(incoming[src]), minlength=len(frame))
X = np.column_stack([np.log1p(incoming), parent_count / np.maximum(incoming, 1)])
labels = frame['class'].astype(str).to_numpy()
known = np.flatnonzero(np.isin(labels, ['1', '2']))
y = (labels == '1').astype(int)
random_train, rest = train_test_split(known, test_size=.2, stratify=y[known], random_state=0)
random_valid, random_test = train_test_split(rest, test_size=.5, stratify=y[rest], random_state=0)
temporal_train = known[time[known] <= 34]
temporal_valid = known[(time[known] >= 35) & (time[known] <= 41)]
temporal_test = known[time[known] >= 42]
print('nodos', len(frame), 'aristas dentro de ventana', len(src), 'etiquetados', len(known))
for name, train, valid, test in [('aleatoria', random_train, random_valid, random_test), ('temporal', temporal_train, temporal_valid, temporal_test)]:
    model = LogisticRegression(C=1, max_iter=500).fit(X[train], y[train])
    scores = model.predict_proba(X[test])[:, 1]
    print(name, 'n train/val/test', len(train), len(valid), len(test), 'positivos test', int(y[test].sum()),
          'ROC-AUC', roc_auc_score(y[test], scores), 'AP', average_precision_score(y[test], scores))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

GIN, SAGPool and pretraining on molhiv

The following lab uses OGB’s scaffold split and ROC-AUC evaluator, without filtering molecules with RDKit. It compares a sum GIN, the same encoder with SAGPool and a GIN pretrained to reconstruct masked atom type on training graphs. Models use atomic features and connectivity, but no bond features: this simplification limits what they can represent. Pretraining uses only the training split. The best fine-tuning epoch is selected on validation; test is evaluated at the end of each seed. Parameter counts and per-seed results are printed: the models do not have exactly the same budget, so do not attribute a difference solely to pooling. The count includes the mask head even when it does not participate in supervised prediction.

In this minimal version zero replaces the hidden atom type and is not an exclusive mask token: the encoder can confuse it with a type present in data. Other features remain visible. This is one control, not a reproduction of every cited pretraining method. Run the cell in an environment with PyTorch, PyTorch Geometric and OGB; it downloads the dataset and may be costly. The functionality check used one seed, one epoch and five batches per split, not the full ten runs. The complete cell is not run automatically in QA.

[ ]GIN and pretraining on ogbg-molhivLocal GPU
from types import SimpleNamespace
import copy
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch_geometric.data.data import Data, DataEdgeAttr, DataTensorAttr
from torch_geometric.data.storage import GlobalStorage
from torch_geometric.nn import GINConv, SAGPooling, global_add_pool
from torch_geometric.loader import DataLoader
from ogb.graphproppred import PygGraphPropPredDataset, Evaluator
from ogb.graphproppred.mol_encoder import AtomEncoder
from ogb.utils.features import get_atom_feature_dims

args = SimpleNamespace(root='dataset', seeds=10, epochs=100, pretrain=10, max_batches=0)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
with torch.serialization.safe_globals([Data, DataEdgeAttr, DataTensorAttr, GlobalStorage]):
    dataset = PygGraphPropPredDataset(name='ogbg-molhiv', root=args.root)
split = dataset.get_idx_split()
evaluator = Evaluator(name='ogbg-molhiv')
loaders = {part: DataLoader(dataset[split[part]], batch_size=128, shuffle=(part == 'train')) for part in split}

class GraphModel(nn.Module):
    def __init__(self, pool, hidden=64):
        super().__init__()
        self.atom = AtomEncoder(hidden)
        self.convs = nn.ModuleList([GINConv(nn.Sequential(nn.Linear(hidden, hidden), nn.ReLU(), nn.Linear(hidden, hidden)), train_eps=True) for _ in range(2)])
        self.pool = SAGPooling(hidden, ratio=.5) if pool else None
        self.classifier = nn.Linear(hidden, 1)
        self.mask_head = nn.Linear(hidden, get_atom_feature_dims()[0])

    def encode(self, x, edges):
        h = self.atom(x)
        for conv in self.convs:
            h = F.relu(conv(h, edges))
        return h

    def forward(self, batch):
        h = self.encode(batch.x, batch.edge_index)
        group = batch.batch
        if self.pool is not None:
            h, _, _, group, _, _ = self.pool(h, batch.edge_index, batch=batch.batch)
        return self.classifier(global_add_pool(h, group))

def pretrain(model, epochs):
    optimizer = torch.optim.Adam(list(model.atom.parameters()) + list(model.convs.parameters()) + list(model.mask_head.parameters()), lr=.001)
    model.train()
    for _ in range(epochs):
        for step, batch in enumerate(loaders['train']):
            batch = batch.to(device)
            mask = torch.rand(batch.x.size(0), device=device) < .15
            if not mask.any(): continue
            x = batch.x.clone(); truth = x[mask, 0].clone(); x[mask, 0] = 0
            optimizer.zero_grad()
            loss = F.cross_entropy(model.mask_head(model.encode(x, batch.edge_index)[mask]), truth)
            loss.backward(); optimizer.step()
            if args.max_batches and step + 1 >= args.max_batches: break

@torch.no_grad()
def evaluate(model, loader):
    model.eval(); true, pred = [], []
    for step, batch in enumerate(loader):
        batch = batch.to(device)
        true.append(batch.y.view(-1, 1).cpu()); pred.append(model(batch).cpu())
        if args.max_batches and step + 1 >= args.max_batches: break
    true, pred = torch.cat(true), torch.cat(pred)
    # Un subconjunto corto puede no contener ambas clases, caso sin ROC-AUC definida.
    if torch.unique(true).numel() < 2: return None
    return evaluator.eval({'y_true': true, 'y_pred': pred})['rocauc']

results = {name: [] for name in ['GIN', 'GIN+SAG', 'GIN+mask']}
for seed in range(args.seeds):
    for name in results:
        torch.manual_seed(seed)
        if device.type == 'cuda': torch.cuda.manual_seed_all(seed)
        model = GraphModel(pool=(name == 'GIN+SAG')).to(device)
        if name == 'GIN+mask': pretrain(model, args.pretrain)
        optimizer = torch.optim.Adam(model.parameters(), lr=.001)
        best, state = -1, None
        for epoch in range(args.epochs):
            model.train()
            for step, batch in enumerate(loaders['train']):
                batch = batch.to(device); optimizer.zero_grad()
                logits = model(batch); truth = batch.y.view(-1, 1).float()
                loss = F.binary_cross_entropy_with_logits(logits, truth)
                loss.backward(); optimizer.step()
                if args.max_batches and step + 1 >= args.max_batches: break
            val = evaluate(model, loaders['valid'])
            if val is not None and val > best:
                best, state = val, copy.deepcopy(model.state_dict())
        if state is None:
            print(name, 'sin AUC de validación en prueba corta', flush=True)
            continue
        model.load_state_dict(state)
        score = evaluate(model, loaders['test'])
        results[name].append(score)
        print('semilla', seed, name, 'test', score, 'parámetros', sum(p.numel() for p in model.parameters()), flush=True)
for name, values in results.items():
    if values and all(v is not None for v in values):
        print(name, 'media', float(np.mean(values)), 'desviación muestral', float(np.std(values, ddof=1)) if len(values) > 1 else None)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Learning without labels

Graph self-supervised learning constructs a signal from structure or features themselves before evaluating a labeled task. Deep Graph Infomax contrasts graph node representations with a corrupted version using a discriminator and global summary. The corruption defines what information the model must distinguish: it does not guarantee the representation serves every task.

GraphCL contrasts augmented views of the same graph; removing edges or features can destroy the property to predict. A masked autoencoder hides features and learns to reconstruct them, taking care to avoid trivial copy paths. Hu et al. study node- and graph-level pretraining strategies. To compare pretraining, fix available data, augmentations, encoder, budget and downstream protocol: a frozen linear probe and fine-tuning answer different questions.

In DGI one specific choice is hi=fθ(X,A)i\vb{h}_i=f_\theta(\mat{X},\mat{A})_i, h~i=fθ(X~,A)i\tilde{\vb{h}}_i=f_\theta(\tilde{\mat{X}},\mat{A})_i, s=σ(n−1∑ihi)\vb{s}=\sigmoid(n^{-1}\sum_i\vb{h}_i) and discriminator D(h,s)=σ(h⊤Wds)D(\vb{h},\vb{s})=\sigmoid(\vb{h}\T\mat{W}_d\vb{s}). A minimizable binary loss, normalized by node count, is

L=−1n∑i[log⁡D(hi,s)+log⁡(1−D(h~i,s))].\Loss=-\frac1n\sum_i\left[\log D(\vb{h}_i,\vb{s})+\log(1-D(\tilde{\vb{h}}_i,\vb{s}))\right].

The following negative signal permutes features and retains edges. The summary comes from the original graph for both positive and negative scores. Here you reuse the preceding lesson’s message-passing framework: hidden preparation includes a copy of its module so the two lesson sessions are independent. The module can also be downloaded from that lesson. This copy corresponds to SHA-256 722eb1df61bde98ee9a7770777bd4ab4646c8094144f4165d9e979f468252587.

There are two passes through the same encoder, original and corrupted. Retain both caches and sum their parameter gradients before updating. The positive branch derivative also includes the summary effect, which depends on every original node. The cell uses a toy graph and SGD; it does not claim to reproduce the paper’s benchmark. Its gradients were checked against PyTorch autograd using the same module’s adapter.

[ ]DGI from scratch with the frameworkBrowser
import numpy as np

X = np.array([[1., .1], [.9, .2], [.2, .9], [.1, 1.]])
edges = np.array([[0, 1, 1, 2, 2, 3], [1, 0, 2, 1, 3, 2]])
permutation = np.array([2, 0, 3, 1])
layer = MPLayer(d=2, hidden=4, aggregation='mean', seed=3)
D = np.array([[.2, -.1], [.1, .3]])

def objective_and_grads(layer, D, X, edges, permutation):
    h, cache = layer.forward(X, edges, return_cache=True)
    neg, neg_cache = layer.forward(X[permutation], edges, return_cache=True)
    summary = 1 / (1 + np.exp(-h.mean(axis=0)))
    positive, negative = h @ D @ summary, neg @ D @ summary
    loss = np.mean(np.logaddexp(0, -positive) + np.logaddexp(0, negative))
    gp = (1 / (1 + np.exp(-positive)) - 1) / len(X)
    gn = (1 / (1 + np.exp(-negative))) / len(X)
    projected = D @ summary
    summary_grad = D.T @ (h.T @ gp + neg.T @ gn)
    dh = gp[:, None] * projected + (summary_grad * summary * (1 - summary) / len(X))[None, :]
    dn = gn[:, None] * projected
    first = layer.backward(dh, cache)
    second = layer.backward(dn, neg_cache)
    grads = {name: first[name] + second[name] for name in layer.params}
    grad_D = np.outer(h.T @ gp + neg.T @ gn, summary)
    return float(loss), grads, grad_D

initial, _, _ = objective_and_grads(layer, D, X, edges, permutation)
for _ in range(80):
    _, grads, grad_D = objective_and_grads(layer, D, X, edges, permutation)
    layer.step(grads, .1)
    D -= .1 * grad_D
final, _, _ = objective_and_grads(layer, D, X, edges, permutation)
print('DGI con mini_mp, pérdida inicial/final:', round(initial, 6), round(final, 6))
print('salida por nodo:', layer.forward(X, edges).shape)

A lower loss only shows the encoder better distinguishes this fixed corruption on this graph. A linear probe must train with training labels on frozen embeddings and choose hyperparameters without consulting test. Inductive pretraining cannot use test graphs either if the protocol does not make them available.

Frozen probes and nested selection on a small graph

Construct two synthetic cycles joined by an edge and noisy class-derived features. The encoder sees the full graph and features during pretraining: this example is transductive. Once data are generated, labels are used only to fit and evaluate the probe. The inner loop selects regularization and the outer measures the full procedure on held-out labels. Node splits of one graph are dependent, so their three scores are not a confidence interval for a population of new graphs.

The DGI bilinear discriminator is also trained here, as is an autoencoder that reconstructs only hidden inputs. Finite differences avoid depending on an autodiff engine but are inefficient at real dimensions. A probe on propagated features without pretraining is added to detect whether the synthetic task is already easy. The example checks probe flow; it does not replace real evaluation or prove any objective improves transfer.

[ ]DGI, masking and nested probeBrowser
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import accuracy_score

rng = np.random.default_rng(4)
n = 40
y = np.arange(n) // 20
A = np.zeros((n, n))
for i in range(n):
    start = (i // 20) * 20
    j = start + (i - start + 1) % 20
    A[i, j] = A[j, i] = 1
A[19, 20] = A[20, 19] = 1
A += np.eye(n)
d = A.sum(1)
P = A / np.sqrt(d[:, None] * d[None, :])
X = np.column_stack([1 - y, y]) + rng.normal(0, .3, (n, 2))
permutation = rng.permutation(n)
mask = rng.random((n, 2)) < .25
masked = X.copy(); masked[mask] = 0

def unpack(theta):
    return theta[:4].reshape(2, 2), theta[4:].reshape(2, 2)

def dgi_loss(theta):
    W, D = unpack(theta)
    h = np.tanh(P @ X @ W)
    neg = np.tanh(P @ X[permutation] @ W)
    summary = 1 / (1 + np.exp(-h.mean(0)))
    pos, negative = h @ D @ summary, neg @ D @ summary
    return np.mean(np.logaddexp(0, -pos) + np.logaddexp(0, negative))

def mask_loss(theta):
    W, decoder = unpack(theta)
    h = np.tanh(P @ masked @ W)
    prediction = h @ decoder
    return np.mean((prediction[mask] - X[mask]) ** 2)

def fit(objective):
    theta = np.array([.2, -.1, .1, .3, .2, .1, -.1, .2])
    before = objective(theta)
    for _ in range(100):
        grad = np.empty_like(theta)
        for j in range(len(theta)):
            delta = np.zeros_like(theta); delta[j] = 1e-4
            grad[j] = (objective(theta + delta) - objective(theta - delta)) / 2e-4
        theta -= .3 * grad
    return theta, before, objective(theta)

def nested_probe(h):
    outer = StratifiedKFold(3, shuffle=True, random_state=2)
    scores = []
    for train, test in outer.split(h, y):
        inner = StratifiedKFold(2, shuffle=True, random_state=3)
        candidates = [.1, 1., 10.]
        means = []
        for C in candidates:
            values = []
            for fit_ids, val_ids in inner.split(h[train], y[train]):
                model = LogisticRegression(C=C, max_iter=200).fit(h[train[fit_ids]], y[train[fit_ids]])
                values.append(accuracy_score(y[train[val_ids]], model.predict(h[train[val_ids]])))
            means.append(np.mean(values))
        chosen = candidates[int(np.argmax(means))]
        model = LogisticRegression(C=chosen, max_iter=200).fit(h[train], y[train])
        scores.append(accuracy_score(y[test], model.predict(h[test])))
    return np.array(scores)

print('sin preentrenar, sonda por fold', np.round(nested_probe(P @ X), 4))
for name, objective in [('DGI', dgi_loss), ('enmascarado', mask_loss)]:
    theta, initial, final = fit(objective)
    W, _ = unpack(theta)
    h = np.tanh(P @ X @ W)
    print(name, 'pérdida inicial/final', round(initial, 6), round(final, 6), 'sonda por fold', np.round(nested_probe(h), 4))

Report checklist

Describe task, prediction unit and target population; split date and rule; available features, edges and labels; preprocessing fitted on training; inner selection; metric and evaluator; seeds and dispersion; budget; and controls. Publish results by split and seed, not only the best run. State whether test samples are dependent and what source of variation each interval captures.

Exercises

Quiz
You want to evaluate prediction of unseen future molecules. Which decisions compromise that objective?

More than one answer may be correct.

Quiz
You want to predict a transaction's category when it arrives. Which procedure introduces future information?
Quiz
In a transductive benchmark, which test use invalidates a held-out evaluation?
Numeric
Across ten paired seeds, A obtains 0.70, 0.72, 0.71, 0.73, 0.69, 0.74, 0.72, 0.71, 0.73, 0.70; B obtains 0.72, 0.73, 0.72, 0.74, 0.71, 0.74, 0.73, 0.73, 0.74, 0.72. What is the mean of the differences B minus A?
Quiz
The paired 95 % t interval for B minus A in the previous exercise is [0.00817, 0.01783]. What conclusion does it permit under its assumptions?
Code
Implement scaffold_split(smiles, frac), returning three lists of nonrepeated indices. Group with RDKit Bemis-Murcko scaffolds without chirality; reject invalid SMILES and negative fractions or fractions that do not sum to one. Sort groups by descending size and then scaffold text; assign each entire group to the split with the largest absolute deficit between desired and current size, breaking ties by index. Fractions are targets, not guaranteed sizes. Install RDKit locally.
def scaffold_split(smiles, frac):
  # Devuelve índices de entrenamiento, validación y test.
  pass
Shift+Enter to run
Proof
Prove: Sum readout and the DiffPool reduced graph are invariant under node reordering if representations and assignments are equivariant.
0
Let Q be a permutation matrix, H the node matrix, S the assignment and A the adjacency.

Step 1 of 3. How do H, S and A change?

Key idea
A good graph result is a claim about a specific task and protocol. Architecture matters, but available information and model selection determine what the score means.