TGraphX › Insights › REINFORCE, DQN and PPO on a Graph Navigation Task in TGraphX
← Back to Insights

REINFORCE, DQN and PPO on a Graph Navigation Task in TGraphX

Topic: Graph mining, generation, optimization and RL

Reinforcement learning on graphs is a research area where graphs appear in two roles: as the state the agent perceives, or as the object being optimised. A graph RL agent might navigate a road network, edit a molecule, schedule tasks on a compute graph or route packets.

TGraphX provides graph environments, small policy and value networks and 13 algorithm names in tgraphx.rl; the learning algorithms are labelled Experimental. This guide trains an agent on one navigation task three ways (REINFORCE, DQN and PPO) with hand-written loops, evaluates all three against a random baseline and the known shortest paths, and lists the traps found along the way. Examples tested with TGraphX 1.5.1 on CPU; the Python blocks build on each other.

For the formal framing, see graph RL framed as an MDP over tensor states.


Two Roles for Graphs in RL

Graph as state. The agent observes a graph at each step. The graph may change after each action, or the agent moves through a fixed graph (navigation). Policy and value networks turn node features and edges into action scores or value estimates.

Graph as the object being optimised. Each action changes a graph or a labelling of it (add an edge, remove a node, put a node on one side of a cut), and the reward measures a property of the result.

tgraphx.rl has environments for both: GraphNavigationEnv and ShortestPathEnv for the first; MaxCutEnv, GraphColoringEnv, VertexCoverEnv and GraphGenerationEnv for the second.


Core Concepts in Code

  • Observation. A dictionary with node_features, edge_index, often action_mask, plus environment-specific keys such as current_node.
  • Action. An integer. In navigation, action k means "move to the k-th neighbour of the current node".
  • Step. env.step(action) returns (obs, reward, done, truncated, info). done is also true when the episode is cut off by max_steps.
  • Reward. GraphNavigationEnv gives +10 for reaching the target and −0.1 for every other step, by default.
  • Policy network. GraphPolicyNetwork runs two mean-aggregation layers (each node averages over its incoming edges, with no self term), mean-pools all nodes into one vector and maps it to one logit per action. The agent applies the action mask and the softmax.

The Task: Make the State Visible

The task is a 3×3 grid with the target in a corner. Every episode starts at a random other node, so the right move depends on where the agent is.

There is a catch. GraphNavigationEnv reports the position in obs["current_node"], which the built-in networks never read; they see only node_features and edge_index, and those do not change. Because the networks used here mean-pool all nodes, the simplest fix is to put the position on every node as a one-hot vector. The observation override below does that.

python
import torch
from tgraphx.rl import GraphNavigationEnv, GraphEnvConfig, RandomPolicy

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

# 3x3 grid, nodes 0..8 row by row, each undirected edge listed once
edges = [(r * 3 + c, r * 3 + c + 1) for r in range(3) for c in range(2)]
edges += [(r * 3 + c, r * 3 + c + 3) for r in range(2) for c in range(3)]
grid = torch.tensor(edges).t()
TARGET = 8

class GridEnv(GraphNavigationEnv):
    def __init__(self, seed=0):
        super().__init__(grid, num_nodes=9, target_node=TARGET,
                         config=GraphEnvConfig(max_steps=12))
        self.starts = torch.Generator().manual_seed(seed)
        self.fixed_start = None                      # set during evaluation

    def reset(self, seed=None):
        super().reset(seed)
        random_start = int(torch.randint(8, (1,), generator=self.starts))
        self._current_node = random_start if self.fixed_start is None else self.fixed_start
        return self.observe()

    def observe(self):
        obs = super().observe()
        obs["node_features"] = torch.eye(9)[self._current_node].repeat(9, 1)   # [9, 9]
        return obs

