TGraphX › Insights › Writing Source-Grounded Documentation for a GNN Library
← Back to Insights

Writing Source-Grounded Documentation for a GNN Library

Topic: APIs, tooling and research-engineering workflow

Documentation that overstates what a library does costs trust quickly. Researchers test claims, read the source and notice when a promise is not kept by the code. This tutorial is for library authors and technical writers who want documentation that is accurate, checkable and useful to those readers. The worked cases use TGraphX 1.5.1, and the Python blocks were tested with it on CPU.

The documentation accuracy problem

GNN library documentation tends to fail in a few recognisable ways:

Failure mode Example
Speed claims without evidence "2x faster than library X on citation networks" with no benchmark
Scope overclaiming "supports distributed training" when only helpers exist
Missing stability signals A Beta feature described as production-ready
Undocumented assumptions "pass your graph" without a shape specification
Outdated examples Code written for an earlier release that now behaves differently

Writing from the code, instead of from intentions, prevents most of these.

Step 1: Audit what is actually exported

Start with what the package declares, rather than dir(), which also lists private names and imported modules:

python
import importlib

import tgraphx

print(tgraphx.__version__, len(tgraphx.__all__))
modules = ["tgraphx.performance", "tgraphx.reproducibility",
           "tgraphx.distributed", "tgraphx.experiments"]
for name in modules:
    print(name, importlib.import_module(name).__all__)

assert "Graph" in tgraphx.__all__ and "Runner" not in tgraphx.__all__

The last line matters: public API is not only the top-level __all__. Runner is public, but it lives in tgraphx.experiments. Treat modules and names with a leading underscore as internal.

For each public name, ask whether it is documented, whether the documentation matches the current signature, and whether its stability is stated. TGraphX keeps a registry for the last question: tgraphx.api_status("Graph") returns stable, beta or experimental, and raises KeyError for names the registry does not list.

Step 2: Read the module docstrings, then check them

Module docstrings set expectations, but they are claims like any other.

  • tgraphx.performance exports env_report, recommended_device and estimate_message_memory. Document each with its signature and what it does not measure.
  • tgraphx.reproducibility exports set_seed, make_generator, seed_worker, reproducibility_report and deterministic_mode. Say what determinism costs and what it does not guarantee.
  • tgraphx.distributed says in its docstring that TGraphX does not ship a distributed training framework. It also provides helpers such as maybe_wrap_ddp, shard_indices and rank_seed.

The distributed case shows why both halves belong in the documentation. The disclaimer alone suggests there is nothing there; a list of helpers alone suggests more than there is.

Step 3: Tag claims by their evidence

[VERIFIED FROM SOURCE]  confirmed by reading the named file
[VERIFIED BY RUNNING]   confirmed by a test, with the version
[FROM DOCSTRING]        stated in a docstring, not independently checked
[VERSION NOTE]          behaviour that depends on the release
[USER RESPONSIBILITY]   the library does not handle this

For example:

markdown
**Message passing aggregation** [VERIFIED FROM SOURCE: layers/base.py,
layers/_scatter.py, layers/sage.py, layers/gat.py, layers/gin.py]
`TensorMessagePassingLayer` aggregates with `index_add` (sum, mean) or a
`scatter_reduce_`-based max. `TensorGraphSAGELayer`, `TensorGATLayer` and
`TensorGINLayer` do not subclass it. None of these loops over nodes in Python.

**Distributed training** [USER RESPONSIBILITY: distributed.py]
No distributed training framework is included. DDP helpers such as
`maybe_wrap_ddp` exist; starting the process group is up to you.

**Low precision** [VERIFIED FROM SOURCE: layers/_scatter.py, layers/gat.py]
`edge_softmax` computes in float32 for float16 and bfloat16 scores and returns
the input dtype. The chunked path of `TensorGATLayer` does not call it.

**Dropout default** [VERSION NOTE: 1.5.0]
`ConvMessagePassing` defaults to `dropout_prob=0.0`. Releases up to 1.4.2
used 0.3. Omitting the argument emits `DropoutDefaultChangeWarning`.

Tags like "verified" are only worth something if the check can be repeated. Where possible, write the check as code:

python
import warnings

import torch
from tgraphx import ConvMessagePassing, DropoutDefaultChangeWarning
from tgraphx.layers._scatter import edge_softmax   # private: check it, do not build on it

scores = torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16)
attn = edge_softmax(scores, torch.tensor([0, 0, 1]), num_nodes=2)
assert attn.dtype == torch.float16                  # the input dtype comes back

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    ConvMessagePassing((3, 8, 8), (4, 8, 8))
assert any(issubclass(w.category, DropoutDefaultChangeWarning) for w in caught)

A precise note such as the low-precision one is easy to get wrong when shortened. "Attention runs in float32" overstates it, since only the softmax is described, and "users will see float32 outputs" is wrong.

Step 4: Use shape specifications as documentation

For every function or class that takes tensors, state the shapes, with symbolic names, and state which ones must agree:

node_features: [N, ...]    N nodes; at least 2 dimensions
edge_index:    [2, E]      dtype long; values in [0, N)
edge_features: [E, ...]    at least 2 dimensions; E must match the edge_index columns
node_labels:   [N, ...]    N must match node_features

Then say what happens when a rule is broken. For tgraphx.Graph, each of the rules above is checked at construction.

Step 5: Make examples that actually run

Examples drift. An argument is renamed or a default changes, and the page still looks fine. So:

  1. State the version the example was tested with.
  2. Let the library's own validation catch errors where it can.
  3. Run every example in CI.
python
import torch

