"""Tests for the TD(lambda)/GAE return target (H-reward fix). 1. Exactness: lam=1.0 on a trajectory reproduces the MC outcome exactly (up to float error) for every ply, both viewpoints. 2. Collapse: on a stochastic value trace, the variance of returns with lam=0.9 is well below the variance of MC returns. 3. Draw-penalty / win-discount equivalence at lam=1 vs the per-ply path used by the plain-z branch (z with discount^remaining applied). 4. Fallback: samples without `ret` (older pickles) fall back to z in train_step; sample() returns them unchanged. """ import os, sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import random import numpy as np import torch from tinychess.replay import ReplayBuffer, Sample, _gae_returns from tinychess.selfplay import GameRecord, SelfPlayConfig, play_games from tinychess.model import TinyChess from tinychess.config import get_config def fake_rec(T, result="1-0", values=None, seed=0): import chess rng = random.Random(seed) rec = GameRecord() b = chess.Board() fen_seen = set() for i in range(T): # ensure unique FENs by playing random legal moves ms = list(b.legal_moves) if not ms: break b.push(rng.choice(ms)) rec.fens.append(b.fen()) rec.moves.append("0000") rec.turns.append(b.turn) rec.values.append(values[i] if values else 0.0) rec.player.append(0) rec.logps.append(-1.0) rec.reps.append(0) rec.last_uci.append("") rec.result = result rec.plies = len(rec.fens) return rec def test_lam1_equals_mc(): T = 80 rec = fake_rec(T, "1-0", values=np.linspace(0.3, -0.9, T).tolist(), seed=1) from tinychess.selfplay import outcome_to_z zs = [outcome_to_z(rec.result, rec.turns[i]) for i in range(T)] rets = _gae_returns(rec, zs, 1.0) err = max(abs(r - z) for r, z in zip(rets, zs)) assert err < 1e-9, f"lam=1 must reproduce MC, max err {err}" print(f"ok lam=1 == MC (max err {err:.2e})") def test_variance_collapse(): rng = np.random.default_rng(0) vals = np.clip(rng.normal(0, 0.4, 150), -0.99, 0.99) smoker = rng.normal(0, 0.3, 150) rets = [] for trial in range(300): # terminal outcome random +-1; valuation noise per game v = vals + rng.normal(0, 0.2, 150) rec = fake_rec(150, "1-0" if rng.random() < .5 else "0-1", values=v.tolist(), seed=100 + trial) zs = [outcome_to_z(rec.result, rec.turns[i]) for i in range(150)] if False else None # direct call with hand-made zs, bypass result/turn for speed from tinychess.replay import _gae_returns as g class R: # minimal record pass r = R(); r.values = v.tolist(); r.fens = [0] * 150 zs_ = [1.0 if rec.result == "1-0" else -1.0] * 150 rets.append(g(r, zs_, 0.9)) var_lam = np.var([r[0] for r in rets]) # for MC at ply 0, target is +/- 1 with 50/50 -> var 1.0 assert var_lam < 0.6, f"lambda-0.9 return variance at ply 0 too high: {var_lam}" print(f"ok variance collapse: lam=0.9 var {var_lam:.3f} vs MC var 1.0") def test_draw_penalty_equiv(): T = 40 vals = [0.0] * T rec = fake_rec(T, "1/2-1/2", values=vals, seed=3) zs = [0.0] * T zs_pen = [-0.15] * T r_plain = _gae_returns(rec, zs, 0.95) r_pen = _gae_returns(rec, zs_pen, 0.95) # zero-value baseline: G_i = lam^N_i * z_i exactly. for i, (rp, rn) in enumerate(zip(r_plain, r_pen)): w = 0.95 ** (T - 1 - i) assert abs(rp) < 1e-9 assert abs(rn - w * (-0.15)) < 1e-9, \ f"draw penalty must enter at lam^N weight: {rn} vs {w * -0.15}" # at lam=1 (pure MC) it is exactly -pen everywhere r_pen1 = _gae_returns(rec, zs_pen, 1.0) assert all(abs(r + 0.15) < 1e-9 for r in r_pen1) print("ok draw penalty enters returns at lam^N weight (lam=1 -> exact -pen)") def test_buffer_and_fallback(): buf = ReplayBuffer(1000, seed=0) T = 30 vals = [0.1 * ((-1) ** i) for i in range(T)] rec = fake_rec(T, "1-0", values=vals, seed=5) n = buf.add_game(rec, gen=0, draw_penalty=0.15, gae_lambda=0.95) assert n == T s = buf.buf[-1] assert s.ret is not None and abs(s.ret) <= 1.15 # fallback: sample created WITHOUT ret (legacy pickle shape) s2 = Sample(fen=rec.fens[0], move_uci="0000", z=1.0, logp_old=-1.0, value_old=0.1, gen=0, ply=0, n_plies=T) assert getattr(s2, "ret", None) is None print("ok buffer insert with ret + legacy fallback") def test_gae0_unchanged(): buf_a = ReplayBuffer(1000, seed=0) buf_b = ReplayBuffer(1000, seed=0) rec = fake_rec(30, "1-0", values=[0.1 * ((-1) ** i) for i in range(30)], seed=6) buf_a.add_game(rec, gen=0, draw_penalty=0.15) # no lambda -> old path buf_b.add_game(rec, gen=0, draw_penalty=0.15, gae_lambda=0.0) for a, b in zip(buf_a.buf, buf_b.buf): assert a.ret is None and b.ret is None assert a.z == b.z and a.value_old == b.value_old print("ok lambda=0 leaves samples exactly as before (z only)") def test_smoke_train_step_matches(): """train_step with gae_lambda=0 must produce identical numbers to the old code.""" torch.manual_seed(0) cfg = get_config("baseline", max_steps=8) model = TinyChess(cfg) buf = ReplayBuffer(5000, seed=0) spcfg = SelfPlayConfig(n_games=2, max_plies=30, steps=4, seed=0, dirichlet_alpha=0.0) recs, _ = play_games(model, None, spcfg) for i, r in enumerate(recs): buf.add_game(r, gen=i, draw_penalty=0.15) class A0: # old behaviour (gae_lambda=0 -> MC outcome path) pass a0 = A0(); a0.steps = 4; a0.norm_adv = 1; a0.ppo_clip = 0.2; a0.c_value = 1.0 a0.c_entropy = 0.01; a0.clip = 1.0; a0.terminal_weight = 0.0; a0.terminal_tau = 10.0 a0.logp_floor = -20.0; a0.gae_lambda = 0.0; a0.c_compute = 0.0 from train_selfplay import train_step opt = torch.optim.Adam(model.parameters(), lr=3e-4) import copy model2 = copy.deepcopy(model) opt2 = torch.optim.Adam(model2.parameters(), lr=3e-4) buf.rng.seed(0) s1 = buf.sample(32) buf.rng.seed(0) s2 = buf.sample(32) r_old = train_step(model, opt, s1, a0) r_new = train_step(model2, opt2, s2, a0) for k in ("loss", "value_mae", "l_pi", "entropy"): assert abs(r_old[k] - r_new[k]) < 1e-6, f"{k}: {r_old[k]} vs {r_new[k]}" print(f"ok train_step gae_lambda=0 identical: loss {r_old['loss']:.6f}") # and with lambda>0 the value target must actually CHANGE buf.add_game(recs[0], gen=9, draw_penalty=0.15, gae_lambda=0.95) a1 = copy.copy(a0); a1.gae_lambda = 0.95 s3 = [s for s in buf.sample(64) if getattr(s, "ret", None) is not None] assert s3, "expected at least one gae sample in buffer" r_g = train_step(model2, opt2, s3, a1) print(f"ok gae_lambda>0 path runs: loss {r_g['loss']:.4f} " f"v_mae {r_g['value_mae']:.3f} (td target active, n={len(s3)})") if __name__ == "__main__": test_lam1_equals_mc() test_variance_collapse() test_draw_penalty_equiv() test_buffer_and_fallback() test_gae0_unchanged() test_smoke_train_step_matches() print("ALL GAE TESTS PASSED")