TGraphX › Insights › Graph Reinforcement Learning as an MDP over Tensor States
← Back to Insights

Graph Reinforcement Learning as an MDP over Tensor States

Topic: Graph mining, generation, optimization and RL

Many graph problems are sequential decision problems: put nodes on the two sides of a cut one at a time, colour them one at a time, grow a graph edit by edit, walk a knowledge graph to answer a query. Each can be written as a Markov decision process (MDP) whose state contains a graph. This note writes that MDP down for Max-Cut, shows which tensors hold the state in the tgraphx.rl subpackage of TGraphX, and trains a small policy against real baselines.

One finding matters before you train anything: with default settings, the built-in graph networks cannot see the part of the state that changes in Max-Cut and several other environments. The fix is a few lines of state encoding, shown below.

The learning agents in this subsystem are labelled Experimental; the random and greedy registry entries are labelled Beta. Examples tested with TGraphX 1.5.1 on CPU. The Python blocks build on each other, so run them in order. For a broader tour, see the introduction to graph RL in TGraphX; for per-algorithm code, the practical guide.

The MDP, with a graph in the state

An MDP is a tuple (S, A, P, R, γ): states, actions, transition dynamics, reward and discount factor. The agent looks for a policy π that maximises the expected return E[ Σ_t γ^t r_t ].

For Max-Cut on an undirected graph G = (V, E) with N nodes, deciding the nodes in index order:

text
state       s_t = (G, c_t, t)     c_t in {unassigned, 0, 1}^N, t = node to decide
action      a_t in {0, 1}         side of node t
transition  c_(t+1)[t] = a_t      deterministic, all other entries unchanged
reward      r_t = cut(c_(t+1)) - cut(c_t)
horizon     T = N

Here cut(c) counts the edges whose two endpoints are both assigned and lie on different sides. The rewards telescope, so with γ = 1 the return equals the final cut size, and maximising return is exactly Max-Cut. With γ < 1 (run_graph_rl defaults to 0.99), early gains weigh more than late ones, so the objective differs slightly from the cut.

The graph alone is not a Markov state. Without the partial assignment c_t and the node index t you cannot tell what an action will earn.

One episode with MaxCutEnv

python
import torch
import torch.nn as nn
import torch.nn.functional as F
import tgraphx as tgx
from tgraphx.rl import MaxCutEnv

def random_graph(n, p, seed):
    """Undirected G(n, p) graph; edge_index lists every edge in both directions."""
    gen = torch.Generator().manual_seed(seed)
    upper = torch.triu(torch.rand(n, n, generator=gen) < p, diagonal=1)
    return (upper | upper.T).nonzero().T

N = 12
edge_index = random_graph(N, 0.4, seed=7)
env = MaxCutEnv(edge_index, num_nodes=N)

obs = env.reset()
print(sorted(obs))
total, done = 0.0, False
while not done:
    action = obs["current_node"] % 2          # any fixed rule: 0, 1, 0, 1, ...
    obs, reward, done, truncated, info = env.step(action)
    total += reward

print("sum of rewards:", total, "final cut:", info["cut_value"])
assert total == info["cut_value"]
text
['action_mask', 'assignment', 'current_node', 'done', 'edge_index', 'node_features', 'step']
sum of rewards: 11.0 final cut: 11

The assignment entry is c_t (with -1 for unassigned) and current_node is t. Three details of the interface:

  • step returns (obs, reward, done, truncated, info). done is also true when an episode is truncated, which differs from Gymnasium's terminated flag.
  • GraphEnvConfig.max_steps defaults to 100. On a graph with more than 100 nodes the episode stops with nodes still unassigned unless you raise it.
  • MaxCutEnv and GraphColoringEnv halve their edge counts, so edge_index must list each undirected edge in both directions. The navigation environments do the opposite: unless config.directed=True they add the reverse edge themselves, so with a symmetric edge_index every neighbour appears twice among the actions.

The environments

