Budget-Conditioned Quantile Masks for Safe Exploration with Discrete Actions

Many agents that must learn safely choose from a finite menu of actions: lane changes, grid moves, discrete thrust levels, a small library of controllers. For these agents we propose a simple, checkable safety rule. The agent learns the full distribution of future safety cost for every action, not just its average. At each step it tracks how much of the episode's cost budget it has already spent. It then allows only those actions for which, with high confidence, the remaining cost will still fit inside what is left of the budget. With finitely many actions this check is exact: we enumerate the menu and compare numbers. No gradient through the action is needed, which is why current distributional safe-RL methods do not transfer to this setting. A coarse formal safety filter (a "shield") acts as the fallback early in training. It hands control over, state by state, to the learned check once the check becomes trustworthy.

The opportunity is that a very common safety requirement is a probability statement about total episode cost: "at most 5% of episodes exceed cost $d$." That requirement becomes a local, per-step test once the agent conditions on the cost it has already spent. The local test needs the distribution of future cost, which the expected cost cannot supply. Distributional reinforcement learning, meaning agents that predict the whole spread of outcomes, supplies exactly this. Discrete actions let us enforce the test by masking actions rather than through a Lagrange multiplier that only settles at convergence.

Core Claim

Let $d$ be the per-episode cost budget, $b = d - C_{\text{spent}}$ the budget remaining at the current step, and $Z(s,b,a)$ the random future cost from state $s$ after taking action $a$ and then following the masked policy. Keeping the episode's total cost within budget with probability at least $\alpha$ requires $\Pr[Z(s,b,a) \le b] \ge \alpha$. This is equivalent to requiring that the $\alpha$-quantile $q_\alpha$ of $Z$ not exceed $b$. We estimate $q_\alpha$ with an ensemble of $K$ quantile cost critics and take the most pessimistic member. This guards against critics that are wrong where data are thin. The allowed action set is therefore

$$\mathcal{A}_\alpha(s,b) = \{\, a : \max_{k \le K} q^{(k)}_\alpha(s,b,a) \le b \,\}.$$

The agent picks the reward-maximizing action inside $\mathcal{A}_\alpha$. If $\mathcal{A}_\alpha$ is empty, it takes the action with the smallest pessimistic quantile, or the shield's fallback when one exists.

The claim has three parts, and the first is the novel one. First, conditioning on remaining budget turns an episode-level quantile constraint into an exact per-step discrete test. An expected-cost critic cannot express this test, because $\mathbb{E}[Z] \le b$ says nothing about how often $Z$ exceeds $b$. Second, handing control from the formal shield to the learned mask one state at a time offers a principled way out of the "conservativeness trap" of pure shielding, without the undirected rule-breaking exploration currently used to escape it. Third, we expect fewer in-training violations than Lagrangian quantile methods, at comparable return. We state one caveat up front. Because the critic evaluates the masked policy, which itself depends on the critic, the per-step test composes into the episode-level guarantee only at a fixed point. We therefore treat the guarantee as an empirical target to be measured, not a theorem.

Where This Sits

Three recent methods pair distributional critics with constrained policy optimization, all in continuous action spaces. Safe Distributional Reinforcement Learning couples implicit quantile networks with a log-barrier objective and differentiates the critic through the actor. Trust Region-Based Safe Distributional Reinforcement Learning for Multiple Constraints constrains a mean-plus-standard-deviation cost inside a trust region. Its authors concede this is not a coherent risk measure. Off-Policy Safe Reinforcement Learning with Cost-Constrained Optimistic Exploration projects reward and cost gradients with respect to the action. These papers motivate the proposal, since they show distributional cost critics help safety. They also constrain it: each relies on action gradients that do not exist for a discrete menu. Our method never differentiates with respect to the action.

Tilted Quantile Gradient Updates for Quantile-Constrained Reinforcement Learning states the same chance constraint we target, a high quantile of total cost. It enforces the constraint through an adaptively updated Lagrange multiplier, which leaves early training exposed. We enforce the same constraint through a hard per-step mask derived from budget conditioning. Budget tracking itself is borrowed from the backward value functions of Harsh Satija et al., which account for historical cost with scalar estimates. Our method supplies a distributional future-cost estimate conditioned on that history.

