SaFormer: A Conditional Sequence Modeling Approach to Offline Safe Reinforcement Learning

Qin Zhang, Linrui Zhang, Haoran Xu, Li Shen, Bowen Wang, Yongzhe Chang, Xueqian Wang, Bo Yuan, Dacheng Tao

TL;DR

SaFormer is the first sequence modeling approach designed for offline safe reinforcement learning, framing constraint satisfaction as a conditional sequence generation problem. By introducing cost-related tokens and a posterior safety verification mechanism, it achieves high reward performance while strictly adhering to safety limits. Crucially, SaFormer allows users to dynamically adjust safety thresholds at deployment time as a flexible prompt, completely eliminating the need for policy retraining.

What Problem Does This Paper Address?

Deploying reinforcement learning (RL) agents in real-world, safety-critical applications (like autonomous driving or smart grids) requires strict adherence to safety constraints. Standard safe RL relies on online trial-and-error, which is far too risky for physical systems. While offline safe RL avoids online risks by learning purely from a fixed dataset, traditional methods struggle with two major hurdles:

  1. Unstable Optimization: Combining offline policy constraints with conventional Bellman backups (Q-learning) often leads to highly unstable dual optimization and poor long-term cost estimation.
  2. Rigid Constraints: Once a policy is trained using traditional methods, its safety constraints are baked in. If the online safety requirements change, the entire policy must be retrained from scratch.

Recent sequence modeling approaches like the Decision Transformer (DT) sidestep Bellman backups entirely by treating RL as a sequence generation task conditioned on a target "reward-to-go." However, standard DT lacks the machinery to navigate the complex trade-off between maximizing performance and strictly respecting safety boundaries.

Methods

SaFormer builds upon the Decision Transformer architecture but introduces a novel architecture tailored for safety constraints:

  • Cost-Related Tokens: The authors introduce two new tokens into the sequence: the Cost Limit ($D$), which is the human-specified maximum allowable cost for the episode, and the Cost-to-Go ($\hat{C}_t$), which tracks the remaining budget the agent can afford at the current timestep.
  • Two-Stage Auto-Regressive Generation: Instead of directly outputting an action, the SaFormer actor first generates a distribution of potential Reward-to-Go (RTG) candidates conditioned on the cost tokens. It then samples from this distribution to generate a set of feasible action candidates.
  • Posterior Safety Verification: Recognizing that pure generative modeling can still make mistakes, SaFormer introduces a Transformer-based Critic ($\zeta_\phi$). This critic acts as a safety filter, predicting the long-term cost of the proposed action candidates, rejecting unsafe attempts, and executing the safe action with the highest expected reward.
The three-step execution schema of SaFormer, illustrating RTG sampling, action candidate generation, and posterior safety verification by the critic.

Datasets

The approach was evaluated using standard D4RL benchmarks across three MuJoCo environments: Hopper, Walker2d, and HalfCheetah.

Unlike prior work that relies on datasets pre-segregated into "safe" and "unsafe" trajectories, the authors used a more practical, cost-agnostic setup. They took standard behavior datasets and retrospectively relabeled them with a safety cost metric based on the total torque applied to the joints (limiting cumulative energy consumption to prolong motor lifespan).

Key Insights and Ideas

  • Safety as a Prompt: By treating the cost limit as a contextual token ($D$), SaFormer turns a hard optimization constraint into a flexible prompt. The agent can adapt to tighter or looser safety requirements on the fly during execution without changing its weights.
  • Generative Proposals + Critic Filtering: Relying solely on a generative model to output safe actions is insufficient for hard constraints. Combining a generative proposal mechanism with a predictive critic filter provides a robust safety net while maximizing reward potential.
  • Stability in Undiscounted Settings: Traditional Q-learning baselines struggle immensely in undiscounted settings ($\gamma_c = 1$), where costs at the first and last steps are weighted equally. SaFormer's sequence modeling paradigm bypasses Bellman backups, providing stable and reliable cost tracking across the entire trajectory horizon.

Key Results

SaFormer was compared against state-of-the-art baselines, including Decision Transformer (DT), BCQ-L (BCQ with Lagrangian relaxation), and CPQ (Constraints Penalized Q-learning).

  • Strict Constraint Satisfaction: In both discounted and undiscounted settings, SaFormer consistently satisfied the target cost limits while maintaining competitive rewards. In the challenging undiscounted setting, traditional baselines frequently failed and violated safety constraints, whereas SaFormer remained safe.
  • High Adaptation Rate: When tested across various in-range cost limits (10th, 20th, 30th, and 50th percentiles of the dataset's cost distribution), SaFormer achieved a 91.6% constraint satisfaction rate without any retraining.
  • Out-of-Distribution (OOD) Generalization: For strict safety limits completely absent from the offline dataset, the authors introduced an online fine-tuning variant (Algorithm 3) that successfully shrinks the cost return below unexplored thresholds with minimal online sample consumption.
Cost returns of SaFormer before and after online fine-tuning across a range of out-of-sample and in-sample cost limits.

Limitations and Future Work

While promising, the authors note a few limitations:

  • Task Complexity: The evaluation was restricted to relatively simple MuJoCo locomotion tasks. Testing on more complex, high-dimensional real-world datasets is an open next step.
  • Single Constraint Focus: The current architecture handles a single cumulative cost constraint. Future work will focus on extending SaFormer to multi-constraint scenarios.
  • Data Assumptions: The method assumes a weak correlation between rewards and costs (i.e., higher risk yields higher reward). Performance under completely decoupled reward/cost structures remains to be fully explored.

Summary updated

BibTeX
@misc{zhang2023saformer,
  author = {Qin Zhang and Linrui Zhang and Haoran Xu and Li Shen and Bowen Wang and Yongzhe Chang and Xueqian Wang and Bo Yuan and Dacheng Tao},
  title = {{SaFormer: A Conditional Sequence Modeling Approach to Offline Safe Reinforcement Learning}},
  year = {2023},
  eprint = {2301.12203},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2301.12203},
}
Figure