Environment One action Reward (defaults)
MaxCutEnv side for the next node increase in cut size
GraphColoringEnv colour for the next node (3 colours by default) minus the number of conflicting edges so far, at every step; +20 for a complete conflict-free colouring
VertexCoverEnv add a node to the cover -1 per node, +0.5 per newly covered edge
GraphNavigationEnv k-th neighbour of the current node +10 at the target, -0.1 otherwise
ShortestPathEnv same shaped with a BFS oracle: 1.0 for an optimal arrival, 0.5 for a longer one; -1/L for a step between two nodes of the optimal path (length L), -0.2 otherwise
KGPathReasoningEnv k-th outgoing edge of the current entity +1 at the tail entity, -0.05 otherwise
GraphGenerationEnv add or remove a node, add an edge, or stop (edge removal fails in 1.5.1, see Action masking) step penalty, optional score and density terms, bonus for stopping with at least 2 nodes

Note that the colouring reward does not favour using fewer colours: the number of colours is fixed. The shortest-path shaping has a trap too: for L < 5, -1/L is below -0.2, so a step along the optimal path that does not yet reach the target is penalised more than a step off it. ContinuousNavigationEnv and ContinuousGraphEditEnv take vector actions instead of integers. In 1.5.1, make_graph_env("kg_reasoning") raises TypeError, so construct KGPathReasoningEnv directly.

Pitfall: the built-in networks do not see the state

The networks behind the built-in agents (GraphPolicyNetwork, GraphQNetwork, GraphDuelingQNetwork, GraphActorCriticNetwork) and GraphValueNetwork read two things: node features of shape [N, F] and edge_index (the edge_in_dim argument is not used). They apply mean-aggregation layers without a self term, mean-pool all nodes into one vector, and output one row of action scores or one value.

In MaxCutEnv, GraphColoringEnv and VertexCoverEnv, node_features defaults to an all-zero [N, 1] tensor. Progress lives in separate keys (assignment, coloring, cover) that these networks never read. The graph_navigation and shortest_path environments built by make_graph_env use all-one features, with current_node again kept in a separate key.

python
from tgraphx.rl import GraphPolicyNetwork, run_graph_rl

net = GraphPolicyNetwork(node_in_dim=1, hidden_dim=16, num_actions=2)
obs0 = env.reset()
obs1, *_ = env.step(1)

print(obs0["assignment"][:4], obs1["assignment"][:4])      # the state changed
with torch.no_grad():
    logits0 = net(obs0["node_features"], obs0["edge_index"])
    logits1 = net(obs1["node_features"], obs1["edge_index"])
assert torch.equal(obs0["node_features"], obs1["node_features"])
assert torch.equal(logits0, logits1)                       # the network cannot tell

result = run_graph_rl(env, algorithm="greedy", episodes=3, seed=0)
print("registry 'greedy' returns:", result.metrics["episode_returns"])

