trioskosmos commited on
Commit
0e3f840
·
verified ·
1 Parent(s): 2e185f9

Upload ai/utils/obs_adapters.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. ai/utils/obs_adapters.py +182 -0
ai/utils/obs_adapters.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from engine.game.game_state import GameState
4
+
5
+
6
+ class UnifiedObservationEncoder:
7
+ """
8
+ Translates current GameState into various historic observation formats.
9
+ """
10
+
11
+ @staticmethod
12
+ def encode(state: GameState, dim: int, player_idx: int = None) -> np.ndarray:
13
+ if player_idx is None:
14
+ player_idx = state.current_player
15
+
16
+ if dim == 8192:
17
+ return UnifiedObservationEncoder._encode_8192(state, player_idx)
18
+ elif dim == 2048:
19
+ return UnifiedObservationEncoder._encode_2048(state, player_idx)
20
+ elif dim == 320:
21
+ return UnifiedObservationEncoder._encode_320(state, player_idx)
22
+ elif dim == 128:
23
+ return UnifiedObservationEncoder._encode_128(state, player_idx)
24
+ else:
25
+ raise ValueError(f"Unsupported observation dimension: {dim}")
26
+
27
+ @staticmethod
28
+ def _encode_8192(state: GameState, player_idx: int) -> np.ndarray:
29
+ from ai.vector_env import VectorGameState as VGS
30
+ from ai.vector_env import encode_observations_vectorized
31
+
32
+ p = state.players[player_idx]
33
+ opp = state.players[1 - player_idx]
34
+
35
+ # Prepare arrays (mirroring VectorGameState layout)
36
+ batch_hand = np.zeros((1, 60), dtype=np.int32)
37
+ h_len = min(len(p.hand), 60)
38
+ for i in range(h_len):
39
+ batch_hand[0, i] = p.hand[i]
40
+
41
+ batch_stage = np.full((1, 3), -1, dtype=np.int32)
42
+ for i in range(3):
43
+ if i < len(p.stage):
44
+ batch_stage[0, i] = p.stage[i]
45
+
46
+ batch_energy_count = np.zeros((1, 3), dtype=np.int32)
47
+ # Assuming p.stage_energy_count exists (based on _encode_2048)
48
+ if hasattr(p, "stage_energy_count"):
49
+ for i in range(3):
50
+ if i < len(p.stage_energy_count):
51
+ batch_energy_count[0, i] = p.stage_energy_count[i]
52
+
53
+ # NOTE: VectorEnv uses size 16 for tapped (Energy Tapping)
54
+ batch_tapped = np.zeros((1, 16), dtype=np.int32)
55
+ if hasattr(p, "tapped_members"):
56
+ for i in range(min(3, len(p.tapped_members))):
57
+ batch_tapped[0, i] = 1 if p.tapped_members[i] else 0
58
+
59
+ batch_scores = np.array([len(p.success_lives)], dtype=np.int32)
60
+ opp_scores = np.array([len(opp.success_lives)], dtype=np.int32)
61
+
62
+ opp_stage = np.full((1, 3), -1, dtype=np.int32)
63
+ for i in range(3):
64
+ if i < len(opp.stage):
65
+ opp_stage[0, i] = opp.stage[i]
66
+
67
+ opp_tapped = np.zeros((1, 16), dtype=np.int32)
68
+ if hasattr(opp, "tapped_members"):
69
+ for i in range(min(3, len(opp.tapped_members))):
70
+ opp_tapped[0, i] = 1 if opp.tapped_members[i] else 0
71
+
72
+ # Global Context - FIXED MAPPING
73
+ # Index 0 (SC): len(p.success_lives)
74
+ # Index 1 (OS): len(opp.success_lives)
75
+ # Index 2 (TR): len(p.discard)
76
+ # Index 3 (HD): len(p.hand)
77
+ # Index 4 (DI): len(opp.hand)
78
+ # Index 5 (EN): p.energy_count
79
+ # Index 6 (DK): len(p.main_deck)
80
+ # Index 7 (OT): len(opp.discard)
81
+ # Index 8 (PH): int(state.phase)
82
+ # Index 9 (OD): len(opp.main_deck)
83
+ g_ctx = np.zeros((1, 128), dtype=np.int32)
84
+ g_ctx[0, 0] = len(p.success_lives)
85
+ g_ctx[0, 1] = len(opp.success_lives)
86
+ g_ctx[0, 2] = len(p.discard)
87
+ g_ctx[0, 3] = len(p.hand)
88
+ g_ctx[0, 4] = len(opp.hand)
89
+ g_ctx[0, 5] = p.energy_count
90
+ g_ctx[0, 6] = len(p.main_deck)
91
+ g_ctx[0, 7] = len(opp.discard)
92
+ g_ctx[0, 8] = int(state.phase)
93
+ g_ctx[0, 9] = len(opp.main_deck)
94
+
95
+ # Additional Buffers for Updated Signature
96
+ batch_live = np.zeros((1, 50), dtype=np.int32)
97
+ batch_opp_history = np.zeros((1, 50), dtype=np.int32)
98
+
99
+ # Fill opp history with discard (Top Cards)
100
+ d_len = min(len(opp.discard), 50)
101
+ # VectorEnv assumes LIFO/Top-is-last.
102
+ for i in range(d_len):
103
+ batch_opp_history[0, i] = opp.discard[-(i + 1)]
104
+
105
+ # VGS Cache
106
+ if not hasattr(UnifiedObservationEncoder, "_vgs_cache"):
107
+ UnifiedObservationEncoder._vgs_cache = VGS(1)
108
+ vgs = UnifiedObservationEncoder._vgs_cache
109
+
110
+ # Output
111
+ obs = np.zeros((1, 8192), dtype=np.float32)
112
+
113
+ encode_observations_vectorized(
114
+ 1,
115
+ batch_hand,
116
+ batch_stage,
117
+ batch_energy_count,
118
+ batch_tapped,
119
+ batch_scores,
120
+ opp_scores,
121
+ opp_stage,
122
+ opp_tapped,
123
+ vgs.card_stats,
124
+ g_ctx,
125
+ batch_live,
126
+ batch_opp_history,
127
+ state.turn_number,
128
+ obs,
129
+ )
130
+ return obs[0]
131
+
132
+ @staticmethod
133
+ def _encode_320(state: GameState, player_idx: int) -> np.ndarray:
134
+ # LEGACY 320 (First Speed-up Era)
135
+ # Replicates the encoding from ai/vector_env_legacy.py exactly.
136
+ # This era ONLY saw Self Stage and Self Score. Hand/Opp were 0.
137
+
138
+ obs = np.zeros(320, dtype=np.float32)
139
+ p = state.players[player_idx]
140
+ max_id_val = 2000.0 # Standard for VectorEnv
141
+
142
+ # Phase [5] = 1.0 (Mocking Main Phase index from Legacy VectorEnv)
143
+ obs[5] = 1.0
144
+ # Current Player [16]
145
+ obs[16] = 1.0
146
+
147
+ # Stage [168:204] (3 slots * 12 features)
148
+ # Note: Hand [36:168] remains 0.0 as in legacy training.
149
+ for i in range(3):
150
+ cid = p.stage[i]
151
+ base = 168 + i * 12
152
+ if cid >= 0:
153
+ obs[base] = 1.0 # Exist
154
+ obs[base + 1] = cid / max_id_val
155
+ # Legacy energy count was normalized by 5.0
156
+ obs[base + 11] = min(p.stage_energy_count[i] / 5.0, 1.0)
157
+
158
+ # Score [270] (Self Score normalized by 5.0 in legacy)
159
+ obs[270] = min(len(p.success_lives) / 5.0, 1.0)
160
+
161
+ return obs
162
+
163
+ @staticmethod
164
+ def _encode_128(state: GameState, player_idx: int) -> np.ndarray:
165
+ # 128-dim is the global_ctx vector
166
+ p = state.players[player_idx]
167
+ opp = state.players[1 - player_idx]
168
+
169
+ g_ctx = np.zeros(128, dtype=np.float32)
170
+ # Standard normalization from AlphaZero era
171
+ g_ctx[0] = len(p.success_lives) / 3.0
172
+ g_ctx[1] = len(opp.success_lives) / 3.0
173
+ g_ctx[2] = len(p.discard) / 50.0
174
+ g_ctx[3] = len(p.hand) / 50.0 # Normalized to deck size usually
175
+ g_ctx[5] = p.energy_count / 10.0
176
+ g_ctx[6] = len(p.main_deck) / 50.0
177
+
178
+ # Turn info
179
+ g_ctx[10] = state.turn_number / 20.0
180
+ g_ctx[11] = 1.0 if state.current_player == player_idx else 0.0
181
+
182
+ return g_ctx