Code Architecture — Deep RL from Human Preferences
This document describes the notebook structure, key functions and classes, data flow, and the simplifications compared with the paper.
Notebook Structure
1. Setup & Imports
Imports gymnasium, PyTorch, NumPy and matplotlib. Pins CPU floating-point behaviour (MKL_CBWR=COMPAT, ATEN_CPU_CAPABILITY=default, one thread) so Kaggle runs give the same numbers on different machines. Seeds Python, NumPy and PyTorch with 42, turns on deterministic algorithms, sets JPEG figures at dpi 80, and registers the atexit hook that saves the executed notebook on Kaggle.
2. Hyperparameters
| Name | Value | |——|——-| | SEGMENT_LENGTH | 20 steps | | PREFERENCES_PER_ROUND | 20 pairs | | REWARD_MODEL_EPOCHS, RM_BATCH | 64 epochs, 16 pairs per minibatch | | FALL_PENALTY | −10 | | REWARD_MODEL_RETRAIN_EVERY | 5 iterations | | TOTAL_ITERATIONS, PPO_STEPS | 50, 2048 | | PPO_EPOCHS, PPO_CLIP | 4, 0.2 | | GAMMA, GAE_LAMBDA | 0.99, 0.95 | | LR_POLICY, LR_VALUE, LR_REWARD | 3e-4, 1e-3, 1e-3 | | ENTROPY_COEF, HIDDEN_DIM, HUMAN_NOISE | 0.01, 64, 0.0 |
3. PPO Agent
PolicyNetwork (4 → 64 → 64 → 2, tanh) and ValueNetwork (4 → 64 → 64 → 1), separate. PPOAgent has get_action (samples from a Categorical), compute_gae (GAE with done flags) and update (clipped surrogate, value MSE, entropy bonus, 4 epochs).
4. Reward Model
RewardModel: 4 → 64 → 64 → 1 MLP giving r̂(s) per state. train_reward_model sums r̂ over each segment and minimises binary_cross_entropy_with_logits(r̂_A − r̂_B, label) on minibatches of 16 pairs for 64 epochs (Bradley-Terry, Eq. 1); a tie has target 0.5. evaluate_reward_model gives the accuracy on pairs that are not ties.
5. Simulated Human Oracle (simulate_human_preference)
Scores each segment as the sum of true rewards plus −10 for the step where the pole fell (terminated), as in Appendix A. Returns 1, 0, or 0.5 for equal scores.
6. Trajectory Collection & Preference Elicitation
collect_trajectories: runs the policy for 2048 steps with seeded resets. The reward for PPO is r̂(s), normalised to zero mean and unit standard deviation over the batch (Section 2.2.1). Rollouts are cut into 20-step segments of (state, action, true reward, terminated).elicit_preferences: picks 20 random pairs of segments and asks the oracle.
7. Alternating RLHF Training Loop (train_rlhf)
Each iteration: collect → elicit 20 pairs → every 5 iterations, measure accuracy on the new pairs (before training on them), then retrain the reward model on all pairs → PPO update. GAE gets all-zero done flags, so the RLHF agent sees one continuous episode and learns nothing from terminations (Appendix A). Logs the true episode reward (never used for training), accuracies and the share of ties.
8. Baseline: PPO with True Reward (train_ppo_baseline)
The same PPO agent trained on CartPole’s true reward with normal episode ends.
9–10. Run RLHF Training / Run PPO Baseline
Run both loops; each prints progress every 10 iterations.
11. Evaluation & Visualization
Plots the true reward of both agents, reward-model accuracy (training pairs and new pairs), the number of preferences collected, and reward-model loss. Prints the accuracy on new pairs per retraining round and the share of ties in the first and last 10 iterations.
12. Evaluate Final Agents (evaluate_agent)
Runs each final policy (sampled actions) for 20 episodes with start seeds 1000 to 1019 and prints the mean ± standard deviation and the RLHF mean as a share of the baseline mean.
13. Summary
States the old oracle bug, the evaluation result (RLHF 190.4 ± 66.4 vs baseline 167.7 ± 49.2, with overlapping ranges and one seed), the reward model’s accuracy on new pairs, the growth in ties, and how this toy differs from the paper.
Data Flow / Shapes
env (CartPole-v1) → 2048 × (state[4], action, r̂(state), log π, V, done)
→ segments: lists of 20 × (state[4], action, true reward, terminated)
segments → oracle → (states_A[20, 4], states_B[20, 4], label ∈ {1, 0, 0.5})
all pairs → reward model → r̂: state[4] → scalar
r̂ (normalised) → GAE (no done flags) → PPO update
Deliberate Simplifications vs. Full Paper
| Aspect | Paper | This Notebook |
|---|---|---|
| Tasks | 8 MuJoCo tasks, 7 Atari games | CartPole-v1 |
| RL algorithm | TRPO (robotics), A2C (Atari) | PPO |
| Labels | real humans and a synthetic oracle | synthetic oracle with a fall penalty |
| Reward model | ensemble, 1/e held out, ℓ2 tuning, 10% random-answer model | one MLP on states, no regularization |
| Query selection | ensemble disagreement | random pairs |
| Processes | asynchronous | alternating in one loop |
| Scale | 700 to 5,500 human queries | 1,000 synthetic pairs, one seed |