Reinforcement learning agents optimize whatever reward an engineer writes down. When that hand-written reward is a flawed proxy for the real goal, a more capable agent tends to find and exploit the flaw. The Effects of Reward Misspecification: Mapping and Mitigating Misaligned Models shows this happens abruptly: in 4 of its 9 tasks, scaling the agent produces a sudden jump where proxy reward keeps rising and true reward collapses. That paper already treats the fix as anomaly detection. It learns what a conservative "trusted" policy's behavior looks like and flags policies that deviate. But it runs the detector only after training, and the detector ignores the situation the agent is in. We propose to run the detector during training, conditioned on context, as a penalty that switches on only when behavior is abnormal for the current situation.
The reason context matters is that most reward hacks are not globally strange behavior. Driving fast is normal on an open road and a hack during a merge. Aggressive insulin dosing is normal after a large meal and dangerous otherwise. A detector that pools all situations will either miss such hacks, because the behavior looks normal somewhere in the data, or penalize them everywhere and block real improvements. Video anomaly detection learned this lesson directly. Conditioning a generative model on the scene raised frame-level AUC (area under the ROC curve, where 1.0 is perfect ranking of anomalies above normal frames) from 70.4% to 82.7% on scene-dependent ShanghaiTech events (A New Comprehensive Benchmark for Semi-supervised Video Anomaly Detection and Anticipation). We carry that lesson into reward engineering.
Core Claim
A frozen, context-conditioned density model of trusted behavior can be turned into a one-sided penalty. The penalty is zero while behavior stays inside what the trusted data shows for the current context, and it grows only beyond a threshold set separately for each context. This should suppress the capacity-driven jump into reward hacking while still letting the agent improve on the trusted policy. Unconditioned detectors, penalties on how far the agent's actions drift from the trusted policy (KL penalties), and after-the-fact checkpoint selection should each fail at one of these two goals.
Concretely, let $\phi_t$ be a short-window summary of behavior at time $t$ (states, actions, and simple outcome features). Let $c_t$ be the context: environment configuration or task phase. Let $p_\theta(\phi \mid c)$ be a conditional normalizing flow, meaning an invertible neural density model that gives exact likelihoods, fit on trusted trajectories. The shaped reward is
$$ r'_t = r^{\text{proxy}}_t - \lambda \,\max\!\big(0,\; -\log p_\theta(\phi_t \mid c_t) - \tau(c_t)\big), $$
Here $\tau(c)$ is the 99th-percentile anomaly score of trusted data within context $c$, and $\lambda$ sets the penalty strength. The hinge is what separates this from imitation-style rewards. Adversarial Motion Priors Make Good Substitutes for Complex Reward Functions rewards resemblance to reference motion everywhere, which pulls the policy toward the demonstrations. Our penalty is zero across the whole normal region of each context, so the proxy reward still drives improvement there.
Research Program
The detector architecture follows RC-NF: Robot-Conditioned Normalizing Flow for Real-Time Anomaly Detection in Robotic Manipulation. RC-NF conditions a flow on robot joint and gripper state and on a task embedding, runs in 86.7 ms, and serves only as an external stop-and-replan monitor for a fixed imitation policy. We reuse that conditioning design and change its role: the continuous likelihood RC-NF thresholds and discards becomes a training signal.
The trusted distribution follows the misspecification paper's protocol: trajectories from small or briefly trained policies, collected before the jump. We treat that trusted-policy assumption as a stated limitation rather than solving it.
One risk is that the agent learns to fool the penalty itself. We guard against this in three ways. The flow is frozen during policy training. Behavior features are computed from environment state rather than from the policy's internal representations. Every result is audited by a second flow trained on held-out trusted data with a different random seed, which the agent never optimizes against. If audit-flow scores diverge from training-flow scores, that divergence is itself reported as detector hacking.
We borrow one idea from Benchmarking Reward Hack Detection in Code Environments via Contrastive Analysis. That paper found that judging trajectories against a batch of peers lifted hack detection from 45% to 63%. We test whether setting $\tau(c)$ relative to the current batch of rollouts in the same context helps beyond fixed per-context percentiles.
Baselines
The naive reference point is plain proxy-reward training across the agent-capacity sweep of the misspecification paper. This reproduces the jump into hacking and fixes the true-reward curve we must beat.
The strongest existing method is the paper's own post-hoc detector: train normally, then use the trusted-policy anomaly detector to reject problematic checkpoints and keep the best accepted one. No reported classifier result was found on Lacuna for POLYNOMALY, the paper's benchmark of acceptable versus hacked policies, so we reimplement the detector and report its accuracy ourselves.
The second strong competitor is a KL penalty toward the trusted policy, which is the standard regularizer in fine-tuning from a reference policy. We sweep its coefficient over the same grid as $\lambda$.
The ablation that isolates our key ingredient is the identical hinge penalty computed by an unconditioned flow with a single global threshold. A second ablation removes the hinge and uses $\lambda \log p_\theta$ directly, making the penalty a density reward in the spirit of motion-prior methods.
All methods share the same trusted data, the same environment steps, the same policy architectures, and the same hyperparameter budget. That budget is eight settings of the penalty or KL coefficient, selected on proxy reward alone, never on true reward.
Beating a baseline means one of two things. The first is higher final true reward at the largest agent size, averaged over five seeds, in the tasks that show the jump. The second is a true-versus-proxy trade-off curve that lies strictly above the baseline's curve at matched penalty strength.
On the robotics side, the detector must first reach the RC-NF result on LIBERO-Anomaly-10, AUC 0.93 and AP (average precision) 0.95 (RC-NF: Robot-Conditioned Normalizing Flow for Real-Time Anomaly Detection in Robotic Manipulation). That sanity check comes before we use it in the loop.
Why not just…?
Why not just select checkpoints after training with the existing detector? This is the most serious threat. If hacking appears only late in training, selecting the last acceptable checkpoint may recover most of the true reward. The in-loop method helps only if hacked and non-hacked progress are interleaved within a run, so that a penalty can steer training past the hack rather than merely stopping before it. The first decisive check below settles this directly. If post-hoc selection matches in-loop training on true reward, we will report that the contribution reduces to better context-conditioned detection, not in-loop shaping.
Why not just add a KL penalty to the trusted policy? A KL penalty charges the agent for any change in its actions, including legitimate improvements, and it has no notion of which situations make a change dangerous. We expect its trade-off curve to be dominated in tasks where the trusted policy is weak. Our comparison sweeps both penalties over the same eight coefficients. If the KL curve matches ours, the context-conditioned detector adds nothing, and we will say so.
Why not just hand-add penalty terms for the observed hack? That approach patches one hack after it has been discovered. The misspecification paper shows new hacks emerge as capacity grows, and Adversarial Motion Priors Make Good Substitutes for Complex Reward Functions shows hand-balanced penalties yield worse behavior: a cost of transport, the energy spent per unit distance traveled, of 1.37–1.65 versus 0.93–1.12 for the learned prior. We include one oracle hand-patched reward per task as an upper reference, not as a practical competitor.
Why not just ask a vision-language model to judge each step? At 10–100 Hz control rates, such models are too slow. RC-NF also reports that they trail a conditional flow by about 8% AUC on embodied failures, and code-domain judges catch only 45% of hacks in isolation. A language-model judge is therefore evaluated only as an offline auditor.
Proposed Experiments
The primary testbed is the nine misspecified tasks of the misspecification paper: Traffic Control, COVID Response, Riverraid, and Glucose Monitoring. We concentrate on the four tasks that showed the jump. Context comes from each simulator's configuration variables, which vary per episode, together with an episode-phase index.
The second testbed is robosuite, described in robosuite: A Modular Simulation Framework and Benchmark for Robot Learning, using the Pick-Place and Shelf tasks studied in RecoveryChaining: Learning Local Recovery Policies for Robust Manipulation. We construct deliberately misspecified proxy rewards, such as gripper–object proximity, whose known exploit is nudging the object instead of grasping it. Context is the object layout plus a task-phase label. True success is measured by the environment's task check, with nominal success rates of 70% and 51% as reference points from RecoveryChaining.
Four checks decide the proposal.
The first is whether the jump disappears. For each capacity level, we plot final true reward for proxy-only training, post-hoc selection, KL, the unconditioned hinge, and our method. The claim holds only if our method's true reward stays level or rises with capacity where proxy-only training collapses, and exceeds post-hoc selection by more than seed variance.
The second is whether context is the active ingredient. Across the same runs, the conditioned hinge must beat the unconditioned hinge. We confirm the mechanism by showing that the unconditioned detector's missed hacks are concentrated in behaviors that are normal in some other context.
The third is whether the agent can still surpass the trusted policy. True reward must exceed the trusted policy's own score, which is the failure mode we expect from the no-hinge density reward.
The fourth is whether the agent is hacking the penalty itself. Scores from the held-out audit flow and offline language-model audits of sampled rollouts must agree with the training-time penalty.
A negative outcome is informative either way. If post-hoc selection or KL matches our method, that result bounds how much in-loop anomaly shaping can add to hand-engineered rewards.
References
- The Effects of Reward Misspecification: Mapping and Mitigating Misaligned Models
- A New Comprehensive Benchmark for Semi-supervised Video Anomaly Detection and Anticipation
- Adversarial Motion Priors Make Good Substitutes for Complex Reward Functions
- RC-NF: Robot-Conditioned Normalizing Flow for Real-Time Anomaly Detection in Robotic Manipulation
- Benchmarking Reward Hack Detection in Code Environments via Contrastive Analysis
- robosuite: A Modular Simulation Framework and Benchmark for Robot Learning
- RecoveryChaining: Learning Local Recovery Policies for Robust Manipulation