|
| 1 | +"""Contract: KV cache slots written while an agent is off-map (removed=1) are |
| 2 | +excluded from attention via per-agent garbage_mask. |
| 3 | +
|
| 4 | +The attention math is verified directly: we drive the transformer's |
| 5 | +forward_eval with a synthetic state dict, mark some slots as garbage, |
| 6 | +and assert that the attention weights at those slots are zero (after |
| 7 | +softmax). |
| 8 | +
|
| 9 | +We use the _probe_attention path in models.py which captures attention |
| 10 | +weights per layer in state["_attn_weights"]. |
| 11 | +""" |
| 12 | + |
| 13 | +import os |
| 14 | + |
| 15 | +# Without this, _USE_LEGACY_EVAL defaults True and the streaming KV path |
| 16 | +# (which owns garbage_mask) is bypassed — the test would silently no-op. |
| 17 | +os.environ.setdefault("PUFFER_TRANSFORMER_LEGACY_EVAL", "0") |
| 18 | +import sys |
| 19 | + |
| 20 | +import numpy as np |
| 21 | +import torch |
| 22 | +import torch.nn as nn |
| 23 | + |
| 24 | +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) |
| 25 | + |
| 26 | + |
| 27 | +class _MinimalPolicy(nn.Module): |
| 28 | + """Stub that satisfies TransformerWrapper's policy contract: |
| 29 | + encode_observations(obs, state) -> (B, hidden) and |
| 30 | + decode_actions(hidden) -> (logits, values).""" |
| 31 | + |
| 32 | + def __init__(self, obs_dim, hidden, n_actions): |
| 33 | + super().__init__() |
| 34 | + self.encoder = nn.Linear(obs_dim, hidden) |
| 35 | + self.decoder_a = nn.Linear(hidden, n_actions) |
| 36 | + self.decoder_v = nn.Linear(hidden, 1) |
| 37 | + self.is_continuous = False |
| 38 | + |
| 39 | + def encode_observations(self, obs, state=None): |
| 40 | + return self.encoder(obs) |
| 41 | + |
| 42 | + def decode_actions(self, hidden): |
| 43 | + return self.decoder_a(hidden), self.decoder_v(hidden).squeeze(-1) |
| 44 | + |
| 45 | + |
| 46 | +class _StubEnv: |
| 47 | + """Just exposes single_observation_space.shape — the only thing |
| 48 | + TransformerWrapper.__init__ reads from env.""" |
| 49 | + |
| 50 | + def __init__(self, obs_dim): |
| 51 | + from gymnasium import spaces |
| 52 | + |
| 53 | + self.single_observation_space = spaces.Box(low=-1, high=1, shape=(obs_dim,)) |
| 54 | + |
| 55 | + |
| 56 | +def _make_wrapper(batch_size=4, horizon=8, hidden=16, n_heads=2): |
| 57 | + from pufferlib.models import TransformerWrapper |
| 58 | + |
| 59 | + env = _StubEnv(obs_dim=hidden) |
| 60 | + policy = _MinimalPolicy(obs_dim=hidden, hidden=hidden, n_actions=3) |
| 61 | + return TransformerWrapper( |
| 62 | + env=env, |
| 63 | + policy=policy, |
| 64 | + horizon=horizon, |
| 65 | + num_layers=2, |
| 66 | + num_heads=n_heads, |
| 67 | + input_size=hidden, |
| 68 | + hidden_size=hidden, |
| 69 | + ) |
| 70 | + |
| 71 | + |
| 72 | +def test_garbage_mask_excludes_slots_from_attention(): |
| 73 | + """If garbage_mask[a, k] = True, the softmax weight at slot k for agent a |
| 74 | + must be 0 after the next forward.""" |
| 75 | + torch.manual_seed(0) |
| 76 | + B, T, H = 4, 8, 16 |
| 77 | + wrapper = _make_wrapper(batch_size=B, horizon=T, hidden=H, n_heads=2) |
| 78 | + wrapper.eval() |
| 79 | + |
| 80 | + state = wrapper.init_eval_state(batch_size=B, device="cpu", dtype=torch.float32) |
| 81 | + state["_probe_attention"] = True |
| 82 | + |
| 83 | + # Step 5 times so cache fills slots 0..4 for all agents. Agent 0 has |
| 84 | + # `removed=True` at steps 2 and 3 — slots 2, 3 should be marked garbage. |
| 85 | + for step in range(5): |
| 86 | + obs = torch.randn(B, H) |
| 87 | + removed = torch.zeros(B, dtype=torch.bool) |
| 88 | + if step in (2, 3): |
| 89 | + removed[0] = True |
| 90 | + state["removed"] = removed |
| 91 | + state["_attn_weights"] = [] # reset per step |
| 92 | + with torch.no_grad(): |
| 93 | + wrapper.forward_eval(obs, state) |
| 94 | + |
| 95 | + # After step 4: garbage_mask[0, 2] and [0, 3] should be True |
| 96 | + gm = state["garbage_mask"] |
| 97 | + assert gm[0, 2].item() and gm[0, 3].item(), f"garbage slots not marked for agent 0: {gm[0]}" |
| 98 | + # Other agents: nothing marked |
| 99 | + assert not gm[1:].any().item(), f"non-removed agents should have empty garbage_mask: {gm[1:]}" |
| 100 | + |
| 101 | + # Now step once more (no removed) and inspect attention weights for agent 0 |
| 102 | + state["removed"] = torch.zeros(B, dtype=torch.bool) |
| 103 | + state["_attn_weights"] = [] |
| 104 | + obs = torch.randn(B, H) |
| 105 | + with torch.no_grad(): |
| 106 | + wrapper.forward_eval(obs, state) |
| 107 | + |
| 108 | + # Per-layer attention weights are (B, H, 1, horizon). |
| 109 | + # Agent 0's slots 2 and 3 must have zero weight (masked out by garbage_mask). |
| 110 | + for layer_rec in state["_attn_weights"]: |
| 111 | + w = layer_rec["weights"] # (B, H, 1, horizon) |
| 112 | + assert w[0, :, 0, 2].abs().max().item() < 1e-6, ( |
| 113 | + f"layer {layer_rec['layer']}: slot 2 weight nonzero for agent 0: {w[0, :, 0, 2]}" |
| 114 | + ) |
| 115 | + assert w[0, :, 0, 3].abs().max().item() < 1e-6, f"layer {layer_rec['layer']}: slot 3 weight nonzero for agent 0" |
| 116 | + # Sanity: other agents' slots 2, 3 should still get nonzero weight |
| 117 | + assert w[1, :, 0, 2].abs().max().item() > 1e-6, "agent 1 slot 2 should NOT be masked" |
| 118 | + |
| 119 | + |
| 120 | +def test_garbage_mask_clears_on_full_reset(): |
| 121 | + """reset_eval_state(state, done_indices=None) must zero garbage_mask.""" |
| 122 | + B, T, H = 4, 8, 16 |
| 123 | + wrapper = _make_wrapper(batch_size=B, horizon=T, hidden=H, n_heads=2) |
| 124 | + state = wrapper.init_eval_state(batch_size=B, device="cpu", dtype=torch.float32) |
| 125 | + state["garbage_mask"][:] = True |
| 126 | + wrapper.reset_eval_state(state, done_indices=None) |
| 127 | + assert not state["garbage_mask"].any().item(), "garbage_mask should be zeroed after full reset" |
| 128 | + |
| 129 | + |
| 130 | +def test_garbage_mask_clears_per_agent_on_partial_reset(): |
| 131 | + """reset_eval_state(state, done_indices=[a]) must zero garbage_mask[a] |
| 132 | + but leave other agents untouched.""" |
| 133 | + B, T, H = 4, 8, 16 |
| 134 | + wrapper = _make_wrapper(batch_size=B, horizon=T, hidden=H, n_heads=2) |
| 135 | + state = wrapper.init_eval_state(batch_size=B, device="cpu", dtype=torch.float32) |
| 136 | + state["garbage_mask"][:] = True |
| 137 | + wrapper.reset_eval_state(state, done_indices=torch.tensor([1, 3])) |
| 138 | + assert state["garbage_mask"][0].all().item(), "agent 0 garbage_mask should be unchanged" |
| 139 | + assert not state["garbage_mask"][1].any().item(), "agent 1 garbage_mask should be cleared" |
| 140 | + assert state["garbage_mask"][2].all().item(), "agent 2 garbage_mask should be unchanged" |
| 141 | + assert not state["garbage_mask"][3].any().item(), "agent 3 garbage_mask should be cleared" |
| 142 | + |
| 143 | + |
| 144 | +def test_no_garbage_mask_no_regression(): |
| 145 | + """Without `removed` in state, forward_eval must still work — model |
| 146 | + creates a fresh garbage_mask (all False), so attention is unchanged |
| 147 | + from the pre-fix behavior.""" |
| 148 | + torch.manual_seed(0) |
| 149 | + B, T, H = 4, 8, 16 |
| 150 | + wrapper = _make_wrapper(batch_size=B, horizon=T, hidden=H, n_heads=2) |
| 151 | + wrapper.eval() |
| 152 | + state = wrapper.init_eval_state(batch_size=B, device="cpu", dtype=torch.float32) |
| 153 | + # No state["removed"] key |
| 154 | + for _ in range(3): |
| 155 | + obs = torch.randn(B, H) |
| 156 | + with torch.no_grad(): |
| 157 | + wrapper.forward_eval(obs, state) |
| 158 | + # garbage_mask stays all-False |
| 159 | + assert not state["garbage_mask"].any().item(), "without removed signal, no slots should be marked garbage" |
| 160 | + |
| 161 | + |
| 162 | +if __name__ == "__main__": |
| 163 | + test_garbage_mask_excludes_slots_from_attention() |
| 164 | + test_garbage_mask_clears_on_full_reset() |
| 165 | + test_garbage_mask_clears_per_agent_on_partial_reset() |
| 166 | + test_no_garbage_mask_no_regression() |
| 167 | + print("test_cache_freeze: PASS") |
0 commit comments