from tgraphx import Graph
from tgraphx.performance import recommended_device, env_report
from tgraphx.reproducibility import set_seed

# Step 1: environment and seed
print(env_report(include_hardware=True))
set_seed(42)

# Step 2: a graph with documented shapes
device = recommended_device()
g = Graph(
    node_features=torch.randn(20, 64),          # [N=20, d=64]
    edge_index=torch.randint(0, 20, (2, 50)),   # [2, E=50]
    edge_features=torch.randn(50, 16),          # [E=50, de=16]
    node_labels=torch.randint(0, 3, (20,)),     # [N=20]
).to(device)

# Construction succeeded: sizes are consistent. It cannot tell whether
# the dimensions mean what you intended.
print(g.node_features.shape, g.edge_index.shape)

A small runner is enough to test a Markdown page: extract the Python blocks and execute them in order in one namespace. Run it only on documentation you control, because it executes whatever it finds.

python
import re

FENCE = "`" * 3


def run_markdown_examples(text):
    pattern = re.compile(rf"^{FENCE}python\n(.*?)^{FENCE}$", re.M | re.S)
    namespace = {"__name__": "doc_example"}
    blocks = pattern.findall(text)
    for number, code in enumerate(blocks, 1):
        exec(compile(code, f"<example {number}>", "exec"), namespace)
    return len(blocks)


page = f"{FENCE}python\nx = 2\n{FENCE}\n\nProse.\n\n{FENCE}python\nassert x == 2\n{FENCE}\n"
assert run_markdown_examples(page) == 2

This handles plain, unindented fences only. A documentation tool's doctest feature may fit better for large sites.

Step 6: Document each layer's input contract

A layer list without input shapes leaves out the most important fact:

Layer Node features What it is
TensorGraphSAGELayer [N, C, H, W], or [N, C, D, H, W] with spatial_rank=3 GraphSAGE; aggr is "mean" or "max"
TensorGATLayer same graph attention
TensorGINLayer same GIN, motivated by graph isomorphism testing
GCNConv [N, D] GCN; adds self-loops
GATv2Conv [N, D] GATv2 attention
APPNP [N, D] personalised-PageRank propagation; no parameters

All of them are called with (x, edge_index), not with a Graph object. A table like this can be tested too:

python
import torch
import tgraphx as tgx


def raises_value_error(layer, x, edge_index):
    try:
        layer(x, edge_index)
    except ValueError:
        return True
    return False


edge_index = torch.randint(0, 6, (2, 12))
vectors, images = torch.randn(6, 8), torch.randn(6, 3, 8, 8)

for layer in (tgx.TensorGraphSAGELayer(3, 4), tgx.TensorGATLayer(3, 4),
              tgx.TensorGINLayer(3, 4)):
    assert layer(images, edge_index).shape == (6, 4, 8, 8)
    assert raises_value_error(layer, vectors, edge_index)

for layer in (tgx.GCNConv(8, 4), tgx.GATv2Conv(8, 4), tgx.APPNP(K=2)):
    assert layer(vectors, edge_index).shape[0] == 6
    assert raises_value_error(layer, images, edge_index)

Step 7: Document the experiments infrastructure

tgraphx.experiments needs particular care, because names such as Runner and ExperimentConfig invite guesses about their signatures. Runner is driven by a declarative configuration. It does not accept a model, an optimizer or data loaders:

python
import tempfile
from pathlib import Path

from tgraphx.experiments import Runner, load_config

with tempfile.TemporaryDirectory() as run_dir:
    config = load_config({
        "seed": 0,
        "run_name": "docs-example",
        "run_dir": run_dir,
        "dataset": {"name": "synthetic:patch_graph",
                    "kwargs": {"num_graphs": 8, "seed": 0}},
        "model": {"task": "graph_classification", "layer": "sage",
                  "in_shape": [1, 8, 8], "hidden_shape": [8, 8, 8],
                  "num_layers": 1, "num_classes": 6},
        "training": {"epochs": 2, "lr": 0.005},
        "callbacks": [{"name": "model_checkpoint"}],
    })
    history = Runner(config).fit()               # fit() takes no arguments
    print(sorted(history[0]))                    # ['epoch', 'train_loss']
    print(sorted(p.name for p in Path(run_dir).iterdir()))
    assert sorted(p.name for p in (Path(run_dir) / "checkpoints").iterdir()) == ["latest.pt"]

The documentation for these objects has to say things that are not obvious from the names. In 1.5.1:

  • Runner trains on one full batch of the whole dataset. training.batch_size, val_ratio and test_ratio are accepted but unused.
  • No validation loss is computed. With their default monitor="val_loss", the early_stopping callback never triggers and model_checkpoint saves only the latest checkpoint. Monitoring "train_loss" makes both act, but that is not a validation criterion.
  • GridRunner runs a configuration over a parameter grid and several seeds.
  • To train your own model on your own loaders, use tgraphx.fit(model, train_loader, val_loader, optimizer=..., loss_fn=...). It has no callbacks and ignores node masks: the loss uses every node label, including validation and test nodes, so for transductive node tasks write your own loop and compute the loss on logits[train_mask] and labels[train_mask].

Common documentation failures to avoid

Failure Prevention
"Fast" without definition No speed claims without data
"Supports X" for partial support "Provides helpers for X; users must implement Y"
Example code not matching the API Run examples in CI
No shape specifications State every tensor argument's shape
No stability or version notes Mark Beta and Experimental features and changed defaults
Missing error behaviour Say what is raised, and when
Silently ignored arguments Say so where it happens

Documentation written from the source and checked by running it holds up better than documentation written from memory. Reading alone has limits, covered in what source code can and cannot tell you.