Post

Improving the Cart Pole RL training: randomized starts and periodic evaluation

The first version of the Cart Pole training was too basic: it always started from the same state, stopped to evaluate after every round, and the physics were not very consistent. This post covers the changes made to turn it into a more solid base project. ROS is not part of it yet.

Upgrades Cart Pole RL training

The improvements made over the past few weeks to achieve more consistent training are as follows:

Training loop

  • The unnecessary pause between episodes is gone. Training now runs continuously and the best model is saved automatically.
  • Evaluation uses Stable-Baselines3’s EvalCallback: the model is evaluated every 20,000 steps, and the best one is kept.
  • Training lasts 200,000 steps in total.

World

  • The masses of the cart and the pole are now more consistent.
  • The force applied per action is increased to 2000 N.

Initial states

  • The pole’s initial angle is random within ±0.2 rad.
  • The cart gets an initial push of -600, 0 or 1000 N, picked at random.
  • Evaluation runs in its own environment with fixed seeds, so every evaluation uses the same initial conditions and results are comparable.

Timing

  • Each agent action lasts 5 ms of simulation (5 physics steps of 1 ms).
  • An episode can last up to 10,000 steps.

With these improvements, we are left with the following code.

train_cart_pole.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import os
import subprocess
import time

import gymnasium as gym
import numpy as np
from stable_baselines3 import PPO
from stable_baselines3.common.callbacks import EvalCallback
from stable_baselines3.common.env_checker import check_env
from gz.sim import TestFixture, World, world_entity, Model, Link, get_install_prefix, Joint
from gz.math import Vector3d

SDF = "/RoboticsAcademy/GAZEBO_MUNDOS/prueba_cart_pole.sdf"
EVAL_SDF = "/RoboticsAcademy/GAZEBO_MUNDOS/prueba_cart_pole_eval.sdf"
STRENGTH = 2_000
ANGLE_RANGE = 0.2
X_LIMIT = 4.8
CART_PUSHES = [-600.0, 0.0, 1000.0]

STEP_MS = 1
ACTION_MS = 5
STEPS_PER_ACTION = ACTION_MS // STEP_MS
MAX_EPISODE_STEPS = 10000

TOTAL_STEPS = 200_000
EVAL_FREQ = 20_000
EVAL_EPISODES = 10
EVAL_SEED = 1000
BEST_DIR = "./best"


