TGraphX › Insights › Drawing Tensor-Shape Diagrams for GNN Articles: ASCII, SVG, and details/summary
← Back to Insights

Drawing Tensor-Shape Diagrams for GNN Articles: ASCII, SVG, and details/summary

Topic: APIs, tooling and research-engineering workflow

"A tensor of shape [N, C, H, W] aggregated over neighbours" is hard to hold in your head as prose. A small diagram makes the axes and their changes visible.

This tutorial shows how to draw tensor shapes without JavaScript libraries, using ASCII art, shape-annotated code, a trace generated from the model, inline SVG, and HTML details/summary for collapsing long diagrams. For the notation behind the axis names, see tensor shape semantics. Examples tested with TGraphX 1.5.1 on CPU.

What a shape diagram has to show

  1. Shapes: how many axes each tensor has and what each one means.
  2. Which axis is shared: N for node tensors, E for edge tensors.
  3. Data flow: how shapes change from layer to layer.

Graph topology is a separate problem. Mixing it into a shape diagram usually makes both harder to read.

Approach 1: ASCII diagrams

ASCII art needs no tooling and works anywhere text is shown in a monospace font, such as a code block, a terminal or a docstring. It breaks in proportional fonts, so do not paste it into rich-text email.

Node features [N, C, H, W]:

  node_features   shape [N=6, C=3, H=16, W=16]

  ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐
  │  n0  │ │  n1  │ │  n2  │ │  n3  │ │  n4  │ │  n5  │
  │ 3×16 │ │ 3×16 │ │ 3×16 │ │ 3×16 │ │ 3×16 │ │ 3×16 │
  │  ×16 │ │  ×16 │ │  ×16 │ │  ×16 │ │  ×16 │ │  ×16 │
  └──────┘ └──────┘ └──────┘ └──────┘ └──────┘ └──────┘

Edge index [2, E]:

  edge_index   shape [2, E=8]

                e0  e1  e2  e3  e4  e5  e6  e7
  row 0 (src)    0   0   1   2   2   3   4   5
  row 1 (dst)    1   2   3   3   4   5   5   0

