Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-plan/benches/projecting.rs

//! Joins that project a variable away, against joins that do not: one run per process, so
//! the process's peak resident memory (`/usr/bin/time -v`) is the run's. Results:
//! `bench/projecting.md`.
//!
//! `cargo bench -p kleene-plan --bench projecting -- <shape> <scale> <explain 0|1> <threads>`
//!
//! - `jret`: `jret(R, A, S, CT) :- up(R, A, S, G), taken(G), blind(G), holes(CT).` and
//!   `jret(R, A, S, NX) :- up(R, A, S, G), dcall(G, NX).`, a stratum reading none of its
//!   relations (the shape of a tail-return rule set): each (R, A, S) holds 16 values of G, so
//!   each fact has 16 bindings. `scale` = rows of (R, A, S) (default 1000; 20000 holes).
//! - `chain`: `p(X, Z) :- e(X, Y), f(Y, Z).` with `f` one-to-one: no two bindings of a
//!   fact (the pass's guard is all it costs). `scale` = rows of `e` (default 20000000).
//! - `walk`: `w(R, Y) :- s(R, Y).  w(R, Y) :- w(R, X), step(X, G, Y).`, a recursion of
//!   joins, `scale` = starts (default 2000) over 4000 nodes, 4 middle values per hop.
//! - `walk1`: the same with one middle value per hop (no repeats).
//! - `place`: `place(A, F, L) :- need(A), at(A, X), row(X, F, L).` with `at` external (by
//!   its first column): 205 needs, `scale` rows of `row` (default 480000).
//! - `fail`: `fail(H) :- ok(H, F), cl(F, I), reached(I), !body(I).`: `scale` holes (default
//!   23162) over 500 functions, 2500 closure rows each.
//! - `loose`: `loose(S) :- ret(S, R), pair(E, S, R), pair(E, A, S), A != S, A != R,
//!   aft(S, E, X), !pair(E, A, X).`: `scale` sites (default 2000), 70 before and after.
//! - `enters`: `enters(HF, G) :- blind_entry(G), taken_fn(G), jump_hole_fn(HF).`, a plain
//!   product (the last rule of a Heimdall rule group): `scale` values of G in both one-column
//!   relations (default 12407), 2033 values of HF, every product row a new fact.
//! - `fscope`: `fscope(F, SC) :- hf(F, FS, FE), scope(SC, 0), srange(SC, LO, HI), LO < FE,
//!   FS < HI.`: `scale` functions (default 2000), 5000 top scopes, 100000 nested.

use std::sync::Arc;
use std::time::Instant;

use kleene_plan::{
    Atom, Cmp, Cond, Engine, External, Facts, Inputs, Literal, Plan, RelId, Term, Value, Var,
};
use kleene_sparse::{CpuBackend, CpuDevice};

fn atom(rel: RelId, terms: &[Var]) -> Atom {
    Atom {
        rel,
        terms: terms.iter().map(|&v| Term::Var(v)).collect(),
    }
}

fn jret(rows: u64) -> (Plan, Inputs, RelId, &'static str) {
    let (per, holes, calls, targets) = (16u64, 20_000u64, 8u64, 5000u64);
    let mut p = Plan::new();
    let up = p.input("up", 4);
    let taken = p.input("taken", 1);
    let blind = p.input("blind", 1);
    let hole = p.input("holes", 1);
    let dcall = p.input("dcall", 2);
    let jret = p.derived("jret", 4);
    let [r, a, s, g, ct] = ["R", "A", "S", "G", "CT"].map(|n| p.var(n));
    p.rule(
        atom(jret, &[r, a, s, ct]),
        [
            atom(up, &[r, a, s, g]),
            atom(taken, &[g]),
            atom(blind, &[g]),
            atom(hole, &[ct]),
        ],
    )
    .unwrap();
    p.rule(
        atom(jret, &[r, a, s, ct]),
        [atom(up, &[r, a, s, g]), atom(dcall, &[g, ct])],
    )
    .unwrap();
    let gs = rows * per + 7;
    let up_rows =
        (0..rows).flat_map(|x| (0..per).map(move |k| [x, x % 7, x % 3, (x * per + k) % gs]));
    let mut inputs = Inputs::new();
    inputs
        .facts(up, Facts::from_rows(4, up_rows).unwrap())
        .facts(taken, Facts::from_rows(1, (0..gs).map(|x| [x])).unwrap())
        .facts(blind, Facts::from_rows(1, (0..gs).map(|x| [x])).unwrap())
        .facts(
            hole,
            Facts::from_rows(1, (0..holes.max(gs + 1)).map(|x| [1_000_000 + x])).unwrap(),
        )
        .facts(
            dcall,
            Facts::from_rows(
                2,
                (0..gs).flat_map(|x| (0..calls).map(move |k| [x, (x / per * 13 + k) % targets])),
            )
            .unwrap(),
        );
    (p, inputs, jret, "jret")
}