class CartEnv(gym.Env):
    def __init__(self, sdf=SDF):
        super().__init__()
        self.action_space = gym.spaces.Discrete(2)
        self.observation_space = gym.spaces.Box(-np.inf, np.inf, (4,), np.float32)

        self.command = None
        self.terminated = False
        self.reward = 1.0
        self.steps = 0
        self.state = np.zeros(4, dtype=np.float32)
        self.cart = None
        self.pole = None
        self.init_angle = 0.0
        self.init_push = 0.0
        self.init_ticks = 0
        self.set_angle = False

        self.fixture = TestFixture(sdf)
        self.fixture.on_pre_update(self.on_pre_update)
        self.fixture.on_post_update(self.on_post_update)
        self.fixture.finalize()
        self.server = self.fixture.server()

    def on_pre_update(self, info, ecm):
        if info.paused:
            return
        world = World(world_entity(ecm))
        model = Model(world.model_by_name(ecm, "cart_pole"))
        self.cart = Link(model.link_by_name(ecm, "cart_link"))
        self.pole = Link(model.link_by_name(ecm, "pole_link"))
        self.cart.enable_velocity_checks(ecm)
        self.pole.enable_velocity_checks(ecm)
        if self.command == 1:
            self.cart.add_world_force(ecm, Vector3d(STRENGTH, 0, 0))
        elif self.command == 0:
            self.cart.add_world_force(ecm, Vector3d(-STRENGTH, 0, 0))
        if self.set_angle:
            joint = Joint(model.joint_by_name(ecm, "pole_base"))
            joint.reset_position(ecm, [self.init_angle])
            self.set_angle = False
        if self.init_ticks > 0:
            self.cart.add_world_force(ecm, Vector3d(self.init_push, 0, 0))
            self.init_ticks -= 1

    def on_post_update(self, info, ecm):
        if info.paused or self.pole is None:
            return
        pole_angle = self.pole.world_pose(ecm).rot().euler().y()
        w = self.pole.world_angular_velocity(ecm)
        pole_ang_vel = w.y() if w is not None else 0.0
        cart_x = self.cart.world_pose(ecm).pos().x()
        v = self.cart.world_linear_velocity(ecm)
        cart_vel = v.x() if v is not None else 0.0

        self.state = np.array([cart_x, cart_vel, pole_angle, pole_ang_vel],
                              dtype=np.float32)
        if not self.terminated:
            self.terminated = abs(pole_angle) > 0.48 or abs(cart_x) > X_LIMIT
        self.reward = 0.0 if self.terminated else 1.0

    def reset(self, *, seed=None, options=None):
        super().reset(seed=seed)
        self.server.reset_all()
        self.command = None
        self.terminated = False
        self.steps = 0
        self.init_angle = float(self.np_random.uniform(-ANGLE_RANGE, ANGLE_RANGE))
        self.init_push = float(self.np_random.choice(CART_PUSHES))
        self.init_ticks = STEPS_PER_ACTION
        self.set_angle = True
        self.server.run(True, STEPS_PER_ACTION, False)
        return self.state, {}

    def step(self, action):
        self.command = int(action)
        self.server.run(True, STEPS_PER_ACTION, False)
        self.steps += 1
        truncated = (not self.terminated) and self.steps >= MAX_EPISODE_STEPS
        return self.state, self.reward, self.terminated, truncated, {}


class EvalCartEnv(CartEnv):
    def __init__(self):
        super().__init__(sdf=EVAL_SDF)
        self.eval_idx = 0

    def reset(self, *, seed=None, options=None):
        seed = EVAL_SEED + (self.eval_idx % (EVAL_EPISODES + 1))
        self.eval_idx += 1
        return super().reset(seed=seed, options=options)


def run_gui():
    base = os.path.join(get_install_prefix(), "libexec", "gz", "sim10",
                        "gz-sim-gui-client")
    return subprocess.Popen(base)


def show_best(env, model_path):
    model = PPO.load(model_path, device="cpu")
    gui = run_gui()
    time.sleep(10)
    print("Showing the best model. Ctrl+C to exit.")
    try:
        obs, _ = env.reset()
        while True:
            action, _ = model.predict(obs, deterministic=True)
            obs, _, terminated, truncated, _ = env.step(int(action))
            time.sleep(ACTION_MS / 1000)
            if terminated or truncated:
                obs, _ = env.reset()
    except KeyboardInterrupt:
        pass
    finally:
        gui.terminate()


if __name__ == "__main__":
    env = CartEnv()
    check_env(env)
    print("check_env OK")

    eval_env = EvalCartEnv()

    model = PPO("MlpPolicy", env, verbose=1, device="cpu")

    eval_cb = EvalCallback(
        eval_env,
        n_eval_episodes=EVAL_EPISODES,
        eval_freq=EVAL_FREQ,
        deterministic=True,
        best_model_save_path=BEST_DIR,
        log_path=BEST_DIR,
        verbose=1,
    )
    model.learn(total_timesteps=TOTAL_STEPS, callback=eval_cb)

    show_best(env, os.path.join(BEST_DIR, "best_model"))

Here is a video showing the agent in operation with the new training code.

With this improved base version and the most fundamental concepts learned from RL, the project can move forward in several directions. The first is integrating ROS with Gymnasium. Beyond that, it opens the door to exploring more RL concepts, such as adding perturbations (noise) during training, and to studying how RL relates to computer vision.

This post is licensed under CC BY 4.0 by the author.