.tgx Files in TGraphX: What They Store and What They Do Not
A headline number is only text. What makes a graph experiment checkable is the set of files that lets someone load your graph, your model and your configuration. The graph itself is the awkward part: common interchange formats such as GraphML, GEXF or edge lists are built around flat attributes such as numbers and strings, so a rank-4 node feature tensor (one image patch per node) needs a custom encoding.
TGraphX has a native format for this, .tgx. This note documents what it holds as of TGraphX 1.5.1, what it leaves out, and how to package a run around it. The Python blocks run in order. Examples tested with TGraphX 1.5.1.
What a .tgx file is
A .tgx file is one torch.save bundle holding either a Graph or a KnowledgeGraph.
import torch
import tgraphx as tgx
torch.manual_seed(0)
node_features = torch.randn(6, 3, 8, 8)
edge_index = torch.tensor([[0, 1, 2, 3, 4], [1, 2, 3, 4, 5]])
labels = torch.tensor([0, 1, 0, 1, 0, 1])
g = tgx.Graph(x=node_features, edge_index=edge_index, labels=labels,
edge_features=torch.randn(5, 2, 2), graph_features=torch.ones(4),
train_mask=torch.arange(6) < 4, metadata={"patch_size": 8})
g.save("my_graph.tgx")
# Look inside a file you have just written (see the loading warning below).
bundle = torch.load("my_graph.tgx", weights_only=True)
print(list(bundle))
print(bundle["tgraphx_format"], bundle["type"])
print(list(bundle["payload"]))
Output:
['tgraphx_format', 'tgraphx_version', 'type', 'payload']
tgx-v1 Graph
['node_features', 'edge_index', 'edge_features', 'node_labels', 'graph_features', 'train_mask', 'metadata']
Apart from metadata, which a Graph bundle always contains (possibly empty), only fields that are set appear in the payload. tgraphx_format is the format tag, and tgraphx_version records which release wrote the file. The layout is internal: read files with the loader, not by indexing into the dictionary.
back = tgx.Graph.load("my_graph.tgx")
assert back.feature_shape == (3, 8, 8) and back.node_features.dtype == torch.float32
assert torch.equal(back.edge_features, g.edge_features)
assert torch.equal(back.train_mask, g.train_mask)
assert back.metadata["patch_size"] == 8
half = tgx.Graph(node_features=node_features.half())
half.save("half.tgx")
assert tgx.Graph.load("half.tgx").node_features.dtype == torch.float16
Loading means unpickling: trusted files only
The loader calls torch.load(..., weights_only=False) because metadata can hold arbitrary Python objects. A crafted file can therefore execute code when loaded. Open only .tgx files you trust, and be especially careful with run directories downloaded from elsewhere. tgx.load(path, trust_source=False) refuses to load at all; the default is True. The serialization how-to shows a restricted way to inspect a file and the PyTorch versions with known flaws in it.
What a Graph bundle keeps and drops
| Kept | Dropped or unsupported |
|---|---|
node_features of any rank, with dtype |
other attributes you attach to the object |
edge_index, edge_weight, edge_features |
autograd history and requires_grad of the tensors above |
node_labels, edge_labels |
device placement (tensors are moved to CPU) |
graph_label, graph_features |
HeteroGraph, TemporalGraphSequence, TemporalGraphBatch (saving raises an error) |
| train, validation and test masks | GraphBatch (it saves, then fails to load) |
the metadata dict |
weights = torch.randn(4, 5, requires_grad=True)
h = tgx.Graph(node_features=weights)
h.custom_note = "not part of the format"
h.save("h.tgx")
h2 = tgx.Graph.load("h.tgx")
assert not h2.node_features.requires_grad
assert not hasattr(h2, "custom_note")
Tensors stored inside metadata are written as they are, not moved or detached, so convert them yourself if that matters.
Knowledge graphs
KnowledgeGraph has no save method of its own. Use tgx.save and tgx.load:
kg = tgx.KnowledgeGraph.from_triples(
[("img1", "depicts", "cat"), ("img2", "depicts", "dog")],
entity_features={"vector": torch.randn(4, 8)},
)
tgx.save(kg, "my_kg.tgx")
kg2 = tgx.load("my_kg.tgx")
assert torch.equal(kg2.triples, kg.triples)
assert torch.equal(kg2.entity_features["vector"], kg.entity_features["vector"])
assert kg.entity_to_id is not None and kg2.entity_to_id is None # names are lost
Stored: the triples, entity and relation counts, entity_features, relation_features, triple_features and metadata. Not stored: the entity_to_id and relation_to_id vocabularies, edge_weight, confidence, entity_types, entity_feature_masks and entity_type_to_id. Save those separately. Learned embeddings belong to the KG model, not the graph, so save the model's state_dict() too.
Temporal knowledge graphs lose their times without any message. A TemporalKnowledgeGraph is a KnowledgeGraph subclass, so it saves without error but reloads as a plain KnowledgeGraph without timestamp. Store kg.timestamp separately.
from tgraphx.kg import TemporalKnowledgeGraph
tkg = TemporalKnowledgeGraph(kg.triples, timestamp=torch.tensor([2019.0, 2021.0]))
tgx.save(tkg, "my_tkg.tgx") # no error
torch.save(tkg.timestamp, "my_tkg_times.pt") # keep the times yourself
back_kg = tgx.load("my_tkg.tgx")
assert type(back_kg) is tgx.KnowledgeGraph and not hasattr(back_kg, "timestamp")
What goes next to the graph
A bundle is graph data only. It does not contain the trained model, the hyperparameters, the training history or a description of the machine. A run directory that other people can use typically looks like this:
runs/exp_001/
├── graph.tgx graph.save(...)
├── model.pt torch.save(model.state_dict(), ...)
├── run_metadata.json write_run_metadata(path, ...)
├── metrics_summary.json write_metrics_summary(path, ...)
└── benchmark_summary.json write_benchmark_results(path, ...)
The three JSON names are the ones tgx.audit_run_dir looks for. Nothing creates this layout for you. The experiments Runner writes a different set (run_metadata.json, experiment_config.json, metrics.csv, experiment_summary.json and optional checkpoints/), with no graph.tgx, no model.pt and no reproducibility report, and the audit reports its directory as incomplete.
Practical workflow
For each experiment:
- Construct the graph and call
g.validate(). - Save it:
g.save(run_dir / "graph.tgx"). - Train, then save the weights:
torch.save(model.state_dict(), run_dir / "model.pt"). - Write the configuration, environment and metrics with the
write_*functions. - Audit the directory with
tgx.audit_run_dir(run_dir).
See also the run-directory pattern built around these artifacts.
A runnable example
import hashlib
import json
from pathlib import Path
import torch.nn.functional as F
from tgraphx.estimators import node_train_val_test_split
run_dir = Path("runs/exp_001")
run_dir.mkdir(parents=True, exist_ok=True)
torch.manual_seed(42)
x = torch.randn(40, 3, 8, 8) # synthetic patch features
y = torch.arange(40) % 2
x += 0.5 * y.view(-1, 1, 1, 1)
ei = torch.randint(0, 40, (2, 120))
train, val, test = node_train_val_test_split(40, 0.6, 0.2, 0.2, seed=42)
graph = tgx.Graph(node_features=x, edge_index=ei, node_labels=y,
train_mask=train, val_mask=val, test_mask=test)
graph.save(run_dir / "graph.tgx")
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
self.conv = tgx.TensorGraphSAGELayer(3, 8)
self.head = torch.nn.Linear(8, 2)
def forward(self, x, edge_index):
return self.head(torch.relu(self.conv(x, edge_index)).mean(dim=(2, 3)))
model = Model()
optimizer = torch.optim.Adam(model.parameters(), lr=0.02)
for _ in range(20): # fixed budget, no selection
optimizer.zero_grad()
loss = F.cross_entropy(model(x, ei)[train], y[train])
loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
test_accuracy = (model(x, ei).argmax(1)[test] == y[test]).float().mean().item()
torch.save(model.state_dict(), run_dir / "model.pt")
digest = hashlib.sha256((run_dir / "graph.tgx").read_bytes()).hexdigest()
tgx.write_run_metadata(run_dir / "run_metadata.json", seed=42,
tgraphx_version=tgx.__version__, torch_version=torch.__version__,
graph_sha256=digest, epochs=20, lr=0.02)
tgx.write_metrics_summary(run_dir / "metrics_summary.json", test_accuracy=test_accuracy)
tgx.write_benchmark_results(run_dir / "benchmark_summary.json",
benchmark="synthetic illustration", test_accuracy=test_accuracy)
audit = tgx.audit_run_dir(run_dir)
assert audit["ok"], audit["issues"]
restored = Model()
restored.load_state_dict(torch.load(run_dir / "model.pt", weights_only=True))
restored.eval()
saved = tgx.Graph.load(run_dir / "graph.tgx")
with torch.no_grad():
again = restored(saved.node_features, saved.edge_index).argmax(1)
again_accuracy = (again[saved.test_mask] == saved.node_labels[saved.test_mask]).float().mean().item()
recorded = json.loads((run_dir / "metrics_summary.json").read_text())["test_accuracy"]
assert abs(again_accuracy - recorded) < 1e-6
The last lines are the point of the exercise: the reported number can be recomputed from the directory plus the model class. A passing audit only means the expected files are there and well formed. Rerunning training and getting the same weights additionally depends on code, library versions and hardware.
Compatibility and interoperability
- Versions. The loader accepts the
tgx-v1tag and rejects anything else. The CHANGELOG for 1.4.2 addededge_labelsandgraph_featuresand states that older bundles still load. Do not assume future formats will be compatible; keep the TGraphX and PyTorch versions with the run. - PyTorch Geometric.
.tgxis read by TGraphX. To hand a graph to a PyG user, convert withtgraphx.interop.to_pyg_data;from_pyg_dataconverts back. In 1.5.1 the masks,graph_features,edge_labelsandmetadatado not survive that round trip, and neither doesgraph_labelwhen the graph also has node labels (without node labels it travels asdata.y). A PyG user will not finddata.train_mask: the masks sit underdata.metadata["masks"]. Assign what is needed by hand. On the way back, set it on theGraphagain:from_pyg_datareads onlyx,edge_index,edge_weight,edge_attrandy. Details are in interoperability. - GraphML. Useful for sharing topology with other tools, but by default it does not write node features, and
read_graphmlis only suited to files thatwrite_graphmlwrote (see the FAQ). - Size. Saving a slice of a larger tensor stores the whole underlying storage; call
.clone()first.
When .tgx is overkill
For flat-vector features and simple structure, an edge list plus a feature file, or GraphML for topology, may be easier for others to consume. .tgx earns its place when features have rank 3 or more, when dtypes must survive, or when you want one file that reloads into TGraphX with masks and labels.
FAQ
Q: Is the format documented for third-party readers?
A: The layout is described in the docstring of tgraphx/ux/serialization.py, and the code is the reference (the docstring places the version under metadata; the file stores it at the top level). Prefer tgx.load over parsing the bundle.
Q: How does .tgx compare to saving a PyG Data object?
A: A PyG Data object is normally persisted with torch.save, and its x may also be a tensor of any rank. .tgx uses the same serialization with a fixed dictionary layout for TGraphX classes.
Q: Can I compress .tgx files?
A: You can gzip them for storage, but the loader does not decompress, so unpack before loading.
Q: How do I convert GraphML to .tgx?
A: It depends on what wrote the file. For a file written by tgraphx.io.write_graphml, read it with tgraphx.io.read_graphml(path) and call .save("graph.tgx") on the result. Node features are zeros unless the file was written with include_tensor_features=True.
Do not use read_graphml for GraphML from other tools. In 1.5.1 it matches data entries by the key ids that write_graphml uses, not by attr.name, and it adds no reverse edges for an undirected file. A file written by NetworkX with its default settings therefore loads without edge weights, node labels or node features, even when the file contains them, and an undirected graph keeps only one direction per edge. No warning is raised. Read such a file with NetworkX and attach what you need:
import networkx as nx
import torch
import tgraphx as tgx
from tgraphx.io import read_graphml
# Stand-in for a file from another tool: undirected, with weights and labels
H = nx.Graph()
H.add_nodes_from([("a", {"y": 0}), ("b", {"y": 1}), ("c", {"y": 0})])
H.add_weighted_edges_from([("a", "b", 0.5), ("b", "c", 2.0)])
nx.write_graphml(H, "other_tool.graphml")
lossy = read_graphml("other_tool.graphml") # no warning
assert lossy.edge_weight is None and lossy.node_labels is None
assert not lossy.is_undirected() # one direction per edge
H = nx.read_graphml("other_tool.graphml")
g = tgx.Graph.from_networkx(H) # both directions, no attributes
w = torch.tensor([d["weight"] for _, _, d in H.edges(data=True)])
g.edge_weight = torch.cat([w, w]) # undirected H; if directed, use w
g.node_labels = torch.tensor([H.nodes[n]["y"] for n in H.nodes])
g.validate()
g.save("graph.tgx")
converted = tgx.Graph.load("graph.tgx")
assert converted.is_undirected() and converted.num_edges == 4
assert converted.edge_weight.tolist() == [0.5, 2.0, 0.5, 2.0]
assert converted.node_labels.tolist() == [0, 1, 0]
Graph.from_networkx adds both directions for an undirected graph, which is why the weights are repeated in the same order. It copies no weights or labels, and without node_feature_key the node_features are zeros of shape [N, 1] until you assign your own tensor, with rows in the order of H.nodes. Node ids are replaced by the indices 0 to N-1.