fn chain(rows: u64) -> (Plan, Inputs, RelId, &'static str) {
    let mut p = Plan::new();
    let e = p.input("e", 2);
    let f = p.input("f", 2);
    let out = p.derived("p", 2);
    let [x, y, z] = ["X", "Y", "Z"].map(|n| p.var(n));
    p.rule(atom(out, &[x, z]), [atom(e, &[x, y]), atom(f, &[y, z])])
        .unwrap();
    let ys = rows / 4 + 1;
    let mut inputs = Inputs::new();
    inputs
        .facts(
            e,
            Facts::from_rows(2, (0..rows).map(|i| [i / 4, (i * 7919) % ys])).unwrap(),
        )
        .facts(
            f,
            Facts::from_rows(2, (0..ys).map(|y| [y, y * 3 + 1])).unwrap(),
        );
    (p, inputs, out, "p")
}

fn walk(starts: u64, per: u64) -> (Plan, Inputs, RelId, &'static str) {
    let nodes = 4000u64;
    let mut p = Plan::new();
    let s = p.input("s", 2);
    let step = p.input("step", 3);
    let w = p.derived("w", 2);
    let [r, x, g, y] = ["R", "X", "G", "Y"].map(|n| p.var(n));
    p.rule(atom(w, &[r, y]), [atom(s, &[r, y])]).unwrap();
    p.rule(atom(w, &[r, y]), [atom(w, &[r, x]), atom(step, &[x, g, y])])
        .unwrap();
    let rows = (0..nodes).flat_map(move |x| {
        (0..per).flat_map(move |k| [[x, k, (x + 1) % nodes], [x, k + per, (x * 3 + 1) % nodes]])
    });
    let mut inputs = Inputs::new();
    inputs
        .facts(
            s,
            Facts::from_rows(2, (0..starts).map(|i| [i, (i * 131) % nodes])).unwrap(),
        )
        .facts(step, Facts::from_rows(3, rows).unwrap());
    (p, inputs, w, "w")
}

fn pos(rel: RelId, terms: &[Var]) -> Literal {
    Literal::Pos(atom(rel, terms))
}

fn neg(rel: RelId, terms: &[Var]) -> Literal {
    Literal::Neg(atom(rel, terms))
}

fn cmp(left: Var, op: Cmp, right: Var) -> Literal {
    Literal::Cond(Cond::Cmp {
        left: Term::Var(left),
        op,
        right: Term::Var(right),
    })
}

/// Two columns answered by the first column bound (or listed whole).
#[derive(Debug)]
struct ByFirst(
    std::collections::HashMap<Value, Vec<[Value; 2]>>,
    Vec<[Value; 2]>,
);

impl External for ByFirst {
    fn arity(&self) -> usize {
        2
    }

    fn can(&self, bound: u64) -> bool {
        bound & 1 == 1 || bound == 0
    }

