native-solver 0.1.0

Heads-up postflop No-Limit Hold'em solver: hand evaluator, ranges, betting trees, and combo-vectorized CFR / CFR+ / DCFR.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Fixed-policy audit, independent of equality between two learning runs.
//! The adapter is test-only: complete trees, symmetric ranges, no abstraction.
use super::*;
use crate::card::Card;
use crate::range::Range;
use crate::solver::Chips;
use crate::solver::{build_tree_bounded, quality::ReferenceEvaluator, GameConfig};
use std::collections::BTreeMap;

type Policies = BTreeMap<usize, Vec<Vec<f64>>>;

/// Concrete history -> representative history. The same composed permutation
/// must map BOTH public cards and hole cards. Returns the count of nontrivial
/// swaps applied after an earlier nontrivial permutation (flop coverage).
fn expand(
    full: &Node,
    reduced: &Node,
    trainer: &Trainer,
    map: [u8; 52],
    out: &mut Policies,
    get: &impl Fn(usize) -> Vec<Vec<f64>>,
) -> usize {
    match (full, reduced) {
        (
            Node::Decision {
                id,
                player,
                actions,
                children,
            },
            Node::Decision {
                id: rid,
                player: rp,
                actions: ra,
                children: rc,
            },
        ) => {
            assert_eq!(player, rp);
            assert_eq!(format!("{actions:?}"), format!("{ra:?}"));
            let combos = trainer.game.combos(*player);
            let policy = get(*rid);
            let indices: Vec<_> = combos
                .iter()
                .map(
                    |&Combo {
                         cards: [a, b],
                         weight: w,
                     }| {
                        let (x, y) = (Card(map[a.0 as usize]), Card(map[b.0 as usize]));
                        let i = combos
                            .iter()
                            .position(|&Combo { cards: [c, d], .. }| {
                                (c == x && d == y) || (c == y && d == x)
                            })
                            .unwrap();
                        assert_eq!(w, combos[i].weight, "range weights must be suit symmetric");
                        i
                    },
                )
                .collect();
            assert!(out
                .insert(
                    *id,
                    policy
                        .iter()
                        .map(|row| indices.iter().map(|&i| row[i]).collect())
                        .collect()
                )
                .is_none());
            assert_eq!(children.len(), rc.len());
            children
                .iter()
                .zip(rc)
                .map(|(a, b)| expand(a, b, trainer, map, out, get))
                .sum()
        }
        (Node::Chance { children }, Node::Chance { children: rc }) => children
            .iter()
            .map(|(cards, child)| {
                assert_eq!(cards.len(), 1);
                let card = Card(map[cards[0].0 as usize]);
                let (members, rep) = rc
                    .iter()
                    .find(|(members, _)| members.contains(&card))
                    .unwrap();
                let (a, b) = (card.suit(), members[0].suit());
                let composed =
                    usize::from(a != b && map.iter().enumerate().any(|(i, &c)| i != c as usize));
                let mut next = map;
                for c in &mut next {
                    let s = *c % 4;
                    *c = *c / 4 * 4
                        + if s == a {
                            b
                        } else if s == b {
                            a
                        } else {
                            s
                        };
                }
                composed + expand(child, rep, trainer, next, out, get)
            })
            .sum(),
        (Node::Terminal(a), Node::Terminal(b)) => {
            assert_eq!(format!("{a:?}"), format!("{b:?}"));
            0
        }
        _ => panic!("tree shape mismatch"),
    }
}

fn projected(
    full: &Node,
    trainer: &Trainer,
    get: impl Fn(usize) -> Vec<Vec<f64>>,
) -> (Policies, usize) {
    let mut policies = Policies::new();
    let composed = expand(
        full,
        trainer.game.tree(),
        trainer,
        std::array::from_fn(|i| i as u8),
        &mut policies,
        &get,
    );
    (policies, composed)
}

