TGraphX › Insights › run_graph_rl in TGraphX: Environments, Algorithms and Result Traps
← Back to Insights

run_graph_rl in TGraphX: Environments, Algorithms and Result Traps

Topic: Graph mining, generation, optimization and RL

Graph reinforcement learning (graph RL) covers sequential decision problems whose state or action space is a graph: choose the next node to visit, the colour of a vertex, the side of a cut, an edge to add. Classic combinatorial problems such as MaxCut, vertex cover, graph colouring and routing fit this framing, and learning heuristics for them is an active research area.

TGraphX includes a small graph RL subpackage, tgraphx.rl, with 13 algorithm names and 9 environments. It labels itself Experimental (the random and greedy registry entries are labelled Beta), and its own documentation string points production users to libraries such as Stable-Baselines3 and RLlib. This introduction shows how to run it, what it returns, and which results not to trust. Examples tested with TGraphX 1.5.1 on CPU; the Python blocks build on each other.

This is the short introduction; the practical guide to REINFORCE, DQN and PPO on graphs walks through individual algorithms.

What the subpackage includes

Environment name Class One action
graph_navigation GraphNavigationEnv move to the k-th neighbour
shortest_path ShortestPathEnv same, with shaped rewards
max_cut MaxCutEnv, GraphMaxCutEnv put the next node on side 0 or 1
graph_coloring GraphColoringEnv colour the next node
vertex_cover VertexCoverEnv add a node to the cover
graph_generation GraphGenerationEnv add a node or edge, remove a node, or stop
kg_reasoning KGPathReasoningEnv follow an outgoing edge of an entity
continuous_navigation ContinuousNavigationEnv a vector, decoded to a neighbour
continuous_graph_edit ContinuousGraphEditEnv a vector, decoded to an edit

Two rough edges in 1.5.1: stepping an edge removal in graph_generation fails even though the action mask marks it valid, and building kg_reasoning by name raises TypeError (construct KGPathReasoningEnv directly).

The algorithm registry is a function call:

python
import torch
from tgraphx.rl import run_graph_rl, list_graph_rl_algorithms

torch.set_num_threads(1)   # tiny graphs: one thread is fastest

algorithms = list_graph_rl_algorithms()
for kind in ("discrete", "continuous"):
    print(kind, [name for name, info in algorithms.items() if info["action_type"] == kind])
text
discrete ['random', 'greedy', 'reinforce', 'actor_critic', 'a2c', 'dqn', 'double_dqn', 'dueling_dqn', 'ppo']
continuous ['ddpg', 'delayed_ddpg', 'td3', 'sac']

A first experiment, and why the learners do not win

run_graph_rl accepts an environment name or an environment object and trains for the number of episodes you ask for (for ppo, that many fixed-length rollouts instead). Build the environment yourself so that you know which graph you are solving: given only the name "max_cut", it uses an 8-node path graph, whatever you intended. If you pass your own edge_index to MaxCutEnv or GraphColoringEnv, list every undirected edge in both directions, because both halve their counts. With a one-way list the cut or conflict count comes out about half, no error is raised, and a colouring with a single clash is reported as a success. The navigation environments are the opposite: unless config.directed=True, they treat each listed edge as two-way when building actions, while obs["edge_index"], which the networks read, is left as you passed it.

python
from tgraphx.rl import GraphMaxCutEnv

