TGraphX › Insights › Building a Minimal Article-to-Graph Pipeline for NLP Experiments
← Back to Insights

Building a Minimal Article-to-Graph Pipeline for NLP Experiments

Topic: Vision, multimodal and domain applications

Text, unlike an image, has no natural grid. A document is a sequence of sentences, but sentences also relate to each other in ways that go beyond order: they repeat terms, return to a topic, or support the same claim. A graph lets you state those relations explicitly.

This tutorial builds a small pipeline from raw text to a TGraphX Graph: split a document into sentences, turn each sentence into a vector, connect the sentences with window or k-nearest-neighbour (kNN) edges, run one GNN forward pass, and batch several documents. Examples tested with TGraphX 1.5.1 on CPU.

Why Build a Text Graph?

A text graph can be worth trying when:

  • relations between distant parts of a document matter for the task
  • sentence representations need to be combined into one document representation
  • you work on tasks such as claim verification, document classification, or information extraction

It is probably not worth it when a sequence model (a transformer) already handles the task, or when your edges add nothing beyond what the model reads from the text. This is a design decision to test against a baseline, not a claim that graph methods beat transformers.

Step 1: Text to Nodes

First decide what a node represents:

Node type Granularity Example use
Word tokens Fine-grained Syntactic analysis, NER
Sentences Medium Document classification, QA
Paragraphs Coarse Long documents
Named entities Task-dependent Knowledge graph construction

Here, sentences are nodes. TGraphX does not include a sentence splitter or a text encoder, so the example uses two small stand-ins that run without any downloads.

python
import re
import zlib

import torch
import torch.nn.functional as F

document = (
    "Graph neural networks learn from graph structure. "
    "A graph has nodes and edges. "
    "Message passing updates each node from its neighbors. "
    "Each node starts with a feature vector. "
    "Reproducible experiments record seeds and configurations."
)

def split_sentences(text):
    """Naive splitter. Use spaCy, NLTK, or similar for real text."""
    return [s for s in re.split(r"(?<=[.!?])\s+", text.strip()) if s]

def embed(sentences, dim=64):
    """Hashed bag of words: a lexical stand-in, not a semantic encoder."""
    out = torch.zeros(len(sentences), dim)
    for row, sentence in enumerate(sentences):
        for word in re.findall(r"[a-z]+", sentence.lower()):
            out[row, zlib.crc32(word.encode()) % dim] += 1.0
    return F.normalize(out, dim=1)

encoder_name = "hashed-bow-64"              # recorded with the graph later
sentences = split_sentences(document)
node_features = embed(sentences)            # [N, 64]
N = len(sentences)
print(N, tuple(node_features.shape))        # 5 (5, 64)

For real experiments, redefine embed so that it calls a sentence encoder, and run that block before the later steps. Everything below, including the batching code, then uses the new vectors. With the sentence-transformers package it looks like this. This block was not run for this article (it needs sentence-transformers and a model download).

python
from sentence_transformers import SentenceTransformer

encoder = SentenceTransformer("all-MiniLM-L6-v2")
encoder_name = "all-MiniLM-L6-v2"

def embed(sentences):                        # replaces the hashed version
    out = encoder.encode(sentences, convert_to_tensor=True,
                         normalize_embeddings=True)
    return out.cpu().clone()                 # [N, 384]

node_features = embed(sentences)

Step 2: Sentence-Window Edges

A window of size w connects each sentence to the w sentences that follow it. This captures local flow and needs no embeddings.

python
def build_window_edges(n, window=2):
    src, dst = [], []
    for i in range(n):
        for j in range(i + 1, min(i + window + 1, n)):
            src += [i, j]       # both directions
            dst += [j, i]
    return torch.tensor([src, dst], dtype=torch.long)   # [2, E]

edge_index_window = build_window_edges(N, window=2)
print(tuple(edge_index_window.shape))        # (2, 14)

Step 3: kNN Similarity Edges

kNN edges connect sentences whose vectors are close, wherever they are in the document. TGraphX provides build_knn_graph. Three details matter:

  • It ranks neighbours by Euclidean distance. For L2-normalised vectors, as here, that gives the same ranking as cosine similarity.
  • By default it symmetrises the edges and adds a self-loop to every node.
  • With directed=True, an edge points from node i to its neighbour, so in message passing node i sends to its neighbours. Flip the edge index if each node should receive from its own nearest neighbours.
python
from tgraphx.graph_builders import build_knn_graph

# Symmetric, without self-loops (the GCN layer below adds its own)
edge_index_knn = build_knn_graph(node_features, k=2, self_loops=False)