fn config(board: &[&str]) -> GameConfig {
    GameConfig {
        board: board.iter().map(|s| s.parse::<Card>().unwrap()).collect(),
        pot: Chips::whole(100),
        effective_stack: Chips::whole(150),
        bet_sizes: vec![0.33, 0.75],
        max_raises: 1,
        suit_isomorphism: false,
    }
}

fn combos(cfg: &GameConfig, ranges: [&str; 2]) -> [Vec<Combo>; 2] {
    ranges.map(|s| {
        let mut cs = Range::parse(s)
            .unwrap()
            .combos(CardSet::from_cards(&cfg.board));
        for combo in &mut cs {
            combo.cards.sort_unstable();
        }
        cs.sort_by_key(|&Combo { cards: [a, b], .. }| (a, b));
        cs
    })
}

fn trainer(cfg: &GameConfig, cs: &[Vec<Combo>; 2], iso: bool) -> Trainer {
    let mut cfg = cfg.clone();
    cfg.suit_isomorphism = iso;
    Trainer::new(
        build_tree_bounded(&cfg, 100_000).unwrap(),
        cs.clone(),
        TrainerOptions {
            algorithm: SolverAlgorithm::Dcfr,
            schedule: UpdateSchedule::Alternating,
            ..TrainerOptions::default()
        },
    )
    .unwrap()
}

/// Compare individual normalized EVs and BRs, not just their zero-sum total.
fn audit(oracle: &ReferenceEvaluator<'_>, full: &Node, t: &Trainer, expected_composition: bool) {
    let (policy, composed) = projected(full, t, |id| t.average_strategy(id));
    if expected_composition {
        assert!(composed > 0, "exercise successive nontrivial suit swaps");
    }
    let q = oracle.evaluate(|id| policy[&id].clone()).unwrap();
    let actual = t.exploitability();
    let ev = t.evaluate().root_values.map(|v| v / q.joint_mass);
    for (name, a, b) in [
        ("OOP EV", ev[0], q.profile_ev[0]),
        ("IP EV", ev[1], q.profile_ev[1]),
        ("OOP BR", actual.oop, q.best_response_ev[0]),
        ("IP BR", actual.ip, q.best_response_ev[1]),
        ("exploitability", actual.total, q.exploitability),
    ] {
        assert!(
            (a - b).abs() < 1e-8,
            "{name} at {}: trainer={a} reference={b}",
            t.iterations_completed()
        );
    }
    println!(
        "audit iterations={} quality={} ev={ev:?} br={:?} max_error={:.3e}",
        t.iterations_completed(),
        q.exploitability,
        q.best_response_ev,
        [
            ev[0] - q.profile_ev[0],
            ev[1] - q.profile_ev[1],
            actual.oop - q.best_response_ev[0],
            actual.ip - q.best_response_ev[1]
        ]
        .into_iter()
        .map(f64::abs)
        .fold(0.0, f64::max)
    );
}

fn current(t: &Trainer, id: usize) -> Vec<Vec<f64>> {
    let data = t.node_data[id].lock().unwrap();
    let (actions, hands) = (data.regret_sum.len(), data.regret_sum[0].len());
    drop(data);
    t.current_strategy(id, actions, hands)
}