    #[allow(clippy::needless_range_loop)]
    fn lookup(
        &self,
        bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> kleene_plan::Result<()> {
        for k in 0..n {
            if bound & 1 == 0 {
                self.1.iter().for_each(|r| out(k, r));
            } else if let Some(rs) = self.0.get(&keys[0][k]) {
                rs.iter().for_each(|r| out(k, r));
            }
        }
        Ok(())
    }
}

fn place(rows: u64) -> (Plan, Inputs, RelId, &'static str) {
    let needs = 205u64;
    let mut p = Plan::new();
    let need = p.input("need", 1);
    let at = p.external("at", 2);
    let row = p.input("row", 3);
    let place = p.derived("place", 3);
    let [a, x, f, l] = ["A", "X", "F", "L"].map(|n| p.var(n));
    p.rule(
        atom(place, &[a, f, l]),
        [atom(need, &[a]), atom(at, &[a, x]), atom(row, &[x, f, l])],
    )
    .unwrap();
    let xs = rows / 2;
    let at_rows: Vec<[Value; 2]> = (0..needs)
        .flat_map(|a| [[a, (a * 7) % xs], [a, (a * 7 + 1) % xs]])
        .collect();
    let mut by = std::collections::HashMap::new();
    for r in &at_rows {
        by.entry(r[0]).or_insert_with(Vec::new).push(*r);
    }
    let mut inputs = Inputs::new();
    inputs
        .facts(need, Facts::from_rows(1, (0..needs).map(|a| [a])).unwrap())
        .facts(
            row,
            Facts::from_rows(3, (0..rows).map(|i| [i % xs, i, 5000 + i / 3])).unwrap(),
        )
        .external(at, Arc::new(ByFirst(by, at_rows)));
    (p, inputs, place, "place")
}

fn fail(holes: u64) -> (Plan, Inputs, RelId, &'static str) {
    let (funcs, per) = (500u64, 2500u64);
    let mut p = Plan::new();
    let ok = p.input("ok", 2);
    let cl = p.input("cl", 2);
    let reached = p.input("reached", 1);
    let body = p.input("body", 1);
    let fail = p.derived("fail", 1);
    let [h, f, i] = ["H", "F", "I"].map(|n| p.var(n));
    p.rule(
        atom(fail, &[h]),
        [
            pos(ok, &[h, f]),
            pos(cl, &[f, i]),
            pos(reached, &[i]),
            neg(body, &[i]),
        ],
    )
    .unwrap();
    let insts = funcs * per;
    let mut inputs = Inputs::new();
    inputs
        .facts(
            ok,
            Facts::from_rows(2, (0..holes).map(|h| [h, h % funcs])).unwrap(),
        )
        .facts(
            cl,
            Facts::from_rows(
                2,
                (0..funcs).flat_map(|f| (0..per).map(move |k| [f, (f * 3 + k * 11) % insts])),
            )
            .unwrap(),
        )
        .facts(
            reached,
            Facts::from_rows(1, (0..insts).map(|i| [i])).unwrap(),
        )
        .facts(
            body,
            Facts::from_rows(1, (0..insts).filter(|i| i % 9973 != 0).map(|i| [i])).unwrap(),
        );
    (p, inputs, fail, "fail")
}

fn loose(sites: u64) -> (Plan, Inputs, RelId, &'static str) {
    let (before, after) = (70u64, 70u64);
    let mut p = Plan::new();
    let ret = p.input("ret", 2);
    let pair = p.input("pair", 3);
    let aft = p.input("aft", 3);
    let loose = p.derived("loose", 1);
    let [s, r, e, a, x] = ["S", "R", "E", "A", "X"].map(|n| p.var(n));
    p.rule(
        atom(loose, &[s]),
        [
            pos(ret, &[s, r]),
            pos(pair, &[e, s, r]),
            pos(pair, &[e, a, s]),
            cmp(a, Cmp::Ne, s),
            cmp(a, Cmp::Ne, r),
            pos(aft, &[s, e, x]),
            neg(pair, &[e, a, x]),
        ],
    )
    .unwrap();
    let mut pairs: Vec<[u64; 3]> = Vec::new();
    let mut afts: Vec<[u64; 3]> = Vec::new();
    for s in 0..sites {
        let (e, r) = (s, 1_000_000_000 + s);
        pairs.push([e, s, r]);
        for b in 0..before {
            let a = 2_000_000_000 + s * before + b;
            pairs.push([e, a, s]);
            if s % 2 == 0 {
                pairs.push([e, a, 3_000_000_000 + s * after]);
            }
        }
        for k in 0..after {
            afts.push([s, e, 3_000_000_000 + s * after + k]);
        }
    }
    let mut inputs = Inputs::new();
    inputs
        .facts(
            ret,
            Facts::from_rows(2, (0..sites).map(|s| [s, 1_000_000_000 + s])).unwrap(),
        )
        .facts(pair, Facts::from_rows(3, pairs).unwrap())
        .facts(aft, Facts::from_rows(3, afts).unwrap());
    (p, inputs, loose, "loose")
}

fn fscope(funcs: u64) -> (Plan, Inputs, RelId, &'static str) {
    let (tops, nested) = (5000u64, 100_000u64);
    let mut p = Plan::new();
    let hf = p.input("hf", 3);
    let scope = p.input("scope", 2);
    let srange = p.input("srange", 3);
    let fscope = p.derived("fscope", 2);
    let [f, fs, fe, sc, lo, hi] = ["F", "FS", "FE", "SC", "LO", "HI"].map(|n| p.var(n));
    p.rule(
        atom(fscope, &[f, sc]),
        [
            pos(hf, &[f, fs, fe]),
            Literal::Pos(Atom {
                rel: scope,
                terms: vec![Term::Var(sc), Term::Const(0)],
            }),
            pos(srange, &[sc, lo, hi]),
            cmp(lo, Cmp::Lt, fe),
            cmp(fs, Cmp::Lt, hi),
        ],
    )
    .unwrap();
    let mut inputs = Inputs::new();
    inputs
        .facts(
            hf,
            Facts::from_rows(3, (0..funcs).map(|f| [f, f * 10, f * 10 + 10])).unwrap(),
        )
        .facts(
            scope,
            Facts::from_rows(
                2,
                (0..tops)
                    .map(|s| [s, 0])
                    .chain((0..nested).map(|s| [tops + s, 1 + s % tops])),
            )
            .unwrap(),
        )
        .facts(
            srange,
            Facts::from_rows(
                3,
                (0..tops)
                    .map(|s| [s, (s % funcs) * 10, (s % funcs) * 10 + 5])
                    .chain(
                        (0..nested)
                            .map(|s| [tops + s, 10_000_000 + s * 10, 10_000_000 + s * 10 + 5]),
                    ),
            )
            .unwrap(),
        );
    (p, inputs, fscope, "fscope")
}

fn enters(gs: u64) -> (Plan, Inputs, RelId, &'static str) {
    let holes = 2033u64;
    let mut p = Plan::new();
    let blind = p.input("blind_entry", 1);
    let taken = p.input("taken_fn", 1);
    let hole = p.input("jump_hole_fn", 1);
    let enters = p.derived("enters", 2);
    let [hf, g] = ["HF", "G"].map(|n| p.var(n));
    p.rule(
        atom(enters, &[hf, g]),
        [atom(blind, &[g]), atom(taken, &[g]), atom(hole, &[hf])],
    )
    .unwrap();
    let gv = |x: u64| 7_000_000 + 13 * x;
    let mut inputs = Inputs::new();
    inputs
        .facts(
            blind,
            Facts::from_rows(1, (0..gs).map(|x| [gv(x)])).unwrap(),
        )
        .facts(
            taken,
            Facts::from_rows(1, (0..gs).map(|x| [gv(x)])).unwrap(),
        )
        .facts(
            hole,
            Facts::from_rows(1, (0..holes).map(|x| [3_000_000 + 7 * x])).unwrap(),
        );
    (p, inputs, enters, "enters")
}

fn main() {
    let args: Vec<String> = std::env::args()
        .skip(1)
        .filter(|a| !a.starts_with("--"))
        .collect();
    let shape = args.first().map_or("jret", String::as_str);
    let scale: Option<u64> = args.get(1).and_then(|s| s.parse().ok());
    let explain = args.get(2).is_some_and(|s| s == "1");
    let threads: usize = args.get(3).and_then(|s| s.parse().ok()).unwrap_or(32);
    let (p, inputs, rel, name) = match shape {
        "jret" => jret(scale.unwrap_or(1000)),
        "enters" => enters(scale.unwrap_or(12_407)),
        "chain" => chain(scale.unwrap_or(20_000_000)),
        "walk" => walk(scale.unwrap_or(2000), 4),
        "walk1" => walk(scale.unwrap_or(2000), 1),
        "place" => place(scale.unwrap_or(480_000)),
        "fail" => fail(scale.unwrap_or(23_162)),
        "loose" => loose(scale.unwrap_or(2000)),
        "fscope" => fscope(scale.unwrap_or(2000)),
        other => {
            panic!("unknown shape {other} (jret, chain, walk, walk1, place, fail, loose, fscope)")
        }
    };
    let rt = tokio::runtime::Builder::new_current_thread()
        .build()
        .unwrap();
    let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(threads)).explain(explain);
    let t = Instant::now();
    let out = rt.block_on(engine.run(&p, &inputs)).unwrap();
    let secs = t.elapsed().as_secs_f64();
    let facts = out.get(rel).map_or(0, Facts::len);
    let r = out
        .report
        .strata
        .iter()
        .find(|s| s.relations.iter().any(|n| n == name))
        .expect("the stratum");
    // a why asked, so the proofs are read back
    if explain && let Some(f) = out.get(rel) {
        let first = f.rows().next().expect("a fact");
        assert!(out.why(&p, rel, &first).is_some());
    }
    println!(
        "shape={shape} scale={} explain={explain} threads={threads} facts={facts} secs={secs:.3} \
         peak_rows={} proof_rows={}",
        scale.map_or("default".to_string(), |s| s.to_string()),
        r.peak_rows,
        r.proof_rows
    );
}