TGraphX › Insights › TGraphX Troubleshooting FAQ: Errors, Layer Shapes and Silent Mistakes
← Back to Insights

TGraphX Troubleshooting FAQ: Errors, Layer Shapes and Silent Mistakes

Topic: Getting started with TGraphX

This FAQ answers common questions from researchers new to TGraphX, with the emphasis on error messages and mistakes that fail silently. Questions are organized by theme: installation, graph construction, message passing, reproducibility, interoperability and troubleshooting.

Examples tested with TGraphX 1.5.1 on CPU. Run the Python blocks in order.


Installation and Setup

Q: Does TGraphX require PyTorch Geometric or DGL?

No. The base package depends only on PyTorch, torchvision and PyYAML, and its graph layers, mining functions, knowledge-graph embeddings, generators and RL environments do not need PyG or DGL. Optional extras include [pyg], [ogb], [mlflow], [tracking] (TensorBoard), [monitoring] and [pillow]. There is no [dgl] extra: install DGL yourself if you want to use the DGL converters.

bash
pip install tgraphx              # no PyG, no DGL required
pip install "tgraphx[pyg]"       # optional: PyG datasets and converters

Q: How do I verify TGraphX is installed correctly?

bash
python -m tgraphx doctor

This prints the TGraphX, Python and PyTorch versions, CUDA availability and which optional dependencies are present. It does not run a model. A three-line forward pass is a better check that things work:

python
import torch
import tgraphx as tgx

torch.manual_seed(0)             # makes the random data on this page repeatable
print(tgx.__version__)
print(tgx.api_status("Graph"))   # stable

x = torch.randn(4, 8)
edge_index = torch.tensor([[0, 1, 2], [1, 2, 3]])
print(tgx.GCNConv(8, 4)(x, edge_index).shape)   # torch.Size([4, 4])

Q: Which Python and PyTorch versions are supported?

TGraphX 1.5.1 declares Python 3.10 or later and PyTorch 1.13 or later (with torchvision 0.14 or later).


Graph Construction

Q: What is the difference between node_features, x, and node_labels in Graph()?

node_features (alias x) is the input tensor that layers consume. node_labels (aliases y and labels) holds supervision targets.

python
from tgraphx import Graph

g = Graph(
    node_features=torch.randn(50, 32),       # input to layers
    edge_index=torch.randint(0, 50, (2, 150), dtype=torch.long),
    node_labels=torch.randint(0, 4, (50,)),  # supervision targets
)
assert g.x is g.node_features
assert g.y is g.node_labels

Passing two different tensors under two aliases of the same field raises ValueError.

Q: My node features are image patches [N, C, H, W]. Does TGraphX support this?

Yes. Pass them directly to Graph():

python
patch_edges = torch.randint(0, 50, (2, 150))
patches = Graph(
    node_features=torch.randn(50, 16, 8, 8),   # [N, C, H, W]
    edge_index=patch_edges,
)
print(patches.feature_shape)                   # (16, 8, 8)

Then use a spatial layer such as ConvMessagePassing, TensorGraphSAGELayer, TensorGATLayer or TensorGINLayer.

Q: How do I construct a graph from a NumPy adjacency matrix?

python
import numpy as np

adj = np.array([[0, 1, 1],
                [1, 0, 0],
                [1, 0, 0]])
g_adj = tgx.make_graph(x=torch.randn(3, 16), adjacency=torch.from_numpy(adj))
print(g_adj.edge_index)   # one column per non-zero entry (row = source, column = target)

Only the positions of non-zero entries are used. If the values are edge weights, pass them yourself as edge_weight.

Q: How do I build a kNN graph from embeddings?

python
embeddings = torch.randn(100, 64)
knn_edges = tgx.knn_graph(embeddings, k=5, metric="cosine", make_symmetric=True)
print(knn_edges.shape)    # [2, E]; E exceeds 500 because edges are symmetrised

With make_symmetric=False, each edge points from a node to one of its neighbors, so node i sends messages to its neighbors rather than receiving from them.

Q: Does Graph validate inputs eagerly?

Yes. Graph() checks shapes, index range, dtype and device consistency at construction and raises ValueError or TypeError. It does not check for NaNs.

