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
Debugging the Code and Identifying the Issue
Error Analysis
The error occurs in the following part of the code:
python
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)
The error is:
code
TypeError: tuple indices must be integers or slices, not str
This indicates that obs is a tuple and not a dictionary-like object, and thus it cannot be accessed using string keys like "feature_screen" or "player".
Understanding PySC2 Observations
In PySC2, the reset() and step() methods return a tuple of TimeStep objects, defined in the environment.py file. Observations from PySC2 do not have keys like "feature_screen" or "player". Instead, the observation is stored in the observation field of the TimeStep object.
Relevant structure in the TimeStep object:
timestep.observation contains the actual observation as a dictionary.
The observation dictionary includes keys like:
feature_screen
feature_minimap
player
The error occurs because the code accesses obs directly as a dictionary, but it must first extract obs.observation.
Fixing the Code
Update the preprocess_observation function to properly handle the TimeStep object:
python
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)
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
The error occurs because the actions module from pysc2.lib is not correctly imported or used, which results in the UnboundLocalError.
Let’s analyze and debug the issue step by step.
Cause of the Error
The error message:
code
UnboundLocalError: local variable 'actions' referenced before assignment
occurs because Python thinks actions has been defined as a local variable somewhere in the code. This happens because there is either:
A conflict between the imported actions module and a local variable named actions.
Improper scoping of the actions module.
In the provided code, actions is imported at the top:
python
from [Redacted SWIFTCode] import actions
But later in the train_dqn function, actions.FUNCTIONS is used. If there is any conflicting local variable named actions within the function scope, it can cause this error.
Debugging the Code
Step 1: Search for Conflicts
Look for any local variable named actions or any reassignment of actions in the code. For example:
python
# Incorrectly assigning `actions` as a local variable (hypothetical code)
actions = some_other_value
If actions is reassigned, it will hide the imported actions module, causing the error.
Step 2: Fix the Issue
Ensure that actions is only referenced as the imported module from pysc2.lib. If there’s unintentional reassignment, rename the conflicting variable to something else.
Corrected Code
Here’s the debugged and fixed version of the code:
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
Understanding the Errors
Let's analyze the errors from the provided logs to understand the root cause and improve the code.
Error 1: ValueError: Wrong number of arguments for function
Cause:
The issue arises when the code attempts to execute a PySC2 action using actions.FunctionCall. The function being executed (e.g., select_control_group) requires specific arguments but receives an empty list ([]).
PySC2 actions are defined in actions.FUNCTIONS, and each function has a required set of arguments that must be provided. For example:
select_point requires arguments like select_point_act and screen.
select_control_group requires arguments like control_group_act and control_group_id.
If the required arguments are not provided, PySC2 raises a ValueError, as seen in the logs.
Error Example:
code
ValueError: Wrong number of arguments for function: 4/select_control_group (4/control_group_act [5]; 5/control_group_id [10]), got: []
This means the function select_control_group (ID 4) expects arguments for control_group_act and control_group_id, but the code provides no arguments ([]).
Error 2: obs = env.step([pysc2_action])[0]
Cause:
The action (pysc2_action) is improperly constructed because it does not include the necessary arguments. This causes the environment to fail when trying to execute the action.
Root Cause
The root cause of both errors is that the actions.FUNCTIONS object contains a mix of actions, some of which require arguments (e.g., select_point, select_control_group) and some that do not (e.g., no_op). The current code does not handle these arguments properly.
Solution
Step 1: Handle Actions with Arguments
To fix this, you'll need to:
User
python
Assistant
Analysis: Why Is the Agent Failing to Learn?
The agent rarely achieves any reward, as evidenced by the logs (Total Reward: 0 for most episodes). Here are potential reasons for this behavior:
1. Sparse Rewards
Issue: The environment (MoveToBeacon) offers rewards only when the agent successfully moves to a beacon. If the agent's actions are mostly random (as in the early stages of training), the probability of reaching the beacon is very low.
Effect: With such sparse rewards, the agent struggles to learn meaningful policies since it has little feedback about what actions are beneficial.
2. Ineffective Exploration
Issue: The agent uses an epsilon-greedy exploration strategy, starting with epsilon = 1.0 (purely random actions) and gradually decaying. However, with sparse rewards, random exploration has a very low chance of discovering useful actions.
Effect: The agent may not find good actions even after many episodes, making it hard to bootstrap learning.
3. Lack of Meaningful Observations
Issue: The agent preprocesses observations into a flat vector of screen features and player stats. However, this preprocessing may discard spatial and contextual information crucial for decision-making (e.g., the position of the beacon or units on the map).
Effect: The agent lacks the information needed to learn a meaningful policy.
4. Lack of Action Transparency
Issue: The current implementation doesn't provide any logs about the agent's actions, environment state, or observations.
Effect: It’s hard to debug or understand why the agent is failing to learn.
Improvements
To address these issues, we need to make changes to both the training process and the logging mechanism.
1. Add Reward Shaping
What is Reward Shaping?
Reward shaping involves providing intermediate rewards to guide the agent toward completing its goal. For example:
Reward the agent for moving closer to the beacon.
Penalize the agent for moving away from the beacon.
Implementation
User
Write the complete train_dqn.py code with the upgrades above:
Assistant
Here’s the complete train_dqn.py code with all the suggested upgrades:
python
User
the code
python
Assistant
Below is the optimized, bug-free, and DQN-compatible training script for PySC2, combining the strengths of both code snippets provided. It addresses the following issues:
Handling the input size mismatch issue in the CNN-based Q-network by correctly calculating the flattened size of the CNN output and using it in the fully connected layers.
Adding reward shaping to guide the agent toward meaningful actions, improving the learning process.
Logging useful information such as actions, arguments, rewards, and the agent's position to make the training process more transparent.
Ensuring default arguments for actions are appropriately handled to avoid invalid actions.
Fixing reward sparsity by incorporating intermediate rewards to encourage progress toward the goal.
Final Optimized Code: train_dqn.py
python
Dataset releases
Not yet included in a published release.
Other Issues in the Code
Action Mapping
The actions.FUNCTIONS object contains all StarCraft II actions, but not all of them are valid for every state. The code already checks for obs["available_actions"] to ensure that invalid actions are not selected, but it is worth ensuring that the selected action is mapped correctly using actions.FunctionCall.
The corrected action execution block:
python
# Map action to PySC2 action
if action in obs.observation["available_actions"]:
pysc2_action = actions.FunctionCall(action, []) # Pass an empty argument list
obs = env.step([pysc2_action])[0]
else:
continue # Skip if the action is unavailable
screen_size Passed to train_dqn
The screen_size parameter in the train_dqn function is not used. It is redundant since the screen size is already defined when creating the SC2Env. This can be removed for clarity.
Revised Code
Here is the fully revised and debugged training script:
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):
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
# 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)
finally:
env.close()
if __name__ == "__main__":
main()
Key Changes
preprocess_observation:
Accessed obs.observation instead of obs.
Action Mapping:
Ensured the correct use of actions.FunctionCall.
Removed screen_size from train_dqn Parameters:
The screen size is already specified in the environment configuration.
Expected Output
The script should now train the DQN agent without the TypeError and interact correctly with the SC2 environment. The PySC2 environment will log the game execution progress while the script prints the reward for each episode.
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 # Make sure actions is imported here
# 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):
obs = env.reset()[0] # Access the first observation
state_size = len(preprocess_observation(obs))
action_size = len(actions.FUNCTIONS) # Correctly use 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_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_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()
Key Fixes
Ensure actions.FUNCTIONS is properly referenced:
The actions module is imported from pysc2.lib and used correctly without any local variable reassignment.
Renamed variables to avoid conflicts:
There were no conflicting variables named actions, but this step ensures future-proofing.
Validation of actions.FunctionCall usage:
Confirmed that the actions.FUNCTIONS object is correctly used for selecting and executing actions.
Expected Behavior
The script should now:
Properly initialize the QNetwork and target_network.
Run the SC2 environment without crashing.
Train the DQN agent and print the total reward for each episode.
Let me know if further debugging is needed!
# 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.
Check the action selected by the agent.
Verify the arguments required by the action using actions.FUNCTIONS[action].args.
Provide appropriate arguments for the selected action.
Step 2: Generate Default Arguments
For simplicity, you can generate default arguments for each action. For example:
For select_point, provide a default screen position.
For select_control_group, provide default values for control_group_act and control_group_id.
Improved Code
Here's the improved version of your train_dqn function, which ensures that actions are properly constructed with the required arguments:
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()
# 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)
Key Changes
construct_action Function:
Dynamically generates the required arguments for a PySC2 action based on the actions.FUNCTIONS[action_id].args.
Provides default values for common argument types (screen, control_group_act, etc.).
Action Validation:
Ensures the action is valid by checking action_id in obs.observation["available_actions"].
Default Argument Handling:
Uses default values to avoid ValueError when required arguments are missing.
Expected Output
After applying these fixes, the script should:
Properly construct and execute PySC2 actions without raising ValueError.
Train the DQN agent and print the total reward for each episode.
If any issues persist, let me know!
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.
Modify the reward to include a distance-based component. The closer the agent gets to the beacon, the higher the reward.
python
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 distance (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
How to Use:
Replace the reward calculation in the training loop:
python
reward = shaped_reward(obs, previous_obs)
2. Improve Exploration
Use [Redacted Person] Exploration
Instead of epsilon-greedy exploration, use [Redacted Person] exploration, where the agent selects actions probabilistically based on their Q-values:
python
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)
Decay epsilon more slowly to allow longer exploration:
python
epsilon_decay = 0.999 # Slower decay
3. Add Detailed Logging
Log Environment State and Agent Actions
Add print statements to track:
The agent's selected action.
The arguments passed to the action.
The agent’s position and the beacon’s position in the environment.
Update the training loop:
python
# Log details about the environment and agent
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}")
4. Improve State Representation
Use CNN for Spatial Features
Instead of flattening the screen features into a vector, use a convolutional neural network (CNN) to process the spatial information:
Update the QNetwork:
python
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 as needed
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 observations to include spatial features:
python
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
Example Updated Logs
After adding the improvements, your logs might look like this:
code
Episode 1/100, Total Reward: 0
Player Position: [31.5, 31.5], Beacon Position: [[Redacted EUGPSCoordinates]]
Selected Action: move_screen, Args: [[32, 32]]
Episode 2/100, Total Reward: -1.5
Player Position: [29.0, 27.0], Beacon Position: [[Redacted EUGPSCoordinates]]
Selected Action: move_screen, Args: [[30, 30]]
...
Episode 93/100, Total Reward: 1.0
Player Position: [[Redacted EUGPSCoordinates]], Beacon Position: [[Redacted EUGPSCoordinates]]
Selected Action: move_screen, Args: [[43, 20]]
Expected Results
With these changes:
Reward shaping makes it easier for the agent to learn by providing intermediate feedback.
Improved exploration techniques allow the agent to discover better actions earlier.
Logging provides insights into the agent's behavior, helping debug issues.
A CNN processes spatial features more effectively, improving performance.
Let me know if you need further assistance!
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()
Key Upgrades
Reward Shaping: Added a shaped_reward function to provide intermediate guidance to the agent.
[Redacted Person] Exploration: Introduced a probabilistic exploration method for better exploration of actions.
Logging: Added detailed logs to track the agent's position, beacon position, selected actions, and arguments.
CNN-Based QNetwork: Modified
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()