Merge Welt v5 part (b) follow-up: Rust E-step equal to the Python reference on 2,000 cases (eps 0 and 0.01)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-02 18:19:03 +01:00
co-authored by Claude Opus 5.5
5 changed files with 90 additions and 36 deletions
+1 -1
View File
@@ -16,7 +16,7 @@ def main():
ap.add_argument("--out", required=True)
ap.add_argument("--faeden", default="4")
ap.add_argument("--mischung", default="0")
ap.add_argument("--max-typen", default="3")
ap.add_argument("--max-typen", default="0")
ap.add_argument("--max", default=None)
ap.add_argument("--vorflop", default=None)
a = ap.parse_args()
+27 -14
View File
@@ -158,15 +158,22 @@ pub struct Optionen {
impl Default for Optionen {
fn default() -> Self {
Optionen { mischung: 0.0, max_typen: 3 }
Optionen { mischung: 0.0, max_typen: 0 }
}
}
/// At most `max` largest weights (stable), renormalised; no usable type -> the pseudo type -1 (pool only).
/// The type list as given (order and weights untouched, like messlatte.typen_des); an empty list is the pseudo type -1 (pool only).
/// `max > 0` additionally keeps only the `max` largest weights (stable), renormalised; 0 = off (the preprocessing already limits to 3).
pub fn typen_vorbereiten(typen: &[(i32, f64)], max: usize) -> Vec<(i32, f64)> {
if typen.is_empty() {
return vec![(-1, 1.0)];
}
if max == 0 {
return typen.to_vec();
}
let mut v: Vec<(i32, f64)> = typen.iter().copied().filter(|&(_, w)| w > 0.0 && w.is_finite()).collect();
v.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
v.truncate(max.max(1));
v.truncate(max);
let s: f64 = v.iter().map(|x| x.1).sum();
if v.is_empty() || s <= 0.0 {
return vec![(-1, 1.0)];
@@ -191,7 +198,7 @@ pub fn estep_hand(p: &Params, opt: &Optionen, hand: &Hand, wz: &mut Werkzeug) ->
let brett = &hand.brett;
let bm = board_maske(brett);
// strengths per street, only if some decision needs them; sorted order over all non-NaN combos
let mut ord_voll: [Option<Vec<u16>>; NS] = [None, None, None, None];
let mut ord_voll: [Option<(Vec<u16>, Vec<f64>)>; NS] = [None, None, None, None];
for sp in &hand.spieler {
for e in &sp.ents {
let s = e.st as usize;
@@ -208,7 +215,9 @@ pub fn estep_hand(p: &Params, opt: &Optionen, hand: &Hand, wz: &mut Werkzeug) ->
}
brett_staerke(&mut wz.st, &brett[..n])
};
ord_voll[s] = Some(ordnung(&st));
let o = ordnung(&st);
let sv = o.iter().map(|&h| st[h as usize]).collect();
ord_voll[s] = Some((o, sv));
}
}
let lam_shift = if hand.bb > 0.0 { (hand.bb / LIMIT_BASIS_BB).log2() } else { 0.0 };
@@ -256,12 +265,18 @@ pub fn estep_hand(p: &Params, opt: &Optionen, hand: &Hand, wz: &mut Werkzeug) ->
for e in &sp.ents {
erl.extend_from_slice(&e.erlaubt);
}
let ords: Vec<Vec<u16>> = (0..NS)
.map(|s| match &ord_voll[s] {
Some(o) if sp.ents.iter().any(|e| e.st as usize == s) => o.iter().copied().filter(|&h| live_flag[h as usize]).collect(),
_ => Vec::new(),
})
.collect();
let mut ords: Vec<Vec<u16>> = vec![Vec::new(); NS];
let mut svs: Vec<Vec<f64>> = vec![Vec::new(); NS];
for s in 0..NS {
if let (Some((o, sv)), true) = (&ord_voll[s], sp.ents.iter().any(|e| e.st as usize == s)) {
for (i, &h) in o.iter().enumerate() {
if live_flag[h as usize] {
ords[s].push(h);
svs[s].push(sv[i]);
}
}
}
}
// per type: kernel run
let mut je_typ: Vec<(f64, Vec<f64>, Vec<f64>)> = Vec::new(); // (total, bin_w, bin_qw)
for &(ty, _) in &typen {
@@ -281,6 +296,7 @@ pub fn estep_hand(p: &Params, opt: &Optionen, hand: &Hand, wz: &mut Werkzeug) ->
beta: &p.beta,
live: &live,
ordnung: [&ords[0], &ords[1], &ords[2], &ords[3]],
sval: [&svs[0], &svs[1], &svs[2], &svs[3]],
evid: &evid,
mischung: opt.mischung,
};
@@ -300,9 +316,6 @@ pub fn estep_hand(p: &Params, opt: &Optionen, hand: &Hand, wz: &mut Werkzeug) ->
}
for (d, e) in sp.ents.iter().enumerate() {
for (ti, &(ty, _)) in typen.iter().enumerate() {
if joint[ti] <= 0.0 {
continue;
}
let f = typen[ti].1 / n_live.max(1.0) / grand;
let mut bins = [(0.0, 0.0); NQ];
for b in 0..NQ {
@@ -98,10 +98,11 @@ fn naiv(p: &Params, hand: &Hand, si: usize, opt: &Optionen) -> (f64, Vec<NaivTyp
idx.sort_by(|&a, &b| s[a].partial_cmp(&s[b]).unwrap().then(a.cmp(&b)));
let tot: f64 = idx.iter().map(|&h| w[h]).sum();
let mut q = vec![0.0; NC];
let mut cum = 0.0;
for &h in &idx {
q[h] = (cum + w[h] / 2.0) / tot;
cum += w[h];
// equal strengths (|d| <= 1e-12) share the midpoint of their group
let below: f64 = idx.iter().filter(|&&g| s[g] < s[h] - 1e-12).map(|&g| w[g]).sum();
let group: f64 = idx.iter().filter(|&&g| s[g] >= s[h] - 1e-12 && s[g] <= s[h] + 1e-12).map(|&g| w[g]).sum();
q[h] = (below + group / 2.0) / tot;
}
let al = p.alpha_fuer(ty, e.codes);
for &h in &idx {
@@ -165,7 +166,7 @@ fn naiv(p: &Params, hand: &Hand, si: usize, opt: &Optionen) -> (f64, Vec<NaivTyp
fn matches_naive_reference_incl_shown_and_muck() {
let p = params();
let hand = drei_spieler();
let opt = Optionen { mischung: 0.0, max_typen: 3 };
let opt = Optionen { mischung: 0.0, max_typen: 0 };
let aus = estep_hand(&p, &opt, &hand, &mut Werkzeug::new()).unwrap();
let mut ll = 0.0;
for si in 0..3 {
@@ -252,12 +253,13 @@ fn evidence_without_decisions_counts_live_combos() {
}
#[test]
fn type_list_truncated_normalised_and_defaulted() {
let v = typen_vorbereiten(&[(1, 0.1), (2, 0.4), (3, 0.3), (4, 0.2)], 3);
fn type_list_is_kept_as_given_unless_limited() {
let l = [(1, 0.1), (2, 0.4), (3, 0.3), (4, 0.2)];
assert_eq!(typen_vorbereiten(&l, 0), l.to_vec());
let v = typen_vorbereiten(&l, 3);
assert_eq!(v.iter().map(|x| x.0).collect::<Vec<_>>(), vec![2, 3, 4]);
assert!((v.iter().map(|x| x.1).sum::<f64>() - 1.0).abs() < 1e-15);
assert!((v[0].1 - 0.4 / 0.9).abs() < 1e-15);
assert_eq!(typen_vorbereiten(&[], 3), vec![(-1, 1.0)]);
assert_eq!(typen_vorbereiten(&[], 0), vec![(-1, 1.0)]);
}
#[test]
+50 -11
View File
@@ -16,6 +16,8 @@ pub const NA: usize = 6;
pub const NK: usize = 5;
pub const NQ: usize = 20;
pub const NS: usize = 4;
/// strengths closer than this count as equal (same rule as messlatte.quantil)
pub const GLEICH_TOL: f64 = 1e-12;
/// Inputs of the kernel. All slices are flat; `ufix` and `erlaubt` have `nd * NA` entries,
/// `beta` has `NS * NA * NK` (beta[s][0][k] must be 0, the kernel does not read it).
@@ -31,6 +33,8 @@ pub struct KernEin<'a> {
pub live: &'a [u16],
/// per street: the live combos sorted by (strength, combo number); only streets that occur in `st` are read
pub ordnung: [&'a [u16]; NS],
/// per street: the strengths in the same order as `ordnung` (ascending); equal strengths (|d| <= TOL) share one quantile
pub sval: [&'a [f64]; NS],
/// showdown evidence per combo (0 or 1)
pub evid: &'a [f64],
/// mixing weight eps of the node frequency (0 = off)
@@ -50,11 +54,13 @@ pub struct KernAus {
pub q: Vec<f64>,
/// P(observed action) per combo, NC
pub p: Vec<f64>,
/// prefix sums of the forward mass in strength order, len(ordnung) + 1
pub kum: Vec<f64>,
}
impl KernAus {
pub fn new() -> Self {
KernAus { gesamt: 0.0, bin_w: Vec::new(), bin_qw: Vec::new(), w: vec![0.0; NC], q: Vec::new(), p: vec![0.0; NC] }
KernAus { gesamt: 0.0, bin_w: Vec::new(), bin_qw: Vec::new(), w: vec![0.0; NC], q: Vec::new(), p: vec![0.0; NC], kum: Vec::with_capacity(NC + 1) }
}
}
@@ -120,16 +126,21 @@ pub fn vorwaerts(e: &KernEin, aus: &mut KernAus) {
for d in 0..nd {
let st = e.st[d] as usize;
let ord = e.ordnung[st];
let mut tot = 0.0;
for &h in ord {
tot += aus.w[h as usize];
}
let qd = &mut aus.q[d * NC..(d + 1) * NC];
let sv = e.sval[st];
aus.kum.clear();
aus.kum.push(0.0);
let mut cum = 0.0;
for &h in ord {
let wh = aus.w[h as usize];
qd[h as usize] = if tot > 0.0 { (cum + 0.5 * wh) / tot } else { 0.5 };
cum += wh;
cum += aus.w[h as usize];
aus.kum.push(cum);
}
let tot = cum;
let qd = &mut aus.q[d * NC..(d + 1) * NC];
for (i, &h) in ord.iter().enumerate() {
let s = sv[i];
let lo = sv.partition_point(|&x| x < s - GLEICH_TOL);
let hi = sv.partition_point(|&x| x <= s + GLEICH_TOL);
qd[h as usize] = if tot > 0.0 { (aus.kum[lo] + 0.5 * (aus.kum[hi] - aus.kum[lo])) / tot } else { 0.5 };
}
let uf = &e.ufix[d * NA..(d + 1) * NA];
let er = &e.erlaubt[d * NA..(d + 1) * NA];
@@ -221,6 +232,7 @@ mod tests {
fn midpoint_quantile_and_bins_on_a_toy_range() {
let live: Vec<u16> = vec![10, 20, 30, 40];
let ord: Vec<u16> = vec![30, 10, 40, 20]; // weak -> strong
let sv: Vec<f64> = (0..ord.len()).map(|i| i as f64).collect();
let st = [1u8];
let zug = [2u8];
let er = [1u8, 0, 1, 0, 0, 0];
@@ -240,6 +252,7 @@ mod tests {
beta: &beta,
live: &live,
ordnung: [&[], &ord, &[], &[]],
sval: [&[], &sv, &[], &[]],
evid: &evid,
mischung: 0.0,
};
@@ -271,6 +284,7 @@ mod tests {
// Decision 2 must see the narrowed range (masses ~0, .5, .5, 1; total 2), not the prior.
let live: Vec<u16> = vec![0, 1, 2, 3];
let ord: Vec<u16> = vec![0, 1, 2, 3];
let sv: Vec<f64> = (0..ord.len()).map(|i| i as f64).collect();
let st = [1u8, 1];
let zug = [2u8, 2];
let er = [1u8, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0];
@@ -280,7 +294,8 @@ mod tests {
beta[1 * NA * NK + 2 * NK] = -40.0;
let mut evid = vec![0.0; NC];
evid[..4].iter_mut().for_each(|x| *x = 1.0);
let e = KernEin { nd: 2, st: &st, zug: &zug, erlaubt: &er, ufix: &uf, beta: &beta, live: &live, ordnung: [&[], &ord, &[], &[]], evid: &evid, mischung: 0.0 };
let e = KernEin { nd: 2, st: &st, zug: &zug, erlaubt: &er, ufix: &uf, beta: &beta, live: &live, ordnung: [&[], &ord, &[], &[]],
sval: [&[], &sv, &[], &[]], evid: &evid, mischung: 0.0 };
let mut aus = KernAus::new();
vorwaerts(&e, &mut aus);
assert!((aus.q[3] - 0.875).abs() < 1e-12);
@@ -294,6 +309,7 @@ mod tests {
// two combos, q = .25 and .75; the strong one raises (beta), the weak one practically never. Evidence only on the weak one.
let live: Vec<u16> = vec![0, 1];
let ord: Vec<u16> = vec![0, 1];
let sv: Vec<f64> = (0..ord.len()).map(|i| i as f64).collect();
let st = [1u8];
let zug = [2u8];
let er = [1u8, 0, 1, 0, 0, 0];
@@ -303,7 +319,8 @@ mod tests {
beta[1 * NA * NK + 2 * NK + 3] = 60.0;
let mut evid = vec![0.0; NC];
evid[0] = 1.0;
let mk = |eps| KernEin { nd: 1, st: &st, zug: &zug, erlaubt: &er, ufix: &uf, beta: &beta, live: &live, ordnung: [&[], &ord, &[], &[]], evid: &evid, mischung: eps };
let mk = |eps| KernEin { nd: 1, st: &st, zug: &zug, erlaubt: &er, ufix: &uf, beta: &beta, live: &live, ordnung: [&[], &ord, &[], &[]],
sval: [&[], &sv, &[], &[]], evid: &evid, mischung: eps };
let mut aus = KernAus::new();
vorwaerts(&mk(0.0), &mut aus);
assert!(aus.gesamt < 1e-20);
@@ -311,4 +328,26 @@ mod tests {
// node frequency of the raise in the range = (P0 + P1) / 2 ~ 0.5; mixed P0 = 0.99 * ~0 + 0.01 * 0.5
assert!((aus.gesamt - 0.005).abs() < 1e-9, "{}", aus.gesamt);
}
#[test]
fn equal_strengths_share_one_midpoint() {
// strengths 0, 1, 1, 2 with mass 1 each: the tie group {1, 1} spans masses [1, 3] -> q = (1 + 0.5 * 2) / 4 = 0.5 for both
let live: Vec<u16> = vec![0, 1, 2, 3];
let ord: Vec<u16> = vec![0, 1, 2, 3];
let sv = vec![0.0, 1.0, 1.0 + 1e-13, 2.0];
let st = [1u8];
let zug = [1u8];
let er = [1u8, 1, 0, 0, 0, 0];
let uf = [0.0f64; 6];
let beta = vec![0.0; NS * NA * NK];
let mut evid = vec![0.0; NC];
evid[..4].iter_mut().for_each(|x| *x = 1.0);
let e = KernEin { nd: 1, st: &st, zug: &zug, erlaubt: &er, ufix: &uf, beta: &beta, live: &live, ordnung: [&[], &ord, &[], &[]], sval: [&[], &sv, &[], &[]], evid: &evid, mischung: 0.0 };
let mut aus = KernAus::new();
vorwaerts(&e, &mut aus);
assert!((aus.q[0] - 0.125).abs() < 1e-15);
assert_eq!(aus.q[1], aus.q[2]);
assert!((aus.q[1] - 0.5).abs() < 1e-15);
assert!((aus.q[3] - 0.875).abs() < 1e-15);
}
}
@@ -1,6 +1,6 @@
//! pokerbench-welt5-estep: Welt v5 E-step.
//!
//! pokerbench-welt5-estep estep --haende IN.jsonl|- --params P.json --out OUT.jsonl|- [--faeden 4] [--mischung 0] [--max-typen 3]
//! pokerbench-welt5-estep estep --haende IN.jsonl|- --params P.json --out OUT.jsonl|- [--faeden 4] [--mischung 0] [--max-typen 0]
//! [--vorflop F.json] [--nice 10] [--max N]
//! pokerbench-welt5-estep vergleich A.jsonl B.jsonl [--tol 1e-9]
//! pokerbench-welt5-estep erzeuge --n N --seed S --haende OUT.jsonl --params OUT.json (synthetic data, for timing and smoke tests)
@@ -49,7 +49,7 @@ fn lauf_main(args: &[String]) -> Result<u8, String> {
faeden: zahl("faeden", 4.0)? as usize,
nice: zahl("nice", 10.0)? as i32,
max: get("max").map(|v| v.parse::<usize>().map_err(|_| "--max: not a number".to_string())).transpose()?,
opt: Optionen { mischung: zahl("mischung", 0.0)?, max_typen: zahl("max-typen", 3.0)? as usize },
opt: Optionen { mischung: zahl("mischung", 0.0)?, max_typen: zahl("max-typen", 0.0)? as usize },
};
if !(0.0..1.0).contains(&lo.opt.mischung) {
return Err("--mischung must be in [0, 1)".into());