diff --git a/entscheiden/motor/loeser-temp.patch b/entscheiden/motor/loeser-temp.patch index ac7ce4d0..d27dc017 100644 --- a/entscheiden/motor/loeser-temp.patch +++ b/entscheiden/motor/loeser-temp.patch @@ -1,7 +1,7 @@ diff -ruN postflop-solver-mess/src/game/boltzmann.rs postflop-solver-temp/src/game/boltzmann.rs --- postflop-solver-mess/src/game/boltzmann.rs 1970-01-01 01:00:00 -+++ postflop-solver-temp/src/game/boltzmann.rs 2026-12-02 00:27:16 -@@ -0,0 +1,468 @@ ++++ postflop-solver-temp/src/game/boltzmann.rs 2026-12-02 11:44:56 +@@ -0,0 +1,477 @@ +//! Messkopie Temperatur: der Gegner als Boltzmann-Antworter (Quantal Response) gegen unsere Strategie. +//! +//! Der Gegner (`gegner`) waehlt an JEDEM seiner Knoten n mit Hand h den Zug a mit @@ -19,9 +19,10 @@ diff -ruN postflop-solver-mess/src/game/boltzmann.rs postflop-solver-temp/src/ga +//! +//! Wir (der andere Spieler) minimieren Regret (DCFR wie bisher). Er auch: er fuehrt DCFR wie wir, aber auf entropie-transformierten Werten +//! -+//! u(a) = cfv(a) - (N_eps / nc) * (Topf / lambda) * (ln max(tau_t(a), DELTA) - ln w(a)), w(a) = exp(beta_Art) / m_Art ++//! u(a) = cfv(a) - (N_eps / nc) * (Topf / lambda) * (ln max(rho_t(a), DELTA) - ln w(a)), w(a) = exp(beta_Art) / m_Art +//! -+//! (tau_t = seine aktuelle Regret-Matching-Strategie; nach oben gereicht wird der reine Chip-Wert). Sein stationaerer Punkt ist genau ++//! (rho_t = Bezugsstrategie: Mischung aus seiner aktuellen Regret-Matching-Strategie tau_t und seiner Durchschnittsstrategie bisher, ++//! `BEZUG_MITTEL`; nach oben gereicht wird der reine Chip-Wert unter tau_t). Sein stationaerer Punkt ist genau +//! tau ~ w * exp(lambda * Q / Topf); fuer lambda -> inf faellt der Zusatz weg und der Durchgang ist der gewoehnliche DCFR-Schritt. Seine +//! Ausgabe ist die normierte Durchschnittsstrategie (`strategy()`, `finalize` wie im Bestand). Bei lambda = 0 ist tau der Anker, direkt +//! gesetzt (`boltzmann_setze`, ein definierter Sonderfall des Modells, keine Naeherung). Warum dieses Verfahren und nicht tau = QR(sigma) @@ -48,8 +49,15 @@ diff -ruN postflop-solver-mess/src/game/boltzmann.rs postflop-solver-temp/src/ga +/// Zufallsknoten bis hierher). Ohne Boden waere Q = 0/0 bei N -> 0 und seine Antwort unstetig in unserer Strategie; mit ihm geht +/// Q -> 0 und er spielt seinen Anker (nur beta und -ln m). Eine Konstante der Normierung, nicht des Limits. +pub const BODEN_REL: f64 = 1e-3; -+/// Untergrenze von tau im Logarithmus der Strafe des Regret-Verfahrens. ++/// Untergrenze der Bezugsstrategie im Logarithmus der Strafe des Regret-Verfahrens. +pub const DELTA: f32 = 1e-6; ++/// Gewicht seiner Durchschnittsstrategie in der Bezugsstrategie der Strafe: rho_t = BEZUG_MITTEL * tau_quer_t + (1 - BEZUG_MITTEL) * tau_t. ++/// Regret-Matching setzt tau_t(a) oft exakt auf 0; mit rho = tau_t (Gewicht 0) springt die Strafe dann um ln DELTA, und bei kleinem lambda ++/// und schiefem Anker (stark negative Neigung einer Art) haengt seine Durchschnittsstrategie lange hinter dem Modell (eps2 gross). Jede ++/// Bezugsstrategie, die im stationaeren Punkt mit tau zusammenfaellt, hat denselben stationaeren Punkt tau ~ w * exp(lambda * Q / Topf); ++/// das Gewicht aendert nur die Dynamik. Gemessen (messung/motor/temperatur/loeser-verfahren.md, Runde 3): 0,5 und 0,75 fast gleich, ++/// 0 und 1 deutlich schlechter. Eine Konstante des Verfahrens, nicht des Limits. ++pub const BEZUG_MITTEL: f32 = 0.5; + +/// Die Parameter des Gegners. `lambda` >= 0 (dimensionslos, mal Q / Topf), `beta_*` sind Neigungen je Art im Logit. +#[derive(Clone, Copy, Debug, PartialEq)] @@ -274,10 +282,11 @@ diff -ruN postflop-solver-mess/src/game/boltzmann.rs postflop-solver-temp/src/ga + (tau, fehler) + } + -+ /// Strafe des Regret-Verfahrens (`a * nh`, cfv-Einheit), um den Mittelwert unter `strategy` bereinigt: -+ /// (N_eps / nc) * (Topf / lambda) * (ln max(tau(a), DELTA) - ln w(a)) minus ihr Mittel unter tau. ++ /// Strafe des Regret-Verfahrens (`a * nh`, cfv-Einheit), um den Mittelwert unter `strategy` (der gespielten Strategie tau_t) bereinigt: ++ /// (N_eps / nc) * (Topf / lambda) * (ln max(rho(a), DELTA) - ln w(a)) minus ihr Mittel unter tau_t. `bezug` = rho_t ist die ++ /// Bezugsstrategie des Logarithmus (`bezugsstrategie`). + #[allow(clippy::too_many_arguments)] -+ pub(crate) fn regulaer_strafe(&self, node: &PostFlopNode, strategy: &[f32], cfreach: &[f32], player: usize, b: &Boltzmann, strassenbeginn: i32, skala: f64) -> Vec { ++ pub(crate) fn regulaer_strafe(&self, node: &PostFlopNode, strategy: &[f32], bezug: &[f32], cfreach: &[f32], player: usize, b: &Boltzmann, strassenbeginn: i32, skala: f64) -> Vec { + let na = node.num_actions(); + let nh = self.num_private_hands(player); + if b.lambda == 0.0 { @@ -291,7 +300,7 @@ diff -ruN postflop-solver-mess/src/game/boltzmann.rs postflop-solver-temp/src/ga + let f = n_eps[h] / self.num_combinations * topf / b.lambda as f64; + let mut mittel = 0.0; + for a in 0..na { -+ let t = strategy[a * nh + h].max(DELTA) as f64; ++ let t = bezug[a * nh + h].max(DELTA) as f64; + p[a] = f * (t.ln() - anker[a]); + mittel += strategy[a * nh + h] as f64 * p[a]; + } @@ -489,11 +498,905 @@ diff -ruN postflop-solver-mess/src/game/mod.rs postflop-solver-temp/src/game/mod mod tests; diff -ruN postflop-solver-mess/src/solver.rs postflop-solver-temp/src/solver.rs --- postflop-solver-mess/src/solver.rs 2026-11-24 14:30:24 -+++ postflop-solver-temp/src/solver.rs 2026-12-02 00:27:16 -@@ -459,3 +459,235 @@ ++++ postflop-solver-temp/src/solver.rs 2026-12-02 11:44:56 +@@ -1,448 +1,448 @@ +-use crate::interface::*; +-use crate::mutex_like::*; +-use crate::sliceop::*; +-use crate::utility::*; +-use std::io::{self, Write}; +-use std::mem::MaybeUninit; +- +-#[cfg(feature = "custom-alloc")] +-use crate::alloc::*; +- +-struct DiscountParams { +- alpha_t: f32, +- beta_t: f32, +- gamma_t: f32, +-} +- +-impl DiscountParams { +- pub fn new(current_iteration: u32) -> Self { +- // 0, 1, 4, 16, 64, 256, ... +- let nearest_lower_power_of_4 = match current_iteration { +- 0 => 0, +- x => 1 << ((x.leading_zeros() ^ 31) & !1), +- }; +- +- let t_alpha = (current_iteration as i32 - 1).max(0) as f64; +- let t_gamma = (current_iteration - nearest_lower_power_of_4) as f64; +- +- let pow_alpha = t_alpha * t_alpha.sqrt(); +- let pow_gamma = (t_gamma / (t_gamma + 1.0)).powi(3); +- +- Self { +- alpha_t: (pow_alpha / (pow_alpha + 1.0)) as f32, +- beta_t: 0.5, +- gamma_t: pow_gamma as f32, +- } +- } +-} +- +-/// Performs Discounted CFR algorithm until the given number of iterations or exploitability is +-/// satisfied. +-/// +-/// This method returns the exploitability of the obtained strategy. +-pub fn solve( +- game: &mut T, +- max_num_iterations: u32, +- target_exploitability: f32, +- print_progress: bool, +-) -> f32 { +- if game.is_solved() { +- panic!("Game is already solved"); +- } +- +- if !game.is_ready() { +- panic!("Game is not ready"); +- } +- +- let mut root = game.root(); +- let mut exploitability = compute_exploitability(game); +- +- if print_progress { +- print!("iteration: 0 / {max_num_iterations} "); +- print!("(exploitability = {exploitability:.4e})"); +- io::stdout().flush().unwrap(); +- } +- +- for t in 0..max_num_iterations { +- if exploitability <= target_exploitability { +- break; +- } +- +- let params = DiscountParams::new(t); +- +- // alternating updates +- for player in 0..2 { +- let mut result = Vec::with_capacity(game.num_private_hands(player)); +- solve_recursive( +- result.spare_capacity_mut(), +- game, +- &mut root, +- player, +- game.initial_weights(player ^ 1), +- ¶ms, +- ); +- } +- +- if (t + 1) % 10 == 0 || t + 1 == max_num_iterations { +- exploitability = compute_exploitability(game); +- } +- +- if print_progress { +- print!("\riteration: {} / {} ", t + 1, max_num_iterations); +- print!("(exploitability = {exploitability:.4e})"); +- io::stdout().flush().unwrap(); +- } +- } +- +- if print_progress { +- println!(); +- io::stdout().flush().unwrap(); +- } +- +- finalize(game); +- +- exploitability +-} +- +-/// Proceeds Discounted CFR algorithm for one iteration. +-#[inline] +-pub fn solve_step(game: &T, current_iteration: u32) { +- if game.is_solved() { +- panic!("Game is already solved"); +- } +- +- if !game.is_ready() { +- panic!("Game is not ready"); +- } +- +- let mut root = game.root(); +- let params = DiscountParams::new(current_iteration); +- +- // alternating updates +- for player in 0..2 { +- let mut result = Vec::with_capacity(game.num_private_hands(player)); +- solve_recursive( +- result.spare_capacity_mut(), +- game, +- &mut root, +- player, +- game.initial_weights(player ^ 1), +- ¶ms, +- ); +- } +-} +- +-/// Recursively solves the counterfactual values. +-fn solve_recursive( +- result: &mut [MaybeUninit], +- game: &T, +- node: &mut T::Node, +- player: usize, +- cfreach: &[f32], +- params: &DiscountParams, +-) { +- // return the counterfactual values when the `node` is terminal +- if node.is_terminal() { +- game.evaluate(result, node, player, cfreach); +- return; +- } +- +- let num_actions = node.num_actions(); +- let num_hands = result.len(); +- +- // simply recurse when the number of actions is one +- if num_actions == 1 && !node.is_chance() { +- let child = &mut node.play(0); +- solve_recursive(result, game, child, player, cfreach, params); +- return; +- } +- +- // allocate memory for storing the counterfactual values +- #[cfg(feature = "custom-alloc")] +- let cfv_actions = MutexLike::new(Vec::with_capacity_in(num_actions * num_hands, StackAlloc)); +- #[cfg(not(feature = "custom-alloc"))] +- let cfv_actions = MutexLike::new(Vec::with_capacity(num_actions * num_hands)); +- +- // if the `node` is chance +- if node.is_chance() { +- // update the reach probabilities +- #[cfg(feature = "custom-alloc")] +- let mut cfreach_updated = Vec::with_capacity_in(cfreach.len(), StackAlloc); +- #[cfg(not(feature = "custom-alloc"))] +- let mut cfreach_updated = Vec::with_capacity(cfreach.len()); +- mul_slice_scalar_uninit( +- cfreach_updated.spare_capacity_mut(), +- cfreach, +- 1.0 / game.chance_factor(node) as f32, +- ); +- unsafe { cfreach_updated.set_len(cfreach.len()) }; +- +- // compute the counterfactual values of each action +- for_each_child(node, |action| { +- solve_recursive( +- row_mut(cfv_actions.lock().spare_capacity_mut(), action, num_hands), +- game, +- &mut node.play(action), +- player, +- &cfreach_updated, +- params, +- ); +- }); +- +- // use 64-bit floating point values +- #[cfg(feature = "custom-alloc")] +- let mut result_f64 = Vec::with_capacity_in(num_hands, StackAlloc); +- #[cfg(not(feature = "custom-alloc"))] +- let mut result_f64 = Vec::with_capacity(num_hands); +- +- // sum up the counterfactual values +- let mut cfv_actions = cfv_actions.lock(); +- unsafe { cfv_actions.set_len(num_actions * num_hands) }; +- sum_slices_f64_uninit(result_f64.spare_capacity_mut(), &cfv_actions); +- unsafe { result_f64.set_len(num_hands) }; +- +- // get information about isomorphic chances +- let isomorphic_chances = game.isomorphic_chances(node); +- +- // process isomorphic chances +- for (i, &isomorphic_index) in isomorphic_chances.iter().enumerate() { +- let swap_list = &game.isomorphic_swap(node, i)[player]; +- let tmp = row_mut(&mut cfv_actions, isomorphic_index as usize, num_hands); +- +- apply_swap(tmp, swap_list); +- +- result_f64.iter_mut().zip(&*tmp).for_each(|(r, &v)| { +- *r += v as f64; +- }); +- +- apply_swap(tmp, swap_list); +- } +- +- result.iter_mut().zip(&result_f64).for_each(|(r, &v)| { +- r.write(v as f32); +- }); +- } +- // if the current player is `player` +- else if node.player() == player { +- // compute the counterfactual values of each action +- for_each_child(node, |action| { +- solve_recursive( +- row_mut(cfv_actions.lock().spare_capacity_mut(), action, num_hands), +- game, +- &mut node.play(action), +- player, +- cfreach, +- params, +- ); +- }); +- +- // compute the strategy by regret-maching algorithm +- let mut strategy = if game.is_compression_enabled() { +- regret_matching_compressed(node.regrets_compressed(), num_actions) +- } else { +- regret_matching(node.regrets(), num_actions) +- }; +- +- // node-locking +- let locking = game.locking_strategy(node); +- apply_locking_strategy(&mut strategy, locking); +- +- // sum up the counterfactual values +- let mut cfv_actions = cfv_actions.lock(); +- unsafe { cfv_actions.set_len(num_actions * num_hands) }; +- let result = fma_slices_uninit(result, &strategy, &cfv_actions); +- +- if game.is_compression_enabled() { +- // update the cumulative strategy +- let scale = node.strategy_scale(); +- let decoder = params.gamma_t * scale / u16::MAX as f32; +- let cum_strategy = node.strategy_compressed_mut(); +- +- strategy.iter_mut().zip(&*cum_strategy).for_each(|(x, y)| { +- *x += (*y as f32) * decoder; +- }); +- +- if !locking.is_empty() { +- strategy.iter_mut().zip(locking).for_each(|(d, s)| { +- if s.is_sign_positive() { +- *d = 0.0; +- } +- }) +- } +- +- let new_scale = encode_unsigned_slice(cum_strategy, &strategy); +- node.set_strategy_scale(new_scale); +- +- // update the cumulative regret +- let scale = node.regret_scale(); +- let alpha_decoder = params.alpha_t * scale / i16::MAX as f32; +- let beta_decoder = params.beta_t * scale / i16::MAX as f32; +- let cum_regret = node.regrets_compressed_mut(); +- +- cfv_actions.iter_mut().zip(&*cum_regret).for_each(|(x, y)| { +- *x += *y as f32 * if *y >= 0 { alpha_decoder } else { beta_decoder }; +- }); +- +- cfv_actions.chunks_exact_mut(num_hands).for_each(|row| { +- sub_slice(row, result); +- }); +- +- if !locking.is_empty() { +- cfv_actions.iter_mut().zip(locking).for_each(|(d, s)| { +- if s.is_sign_positive() { +- *d = 0.0; +- } +- }) +- } +- +- let new_scale = encode_signed_slice(cum_regret, &cfv_actions); +- node.set_regret_scale(new_scale); +- } else { +- // update the cumulative strategy +- let gamma = params.gamma_t; +- let cum_strategy = node.strategy_mut(); +- cum_strategy.iter_mut().zip(&strategy).for_each(|(x, y)| { +- *x = *x * gamma + *y; +- }); +- +- // update the cumulative regret +- let (alpha, beta) = (params.alpha_t, params.beta_t); +- let cum_regret = node.regrets_mut(); +- cum_regret.iter_mut().zip(&*cfv_actions).for_each(|(x, y)| { +- let coef = if x.is_sign_positive() { alpha } else { beta }; +- *x = *x * coef + *y; +- }); +- cum_regret.chunks_exact_mut(num_hands).for_each(|row| { +- sub_slice(row, result); +- }); +- } +- } +- // if the current player is not `player` +- else { +- // compute the strategy by regret-matching algorithm +- let mut cfreach_actions = if game.is_compression_enabled() { +- regret_matching_compressed(node.regrets_compressed(), num_actions) +- } else { +- regret_matching(node.regrets(), num_actions) +- }; +- +- // node-locking +- let locking = game.locking_strategy(node); +- apply_locking_strategy(&mut cfreach_actions, locking); +- +- // update the reach probabilities +- let row_size = cfreach.len(); +- cfreach_actions.chunks_exact_mut(row_size).for_each(|row| { +- mul_slice(row, cfreach); +- }); +- +- // compute the counterfactual values of each action +- for_each_child(node, |action| { +- solve_recursive( +- row_mut(cfv_actions.lock().spare_capacity_mut(), action, num_hands), +- game, +- &mut node.play(action), +- player, +- row(&cfreach_actions, action, row_size), +- params, +- ); +- }); +- +- // sum up the counterfactual values +- let mut cfv_actions = cfv_actions.lock(); +- unsafe { cfv_actions.set_len(num_actions * num_hands) }; +- sum_slices_uninit(result, &cfv_actions); +- } +-} +- +-/// Computes the strategy by regret-matching algorithm. +-#[cfg(feature = "custom-alloc")] +-#[inline] +-fn regret_matching(regret: &[f32], num_actions: usize) -> Vec { +- let mut strategy = Vec::with_capacity_in(regret.len(), StackAlloc); +- let uninit = strategy.spare_capacity_mut(); +- uninit.iter_mut().zip(regret).for_each(|(s, r)| { +- s.write(max(*r, 0.0)); +- }); +- unsafe { strategy.set_len(regret.len()) }; +- +- let row_size = regret.len() / num_actions; +- let mut denom = Vec::with_capacity_in(row_size, StackAlloc); +- sum_slices_uninit(denom.spare_capacity_mut(), &strategy); +- unsafe { denom.set_len(row_size) }; +- +- let default = 1.0 / num_actions as f32; +- strategy.chunks_exact_mut(row_size).for_each(|row| { +- div_slice(row, &denom, default); +- }); +- +- strategy +-} +- +-/// Computes the strategy by regret-matching algorithm. +-#[cfg(not(feature = "custom-alloc"))] +-#[inline] +-fn regret_matching(regret: &[f32], num_actions: usize) -> Vec { +- let mut strategy = Vec::with_capacity(regret.len()); +- let uninit = strategy.spare_capacity_mut(); +- uninit.iter_mut().zip(regret).for_each(|(s, r)| { +- s.write(max(*r, 0.0)); +- }); +- unsafe { strategy.set_len(regret.len()) }; +- +- let row_size = regret.len() / num_actions; +- let mut denom = Vec::with_capacity(row_size); +- sum_slices_uninit(denom.spare_capacity_mut(), &strategy); +- unsafe { denom.set_len(row_size) }; +- +- let default = 1.0 / num_actions as f32; +- strategy.chunks_exact_mut(row_size).for_each(|row| { +- div_slice(row, &denom, default); +- }); +- +- strategy +-} +- +-/// Computes the strategy by regret-matching algorithm. +-#[cfg(feature = "custom-alloc")] +-#[inline] +-fn regret_matching_compressed(regret: &[i16], num_actions: usize) -> Vec { +- let mut strategy = Vec::with_capacity_in(regret.len(), StackAlloc); +- strategy.extend(regret.iter().map(|&r| r.max(0) as f32)); +- +- let row_size = strategy.len() / num_actions; +- let mut denom = Vec::with_capacity_in(row_size, StackAlloc); +- sum_slices_uninit(denom.spare_capacity_mut(), &strategy); +- unsafe { denom.set_len(row_size) }; +- +- let default = 1.0 / num_actions as f32; +- strategy.chunks_exact_mut(row_size).for_each(|row| { +- div_slice(row, &denom, default); +- }); +- +- strategy +-} +- +-/// Computes the strategy by regret-matching algorithm. +-#[cfg(not(feature = "custom-alloc"))] +-#[inline] +-fn regret_matching_compressed(regret: &[i16], num_actions: usize) -> Vec { +- let mut strategy = Vec::with_capacity(regret.len()); +- strategy.extend(regret.iter().map(|&r| r.max(0) as f32)); +- +- let row_size = strategy.len() / num_actions; +- let mut denom = Vec::with_capacity(row_size); +- sum_slices_uninit(denom.spare_capacity_mut(), &strategy); +- unsafe { denom.set_len(row_size) }; +- +- let default = 1.0 / num_actions as f32; +- strategy.chunks_exact_mut(row_size).for_each(|row| { +- div_slice(row, &denom, default); +- }); +- +- strategy +-} ++use crate::interface::*; ++use crate::mutex_like::*; ++use crate::sliceop::*; ++use crate::utility::*; ++use std::io::{self, Write}; ++use std::mem::MaybeUninit; + ++#[cfg(feature = "custom-alloc")] ++use crate::alloc::*; ++ ++struct DiscountParams { ++ alpha_t: f32, ++ beta_t: f32, ++ gamma_t: f32, ++} ++ ++impl DiscountParams { ++ pub fn new(current_iteration: u32) -> Self { ++ // 0, 1, 4, 16, 64, 256, ... ++ let nearest_lower_power_of_4 = match current_iteration { ++ 0 => 0, ++ x => 1 << ((x.leading_zeros() ^ 31) & !1), ++ }; ++ ++ let t_alpha = (current_iteration as i32 - 1).max(0) as f64; ++ let t_gamma = (current_iteration - nearest_lower_power_of_4) as f64; ++ ++ let pow_alpha = t_alpha * t_alpha.sqrt(); ++ let pow_gamma = (t_gamma / (t_gamma + 1.0)).powi(3); ++ ++ Self { ++ alpha_t: (pow_alpha / (pow_alpha + 1.0)) as f32, ++ beta_t: 0.5, ++ gamma_t: pow_gamma as f32, ++ } ++ } ++} ++ ++/// Performs Discounted CFR algorithm until the given number of iterations or exploitability is ++/// satisfied. ++/// ++/// This method returns the exploitability of the obtained strategy. ++pub fn solve( ++ game: &mut T, ++ max_num_iterations: u32, ++ target_exploitability: f32, ++ print_progress: bool, ++) -> f32 { ++ if game.is_solved() { ++ panic!("Game is already solved"); ++ } ++ ++ if !game.is_ready() { ++ panic!("Game is not ready"); ++ } ++ ++ let mut root = game.root(); ++ let mut exploitability = compute_exploitability(game); ++ ++ if print_progress { ++ print!("iteration: 0 / {max_num_iterations} "); ++ print!("(exploitability = {exploitability:.4e})"); ++ io::stdout().flush().unwrap(); ++ } ++ ++ for t in 0..max_num_iterations { ++ if exploitability <= target_exploitability { ++ break; ++ } ++ ++ let params = DiscountParams::new(t); ++ ++ // alternating updates ++ for player in 0..2 { ++ let mut result = Vec::with_capacity(game.num_private_hands(player)); ++ solve_recursive( ++ result.spare_capacity_mut(), ++ game, ++ &mut root, ++ player, ++ game.initial_weights(player ^ 1), ++ ¶ms, ++ ); ++ } ++ ++ if (t + 1) % 10 == 0 || t + 1 == max_num_iterations { ++ exploitability = compute_exploitability(game); ++ } ++ ++ if print_progress { ++ print!("\riteration: {} / {} ", t + 1, max_num_iterations); ++ print!("(exploitability = {exploitability:.4e})"); ++ io::stdout().flush().unwrap(); ++ } ++ } ++ ++ if print_progress { ++ println!(); ++ io::stdout().flush().unwrap(); ++ } ++ ++ finalize(game); ++ ++ exploitability ++} ++ ++/// Proceeds Discounted CFR algorithm for one iteration. ++#[inline] ++pub fn solve_step(game: &T, current_iteration: u32) { ++ if game.is_solved() { ++ panic!("Game is already solved"); ++ } ++ ++ if !game.is_ready() { ++ panic!("Game is not ready"); ++ } ++ ++ let mut root = game.root(); ++ let params = DiscountParams::new(current_iteration); ++ ++ // alternating updates ++ for player in 0..2 { ++ let mut result = Vec::with_capacity(game.num_private_hands(player)); ++ solve_recursive( ++ result.spare_capacity_mut(), ++ game, ++ &mut root, ++ player, ++ game.initial_weights(player ^ 1), ++ ¶ms, ++ ); ++ } ++} ++ ++/// Recursively solves the counterfactual values. ++fn solve_recursive( ++ result: &mut [MaybeUninit], ++ game: &T, ++ node: &mut T::Node, ++ player: usize, ++ cfreach: &[f32], ++ params: &DiscountParams, ++) { ++ // return the counterfactual values when the `node` is terminal ++ if node.is_terminal() { ++ game.evaluate(result, node, player, cfreach); ++ return; ++ } ++ ++ let num_actions = node.num_actions(); ++ let num_hands = result.len(); ++ ++ // simply recurse when the number of actions is one ++ if num_actions == 1 && !node.is_chance() { ++ let child = &mut node.play(0); ++ solve_recursive(result, game, child, player, cfreach, params); ++ return; ++ } ++ ++ // allocate memory for storing the counterfactual values ++ #[cfg(feature = "custom-alloc")] ++ let cfv_actions = MutexLike::new(Vec::with_capacity_in(num_actions * num_hands, StackAlloc)); ++ #[cfg(not(feature = "custom-alloc"))] ++ let cfv_actions = MutexLike::new(Vec::with_capacity(num_actions * num_hands)); ++ ++ // if the `node` is chance ++ if node.is_chance() { ++ // update the reach probabilities ++ #[cfg(feature = "custom-alloc")] ++ let mut cfreach_updated = Vec::with_capacity_in(cfreach.len(), StackAlloc); ++ #[cfg(not(feature = "custom-alloc"))] ++ let mut cfreach_updated = Vec::with_capacity(cfreach.len()); ++ mul_slice_scalar_uninit( ++ cfreach_updated.spare_capacity_mut(), ++ cfreach, ++ 1.0 / game.chance_factor(node) as f32, ++ ); ++ unsafe { cfreach_updated.set_len(cfreach.len()) }; ++ ++ // compute the counterfactual values of each action ++ for_each_child(node, |action| { ++ solve_recursive( ++ row_mut(cfv_actions.lock().spare_capacity_mut(), action, num_hands), ++ game, ++ &mut node.play(action), ++ player, ++ &cfreach_updated, ++ params, ++ ); ++ }); ++ ++ // use 64-bit floating point values ++ #[cfg(feature = "custom-alloc")] ++ let mut result_f64 = Vec::with_capacity_in(num_hands, StackAlloc); ++ #[cfg(not(feature = "custom-alloc"))] ++ let mut result_f64 = Vec::with_capacity(num_hands); ++ ++ // sum up the counterfactual values ++ let mut cfv_actions = cfv_actions.lock(); ++ unsafe { cfv_actions.set_len(num_actions * num_hands) }; ++ sum_slices_f64_uninit(result_f64.spare_capacity_mut(), &cfv_actions); ++ unsafe { result_f64.set_len(num_hands) }; ++ ++ // get information about isomorphic chances ++ let isomorphic_chances = game.isomorphic_chances(node); ++ ++ // process isomorphic chances ++ for (i, &isomorphic_index) in isomorphic_chances.iter().enumerate() { ++ let swap_list = &game.isomorphic_swap(node, i)[player]; ++ let tmp = row_mut(&mut cfv_actions, isomorphic_index as usize, num_hands); ++ ++ apply_swap(tmp, swap_list); ++ ++ result_f64.iter_mut().zip(&*tmp).for_each(|(r, &v)| { ++ *r += v as f64; ++ }); ++ ++ apply_swap(tmp, swap_list); ++ } ++ ++ result.iter_mut().zip(&result_f64).for_each(|(r, &v)| { ++ r.write(v as f32); ++ }); ++ } ++ // if the current player is `player` ++ else if node.player() == player { ++ // compute the counterfactual values of each action ++ for_each_child(node, |action| { ++ solve_recursive( ++ row_mut(cfv_actions.lock().spare_capacity_mut(), action, num_hands), ++ game, ++ &mut node.play(action), ++ player, ++ cfreach, ++ params, ++ ); ++ }); ++ ++ // compute the strategy by regret-maching algorithm ++ let mut strategy = if game.is_compression_enabled() { ++ regret_matching_compressed(node.regrets_compressed(), num_actions) ++ } else { ++ regret_matching(node.regrets(), num_actions) ++ }; ++ ++ // node-locking ++ let locking = game.locking_strategy(node); ++ apply_locking_strategy(&mut strategy, locking); ++ ++ // sum up the counterfactual values ++ let mut cfv_actions = cfv_actions.lock(); ++ unsafe { cfv_actions.set_len(num_actions * num_hands) }; ++ let result = fma_slices_uninit(result, &strategy, &cfv_actions); ++ ++ if game.is_compression_enabled() { ++ // update the cumulative strategy ++ let scale = node.strategy_scale(); ++ let decoder = params.gamma_t * scale / u16::MAX as f32; ++ let cum_strategy = node.strategy_compressed_mut(); ++ ++ strategy.iter_mut().zip(&*cum_strategy).for_each(|(x, y)| { ++ *x += (*y as f32) * decoder; ++ }); ++ ++ if !locking.is_empty() { ++ strategy.iter_mut().zip(locking).for_each(|(d, s)| { ++ if s.is_sign_positive() { ++ *d = 0.0; ++ } ++ }) ++ } ++ ++ let new_scale = encode_unsigned_slice(cum_strategy, &strategy); ++ node.set_strategy_scale(new_scale); ++ ++ // update the cumulative regret ++ let scale = node.regret_scale(); ++ let alpha_decoder = params.alpha_t * scale / i16::MAX as f32; ++ let beta_decoder = params.beta_t * scale / i16::MAX as f32; ++ let cum_regret = node.regrets_compressed_mut(); ++ ++ cfv_actions.iter_mut().zip(&*cum_regret).for_each(|(x, y)| { ++ *x += *y as f32 * if *y >= 0 { alpha_decoder } else { beta_decoder }; ++ }); ++ ++ cfv_actions.chunks_exact_mut(num_hands).for_each(|row| { ++ sub_slice(row, result); ++ }); ++ ++ if !locking.is_empty() { ++ cfv_actions.iter_mut().zip(locking).for_each(|(d, s)| { ++ if s.is_sign_positive() { ++ *d = 0.0; ++ } ++ }) ++ } ++ ++ let new_scale = encode_signed_slice(cum_regret, &cfv_actions); ++ node.set_regret_scale(new_scale); ++ } else { ++ // update the cumulative strategy ++ let gamma = params.gamma_t; ++ let cum_strategy = node.strategy_mut(); ++ cum_strategy.iter_mut().zip(&strategy).for_each(|(x, y)| { ++ *x = *x * gamma + *y; ++ }); ++ ++ // update the cumulative regret ++ let (alpha, beta) = (params.alpha_t, params.beta_t); ++ let cum_regret = node.regrets_mut(); ++ cum_regret.iter_mut().zip(&*cfv_actions).for_each(|(x, y)| { ++ let coef = if x.is_sign_positive() { alpha } else { beta }; ++ *x = *x * coef + *y; ++ }); ++ cum_regret.chunks_exact_mut(num_hands).for_each(|row| { ++ sub_slice(row, result); ++ }); ++ } ++ } ++ // if the current player is not `player` ++ else { ++ // compute the strategy by regret-matching algorithm ++ let mut cfreach_actions = if game.is_compression_enabled() { ++ regret_matching_compressed(node.regrets_compressed(), num_actions) ++ } else { ++ regret_matching(node.regrets(), num_actions) ++ }; ++ ++ // node-locking ++ let locking = game.locking_strategy(node); ++ apply_locking_strategy(&mut cfreach_actions, locking); ++ ++ // update the reach probabilities ++ let row_size = cfreach.len(); ++ cfreach_actions.chunks_exact_mut(row_size).for_each(|row| { ++ mul_slice(row, cfreach); ++ }); ++ ++ // compute the counterfactual values of each action ++ for_each_child(node, |action| { ++ solve_recursive( ++ row_mut(cfv_actions.lock().spare_capacity_mut(), action, num_hands), ++ game, ++ &mut node.play(action), ++ player, ++ row(&cfreach_actions, action, row_size), ++ params, ++ ); ++ }); ++ ++ // sum up the counterfactual values ++ let mut cfv_actions = cfv_actions.lock(); ++ unsafe { cfv_actions.set_len(num_actions * num_hands) }; ++ sum_slices_uninit(result, &cfv_actions); ++ } ++} ++ ++/// Computes the strategy by regret-matching algorithm. ++#[cfg(feature = "custom-alloc")] ++#[inline] ++fn regret_matching(regret: &[f32], num_actions: usize) -> Vec { ++ let mut strategy = Vec::with_capacity_in(regret.len(), StackAlloc); ++ let uninit = strategy.spare_capacity_mut(); ++ uninit.iter_mut().zip(regret).for_each(|(s, r)| { ++ s.write(max(*r, 0.0)); ++ }); ++ unsafe { strategy.set_len(regret.len()) }; ++ ++ let row_size = regret.len() / num_actions; ++ let mut denom = Vec::with_capacity_in(row_size, StackAlloc); ++ sum_slices_uninit(denom.spare_capacity_mut(), &strategy); ++ unsafe { denom.set_len(row_size) }; ++ ++ let default = 1.0 / num_actions as f32; ++ strategy.chunks_exact_mut(row_size).for_each(|row| { ++ div_slice(row, &denom, default); ++ }); ++ ++ strategy ++} ++ ++/// Computes the strategy by regret-matching algorithm. ++#[cfg(not(feature = "custom-alloc"))] ++#[inline] ++fn regret_matching(regret: &[f32], num_actions: usize) -> Vec { ++ let mut strategy = Vec::with_capacity(regret.len()); ++ let uninit = strategy.spare_capacity_mut(); ++ uninit.iter_mut().zip(regret).for_each(|(s, r)| { ++ s.write(max(*r, 0.0)); ++ }); ++ unsafe { strategy.set_len(regret.len()) }; ++ ++ let row_size = regret.len() / num_actions; ++ let mut denom = Vec::with_capacity(row_size); ++ sum_slices_uninit(denom.spare_capacity_mut(), &strategy); ++ unsafe { denom.set_len(row_size) }; ++ ++ let default = 1.0 / num_actions as f32; ++ strategy.chunks_exact_mut(row_size).for_each(|row| { ++ div_slice(row, &denom, default); ++ }); ++ ++ strategy ++} ++ ++/// Computes the strategy by regret-matching algorithm. ++#[cfg(feature = "custom-alloc")] ++#[inline] ++fn regret_matching_compressed(regret: &[i16], num_actions: usize) -> Vec { ++ let mut strategy = Vec::with_capacity_in(regret.len(), StackAlloc); ++ strategy.extend(regret.iter().map(|&r| r.max(0) as f32)); ++ ++ let row_size = strategy.len() / num_actions; ++ let mut denom = Vec::with_capacity_in(row_size, StackAlloc); ++ sum_slices_uninit(denom.spare_capacity_mut(), &strategy); ++ unsafe { denom.set_len(row_size) }; ++ ++ let default = 1.0 / num_actions as f32; ++ strategy.chunks_exact_mut(row_size).for_each(|row| { ++ div_slice(row, &denom, default); ++ }); ++ ++ strategy ++} ++ ++/// Computes the strategy by regret-matching algorithm. ++#[cfg(not(feature = "custom-alloc"))] ++#[inline] ++fn regret_matching_compressed(regret: &[i16], num_actions: usize) -> Vec { ++ let mut strategy = Vec::with_capacity(regret.len()); ++ strategy.extend(regret.iter().map(|&r| r.max(0) as f32)); ++ ++ let row_size = strategy.len() / num_actions; ++ let mut denom = Vec::with_capacity(row_size); ++ sum_slices_uninit(denom.spare_capacity_mut(), &strategy); ++ unsafe { denom.set_len(row_size) }; ++ ++ let default = 1.0 / num_actions as f32; ++ strategy.chunks_exact_mut(row_size).for_each(|row| { ++ div_slice(row, &denom, default); ++ }); ++ ++ strategy ++} ++ + /// Messkopie: ein Schritt mit vorgegebener Reichweite des Gegners; liefert dessen kontrafaktische Werte (gegen die aktuelle Strategie). + pub fn mess_schritt(game: &T, t: u32, gegner: usize, reich: &[f32]) -> Vec { + let mut root = game.root(); +@@ -458,4 +458,247 @@ + } } aus - } ++} + +/// Messkopie Temperatur: ein Schritt nur fuer `player` (DCFR-Aktualisierung gegen die aktuelle Strategie des Gegners). +/// Der Gegner wird ueber Regret-Matching der Regrets seiner Knoten gelesen, siehe `game/boltzmann.rs`. @@ -629,7 +1532,18 @@ diff -ruN postflop-solver-mess/src/solver.rs postflop-solver-temp/src/solver.rs + let result = fma_slices_uninit(result, &strategy, &cfv_actions); + + // Regrets auf entropie-transformierten Werten: cfv - Strafe (um den Mittelwert unter der Strategie bereinigt) -+ let strafe = game.regulaer_strafe(node, &strategy, cfreach, player, b, strassenbeginn, skala); ++ // Bezugsstrategie der Strafe: Mischung aus seiner Durchschnittsstrategie bisher und der aktuellen (siehe `BEZUG_MITTEL`); ++ // vor der ersten Runde (Summe 0) die aktuelle ++ let mut bezug: Vec = if game.is_compression_enabled() { node.strategy_compressed().iter().map(|&x| x as f32).collect() } else { node.strategy().to_vec() }; ++ let mittel = crate::game::BEZUG_MITTEL; ++ for h in 0..num_hands { ++ let summe: f32 = (0..num_actions).map(|a| bezug[a * num_hands + h]).sum(); ++ for a in 0..num_actions { ++ let i = a * num_hands + h; ++ bezug[i] = if summe > 0.0 { mittel * bezug[i] / summe + (1.0 - mittel) * strategy[i] } else { strategy[i] }; ++ } ++ } ++ let strafe = game.regulaer_strafe(node, &strategy, &bezug, cfreach, player, b, strassenbeginn, skala); + cfv_actions.iter_mut().zip(&strafe).for_each(|(x, s)| *x -= s); + + if game.is_compression_enabled() { @@ -725,4 +1639,4 @@ diff -ruN postflop-solver-mess/src/solver.rs postflop-solver-temp/src/solver.rs + unsafe { cfv_actions.set_len(num_actions * num_hands) }; + sum_slices_uninit(result, &cfv_actions); + } -+} + } diff --git a/entscheiden/motor/src/temperatur_spec.rs b/entscheiden/motor/src/temperatur_spec.rs index 962dad8e..bab77e0c 100644 --- a/entscheiden/motor/src/temperatur_spec.rs +++ b/entscheiden/motor/src/temperatur_spec.rs @@ -659,7 +659,11 @@ fn verfahrensvergleich() { use std::time::Instant; let env = |k: &str, d: &str| std::env::var(k).unwrap_or_else(|_| d.to_string()); let (lage_f, lam_f, beta_f) = (env("LAGE", ""), env("LAMBDA", "2,5,15,50,1000"), env("BETA", "b1,b0")); - for (name, a, budget) in lagen().into_iter().filter(|l| l.0.contains(&lage_f)) { + for (name, mut a, budget) in lagen().into_iter().filter(|l| l.0.contains(&lage_f)) { + // STACK= ueberschreibt den Stack der Lage (tiefe Lagen wie live: SPR 8 bis 12) + if let Ok(st) = env("STACK", "").parse::() { + a.stack = st; + } // Bezug: Gleichgewicht (Werte) und Zeit je Runde let ref_runden: u32 = env("REF", "0").parse().ok().filter(|r| *r > 0).unwrap_or(if a.brett.len() == 5 { 1500 } else { 400 }); let mult: u32 = env("MULT", "4").parse().unwrap_or(4); @@ -677,7 +681,9 @@ fn verfahrensvergleich() { { for lambda in lam_f.split(',').map(|x| x.parse::().unwrap()) { for bs in beta_f.split(',') { - let beta = if bs == "b1" { [0.3, -0.4, 0.2] } else { [0.0; 3] }; + // b1 / b0 oder frei "call:raise:setz" (z. B. die geschaetzten Neigungen) + let frei: Vec = bs.split(':').filter_map(|x| x.parse().ok()).collect(); + let beta = if frei.len() == 3 { [frei[0], frei[1], frei[2]] } else if bs == "b1" { [0.3, -0.4, 0.2] } else { [0.0; 3] }; let b = Boltzmann { gegner: 1, lambda, beta_call: beta[0], beta_raise: beta[1], beta_setz: beta[2], fest: false }; let g = bau(&a, &[], true).unwrap(); if lambda == 0.0 {