/// Diagnostics compare the same public history and concrete, board-live hand.
/// Never require two independently learned profiles to be numerically equal.
fn trace(full: &Trainer, reduced: &Trainer) {
    let (regrets, _) = projected(full.game.tree(), reduced, |id| {
        reduced.node_data[id].lock().unwrap().regret_sum.clone()
    });
    let (strategy, _) = projected(full.game.tree(), reduced, |id| current(reduced, id));
    let mut max_regret: f64 = 0.0;
    let mut max_policy = (0.0, 0, 0);
    for (&id, rows) in &regrets {
        let own = full.node_data[id].lock().unwrap();
        for (row, other) in rows.iter().zip(&own.regret_sum) {
            for (a, b) in row.iter().zip(other) {
                max_regret = max_regret.max((a - b).abs());
            }
        }
        drop(own);
        let own = current(full, id);
        let (player, board) = &full.game.node_meta[id];
        for (a, b) in own.iter().zip(&strategy[&id]) {
            for (i, (x, y)) in a.iter().zip(b).enumerate() {
                let [h1, h2] = full.game.combos[*player][i].cards;
                if !board.contains(&h1) && !board.contains(&h2) && (x - y).abs() > max_policy.0 {
                    max_policy = ((x - y).abs(), id, i);
                }
            }
        }
    }
    let (gap, id, i) = max_policy;
    println!("trace iterations={} regret_gap={max_regret:.3e} current_gap={gap} node={id} hand={i} board={:?} full_regrets={:?} reduced_regrets={:?}",
        full.iterations_completed(),full.game.node_board(id),full.node_data[id].lock().unwrap().regret_sum.iter().map(|r|r[i]).collect::<Vec<_>>(),regrets[&id].iter().map(|r|r[i]).collect::<Vec<_>>());
    println!(
        "trajectory full={} reduced={}",
        full.exploitability().total,
        reduced.exploitability().total
    );
}

#[test]
fn turn_fixed_profiles_match_independent_ev_and_each_best_response() {
    for threads in [1, 2] {
        rayon::ThreadPoolBuilder::new()
            .num_threads(threads)
            .build()
            .unwrap()
            .install(|| {
                let cfg = config(&["Js", "9s", "4d", "2d"]);
                let cs = combos(&cfg, ["AKs,AQs", "AKs,AQs"]);
                let tree = build_tree_bounded(&cfg, 100_000).unwrap();
                let oracle =
                    ReferenceEvaluator::new(&tree.root, &cfg.board, [&cs[0], &cs[1]]).unwrap();
                let (mut full, mut reduced) = (trainer(&cfg, &cs, false), trainer(&cfg, &cs, true));
                for step in 0..=25 {
                    if [0, 1, 2, 3, 4, 5, 25].contains(&step) {
                        audit(&oracle, &tree.root, &full, false);
                        audit(&oracle, &tree.root, &reduced, false);
                        if threads == 1 {
                            trace(&full, &reduced);
                        }
                    }
                    if step < 25 {
                        full.train(1);
                        reduced.train(1);
                    }
                }
            });
    }
}

#[test]
fn flop_fixed_profile_audits_composed_swaps_and_weighted_ranges() {
    rayon::ThreadPoolBuilder::new()
        .num_threads(2)
        .build()
        .unwrap()
        .install(|| {
            let mut cfg = config(&["Ks", "7s", "2s"]);
            cfg.effective_stack = Chips::whole(100);
            cfg.bet_sizes = vec![0.5];
            cfg.max_raises = 0;
            let cs = combos(&cfg, ["AKs:0.5,AQs", "AKs,AQs:0.25"]);
            let tree = build_tree_bounded(&cfg, 100_000).unwrap();
            assert!(tree.num_decision_nodes * cs[0].len() * cs[1].len() < 3_000_000);
            let oracle = ReferenceEvaluator::new(&tree.root, &cfg.board, [&cs[0], &cs[1]]).unwrap();
            let mut reduced = trainer(&cfg, &cs, true);
            for step in [0, 1, 5, 25] {
                reduced.train(step - reduced.iterations_completed() as u32);
                audit(&oracle, &tree.root, &reduced, true);
            }
        });
}

