A robot that learns by trial and error with only a "you reached the goal / you didn't" signal almost never succeeds by chance, so it learns almost nothing. Hindsight goal relabeling fixes this by pretending, after the fact, that wherever the robot ended up was the goal all along. The trick is blind to safety, though. A trajectory that reached its end state by slamming into an obstacle or exceeding a torque limit is replayed as a perfect example of how to get there. We propose to relabel two things in hindsight: the goal, and the amount of safety cost the trajectory spent. A trajectory that reached state $s'$ while accumulating cost $C$ becomes a success example for "reach $s'$ with budget at least $C$" and a failure example for "reach $s'$ with budget below $C$." The result is one policy that takes both a target and a safety budget as inputs, trained from sparse rewards with no hand-tuned penalty weight.
The payoff shows up at transfer time. Simulators misestimate contact forces, friction, and disturbances, so a policy that respects a cost limit in simulation often spends more on real hardware. If the budget is an input, a few cautious real-world rollouts can find the commanded budget at which the real cost meets the real limit. The network does not need retraining, and nobody has to guess a safety margin before deployment. The main claim is that relabeling the budget does three jobs at once. It resolves the direct conflict between hindsight relabeling and constrained RL. It replaces the penalty coefficient that engineers otherwise tune by hand. It also turns sim-to-real cost mismatch into a one-dimensional calibration problem.
Core Claim
The research file identifies a genuine contradiction. Hindsight Experience Replay (HER), which stores failed episodes a second time with a goal they did achieve, assumes every reached state is a legitimate target. Constrained RL assumes that transitions violating a cost limit should never be reinforced. The obvious fix is to drop unsafe trajectories from the relabeling pool, or to add a Lagrangian cost critic on top of HER. Either way the safety budget stays a fixed training constant, and informative data gets thrown away or penalized. We instead make the budget part of the goal. Let $g$ be a target state, $b$ a cost budget, $c_t$ the per-step safety cost (contact force above threshold, collision, torque excess), and $\beta_t = b - \sum_{k<t} c_k$ the remaining budget, which is appended to the observation. The sparse reward is
$$r_t = \mathbb{1}\big[\,\|\phi(s_{t+1}) - g\| < \delta \ \text{ and } \ \beta_{t+1} \ge 0\,\big],$$
where $\phi$ maps a state to its achieved-goal coordinates and $\delta$ is the success tolerance. An episode terminates as a failure when $\beta_t < 0$. Hindsight relabeling picks $g'$ from states achieved later in the episode, as HER does. It also picks $b'$, either above the cost actually spent before reaching $g'$ (a success) or below it (a budget-exhaustion failure, which teaches the value function where the constraint bites). Because $\beta_t$ is part of the state, the reward stays Markovian and the policy can be trained with a standard off-policy goal-conditioned learner such as SAC with HER.
Relation to Prior Work
Several papers motivate the gap. Safe Reinforcement Learning via Constrained Markov Decision Processes shows why folding safety into a scalar penalty fails. Small penalties produce risky policies and large ones produce frozen, "safe but useless" ones. Our budget input removes that coefficient rather than tuning it. Safe Policy Exploration Improvement via Subgoals (SPEIS) shows that safe learners stall without intermediate guidance: SAC-Lagrangian reaches 0% success in narrow corridors. SPEIS adds guidance through a hand-designed distance-based subgoal planner, and it discards failed subgoal rollouts. We get intermediate guidance from hindsight instead.
The closest method is A Provable Approach for End-to-End Safe Reinforcement Learning (PLS). PLS trains a return-and-cost-conditioned decision transformer offline, then fits a Gaussian process online to choose safe target values under distribution shift. We borrow its central insight, that tuning a conditioning input is a cheap and safe way to adapt. We differ in three ways. Our conditioning is goal-and-budget, learned online from sparse rewards. Budgets are manufactured by relabeling rather than read from a labeled offline dataset. And we need no dense reward labels at all.
Do It for HER relabels trajectories against temporal-logic formulas they happened to satisfy. A cost bound is expressible in its logic, so in principle it subsumes our relabeling rule. However, that work never treats safety, never studies what relabeling unsafe data does, and never touches transfer, which is where our contribution lies.
Other papers constrain the design. Sim-to-Lab-to-Real relabels actions when a reachability shield overrides the learner. That is complementary to our goal-and-budget relabeling, and the pipeline still relies on engineered task rewards and hundreds of lab rollouts. Provably Safe Sim-to-Real Transfer localizes the region where the simulator is wrong and explores it safely. It proves its guarantees only for tabular problems and reuses no failed trajectories. We give up its guarantees and gain continuous control. Demystifying The Mechanisms Behind Emergent Exploration in Goal-Conditioned RL steers exploration away from unsafe regions by hand-placing their embeddings opposite the goal. That requires knowing the unsafe region in advance, whereas our cost signal only has to be measurable. Finally, Emergent Dexterity via Diverse Resets and Large-Scale Reinforcement Learning (OmniReset) avoids reward engineering through massive state resets. It reaches 25% real peg insertion but ignores contact force during training, which is exactly the kind of cost our method would budget.
Research Program
We will build budget-conditioned SAC with HER. The implementation has four parts: remaining budget appended to the observation, termination on budget exhaustion, and a relabeling sampler over $(g', b')$ pairs. We will study three sampler designs. The first samples $b'$ uniformly in $[C, b_{\max}]$. The second mixes in deliberate below-cost negatives. The third applies a correction in the spirit of USHER, which reweights relabeled goals to reduce the bias of hindsight sampling, extended here to budgets.
We will then examine what the learned value function represents. For a fixed goal, success probability should rise monotonically with budget, and we will measure violations of that monotonicity as a diagnostic. We will also measure how often the policy's achieved cost falls below the commanded budget, which we call calibration.
The deployment procedure is a safe one-dimensional search over the commanded budget in the target domain. It starts from a small, known-safe budget and expands it using a Gaussian-process model of real cost versus commanded budget, in the manner of PLS. Every rollout counts toward a real-world cost tally, and that tally is itself a reported metric.
Baselines
The naive reference point is plain HER with SAC and no cost signal. It shows how much unconstrained relabeling reinforces unsafe behavior, and it sets the success ceiling that safety costs.
The strongest existing competitor is HER combined with SAC-Lagrangian at a fixed budget. It uses the same off-policy learner, the same relabeling of goals, and a learned multiplier that enforces the budget. This is the method a practitioner would assemble today. On the question "does relabeling the budget add anything beyond relabeling the goal under a constraint?" it isolates exactly our ingredient. We found no reported result on Lacuna for HER combined with a Lagrangian cost critic on any benchmark in the file, so we will run it ourselves.
For context on the Lagrangian family, Safety Gymnasium reports that in its velocity tasks PPO-Lag achieved "a 98% reduction in safety violations compared to standard PPO, with only a 45% drop in total reward." On POLAMP narrow corridors, SPEIS reports 84% success with about 3% collisions against 0% for SAC-Lagrangian. We will include SPEIS on the Safety-Gymnasium navigation tasks as a subgoal-guided safe learner.
Fairness rules apply to every method. All share one codebase built on SafePO/Safety-Gymnasium, the same network sizes, the same environment-step budget, and the same number of hyperparameter-search trials. The fixed-budget baselines receive a separate training run for each evaluated budget. That gives them strictly more compute than our single conditioned policy.
We will run two ablations. The first ("filtered HER") keeps goal relabeling but discards any trajectory prefix whose cost exceeds the budget. The second relabels budgets without the below-cost negatives.
Beating the strongest baseline in simulation means the following. At each of at least three budgets, our single policy must match the separately trained HER with SAC-Lagrangian policies' success rate within a pre-set margin at equal or lower cost. It must also do strictly better at the tightest budget, where we predict fixed-budget training starves for positive examples. Beating it at transfer means reaching the target-domain cost limit with higher success than the fixed-budget policy at its best pre-chosen margin, while spending fewer violating rollouts.
Why not just…?
Why not just add a large penalty for unsafe steps to the sparse reward? This is the manual reward engineering our method is meant to eliminate. The CMDP literature (Safe Reinforcement Learning via Constrained Markov Decision Processes) documents that the penalty size either tolerates catastrophes or freezes the agent. With sparse goal rewards the freezing risk is worse, because the penalty is the only dense signal. We include a penalty-HER sweep over five coefficients as a secondary baseline and report the best one, so readers can see directly whether any single weight competes.
Why not just filter unsafe trajectories out of the HER buffer? Filtering is the obvious safety patch and is cheap. It discards exactly the data that tells the learner where the constraint lies, and it keeps the budget fixed, so transfer still needs retraining. The filtered-HER ablation tests this. If it matches our method at every budget, then the value of budget relabeling reduces to amortization across budgets. We would report that result plainly.
Why not just train with domain randomization and a conservatively tightened budget? This is the most serious threat. If an engineer could choose the right margin in advance, one fixed-budget policy trained under randomized physics would transfer safely, and our calibration step would be redundant. The known weaknesses are that broad randomization makes contact-rich policies conservative, and that a guessed margin is either wasteful or insufficient when the mismatch is not what was randomized. The file's evidence is indirect: 68.5% unsafe iterations for unconstrained transfer in Provably Safe Sim-to-Real Transfer and up to 54% violation rates for deep RL baselines in LyEvO. We settle the question directly. We train randomized fixed-budget policies at a sweep of margins and compare against the oracle margin, the best one chosen with hindsight on the target domain. Our method wins only if it approaches the oracle without being told the answer. Matching the oracle margin with a handful of calibration rollouts is the success criterion, not beating it.
Proposed Experiments
Simulation. We use sparse-reward variants of the Safety-Gymnasium Goal and Push tasks with Point and Car robots, keeping the built-in hazard costs. We add robosuite Block Lifting and Door Opening on the Panda arm with the operational-space controller (robosuite). For the manipulation tasks the cost is fingertip contact force above a threshold. No reported success numbers were found on Lacuna for these robosuite tasks, so all figures will be our own runs. Metrics are success rate, mean episode cost, fraction of episodes exceeding budget, and cumulative training-time violations. All are reported as curves over commanded budget.
Controlled transfer. Before any hardware, we create "real" domains by altering physics in ways the training randomization does not cover. We raise contact stiffness and friction, add actuator latency, and scale sensed force. These mimic the physical discrepancies catalogued in the file. The deployment search then runs under a cap of 20 target-domain episodes, and we count every violating episode. We also reproduce the windy-cell mismatch idea from Provably Safe Sim-to-Real Transfer in continuous Point navigation, with hidden disturbance zones near hazards.
Hardware pilot. A Panda arm performs a lifting or door task with a wrist force-torque sensor defining the real cost. It compares our calibrated policy against the fixed-margin randomized baseline.
Decisive checks. The proposal succeeds only if all three of the following hold.
First, the conditioned policy must be calibrated in simulation: achieved cost falls at or below the commanded budget in at least 90% of episodes across the budget range. Without calibration the deployment knob means nothing.
Second, it must match or beat per-budget HER with SAC-Lagrangian while using one training run instead of several. It must win clearly at the tightest budget.
Third, in the shifted domains, calibration within 20 episodes must land within a pre-registered tolerance of the oracle-margin baseline's success at the true cost limit, with fewer violating rollouts than a pre-set fixed margin.
If the first check fails, the idea fails. If the third fails because the oracle-margin baseline matches easily, we conclude that the contribution is multi-budget amortization rather than transfer, and we would write that paper instead.
References
- Hindsight Experience Replay
- MetaDrive: Composing Diverse Driving Scenarios for Generalizable Reinforcement Learning
- Safe Policy Exploration Improvement via Subgoals
- A Provable Approach for End-to-End Safe Reinforcement Learning
- Do It for HER: First-Order Temporal Logic Reward Specification in Reinforcement Learning (Extended Version)
- Sim-to-Lab-to-Real: Safe reinforcement learning with shielding and generalization guarantees
- Provably Safe Sim-to-Real Transfer
- Demystifying The Mechanisms Behind Emergent Exploration in Goal-Conditioned RL
- Emergent Dexterity Via Diverse Resets and Large-Scale Reinforcement Learning
- USHER: Unbiased Sampling for Hindsight Experience Replay
- Safety Gymnasium: A Unified Safe Reinforcement Learning Benchmark
- LyEvO: Lyapunov-Guided Evolutionary Optimization for Safe and Robust Sim-to-Real Policy Learning
- robosuite: A Modular Simulation Framework and Benchmark for Robot Learning