diff --git a/src/exploit/mod.rs b/src/exploit/mod.rs index 5c613619..f7feb231 100644 --- a/src/exploit/mod.rs +++ b/src/exploit/mod.rs @@ -27,4 +27,5 @@ pub mod style; pub mod style_rung; pub mod style_shift; pub mod table_fold; +pub mod thompson; pub mod thresholds; diff --git a/src/exploit/thompson.rs b/src/exploit/thompson.rs new file mode 100644 index 00000000..aa6959c7 --- /dev/null +++ b/src/exploit/thompson.rs @@ -0,0 +1,227 @@ +//! Thompson-Sampling: jeder Arm haelt ein Beta(a,b) ueber seine Erfolgsquote. +//! Waehlen = je Arm ziehen, Argmax nehmen; danach konjugiert nachziehen. +//! Eine Aktion hat zwei Renditen: Chips und das, was sie verraet (Explorationswert). + +use crate::rng::split_mix::Rng; + +/// Beta-Glaube; Start Beta(1,1) = gleichverteilt. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Posterior { + pub alpha: f64, + pub beta: f64, +} + +impl Posterior { + pub const fn uniform() -> Posterior { + Posterior { alpha: 1.0, beta: 1.0 } + } + + pub const fn new(alpha: f64, beta: f64) -> Posterior { + Posterior { alpha, beta } + } + + pub fn mean(&self) -> f64 { + self.alpha / (self.alpha + self.beta) + } + + /// Konjugiertes Update; `reward` in [0,1] (Bernoulli 0/1 oder Bruchteil). + pub fn update(&mut self, reward: f64) { + let r = reward.clamp(0.0, 1.0); + self.alpha += r; + self.beta += 1.0 - r; + } + + /// Eine Ziehung aus Beta(a,b) ueber Gamma-Verhaeltnis. + pub fn sample(&self, rng: &mut Rng) -> f64 { + let x = gamma(self.alpha, rng); + let y = gamma(self.beta, rng); + let s = x + y; + if s > 0.0 { x / s } else { self.mean() } + } +} + +fn unit_open(rng: &mut Rng) -> f64 { + let (u, next) = rng.unit(); + *rng = next; + u.max(f64::MIN_POSITIVE) +} + +fn normal(rng: &mut Rng) -> f64 { + let u1 = unit_open(rng); + let u2 = unit_open(rng); + (-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos() +} + +/// Gamma(shape, 1) nach Marsaglia-Tsang; shape < 1 per Boost u^(1/shape). +fn gamma(shape: f64, rng: &mut Rng) -> f64 { + if shape < 1.0 { + let g = gamma(shape + 1.0, rng); + return g * unit_open(rng).powf(1.0 / shape); + } + let d = shape - 1.0 / 3.0; + let c = 1.0 / (9.0 * d).sqrt(); + loop { + let x = normal(rng); + let v = 1.0 + c * x; + if v <= 0.0 { + continue; + } + let v = v * v * v; + let u = unit_open(rng); + if u.ln() < 0.5 * x * x + d - d * v + d * v.ln() { + return d * v; + } + } +} + +/// k Arme mit je einem Posterior. +#[derive(Clone, Debug)] +pub struct Bandit { + pub arms: Vec, +} + +impl Bandit { + pub fn new(k: usize) -> Bandit { + Bandit { arms: vec![Posterior::uniform(); k] } + } + + /// Thompson-Zug: je Arm ziehen, Argmax (erster bei Gleichstand). + pub fn choose(&mut self, rng: &mut Rng) -> usize { + let mut best = 0; + let mut best_v = f64::NEG_INFINITY; + for (i, p) in self.arms.iter().enumerate() { + let v = p.sample(rng); + if v > best_v { + best_v = v; + best = i; + } + } + best + } + + pub fn update(&mut self, arm: usize, reward: f64) { + self.arms[arm].update(reward); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const MEANS: [f64; 3] = [0.3, 0.5, 0.8]; + const T: usize = 2000; + + fn pull(mean: f64, rng: &mut Rng) -> f64 { + let (u, n) = rng.unit(); + *rng = n; + if u < mean { 1.0 } else { 0.0 } + } + + /// (kumulatives Bedauern, Zuege je Arm, Zuege je Arm in der letzten Haelfte) + fn run_thompson(seed: u64) -> (f64, [usize; 3], [usize; 3]) { + let mut rng = Rng::seeded(seed); + let mut b = Bandit::new(3); + let (mut regret, mut n, mut late) = (0.0, [0; 3], [0; 3]); + for t in 0..T { + let a = b.choose(&mut rng); + b.update(a, pull(MEANS[a], &mut rng)); + regret += 0.8 - MEANS[a]; + n[a] += 1; + if t >= T / 2 { + late[a] += 1; + } + } + (regret, n, late) + } + + /// Basislinie: eps-greedy auf Empirie (eps = 0.1), erst jeden Arm einmal. + fn run_eps_greedy(seed: u64, eps: f64) -> (f64, [usize; 3]) { + let mut rng = Rng::seeded(seed); + let (mut regret, mut n, mut sum) = (0.0, [0usize; 3], [0.0f64; 3]); + for t in 0..T { + let (u, nx) = rng.unit(); + rng = nx; + let a = if t < 3 { + t + } else if u < eps { + let (r, nx) = rng.below(3); + rng = nx; + r as usize + } else { + (0..3) + .max_by(|&i, &j| (sum[i] / n[i] as f64).total_cmp(&(sum[j] / n[j] as f64))) + .unwrap() + }; + sum[a] += pull(MEANS[a], &mut rng); + n[a] += 1; + regret += 0.8 - MEANS[a]; + } + (regret, n) + } + + #[test] + fn beta_sampler_matches_moments() { + let mut rng = Rng::seeded(7); + for &(a, b) in &[(1.0, 1.0), (2.0, 5.0), (0.5, 0.5), (30.0, 10.0)] { + let p = Posterior::new(a, b); + let n = 20000; + let xs: Vec = (0..n).map(|_| p.sample(&mut rng)).collect(); + let m = xs.iter().sum::() / n as f64; + let v = xs.iter().map(|x| (x - m) * (x - m)).sum::() / n as f64; + let tv = a * b / ((a + b) * (a + b) * (a + b + 1.0)); + assert!((m - p.mean()).abs() < 0.01, "mean {a},{b}: {m}"); + assert!((v - tv).abs() < 0.1 * tv + 1e-4, "var {a},{b}: {v} vs {tv}"); + assert!(xs.iter().all(|x| (0.0..=1.0).contains(x))); + } + } + + #[test] + fn update_is_conjugate() { + let mut p = Posterior::uniform(); + p.update(1.0); + p.update(0.0); + p.update(1.0); + assert_eq!((p.alpha, p.beta), (3.0, 2.0)); + } + + #[test] + fn deterministic() { + assert_eq!(run_thompson(5), run_thompson(5)); + } + + #[test] + fn thompson_beats_baseline_regret() { + let seeds = 20u64; + let (mut rt, mut re, mut rg) = (0.0, 0.0, 0.0); + let (mut nt, mut ne) = ([0usize; 3], [0usize; 3]); + let mut late = [0usize; 3]; + for s in 0..seeds { + let (r, n, l) = run_thompson(1000 + s); + rt += r; + for i in 0..3 { + nt[i] += n[i]; + late[i] += l[i]; + } + let (r, n) = run_eps_greedy(1000 + s, 0.1); + re += r; + for i in 0..3 { + ne[i] += n[i]; + } + rg += run_eps_greedy(1000 + s, 0.0).0; + } + let k = seeds as f64; + println!("Regret ueber T={T}, Mittel aus {seeds} Seeds:"); + println!(" Thompson {:.1}", rt / k); + println!(" eps-greedy {:.1} (eps=0.1)", re / k); + println!(" greedy {:.1} (eps=0)", rg / k); + println!("Zuege je Arm (Mittel) Thompson {:?}", nt.map(|x| x / seeds as usize)); + println!("Zuege je Arm (Mittel) eps-greedy {:?}", ne.map(|x| x / seeds as usize)); + let half = (T / 2) as f64 * k; + let share = late[2] as f64 / half; + println!("Thompson Anteil bester Arm, 2. Haelfte: {share:.3}"); + assert!(rt < 0.6 * re, "Thompson {rt} vs eps-greedy {re}"); + assert!(rt < rg, "Thompson {rt} vs greedy {rg}"); + assert!(share > 0.9, "konzentriert nicht: {share}"); + assert!(nt[2] > nt[1] && nt[1] > nt[0]); + } +}