Skip to main content

optimization_job_api/legacy/
spec.rs

1//! The job format `fcmaes.job/0.1`: one registered scalar problem, solved by
2//! independent BiteOpt or DE retries.
3use crate::Result;
4use serde::{Deserialize, Serialize};
5/// Declares a strict serde struct with public fields, keeping the attributes,
6/// such as doc comments, of the struct and of each field.
7macro_rules! contract {
8    ($(#[$meta:meta])* $name:ident { $($(#[$field_meta:meta])* $field:ident : $ty:ty),* $(,)? }) => {
9        $(#[$meta])*
10        #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
11        #[serde(deny_unknown_fields)]
12        pub struct $name { $($(#[$field_meta])* pub $field: $ty),* }
13    };
14}
15contract!(
16    /// A job of the format `fcmaes.job/0.1`, which the native fcmaes worker runs.
17    JobSpec {
18        /// Exactly `fcmaes.job/0.1`.
19        schema_version: String,
20        /// The caller-chosen idempotency key, 1 to 200 bytes.
21        request_key: String,
22        /// The registered problem.
23        problem: Problem,
24        /// The optimizer of the retries.
25        optimizer: Optimizer,
26        /// The seed and parallelism of the retries.
27        execution: Execution,
28        /// The retries, evaluations and time of the job.
29        budget: Budget,
30        /// What the job reports as progress.
31        outputs: Outputs
32    }
33);
34contract!(
35    /// A registered problem: `benchmark.sphere`, `benchmark.rosenbrock` or
36    /// `gtop.cassini1`.
37    Problem {
38        /// The problem's identifier.
39        id: String,
40        /// The problem's version, `1`.
41        version: String,
42        /// The problem's configuration.
43        config: ProblemConfig,
44        /// The search box.
45        bounds: Bounds
46    }
47);
48contract!(
49    /// The configuration of a registered problem.
50    ProblemConfig {
51        /// The number of variables: 1 to 10,000, at least 2 for Rosenbrock
52        /// and 6 for Cassini1.
53        dimension: usize
54    }
55);
56contract!(
57    /// A search box.
58    Bounds {
59        /// The lower bounds, one per variable, or one value with `broadcast`.
60        lower: Vec<f64>,
61        /// The upper bounds, one per variable, or one value with `broadcast`.
62        upper: Vec<f64>,
63        /// Whether one lower and one upper bound apply to every variable;
64        /// [`Bounds::resolve`] expands them.
65        broadcast: bool
66    }
67);
68contract!(
69    /// The optimizer of the retries.
70    Optimizer {
71        /// `biteopt`, with a hard evaluation limit, or `de`, with a soft one.
72        kind: String,
73        /// The optimizer's parameters.
74        parameters: Parameters
75    }
76);
77/// The optimizer's parameters.
78#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
79#[serde(deny_unknown_fields)]
80pub struct Parameters {
81    /// The population size, 4 to 1,000,000; by default 9 + 3 * dimension for
82    /// BiteOpt and 31 for DE. `population * dimension` must not exceed
83    /// [`MAX_POPULATION_CELLS`].
84    pub population: Option<usize>,
85}
86contract!(
87    /// How the retries run.
88    Execution {
89        /// Exactly `independent_retry`.
90        strategy: String,
91        /// The root seed; each retry's seed derives from it and the retry's
92        /// index.
93        seed: u64,
94        /// The retries that run at the same time; the job's CPU slots.
95        workers: usize,
96        /// The retries started together; no new wave starts after the wall
97        /// time.
98        retry_wave_size: usize
99    }
100);
101/// Evaluation and time budget of one job.
102#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
103#[serde(deny_unknown_fields)]
104pub struct Budget {
105    /// The number of independent retries.
106    pub retries: usize,
107    /// The objective evaluations of each retry.
108    pub evaluations_per_retry: u64,
109    /// `hard` for BiteOpt, which never exceeds the evaluations, or `soft` for
110    /// DE, which may exceed them by `2 * population - 1` per retry.
111    pub evaluation_limit_mode: String,
112    /// No new retry wave starts after this execution time.
113    pub wall_time_seconds: f64,
114    /// Declared interval between the wall-time deadline and killing the
115    /// worker. A retry wave still running after it is lost and the job's
116    /// accounting becomes incomplete.
117    #[serde(default = "default_grace_seconds")]
118    pub grace_seconds: f64,
119}
120fn default_grace_seconds() -> f64 {
121    1.0
122}
123contract!(
124    /// What the job reports as progress.
125    Outputs {
126        /// Exactly `completed_retries`.
127        progress: String
128    }
129);
130impl Bounds {
131    /// Expands broadcast bounds to `n` coordinates and checks that every
132    /// bound is finite with `lower < upper` and a finite span.
133    pub fn resolve(mut self, n: usize) -> Result<Self> {
134        if self.broadcast {
135            if self.lower.len() != 1 || self.upper.len() != 1 {
136                return Err("broadcast requires scalar bounds".into());
137            }
138            self.lower = vec![self.lower[0]; n];
139            self.upper = vec![self.upper[0]; n];
140            self.broadcast = false;
141        }
142        if self.lower.len() != n
143            || self.upper.len() != n
144            || self
145                .lower
146                .iter()
147                .zip(&self.upper)
148                .any(|(l, u)| !l.is_finite() || !u.is_finite() || l >= u || !(u - l).is_finite())
149        {
150            return Err("invalid bounds".into());
151        }
152        Ok(self)
153    }
154    /// Whether every coordinate lies inside the box `[lower, upper]`.
155    pub fn within(&self, lower: &[f64], upper: &[f64]) -> bool {
156        self.lower.len() == lower.len()
157            && self.upper.len() == upper.len()
158            && self.lower.iter().zip(lower).all(|(l, c)| l >= c)
159            && self.upper.iter().zip(upper).all(|(u, c)| u <= c)
160    }
161}
162impl Problem {
163    /// Validates a registered scalar problem (version, dimension, identifier
164    /// and bounds) and expands broadcast bounds. Used by `fcmaes.job/0.1` and
165    /// by the scalar retry profile of the common fcmaes worker.
166    pub fn resolve(mut self) -> Result<Self> {
167        if self.version != "1" {
168            return Err("unsupported schema/problem version".into());
169        }
170        let n = self.config.dimension;
171        if !(1..=10000).contains(&n) {
172            return Err("dimension must be 1..10000".into());
173        }
174        match self.id.as_str() {
175            "benchmark.sphere" => (),
176            "benchmark.rosenbrock" if n >= 2 => (),
177            "gtop.cassini1" if n == 6 => (),
178            _ => return Err("unknown problem or invalid dimension".into()),
179        }
180        self.bounds = self.bounds.resolve(n)?;
181        if self.id == "gtop.cassini1" && !self.bounds.within(&CASSINI1_LOWER, &CASSINI1_UPPER) {
182            return Err("gtop.cassini1 bounds must lie inside the canonical Cassini1 box".into());
183        }
184        Ok(self)
185    }
186}
187/// Largest population x dimension of a BiteOpt or DE run: each of the
188/// optimizer's population tables then holds at most 80 MB of coordinates.
189/// The default BiteOpt population, 9 + 3 * dimension, exceeds it from
190/// dimension 1825 on; set a smaller population there.
191pub const MAX_POPULATION_CELLS: usize = 10_000_000;
192/// Canonical Cassini1 box; job bounds must lie inside it.
193pub const CASSINI1_LOWER: [f64; 6] = [-1000.0, 30.0, 100.0, 30.0, 400.0, 1000.0];
194/// Canonical Cassini1 box; job bounds must lie inside it.
195pub const CASSINI1_UPPER: [f64; 6] = [0.0, 400.0, 470.0, 400.0, 2000.0, 6000.0];
196impl JobSpec {
197    /// Checks the job and resolves its defaults: the schema and problem, the
198    /// bounds, positive counts, the time limits, the progress mode, the
199    /// population and the optimizer's limit mode. The evaluation totals must
200    /// not overflow.
201    pub fn resolve(mut self) -> Result<Self> {
202        if self.schema_version != "fcmaes.job/0.1" || self.problem.version != "1" {
203            return Err("unsupported schema/problem version".into());
204        }
205        if self.request_key.is_empty() || self.request_key.len() > 200 {
206            return Err("request_key must be 1..200 bytes".into());
207        }
208        self.problem = self.problem.resolve()?;
209        let n = self.problem.config.dimension;
210        let e = &self.execution;
211        let k = &self.budget;
212        if e.strategy != "independent_retry"
213            || e.workers == 0
214            || e.retry_wave_size == 0
215            || k.retries == 0
216            || k.evaluations_per_retry == 0
217        {
218            return Err(
219                "positive explicit workers, retries, wave size and evaluations required".into(),
220            );
221        }
222        if !k.wall_time_seconds.is_finite()
223            || k.wall_time_seconds <= 0.0
224            || k.wall_time_seconds > 31_536_000.0
225        {
226            return Err("wall_time_seconds must be in (0,31536000]".into());
227        }
228        if !k.grace_seconds.is_finite() || !(0.0..=86_400.0).contains(&k.grace_seconds) {
229            return Err("grace_seconds must be in [0,86400]".into());
230        }
231        if self.outputs.progress != "completed_retries" {
232            return Err("only completed_retries progress is supported".into());
233        }
234        let p = self
235            .optimizer
236            .parameters
237            .population
238            .unwrap_or(if self.optimizer.kind == "de" {
239                31
240            } else {
241                9 + 3 * n
242            });
243        if !(4..=1_000_000).contains(&p) {
244            return Err("population must be 4..1000000".into());
245        }
246        // The optimizer keeps several population x dimension tables; the
247        // evaluation budget does not bound them, as they are allocated first.
248        if p.saturating_mul(n) > MAX_POPULATION_CELLS {
249            return Err(format!(
250                "population * dimension must be at most {MAX_POPULATION_CELLS} (population {p}, dimension {n}); set a smaller optimizer.parameters.population"
251            )
252            .into());
253        }
254        match (
255            self.optimizer.kind.as_str(),
256            k.evaluation_limit_mode.as_str(),
257        ) {
258            ("biteopt", "hard") | ("de", "soft") => (),
259            _ => {
260                return Err(
261                    "supported paths: biteopt/hard, de/soft; DE hard cap is unavailable".into(),
262                );
263            }
264        }
265        self.optimizer.parameters.population = Some(p);
266        self.requested()?;
267        self.maximum_evaluations()?;
268        Ok(self)
269    }
270    /// The evaluations the job requests: `retries * evaluations_per_retry`.
271    pub fn requested(&self) -> Result<u64> {
272        (self.budget.retries as u64)
273            .checked_mul(self.budget.evaluations_per_retry)
274            .ok_or_else(|| "requested evaluations overflow".into())
275    }
276    /// The most evaluations the job can use: DE may exceed each retry's
277    /// evaluations by `2 * population - 1`.
278    pub fn maximum_evaluations(&self) -> Result<u64> {
279        let extra = if self.optimizer.kind == "de" {
280            2 * self.optimizer.parameters.population.unwrap_or(31) as u64 - 1
281        } else {
282            0
283        };
284        self.budget
285            .evaluations_per_retry
286            .checked_add(extra)
287            .and_then(|x| x.checked_mul(self.budget.retries as u64))
288            .ok_or_else(|| "actual budget bound overflow".into())
289    }
290    /// Digest of the execution specification. The request key is excluded:
291    /// it names a submission, not an experiment, so identical experiments
292    /// submitted under different keys share a digest.
293    pub fn digest(&self) -> Result<String> {
294        let mut value = serde_json::to_value(self)?;
295        if let Some(object) = value.as_object_mut() {
296            object.remove("request_key");
297        }
298        Ok(crate::storage::digest(&serde_json::to_vec(&value)?))
299    }
300}
301/// The description of the native worker: its problems, optimizers and
302/// population rules.
303pub fn discovery() -> serde_json::Value {
304    serde_json::json!({
305        "protocol":"fcmaes.worker/0.1", "problems":[
306        {"id":"benchmark.sphere","version":"1","dimensions":"1..10000"},
307        {"id":"benchmark.rosenbrock","version":"1","dimensions":"2..10000"},
308        {"id":"gtop.cassini1","version":"1","dimensions":6,
309        "lower":CASSINI1_LOWER,"upper":CASSINI1_UPPER,"bounds":"must lie inside lower/upper"}],
310        "optimizers":{"biteopt":{"limit":"hard"},"de":{"limit":"soft","maximum_overshoot_per_retry":"2*population-1"}},
311        "population":"4..1000000; population * dimension <= 1e7 (default: biteopt 9 + 3 * dimension, de 31)",
312        "parallelism":"independent retries; one evaluation thread per retry"
313    })
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319    use serde_json::json;
320
321    fn base() -> serde_json::Value {
322        json!({
323            "schema_version": "fcmaes.job/0.1",
324            "request_key": "k1",
325            "problem": {"id": "benchmark.sphere", "version": "1", "config": {"dimension": 3},
326                        "bounds": {"lower": [-5.0], "upper": [5.0], "broadcast": true}},
327            "optimizer": {"kind": "biteopt", "parameters": {}},
328            "execution": {"strategy": "independent_retry", "seed": 1, "workers": 2, "retry_wave_size": 2},
329            "budget": {"retries": 4, "evaluations_per_retry": 100, "evaluation_limit_mode": "hard",
330                       "wall_time_seconds": 10.0},
331            "outputs": {"progress": "completed_retries"}
332        })
333    }
334    fn resolve(v: serde_json::Value) -> Result<JobSpec> {
335        serde_json::from_value::<JobSpec>(v)?.resolve()
336    }
337
338    #[test]
339    fn resolves_defaults_and_broadcast_bounds() {
340        let s = resolve(base()).unwrap();
341        assert_eq!(s.problem.bounds.lower, vec![-5.0; 3]);
342        assert!(!s.problem.bounds.broadcast);
343        assert_eq!(s.budget.grace_seconds, 1.0);
344        assert_eq!(s.optimizer.parameters.population, Some(9 + 3 * 3));
345        assert_eq!(s.requested().unwrap(), 400);
346        assert_eq!(s.maximum_evaluations().unwrap(), 400);
347    }
348
349    #[test]
350    fn population_tables_are_bounded_before_allocation() {
351        // Review FC-01: 10000 x 1000000 coordinates would be 80 GB per table.
352        let mut v = base();
353        v["problem"]["config"]["dimension"] = json!(10000);
354        v["optimizer"] = json!({"kind": "de", "parameters": {"population": 1000000}});
355        v["budget"]["evaluation_limit_mode"] = json!("soft");
356        v["budget"]["evaluations_per_retry"] = json!(1);
357        let error = resolve(v.clone()).unwrap_err().to_string();
358        assert!(error.contains("population * dimension"), "{error}");
359        // The limit itself is accepted, one cell more is not.
360        v["optimizer"]["parameters"]["population"] = json!(1000);
361        assert!(resolve(v.clone()).is_ok());
362        v["problem"]["config"]["dimension"] = json!(10001);
363        assert!(resolve(v.clone()).is_err());
364        // The default BiteOpt population: dimension 1824 fits, 1825 does not.
365        let mut v = base();
366        v["problem"]["config"]["dimension"] = json!(1824);
367        assert_eq!(
368            resolve(v.clone()).unwrap().optimizer.parameters.population,
369            Some(9 + 3 * 1824)
370        );
371        v["problem"]["config"]["dimension"] = json!(1825);
372        assert!(resolve(v).is_err());
373    }
374
375    #[test]
376    fn de_is_soft_with_declared_overshoot_bound() {
377        let mut v = base();
378        v["optimizer"] = json!({"kind": "de", "parameters": {"population": 10}});
379        assert!(resolve(v.clone()).is_err(), "DE must reject a hard cap");
380        v["budget"]["evaluation_limit_mode"] = json!("soft");
381        let s = resolve(v).unwrap();
382        assert_eq!(s.maximum_evaluations().unwrap(), 4 * (100 + 2 * 10 - 1));
383    }
384
385    #[test]
386    fn rejects_zero_unknown_and_overflowing_inputs() {
387        for (path, value) in [
388            (vec!["execution", "workers"], json!(0)),
389            (vec!["execution", "retry_wave_size"], json!(0)),
390            (vec!["budget", "retries"], json!(0)),
391            (vec!["budget", "evaluations_per_retry"], json!(0)),
392            (vec!["budget", "grace_seconds"], json!(-1.0)),
393            (vec!["budget", "wall_time_seconds"], json!(0.0)),
394        ] {
395            let mut v = base();
396            v[path[0]][path[1]] = value;
397            assert!(resolve(v).is_err(), "{path:?} accepted");
398        }
399        let mut v = base();
400        v["budget"]["total"] = json!(5);
401        assert!(resolve(v).is_err(), "unknown field accepted");
402        let mut v = base();
403        v["budget"]["retries"] = json!(usize::MAX);
404        v["budget"]["evaluations_per_retry"] = json!(u64::MAX);
405        assert!(resolve(v).is_err(), "overflow accepted");
406    }
407
408    #[test]
409    fn cassini1_bounds_must_stay_in_the_canonical_box() {
410        let mut v = base();
411        v["problem"] = json!({"id": "gtop.cassini1", "version": "1", "config": {"dimension": 6},
412            "bounds": {"lower": CASSINI1_LOWER, "upper": CASSINI1_UPPER, "broadcast": false}});
413        assert!(resolve(v.clone()).is_ok());
414        v["problem"]["bounds"]["upper"][5] = json!(7000.0);
415        assert!(resolve(v.clone()).is_err());
416        v["problem"]["bounds"] = json!({"lower": [-1e6], "upper": [1e6], "broadcast": true});
417        assert!(resolve(v).is_err());
418    }
419
420    #[test]
421    fn digest_ignores_request_key_but_not_the_experiment() {
422        let a = resolve(base()).unwrap();
423        let mut v = base();
424        v["request_key"] = json!("another-key");
425        let b = resolve(v).unwrap();
426        assert_eq!(a.digest().unwrap(), b.digest().unwrap());
427        let mut v = base();
428        v["execution"]["seed"] = json!(2);
429        assert_ne!(a.digest().unwrap(), resolve(v).unwrap().digest().unwrap());
430    }
431}