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
To adapt the provided DQN training code to work with the PySC2 environment, we need to make several modifications to align with PySC2's interface and the nature of StarCraft II game states. Here's how we can do it:
Key Changes Needed:
Environment Integration:
Replace the custom SC2Env with PySC2's sc2_env.SC2Env.
Use PySC2's observation and action spaces.
State Representation:
Extract relevant features from PySC2's observation (e.g., feature layers, unit counts, etc.).
Convert these features into a state vector that the DQN can process.
Action Space:
Map DQN's output to PySC2's action space using FUNCTIONS from pysc2.lib.actions.
Reward Calculation:
Use PySC2's built-in reward signals or define custom rewards based on game progress (e.g., mineral collection, units killed, etc.).
Training Loop:
Adjust the training loop to work with PySC2's step-based environment.
Modified Code:
python
User
How can I train this network in a linux server but visualize the playback(demo) of the trained agents in a windows PC? If possible, list the todo steps in detail:
Assistant
To train the DQN network on a Linux server and visualize the playback (demo) of the trained agents on a Windows PC, you need to follow a structured approach. Below are the detailed steps to achieve this:
Step 1: Train the DQN Network on the Linux Server
Set Up the Linux Server Environment:
Install Python and required dependencies (e.g., PyTorch, PySC2) on the Linux server.
Ensure the Linux server has a GPU if you want to accelerate training (optional but recommended).
Save the Trained Model:
Modify the training script to save the trained model (q_network) to a file after training.
python
torch.save(q_network.state_dict(), "sc2_dqn.pth")
Transfer the saved model file (sc2_dqn.pth) from the Linux server to your Windows PC using a file transfer method like scp or a cloud storage service (e.g., Google Drive, Dropbox).
This API exposes functionality for developing software for:
Scripted bots.
Machine-learning based bots.
Replay analysis.
Tool assisted human play.
The API is available in the retail Windows and Mac clients. There are also Linux clients available at the download links below.
Contents
Official
Protocol
Protobuf protocol definition of the API.
Definition
Documentation
Reference C++ implementation
Library designed for building a scripted bots using the API.
Repository
StarCraft II Linux Packages
Self contained headless linux StarCraft II builds.
Documentation
Download
Maps
Maps from the 1v1 ladder and other custom maps.
Download
Replays
Replay packs of 1v1 ladder games.
Download
Community
PySC2
DeepMind's python environment wrapper.
Repository
CommandCenter
A robust architecture for quickly developing Starcraft AI bots.
Repository
Bot Ladders
SC2AI - Unofficial community organized ladder.
AI Arena - Unofficial community organized ladder.
Community Wiki
Unofficial wiki of documentation and tutorials.
Website
Discord Server
Unofficial server for discussing AI questions and projects.
Invite Link
Facebook Group
Unofficial community page.
Website
Downloads
To access the linux packages, map packs and replay packs, you must agree to the AI and Machine Learning License
The files are password protected with the password 'iagreetotheeula'.
By typing in the password ‘iagreetotheeula’ you agree to be bound by the terms of the AI and Machine Learning License
Linux Packages
3.17
3.16.1
4.0.2
4.1.2
4.6
4.6.1
4.6.2
4.7
4.7.1
4.8.2
4.8.3
4.8.4
4.8.6
4.9.0
4.9.1
4.9.2
4.9.3
4.10
Map Packs
Ladder 2017 Season 1
Ladder 2017 Season 2
Ladder 2017 Season 3 Updated
Ladder 2017 Season 4
Ladder 2018 Season 1
Ladder 2018 Season 2
Ladder 2018 Season 3
Ladder 2018 Season 4
Ladder 2019 Season 1
Ladder 2019 Season 2
Ladder 2019 Season 3
Melee
This is the previous version of the Ladder 2017 Season 3 Map Pack
Ladder 2017 Season 3 Original
Replay Packs
3.16.1 - Pack 1
3.16.1 - Pack 2
Installing Map and Replay Packs
All additional game data should be extracted within the installation directory.
The default installation directories are:
Windows: C:\Program Files (x86)\StarCraft II
Mac: /Applications/StarCraft II/
On Linux, the installation directory is the folder you extracted the linux package into.
The folder structure is the same accross all platforms. However you may need to create some folders if they are missing.
Standard folder layout:
StarCraft II/
Battle.net/
Maps/
Replays/
SC2Data/
Versions/
Map Packs
Extract the zip file directly into the "Maps" folder.
In the API, a map can be specified as either an absolute path or its relative path inside this "Maps" folder.
Replay Packs
Replace the "Battle.net" and "Replays" folders with the ones in the zip file.
In the API, a replay must be specified as an absolute path.
Stable IDs
These define the action mappings from ability ids in the protobuf api to the internals of the game. They also define some general ids that combine multiple abilities that have a similar semantic meaning (eg various forms of burrow, cancel, lift/land, etc). The stableid.json is updated occasionally with the game, but can also be updated manually by downloading the stableid.json from here and placing it in the root of your StarCraft II directory. ###USER QUESTION: which one should I download?
Assistant
To set up the StarCraft II environment for training and running AI agents using PySC2, you need to download specific components from the repository. Here's a breakdown of what you should download and why:
1. StarCraft II Linux Package
Since you're training on a Linux server, you need the StarCraft II Linux Package. This is the headless version of StarCraft II that runs without a graphical interface, optimized for server environments.
Which Version to Download:
Latest Stable Version: Download the most recent version available (e.g., 4.10 as of the current list).
This ensures compatibility with the latest features and bug fixes.
The stableid.json file defines action mappings for the game. It is occasionally updated, but you usually don't need to download it unless you're working with custom actions or the latest game patches.
When to Download:
Only download if you encounter issues with action mappings or if you're working with the latest game version.
User
Has the pysc2 repo recommended any RL pipeline? What RL technique would fit the starcraft game?
Assistant
The PySC2 repository itself does not explicitly recommend a specific reinforcement learning (RL) pipeline or technique. However, it provides a flexible environment for experimenting with various RL approaches. The choice of RL technique depends on the complexity of StarCraft II as a game and the specific challenges it presents.
Why StarCraft II is Challenging for RL
StarCraft II is a highly complex real-time strategy (RTS) game that poses several challenges for RL:
Large State and Action Spaces:
The game state is vast, with multiple units, buildings, resources, and map features.
The action space is combinatorial, with many possible actions and their parameters (e.g., selecting units, targeting locations, casting abilities).
Partial Observability:
Players only see a portion of the map (fog of war), requiring agents to make decisions under uncertainty.
Long Time Horizons:
Games can last hundreds or thousands of steps, requiring agents to plan long-term strategies.
Multi-Agent Dynamics:
The game involves controlling multiple units simultaneously, which can be framed as a multi-agent problem.
Sparse and Delayed Rewards:
Rewards (e.g., winning the game) are sparse and delayed, making it difficult for RL agents to learn effective policies.
Recommended RL Techniques for StarCraft II
Based on the challenges and the success of recent research, the following RL techniques are well-suited for StarCraft II:
1. Deep Q-Networks (DQN)
Why It Fits:
DQN is a foundational RL algorithm that works well for discrete action spaces.
It can handle large state spaces by using neural networks to approximate the Q-function.
Limitations:
DQN struggles with continuous or highly combinatorial action spaces.
It may not scale well to the full complexity of StarCraft II.
2. Proximal Policy Optimization (PPO)
Why It Fits:
PPO is a policy-gradient method that is stable and efficient for training in complex environments.
User
Code writing command: write a train_dqn.py with save_replay, to train a NN to play the mini game "MoveToBeacon"!
Assistant
Below is the complete code for train_dqn.py, which trains a Deep Q-Network (DQN) to play the "MoveToBeacon" mini-game in StarCraft II using PySC2. The script saves replays periodically and trains the agent using the DQN algorithm.
Code: train_dqn.py
python
User
After running the train_dqn.py above, got the following error: Traceback (most recent call last):
File "train_dqn_A.py", line 8, in
from pysc2.env import sc2_env
File "/opt/conda/lib/python3.8/site-packages/pysc2/env/sc2_env.py", line 24, in
from pysc2 import run_configs
File "/opt/conda/lib/python3.8/site-packages/pysc2/run_configs/init.py", line 18, in
from pysc2.lib import sc_process
File "/opt/conda/lib/python3.8/site-packages/pysc2/lib/sc_process.py", line 27, in
from pysc2.lib import remote_controller
File "/opt/conda/lib/python3.8/site-packages/pysc2/lib/remote_controller.py", line 24, in
from pysc2.lib import protocol
File "/opt/conda/lib/python3.8/site-packages/pysc2/lib/protocol.py", line 29, in
from s2clientprotocol import sc2api_pb2 as sc_pb
File "/opt/conda/lib/python3.8/site-packages/s2clientprotocol/sc2api_pb2.py", line 17, in
from s2clientprotocol import common_pb2 as s2clientprotocol_dot_common__pb2
File "/opt/conda/lib/python3.8/site-packages/s2clientprotocol/common_pb2.py", line 32, in
_descriptor.EnumValueDescriptor(
File "/opt/conda/lib/python3.8/site-packages/google/protobuf/descriptor.py", line 920, in new
_message.Message._CheckCalledFromGeneratedFile()
TypeError: Descriptors cannot be created directly.
If this call came from a _pb2.py file, your generated code is out of date and must be regenerated with protoc >= 3.19.0.
If you cannot immediately regenerate your protos, some other possible workarounds are:
Downgrade the protobuf package to 3.20.x or lower.
Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python (but this will use pure-Python parsing and will be much slower).
The error you're encountering is related to the Protobuf library version incompatibility. Specifically, the error message indicates that the generated code for the Protobuf messages (_pb2.py files) is out of date and requires regeneration with protoc >= 3.19.0. However, the PySC2 library and its dependencies were built with an older version of Protobuf, and the current version of Protobuf installed in your environment is likely >= 3.20.0, which enforces stricter rules for descriptor creation.
Why This Happens
Protobuf Version Mismatch:
PySC2 and its dependencies (e.g., s2clientprotocol) were designed to work with older versions of the Protobuf library (<= 3.20.x).
Starting from Protobuf 3.21.0, the library enforces stricter rules for descriptor creation, causing compatibility issues with older generated code.
Generated Code Out of Date:
The .proto files in PySC2 were compiled with an older version of protoc, and the generated _pb2.py files are incompatible with newer versions of the Protobuf library.
Detailed Solutions
Here are the step-by-step solutions to resolve this issue:
Solution 1: Downgrade Protobuf to 3.20.x or Lower
This is the simplest and most effective solution. Downgrade the Protobuf library to a version that is compatible with PySC2.
Uninstall the current Protobuf version:
bash
pip uninstall protobuf
Install Protobuf 3.20.x or lower:
bash
pip install protobuf==3.20.3
Verify the installation:
bash
pip show [Redacted Person]
Re-run your script:
bash
python train_dqn.py
Solution 2: Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python
If you cannot downgrade Protobuf, you can use an environment variable to force the Protobuf library to use the pure-Python implementation. However, this will be slower.
User
You share the same user prompt with another LLM model. So please firstly distinguish which one of the A/B error is caused by your train_dqn_*.py code and provide the solution to debug: python train_dqn_B.py ERROR:
pygame 2.6.1 (SDL 2.28.4, Python 3.8.13)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "train_dqn_B.py", line 171, in
main()
File "train_dqn_B.py", line 152, in main
env = sc2_env.SC2Env(
File "/opt/conda/lib/python3.8/site-packages/pysc2/env/sc2_env.py", line 235, in init
self._run_config = run_configs.get(version=version)
File "/opt/conda/lib/python3.8/site-packages/pysc2/run_configs/init.py", line 35, in get
if FLAGS.sc2_run_config is None: # Find the highest priority as default.
File "/opt/conda/lib/python3.8/site-packages/absl/flags/_flagvalues.py", line 499, in getattr
raise _exceptions.UnparsedFlagAccessError(error_message)
absl.flags._exceptions.UnparsedFlagAccessError: Trying to access flag --sc2_run_config before flags were parsed.
root@localhost:/workspace/StarCraftII# python train_dqn_A.py
pygame 2.6.1 (SDL 2.28.4, Python 3.8.13)
Hello from the pygame community. https://www.pygame.org/contribute.html
I0120 09:34:11.941221 [Redacted PhoneNumber] sc_process.py:130] Launching SC2: /workspace/StarCraftII/Versions/Base75689/SC2_x64 -listen [Redacted IPAddress] -port 39700 -dataDir /workspace/StarCraftII/ -tempDir /tmp/sc-kiw3q3s3/
I0120 09:34:11.958765 [Redacted PhoneNumber] remote_controller.py:162] Connecting to: ws://[Redacted IPAddress]:39700/sc2api, attempt: 0, running: True
Version: B75689 (SC2.4.10)
Build: Aug 12 2019 17:16:57
Command Line: '"/workspace/StarCraftII/Versions/Base75689/SC2_x64" -listen [Redacted IPAddress] -port 39700 -dataDir /workspace/StarCraftII/ -tempDir /tmp/sc-kiw3q3s3/'
Starting up...
Startup Phase 1 complete
I0120 09:34:12.962749 [Redacted PhoneNumber] remote_controller.py:162] Connecting to: ws://[Redacted IPAddress]:39700/sc2api, attempt: 1, running: True
Startup Phase 2 complete
Creating stub renderer...
Listening on: [Redacted IPAddress]:39700
Startup Phase 3 complete. Ready for commands.
I0120 09:34:13.964565 [Redacted PhoneNumber] remote_controller.py:162] Connecting to: ws://[Redacted IPAddress]:39700/sc2api, attempt: 2, running: True
ConnectHandler: Request from [Redacted IPAddress]:36888 accepted
ReadyHandler: [Redacted IPAddress]:36888 ready
Requesting to join a single player game
Configuring interface options
Configure: raw interface disabled
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
I0120 09:34:18.551993 [Redacted PhoneNumber] sc2_env.py:288] Environment is ready
[Redacted InternationalBankingAccountNumber].552373 [Redacted PhoneNumber] sc2_env.py:493] Starting episode 1: [terran] on MoveToBeacon
Traceback (most recent call last):
File "train_dqn_A.py", line 148, in
app.run(main)
File "/opt/conda/lib/python3.8/site-packages/absl/app.py", line 312, in run
_run_main(main, args)
File "/opt/conda/lib/python3.8/site-packages/absl/app.py", line 258, in _run_main
sys.exit(main(argv))
File "train_dqn_A.py", line 142, in main
train_dqn(env)
File "train_dqn_A.py", line 41, in train_dqn
action_size = len(actions.FUNCTIONS)
UnboundLocalError: local variable 'actions' referenced before assignment
[Redacted InternationalBankingAccountNumber].744410 [Redacted PhoneNumber] sc2_env.py:740] Environment Close
RequestQuit command received.
Closing Application...
DataHandler: unable to parse websocket frame.
CloseHandler: [Redacted IPAddress]:36888 disconnected
I0120 09:34:18.945785 [Redacted PhoneNumber] sc_process.py:227] Shutdown gracefully.
[Redacted InternationalBankingAccountNumber].[Redacted InternationalBankingAccountNumber] sc_process.py:205] Shutdown with return code: -15
Assistant
Let’s analyze the two errors and identify which one is caused by the train_dqn_*.py code, followed by debugging steps for each.
Error A: UnboundLocalError: local variable 'actions' referenced before assignment
This error occurs in train_dqn_A.py and is caused by a programming mistake in the code. Specifically, the variable actions is referenced before it is assigned.
Root Cause
In the train_dqn function, the line:
python
action_size = len(actions.FUNCTIONS)
is trying to access the actions module, but the actions module is not imported or defined in the scope of the train_dqn function.
Solution
Import the actions module from pysc2.lib at the beginning of the script:
python
from [Redacted SWIFTCode] import actions
Ensure the actions module is accessible in the train_dqn function.
Update the train_dqn function to use the imported actions module:
python
action_size = len(actions.FUNCTIONS)
Error B: UnparsedFlagAccessError: Trying to access flag --sc2_run_config before flags were parsed
This error occurs in train_dqn_B.py and is related to the way PySC2 initializes its environment. The error indicates that the absl.flags system is trying to access a flag (--sc2_run_config) before the flags are parsed.
Root Cause
The sc2_env.SC2Env initialization is being called before the absl.flags system has parsed the command-line arguments. This is a common issue when using PySC2's sc2_env with the absl library.
Solution
Wrap the main logic of your script in an absl.app.run function to ensure proper flag parsing:
python
User
After modifications of both train_dqn_A/B.py, got the errors: root@localhost:/workspace/StarCraftII# python train_dqn_A.py
pygame 2.6.1 (SDL 2.28.4, Python 3.8.13)
Hello from the pygame community. https://www.pygame.org/contribute.html
I0120 09:58:01.546324 [Redacted PhoneNumber] sc_process.py:130] Launching SC2: /workspace/StarCraftII/Versions/Base75689/SC2_x64 -listen [Redacted IPAddress] -port 38140 -dataDir /workspace/StarCraftII/ -tempDir /tmp/sc-n265ios6/
I0120 09:58:01.561703 [Redacted PhoneNumber] remote_controller.py:162] Connecting to: ws://[Redacted IPAddress]:38140/sc2api, attempt: 0, running: True
Version: B75689 (SC2.4.10)
Build: Aug 12 2019 17:16:57
Command Line: '"/workspace/StarCraftII/Versions/Base75689/SC2_x64" -listen [Redacted IPAddress] -port 38140 -dataDir /workspace/StarCraftII/ -tempDir /tmp/sc-n265ios6/'
Starting up...
Startup Phase 1 complete
I0120 09:58:02.564812 [Redacted PhoneNumber] remote_controller.py:162] Connecting to: ws://[Redacted IPAddress]:38140/sc2api, attempt: 1, running: True
Startup Phase 2 complete
Creating stub renderer...
Listening on: [Redacted IPAddress]:38140
Startup Phase 3 complete. Ready for commands.
I0120 09:58:03.566400 [Redacted PhoneNumber] remote_controller.py:162] Connecting to: ws://[Redacted IPAddress]:38140/sc2api, attempt: 2, running: True
ConnectHandler: Request from [Redacted IPAddress]:43270 accepted
ReadyHandler: [Redacted IPAddress]:43270 ready
Requesting to join a single player game
Configuring interface options
Configure: raw interface disabled
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
I0120 09:58:08.243153 [Redacted PhoneNumber] sc2_env.py:288] Environment is ready
[Redacted InternationalBankingAccountNumber].[Redacted InternationalBankingAccountNumber] sc2_env.py:493] Starting episode 1: [terran] on MoveToBeacon
Game has started.
I0120 09:58:14.395848 [Redacted PhoneNumber] sc2_env.py:493] Starting episode 2: [terran] on MoveToBeacon
Traceback (most recent call last):
File "train_dqn_A.py", line 149, in
app.run(main)
File "/opt/conda/lib/python3.8/site-packages/absl/app.py", line 312, in run
_run_main(main, args)
File "/opt/conda/lib/python3.8/site-packages/absl/app.py", line 258, in _run_main
sys.exit(main(argv))
File "train_dqn_A.py", line 143, in main
train_dqn(env)
File "train_dqn_A.py", line 69, in train_dqn
if action_func.function_type in env.available_actions():
AttributeError: 'SC2Env' object has no attribute 'available_actions'
I0120 09:58:14.805954 [Redacted PhoneNumber] sc2_env.py:740] Environment Close
RequestQuit command received.
Closing Application...
DataHandler: unable to parse websocket frame.
CloseHandler: [Redacted IPAddress]:43270 disconnected
I0120 09:58:15.007532 [Redacted PhoneNumber] sc_process.py:227] Shutdown gracefully.
I0120 09:58:15.007870 [Redacted PhoneNumber] sc_process.py:205] Shutdown with return code: -15
Assistant
The error you're encountering now is due to the incorrect usage of the available_actions() method. The SC2Env object does not have a method called available_actions(). Instead, you should check if the action is available in the current observation.
Root Cause
The error occurs in this line:
python
if action_func.function_type in env.available_actions():
The SC2Env object does not have an available_actions() method. Instead, the available actions are part of the observation returned by the environment.
Solution
Correctly Check Available Actions:
The available actions are stored in the observation object, specifically in obs.observation.available_actions.
You need to check if the action is available in the current observation.
Modify the Code:
Replace the incorrect line with the proper check for available actions.
Updated Code
Here’s the corrected version of the train_dqn function:
python
User
python train_dqn_B.py
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 34896 -dataDir /workspace/StarCraftII/ -tempDir /tmp/sc-8p3lalbg/'
Starting up...
Startup Phase 1 complete
Startup Phase 2 complete
Creating stub renderer...
Listening on: [Redacted IPAddress]:34896
Startup Phase 3 complete. Ready for commands.
ConnectHandler: Request from [Redacted IPAddress]:41362 accepted
ReadyHandler: [Redacted IPAddress]:41362 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]:41362 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 38, in train_dqn
state_size = len(preprocess_observation(env.reset()))
File "train_dqn_B.py", line 31, in preprocess_observation
screen = obs.observation["feature_screen"]
AttributeError: 'tuple' object has no attribute 'observation'
///python train_dqn_A.py
pygame 2.6.1 (SDL 2.28.4, Python 3.8.13)
Hello from the pygame community. https://www.pygame.org/contribute.html
[Redacted InternationalBankingAccountNumber].442206 [Redacted PhoneNumber] sc_process.py:130] Launching SC2: /workspace/StarCraftII/Versions/Base75689/SC2_x64 -listen [Redacted IPAddress] -port 46438 -dataDir /workspace/StarCraftII/ -tempDir /tmp/sc-1rl8cy0b/
I0120 10:05:05.458696 [Redacted PhoneNumber] remote_controller.py:162] Connecting to: ws://[Redacted IPAddress]:46438/sc2api, attempt: 0, running: True
Version: B75689 (SC2.4.10)
Build: Aug 12 2019 17:16:57
Command Line: '"/workspace/StarCraftII/Versions/Base75689/SC2_x64" -listen [Redacted IPAddress] -port 46438 -dataDir /workspace/StarCraftII/ -tempDir /tmp/sc-1rl8cy0b/'
Starting up...
Startup Phase 1 complete
I0120 10:05:06.462065 [Redacted PhoneNumber] remote_controller.py:162] Connecting to: ws://[Redacted IPAddress]:46438/sc2api, attempt: 1, running: True
Startup Phase 2 complete
Creating stub renderer...
Listening on: [Redacted IPAddress]:46438
Startup Phase 3 complete. Ready for commands.
I0120 10:05:07.463754 [Redacted PhoneNumber] remote_controller.py:162] Connecting to: ws://[Redacted IPAddress]:46438/sc2api, attempt: 2, running: True
ConnectHandler: Request from [Redacted IPAddress]:46290 accepted
ReadyHandler: [Redacted IPAddress]:46290 ready
Requesting to join a single player game
Configuring interface options
Configure: raw interface disabled
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
I0120 10:05:12.[Redacted InternationalBankingAccountNumber] sc2_env.py:288] Environment is ready
I0120 10:05:12.004638 [Redacted PhoneNumber] sc2_env.py:493] Starting episode 1: [terran] on MoveToBeacon
Game has started.
I0120 10:05:13.536448 [Redacted PhoneNumber] sc2_env.py:493] Starting episode 2: [terran] on MoveToBeacon
Traceback (most recent call last):
File "train_dqn_A.py", line 149, in
app.run(main)
File "/opt/conda/lib/python3.8/site-packages/absl/app.py", line 312, in run
_run_main(main, args)
File "/opt/conda/lib/python3.8/site-packages/absl/app.py", line 258, in _run_main
sys.exit(main(argv))
File "train_dqn_A.py", line 143, in main
train_dqn(env)
File "train_dqn_A.py", line 70, in train_dqn
obs = env.step([action_func()])
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: []
I0120 10:05:13.811810 [Redacted PhoneNumber] sc2_env.py:740] Environment Close
RequestQuit command received.
DataHandler: unable to parse websocket frame.
Closing Application...
CloseHandler: [Redacted IPAddress]:46290 disconnected
I0120 10:05:14.013121 [Redacted PhoneNumber] sc_process.py:227] Shutdown gracefully.
I0120 10:05:14.013335 [Redacted PhoneNumber] sc_process.py:205] Shutdown with return code: -15
Assistant
Let’s address the errors in both scripts (train_dqn_A.py and train_dqn_B.py) step by step.
Error in train_dqn_B.py: AttributeError: 'tuple' object has no attribute 'observation'
This error occurs because the env.reset() method returns a tuple, but the code assumes it returns a single observation object.
Root Cause
In PySC2, env.reset() returns a tuple of observations (one for each agent). You need to extract the observation for the first agent.
Fix
Update the preprocess_observation function to handle the tuple returned by env.reset():
python
def preprocess_observation(obs):
# Extract the observation for the first agent
obs = obs[0]
screen = obs.observation["feature_screen"]
state = []
# Flatten relevant feature layers
for feature in [screen.player_relative, screen.unit_type]:
state.extend(feature.flatten())
# Normalize to [0, 1]
state = np.array(state, dtype=np.float32) / 255.0
return state
Update the train_dqn Function
Ensure env.reset() is handled correctly:
python
obs = env.reset()
state = preprocess_observation(obs)
state = torch.FloatTensor(state).unsqueeze(0)
Error in train_dqn_A.py: ValueError: Wrong number of arguments for function
This error occurs because the action function (select_point) requires arguments, but none are provided.
Root Cause
The select_point action requires two arguments:
select_point_act: The type of selection (e.g., select, toggle).
screen: The screen coordinates for the selection.
However, the code attempts to execute the action without providing these arguments.
Download stableid.json and place it in the root of your StarCraft II directory:
bash
cp stableid.json ~/StarCraftII/
Next Steps
After setting up the environment, you can proceed with training your DQN agent using PySC2.
If you plan to visualize the agent's performance on a Windows PC, install StarCraft II on Windows and transfer the trained model and replay files as described earlier.
Let me know if you need further assistance!
It can handle both discrete and continuous action spaces.
It works well with large state spaces and long time horizons.
Examples:
DeepMind's AlphaStar used a variant of PPO for training their StarCraft II agent.
3. Actor-Critic Methods (e.g., A3C, A2C)
Why It Fits:
Actor-critic methods combine the benefits of policy-based and value-based approaches.
They are sample-efficient and can handle large state and action spaces.
Examples:
Used in early research on StarCraft II AI.
4. Imitation Learning + RL
Why It Fits:
Imitation learning can bootstrap an agent by learning from expert demonstrations (e.g., human replays).
RL can then fine-tune the agent's policy for better performance.
Examples:
AlphaStar used supervised learning on human replays before applying RL.
5. Hierarchical RL
Why It Fits:
Hierarchical RL decomposes the problem into high-level strategies (e.g., build order) and low-level actions (e.g., unit control).
This approach is well-suited for the multi-scale nature of StarCraft II.
Examples:
Used in some research to manage macro and micro strategies separately.
6. Multi-Agent RL (MARL)
Why It Fits:
StarCraft II can be framed as a multi-agent problem, where each unit is an agent.
MARL techniques can coordinate multiple agents to achieve a common goal.
Challenges:
Scalability and coordination are major challenges in MARL.
7. Transformers and Attention Mechanisms
Why It Fits:
Transformers can model long-term dependencies and relationships between units and map features.
Attention mechanisms can help focus on relevant parts of the state space.
Examples:
Recent research has explored using transformers for StarCraft II AI.
Pipeline Recommendations
Based on the above techniques, here’s a recommended RL pipeline for StarCraft II:
Preprocessing:
Use PySC2's feature layers (e.g., screen, minimap, player stats) to represent the game state.
Normalize and preprocess the state for input to the RL model.
Imitation Learning (Optional):
Train the agent on human replays using supervised learning to bootstrap policies.
Reinforcement Learning:
Use PPO or an actor-critic method to train the agent in the full game environment.
Consider hierarchical RL for macro and micro strategies.
Curriculum Learning:
Start with simpler scenarios (e.g., limited units, small maps) and gradually increase complexity.
Evaluation:
Test the agent against built-in AI or human players.
Analyze replays to identify weaknesses and improve the agent.
Key Resources and Tools
PySC2: Provides the environment and tools for interacting with StarCraft II.
Stable-Baselines3: A library implementing PPO and other RL algorithms.
Ray RLlib: A scalable RL library with support for multi-agent and hierarchical RL.
AlphaStar Paper: DeepMind's work on StarCraft II AI provides insights into effective RL techniques.
Example Code for PPO with PySC2
Here’s a basic example of how to use PPO with PySC2:
python
from pysc2.env import sc2_env
from stable_baselines3 import PPO
from stable_baselines3.common.env_util import make_vec_env
# Define the environment
env = make_vec_env(
lambda: sc2_env.SC2Env(
map_name="Simple64",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(screen=84, minimap=64)
),
step_mul=8,
game_steps_per_episode=0,
visualize=False # Disable visualization for training
),
n_envs=4 # Use multiple environments for parallel training
)
# Initialize the PPO model
model = PPO("MlpPolicy", env, verbose=1, tensorboard_log="./sc2_ppo_tensorboard/")
# Train the model
model.learn(total_timesteps=1_000_000)
# Save the trained model
model.save("sc2_ppo_model")
# Load the model for evaluation
model = PPO.load("sc2_ppo_model")
# Evaluate the model
obs = env.reset()
for _ in range(1000):
action, _ = model.predict(obs)
obs, rewards, dones, info = env.step(action)
Conclusion
For StarCraft II, PPO and hierarchical RL are the most promising techniques, especially when combined with imitation learning and curriculum learning. Start with simpler scenarios and gradually scale up to full games. Use tools like Stable-Baselines3 or Ray RLlib to implement these techniques efficiently.
Let me know if you need further guidance!
import os
import random
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from collections import deque
from pysc2.env import sc2_env
from pysc2.lib import actions, features
from absl import app
# Define the Q-network
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 observation (flatten and normalize)
def preprocess_observation(obs):
feature_screen = obs.observation.feature_screen
state = []
# Flatten relevant feature layers
for feature in [feature_screen.player_relative, feature_screen.unit_type]:
state.extend(feature.flatten())
# Normalize to [0, 1]
state = np.array(state, dtype=np.float32) / 255.0
return state
# Train the DQN agent
def train_dqn(env, episodes=1000, batch_size=32, replay_size=2000, gamma=0.99, epsilon=1.0, epsilon_min=0.01, epsilon_decay=0.995, target_update=10, save_replay_interval=100):
# Initialize networks
state_size = len(preprocess_observation(env.reset()[0]))
action_size = len(actions.FUNCTIONS)
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=replay_size) # Experience replay buffer
epsilon = epsilon # Exploration rate
for episode in range(episodes):
state = preprocess_observation(env.reset()[0])
state = torch.FloatTensor(state).unsqueeze(0)
total_reward = 0
done = False
while not done:
# Epsilon-greedy action selection
if random.random() < epsilon:
action = random.choice(range(action_size))
else:
with torch.no_grad():
q_values = q_network(state)
action = torch.argmax(q_values).item()
# Execute action in the environment
action_func = actions.FUNCTIONS[action]
if action_func.function_type in env.available_actions():
obs = env.step([action_func()])
next_state = preprocess_observation(obs[0])
reward = obs[0].reward
done = obs[0].last()
next_state = torch.FloatTensor(next_state).unsqueeze(0)
total_reward += reward
# Store experience in replay buffer
memory.append((state, action, torch.FloatTensor([reward]), next_state, done))
state = next_state
# Train the network if enough experiences are collected
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 Q-values and target Q-values
q_values = q_network(states).gather(1, actions)
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 = nn.functional.mse_loss(q_values, target_q)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Decay epsilon
if epsilon > epsilon_min:
epsilon *= epsilon_decay
# Update target network
if (episode + 1) % target_update == 0:
target_network.load_state_dict(q_network.state_dict())
# Save replay periodically
if (episode + 1) % save_replay_interval == 0:
replay_dir = "replays"
os.makedirs(replay_dir, exist_ok=True)
env.save_replay(replay_dir)
print(f"Replay saved at episode {episode + 1}")
# Print episode stats
print(f"Episode {episode + 1}/{episodes}, Total Reward: {total_reward}, Epsilon: {epsilon:.4f}")
# Save the trained model
torch.save(q_network.state_dict(), "sc2_dqn.pth")
print("Training complete. Model saved as 'sc2_dqn.pth'.")
# Main function
def main(unused_argv):
# Create the StarCraft II environment
env = sc2_env.SC2Env(
map_name="MoveToBeacon",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(screen=84, minimap=64)
),
step_mul=8,
game_steps_per_episode=0,
visualize=False # Disable visualization for training
)
# Train the DQN agent
train_dqn(env)
# Close the environment
env.close()
if __name__ == "__main__":
app.run(main)
Key Features of the Code
DQN Implementation:
A simple neural network (QNetwork) is used to approximate the Q-function.
Experience replay is used to stabilize training.
Epsilon-Greedy Exploration:
The agent explores the environment with a decaying exploration rate (epsilon).
Replay Saving:
Replays are saved every save_replay_interval episodes to the replays directory.
Training Loop:
The agent is trained for a specified number of episodes, with progress printed after each episode.
Model Saving:
The trained model is saved as sc2_dqn.pth after training.
How to Run
Install Dependencies:
bash
pip install torch pysc2 absl-py
Run the Script:
bash
python train_dqn.py
Check Output:
The script will print training progress and save replays in the replays directory.
The trained model will be saved as sc2_dqn.pth.
Next Steps
Visualize the saved replays using StarCraft II's replay viewer.
Fine-tune hyperparameters (e.g., epsilon_decay, gamma, batch_size) for better performance.
Experiment with more advanced RL techniques (e.g., PPO, hierarchical RL) for better results.
Let me know if you need further assistance!
Set the environment variable before running your script:
If you want to use the latest version of Protobuf, you can regenerate the _pb2.py files using the latest protoc compiler. This requires some manual work.
The easiest and most reliable solution is to downgrade Protobuf to 3.20.x or lower (Solution 1). This ensures compatibility with PySC2 without requiring additional configuration or manual intervention.
Error A is caused by a missing import and incorrect variable usage in the train_dqn function. Fixing the import and ensuring proper variable scope resolves the issue.
Error B is caused by improper initialization of the sc2_env.SC2Env environment before the absl.flags system has parsed the command-line arguments. Wrapping the main logic in absl.app.run ensures proper flag parsing.
After applying these fixes, both scripts should run without errors. Let me know if you encounter further issues!
def train_dqn(env, episodes=1000, batch_size=32, replay_size=2000, gamma=0.99, epsilon=1.0, epsilon_min=0.01, epsilon_decay=0.995, target_update=10, save_replay_interval=100):
# Initialize networks
state_size = len(preprocess_observation(env.reset()[0]))
action_size = len(actions.FUNCTIONS)
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=replay_size) # Experience replay buffer
epsilon = epsilon # Exploration rate
for episode in range(episodes):
obs = env.reset()
state = preprocess_observation(obs[0])
state = torch.FloatTensor(state).unsqueeze(0)
total_reward = 0
done = False
while not done:
# Epsilon-greedy action selection
if random.random() < epsilon:
action = random.choice(range(action_size))
else:
with torch.no_grad():
q_values = q_network(state)
action = torch.argmax(q_values).item()
# Execute action in the environment
action_func = actions.FUNCTIONS[action]
if action in obs[0].observation.available_actions: # Check if action is available
obs = env.step([action_func()])
next_state = preprocess_observation(obs[0])
reward = obs[0].reward
done = obs[0].last()
next_state = torch.FloatTensor(next_state).unsqueeze(0)
total_reward += reward
# Store experience in replay buffer
memory.append((state, action, torch.FloatTensor([reward]), next_state, done))
state = next_state
# Train the network if enough experiences are collected
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 Q-values and target Q-values
q_values = q_network(states).gather(1, actions)
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 = nn.functional.mse_loss(q_values, target_q)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Decay epsilon
if epsilon > epsilon_min:
epsilon *= epsilon_decay
# Update target network
if (episode + 1) % target_update == 0:
target_network.load_state_dict(q_network.state_dict())
# Save replay periodically
if (episode + 1) % save_replay_interval == 0:
replay_dir = "replays"
os.makedirs(replay_dir, exist_ok=True)
env.save_replay(replay_dir)
print(f"Replay saved at episode {episode + 1}")
# Print episode stats
print(f"Episode {episode + 1}/{episodes}, Total Reward: {total_reward}, Epsilon: {epsilon:.4f}")
# Save the trained model
torch.save(q_network.state_dict(), "sc2_dqn.pth")
print("Training complete. Model saved as 'sc2_dqn.pth'.")
Key Changes
Check Available Actions:
The line:
python
if action_func.function_type in env.available_actions():
is replaced with:
python
if action in obs[0].observation.available_actions:
Observation Handling:
The obs object is used to access the current observation, including available actions.
Re-run the Script
After making these changes, re-run the script:
bash
python train_dqn_A.py
Expected Behavior
The script should now run without errors.
The agent will train in the "MoveToBeacon" mini-game, and replays will be saved periodically.
Debugging Tips
If you encounter further issues, verify that:
The actions.FUNCTIONS list is correctly imported and contains valid actions.
The obs[0].observation.available_actions list is not empty and contains valid actions.
Let me know if you need further assistance!
Fix
Update the action execution logic to provide the required arguments. For example:
python
if action in obs[0].observation.available_actions:
action_func = actions.FUNCTIONS[action]
if action_func.function_type == actions.FUNCTIONS.select_point.id:
# Example: Select a random point on the screen
screen_size = obs[0].observation.feature_screen.player_relative.shape
target_point = (random.randint(0, screen_size[1] - 1), random.randint(0, screen_size[0] - 1))
obs = env.step([action_func("select", target_point)])
else:
obs = env.step([action_func()])
Updated Code for train_dqn_A.py
Here’s the corrected version of train_dqn_A.py:
python
import os
import random
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from collections import deque
from pysc2.env import sc2_env
from pysc2.lib import actions, features
from absl import app
# Define the Q-network
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 observation (flatten and normalize)
def preprocess_observation(obs):
obs = obs[0] # Extract the observation for the first agent
screen = obs.observation["feature_screen"]
state = []
# Flatten relevant feature layers
for feature in [screen.player_relative, screen.unit_type]:
state.extend(feature.flatten())
# Normalize to [0, 1]
state = np.array(state, dtype=np.float32) / 255.0
return state
# Train the DQN agent
def train_dqn(env, episodes=1000, batch_size=32, replay_size=2000, gamma=0.99, epsilon=1.0, epsilon_min=0.01, epsilon_decay=0.995, target_update=10, save_replay_interval=100):
# Initialize networks
state_size = len(preprocess_observation(env.reset()))
action_size = len(actions.FUNCTIONS)
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=replay_size) # Experience replay buffer
epsilon = epsilon # Exploration rate
for episode in range(episodes):
obs = env.reset()
state = preprocess_observation(obs)
state = torch.FloatTensor(state).unsqueeze(0)
total_reward = 0
done = False
while not done:
# Epsilon-greedy action selection
if random.random() < epsilon:
action = random.choice(range(action_size))
else:
with torch.no_grad():
q_values = q_network(state)
action = torch.argmax(q_values).item()
# Execute action in the environment
if action in obs[0].observation.available_actions:
action_func = actions.FUNCTIONS[action]
if action_func.function_type == actions.FUNCTIONS.select_point.id:
# Example: Select a random point on the screen
screen_size = obs[0].observation.feature_screen.player_relative.shape
target_point = (random.randint(0, screen_size[1] - 1), random.randint(0, screen_size[0] - 1))
obs = env.step([action_func("select", target_point)])
else:
obs = env.step([action_func()])
next_state = preprocess_observation(obs)
reward = obs[0].reward
done = obs[0].last()
next_state = torch.FloatTensor(next_state).unsqueeze(0)
total_reward += reward
# Store experience in replay buffer
memory.append((state, action, torch.FloatTensor([reward]), next_state, done))
state = next_state
# Train the network if enough experiences are collected
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 Q-values and target Q-values
q_values = q_network(states).gather(1, actions)
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 = nn.functional.mse_loss(q_values, target_q)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Decay epsilon
if epsilon > epsilon_min:
epsilon *= epsilon_decay
# Update target network
if (episode + 1) % target_update == 0:
target_network.load_state_dict(q_network.state_dict())
# Save replay periodically
if (episode + 1) % save_replay_interval == 0:
replay_dir = "replays"
os.makedirs(replay_dir, exist_ok=True)
env.save_replay(replay_dir)
print(f"Replay saved at episode {episode + 1}")
# Print episode stats
print(f"Episode {episode + 1}/{episodes}, Total Reward: {total_reward}, Epsilon: {epsilon:.4f}")
# Save the trained model
torch.save(q_network.state_dict(), "sc2_dqn.pth")
print("Training complete. Model saved as 'sc2_dqn.pth'.")
# Main function
def main(unused_argv):
# Create the StarCraft II environment
env = sc2_env.SC2Env(
map_name="MoveToBeacon",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(screen=84, minimap=64)
),
step_mul=8,
game_steps_per_episode=0,
visualize=False # Disable