def main(): """ Entry-point for the program. """ args = _parse_args() env = batched_gym_env([partial(make_single_env, args.game)] * args.workers) # Using BatchedFrameStack with concat=False is more # memory efficient than other stacking options. env = BatchedFrameStack(env, num_images=4, concat=False) with tf.Session() as sess: def make_net(name): return NatureQNetwork(sess, env.action_space.n, gym_space_vectorizer(env.observation_space), name, dueling=True) dqn = DQN(make_net('online'), make_net('target')) player = BatchedPlayer(env, EpsGreedyQNetwork(dqn.online_net, args.epsilon)) optimize = dqn.optimize(learning_rate=args.lr) sess.run(tf.global_variables_initializer()) reward_hist = [] total_steps = 0 def _handle_ep(steps, rew): nonlocal total_steps total_steps += steps reward_hist.append(rew) if len(reward_hist) == REWARD_HISTORY: print('%d steps: mean=%f' % (total_steps, sum(reward_hist) / len(reward_hist))) reward_hist.clear() dqn.train(num_steps=int(1e7), player=player, replay_buffer=UniformReplayBuffer(args.buffer_size), optimize_op=optimize, target_interval=args.target_interval, batch_size=args.batch_size, min_buffer_size=args.min_buffer_size, handle_ep=_handle_ep) env.close()
def main(): """Run DQN until the environment throws an exception.""" # "results/rainbow/2/videos/6" env = make_env(stack=False, scale_rew=False, render=20, monitor=None, timelimit=False) # env = AllowBacktracking(make_env(stack=False, scale_rew=False)) # TODO we might not want to allow backtracking, it kinda hurts in mario env = BatchedFrameStack(BatchedGymEnv([[env]]), num_images=4, concat=False) config = tf.ConfigProto() config.gpu_options.allow_growth = True # pylint: disable=E1101 config.gpu_options.per_process_gpu_memory_fraction = 0.6 with tf.Session(config=config) as sess: dqn = DQN(*rainbow_models(sess, env.action_space.n, gym_space_vectorizer(env.observation_space), min_val=-200, max_val=200)) # TODO rebuild the online_net form the saved model # type <anyrl.models.dqn_dist.NatureDistQNetwork object at ???> # important methods # model = dqn.online_net player = NStepPlayer(BatchedPlayer(env, dqn.online_net), 3) with tf.device("/cpu"): # sess.run(tf.global_variables_initializer()) vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES) try: for i in tqdm(range(100000)): trajectories = player.play() for trajectori in trajectories: trajectori pass except KeyboardInterrupt: env.close()
def main(): """Run DQN until the environment throws an exception.""" env = AllowBacktracking(make_env(stack=False, scale_rew=False)) env = BatchedFrameStack(BatchedGymEnv([[env]]), num_images=4, concat=False) config = tf.ConfigProto() config.gpu_options.allow_growth = True # pylint: disable=E1101 with tf.Session(config=config) as sess: dqn = DQN(*rainbow_models(sess, env.action_space.n, gym_space_vectorizer(env.observation_space), min_val=-200, max_val=200)) player = NStepPlayer(BatchedPlayer(env, dqn.online_net), 3) optimize = dqn.optimize(learning_rate=1e-4) sess.run(tf.global_variables_initializer()) saver = tf.train.Saver() saver.restore(sess, "/root/compo/model.ckpt") #print('model restored') replay_buffer = pickle.load( gzip.open('/root/compo/replay_buffer.p.gz', 'rb')) replay_buffer.alpha = 0.2 replay_buffer.beta = 0.4 replay_buffer.capacity = 100000 restore_ppo2_weights(sess) dqn.train( num_steps=2000000, # Make sure an exception arrives before we stop. player=player, replay_buffer= replay_buffer, #PrioritizedReplayBuffer(500000, 0.5, 0.4, epsilon=0.1), optimize_op=optimize, train_interval=4, target_interval=8192, batch_size=32, min_buffer_size=20000)
def main(): """Run DQN until the environment throws an exception.""" env = AllowBacktracking(make_env(stack=False, scale_rew=False)) env = BatchedFrameStack(BatchedGymEnv([[env]]), num_images=4, concat=False) config = tf.ConfigProto() config.gpu_options.allow_growth = True # pylint: disable=E1101 with tf.Session(config=config) as sess: dqn = DQN(*rainbow_models(sess, env.action_space.n, gym_space_vectorizer(env.observation_space), min_val=-200, max_val=200)) player = NStepPlayer(BatchedPlayer(env, dqn.online_net), 3) optimize = dqn.optimize(learning_rate=1e-4) sess.run(tf.global_variables_initializer()) dqn.train(num_steps=2000000, # Make sure an exception arrives before we stop. player=player, replay_buffer=PrioritizedReplayBuffer(500000, 0.5, 0.4, epsilon=0.1), optimize_op=optimize, train_interval=1, target_interval=8192, batch_size=32, min_buffer_size=20000)
def test_remote(args): if not args.anyrl: agent_folder = args.folder env = EnvWrap(RemoteEnv(os.environ['REMOTE_HOST']), remote_testing=True) agent = load_agent(agent_folder, save_dir="./{}/".format(agent_folder)) test(agent, env) agent.close() env.close() else: online = builder.build_network(sess, 'online') target = builder.build_network(sess, 'target') dqn = DQN(online, target) sess.run(tf.global_variables_initializer()) with tf.Session(graph=tf.Graph()) as sess: sess.run(tf.global_variables_initializer()) with tf.Session(graph=tf.Graph()) as sess: def add_hyperopt_parser(subparsers): parser_hyperopt = subparsers.add_parser('hyperopt') parser_hyperopt.add_argument("environment", type=str, help="OpenAI Gym environment to train the agent on") parser_hyperopt.add_argument("num_agents", type=int, help="Number of agents to be generated and tested") parser_hyperopt.add_argument("num_episodes", type=int, help="Number of episodes each agent should be trained on") parser_hyperopt.add_argument('-b', '--base-agent', type=str, help="JSON file to load the base agent spec from", default="agent.json") parser_hyperopt.add_argument('-hp', '--hyperparam-space', type=str, help="JSON file to load the hyperparameter search space from", default="hyperparam_space.json") def add_train_parser(subparsers): parser_train = subparsers.add_parser('train') parser_train.add_argument("agent_name", type=str, help="Name of the folder the agent is stored in \ within the folder specified by --folder (-f)") parser_train.add_argument("num_episodes", type=int, help="Number of episodes to train on") def add_test_remote_parser(subparsers): parser_test_remote = subparsers.add_parser('test-remote') parser_test_remote.add_argument("agent_name", type=str, help="Name of the folder the agent is stored in \ within the folder specified by --folder (-f)") def parse_args(): parser = argparse.ArgumentParser( description="Suite of tools for training reinforcement learning agents") subparsers = parser.add_subparsers() subparsers.required = True subparsers.dest = 'mode' parser.add_argument('-f', '--folder', type=str, help="Folder the agent files are stored in (default: ./models)", default="./models") parser.add_argument('-d', '--anyrl', action="store_true", help="Use DQN agent") parser.add_argument('-r', '--rainbow', action="store_true", help="Use rainbow DQN agent") parser.add_argument('-s', '--seasonals', action="store_true", help="Use seasonals environment") add_hyperopt_parser(subparsers) add_train_parser(subparsers) add_test_remote_parser(subparsers) return parser.parse_args() def main(): args = parse_args() if args.environment == "seasonals-v1": import gym from gym_seasonals.envs.seasonals_env import SeasonalsEnv from gym_seasonals.envs.seasonals_env import portfolio_var from gym_seasonals.envs.remote_env import RemoteEnv if args.mode == "hyperopt": hyperparam_search(space_filename=args.hyperparam_space, env_name=args.environment, num_tests=args.num_agents, num_episodes=args.num_episodes, save_folder=args.folder, base_agent=args.base_agent, anyrl=args.anyrl, rainbow=args.rainbow) elif args.mode == 'train': dqn_train(args) elif args.mode == 'test-remote': test_remote(args)
def anyrl_experiment(args, env_name, agent_folder=None, visualize=True, num_episodes=500, rainbow=False, seasonals=False): tf.reset_default_graph() seasonals = env_name == 'seasonals-v1' if seasonals: os.mkdir(agent_folder) ep_record = Record(filename=os.path.join(agent_folder, "model")) handle_ep = functools.partial(handle_ep_with_context, num_episodes, ep_record) def video_callable_with_context(context, episode_id): if episode_id == 50 or episode_id % 100 == 0: return True if np.mean(context.rewards[-98:]) > 200: return True return False env = gym.wrappers.Monitor( gym.make(env_name), os.path.join(agent_folder, "monitor"), video_callable=functools.partial( video_callable_with_context, ep_record ) ) if not seasonals else EnvWrap( gym.make('seasonals-v1')) env.set_simulation_window(start_index=1500, end_index=1968) config = tf.ConfigProto() config.gpu_options.allow_growth = True builder_class = RainbowDQNBuilder if rainbow else DQNBuilder builder = builder_class(env, args) with tf.Session(config=config) as sess: online = builder.build_network(sess, 'online') target = builder.build_network(sess, 'target') dqn = DQN(online, target) train_kwargs = builder.finish(sess, dqn) sess.run(tf.global_variables_initializer()) try: dqn.train(num_steps=3000000, train_interval=4, target_interval=args['target_sync_frequency'], batch_size=32, min_buffer_size=200, handle_ep=handle_ep, **train_kwargs) except gym.error.Error: aves, std_dev = plot_rewards(ep_record.rewards, save_dir=agent_folder, ylims=((-500, 250) if not seasonals else None), half_window=round(num_episodes / 20)) pass except KeyboardInterrupt: aves, std_dev = plot_rewards(ep_record.rewards, save_dir=agent_folder, ylims=((-500, 250) if not seasonals else None), half_window=round(num_episodes / 20)) raise filename = os.path.join(agent_folder, "model") if not os.path.exists(filename): os.mkdir(filename) tf.train.Saver().save(sess, os.path.join(filename, "model-best.ckpt")) experiment_data = {"final_test_reward":np.mean(ep_record.rewards[-1]), "test_average_last_50":np.mean(ep_record.rewards[-50::10]), "train_average_last_50":np.mean(ep_record.rewards[-50:]), "test_average_last_10":np.mean(ep_record.rewards[-10::5]), "train_average_last_10":np.mean(ep_record.rewards[-10:]), "max_score":max(ep_record.rewards) } experiment_data.update(args) experiment_data['solved'] = True \ if np.mean(ep_record.rewards[-100:]) > 200 \ else False experiment_data['final_std_dev'] = std_dev del builder del dqn env.close() experiment_data['agent'] = agent_folder.split('/')[-1] return experiment_data
def main(): """ Entry-point for the program. """ args = _parse_args() # batched env = creates gym env, not sure what batched means # make_single_env = GrayscaleEnv > DownsampleEnv # GrayscaleEnv = turns RGB into grayscale # DownsampleEnv = down samples observation by N times where N is the specified variable (e.g. 2x smaller) env = batched_gym_env([partial(make_single_env, args.game)] * args.workers) env_test = make_single_env(args.game) #make_single_env(args.game) print('OBSSSS', env_test.observation_space) #env = CustomWrapper(args.game) # Using BatchedFrameStack with concat=False is more # memory efficient than other stacking options. env = BatchedFrameStack(env, num_images=4, concat=False) with tf.Session() as sess: def make_net(name): return rainbow_models(sess, env.action_space.n, gym_space_vectorizer(env.observation_space), min_val=-200, max_val=200) dqn = DQN(*rainbow_models(sess, env.action_space.n, gym_space_vectorizer(env.observation_space), min_val=-200, max_val=200)) player = BatchedPlayer(env, EpsGreedyQNetwork(dqn.online_net, args.epsilon)) optimize = dqn.optimize(learning_rate=args.lr) sess.run(tf.global_variables_initializer()) reward_hist = [] total_steps = 0 def _handle_ep(steps, rew): nonlocal total_steps total_steps += steps reward_hist.append(rew) if len(reward_hist) == REWARD_HISTORY: print('%d steps: mean=%f' % (total_steps, sum(reward_hist) / len(reward_hist))) reward_hist.clear() dqn.train(num_steps=int(1e7), player=player, replay_buffer=UniformReplayBuffer(args.buffer_size), optimize_op=optimize, target_interval=args.target_interval, batch_size=args.batch_size, min_buffer_size=args.min_buffer_size, handle_ep=_handle_ep) env.close()
def main(): if local_env: # Select Random Level if local levels = ['SpringYardZone.Act3', 'SpringYardZone.Act2', 'GreenHillZone.Act3', 'GreenHillZone.Act1', 'StarLightZone.Act2', 'StarLightZone.Act1', 'MarbleZone.Act2', 'MarbleZone.Act1', 'MarbleZone.Act3', 'ScrapBrainZone.Act2', 'LabyrinthZone.Act2', 'LabyrinthZone.Act1', 'LabyrinthZone.Act3'] level_choice = random.randrange(0, 13, 1) env = make_env(stack=True, scale_rew=False, local=local_env, level_choice=level_choice) #-3 else: print('connecting to remote environment') env = grc.RemoteEnv('tmp/sock') print('starting episode') env = AllowBacktracking(env) solutions = env.solutions # Track Solutions state_size = env.observation_space action_size = env.action_space.n print(state_size, action_size) env.assist = False env.trainer = train # Begin with mentor led exploration env.reset() while env.total_steps_ever <= TOTAL_TIMESTEPS: # Interact with Retro environment until Total TimeSteps expire. while env.trainer: print('Entering Self Play') keys = getch() if keys == 'A': env.control(-1) if keys == 'B': env.control(4) if keys == 'C': env.control(3) if keys == 'D': env.control(2) buttons = ["B", "A", "MODE", "START", "UP", "DOWN", "LEFT", "RIGHT", "C", "Y", "X", "Z"] actions = [['LEFT'], ['RIGHT'], ['LEFT', 'DOWN'], ['RIGHT', 'DOWN'], ['DOWN'], ['DOWN', 'B'], ['B']] if keys == 'rr': env.trainer = False continue if keys == ' ': env.close() env = make_env(stack=False, scale_rew=False, local=local_env) env = AllowBacktracking(env) env.reset() # Initialize Gaming Environment env.trainer = True if env.episode % RL_PLAY_PCT == 0: tf.reset_default_graph() with tf.Session() as sess: def make_net(name): return MLPQNetwork(sess, env.action_space.n, gym_space_vectorizer(env.observation_space), name, layer_sizes=[32]) dqn = DQN(make_net('online'), make_net('target')) bplayer = BasicPlayer(env, EpsGreedyQNetwork(dqn.online_net, EPSILON), batch_size=STEPS_PER_UPDATE) optimize = dqn.optimize(learning_rate=LEARNING_RATE) sess.run(tf.global_variables_initializer()) env.agent = 'DQN' dqn.train(num_steps=TRAINING_STEPS, player=bplayer, replay_buffer=PrioritizedReplayBuffer(500000, 0.5, 0.4, epsilon=0.1), optimize_op=optimize, target_interval=200, batch_size=64, min_buffer_size=200, handle_ep=lambda _, rew: print('Exited DQN with : ' + str(rew) + str(env.steps))) new_ep = True # New Episode Flag while new_ep: if new_ep: if (solutions and random.random() < EXPLOIT_BIAS + env.total_steps_ever / TOTAL_TIMESTEPS): new_state, new_rew, done = env.spawn() continue else: env.reset() new_ep = False env.agent = 'JERK' rew, new_ep = move(env, 100) if not new_ep and rew <= 0: #print('backtracking due to negative reward: %f' % rew) _, new_ep = move(env, 70, left=True) if new_ep: solutions.append(([max(env.reward_history)], env.best_sequence()))
def main(): parser = argparse.ArgumentParser() parser.add_argument('--restore', '-restore', action='store_true', help='restore from checkpoint file') parser.add_argument('--record', '-record', action='store_true', help='record bk2 movies') args = parser.parse_args() """Run DQN until the environment throws an exception.""" env = AllowBacktracking( make_env(stack=False, scale_rew=False, record=args.record)) env = BatchedFrameStack(BatchedGymEnv([[env]]), num_images=4, concat=False) checkpoint_dir = os.path.join(os.getcwd(), 'results') results_dir = os.path.join(os.getcwd(), 'results', time.strftime("%d-%m-%Y_%H-%M-%S")) if not os.path.exists(results_dir): os.makedirs(results_dir) summary_writer = tf.summary.FileWriter(results_dir) # TODO # env = wrappers.Monitor(env, results_dir, force=True) config = tf.ConfigProto() config.gpu_options.allow_growth = True # pylint: disable=E1101 with tf.Session(config=config) as sess: dqn = DQN(*rainbow_models(sess, env.action_space.n, gym_space_vectorizer(env.observation_space), min_val=-200, max_val=200)) saver = tf.train.Saver() if args.restore: latest_checkpoint = tf.train.latest_checkpoint(checkpoint_dir) if latest_checkpoint: print("Loading model checkpoint {} ...\n".format( latest_checkpoint)) saver.restore(sess, latest_checkpoint) else: print("Checkpoint not found") player = NStepPlayer(BatchedPlayer(env, dqn.online_net), 3) optimize = dqn.optimize(learning_rate=1e-4) sess.run(tf.global_variables_initializer()) reward_hist = [] total_steps = 0 # runs with every completed episode def _handle_ep(steps, rew): nonlocal total_steps total_steps += steps reward_hist.append(rew) summary_reward = tf.Summary() summary_reward.value.add(tag='global/reward', simple_value=rew) summary_writer.add_summary(summary_reward, global_step=total_steps) print('save model') saver.save(sess=sess, save_path=checkpoint_dir + '/model', global_step=total_steps) if len(reward_hist) == REWARD_HISTORY: print('%d steps: mean=%f' % (total_steps, sum(reward_hist) / len(reward_hist))) summary_meanreward = tf.Summary() summary_meanreward.value.add(tag='global/mean_reward', simple_value=sum(reward_hist) / len(reward_hist)) summary_writer.add_summary(summary_meanreward, global_step=total_steps) reward_hist.clear() dqn.train( num_steps=7000000, # Make sure an exception arrives before we stop. player=player, replay_buffer=PrioritizedReplayBuffer(500000, 0.5, 0.4, epsilon=0.1), optimize_op=optimize, train_interval=1, target_interval=8192, batch_size=32, min_buffer_size=20000, handle_ep=_handle_ep)
def main(): if local_env: # Select Random Level if local from retro_contest.local import make levels = [ 'SpringYardZone.Act3', 'SpringYardZone.Act2', 'GreenHillZone.Act3', 'GreenHillZone.Act1', 'StarLightZone.Act2', 'StarLightZone.Act1', 'MarbleZone.Act2', 'MarbleZone.Act1', 'MarbleZone.Act3', 'ScrapBrainZone.Act2', 'LabyrinthZone.Act2', 'LabyrinthZone.Act1', 'LabyrinthZone.Act3' ] level_choice = levels[random.randrange(0, 13, 1)] env = make(game='SonicTheHedgehog-Genesis', state=level_choice) else: print('connecting to remote environment') env = grc.RemoteEnv('tmp/sock') print('starting episode') env = TrackedEnv(env) solutions = env.solutions # Track Solutions state_size = env.observation_space action_size = env.action_space.n print(state_size, action_size) env.assist = False env.trainer = False # Begin with mentor led exploration env.resume_rl(True) # Begin with RL exploration env.reset() while env.total_steps_ever <= TOTAL_TIMESTEPS: # Interact with Retro environment until Total TimeSteps expire. while env.trainer: print('Entering Self Play') keys = getch() if keys == 'A': env.control(-1) if keys == 'B': env.control(4) if keys == 'C': env.control(3) if keys == 'D': env.control(2) if keys == 'rr': env.trainer = False continue if keys == ' ': env.close() env = make(game='SonicTheHedgehog-Genesis', state=levels[random.randrange(0, 13, 1)]) env = TrackedEnv(env) env.reset() # Initialize Gaming Environment env.trainer = True if env.steps > 1: print('Prev Rew', env.step_rew_history[-1], 'Curr_Loc', env.reward_history[-1], 'Med Rew', np.median(env.step_rew_history[-3:])) if env.episode % RL_PLAY_PCT == 0: tf.reset_default_graph() with tf.Session() as sess: def make_net(name): return MLPQNetwork(sess, env.action_space.n, gym_space_vectorizer( env.observation_space), name, layer_sizes=[32]) dqn = DQN(make_net('online'), make_net('target')) bplayer = BasicPlayer(env, EpsGreedyQNetwork( dqn.online_net, EPSILON), batch_size=STEPS_PER_UPDATE) optimize = dqn.optimize(learning_rate=LEARNING_RATE) sess.run(tf.global_variables_initializer()) env.agent = 'DQN' dqn.train( num_steps=TRAINING_STEPS, player=bplayer, replay_buffer=PrioritizedReplayBuffer(500000, 0.5, 0.4, epsilon=0.1), optimize_op=optimize, target_interval=200, batch_size=64, min_buffer_size=200, handle_ep=lambda _, rew: print('Exited DQN with : ' + str( rew) + str(env.steps))) new_ep = True # New Episode Flag while new_ep: if new_ep: if (solutions and random.random() < EXPLOIT_BIAS + env.total_steps_ever / TOTAL_TIMESTEPS): solutions = sorted(solutions, key=lambda x: np.mean(x[0])) best_pair = solutions[-1] new_rew = exploit(env, best_pair[1]) best_pair[0].append(new_rew) print('replayed best with reward %f' % new_rew) print(best_pair[0]) continue else: env.reset() new_ep = False env.agent = 'JERK' rew, new_ep = move(env, 100) if not new_ep and rew <= 0: #print('backtracking due to negative reward: %f' % rew) _, new_ep = move(env, 70, left=True) if new_ep: solutions.append( ([max(env.reward_history)], env.best_sequence()))
def main(): """Run DQN until the environment throws an exception.""" print('creating env') env = AllowBacktracking(make_env(stack=False, scale_rew=False)) env = BatchedFrameStack(BatchedGymEnv([[env]]), num_images=4, concat=False) config = tf.ConfigProto() config.gpu_options.allow_growth = True # pylint: disable=E1101 print('starting tf session') with tf.Session(config=config) as sess: print('creating agent') online_net, target_net = rainbow_models(sess, env.action_space.n, gym_space_vectorizer( env.observation_space), min_val=-200, max_val=200) dqn = DQN(online_net, target_net) player = NStepPlayer(BatchedPlayer(env, dqn.online_net), 3) optimize = dqn.optimize(learning_rate=1e-4) saver = tf.train.Saver() sess.run(tf.global_variables_initializer()) train_steps = 5000 print('training steps:', train_steps) for j in range(1): print(j) start = time.time() dqn.train( num_steps= train_steps, # Make sure an exception arrives before we stop. player=player, replay_buffer=PrioritizedReplayBuffer(500000, 0.5, 0.4, epsilon=0.1), optimize_op=optimize, train_interval=1, target_interval=8192, batch_size=32, min_buffer_size=10000) end = time.time() print(end - start) print('done training') print('save nn') save_path = saver.save(sess, "saved_models/rainbow5.ckpt") print("Model saved in path: %s" % save_path) tvars = tf.trainable_variables() tvars_vals = sess.run(tvars) #for var, val in zip(tvars, tvars_vals): # print(var.name, val[0]) #print(tvars_vals[0][-5:]) #print('stepping') #obs = env.reset() #online_net.step(obs, obs) '''
def main(): """Run DQN until the environment throws an exception.""" #env = AllowBacktracking(make_env(stack=False, scale_rew=False)) #envs = make_training_envs() #env = BatchedFrameStack(BatchedGymEnv(envs), num_images=4, concat=False) #env = BatchedFrameStack(BatchedGymEnv([[env]]), num_images=4, concat=False) envs = get_training_envs() game, state = random.choice(envs) env = make_training_env(game, state, stack=False, scale_rew=False) env = prep_env(env) config = tf.ConfigProto() config.gpu_options.allow_growth = True # pylint: disable=E1101 with tf.Session(config=config) as sess: dqn = DQN(*models(sess, env.action_space.n, gym_space_vectorizer(env.observation_space), min_val=-200, max_val=200)) player = NStepPlayer(BatchedPlayer(env, dqn.online_net), 3) optimize = dqn.optimize(learning_rate=1e-4) loss = dqn.loss train_writer = tf.summary.FileWriter('./logs/multiple/train', sess.graph) tf.summary.scalar("loss", loss) reward = tf.Variable(0., name='reward', trainable=False) tf.summary.scalar('reward', tf.reduce_mean(reward)) steps = tf.Variable(0, name='steps', trainable=False) tf.summary.scalar('steps', tf.reduce_mean(steps)) summary_op = tf.summary.merge_all() sess.run(tf.global_variables_initializer()) print(tf.trainable_variables()) #graph = tf.get_default_graph() #restore_saver = tf.train.Saver({ # 'dense1/bias': graph.get_tensor_by_name('online/dense1/bias:0'), # 'dense1/kernel': graph.get_tensor_by_name('online/dense1/kernel:0'), # 'layer_1/bias': graph.get_tensor_by_name('online/layer_1/bias:0'), # 'layer_1/kernel': graph.get_tensor_by_name('online/layer_1/kernel:0'), # 'layer_2/bias': graph.get_tensor_by_name('online/layer_2/bias:0'), # 'layer_2/kernel': graph.get_tensor_by_name('online/layer_2/kernel:0'), # 'layer_3/bias': graph.get_tensor_by_name('online/layer_3/bias:0'), # 'layer_3/kernel': graph.get_tensor_by_name('online/layer_3/kernel:0'), # 'dense1/bias': graph.get_tensor_by_name('online_1/dense1/bias:0'), # 'dense1/kernel': graph.get_tensor_by_name('online_1/dense1/kernel:0'), # 'layer_1/bias': graph.get_tensor_by_name('online_1/layer_1/bias:0'), # 'layer_1/kernel': graph.get_tensor_by_name('online_1/layer_1/kernel:0'), # 'layer_2/bias': graph.get_tensor_by_name('online_1/layer_2/bias:0'), # 'layer_2/kernel': graph.get_tensor_by_name('online_1/layer_2/kernel:0'), # 'layer_3/bias': graph.get_tensor_by_name('online_1/layer_3/bias:0'), # 'layer_3/kernel': graph.get_tensor_by_name('online_1/layer_3/kernel:0'), # 'dense1/bias': graph.get_tensor_by_name('online_2/dense1/bias:0'), # 'dense1/kernel': graph.get_tensor_by_name('online_2/dense1/kernel:0'), # 'layer_1/bias': graph.get_tensor_by_name('online_2/layer_1/bias:0'), # 'layer_1/kernel': graph.get_tensor_by_name('online_2/layer_1/kernel:0'), # 'layer_2/bias': graph.get_tensor_by_name('online_2/layer_2/bias:0'), # 'layer_2/kernel': graph.get_tensor_by_name('online_2/layer_2/kernel:0'), # 'layer_3/bias': graph.get_tensor_by_name('online_2/layer_3/bias:0'), # 'layer_3/kernel': graph.get_tensor_by_name('online_2/layer_3/kernel:0'), # 'dense1/bias': graph.get_tensor_by_name('target/dense1/bias:0'), # 'dense1/kernel': graph.get_tensor_by_name('target/dense1/kernel:0'), # 'layer_1/bias': graph.get_tensor_by_name('target/layer_1/bias:0'), # 'layer_1/kernel': graph.get_tensor_by_name('target/layer_1/kernel:0'), # 'layer_2/bias': graph.get_tensor_by_name('target/layer_2/bias:0'), # 'layer_2/kernel': graph.get_tensor_by_name('target/layer_2/kernel:0'), # 'layer_3/bias': graph.get_tensor_by_name('target/layer_3/bias:0'), # 'layer_3/kernel': graph.get_tensor_by_name('target/layer_3/kernel:0'), # }) #restore_saver.restore(sess, './model-images/model.ckpt') #print('model restored') weights = joblib.load('./ppo2_weights_266.joblib') #[<tf.Variable 'model/c1/w:0' shape=(8, 8, 4, 32) dtype=float32_ref>, <tf.Variable 'model/c1/b:0' shape=(1, 32, 1, 1) dtype=float32_ref>, <tf.Variable 'model/c2/w:0' shape=(4, 4, 32, 64) dtype=float32_ref>, <tf.Variable 'model/c2/b:0' shape=(1, 64, 1, 1) dtype=float32_ref>, <tf.Variable 'model/c3/w:0' shape=(3, 3, 64, 64) dtype=float32_ref>, <tf.Variable 'model/c3/b:0' shape=(1, 64, 1, 1) dtype=float32_ref>, <tf.Variable 'model/fc1/w:0' shape=(3136, 512) dtype=float32_ref>, <tf.Variable 'model/fc1/b:0' shape=(512,) dtype=float32_ref>, <tf.Variable 'model/v/w:0' shape=(512, 1) dtype=float32_ref>, <tf.Variable 'model/v/b:0' shape=(1,) dtype=float32_ref>, <tf.Variable 'model/pi/w:0' shape=(512, 7) dtype=float32_ref>, <tf.Variable 'model/pi/b:0' shape=(7,) dtype=float32_ref>] graph = tf.get_default_graph() for model in ['online', 'target']: tensor_names = [ '{}/layer_1/conv2d/kernel:0', '{}/layer_1/conv2d/bias:0', '{}/layer_2/conv2d/kernel:0', '{}/layer_2/conv2d/bias:0', '{}/layer_3/conv2d/kernel:0', '{}/layer_3/conv2d/bias:0', #'{}/dense1/kernel:0', #'{}/dense1/bias:0' ] for i in range(len(tensor_names)): tensor_name = tensor_names[i].format(model) tensor = graph.get_tensor_by_name(tensor_name) weight = weights[i] if 'bias' in tensor_name: weight = np.reshape(weight, tensor.get_shape()) print('about to assign {} value with size {}'.format( tensor_name, weights[i].shape)) sess.run(tf.assign(tensor, weight)) saver = tf.train.Saver() save_path = saver.save(sess, "./model/model.ckpt") print('Saved model') replay_buffer = PrioritizedReplayBuffer(100000, 0.5, 0.4, epsilon=0.1) #replay_buffer = pickle.load(gzip.open('./docker-build/model/replay_buffer.p.gz', 'rb')) #replay_buffer = pickle.load(open('./model/replay_buffer.p', 'rb')) total_steps = 50000000 steps_per_env = 5000 env.close() for i in range(int(total_steps / steps_per_env)): game, state = random.choice(envs) env = make_training_env(game, state, stack=False, scale_rew=False) env = prep_env(env) player = NStepPlayer(BatchedPlayer(env, dqn.online_net), 3) #dqn.train(num_steps=steps_per_env, # Make sure an exception arrives before we stop. # player=player, # replay_buffer=replay_buffer, # optimize_op=optimize, # train_interval=1, # target_interval=8192, # batch_size=32, # min_buffer_size=20000) summary = train( dqn, num_steps= steps_per_env, # Make sure an exception arrives before we stop. player=player, replay_buffer=replay_buffer, optimize_op=optimize, train_interval=4, target_interval=8192, batch_size=32, min_buffer_size=20000, summary_op=summary_op, handle_ep=lambda st, rew: (reward.assign(rew), steps.assign(st)), handle_step=lambda st, rew: (reward.assign(reward + rew), steps.assign(steps + st))) env.close() if summary: train_writer.add_summary(summary, i) else: print('No summary') save_path = saver.save(sess, "./model/model.ckpt") pickle.dump(replay_buffer, open("./model/replay_buffer.p", "wb")) print('Saved model')
def main(): """Run DQN until the environment throws an exception.""" config = tf.ConfigProto() config.gpu_options.allow_growth = True # pylint: disable=E1101 comm = MPI.COMM_WORLD # Use MPI for parallel evaluation rank = comm.Get_rank() size = comm.Get_size() env_fns, env_names = create_eval_envs() env = AllowBacktracking(env_fns[rank](stack=False, scale_rew=False)) env = BatchedFrameStack(BatchedGymEnv([[env]]), num_images=4, concat=False) with tf.Session(config=config) as sess: dqn = DQN(*rainbow_models(sess, env.action_space.n, gym_space_vectorizer(env.observation_space), min_val=-200, max_val=200)) player = NStepPlayer(BatchedPlayer(env, dqn.online_net), 3) optimize = dqn.optimize(learning_rate=1e-4) sess.run(tf.global_variables_initializer()) reward_hist = [] total_steps = 0 def _handle_ep(steps, rew, env_rewards): nonlocal total_steps total_steps += steps reward_hist.append(rew) if total_steps % 1 == 0: avg_score = sum(reward_hist[-100:]) / len(reward_hist[-100:]) # Global Score global_score = np.zeros(1) local_score = np.array(avg_score) print("Local Score for " + env_names[rank] + " at episode " + str(len(reward_hist)) + " with timesteps: " + str(total_steps) + ": " + str(local_score)) comm.Allreduce(local_score, global_score, op=MPI.SUM) global_score /= size if rank == 0: print("Global Average Score at episode: " + str(len(reward_hist)) + ": " + str(global_score)) dqn.train( num_steps=2000000, # Make sure an exception arrives before we stop. player=player, replay_buffer=PrioritizedReplayBuffer(500000, 0.5, 0.4, epsilon=0.1), optimize_op=optimize, train_interval=1, target_interval=8192, batch_size=32, min_buffer_size=20000, handle_ep=_handle_ep, save_interval=None, restore_path= './checkpoints_rainbow/model-10' # Model to be evaluated )
def train(batched_env, env_count=1, batch_size_multiplier=32, num_steps=2000000, pretrained_model='artifacts/model/model.cpkt', output_dir='artifacts/model', use_schedules=True): """ Trains on a batched_env using anyrl-py's dqn and rainbow model. env_count: The number of envs in batched_env batch_size_multiplier: batch_size of the dqn train call will be env_count * batch_size_multiplier num_steps: The number of steps to run training for pretrained_model: Load tf weights from this model file output_dir: Save tf weights to this file use_schedules: Enables the tf_schedules for the train call. Schedules require internet access, so don't include on retro-contest evaluation server """ env = CollisionMapWrapper(batched_env) env = BatchedResizeImageWrapper(env) config = tf.ConfigProto() config.gpu_options.allow_growth = True # pylint: disable=E1101 with tf.Session(config=config) as sess: dqn = DQN(*rainbow_models(sess, env.action_space.n, gym_space_vectorizer(env.observation_space), min_val=-200, max_val=200)) scheduled_saver = ScheduledSaver(save_interval=10000, save_dir=output_dir) print('Outputting trained model to', output_dir) # Reporting uses BatchedPlayer to get _total_rewards batched_player = BatchedPlayer(env, dqn.online_net) player = NStepPlayer(batched_player, 3) optimize = dqn.optimize(learning_rate=1e-4) if pretrained_model is None: print('Initializing with random weights') sess.run(tf.global_variables_initializer()) else: print('Loading pre-trained model from', pretrained_model) scheduled_saver.saver.restore(sess, pretrained_model) print('Beginning Training, steps', num_steps) tf_schedules = [] if (use_schedules): tf_schedules = [ scheduled_saver, LosswiseSchedule(num_steps, batched_player), LoadingBar(num_steps) ] print(env_count * batch_size_multiplier) dqn.train( num_steps=num_steps, player=player, replay_buffer=PrioritizedReplayBuffer(300000, 0.5, 0.4, epsilon=0.1), optimize_op=optimize, train_interval=env_count, target_interval=8192, batch_size=env_count * batch_size_multiplier, min_buffer_size=max(4500, env_count * batch_size_multiplier), # min_buffer_size=60, tf_schedules=tf_schedules, handle_ep=print) scheduled_saver.save(sess)
print('creating env') env = AllowBacktracking(make_env(stack=False, scale_rew=False)) env = BatchedFrameStack(BatchedGymEnv([[env]]), num_images=4, concat=False) print('creating agent') online_net, target_net = rainbow_models(sess, env.action_space.n, gym_space_vectorizer( env.observation_space), min_val=-200, max_val=200) dqn = DQN(online_net, target_net) env.close() optimize = dqn.optimize(learning_rate=1e-4) saver = tf.train.Saver() sess.run(tf.global_variables_initializer()) train_steps = 1000 #200000 for i in range(3): stage = random.choice(stages) game = random.choice(games)
def main(): discount = os.environ.get('RETRO_DISCOUNT') if discount != None: discount = float(discount) else: discount = 0.99 print("DISCOUNT: %s" % (discount, )) """Run DQN until the environment throws an exception.""" config = tf.ConfigProto() config.gpu_options.allow_growth = True # pylint: disable=E1101 config.log_device_placement = False with tf.Session(config=config) as sess: state_encoder = StateEncoder(sess) env = make_batched_env() env_ids = env.env_ids env = BatchedFrameStack(env, num_images=4, concat=True) env.env_ids = env_ids env = ExplorationBatchedEnv(env, Exploration, state_encoder=state_encoder) if 'RETRO_POLICY_DIR' in os.environ: expert = PolicyExpert(sess, batch_size=1, policy_dir=os.environ['RETRO_POLICY_DIR']) elif not 'RETRO_NOEXPERT' in os.environ: expert = RandomMoveExpert() else: expert = None if os.environ['RETRO_DQN'] == 'soft_noisy_net': dqn = DQN(*soft_noisy_net_models( sess, env.action_space.n, gym_space_vectorizer(env.observation_space), discount=discount, #0.99 expert=expert)) elif os.environ['RETRO_DQN'] == 'soft_rainbow': dqn = DQN(*soft_rainbow_models( sess, env.action_space.n, gym_space_vectorizer(env.observation_space), num_atoms=101, min_val=-1000, #-200 max_val=1000, #200 discount=discount, #0.99 expert=expert)) if "RETRO_CHECKPOINT_DIR" in os.environ: scheduler_saver = ScheduledSaver( sess, os.environ["RETRO_CHECKPOINT_DIR"] + "/tensorflow/") else: scheduler_saver = None player = NStepPlayer(BatchedPlayer(env, dqn.online_net), 3) optimize = dqn.optimize(learning_rate=1e-4) sess.run(tf.global_variables_initializer()) if 'RETRO_INIT_DIR' in os.environ: saver = tf.train.Saver(var_list=list( filter( lambda v: not 'sigma' in v.name and not 'dqn_model/noisy_layer_1' in v.name and not 'dqn_model/noisy_layer_2' in v.name, tf.trainable_variables('^dqn_model/')))) latest_checkpoint = tf.train.latest_checkpoint( os.environ['RETRO_INIT_DIR']) print("DQN_INIT_CHECKPOINT: %s" % (latest_checkpoint, )) saver.restore(sess, latest_checkpoint) #from tensorflow.python.tools import inspect_checkpoint as chkp #chkp.print_tensors_in_checkpoint_file(latest_checkpoint,'',all_tensors=True) state_encoder.initialize() if expert: expert.initialize() replay_buffer = PrioritizedReplayBuffer(int( os.environ.get("RETRO_DQN_BUFFER_SIZE", 250000)), 0.5, 0.4, epsilon=0.1) dqn.train( num_steps=1000000, # Make sure an exception arrives before we stop. player=player, replay_buffer=replay_buffer, optimize_op=optimize, train_interval=1, target_interval=int( os.environ.get("RETRO_DQN_TARGET_INTERVAL", 8192)), batch_size=32, min_buffer_size=int( os.environ.get('RETRO_DQN_MIN_BUFFER_SIZE', 20000)), handle_ep=lambda steps, rew: scheduler_saver.handle_episode(steps) if scheduler_saver is not None else None)