On the discrete side, Safe Reinforcement Learning via Shielding and Provably Safe Reinforcement Learning: Conceptual Analysis, Survey, and Benchmarking show that a shield which replaces unsafe actions keeps training violation-free and learns well. Both are scalar and assume a correct model of the dynamics. We reuse action replacement as the fallback. Adaptive Probabilistic Shielding by Learning MDPs for Safe Reinforcement Learning is the closest discrete-action competitor. It learns interval bounds on transition probabilities, re-synthesizes the shield with the PRISM model checker, and argues that some unshielded exploration is necessary to escape the conservativeness trap. It implements that exploration with $\epsilon$-greedy moves outside the shield. We accept the argument but disagree on the mechanism. The formal methods papers, such as Neurosymbolic Reinforcement Learning with Formally Verified Exploration, insist on zero violations. The adaptive-shielding paper says zero violations cause suboptimality. Our proposal sits between them: it spends a small, explicit violation budget only on blocked actions whose learned tail cost is confidently low. Finally, Breaking Safety Paradox with Feasible Dual Policy Iteration warns that safe policies starve their own cost estimators of violation data. That warning directly limits us, since upper quantiles are exactly what starves first.

Research Program

The agent builds on a discrete-action quantile Q-learner. The reward critic is a standard implicit quantile network. The cost critic is an ensemble of $K=5$ implicit quantile networks that take the remaining budget $b$ as an extra input, embedded with the same cosine features used for risk levels in Risk-Conditioned Distributional Soft Actor-Critic for Risk-Sensitive Navigation. Cost targets are built from the next state with $b' = b - c_t$ under the masked greedy policy. Because every replayed transition can be relabelled with any starting budget, a single trajectory trains the critic across many budgets. Relabelling is cheap here since $b$ enters only through the input and the target.

Hand-off from shield to mask works as follows. Wherever an abstract model exists, as in the discrete shielding benchmarks, the shield is authoritative in a state until the ensemble's disagreement on $q_\alpha$ for that state's actions falls below a tolerance. After that the mask decides. A blocked action can be released only if its pessimistic quantile fits the budget. Any release is charged against a global "exploration violation" allowance, which we report.

To counter the safety paradox, shield-blocked actions are not simply dropped from training. At each visited state we enumerate the blocked actions and give the cost critic a pessimistic synthetic target for each, taken from the shield's worst-case model. This keeps the upper tail from collapsing to zero merely because failures are never observed. The analysis component asks when this per-step mask provably implies the episode-level chance constraint. We expect this to hold under an exact critic and monotone budget consumption, and we will test it on the small tabular benchmarks, where exact cost distributions can be computed by dynamic programming.

Baselines

The naive reference point is Double DQN with no safety mechanism. Next to it is the same learner with a hand-tuned per-violation penalty, tuned over a fixed grid. This pair shows both the reckless regime and the "safe but useless" regime that Quanyi Li et al. document for penalty shaping. Our method beats them if it cuts training violations by an order of magnitude while matching the penalty baseline's best return.

The standard constrained baseline is discrete-action PPO-Lagrangian. Safety Gymnasium: A Unified Safe Reinforcement Learning Benchmark reports a 98% reduction in safety violations for this method relative to PPO, at a 45% drop in total reward, on its velocity tasks. We treat this as the calibration target for the reward-versus-safety trade-off. Next is a discrete port of the tilted-quantile Lagrangian from Tilted Quantile Gradient Updates for Quantile-Constrained Reinforcement Learning. This is the strongest method that targets the same quantile constraint. Its pinball-loss multiplier update carries over unchanged to a categorical policy. No reported discrete-action result for it was found on Lacuna. We beat it if we match its end-of-training quantile satisfaction while incurring substantially fewer violating episodes before convergence.

The strongest existing discrete-action safe-exploration method is Adaptive Probabilistic Shielding by Learning MDPs for Safe Reinforcement Learning, run with its own code on its five benchmarks. The paper reports cumulative violations "nearly identical to the Oracle" and higher reward than the Oracle on Aircraft, but gives no exact scalar figures in the file. We will therefore reproduce its curves before comparing. We beat it if we reach its final return with fewer unshielded violations, or a higher return at equal violations, at lower wall-clock cost with no PRISM calls after warm-up. We also run static shielding with action replacement, following Provably Safe Reinforcement Learning: Conceptual Analysis, Survey, and Benchmarking, and the permissibility shield of Safety through Permissibility: Shield Construction for Fast and Safe Reinforcement Learning. That paper reports convergence on CartPole in under 200 episodes, where Double DQN failed after 500.

