DiReCL: Learning Differentiable Reward Code with Inverse Reinforcement Learning

Aoran Wang, Jingtao Zhang, Maosen Li, Zongzhang ZhangNeurIPS 2026

TL;DR

Teaching an AI what to want is notoriously difficult: black-box neural rewards learned from data are impossible to inspect, while human- or LLM-written reward code is readable, fragile, and full of guessed numbers. DiReCL gets the best of both worlds by having an LLM write readable Python reward code, turning the numbers inside that code into differentiable parameters, and tuning them directly against expert demonstrations. The result is clean, human-readable reward logic that outperforms standard neural and LLM-based methods—and transfers smoothly when environment physics change.

What Problem Does This Paper Address?

In Reinforcement Learning (RL), an agent is only as good as its reward function. Misspecify the math—say, how aggressively a self-driving car should brake near a crosswalk versus keeping passengers comfortable—and your agent will either fail or find creative ways to "hack" the metric.

Historically, researchers have been stuck choosing between two flawed paradigms:

  1. Inverse Reinforcement Learning (IRL): Instead of writing a reward, you show the agent expert demonstrations and let a neural network infer the hidden objective. It is grounded in real behavior, but the resulting reward is an opaque neural net. You cannot read it, audit it, or easily tweak it, and it tends to overfit to the exact physics of the training environment.
  2. Heuristic / LLM-Assisted Reward Design: Humans (or Large Language Models) write explicit Python functions for rewards. You get crystal-clear semantic structure—explicit terms for speed, safety, and posture—but the specific numbers (weights, thresholds, penalties) are basically educated guesses ungrounded in actual expert behavior.

The authors ask: Can we keep the readable, modular code structure of LLM-designed rewards, while calibrating their exact numbers using data-driven IRL?

Methods

The authors introduce DiReCL (Differentiable Reward Code Learning), a pipeline that treats Python code not as a static script, but as a structured, trainable mathematical hypothesis.

Figure 1: Pipeline of DiReCL. DiReCL queries an LLM with task descriptions to generate reward code, parses eligible numerical elements as learnable parameters (blue), optimizes these parameters with IRL gradients (red), and uses optimization diagnostics to revise the reward code (green).

Here is how the loop works, blending standard RL machinery with novel code-level tricks:

  • LLM Template Synthesis: Given a task description, an LLM (GLM-5.1) writes a modular Python reward function (compute_reward(obs, action)).
  • Differentiable Logic Relaxation & AST Parsing (Novel): Code is full of if/else branches and hard thresholds that kill gradients. DiReCL parses the code into an Abstract Syntax Tree (AST) and smooths out non-differentiable logic (e.g., replacing hard if x > m branches with smooth sigmoid functions). Next, it hunts down numeric literals: tunable weights and thresholds become learnable PyTorch-style parameters, while structural numbers (like array indices s[i] or exponents **2) stay locked so gradients don't break the code's meaning.
  • IRL Parameter Alignment (Standard Engine, New Space): With the code structure frozen, DiReCL uses standard Maximum-Likelihood IRL (ML-IRL) to optimize those extracted numbers via gradient ascent so that an RL policy trained on the code mimics expert demonstrations.
  • Diagnostic Reflection (Novel): What if the LLM forgot a crucial safety term altogether? Tuning numbers won't fix missing logic. DiReCL tracks diagnostics—like which specific behavioral features still diverge from the expert ("imitation gap"), dead/oscillating parameters, and worst-rollout failure summaries—and feeds this evidence back to the LLM to rewrite the code template for the next round.

Datasets

The authors evaluate DiReCL on two established benchmark suites (no new datasets are introduced):

  • MuJoCo Locomotion: Four continuous robotic control tasks (Ant, HalfCheetah, Hopper, Humanoid), using 25 expert trajectories per task generated by Soft Actor-Critic (SAC) agents.
  • CommonRoad-RL: Two realistic autonomous driving benchmarks built from drone-captured German traffic datasets—highD (highways) and inD (intersections)—using 100 expert trajectories per task generated by PPO agents.