#[test]
fn tiny_positive_regrets_retain_scale_and_explain_zero_discontinuity() {
    let cfg = config(&["Js", "9s", "4d", "2d", "3c"]);
    let cs = combos(&cfg, ["AKs,AQs", "AKs,AQs"]);
    let t = trainer(&cfg, &cs, false);
    for scale in [1.0, 1e-18, 1e-100] {
        let mut data = t.node_data[0].lock().unwrap();
        for (row, value) in data.regret_sum.iter_mut().zip([-1.0, 1.0, 3.0]) {
            row.fill(value * scale);
        }
        drop(data);
        let policy = current(&t, 0);
        assert_eq!(
            [policy[0][0], policy[1][0], policy[2][0]],
            [0.0, 0.25, 0.75]
        );
    }
    let mut data = t.node_data[0].lock().unwrap();
    for row in &mut data.regret_sum {
        row.fill(0.0);
    }
    drop(data);
    assert_eq!(current(&t, 0)[0][0], 1.0 / 3.0);
}

// Manual audits of the two archived matrix fixtures. More expensive than the
// small CI cases; bounded trees and explicit pair-work caps remain enforced.
fn audit_matrix(mut cfg: GameConfig, ranges: [&str; 2], checkpoints: &[u32]) {
    rayon::ThreadPoolBuilder::new()
        .num_threads(1)
        .build()
        .unwrap()
        .install(|| {
            cfg.suit_isomorphism = false;
            let cs = combos(&cfg, ranges);
            let tree = build_tree_bounded(&cfg, 100_000).unwrap();
            let work = tree.num_decision_nodes * cs[0].len() * cs[1].len();
            assert!(work < 300_000_000, "manual audit work budget");
            println!(
                "matrix nodes={} combos={:?} pair_work={work}",
                tree.num_decision_nodes,
                cs.each_ref().map(Vec::len)
            );
            let oracle = ReferenceEvaluator::new(&tree.root, &cfg.board, [&cs[0], &cs[1]]).unwrap();
            let (mut full, mut reduced) = (trainer(&cfg, &cs, false), trainer(&cfg, &cs, true));
            for &step in checkpoints {
                full.train(step - full.iterations_completed() as u32);
                reduced.train(step - reduced.iterations_completed() as u32);
                audit(&oracle, &tree.root, &full, false);
                audit(&oracle, &tree.root, &reduced, cfg.board.len() == 3);
                println!(
                    "matrix trajectory step={step} full={} reduced={}",
                    full.exploitability().total,
                    reduced.exploitability().total
                );
            }
        });
}

#[test]
#[ignore = "bounded manual audit of archived wide matrix case"]
fn matrix_turn_wide_fixed_profiles() {
    audit_matrix(config(&["Js","9s","4d","2d"]),[
        "AA,KK,QQ,JJ,TT,99,88,77,66,55,44,33,22,AKs,AQs,AJs,ATs,A9s,A8s,A7s,A6s,A5s,A4s,A3s,A2s,KQs,KJs,KTs,K9s,QJs,QTs,JTs,T9s,98s,87s,76s,65s,54s,AKo,AQo,AJo,KQo",
        "AA,KK,QQ,JJ,TT,99,88,77,66,55,44,33,22,AKs,AQs,AJs,ATs,A9s,A8s,A7s,A6s,A5s,A4s,A3s,A2s,KQs,KJs,KTs,K9s,K8s,QJs,QTs,Q9s,JTs,J9s,T9s,T8s,98s,97s,87s,86s,76s,75s,65s,64s,54s,AKo,AQo,AJo,ATo,KQo,KJo,QJo"
    ],&[25,150]);
}

#[test]
#[ignore = "bounded manual audit of archived medium matrix case"]
fn matrix_flop_medium_fixed_profiles() {
    let mut cfg = config(&["Ks", "7s", "2s"]);
    cfg.effective_stack = Chips::whole(100);
    cfg.bet_sizes = vec![0.5];
    cfg.max_raises = 0;
    audit_matrix(
        cfg,
        ["AA,KK,QQ,JJ,TT,AKs,AQs,KQs", "QQ,JJ,TT,99,88,AQs,AJs,KQs"],
        &[25, 50, 75],
    );
}