The ablation that isolates our key ingredient is a scalar twin. It uses the identical mask, budget conditioning, ensemble, and shield hand-off, but replaces the quantile cost critic with an expected-cost critic under a conservative margin $\mathbb{E}[Z] + m \le b$, with $m$ tuned on the same grid. Further ablations remove budget conditioning (the mask uses $d$ at every step), remove the ensemble, and remove the synthetic blocked-action targets. All methods get the same environment steps, network sizes, and a 20-configuration tuning budget, and results are averaged over 10 seeds.

Why not just…?

Why not just use a scalar expected-cost critic with a conservative margin? This is the real threat. When the only cost is a single binary catastrophe at episode end, expected cost equals violation probability, and the distribution adds nothing. We predict the advantage appears only when cost accumulates stochastically, so that the same mean hides very different chances of exceeding $d$. The tail-risk argument of Tilted Quantile Gradient Updates for Quantile-Constrained Reinforcement Learning and the hazard-zone costs of Safety Gym both describe such regimes. The scalar-twin ablation run on both kinds of environment settles the question. If the twin matches us on cumulative-cost tasks, we will report that the budget-conditioned mask, not the distribution, carries the gains.

Why not just run PPO-Lagrangian or its quantile variant on the discrete policy? Multiplier methods satisfy constraints only once the multiplier has adapted. Off-Policy Safe Reinforcement Learning with Cost-Constrained Optimistic Exploration and Neurosymbolic Reinforcement Learning with Formally Verified Exploration both document heavy violations during training under such methods. Our comparison counts violating episodes over the whole learning curve, not just at the end.

Why not just use a static shield with a failsafe action? Static shields are violation-free but can be overly conservative. Adaptive Probabilistic Shielding by Learning MDPs for Safe Reinforcement Learning shows an Oracle shield losing reward on Aircraft. Static shields also need a model and a known failsafe, which Provably Safe Reinforcement Learning: Conceptual Analysis, Survey, and Benchmarking notes are rarely available in complex settings. We keep the shield as a fallback and measure how much return the hand-off recovers over it.

Why not just use adaptive probabilistic shielding? It needs the exact transition topology in advance, relies on tabular interval estimates, and calls a model checker online. Its escape from conservatism is untargeted $\epsilon$-greedy rule-breaking. Discretized Safety-Gymnasium navigation tests whether our method works where that topology is unavailable. The head-to-head on its own benchmarks tests whether choosing releases by learned tail risk spends fewer violations for the same gain.

Proposed Experiments

We use three benchmark families. The first is the five discrete shielding environments of Adaptive Probabilistic Shielding by Learning MDPs for Safe Reinforcement Learning (Aircraft, Antlion, Sinkholes, Crossroads, Gravity). They are small enough to compute exact future-cost distributions, so there we can measure critic quantile error and check whether the per-step mask actually yields the episode-level constraint. The second is CartPole, FlappyBird, and the inverted pendulum and quadrotor tasks with Double DQN and discrete PPO, following Safety through Permissibility: Shield Construction for Fast and Safe Reinforcement Learning and Provably Safe Reinforcement Learning: Conceptual Analysis, Survey, and Benchmarking. The third is Safety-Gymnasium Point and Car Goal and Button tasks from Safety Gymnasium: A Unified Safe Reinforcement Learning Benchmark, with the action space discretized into 9 and 25 motion primitives. There, hazard costs accumulate and no model is given. On this third family we also report continuous distributional safe-RL methods on the native action space, as a reference for what discretization costs. For those methods the file gives only relative figures, such as 1.78 times fewer violations for Trust Region-Based Safe Distributional Reinforcement Learning for Multiple Constraints. We found no reported absolute Safety Gym result on Lacuna, so we will run them ourselves.

The metrics are the total number of episodes whose cost exceeded $d$ during training; the fraction of evaluation episodes exceeding $d$, compared against the target $1-\alpha$; final and area-under-curve return; and, on the shielding benchmarks, the fraction of shield-blocked actions later confirmed safe. The decisive check is the scalar twin on discretized Safety-Gymnasium. The proposal succeeds if the quantile mask holds evaluation exceedance at or below $1-\alpha$ while the tuned scalar twin either exceeds it or gives up reward to avoid doing so, and if on binary terminal-cost tasks the two methods tie as predicted. A second check is whether the synthetic blocked-action targets keep upper-quantile error flat late in training, when real violations have stopped. If that error still grows, the safety paradox has defeated the mechanism, and we will report it as a negative result.