Key Insights and Ideas

  • Code is a phenomenal inductive bias: When using the exact same expert data and RL backbone, learning parameters inside a few lines of LLM-written code beats training an unconstrained neural network (AIRL, ML-IRL). Constraining rewards to sensible semantic relationships prevents overfitting.
  • Readable rewards survive physics shifts: When the authors took rewards learned on HalfCheetah and trained a fresh agent in an environment with altered physics dynamics, neural IRL rewards stumbled badly because they had memorized source dynamics. DiReCL's programmatic rewards transferred cleanly and achieved top returns.
  • LLMs know what matters, not how much: Pure LLM/evolutionary baselines (like EUREKA) guess the right concepts (forward velocity, control cost) but struggle with numerical calibration. Grounding those numbers in expert data bridges the gap—and even works if you feed DiReCL human-written code instead of LLM code.

Key Results

Across both robotics and driving tasks, DiReCL achieves over 1.25× the performance of compared IRL and LLM-assisted baselines—remarkably outperforming the original ground-truth environment rewards on all four MuJoCo tasks.

Table 1: MuJoCo results: mean ± standard deviation over five independent runs. EUREKA and DiReCL both perform four reflection iterations and evaluate their selected reward code.
  • MuJoCo: On HalfCheetah, DiReCL hits a return of 15,005.1, comfortably beating neural ML-IRL (12,083.2), iterative LLM baseline EUREKA (10,215.6), and even the ground-truth Expert (10,999.1). On Humanoid, DiReCL scores 7,913.0 vs. EUREKA's 6,401.6 and ML-IRL's 5,000.8.
  • Autonomous Driving: On CommonRoad-RL, DiReCL reaches a 92.0% success rate on highD (vs. 73.2% for EUREKA and 62.6% for ML-IRL) and 88.6% success on inD (vs. 67.6% for EUREKA and 51.4% for ML-IRL).
  • Reflection Matters: Stripping away the diagnostic reflection stage (DiReCL w/o R) drops highD driving success from 92.0% down to 71.6%, proving that data-driven structural edits are vital when initial code templates fall short.

Limitations and Future Work

  • No Visual Inputs Yet: DiReCL currently relies on structured state vectors (joint angles, velocities, lane coordinates) where variables map neatly to code. Extending this to high-dimensional pixel/camera inputs will require integrating Vision-Language Models (VLMs) into the generation and reflection loop.
  • Reliance on Expert Demonstrations: Parameter tuning currently requires expert trajectories. Future work aims to calibrate differentiable reward code from weaker, cheaper human signals—like pairwise preferences, rankings, or natural-language critiques.

Summary updated

Abstract

In reinforcement learning (RL), reward specification plays a fundamental role in shaping policy optimization. Inverse RL (IRL) offers a data-driven approach to inferring rewards from demonstrations, but widely used neural-network-based methods often produce rewards that are difficult to interpret, inspect, or revise manually. In contrast, human-written or large language model (LLM)-generated reward code provides explicit semantic structure, yet its precise numerical parameters are often difficult to calibrate and prone to specification errors. To bridge this gap, we propose DiReCL (\textbf{Di}fferentiable \textbf{Re}ward \textbf{C}ode \textbf{L}earning), a novel framework that unifies these two paradigms by formulating reward learning in a differentiable reward code space. DiReCL first prompts an LLM to synthesize reward code templates, then converts the numeric elements in these templates into differentiable parameters and aligns them with expert demonstrations through IRL. We further introduce a reflection mechanism that uses IRL diagnostics to provide evidence of inadequacies in the reward structure and guide template revision. Experiments on four MuJoCo locomotion tasks and two autonomous driving benchmarks demonstrate that DiReCL achieves over $1.25 \times$ the performance of the compared IRL and LLM-assisted reward design baselines, while retaining explicit and inspectable reward semantics.
BibTeX
@inproceedings{wang2026direcl,
  author = {Aoran Wang and Jingtao Zhang and Maosen Li and Zongzhang Zhang},
  title = {{DiReCL: Learning Differentiable Reward Code with Inverse Reinforcement Learning}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2026},
  url = {https://openreview.net/forum?id=yXtaGQVE33},
}
Figure