"""Pinned DGL SIGN training, separate from the prediction time allowance.""" from __future__ import annotations import time import numpy as np from sign_numpy import SIGN, Adam, cross_entropy # The pinned DGL README's ogbn-mag command and sign.py defaults. HOPS = 5 HIDDEN = 512 LAYERS = 2 DROPOUT = 0.5 INPUT_DROPOUT = 0.0 LEARNING_RATE = 0.001 BATCH_SIZE = 50000 EPOCHS = 1000 EVAL_EVERY = 10 SEED = 0 # Only execution chunk sizes. There is one optimizer step per logical batch, # and SIGN has no batch normalization or other cross-example layer. MICROBATCH = 512 PREDICT_BATCH = 1024 def split_known(known, labels): """Retain the previous adapter's fixed 90/10 split, independently per graph.""" permutation = np.random.default_rng(SEED).permutation(len(known)) validation_size = max(1, len(known) // 10) if len(known) > 1 else 0 valid, train = permutation[:validation_size], permutation[validation_size:] return known[train], labels[train], known[valid], labels[valid] def predict(model, features, ids=None, classes=None): if ids is None: ids = np.arange(len(features)) result = np.empty(len(ids), dtype=np.int64) width = features.shape[1] // (HOPS + 1) for start in range(0, len(ids), PREDICT_BATCH): batch = features[ids[start:start + PREDICT_BATCH]] blocks = [batch[:, h * width:(h + 1) * width] for h in range(HOPS + 1)] logits, _ = model.forward(blocks) if classes is not None: logits = logits[:, :classes] result[start:start + len(batch)] = logits.argmax(axis=1) return result def fit(train_features, train_labels, valid_features, valid_labels, classes, training_deadline, num_epochs=EPOCHS, checkpoint=None): """Shuffle the pooled examples; use source-size batches and source Adam. The union of independent training graphs changes the data adapter, not the SIGN layers or their objective. No edges or local IDs cross graphs. """ if not len(train_labels): raise ValueError("SIGN needs supplied known labels to train") width = train_features.shape[1] // (HOPS + 1) model = SIGN(width, HIDDEN, classes, HOPS + 1, LAYERS, DROPOUT, INPUT_DROPOUT, seed=SEED) optimizer = Adam(model, lr=LEARNING_RATE) shuffle_rng = np.random.default_rng(SEED) best_state, best_val, best_epoch = None, -1.0, 0 completed_state = None completed_epochs = 0 epoch_times, evaluations = [], [] last_evaluated = 0 stopped_for_budget = False def evaluate(epoch): nonlocal best_state, best_val, best_epoch, last_evaluated accuracy = float(np.mean(predict(model, valid_features) == valid_labels)) evaluations.append({"epoch": epoch, "validation_accuracy": accuracy}) print(f"SIGN validation epoch={epoch} accuracy={accuracy:.8f}", flush=True) if accuracy > best_val: best_state = model.state_dict() best_val, best_epoch = accuracy, epoch if checkpoint is not None: checkpoint(model, epoch, accuracy) last_evaluated = epoch for epoch in range(1, num_epochs + 1): estimated_epoch = max(epoch_times[-3:], default=0.0) if time.monotonic() + 1.15 * estimated_epoch >= training_deadline: stopped_for_budget = True break started = time.monotonic() order = shuffle_rng.permutation(len(train_labels)) interrupted = False total_loss = 0.0 for start in range(0, len(order), BATCH_SIZE): logical_batch = order[start:start + BATCH_SIZE] model.zero_grad() for offset in range(0, len(logical_batch), MICROBATCH): if time.monotonic() >= training_deadline: interrupted = True break indexes = logical_batch[offset:offset + MICROBATCH] batch = train_features[indexes] blocks = [batch[:, h * width:(h + 1) * width] for h in range(HOPS + 1)] logits, cache = model.forward(blocks, training=True) loss, gradient = cross_entropy(logits, train_labels[indexes], denominator=len(logical_batch)) if not np.isfinite(loss): raise FloatingPointError("Non-finite SIGN cross-entropy") total_loss += loss * len(logical_batch) / len(train_labels) model.backward(gradient, cache) if interrupted: break optimizer.step() if interrupted: # An incomplete logical batch is discarded, not applied with a # different denominator. Discard earlier steps in that epoch too. if completed_state is not None: model.load_state_dict(completed_state) stopped_for_budget = True break completed_epochs = epoch completed_state = model.state_dict() epoch_times.append(time.monotonic() - started) print(f"SIGN epoch={epoch} seconds={epoch_times[-1]:.3f} " f"loss={total_loss:.6f}", flush=True) if len(valid_labels) and epoch % EVAL_EVERY == 0: evaluate(epoch) if not completed_epochs: raise RuntimeError("The training budget did not permit a complete SIGN epoch") if len(valid_labels) and last_evaluated != completed_epochs: evaluate(completed_epochs) if best_state is not None: model.load_state_dict(best_state) else: best_epoch = completed_epochs return model, { "method": "DGL SIGN (NumPy; offline fitting on visible known labels)", "source_commit": "3d16000b4170fa741ed9e9667f22ba84d3493026", "hops": HOPS, "hidden": HIDDEN, "feed_forward_layers": LAYERS, "dropout": DROPOUT, "input_dropout": INPUT_DROPOUT, "learning_rate": LEARNING_RATE, "weight_decay": 0, "optimizer": "Adam", "adam_betas": [0.9, 0.999], "adam_eps": 1e-8, "batch_size": BATCH_SIZE, "microbatch_size": MICROBATCH, "source_epochs": EPOCHS, "requested_epochs": num_epochs, "completed_epochs": completed_epochs, "selected_epoch": best_epoch, "selected_validation_accuracy": best_val if len(valid_labels) else None, "eval_every": EVAL_EVERY, "train_count": len(train_labels), "validation_count": len(valid_labels), "optimizer_steps": optimizer.steps, "parameter_count": sum(p.value.size for _, p in model.named_parameters()), "epoch_seconds": epoch_times, "evaluations": evaluations, "stopped_for_budget": stopped_for_budget, "degraded": completed_epochs < EPOCHS, "seed": SEED, }