Spaces:
Build error
Build error
Allow to pass hiperparameters as command line arguments
Browse filesFiles changed (5)
- a3c/discrete_A3C.py+12-20
- a3c/utils.py+9-8
- main.py+8-7
- wordle_env/__init__.py+6
- wordle_env/wordle.py+9-10
12 unmodified lines1314151617181920213 unmodified lines25262728293031325 unmodified lines38394041424344454633 unmodified lines80818283848586872 unmodified lines9091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212 unmodified linesfrom .utils import v_wrap, set_init, push_and_pull, recordimport numpy as npUPDATE_GLOBAL_ITER = 5GAMMA = 0.9MAX_EP = 500000class Net(nn.Module):def __init__(self, s_dim, a_dim, word_list, words_width):3 unmodified linesn_emb = 32# self.pi1 = nn.Linear(s_dim, 128)# self.pi2 = nn.Linear(128, a_dim)self.v1 = nn.Linear(s_dim, 128)self.v2 = nn.Linear(128, n_emb)self.v3 = nn.Linear(n_emb, 1)set_init([ self.v1, self.v2]) # n_embself.distribution = torch.distributions.Categorical5 unmodified linesword_array[i, j*26 + (ord(c) - ord('A'))] = 1self.words = torch.Tensor(word_array)self.f_word = nn.Sequential(nn.Linear(word_width, 128),nn.Tanh(),nn.Linear(128, n_emb),)def forward(self, x):33 unmodified linesclass Worker(mp.Process):def __init__(self, gnet, opt, global_ep, global_ep_r, res_queue, name, env, N_S, N_A, words_list, word_width, winning_ep):super(Worker, self).__init__()self.name = 'w%02i' % nameself.g_ep, self.g_ep_r, self.res_queue, self.winning_ep = global_ep, global_ep_r, res_queue, winning_epself.gnet, self.opt = gnet, opt2 unmodified linesself.env = env.unwrappeddef run(self):total_step = 1while self.g_ep.value < MAX_EP:s = self.env.reset()buffer_s, buffer_a, buffer_r = [], [], []ep_r = 0.while True:if self.name == 'w00':self.env.render()a = self.lnet.choose_action(v_wrap(s[None, :]))s_, r, done, _ = self.env.step(self.env.encode_word(self.word_list[a]))ep_r += rbuffer_a.append(a)buffer_s.append(s)buffer_r.append(r)if total_step % UPDATE_GLOBAL_ITER == 0 or done: # update global and assign to local net# syncpush_and_pull(self.opt, self.lnet, self.gnet, done, s_, buffer_s, buffer_a, buffer_r, GAMMA)if done: # done and print informationgoal_word = self.env.decode_word(self.env.goal_word)record(self.g_ep, self.g_ep_r, ep_r, self.res_queue, self.name, goal_word, self.word_list[a], len(buffer_a), self.winning_ep)breakbuffer_s, buffer_a, buffer_r = [], [], []s = s_total_step += 1self.res_queue.put(None)12 unmodified lines131415161718193 unmodified lines23242526272829305 unmodified lines36373839404142434433 unmodified lines7879808182838485862 unmodified lines899091929394959697989910010110210310410510610710810911011111211311412 unmodified linesfrom .utils import v_wrap, set_init, push_and_pull, recordimport numpy as npGAMMA = 0.9class Net(nn.Module):def __init__(self, s_dim, a_dim, word_list, words_width):3 unmodified linesn_emb = 32# self.pi1 = nn.Linear(s_dim, 128)# self.pi2 = nn.Linear(128, a_dim)self.v1 = nn.Linear(s_dim, 256)self.v2 = nn.Linear(256, n_emb)self.v3 = nn.Linear(n_emb, 1)set_init([ self.v1, self.v2]) # n_embself.distribution = torch.distributions.Categorical5 unmodified linesword_array[i, j*26 + (ord(c) - ord('A'))] = 1self.words = torch.Tensor(word_array)self.f_word = nn.Sequential(nn.Linear(word_width, 64),nn.Tanh(),nn.Linear(64, n_emb),)def forward(self, x):33 unmodified linesclass Worker(mp.Process):def __init__(self, max_ep, gnet, opt, global_ep, global_ep_r, res_queue, name, env, N_S, N_A, words_list, word_width, winning_ep):super(Worker, self).__init__()self.max_ep = max_epself.name = 'w%02i' % nameself.g_ep, self.g_ep_r, self.res_queue, self.winning_ep = global_ep, global_ep_r, res_queue, winning_epself.gnet, self.opt = gnet, opt2 unmodified linesself.env = env.unwrappeddef run(self):while self.g_ep.value < self.max_ep:s = self.env.reset()buffer_s, buffer_a, buffer_r = [], [], []ep_r = 0.while True:a = self.lnet.choose_action(v_wrap(s[None, :]))s_, r, done, _ = self.env.step(a)ep_r += rbuffer_a.append(a)buffer_s.append(s)buffer_r.append(r)if done: # update global and assign to local net# syncpush_and_pull(self.opt, self.lnet, self.gnet, done, s_, buffer_s, buffer_a, buffer_r, GAMMA)goal_word = self.word_list[self.env.goal_word]record(self.g_ep, self.g_ep_r, ep_r, self.res_queue, self.name, goal_word, self.word_list[a], len(buffer_a), self.winning_ep)buffer_s, buffer_a, buffer_r = [], [], []breaks = s_self.res_queue.put(None)
57 unmodified lines585960616263646566676857 unmodified linesres_queue.put(global_ep_r.value)if goal_word == action:winning_ep.value += 1print(name,"Ep:", global_ep.value,"| Ep_r: %.0f" % global_ep_r.value,"| Goal :", goal_word,"| Action: ", action,"| Actions: ", action_number)57 unmodified lines58596061626364656667686957 unmodified linesres_queue.put(global_ep_r.value)if goal_word == action:winning_ep.value += 1if global_ep.value % 100 == 0:print(name,"Ep:", global_ep.value,"| Ep_r: %.0f" % global_ep_r.value,"| Goal :", goal_word,"| Action: ", action,"| Actions: ", action_number)
12342 unmodified lines7891011121314151617181920212223242526272829import osimport gymimport matplotlib.pyplot as pltimport torch.multiprocessing as mp2 unmodified linesfrom a3c.shared_adam import SharedAdamfrom wordle_env.wordle import WordleEnvBaseos.environ["OMP_NUM_THREADS"] = "1"env = gym.make('WordleEnv100FullAction-v0')N_S = env.observation_space.shape[0]N_A = env.action_space.shape[0]if __name__ == "__main__":words_list = env.wordsword_width = len(env.words[0])gnet = Net(N_S, N_A, words_list, word_width) # global networkgnet.share_memory() # share the global parameters in multiprocessingopt = SharedAdam(gnet.parameters(), lr=1e-4, betas=(0.92, 0.999)) # global optimizerglobal_ep, global_ep_r, res_queue, win_ep = mp.Value('i', 0), mp.Value('d', 0.), mp.Queue(), mp.Value('i', 0)# parallel trainingworkers = [Worker(gnet, opt, global_ep, global_ep_r, res_queue, i, env, N_S, N_A, words_list, word_width, win_ep) for i in range(mp.cpu_count())][w.start() for w in workers]res = [] # record episode reward to plotwhile True:123452 unmodified lines89101112131415161718192021222324252627282930import osimport sysimport gymimport matplotlib.pyplot as pltimport torch.multiprocessing as mp2 unmodified linesfrom a3c.shared_adam import SharedAdamfrom wordle_env.wordle import WordleEnvBaseos.environ["OMP_NUM_THREADS"] = "1"if __name__ == "__main__":max_ep = int(sys.argv[1]) if len(sys.argv) > 1 else 100000env_id = sys.argv[2] if len(sys.argv) > 2 else 'WordleEnv100FullAction-v0'env = gym.make(env_id)n_s = env.observation_space.shape[0]n_a = env.action_space.nwords_list = env.wordsword_width = len(env.words[0])gnet = Net(n_s, n_a, words_list, word_width) # global networkgnet.share_memory() # share the global parameters in multiprocessingopt = SharedAdam(gnet.parameters(), lr=1e-4, betas=(0.92, 0.999)) # global optimizerglobal_ep, global_ep_r, res_queue, win_ep = mp.Value('i', 0), mp.Value('d', 0.), mp.Queue(), mp.Value('i', 0)# parallel trainingworkers = [Worker(max_ep, gnet, opt, global_ep, global_ep_r, res_queue, i, env, n_s, n_a, words_list, word_width, win_ep) for i in range(mp.cpu_count())][w.start() for w in workers]res = [] # record episode reward to plotwhile True:
34 unmodified lines35363738394034 unmodified linesmax_episode_steps=500,)register(id="WordleEnv100FullAction-v0",entry_point=wordle.WordleEnv100FullAction,34 unmodified lines35363738394041424344454634 unmodified linesmax_episode_steps=500,)register(id="WordleEnv100fiftyAction-v0",entry_point=wordle.WordleEnv100fiftyAction,max_episode_steps=500,)register(id="WordleEnv100FullAction-v0",entry_point=wordle.WordleEnv100FullAction,
50 unmodified lines5152535455565712 unmodified lines70717273747576777879808182838412 unmodified lines97989910010110210310410510610710810911011111211311411511640 unmodified lines15715815916016116250 unmodified linesassert len(words) == len(frequencies), f'{len(words), len(frequencies)}'self.frequencies = np.array(frequencies, dtype=np.float32) / sum(frequencies)self.action_space = spaces.MultiDiscrete(self.words_as_action_space())self.observation_space = spaces.MultiDiscrete(state.get_nvec(self.max_turns))self.done = True12 unmodified lines"should always call 'reset()' once you receive 'done = ""True' -- any further steps are undefined behavior.")word = self.decode_word(action)goal_word = self.decode_word(self.goal_word)# assert word in self.words, f'{word} not in words list'self.state = self.state_updater(state=self.state,word=word,goal_word=goal_word)reward = 0action = tuple(map(tuple, action))if action == self.goal_word:self.done = True#reward = REWARD12 unmodified linesself.state = state.new(self.max_turns)self.done = Falserandom_word = random.choice(self.words[:self.allowable_words])encoded_random_word = self.encode_word(random_word)self.goal_word = tuple(map(tuple, encoded_random_word))return self.state.copy()def set_goal_word(self, goal_word: str):encoded_word = self.encode_word(goal_word.upper())self.goal_word = tuple(map(tuple, encoded_word))def set_goal_encoded(self, goal_encoded: int):goal_encoded = tuple(map(tuple, goal_encoded))self.goal_word = goal_encodeddef words_as_action_space(self):return [[[2] * WORDLE_N] * len(WORDLE_CHARS)] * len(self.words)def encode_word(self, word):encoded_word = np.array(40 unmodified linesdef __init__(self):super().__init__(words=_load_words(100), allowable_words=2)class WordleEnv100FullAction(WordleEnvBase):def __init__(self):50 unmodified lines5152535455565712 unmodified lines707172737475767778798081828312 unmodified lines9697989910010110210310410510610710810911011111240 unmodified lines15315415515615715815916016150 unmodified linesassert len(words) == len(frequencies), f'{len(words), len(frequencies)}'self.frequencies = np.array(frequencies, dtype=np.float32) / sum(frequencies)self.action_space = spaces.Discrete(self.words_as_action_space())self.observation_space = spaces.MultiDiscrete(state.get_nvec(self.max_turns))self.done = True12 unmodified lines"should always call 'reset()' once you receive 'done = ""True' -- any further steps are undefined behavior.")word = self.words[action]goal_word = self.words[self.goal_word]# assert word in self.words, f'{word} not in words list'self.state = self.state_updater(state=self.state,word=word,goal_word=goal_word)reward = 0if action == self.goal_word:self.done = True#reward = REWARD12 unmodified linesself.state = state.new(self.max_turns)self.done = Falserandom_word = random.choice(self.words[:self.allowable_words])self.goal_word = self.words.index(random_word)return self.state.copy()def set_goal_word(self, goal_word: str):self.goal_word = self.words.index(goal_word)def set_goal_encoded(self, goal_encoded: int):self.goal_word = goal_encodeddef words_as_action_space(self):return len(self.words)def encode_word(self, word):encoded_word = np.array(40 unmodified linesdef __init__(self):super().__init__(words=_load_words(100), allowable_words=2)class WordleEnv100fiftyAction(WordleEnvBase):def __init__(self):super().__init__(words=_load_words(100), allowable_words=50)class WordleEnv100FullAction(WordleEnvBase):def __init__(self):
a3c/discrete_A3C.py+12-20
a3c/utils.py+9-8
main.py+8-7
wordle_env/__init__.py+6
wordle_env/wordle.py+9-10