Skip to main content

stochastic_search/bounds/
brtdp.rs

1//! Bounded real-time dynamic programming (BRTDP, McMahan, Likhachev and Gordon 2005):
2//! gap-weighted successor sampling.
3
4use core::hash::Hash;
5
6use crate::bounds::{Explorer, Run, solve};
7use crate::budget::{Budget, Limits, Stats};
8use crate::config::Config;
9use crate::error::Error;
10use crate::model::{Goal, Heuristic, Mdp};
11use crate::observer::Observer;
12use crate::solution::SolveResult;
13use crate::space::Id;
14
15/// Settings of [`brtdp`]: the shared [`Config`] and BRTDP's trial-end ratio.
16///
17/// Build one with [`BrtdpConfig::default`], or with [`BrtdpConfig::new`] (or `into`) from a
18/// [`Config`], and adjust it with [`BrtdpConfig::with_tau`].
19#[non_exhaustive]
20#[derive(Debug, Clone, Copy, PartialEq)]
21pub struct BrtdpConfig<B = Limits, O = ()> {
22    /// Epsilon (the gap that ends the run), dead ends, seed, trial length, budget and
23    /// observer.
24    pub base: Config<B, O>,
25    /// The trial-end ratio `tau`: a trial ends once the expected gap of the next state
26    /// falls below the initial state's gap divided by `tau`. Finite and greater than `1`;
27    /// larger values make trials longer.
28    ///
29    /// Default [`BrtdpConfig::DEFAULT_TAU`].
30    pub tau: f64,
31}
32
33impl BrtdpConfig {
34    /// The default `tau`, `10`: the low end of the range the paper used ("we used `tau`
35    /// between 10 and 100 in our experiments"), which favours short trials.
36    pub const DEFAULT_TAU: f64 = 10.0;
37}
38
39impl Default for BrtdpConfig {
40    fn default() -> Self {
41        Self::new(Config::default())
42    }
43}
44
45impl<B, O> BrtdpConfig<B, O> {
46    /// Wraps `base` with the default `tau`.
47    #[must_use]
48    pub fn new(base: Config<B, O>) -> Self {
49        Self {
50            base,
51            tau: BrtdpConfig::DEFAULT_TAU,
52        }
53    }
54
55    /// Returns the same settings with another `tau`.
56    #[must_use]
57    pub fn with_tau(self, tau: f64) -> Self {
58        Self { tau, ..self }
59    }
60
61    /// Checks `tau`.
62    ///
63    /// # Errors
64    ///
65    /// Returns [`Error::InvalidConfig`] for a `tau` that is not finite and greater than 1.
66    fn validate<S>(&self) -> Result<(), Error<S>> {
67        if self.tau.is_finite() && self.tau > 1.0 {
68            Ok(())
69        } else {
70            Err(Error::InvalidConfig {
71                reason: "tau must be finite and greater than 1",
72            })
73        }
74    }
75}
76
77impl<B, O> From<Config<B, O>> for BrtdpConfig<B, O> {
78    fn from(base: Config<B, O>) -> Self {
79        Self::new(base)
80    }
81}
82
83/// Solves an SSP from `initial` with bounded RTDP, keeping a lower and an upper bound on
84/// every stored state's optimal value.
85///
86/// `lower` estimates the lower bound of a new state as the heuristic of
87/// [`lrtdp`](crate::lrtdp()) does (admissible for the guarantee, `None` for a proven dead
88/// end). `upper` estimates its upper bound: at least the optimal value, `None` if no finite
89/// bound is known. Each trial starts at `initial`; at every state it backs up both bounds,
90/// takes the action that is greedy on the lower bound, and samples a successor with
91/// probability proportional to `P(s' | s, a) * (U(s') - L(s'))`, so trials go where the
92/// bounds are far apart. A trial ends when that weight summed over the successors falls
93/// below `(U(initial) - L(initial)) / tau` ([`BrtdpConfig::tau`]), at a goal or dead end, or
94/// after [`Config::max_trial_length`] steps; then it backs up its states again, last first.
95/// The run stops when `U(initial) - L(initial) <= epsilon` ([`Config::epsilon`]). After
96/// convergence, a fill pass backs up every state that the upper-greedy policy reaches from
97/// `initial` but no trial backed up, so the returned policy has an action wherever one
98/// exists in its envelope (unless the budget runs out during the pass).
99///
100/// The returned [`Solution`](crate::Solution) has the lower bounds as [`Solution::value`](crate::Solution::value) and the upper
101/// bounds as [`Solution::upper_bound`](crate::Solution::upper_bound). Its policy is greedy on the upper bound, as of each
102/// state's last backup, as the paper prescribes (`greedy(v_u)`): only an upper-greedy policy
103/// has a cost guarantee. [`frtdp`](crate::frtdp()) and [`vpi_rtdp`](crate::vpi_rtdp())
104/// share everything in this documentation except how trials pick states.
105///
106/// # Dead ends
107///
108/// An infinite upper bound on a state with a finite optimal value never becomes finite: on a
109/// cycle such as "retry until it works", a backup computes `c + p * 0 + (1 - p) * inf`.
110/// BRTDP therefore requires a finite upper bound on every state it stores, except where the
111/// lower bound already proves a dead end (then both bounds are infinite and the gap counts as
112/// `0`, so trials never sample it):
113///
114/// - Under [`DeadEnds::Penalty`](crate::DeadEnds::Penalty)`(p)` this always holds: an upper
115///   estimate of `None` or above `p` becomes `p`, since giving up is always possible. With
116///   `upper` returning `None` everywhere, `p` is the initial upper bound of every state.
117/// - Under [`DeadEnds::Infinite`](crate::DeadEnds::Infinite), the run fails with
118///   [`Error::UnboundedUpper`] at the first stored state whose upper estimate is `None` or
119///   infinite while its lower estimate is finite. Such a problem needs a lower bound that
120///   recognizes its dead ends, a finite upper bound, or a penalty.
121///
122/// Since every stored state that may have a finite value has a finite upper bound, BRTDP
123/// needs no dead-end proof: a state with a finite upper bound has a proper policy if the
124/// bound is valid.
125///
126/// # Guarantee
127///
128/// If `lower` is admissible and `upper` is a valid upper bound (at least the optimal value
129/// `V*` under the configured dead-end semantics), then at any time, in particular whatever
130/// the [`Status`](crate::Status), every stored state `s` satisfies
131/// `L(s) <= V*(s) <= U(s)` (up to floating-point rounding): Bellman backups of a lower bound
132/// stay below `V*`, those of an upper bound stay above it. A run with
133/// [`Status::Converged`](crate::Status::Converged) also has
134/// `U(initial) - L(initial) <= epsilon`.
135///
136/// If, in addition, the upper bound is monotone (`U(s) >= min_a Q_U(s, a)` everywhere, as
137/// for the constant penalty), backups keep it monotone, and every stored state with a policy
138/// action `pi(s)` satisfies `U(s) >= Q_U(s, pi(s))`. Then following the policy from a state
139/// whose policy successors all have actions costs at most `U` in expectation. After a
140/// converged run and its fill pass, that holds from `initial`: following the policy costs at
141/// most `U(initial)`. A run stopped by the budget may leave envelope states without an
142/// action; [`Solution::action`](crate::Solution::action) is `None` there.
143///
144/// # Termination
145///
146/// With the default [`Limits`] budget the call always returns. With valid
147/// bounds both converge to `V*` on the states trials keep visiting, so the gap at `initial`
148/// shrinks to `epsilon` on finite problems.
149///
150/// # Events
151///
152/// [`Event::Progress`](crate::Event::Progress) as for [`lrtdp`](crate::lrtdp()), with the
153/// lower bound as `initial_value` and the current gap `U(initial) - L(initial)` as
154/// `residual`. No dead-end or divergence events.
155///
156/// # Cost
157///
158/// One backup updates both bounds and counts once in [`Stats::backups`](crate::Stats). The
159/// upper bounds take 8 more bytes per stored state. The fill pass is not bounded by the
160/// trials' work: it expands every state of the upper-greedy envelope, which under dense
161/// noise is every state reachable from `initial`; the budget still caps it (and an exhausted
162/// budget during the pass keeps the converged status). One seed gives identical results on
163/// every run.
164///
165/// # Errors
166///
167/// Returns an [`Error`] for an invalid [`Config`] or `tau`, for invalid MDP output or estimates in the
168/// states the run touches (see [`Error::InvalidHeuristic`] for the upper bound), and
169/// [`Error::UnboundedUpper`] as described in "Dead ends".
170///
171/// # Panics
172///
173/// Panics if more than `u32::MAX` states, actions or outcomes are stored.
174///
175/// # Example
176///
177/// A sure route for cost 3, or a coin flip for cost 1 that retries on failure (expected
178/// cost 2). The sure route bounds the value from above:
179///
180/// ```
181/// use stochastic_search::{BrtdpConfig, Mdp, Zero, brtdp, heuristic_fn};
182///
183/// struct Routes;
184///
185/// impl Mdp for Routes {
186///     type State = bool;
187///     type Action = &'static str;
188///
189///     fn actions(&self, _done: &bool, mut emit: impl FnMut(&'static str, f64)) {
190///         emit("sure", 3.0);
191///         emit("flip", 1.0);
192///     }
193///
194///     fn outcomes(&self, _done: &bool, action: &&'static str, mut emit: impl FnMut(bool, f64)) {
195///         if *action == "sure" {
196///             emit(true, 1.0);
197///         } else {
198///             emit(true, 0.5);
199///             emit(false, 0.5);
200///         }
201///     }
202/// }
203///
204/// let upper = heuristic_fn(|_: &bool| Some(3.0));
205/// let config = BrtdpConfig::default();
206/// let solution = brtdp(&Routes, false, &|done: &bool| *done, Zero, upper, config)?;
207///
208/// assert!(solution.is_converged());
209/// let (lower, upper) = (solution.initial_value(), solution.initial_upper_bound().unwrap());
210/// assert!(lower <= 2.0 && 2.0 <= upper && upper - lower <= 1e-6);
211/// assert_eq!(solution.initial_action(), Some(&"flip"));
212/// # Ok::<(), stochastic_search::Error<bool>>(())
213/// ```
214pub fn brtdp<M, G, L, U, B, O>(
215    mdp: &M,
216    initial: M::State,
217    goal: &G,
218    lower: L,
219    upper: U,
220    config: BrtdpConfig<B, O>,
221) -> SolveResult<M>
222where
223    M: Mdp,
224    M::State: Clone + Eq + Hash,
225    G: Goal<M::State>,
226    L: Heuristic<M::State, f64>,
227    U: Heuristic<M::State, f64>,
228    B: Budget<Stats>,
229    O: Observer,
230{
231    config.validate()?;
232    let explorer = Explorer::Brtdp { tau: config.tau };
233
234    solve((mdp, initial, goal), lower, upper, config.base, explorer)
235}
236
237impl<M: Mdp, G, L, U, B, O> Run<'_, M, G, L, U, B, O> {
238    /// BRTDP's successor choice: samples a successor of the action at `index` with
239    /// probability proportional to `P(s') * gap(s')`, or returns `None` if that weight
240    /// summed over the successors is `0` or below the initial state's gap divided by `tau`.
241    ///
242    /// Called after the current state's backup, so at the initial state the summed weight is
243    /// at least its gap (up to rounding) and a trial always moves on from there.
244    pub(crate) fn brtdp_next(&mut self, index: u32, tau: f64) -> Option<Id> {
245        let u = self.rng.next_unit();
246        let (total, _) = self.gap_weights(index);
247        if total <= 0.0 || total < self.gap(self.start) / tau {
248            return None;
249        }
250
251        self.pick_weighted(index, total, u)
252    }
253}