validate_graph is useful for re-checking a graph after you have modified it, but it checks less than the constructor (negative indices pass, for example). To re-run the constructor's checks (except mask lengths, which validate_graph does report) use g.validate(), and ask validate_graph for NaN/Inf checking explicitly:

python
g.validate()
report = tgx.validate_graph(g, check_finite=True)
print(report["ok"], report["issues"])

Message Passing

Q: Which layer should I use for [N, D] vector features?

GCNConv, GATv2Conv, APPNP or LinearMessagePassing:

python
from tgraphx import GCNConv, GATv2Conv, LinearMessagePassing

gcn = GCNConv(32, 64)
gat = GATv2Conv(32, 64, num_heads=4)
lin = LinearMessagePassing(in_shape=(32,), out_shape=(64,))

for layer in (gcn, gat, lin):
    print(type(layer).__name__, layer(g.node_features, g.edge_index).shape)

Q: Which layer should I use for [N, C, H, W] spatial features?

ConvMessagePassing takes full shapes; the Tensor* layers take channel counts. For volumes [N, C, D, H, W], give the Tensor* layers spatial_rank=3.

python
from tgraphx import ConvMessagePassing, TensorGINLayer, TensorGraphSAGELayer

conv_mp = ConvMessagePassing(in_shape=(16, 8, 8), out_shape=(32, 8, 8), dropout_prob=0.0)
gin = TensorGINLayer(16, 32)
sage = TensorGraphSAGELayer(16, 32)

for layer in (conv_mp, gin, sage):
    print(type(layer).__name__, layer(patches.node_features, patches.edge_index).shape)

Pass dropout_prob to ConvMessagePassing explicitly. Its default changed to 0.0 in 1.5.0 and omitting it emits a warning.

Q: The layer expects [N, C, H, W] but I have [N, H, W, C] (channels last). What should I do?

TGraphX follows the PyTorch channels-first convention. Convert before calling the layer:

python
x_hwc = torch.randn(50, 8, 8, 16)                  # [N, H, W, C]
x_chw = x_hwc.permute(0, 3, 1, 2).contiguous()     # [N, C, H, W]
print(x_chw.shape)                                 # torch.Size([50, 16, 8, 8])

The layout is not detected for you. Usually you get a PyTorch channel-mismatch RuntimeError; if the sizes happen to match, it runs and computes the wrong thing.

Q: My graph has no edges, or some nodes have none. Will message passing fail?

It will not fail: an empty edge_index of shape [2, 0] with dtype torch.long is valid. What a node without incoming edges receives depends on the layer, though:

Layer Node with no incoming edges
GCNConv, GATv2Conv (add self-loops by default) Output depends on its own features
TensorGraphSAGELayer, TensorGINLayer Output depends on its own features (self term)
LinearMessagePassing All zeros
TensorGATLayer (add_self_loops=False by default) Own features are not used
ConvMessagePassing Own features are not used
python
no_edges = torch.zeros(2, 0, dtype=torch.long)
v = torch.randn(3, 8)
t = torch.randn(3, 4, 5, 5)

assert (LinearMessagePassing((8,), (6,))(v, no_edges) == 0).all()

for layer in (tgx.TensorGATLayer(4, 6),
              ConvMessagePassing((4, 5, 5), (6, 5, 5), dropout_prob=0.0)):
    layer.eval()
    out = layer(t, no_edges)
    # three different inputs, three identical outputs
    assert torch.allclose(out[0], out[1]) and torch.allclose(out[1], out[2])

For the last three rows, add self-loops (graph.add_self_loops(), or add_self_loops=True on TensorGATLayer) if a node's own features must survive.

The exception to "it will not fail" is sampling. In 1.5.1, NeighborLoader on a graph that has no edges at all (an empty [2, 0] edge_index) yields batches with edge_index=None, and the layer call then fails. A batch without edges that is sampled from a graph that has edges gets a [2, 0] tensor. Graph generation with tensor-valued node features shows the case in a test.


Reproducibility

Q: How do I make my experiment reproducible?

Seed before creating data, models and loaders:

python
from tgraphx import NeighborLoader
from tgraphx.reproducibility import set_seed

set_seed(42, deterministic=True)
# Seeds Python's random, NumPy (if installed) and torch (CPU and CUDA).
# deterministic=True also asks PyTorch for deterministic algorithms.

