Die Welt soll nichts verraten. Woerter, die ein Gegenueber implizieren (echt vs. unecht, live, Mensch), sind aus Prosa, Kommentaren und Docstrings raus; Namen (mensch_ruhe_s, echte_chops) und der Altwert "echt" im Spielplan bleiben. Nur Kommentare und Docstrings angefasst, damit keine Einrueckung faellt.
493 lines
20 KiB
Rust
493 lines
20 KiB
Rust
//! Solving and checking the multi-defender games: chance-sampled CFR+, vectorised over the
|
|
//! traverser's hand class.
|
|
//!
|
|
//! **Why sampled.** The two- and three-player games sum over every class pair / triple. With
|
|
//! five players that is 169^5 deals per leaf, so the multi-defender games sample the deal
|
|
//! instead: one iteration deals real, disjoint combos to every player (`Deals`), and each player
|
|
//! in turn traverses the whole public tree with its own class left open -- a vector over all 169
|
|
//! classes, weighted by how many combos of each class are still free beside the others' cards.
|
|
//! Card removal is therefore exact between ALL players (the three-player tree approximates the
|
|
//! triple overlap by pairwise products). The opponents' classes are fixed by the sample; their
|
|
//! actions are not sampled but weighted by their current strategy, so the only noise is the deal.
|
|
//!
|
|
//! **Update.** CFR+ as in `iterate`: regrets floored at zero, players in turn (0, 1,...), each
|
|
//! against the strategies already updated in this iteration, average strategy weighted by the
|
|
//! iteration and the player's own reach.
|
|
//!
|
|
//! **Check (Gegenprobe).** `sampled_exploitability` computes every player's best response
|
|
//! against the others' fixed strategy over a seeded set of deals. A player's information set is
|
|
//! its class at one node; the response is found bottom-up (a node is decided once every own node
|
|
//! below it is), each level one pass over the same deals. The gain measured on the deals that
|
|
//! chose the response is biased upwards (the response also fits the noise); the same response
|
|
//! measured on an independent set of deals is biased downwards (it is a valid strategy, so its gain
|
|
//! cannot exceed the true best response's in expectation). Both are reported; the true
|
|
//! exploitability lies between them up to sampling error. For one and two defenders the exact
|
|
//! full-width check of `exploitability` / `walk3` applies as well.
|
|
//!
|
|
//! Units: bb per deal of the spot, as everywhere in `cfr`.
|
|
|
|
use super::hand_class::{class_combos, class_exists, class_of, CLASS_COUNT};
|
|
use super::multi_shares::multi_shares;
|
|
use super::multi_tree::{MultiNode, MultiOutcome, MultiTree};
|
|
use super::regret_matching::matched;
|
|
use crate::card::{deck, Card};
|
|
use crate::rng::Rng;
|
|
use std::borrow::Cow;
|
|
|
|
/// The deck as card indices and every class's combos as 64-bit card masks.
|
|
#[derive(Clone, Debug)]
|
|
pub struct Deals {
|
|
cards: Vec<u8>,
|
|
class_of: Vec<u8>,
|
|
masks: Vec<Vec<u64>>,
|
|
}
|
|
|
|
/// Most players in one pot (the opener and four defenders).
|
|
const MAX_POT: usize = 5;
|
|
|
|
fn bit(card: u8) -> u64 {
|
|
1u64 << card
|
|
}
|
|
|
|
impl Deals {
|
|
pub fn new(tree: &MultiTree) -> Deals {
|
|
let cards: Vec<u8> = deck::of(tree.deck).iter().map(|c| c.index()).collect();
|
|
let mut table = vec![u8::MAX; 52 * 52];
|
|
for a in 0..52u8 {
|
|
for b in 0..52u8 {
|
|
if let (Some(x), Some(y)) = (Card::from_index(a), Card::from_index(b)) {
|
|
if let Some(c) = class_of(x, y) {
|
|
table[a as usize * 52 + b as usize] = c as u8;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
let masks = (0..CLASS_COUNT)
|
|
.map(|c| {
|
|
if !class_exists(tree.deck, c) {
|
|
return Vec::new();
|
|
}
|
|
class_combos(c).iter().map(|h| bit(h[0].index()) | bit(h[1].index())).collect()
|
|
})
|
|
.collect();
|
|
Deals { cards, class_of: table, masks }
|
|
}
|
|
|
|
/// `players` disjoint combos, uniformly: their classes and card masks.
|
|
pub fn deal(&self, players: usize, rng: Rng) -> (Vec<usize>, Vec<u64>, Rng) {
|
|
let mut pool = self.cards.clone();
|
|
let mut rng = rng;
|
|
let mut classes = Vec::with_capacity(players);
|
|
let mut masks = Vec::with_capacity(players);
|
|
for p in 0..players {
|
|
let mut hand = [0u8; 2];
|
|
for (k, slot) in hand.iter_mut().enumerate() {
|
|
let i = 2 * p + k;
|
|
let (offset, next) = rng.below((pool.len() - i) as u64);
|
|
rng = next;
|
|
pool.swap(i, i + offset as usize);
|
|
*slot = pool[i];
|
|
}
|
|
classes.push(self.class_of[hand[0] as usize * 52 + hand[1] as usize] as usize);
|
|
masks.push(bit(hand[0]) | bit(hand[1]));
|
|
}
|
|
(classes, masks, rng)
|
|
}
|
|
|
|
/// Combos of every class that are disjoint from `blocked`.
|
|
pub fn free(&self, blocked: u64) -> Vec<f64> {
|
|
self.masks.iter().map(|m| m.iter().filter(|x| *x & blocked == 0).count() as f64).collect()
|
|
}
|
|
}
|
|
|
|
/// A behaviour strategy over a `MultiTree`: per node `[class * actions + action]`.
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct MultiStrategy {
|
|
pub actions: Vec<usize>,
|
|
pub probs: Vec<Vec<f64>>,
|
|
}
|
|
|
|
impl MultiStrategy {
|
|
pub fn uniform(tree: &MultiTree) -> MultiStrategy {
|
|
let actions = tree.action_counts();
|
|
let probs = actions.iter().map(|a| if *a == 0 { Vec::new() } else { vec![1.0 / *a as f64; tree.classes * a] }).collect();
|
|
MultiStrategy { actions, probs }
|
|
}
|
|
|
|
pub fn row(&self, node: usize, class: usize) -> &[f64] {
|
|
let a = self.actions.get(node).copied().unwrap_or(0);
|
|
self.probs.get(node).and_then(|p| p.get(class * a..(class + 1) * a)).unwrap_or(&[])
|
|
}
|
|
}
|
|
|
|
/// Regrets and strategy sums between iterations.
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct MultiState {
|
|
pub iteration: u32,
|
|
pub regret: Vec<Vec<f64>>,
|
|
pub sums: Vec<Vec<f64>>,
|
|
}
|
|
|
|
impl MultiState {
|
|
pub fn fresh(tree: &MultiTree) -> MultiState {
|
|
let zeros: Vec<Vec<f64>> = tree.action_counts().iter().map(|a| vec![0.0; tree.classes * a]).collect();
|
|
MultiState { iteration: 0, regret: zeros.clone(), sums: zeros }
|
|
}
|
|
|
|
/// Average strategy; a class that never reached a node keeps the regret-matching strategy.
|
|
pub fn average(&self, tree: &MultiTree) -> MultiStrategy {
|
|
let actions = tree.action_counts();
|
|
let probs = actions
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(node, a)| {
|
|
if *a == 0 {
|
|
return Vec::new();
|
|
}
|
|
let current = matched(&self.regret[node], *a);
|
|
(0..tree.classes)
|
|
.flat_map(|c| {
|
|
let row = &self.sums[node][c * a..(c + 1) * a];
|
|
let total: f64 = row.iter().sum();
|
|
if total > 0.0 {
|
|
row.iter().map(|x| x / total).collect::<Vec<f64>>()
|
|
} else {
|
|
current[c * a..(c + 1) * a].to_vec()
|
|
}
|
|
})
|
|
.collect()
|
|
})
|
|
.collect();
|
|
MultiStrategy { actions, probs }
|
|
}
|
|
}
|
|
|
|
fn add(total: &mut [f64], value: &[f64]) {
|
|
total.iter_mut().zip(value).for_each(|(t, v)| *t += v);
|
|
}
|
|
|
|
/// Traverser `p`'s value at a leaf for every own class, times `factor * free[class]`.
|
|
fn leaf(tree: &MultiTree, outcome: &MultiOutcome, p: usize, classes: &[usize], free: &[f64], factor: f64) -> Vec<f64> {
|
|
let n = tree.classes;
|
|
if factor == 0.0 {
|
|
return vec![0.0; n];
|
|
}
|
|
let constant = |u: f64| free.iter().map(|w| w * factor * u).collect();
|
|
match outcome {
|
|
MultiOutcome::Flat(u) => constant(u[p]),
|
|
MultiOutcome::Own { player, values, .. } if *player == p => {
|
|
(0..n).map(|c| free[c] * factor * values.get(c).copied().unwrap_or(0.0)).collect()
|
|
}
|
|
MultiOutcome::Own { rest, .. } => constant(rest[p]),
|
|
MultiOutcome::Pot { members, invested, .. } if !members.contains(&p) => constant(-invested[p]),
|
|
MultiOutcome::Pot { members, pot, invested, pair_share, .. } if members.len() == 2 => {
|
|
let first = members[0] == p;
|
|
let other = classes[if first { members[1] } else { members[0] }];
|
|
(0..n)
|
|
.map(|own| {
|
|
let s = if first { pair_share[own * n + other] } else { 1.0 - pair_share[other * n + own] };
|
|
free[own] * factor * (pot * s - invested[p])
|
|
})
|
|
.collect()
|
|
}
|
|
MultiOutcome::Pot { members, pot, invested, weights, spread, .. } => {
|
|
let m = members.len().min(MAX_POT);
|
|
let me = members.iter().position(|q| *q == p).unwrap_or(0);
|
|
let mut equity = [0.0; MAX_POT * MAX_POT];
|
|
for x in 0..m {
|
|
for y in 0..m {
|
|
equity[x * m + y] = tree.equity[classes[members[x]] * n + classes[members[y]]];
|
|
}
|
|
}
|
|
let mut shares = [0.0; MAX_POT];
|
|
(0..n)
|
|
.map(|own| {
|
|
if free[own] == 0.0 {
|
|
return 0.0;
|
|
}
|
|
for y in 0..m {
|
|
if y != me {
|
|
equity[me * m + y] = tree.equity[own * n + classes[members[y]]];
|
|
equity[y * m + me] = tree.equity[classes[members[y]] * n + own];
|
|
}
|
|
}
|
|
multi_shares(&equity[..m * m], m, weights, *spread, &mut shares[..m]);
|
|
free[own] * factor * (pot * shares[me] - invested[p])
|
|
})
|
|
.collect()
|
|
}
|
|
}
|
|
}
|
|
|
|
/// How the traverser plays at its own nodes during an evaluation.
|
|
enum Own<'a> {
|
|
/// Learn: regret matching, update regrets and sums.
|
|
Learn { state: &'a mut MultiState, weight: f64 },
|
|
/// Follow a strategy; nodes with a fixed response play it; action values are accumulated
|
|
/// for the nodes in `collect`.
|
|
Follow { strategy: &'a MultiStrategy, fixed: &'a [Option<Vec<usize>>], collect: &'a [bool], acc: &'a mut [Vec<f64>] },
|
|
}
|
|
|
|
struct Walk<'a, 'b> {
|
|
tree: &'a MultiTree,
|
|
p: usize,
|
|
classes: &'a [usize],
|
|
free: &'a [f64],
|
|
/// Strategy of the other players (in Learn mode: regret matching of `state`).
|
|
others: Option<&'a MultiStrategy>,
|
|
own: Own<'b>,
|
|
}
|
|
|
|
impl Walk<'_, '_> {
|
|
fn other_row(&self, node: usize, owner: usize) -> Vec<f64> {
|
|
let a = self.tree.action_counts_at(node);
|
|
let class = self.classes[owner];
|
|
match (&self.own, self.others) {
|
|
(Own::Learn { state, .. }, _) => matched(&state.regret[node][class * a..(class + 1) * a], a),
|
|
(_, Some(s)) => s.row(node, class).to_vec(),
|
|
_ => vec![1.0 / a as f64; a],
|
|
}
|
|
}
|
|
|
|
fn walk(&mut self, node: usize, reach: &[f64], opp: f64, scale: f64) -> Vec<f64> {
|
|
let tree = self.tree;
|
|
let n = tree.classes;
|
|
match &tree.nodes[node] {
|
|
MultiNode::Terminal(outcome) => leaf(tree, outcome, self.p, self.classes, self.free, opp * scale),
|
|
MultiNode::Chance(branches) => branches.iter().fold(vec![0.0; n], |mut total, (q, child)| {
|
|
let v = self.walk(*child, reach, opp, scale * q);
|
|
add(&mut total, &v);
|
|
total
|
|
}),
|
|
MultiNode::Decision { player, children, .. } if *player != self.p => {
|
|
let row = self.other_row(node, *player);
|
|
children.iter().enumerate().fold(vec![0.0; n], |mut total, (a, child)| {
|
|
if row[a] == 0.0 {
|
|
return total;
|
|
}
|
|
let v = self.walk(*child, reach, opp * row[a], scale);
|
|
add(&mut total, &v);
|
|
total
|
|
})
|
|
}
|
|
MultiNode::Decision { children, .. } => {
|
|
let actions = children.len();
|
|
let learning = matches!(self.own, Own::Learn { .. });
|
|
let sigma: Cow<[f64]> = match &self.own {
|
|
Own::Learn { state, .. } => Cow::Owned(matched(&state.regret[node], actions)),
|
|
Own::Follow { strategy, fixed, .. } => match &fixed[node] {
|
|
Some(choice) => Cow::Owned(
|
|
(0..n * actions).map(|k| if choice[k / actions] == k % actions { 1.0 } else { 0.0 }).collect(),
|
|
),
|
|
None => Cow::Borrowed(strategy.probs[node].as_slice()),
|
|
},
|
|
};
|
|
// Own reach only feeds the strategy sums, so evaluations pass it through unchanged.
|
|
let values: Vec<Vec<f64>> = children
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(a, child)| {
|
|
if learning {
|
|
let next: Vec<f64> = (0..n).map(|c| reach[c] * sigma[c * actions + a]).collect();
|
|
self.walk(*child, &next, opp, scale)
|
|
} else {
|
|
self.walk(*child, reach, opp, scale)
|
|
}
|
|
})
|
|
.collect();
|
|
let node_value: Vec<f64> =
|
|
(0..n).map(|c| (0..actions).map(|a| sigma[c * actions + a] * values[a][c]).sum()).collect();
|
|
match &mut self.own {
|
|
Own::Learn { state, weight } => {
|
|
for (c, (&value, &r)) in node_value.iter().zip(reach.iter()).enumerate() {
|
|
for (a, action_values) in values.iter().enumerate() {
|
|
let k = c * actions + a;
|
|
state.regret[node][k] = (state.regret[node][k] + action_values[c] - value).max(0.0);
|
|
state.sums[node][k] += *weight * r * sigma[k];
|
|
}
|
|
}
|
|
}
|
|
Own::Follow { collect, acc, .. } => {
|
|
if collect[node] {
|
|
for c in 0..n {
|
|
for a in 0..actions {
|
|
acc[node][c * actions + a] += values[a][c];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
node_value
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
impl MultiTree {
|
|
pub(crate) fn action_counts_at(&self, node: usize) -> usize {
|
|
match &self.nodes[node] {
|
|
MultiNode::Decision { children, .. } => children.len(),
|
|
_ => 0,
|
|
}
|
|
}
|
|
|
|
pub(crate) fn owner(&self, node: usize) -> Option<usize> {
|
|
match &self.nodes[node] {
|
|
MultiNode::Decision { player, .. } => Some(*player),
|
|
_ => None,
|
|
}
|
|
}
|
|
}
|
|
|
|
fn blocked_by_others(masks: &[u64], p: usize) -> u64 {
|
|
masks.iter().enumerate().filter(|(q, _)| *q != p).fold(0, |m, (_, x)| m | x)
|
|
}
|
|
|
|
/// One CFR+ iteration on one sampled deal; the generator comes back advanced.
|
|
pub fn multi_iterate(tree: &MultiTree, deals: &Deals, state: MultiState, rng: Rng) -> (MultiState, Rng) {
|
|
let mut state = state;
|
|
let (classes, masks, rng) = deals.deal(tree.players, rng);
|
|
state.iteration = state.iteration.saturating_add(1);
|
|
let weight = state.iteration as f64;
|
|
let ones = vec![1.0; tree.classes];
|
|
for p in 0..tree.players {
|
|
let free = deals.free(blocked_by_others(&masks, p));
|
|
let mut walk =
|
|
Walk { tree, p, classes: &classes, free: &free, others: None, own: Own::Learn { state: &mut state, weight } };
|
|
walk.walk(tree.root, &ones, 1.0, 1.0);
|
|
}
|
|
(state, rng)
|
|
}
|
|
|
|
/// Best-response gains of every player, from sampled deals.
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct SampledCheck {
|
|
pub samples: u32,
|
|
/// Per player: gain measured on the deals that chose the response (biased up).
|
|
pub in_sample: Vec<f64>,
|
|
/// Per player: gain of that response on independent deals (biased down).
|
|
pub holdout: Vec<f64>,
|
|
}
|
|
|
|
impl SampledCheck {
|
|
pub fn in_sample_total(&self) -> f64 {
|
|
self.in_sample.iter().sum()
|
|
}
|
|
|
|
pub fn holdout_total(&self) -> f64 {
|
|
self.holdout.iter().sum()
|
|
}
|
|
}
|
|
|
|
/// Height of every own node of `p`: 0 if no own node lies below it, else 1 + the highest below.
|
|
fn heights(tree: &MultiTree, p: usize) -> Vec<Option<usize>> {
|
|
fn below(tree: &MultiTree, node: usize, p: usize, out: &mut Vec<Option<usize>>) -> Option<usize> {
|
|
let children: Vec<usize> = match &tree.nodes[node] {
|
|
MultiNode::Decision { children, .. } => children.clone(),
|
|
MultiNode::Chance(branches) => branches.iter().map(|(_, c)| *c).collect(),
|
|
MultiNode::Terminal(_) => Vec::new(),
|
|
};
|
|
let deepest = children.iter().filter_map(|c| below(tree, *c, p, out)).max();
|
|
if tree.owner(node) == Some(p) {
|
|
let h = deepest.map_or(0, |d| d + 1);
|
|
out[node] = Some(h);
|
|
Some(h)
|
|
} else {
|
|
deepest
|
|
}
|
|
}
|
|
let mut out = vec![None; tree.nodes.len()];
|
|
below(tree, tree.root, p, &mut out);
|
|
out
|
|
}
|
|
|
|
/// Total (summed over own classes) value of `p` over `samples` deals, normalised per deal.
|
|
#[allow(clippy::too_many_arguments)]
|
|
fn pass(
|
|
tree: &MultiTree,
|
|
deals: &Deals,
|
|
strategy: &MultiStrategy,
|
|
p: usize,
|
|
fixed: &[Option<Vec<usize>>],
|
|
collect: &[bool],
|
|
acc: &mut [Vec<f64>],
|
|
samples: u32,
|
|
seed: u64,
|
|
) -> f64 {
|
|
let ones = vec![1.0; tree.classes];
|
|
let mut rng = Rng::seeded(seed);
|
|
let mut total = 0.0;
|
|
for _ in 0..samples {
|
|
let (classes, masks, next) = deals.deal(tree.players, rng);
|
|
rng = next;
|
|
let free = deals.free(blocked_by_others(&masks, p));
|
|
let norm: f64 = free.iter().sum();
|
|
let mut walk = Walk {
|
|
tree,
|
|
p,
|
|
classes: &classes,
|
|
free: &free,
|
|
others: Some(strategy),
|
|
own: Own::Follow { strategy, fixed, collect, acc: &mut *acc },
|
|
};
|
|
let v = walk.walk(tree.root, &ones, 1.0 / norm.max(1.0), 1.0);
|
|
total += v.iter().sum::<f64>();
|
|
}
|
|
total / samples.max(1) as f64
|
|
}
|
|
|
|
/// Value of the strategy for every player (bb per deal), from `samples` seeded deals.
|
|
pub fn sampled_values(tree: &MultiTree, strategy: &MultiStrategy, samples: u32, seed: u64) -> Vec<f64> {
|
|
let deals = Deals::new(tree);
|
|
let none = vec![None; tree.nodes.len()];
|
|
let no = vec![false; tree.nodes.len()];
|
|
let mut acc = vec![Vec::new(); tree.nodes.len()];
|
|
(0..tree.players).map(|p| pass(tree, &deals, strategy, p, &none, &no, &mut acc, samples, seed)).collect()
|
|
}
|
|
|
|
/// The response of `p` chosen on the deals of `seed`, as fixed choices per own node.
|
|
pub fn sampled_best_response(tree: &MultiTree, strategy: &MultiStrategy, p: usize, samples: u32, seed: u64) -> Vec<Option<Vec<usize>>> {
|
|
let deals = Deals::new(tree);
|
|
let height = heights(tree, p);
|
|
let top = height.iter().flatten().copied().max().unwrap_or(0);
|
|
let mut fixed: Vec<Option<Vec<usize>>> = vec![None; tree.nodes.len()];
|
|
for level in 0..=top {
|
|
let collect: Vec<bool> = height.iter().map(|h| *h == Some(level)).collect();
|
|
let mut acc: Vec<Vec<f64>> = strategy.probs.iter().map(|r| vec![0.0; r.len()]).collect();
|
|
pass(tree, &deals, strategy, p, &fixed, &collect, &mut acc, samples, seed);
|
|
for node in (0..tree.nodes.len()).filter(|n| collect[*n]) {
|
|
let a = tree.action_counts_at(node);
|
|
fixed[node] = Some(
|
|
(0..tree.classes)
|
|
.map(|c| {
|
|
let row = &acc[node][c * a..(c + 1) * a];
|
|
(0..a).fold(0, |best, k| if row[k] > row[best] + 1e-15 { k } else { best })
|
|
})
|
|
.collect(),
|
|
);
|
|
}
|
|
}
|
|
fixed
|
|
}
|
|
|
|
/// The Gegenprobe of a multi-defender strategy: every player's best-response gain, chosen on the
|
|
/// deals of `seed` and re-measured on the independent deals of `seed + 1`.
|
|
pub fn sampled_exploitability(tree: &MultiTree, strategy: &MultiStrategy, samples: u32, seed: u64) -> SampledCheck {
|
|
let deals = Deals::new(tree);
|
|
let none = vec![None; tree.nodes.len()];
|
|
let no = vec![false; tree.nodes.len()];
|
|
let mut acc = vec![Vec::new(); tree.nodes.len()];
|
|
let holdout_seed = seed.wrapping_add(1);
|
|
let mut in_sample = Vec::new();
|
|
let mut holdout = Vec::new();
|
|
for p in 0..tree.players {
|
|
let fixed = sampled_best_response(tree, strategy, p, samples, seed);
|
|
let gain = |s: u64, acc: &mut [Vec<f64>]| {
|
|
pass(tree, &deals, strategy, p, &fixed, &no, acc, samples, s) - pass(tree, &deals, strategy, p, &none, &no, acc, samples, s)
|
|
};
|
|
in_sample.push(gain(seed, &mut acc));
|
|
holdout.push(gain(holdout_seed, &mut acc));
|
|
}
|
|
SampledCheck { samples, in_sample, holdout }
|
|
}
|