fn assert_policy_symmetry(t: &Trainer) {
    let mut compared = 0;
    for (id, (player, board)) in t.game.node_meta.iter().enumerate() {
        let free: Vec<_> = (0..4)
            .filter(|s| !board.iter().any(|&c| c.suit() == *s))
            .collect();
        let (_, buckets) = t.game.combo_buckets(*player, board);
        let current = current(t, id);
        let average = t.average_strategy(id);
        for &a in &free {
            for &b in &free {
                if a >= b {
                    continue;
                }
                for (
                    i,
                    &Combo {
                        cards: [h1, h2], ..
                    },
                ) in t.game.combos[*player].iter().enumerate()
                {
                    let mapped = normalize_pair(swap_suit(h1, a, b), swap_suit(h2, a, b));
                    let j = t.game.combos[*player]
                        .iter()
                        .position(|&Combo { cards: [c, d], .. }| normalize_pair(c, d) == mapped)
                        .unwrap();
                    if i == j {
                        continue;
                    }
                    for row in &current {
                        assert_eq!(row[buckets[i]], row[buckets[j]], "current node {id}");
                    }
                    for row in &average {
                        assert_eq!(row[i], row[j], "average node {id}");
                    }
                    compared += 1;
                }
            }
        }
        for i in 0..t.game.combos[*player].len() {
            assert!((average.iter().map(|r| r[i]).sum::<f64>() - 1.0).abs() < 1e-12);
            assert!((current.iter().map(|r| r[buckets[i]]).sum::<f64>() - 1.0).abs() < 1e-12);
        }
    }
    assert!(compared > 0);
}

#[test]
fn reduced_policies_are_exactly_symmetric_across_algorithms_and_buckets() {
    rayon::ThreadPoolBuilder::new()
        .num_threads(2)
        .build()
        .unwrap()
        .install(|| {
            let mut cfg = config(&["Js", "9s", "4d", "2d"]);
            let cs = combos(&cfg, ["AKs:0.5,AQs", "AKs,AQs:0.25"]);
            let full = build_tree_bounded(&cfg, 100_000).unwrap();
            let oracle = ReferenceEvaluator::new(&full.root, &cfg.board, [&cs[0], &cs[1]]).unwrap();
            cfg.suit_isomorphism = true;
            for algorithm in [
                SolverAlgorithm::Cfr,
                SolverAlgorithm::CfrPlus,
                SolverAlgorithm::Dcfr,
            ] {
                for schedule in [UpdateSchedule::Simultaneous, UpdateSchedule::Alternating] {
                    for abstraction in [
                        CardAbstraction::default(),
                        CardAbstraction {
                            flop: None,
                            turn: Some(3),
                            river: Some(3),
                        },
                    ] {
                        let mut t = Trainer::new(
                            build_tree_bounded(&cfg, 100_000).unwrap(),
                            cs.clone(),
                            TrainerOptions {
                                algorithm,
                                schedule,
                                abstraction,
                            },
                        )
                        .unwrap();
                        t.train(25);
                        assert_policy_symmetry(&t);
                        audit(&oracle, &full.root, &t, false);
                    }
                }
            }
        });
}

#[test]
fn reduced_tree_rejects_asymmetric_initial_weights() {
    let mut cfg = config(&["Js", "9s", "4d", "2d"]);
    let mut cs = combos(&cfg, ["AKs,AQs", "AKs,AQs"]);
    cs[0][0].weight = 0.25;
    let new = |cfg: &GameConfig| {
        Trainer::new(
            build_tree_bounded(cfg, 100_000).unwrap(),
            cs.clone(),
            TrainerOptions::default(),
        )
    };
    cfg.suit_isomorphism = true;
    assert_eq!(
        new(&cfg).err(),
        Some(TrainerError::AsymmetricRange {
            player: Player::Oop
        })
    );
    // Without reduction the same asymmetric range is a legal game.
    cfg.suit_isomorphism = false;
    assert!(new(&cfg).is_ok());
}