env = GraphMaxCutEnv(num_nodes=10, edge_density=0.4, seed=1)    # a random graph
print("undirected edges:", env.num_edges // 2)                  # both directions are stored

results = {}
for name in ("random", "reinforce", "dqn"):
    results[name] = run_graph_rl(env, algorithm=name, episodes=40, seed=0)
    returns = results[name].metrics["episode_returns"]
    print(f"{name:9s} mean cut, last 20 episodes: {sum(returns[-20:]) / 20:.2f}")

print(sorted(results["dqn"].metrics))
text
undirected edges: 15
random    mean cut, last 20 episodes: 6.95
reinforce mean cut, last 20 episodes: 7.05
dqn       mean cut, last 20 episodes: 1.10
['algorithm', 'environment', 'episode_returns', 'final_epsilon', 'mean_return', 'success_rate']

The learners are no better than random, and DQN is far worse. This is not a matter of more episodes:

  • The networks cannot see the state. By default MaxCutEnv gives every node the same all-zero feature. The partial cut is in obs["assignment"], which the built-in networks never read, so the network output is the same at every step.
  • DQN stops exploring almost at once. Its default eps_decay=0.995 is used as the time constant of an exponential, not as a per-step factor, so epsilon is near its floor of 0.05 after a handful of updates. A greedy choice that ignores the state puts nearly every node on the same side, which cuts almost nothing.

The fix is to encode the state into the node features and to read the scores at the node being decided. Graph RL as an MDP over tensor states does exactly that for MaxCut.

A sanity check that can learn

A useful first test of any training loop is a task whose best policy needs no state at all. Take a corridor whose edges are listed once, from left to right. At every inner node, action 1 means "step right", and at node 0 the only valid action also steps right:

python
from tgraphx.rl import GraphNavigationEnv, GraphEnvConfig

L = 6
corridor = torch.stack([torch.arange(L - 1), torch.arange(1, L)])   # 0-1-2-3-4-5
nav = GraphNavigationEnv(corridor, num_nodes=L, target_node=L - 1,
                         config=GraphEnvConfig(max_steps=30))

for name in ("random", "greedy", "reinforce"):
    r = run_graph_rl(nav, algorithm=name, episodes=150, seed=0, lr=1e-2)
    returns = r.metrics["episode_returns"]
    print(f"{name:9s} return, last 50: {sum(returns[-50:]) / 50:5.2f}   "
          f"success_rate: {r.metrics['success_rate']:.2f}")
text
random    return, last 50:  6.10   success_rate: 0.73
greedy    return, last 50: -3.00   success_rate: 0.00
reinforce return, last 50:  9.39   success_rate: 0.00

The best return is 9.6 (four steps at −0.1, then +10), so REINFORCE has learned to walk right. Two things in that table are traps:

  • greedy is not a graph heuristic. It takes the argmax of a freshly initialised, untrained Q-network. Here it walks back and forth until the step limit.
  • success_rate reads 0.00 for REINFORCE although its returns show that it reaches the target. In 1.5.1 the runner does not record success for reinforce and ppo. Judge those two by their returns, or count successes yourself.

What the result holds, and keeping the agent

RLResult has metrics (the keys shown above; final_epsilon only for the DQN family), config, and the properties mean_return and final_reward (the last episode's return). It does not contain the trained policy. If you need the policy, build the agent yourself:

python
from tgraphx.rl import GraphPolicyNetwork, REINFORCEAgent

torch.manual_seed(0)
policy = GraphPolicyNetwork(node_in_dim=1, hidden_dim=16, num_actions=nav.action_space)
agent = REINFORCEAgent(policy, torch.optim.Adam(policy.parameters(), lr=1e-2))

rng = torch.Generator().manual_seed(0)
for episode in range(150):
    agent.update(agent.collect_episode(nav, generator=rng))

obs, done, path = nav.reset(), False, [0]
while not done:
    obs, reward, done, truncated, info = nav.step(agent.select_action(obs, deterministic=True))
    path.append(info["current_node"])
print("path:", path)
text
path: [0, 1, 2, 3, 4, 5]

Your own environment

Subclass tgraphx.rl.GraphEnv. Five methods are abstract: reset, step, observe, valid_action_mask and state_to_graph. Discrete algorithms also need an integer action_space. Observations are dictionaries with at least node_features, edge_index and, if some actions are invalid, action_mask.

python
from tgraphx.rl import GraphEnv
from tgraphx.generation import GeneratedGraph

class PickHubEnv(GraphEnv):
    """One decision: pick a node. The reward is its degree relative to the largest degree."""

    def __init__(self, edge_index, num_nodes):
        super().__init__(GraphEnvConfig(max_steps=1))
        self.edge_index, self.n = edge_index, num_nodes
        degree = torch.bincount(edge_index.flatten(), minlength=num_nodes).float()
        self.score = degree / degree.max()
        self.done = False

    @property
    def action_space(self):
        return self.n

    def reset(self, seed=None):
        self.done = False
        return self.observe()

    def observe(self):
        return {"node_features": self.score.unsqueeze(1), "edge_index": self.edge_index,
                "action_mask": self.valid_action_mask(), "done": self.done}

    def valid_action_mask(self):
        return torch.ones(self.n, dtype=torch.bool)

    def state_to_graph(self):
        return GeneratedGraph(edge_index=self.edge_index, num_nodes=self.n)

    def step(self, action):
        self.done = True
        reward = float(self.score[action])
        return self.observe(), reward, True, False, {"success": reward == 1.0}

hub_graph = torch.tensor([[3, 3, 3, 3, 0], [0, 1, 2, 4, 1]])     # node 3 is the hub
hub_env = PickHubEnv(hub_graph, num_nodes=5)
for name in ("random", "a2c", "reinforce"):
    r = run_graph_rl(hub_env, algorithm=name, episodes=150, seed=0, lr=1e-2)
    returns = r.metrics["episode_returns"]
    print(f"{name:9s} mean reward, last 50: {sum(returns[-50:]) / 50:.2f}")
text
random    mean reward, last 50: 0.48
a2c       mean reward, last 50: 1.00
reinforce mean reward, last 50: 0.48

REINFORCE stays at the random level for a mechanical reason. Its default baseline subtracts the mean return of the same episode. With one step per episode that leaves exactly zero, so there is no policy gradient. Construct REINFORCEAgent(..., use_baseline=False) for one-step problems, or use a critic-based method.

Continuous actions

DDPG, delayed DDPG, TD3 and SAC need a continuous environment. Observations are the same kind of graph dictionary; only the action is a vector in [−1, 1]. In continuous_navigation the neighbour whose projected features are most similar to the action vector is chosen.

python
sac = run_graph_rl("continuous_navigation", algorithm="sac", episodes=3, seed=0,
                   num_nodes=6, config=GraphEnvConfig(max_steps=20))
print(sac.metrics["environment"], len(sac.metrics["episode_returns"]))

swapped = run_graph_rl("max_cut", algorithm="td3", episodes=1,
                       config=GraphEnvConfig(max_steps=5))
print(swapped.metrics["environment"])
text
continuous_navigation 3
continuous_navigation

The first call only shows that the pipeline runs; three episodes say nothing about learning. The second shows a trap: pass a continuous algorithm together with a discrete environment name, and you silently get continuous_navigation instead of the problem you asked for.

About the tgx.train_graph_rl wrapper

There is also a shorter tgx.train_graph_rl(...). Know its defaults before using it: algorithm="random", and fast_mode=True, which caps a run at 5 episodes and, for environments given by name without your own config=, 20 steps per episode, even if episodes= or max_steps= ask for more; fast_mode=False removes both caps. The wrapper also drops num_nodes and edge_density. For experiments, call run_graph_rl.

When it fits, and when it does not

It is a reasonable fit when you are exploring how to formulate a graph decision problem, teaching, or prototyping on very small graphs with environments you can read.

It is a poor fit for production control, for large graphs, or for comparisons with published results. For the latter, use an established RL library with your own environment, or the code released with the paper.

On graph size: the networks run_graph_rl builds have one output per action, so each is tied to one action-space size. tgraphx.rl.NodeActionPolicy and EdgeActionPolicy score each node or edge instead, which suits actions that are node or edge indices, but run_graph_rl does not use them and you must write the training loop yourself.

Whatever you use:

  • compare with random and a hand-written heuristic for your problem (GreedyPolicy(scoring_fn=..., n_actions=...) lets you plug one in);
  • check that two different states give the network different inputs;
  • run several seeds. run_graph_rl seeds itself from seed=, but one seed is one sample.

FAQ

Q: Are the environments Gymnasium environments?
A: No. step returns five values like Gymnasium, but reset returns only the observation, done is also true on truncation, and there are no Gymnasium space objects. Using Gymnasium tools needs an adapter.

Q: Does tgraphx.rl support multiple agents?
A: There is no multi-agent abstraction in 1.5.1.

Q: Do the DQN variants use prioritized replay?
A: No. ReplayBuffer samples uniformly.

Q: Is there a benchmark against Stable-Baselines3?
A: The package does not include one, and this article makes no performance comparison.