Messages arriving at one node:

  Messages into n3 (edges e2 and e3 above)

  x[n1]  [C,H,W] ──e2──┐
                       ├──► aggregate ──► out[n3]  [C',H,W]
  x[n2]  [C,H,W] ──e3──┘

C' is the output channel count of the layer. H and W are unchanged here, which is how TensorGraphSAGELayer, TensorGATLayer and TensorGINLayer behave; a layer with a different message function may change them.

Approach 2: Shape-annotated code

The simplest diagram is code with shape comments. It is searchable and copyable, and an assertion keeps the comments from drifting:

python
import torch
import torch.nn as nn
import tgraphx as tgx
from tgraphx import Graph, GraphBatch

N, E, C, H, W = 32, 80, 3, 16, 16

node_features = torch.randn(N, C, H, W)         # [32, 3, 16, 16]
edge_index    = torch.randint(0, N, (2, E))     # [2, 80]
edge_features = torch.randn(E, 64)              # [80, 64]
node_labels   = torch.randint(0, 5, (N,))       # [32]

g = Graph(
    node_features=node_features,                # [N, C, H, W]
    edge_index=edge_index,                      # [2, E]
    edge_features=edge_features,                # [E, d_e]
    node_labels=node_labels,                    # [N]
)
assert g.feature_shape == (C, H, W) and g.edge_feature_shape == (64,)

Approach 3: Generate the trace from the model

Hand-written shape diagrams go stale when a layer changes. Forward hooks record what each module really returns, so the diagram can be rebuilt from the code. Hooks only see modules, so the spatial average is written as one:

python
class SpatialMean(nn.Module):
    def forward(self, h):
        return h.mean(dim=(-2, -1))             # average over H and W


class TensorNodeClassifier(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = tgx.TensorGraphSAGELayer(3, 16)
        self.conv2 = tgx.TensorGraphSAGELayer(16, 32)
        self.pool = SpatialMean()
        self.head = nn.Linear(32, 5)

    def forward(self, x, edge_index):
        h = self.conv1(x, edge_index)
        h = self.conv2(h, edge_index)
        return self.head(self.pool(h))


def shape_trace(model, x, edge_index):
    rows = [("input", tuple(x.shape))]
    hooks = [
        module.register_forward_hook(
            lambda mod, args, out, name=name: rows.append((name, tuple(out.shape))))
        for name, module in model.named_children()
    ]
    try:
        with torch.no_grad():
            model.eval()(x, edge_index)
    finally:
        for hook in hooks:
            hook.remove()
    return rows


rows = shape_trace(TensorNodeClassifier(), node_features, edge_index)
for name, shape in rows:
    print(f"{name:<6} {list(shape)}")

assert [shape for _, shape in rows] == [
    (32, 3, 16, 16), (32, 16, 16, 16), (32, 32, 16, 16), (32, 32), (32, 5)]

The printed trace is already a usable diagram:

input  [32, 3, 16, 16]
conv1  [32, 16, 16, 16]
conv2  [32, 32, 16, 16]
pool   [32, 32]
head   [32, 5]

Rows appear in the order the modules are called. The sketch assumes each direct child is called once and returns a single tensor; operations written as plain functions, outside any module, do not appear.

Approach 4: Inline SVG

Where raw HTML is allowed, inline SVG gives precise control with no external dependencies. This hand-written example draws the node tensor:

html
<figure>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 130" width="500" height="130"
     style="max-width:100%;height:auto" role="img" aria-labelledby="nf-title">
  <title id="nf-title">node_features of shape N by C by H by W: N node tensors</title>
  <rect width="500" height="130" fill="#f8f9fa" rx="8"/>
  <text x="10" y="22" font-family="monospace" font-size="13" fill="#333">node_features  shape: [N, C, H, W]</text>
  <rect x="10"  y="35" width="60" height="60" fill="#d0e8ff" stroke="#4a90e2" rx="4"/>
  <text x="40"  y="58" text-anchor="middle" font-size="11" fill="#333">n0</text>
  <text x="40"  y="74" text-anchor="middle" font-size="10" fill="#333">[C,H,W]</text>
  <rect x="80"  y="35" width="60" height="60" fill="#d0e8ff" stroke="#4a90e2" rx="4"/>
  <text x="110" y="58" text-anchor="middle" font-size="11" fill="#333">n1</text>
  <text x="110" y="74" text-anchor="middle" font-size="10" fill="#333">[C,H,W]</text>
  <rect x="150" y="35" width="60" height="60" fill="#d0e8ff" stroke="#4a90e2" rx="4"/>
  <text x="180" y="58" text-anchor="middle" font-size="11" fill="#333">n2</text>
  <text x="180" y="74" text-anchor="middle" font-size="10" fill="#333">[C,H,W]</text>
  <text x="230" y="68" font-size="20" fill="#666">···</text>
  <rect x="270" y="35" width="60" height="60" fill="#d0e8ff" stroke="#4a90e2" rx="4"/>
  <text x="300" y="58" text-anchor="middle" font-size="11" fill="#333">n(N-1)</text>
  <text x="300" y="74" text-anchor="middle" font-size="10" fill="#333">[C,H,W]</text>
  <line x1="10" y1="106" x2="330" y2="106" stroke="#999" stroke-width="1"/>
  <text x="170" y="122" text-anchor="middle" font-size="11" fill="#333">← N nodes →</text>
</svg>
</figure>

The viewBox lets the drawing shrink on narrow screens. The trace from the previous section can be turned into SVG as well, and tested like any other build output:

python
import xml.etree.ElementTree as ET
from html import escape


def trace_to_svg(rows, uid, box_w=320, box_h=36, gap=18):
    width, height = box_w + 2, len(rows) * (box_h + gap) - gap + 2
    desc = "; ".join(f"{name} {list(shape)}" for name, shape in rows)
    out = [
        f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {height}" '
        f'width="{width}" height="{height}" style="max-width:100%;height:auto" '
        f'role="img" aria-labelledby="{uid}-title {uid}-desc">',
        f'<title id="{uid}-title">Tensor shapes through the model</title>',
        f'<desc id="{uid}-desc">{escape(desc)}</desc>',
        f'<rect width="{width}" height="{height}" fill="#fff"/>',
    ]
    for i, (name, shape) in enumerate(rows):
        top = 1 + i * (box_h + gap)
        if i:
            out.append(f'<text x="{width // 2}" y="{top - 4}" text-anchor="middle" '
                       f'font-size="14" fill="#555">↓</text>')
        out.append(f'<rect x="1" y="{top}" width="{box_w}" height="{box_h}" rx="6" '
                   f'fill="#e8f4fd" stroke="#1f5fa8"/>')
        out.append(f'<text x="{width // 2}" y="{top + 23}" text-anchor="middle" '
                   f'font-family="monospace" font-size="13" fill="#111">'
                   f'{escape(name)}  {list(shape)}</text>')
    out.append("</svg>")
    return "\n".join(out)


svg = trace_to_svg(rows, uid="trace")
ns = {"svg": "http://www.w3.org/2000/svg"}
root = ET.fromstring(svg)                       # raises if the markup is malformed
assert root.get("role") == "img" and root.find("svg:title", ns) is not None
assert len(root.findall("svg:rect", ns)) == len(rows) + 1     # boxes plus background

Support for inline SVG varies. GitHub strips it from Markdown, so commit an .svg file and reference it as an image there. Hugo's default renderer omits raw HTML unless you enable it. Some sites, including this one, allow only a small set of tags in article text, which is why the SVG above is shown as source. Static SVG graph diagrams covers the Markdown and platform pitfalls in detail.

Collapsible diagrams with details/summary

Long diagrams interrupt the reading flow. details and summary make them opt-in with plain HTML:

html
<details>
<summary>What the block contains</summary>
<pre>
the diagram
</pre>
</details>

The block below is live. It shows how shapes combine in a GraphBatch. In each row, the bracketed numbers are the node_features shape, E is the number of edges (columns of edge_index) and off is the offset added to that graph's node ids in the batch. The last lines show batch.batch, which records the graph each node came from.

GraphBatch([g1, g2, g3]): shapes and node id offsets
g1    [4,3,16,16]  E=5  off 0
g2    [3,3,16,16]  E=4  off 4
g3    [5,3,16,16]  E=6  off 7
batch [12,3,16,16] E=15

batch.batch [12]:
[0,0,0,0, 1,1,1, 2,2,2,2,2]

Check the numbers before you publish them:

python
def toy(num_nodes, num_edges):
    return Graph(node_features=torch.zeros(num_nodes, 3, 16, 16),
                 edge_index=torch.randint(0, num_nodes, (2, num_edges)))


g1, g2, g3 = toy(4, 5), toy(3, 4), toy(5, 6)
batch = GraphBatch([g1, g2, g3])

assert batch.node_features.shape == (12, 3, 16, 16)
assert batch.edge_index.shape == (2, 15)
assert batch.batch.tolist() == [0] * 4 + [1] * 3 + [2] * 5
assert torch.equal(batch.edge_index[:, 5:9], g2.edge_index + 4)
assert torch.equal(batch.edge_index[:, 9:], g3.edge_index + 7)

Accessibility

For SVG:

  • A diagram that carries information gets role="img" and an accessible name, from a <title> referenced by aria-labelledby or from aria-label. Add a <desc> when the content matters.
  • A purely decorative graphic is hidden from assistive technology with aria-hidden="true".
  • Keep labels as real <text> elements, not paths or images of text, and do not let colour be the only carrier of meaning.

For ASCII diagrams:

  • Use a fenced code block or <pre> so that columns stay aligned.
  • Put a one-sentence summary before the diagram; a screen reader may read box-drawing characters one by one.

For details/summary:

  • The summary text should say what is inside, not only "expand".
  • Avoid nesting them.
  • Closed content is hidden, so open the block before printing or exporting a page.

For topology rather than shapes, see static node-edge diagrams.

When to use each approach

Situation Approach
README or docstring ASCII in a code block
Shapes that change with the code Trace generated by forward hooks
Quick reference next to code Shape-annotated code
Your own HTML site that passes raw HTML Inline SVG
Long appendix-style layout details/summary around pre
Print or PDF Visible (not collapsed) text or figures; convert SVG to PDF for LaTeX

A complete example: explaining Graph construction

The pieces combine well: code first, then an optional detail for the edge case.

python
feats = torch.randn(6, 8)                       # [N, d]
edges = torch.tensor([[0, 0, 1, 2, 2, 3, 4, 5],
                      [1, 2, 3, 3, 4, 5, 5, 0]])  # [2, E]
e_feats = torch.randn(8, 4)                     # [E, d_e]
labels = torch.randint(0, 3, (6,))              # [N]

example = Graph(node_features=feats, edge_index=edges,
                edge_features=e_feats, node_labels=labels)

try:
    Graph(node_features=feats, edge_index=edges, edge_features=e_feats[:5])
except ValueError as err:
    print(err)       # edge_features has 5 entries but edge_index has 8 edges
else:
    raise AssertionError("mismatched edge features should be rejected")
What happens if the edge features do not match the edges?

If edge_features.shape[0] differs from edge_index.shape[1], the Graph constructor raises a ValueError before any forward pass runs. It cannot detect features that have the right length but the wrong order.

This pattern keeps the main text short while giving depth to readers who want it.