import os
import random
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from collections import deque
import torch.nn.functional as F
from pysc2.env import sc2_env
from pysc2.lib import actions, features
# Define the QNetwork
class QNetwork(nn.Module):
def __init__(self, input_dim, output_dim):
super(QNetwork, self).__init__()
self.fc1 = nn.Linear(input_dim, 128)
self.fc2 = nn.Linear(128, 128)
self.fc3 = nn.Linear(128, output_dim)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
# Preprocess PySC2 observation
def preprocess_observation(obs):
"""Extract and preprocess relevant information from PySC2 observations."""
screen = obs["feature_screen"]
player = obs["player"]
return np.concatenate([screen.flatten(), player], axis=0)
# Train the DQN agent in PySC2
def train_dqn(env, episodes=100, batch_size=32, screen_size=64):
obs = env.reset()[0] # Access the first observation
state_size = len(preprocess_observation(obs))
action_size = len(actions.FUNCTIONS)
# Initialize Q-network and target network
q_network = QNetwork(state_size, action_size)
target_network = QNetwork(state_size, action_size)
target_network.load_state_dict(q_network.state_dict())
target_network.eval()
optimizer = optim.[Redacted Person](q_network.parameters(), lr=0.001)
memory = deque(maxlen=2000)
gamma = 0.99
epsilon = 1.0
epsilon_min = 0.01
epsilon_decay = 0.995
target_update = 10
for episode in range(episodes):
obs = env.reset()[0] # Access the first observation
state = preprocess_observation(obs)
state = torch.FloatTensor(state).unsqueeze(0)
total_reward = 0
while True:
# Epsilon-greedy action selection
if random.random() < epsilon:
action = random.choice(obs["available_actions"])
else:
with torch.no_grad():
q_values = q_network(state)
# Mask unavailable actions
mask = torch.full((action_size,), float("-inf"))
mask[obs["available_actions"]] = 0
q_values = q_values + mask
action = torch.argmax(q_values).item()
# Map action to PySC2 action
pysc2_action = actions.FUNCTIONS[action]
if pysc2_action.id in obs["available_actions"]:
obs = env.step([pysc2_action()])[0]
else:
continue # Skip if the action is unavailable
# Preprocess next state and compute reward
next_state = preprocess_observation(obs)
next_state = torch.FloatTensor(next_state).unsqueeze(0)
reward = obs.reward
done = obs.last()
total_reward += reward
# Store experience in replay buffer
memory.append((state, action, torch.FloatTensor([reward]), next_state, done))
state = next_state
if done:
print(f"Episode {episode + 1}/{episodes}, Total Reward: {total_reward}")
break
# Train the network if the replay buffer is sufficiently large
if len(memory) >= batch_size:
batch = random.sample(memory, batch_size)
states, actions, rewards, next_states, dones = zip(*batch)
states = torch.cat(states)
actions = torch.LongTensor(actions).unsqueeze(1)
rewards = torch.cat(rewards)
next_states = torch.cat(next_states)
dones = torch.FloatTensor(dones)
# Compute current Q-values
q_values = q_network(states).gather(1, actions)
# Compute target Q-values
with torch.no_grad():
target_q = target_network(next_states).max(1)[0]
target_q = rewards + (gamma * target_q) * (1 - dones)
target_q = target_q.unsqueeze(1)
# Compute loss and update the network
loss = F.mse_loss(q_values, target_q)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Update the target network
if (episode + 1) % target_update == 0:
target_network.load_state_dict(q_network.state_dict())
# Decay epsilon
if epsilon > epsilon_min:
epsilon *= epsilon_decay
print("Training complete.")
return q_network
# Main function to train the DQN agent
def main():
from absl import app, flags
flags.FLAGS(["train_dqn_B.py"])
screen_size = 64
env = sc2_env.SC2Env(
map_name="MoveToBeacon",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=features.AgentInterfaceFormat(
feature_dimensions=features.Dimensions(screen=screen_size, minimap=screen_size),
use_feature_units=True,
),
step_mul=8,
game_steps_per_episode=0,
visualize=False,
)
try:
train_dqn(env, episodes=100, batch_size=32, screen_size=screen_size)
finally:
env.close()
if __name__ == "__main__":
main()
运行得到如下报错信息:
pygame 2.6.1 (SDL 2.28.4, Python 3.8.13)
Hello from the pygame community. https://www.pygame.org/contribute.html
Version: B75689 (SC2.4.10)
Build: Aug 12 2019 17:16:57
Command Line: '"/workspace/StarCraftII/Versions/Base75689/SC2_x64" -listen 127 .0.0.1 -port 39390 -dataDir /workspace/StarCraftII/ -tempDir /tmp/sc-p6x2j9x2/ '
Starting up...
Startup Phase 1 complete
Startup Phase 2 complete
Creating stub renderer...
Listening on: [Redacted IPAddress]:39390
Startup Phase 3 complete. Ready for commands.
ConnectHandler: Request from [Redacted IPAddress]:52578 accepted
ReadyHandler: [Redacted IPAddress]:52578 ready
Requesting to join a single player game
Configuring interface options
Configure: raw interface enabled
Configure: feature layer interface enabled
Configure: score interface enabled
Configure: render interface disabled
Launching next game.
Next launch phase started: 2
Next launch phase started: 3
Next launch phase started: 4
Next launch phase started: 5
Next launch phase started: 6
Next launch phase started: 7
Next launch phase started: 8
Game has started.
Using default stable ids, none found at: /workspace/StarCraftII/stableid.json
Successfully loaded stable ids: GameData\stableid.json
Sending ResponseJoinGame
RequestQuit command received.
Closing Application...
DataHandler: unable to parse websocket frame.
CloseHandler: [Redacted IPAddress]:52578 disconnected
Traceback (most recent call last):
File "train_dqn_B.py", line 160, in
main()
File "train_dqn_B.py", line 154, in main
train_dqn(env, episodes=100, batch_size=32, screen_size=screen_size)
File "train_dqn_B.py", line 39, in train_dqn
state_size = len(preprocess_observation(obs))
File "train_dqn_B.py", line 31, in preprocess_observation
screen = obs["feature_screen"]
TypeError: tuple indices must be integers or slices, not str
###用户需求: 请定位导致Error的问题,并debug这段dqn 训练代码:
Assistant
Okay, let's analyze the traceback and debug the provided DQN training code for PySC2.
Understanding the Error
The core issue is this line:
python
TypeError: tuple indices must be integers or slices, not str
This error occurs within the preprocess_observation function, specifically on the line screen = obs["feature_screen"]. The traceback tells us that obs is a tuple, not a dictionary. We are trying to access it using a string key ("feature_screen"), which is not valid for tuples.
Root Cause
The problem is how the environment's reset() and step() methods return their observations. In the provided code, they are called like this:
python
obs = env.reset()[0] # Access the first observation
...
obs = env.step([pysc2_action()])[0]
According to the pysc2/env/sc2_env.py file, the environment returns a tuple of TimeStep objects when there are multiple agents (or one agent in a multi-agent setting). Each TimeStep object contains the observation of one agent. In this case there is one agent, so we are getting one timestep. The observation is accessible through obs.observation.
Debugging Steps
Modify preprocess_observation: Change the function to expect the observation within the TimeStep object:
python
def preprocess_observation(obs):
"""Extract and preprocess relevant information from PySC2 observations."""
screen = obs.observation["feature_screen"]
player = obs.observation["player"]
return np.concatenate([screen.flatten(), player], axis=0)
Modify train_dqn: Modify the calls to reset and step in train_dqn to access the observation properly:
python
User
Running the code above caused the following error:
pygame 2.6.1 (SDL 2.28.4, Python 3.8.13)
Hello from the pygame community. https://www.pygame.org/contribute.html
Version: B75689 (SC2.4.10)
Build: Aug 12 2019 17:16:57
Command Line: '"/workspace/StarCraftII/Versions/Base75689/SC2_x64" -listen [Redacted IPAddress] -port 33872 -dataDir /workspace/StarCraftII/ -tempDir /tmp/sc-97vxygag/'
Starting up...
Startup Phase 1 complete
Startup Phase 2 complete
Creating stub renderer...
Listening on: [Redacted IPAddress]:33872
Startup Phase 3 complete. Ready for commands.
ConnectHandler: Request from [Redacted IPAddress]:51746 accepted
ReadyHandler: [Redacted IPAddress]:51746 ready
Requesting to join a single player game
Configuring interface options
Configure: raw interface enabled
Configure: feature layer interface enabled
Configure: score interface enabled
Configure: render interface disabled
Launching next game.
Next launch phase started: 2
Next launch phase started: 3
Next launch phase started: 4
Next launch phase started: 5
Next launch phase started: 6
Next launch phase started: 7
Next launch phase started: 8
Game has started.
Using default stable ids, none found at: /workspace/StarCraftII/stableid.json
Successfully loaded stable ids: GameData\stableid.json
Sending ResponseJoinGame
RequestQuit command received.
Closing Application...
DataHandler: unable to parse websocket frame.
CloseHandler: [Redacted IPAddress]:51746 disconnected
Traceback (most recent call last):
File "train_dqn_BB.py", line 157, in
main()
File "train_dqn_BB.py", line 151, in main
train_dqn(env, episodes=100, batch_size=32)
File "train_dqn_BB.py", line 38, in train_dqn
action_size = len(actions.FUNCTIONS)
UnboundLocalError: local variable 'actions' referenced before assignment
#please debug:
Assistant
Okay, let's analyze this new error and debug the code further.
Understanding the Error
The traceback shows an UnboundLocalError:
code
UnboundLocalError: local variable 'actions' referenced before assignment
This error occurs on the line action_size = len(actions.FUNCTIONS) within the train_dqn function. This means that the actions variable is being used before it has been assigned a value within the scope of the train_dqn function.
Root Cause
The issue is that we import actions from pysc2.lib at the top of the script:
python
from pysc2.lib import actions, features
This makes the actions namespace available in the main scope but not within the function train_dqn.
Debugging Steps
The fix is to explicitly import the actions module within the scope of the train_dqn function.
Corrected Code
Here's the corrected code with the import statement added:
python
User
The previous error is due to the issue that we import actions from pysc2.lib at the top of the script:
from pysc2.lib import actions, features
This makes the actions namespace available in the main scope but not within the function train_dqn.
Debugging Steps
The fix is to explicitly import the actions module within the scope of the train_dqn function.
Moving on after debugging this,
python
Assistant
Okay, let's analyze the new errors and refine the code to address the issues.
Understanding the Errors
Both train_dqn_BA.py and train_dqn_BB.py produce similar ValueError messages:
train_dqn_BA.py: ValueError: Wrong number of arguments for function: 2/select_point (6/select_point_act [4]; 0/screen [0, 0]), got: []
train_dqn_BB.py: ValueError: Wrong number of arguments for function: 4/select_control_group (4/control_group_act [5]; 5/control_group_id [10]), got: []
These errors occur during the env.step() call, specifically within the transform_action function in pysc2.lib.features.py. The core issue is that the PySC2 actions (i.e. actions.FunctionCall objects) require specific arguments depending on the function, and the current code passes an empty list [] as the argument list to the actions. This is insufficient for actions like select_point or select_control_group that require additional parameters like screen coordinates or control group IDs.
Root Cause
The DQN agent is selecting action IDs correctly, but it's not providing the required arguments for those actions. We need to inspect the action spec to figure out what arguments a function requires.
Debugging Steps
Inspect the Action Spec: Before training, let's retrieve the action spec from the environment and examine the arguments required for each action.
Implement Argument Passing: Inside the training loop, for each action, if the action has any arguments, we need to supply some (dummy) arguments to prevent the error.
Corrected Code
Here's the corrected train_dqn_BC.py code:
python
User
python
Assistant
Okay, let's analyze why the agent is rarely getting rewards, address the lack of transparency in logging, and then improve the code accordingly.
Analysis of Low Rewards
The primary reason for the agent's low reward frequency is the combination of:
Random Action Selection: Initially, the agent explores randomly with a high epsilon value. This means it's mostly taking arbitrary actions, which, in the "MoveToBeacon" map, likely won't lead to the beacon very often unless by chance.
Default Action Arguments: The construct_action function is generating actions with static default arguments. This means that the agent is executing actions without context of the game state. For example, if an action requires a target coordinate, it will always try to execute the action at a predefined coordinate, which is less likely to be beneficial unless the agent randomly gets into the right position.
Sparse Rewards: The "MoveToBeacon" environment gives a reward of +1 only when the unit reaches the beacon. If the unit doesn't move in the correct direction to reach the beacon, there is no reward. This makes it very difficult for the agent to learn because it receives almost no feedback for the actions it takes.
Lack of Transparency
The current logging only prints the episode number and total reward, making it very hard to understand the agent's behavior. We want to log information like:
The current game state (a summary of the observation).
The selected action, and which action function it belongs to.
The arguments passed into the action.
The resulting reward.
Improved Code
Here's the improved code (train_dqn_CD.py) with logging enhancements and a few other changes to help the agent learn more quickly:
python
User
Write the complete train_dqn.py code with the upgrades above:
Assistant
Okay, here's the complete train_dqn.py code, incorporating all the improvements we've discussed:
python
User
the code
python
Assistant
python
Dataset releases
Not yet included in a published release.
def train_dqn(env, episodes=100, batch_size=32, screen_size=64):
obs = env.reset()[0] # Access the first observation in the TimeStep
state_size = len(preprocess_observation(obs))
action_size = len(actions.FUNCTIONS)
...
if pysc2_action.id in obs.observation["available_actions"]:
obs = env.step([pysc2_action()])[0] #Access the first observation in the TimeStep
else:
continue # Skip if the action is unavailable
# Preprocess next state and compute reward
next_state = preprocess_observation(obs)
...
reward = obs.reward
done = obs.last()
Corrected Code
Here's the corrected code with the changes applied:
python
import os
import random
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from collections import deque
import torch.nn.functional as F
from pysc2.env import sc2_env
from pysc2.lib import actions, features
# Define the QNetwork
class QNetwork(nn.Module):
def __init__(self, input_dim, output_dim):
super(QNetwork, self).__init__()
self.fc1 = nn.Linear(input_dim, 128)
self.fc2 = nn.Linear(128, 128)
self.fc3 = nn.Linear(128, output_dim)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
# Preprocess PySC2 observation
def preprocess_observation(obs):
"""Extract and preprocess relevant information from PySC2 observations."""
screen = obs.observation["feature_screen"]
player = obs.observation["player"]
return np.concatenate([screen.flatten(), player], axis=0)
# Train the DQN agent in PySC2
def train_dqn(env, episodes=100, batch_size=32, screen_size=64):
obs = env.reset()[0] # Access the first observation in the TimeStep
state_size = len(preprocess_observation(obs))
action_size = len(actions.FUNCTIONS)
# Initialize Q-network and target network
q_network = QNetwork(state_size, action_size)
target_network = QNetwork(state_size, action_size)
target_network.load_state_dict(q_network.state_dict())
target_network.eval()
optimizer = optim.[Redacted Person](q_network.parameters(), lr=0.001)
memory = deque(maxlen=2000)
gamma = 0.99
epsilon = 1.0
epsilon_min = 0.01
epsilon_decay = 0.995
target_update = 10
for episode in range(episodes):
obs = env.reset()[0] # Access the first observation in the TimeStep
state = preprocess_observation(obs)
state = torch.FloatTensor(state).unsqueeze(0)
total_reward = 0
while True:
# Epsilon-greedy action selection
if random.random() < epsilon:
action = random.choice(obs.observation["available_actions"])
else:
with torch.no_grad():
q_values = q_network(state)
# Mask unavailable actions
mask = torch.full((action_size,), float("-inf"))
mask[obs.observation["available_actions"]] = 0
q_values = q_values + mask
action = torch.argmax(q_values).item()
# Map action to PySC2 action
pysc2_action = actions.FUNCTIONS[action]
if pysc2_action.id in obs.observation["available_actions"]:
obs = env.step([pysc2_action()])[0] #Access the first observation in the TimeStep
else:
continue # Skip if the action is unavailable
# Preprocess next state and compute reward
next_state = preprocess_observation(obs)
next_state = torch.FloatTensor(next_state).unsqueeze(0)
reward = obs.reward
done = obs.last()
total_reward += reward
# Store experience in replay buffer
memory.append((state, action, torch.FloatTensor([reward]), next_state, done))
state = next_state
if done:
print(f"Episode {episode + 1}/{episodes}, Total Reward: {total_reward}")
break
# Train the network if the replay buffer is sufficiently large
if len(memory) >= batch_size:
batch = random.sample(memory, batch_size)
states, actions, rewards, next_states, dones = zip(*batch)
states = torch.cat(states)
actions = torch.LongTensor(actions).unsqueeze(1)
rewards = torch.cat(rewards)
next_states = torch.cat(next_states)
dones = torch.FloatTensor(dones)
# Compute current Q-values
q_values = q_network(states).gather(1, actions)
# Compute target Q-values
with torch.no_grad():
target_q = target_network(next_states).max(1)[0]
target_q = rewards + (gamma * target_q) * (1 - dones)
target_q = target_q.unsqueeze(1)
# Compute loss and update the network
loss = F.mse_loss(q_values, target_q)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Update the target network
if (episode + 1) % target_update == 0:
target_network.load_state_dict(q_network.state_dict())
# Decay epsilon
if epsilon > epsilon_min:
epsilon *= epsilon_decay
print("Training complete.")
return q_network
# Main function to train the DQN agent
def main():
from absl import app, flags
flags.FLAGS(["train_dqn_B.py"])
screen_size = 64
env = sc2_env.SC2Env(
map_name="MoveToBeacon",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=features.AgentInterfaceFormat(
feature_dimensions=features.Dimensions(screen=screen_size, minimap=screen_size),
use_feature_units=True,
),
step_mul=8,
game_steps_per_episode=0,
visualize=False,
)
try:
train_dqn(env, episodes=100, batch_size=32, screen_size=screen_size)
finally:
env.close()
if __name__ == "__main__":
main()
Explanation of Changes
preprocess_observation Function: Changed obs["feature_screen"] to obs.observation["feature_screen"] and obs["player"] to obs.observation["player"] to correctly access the observation within the TimeStep.
train_dqn Function: Changed obs["available_actions"] to obs.observation["available_actions"] to correctly access available actions, and modified the calls to env.reset() and env.step() to correctly access the observations via the TimeStep object.
To Run the Corrected Code:
Save the corrected code as train_dqn_B.py.
Ensure you have PySC2 installed (pip install pysc2) and the StarCraft II maps in the correct directory as described in the prompt.
Run the script: python train_dqn_B.py
This will now run the DQN training process without the TypeError. Let me know if you have any further questions!
import os
import random
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from collections import deque
import torch.nn.functional as F
from pysc2.env import sc2_env
from pysc2.lib import features
# Define the QNetwork
class QNetwork(nn.Module):
def __init__(self, input_dim, output_dim):
super(QNetwork, self).__init__()
self.fc1 = nn.Linear(input_dim, 128)
self.fc2 = nn.Linear(128, 128)
self.fc3 = nn.Linear(128, output_dim)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
# Preprocess PySC2 observation
def preprocess_observation(obs):
"""Extract and preprocess relevant information from PySC2 observations."""
screen = obs.observation["feature_screen"]
player = obs.observation["player"]
return np.concatenate([screen.flatten(), player], axis=0)
# Train the DQN agent in PySC2
def train_dqn(env, episodes=100, batch_size=32, screen_size=64):
from pysc2.lib import actions #Import actions here
obs = env.reset()[0] # Access the first observation in the TimeStep
state_size = len(preprocess_observation(obs))
action_size = len(actions.FUNCTIONS)
# Initialize Q-network and target network
q_network = QNetwork(state_size, action_size)
target_network = QNetwork(state_size, action_size)
target_network.load_state_dict(q_network.state_dict())
target_network.eval()
optimizer = optim.[Redacted Person](q_network.parameters(), lr=0.001)
memory = deque(maxlen=2000)
gamma = 0.99
epsilon = 1.0
epsilon_min = 0.01
epsilon_decay = 0.995
target_update = 10
for episode in range(episodes):
obs = env.reset()[0] # Access the first observation in the TimeStep
state = preprocess_observation(obs)
state = torch.FloatTensor(state).unsqueeze(0)
total_reward = 0
while True:
# Epsilon-greedy action selection
if random.random() < epsilon:
action = random.choice(obs.observation["available_actions"])
else:
with torch.no_grad():
q_values = q_network(state)
# Mask unavailable actions
mask = torch.full((action_size,), float("-inf"))
mask[obs.observation["available_actions"]] = 0
q_values = q_values + mask
action = torch.argmax(q_values).item()
# Map action to PySC2 action
pysc2_action = actions.FUNCTIONS[action]
if pysc2_action.id in obs.observation["available_actions"]:
obs = env.step([pysc2_action()])[0] #Access the first observation in the TimeStep
else:
continue # Skip if the action is unavailable
# Preprocess next state and compute reward
next_state = preprocess_observation(obs)
next_state = torch.FloatTensor(next_state).unsqueeze(0)
reward = obs.reward
done = obs.last()
total_reward += reward
# Store experience in replay buffer
memory.append((state, action, torch.FloatTensor([reward]), next_state, done))
state = next_state
if done:
print(f"Episode {episode + 1}/{episodes}, Total Reward: {total_reward}")
break
# Train the network if the replay buffer is sufficiently large
if len(memory) >= batch_size:
batch = random.sample(memory, batch_size)
states, actions, rewards, next_states, dones = zip(*batch)
states = torch.cat(states)
actions = torch.LongTensor(actions).unsqueeze(1)
rewards = torch.cat(rewards)
next_states = torch.cat(next_states)
dones = torch.FloatTensor(dones)
# Compute current Q-values
q_values = q_network(states).gather(1, actions)
# Compute target Q-values
with torch.no_grad():
target_q = target_network(next_states).max(1)[0]
target_q = rewards + (gamma * target_q) * (1 - dones)
target_q = target_q.unsqueeze(1)
# Compute loss and update the network
loss = F.mse_loss(q_values, target_q)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Update the target network
if (episode + 1) % target_update == 0:
target_network.load_state_dict(q_network.state_dict())
# Decay epsilon
if epsilon > epsilon_min:
epsilon *= epsilon_decay
print("Training complete.")
return q_network
# Main function to train the DQN agent
def main():
from absl import app, flags
flags.FLAGS(["train_dqn_BB.py"])
screen_size = 64
env = sc2_env.SC2Env(
map_name="MoveToBeacon",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=features.AgentInterfaceFormat(
feature_dimensions=features.Dimensions(screen=screen_size, minimap=screen_size),
use_feature_units=True,
),
step_mul=8,
game_steps_per_episode=0,
visualize=False,
)
try:
train_dqn(env, episodes=100, batch_size=32)
finally:
env.close()
if __name__ == "__main__":
main()
Explanation of Changes
Import actions in train_dqn: Added the line from pysc2.lib import actions inside the train_dqn function. This makes the actions module available within the function's scope, resolving the UnboundLocalError.
To Run the Corrected Code:
Save the corrected code as train_dqn_BB.py.
Ensure you have PySC2 installed (pip install pysc2) and the StarCraft II maps in the correct directory.
Run the script: python train_dqn_BB.py
This should now run the DQN training process without the UnboundLocalError. Let me know if you encounter any further issues!
# Train the DQN agent in PySC2
def train_dqn(env, episodes=100, batch_size=32, screen_size=64):
from pysc2.lib import actions #Import actions here
obs = env.reset()[0] # Access the first observation in the TimeStep
state_size = len(preprocess_observation(obs))
action_size = len(actions.FUNCTIONS)
# Initialize Q-network and target network
q_network = QNetwork(state_size, action_size)
target_network = QNetwork(state_size, action_size)
target_network.load_state_dict(q_network.state_dict())
target_network.eval()
optimizer = optim.[Redacted Person](q_network.parameters(), lr=0.001)
memory = deque(maxlen=2000)
gamma = 0.99
epsilon = 1.0
epsilon_min = 0.01
epsilon_decay = 0.995
target_update = 10
for episode in range(episodes):
obs = env.reset()[0] # Access the first observation in the TimeStep
state = preprocess_observation(obs)
state = torch.FloatTensor(state).unsqueeze(0)
total_reward = 0
while True:
# Epsilon-greedy action selection
if random.random() < epsilon:
action = random.choice(obs.observation["available_actions"])
else:
with torch.no_grad():
q_values = q_network(state)
# Mask unavailable actions
mask = torch.full((action_size,), float("-inf"))
mask[obs.observation["available_actions"]] = 0
q_values = q_values + mask
action = torch.argmax(q_values).item()
# Map action to PySC2 action
pysc2_action = actions.FUNCTIONS[action]
if pysc2_action.id in obs.observation["available_actions"]:
obs = env.step([pysc2_action()])[0] #Access the first observation in the TimeStep
else:
continue # Skip if the action is unavailable
# Preprocess next state and compute reward
next_state = preprocess_observation(obs)
next_state = torch.FloatTensor(next_state).unsqueeze(0)
reward = obs.reward
done = obs.last()
total_reward += reward
# Store experience in replay buffer
memory.append((state, action, torch.FloatTensor([reward]), next_state, done))
state = next_state
if done:
print(f"Episode {episode + 1}/{episodes}, Total Reward: {total_reward}")
break
# Train the network if the replay buffer is sufficiently large
if len(memory) >= batch_size:
batch = random.sample(memory, batch_size)
states, actions, rewards, next_states, dones = zip(*batch)
states = torch.cat(states)
actions = torch.LongTensor(actions).unsqueeze(1)
rewards = torch.cat(rewards)
next_states = torch.cat(next_states)
dones = torch.FloatTensor(dones)
# Compute current Q-values
q_values = q_network(states).gather(1, actions)
# Compute target Q-values
with torch.no_grad():
target_q = target_network(next_states).max(1)[0]
target_q = rewards + (gamma * target_q) * (1 - dones)
target_q = target_q.unsqueeze(1)
# Compute loss and update the network
loss = F.mse_loss(q_values, target_q)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Update the target network
if (episode + 1) % target_update == 0:
target_network.load_state_dict(q_network.state_dict())
# Decay epsilon
if epsilon > epsilon_min:
epsilon *= epsilon_decay
print("Training complete.")
return q_network
train_dqn_BA.py got the following error:
pygame 2.6.1 (SDL 2.28.4, Python 3.8.13)
Hello from the pygame community. https://www.pygame.org/contribute.html
Version: B75689 (SC2.4.10)
Build: Aug 12 2019 17:16:57
Command Line: '"/workspace/StarCraftII/Versions/Base75689/SC2_x64" -listen [Redacted IPAddress] -port 46243 -dataDir /workspace/StarCraftII/ -tempDir /tmp/sc-jfg0i73k/'
Starting up...
Startup Phase 1 complete
Startup Phase 2 complete
Creating stub renderer...
Listening on: [Redacted IPAddress]:46243
Startup Phase 3 complete. Ready for commands.
ConnectHandler: Request from [Redacted IPAddress]:47798 accepted
ReadyHandler: [Redacted IPAddress]:47798 ready
Requesting to join a single player game
Configuring interface options
Configure: raw interface enabled
Configure: feature layer interface enabled
Configure: score interface enabled
Configure: render interface disabled
Launching next game.
Next launch phase started: 2
Next launch phase started: 3
Next launch phase started: 4
Next launch phase started: 5
Next launch phase started: 6
Next launch phase started: 7
Next launch phase started: 8
Game has started.
Using default stable ids, none found at: /workspace/StarCraftII/stableid.json
Successfully loaded stable ids: GameData\stableid.json
Sending ResponseJoinGame
Game has started.
DataHandler: unable to parse websocket frame.
CloseHandler: [Redacted IPAddress]:47798 disconnected
Traceback (most recent call last):
File "train_dqn_BA.py", line 157, in
main()
File "train_dqn_BA.py", line 151, in main
train_dqn(env, episodes=100, batch_size=32)
File "train_dqn_BA.py", line 76, in train_dqn
obs = env.step([pysc2_action()])[0] #Access the first observation in the TimeStep
File "/opt/conda/lib/python3.8/site-packages/pysc2/lib/stopwatch.py", line 205, in _stopwatch
return func(*args, **kwargs)
File "/opt/conda/lib/python3.8/site-packages/pysc2/env/sc2_env.py", line 524, in step
actions = [[f.transform_action(o.observation, a, skip_available=skip)
File "/opt/conda/lib/python3.8/site-packages/pysc2/env/sc2_env.py", line 524, in
actions = [[f.transform_action(o.observation, a, skip_available=skip)
File "/opt/conda/lib/python3.8/site-packages/pysc2/env/sc2_env.py", line 524, in
actions = [[f.transform_action(o.observation, a, skip_available=skip)
File "/opt/conda/lib/python3.8/site-packages/pysc2/lib/stopwatch.py", line 205, in _stopwatch
return func(*args, **kwargs)
File "/opt/conda/lib/python3.8/site-packages/pysc2/lib/features.py", line 1611, in transform_action
raise ValueError(
ValueError: Wrong number of arguments for function: 2/select_point (6/select_point_act [4]; 0/screen [0, 0]), got: []
python
# Train the DQN agent in PySC2
def train_dqn(env, episodes=100, batch_size=32):
from pysc2.lib import actions #Import actions here
obs = env.reset()[0] # Access the first observation
state_size = len(preprocess_observation(obs))
action_size = len(actions.FUNCTIONS)
# Initialize Q-network and target network
q_network = QNetwork(state_size, action_size)
target_network = QNetwork(state_size, action_size)
target_network.load_state_dict(q_network.state_dict())
target_network.eval()
optimizer = optim.[Redacted Person](q_network.parameters(), lr=0.001)
memory = deque(maxlen=2000)
gamma = 0.99
epsilon = 1.0
epsilon_min = 0.01
epsilon_decay = 0.995
target_update = 10
for episode in range(episodes):
obs = env.reset()[0] # Access the first observation
state = preprocess_observation(obs)
state = torch.FloatTensor(state).unsqueeze(0)
total_reward = 0
while True:
# Epsilon-greedy action selection
if random.random() < epsilon:
action = random.choice(obs.observation["available_actions"])
else:
with torch.no_grad():
q_values = q_network(state)
# Mask unavailable actions
mask = torch.full((action_size,), float("-inf"))
mask[obs.observation["available_actions"]] = 0
q_values = q_values + mask
action = torch.argmax(q_values).item()
# Map action to PySC2 action
if action in obs.observation["available_actions"]:
pysc2_action = actions.FunctionCall(action, [])
obs = env.step([pysc2_action])[0]
else:
continue # Skip if the action is unavailable
# Preprocess next state and compute reward
next_state = preprocess_observation(obs)
next_state = torch.FloatTensor(next_state).unsqueeze(0)
reward = obs.reward
done = obs.last()
total_reward += reward
# Store experience in replay buffer
memory.append((state, action, torch.FloatTensor([reward]), next_state, done))
state = next_state
if done:
print(f"Episode {episode + 1}/{episodes}, Total Reward: {total_reward}")
break
# Train the network if the replay buffer is sufficiently large
if len(memory) >= batch_size:
batch = random.sample(memory, batch_size)
states, actions, rewards, next_states, dones = zip(*batch)
states = torch.cat(states)
actions = torch.LongTensor(actions).unsqueeze(1)
rewards = torch.cat(rewards)
next_states = torch.cat(next_states)
dones = torch.FloatTensor(dones)
# Compute current Q-values
q_values = q_network(states).gather(1, actions)
# Compute target Q-values
with torch.no_grad():
target_q = target_network(next_states).max(1)[0]
target_q = rewards + (gamma * target_q) * (1 - dones)
target_q = target_q.unsqueeze(1)
# Compute loss and update the network
loss = F.mse_loss(q_values, target_q)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Update the target network
if (episode + 1) % target_update == 0:
target_network.load_state_dict(q_network.state_dict())
# Decay epsilon
if epsilon > epsilon_min:
epsilon *= epsilon_decay
print("Training complete.")
return q_network
run train_dqn_BB.py, got the following error:
pygame 2.6.1 (SDL 2.28.4, Python 3.8.13)
Hello from the pygame community. https://www.pygame.org/contribute.html
Version: B75689 (SC2.4.10)
Build: Aug 12 2019 17:16:57
Command Line: '"/workspace/StarCraftII/Versions/Base75689/SC2_x64" -listen [Redacted IPAddress] -port 36089 -dataDir /workspace/StarCraftII/ -tempDir /tmp/sc-xp0tzhjr/'
Starting up...
Startup Phase 1 complete
Startup Phase 2 complete
Creating stub renderer...
Listening on: [Redacted IPAddress]:36089
Startup Phase 3 complete. Ready for commands.
ConnectHandler: Request from [Redacted IPAddress]:36506 accepted
ReadyHandler: [Redacted IPAddress]:36506 ready
Requesting to join a single player game
Configuring interface options
Configure: raw interface enabled
Configure: feature layer interface enabled
Configure: score interface enabled
Configure: render interface disabled
Launching next game.
Next launch phase started: 2
Next launch phase started: 3
Next launch phase started: 4
Next launch phase started: 5
Next launch phase started: 6
Next launch phase started: 7
Next launch phase started: 8
Game has started.
Using default stable ids, none found at: /workspace/StarCraftII/stableid.json
Successfully loaded stable ids: GameData\stableid.json
Sending ResponseJoinGame
Game has started.
RequestQuit command received.
Closing Application...
DataHandler: unable to parse websocket frame.
CloseHandler: [Redacted IPAddress]:36506 disconnected
Traceback (most recent call last):
File "train_dqn_BB.py", line 158, in
main()
File "train_dqn_BB.py", line 152, in main
train_dqn(env, episodes=100, batch_size=32)
File "train_dqn_BB.py", line 77, in train_dqn
obs = env.step([pysc2_action])[0]
File "/opt/conda/lib/python3.8/site-packages/pysc2/lib/stopwatch.py", line 205, in _stopwatch
return func(*args, **kwargs)
File "/opt/conda/lib/python3.8/site-packages/pysc2/env/sc2_env.py", line 524, in step
actions = [[f.transform_action(o.observation, a, skip_available=skip)
File "/opt/conda/lib/python3.8/site-packages/pysc2/env/sc2_env.py", line 524, in
actions = [[f.transform_action(o.observation, a, skip_available=skip)
File "/opt/conda/lib/python3.8/site-packages/pysc2/env/sc2_env.py", line 524, in
actions = [[f.transform_action(o.observation, a, skip_available=skip)
File "/opt/conda/lib/python3.8/site-packages/pysc2/lib/stopwatch.py", line 205, in _stopwatch
return func(*args, **kwargs)
File "/opt/conda/lib/python3.8/site-packages/pysc2/lib/features.py", line 1611, in transform_action
raise ValueError(
ValueError: Wrong number of arguments for function: 4/select_control_group (4/control_group_act [5]; 5/control_group_id [10]), got: []
USER DEBUG command: understand the errors above and improve your code to avoid the problem.
import os
import random
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from collections import deque
import torch.nn.functional as F
from pysc2.env import sc2_env
from pysc2.lib import features
# Define the QNetwork
class QNetwork(nn.Module):
def __init__(self, input_dim, output_dim):
super(QNetwork, self).__init__()
self.fc1 = nn.Linear(input_dim, 128)
self.fc2 = nn.Linear(128, 128)
self.fc3 = nn.Linear(128, output_dim)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
# Preprocess PySC2 observation
def preprocess_observation(obs):
"""Extract and preprocess relevant information from PySC2 observations."""
screen = obs.observation["feature_screen"]
player = obs.observation["player"]
return np.concatenate([screen.flatten(), player], axis=0)
# Train the DQN agent in PySC2
def train_dqn(env, episodes=100, batch_size=32):
from pysc2.lib import actions # Import actions here
obs = env.reset()[0] # Access the first observation
state_size = len(preprocess_observation(obs))
action_size = len(actions.FUNCTIONS)
# Get action spec from the env
action_spec = env.action_spec()[0] # Assuming single agent
# Initialize Q-network and target network
q_network = QNetwork(state_size, action_size)
target_network = QNetwork(state_size, action_size)
target_network.load_state_dict(q_network.state_dict())
target_network.eval()
optimizer = optim.[Redacted Person](q_network.parameters(), lr=0.001)
memory = deque(maxlen=2000)
gamma = 0.99
epsilon = 1.0
epsilon_min = 0.01
epsilon_decay = 0.995
target_update = 10
for episode in range(episodes):
obs = env.reset()[0] # Access the first observation
state = preprocess_observation(obs)
state = torch.FloatTensor(state).unsqueeze(0)
total_reward = 0
while True:
# Epsilon-greedy action selection
if random.random() < epsilon:
action = random.choice(obs.observation["available_actions"])
else:
with torch.no_grad():
q_values = q_network(state)
# Mask unavailable actions
mask = torch.full((action_size,), float("-inf"))
mask[obs.observation["available_actions"]] = 0
q_values = q_values + mask
action = torch.argmax(q_values).item()
# Map action to PySC2 action
if action in obs.observation["available_actions"]:
func = actions.FUNCTIONS[action]
# Create dummy arguments based on the spec
args = []
for arg_type in func.args:
if arg_type.name == 'screen' or arg_type.name == 'minimap':
args.append([0, 0]) # Dummy screen/minimap coordinate.
[Redacted Person] arg_type.name == 'control_group_id':
args.append([1]) # Dummy control group
[Redacted Person] arg_type.name == 'unit_tags':
args.append([]) # Dummy unit_tags
else:
args.append([0]) # Dummy values, modify as needed
pysc2_action = actions.FunctionCall(action, args)
obs = env.step([pysc2_action])[0]
else:
continue # Skip if the action is unavailable
# Preprocess next state and compute reward
next_state = preprocess_observation(obs)
next_state = torch.FloatTensor(next_state).unsqueeze(0)
reward = obs.reward
done = obs.last()
total_reward += reward
# Store experience in replay buffer
memory.append((state, action, torch.FloatTensor([reward]), next_state, done))
state = next_state
if done:
print(f"Episode {episode + 1}/{episodes}, Total Reward: {total_reward}")
break
# Train the network if the replay buffer is sufficiently large
if len(memory) >= batch_size:
batch = random.sample(memory, batch_size)
states, actions, rewards, next_states, dones = zip(*batch)
states = torch.cat(states)
actions = torch.LongTensor(actions).unsqueeze(1)
rewards = torch.cat(rewards)
next_states = torch.cat(next_states)
dones = torch.FloatTensor(dones)
# Compute current Q-values
q_values = q_network(states).gather(1, actions)
# Compute target Q-values
with torch.no_grad():
target_q = target_network(next_states).max(1)[0]
target_q = rewards + (gamma * target_q) * (1 - dones)
target_q = target_q.unsqueeze(1)
# Compute loss and update the network
loss = F.mse_loss(q_values, target_q)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Update the target network
if (episode + 1) % target_update == 0:
target_network.load_state_dict(q_network.state_dict())
# Decay epsilon
if epsilon > epsilon_min:
epsilon *= epsilon_decay
print("Training complete.")
return q_network
# Main function to train the DQN agent
def main():
from absl import app, flags
flags.FLAGS(["train_dqn_BC.py"])
screen_size = 64
env = sc2_env.SC2Env(
map_name="MoveToBeacon",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=features.AgentInterfaceFormat(
feature_dimensions=features.Dimensions(screen=screen_size, minimap=screen_size),
use_feature_units=True,
),
step_mul=8,
game_steps_per_episode=0,
visualize=False,
)
try:
train_dqn(env, episodes=100, batch_size=32)
finally:
env.close()
if __name__ == "__main__":
main()
Explanation of Changes
Action Spec Retrieval:
action_spec = env.action_spec()[0] is added after the environment is created to access the action spec of the first agent, which we need to inspect the arguments that the actions take.
Argument Generation
In the training loop, args = [] initializes an empty list to hold the arguments for the function call.
The code iterates through the func.args to check for each argument.
If an argument name matches 'screen' or 'minimap', we create a dummy coordinate [0, 0] which is appended to args. If the argument name is 'control_group_id', we append [1] to args, and for 'unit_tags' we append an empty list []. For other cases, we append a dummy argument [0].
FunctionCall with Arguments:
pysc2_action = actions.FunctionCall(action, args) constructs an actions.FunctionCall object, passing the arguments.
To Run the Corrected Code:
Save the corrected code as train_dqn_BC.py.
Ensure you have PySC2 installed and the StarCraft II maps in the correct directory.
Run the script: python train_dqn_BC.py
This should now correctly pass dummy arguments to the actions, and you should be able to train the DQN agent.
Important Note:
The dummy arguments provided are placeholders and may not result in meaningful gameplay. The agent will still learn, but the actions might be ineffective because the arguments are not driven by the current game state. In future iterations, you'll need to modify the argument generation to choose the arguments based on observations from the environment to take more meaningful actions. Let me know if you have more questions!
import os
import random
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from collections import deque
import torch.nn.functional as F
from pysc2.env import sc2_env
from pysc2.lib import actions, features
# Define the QNetwork
class QNetwork(nn.Module):
def __init__(self, input_dim, output_dim):
super(QNetwork, self).__init__()
self.fc1 = nn.Linear(input_dim, 128)
self.fc2 = nn.Linear(128, 128)
self.fc3 = nn.Linear(128, output_dim)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
# Preprocess PySC2 observation
def preprocess_observation(obs):
"""Extract and preprocess relevant information from PySC2 observations."""
observation = obs.observation # Access the observation dictionary
screen = observation["feature_screen"]
player = observation["player"]
return np.concatenate([screen.flatten(), player], axis=0)
# Train the DQN agent in PySC2
def train_dqn(env, episodes=100, batch_size=32):
from pysc2.lib import actions # Import actions here
obs = env.reset()[0] # Access the first observation
state_size = len(preprocess_observation(obs))
action_size = len(actions.FUNCTIONS)
# Initialize Q-network and target network
q_network = QNetwork(state_size, action_size)
target_network = QNetwork(state_size, action_size)
target_network.load_state_dict(q_network.state_dict())
target_network.eval()
optimizer = optim.[Redacted Person](q_network.parameters(), lr=0.001)
memory = deque(maxlen=2000)
gamma = 0.99
epsilon = 1.0
epsilon_min = 0.01
epsilon_decay = 0.995
target_update = 10
for episode in range(episodes):
obs = env.reset()[0] # Access the first observation
state = preprocess_observation(obs)
state = torch.FloatTensor(state).unsqueeze(0)
total_reward = 0
while True:
# Epsilon-greedy action selection
if random.random() < epsilon:
action = random.choice(obs.observation["available_actions"])
else:
with torch.no_grad():
q_values = q_network(state)
# Mask unavailable actions
mask = torch.full((action_size,), float("-inf"))
mask[obs.observation["available_actions"]] = 0
q_values = q_values + mask
action = torch.argmax(q_values).item()
# Construct the PySC2 action with default arguments
pysc2_action = construct_action(action, obs)
# Skip if the action is invalid or unavailable
if pysc2_action is None:
continue
# Execute the action in the environment
obs = env.step([pysc2_action])[0] # Access the first observation in the TimeStep
# Preprocess next state and compute reward
next_state = preprocess_observation(obs)
next_state = torch.FloatTensor(next_state).unsqueeze(0)
reward = obs.reward
done = obs.last()
total_reward += reward
# Store experience in replay buffer
memory.append((state, action, torch.FloatTensor([reward]), next_state, done))
state = next_state
if done:
print(f"Episode {episode + 1}/{episodes}, Total Reward: {total_reward}")
break
# Train the network if the replay buffer is sufficiently large
if len(memory) >= batch_size:
batch = random.sample(memory, batch_size)
states, actions_batch, rewards, next_states, dones = zip(*batch)
states = torch.cat(states)
actions_batch = torch.LongTensor(actions_batch).unsqueeze(1)
rewards = torch.cat(rewards)
next_states = torch.cat(next_states)
dones = torch.FloatTensor(dones)
# Compute current Q-values
q_values = q_network(states).gather(1, actions_batch)
# Compute target Q-values
with torch.no_grad():
target_q = target_network(next_states).max(1)[0]
target_q = rewards + (gamma * target_q) * (1 - dones)
target_q = target_q.unsqueeze(1)
# Compute loss and update the network
loss = F.mse_loss(q_values, target_q)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Update the target network
if (episode + 1) % target_update == 0:
target_network.load_state_dict(q_network.state_dict())
# Decay epsilon
if epsilon > epsilon_min:
epsilon *= epsilon_decay
print("Training complete.")
return q_network
def construct_action(action_id, obs):
"""Construct a PySC2 action with default arguments."""
from [Redacted SWIFTCode] import actions
# Get the action function
action_fn = actions.FUNCTIONS[action_id]
# Check if the action is available
if action_id not in obs.observation["available_actions"]:
return None
# Construct the arguments for the action
args = []
for arg in action_fn.args:
if arg.name in ["screen", "minimap", "screen2"]:
# Provide default coordinates (e.g., center of the screen)
args.append([32, 32]) # Replace with appropriate screen size
[Redacted Person] arg.name in ["control_group_act", "control_group_id"]:
# Provide default control group values
args.append([0]) # Default to "Recall" for control_group_act
[Redacted Person] arg.name == "queued":
# Provide default queued value (0 = immediate)
args.append([0])
else:
# Default value for other arguments
args.append([0])
return actions.FunctionCall(action_id, args)
# Main function to train the DQN agent
def main():
from absl import app, flags
flags.FLAGS(["train_dqn_BB.py"])
screen_size = 64
env = sc2_env.SC2Env(
map_name="MoveToBeacon",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=features.AgentInterfaceFormat(
feature_dimensions=features.Dimensions(screen=screen_size, minimap=screen_size),
use_feature_units=True,
),
step_mul=8,
game_steps_per_episode=0,
visualize=False,
)
try:
train_dqn(env, episodes=100, batch_size=32)
finally:
env.close()
if __name__ == "__main__":
main()
The code above works, and printing the following episodes:
code
pygame 2.6.1 (SDL 2.28.4, Python 3.8.13)
Hello from the pygame community. https://www.pygame.org/contribute.html
Version: B75689 (SC2.4.10)
Build: Aug 12 2019 17:16:57
Command Line: '"/workspace/StarCraftII/Versions/Base75689/SC2_x64" -listen [Redacted IPAddress] -port 40144 -dataDir /workspace/StarCraftII/ -tempDir /tmp/sc-fdogbb__/'
Starting up...
Startup Phase 1 complete
Startup Phase 2 complete
Creating stub renderer...
Listening on: [Redacted IPAddress]:40144
Startup Phase 3 complete. Ready for commands.
ConnectHandler: Request from [Redacted IPAddress]:33204 accepted
ReadyHandler: [Redacted IPAddress]:33204 ready
Requesting to join a single player game
Configuring interface options
Configure: raw interface enabled
Configure: feature layer interface enabled
Configure: score interface enabled
Configure: render interface disabled
Launching next game.
Next launch phase started: 2
Next launch phase started: 3
Next launch phase started: 4
Next launch phase started: 5
Next launch phase started: 6
Next launch phase started: 7
Next launch phase started: 8
Game has started.
Using default stable ids, none found at: /workspace/StarCraftII/stableid.json
Successfully loaded stable ids: GameData\stableid.json
Sending ResponseJoinGame
Game has started.
Episode 1/100, Total Reward: 0
Game has started.
Episode 2/100, Total Reward: 0
Game has started.
Episode 3/100, Total Reward: 0
Game has started.
Episode 4/100, Total Reward: 0
Game has started.
Episode 5/100, Total Reward: 0
Game has started.
...
Episode 92/100, Total Reward: 0
Game has started.
Episode 93/100, Total Reward: 1
Game has started.
Episode 94/100, Total Reward: 0
Game has started.
Episode 95/100, Total Reward: 0
Game has started.
Episode 96/100, Total Reward: 0
Game has started.
Episode 97/100, Total Reward: 0
Game has started.
Episode 98/100, Total Reward: 0
Game has started.
Episode 99/100, Total Reward: 0
Game has started.
Episode 100/100, Total Reward: 0
Training complete.
RequestQuit command received.
Closing Application...
DataHandler: unable to parse websocket frame.
CloseHandler: [Redacted IPAddress]:33204 disconnected
Very rarely does the training process lead to reward (Episode 93/100, Total Reward: 1), think and explain why this is happening, and suggest how to improve. Also, the current episode logs are not transparent--I do not know what is going on (env/state/action). Print out enough information so that users could understand what is going on with the env and the agent.
import os
import random
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from collections import deque
import torch.nn.functional as F
from pysc2.env import sc2_env
from pysc2.lib import actions, features
# Define the QNetwork
class QNetwork(nn.Module):
def __init__(self, input_dim, output_dim):
super(QNetwork, self).__init__()
self.fc1 = nn.Linear(input_dim, 128)
self.fc2 = nn.Linear(128, 128)
self.fc3 = nn.Linear(128, output_dim)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
# Preprocess PySC2 observation
def preprocess_observation(obs):
"""Extract and preprocess relevant information from PySC2 observations."""
observation = obs.observation # Access the observation dictionary
screen = observation["feature_screen"]
player = observation["player"]
return np.concatenate([screen.flatten(), player], axis=0)
# Train the DQN agent in PySC2
def train_dqn(env, episodes=100, batch_size=32):
from pysc2.lib import actions # Import actions here
obs = env.reset()[0] # Access the first observation
state_size = len(preprocess_observation(obs))
action_size = len(actions.FUNCTIONS)
# Initialize Q-network and target network
q_network = QNetwork(state_size, action_size)
target_network = QNetwork(state_size, action_size)
target_network.load_state_dict(q_network.state_dict())
target_network.eval()
optimizer = optim.[Redacted Person](q_network.parameters(), lr=0.001)
memory = deque(maxlen=2000)
gamma = 0.99
epsilon = 1.0
epsilon_min = 0.01
epsilon_decay = 0.995
target_update = 10
for episode in range(episodes):
obs = env.reset()[0] # Access the first observation
state = preprocess_observation(obs)
state = torch.FloatTensor(state).unsqueeze(0)
total_reward = 0
step_count = 0
while True:
# Epsilon-greedy action selection
if random.random() < epsilon:
action = random.choice(obs.observation["available_actions"])
else:
with torch.no_grad():
q_values = q_network(state)
# Mask unavailable actions
mask = torch.full((action_size,), float("-inf"))
mask[obs.observation["available_actions"]] = 0
q_values = q_values + mask
action = torch.argmax(q_values).item()
# Construct the PySC2 action with default arguments
pysc2_action, action_name, action_args = construct_action(action, obs)
# Skip if the action is invalid or unavailable
if pysc2_action is None:
continue
# Execute the action in the environment
next_obs = env.step([pysc2_action])[0] # Access the first observation in the TimeStep
# Preprocess next state and compute reward
next_state = preprocess_observation(next_obs)
next_state = torch.FloatTensor(next_state).unsqueeze(0)
reward = next_obs.reward
done = next_obs.last()
total_reward += reward
# Log information
print(f"Episode: {episode + 1}, Step: {step_count}, Action: {action_name}, Args: {action_args}, Reward: {reward}, Done: {done}")
# Store experience in replay buffer
memory.append((state, action, torch.FloatTensor([reward]), next_state, done))
state = next_state
obs = next_obs
step_count += 1
if done:
print(f"Episode {episode + 1}/{episodes}, Total Reward: {total_reward}")
break
# Train the network if the replay buffer is sufficiently large
if len(memory) >= batch_size:
batch = random.sample(memory, batch_size)
states, actions_batch, rewards, next_states, dones = zip(*batch)
states = torch.cat(states)
actions_batch = torch.LongTensor(actions_batch).unsqueeze(1)
rewards = torch.cat(rewards)
next_states = torch.cat(next_states)
dones = torch.FloatTensor(dones)
# Compute current Q-values
q_values = q_network(states).gather(1, actions_batch)
# Compute target Q-values
with torch.no_grad():
target_q = target_network(next_states).max(1)[0]
target_q = rewards + (gamma * target_q) * (1 - dones)
target_q = target_q.unsqueeze(1)
# Compute loss and update the network
loss = F.mse_loss(q_values, target_q)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Update the target network
if (episode + 1) % target_update == 0:
target_network.load_state_dict(q_network.state_dict())
# Decay epsilon
if epsilon > epsilon_min:
epsilon *= epsilon_decay
print("Training complete.")
return q_network
def construct_action(action_id, obs):
"""Construct a PySC2 action with default arguments."""
from [Redacted SWIFTCode] import actions
# Get the action function
action_fn = actions.FUNCTIONS[action_id]
# Check if the action is available
if action_id not in obs.observation["available_actions"]:
return None, None, None
# Construct the arguments for the action
args = []
for arg in action_fn.args:
if arg.name in ["screen", "minimap", "screen2"]:
# Provide default coordinates (e.g., center of the screen)
args.append([32, 32]) # Replace with appropriate screen size
[Redacted Person] arg.name in ["control_group_act", "control_group_id"]:
# Provide default control group values
args.append([0]) # Default to "Recall" for control_group_act
[Redacted Person] arg.name == "queued":
# Provide default queued value (0 = immediate)
args.append([0])
else:
# Default value for other arguments
args.append([0])
return actions.FunctionCall(action_id, args), action_fn.name, args
# Main function to train the DQN agent
def main():
from absl import app, flags
flags.FLAGS(["train_dqn_CD.py"])
screen_size = 64
env = sc2_env.SC2Env(
map_name="MoveToBeacon",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=features.AgentInterfaceFormat(
feature_dimensions=features.Dimensions(screen=screen_size, minimap=screen_size),
use_feature_units=True,
),
step_mul=8,
game_steps_per_episode=0,
visualize=False,
)
try:
train_dqn(env, episodes=100, batch_size=32)
finally:
env.close()
if __name__ == "__main__":
main()
Key Improvements:
Detailed Logging: Inside the training loop, before calling env.step(), the code now prints:
Episode: The current episode number.
Step: How many steps the agent has taken in the episode.
Action: The name of the action function that was executed.
Args: The arguments that were passed to that action.
Reward: The reward the agent got after the action.
Done: Indicates if the episode is over.
Return action info from construct_action: The construct_action function now returns the constructed action, the name of the action, and the arguments of the actions, so they can be used for logging.
Step counter: step_count is added to provide more detailed logging.
Access next observation The step function returns the next observation, so the obs is updated via the variable next_obs, and it gets copied to the obs variable.
Next Steps for Improving Performance
While this version is much more transparent and debuggable, the agent still may not learn effectively due to the following issues:
Improve Exploration: Modify the exploration policy to be more effective. Start with a high epsilon value, but also add an exploration bonus so the agent tries different things to receive rewards, rather than random exploration.
Argument Selection The default coordinates in construct_action should be improved to include the context of the environment, and pass in the real coordinates of units in the game.
Reward Shaping: Add intermediate rewards to encourage the agent to move in the right direction. One approach could be to provide a small positive reward for moving closer to the beacon.
More Sophisticated Q Network: The current Q network is very simple, and can be improved by adding convolutional layers which can better extract the spatial relationship between different features.
To Run the Corrected Code:
Save the corrected code as train_dqn_CD.py.
Ensure you have PySC2 installed and the StarCraft II maps in the correct directory.
Run the script: python train_dqn_CD.py
This will provide much better insight into what the agent is doing. Remember, RL algorithms often require careful tuning and experimentation to work well. Let me know if you have more questions!
import os
import random
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from collections import deque
import torch.nn.functional as F
from pysc2.env import sc2_env
from pysc2.lib import actions, features
# Define the QNetwork
class QNetwork(nn.Module):
def __init__(self, input_dim, output_dim):
super(QNetwork, self).__init__()
self.fc1 = nn.Linear(input_dim, 128)
self.fc2 = nn.Linear(128, 128)
self.fc3 = nn.Linear(128, output_dim)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
# Preprocess PySC2 observation
def preprocess_observation(obs):
"""Extract and preprocess relevant information from PySC2 observations."""
observation = obs.observation # Access the observation dictionary
screen = observation["feature_screen"]
player = observation["player"]
return np.concatenate([screen.flatten(), player], axis=0)
# Train the DQN agent in PySC2
def train_dqn(env, episodes=100, batch_size=32):
from pysc2.lib import actions # Import actions here
obs = env.reset()[0] # Access the first observation
state_size = len(preprocess_observation(obs))
action_size = len(actions.FUNCTIONS)
# Initialize Q-network and target network
q_network = QNetwork(state_size, action_size)
target_network = QNetwork(state_size, action_size)
target_network.load_state_dict(q_network.state_dict())
target_network.eval()
optimizer = optim.[Redacted Person](q_network.parameters(), lr=0.001)
memory = deque(maxlen=2000)
gamma = 0.99
epsilon = 1.0
epsilon_min = 0.01
epsilon_decay = 0.995
target_update = 10
for episode in range(episodes):
obs = env.reset()[0] # Access the first observation
state = preprocess_observation(obs)
state = torch.FloatTensor(state).unsqueeze(0)
total_reward = 0
step_count = 0
while True:
# Epsilon-greedy action selection
if random.random() < epsilon:
action = random.choice(obs.observation["available_actions"])
else:
with torch.no_grad():
q_values = q_network(state)
# Mask unavailable actions
mask = torch.full((action_size,), float("-inf"))
mask[obs.observation["available_actions"]] = 0
q_values = q_values + mask
action = torch.argmax(q_values).item()
# Construct the PySC2 action with default arguments
pysc2_action, action_name, action_args = construct_action(action, obs)
# Skip if the action is invalid or unavailable
if pysc2_action is None:
continue
# Execute the action in the environment
next_obs = env.step([pysc2_action])[0] # Access the first observation in the TimeStep
# Preprocess next state and compute reward
next_state = preprocess_observation(next_obs)
next_state = torch.FloatTensor(next_state).unsqueeze(0)
reward = next_obs.reward
done = next_obs.last()
total_reward += reward
# Log information
print(f"Episode: {episode + 1}, Step: {step_count}, Action: {action_name}, Args: {action_args}, Reward: {reward}, Done: {done}")
# Store experience in replay buffer
memory.append((state, action, torch.FloatTensor([reward]), next_state, done))
state = next_state
obs = next_obs
step_count += 1
if done:
print(f"Episode {episode + 1}/{episodes}, Total Reward: {total_reward}")
break
# Train the network if the replay buffer is sufficiently large
if len(memory) >= batch_size:
batch = random.sample(memory, batch_size)
states, actions_batch, rewards, next_states, dones = zip(*batch)
states = torch.cat(states)
actions_batch = torch.LongTensor(actions_batch).unsqueeze(1)
rewards = torch.cat(rewards)
next_states = torch.cat(next_states)
dones = torch.FloatTensor(dones)
# Compute current Q-values
q_values = q_network(states).gather(1, actions_batch)
# Compute target Q-values
with torch.no_grad():
target_q = target_network(next_states).max(1)[0]
target_q = rewards + (gamma * target_q) * (1 - dones)
target_q = target_q.unsqueeze(1)
# Compute loss and update the network
loss = F.mse_loss(q_values, target_q)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Update the target network
if (episode + 1) % target_update == 0:
target_network.load_state_dict(q_network.state_dict())
# Decay epsilon
if epsilon > epsilon_min:
epsilon *= epsilon_decay
print("Training complete.")
return q_network
def construct_action(action_id, obs):
"""Construct a PySC2 action with default arguments."""
from [Redacted SWIFTCode] import actions
# Get the action function
action_fn = actions.FUNCTIONS[action_id]
# Check if the action is available
if action_id not in obs.observation["available_actions"]:
return None, None, None
# Construct the arguments for the action
args = []
for arg in action_fn.args:
if arg.name in ["screen", "minimap", "screen2"]:
# Provide default coordinates (e.g., center of the screen)
args.append([32, 32]) # Replace with appropriate screen size
[Redacted Person] arg.name in ["control_group_act", "control_group_id"]:
# Provide default control group values
args.append([0]) # Default to "Recall" for control_group_act
[Redacted Person] arg.name == "queued":
# Provide default queued value (0 = immediate)
args.append([0])
else:
# Default value for other arguments
args.append([0])
return actions.FunctionCall(action_id, args), action_fn.name, args
# Main function to train the DQN agent
def main():
from absl import app, flags
flags.FLAGS(["train_dqn.py"])
screen_size = 64
env = sc2_env.SC2Env(
map_name="MoveToBeacon",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=features.AgentInterfaceFormat(
feature_dimensions=features.Dimensions(screen=screen_size, minimap=screen_size),
use_feature_units=True,
),
step_mul=8,
game_steps_per_episode=0,
visualize=False,
)
try:
train_dqn(env, episodes=100, batch_size=32)
finally:
env.close()
if __name__ == "__main__":
main()
Key Features of this Complete Code:
All Previous Fixes: Incorporates all the previous fixes, resolving the TypeError, UnboundLocalError, and ValueError issues related to action arguments.
Clear Logging: Prints detailed logs for each step, making it easier to monitor the agent's actions, arguments, and rewards.
Modular Structure: Keeps the action construction logic separate in the construct_action function.
Standard DQN: Uses standard DQN implementation to allow better understanding of the training process.
How to Use:
Save the code above as train_dqn.py.
Ensure that you have PySC2 installed and that the Starcraft II maps are in your $SC2PATH/Maps/ directory.
Run: python train_dqn.py
This version should run without errors, be transparent, and provide you with more detailed output, making it easier to observe the behavior of the DQN agent during training. Remember that further improvements are needed to get the agent to learn efficiently, including exploration strategy, reward shaping, and action argument selection.
import os
import random
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from collections import deque
import torch.nn.functional as F
from pysc2.env import sc2_env
from pysc2.lib import actions, features
# Define the QNetwork with CNN for spatial features
class QNetwork(nn.Module):
def __init__(self, input_channels, output_dim):
super(QNetwork, self).__init__()
self.conv1 = nn.Conv2d(input_channels, 16, kernel_size=3, stride=1)
self.conv2 = nn.Conv2d(16, 32, kernel_size=3, stride=1)
self.fc1 = nn.Linear(32 * 6 * 6, 128) # Adjust dimensions based on screen size
self.fc2 = nn.Linear(128, output_dim)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = x.view(x.size(0), -1) # Flatten
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
# Preprocess PySC2 observation for CNN
def preprocess_observation(obs):
"""Extract screen features as input for CNN."""
screen = obs.observation["feature_screen"] # (C, H, W)
return torch.FloatTensor(screen).unsqueeze(0) # Add batch dimension
# Compute shaped reward
def shaped_reward(obs, previous_obs):
"""Compute a shaped reward based on the distance to the beacon."""
# Extract beacon position from feature_screen (value 3 is the beacon)
beacon_screen = (obs.observation["feature_screen"][3] > 0).nonzero()
player_screen = obs.observation["feature_screen"][1].nonzero() # Player position
if beacon_screen[0].size == 0 or player_screen[0].size == 0:
# No beacon or player visible
return obs.reward
# Compute the Manhattan or Euclidean distance between the player and beacon
beacon_position = np.mean(beacon_screen, axis=1)
player_position = np.mean(player_screen, axis=1)
distance = np.linalg.norm(beacon_position - player_position)
# Shaped reward: negative distance (closer is better) + original reward
return -distance + obs.reward
# [Redacted Person] exploration for better action selection
def [Redacted Person]_exploration(q_values, temperature=1.0):
"""Select an action based on [Redacted Person] exploration."""
probabilities = torch.softmax(q_values / temperature, dim=0).numpy()
return np.random.choice(len(q_values), p=probabilities)
# Construct PySC2 actions with default arguments
def construct_action(action_id, obs):
"""Construct a PySC2 action with default arguments."""
from [Redacted SWIFTCode] import actions
# Get the action function
action_fn = actions.FUNCTIONS[action_id]
# Check if the action is available
if action_id not in obs.observation["available_actions"]:
return None
# Construct the arguments for the action
args = []
for arg in action_fn.args:
if arg.name in ["screen", "minimap", "screen2"]:
# Provide default coordinates (e.g., center of the screen)
args.append([32, 32]) # Replace with appropriate screen size
[Redacted Person] arg.name in ["control_group_act", "control_group_id"]:
# Provide default control group values
args.append([0]) # Default to "Recall" for control_group_act
[Redacted Person] arg.name == "queued":
# Provide default queued value (0 = immediate)
args.append([0])
else:
# Default value for other arguments
args.append([0])
return actions.FunctionCall(action_id, args)
# Train the DQN agent in PySC2
def train_dqn(env, episodes=100, batch_size=32):
obs = env.reset()[0] # Access the first observation
state_size = obs.observation["feature_screen"].shape[0] # Number of channels
action_size = len(actions.FUNCTIONS)
# Initialize Q-network and target network
q_network = QNetwork(state_size, action_size)
target_network = QNetwork(state_size, action_size)
target_network.load_state_dict(q_network.state_dict())
target_network.eval()
optimizer = optim.[Redacted Person](q_network.parameters(), lr=0.001)
memory = deque(maxlen=2000)
gamma = 0.99
epsilon = 1.0
epsilon_min = 0.01
epsilon_decay = 0.995
target_update = 10
for episode in range(episodes):
obs = env.reset()[0] # Access the first observation
state = preprocess_observation(obs)
total_reward = 0
previous_obs = obs
while True:
# Epsilon-greedy action selection with [Redacted Person] exploration
if random.random() < epsilon:
action = random.choice(obs.observation["available_actions"])
else:
with torch.no_grad():
q_values = q_network(state)
# Mask unavailable actions
mask = torch.full((action_size,), float("-inf"))
mask[obs.observation["available_actions"]] = 0
q_values = q_values + mask
action = [Redacted Person]_exploration(q_values)
# Construct the PySC2 action with default arguments
pysc2_action = construct_action(action, obs)
# Skip if the action is invalid or unavailable
if pysc2_action is None:
continue
# Execute the action in the environment
obs = env.step([pysc2_action])[0] # Access the first observation in the TimeStep
# Log environment state and agent actions
player_screen = obs.observation["feature_screen"][1].nonzero() # Player position
beacon_screen = obs.observation["feature_screen"][3].nonzero() # Beacon position
if player_screen[0].size > 0 and beacon_screen[0].size > 0:
player_position = np.mean(player_screen, axis=1)
beacon_position = np.mean(beacon_screen, axis=1)
print(f"Player Position: {player_position}, Beacon Position: {beacon_position}")
print(f"Selected Action: {pysc2_action.function}, Args: {pysc2_action.arguments}")
# Preprocess next state and compute reward
next_state = preprocess_observation(obs)
reward = shaped_reward(obs, previous_obs)
previous_obs = obs
done = obs.last()
total_reward += reward
# Store experience in replay buffer
memory.append((state, action, torch.FloatTensor([reward]), next_state, done))
state = next_state
if done:
print(f"Episode {episode + 1}/{episodes}, Total Reward: {total_reward}")
break
# Train the network if the replay buffer is sufficiently large
if len(memory) >= batch_size:
batch = random.sample(memory, batch_size)
states, actions_batch, rewards, next_states, dones = zip(*batch)
states = torch.cat(states)
actions_batch = torch.LongTensor(actions_batch).unsqueeze(1)
rewards = torch.cat(rewards)
next_states = torch.cat(next_states)
dones = torch.FloatTensor(dones)
# Compute current Q-values
q_values = q_network(states).gather(1, actions_batch)
# Compute target Q-values
with torch.no_grad():
target_q = target_network(next_states).max(1)[0]
target_q = rewards + (gamma * target_q) * (1 - dones)
target_q = target_q.unsqueeze(1)
# Compute loss and update the network
loss = F.mse_loss(q_values, target_q)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Update the target network
if (episode + 1) % target_update == 0:
target_network.load_state_dict(q_network.state_dict())
# Decay epsilon
if epsilon > epsilon_min:
epsilon *= epsilon_decay
print("Training complete.")
return q_network
# Main function to train the DQN agent
def main():
from absl import app, flags
flags.FLAGS(["train_dqn.py"])
screen_size = 64
env = sc2_env.SC2Env(
map_name="MoveToBeacon",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=features.AgentInterfaceFormat(
feature_dimensions=features.Dimensions(screen=screen_size, minimap=screen_size),
use_feature_units=True,
),
step_mul=8,
game_steps_per_episode=0,
visualize=False,
)
try:
train_dqn(env, episodes=100, batch_size=32)
finally:
env.close()
if __name__ == "__main__":
main()
```is causing the following error:
pygame 2.6.1 (SDL 2.28.4, Python 3.8.13)
Hello from the pygame community. https://www.pygame.org/contribute.html
Version: B75689 (SC2.4.10)
Build: Aug 12 2019 17:16:57
Command Line: '"/workspace/StarCraftII/Versions/Base75689/SC2_x64" -listen [Redacted IPAddress] -port 37909 -dataDir /workspace/StarCraftII/ -tempDir /tmp/sc-d2jisugn/'
Starting up...
Startup Phase 1 complete
Startup Phase 2 complete
Creating stub renderer...
Listening on: [Redacted IPAddress]:37909
Startup Phase 3 complete. Ready for commands.
ConnectHandler: Request from [Redacted IPAddress]:52150 accepted
ReadyHandler: [Redacted IPAddress]:52150 ready
Requesting to join a single player game
Configuring interface options
Configure: raw interface enabled
Configure: feature layer interface enabled
Configure: score interface enabled
Configure: render interface disabled
Launching next game.
Next launch phase started: 2
Next launch phase started: 3
Next launch phase started: 4
Next launch phase started: 5
Next launch phase started: 6
Next launch phase started: 7
Next launch phase started: 8
Game has started.
Using default stable ids, none found at: /workspace/StarCraftII/stableid.json
Successfully loaded stable ids: GameData\stableid.json
Sending ResponseJoinGame
Game has started.
Selected Action: 1, Args: [[32, 32]]
Selected Action: 3, Args: [[0], [32, 32], [32, 32]]
Selected Action: 4, Args: [[0], [0]]
Selected Action: 7, Args: [[0]]
Selected Action: 1, Args: [[32, 32]]
Selected Action: 12, Args: [[0], [32, 32]]
Selected Action: 333, Args: [[0], [32, 32]]
Selected Action: 4, Args: [[0], [0]]
Selected Action: 451, Args: [[0], [32, 32]]
Selected Action: 331, Args: [[0], [32, 32]]
Selected Action: 4, Args: [[0], [0]]
Selected Action: 332, Args: [[0], [32, 32]]
Selected Action: 0, Args: []
Selected Action: 0, Args: []
Selected Action: 12, Args: [[0], [32, 32]]
Selected Action: 4, Args: [[0], [0]]
Selected Action: 331, Args: [[0], [32, 32]]
Selected Action: 13, Args: [[0], [32, 32]]
Selected Action: 13, Args: [[0], [32, 32]]
Selected Action: 451, Args: [[0], [32, 32]]
Selected Action: 274, Args: [[0]]
Selected Action: 451, Args: [[0], [32, 32]]
Selected Action: 1, Args: [[32, 32]]
Selected Action: 451, Args: [[0], [32, 32]]
Selected Action: 452, Args: [[0], [32, 32]]
Selected Action: 7, Args: [[0]]
Selected Action: 13, Args: [[0], [32, 32]]
Selected Action: 334, Args: [[0], [32, 32]]
Selected Action: 452, Args: [[0], [32, 32]]
Selected Action: 2, Args: [[0], [32, 32]]
Selected Action: 2, Args: [[0], [32, 32]]
Selected Action: 4, Args: [[0], [0]]
RequestQuit command received.
Closing Application...
DataHandler: unable to parse websocket frame.
CloseHandler: [Redacted IPAddress]:52150 disconnected
Traceback (most recent call last):
File "train_dqn_BBB.py", line 232, in <module>
main()
File "train_dqn_BBB.py", line 226, in main
train_dqn(env, episodes=100, batch_size=32)
File "train_dqn_BBB.py", line 181, in train_dqn
q_values = q_network(states).gather(1, actions_batch)
File "/opt/conda/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1532, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/conda/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1541, in _call_impl
return forward_call(*args, **kwargs)
File "train_dqn_BBB.py", line 26, in forward
x = F.relu(self.fc1(x))
File "/opt/conda/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1532, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/conda/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1541, in _call_impl
return forward_call(*args, **kwargs)
File "/opt/conda/lib/python3.8/site-packages/torch/nn/modules/linear.py", line 116, in forward
return F.linear(input, self.weight, self.bias)
RuntimeError: mat1 and mat2 shapes cannot be multiplied (32x115200 and 1152x128)
while the code
```python
import os
import random
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from collections import deque
import torch.nn.functional as F
from pysc2.env import sc2_env
from pysc2.lib import actions, features
# Define the QNetwork
class QNetwork(nn.Module):
def __init__(self, input_dim, output_dim):
super(QNetwork, self).__init__()
self.fc1 = nn.Linear(input_dim, 128)
self.fc2 = nn.Linear(128, 128)
self.fc3 = nn.Linear(128, output_dim)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
# Preprocess PySC2 observation
def preprocess_observation(obs):
"""Extract and preprocess relevant information from PySC2 observations."""
observation = obs.observation # Access the observation dictionary
screen = observation["feature_screen"]
player = observation["player"]
return np.concatenate([screen.flatten(), player], axis=0)
# Train the DQN agent in PySC2
def train_dqn(env, episodes=100, batch_size=32):
from pysc2.lib import actions # Import actions here
obs = env.reset()[0] # Access the first observation
state_size = len(preprocess_observation(obs))
action_size = len(actions.FUNCTIONS)
# Initialize Q-network and target network
q_network = QNetwork(state_size, action_size)
target_network = QNetwork(state_size, action_size)
target_network.load_state_dict(q_network.state_dict())
target_network.eval()
optimizer = optim.[Redacted Person](q_network.parameters(), lr=0.001)
memory = deque(maxlen=2000)
gamma = 0.99
epsilon = 1.0
epsilon_min = 0.01
epsilon_decay = 0.995
target_update = 10
for episode in range(episodes):
obs = env.reset()[0] # Access the first observation
state = preprocess_observation(obs)
state = torch.FloatTensor(state).unsqueeze(0)
total_reward = 0
step_count = 0
while True:
# Epsilon-greedy action selection
if random.random() < epsilon:
action = random.choice(obs.observation["available_actions"])
else:
with torch.no_grad():
q_values = q_network(state)
# Mask unavailable actions
mask = torch.full((action_size,), float("-inf"))
mask[obs.observation["available_actions"]] = 0
q_values = q_values + mask
action = torch.argmax(q_values).item()
# Construct the PySC2 action with default arguments
pysc2_action, action_name, action_args = construct_action(action, obs)
# Skip if the action is invalid or unavailable
if pysc2_action is None:
continue
# Execute the action in the environment
next_obs = env.step([pysc2_action])[0] # Access the first observation in the TimeStep
# Preprocess next state and compute reward
next_state = preprocess_observation(next_obs)
next_state = torch.FloatTensor(next_state).unsqueeze(0)
reward = next_obs.reward
done = next_obs.last()
total_reward += reward
# Log information
print(f"Episode: {episode + 1}, Step: {step_count}, Action: {action_name}, Args: {action_args}, Reward: {reward}, Done: {done}")
# Store experience in replay buffer
memory.append((state, action, torch.FloatTensor([reward]), next_state, done))
state = next_state
obs = next_obs
step_count += 1
if done:
print(f"Episode {episode + 1}/{episodes}, Total Reward: {total_reward}")
break
# Train the network if the replay buffer is sufficiently large
if len(memory) >= batch_size:
batch = random.sample(memory, batch_size)
states, actions_batch, rewards, next_states, dones = zip(*batch)
states = torch.cat(states)
actions_batch = torch.LongTensor(actions_batch).unsqueeze(1)
rewards = torch.cat(rewards)
next_states = torch.cat(next_states)
dones = torch.FloatTensor(dones)
# Compute current Q-values
q_values = q_network(states).gather(1, actions_batch)
# Compute target Q-values
with torch.no_grad():
target_q = target_network(next_states).max(1)[0]
target_q = rewards + (gamma * target_q) * (1 - dones)
target_q = target_q.unsqueeze(1)
# Compute loss and update the network
loss = F.mse_loss(q_values, target_q)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Update the target network
if (episode + 1) % target_update == 0:
target_network.load_state_dict(q_network.state_dict())
# Decay epsilon
if epsilon > epsilon_min:
epsilon *= epsilon_decay
print("Training complete.")
return q_network
def construct_action(action_id, obs):
"""Construct a PySC2 action with default arguments."""
from [Redacted SWIFTCode] import actions
# Get the action function
action_fn = actions.FUNCTIONS[action_id]
# Check if the action is available
if action_id not in obs.observation["available_actions"]:
return None, None, None
# Construct the arguments for the action
args = []
for arg in action_fn.args:
if arg.name in ["screen", "minimap", "screen2"]:
# Provide default coordinates (e.g., center of the screen)
args.append([32, 32]) # Replace with appropriate screen size
[Redacted Person] arg.name in ["control_group_act", "control_group_id"]:
# Provide default control group values
args.append([0]) # Default to "Recall" for control_group_act
[Redacted Person] arg.name == "queued":
# Provide default queued value (0 = immediate)
args.append([0])
else:
# Default value for other arguments
args.append([0])
return actions.FunctionCall(action_id, args), action_fn.name, args
# Main function to train the DQN agent
def main():
from absl import app, flags
flags.FLAGS(["train_dqn.py"])
screen_size = 64
env = sc2_env.SC2Env(
map_name="MoveToBeacon",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=features.AgentInterfaceFormat(
feature_dimensions=features.Dimensions(screen=screen_size, minimap=screen_size),
use_feature_units=True,
),
step_mul=8,
game_steps_per_episode=0,
visualize=False,
)
try:
train_dqn(env, episodes=100, batch_size=32)
finally:
env.close()
if __name__ == "__main__":
main()
import os
import random
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from collections import deque
import torch.nn.functional as F
from pysc2.env import sc2_env
from pysc2.lib import actions, features
# Define the QNetwork with CNN for spatial features
class QNetwork(nn.Module):
def __init__(self, input_channels, output_dim):
super(QNetwork, self).__init__()
self.conv1 = nn.Conv2d(input_channels, 16, kernel_size=3, stride=1)
self.conv2 = nn.Conv2d(16, 32, kernel_size=3, stride=1)
self.fc1 = nn.Linear(32 * 60 * 60, 128) # Adjusted for 64x64 screen
self.fc2 = nn.Linear(128, output_dim)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = x.view(x.size(0), -1) # Flatten
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
# Preprocess PySC2 observation for CNN
def preprocess_observation(obs):
"""Extract screen features and add batch dimension."""
screen = obs.observation["feature_screen"] # (C, H, W)
screen = np.transpose(screen, (1, 2, 0)) # Transpose to (H, W, C)
screen = torch.FloatTensor(screen).unsqueeze(0) # Add batch dimension (B, H, W, C)
screen = screen.permute(0, 3, 1, 2) # Permute to (B, C, H, W) for CNN input
return screen
# Compute shaped reward based on distance to the beacon
def shaped_reward(obs, previous_obs):
"""Compute shaped reward based on distance to beacon."""
if obs.last():
return obs.reward
beacon_y, beacon_x = (obs.observation["feature_screen"][3] == 1).nonzero()
player_y, player_x = (obs.observation["feature_screen"][1] == 1).nonzero()
if not beacon_y.any() or not [Redacted Person]_[Redacted Person].any():
return obs.reward # Return original reward if beacon or player not found
beacon_pos = [np.mean(beacon_x), np.mean(beacon_y)]
player_pos = [np.mean(player_x), np.mean(player_y)]
previous_beacon_y, previous_beacon_x = (previous_obs.observation["feature_screen"][3] == 1).nonzero()
previous_player_y, previous_player_x = (previous_obs.observation["feature_screen"][1] == 1).nonzero()
if not previous_beacon_y.any() or not previous_player_y.any():
# Initialize previous player/beacon positions
previous_player_pos = player_pos
previous_beacon_pos = beacon_pos
else:
previous_beacon_pos = [np.mean(previous_beacon_x), np.mean(previous_beacon_y)]
previous_player_pos = [np.mean(previous_player_x), np.mean(previous_player_y)]
dist = np.linalg.norm(np.array(player_pos) - np.array(beacon_pos))
previous_dist = np.linalg.norm(np.array(previous_player_pos) - np.array(previous_beacon_pos))
return obs.reward - (dist - previous_dist)
# [Redacted Person] exploration for action selection
def [Redacted Person]_exploration(q_values, temperature=1.0):
"""Select an action using [Redacted Person] exploration."""
probabilities = torch.softmax(q_values / temperature, dim=1).squeeze().numpy() #dim=1 since the input is (1, action_size)
action = np.random.choice(len(q_values[0]), p=probabilities) # Correctly sample from available actions
return action
def construct_action(action_id, obs):
# ... (same as before)
return actions.FunctionCall(action_id, args), actions.FUNCTIONS[action_id].name, args
def train_dqn(env, episodes=100, batch_size=32):
# ... (rest of the training loop remains mostly the same)
obs = env.reset()[0]
state = preprocess_observation(obs) # Use CNN preprocessing
state_size = state.shape[1] # Extract the number of input channels after preprocessing
# Initialize the Q network with correct input channel size.
q_network = QNetwork(state_size, action_size).to(device) # Send the network to the device
target_network = QNetwork(state_size, action_size).to(device)
# ... (rest is the same)
# Main function
def main():
# Set device for PyTorch (use GPU if available, otherwise CPU)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# ... (rest of main function, including env creation, remains the same)
try:
train_dqn(env, episodes=100, batch_size=32)
finally:
env.close()
if __name__ == "__main__":
main()
Key Changes and Explanations:
CNN Input Shape:
The preprocess_observation function now transposes the screen feature map to (H, W, C) format and then adds the batch dimension and permutes it to (B, C, H, W) to match what PyTorch CNNs expect.
The fully connected layer self.fc1 input dimension is adjusted according to the output shape of the convolutional layers. Since the output shape after 2 convolutional layers with kernel size 3 and stride 1 from an original size of 64x64 is 60x60, self.fc1 = nn.Linear(32 * 60 * 60, 128) is used. The correct state size (number of channels) is obtained after preprocessing.
Shaped Reward:
The shaped_reward function now correctly calculates the distance to the beacon. It returns the environment reward if either the player or the beacon are not found in the observation. The previous player/beacon positions are initialized appropriately if they are not found in the first observation. The shaped reward is then calculated by adding the difference between the current and the previous distance between the player and the beacon to the environment reward.
[Redacted Person] Exploration:
The boltzmann_exploration function is modified to correctly sample actions using the softmax probabilities. It samples an action from the range [0, action_size-1] with appropriate probabilities. The softmax is applied to the q_values along dim=1.
Device handling The device is obtained using torch.device("cuda" if torch.cuda.is_available() else "cpu"), and the network is send to the device using .to(device).
With these changes, the training process is more transparent (logs provide context), incorporates convolutional layers for spatial feature extraction, uses a shaped reward to give better feedback to the agent, and uses a boltzmann exploration policy so that actions are sampled based on their q values, and not fully random. Although there are still further enhancements you can add, this improved codebase should address many of the core issues you observed with the previous version, and you should see some reasonable learning behavior. Let me know if you have any other questions.