def evaluate(select_action):
    """Start once from each of the 8 non-target nodes."""
    env, reached, shortest = GridEnv(), 0, 0
    for start in range(8):
        env.fixed_start = start
        obs, done, steps = env.reset(), False, 0
        while not done:
            obs, reward, done, truncated, info = env.step(select_action(obs))
            steps += 1
        distance = (2 - start // 3) + (2 - start % 3)
        reached += info["success"]
        shortest += info["success"] and steps == distance
    return reached, shortest

num_actions = GridEnv().action_space                     # largest degree: 4
rng = torch.Generator().manual_seed(0)
random_agent = RandomPolicy(num_actions)
runs = [evaluate(lambda o: random_agent.select_action(o, generator=rng)) for _ in range(200)]
print("random: reached %.1f of 8, by a shortest path %.1f of 8"
      % tuple(sum(column) / len(runs) for column in zip(*runs)))
text
random: reached 4.3 of 8, by a shortest path 1.5 of 8

A second catch concerns edge direction. The environment treats each listed edge as two-way when it builds the actions, but obs["edge_index"] is the list exactly as you passed it, and the network layers send messages from source to destination only. With the one-way list above, node 0 receives nothing. The task is still learnable here because every node carries the position. If messages should flow both ways, add the reverse edges to the observation inside observe (torch.cat([ei, ei.flip(0)], dim=1)). Do not pass the symmetric list to the navigation environment itself: with the default directed=False, every neighbour would then appear twice among the actions.

This encoding makes the network a lookup over nine positions: it can learn this grid, but nothing transfers to another graph. A policy that generalises has to score neighbours from graph structure. tgraphx.rl.NodeActionPolicy returns one logit per node for any graph size, but action k here means the k-th neighbour, so you would still have to turn node scores into action scores yourself, and run_graph_rl does not use that class. The MDP article shows a hand-written readout for MaxCut.


REINFORCE: Simplest Policy Gradient

REINFORCEAgent takes a policy module and an optimizer. collect_episode returns a dictionary (log_probs, rewards, entropies, total_return), and update turns it into one gradient step and returns the losses.

python
from tgraphx.rl import GraphPolicyNetwork, REINFORCEAgent

torch.manual_seed(0)
policy = GraphPolicyNetwork(node_in_dim=9, hidden_dim=32, num_actions=num_actions)
reinforce = REINFORCEAgent(policy, torch.optim.Adam(policy.parameters(), lr=1e-2), gamma=0.99)

env, rng = GridEnv(seed=0), torch.Generator().manual_seed(0)
for episode in range(600):
    trajectory = reinforce.collect_episode(env, generator=rng)
    losses = reinforce.update(trajectory)

print(sorted(losses))
print("REINFORCE:", evaluate(lambda o: reinforce.select_action(o, deterministic=True)))
text
['entropy_loss', 'policy_loss', 'total_loss']
REINFORCE: (8, 7)

The tuple reads "reached from 8 starts, 7 of them by a shortest path". By default the agent subtracts the mean return of the same episode as its baseline. That baseline depends on the actions being scored, and for one-step episodes it zeroes the policy-gradient term, so the reward has no effect on the update (only the entropy bonus remains); pass use_baseline=False when that matters.


DQN: Replay and Target Network

DQNAgent takes the online network, a target network, an optimizer and hyperparameters. It has no episode collector: you write the loop, push transitions into agent.buffer and call update.

python
from tgraphx.rl import GraphQNetwork, DQNAgent

torch.manual_seed(0)
q_net = GraphQNetwork(node_in_dim=9, hidden_dim=32, num_actions=num_actions)
target_net = GraphQNetwork(node_in_dim=9, hidden_dim=32, num_actions=num_actions)
dqn = DQNAgent(q_net, target_net, torch.optim.Adam(q_net.parameters(), lr=5e-3),
               gamma=0.99, eps_start=1.0, eps_end=0.05,
               eps_decay=500.0,            # time constant, counted in updates
               target_update_freq=50, batch_size=16)

env, rng = GridEnv(seed=0), torch.Generator().manual_seed(0)
for episode in range(150):
    obs, done = env.reset(), False
    while not done:
        action = dqn.select_action(obs, generator=rng)
        next_obs, reward, done, truncated, info = env.step(action)
        dqn.buffer.push(obs, action, reward, next_obs, info["success"])  # terminal only at the target
        dqn.update()                       # does nothing until the buffer holds a batch
        obs = next_obs

print("DQN:", evaluate(lambda o: dqn.select_action(o, deterministic=True)))
text
DQN: (8, 8)

Two details decide whether this works:

  • Set eps_decay. Epsilon is eps_end + (eps_start − eps_end)·exp(−updates / eps_decay). The default, 0.995, looks like a per-step multiplier but is used as the time constant, so exploration is almost gone after a few updates.
  • Store the right done. The last argument of push should mean "no future reward". A cut-off at max_steps is not that, so the loop stores info["success"].

DoubleDQNAgent has the same constructor and picks the next action with the online network while evaluating it with the target network.


PPO: Clipped Policy Updates

PPOAgent needs an actor-critic module that returns (logits, value). collect_rollout(env, n_steps) gathers a fixed number of steps, resetting the environment as episodes end, and update runs several epochs with a clipped ratio.

python
from tgraphx.rl import GraphActorCriticNetwork, PPOAgent

torch.manual_seed(0)
actor_critic = GraphActorCriticNetwork(node_in_dim=9, hidden_dim=32, num_actions=num_actions)
ppo = PPOAgent(actor_critic, torch.optim.Adam(actor_critic.parameters(), lr=5e-3),
               gamma=0.99, gae_lambda=0.95, clip_eps=0.2, n_epochs=4,
               value_loss_coef=0.5, entropy_coef=0.01)

env, rng = GridEnv(seed=0), torch.Generator().manual_seed(0)
for iteration in range(20):
    rollout = ppo.collect_rollout(env, n_steps=64, generator=rng)
    stats = ppo.update(rollout)

print(sorted(stats))
print("PPO:", evaluate(lambda o: ppo.select_action(o, deterministic=True)))
text
['approx_kl', 'clip_fraction', 'entropy', 'total_loss']
PPO: (8, 8)

Choose n_steps several times longer than an episode. A rollout that is cut off mid-episode is treated as if no further reward followed it, so very short rollouts bias the value targets.

PPOAgent treats a max_steps cut-off the same way. collect_rollout records done or truncated as done, so it bootstraps no value there: the cut-off counts as "no future reward", unlike the info["success"] flag stored in the DQN loop above. The DQN loop inside run_graph_rl also stores done or truncated.


Reading the Results

With seed 0 all three reach the target from every start, far more often than random and mostly or always by a shortest path. These numbers do not rank the algorithms. The three runs use different amounts of experience and different settings, none was tuned systematically, and the task is tiny.

Seeds matter even here. When the three training blocks are repeated with seeds 0, 1 and 2, REINFORCE and PPO reach the target from all eight starts every time, while DQN does so for two seeds and from only four starts for the third. Always report several seeds.


The One-Call API

run_graph_rl builds its own network and agent for any registry name and returns metrics, not the trained agent:

python
from tgraphx.rl import run_graph_rl

result = run_graph_rl("max_cut", algorithm="random", episodes=5, seed=42)
print(sorted(result.metrics))
print(result.metrics["environment"], len(result.metrics["episode_returns"]))
text
['algorithm', 'environment', 'episode_returns', 'mean_return', 'success_rate']
max_cut 5

The environment names use underscores: "max_cut" and "graph_navigation". "maxcut" and "navigation" are aliases of the separate tgx.train_graph_rl wrapper only, and that wrapper's default fast_mode=True caps runs at 5 episodes. Given just a name such as "max_cut", run_graph_rl uses a small built-in path graph, so pass your own environment object (or edge_index= and num_nodes=) for real work.

MaxCutEnv and GraphColoringEnv need the opposite of the navigation convention: they halve their edge counts, so edge_index must list every undirected edge in both directions (for the grid above, torch.cat([grid, grid.flip(0)], dim=1)). With the one-way grid, a perfect cut of 12 is reported as 6, and the colouring environment can report success while an edge still has a conflict. Neither raises an error. The introduction to graph RL covers this API and more of its traps.


Supported Algorithms

The registry is what list_graph_rl_algorithms() returns:

Name Actions Label Family
random discrete Beta baseline
greedy discrete Beta argmax of an untrained Q-network
reinforce discrete Experimental policy gradient
actor_critic discrete Experimental actor-critic
a2c discrete Experimental advantage actor-critic
dqn discrete Experimental value-based
double_dqn discrete Experimental value-based
dueling_dqn discrete Experimental value-based
ppo discrete Experimental clipped policy gradient
ddpg continuous Experimental deterministic actor-critic
delayed_ddpg continuous Experimental DDPG with delayed actor updates
td3 continuous Experimental twin critics
sac continuous Experimental entropy-regularised

greedy is not a graph heuristic. For a heuristic baseline, write one and pass it to GreedyPolicy(scoring_fn=..., n_actions=...).


Environments

There are nine environment names: graph_navigation, shortest_path, max_cut, graph_coloring, vertex_cover, graph_generation, kg_reasoning, continuous_navigation and continuous_graph_edit. In 1.5.1, kg_reasoning cannot be built by name; construct KGPathReasoningEnv directly.

To define your own, subclass tgraphx.rl.GraphEnv and implement reset, step, observe, valid_action_mask and state_to_graph, plus an integer action_space for discrete algorithms.

The built-in environments are small and simple. They are meant for studying algorithms, not for production graph optimisation. For hard combinatorial problems such as TSP, vehicle routing or large colouring instances, look first at exact or heuristic solvers, or at libraries built for neural combinatorial optimisation such as RL4CO.


Limitations: What This Does Not Cover

  • No model-based RL. World models and planning are not implemented.
  • No offline RL. Learning from pre-collected trajectories is not included.
  • One output per action in the networks used here. GraphPolicyNetwork, GraphQNetwork, GraphDuelingQNetwork and GraphActorCriticNetwork (what run_graph_rl builds for discrete actions) pool the graph and emit a fixed number of values. tgraphx.rl also exports NodeActionPolicy and EdgeActionPolicy, which score each node or edge for any graph size. run_graph_rl does not use them, so you wire them into your own loop; used as they are, they fit actions that are node or edge indices.
  • Vector node features only. The networks expect [N, F] node features, so encode images or volumes first. The four pooled networks above raise ValueError for other ranks; NodeActionPolicy and EdgeActionPolicy do not check the rank.
  • No performance claims. This guide does not compare tgraphx.rl with established RL libraries; see the TGraphX benchmark disclaimers.
  • APIs may change. The subsystem is Experimental, so pin your version.

When You Only Need a Good Graph

If the goal is one good graph rather than a policy that can be reused, direct search is a simpler alternative to try first:

python
import tgraphx as tgx

found = tgx.optimize_graph("density", algorithm="ga", num_nodes=10, generations=20,
                           population_size=10, max_edges=90, seed=42, fast_mode=False)
print(len(found.fitness_history), round(found.fitness_history[0], 3), round(found.best_fitness, 3))
text
20 0.989 1.0

The output is the number of generations, then the best fitness in the first generation and at the end. The "density" objective is 1 minus the distance from a density of 0.5, where density counts directed edges. Two arguments matter. fast_mode=False, because the default caps the search at 3 generations and a population of 6. And max_edges, which defaults to 20 directed edges: on 10 nodes that limits the density to 20/90, and the same call without it stays at 0.722 from the first generation to the last, so set it. Even with the cap lifted, the first generation is already close to the target, so this shows how to call the search rather than how strong it is. See evolutionary optimization of graph structures for custom objectives and further traps. This guide does not compare it with RL experimentally.


Related Articles