Zero Labs
Industry News / AI

Apollo DQN: Building an RL Agent for LunarLander-v3

Source · Towards AI By Yaroslav Dubovikov

From the publisher’s feed, collected in the ZeroLabs newsroom.

Comparing DQN variants: training diagnostics and evaluation beyond raw reward (with human reference)Photo by NASA on UnsplashI trained an MLP-based agent to solve LunarLander-v3 (Gymnasium), experimenting with residual connections, prioritized replay, single vs. dueling heads, and DQN vs. Double DQN training.Instead of focusing only on average reward, I built a reproducible evaluation pipeline with fixed seeds, confidence intervals, and human-prefix rollouts to measure how well each policy generalizes under unseen initial conditions. The same framework can be applied to other Gymnasium tasks.My final agent is a lightweight model with Problem SetupI use the LunarLander-v3 environment from Gymnasium, a discrete-action, fully observed Markov Decision Process with an 8-dimensional state. To speed up interaction, frame skipping of 4 steps is applied, effectively increasing environment throughput without changing the underlying task.At the start of each episode the lander is initialized above the surface with a small random push. The agent can either do nothing or fire one of three thrusters. The objective is to land within the target zone while maintaining low velocity and stable orientation. The moon surface changes every run.The reward function combines shaping terms (velocity, tilt, distance to target), time and fuel penalties, a bonus for each leg touchdown, and a strong penalty when lander’s body contacts the ground.The agent learns an approximation of the action-value function Q(s, a) using value-based, model-free reinforcement learning (DQN family). The policy is derived greedily from the learned Q-function.Since I’m not a big gamer, the human baseline consists of 500 manually played episodes (5 x 100) by an EU Top 500 Overwatch 2 player, serving as a strong reference for comparison.Model & Training DesignStandard DQN is known to overestimate Q-values because the same network is used both to select and evaluate actions. To address this, I use Double DQN, where the student network selects the action and a separate teacher network evaluates it.The base architecture is a Residual MLP (ResMLP). A plain feedforward network quickly drifts and suffers from gradient attenuation. Residual connections introduce skip paths that allow gradients to propagate more directly and reduce saturation in Tanh activations (see Training Diagnostics, Figure 2).Figure 1. Architecture of the ResMLP agent with single-head and dueling-head variants. “A” denotes the aggregation operation. (Image by Author)The network consists of a projection layer followed by two residual blocks. On top of this backbone I experiment with two heads:a single head producing Q(s, a),a dueling head that separately estimates the state value V(s) and action advantages A(s, a), which are then aggregated into Q(s, a).The dueling formulation is useful when many actions have similar effects, allowing model to learn state value without estimating every action independently.I train and compare three variants: DQN (baseline), Double DQN, and Dueling Double DQN.Replay & SamplingTo improve sample efficiency, I use a simplified prioritized replay (PER-lite). Instead of TD-error prioritization, the replay oversamples low-return episodes, increasing the frequency of rare but informative cases.If an episode ends below reward threshold, the last segment of its transitions is copied into a dedicated failure buffer. It becomes active only after it is filled. Each batch is then sampled jointly from the main and failure buffers. This biases training toward learning corrective behavior in difficult landings without the overhead of full PER.Training PipelineI use Z-score normalization with running EMA statistics instead of fixed normalization, even though environment bounds are known. This allows the model to focus on the actual distribution of explored transitions rather than full state space.In bootstrap-based RL, targets are noisy and large batches tend to overfit to imperfect value estimates. Empirically, 32 provided the best tradeoff between stability and informativeness. Each batch contains 26 transitions from the main replay buffer and 6 from the failure buffer.The main replay buffer size is 131072, and the failure buffer size is 32768. Episodes with return below 100 are considered failures. Their last 30 transitions are pushed into the failure buffer.I use SGD with momentum 0.1 instead of Adam. In this setup it leads to more stable parameter updates (see Training Diagnostics, Figure 3).Learning rate follows a cosine schedule from 7.5e-4 to 3e-3 over 25k optimization steps. A 0.1 scaling factor is applied to the projection stem learning rate to prevent it from dominating parameter movement.I use Huber loss (β = 2.0) instead of MSE to reduce sensitivity to large TD-errors. In addition, gradient norm clipping at 40 is applied, with The network uses two residual blocks with hidden size 64, projection size 32, and residual scale factor α = 0.2. The single head is a linear layer (32 → 4) while the dueling head uses two heads (32 → 4) and (32 → 1). All layers follow Xavier uniform initialization with zero biases. Total parameter counts are 8804 (single) and 8837 (dueling).All models are trained for 600k steps. Epsilon decays from 1.0 to 0.005 over 300k steps. Discount factor γ = 0.97. The target network is updated with Polyak averaging (τ = 0.001).Evaluation ProtocolI consider the environment solved when the episode return is ≥ 200. My evaluation pipeline consists of two stages: in-training selection and post-training benchmarking.During the training, I track the rolling mean reward over the last 128 episodes. Once this metric exceeds 250, evaluation is activated and it runs every 50 training steps on a fixed set of 100 seeds. For each evaluation run, I compute the win rate and its 95% confidence interval under a Bernoulli assumption. The lower bound of this interval represents a conservative estimate of performance on unseen seeds, and once it exceeds 0.95, a checkpoint is saved.After training, each model is evaluated on 500 fixed seeds. These are the same seeds that were played by the human agent, which allows direct comparison. Random episodes are also generated on this seed set and are used only as a reference floor for normalization.For each policy, I compute an average episode reward and the win rate with a 95% confidence interval. To make results easier to interpret, I report a normalized score relative to human performance, computed asThe best performing DQN single-head model is used as an internal baseline, and same normalization is applied when comparing other architectures against it.To test generalization rather than memorization, I evaluate policies under a human-prefix setting. Each episode starts with the first 20 actions (~2.66 seconds) played by the human, after which control is handed over to the agent. All reward statistics are computed only on the agent-controlled segment, while prefix reward is included only when computing win rates.In addition to standard success threshold (return ≥ 200), I also report a soft win rate defined as return ≥ 100, again with confidence intervals.Training DiagnosticsI inspect training from three perspectives: internal representations, optimization dynamics and policy behavior.To better understand the effect of residual connections, I compared activation and pre-activation distributions between ResMLP and a plain MLP after 600k optimization steps.Figure 2. Pre-activation and activation distributions for a 3-layer MLP and ResMLP. Vertical dashed lines indicate Tanh saturation region (|x| > 0.97). (Image by Author)The ResMLP shows tighter pre-activation ranges in early layers and significantly reduced saturation in the first layer (~3.6% vs ~21.6% for the plain MLP). Deeper layers still exhibit noticeable saturation in both architectures, although ResMLP remains better behaved. In practice, this corresponds to improved gradient flow compared to vanilla MLP.To understand optimizer behavior, I tracked update-to-data ratio (log₁₀ scale) for each layer during training.Figure 3. Update-to-data ratios during training. The dashed line at -3 indicates a reference update scale (~10⁻³ relative to parameter magnitude). (Image by Author)With Adam (β₁=0.1, β₂=0.999), update magnitudes become increasingly noisy and dispersed over time. This is especially visible in later stages of training, where gradients become sparse and second-moment adaptation amplifies rare TD-error spikes, leading to unstable parameter updates.In contrast, SGD with momentum 0.1 maintains a much tighter and more consistent update range across layers. The update-to-data ratios remain stable throughout training, indicating more uniform parameter movement.This difference translates into training stability: SGD avoids sudden “shock” updates while still making steady progress toward the target Q-function.To analyze policy behavior during training, I track three metrics: action gap, value estimates, and episode reward.The action gap is defined as the difference between the highest and second-highest predicted Q-values, averaged across the batch every 10 optimization steps. It reflects model’s confidence in its chosen action.To track value estimation dynamics, I use a fixed set of 1024 states sampled from replay before training begins (at that stage the buffer contains only random transitions). After each episode, I compute the average max-Q value across this set to measure how model optimism evolves over time. The same state set is used for all models.Episode reward is the same metric used in in-training evaluation. All metrics are shown as rolling averages over the last 128 episodes.Figure 4. Rolling averages of action gap, estimated Q-value, and episode reward for the compared models over training steps. (Image by Author)During the early training phase (first ~250 steps), all models exhibit similar action gaps. After this point, DQN and Double DQN gradually converge to lower confidence levels (~1.5–3.0), with Double DQN being the most conservative. In contrast, the dueling architecture maintains consistently higher action gaps, frequently producing spikes up to ~6.0. This suggests that separating state value and action advantages leads to stronger action preference signals.The estimated Q-value curves follow a similar pattern across all models: initial pessimism (~-30), followed by rapid optimism growth (~40), and eventual stabilization around 20 by the end of the training. As expected, plain DQN shows the highest final optimism (~22), followed by dueling (~20) and Double DQN (~18). This confirms the known effect of overestimation bias in vanilla DQN.In terms of episode reward, all models eventually reach similar final performance (~280), but differ in convergence speed. DQN reaches high performance earliest (~300k steps), while Double DQN and Dueling Double DQN follow later (~500k and ~540k steps respectively).ResultsIn this section I report final post-train evaluation metrics for DQN, Double DQN and Dueling Double DQN (see Evaluation Pipeline).Table 1. Post-training evaluation on 500 fixed seeds for the compared models. (Image by Author)DQN already provides a strong baseline, exceeding human performance by 8.6% on regular starts. Under the human-prefix setting, its win rate drops by ~10%, falling slightly below the human baseline. This indicates limited robustness to unseen initial conditions.Double DNQ behaves similarly on regular starts but shows slightly weaker generalization under the prefix setup, with a further 3% decline in win rate. This suggests that reducing Q-overestimation alone does not translate into better control in this environment.Dueling Double DQN delivers the best overall performance. It achieves the highest average reward in both settings and outperforms the baseline on generalization. On regular starts it reaches ~109% of human performance, and under prefixes remains on par with a human agent.Policy BehaviorI run an additional stress test for the strongest policy by evaluating it on 10k new seeds . It fails only 157 of them, confirming the results with 98.43% win rate (±0.24%, 95% CI).Figure 5. Episode length and reward distributions over 10000 rollouts with 157 fails (Dueling Double DQN). (Image by Author)Most episodes end successfully with durations concentrated around ~5–10 seconds. A thin line near the maximum episode length corresponds to “sliding” mode: the agent lands but keeps firing thrusters to stabilize until timeout. Another cluster with rewards between 0 and 100 comes from overly aggressive descents where lander’s body touches down near the target zone. Rare outliers with strongly negative returns are extreme failures such as flipping or drifting out of bounds.https://medium.com/media/9e6c75e03654434af49e5527eba35b7f/hrefThe left column shows clean landings. The left-middle column highlights “sliding” behavior, where the agent lands but struggles to fully stabilize. The right-middle column shows failed landings with loss of control. The top-right episode illustrates an overly fast fast landing with a hard ground contact. The bottom-right episode shows slightly missed target region followed by a crash due to unfavorable terrain geometry.ConclusionIn this project, I focused on making the training process interpretable and, even in a relatively simple environment this approach revealed a lot about how value-based agents actually learn.A key takeaway is that good training design mattered more than model size — even a small network was able to learn a reliable and generalizable policy.The main limitation of the current setup is the state representation. The agent does not “see” the ground and implicitly assumes a flat surface, which leads to sliding and most of the crashes. Addressing this would require either improving the state representation (e.g., adding terrain awareness) or modifying the reward structure to penalize these outcomes more explicitly.ResourcesFull code, configs and evaluation pipeline — GitHub repositoryDavid Silver — Introduction to Reinforcement LearningMnih et al. — Playing Atari with Deep Reinforcement LearningVan Hasselt et al. — Deep Reinforcement Learning with Double Q-learningWang et al. — Dueling Network Architectures for Deep Reinforcement LearningApollo DQN: Building an RL Agent for LunarLander-v3 was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.