# Alternative: each sentence receives from exactly its 2 nearest sentences
edge_index_in = build_knn_graph(node_features, k=2, directed=True,
                                self_loops=False).flip(0)

print(tuple(edge_index_knn.shape))
print(torch.bincount(edge_index_in[1], minlength=N).tolist())   # [2, 2, 2, 2, 2]

After symmetrisation a node can have more than k neighbours, because other nodes may select it. To combine order and similarity, concatenate the two edge sets and drop duplicates:

python
edge_index_both = torch.unique(
    torch.cat([edge_index_window, edge_index_knn], dim=1), dim=1
)
print(tuple(edge_index_both.shape))

Step 4: Build the Graph and Run a Forward Pass

Sentence vectors are ordinary [N, D] features, so use a vector layer such as GCNConv or GATv2Conv. TensorGraphSAGELayer, TensorGATLayer and TensorGINLayer expect [N, C, H, W] or volumetric features and reject this input. Take the layer's input width from the features, so that it follows the encoder.

python
import tgraphx as tgx
from tgraphx import Graph

g = Graph(node_features=node_features, edge_index=edge_index_knn)

torch.manual_seed(0)
conv = tgx.GCNConv(g.node_features.shape[1], 32)         # width of the encoder
h = torch.relu(conv(g.node_features, g.edge_index))      # [N, 32]
print(g.num_nodes, g.num_edges, tuple(h.shape))

GCNConv adds a self-loop to every node even if the edge index already contains one. If you keep the self-loops from build_knn_graph, each node counts itself twice, which is why Step 3 passed self_loops=False.

The Pipeline at a Glance

  raw text
     |  split_sentences          (stand-in: use a real splitter)
  [s0, s1, s2, s3, s4]
     |  embed                    (stand-in: use a real encoder)
  node_features [N=5, d]     (d = 64 for the stand-in)
     |  build_window_edges  and/or  build_knn_graph
  edge_index [2, E]
     |  Graph(node_features, edge_index)   shape and index checks
     |  GCNConv                            node vectors [N, 32]
     |  global_mean_pool                   one vector per document

Batching Multiple Documents

Real corpora contain very short documents. build_knn_graph requires k < N and raises otherwise, so limit k and give a one-sentence document an empty edge index.

python
from tgraphx import GraphDataLoader, GraphDataset, global_mean_pool

def document_to_graph(text, label, k=2):
    sents = split_sentences(text)
    x = embed(sents)
    k = min(k, len(sents) - 1)
    if k > 0:
        edge_index = build_knn_graph(x, k=k, self_loops=False)
    else:
        edge_index = torch.empty(2, 0, dtype=torch.long)
    return Graph(node_features=x, edge_index=edge_index,
                 graph_label=torch.tensor(label))

corpus = [
    (document, 0),
    ("Bake the bread for an hour. Let the bread cool before slicing.", 1),
    ("One sentence only.", 1),
]
graphs = [document_to_graph(text, label) for text, label in corpus]
loader = GraphDataLoader(GraphDataset(graphs), batch_size=2)

classifier = torch.nn.Linear(32, 2)
for batch in loader:
    h = torch.relu(conv(batch.node_features, batch.edge_index))
    logits = classifier(global_mean_pool(h, batch.batch))   # [num_graphs, 2]
    loss = F.cross_entropy(logits, batch.graph_labels)
    print(batch.num_graphs, tuple(logits.shape), round(loss.item(), 3))

The loop shows the data flow only. To train it, optimise the parameters of both conv and classifier, and split by document so that no sentence from a test document appears in training.

Recording What Was Built

When the edge method or encoder changes between experiments, save what each graph looked like. Passing a Graph to write_graph_stats records only num_nodes and num_edges; pass a dictionary to record more. Each call overwrites the file, so use a different path per graph or experiment.

python
from tgraphx import write_graph_stats

write_graph_stats(
    {"num_nodes": g.num_nodes, "num_edges": g.num_edges,
     "feature_shape": list(g.feature_shape), "edges": "knn", "k": 2,
     "encoder": encoder_name},
    path="logs/text_graph_stats.json",
)

To take this further with dependency and entity graphs, see text-to-graph pipelines with a GNN classifier.

Limitations and Honest Caveats

Node features decide a lot. If the encoder produces uninformative vectors, message passing over them will not repair that. The hashed bag of words used here only measures shared words.

Window size and k are hyperparameters. There is no universally correct value; tune them on validation data.

kNN is not semantic understanding. It connects by vector distance. The edges are only as meaningful as the embedding space.

Order can be lost. These edges carry no direction or position. If sentence order matters, add position features or separate forward and backward relations.

Compare against a baseline. A text graph is a hypothesis. Check it against the same encoder with no edges, and against a sequence model.