train_mask = torch.zeros(g.num_nodes, dtype=torch.bool)
train_mask[:30] = True
loader = NeighborLoader(g, fanouts=[10, 5], mask=train_mask, batch_size=16, seed=42)

Two things people expect and do not get: set_seed does not set PYTHONHASHSEED (set it in the shell before starting Python if you need it), and the tgx.reproducible(...) context manager does not restore earlier settings when the block exits. Also note the loader's mask=: without it, every node is a seed, including your validation and test nodes.

set_seed also does not seed the loader's neighbor draw. In 1.5.1 a batch with the same target (seed) nodes in the same order gets the same neighbors on every pass, with or without seed=, so give each run of a multi-seed study its own loader seed= (details in the PyTorch FAQ).

Q: Are results reproducible across different GPUs or CUDA versions?

Not necessarily. Even with seeds fixed and deterministic algorithms on, results can differ between hardware, CUDA versions and PyTorch releases. Record all of them with your results.

Q: How do I report results across multiple seeds?

Keep the data split fixed and vary the model seed. Choose models and hyperparameters on validation nodes, then report the mean and standard deviation of test accuracy for the chosen setting. The three masks must not overlap:

python
import statistics
import torch.nn.functional as F

set_seed(0)    # g.edge_index was already fixed by torch.manual_seed(0) in the first block
features = torch.randn(g.num_nodes, 32)
labels = (features[:, 0] > 0).long()
val_mask = torch.zeros(g.num_nodes, dtype=torch.bool)
val_mask[30:40] = True                     # train_mask above covers nodes 0-29
test_mask = torch.zeros(g.num_nodes, dtype=torch.bool)
test_mask[40:] = True
assert tgx.check_leakage(train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)["ok"]

def run_with_seed(seed, lr):
    set_seed(seed)
    model = GCNConv(32, 2)
    optimizer = torch.optim.Adam(model.parameters(), lr=lr)
    for _ in range(30):
        optimizer.zero_grad()
        loss = F.cross_entropy(model(features, g.edge_index)[train_mask], labels[train_mask])
        loss.backward()
        optimizer.step()
    model.eval()
    with torch.no_grad():
        correct = model(features, g.edge_index).argmax(dim=1) == labels
    return correct[val_mask].float().mean().item(), correct[test_mask].float().mean().item()

seeds = [42, 123, 456]
runs = {lr: [run_with_seed(s, lr) for s in seeds] for lr in (1e-2, 1e-1)}

# select on validation only
best_lr = max(runs, key=lambda lr: statistics.mean(val for val, _ in runs[lr]))
# report test accuracy of the selected setting
test_acc = [test for _, test in runs[best_lr]]
print(f"lr={best_lr}: test accuracy {statistics.mean(test_acc):.3f} ± {statistics.stdev(test_acc):.3f}")

Three seeds is a minimum; more are better when the spread is large. The edges here are random and there are only ten validation and ten test nodes, so read nothing into the score itself; the block shows the procedure.


Interoperability

Q: Can I convert a NetworkX graph to a TGraphX Graph?

Yes (NetworkX must be installed). Node attributes are only used if you name one with node_feature_key; otherwise you get placeholder features that are all zeros, with shape [N, 1]. Edge attributes are not copied.

python
import networkx as nx

G = nx.karate_club_graph()
placeholder = Graph.from_networkx(G)
print(placeholder.node_features.shape, placeholder.node_features.abs().sum())  # [34, 1], 0

for node in G.nodes:
    G.nodes[node]["feat"] = [float(G.degree[node]), 1.0]
g_nx = Graph.from_networkx(G, node_feature_key="feat")
print(g_nx.node_features.shape)   # torch.Size([34, 2])

Q: Can I use a PyG dataset with TGraphX?

Yes, with torch_geometric installed. tgx.load_dataset("cora") wraps the PyG dataset and converts each item, but the converter does not carry over the train, validation and test masks. To keep the official split, load with PyG and build the Graph yourself:

python
from torch_geometric.datasets import Planetoid
from tgraphx import Graph

data = Planetoid(root="data/Planetoid", name="Cora")[0]
cora = Graph(
    node_features=data.x,
    edge_index=data.edge_index,
    node_labels=data.y,
    train_mask=data.train_mask,
    val_mask=data.val_mask,
    test_mask=data.test_mask,
)

