Balance a Machine in Simulation
Train and stress-test CartPole policies with domain-randomized physics.
Introduction
30 Second Summary
In ETH Zürich's official loader video, a 5-tonne skid-steer loader performs controlled swing-ups. It completed 23 of 23 attempts across the 28° and 31° configurations, with 11 of 11 successes at 28° and 12 of 12 at 31°.
In this project, you will use reinforcement learning to teach a simulated cart to balance a pole. You will expose a PPO policy's failure under changed physics, then use domain randomization to train a more robust policy.
What You'll Build
You will demo a balancing policy under familiar physics, watch it fail when the pole changes, and reveal a second policy that survives the same stress test.
By the end of this project, you'll have:
- A visible random-action baseline where the cart pushes left or right until the pole falls, with the final score printed in your terminal.
- A saved PPO balancing policy that keeps the default pole upright and earns a measured score out of 500.
- A failure-then-fix stress test showing the plain policy struggle at pole half-length 1.5, followed by a randomized-physics policy tested at half-lengths 0.5, 1.0, and 1.5.
- Secret Mission: Use SAC to train a continuous-torque policy that swings up a pendulum in Pendulum-v1.
What Connects the Loader to This Project?
The policy did not observe the arm configuration, which was randomized between 29° and 31° during training.
The loader research used its own RaiSim-based stack, with none of this project's CartPole-v1, Gymnasium, or Stable-Baselines3 setup.
Before We Start
Before the hands-on work begins, lock in the experiment you are about to build. You will create a brittle default-physics policy first, then use its failure on unfamiliar physics to motivate more robust randomized training.
Set Up Your Tools
Starting from an empty computer should not block the balancing experiment. This step creates one verified toolchain for every script that follows.
You'll use Claude Code to generate files from your terminal. An isolated Python environment keeps this project's packages separate from the rest of your computer.
In this step, get ready to:
- Install Claude Code. Verify its version and authenticate with your paid plan.
- Install Python 3.14.10. Activate an isolated environment inside teach-machine-balance.
- Create requirements.txt. Install every pinned package and keep Claude Code open from the project folder.
Install and authenticate Claude Code
Claude Code reads your project files from the folder where you start it. Installing it first gives you the coding assistant that creates the experiment files later.
macOS
- Open macOS Terminal.
- Press Cmd+Space to open Spotlight.
- Type Terminal into the search field.
- Press Enter to open macOS Terminal.
- Install Claude Code by running this command:
curl -fsSL https://claude.ai/install.sh | bash
What does this command do?
- The curl portion downloads the official Claude Code installer.
- The bash portion runs the downloaded installer.
You should see the installation finish without a failure message.
- Open a fresh macOS Terminal window.
- Close the current macOS Terminal window.
- Press Cmd+Space to open Spotlight again.
- Type Terminal into the search field.
- Press Enter to open a fresh macOS Terminal window.
- Verify the Claude Code installation by running this command:
claude --version
What does this command do?
The version check asks the installed Claude Code command to identify itself. A printed version number confirms your fresh terminal can find it.
You should see a Claude Code version number in the terminal.
- Start Claude Code by running this command:
claude
What does this command do?
The command starts Claude Code in your terminal. The first session opens a browser flow so you can connect your existing paid plan.
- Complete the browser sign-in flow with your existing paid plan.
You should return to an authenticated Claude Code session in the terminal.
- Close this terminal window after the authenticated Claude Code session opens.
Windows
- Open Windows PowerShell.
- Press the Windows key to open search.
- Type PowerShell into the search field.
- Press Enter to open Windows PowerShell.
- Install Claude Code by running this command:
irm https://claude.ai/install.ps1 | iex
What does this command do?
- The irm portion downloads the official Claude Code installer script.
- The iex portion runs the downloaded installer script.
You should see the installation finish without a failure message.
- Open a fresh Windows PowerShell window.
- Close the current Windows PowerShell window.
- Press the Windows key to open search again.
- Type PowerShell into the search field.
- Press Enter to open a fresh Windows PowerShell window.
- Verify the Claude Code installation by running this command:
claude --version
What does this command do?
The version check asks the installed Claude Code command to identify itself. A printed version number confirms your fresh terminal can find it.
You should see a Claude Code version number in Windows PowerShell.
- Start Claude Code by running this command:
claude
What does this command do?
The command starts Claude Code in Windows PowerShell. The first session opens a browser flow so you can connect your existing paid plan.
- Complete the browser sign-in flow with your existing paid plan.
You should return to an authenticated Claude Code session in Windows PowerShell.
- Close this Windows PowerShell window after the authenticated Claude Code session opens.
Create an isolated Python environment
A virtual environment gives this project its own Python packages. This prevents another project from changing the versions used by the balancing experiment.
macOS
- Open the Python downloads page in your browser.
- Download the Python 3.14.10 installer for macOS.
- Find the Python 3.14.10 release on the downloads page.
- Choose the macOS installer from that release.
- Install Python 3.14.10 with the downloaded installer.
- Open the downloaded installer from your Downloads folder.
- Complete the installer using its default choices.
Before you check, which Python version do you expect the fresh installation to report?
- Open a fresh macOS Terminal window.
- Press Cmd+Space to open Spotlight.
- Type Terminal into the search field.
- Press Enter to open macOS Terminal.
- Check the installed Python version by running this command:
python3 --version
What does this command do?
The command prints the version attached to the macOS python3 executable. This catches an older installation before it creates your virtual environment.
You should see Python 3.14.10.
✔️ I see Python 3.14.10
Your Python installation is ready to create this project's virtual environment.
ⓧ I see an older version
Your terminal is finding an older Python installation.
- Return to the Python downloads page.
- Install Python 3.14.10 for macOS.
- Open another fresh macOS Terminal window.
- Repeat the Python version check before continuing.
ⓧ Python is not found
The installer did not make Python available to this terminal.
- Return to the Python downloads page.
- Run the Python 3.14.10 macOS installer again.
- Open another fresh macOS Terminal window.
- Repeat the Python version check before continuing.
- Create the teach-machine-balance folder on your Desktop by running these commands:
cd ~/Desktop
mkdir teach-machine-balance
cd teach-machine-balance
What do these commands do?
- The first command moves your terminal to the Desktop.
- The second command creates the teach-machine-balance folder.
- The final command moves your terminal into the new folder.
- Create and activate the macOS virtual environment by running these commands:
python3 -m venv venv
source venv/bin/activate
What do these commands do?
- The first command creates an isolated environment in the venv folder.
- The second command activates that environment for the current terminal session.
Your terminal prompt should now begin with (venv).
Windows
- Open the Python downloads page in your browser.
- Download the Python 3.14.10 installer for Windows.
- Find the Python 3.14.10 release on the downloads page.
- Choose the Windows installer from that release.
- Install Python 3.14.10 with the downloaded installer.
- Open the downloaded installer from your Downloads folder.
- Complete the installer using its default choices.
Before you check, which Python version do you expect the fresh installation to report?
- Open a fresh Windows PowerShell window.
- Press the Windows key to open search.
- Type PowerShell into the search field.
- Press Enter to open Windows PowerShell.
- Check the installed Python version by running this command:
python --version
What does this command do?
The command prints the version attached to the Windows python executable. This catches an older installation before it creates your virtual environment.
You should see Python 3.14.10.
✔️ I see Python 3.14.10
Your Python installation is ready to create this project's virtual environment.
ⓧ I see an older version
Windows PowerShell is finding an older Python installation.
- Return to the Python downloads page.
- Install Python 3.14.10 for Windows.
- Open another fresh Windows PowerShell window.
- Repeat the Python version check before continuing.
ⓧ Python is not found
The installer did not make Python available to Windows PowerShell.
- Return to the Python downloads page.
- Run the Python 3.14.10 Windows installer again.
- Open another fresh Windows PowerShell window.
- Repeat the Python version check before continuing.
- Create the teach-machine-balance folder on your Desktop by running these commands:
cd ~/Desktop
mkdir teach-machine-balance
cd teach-machine-balance
What do these commands do?
- The first command moves Windows PowerShell to the Desktop.
- The second command creates the teach-machine-balance folder.
- The final command moves Windows PowerShell into the new folder.
- Create and activate the Windows virtual environment by running these commands:
python -m venv .venv
.venv\Scripts\activate
What do these commands do?
- The first command creates an isolated environment in the .venv folder.
- The second command activates that environment for the current Windows PowerShell session.
Your Windows PowerShell prompt should now begin with (.venv).
Before you run the environment check, do you expect both commands to print version numbers from inside the project environment?
- Verify Claude Code and Python inside the activated project environment by running these commands:
claude --version
python --version
What do these commands do?
The first command confirms Claude Code remains available inside the project environment. The second command confirms the activated environment uses the pinned Python release.
Both commands should print version numbers. Python should report 3.14.10.
Install the project dependencies
The project pins every package version so the generated scripts use one consistent set of APIs. The dependency file records that toolchain in a form you can inspect later.
- Start Claude Code from the teach-machine-balance folder by running this command:
claude
What does this command do?
Claude Code uses the current folder as its project context. Starting it here keeps every generated file inside teach-machine-balance.
You should see an authenticated Claude Code session open from the project folder.
- Ask Claude Code to create requirements.txt in the current folder with the exact contents below:
stable-baselines3==2.9.2
gymnasium[classic-control]==1.4.0
torch==2.15.0
pygame-ce==2.5.8
What does this file do?
- The Stable-Baselines3 pin provides PPO and the policy tools at version 2.9.2.
- The Gymnasium pin provides CartPole plus classic-control rendering at version 1.4.0.
- The PyTorch pin provides the learning runtime at version 2.15.0.
- The pygame-ce pin provides the simulation window at version 2.5.8.
- Ask Claude Code to confirm that requirements.txt contains exactly four lines.
Claude Code should confirm that requirements.txt exists in teach-machine-balance with the four pinned entries.
- Ask Claude Code to install the pinned packages by running this command:
python -m pip install stable-baselines3==2.9.2 "gymnasium[classic-control]==1.4.0" torch==2.15.0 pygame-ce==2.5.8
What does this command do?
The command uses the activated environment's Python interpreter to run pip. Each package receives the exact version recorded in requirements.txt.
- Approve Claude Code's request to run the installation command if it asks for permission.
You should see the package installation complete without a failure message.
Package installation failed?
Confirm your terminal prompt shows the active virtual environment. Check that Python reports 3.14.10 before asking Claude Code to retry the same installation command.
Help me diagnose this package installation
Use these tabs to compare the finished dependency file before the final check.
✔️ Awesome, I've got everything!
Great. Confirm that Claude Code saved requirements.txt in the teach-machine-balance folder.
ⓧ I'd like to double check the full code
stable-baselines3==2.9.2
gymnasium[classic-control]==1.4.0
torch==2.15.0
pygame-ce==2.5.8
Before the final check, do you expect Claude Code and Python to report their versions from this project environment?
- Ask Claude Code to run these final verification commands without editing any files:
claude --version
python --version
What do these commands do?
These checks confirm that Claude Code can run from the project folder. They also confirm that the active environment still uses the pinned Python release.
Both commands should print version numbers. Python should report 3.14.10 while Claude Code remains open in teach-machine-balance.
Your isolated toolchain is ready. Every balancing script can now use the same verified packages.
Your tools are installed and Claude Code is waiting in the project folder. Next up, you'll watch random actions make the pole wobble and fall.
Watch the Pole Fall
Your isolated toolchain is ready. Now you'll use Claude Code to build the first visible experiment.
A random agent makes the need for a learned policy visible through failure.
In this step, get ready to:
- Create watch_fall.py with a seeded random agent.
- Confirm that the script handles reset plus both episode-ending signals.
- Run the simulation to capture the falling pole plus its printed baseline score.
Create the random-policy script
The Gymnasium CartPole-v1 environment turns the experiment into a visible cart-and-pole problem. This gives you a concrete baseline before training begins.
- In the Claude Code session from the previous step, ask it to create watch_fall.py so the file matches the reference below.
- Approve the file edit if Claude Code asks for permission.
You should see watch_fall.py appear inside the teach-machine-balance folder.
- Ask Claude Code to explain the four observations in beginner language.
- Ask Claude Code to explain the two actions in beginner language.
- Ask Claude Code to explain how the one-point-per-step reward becomes the score.
You should get a beginner explanation of the four observation values.
You should get a second explanation of the two available pushes.
You should get a final explanation of the one-point reward.
- Compare Claude Code's result with the complete watch_fall.py reference below.
✔️ I'll try it first
Check each line in your new file before opening the full reference.
ⓧ Let me check my work
import gymnasium as gym
env = gym.make("CartPole-v1", render_mode="human")
env.action_space.seed(42)
env.reset(seed=42)
score = 0.0
while True:
action = env.action_space.sample()
_, reward, terminated, truncated, _ = env.step(action)
score += float(reward)
if terminated or truncated:
break
env.close()
print(f"Random policy score: {score:.0f}/500")
What does this code do?
- The gym.make("CartPole-v1") call creates the cart-and-pole simulation.
- The human rendering mode displays the simulation in a window.
- The four observation values describe cart position, cart velocity, pole angle, plus pole angular velocity.
- The two available actions push the cart left or right.
- The env.action_space.sample() call chooses each push randomly.
- Each env.step(action) call gives the agent one reward point while the episode continues.
- The terminated plus truncated values tell the loop when the episode has ended.
- The env.close() call closes the simulation after the episode.
Check the environment loop
Gymnasium separates a natural episode ending from a time-limit ending. The loop must handle both for every episode to close cleanly.
- Ask Claude Code to check env.reset(seed=42) against the current Gymnasium reset API.
- Ask Claude Code to check the assignment containing env.step(action) against the current Gymnasium step API.
- Ask Claude Code to confirm that terminated can stop the loop.
- Ask Claude Code to confirm that truncated can stop the loop.
- Tell Claude Code to leave the current packages unchanged during this review.
- Tell Claude Code to leave every other project file unchanged during this review.
Claude Code should confirm that the file handles the current reset result.
Claude Code should also confirm that the file handles the current step result.
Watch the designed failure
Random sampling ignores the observation. Each push is disconnected from the pole's motion.
- Before you run the script, predict whether random pushes can keep the pole upright for all 500 steps.
- Run the simulation from the activated project environment with this command:
python watch_fall.py
What does this command do?
The python command uses your activated environment to execute watch_fall.py.
The script opens the rendered simulation. It prints the episode score after the pole falls.
You'll see a CartPole window where random left-or-right pushes make the pole wobble before it falls.
The terminal then prints a line beginning with Random policy score: plus a score ending with /500.
That fall gives you a no-learning baseline for the policy you train next.
- Record the number from the printed line here: your random policy score.
Does the CartPole window fail to open?
- Confirm that the activated environment name still appears in your terminal prompt.
- Return to the dependency installation from Step 1 if Python reports a missing rendering package.
Help me diagnose the missing CartPole window.
Your random agent has exposed the problem. Next, you'll train a policy that reacts to the pole's motion.
Train and Score a Policy
Your random-action baseline made the problem visible. The pole falls because no action responds to its movement.
A PPO policy learns to react to the pole's motion where random pushes failed.
A saved model becomes useful when its behavior can be watched and measured. A deterministic evaluation lets you test the same learned policy without random action choices.
In this step, get ready to:
- Train a PPO policy on default CartPole physics for 50,000 timesteps and see its training logs.
- Save the trained policy as cartpole_ppo.zip.
- Watch one deterministic episode and measure a ten-episode mean score out of 500.
Train the plain PPO policy
The Gymnasium environment supplies observations and rewards. Stable-Baselines3 uses that experience to update the policy on the default physics.
- Ask Claude Code to create train.py with exactly this code:
import gymnasium as gym
from stable_baselines3 import PPO
env = gym.make("CartPole-v1")
model = PPO("MlpPolicy", env, verbose=1, seed=42, device="cpu")
model.learn(total_timesteps=50_000)
model.save("cartpole_ppo")
env.close()
print("Saved cartpole_ppo.zip")
What does this code do?
- The environment provides the default CartPole-v1 observations and rewards.
- The model uses an MlpPolicy with seed 42 on the CPU.
- The learning run collects 50,000 timesteps of experience before saving the policy.
- The final print confirms that cartpole_ppo.zip exists.
✔️ Awesome, I've got everything!
Your train.py file matches the training script above.
ⓧ I'd like to double check the full code
import gymnasium as gym
from stable_baselines3 import PPO
env = gym.make("CartPole-v1")
model = PPO("MlpPolicy", env, verbose=1, seed=42, device="cpu")
model.learn(total_timesteps=50_000)
model.save("cartpole_ppo")
env.close()
print("Saved cartpole_ppo.zip")
Before you run it, consider whether the PPO log will stay silent or update throughout learning.
- Train the plain policy by running this command:
python train.py
What does this command do?
Python runs train.py. The script trains the model before saving it as cartpole_ppo.zip.
You'll see PPO training logs update during the run. The final line says Saved cartpole_ppo.zip.
That is the main training run complete. Your first learned balancing policy is now saved for evaluation.
Training does not finish?
- Confirm that Claude Code is still using the activated teach-machine-balance environment.
- Confirm that the packages from requirements.txt remain installed in that environment.
Ask for help with the training run.
Watch one deterministic episode
A deterministic policy selects its preferred action for each observation. Watching one episode shows how those learned choices behave on the same default physics used during training.
- Ask Claude Code to create watch_and_score.py with this first runnable section:
import gymnasium as gym
from stable_baselines3 import PPO
from stable_baselines3.common.evaluation import evaluate_policy
from stable_baselines3.common.monitor import Monitor
model = PPO.load("cartpole_ppo")
watch_env = gym.make("CartPole-v1", render_mode="human")
observation, _ = watch_env.reset(seed=42)
watched_score = 0.0
while True:
action, _ = model.predict(observation, deterministic=True)
observation, reward, terminated, truncated, _ = watch_env.step(action)
watched_score += float(reward)
if terminated or truncated:
break
watch_env.close()
What does this code do?
- The script loads cartpole_ppo.zip without training another model.
- The human render mode opens a visible CartPole window during each environment step.
- Deterministic prediction selects the policy's preferred action for each observation.
- The loop stops when the episode terminates or reaches its time limit.
Before you run this first section, consider how the learned policy will look beside the random-action baseline.
- Watch the learned policy by running this command:
python watch_and_score.py
What does this command do?
Python loads the saved model and runs one rendered episode. The script closes the window when that episode ends.
You'll see the cart make deterministic left-or-right pushes while the pole stays upright for much longer than it did under random actions.
Add the ten-episode score
One watched episode gives you a useful demonstration. Ten unrendered episodes provide a broader mean score without making you wait for ten animation windows.
- Ask Claude Code to append this evaluation section below watch_env.close() in watch_and_score.py exactly as shown:
evaluation_env = Monitor(gym.make("CartPole-v1"))
mean_score, score_spread = evaluate_policy(
model,
evaluation_env,
n_eval_episodes=10,
deterministic=True,
)
evaluation_env.close()
print(f"Watched episode score: {watched_score:.0f}/500")
print(f"Ten-episode mean: {mean_score:.1f}/500 (+/- {score_spread:.1f})")
if mean_score < 475:
print("Score is below 475. Rerun train.py once, then score this policy again.")
else:
print("Score is at least 475. Continue to the altered-physics test.")
What does this code do?
- The monitored environment records complete episode returns during evaluation.
- The evaluator measures ten deterministic episodes and returns their mean score with the score spread.
- The watched score and ten-episode mean are printed out of the 500-step limit.
- The final condition applies the project's one-retry rule when the mean is below 475.
✔️ Awesome, I've got everything!
Your complete watch_and_score.py file now watches one episode and evaluates ten more.
ⓧ I'd like to double check the full code
import gymnasium as gym
from stable_baselines3 import PPO
from stable_baselines3.common.evaluation import evaluate_policy
from stable_baselines3.common.monitor import Monitor
model = PPO.load("cartpole_ppo")
watch_env = gym.make("CartPole-v1", render_mode="human")
observation, _ = watch_env.reset(seed=42)
watched_score = 0.0
while True:
action, _ = model.predict(observation, deterministic=True)
observation, reward, terminated, truncated, _ = watch_env.step(action)
watched_score += float(reward)
if terminated or truncated:
break
watch_env.close()
evaluation_env = Monitor(gym.make("CartPole-v1"))
mean_score, score_spread = evaluate_policy(
model,
evaluation_env,
n_eval_episodes=10,
deterministic=True,
)
evaluation_env.close()
print(f"Watched episode score: {watched_score:.0f}/500")
print(f"Ten-episode mean: {mean_score:.1f}/500 (+/- {score_spread:.1f})")
if mean_score < 475:
print("Score is below 475. Rerun train.py once, then score this policy again.")
else:
print("Score is at least 475. Continue to the altered-physics test.")
Before the final run, consider whether one watched episode or the ten-episode mean will give you the steadier measure of the policy.
- Watch and score the completed policy by running this command:
python watch_and_score.py
What does this command do?
The command runs one rendered episode before evaluating ten deterministic episodes without rendering. It then prints both measurements in the terminal.
You'll see the rendered policy balance before the terminal prints Watched episode score and Ten-episode mean values out of 500.
The supplied reference run reached a ten-episode mean of 500.0 out of 500. This is a reference-run result. Your measured score can vary.
- Continue with the saved policy if the ten-episode mean is at least 475.
- Ignore one weak watched episode when the ten-episode mean is at least 475.
- Retrain the policy once if the ten-episode mean is below 475 by running these commands:
python train.py
python watch_and_score.py
What do these commands do?
- The first command performs the single allowed retry and replaces cartpole_ppo.zip with the newly trained policy.
- The second command watches the replacement policy and calculates its ten-episode mean.
After the retry, keep the second policy and continue with its measured score. Do not train several seeds or compare seed results.
Your plain policy now balances and has a measured default-physics score. Next, you'll change the physics and discover where this trained policy stops generalizing.
Test Unseen Physics
Your plain PPO policy has already balanced the default pole across deterministic evaluations. Now you will test whether that success survives unfamiliar physics.
The plain policy has never seen a pole half-length of 1.5, so this test reveals whether its default-physics success survives unfamiliar dynamics.
In this step, get ready to:
- Stress-test cartpole_ppo.zip at pole half-lengths 0.5, 1.0, and 1.5. Its result at 1.5 is recorded.
- Train cartpole_random.zip across random pole half-lengths from 0.25 to 1.25. The model file is saved.
- Compare both policies at all three test lengths. The randomized policy is rendered at 1.5.
Stress-test the plain policy
Changing the pole length also changes how its mass affects motion. The test must update both length and polemass_length to keep the simulated physics consistent.
- Ask Claude Code to create stress_test.py with deterministic ten-episode evaluations of cartpole_ppo.zip at half-lengths 0.5, 1.0, and 1.5. The script must update polemass_length, render the plain policy at 1.5, and stop after giving the next command when cartpole_random.zip is missing.
The reference below is your checkpoint for the generated file.
✔️ I'll try it first
Claude Code has enough detail to create the stress test. Continue when stress_test.py is ready.
ⓧ Let me check my work
- Compare stress_test.py with the full reference below.
- Replace any mismatched lines in stress_test.py with the reference version.
from pathlib import Path
import gymnasium as gym
from stable_baselines3 import PPO
HALF_LENGTHS = (0.5, 1.0, 1.5)
EPISODE_SEEDS = tuple(range(10))
def make_cartpole(half_length, render_mode=None):
env = gym.make("CartPole-v1", render_mode=render_mode)
cartpole = env.unwrapped
cartpole.length = half_length
cartpole.polemass_length = cartpole.masspole * cartpole.length
return env
def score_policy(model, half_length):
scores = []
for episode_seed in EPISODE_SEEDS:
env = make_cartpole(half_length)
observation, _ = env.reset(seed=episode_seed)
score = 0.0
while True:
action, _ = model.predict(observation, deterministic=True)
observation, reward, terminated, truncated, _ = env.step(action)
score += float(reward)
if terminated or truncated:
break
env.close()
scores.append(score)
return sum(scores) / len(scores)
def print_scores(label, model):
results = {}
for half_length in HALF_LENGTHS:
results[half_length] = score_policy(model, half_length)
print(label)
print("half-length | mean score")
print("------------|-----------")
for half_length, mean_score in results.items():
print(f"{half_length:>11.1f} | {mean_score:>10.1f}")
return results
def watch_policy(label, model, half_length):
print(f"Watching {label} at half-length {half_length:.1f}")
env = make_cartpole(half_length, render_mode="human")
observation, _ = env.reset(seed=42)
while True:
action, _ = model.predict(observation, deterministic=True)
observation, _, terminated, truncated, _ = env.step(action)
if terminated or truncated:
break
env.close()
plain_model = PPO.load("cartpole_ppo")
plain_results = print_scores("Plain policy: cartpole_ppo.zip", plain_model)
watch_policy("cartpole_ppo.zip", plain_model, 1.5)
if plain_results[1.5] < 500:
print("Expected failure observed: cartpole_ppo.zip fell before 500 at 1.5.")
else:
print("This run reached 500 at 1.5; keep the reference failure as the lesson and continue with domain randomization.")
if not Path("cartpole_random.zip").exists():
print("Run python train_random.py, then run python stress_test.py again.")
raise SystemExit
random_model = PPO.load("cartpole_random")
print_scores("Randomized policy: cartpole_random.zip", random_model)
watch_policy("cartpole_random.zip", random_model, 1.5)
What does this code do?
- The make_cartpole() function changes both physics fields before returning each Gymnasium environment.
- The score_policy() function averages ten deterministic episodes for one half-length.
- The script scores the plain model first. It pauses before the randomized comparison when the second model does not exist.
Before you run the stress test, do you think a policy trained only on default physics can balance all three pole lengths?
- Run the first altered-physics test by using this command:
python stress_test.py
What does this command do?
This runs the three plain-policy evaluations. It then renders the plain policy at half-length 1.5.
You will see a plain-policy score table. A CartPole window then shows how the policy behaves with the longer pole.
A score below 500 at half-length 1.5 prints Expected failure observed: cartpole_ppo.zip fell before 500 at 1.5. If your run reaches 500, the script reports the permitted alternate and continues the lesson.
Does the stress test stop early?
Check that cartpole_ppo.zip remains inside the teach-machine-balance folder. Compare stress_test.py with the full reference if Python points to a mismatched line.
Ask for targeted help with the failing line: Help me debug my first stress_test.py run without changing its intended behavior.
Train across randomized physics
Domain randomization exposes one policy to many versions of the environment during training. The RandomPoleLength wrapper draws a fresh half-length on every reset.
The wrapper samples from 0.25 to 1.25. It updates polemass_length before the next episode begins.
- Ask Claude Code to create train_random.py with a RandomPoleLength wrapper that samples self.np_random.uniform(0.25, 1.25), updates polemass_length, records info["pole_half_length"], trains for 50_000 timesteps, and saves cartpole_random.zip.
The reference below is your checkpoint for the randomized training file.
✔️ I'll try it first
Continue when Claude Code has created train_random.py with the requested wrapper and training run.
ⓧ Let me check my work
- Compare train_random.py with the full reference below.
- Replace any mismatched lines in train_random.py with the reference version.
import gymnasium as gym
from stable_baselines3 import PPO
class RandomPoleLength(gym.Wrapper):
def reset(self, *, seed=None, options=None):
observation, info = super().reset(seed=seed, options=options)
half_length = float(self.np_random.uniform(0.25, 1.25))
cartpole = self.unwrapped
cartpole.length = half_length
cartpole.polemass_length = cartpole.masspole * cartpole.length
info["pole_half_length"] = half_length
return observation, info
env = RandomPoleLength(gym.make("CartPole-v1"))
model = PPO("MlpPolicy", env, verbose=1, seed=42, device="cpu")
model.learn(total_timesteps=50_000)
model.save("cartpole_random")
env.close()
print("Saved cartpole_random.zip")
What does this code do?
- The wrapper changes the pole half-length each time the environment resets.
- The model experiences many physics configurations during its 50_000 training timesteps.
- The final policy is saved separately as cartpole_random.zip.
This is the longest wait in this step. Training can take several minutes while the PPO logs show the model progressing through its timesteps.
- Train the randomized-physics policy once by running this command:
python train_random.py
What does this command do?
This starts a fresh PPO training run inside the randomized wrapper. Each reset gives the model another pole half-length to handle.
You will see PPO training logs until the model reaches at least 50_000 timesteps. The final line is Saved cartpole_random.zip.
That is the new policy trained. cartpole_random.zip now contains experience from changing pole physics.
Training does not save the model?
Keep the terminal open until the 50_000 timestep run finishes. Check that model.save("cartpole_random") matches the reference.
Get help with the training failure: Help me debug train_random.py without changing the wrapper or training settings.
Compare both policies
The same stress test now detects cartpole_random.zip. It preserves the plain-policy results before evaluating the randomized policy under identical test lengths.
Before you run the final comparison, which policy do you expect to handle half-length 1.5 for longer?
- Run the final side-by-side stress test by using this command:
python stress_test.py
What does this command do?
The script repeats the plain-policy table. It then adds the randomized-policy table before rendering cartpole_random.zip at half-length 1.5.
You will see separate score tables for cartpole_ppo.zip and cartpole_random.zip at half-lengths 0.5, 1.0, and 1.5.
In the reference run, cartpole_ppo.zip scored 500.0 at 0.5 and 1.0. It failed before 500 at 1.5.
In the same reference run, cartpole_random.zip scored 500.0 at all three test lengths. These values are reference-run results, so keep your own measured scores.
You have completed the failure-then-fix experiment. The plain and randomized policies now face the same unfamiliar physics in one comparison.
What does the comparison prove?
Success on default physics does not guarantee success after the dynamics change. The first stress test exposes that simulation gap.
Training across randomized half-lengths gives the second policy broader experience. That broader experience improves its chance of handling physics outside its training range.
- Keep both saved models unchanged after the altered-physics comparison. A low stress-test score is not a reason to retrain.
- Keep this as a single-seed experiment. Skip multi-seed comparisons.
Secret mission
Secret Mission: Swing up a pendulum with SAC
CartPole gave your policies two fixed actions. Extend the experiment by training SAC to choose continuous torque in Pendulum-v1, save the policy, and watch it control a rotating pendulum.
Clean Up Your Resources
Clean Up Your Resources
Every project resource runs locally, so there are no ongoing cloud costs beyond your existing paid Claude plan. Choose whether to keep the files, pause the active session, or delete the experiment from your machine.
Resources you used:
- Local teach-machine-balance folder containing the complete experiment.
Keep everything running
Keeping the experiment requires no further action. Choose this option if you want to rerun the simulations or compare the saved policies later.
- Keep cartpole_ppo.zip for the familiar-physics baseline.
- Keep cartpole_random.zip for randomized-physics comparisons.
- Keep pendulum_sac.zip for the continuous-control extension.
The experiment uses local disk space only. Your existing paid Claude plan remains unchanged.
Pause - I'll come back to this later
Pausing ends the active local session while preserving every script and trained policy for later.
- Close any CartPole or Pendulum window that is still open.
- Close the terminal window running Claude Code.
No training or simulation process remains active. The teach-machine-balance folder stays unchanged.
Delete - I don't want to use this again
Deleting this experiment removes the local project folder from your machine. Your existing paid Claude plan remains unchanged.
Deletion Is Permanent
Deleting the folder permanently removes the complete local experiment. Copy anything you want to keep before continuing.
macOS
- Return to the shell prompt in the terminal running Claude Code.
- Leave the activated environment and remove the entire teach-machine-balance folder by running these commands:
deactivate
cd ..
rm -rf teach-machine-balance
What do these commands do?
- The first command leaves the virtual environment.
- The second command moves outside teach-machine-balance.
- The final command permanently removes the project folder.
A successful cleanup returns you to the prompt without an error. The teach-machine-balance folder is removed.
Windows
- Return to the shell prompt in the Windows PowerShell window running Claude Code.
- Leave the activated environment and remove the entire teach-machine-balance folder by running these commands:
deactivate
cd ..
Remove-Item -Recurse -Force teach-machine-balance
What do these commands do?
- The first command leaves the virtual environment.
- The second command moves outside teach-machine-balance.
- The final command permanently removes the project folder.
A successful cleanup returns you to the prompt without an error. The teach-machine-balance folder is removed.
Nice Work!
Nice Work!
Mission complete! You built a terminal-driven reinforcement learning experiment that makes brittle behavior visible. Your CartPole policies provide a small educational analogy to the ETH Zürich loader's randomized-training story.
What you learned:
- Built a visible random-action baseline that demonstrates why learning is necessary.
- Trained PPO on default physics to create cartpole_ppo.zip. Exposed its expected failure at pole half-length 1.5.
- Applied domain randomization across pole half-lengths from 0.25 to 1.25. Demonstrated how cartpole_random.zip survives tests at 0.5, 1.0, and 1.5.
- Secret Mission: Trained a SAC policy to control Pendulum-v1 with continuous torque. Watched its deterministic swing-up attempt over a 200-step episode.
Ready to quiz yourself?