← All projects
Complete · 9 build phases

RL gym from scratch

Reinforcement learning built brick by brick, where every agent is checked against the exact answer.

A hand-built gym in Python and NumPy: a Gymnasium-compatible environment, a planner that solves it exactly, and agents that learn it from experience, up to a DQN on CartPole. Built to understand RL from first principles, so every line is explainable.

The RL Playground in the browser: a 4×4 grid world coloured by learned value, with arrows showing the agent’s policy, and an agent panel with Q-learning selected, sliders for slip, exploration, learning rate and discount, 100% greedy success, and a return-per-episode chart approaching the optimal line
StackPython · NumPy · PyTorch · Gymnasium · JavaScript
AlgorithmsValue iteration, Q-learning, SARSA, Double Q-learning, DQN / Double DQN
Tested89 tests, plus Python ↔ JavaScript parity checks in CI
DemoOne static page on GitHub Pages: no server, works on phones
01

Planning checks learning

The project is built around one distinction. Value iteration knows the rules of the world and solves it exactly. Q-learning only sees samples of what happened, and has to learn from them. Here the planner is the checker and the learner is the maker.

The environment exposes its transition model even though real environments don’t, so learning is verified against ground truth rather than eyeballed. The environment mirrors Gymnasium’s API, so the same agent runs unchanged on Gymnasium’s FrozenLake: 100% on the deterministic map and about 73% on the slippery one, where optimal is about 74–82%.

02

Same cliff, two answers

One line of the update rule separates Q-learning from SARSA: score the next state by its best action, or by the action you will actually take. On the cliff map (Sutton & Barto, Example 6.6, 10 seeds), that line changes which path the agent learns.

Cliff walk grid after Q-learning: the greedy arrows go up one row from the start and run right along the cliff edge to the goal
1Q-learning walks the edge. The shortest path, 9 steps, right beside the cliff. It keeps falling off while it explores: about −26 average return during training.
Cliff walk grid after SARSA: the greedy arrows climb to the top row and go around, far from the cliff
2SARSA takes the long way. It learns 11 to 13 steps, one or two rows up, because its own exploration is part of the risk. It earns more while learning: about −15.
03

Measuring maximization bias

Q-learning’s max uses the same noisy estimates to pick an action and to score it, so it overestimates. Double Q-learning splits that across two tables. On Sutton & Barto’s Example 6.7, LEFT is the worse choice; with ε = 0.1 the best possible LEFT rate is 5%. Averaged over 1000 runs:

Peak % LEFTEpisodes 10–30Last 50 episodes
Q-learning95%93%15%
Double Q-learning62%54%7%

One seed is an anecdote

An earlier version claimed Q-learning overestimated the slippery grid. That was one run; over 10 seeds there was no overestimate, so Phase 7 uses an environment built to expose it.

The test had to see both branches

The first update test used r = 0, where one coin-flip branch’s correct answer is also 0. Using r = 1 and several seeds checks both.

DQN learned CartPole, then forgot it.

Every early configuration reached a high score and then un-learned it. Once the replay buffer filled with successful episodes, the network stopped seeing the failures that had taught it what to avoid. A bigger buffer helped on two seeds out of three and still collapsed.

What worked was a wider network, a higher learning rate, syncing the target network every 500 steps and training every 4, plus keeping the best checkpoint from a separate greedy evaluation. It hit 500, the maximum, on all three seeds and held there. One lucky seed had hit 500 under a config that failed on the other two, which is why every result here is reported across seeds.

Beforepeaked, then collapsed
After500 on 3 of 3 seeds
Also caughtstore terminated, not truncated: a time limit isn’t “game over”
05

A playground that can’t drift

The browser runs a JavaScript port

Tabular agents train instantly on the page. You can edit the map, switch algorithms, change slip, ε, α and γ, and compare against the optimal policy.

CI keeps the two copies honest

A parity test cuts the JS core out of the page, runs it in Node and checks it against the Python package: identical transition models, values within 1e-9, identical optimal policies, the same hand-computed updates.

No Pyodide, on purpose

Running the real Python in the browser would remove the port, but costs a ~10 MB download and seconds of loading on every visit: a bad trade for a link opened on a phone.

The playground on a phone: the title, a short explanation, and the 4×4 grid world with the learned policy arrows
06

Key engineering decisions

Mirror Gymnasium’s API

reset returns (obs, info) and step returns the 5-tuple, so agents port to the real library with zero changes.

The training loop lives outside agent and environment

The same train() works for any agent on any environment.

Random tie-breaking in argmax

A zero-initialized Q-table with np.argmax always picks action 0, which biases early exploration toward UP.

Loud failures over silent garbage

Invalid actions and out-of-order calls raise. A failure-path test caught GridWorld([]) silently loading the default map, because an empty list is falsy.

07 · Limitations
  • The playground covers the tabular agents only; DQN needs PyTorch, so it runs locally
  • Grid worlds and CartPole are small; nothing here is tested at scale
  • The JavaScript port is a second copy of the logic, kept in sync by tests rather than shared code
08 · Next
  • Policy gradients (REINFORCE), then PPO, the algorithm behind RLHF
  • The same DQN code on LunarLander
  • Policy iteration, compared with value iteration on sweeps to converge
  • A hyperparameter sweep over α and γ, with plotted curves