Q: Can I save and load a TGraphX graph?

python
g.save("my_graph.tgx")
g_loaded = Graph.load("my_graph.tgx")
print(g_loaded.num_nodes, g_loaded.num_edges)

.tgx is TGraphX's own format and keeps tensor-valued features, labels and masks. Loading unpickles the file, so load only files you trust. With tgraphx.io.write_graphml, node features are omitted by default and features of rank above 2 cannot be written.

Q: Can TGraphX graphs be moved to GPU?

python
from tgraphx.performance import recommended_device

device = recommended_device()          # cuda, mps or cpu
g_device = g.clone().to(device)        # Graph.to() works in place, so clone to keep g
model_device = gcn.to(device)
print(model_device(g_device.x, g_device.edge_index).shape)

Common Mistakes

Q: I get edge_index must have dtype torch.long, got torch.int32. What am I doing wrong?

Your edge index is not a 64-bit integer tensor. Cast it with edge_index = edge_index.long(). This is raised as a TypeError.

Q: I get edge_index must have shape [2, E], got (3, 2).

Your edges are stored one per row. Transpose them: edge_index = edge_index.t().contiguous().

Q: I get edge_index contains out-of-range indices for 50 nodes (found min=0, max=95; valid range [0, 49]). Why?

Some indices point past the last node. A typical cause is slicing node features into a subgraph while edge_index still uses the original node IDs. induced_subgraph slices features, labels and edges together and renumbers the edges:

python
keep = torch.arange(0, 50, 2)                 # keep every second node
sub = tgx.induced_subgraph(g, keep)
print(sub.num_nodes, int(sub.edge_index.max()) < sub.num_nodes)
print(sub.metadata["sampling"]["original_node_ids"][:5])  # mapping back to the full graph

k_hop_subgraph and edge_subgraph are also available.

Q: Training loss decreases but validation accuracy is stuck. What should I check?

  1. Train and validation masks do not overlap: tgx.check_leakage(train_mask=..., val_mask=..., test_mask=...). Use keyword arguments.
  2. Only training nodes reach the loss. tgraphx.fit ignores node masks, and NeighborLoader needs mask=.
  3. With NeighborLoader, the loss uses batch.seed_logits(logits), not all of logits.
  4. Validation runs in model.eval() mode under torch.no_grad().
python
overlap_report = tgx.check_leakage(train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)
print(overlap_report["ok"], overlap_report["counts"])

Q: My model gives identical outputs for many nodes. Why?

Check for:

  1. Nodes with no incoming edges in a layer without a self term (see the table above)
  2. Identical or all-zero input features, for example the placeholders from from_networkx
  3. Over-smoothing from too many message-passing layers
  4. A normalisation or activation step that zeroes the signal
  5. A learning rate high enough to saturate the network

Questions About TGraphX vs Other Libraries

Q: Should I use TGraphX or PyTorch Geometric for my project?

If your node features are ordinary vectors and you want a large, established ecosystem of layers, datasets and examples, use PyG. If your node features are image-like or volumetric and you want layers that keep that structure during message passing, that is what TGraphX is designed for. Both libraries cover more than basic message passing (sampling and knowledge-graph embeddings, for instance), so compare the specific features you need. See TGraphX vs PyTorch Geometric.

For the DGL side of the same question, see TGraphX and DGL for tensor-valued workflows.

Q: Is TGraphX production-ready?

The package as a whole is published as Beta. Individual names carry their own labels: for example Graph, GraphBatch and the main tensor layers report stable, NeighborLoader reports beta, and HeteroGraph, TemporalGraphSequence, generate_graph and train_graph_rl report experimental. Check what you depend on and pin the version.

python
for name in ("Graph", "NeighborLoader", "HeteroGraph", "graph_summary"):
    print(name, tgx.api_status(name))

api_status covers a curated list of names and raises KeyError for others.

Q: Where can I find TGraphX's API documentation?

  • The learn section on this website
  • The compare section for framework comparisons
  • The README and docs/ folder in the GitHub repository (they are not part of the PyPI wheel)
  • help(...) on any class or function in your installation
  • python -m tgraphx readiness for a summary of installed capabilities

Questions about devices, seeds, batching and maturity are answered in the FAQ for PyTorch users.


Related Articles