stochastic_search/budget.rs
1//! Run counters ([`Stats`], [`TreeStats`]) and early stopping ([`Budget`], [`Limits`]).
2
3pub use search_core::Budget;
4
5/// Counters collected during one run of an algorithm.
6#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
7pub struct Stats {
8 /// Bellman backups that wrote a value. The solved checks of LRTDP, RTDP, LAO* and iLAO* also
9 /// evaluate the Bellman equation; those evaluations count here too, since they cost the
10 /// same.
11 pub backups: u64,
12 /// LRTDP, RTDP, BRTDP, FRTDP and VPI-RTDP trials started. Always `0` for value iteration,
13 /// LAO* and iLAO*.
14 pub trials: u64,
15 /// Value iteration sweeps over the state space, iLAO* passes over the greedy graph, or LAO*
16 /// sweeps over ancestor sets and the solution graph.
17 /// Always `0` for LRTDP and RTDP.
18 pub sweeps: u64,
19 /// States whose actions and outcomes were queried from the MDP.
20 pub expanded: u64,
21 /// Distinct states stored, expanded or not, including goals and dead ends.
22 pub states: u64,
23}
24
25/// Counters collected during one call of a tree planner ([`pomcp`](crate::pomcp()),
26/// [`despot`](crate::despot())), returned in [`Plan::stats`](crate::Plan::stats) and given
27/// to the budget.
28#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
29pub struct TreeStats {
30 /// POMCP simulations or DESPOT explorations started.
31 pub simulations: u64,
32 /// Nodes in the tree: POMCP history nodes, DESPOT belief nodes. After a re-rooting by
33 /// tree reuse, only the kept nodes.
34 pub nodes: u64,
35 /// Node value updates: POMCP action-node updates along each simulation's path, DESPOT
36 /// belief-node backups.
37 pub backups: u64,
38 /// Calls of [`Pomdp::step`](crate::Pomdp::step), in the tree, in rollouts and in
39 /// default-policy simulations.
40 pub steps: u64,
41 /// The depth of the deepest tree node, counted from the current root.
42 pub depth: u64,
43}
44
45/// Simple counter limits.
46///
47/// Every algorithm asks its [`Budget`] (`search_core::Budget<Stats>`, implemented by
48/// `search-core` for every `FnMut(&Stats) -> bool`, which lets callers with a clock add a
49/// time limit, and here for `Limits`) before every Bellman backup, every LRTDP, RTDP or
50/// BRTDP, FRTDP or VPI-RTDP trial, every iLAO* pass, LAO* sweep and every state expansion of value iteration's
51/// enumeration, with the counters so far. So a run stopped by [`Limits::max_backups`]
52/// `= n` has performed exactly `n` backups.
53///
54/// The default, [`Limits::DEFAULT`], is generous but finite, so a run with the default
55/// [`Config`](crate::Config) always returns. [`Limits::unlimited`] removes every limit.
56///
57/// Raise a cap with struct update syntax:
58///
59/// ```
60/// use stochastic_search::{Config, Limits};
61///
62/// let config = Config::default().with_budget(Limits {
63/// max_states: Some(20_000_000),
64/// max_backups: Some(2_000_000_000),
65/// ..Limits::DEFAULT
66/// });
67/// # let _ = config;
68/// ```
69///
70/// # Memory per stored state
71///
72/// Roughly `38 + size_of::<S>()` bytes per state (node, state copy, hash table slot), plus
73/// `16 + size_of::<A>()` bytes per action and `16` bytes per outcome once the state is
74/// expanded, plus whatever heap memory the state itself owns. A state with three actions of
75/// three outcomes each and small `S` and `A` takes about 250 bytes, so the default cap of
76/// `10^6` states is about 250 MB.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub struct Limits {
79 /// Stop once this many Bellman backups have been performed. `None` is unbounded.
80 pub max_backups: Option<u64>,
81 /// Stop once this many LRTDP, RTDP or bounded trials have been started. `None` is unbounded.
82 pub max_trials: Option<u64>,
83 /// Stop once this many states are stored. `None` is unbounded.
84 ///
85 /// See [Memory per stored state](Limits#memory-per-stored-state) to size it.
86 ///
87 /// Bounds memory, and the state enumeration of value iteration on huge or infinite
88 /// state spaces. Checked before every expansion and backup, so the final count may
89 /// exceed the limit by the successors of one state.
90 pub max_states: Option<u64>,
91}
92
93impl Limits {
94 /// The default limits: `10^8` backups and `10^6` stored states, no trial limit.
95 ///
96 /// The state cap keeps memory around 250 MB for typical states (see
97 /// [Memory per stored state](Limits#memory-per-stored-state)); the backup cap allows
98 /// about 100 backups per stored state, which LRTDP and value iteration rarely exceed,
99 /// and takes seconds to a minute. A non-converging run (see [`lrtdp`](crate::lrtdp())'s
100 /// termination notes) stops instead of hanging. Raise either cap as shown on
101 /// [`Limits`].
102 pub const DEFAULT: Self = Self {
103 max_backups: Some(100_000_000),
104 max_trials: None,
105 max_states: Some(1_000_000),
106 };
107
108 /// No limits: the run continues until it converges, which may be never.
109 #[must_use]
110 pub const fn unlimited() -> Self {
111 Self {
112 max_backups: None,
113 max_trials: None,
114 max_states: None,
115 }
116 }
117
118 /// Stops after `max` Bellman backups, with no other limit.
119 #[must_use]
120 pub const fn backups(max: u64) -> Self {
121 Self {
122 max_backups: Some(max),
123 ..Self::unlimited()
124 }
125 }
126}
127
128impl Default for Limits {
129 fn default() -> Self {
130 Self::DEFAULT
131 }
132}
133
134/// For the tree planners, [`Limits::max_trials`] caps [`TreeStats::simulations`],
135/// [`Limits::max_states`] caps [`TreeStats::nodes`] and [`Limits::max_backups`] caps
136/// [`TreeStats::backups`].
137impl Budget<TreeStats> for Limits {
138 fn exhausted(&mut self, stats: &TreeStats) -> bool {
139 self.max_backups.is_some_and(|max| stats.backups >= max)
140 || self.max_trials.is_some_and(|max| stats.simulations >= max)
141 || self.max_states.is_some_and(|max| stats.nodes >= max)
142 }
143}
144
145impl Budget<Stats> for Limits {
146 fn exhausted(&mut self, stats: &Stats) -> bool {
147 self.max_backups.is_some_and(|max| stats.backups >= max)
148 || self.max_trials.is_some_and(|max| stats.trials >= max)
149 || self.max_states.is_some_and(|max| stats.states >= max)
150 }
151}