├── agents ├── __init__.py ├── prolonet.py ├── random_prolonet_agent.py ├── non_deep_prolonet_agent.py ├── baseline_agent.py ├── lstm_agent.py ├── heuristic_agent.py ├── prolonet_agent.py └── prolonet_helpers.py ├── models └── README.md ├── opt_helpers ├── __init__.py ├── replay_buffer.py └── ppo_update.py ├── txts └── README.md ├── .gitignore ├── README.md ├── runfiles ├── sc_helpers.py ├── gym_runner.py └── minigame_runner.py └── LICENSE /agents/__init__.py: -------------------------------------------------------------------------------- 1 | # Created by Andrew Silva, andrew.silva@gatech.edu 2 | -------------------------------------------------------------------------------- /models/README.md: -------------------------------------------------------------------------------- 1 | Empty directory used to house models genereated from runfiles. -------------------------------------------------------------------------------- /opt_helpers/__init__.py: -------------------------------------------------------------------------------- 1 | # Created by Andrew Silva, andrew.silva@gatech.edu 2 | -------------------------------------------------------------------------------- /txts/README.md: -------------------------------------------------------------------------------- 1 | Empty directory used to house .txt files generated from runfiles. -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | *.txt 3 | *.png 4 | *.pth.tar 5 | */__pycache__/ 6 | .idea/ 7 | -------------------------------------------------------------------------------- /agents/prolonet.py: -------------------------------------------------------------------------------- 1 | # Created by Andrew Silva, andrew.silva@gatech.edu 2 | import torch.nn as nn 3 | import torch 4 | 5 | 6 | class ProLoNet(nn.Module): 7 | def __init__(self, input_dim, weights, comparators, leaves, alpha=1.0, is_value=False): 8 | super(ProLoNet, self).__init__() 9 | """ 10 | Initialize the ProLoNet, taking in premade weights for inputs to comparators and sigmoids 11 | :param leaves: truple of [[left turn indices], [right turn indices], [final_probs]] 12 | """ 13 | self.layers = nn.ParameterList() 14 | self.comparators = nn.ParameterList() 15 | for comparison_val in comparators: 16 | self.comparators.append(nn.Parameter(torch.Tensor([comparison_val]))) 17 | for weight_layer in weights: 18 | new_weights = torch.Tensor(weight_layer) 19 | new_weights.requires_grad = True 20 | screening = nn.Parameter(new_weights) 21 | self.layers.append(screening) 22 | 23 | self.alpha = torch.Tensor([alpha]) 24 | self.alpha.requires_grad = True 25 | self.alpha = nn.Parameter(self.alpha) 26 | self.leaf_init_information = leaves 27 | self.input_dim = input_dim 28 | left_branches = torch.zeros((len(weights), len(leaves))) 29 | right_branches = torch.zeros((len(weights), len(leaves))) 30 | 31 | for n in range(0, len(leaves)): 32 | for i in leaves[n][0]: 33 | left_branches[i][n] = 1.0 34 | for j in leaves[n][1]: 35 | right_branches[j][n] = 1.0 36 | 37 | left_branches.requires_grad = False 38 | right_branches.requires_grad = False 39 | self.left_path_sigs = left_branches 40 | self.right_path_sigs = right_branches 41 | 42 | new_leaves = [leaf[-1] for leaf in leaves] 43 | labels = torch.Tensor(new_leaves) 44 | labels.requires_grad = True 45 | self.action_probs = nn.Parameter(labels) 46 | 47 | self.added_levels = nn.Sequential() 48 | 49 | self.sig = nn.Sigmoid() 50 | self.softmax = nn.Softmax(dim=-1) 51 | self.is_value = is_value 52 | 53 | def forward(self, input_data, vis_emb=None, grid_emb=None): 54 | sig_vals = None 55 | for layer, comparator in zip(self.layers, self.comparators): 56 | comp = layer.mul(input_data) 57 | comp = comp.sum(dim=1) 58 | comp = comp.sub(comparator) 59 | comp = comp.mul(self.alpha) 60 | sig_out = self.sig(comp) 61 | if sig_vals is None: 62 | sig_vals = sig_out 63 | else: 64 | sig_vals = torch.cat((sig_vals, sig_out)) 65 | 66 | sig_vals = sig_vals.view(input_data.size(0), -1) 67 | one_minus_sig = torch.ones(sig_vals.size()).sub(sig_vals) 68 | 69 | left_path_probs = self.left_path_sigs.t() 70 | right_path_probs = self.right_path_sigs.t() 71 | left_path_probs = left_path_probs * sig_vals 72 | right_path_probs = right_path_probs * one_minus_sig 73 | left_path_probs = left_path_probs.t() 74 | right_path_probs = right_path_probs.t() 75 | 76 | # We don't want 0s to ruin leaf probabilities, so replace them with 1s so they don't affect the product 77 | left_filler = torch.zeros(self.left_path_sigs.size()) 78 | left_filler[self.left_path_sigs == 0] = 1 79 | right_filler = torch.zeros(self.right_path_sigs.size()) 80 | right_filler[self.right_path_sigs == 0] = 1 81 | 82 | left_path_probs = left_path_probs + left_filler 83 | right_path_probs = right_path_probs + right_filler 84 | 85 | probs = torch.cat((left_path_probs, right_path_probs), dim=0) 86 | probs = probs.prod(dim=0) 87 | 88 | probs = probs.view(input_data.size(0), -1) 89 | actions = probs.mm(self.action_probs).view(-1) 90 | if len(self.added_levels) > 0: 91 | seq_in = torch.cat((input_data.view(-1), actions), dim=0) 92 | actions = self.added_levels(seq_in) 93 | if not self.is_value: 94 | return self.softmax(actions) 95 | else: 96 | return actions 97 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ProLoNets 2 | 3 | This project houses all of the code for **ProLoNets: Neural-encoding Human Experts' Domain Knowledge to Warm Start Reinforcement Learning**. 4 | 5 | ### Requirements 6 | 7 | I've gone ahead and made two separate virtualenvs for the OpenAI gym environments and the StarCraft II environments, both of which are built on Python 3.6. In order to work with the SC2 environments, you must have Python >= 3.6, and then installing the requirements in the `sc2_requirements.txt` file should do it. For the gym environments, any Python that works with OpenAI Gym _should_ work, but I haven't tested this. 8 | 9 | ### Running Experiments 10 | 11 | All of the code to run various domains lives in the `runfiles/` directory. 12 | All file involve a few command line arguments, which I'll review now: 13 | 14 | * `-a` or `--agent_type`: Which agent should play through the domain. Details below. Default: `fc` 15 | * `-e` or `--episodes`: How many episodes to run for. Default: 1000 16 | * `-p` or `--processes`: How many concurrent processes to run. Default: 1 17 | * `-s` or `--sl_init`: Should the agent be trained via imitation learning first? Only applies if `agent_type` is `fc`.Default: False 18 | * `-adv` or `--adversary`: Should the agent be mistakenly initialized? Only applies if `agent_type` is `shallow_prolo`. Default: False 19 | 20 | For the `-a` or `--agent_type` flag, valid options are: 21 | * `prolo` for a normal ProLoNet agent 22 | * `shallow_prolo` for a non-deepening ProLoNet agent 23 | * `random` for a randomly-initialized ProLoNet agent 24 | * `fc` for a fully-connected agent 25 | * `lstm` for an LSTM agent 26 | 27 | #### gym_runner.py 28 | 29 | This file runs both of the OpenAI gym domains from the paper, namely cart pole and lunar lander. It has one additional command line argument: 30 | * `-env` or `--env_type`: Which environment to run. Valid options are `cart` and `lunar`. Default: `cart` 31 | In order to run, you must have the a Python environment with the OpenAI Gym installed. Furthermore, you must have box2d-py if you want the lunar lander agents to run. The `gym_requirements.txt` file should have everything necessary for a Python 3.6 environment. 32 | 33 | Running a ProLoNet agent on lunar lander for 1500 episodes with 4 concurrent processes looks like: 34 | ``` 35 | python gym_runner.py -a prolo -e 1500 -p 4 -env lunar 36 | ``` 37 | For the _LOKI_ agent: 38 | ``` 39 | python gym_runner.py -a fc -e 1500 -p 4 -env lunar -s True 40 | ``` 41 | And for the _N-Mistake_ agent: 42 | ``` 43 | python gym_runner.py -a shallow_prolo -e 1500 -p 4 -env lunar -adv True 44 | ``` 45 | 46 | #### minigame_runner.py 47 | 48 | This file runs the FindAndDefeatZerglings minigame from the SC2LE. Running this is exactly the same as the `gym_runner.py` runfile, with the exception that no `--env_type` flag exists for this domain. You must also have all of the StarCraft II setup complete, which means having a valid copy of StarCraft II, having Python >= 3.6, and installing the requirements from the `sc2_requirements.txt` file. For information on setting up StarCraft II, refer to [Blizzard's Documentation](https://github.com/Blizzard/s2client-proto) and for the minigame itself, you'll need the map from [DeepMind's repo](https://github.com/deepmind/pysc2). 49 | 50 | Running a ProLoNet agent: 51 | ``` 52 | python minigame_runner.py -a prolo -e 2000 -p 1 53 | ``` 54 | And a fully-connected agent: 55 | ``` 56 | python minigame_runner.py -a fc -e 2000 -p 1 57 | ``` 58 | And an LSTM agent: 59 | ``` 60 | python minigame_runner.py -a lstm -e 2000 -p 1 61 | ``` 62 | 63 | #### sc_runner.py 64 | 65 | This file runs the full SC2 game against in-game AI. In game AI difficulty is set on lines 836-838. Simply changing "Difficult.VeryEasy" to "Difficulty.Easy", "Difficulty.Medium", or "Difficulty.Hard" does the trick. Again, you'll need SC2 and all of the requirements for the appropriate Python environment, as discussed above. 66 | Running a ProLoNet agent: 67 | ``` 68 | python sc_runner.py -a prolo -e 500 -p 1 69 | ``` 70 | And a random ProLoNet agent: 71 | ``` 72 | python sc_runner.py -a random -e 500 -p 1 73 | ``` 74 | And a non-deepening ProLoNet agent: 75 | ``` 76 | python sc_runner.py -a shallow_prolo -e 500 -p 1 77 | ``` 78 | 79 | 80 | ### Questions: 81 | Any questions about the work or the code can be either opened up as GitHub issues, or sent directly to me at andrew.silva@gatech.edu 82 | -------------------------------------------------------------------------------- /agents/random_prolonet_agent.py: -------------------------------------------------------------------------------- 1 | # Created by Andrew Silva, andrew.silva@gatech.edu 2 | import torch 3 | from torch.distributions import Categorical 4 | from opt_helpers import replay_buffer, ppo_update 5 | import copy 6 | import os 7 | from agents.prolonet_helpers import init_random_cart_net, init_random_lander_net,\ 8 | save_prolonet, load_prolonet, init_random_sc_net, init_random_micro_net 9 | 10 | 11 | class RandomProLoNet: 12 | def __init__(self, 13 | bot_name='RandomProLoNet', 14 | input_dim=4, 15 | output_dim=2): 16 | self.replay_buffer = replay_buffer.ReplayBufferSingleAgent() 17 | # self.replay_buffer = ReplayMemory(1000) 18 | self.bot_name = bot_name 19 | if input_dim == 4 and output_dim == 2: 20 | self.action_network, self.value_network = init_random_cart_net() 21 | 22 | elif input_dim == 8 and output_dim == 4: 23 | self.action_network, self.value_network = init_random_lander_net() 24 | 25 | elif input_dim == 194 and output_dim == 44: 26 | self.action_network, self.value_network = init_random_sc_net() 27 | elif input_dim == 32 and output_dim == 10: 28 | self.action_network, self.value_network = init_random_micro_net() 29 | 30 | self.ppo = ppo_update.PPO([self.action_network, self.value_network], two_nets=True) 31 | self.actor_opt = torch.optim.RMSprop(self.action_network.parameters()) 32 | self.value_opt = torch.optim.RMSprop(self.value_network.parameters()) 33 | self.last_state = [0, 0, 0, 0] 34 | self.last_action = 0 35 | self.last_action_probs = torch.Tensor([0]) 36 | self.last_value_pred = torch.Tensor([[0, 0]]) 37 | self.full_probs = None 38 | self.reward_history = [] 39 | self.num_steps = 0 40 | 41 | def get_action(self, observation): 42 | with torch.no_grad(): 43 | obs = torch.Tensor(observation) 44 | obs = obs.view(1, -1) 45 | self.last_state = obs 46 | probs = self.action_network(obs) 47 | value_pred = self.value_network(obs) 48 | probs = probs.view(-1) 49 | self.full_probs = probs 50 | if self.action_network.input_dim > 10: 51 | probs, inds = torch.topk(probs, 3) 52 | m = Categorical(probs) 53 | action = m.sample() 54 | log_probs = m.log_prob(action) 55 | self.last_action_probs = log_probs 56 | self.last_value_pred = value_pred 57 | 58 | if self.action_network.input_dim > 10: 59 | self.last_action = inds[action] 60 | else: 61 | self.last_action = action 62 | if self.action_network.input_dim > 10: 63 | action = inds[action].item() 64 | else: 65 | action = action.item() 66 | return action 67 | 68 | def save_reward(self, reward): 69 | self.replay_buffer.insert(obs=[self.last_state], 70 | action_log_probs=self.last_action_probs, 71 | value_preds=self.last_value_pred[self.last_action.item()], 72 | last_action=self.last_action, 73 | full_probs_vector=self.full_probs, 74 | rewards=reward) 75 | return True 76 | 77 | def end_episode(self, timesteps, num_processes=1): 78 | self.reward_history.append(timesteps) 79 | value_loss, action_loss = self.ppo.cartpole_update(self.replay_buffer, self) 80 | bot_name = '../txts/' + self.bot_name + str(num_processes) + '_processes' 81 | with open(bot_name + "_losses.txt", "a") as myfile: 82 | myfile.write(str(value_loss + action_loss) + '\n') 83 | with open(bot_name + '_rewards.txt', 'a') as myfile: 84 | myfile.write(str(timesteps) + '\n') 85 | self.num_steps += 1 86 | 87 | def lower_lr(self): 88 | for param_group in self.ppo.actor_opt.param_groups: 89 | param_group['lr'] = param_group['lr'] * 0.5 90 | for param_group in self.ppo.critic_opt.param_groups: 91 | param_group['lr'] = param_group['lr'] * 0.5 92 | 93 | def reset(self): 94 | self.replay_buffer.clear() 95 | 96 | def save(self, fn='last'): 97 | act_fn = fn + self.bot_name + '_actor_' + '.pth.tar' 98 | val_fn = fn + self.bot_name + '_critic_' + '.pth.tar' 99 | 100 | save_prolonet(act_fn, self.action_network) 101 | save_prolonet(val_fn, self.value_network) 102 | 103 | def load(self, fn='last'): 104 | act_fn = fn + self.bot_name + '_actor_' + '.pth.tar' 105 | val_fn = fn + self.bot_name + '_critic_' + '.pth.tar' 106 | 107 | if os.path.exists(act_fn): 108 | self.action_network = load_prolonet(act_fn) 109 | self.value_network = load_prolonet(val_fn) 110 | 111 | def deepen_networks(self, force_switch=False): 112 | pass 113 | 114 | def change_to_deeper(self, random=False): 115 | pass 116 | 117 | def __getstate__(self): 118 | return { 119 | 'action_network': self.action_network, 120 | 'value_network': self.value_network, 121 | 'ppo': self.ppo, 122 | 'actor_opt': self.actor_opt, 123 | 'value_opt': self.value_opt, 124 | } 125 | 126 | def __setstate__(self, state): 127 | self.action_network = copy.deepcopy(state['action_network']) 128 | self.value_network = copy.deepcopy(state['value_network']) 129 | self.ppo = copy.deepcopy(state['ppo']) 130 | self.actor_opt = copy.deepcopy(state['actor_opt']) 131 | self.value_opt = copy.deepcopy(state['value_opt']) 132 | 133 | def duplicate(self): 134 | new_agent = RandomProLoNet() 135 | new_agent.__setstate__(self.__getstate__()) 136 | return new_agent 137 | -------------------------------------------------------------------------------- /opt_helpers/replay_buffer.py: -------------------------------------------------------------------------------- 1 | # Created by Andrew Silva, andrew.silva@gatech.edu 2 | import random 3 | 4 | 5 | class ReplayBufferSingleAgent(object): 6 | def __init__(self): 7 | self.states_list = [] 8 | self.action_probs_list = [] 9 | self.value_list = [] 10 | self.hidden_state_list = [] 11 | self.rewards_list = [] 12 | self.deeper_value_list = [] 13 | self.deeper_action_list = [] 14 | self.deeper_advantage_list = [] 15 | self.action_taken_list = [] 16 | self.advantage_list = [] 17 | self.full_probs_list = [] 18 | self.deeper_full_probs_list = [] 19 | self.step = -1 20 | 21 | def __getstate__(self): 22 | all_data = { 23 | 'states': self.states_list, 24 | 'actions': self.action_probs_list, 25 | 'values': self.value_list, 26 | 'hidden_states': self.hidden_state_list, 27 | 'rewards': self.rewards_list, 28 | 'steps': self.step, 29 | 'deeper_values': self.deeper_value_list, 30 | 'deeper_actions': self.deeper_action_list, 31 | 'actions_taken': self.action_taken_list, 32 | 'advantage_list': self.advantage_list, 33 | 'deeper_advantage_list': self.deeper_advantage_list, 34 | 'full_probs_list': self.full_probs_list, 35 | 'deeper_full_probs_list': self.deeper_full_probs_list 36 | } 37 | return all_data 38 | 39 | def __setstate__(self, state): 40 | self.states_list = state['states'] 41 | self.action_probs_list = state['actions'] 42 | self.value_list = state['values'] 43 | self.hidden_state_list = state['hidden_states'] 44 | self.rewards_list = state['rewards'] 45 | self.step = state['steps'] 46 | self.deeper_value_list = state['deeper_values'] 47 | self.deeper_action_list = state['deeper_actions'] 48 | self.action_taken_list = state['actions_taken'] 49 | self.advantage_list = state['advantage_list'] 50 | self.deeper_advantage_list = state['deeper_advantage_list'] 51 | self.full_probs_list = state['full_probs_list'] 52 | self.deeper_full_probs_list = state['deeper_full_probs_list'] 53 | 54 | def extend(self, state): 55 | self.states_list.extend(state['states']) 56 | self.action_probs_list.extend(state['actions']) 57 | self.value_list.extend(state['values']) 58 | self.hidden_state_list.extend(state['hidden_states']) 59 | self.rewards_list.extend(state['rewards']) 60 | self.step += state['steps'] 61 | self.deeper_value_list.extend(state['deeper_values']) 62 | self.deeper_action_list.extend(state['deeper_actions']) 63 | self.action_taken_list.extend(state['actions_taken']) 64 | self.advantage_list.extend(state['advantage_list']) 65 | self.deeper_advantage_list.extend(state['deeper_advantage_list']) 66 | self.full_probs_list.extend(state['full_probs_list']) 67 | self.deeper_full_probs_list.extend(state['deeper_full_probs_list']) 68 | 69 | def insert(self, 70 | obs=None, 71 | recurrent_hidden_states=None, 72 | action_log_probs=None, 73 | value_preds=None, 74 | deeper_action_log_probs=None, 75 | deeper_value_pred=None, 76 | last_action=None, 77 | full_probs_vector=None, 78 | deeper_full_probs_vector=None, 79 | rewards=None): 80 | self.states_list.append(obs) 81 | self.hidden_state_list.append(recurrent_hidden_states) 82 | self.action_probs_list.append(action_log_probs) 83 | self.value_list.append(value_preds) 84 | self.rewards_list.append(rewards) 85 | self.deeper_action_list.append(deeper_action_log_probs) 86 | self.deeper_value_list.append(deeper_value_pred) 87 | self.action_taken_list.append(last_action) 88 | self.full_probs_list.append(full_probs_vector) 89 | self.deeper_full_probs_list.append(deeper_full_probs_vector) 90 | # self.done_list.append(done) 91 | self.step += 1 92 | 93 | def clear(self): 94 | del self.states_list[:] 95 | del self.hidden_state_list[:] 96 | del self.value_list[:] 97 | del self.action_probs_list[:] 98 | del self.rewards_list[:] 99 | del self.deeper_value_list[:] 100 | del self.deeper_action_list[:] 101 | del self.action_taken_list[:] 102 | del self.deeper_advantage_list[:] 103 | del self.advantage_list[:] 104 | del self.full_probs_list[:] 105 | del self.deeper_full_probs_list[:] 106 | self.step = 0 107 | 108 | def sample(self): 109 | # randomly sample a time step 110 | if len(self.states_list) <= 0: 111 | return False 112 | t = random.randint(0, len(self.states_list)-1) 113 | sample_back = { 114 | 'state': self.states_list[t], 115 | 'hidden_state': self.hidden_state_list[t], 116 | 'action_prob': self.action_probs_list[t], 117 | 'value_pred': self.value_list[t], 118 | 'deeper_action_prob': self.deeper_action_list[t], 119 | 'deeper_value_pred': self.deeper_value_list[t], 120 | 'reward': self.rewards_list[t], 121 | 'advantage': self.advantage_list[t], 122 | 'action_taken': self.action_taken_list[t], 123 | 'deeper_advantage': self.deeper_advantage_list[t], 124 | 'full_prob_vector': self.full_probs_list[t], 125 | 'deeper_full_prob_vector': self.deeper_full_probs_list[t] 126 | } 127 | del self.states_list[t] 128 | del self.hidden_state_list[t] 129 | del self.action_probs_list[t] 130 | del self.value_list[t] 131 | del self.rewards_list[t] 132 | del self.deeper_action_list[t] 133 | del self.deeper_value_list[t] 134 | del self.action_taken_list[t] 135 | del self.advantage_list[t] 136 | del self.deeper_advantage_list[t] 137 | del self.full_probs_list[t] 138 | del self.deeper_full_probs_list[t] 139 | return sample_back 140 | -------------------------------------------------------------------------------- /runfiles/sc_helpers.py: -------------------------------------------------------------------------------- 1 | # Created by Andrew Silva, andrew.silva@gatech.edu 2 | from sc2.constants import * 3 | from sc2.ids.unit_typeid import * 4 | import numpy as np 5 | from sc2 import Race 6 | MY_POSSIBLES = [PROBE, ZEALOT, STALKER, SENTRY, ADEPT, HIGHTEMPLAR, DARKTEMPLAR, OBSERVER, WARPPRISM, 7 | IMMORTAL, COLOSSUS, DISRUPTOR, PHOENIX, VOIDRAY, ORACLE, TEMPEST, CARRIER, INTERCEPTOR, 8 | MOTHERSHIP, NEXUS, PYLON, ASSIMILATOR, GATEWAY, WARPGATE, FORGE, CYBERNETICSCORE, PHOTONCANNON, 9 | SHIELDBATTERY, ROBOTICSFACILITY, STARGATE, TWILIGHTCOUNCIL, ROBOTICSBAY, FLEETBEACON, 10 | TEMPLARARCHIVE, DARKSHRINE, ORACLESTASISTRAP] 11 | 12 | ENEMY_POSSIBLES = [PROBE, ZEALOT, STALKER, SENTRY, ADEPT, HIGHTEMPLAR, DARKTEMPLAR, OBSERVER, ARCHON, WARPPRISM, 13 | IMMORTAL, COLOSSUS, DISRUPTOR, PHOENIX, VOIDRAY, ORACLE, TEMPEST, CARRIER, INTERCEPTOR, 14 | MOTHERSHIP, NEXUS, PYLON, ASSIMILATOR, GATEWAY, WARPGATE, FORGE, CYBERNETICSCORE, PHOTONCANNON, 15 | SHIELDBATTERY, ROBOTICSFACILITY, STARGATE, TWILIGHTCOUNCIL, ROBOTICSBAY, FLEETBEACON, 16 | TEMPLARARCHIVE, DARKSHRINE, ORACLESTASISTRAP, SCV, MULE, MARINE, REAPER, MARAUDER, GHOST, HELLION, WIDOWMINE, 17 | CYCLONE, SIEGETANKSIEGED, THOR, VIKINGFIGHTER, MEDIVAC, LIBERATOR, RAVEN, BANSHEE, BATTLECRUISER, COMMANDCENTER, 18 | SUPPLYDEPOT, REFINERY, ENGINEERINGBAY, BUNKER, MISSILETURRET, SENSORTOWER, GHOSTACADEMY, FACTORY, BARRACKS, STARPORT, 19 | FUSIONCORE, TECHLAB, REACTOR, AUTOTURRET, ORBITALCOMMAND, PLANETARYFORTRESS, HELLIONTANK, LARVA, DRONE, OVERLORD, 20 | QUEEN, ZERGLING, BANELING, ROACH, RAVAGER, OVERSEER, CHANGELING, HYDRALISK, LURKER, MUTALISK, CORRUPTOR, 21 | SWARMHOSTMP, LOCUSTMP, INFESTOR, INFESTEDTERRAN, VIPER, ULTRALISK, BROODLORD, BROODLING, HATCHERY, EXTRACTOR, 22 | SPAWNINGPOOL, SPINECRAWLER, SPORECRAWLER, EVOLUTIONCHAMBER, ROACHWARREN, BANELINGNEST, HYDRALISKDEN, LURKERDENMP, 23 | SPIRE, NYDUSNETWORK, INFESTATIONPIT, ULTRALISKCAVERN, CREEPTUMOR, LAIR, HIVE, GREATERSPIRE] 24 | ENEMY_MAPPINGS = { 25 | WIDOWMINEBURROWED: WIDOWMINE, # widow mine / burrowed widow mine 26 | SIEGETANK: SIEGETANKSIEGED, # siege tank siege / tank 27 | VIKINGASSAULT: VIKINGFIGHTER, # viking assault / viking fighter 28 | COMMANDCENTERFLYING: COMMANDCENTER, # flying command center / command center 29 | ORBITALCOMMANDFLYING: ORBITALCOMMAND, # flying orbital command / command center 30 | SUPPLYDEPOTLOWERED: SUPPLYDEPOT, # supply depot / lowered 31 | BARRACKSFLYING: BARRACKS, # barracks / flying barracks 32 | FACTORYFLYING: FACTORY, # factory / factory flying 33 | STARPORTFLYING: STARPORT, # starport / starport flying 34 | BARRACKSTECHLAB: TECHLAB, # barracks tech lab / tech lab 35 | FACTORYTECHLAB: TECHLAB, # factory tech lab / tech lab 36 | STARPORTTECHLAB: TECHLAB, # starport tech lab / tech lab 37 | BARRACKSREACTOR: REACTOR, # barracks reactor / reactor 38 | FACTORYREACTOR: REACTOR, # factory reactor / reactor 39 | STARPORTREACTOR: REACTOR, # starport reactor / reactor 40 | DRONEBURROWED: DRONE, 41 | BANELINGBURROWED: BANELING, 42 | HYDRALISKBURROWED: HYDRALISK, 43 | ROACHBURROWED: ROACH, 44 | ZERGLINGBURROWED: ZERGLING, 45 | QUEENBURROWED: QUEEN, 46 | RAVAGERBURROWED: RAVAGER, 47 | CHANGELINGZEALOT: CHANGELING, 48 | CHANGELINGMARINESHIELD: CHANGELING, 49 | CHANGELINGMARINE: CHANGELING, 50 | CHANGELINGZERGLINGWINGS: CHANGELING, 51 | CHANGELINGZERGLING: CHANGELING, 52 | LURKERBURROWED: LURKER, 53 | SWARMHOSTBURROWEDMP: SWARMHOSTMP, 54 | LOCUSTMPFLYING: LOCUSTMP, 55 | INFESTORTERRANBURROWED: INFESTOR, 56 | INFESTORBURROWED: INFESTOR, 57 | INFESTORTERRAN: INFESTOR, 58 | ULTRALISKBURROWED: ULTRALISK, 59 | SPINECRAWLERUPROOTED: SPINECRAWLER, 60 | SPORECRAWLERUPROOTED: SPORECRAWLER, 61 | LURKERDEN: LURKERDENMP, 62 | } 63 | 64 | def my_units_to_type_count(unit_array_in): 65 | """ 66 | Take in current units owned by player and return a 36-dim list of how many of each type there are 67 | :param unit_array_in: self.units from a python-sc2 bot 68 | :return: 1x36 where each element is the count of units of that type 69 | """ 70 | type_counts = np.zeros(len(MY_POSSIBLES)) 71 | for unit in unit_array_in: 72 | type_counts[MY_POSSIBLES.index(unit.type_id)] += 1 73 | return type_counts 74 | 75 | 76 | def enemy_units_to_type_count(enemy_array_in): 77 | """ 78 | Take in enemy units and map them to type counts, as in my army. But here I consider all 3 races 79 | :param enemy_array_in: self.known_enemy_units (or my all_enemy_units list) from python-sc2 bot 80 | :return: 1x111 where each element is the count of units of that type 81 | """ 82 | type_counts = np.zeros(len(ENEMY_POSSIBLES)) 83 | for unit in enemy_array_in: 84 | if unit.type_id in ENEMY_POSSIBLES: 85 | type_counts[ENEMY_POSSIBLES.index(unit.type_id)] += 1 86 | elif unit.type_id in ENEMY_MAPPINGS.keys(): 87 | type_counts[ENEMY_POSSIBLES.index(ENEMY_MAPPINGS[unit.type_id])] += 1 88 | else: 89 | continue 90 | return type_counts 91 | 92 | 93 | def get_player_state(state_in): 94 | 95 | sorted_observed_player_state = [ 96 | state_in.observation.player_common.army_count, 97 | state_in.observation.player_common.food_army, 98 | state_in.observation.player_common.food_cap, 99 | state_in.observation.player_common.food_used, 100 | state_in.observation.player_common.idle_worker_count, 101 | state_in.observation.player_common.larva_count, 102 | state_in.observation.player_common.minerals, 103 | state_in.observation.player_common.vespene, 104 | state_in.observation.player_common.warp_gate_count 105 | ] 106 | return sorted_observed_player_state 107 | 108 | 109 | def get_unit_data(unit_in): 110 | if unit_in is None: 111 | return [-1, -1, -1, -1] 112 | extracted_data = [ 113 | float(unit_in.position.x), 114 | float(unit_in.position.y), 115 | float(unit_in.health), 116 | float(unit_in.weapon_cooldown), 117 | ] 118 | return extracted_data 119 | 120 | 121 | def get_nearest_enemies(unit_in, enemy_list): 122 | my_pos = [unit_in.position.x, unit_in.position.y] 123 | distances = [] 124 | enemies = [] 125 | for enemy in enemy_list: 126 | enemy_pos = [enemy.position.x, enemy.position.y] 127 | distances.append(dist(my_pos, enemy_pos)) 128 | enemies.append(enemy) 129 | sorted_results = [x for _, x in sorted(zip(distances, enemies))] 130 | sorted_results.extend([None, None, None, None, None]) 131 | return sorted_results[:5] 132 | 133 | 134 | def dist(pos1, pos2): 135 | return np.sqrt((pos1[0]-pos2[0])**2 + (pos1[1]-pos2[1])**2) 136 | -------------------------------------------------------------------------------- /agents/non_deep_prolonet_agent.py: -------------------------------------------------------------------------------- 1 | # Created by Andrew Silva, andrew.silva@gatech.edu 2 | import torch 3 | from torch.distributions import Categorical 4 | from opt_helpers import replay_buffer, ppo_update 5 | import copy 6 | from agents.prolonet_helpers import init_cart_nets, init_lander_nets, init_adversarial_net, \ 7 | save_prolonet, load_prolonet, init_sc_nets, init_micro_net 8 | import os 9 | 10 | 11 | class ShallowProLoNet: 12 | def __init__(self, 13 | distribution='one_hot', 14 | bot_name='ShallowProLoNet', 15 | input_dim=4, 16 | output_dim=2, 17 | adversarial=False): 18 | self.replay_buffer = replay_buffer.ReplayBufferSingleAgent() 19 | self.bot_name = bot_name 20 | self.adv_prob = 0.1 21 | if input_dim == 4 and output_dim == 2: 22 | if adversarial: 23 | self.action_network, self.value_network = init_adversarial_net(adv_type='cart', 24 | distribution_in=distribution, 25 | adv_prob=self.adv_prob) 26 | self.bot_name += '_adversarial' + str(self.adv_prob) 27 | else: 28 | self.action_network, self.value_network = init_cart_nets(distribution) 29 | elif input_dim == 8 and output_dim == 4: 30 | if adversarial: 31 | self.action_network, self.value_network = init_adversarial_net(adv_type='lunar', 32 | distribution_in=distribution) 33 | self.bot_name += '_adversarial' + str(self.adv_prob) 34 | else: 35 | self.action_network, self.value_network = init_lander_nets(distribution) 36 | elif input_dim == 194 and output_dim == 44: 37 | if adversarial: 38 | self.action_network, self.value_network = init_adversarial_net(adv_type='sc', 39 | distribution_in=distribution) 40 | self.bot_name += '_adversarial' + str(self.adv_prob) 41 | else: 42 | self.action_network, self.value_network = init_sc_nets(distribution) 43 | elif input_dim == 32 and output_dim == 10: 44 | if adversarial: 45 | self.action_network, self.value_network = init_adversarial_net(adv_type='micro', 46 | distribution_in=distribution) 47 | self.bot_name += '_adversarial' + str(self.adv_prob) 48 | else: 49 | self.action_network, self.value_network = init_micro_net(distribution) 50 | 51 | self.ppo = ppo_update.PPO([self.action_network, self.value_network], two_nets=True) 52 | self.actor_opt = torch.optim.RMSprop(self.action_network.parameters()) 53 | self.value_opt = torch.optim.RMSprop(self.value_network.parameters()) 54 | 55 | self.last_state = [0, 0, 0, 0] 56 | self.last_action = 0 57 | self.last_action_probs = torch.Tensor([0]) 58 | self.last_value_pred = torch.Tensor([[0, 0]]) 59 | self.full_probs = None 60 | self.reward_history = [] 61 | self.num_steps = 0 62 | 63 | def get_action(self, observation): 64 | with torch.no_grad(): 65 | obs = torch.Tensor(observation) 66 | obs = obs.view(1, -1) 67 | self.last_state = obs 68 | probs = self.action_network(obs) 69 | value_pred = self.value_network(obs) 70 | probs = probs.view(-1) 71 | self.full_probs = probs 72 | if self.action_network.input_dim > 10: 73 | probs, inds = torch.topk(probs, 3) 74 | m = Categorical(probs) 75 | action = m.sample() 76 | log_probs = m.log_prob(action) 77 | self.last_action_probs = log_probs 78 | self.last_value_pred = value_pred 79 | 80 | if self.action_network.input_dim > 10: 81 | self.last_action = inds[action] 82 | else: 83 | self.last_action = action 84 | if self.action_network.input_dim > 10: 85 | action = inds[action].item() 86 | else: 87 | action = action.item() 88 | return action 89 | 90 | def save_reward(self, reward): 91 | self.replay_buffer.insert(obs=[self.last_state], 92 | recurrent_hidden_states=None, 93 | action_log_probs=self.last_action_probs, 94 | value_preds=self.last_value_pred[self.last_action.item()], 95 | last_action=self.last_action, 96 | full_probs_vector=self.full_probs, 97 | rewards=reward) 98 | return True 99 | 100 | def end_episode(self, timesteps, num_processes=1): 101 | self.reward_history.append(timesteps) 102 | value_loss, action_loss = self.ppo.cartpole_update(self.replay_buffer, self) 103 | bot_name = '../txts/' + self.bot_name + str(num_processes) + '_processes' 104 | with open(bot_name + "_losses.txt", "a") as myfile: 105 | myfile.write(str(value_loss + action_loss) + '\n') 106 | with open(bot_name + '_rewards.txt', 'a') as myfile: 107 | myfile.write(str(timesteps) + '\n') 108 | 109 | def lower_lr(self): 110 | for param_group in self.ppo.actor_opt.param_groups: 111 | param_group['lr'] = param_group['lr'] * 0.5 112 | for param_group in self.ppo.critic_opt.param_groups: 113 | param_group['lr'] = param_group['lr'] * 0.5 114 | 115 | def reset(self): 116 | self.replay_buffer.clear() 117 | 118 | def save(self, fn='last'): 119 | act_fn = fn + self.bot_name + '_actor_' + '.pth.tar' 120 | val_fn = fn + self.bot_name + '_critic_' + '.pth.tar' 121 | save_prolonet(act_fn, self.action_network) 122 | save_prolonet(val_fn, self.value_network) 123 | 124 | def load(self, fn='last'): 125 | act_fn = fn + self.bot_name + '_actor_' + '.pth.tar' 126 | val_fn = fn + self.bot_name + '_critic_' + '.pth.tar' 127 | if os.path.exists(act_fn): 128 | self.action_network = load_prolonet(act_fn) 129 | self.value_network = load_prolonet(val_fn) 130 | 131 | def deepen_networks(self, force_switch=False): 132 | pass 133 | 134 | def change_to_deeper(self, random=False): 135 | pass 136 | 137 | def __getstate__(self): 138 | return { 139 | 'action_network': self.action_network, 140 | 'value_network': self.value_network, 141 | 'ppo': self.ppo, 142 | 'actor_opt': self.actor_opt, 143 | 'value_opt': self.value_opt, 144 | 'bot_name': self.bot_name 145 | } 146 | 147 | def __setstate__(self, state): 148 | self.action_network = copy.deepcopy(state['action_network']) 149 | self.value_network = copy.deepcopy(state['value_network']) 150 | self.ppo = copy.deepcopy(state['ppo']) 151 | self.actor_opt = copy.deepcopy(state['actor_opt']) 152 | self.value_opt = copy.deepcopy(state['value_opt']) 153 | self.bot_name = copy.deepcopy(state['bot_name']) 154 | 155 | def duplicate(self): 156 | new_agent = ShallowProLoNet() 157 | new_agent.__setstate__(self.__getstate__()) 158 | return new_agent 159 | -------------------------------------------------------------------------------- /agents/baseline_agent.py: -------------------------------------------------------------------------------- 1 | # Created by Andrew Silva, andrew.silva@gatech.edu 2 | import torch 3 | import torch.nn as nn 4 | from torch.distributions import Categorical 5 | from opt_helpers import replay_buffer, ppo_update 6 | import copy 7 | from agents.heuristic_agent import CartPoleHeuristic, LunarHeuristic, \ 8 | StarCraftMacroHeuristic, StarCraftMicroHeuristic 9 | 10 | 11 | class BaselineFCNet(nn.Module): 12 | def __init__(self, input_dim, is_value=False, output_dim=2): 13 | super(BaselineFCNet, self).__init__() 14 | self.lin1 = nn.Linear(input_dim, input_dim) 15 | self.lin2 = nn.Linear(input_dim, input_dim) 16 | self.lin3 = nn.Linear(input_dim, output_dim) 17 | self.sig = nn.ReLU() 18 | self.input_dim = input_dim 19 | if input_dim == 4: 20 | self.lin2 = nn.Sequential( 21 | nn.Linear(input_dim, input_dim), 22 | ) 23 | elif input_dim == 8: 24 | self.lin2 = nn.Sequential( 25 | nn.Linear(input_dim, 64), 26 | nn.ReLU(), 27 | nn.Linear(64, input_dim), 28 | ) 29 | elif input_dim > 10: 30 | self.lin2 = nn.Sequential( 31 | nn.Linear(input_dim, input_dim), 32 | nn.ReLU(), 33 | nn.Linear(input_dim, input_dim), 34 | nn.ReLU(), 35 | nn.Linear(input_dim, input_dim), 36 | nn.ReLU(), 37 | nn.Linear(input_dim, input_dim), 38 | nn.ReLU(), 39 | nn.Linear(input_dim, input_dim), 40 | ) 41 | self.softmax = nn.Softmax(dim=0) 42 | self.is_value = is_value 43 | 44 | def forward(self, input_data): 45 | act_out = self.lin3(self.sig(self.lin2(self.sig(self.lin1(input_data))))).view(-1) 46 | if self.is_value: 47 | return act_out 48 | else: 49 | return self.softmax(act_out) 50 | 51 | 52 | class FCNet: 53 | def __init__(self, 54 | bot_name='FCNet', 55 | input_dim=4, 56 | output_dim=2, 57 | sl_init=False): 58 | self.bot_name = bot_name 59 | self.sl_init = sl_init 60 | 61 | self.replay_buffer = replay_buffer.ReplayBufferSingleAgent() 62 | self.action_network = BaselineFCNet(input_dim=input_dim, 63 | output_dim=output_dim, 64 | is_value=False) 65 | self.value_network = BaselineFCNet(input_dim=input_dim, 66 | output_dim=output_dim, 67 | is_value=True) 68 | if self.sl_init: 69 | if input_dim == 4: 70 | self.teacher = CartPoleHeuristic() 71 | self.action_loss_threshold = 250 72 | elif input_dim == 8: 73 | self.teacher = LunarHeuristic() 74 | self.action_loss_threshold = 350 75 | elif input_dim == 32: 76 | self.teacher = StarCraftMicroHeuristic() 77 | self.action_loss_threshold = 500 78 | elif input_dim > 100: 79 | self.teacher = StarCraftMacroHeuristic() 80 | self.action_loss_threshold = 1000 81 | self.bot_name += '_SLtoRL_' 82 | self.ppo = ppo_update.PPO([self.action_network, self.value_network], two_nets=True) 83 | self.actor_opt = torch.optim.RMSprop(self.action_network.parameters()) 84 | self.value_opt = torch.optim.RMSprop(self.value_network.parameters()) 85 | 86 | self.last_state = [0, 0, 0, 0] 87 | self.last_action = 0 88 | self.last_action_probs = torch.Tensor([0]) 89 | self.last_value_pred = torch.Tensor([[0, 0]]) 90 | self.last_deep_action_probs = torch.Tensor([0]) 91 | self.last_deep_value_pred = torch.Tensor([[0, 0]]) 92 | self.full_probs = None 93 | self.reward_history = [] 94 | self.num_steps = 0 95 | 96 | def get_action(self, observation): 97 | with torch.no_grad(): 98 | obs = torch.Tensor(observation) 99 | obs = obs.view(1, -1) 100 | self.last_state = obs 101 | probs = self.action_network(obs) 102 | value_pred = self.value_network(obs) 103 | probs = probs.view(-1) 104 | self.full_probs = probs 105 | if self.action_network.input_dim > 10: 106 | probs, inds = torch.topk(probs, 3) 107 | m = Categorical(probs) 108 | action = m.sample() 109 | log_probs = m.log_prob(action) 110 | self.last_action_probs = log_probs 111 | self.last_value_pred = value_pred 112 | 113 | if self.action_network.input_dim > 10: 114 | self.last_action = inds[action] 115 | else: 116 | self.last_action = action 117 | if self.action_network.input_dim > 10: 118 | action = inds[action].item() 119 | else: 120 | action = action.item() 121 | return action 122 | 123 | def save_reward(self, reward): 124 | self.replay_buffer.insert(obs=[self.last_state], 125 | action_log_probs=self.last_action_probs, 126 | value_preds=self.last_value_pred[self.last_action.item()], 127 | last_action=self.last_action, 128 | full_probs_vector=self.full_probs, 129 | rewards=reward) 130 | return True 131 | 132 | def end_episode(self, timesteps, num_processes=1): 133 | self.reward_history.append(timesteps) 134 | if self.sl_init: 135 | action_loss = self.ppo.sl_updates(self.replay_buffer, self, self.teacher) 136 | value_loss = action_loss 137 | if self.num_steps >= self.action_loss_threshold: 138 | self.sl_init = False 139 | else: 140 | value_loss, action_loss = self.ppo.cartpole_update(self.replay_buffer, self) 141 | bot_name = '../txts/' + self.bot_name + str(num_processes) + '_processes' 142 | with open(bot_name + "_losses.txt", "a") as myfile: 143 | myfile.write(str(value_loss + action_loss) + '\n') 144 | with open(bot_name + '_rewards.txt', 'a') as myfile: 145 | myfile.write(str(timesteps) + '\n') 146 | 147 | def lower_lr(self): 148 | for param_group in self.ppo.actor_opt.param_groups: 149 | param_group['lr'] = param_group['lr'] * 0.5 150 | for param_group in self.ppo.critic_opt.param_groups: 151 | param_group['lr'] = param_group['lr'] * 0.5 152 | 153 | def reset(self): 154 | self.replay_buffer.clear() 155 | 156 | def deepen_networks(self): 157 | pass 158 | 159 | def save(self, fn='last'): 160 | checkpoint = dict() 161 | checkpoint['actor'] = self.action_network.state_dict() 162 | checkpoint['value'] = self.value_network.state_dict() 163 | torch.save(checkpoint, fn+self.bot_name+'.pth.tar') 164 | 165 | def load(self, fn='last'): 166 | fn = fn + self.bot_name + '.pth.tar' 167 | model_checkpoint = torch.load(fn, map_location='cpu') 168 | actor_data = model_checkpoint['actor'] 169 | value_data = model_checkpoint['value'] 170 | self.action_network.load_state_dict(actor_data) 171 | self.value_network.load_state_dict(value_data) 172 | 173 | def __getstate__(self): 174 | return { 175 | # 'replay_buffer': self.replay_buffer, 176 | 'action_network': self.action_network, 177 | 'value_network': self.value_network, 178 | 'ppo': self.ppo, 179 | 'actor_opt': self.actor_opt, 180 | 'value_opt': self.value_opt 181 | } 182 | 183 | def __setstate__(self, state): 184 | self.action_network = copy.deepcopy(state['action_network']) 185 | self.value_network = copy.deepcopy(state['value_network']) 186 | self.ppo = copy.deepcopy(state['ppo']) 187 | self.actor_opt = copy.deepcopy(state['actor_opt']) 188 | self.value_opt = copy.deepcopy(state['value_opt']) 189 | 190 | def duplicate(self): 191 | new_agent = FCNet() 192 | new_agent.__setstate__(self.__getstate__()) 193 | return new_agent 194 | -------------------------------------------------------------------------------- /agents/lstm_agent.py: -------------------------------------------------------------------------------- 1 | # Created by Andrew Silva, andrew.silva@gatech.edu 2 | import torch 3 | import torch.nn as nn 4 | from torch.distributions import Categorical 5 | from opt_helpers import replay_buffer, ppo_update 6 | import copy 7 | use_gpu = False 8 | 9 | 10 | class BaselineLSTMNet(nn.Module): 11 | def __init__(self, input_dim, output_dim, is_value=False): 12 | super(BaselineLSTMNet, self).__init__() 13 | self.num_layers = 1 14 | self.input_dim = input_dim 15 | self.batch_size = 1 16 | self.hidden_dim = input_dim 17 | self.lin1 = nn.Linear(input_dim, input_dim) 18 | self.rnn = nn.LSTM(input_dim, self.hidden_dim, self.num_layers) 19 | self.lin2 = nn.Linear(self.hidden_dim, input_dim) 20 | self.lin3 = nn.Linear(input_dim, output_dim) 21 | self.sig = nn.ReLU() 22 | if input_dim > 10: 23 | self.lin1 = nn.Sequential( 24 | nn.Linear(input_dim, input_dim), 25 | nn.ReLU(), 26 | nn.Linear(input_dim, input_dim), 27 | nn.ReLU(), 28 | nn.Linear(input_dim, input_dim), 29 | nn.ReLU(), 30 | nn.Linear(input_dim, input_dim), 31 | ) 32 | self.softmax = nn.Softmax(dim=0) 33 | self.is_value = is_value 34 | 35 | def init_hidden(self, batch_size=1): 36 | """ 37 | Initialize hidden state so that it can be clean for each new series of inputs 38 | :return: Variable of zeros of shape (num_layers, minibatch_size, hidden_dim) 39 | """ 40 | first_dim = self.num_layers 41 | second_dim = batch_size 42 | self.batch_size = batch_size 43 | third_dim = self.hidden_dim 44 | if use_gpu: 45 | return (torch.zeros(first_dim, second_dim, third_dim).cuda(), 46 | torch.zeros(first_dim, second_dim, third_dim).cuda()) 47 | else: 48 | return (torch.zeros(first_dim, second_dim, third_dim), 49 | torch.zeros(first_dim, second_dim, third_dim)) 50 | 51 | def forward(self, input_data, hidden_state): 52 | input_data = input_data.unsqueeze(0) 53 | act_out = self.sig(self.lin1(input_data)) 54 | act_out, hidden_out = self.rnn(act_out, hidden_state) 55 | act_out = self.lin3(self.sig(self.lin2(self.sig(act_out)))).view(-1) 56 | if self.is_value: 57 | return act_out, hidden_out 58 | else: 59 | return self.softmax(act_out), hidden_out 60 | 61 | 62 | class LSTMNet: 63 | def __init__(self, 64 | bot_name='LSTMNet', 65 | input_dim=4, 66 | output_dim=2): 67 | self.bot_name = bot_name 68 | self.input_dim = input_dim 69 | self.replay_buffer = replay_buffer.ReplayBufferSingleAgent() 70 | self.action_network = BaselineLSTMNet(input_dim=input_dim, 71 | output_dim=output_dim, 72 | is_value=False) 73 | self.value_network = BaselineLSTMNet(input_dim=input_dim, 74 | output_dim=output_dim, 75 | is_value=True) 76 | self.ppo = ppo_update.PPO([self.action_network, self.value_network], two_nets=True) 77 | self.actor_opt = torch.optim.RMSprop(self.action_network.parameters()) 78 | self.value_opt = torch.optim.RMSprop(self.value_network.parameters()) 79 | 80 | self.last_state = [0, 0, 0, 0] 81 | self.last_action = 0 82 | self.last_action_probs = torch.Tensor([0]) 83 | self.last_value_pred = torch.Tensor([[0, 0]]) 84 | self.action_hidden_state = None 85 | self.full_probs = None 86 | self.value_hidden_state = None 87 | self.new_action_hidden = None 88 | self.new_value_hidden = None 89 | self.reward_history = [] 90 | self.num_steps = 0 91 | 92 | def get_action(self, observation): 93 | if self.action_hidden_state is None: 94 | self.action_hidden_state = self.action_network.init_hidden() 95 | self.value_hidden_state = self.value_network.init_hidden() 96 | self.new_action_hidden = self.action_network.init_hidden() 97 | self.new_value_hidden = self.value_network.init_hidden() 98 | with torch.no_grad(): 99 | obs = torch.Tensor(observation) 100 | obs = obs.view(1, -1) 101 | self.last_state = obs 102 | probs, action_hidden = self.action_network(obs, self.action_hidden_state) 103 | value_pred, value_hidden = self.value_network(obs, self.value_hidden_state) 104 | probs = probs.view(-1) 105 | self.full_probs = probs 106 | if self.action_network.input_dim > 10: 107 | probs, inds = torch.topk(probs, 3) 108 | m = Categorical(probs) 109 | action = m.sample() 110 | log_probs = m.log_prob(action) 111 | self.new_action_hidden = action_hidden 112 | self.new_value_hidden = value_hidden 113 | self.last_action_probs = log_probs 114 | self.last_value_pred = value_pred 115 | 116 | if self.action_network.input_dim > 10: 117 | self.last_action = inds[action] 118 | else: 119 | self.last_action = action 120 | if self.action_network.input_dim > 10: 121 | action = inds[action].item() 122 | else: 123 | action = action.item() 124 | return action 125 | 126 | def save_reward(self, reward): 127 | self.replay_buffer.insert(obs=[self.last_state], 128 | recurrent_hidden_states=(self.action_hidden_state, self.value_hidden_state), 129 | action_log_probs=self.last_action_probs, 130 | value_preds=self.last_value_pred[self.last_action.item()], 131 | last_action=self.last_action, 132 | full_probs_vector=self.full_probs, 133 | rewards=reward) 134 | self.action_hidden_state = self.new_action_hidden 135 | self.value_hidden_state = self.new_value_hidden 136 | return True 137 | 138 | def end_episode(self, timesteps, num_processes=1): 139 | self.reward_history.append(timesteps) 140 | value_loss, action_loss = self.ppo.cartpole_update(self.replay_buffer, self) 141 | bot_name = '../txts/' + self.bot_name + str(num_processes) + '_processes' 142 | with open(bot_name + "_losses.txt", "a") as myfile: 143 | myfile.write(str(value_loss + action_loss) + '\n') 144 | with open(bot_name + '_rewards.txt', 'a') as myfile: 145 | myfile.write(str(timesteps) + '\n') 146 | 147 | def lower_lr(self): 148 | for param_group in self.ppo.actor_opt.param_groups: 149 | param_group['lr'] = param_group['lr'] * 0.5 150 | for param_group in self.ppo.critic_opt.param_groups: 151 | param_group['lr'] = param_group['lr'] * 0.5 152 | 153 | def reset(self): 154 | self.replay_buffer.clear() 155 | 156 | def deepen_networks(self): 157 | pass 158 | 159 | def save(self, fn='last'): 160 | checkpoint = dict() 161 | checkpoint['actor'] = self.action_network.state_dict() 162 | checkpoint['value'] = self.value_network.state_dict() 163 | torch.save(checkpoint, fn+self.bot_name+'.pth.tar') 164 | 165 | def load(self, fn='last'): 166 | fn = fn+self.bot_name+'.pth.tar' 167 | model_checkpoint = torch.load(fn, map_location='cpu') 168 | actor_data = model_checkpoint['actor'] 169 | value_data = model_checkpoint['value'] 170 | self.action_network.load_state_dict(actor_data) 171 | self.value_network.load_state_dict(value_data) 172 | 173 | def __getstate__(self): 174 | return { 175 | 'action_network': self.action_network, 176 | 'value_network': self.value_network, 177 | 'ppo': self.ppo, 178 | 'actor_opt': self.actor_opt, 179 | 'value_opt': self.value_opt 180 | } 181 | 182 | def __setstate__(self, state): 183 | self.action_network = copy.deepcopy(state['action_network']) 184 | self.value_network = copy.deepcopy(state['value_network']) 185 | self.ppo = copy.deepcopy(state['ppo']) 186 | self.actor_opt = copy.deepcopy(state['actor_opt']) 187 | self.value_opt = copy.deepcopy(state['value_opt']) 188 | 189 | def duplicate(self): 190 | new_agent = LSTMNet() 191 | new_agent.__setstate__(self.__getstate__()) 192 | return new_agent 193 | -------------------------------------------------------------------------------- /runfiles/gym_runner.py: -------------------------------------------------------------------------------- 1 | # Created by Andrew Silva, andrew.silva@gatech.edu 2 | import gym 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | import pandas as pd 6 | import sys 7 | import torch 8 | sys.path.insert(0, '../') 9 | from agents.prolonet_agent import DeepProLoNet 10 | from agents.non_deep_prolonet_agent import ShallowProLoNet 11 | from agents.random_prolonet_agent import RandomProLoNet 12 | from agents.lstm_agent import LSTMNet 13 | from agents.baseline_agent import FCNet 14 | import random 15 | import torch.multiprocessing as mp 16 | import argparse 17 | 18 | 19 | def run_episode(q, agent_in, ENV_NAME): 20 | agent = agent_in.duplicate() 21 | if ENV_NAME == 'lunar': 22 | env = gym.make('LunarLander-v2') 23 | elif ENV_NAME == 'cart': 24 | env = gym.make('CartPole-v1') 25 | else: 26 | raise Exception('No valid environment selected') 27 | 28 | state = env.reset() # Reset environment and record the starting state 29 | done = False 30 | 31 | for timestep in range(1000): 32 | action = agent.get_action(state) 33 | # Step through environment using chosen action 34 | state, reward, done, _ = env.step(action) 35 | 36 | # Save reward 37 | agent.save_reward(reward) 38 | if done: 39 | break 40 | R = 0 41 | rewards = [] 42 | all_rewards = agent.replay_buffer.rewards_list 43 | 44 | reward_sum = sum(all_rewards) 45 | all_values = agent.replay_buffer.value_list 46 | deeper_all_values = agent.replay_buffer.deeper_value_list 47 | # Discount future rewards back to the present using gamma 48 | advantages = [] 49 | deeper_advantages = [] 50 | 51 | for r, v, d_v in zip(all_rewards[::-1], all_values[::-1], deeper_all_values[::-1]): 52 | R = r + 0.99 * R 53 | rewards.insert(0, R) 54 | advantages.insert(0, R - v) 55 | if d_v is not None: 56 | deeper_advantages.insert(0, R - d_v) 57 | advantages = torch.Tensor(advantages) 58 | rewards = torch.Tensor(rewards) 59 | 60 | if len(deeper_advantages) > 0: 61 | deeper_advantages = torch.Tensor(deeper_advantages) 62 | deeper_advantages = (deeper_advantages - deeper_advantages.mean()) / ( 63 | deeper_advantages.std() + np.finfo(np.float32).eps) 64 | agent.replay_buffer.deeper_advantage_list = deeper_advantages.detach().clone().cpu().numpy().tolist() 65 | else: 66 | agent.replay_buffer.deeper_advantage_list = [None] * len(all_rewards) 67 | # Scale rewards .abs() 68 | rewards = (rewards - rewards.mean()) / (rewards.std() + np.finfo(np.float32).eps) 69 | advantages = (advantages - advantages.mean()) / (advantages.std() + np.finfo(np.float32).eps) 70 | 71 | agent.replay_buffer.rewards_list = rewards.detach().clone().cpu().numpy().tolist() 72 | agent.replay_buffer.advantage_list = advantages.detach().clone().cpu().numpy().tolist() 73 | if q is not None: 74 | try: 75 | q.put([reward_sum, agent.replay_buffer.__getstate__()]) 76 | except RuntimeError as e: 77 | print(e) 78 | return [reward_sum, agent.replay_buffer.__getstate__()] 79 | return [reward_sum, agent.replay_buffer.__getstate__()] 80 | 81 | 82 | def main(episodes, agent, num_processes, ENV_NAME): 83 | running_reward_array = [] 84 | for episode in range(episodes): 85 | master_reward = 0 86 | reward, running_reward = 0, 0 87 | processes = [] 88 | q = mp.Manager().Queue() 89 | for proc in range(num_processes): 90 | p = mp.Process(target=run_episode, args=(q, agent, ENV_NAME)) 91 | p.start() 92 | processes.append(p) 93 | for p in processes: 94 | p.join() 95 | while not q.empty(): 96 | fake_out = q.get() 97 | master_reward += fake_out[0] 98 | running_reward_array.append(fake_out[0]) 99 | agent.replay_buffer.extend(fake_out[1]) 100 | 101 | tuple_out = run_episode(None, agent, ENV_NAME) 102 | master_reward += tuple_out[0] 103 | running_reward_array.append(tuple_out[0]) 104 | agent.replay_buffer.extend(tuple_out[1]) 105 | reward = master_reward / float(num_processes+1) 106 | agent.end_episode(reward, num_processes) 107 | 108 | running_reward = sum(running_reward_array[-100:]) / float(min(100.0, len(running_reward_array))) 109 | print(episode) 110 | if episode % 50 == 0: 111 | print(f'Episode {episode} Last Reward: {reward} Average Reward: {running_reward}') 112 | if episode % 500 == 0: 113 | agent.save('../models/'+str(episode)+'th') 114 | return running_reward_array 115 | 116 | 117 | if __name__ == "__main__": 118 | parser = argparse.ArgumentParser() 119 | parser.add_argument("-a", "--agent_type", help="architecture of agent to run", type=str, default='fc') 120 | parser.add_argument("-adv", "--adversary", 121 | help="for prolonet, init as adversarial? true for yes, false for no", 122 | type=bool, default=False) 123 | parser.add_argument("-s", "--sl_init", help="sl to rl for fc net?", type=bool, default=False) 124 | parser.add_argument("-dm", "--deepen_method", help="how to deepen?", type=str, default='random') 125 | parser.add_argument("-dc", "--deepen_criteria", help="when to deepen?", type=str, default='entropy') 126 | parser.add_argument("-e", "--episodes", help="how many episodes", type=int, default=1000) 127 | parser.add_argument("-p", "--processes", help="how many processes?", type=int, default=1) 128 | parser.add_argument("-env", "--env_type", help="environment to run on", type=str, default='cart') 129 | 130 | args = parser.parse_args() 131 | AGENT_TYPE = args.agent_type # 'shallow_prolo', 'prolo', 'random', 'fc', 'lstm' 132 | ADVERSARIAL = args.adversary # Adversarial prolo, applies for AGENT_TYPE=='shallow_prolo' 133 | SL_INIT = args.sl_init # SL->RL fc, applies only for AGENT_TYPE=='fc' 134 | DEEPEN_METHOD = args.deepen_method # 'random', 'fc', 'parent', method for deepening, only applies for AGENT_TYPE=='prolo' 135 | DEEPEN_CRITERIA = args.deepen_criteria # 'entropy', 'num', 'value', criteria for when to deepen. AGENT_TYPE=='prolo' only 136 | NUM_EPS = args.episodes 137 | NUM_PROCS = args.processes 138 | ENV_TYPE = args.env_type 139 | for NUM_PROCS in [NUM_PROCS]: 140 | if ENV_TYPE == 'lunar': 141 | init_env = gym.make('LunarLander-v2') 142 | dim_in = init_env.observation_space.shape[0] 143 | dim_out = init_env.action_space.n 144 | elif ENV_TYPE == 'cart': 145 | init_env = gym.make('CartPole-v1') 146 | dim_in = init_env.observation_space.shape[0] 147 | dim_out = init_env.action_space.n 148 | else: 149 | raise Exception('No valid environment selected') 150 | 151 | print(f"Agent {AGENT_TYPE} on {ENV_TYPE} with {NUM_PROCS} runners") 152 | mp.set_start_method('spawn') 153 | 154 | for i in range(5): 155 | torch.manual_seed(0) 156 | np.random.seed(0) 157 | random.seed(0) 158 | bot_name = AGENT_TYPE + ENV_TYPE 159 | 160 | if AGENT_TYPE == 'prolo': 161 | policy_agent = DeepProLoNet(distribution='one_hot', 162 | bot_name=bot_name, 163 | input_dim=dim_in, 164 | output_dim=dim_out, 165 | deepen_method=DEEPEN_METHOD, 166 | deepen_criteria=DEEPEN_CRITERIA) 167 | elif AGENT_TYPE == 'fc': 168 | policy_agent = FCNet(input_dim=dim_in, 169 | bot_name=bot_name, 170 | output_dim=dim_out, 171 | sl_init=SL_INIT) 172 | elif AGENT_TYPE == 'random': 173 | policy_agent = RandomProLoNet(input_dim=dim_in, 174 | bot_name=bot_name, 175 | output_dim=dim_out) 176 | elif AGENT_TYPE == 'lstm': 177 | policy_agent = LSTMNet(input_dim=dim_in, 178 | bot_name=bot_name, 179 | output_dim=dim_out) 180 | elif AGENT_TYPE == 'shallow_prolo': 181 | policy_agent = ShallowProLoNet(distribution='one_hot', 182 | input_dim=dim_in, 183 | bot_name=bot_name, 184 | output_dim=dim_out, 185 | adversarial=ADVERSARIAL) 186 | else: 187 | raise Exception('No valid network selected') 188 | 189 | if AGENT_TYPE == 'fc' and SL_INIT: 190 | NUM_EPS += policy_agent.action_loss_threshold 191 | num_procs = NUM_PROCS 192 | reward_array = main(NUM_EPS, policy_agent, num_procs, ENV_TYPE) 193 | -------------------------------------------------------------------------------- /agents/heuristic_agent.py: -------------------------------------------------------------------------------- 1 | # Created by Andrew Silva, andrew.silva@gatech.edu 2 | import random 3 | 4 | 5 | class CartPoleHeuristic: 6 | def __init__(self): 7 | pass 8 | 9 | def get_action(self, observation): 10 | action = random.choice([0, 1]) 11 | if observation[0] > -1: 12 | if observation[0] < 1: 13 | if observation[2] < 0: 14 | action = 0 15 | else: 16 | action = 1 17 | else: 18 | if observation[2] < 0: 19 | action = 0 20 | else: 21 | if observation[1] > 0: 22 | if observation[3] < 0: 23 | action = 0 24 | else: 25 | action = 1 26 | else: 27 | if observation[2] < 0: 28 | action = 0 29 | else: 30 | action = 1 31 | else: 32 | if observation[2] < 0: 33 | if observation[1] < 0: 34 | if observation[3] > 0: 35 | action = 1 36 | else: 37 | action = 0 38 | else: 39 | if observation[2] < 0: 40 | action = 0 41 | else: 42 | action = 1 43 | return action 44 | 45 | def end_episode(self, timesteps=None): 46 | pass 47 | 48 | def save_reward(self, reward=None): 49 | pass 50 | 51 | def reset(self): 52 | pass 53 | 54 | 55 | class LunarHeuristic: 56 | def __init__(self): 57 | pass 58 | 59 | def get_action(self, observation): 60 | if observation[1] < 1.1: # 0 61 | if observation[3] < 0.2: # 1 62 | if observation[5] < 0: # 3 63 | if (observation[6] + observation[7]) > 1.2: # 7 64 | action = 0 65 | else: 66 | if observation[4] > -0.1: # 11 67 | action = 2 68 | else: 69 | action = 1 70 | else: 71 | action = 3 72 | else: 73 | if (observation[6] + observation[7]) > 1.2: # 4 74 | action = 0 75 | else: 76 | if observation[0] > 0.2: # 8 77 | action = 1 78 | else: 79 | if observation[0] < -0.2: # 12 80 | action = 3 81 | else: 82 | action = 0 83 | else: 84 | if observation[5] > 0.1: # 2 85 | if observation[5] < -0.1: # 5 86 | if (observation[6] + observation[7]) > 1.2: # 9 87 | action = 0 88 | else: 89 | action = 1 90 | else: 91 | if observation[0] > 0.2: # 10 92 | action = 1 93 | else: 94 | if observation[0] < -0.2: # 13 95 | action = 3 96 | else: 97 | action = 0 98 | else: 99 | if (observation[6] + observation[7]) > 1.2: # 6 100 | action = 0 101 | else: 102 | action = 3 103 | return action 104 | 105 | def end_episode(self, timesteps=None): 106 | pass 107 | 108 | def save_reward(self, reward=None): 109 | pass 110 | 111 | def reset(self): 112 | pass 113 | 114 | 115 | class StarCraftMacroHeuristic: 116 | def __init__(self): 117 | from ProLoNetICML.opt_helpers import replay_buffer 118 | self.replay_buffer = replay_buffer.ReplayBufferSingleAgent() 119 | pass 120 | 121 | def get_action(self, observation): 122 | if observation[10] + observation[12] > 12: # Attackers > 12 123 | if sum(observation[45:65])+sum(observation[82:99])+sum(observation[118:139]) > 4: # enemy units 124 | action = 41 125 | else: 126 | if sum(observation[65:82])+sum(observation[99:118])+sum(observation[139:157]) > 0: # enemy buildings 127 | action = 39 128 | else: 129 | action = 42 130 | else: 131 | if observation[4] > 0.5: # idle workers 132 | action = 40 133 | else: 134 | if observation[3]-observation[2] < 4: # low supply 135 | action = 1 136 | else: 137 | if observation[9]+observation[157] < 15: # few probes 138 | action = 16 139 | else: 140 | if observation[30]+observation[178] > 0: # no assimilators 141 | if observation[38]+observation[186] > 1.5: # stargates 1.5 142 | if observation[22]+observation[170] > 7: # voidrays 143 | action = 39 144 | else: 145 | action = 29 146 | else: 147 | if observation[38] + observation[186] > 0.5: # stargates 0.5 148 | action = 0 149 | else: 150 | action = 10 151 | else: 152 | if observation[31]+observation[179] > 0.5: # gateway > 0.5 153 | if observation[10]+observation[158] > 6: 154 | if observation[34]+observation[182] > 0.5: 155 | action = 2 156 | else: 157 | action = 6 158 | else: 159 | action = 17 160 | else: 161 | action = 3 162 | return action 163 | 164 | def end_episode(self, total_reward=None, num_procs=None): 165 | pass 166 | 167 | def save(self, fn=None): 168 | pass 169 | 170 | def save_reward(self, reward=None): 171 | pass 172 | 173 | def reset(self): 174 | pass 175 | 176 | def duplicate(self): 177 | return self 178 | 179 | 180 | class StarCraftMicroHeuristic: 181 | def __init__(self): 182 | from ProLoNetICML.opt_helpers import replay_buffer 183 | self.replay_buffer = replay_buffer.ReplayBufferSingleAgent() 184 | pass 185 | 186 | def get_action(self, observation): 187 | if observation[0] - observation[4] > 3.5: 188 | action = 3 189 | else: 190 | if observation[4] - observation[0] > 3.5: 191 | action = 1 192 | else: 193 | if observation[1] - observation[5] > 3.5: 194 | action = 2 195 | else: 196 | if observation[5] - observation[1] > 3.5: 197 | action = 0 198 | else: 199 | if observation[14] > 0: 200 | if observation[0] - observation[12] > 5: 201 | action = 3 202 | else: 203 | if observation[12] - observation[0] > 5: 204 | action = 1 205 | else: 206 | if observation[1] - observation[13] > 5: 207 | action = 2 208 | else: 209 | if observation[13] - observation[1] > 5: 210 | action = 0 211 | else: 212 | action = 4 213 | else: 214 | if observation[1] > 30: 215 | if observation[0] > 20: 216 | action = 2 217 | else: 218 | if observation[0] > 40: 219 | action = 0 220 | else: 221 | action = 3 222 | else: 223 | if observation[1] > 18: 224 | action = 2 225 | else: 226 | if observation[0] > 40: 227 | action = 1 228 | else: 229 | action = 0 230 | return action 231 | 232 | def end_episode(self, total_reward=None, num_procs=None): 233 | pass 234 | 235 | def save(self, fn=None): 236 | pass 237 | 238 | def save_reward(self, reward=None): 239 | pass 240 | 241 | def reset(self): 242 | pass 243 | 244 | def duplicate(self): 245 | return self 246 | -------------------------------------------------------------------------------- /opt_helpers/ppo_update.py: -------------------------------------------------------------------------------- 1 | # Created by Andrew Silva, andrew.silva@gatech.edu 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | import torch.optim as optim 6 | from torch.distributions import Categorical 7 | import numpy as np 8 | 9 | 10 | class PPO: 11 | def __init__(self, actor_critic_arr, two_nets=True): 12 | 13 | lr = 1e-3 14 | eps = 1e-5 15 | self.clip_param = 0.2 16 | self.ppo_epoch = 8 17 | self.num_mini_batch = 4 18 | self.value_loss_coef = 0.05 19 | self.entropy_coef = 0.01 20 | self.max_grad_norm = 0.5 21 | 22 | if two_nets: 23 | self.actor = actor_critic_arr[0] 24 | self.critic = actor_critic_arr[1] 25 | if self.actor.input_dim > 100: 26 | self.actor_opt = optim.RMSprop(self.actor.parameters(), lr=1e-4) 27 | self.critic_opt = optim.RMSprop(self.critic.parameters(), lr=1e-4) 28 | elif self.actor.input_dim >= 8: 29 | self.actor_opt = optim.RMSprop(self.actor.parameters(), lr=1e-3) 30 | self.critic_opt = optim.RMSprop(self.critic.parameters(), lr=1e-3) 31 | else: 32 | self.actor_opt = optim.RMSprop(self.actor.parameters(), lr=1e-2) 33 | self.critic_opt = optim.RMSprop(self.critic.parameters(), lr=1e-2) 34 | else: 35 | self.actor = actor_critic_arr 36 | self.actor_opt = optim.Adam(self.actor.parameters(), lr=lr, eps=eps) 37 | 38 | self.two_nets = two_nets 39 | self.epoch_counter = 0 40 | 41 | def cartpole_update(self, rollouts, agent_in, go_deeper=False): 42 | if self.actor.input_dim < 10: 43 | batch_size = max(rollouts.step // 32, 1) 44 | num_iters = rollouts.step // batch_size 45 | else: 46 | num_iters = 8 47 | batch_size = 4 48 | total_action_loss = torch.Tensor([0]) 49 | total_value_loss = torch.Tensor([0]) 50 | for iteration in range(num_iters): 51 | total_action_loss = torch.Tensor([0]) 52 | total_value_loss = torch.Tensor([0]) 53 | if go_deeper: 54 | deep_total_action_loss = torch.Tensor([0]) 55 | deep_total_value_loss = torch.Tensor([0]) 56 | for b in range(batch_size): 57 | sample = rollouts.sample() 58 | if not sample: 59 | break 60 | state = sample['state'] 61 | action_probs = sample['action_prob'] 62 | adv_targ = torch.Tensor([sample['advantage']]) 63 | reward = sample['reward'] 64 | old_action_probs = sample['full_prob_vector'] 65 | if np.isnan(adv_targ) or np.isnan(reward) or True in np.isnan(old_action_probs): 66 | continue 67 | action_taken = sample['action_taken'] 68 | hidden_state = sample['hidden_state'] 69 | if hidden_state is not None: 70 | new_action_probs, _ = self.actor(*state, hidden_state[0]) 71 | new_value, _ = self.critic(*state, hidden_state[1]) 72 | else: 73 | new_action_probs = self.actor(*state) 74 | new_value = self.critic(*state) 75 | 76 | if go_deeper: 77 | deep_action_probs = sample['deeper_action_prob'] 78 | deep_adv = torch.Tensor([sample['deeper_advantage']]) 79 | deeper_old_probs = sample['deeper_full_prob_vector'] 80 | 81 | new_deep_probs = agent_in.deeper_action_network(*state) 82 | new_deep_vals = agent_in.deeper_value_network(*state) 83 | deep_dist = Categorical(new_deep_probs) 84 | deeper_probs = deep_dist.log_prob(action_taken) 85 | deeper_val = new_deep_vals[action_taken.item()] 86 | deeper_entropy = deep_dist.entropy().mean() * self.entropy_coef 87 | # deep_ratio = torch.div(deeper_probs, deep_action_probs) 88 | deep_ratio = torch.nn.functional.kl_div(new_deep_probs, deeper_old_probs, reduction='batchmean') 89 | deep_surr1 = deep_ratio.mul(deep_adv).mul(deeper_probs) 90 | deep_surr2 = torch.clamp(deep_ratio, 1.0 - self.clip_param, 91 | 1.0 + self.clip_param).pow(-1).mul(deep_adv).mul(deeper_probs) 92 | deep_action_loss = -torch.min(deep_surr1, deep_surr2).mean() 93 | deep_total_action_loss = deep_total_action_loss + deep_action_loss - deeper_entropy 94 | 95 | deeper_val = deeper_val.view(-1, 1) 96 | copy_reward = torch.FloatTensor([reward]).view(-1, 1) 97 | deeper_value_loss = F.mse_loss(copy_reward, deeper_val) 98 | 99 | deep_total_value_loss = deep_total_value_loss + deeper_value_loss 100 | 101 | update_m = Categorical(new_action_probs) 102 | update_log_probs = update_m.log_prob(action_taken) 103 | new_value = new_value[action_taken.item()] 104 | entropy = update_m.entropy().mean() * self.entropy_coef 105 | # ratio = torch.div(update_log_probs, action_probs) 106 | ratio = torch.nn.functional.kl_div(new_action_probs, old_action_probs, reduction='batchmean') 107 | clipped = torch.clamp(ratio, 1.0 - self.clip_param, 108 | 1.0 + self.clip_param).mul(adv_targ).mul(update_log_probs) 109 | ratio = ratio.mul(adv_targ).mul(update_log_probs) 110 | action_loss = -torch.min(ratio, clipped).mean() 111 | new_value = new_value.view(-1, 1) 112 | reward = torch.FloatTensor([reward]).view(-1, 1) 113 | value_loss = F.mse_loss(reward, new_value) 114 | 115 | total_value_loss = total_value_loss + value_loss 116 | total_action_loss = total_action_loss + action_loss - entropy 117 | if total_value_loss != 0: 118 | nn.utils.clip_grad_norm_(self.critic.parameters(), self.max_grad_norm) 119 | self.critic_opt.zero_grad() 120 | total_value_loss.backward() 121 | self.critic_opt.step() 122 | if total_action_loss != 0: 123 | nn.utils.clip_grad_norm_(self.actor.parameters(), self.max_grad_norm) 124 | self.actor_opt.zero_grad() 125 | total_action_loss.backward() 126 | self.actor_opt.step() 127 | if go_deeper: 128 | if deep_total_value_loss != 0: 129 | nn.utils.clip_grad_norm_(agent_in.deeper_value_network.parameters(), self.max_grad_norm) 130 | agent_in.deeper_value_opt.zero_grad() 131 | deep_total_value_loss.backward() 132 | agent_in.deeper_value_opt.step() 133 | if deep_total_action_loss != 0: 134 | nn.utils.clip_grad_norm_(agent_in.deeper_action_network.parameters(), self.max_grad_norm) 135 | agent_in.deeper_actor_opt.zero_grad() 136 | deep_total_action_loss.backward() 137 | agent_in.deeper_actor_opt.step() 138 | agent_in.deepen_networks() 139 | agent_in.reset() 140 | return total_action_loss.item(), total_value_loss.item() 141 | 142 | def sl_updates(self, rollouts, agent_in, heuristic_teacher): 143 | if self.actor.input_dim < 10: 144 | batch_size = max(rollouts.step // 32, 1) 145 | num_iters = rollouts.step // batch_size 146 | else: 147 | num_iters = 8 148 | batch_size = 4 149 | aggregate_actor_loss = 0 150 | for iteration in range(num_iters): 151 | total_action_loss = torch.Tensor([0]) 152 | total_value_loss = torch.Tensor([0]) 153 | for b in range(batch_size): 154 | sample = rollouts.sample() 155 | if not sample: 156 | break 157 | state = sample['state'] 158 | reward = sample['reward'] 159 | if np.isnan(reward): 160 | continue 161 | new_action_probs = self.actor(*state).view(1, -1) 162 | new_value = self.critic(*state) 163 | label = torch.LongTensor([heuristic_teacher.get_action(state[0].detach().clone().data.cpu().numpy()[0])]) 164 | action_loss = torch.nn.functional.cross_entropy(new_action_probs, label) 165 | new_value = new_value.view(-1, 1) 166 | reward = torch.Tensor([reward]).view(-1, 1) 167 | value_loss = F.mse_loss(reward, new_value) 168 | 169 | total_value_loss = total_value_loss + value_loss 170 | total_action_loss = total_action_loss + action_loss 171 | if total_value_loss != 0: 172 | self.critic_opt.zero_grad() 173 | total_value_loss.backward() 174 | self.critic_opt.step() 175 | if total_action_loss != 0: 176 | self.actor_opt.zero_grad() 177 | total_action_loss.backward() 178 | self.actor_opt.step() 179 | aggregate_actor_loss += total_action_loss.item() 180 | aggregate_actor_loss /= float(num_iters*batch_size) 181 | agent_in.reset() 182 | return aggregate_actor_loss 183 | -------------------------------------------------------------------------------- /agents/prolonet_agent.py: -------------------------------------------------------------------------------- 1 | # Created by Andrew Silva, andrew.silva@gatech.edu 2 | import torch 3 | from torch.distributions import Categorical 4 | from opt_helpers import replay_buffer, ppo_update 5 | from agents.prolonet_helpers import init_cart_nets, add_level, init_lander_nets, swap_in_node, \ 6 | save_prolonet, load_prolonet, init_sc_nets, init_micro_net 7 | import copy 8 | import os 9 | 10 | 11 | class DeepProLoNet: 12 | def __init__(self, 13 | distribution='one_hot', 14 | bot_name='ProLoNet', 15 | input_dim=4, 16 | output_dim=2, 17 | deepen_method='random', 18 | deepen_criteria='entropy'): 19 | self.replay_buffer = replay_buffer.ReplayBufferSingleAgent() 20 | self.bot_name = bot_name 21 | 22 | if input_dim == 4 and output_dim == 2: 23 | self.action_network, self.value_network = init_cart_nets(distribution) 24 | elif input_dim == 8 and output_dim == 4: 25 | self.action_network, self.value_network = init_lander_nets(distribution) 26 | elif input_dim == 194 and output_dim == 44: 27 | self.action_network, self.value_network = init_sc_nets(distribution) 28 | elif input_dim == 32 and output_dim == 10: 29 | self.action_network, self.value_network = init_micro_net(distribution) 30 | 31 | self.deepen_method = deepen_method 32 | self.deeper_action_network = add_level(self.action_network, method=deepen_method) 33 | self.deeper_value_network = add_level(self.value_network, method=deepen_method) 34 | 35 | self.ppo = ppo_update.PPO([self.action_network, self.value_network], two_nets=True) 36 | self.actor_opt = torch.optim.RMSprop(self.action_network.parameters()) 37 | self.value_opt = torch.optim.RMSprop(self.value_network.parameters()) 38 | 39 | self.deeper_actor_opt = torch.optim.RMSprop(self.deeper_action_network.parameters()) 40 | self.deeper_value_opt = torch.optim.RMSprop(self.deeper_value_network.parameters()) 41 | 42 | self.last_state = [0, 0, 0, 0] 43 | self.last_action = 0 44 | self.last_action_probs = torch.Tensor([0]) 45 | self.last_value_pred = torch.Tensor([[0, 0]]) 46 | self.last_deep_action_probs = torch.Tensor([0]) 47 | self.last_deep_value_pred = torch.Tensor([[0, 0]]) 48 | self.full_probs = None 49 | self.deeper_full_probs = None 50 | self.reward_history = [] 51 | self.num_steps = 0 52 | self.deepen_criteria = deepen_criteria 53 | self.deepen_threshold = 350 54 | self.times_deepened = 0 55 | 56 | def get_action(self, observation): 57 | with torch.no_grad(): 58 | obs = torch.Tensor(observation) 59 | obs = obs.view(1, -1) 60 | self.last_state = obs 61 | probs = self.action_network(obs) 62 | value_pred = self.value_network(obs) 63 | probs = probs.view(-1) 64 | self.full_probs = probs 65 | 66 | if self.action_network.input_dim > 10: 67 | probs, inds = torch.topk(probs, 3) 68 | m = Categorical(probs) 69 | action = m.sample() 70 | log_probs = m.log_prob(action) 71 | self.last_action_probs = log_probs 72 | self.last_value_pred = value_pred 73 | 74 | deeper_obs = torch.Tensor(observation) 75 | deeper_obs = deeper_obs.view(1, -1) 76 | deeper_probs = self.deeper_action_network(deeper_obs) 77 | deeper_value_pred = self.deeper_value_network(deeper_obs) 78 | deeper_probs = deeper_probs.view(-1) 79 | self.deeper_full_probs = deeper_probs 80 | if self.action_network.input_dim > 10: 81 | deeper_probs, _ = torch.topk(probs, 3) 82 | deep_m = Categorical(deeper_probs) 83 | deep_log_probs = deep_m.log_prob(action) 84 | self.last_deep_action_probs = deep_log_probs 85 | self.last_deep_value_pred = deeper_value_pred 86 | if self.action_network.input_dim > 10: 87 | self.last_action = inds[action] 88 | else: 89 | self.last_action = action 90 | if self.action_network.input_dim > 10: 91 | action = inds[action].item() 92 | else: 93 | action = action.item() 94 | return action 95 | 96 | def save_reward(self, reward): 97 | self.replay_buffer.insert(obs=[self.last_state], 98 | action_log_probs=self.last_action_probs, 99 | value_preds=self.last_value_pred[self.last_action.item()], 100 | deeper_action_log_probs=self.last_deep_action_probs, 101 | deeper_value_pred=self.last_deep_value_pred[self.last_action.item()], 102 | last_action=self.last_action, 103 | full_probs_vector=self.full_probs, 104 | deeper_full_probs_vector=self.deeper_full_probs, 105 | rewards=reward) 106 | return True 107 | 108 | def end_episode(self, timesteps, num_processes): 109 | value_loss, action_loss = self.ppo.cartpole_update(self.replay_buffer, self, go_deeper=True) 110 | self.num_steps += 1 111 | bot_name = '../txts/' + self.bot_name + str(num_processes) + '_processes_' + \ 112 | self.deepen_criteria+'_deepen_'+self.deepen_method 113 | with open(bot_name + "_losses.txt", "a") as myfile: 114 | myfile.write(str(value_loss + action_loss) + '\n') 115 | with open(bot_name + '_rewards.txt', 'a') as myfile: 116 | myfile.write(str(timesteps) + '\n') 117 | 118 | def lower_lr(self): 119 | for param_group in self.ppo.actor_opt.param_groups: 120 | param_group['lr'] = param_group['lr'] * 0.5 121 | for param_group in self.ppo.critic_opt.param_groups: 122 | param_group['lr'] = param_group['lr'] * 0.5 123 | 124 | def reset(self): 125 | self.replay_buffer.clear() 126 | 127 | def save(self, fn='last'): 128 | act_fn = fn + self.bot_name + '_actor_' + '.pth.tar' 129 | val_fn = fn + self.bot_name + '_critic_' + '.pth.tar' 130 | 131 | deep_act_fn = fn + self.bot_name + '_deep_actor_' + '.pth.tar' 132 | deep_val_fn = fn + self.bot_name + '_deep_critic_' + '.pth.tar' 133 | save_prolonet(act_fn, self.action_network) 134 | save_prolonet(val_fn, self.value_network) 135 | save_prolonet(deep_act_fn, self.deeper_action_network) 136 | save_prolonet(deep_val_fn, self.deeper_value_network) 137 | 138 | def load(self, fn='last'): 139 | act_fn = fn + self.bot_name + '_actor_' + '.pth.tar' 140 | val_fn = fn + self.bot_name + '_critic_' + '.pth.tar' 141 | 142 | deep_act_fn = fn + self.bot_name + '_deep_actor_' + '.pth.tar' 143 | deep_val_fn = fn + self.bot_name + '_deep_critic_' + '.pth.tar' 144 | if os.path.exists(act_fn): 145 | self.action_network = load_prolonet(act_fn) 146 | self.value_network = load_prolonet(val_fn) 147 | self.deeper_action_network = load_prolonet(deep_act_fn) 148 | self.deeper_value_network = load_prolonet(deep_val_fn) 149 | 150 | def deepen_networks(self): 151 | self.entropy_leaf_checks() 152 | 153 | def entropy_leaf_checks(self): 154 | leaf_max = torch.nn.Softmax(dim=0) 155 | new_action_network = copy.deepcopy(self.action_network) 156 | changes_made = [] 157 | for leaf_index in range(len(self.action_network.action_probs)): 158 | existing_leaf = leaf_max(self.action_network.action_probs[leaf_index]) 159 | new_leaf_1 = leaf_max(self.deeper_action_network.action_probs[2*leaf_index+1]) 160 | new_leaf_2 = leaf_max(self.deeper_action_network.action_probs[2*leaf_index]) 161 | existing_entropy = Categorical(existing_leaf).entropy().item() 162 | new_entropy = Categorical(new_leaf_1).entropy().item() + \ 163 | Categorical(new_leaf_2).entropy().item() 164 | 165 | if new_entropy+0.1 <= existing_entropy: 166 | with open(self.bot_name + '_entropy_splits.txt', 'a') as myfile: 167 | myfile.write('Split at ' + str(self.num_steps) + ' steps' + ': \n') 168 | myfile.write('Leaf: ' + str(leaf_index) + '\n') 169 | myfile.write('Prior Probs: ' + str(self.action_network.action_probs[leaf_index]) + '\n') 170 | myfile.write('New Probs 1: ' + str(self.deeper_action_network.action_probs[leaf_index*2]) + '\n') 171 | myfile.write('New Probs 2: ' + str(self.deeper_action_network.action_probs[leaf_index*2+1]) + '\n') 172 | 173 | new_action_network = swap_in_node(new_action_network, self.deeper_action_network, leaf_index) 174 | changes_made.append(leaf_index) 175 | if len(changes_made) > 0: 176 | self.action_network = new_action_network 177 | self.actor_opt = torch.optim.RMSprop(self.action_network.parameters(), lr=1e-3) 178 | self.ppo.actor = self.action_network 179 | self.ppo.actor_opt = self.actor_opt 180 | for change in changes_made[::-1]: 181 | self.deeper_action_network = swap_in_node(self.deeper_action_network, None, change*2+1) 182 | self.deeper_action_network = swap_in_node(self.deeper_action_network, None, change*2) 183 | self.deeper_actor_opt = torch.optim.RMSprop(self.deeper_action_network.parameters(), lr=1e-3) 184 | 185 | def __getstate__(self): 186 | return { 187 | 'action_network': self.action_network, 188 | 'value_network': self.value_network, 189 | 'ppo': self.ppo, 190 | 'deeper_action_network': self.deeper_action_network, 191 | 'deeper_value_network': self.deeper_value_network, 192 | 'actor_opt': self.actor_opt, 193 | 'value_opt': self.value_opt, 194 | 'deeper_actor_opt': self.deeper_actor_opt, 195 | 'deeper_value_opt': self.deeper_value_opt 196 | } 197 | 198 | def __setstate__(self, state): 199 | self.action_network = copy.deepcopy(state['action_network']) 200 | self.value_network = copy.deepcopy(state['value_network']) 201 | self.ppo = copy.deepcopy(state['ppo']) 202 | self.deeper_action_network = copy.deepcopy(state['deeper_action_network']) 203 | self.deeper_value_network = copy.deepcopy(state['deeper_value_network']) 204 | self.actor_opt = copy.deepcopy(state['actor_opt']) 205 | self.value_opt = copy.deepcopy(state['value_opt']) 206 | self.deeper_value_opt = copy.deepcopy(state['deeper_value_opt']) 207 | self.deeper_actor_opt = copy.deepcopy(state['deeper_actor_opt']) 208 | 209 | def duplicate(self): 210 | new_agent = DeepProLoNet() 211 | new_agent.__setstate__(self.__getstate__()) 212 | return new_agent 213 | -------------------------------------------------------------------------------- /runfiles/minigame_runner.py: -------------------------------------------------------------------------------- 1 | # Created by Andrew Silva, andrew.silva@gatech.edu 2 | import sc2 3 | from sc2 import Race, Difficulty 4 | import os 5 | import sys 6 | from sc2.constants import * 7 | from sc2.position import Pointlike, Point2 8 | from sc2.player import Bot, Computer 9 | from sc2.unit import Unit as sc2Unit 10 | sys.path.insert(0, os.path.abspath('../')) 11 | import torch 12 | from agents.prolonet_agent import DeepProLoNet 13 | from agents.non_deep_prolonet_agent import ShallowProLoNet 14 | from agents.random_prolonet_agent import RandomProLoNet 15 | from agents.lstm_agent import LSTMNet 16 | from agents.baseline_agent import FCNet 17 | from runfiles import sc_helpers 18 | import numpy as np 19 | import torch.multiprocessing as mp 20 | import argparse 21 | 22 | DEBUG = False 23 | SUPER_DEBUG = False 24 | if SUPER_DEBUG: 25 | DEBUG = True 26 | 27 | FAILED_REWARD = -0.0 28 | SUCCESS_BUILD_REWARD = 1. 29 | SUCCESS_TRAIN_REWARD = 1. 30 | SUCCESS_SCOUT_REWARD = 1. 31 | SUCCESS_ATTACK_REWARD = 1. 32 | SUCCESS_MINING_REWARD = 1. 33 | 34 | 35 | def discount_reward(reward, value, deeper_value): 36 | R = 0 37 | rewards = [] 38 | all_rewards = reward 39 | reward_sum = sum(all_rewards) 40 | all_values = value 41 | deeper_all_values = deeper_value 42 | # Discount future rewards back to the present using gamma 43 | advantages = [] 44 | deeper_advantages = [] 45 | 46 | for r, v, d_v in zip(all_rewards[::-1], all_values[::-1], deeper_all_values[::-1]): 47 | R = r + 0.99 * R 48 | rewards.insert(0, R) 49 | advantages.insert(0, R - v) 50 | if d_v is not None: 51 | deeper_advantages.insert(0, R - d_v) 52 | advantages = torch.Tensor(advantages) 53 | rewards = torch.Tensor(rewards) 54 | 55 | if len(deeper_advantages) > 0: 56 | deeper_advantages = torch.Tensor(deeper_advantages) 57 | deeper_advantages = (deeper_advantages - deeper_advantages.mean()) / ( 58 | deeper_advantages.std() + torch.Tensor([np.finfo(np.float32).eps])) 59 | deeper_advantage_list = deeper_advantages.detach().clone().cpu().numpy().tolist() 60 | else: 61 | deeper_advantage_list = [None] * len(all_rewards) 62 | # Scale rewards 63 | rewards = (rewards - rewards.mean()) / (rewards.std() + torch.Tensor([np.finfo(np.float32).eps])) 64 | advantages = (advantages - advantages.mean()) / (advantages.std() + torch.Tensor([np.finfo(np.float32).eps])) 65 | rewards_list = rewards.detach().clone().cpu().numpy().tolist() 66 | advantage_list = advantages.detach().clone().cpu().numpy().tolist() 67 | return rewards_list, advantage_list, deeper_advantage_list 68 | 69 | 70 | class SC2MicroBot(sc2.BotAI): 71 | def __init__(self, rl_agent): 72 | super(SC2MicroBot, self).__init__() 73 | self.agent = rl_agent 74 | self.action_buffer = [] 75 | self.prev_state = None 76 | self.last_known_enemy_units = [] 77 | self.itercount = 0 78 | self.last_reward = 0 79 | self.my_tags = None 80 | self.agent_list = [] 81 | self.dead_agent_list = [] 82 | self.dead_index_mover = 0 83 | 84 | async def on_step(self, iteration): 85 | 86 | if iteration == 0: 87 | self.my_tags = [unit.tag for unit in self.units] 88 | for unit in self.units: 89 | self.agent_list.append(self.agent.duplicate()) 90 | else: 91 | self.last_reward = 0 92 | for unit in self.state.dead_units: 93 | if unit in self.my_tags: 94 | self.last_reward -= 1 95 | self.dead_agent_list.append(self.agent_list[self.my_tags.index(unit)]) 96 | del self.agent_list[self.my_tags.index(unit)] 97 | del self.my_tags[self.my_tags.index(unit)] 98 | self.dead_agent_list[-1].save_reward(self.last_reward) 99 | else: 100 | self.last_reward += 1 101 | if len(self.state.dead_units) > 0: 102 | for agent in self.agent_list: 103 | agent.save_reward(self.last_reward) 104 | # if iteration % 20 != 0: 105 | # return 106 | all_unit_data = [] 107 | for unit in self.units: 108 | all_unit_data.append(sc_helpers.get_unit_data(unit)) 109 | while len(all_unit_data) < 3: 110 | all_unit_data.append([-1, -1, -1, -1]) 111 | for unit, agent in zip(self.units, self.agent_list): 112 | my_index = self.units.index(unit) 113 | unit_data = all_unit_data[my_index] 114 | allied_data = all_unit_data[0:my_index] + all_unit_data[my_index+1:] 115 | nearest_enemies = sc_helpers.get_nearest_enemies(unit, self.known_enemy_units) 116 | unit_data = np.array(unit_data).reshape(-1) 117 | allied_data = np.array(allied_data).reshape(-1) 118 | nearest_enemies = nearest_enemies 119 | enemy_data = [] 120 | for enemy in nearest_enemies: 121 | enemy_data.extend(sc_helpers.get_unit_data(enemy)) 122 | enemy_data = np.array(enemy_data).reshape(-1) 123 | state_in = np.concatenate((unit_data, allied_data, enemy_data)) 124 | action = agent.get_action(state_in) 125 | await self.execute_unit_action(unit, action, nearest_enemies) 126 | try: 127 | await self.do_actions(self.action_buffer) 128 | except sc2.protocol.ProtocolError: 129 | print("Not in game?") 130 | self.action_buffer = [] 131 | return 132 | self.action_buffer = [] 133 | 134 | async def execute_unit_action(self, unit_in, action_in, nearest_enemies): 135 | if action_in < 4: 136 | await self.move_unit(unit_in, action_in) 137 | elif action_in < 9: 138 | await self.attack_nearest(unit_in, action_in, nearest_enemies) 139 | else: 140 | pass 141 | 142 | async def move_unit(self, unit_to_move, direction): 143 | current_pos = unit_to_move.position 144 | target_destination = current_pos 145 | if direction == 0: 146 | target_destination = [current_pos.x, current_pos.y + 5] 147 | elif direction == 1: 148 | target_destination = [current_pos.x + 5, current_pos.y] 149 | elif direction == 2: 150 | target_destination = [current_pos.x, current_pos.y - 5] 151 | elif direction == 3: 152 | target_destination = [current_pos.x - 5, current_pos.y] 153 | self.action_buffer.append(unit_to_move.move(Point2(Pointlike(target_destination)))) 154 | 155 | async def attack_nearest(self, unit_to_attack, action_in, nearest_enemies_list): 156 | if len(nearest_enemies_list) > action_in-4: 157 | target = nearest_enemies_list[action_in-4] 158 | if target is None: 159 | return -1 160 | self.action_buffer.append(unit_to_attack.attack(target)) 161 | else: 162 | return -1 163 | 164 | def finish_episode(self, game_result): 165 | print("Game over!") 166 | if game_result == sc2.Result.Defeat: 167 | for index in range(len(self.agent_list), 0, -1): 168 | self.dead_agent_list.append(self.agent_list[index-1]) 169 | self.dead_agent_list[-1].save_reward(-1) 170 | del self.agent_list[:] 171 | elif game_result == sc2.Result.Tie: 172 | reward = 0 173 | elif game_result == sc2.Result.Victory: 174 | reward = 0 # - min(self.itercount/500.0, 900) + self.units.amount 175 | else: 176 | # ??? 177 | return -13 178 | if len(self.agent_list) > 0: 179 | reward_sum = sum(self.agent_list[0].replay_buffer.rewards_list) 180 | else: 181 | reward_sum = sum(self.dead_agent_list[-1].replay_buffer.rewards_list) 182 | 183 | for agent_index in range(len(self.agent_list)): 184 | rewards_list, advantage_list, deeper_advantage_list = discount_reward( 185 | self.agent_list[agent_index].replay_buffer.rewards_list, 186 | self.agent_list[agent_index].replay_buffer.value_list, 187 | self.agent_list[agent_index].replay_buffer.deeper_value_list) 188 | self.agent_list[agent_index].replay_buffer.rewards_list = rewards_list 189 | self.agent_list[agent_index].replay_buffer.advantage_list = advantage_list 190 | self.agent_list[agent_index].replay_buffer.deeper_advantage_list = deeper_advantage_list 191 | for dead_agent_index in range(len(self.dead_agent_list)): 192 | rewards_list, advantage_list, deeper_advantage_list = discount_reward( 193 | self.dead_agent_list[dead_agent_index].replay_buffer.rewards_list, 194 | self.dead_agent_list[dead_agent_index].replay_buffer.value_list, 195 | self.dead_agent_list[dead_agent_index].replay_buffer.deeper_value_list) 196 | self.dead_agent_list[dead_agent_index].replay_buffer.rewards_list = rewards_list 197 | self.dead_agent_list[dead_agent_index].replay_buffer.advantage_list = advantage_list 198 | self.dead_agent_list[dead_agent_index].replay_buffer.deeper_advantage_list = deeper_advantage_list 199 | return reward_sum 200 | 201 | 202 | def run_episode(q, main_agent): 203 | result = None 204 | agent_in = main_agent.duplicate() 205 | 206 | bot = SC2MicroBot(rl_agent=agent_in) 207 | 208 | try: 209 | result = sc2.run_game(sc2.maps.get("FindAndDefeatZerglings"), 210 | [Bot(Race.Protoss, bot)], 211 | realtime=False) 212 | except KeyboardInterrupt: 213 | result = [-1, -1] 214 | except Exception as e: 215 | print(str(e)) 216 | print("No worries", e, " carry on please") 217 | if type(result) == list and len(result) > 1: 218 | result = result[0] 219 | reward_sum = bot.finish_episode(result) 220 | for agent in bot.agent_list+bot.dead_agent_list: 221 | agent_in.replay_buffer.extend(agent.replay_buffer.__getstate__()) 222 | if q is not None: 223 | try: 224 | q.put([reward_sum, agent_in.replay_buffer.__getstate__()]) 225 | except RuntimeError as e: 226 | print(e) 227 | return [reward_sum, agent_in.replay_buffer.__getstate__()] 228 | return [reward_sum, agent_in.replay_buffer.__getstate__()] 229 | 230 | 231 | def main(episodes, agent, num_processes): 232 | running_reward_array = [] 233 | # lowered = False 234 | mp.set_start_method('spawn') 235 | for episode in range(episodes): 236 | successful_runs = 0 237 | master_reward, reward, running_reward = 0, 0, 0 238 | processes = [] 239 | queueue = mp.Manager().Queue() 240 | for proc in range(num_processes): 241 | p = mp.Process(target=run_episode, args=(queueue, agent)) 242 | p.start() 243 | processes.append(p) 244 | for p in processes: 245 | p.join() 246 | while not queueue.empty(): 247 | try: 248 | fake_out = queueue.get() 249 | except MemoryError as e: 250 | print(e) 251 | fake_out = [-13, None] 252 | if fake_out[0] != -13: 253 | master_reward += fake_out[0] 254 | running_reward_array.append(fake_out[0]) 255 | agent.replay_buffer.extend(fake_out[1]) 256 | successful_runs += 1 257 | 258 | if successful_runs > 0: 259 | reward = master_reward / float(successful_runs) 260 | agent.end_episode(reward, num_processes) 261 | running_reward = sum(running_reward_array[-100:]) / float(min(100.0, len(running_reward_array))) 262 | if episode % 50 == 0: 263 | print(f'Episode {episode} Last Reward: {reward} Average Reward: {running_reward}') 264 | print(f"Running {num_processes} concurrent simulations per episode") 265 | if episode % 500 == 0: 266 | agent.save('../models/' + str(episode) + 'th') 267 | return running_reward_array 268 | 269 | 270 | if __name__ == '__main__': 271 | parser = argparse.ArgumentParser() 272 | parser.add_argument("-a", "--agent_type", help="architecture of agent to run", type=str, default='fc') 273 | parser.add_argument("-adv", "--adversary", 274 | help="for prolonet, init as adversarial? true for yes, false for no", 275 | type=bool, default=False) 276 | parser.add_argument("-s", "--sl_init", help="sl to rl for fc net?", type=bool, default=False) 277 | parser.add_argument("-dm", "--deepen_method", help="how to deepen?", type=str, default='random') 278 | parser.add_argument("-dc", "--deepen_criteria", help="when to deepen?", type=str, default='entropy') 279 | parser.add_argument("-e", "--episodes", help="how many episodes", type=int, default=1000) 280 | parser.add_argument("-p", "--processes", help="how many processes?", type=int, default=1) 281 | 282 | args = parser.parse_args() 283 | AGENT_TYPE = args.agent_type # 'shallow_prolo', 'prolo', 'random', 'fc', 'lstm' 284 | ADVERSARIAL = args.adversary # Adversarial prolo, applies for AGENT_TYPE=='shallow_prolo' 285 | SL_INIT = args.sl_init # SL->RL fc, applies only for AGENT_TYPE=='fc' 286 | DEEPEN_METHOD = args.deepen_method # 'random', 'fc', 'parent', method for deepening, only applies for AGENT_TYPE=='prolo' 287 | DEEPEN_CRITERIA = args.deepen_criteria # 'entropy', 'num', 'value', criteria for when to deepen. AGENT_TYPE=='prolo' only 288 | NUM_EPS = args.episodes 289 | NUM_PROCS = args.processes 290 | dim_in = 32 291 | dim_out = 10 292 | bot_name = AGENT_TYPE + 'SC_Micro' 293 | 294 | if AGENT_TYPE == 'prolo': 295 | policy_agent = DeepProLoNet(distribution='one_hot', 296 | bot_name=bot_name, 297 | input_dim=dim_in, 298 | output_dim=dim_out, 299 | deepen_method=DEEPEN_METHOD, 300 | deepen_criteria=DEEPEN_CRITERIA) 301 | elif AGENT_TYPE == 'fc': 302 | policy_agent = FCNet(input_dim=dim_in, 303 | bot_name=bot_name, 304 | output_dim=dim_out, 305 | sl_init=SL_INIT) 306 | elif AGENT_TYPE == 'random': 307 | policy_agent = RandomProLoNet(input_dim=dim_in, 308 | bot_name=bot_name, 309 | output_dim=dim_out) 310 | elif AGENT_TYPE == 'lstm': 311 | policy_agent = LSTMNet(input_dim=dim_in, 312 | bot_name=bot_name, 313 | output_dim=dim_out) 314 | elif AGENT_TYPE == 'shallow_prolo': 315 | policy_agent = ShallowProLoNet(distribution='one_hot', 316 | input_dim=dim_in, 317 | bot_name=bot_name, 318 | output_dim=dim_out, 319 | adversarial=ADVERSARIAL) 320 | else: 321 | raise Exception('No valid network selected') 322 | main(episodes=NUM_EPS, agent=policy_agent, num_processes=NUM_PROCS) 323 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /agents/prolonet_helpers.py: -------------------------------------------------------------------------------- 1 | # Created by Andrew Silva, andrew.silva@gatech.edu 2 | import numpy as np 3 | from agents.prolonet import ProLoNet 4 | import torch.nn as nn 5 | import copy 6 | import torch 7 | 8 | 9 | def init_cart_nets(distribution): 10 | dim_in = 4 11 | dim_out = 2 12 | w1 = np.zeros(dim_in) 13 | w1[0] = 1 # cart position 14 | c1 = -1 # > -1 15 | 16 | w2 = np.zeros(dim_in) 17 | w2[0] = -1 # negative position 18 | c2 = -1 # < 1 (so if positive < 4) 19 | 20 | w3 = np.zeros(dim_in) 21 | w3[2] = -1 # pole angle 22 | c3 = 0 # < 0 23 | 24 | w4 = np.zeros(dim_in) 25 | w4[2] = -1 26 | c4 = 0 # < 0 27 | 28 | w5 = np.zeros(dim_in) 29 | w5[2] = -1 30 | c5 = 0 # < 0 31 | 32 | w6 = np.zeros(dim_in) 33 | w6[1] = -1 # cart velocity 34 | c6 = 0 # < 0 35 | 36 | w7 = np.zeros(dim_in) 37 | w7[1] = 1 # cart velocity 38 | c7 = 0 # > 0 39 | 40 | w8 = np.zeros(dim_in) 41 | w8[3] = 1 # pole rate 42 | c8 = 0 # > 0 43 | 44 | w9 = np.zeros(dim_in) 45 | w9[2] = -1 46 | c9 = 0 47 | 48 | w10 = np.zeros(dim_in) 49 | w10[3] = -1 50 | c10 = 0 51 | 52 | w11 = np.zeros(dim_in) 53 | w11[2] = -1 54 | c11 = 0 55 | 56 | init_weights = [ 57 | w1, 58 | w2, 59 | w3, 60 | w4, 61 | w5, 62 | w6, 63 | w7, 64 | w8, 65 | w9, 66 | w10, 67 | w11, 68 | ] 69 | init_comparators = [ 70 | c1, 71 | c2, 72 | c3, 73 | c4, 74 | c5, 75 | c6, 76 | c7, 77 | c8, 78 | c9, 79 | c10, 80 | c11, 81 | ] 82 | if distribution == 'one_hot': 83 | leaf_base_init_val = 0. 84 | leaf_target_init_val = 1. 85 | elif distribution == 'soft_hot': 86 | leaf_base_init_val = 0.1 / dim_out 87 | leaf_target_init_val = 0.9 88 | else: # uniform 89 | leaf_base_init_val = 1.0 / dim_out 90 | leaf_target_init_val = 1.0 / dim_out 91 | leaf_base = [leaf_base_init_val] * 2 92 | 93 | l1 = [[], [0, 2], leaf_base.copy()] 94 | l1[-1][1] = leaf_target_init_val # Right 95 | 96 | l2 = [[0, 1, 3], [], leaf_base.copy()] 97 | l2[-1][0] = leaf_target_init_val # Left 98 | 99 | l3 = [[0, 1], [3], leaf_base.copy()] 100 | l3[-1][1] = leaf_target_init_val # Right 101 | 102 | l4 = [[0, 4], [1], leaf_base.copy()] 103 | l4[-1][0] = leaf_target_init_val # Left 104 | 105 | l5 = [[2, 5, 7], [0], leaf_base.copy()] 106 | l5[-1][1] = leaf_target_init_val # Right 107 | 108 | l6 = [[2, 5], [0, 7], leaf_base.copy()] 109 | l6[-1][0] = leaf_target_init_val # Left 110 | 111 | l7 = [[2, 8], [0, 5], leaf_base.copy()] 112 | l7[-1][0] = leaf_target_init_val # Left 113 | 114 | l8 = [[2], [0, 5, 8], leaf_base.copy()] 115 | l8[-1][1] = leaf_target_init_val # Right 116 | 117 | l9 = [[0, 6, 9], [1, 4], leaf_base.copy()] 118 | l9[-1][0] = leaf_target_init_val # Left 119 | 120 | l10 = [[0, 6], [1, 4, 9], leaf_base.copy()] 121 | l10[-1][1] = leaf_target_init_val # Right 122 | 123 | l11 = [[0, 10], [1, 4, 6], leaf_base.copy()] 124 | l11[-1][0] = leaf_target_init_val # Left 125 | 126 | l12 = [[0], [1, 4, 6, 10], leaf_base.copy()] 127 | l12[-1][1] = leaf_target_init_val # Right 128 | 129 | init_leaves = [ 130 | l1, 131 | l2, 132 | l3, 133 | l4, 134 | l5, 135 | l6, 136 | l7, 137 | l8, 138 | l9, 139 | l10, 140 | l11, 141 | l12, 142 | ] 143 | action_network = ProLoNet(input_dim=dim_in, 144 | weights=init_weights, 145 | comparators=init_comparators, 146 | leaves=init_leaves, 147 | alpha=1, 148 | is_value=False) 149 | value_network = ProLoNet(input_dim=dim_in, 150 | weights=init_weights, 151 | comparators=init_comparators, 152 | leaves=init_leaves, 153 | alpha=1, 154 | is_value=True) 155 | return action_network, value_network 156 | 157 | 158 | def add_level(pro_lo_net, split_noise_scale=0.2, method='parent'): 159 | old_weights = pro_lo_net.layers # Get the weights out 160 | new_weights = [weight.detach().clone().data.cpu().numpy() for weight in old_weights] 161 | 162 | old_comparators = pro_lo_net.comparators # get the comparator values out 163 | new_comparators = [comp.detach().clone().data.cpu().numpy()[0] for comp in 164 | old_comparators] 165 | old_leaf_information = pro_lo_net.leaf_init_information # get the leaf init info out 166 | 167 | if method == 'fc': 168 | new_network = ProLoNet(input_dim=pro_lo_net.input_dim, weights=new_weights, comparators=new_comparators, 169 | leaves=old_leaf_information, alpha=pro_lo_net.alpha.item(), is_value=pro_lo_net.is_value) 170 | 171 | new_network.added_levels = copy.deepcopy(pro_lo_net.added_levels) 172 | len_levels = len(new_network.added_levels) 173 | dim_out = pro_lo_net.action_probs.size(-1) 174 | if len_levels > 1: 175 | old_dim_in = 64 176 | else: 177 | old_dim_in = pro_lo_net.input_dim + dim_out 178 | 179 | if len_levels == 0: 180 | dim_in = pro_lo_net.input_dim + dim_out 181 | else: 182 | dim_in = 64 183 | new_network.added_levels[-1] = nn.Linear(old_dim_in, 64) 184 | new_network.added_levels.add_module('relu_'+str(len_levels), nn.ReLU()) 185 | 186 | new_network.added_levels.add_module('linear_'+str(len_levels), nn.Linear(dim_in, dim_out)) 187 | else: 188 | 189 | new_leaf_information = [] 190 | 191 | for leaf_index in range(len(old_leaf_information)): 192 | prior_leaf = pro_lo_net.action_probs[leaf_index].detach().clone().cpu().numpy() 193 | leaf_information = old_leaf_information[leaf_index] 194 | left_path = leaf_information[0] 195 | right_path = leaf_information[1] 196 | # This hideousness is to handle empty sequences... get the index of the node this used to split at 197 | weight_index = max( 198 | max(max(left_path, 199 | [-1]) 200 | ), 201 | max(max(right_path, 202 | [-1]) 203 | ) 204 | ) 205 | 206 | new_weight = np.random.normal(scale=split_noise_scale, 207 | size=old_weights[weight_index].size()[0]) 208 | new_comparator = np.random.normal(scale=split_noise_scale, 209 | size=old_comparators[weight_index].size()[0]) 210 | if method == 'parent': 211 | new_weight += new_weights[weight_index] 212 | new_comparator += new_comparators[weight_index] 213 | new_weights.append(new_weight) # Add it to the list of nodes 214 | new_comparators.extend(new_comparator) # Add it to the list of nodes 215 | 216 | new_node_ind = len(new_weights) - 1 # Remember where we put it 217 | 218 | # Create our two new leaves 219 | new_leaf1 = np.random.normal(scale=split_noise_scale, size=prior_leaf.shape) 220 | new_leaf2 = np.random.normal(scale=split_noise_scale, size=prior_leaf.shape) 221 | if method == 'parent': 222 | new_leaf1 = new_leaf1 + prior_leaf 223 | new_leaf2 = new_leaf2 + prior_leaf 224 | # Create the paths, which are copies of the old path but now with a left / right at the new node 225 | new_leaf1_left = left_path.copy() 226 | new_leaf1_right = right_path.copy() 227 | new_leaf2_left = left_path.copy() 228 | new_leaf2_right = right_path.copy() 229 | # Leaf 1 goes left at the new node, leaf 2 goes right 230 | new_leaf1_left.append(new_node_ind) 231 | new_leaf2_right.append(new_node_ind) 232 | 233 | new_leaf_information.append([new_leaf1_left, new_leaf1_right, new_leaf1]) 234 | new_leaf_information.append([new_leaf2_left, new_leaf2_right, new_leaf2]) 235 | 236 | new_network = ProLoNet(input_dim=pro_lo_net.input_dim, weights=new_weights, comparators=new_comparators, 237 | leaves=new_leaf_information, alpha=pro_lo_net.alpha.item(), is_value=pro_lo_net.is_value) 238 | return new_network 239 | 240 | 241 | def swap_in_node(network, deeper_network, leaf_index): 242 | """ 243 | Duplicates the network and returns a new one, where the node at leaf_index as been turned into a splitting node 244 | with two leaves that are slightly noisy copies of the previous node 245 | :param network: prolonet in 246 | :param deeper_network: deeper_network to take the new node / leaves from 247 | :param leaf_index: index of leaf to turn into a split 248 | :return: new prolonet (value or normal) 249 | """ 250 | old_weights = network.layers # Get the weights out 251 | old_comparators = network.comparators # get the comparator values out 252 | leaf_information = network.leaf_init_information[leaf_index] # get the old leaf init info out 253 | left_path = leaf_information[0] 254 | right_path = leaf_information[1] 255 | if deeper_network is not None: 256 | deeper_weights = [weight.detach().clone().data.cpu().numpy() for weight in deeper_network.layers] 257 | 258 | deeper_comparators = [comp.detach().clone().data.cpu().numpy()[0] for comp in 259 | deeper_network.comparators] 260 | 261 | deeper_leaf_info = deeper_network.leaf_init_information[leaf_index*2] 262 | deeper_left_path = deeper_leaf_info[0] 263 | deeper_right_path = deeper_leaf_info[1] 264 | deeper_weight_index = max( 265 | max(max(deeper_left_path, 266 | [-1]) 267 | ), 268 | max(max(deeper_right_path, 269 | [-1]) 270 | ) 271 | ) 272 | 273 | # Make a new weight vector, mostly the same as the old one 274 | 275 | new_weight = deeper_weights[deeper_weight_index] 276 | new_comparator = deeper_comparators[deeper_weight_index] 277 | new_leaf1 = deeper_network.action_probs[leaf_index * 2].detach().clone().data.cpu().numpy() 278 | new_leaf2 = deeper_network.action_probs[leaf_index * 2 + 1].detach().clone().data.cpu().numpy() 279 | else: 280 | new_weight = np.random.normal(scale=0.2, 281 | size=old_weights[0].size()[0]) 282 | new_comparator = np.random.normal(scale=0.2, 283 | size=old_comparators[0].size()[0])[0] 284 | new_leaf1 = np.random.normal(scale=0.2, 285 | size=network.action_probs[leaf_index].size()[0]) 286 | new_leaf2 = np.random.normal(scale=0.2, 287 | size=network.action_probs[leaf_index].size()[0]) 288 | 289 | new_weights = [weight.detach().clone().data.cpu().numpy() for weight in old_weights] 290 | new_weights.append(new_weight) # Add it to the list of nodes 291 | new_comparators = [comp.detach().clone().data.cpu().numpy()[0] for comp in old_comparators] 292 | new_comparators.append(new_comparator) # Add it to the list of nodes 293 | 294 | new_node_ind = len(new_weights) - 1 # Remember where we put it 295 | 296 | # Create the paths, which are copies of the old path but now with a left / right at the new node 297 | new_leaf1_left = left_path.copy() 298 | new_leaf1_right = right_path.copy() 299 | new_leaf2_left = left_path.copy() 300 | new_leaf2_right = right_path.copy() 301 | # Leaf 1 goes left at the new node, leaf 2 goes right 302 | new_leaf1_left.append(new_node_ind) 303 | new_leaf2_right.append(new_node_ind) 304 | 305 | new_leaf_information = network.leaf_init_information 306 | for index, leaf_prob_vec in enumerate(network.action_probs): # Copy over the learned leaf weight 307 | new_leaf_information[index][-1] = leaf_prob_vec.detach().clone().data.cpu().numpy() 308 | new_leaf_information.append([new_leaf1_left, new_leaf1_right, new_leaf1]) 309 | new_leaf_information.append([new_leaf2_left, new_leaf2_right, new_leaf2]) 310 | # Remove the old leaf 311 | del new_leaf_information[leaf_index] 312 | new_network = ProLoNet(input_dim=network.input_dim, weights=new_weights, comparators=new_comparators, 313 | leaves=new_leaf_information, alpha=network.alpha.item(), is_value=network.is_value) 314 | return new_network 315 | 316 | 317 | def init_lander_nets(distribution): 318 | dim_in = 8 319 | dim_out = 4 320 | w0 = np.zeros(dim_in) 321 | w0[1] = -1 322 | c0 = -1.1 # < 1.1 323 | 324 | w1 = np.zeros(dim_in) 325 | w1[3] = -1 326 | c1 = 0.2 # < -0.2 327 | 328 | w2 = np.zeros(dim_in) 329 | w2[5] = 1 330 | c2 = 0.1 # > 0.1 331 | 332 | w3 = np.zeros(dim_in) 333 | w3[5] = -1 334 | c3 = -0.1 # < 0.1 335 | 336 | w4 = np.zeros(dim_in) 337 | w4[6] = 1 338 | w4[7] = 1 339 | c4 = 1.2 # both 6 & 7 == 1 340 | 341 | w5 = np.zeros(dim_in) 342 | w5[5] = -1 343 | c5 = 0.1 # < -0.1 344 | 345 | w6 = np.zeros(dim_in) 346 | w6[6] = 1 347 | w6[7] = 1 348 | c6 = 1.2 # both 6 & 7 == 1 349 | 350 | w7 = np.zeros(dim_in) 351 | w7[6] = 1 352 | w7[7] = 1 353 | c7 = 1.2 # both 6 & 7 == 1 354 | 355 | w8 = np.zeros(dim_in) 356 | w8[0] = 1 357 | c8 = 0.2 # > 0 358 | 359 | w9 = np.zeros(dim_in) 360 | w9[6] = 1 361 | w9[7] = 1 362 | c9 = 1.2 # both 6 & 7 == 1 363 | 364 | w10 = np.zeros(dim_in) 365 | w10[0] = 1 366 | c10 = 0.2 367 | 368 | w11 = np.zeros(dim_in) 369 | w11[5] = 1 370 | c11 = -0.1 # > -0.1 371 | 372 | w12 = np.zeros(dim_in) 373 | w12[0] = -1 374 | c12 = 0.2 # < -0.2 375 | 376 | w13 = np.zeros(dim_in) 377 | w13[0] = -1 378 | c13 = 0.2 # < -0.2 379 | 380 | init_weights = [ 381 | w0, 382 | w1, 383 | w2, 384 | w3, 385 | w4, 386 | w5, 387 | w6, 388 | w7, 389 | w8, 390 | w9, 391 | w10, 392 | w11, 393 | w12, 394 | w13 395 | ] 396 | init_comparators = [ 397 | c0, 398 | c1, 399 | c2, 400 | c3, 401 | c4, 402 | c5, 403 | c6, 404 | c7, 405 | c8, 406 | c9, 407 | c10, 408 | c11, 409 | c12, 410 | c13 411 | ] 412 | if distribution == 'one_hot': 413 | leaf_base_init_val = 0. 414 | leaf_target_init_val = 1. 415 | elif distribution == 'soft_hot': 416 | leaf_base_init_val = 0.1 / dim_out 417 | leaf_target_init_val = 0.9 418 | else: # uniform 419 | leaf_base_init_val = 1.0 / dim_out 420 | leaf_target_init_val = 1.0 / dim_out 421 | leaf_base = [leaf_base_init_val] * dim_out 422 | 423 | l0 = [[0, 1], [3], leaf_base.copy()] 424 | l0[-1][3] = leaf_target_init_val 425 | 426 | l1 = [[0, 4], [1], leaf_base.copy()] 427 | l1[-1][0] = leaf_target_init_val 428 | 429 | l2 = [[6], [0, 2], leaf_base.copy()] 430 | l2[-1][0] = leaf_target_init_val 431 | 432 | l3 = [[], [0, 2, 6], leaf_base.copy()] 433 | l3[-1][3] = leaf_target_init_val 434 | 435 | l4 = [[0, 1, 3, 7], [], leaf_base.copy()] 436 | l4[-1][0] = leaf_target_init_val 437 | 438 | l5 = [[0, 8], [1, 4], leaf_base.copy()] 439 | l5[-1][1] = leaf_target_init_val 440 | 441 | l6 = [[2, 5, 9], [0], leaf_base.copy()] 442 | l6[-1][0] = leaf_target_init_val 443 | 444 | l7 = [[2, 5], [0, 9], leaf_base.copy()] 445 | l7[-1][1] = leaf_target_init_val 446 | 447 | l8 = [[2, 10], [0, 5], leaf_base.copy()] 448 | l8[-1][1] = leaf_target_init_val 449 | 450 | l9 = [[0, 1, 3, 11], [7], leaf_base.copy()] 451 | l9[-1][2] = leaf_target_init_val 452 | 453 | l10 = [[0, 1, 3], [7, 11], leaf_base.copy()] 454 | l10[-1][1] = leaf_target_init_val 455 | 456 | l11 = [[0, 12], [1, 4, 8], leaf_base.copy()] 457 | l11[-1][3] = leaf_target_init_val 458 | 459 | l12 = [[0], [1, 4, 8, 12], leaf_base.copy()] 460 | l12[-1][0] = leaf_target_init_val 461 | 462 | l13 = [[2, 13], [0, 5, 10], leaf_base.copy()] 463 | l13[-1][3] = leaf_target_init_val 464 | 465 | l14 = [[2], [0, 5, 10, 13], leaf_base.copy()] 466 | l14[-1][0] = leaf_target_init_val 467 | 468 | init_leaves = [ 469 | l0, 470 | l1, 471 | l2, 472 | l3, 473 | l4, 474 | l5, 475 | l6, 476 | l7, 477 | l8, 478 | l9, 479 | l10, 480 | l11, 481 | l12, 482 | l13, 483 | l14 484 | ] 485 | action_network = ProLoNet(input_dim=dim_in, 486 | weights=init_weights, 487 | comparators=init_comparators, 488 | leaves=init_leaves, 489 | alpha=1, 490 | is_value=False) 491 | value_network = ProLoNet(input_dim=dim_in, 492 | weights=init_weights, 493 | comparators=init_comparators, 494 | leaves=init_leaves, 495 | alpha=1, 496 | is_value=True) 497 | return action_network, value_network 498 | 499 | 500 | def init_random_cart_net(): 501 | dim_in = 4 502 | output_dim = 2 503 | w1 = np.random.normal(0, 0.1, dim_in) 504 | c1 = np.random.normal(0, 0.1, 1)[0] 505 | 506 | w2 = np.random.normal(0, 0.1, dim_in) 507 | c2 = np.random.normal(0, 0.1, 1)[0] 508 | 509 | w3 = np.random.normal(0, 0.1, dim_in) 510 | c3 = np.random.normal(0, 0.1, 1)[0] 511 | 512 | w4 = np.random.normal(0, 0.1, dim_in) 513 | c4 = np.random.normal(0, 0.1, 1)[0] 514 | 515 | w5 = np.random.normal(0, 0.1, dim_in) 516 | c5 = np.random.normal(0, 0.1, 1)[0] 517 | 518 | w6 = np.random.normal(0, 0.1, dim_in) 519 | c6 = np.random.normal(0, 0.1, 1)[0] 520 | 521 | w7 = np.random.normal(0, 0.1, dim_in) 522 | c7 = np.random.normal(0, 0.1, 1)[0] 523 | 524 | w8 = np.random.normal(0, 0.1, dim_in) 525 | c8 = np.random.normal(0, 0.1, 1)[0] 526 | 527 | w9 = np.random.normal(0, 0.1, dim_in) 528 | c9 = np.random.normal(0, 0.1, 1)[0] 529 | 530 | w10 = np.random.normal(0, 0.1, dim_in) 531 | c10 = np.random.normal(0, 0.1, 1)[0] 532 | 533 | w11 = np.random.normal(0, 0.1, dim_in) 534 | c11 = np.random.normal(0, 0.1, 1)[0] 535 | 536 | init_weights = [ 537 | w1, 538 | w2, 539 | w3, 540 | w4, 541 | w5, 542 | w6, 543 | w7, 544 | w8, 545 | w9, 546 | w10, 547 | w11, 548 | ] 549 | init_comparators = [ 550 | c1, 551 | c2, 552 | c3, 553 | c4, 554 | c5, 555 | c6, 556 | c7, 557 | c8, 558 | c9, 559 | c10, 560 | c11, 561 | ] 562 | 563 | l1 = [[], [0, 2], np.random.normal(0, 0.1, output_dim)] 564 | 565 | l2 = [[0, 1, 3], [], np.random.normal(0, 0.1, output_dim)] 566 | 567 | l3 = [[0, 1], [3], np.random.normal(0, 0.1, output_dim)] 568 | 569 | l4 = [[0, 4], [1], np.random.normal(0, 0.1, output_dim)] 570 | 571 | l5 = [[2, 5, 7], [0], np.random.normal(0, 0.1, output_dim)] 572 | 573 | l6 = [[2, 5], [0, 7], np.random.normal(0, 0.1, output_dim)] 574 | 575 | l7 = [[2, 8], [0, 5], np.random.normal(0, 0.1, output_dim)] 576 | 577 | l8 = [[2], [0, 5, 8], np.random.normal(0, 0.1, output_dim)] 578 | 579 | l9 = [[0, 6, 9], [1, 4], np.random.normal(0, 0.1, output_dim)] 580 | 581 | l10 = [[0, 6], [1, 4, 9], np.random.normal(0, 0.1, output_dim)] 582 | 583 | l11 = [[0, 10], [1, 4, 6], np.random.normal(0, 0.1, output_dim)] 584 | 585 | l12 = [[0], [1, 4, 6, 10], np.random.normal(0, 0.1, output_dim)] 586 | 587 | init_leaves = [ 588 | l1, 589 | l2, 590 | l3, 591 | l4, 592 | l5, 593 | l6, 594 | l7, 595 | l8, 596 | l9, 597 | l10, 598 | l11, 599 | l12, 600 | ] 601 | action_network = ProLoNet(input_dim=dim_in, 602 | weights=init_weights, 603 | comparators=init_comparators, 604 | leaves=init_leaves, 605 | alpha=1, 606 | is_value=False) 607 | value_network = ProLoNet(input_dim=dim_in, 608 | weights=init_weights, 609 | comparators=init_comparators, 610 | leaves=init_leaves, 611 | alpha=1, 612 | is_value=True) 613 | return action_network, value_network 614 | 615 | 616 | def init_random_lander_net(): 617 | dim_in = 8 618 | dim_out = 4 619 | w0 = np.random.normal(0, 0.1, dim_in) 620 | c0 = np.random.normal(0, 0.1, 1)[0] 621 | 622 | w1 = np.random.normal(0, 0.1, dim_in) 623 | c1 = np.random.normal(0, 0.1, 1)[0] 624 | 625 | w2 = np.random.normal(0, 0.1, dim_in) 626 | c2 = np.random.normal(0, 0.1, 1)[0] 627 | 628 | w3 = np.random.normal(0, 0.1, dim_in) 629 | c3 = np.random.normal(0, 0.1, 1)[0] 630 | 631 | w4 = np.random.normal(0, 0.1, dim_in) 632 | c4 = np.random.normal(0, 0.1, 1)[0] 633 | 634 | w5 = np.random.normal(0, 0.1, dim_in) 635 | c5 = np.random.normal(0, 0.1, 1)[0] 636 | 637 | w6 = np.random.normal(0, 0.1, dim_in) 638 | c6 = np.random.normal(0, 0.1, 1)[0] 639 | 640 | w7 = np.random.normal(0, 0.1, dim_in) 641 | c7 = np.random.normal(0, 0.1, 1)[0] 642 | 643 | w8 = np.random.normal(0, 0.1, dim_in) 644 | c8 = np.random.normal(0, 0.1, 1)[0] 645 | 646 | w9 = np.random.normal(0, 0.1, dim_in) 647 | c9 = np.random.normal(0, 0.1, 1)[0] 648 | 649 | w10 = np.random.normal(0, 0.1, dim_in) 650 | c10 = np.random.normal(0, 0.1, 1)[0] 651 | 652 | w11 = np.random.normal(0, 0.1, dim_in) 653 | c11 = np.random.normal(0, 0.1, 1)[0] 654 | 655 | w12 = np.random.normal(0, 0.1, dim_in) 656 | c12 = np.random.normal(0, 0.1, 1)[0] 657 | 658 | w13 = np.random.normal(0, 0.1, dim_in) 659 | c13 = np.random.normal(0, 0.1, 1)[0] 660 | 661 | init_weights = [ 662 | w0, 663 | w1, 664 | w2, 665 | w3, 666 | w4, 667 | w5, 668 | w6, 669 | w7, 670 | w8, 671 | w9, 672 | w10, 673 | w11, 674 | w12, 675 | w13 676 | ] 677 | init_comparators = [ 678 | c0, 679 | c1, 680 | c2, 681 | c3, 682 | c4, 683 | c5, 684 | c6, 685 | c7, 686 | c8, 687 | c9, 688 | c10, 689 | c11, 690 | c12, 691 | c13 692 | ] 693 | 694 | l0 = [[0, 1], [3], np.random.normal(0, 0.1, dim_out)] 695 | 696 | l1 = [[0, 4], [1], np.random.normal(0, 0.1, dim_out)] 697 | 698 | l2 = [[6], [0, 2], np.random.normal(0, 0.1, dim_out)] 699 | 700 | l3 = [[], [0, 2, 6], np.random.normal(0, 0.1, dim_out)] 701 | 702 | l4 = [[0, 1, 3, 7], [], np.random.normal(0, 0.1, dim_out)] 703 | 704 | l5 = [[0, 8], [1, 4], np.random.normal(0, 0.1, dim_out)] 705 | 706 | l6 = [[2, 5, 9], [0], np.random.normal(0, 0.1, dim_out)] 707 | 708 | l7 = [[2, 5], [0, 9], np.random.normal(0, 0.1, dim_out)] 709 | 710 | l8 = [[2, 10], [0, 5], np.random.normal(0, 0.1, dim_out)] 711 | 712 | l9 = [[0, 1, 3, 11], [7], np.random.normal(0, 0.1, dim_out)] 713 | 714 | l10 = [[0, 1, 3], [7, 11], np.random.normal(0, 0.1, dim_out)] 715 | 716 | l11 = [[0, 12], [1, 4, 8], np.random.normal(0, 0.1, dim_out)] 717 | 718 | l12 = [[0], [1, 4, 8, 12], np.random.normal(0, 0.1, dim_out)] 719 | 720 | l13 = [[2, 13], [0, 5, 10], np.random.normal(0, 0.1, dim_out)] 721 | 722 | l14 = [[2], [0, 5, 10, 13], np.random.normal(0, 0.1, dim_out)] 723 | 724 | init_leaves = [ 725 | l0, 726 | l1, 727 | l2, 728 | l3, 729 | l4, 730 | l5, 731 | l6, 732 | l7, 733 | l8, 734 | l9, 735 | l10, 736 | l11, 737 | l12, 738 | l13, 739 | l14 740 | ] 741 | action_network = ProLoNet(input_dim=dim_in, 742 | weights=init_weights, 743 | comparators=init_comparators, 744 | leaves=init_leaves, 745 | alpha=1, 746 | is_value=False) 747 | value_network = ProLoNet(input_dim=dim_in, 748 | weights=init_weights, 749 | comparators=init_comparators, 750 | leaves=init_leaves, 751 | alpha=1, 752 | is_value=True) 753 | return action_network, value_network 754 | 755 | 756 | def init_adversarial_net(adv_type='cart', distribution_in='one_hot', adv_prob=0.05): 757 | """ 758 | initialize networks intelligently but also wrongly 759 | with p=adv_prob negate weights 760 | with p=adv_prob negate comparators 761 | with p=adv_prob negate leaf probabilities 762 | :param adv_type: which env is this for: cart, lunar, sc 763 | :param distribution_in: same as init_cart_nets or init_lander_nets. one_hot, soft_hot, or other... 764 | :param adv_prob: probability to negate the things above 765 | :return: actor, critic 766 | """ 767 | cart_act = None 768 | if adv_type == 'cart': 769 | cart_act, cart_value = init_cart_nets(distribution=distribution_in) 770 | elif adv_type == 'lunar': 771 | cart_act, cart_value = init_lander_nets(distribution=distribution_in) 772 | elif adv_type == 'sc': 773 | cart_act, cart_value = init_sc_nets(distribution_in) 774 | elif adv_type == 'micro': 775 | cart_act, cart_value = init_micro_net(distribution=distribution_in) 776 | if cart_act is None: 777 | return -1 778 | old_weights = cart_act.layers # Get the weights out 779 | new_weights = [weight.detach().clone().data.cpu().numpy() for weight in old_weights] 780 | 781 | old_comparators = cart_act.comparators # get the comparator values out 782 | new_comparators = [comp.detach().clone().data.cpu().numpy()[0] for comp in 783 | old_comparators] 784 | 785 | prob_flip = adv_prob 786 | old_leaf_information = cart_act.leaf_init_information # get the leaf init info out 787 | weight_flips = 0 788 | comp_flips = 0 789 | leaf_flips = 0 790 | quarter_weights = len(new_weights)*(prob_flip*2) 791 | quarter_leaves = len(old_leaf_information)*(prob_flip*2) 792 | for index in range(len(new_weights)): 793 | if np.random.random() < prob_flip and weight_flips < quarter_weights: 794 | new_weights[index] *= -1 795 | weight_flips += 1 796 | if np.random.random() < prob_flip and comp_flips < quarter_weights: 797 | new_comparators[index] *= -1 798 | comp_flips += 1 799 | for index in range(len(old_leaf_information)): 800 | if np.random.random() < prob_flip and leaf_flips < quarter_leaves: 801 | new_leaf_info = np.array(old_leaf_information[index][-1])*-1 802 | old_leaf_information[index][-1] = new_leaf_info.tolist() 803 | leaf_flips += 1 804 | 805 | new_actor = ProLoNet(input_dim=cart_act.input_dim, weights=new_weights, comparators=new_comparators, 806 | leaves=old_leaf_information, alpha=cart_act.alpha.item(), is_value=False) 807 | new_value = ProLoNet(input_dim=cart_act.input_dim, weights=new_weights, comparators=new_comparators, 808 | leaves=old_leaf_information, alpha=cart_act.alpha.item(), is_value=True) 809 | 810 | return new_actor, new_value 811 | 812 | 813 | def init_sc_nets(dist='one_hot'): 814 | dim_in = 194 815 | dim_out = 44 816 | 817 | w0 = np.zeros(dim_in) 818 | w0[10] = 1 # zealot 819 | w0[22] = 1 # voidray 820 | c0 = 8 # > 8 821 | 822 | w1 = np.zeros(dim_in) 823 | w1[45:65] = 1 # Enemy Protoss non-buildings 824 | w1[82:99] = 1 # Enemy Terran non-buildings 825 | w1[118:139] = 1 # Enemy Zerg non-buildings 826 | c1 = 2 # > 4 enemies, potentially under attack? 827 | 828 | w2 = np.zeros(dim_in) 829 | w2[4] = 1 # idle workers 830 | c2 = 0.5 # > 0.5 831 | 832 | w3 = np.zeros(dim_in) 833 | w3[65:82] = 1 # Enemy Protoss non-buildings 834 | w3[99:118] = 1 # Enemy Terran non-buildings 835 | w3[139:157] = 1 # Enemy Zerg non-buildings 836 | c3 = 0 # > 0 # know where some enemy structures are 837 | 838 | w4 = np.zeros(dim_in) 839 | w4[2] = -1 # negative food capacity 840 | w4[3] = 1 # plus food used = negative food available 841 | c4 = -4 # > -4 (so if positive < 4) 842 | 843 | w5 = np.zeros(dim_in) 844 | w5[9] = -1 # probes 845 | w5[157] = -1 846 | c5 = -20 # > -16 == #probes<16 847 | 848 | w6 = np.zeros(dim_in) 849 | w6[30] = 1 # ASSIMILATOR 850 | w6[178] = 1 851 | c6 = 0.5 # > 0.5 852 | 853 | w7 = np.zeros(dim_in) 854 | w7[38] = 1 # STARGATE 855 | w7[186] = 1 856 | c7 = 0.5 # > 1.5 857 | 858 | w8 = np.zeros(dim_in) 859 | w8[31] = 1 # GATEWAY 860 | w8[179] = 1 861 | c8 = 0.5 # > 0.5 862 | 863 | w9 = np.zeros(dim_in) 864 | w9[22] = 1 # VOIDRAY 865 | w9[170] = 1 866 | c9 = 7 # > 7 867 | 868 | w10 = np.zeros(dim_in) 869 | w10[10] = 1 # zealot 870 | w10[158] = 1 871 | c10 = 2 # > 3 872 | 873 | w11 = np.zeros(dim_in) 874 | w11[34] = 10 # CYBERNETICSCORE 875 | w11[182] = 10 876 | c11 = 0.5 # > 0.5 877 | 878 | init_weights = [ 879 | w0, 880 | w1, 881 | w2, 882 | w3, 883 | w4, 884 | w5, 885 | w6, 886 | w7, 887 | w8, 888 | w9, 889 | w10, 890 | w11, 891 | ] 892 | init_comparators = [ 893 | c0, 894 | c1, 895 | c2, 896 | c3, 897 | c4, 898 | c5, 899 | c6, 900 | c7, 901 | c8, 902 | c9, 903 | c10, 904 | c11, 905 | ] 906 | if dist == 'one_hot': 907 | leaf_base_init_val = 0. 908 | leaf_target_init_val = 1. 909 | elif dist == 'soft_hot': 910 | leaf_base_init_val = 0.1/(max(dim_out-1, 1)) 911 | leaf_target_init_val = 0.9 912 | else: # uniform 913 | leaf_base_init_val = 1.0/dim_out 914 | leaf_target_init_val = 1.0/dim_out 915 | leaf_base = [leaf_base_init_val] * dim_out 916 | 917 | l0 = [[0, 1], [], leaf_base.copy()] 918 | l0[-1][41] = leaf_target_init_val # Defend 919 | l0[-1][39] = leaf_target_init_val 920 | 921 | l1 = [[2], [0], leaf_base.copy()] 922 | l1[-1][40] = leaf_target_init_val # Mine 923 | 924 | l2 = [[0, 1], [3], leaf_base.copy()] 925 | l2[-1][39] = leaf_target_init_val # Attack 926 | 927 | l3 = [[0], [1, 3], leaf_base.copy()] 928 | l3[-1][42] = leaf_target_init_val # Scout 929 | 930 | l4 = [[4], [0, 2], leaf_base.copy()] 931 | l4[-1][1] = leaf_target_init_val # Pylon 932 | 933 | l5 = [[5], [0, 2, 4], leaf_base.copy()] 934 | l5[-1][16] = leaf_target_init_val # Probe 935 | 936 | l6 = [[], [0, 2, 4, 5, 6, 8], leaf_base.copy()] 937 | l6[-1][3] = leaf_target_init_val # Gateway 938 | 939 | l7 = [[6, 7, 9], [0, 2, 4, 5], leaf_base.copy()] 940 | l7[-1][39] = leaf_target_init_val # Attack 941 | 942 | l8 = [[6, 7], [0, 2, 4, 5, 9], leaf_base.copy()] 943 | l8[-1][29] = leaf_target_init_val # Voidray 944 | 945 | l9 = [[6, 10], [0, 2, 4, 5, 7], leaf_base.copy()] 946 | l9[-1][40] = leaf_target_init_val # Mine (Get vespene) 947 | 948 | l10 = [[6], [0, 2, 4, 5, 7], leaf_base.copy()] 949 | l10[-1][10] = leaf_target_init_val # Stargate 950 | 951 | l11 = [[8], [0, 2, 4, 5, 6, 10], leaf_base.copy()] 952 | l11[-1][17] = leaf_target_init_val # Zealot 953 | 954 | l12 = [[8, 10, 11], [0, 2, 4, 5, 6], leaf_base.copy()] 955 | l12[-1][2] = leaf_target_init_val # Assimilator 956 | 957 | l13 = [[8, 10], [0, 2, 4, 5, 6, 11], leaf_base.copy()] 958 | l13[-1][6] = leaf_target_init_val # Cybernetics Core 959 | 960 | init_leaves = [ 961 | l1, 962 | l2, 963 | l3, 964 | l4, 965 | l5, 966 | l10, 967 | l6, 968 | l7, 969 | l8, 970 | l9, 971 | l10, 972 | l11, 973 | l12, 974 | l13, 975 | ] 976 | actor = ProLoNet(input_dim=dim_in, 977 | weights=init_weights, 978 | comparators=init_comparators, 979 | leaves=init_leaves, 980 | alpha=1, 981 | is_value=False) 982 | critic = ProLoNet(input_dim=dim_in, 983 | weights=init_weights, 984 | comparators=init_comparators, 985 | leaves=init_leaves, 986 | alpha=1, 987 | is_value=True) 988 | return actor, critic 989 | 990 | 991 | def init_random_sc_net(): 992 | dim_in = 194 993 | dim_out = 44 994 | w0 = np.random.normal(0, 0.1, dim_in) 995 | c0 = np.random.normal(0, 0.1, 1)[0] 996 | 997 | w1 = np.random.normal(0, 0.1, dim_in) 998 | c1 = np.random.normal(0, 0.1, 1)[0] 999 | 1000 | w2 = np.random.normal(0, 0.1, dim_in) 1001 | c2 = np.random.normal(0, 0.1, 1)[0] 1002 | 1003 | w3 = np.random.normal(0, 0.1, dim_in) 1004 | c3 = np.random.normal(0, 0.1, 1)[0] 1005 | 1006 | w4 = np.random.normal(0, 0.1, dim_in) 1007 | c4 = np.random.normal(0, 0.1, 1)[0] 1008 | 1009 | w5 = np.random.normal(0, 0.1, dim_in) 1010 | c5 = np.random.normal(0, 0.1, 1)[0] 1011 | 1012 | w6 = np.random.normal(0, 0.1, dim_in) 1013 | c6 = np.random.normal(0, 0.1, 1)[0] 1014 | 1015 | w7 = np.random.normal(0, 0.1, dim_in) 1016 | c7 = np.random.normal(0, 0.1, 1)[0] 1017 | 1018 | w8 = np.random.normal(0, 0.1, dim_in) 1019 | c8 = np.random.normal(0, 0.1, 1)[0] 1020 | 1021 | w9 = np.random.normal(0, 0.1, dim_in) 1022 | c9 = np.random.normal(0, 0.1, 1)[0] 1023 | 1024 | w10 = np.random.normal(0, 0.1, dim_in) 1025 | c10 = np.random.normal(0, 0.1, 1)[0] 1026 | 1027 | w11 = np.random.normal(0, 0.1, dim_in) 1028 | c11 = np.random.normal(0, 0.1, 1)[0] 1029 | 1030 | w12 = np.random.normal(0, 0.1, dim_in) 1031 | c12 = np.random.normal(0, 0.1, 1)[0] 1032 | 1033 | init_weights = [ 1034 | w0, 1035 | w1, 1036 | w2, 1037 | w3, 1038 | w4, 1039 | w5, 1040 | w6, 1041 | w7, 1042 | w8, 1043 | w9, 1044 | w10, 1045 | w11, 1046 | w12, 1047 | ] 1048 | init_comparators = [ 1049 | c0, 1050 | c1, 1051 | c2, 1052 | c3, 1053 | c4, 1054 | c5, 1055 | c6, 1056 | c7, 1057 | c8, 1058 | c9, 1059 | c10, 1060 | c11, 1061 | c12, 1062 | ] 1063 | 1064 | l1 = [[2], [0], np.random.normal(0, 0.1, dim_out)] 1065 | 1066 | l2 = [[0, 1], [3], np.random.normal(0, 0.1, dim_out)] 1067 | 1068 | l3 = [[0], [1, 3], np.random.normal(0, 0.1, dim_out)] 1069 | 1070 | l4 = [[4], [0, 2], np.random.normal(0, 0.1, dim_out)] 1071 | 1072 | l5 = [[5], [0, 2, 4], np.random.normal(0, 0.1, dim_out)] 1073 | 1074 | l6 = [[], [0, 2, 4, 5, 6, 8], np.random.normal(0, 0.1, dim_out)] 1075 | 1076 | l7 = [[6, 7, 9], [0, 2, 4, 5], np.random.normal(0, 0.1, dim_out)] 1077 | 1078 | l8 = [[6, 7], [0, 2, 4, 5, 9], np.random.normal(0, 0.1, dim_out)] 1079 | 1080 | l9 = [[6, 10], [0, 2, 4, 5, 7], np.random.normal(0, 0.1, dim_out)] 1081 | 1082 | l10 = [[6], [0, 2, 4, 5, 7, 10], np.random.normal(0, 0.1, dim_out)] 1083 | 1084 | l11 = [[8], [0, 2, 4, 5, 6, 11], np.random.normal(0, 0.1, dim_out)] 1085 | 1086 | l12 = [[8, 11, 12], [0, 2, 4, 5, 6], np.random.normal(0, 0.1, dim_out)] 1087 | 1088 | l13 = [[8, 11], [0, 2, 4, 5, 6, 12], np.random.normal(0, 0.1, dim_out)] 1089 | 1090 | init_leaves = [ 1091 | l1, 1092 | l2, 1093 | l3, 1094 | l4, 1095 | l5, 1096 | l6, 1097 | l7, 1098 | l8, 1099 | l9, 1100 | l10, 1101 | l11, 1102 | l12, 1103 | l13, 1104 | ] 1105 | actor = ProLoNet(input_dim=dim_in, 1106 | weights=init_weights, 1107 | comparators=init_comparators, 1108 | leaves=init_leaves, 1109 | alpha=1, 1110 | is_value=False) 1111 | critic = ProLoNet(input_dim=dim_in, 1112 | weights=init_weights, 1113 | comparators=init_comparators, 1114 | leaves=init_leaves, 1115 | alpha=1, 1116 | is_value=True) 1117 | return actor, critic 1118 | 1119 | 1120 | def save_prolonet(fn, model): 1121 | checkpoint = dict() 1122 | mdl_data = dict() 1123 | mdl_data['weights'] = model.layers 1124 | mdl_data['comparators'] = model.comparators 1125 | mdl_data['leaf_init_information'] = model.leaf_init_information 1126 | mdl_data['action_probs'] = model.action_probs 1127 | mdl_data['alpha'] = model.alpha 1128 | mdl_data['input_dim'] = model.input_dim 1129 | mdl_data['is_value'] = model.is_value 1130 | checkpoint['model_data'] = mdl_data 1131 | torch.save(checkpoint, fn) 1132 | 1133 | 1134 | def load_prolonet(fn): 1135 | model_checkpoint = torch.load(fn, map_location='cpu') 1136 | model_data = model_checkpoint['model_data'] 1137 | init_weights = [weight.detach().clone().data.cpu().numpy() for weight in model_data['weights']] 1138 | init_comparators = [comp.item() for comp in model_data['comparators']] 1139 | 1140 | new_model = ProLoNet(input_dim=model_data['input_dim'], 1141 | weights=init_weights, 1142 | comparators=init_comparators, 1143 | leaves=model_data['leaf_init_information'], 1144 | alpha=model_data['alpha'].item(), 1145 | is_value=model_data['is_value']) 1146 | new_model.action_probs = model_data['action_probs'] 1147 | return new_model 1148 | 1149 | 1150 | def init_shallow_cart_nets(distribution): 1151 | dim_in = 4 1152 | dim_out = 2 1153 | w0 = np.zeros(dim_in) 1154 | w0[2] = -1 # pole angle 1155 | c0 = 0 # < 0 1156 | init_weights = [ 1157 | w0 1158 | ] 1159 | init_comparators = [ 1160 | c0 1161 | ] 1162 | if distribution == 'one_hot': 1163 | leaf_base_init_val = 0. 1164 | leaf_target_init_val = 1. 1165 | elif distribution == 'soft_hot': 1166 | leaf_base_init_val = 0.1 / dim_out 1167 | leaf_target_init_val = 0.9 1168 | else: # uniform 1169 | leaf_base_init_val = 1.0 / dim_out 1170 | leaf_target_init_val = 1.0 / dim_out 1171 | leaf_base = [leaf_base_init_val] * dim_out 1172 | 1173 | l0 = [[], [0], leaf_base.copy()] 1174 | l0[-1][1] = leaf_target_init_val # Right 1175 | 1176 | l1 = [[0], [0], leaf_base.copy()] 1177 | l1[-1][0] = leaf_target_init_val # Right 1178 | 1179 | init_leaves = [ 1180 | l0, 1181 | l1 1182 | ] 1183 | action_network = ProLoNet(input_dim=dim_in, 1184 | weights=init_weights, 1185 | comparators=init_comparators, 1186 | leaves=init_leaves, 1187 | alpha=1, 1188 | is_value=False) 1189 | value_network = ProLoNet(input_dim=dim_in, 1190 | weights=init_weights, 1191 | comparators=init_comparators, 1192 | leaves=init_leaves, 1193 | alpha=1, 1194 | is_value=True) 1195 | return action_network, value_network 1196 | 1197 | 1198 | def init_random_micro_net(): 1199 | dim_in = 32 1200 | dim_out = 10 1201 | w0 = np.random.normal(0, 0.1, dim_in) 1202 | c0 = np.random.normal(0, 0.1, 1)[0] 1203 | 1204 | w1 = np.random.normal(0, 0.1, dim_in) 1205 | c1 = np.random.normal(0, 0.1, 1)[0] 1206 | 1207 | w2 = np.random.normal(0, 0.1, dim_in) 1208 | c2 = np.random.normal(0, 0.1, 1)[0] 1209 | 1210 | w3 = np.random.normal(0, 0.1, dim_in) 1211 | c3 = np.random.normal(0, 0.1, 1)[0] 1212 | 1213 | w4 = np.random.normal(0, 0.1, dim_in) 1214 | c4 = np.random.normal(0, 0.1, 1)[0] 1215 | 1216 | w5 = np.random.normal(0, 0.1, dim_in) 1217 | c5 = np.random.normal(0, 0.1, 1)[0] 1218 | 1219 | w6 = np.random.normal(0, 0.1, dim_in) 1220 | c6 = np.random.normal(0, 0.1, 1)[0] 1221 | 1222 | w7 = np.random.normal(0, 0.1, dim_in) 1223 | c7 = np.random.normal(0, 0.1, 1)[0] 1224 | 1225 | w8 = np.random.normal(0, 0.1, dim_in) 1226 | c8 = np.random.normal(0, 0.1, 1)[0] 1227 | 1228 | w9 = np.random.normal(0, 0.1, dim_in) 1229 | c9 = np.random.normal(0, 0.1, 1)[0] 1230 | 1231 | init_weights = [ 1232 | w0, 1233 | w1, 1234 | w2, 1235 | w3, 1236 | w4, 1237 | w5, 1238 | w6, 1239 | w7, 1240 | w8, 1241 | w9 1242 | ] 1243 | init_comparators = [ 1244 | c0, 1245 | c1, 1246 | c2, 1247 | c3, 1248 | c4, 1249 | c5, 1250 | c6, 1251 | c7, 1252 | c8, 1253 | c9 1254 | ] 1255 | l0 = [[0], [], np.random.normal(0, 0.1, dim_out)] 1256 | 1257 | l1 = [[1], [0], np.random.normal(0, 0.1, dim_out)] 1258 | 1259 | l2 = [[2], [0, 1], np.random.normal(0, 0.1, dim_out)] 1260 | 1261 | l3 = [[3], [0, 1, 2], np.random.normal(0, 0.1, dim_out)] 1262 | l4 = [[4], [0, 1, 2, 3], np.random.normal(0, 0.1, dim_out)] 1263 | 1264 | l5 = [[5, 6], [0, 1, 2, 3, 4], np.random.normal(0, 0.1, dim_out)] 1265 | 1266 | l6 = [[7], [0, 1, 2, 3, 4, 5], np.random.normal(0, 0.1, dim_out)] 1267 | 1268 | l7 = [[5, 8], [0, 1, 2, 3, 4, 6], np.random.normal(0, 0.1, dim_out)] 1269 | 1270 | l8 = [[5], [0, 1, 2, 3, 4, 6, 8], np.random.normal(0, 0.1, dim_out)] 1271 | 1272 | l9 = [[9], [0, 1, 2, 3, 4, 5, 7], np.random.normal(0, 0.1, dim_out)] 1273 | 1274 | l10 = [[], [0, 1, 2, 3, 4, 5, 7, 9], np.random.normal(0, 0.1, dim_out)] 1275 | 1276 | init_leaves = [ 1277 | l0, 1278 | l1, 1279 | l2, 1280 | l3, 1281 | l4, 1282 | l5, 1283 | l6, 1284 | l7, 1285 | l8, 1286 | l9, 1287 | l10 1288 | ] 1289 | action_network = ProLoNet(input_dim=dim_in, 1290 | weights=init_weights, 1291 | comparators=init_comparators, 1292 | leaves=init_leaves, 1293 | alpha=1, 1294 | is_value=False) 1295 | value_network = ProLoNet(input_dim=dim_in, 1296 | weights=init_weights, 1297 | comparators=init_comparators, 1298 | leaves=init_leaves, 1299 | alpha=1, 1300 | is_value=True) 1301 | return action_network, value_network 1302 | 1303 | 1304 | def init_micro_net(distribution='one_hot'): 1305 | dim_in = 32 1306 | dim_out = 10 1307 | w0 = np.zeros(dim_in) 1308 | w0[0] = 1 1309 | w0[4] = -1 1310 | c0 = 3.5 1311 | 1312 | w1 = np.zeros(dim_in) 1313 | w1[0] = -1 1314 | w1[4] = 1 1315 | c1 = 3.5 1316 | 1317 | w2 = np.zeros(dim_in) 1318 | w2[1] = 1 1319 | w2[5] = -1 1320 | c2 = 3.5 1321 | 1322 | w3 = np.zeros(dim_in) 1323 | w3[1] = -1 1324 | w3[5] = 1 1325 | c3 = 3.5 1326 | 1327 | w4 = np.zeros(dim_in) 1328 | w4[14] = 1 # zergling health 1329 | c4 = 0 1330 | 1331 | w5 = np.zeros(dim_in) 1332 | w5[1] = 1 # y position 1333 | c5 = 30 # > 30 1334 | 1335 | w6 = np.zeros(dim_in) 1336 | w6[0] = -1 # y position 1337 | c6 = -20 # < 20 1338 | 1339 | w7 = np.zeros(dim_in) 1340 | w7[1] = 1 # y position 1341 | c7 = 18 # < 20 1342 | 1343 | w8 = np.zeros(dim_in) 1344 | w8[0] = 1 # y position 1345 | c8 = 40 # < 20 1346 | 1347 | w9 = np.zeros(dim_in) 1348 | w9[0] = -1 # y position 1349 | c9 = -40 # < 20 1350 | 1351 | init_weights = [ 1352 | w0, 1353 | w1, 1354 | w2, 1355 | w3, 1356 | w4, 1357 | w5, 1358 | w6, 1359 | w7, 1360 | w8, 1361 | w9 1362 | ] 1363 | init_comparators = [ 1364 | c0, 1365 | c1, 1366 | c2, 1367 | c3, 1368 | c4, 1369 | c5, 1370 | c6, 1371 | c7, 1372 | c8, 1373 | c9 1374 | ] 1375 | 1376 | if distribution == 'one_hot': 1377 | leaf_base_init_val = 0. 1378 | leaf_target_init_val = 1. 1379 | elif distribution == 'soft_hot': 1380 | leaf_base_init_val = 0.1 / dim_out 1381 | leaf_target_init_val = 0.9 1382 | else: # uniform 1383 | leaf_base_init_val = 1.0 / dim_out 1384 | leaf_target_init_val = 1.0 / dim_out 1385 | leaf_base = [leaf_base_init_val] * dim_out 1386 | 1387 | l0 = [[0], [], leaf_base.copy()] 1388 | l0[-1][3] = leaf_target_init_val # west 1389 | 1390 | l1 = [[1], [0], leaf_base.copy()] 1391 | l1[-1][1] = leaf_target_init_val # east 1392 | 1393 | l2 = [[2], [0, 1], leaf_base.copy()] 1394 | l2[-1][2] = leaf_target_init_val # South 1395 | 1396 | l3 = [[3], [0, 1, 2], leaf_base.copy()] 1397 | l3[-1][0] = leaf_target_init_val # north 1398 | 1399 | l4 = [[4], [0, 1, 2, 3], leaf_base.copy()] 1400 | l4[-1][4] = leaf_target_init_val # Attack 1401 | 1402 | l5 = [[5, 6], [0, 1, 2, 3, 4], leaf_base.copy()] 1403 | l5[-1][2] = leaf_target_init_val # S 1404 | 1405 | l6 = [[7], [0, 1, 2, 3, 4, 5], leaf_base.copy()] 1406 | l6[-1][2] = leaf_target_init_val # S 1407 | 1408 | l7 = [[5, 8], [0, 1, 2, 3, 4, 6], leaf_base.copy()] 1409 | l7[-1][0] = leaf_target_init_val # N 1410 | 1411 | l8 = [[5], [0, 1, 2, 3, 4, 6, 8], leaf_base.copy()] 1412 | l8[-1][3] = leaf_target_init_val # N 1413 | 1414 | l9 = [[9], [0, 1, 2, 3, 4, 5, 7], leaf_base.copy()] 1415 | l9[-1][1] = leaf_target_init_val # E 1416 | 1417 | l10 = [[], [0, 1, 2, 3, 4, 5, 7, 9], leaf_base.copy()] 1418 | l10[-1][0] = leaf_target_init_val # N 1419 | 1420 | init_leaves = [ 1421 | l0, 1422 | l1, 1423 | l2, 1424 | l3, 1425 | l4, 1426 | l5, 1427 | l6, 1428 | l7, 1429 | l8, 1430 | l9, 1431 | l10 1432 | ] 1433 | action_network = ProLoNet(input_dim=dim_in, 1434 | weights=init_weights, 1435 | comparators=init_comparators, 1436 | leaves=init_leaves, 1437 | alpha=1, 1438 | is_value=False) 1439 | value_network = ProLoNet(input_dim=dim_in, 1440 | weights=init_weights, 1441 | comparators=init_comparators, 1442 | leaves=init_leaves, 1443 | alpha=1, 1444 | is_value=True) 1445 | return action_network, value_network 1446 | --------------------------------------------------------------------------------