|
| 1 | +import numpy as np |
| 2 | +import os |
| 3 | +import torch |
| 4 | +import torch.nn as nn |
| 5 | +import torch.optim as optim |
| 6 | +from collections import deque |
| 7 | +import random |
| 8 | +from agents import SelfRegisteringAgent |
| 9 | + |
| 10 | + |
| 11 | +class DQNNetwork(nn.Module): |
| 12 | + """ |
| 13 | + Neural network model for Deep Q-learning. |
| 14 | + Takes observation from the Quoridor game and outputs Q-values for each action. |
| 15 | + """ |
| 16 | + |
| 17 | + def __init__(self, board_size, action_size): |
| 18 | + super(DQNNetwork, self).__init__() |
| 19 | + |
| 20 | + # Calculate input dimensions based on observation space |
| 21 | + # Board is board_size x board_size with 2 channels (player position and opponent position) |
| 22 | + # Walls are (board_size-1) x (board_size-1) with 2 channels (vertical and horizontal walls) |
| 23 | + board_input_size = board_size * board_size |
| 24 | + walls_input_size = (board_size - 1) * (board_size - 1) * 2 |
| 25 | + |
| 26 | + # Additional features: walls remaining for both players |
| 27 | + flat_input_size = board_input_size + walls_input_size + 2 |
| 28 | + |
| 29 | + # Define network architecture |
| 30 | + self.model = nn.Sequential( |
| 31 | + nn.Linear(flat_input_size, 256), nn.ReLU(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, action_size) |
| 32 | + ) |
| 33 | + |
| 34 | + def forward(self, x): |
| 35 | + return self.model(x) |
| 36 | + |
| 37 | + |
| 38 | +class ReplayBuffer: |
| 39 | + """ |
| 40 | + Experience replay buffer to store and sample transitions. |
| 41 | + """ |
| 42 | + |
| 43 | + def __init__(self, capacity): |
| 44 | + self.buffer = deque(maxlen=capacity) |
| 45 | + |
| 46 | + def add(self, state, action, reward, next_state, done): |
| 47 | + self.buffer.append((state, action, reward, next_state, done)) |
| 48 | + |
| 49 | + def sample(self, batch_size): |
| 50 | + return random.sample(self.buffer, batch_size) |
| 51 | + |
| 52 | + def __len__(self): |
| 53 | + return len(self.buffer) |
| 54 | + |
| 55 | + |
| 56 | +class FlatDQNAgent(SelfRegisteringAgent): |
| 57 | + """ |
| 58 | + Agent that uses Deep Q-Network for action selection. |
| 59 | + """ |
| 60 | + |
| 61 | + def __init__(self, board_size, epsilon=1.0, epsilon_min=0.01, epsilon_decay=0.995, gamma=0.99): |
| 62 | + super(FlatDQNAgent, self).__init__() |
| 63 | + self.board_size = board_size |
| 64 | + # Assumes action representation is a flat array of size board_size**2 + (board_size - 1)**2 * 2 |
| 65 | + # See quoridor_env.py for details |
| 66 | + self.action_size = board_size**2 + (board_size - 1) ** 2 * 2 |
| 67 | + self.epsilon = epsilon # Exploration rate |
| 68 | + self.epsilon_min = epsilon_min |
| 69 | + self.epsilon_decay = epsilon_decay |
| 70 | + self.gamma = gamma # Discount factor |
| 71 | + |
| 72 | + # Initialize Q-networks (online and target) |
| 73 | + self.online_network = DQNNetwork(board_size, self.action_size) |
| 74 | + self.target_network = DQNNetwork(board_size, self.action_size) |
| 75 | + self.update_target_network() |
| 76 | + |
| 77 | + # Set up optimizer |
| 78 | + self.optimizer = optim.Adam(self.online_network.parameters(), lr=0.001) |
| 79 | + self.criterion = nn.MSELoss() |
| 80 | + |
| 81 | + # Initialize replay buffer |
| 82 | + self.replay_buffer = ReplayBuffer(capacity=10000) |
| 83 | + |
| 84 | + self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| 85 | + self.online_network.to(self.device) |
| 86 | + self.target_network.to(self.device) |
| 87 | + |
| 88 | + def update_target_network(self): |
| 89 | + """Copy parameters from online network to target network.""" |
| 90 | + self.target_network.load_state_dict(self.online_network.state_dict()) |
| 91 | + |
| 92 | + def preprocess_observation(self, observation): |
| 93 | + """ |
| 94 | + Convert the observation dict to a flat tensor. |
| 95 | + """ |
| 96 | + obs = observation["observation"] |
| 97 | + board = obs["board"].flatten() |
| 98 | + walls = obs["walls"].flatten() |
| 99 | + my_walls = np.array([obs["my_walls_remaining"]]) |
| 100 | + opponent_walls = np.array([obs["opponent_walls_remaining"]]) |
| 101 | + |
| 102 | + # Concatenate all components |
| 103 | + flat_obs = np.concatenate([board, walls, my_walls, opponent_walls]) |
| 104 | + return torch.FloatTensor(flat_obs).to(self.device) |
| 105 | + |
| 106 | + def get_action(self, game): |
| 107 | + """ |
| 108 | + Select an action using epsilon-greedy policy. |
| 109 | + """ |
| 110 | + observation, _, termination, truncation, _ = game.last() |
| 111 | + if termination or truncation: |
| 112 | + return None |
| 113 | + |
| 114 | + mask = observation["action_mask"] |
| 115 | + valid_actions = np.where(mask == 1)[0] |
| 116 | + |
| 117 | + # With probability epsilon, select a random action (exploration) |
| 118 | + if random.random() < self.epsilon: |
| 119 | + return np.random.choice(valid_actions) |
| 120 | + |
| 121 | + # Otherwise, select the action with the highest Q-value (exploitation) |
| 122 | + state = self.preprocess_observation(observation) |
| 123 | + with torch.no_grad(): |
| 124 | + q_values = self.online_network(state) |
| 125 | + |
| 126 | + # Apply action mask to q_values |
| 127 | + mask_tensor = torch.FloatTensor(mask).to(self.device) |
| 128 | + q_values = q_values * mask_tensor - 1e9 * (1 - mask_tensor) |
| 129 | + |
| 130 | + return torch.argmax(q_values).item() |
| 131 | + |
| 132 | + def train(self, batch_size): |
| 133 | + """ |
| 134 | + Train the network on a batch of samples from the replay buffer. |
| 135 | + """ |
| 136 | + if len(self.replay_buffer) < batch_size: |
| 137 | + return |
| 138 | + |
| 139 | + # Sample a batch of transitions |
| 140 | + batch = self.replay_buffer.sample(batch_size) |
| 141 | + states, actions, rewards, next_states, dones = zip(*batch) |
| 142 | + |
| 143 | + # Convert to tensors |
| 144 | + states = torch.stack([torch.FloatTensor(s) for s in states]).to(self.device) |
| 145 | + actions = torch.LongTensor(actions).unsqueeze(1).to(self.device) |
| 146 | + rewards = torch.FloatTensor(rewards).to(self.device) |
| 147 | + next_states = torch.stack([torch.FloatTensor(s) for s in next_states]).to(self.device) |
| 148 | + dones = torch.FloatTensor(dones).to(self.device) |
| 149 | + |
| 150 | + # Compute current Q values |
| 151 | + current_q_values = self.online_network(states).gather(1, actions).squeeze() |
| 152 | + |
| 153 | + # Compute next Q values using target network |
| 154 | + with torch.no_grad(): |
| 155 | + next_q_values = self.target_network(next_states).max(1)[0] |
| 156 | + target_q_values = rewards + (1 - dones) * self.gamma * next_q_values |
| 157 | + |
| 158 | + # Compute loss and update online network |
| 159 | + loss = self.criterion(current_q_values, target_q_values) |
| 160 | + self.optimizer.zero_grad() |
| 161 | + loss.backward() |
| 162 | + self.optimizer.step() |
| 163 | + |
| 164 | + # Decay epsilon |
| 165 | + self.epsilon = max(self.epsilon_min, self.epsilon * self.epsilon_decay) |
| 166 | + |
| 167 | + return loss.item() |
| 168 | + |
| 169 | + def save_model(self, path): |
| 170 | + """Save the model to disk.""" |
| 171 | + torch.save(self.online_network.state_dict(), path) |
| 172 | + |
| 173 | + def load_model(self, path): |
| 174 | + """Load the model from disk.""" |
| 175 | + self.online_network.load_state_dict(torch.load(path)) |
| 176 | + self.update_target_network() |
| 177 | + |
| 178 | + |
| 179 | +class Pretrained01FlatDQNAgent(FlatDQNAgent): |
| 180 | + """ |
| 181 | + A FlatDQNAgent that is initialized with the pre-trained model from main.py. |
| 182 | + """ |
| 183 | + |
| 184 | + def __init__(self, board_size, **kwargs): |
| 185 | + super(Pretrained01FlatDQNAgent, self).__init__(board_size) |
| 186 | + model_path = "/home/julian/aaae/deep-rabbit-hole/code/deep_rabbit_hole/models/dqn_flat_nostep_final.pt" |
| 187 | + if os.path.exists(model_path): |
| 188 | + print(f"Loading pre-trained model from {model_path}") |
| 189 | + self.load_model(model_path) |
| 190 | + else: |
| 191 | + print( |
| 192 | + f"Warning: Model file {model_path} not found, using untrained agent. Ask Julian for the weights file." |
| 193 | + ) |
0 commit comments