result = run_graph_rl(env, algorithm="reinforce", episodes=300, seed=0)
returns = result.metrics["episode_returns"]
print(edge_index.shape[1] // 2, "edges; mean of last 100 returns:", sum(returns[-100:]) / 100)
text
tensor([-1, -1, -1, -1]) tensor([ 1, -1, -1, -1])
registry 'greedy' returns: [0.0, 0.0, 0.0]
24 edges; mean of last 100 returns: 12.08

Both results follow from the inputs. With fixed weights, a network that sees the same input at every step gives every node the same probability p of side 1, independently, so the expected cut is 2p(1-p)|E|, at most |E|/2. That is what coin flips achieve, and training longer does not change the bound. The printed 12.08 is a mean over 100 sampled episodes, so its small excess over the ceiling of 12 is sampling noise.

The registry's greedy entry is not a Max-Cut heuristic. It takes the argmax of a freshly initialised, never-trained GraphQNetwork. With all-zero features every action gets the same score, ties go to action 0, every node lands on side 0 and the cut is zero. Do not use it as the floor your agent has to beat.

Put the state into the node features

Encode c_t and t as node features: a one-hot of unassigned / side 0 / side 1, plus a flag on the current node. Then read the action scores out at that node instead of pooling the whole graph.

python
class MaxCutStateEnv(MaxCutEnv):
    """MaxCutEnv whose node features encode the Markov state."""

    def observe(self):
        obs = super().observe()
        side = F.one_hot(obs["assignment"] + 1, num_classes=3).float()   # none / 0 / 1
        current = torch.zeros(self.num_nodes, 1)
        if obs["current_node"] < self.num_nodes:
            current[obs["current_node"]] = 1.0
        obs["node_features"] = torch.cat([side, current], dim=1)         # [N, 4]
        return obs

class CurrentNodePolicy(nn.Module):
    """One message-passing layer, read out at the node being decided."""

    def __init__(self, in_dim=4):
        super().__init__()
        self.conv = tgx.LinearMessagePassing((in_dim,), (2,))

    def forward(self, x, edge_index):
        h = self.conv(x, edge_index)      # [N, 2]: one logit per side, per node
        return x[:, -1:].T @ h            # last column flags the current node: [1, 2]

senv = MaxCutStateEnv(edge_index, num_nodes=N)
obs = senv.reset()
print(obs["node_features"].shape, CurrentNodePolicy()(obs["node_features"], edge_index).shape)
text
torch.Size([12, 4]) torch.Size([1, 2])

LinearMessagePassing sums, over the neighbours u of node v, a linear function of the features of u and v. At the current node the two logits therefore depend on how many neighbours are unassigned, on side 0 and on side 1. With suitable weights (score for side 0 = number of neighbours on side 1, and the reverse) this layer reproduces the greedy heuristic below, so the question is only whether training finds a good rule.

Baselines that mean something

For Max-Cut you can write three references yourself. A uniformly random policy cuts |E|/2 in expectation. A sequential greedy heuristic puts each node on the side that cuts more edges to the nodes already placed, which guarantees at least |E|/2. On small graphs the optimum can be enumerated. GreedyPolicy takes your own scoring_fn(obs, action):

python
from tgraphx.rl import GreedyPolicy, RandomPolicy

def greedy_score(obs, action):
    """Number of edges that `action` would add to the cut right now."""
    v = obs["current_node"]
    src, dst = obs["edge_index"]
    neighbour_side = obs["assignment"][src[dst == v]]
    return float((neighbour_side == 1 - action).sum())

def play(agent, graph, **kwargs):
    env = MaxCutStateEnv(graph, num_nodes=N)
    obs, done = env.reset(), False
    while not done:
        obs, _, done, _, info = env.step(agent.select_action(obs, **kwargs))
    return info["cut_value"]

def optimum(graph):
    """Exact max cut by enumerating all 2**N assignments (small N only)."""
    sides = (torch.arange(2 ** N)[:, None] >> torch.arange(N)) & 1
    return int((sides[:, graph[0]] != sides[:, graph[1]]).sum(1).max()) // 2

def mean(values):
    return sum(values) / len(values)

test_graphs = [random_graph(N, 0.4, seed=3000 + i) for i in range(50)]
rng = torch.Generator().manual_seed(0)
greedy = GreedyPolicy(scoring_fn=greedy_score, n_actions=2)
reference = {
    "random": mean([play(RandomPolicy(2), g, generator=rng) for g in test_graphs for _ in range(20)]),
    "greedy heuristic": mean([play(greedy, g) for g in test_graphs]),
    "optimum": mean([optimum(g) for g in test_graphs]),
}
print({k: round(v, 2) for k, v in reference.items()})
text
{'random': 13.46, 'greedy heuristic': 19.18, 'optimum': 20.44}

Training with REINFORCE

REINFORCEAgent accepts any module that maps (node_features, edge_index) to logits of shape [1, A]. Two choices matter in the code below.

First, the training environment subtracts d_t/2 from each reward, where d_t is the number of neighbours of node t that are already placed. With a fixed node order, d_t depends on the graph and t, never on the actions, so it acts as a baseline: it reduces gradient noise and leaves the ranking of policies unchanged. Second, use_baseline=False turns off the agent's built-in baseline, which subtracts the mean return of the same episode and so depends on the very actions being scored.

python
from tgraphx.rl import REINFORCEAgent

class TrainingEnv(MaxCutStateEnv):
    """Subtracts the expected gain of a coin flip: half the already-placed neighbours."""

    def step(self, action):
        before = self.observe()
        v = before["current_node"]
        src, dst = before["edge_index"]
        placed = int((before["assignment"][src[dst == v]] != -1).sum())
        obs, reward, done, truncated, info = super().step(action)
        return obs, reward - placed / 2, done, truncated, info

learned = []
for seed in range(3):
    torch.manual_seed(seed)
    rng = torch.Generator().manual_seed(seed)
    policy = CurrentNodePolicy()
    agent = REINFORCEAgent(policy, torch.optim.Adam(policy.parameters(), lr=0.02),
                           gamma=1.0, use_baseline=False)
    for episode in range(300):
        graph = random_graph(N, 0.4, seed=10_000 * (seed + 1) + episode)  # training graphs
        agent.update(agent.collect_episode(TrainingEnv(graph, num_nodes=N), generator=rng))
    learned.append(mean([play(agent, g, deterministic=True) for g in test_graphs]))

print("learned, one value per seed:", [round(v, 2) for v in learned])
assert min(learned) > reference["random"]
text
learned, one value per seed: [17.98, 18.34, 18.48]

On graphs they never trained on, all three seeds land well above random (13.46) and below both the greedy heuristic (19.18) and the optimum (20.44). The policy learned something useful from reward alone. The learning rate and the reward baseline were chosen on a separate set of graphs (seeds 2000 to 2049), not on the test graphs.

Re-running the same loop with range(20) instead of range(3) gave values from 15.86 to 19.34 (mean 18.47). The short greedy heuristic is therefore better on average and better than 18 of the 20 seeds, while 2 seeds edged slightly above it (19.34 and 19.24). Reporting only a lucky seed would reverse the conclusion.

Action masking

Observations carry an action_mask. MaskedCategoricalPolicy sets the logits of invalid actions to -1e9, so their probability is zero in practice.

python
from tgraphx.rl import VertexCoverEnv, MaskedCategoricalPolicy

square = torch.tensor([[0, 1, 2, 3], [1, 2, 3, 0]])
cover_env = VertexCoverEnv(square, num_nodes=4)
cover_env.reset()
obs, reward, done, _, info = cover_env.step(0)             # put node 0 in the cover

dist = MaskedCategoricalPolicy(torch.zeros(1, 4), obs["action_mask"].unsqueeze(0))
probs = torch.stack([dist.log_prob(torch.tensor([a])) for a in range(4)]).exp().squeeze()
print(obs["action_mask"].tolist(), [round(p, 3) for p in probs.tolist()])
assert probs[0] == 0                                       # the mask removes node 0

_, reward, done, _, info = cover_env.step(0)               # ignore the mask: node 0 again
print(info["action_valid"], reward, done)
text
[False, True, True, True] [0.0, 0.333, 0.333, 0.333]
True -1.0 False

In vertex cover the mask is the only thing that prevents adding a node twice. The environment itself accepts the repeated node: it reports action_valid as true, charges -1 and carries on. In navigation and KG reasoning the mask limits actions to existing neighbours, and an index beyond them ends the episode. In Max-Cut and colouring every action is always allowed; colouring penalises conflicts instead of forbidding them.

Graph generation: some masked-valid actions fail

In 1.5.1 the mask of GraphGenerationEnv also marks edge removals as valid, but stepping one fails, because the action index is decoded without the endpoints of the edge. No exception is raised. The step returns reward -1 (times reward_scale), done=True and an error in info, so a masked agent or random policy silently loses the episode. The edge-removal slots are the last max_edges entries of the mask, and you can clear them:

python
from tgraphx.rl import GraphGenerationEnv, GraphEnvConfig

gen_config = GraphEnvConfig(max_nodes=5, max_edges=10)
gen_env = GraphGenerationEnv(config=gen_config)
gen_env.reset()
for action in (1, 1, 1, 8):                      # add three nodes, then the edge 0 -> 1
    obs, *_ = gen_env.step(action)

remove = len(obs["action_mask"]) - gen_config.max_edges    # first edge-removal slot
print(remove, bool(obs["action_mask"][remove]))
_, reward, done, _, info = gen_env.step(remove)
print(reward, done, info)

class NoEdgeRemovalEnv(GraphGenerationEnv):
    """Hides the edge-removal slots from the action mask."""

    def valid_action_mask(self):
        mask = super().valid_action_mask()
        mask[-self.config.max_edges:] = False
        return mask

safe_env = NoEdgeRemovalEnv(config=gen_config)
random_agent = RandomPolicy(safe_env.action_space)
rng = torch.Generator().manual_seed(0)
steps_with_edges = 0
for episode in range(200):
    obs, done = safe_env.reset(), False
    while not done:
        steps_with_edges += int(safe_env.num_edges > 0)
        obs, _, done, _, info = safe_env.step(random_agent.select_action(obs, generator=rng))
        assert info["action_valid"], info
print("no failed step; steps taken while edges existed:", steps_with_edges)
text
32 True
-1.0 True {'action_valid': False, 'error': 'REMOVE_EDGE action requires src_id and tgt_id'}
no failed step; steps taken while edges existed: 80

The override works because observe() fills action_mask from valid_action_mask(). The cost is that the agent can no longer remove a single edge, although removing a node still drops its edges. If you pass your own action_space_config, slice by its max_edges instead.

Tensor-valued node states

The five networks named in the pitfall section above accept only [N, F] features and raise ValueError for image-shaped [N, C, H, W] inputs. Tensor states still work, because you can encode each node first. TGraphX ships tgx.ImageNodeEncoder (two 3×3 convolutions and global average pooling, [N, C, H, W] to [N, out_dim]) and, for volumes, tgraphx.generation.VolumeNodeEncoder. tgraphx.rl.StateFeatureProjector takes an ImageNodeEncoder as its image_encoder argument and can also mix in edge or graph-level features; give it the same out_dim as the encoder.

Encoding does not remove the two requirements from above: the state flags must reach the network, and for Max-Cut the scores should be read at the current node. Below, a wrapper encodes the image channels, appends the flags and hands the result to either a built-in network or CurrentNodePolicy:

python
class ImageMaxCutEnv(MaxCutStateEnv):
    """Node features: each node's image plus the four state flags as constant planes."""

    def __init__(self, edge_index, images):
        super().__init__(edge_index, num_nodes=images.shape[0])
        self.images = images                                    # [N, C, H, W]

    def observe(self):
        obs = super().observe()
        flags = obs["node_features"][:, :, None, None].expand(-1, -1, *self.images.shape[2:])
        obs["node_features"] = torch.cat([self.images, flags], dim=1)
        return obs

class EncodedPolicy(nn.Module):
    """ImageNodeEncoder in front of a policy that takes [N, F] features."""

    def __init__(self, head, channels=3, dim=16):
        super().__init__()
        self.encoder = tgx.ImageNodeEncoder(channels, dim)      # [N, C, H, W] -> [N, dim]
        self.head = head

    def forward(self, x, edge_index):
        images, flags = x[:, :-4], x[:, -4:, 0, 0]              # image channels, state flags
        h = torch.cat([self.encoder(images), flags], dim=1)     # [N, dim + 4]
        return self.head(h, edge_index)                         # [1, 2]

images = torch.randn(N, 3, 8, 8)
image_env = ImageMaxCutEnv(edge_index, images)

heads = {
    "built-in network": GraphPolicyNetwork(node_in_dim=20, hidden_dim=16, num_actions=2),
    "current-node readout": CurrentNodePolicy(in_dim=20),
}
for name, head in heads.items():
    encoded_policy = EncodedPolicy(head)
    encoded_agent = REINFORCEAgent(encoded_policy, torch.optim.Adam(encoded_policy.parameters()),
                                   gamma=1.0, use_baseline=False)
    trajectory = encoded_agent.collect_episode(image_env)
    encoded_agent.update(trajectory)
    print(f"{name}: {len(trajectory['rewards'])} steps collected, one update done")
text
built-in network: 12 steps collected, one update done
current-node readout: 12 steps collected, one update done

Build on the second form for this problem. The built-in network accepts the encoded vectors, but it averages all nodes into one before scoring actions, so it has no readout at the node being decided.

The encoder has its own cost: its global pooling averages positions out before any message passing. If neighbouring images should be compared position by position, keep the feature maps through message passing instead. TensorGraphSAGELayer keeps [H, W] and combines a node with its neighbours pixel by pixel. Its convolutions are 1×1, so it does not look at neighbouring pixels, and the policy below averages over positions only afterwards:

python
class ImageStatePolicy(nn.Module):
    """Message passing on whole feature maps, then a readout at the current node."""

    def __init__(self, channels, hidden=8):
        super().__init__()
        self.conv = tgx.TensorGraphSAGELayer(channels + 4, hidden)
        self.head = nn.Linear(hidden, 2)

    def forward(self, x, edge_index):
        h = F.relu(self.conv(x, edge_index)).mean(dim=(2, 3))   # [N, hidden]
        current = x[:, -1, 0, 0]                                # the "current node" plane
        return self.head(current @ h).unsqueeze(0)              # [1, 2]

image_policy = ImageStatePolicy(channels=3)
obs = image_env.reset()
print(obs["node_features"].shape, image_policy(obs["node_features"], edge_index).shape)

image_agent = REINFORCEAgent(image_policy, torch.optim.Adam(image_policy.parameters()),
                             gamma=1.0, use_baseline=False)
trajectory = image_agent.collect_episode(image_env)
print(len(trajectory["rewards"]), "steps collected")
text
torch.Size([12, 7, 8, 8]) torch.Size([1, 2])
12 steps collected

These runs only show that the shapes and the agent interface work: the images are random noise and say nothing about the cut. run_graph_rl does not insert an encoder. Its network-based algorithms raise the same ValueError on this environment (the DQN variants once they first call their network), so build the policy and the agent yourself.

The algorithm registry

python
algos = tgx.list_graph_rl_algorithms()
for kind in ("discrete", "continuous"):
    print(kind, [f"{name} ({info['stability']})" for name, info in algos.items()
                 if info["action_type"] == kind])
assert len(algos) == 13
text
discrete ['random (Beta)', 'greedy (Beta)', 'reinforce (Experimental)', 'actor_critic (Experimental)', 'a2c (Experimental)', 'dqn (Experimental)', 'double_dqn (Experimental)', 'dueling_dqn (Experimental)', 'ppo (Experimental)']
continuous ['ddpg (Experimental)', 'delayed_ddpg (Experimental)', 'td3 (Experimental)', 'sac (Experimental)']

run_graph_rl(env, algorithm=...) takes any of these names (discrete algorithms need integer actions, continuous ones vector actions). Its RLResult holds metrics and config, not the trained agent, so to evaluate a policy on new graphs, construct the agent yourself as above. Behaviour to know about in 1.5.1:

  • With ppo, each entry of episode_returns is the reward sum of a fixed-length rollout (10 steps for a two-action problem), not of one full episode. Do not compare it with other algorithms' returns unless the lengths match.
  • Every PPO rollout also starts from env.reset(). On a Max-Cut graph with more than 10 nodes, run_graph_rl therefore never reaches the later nodes: PPO never makes, or trains on, a decision for them. In your own loop, give PPOAgent.collect_rollout an n_steps that is a multiple of the number of nodes, so that each rollout holds whole Max-Cut episodes.
  • A continuous algorithm given a discrete environment name, such as "max_cut", silently runs on continuous_navigation instead.
  • The wrapper tgx.train_graph_rl defaults to algorithm="random" and fast_mode=True, which caps a run at 5 episodes and, for environments built from a name, 20 steps each. It also drops num_nodes and edge_density.

The module is a small-scale research tool; its own documentation string points production users to libraries such as Stable-Baselines3 and RLlib.

Before you report a result

  1. Check that two different states give different network inputs.
  2. Compare with random, with a heuristic for your problem (your own scoring_fn), and with the optimum when you can compute it.
  3. Run several seeds and report the spread, not the best run.
  4. Use three separate sets of graphs: train on one, choose settings (learning rate, reward baseline, architecture) on a second, and report on a third that played no part in either.
  5. State γ, and report the true objective (here the cut size), not only the training return.

References

  • Khalil, Dai, Zhang, Dilkina and Song, "Learning Combinatorial Optimization Algorithms over Graphs", NeurIPS 2017. Like the example here, it feeds the partial solution to a graph network as a per-node input.
  • Sutton and Barto, Reinforcement Learning: An Introduction, 2nd edition, MIT Press, 2018.

Related guides

Conclusion

The MDP view tells you exactly what the network has to see: the graph, the partial solution and the decision point. In tgraphx.rl the Max-Cut environment exposes all three, but what the built-in networks read carries only the graph. Encode the rest yourself, read out at the node being decided, and judge the result against a heuristic, not against a learning curve.