def __init__(self, save_path, observation_space, action_space, model, queue, config, logger): self.config = config self.queue = queue self.logger = logger self.save_path = save_path self.batch_size = config.batch_size with tf.device('/cpu:0'): self.global_step = tf.train.create_global_step() self.update_global_step = tf.assign_add(self.global_step, 1) with tf.device('/gpu:0'): queue_size_op = self.queue.size() self.queue_size = U.function([], queue_size_op) dequeue_op = self.queue.get() self.act, self.train, self.update_target, self.debug = qdqn.build_train( make_obs_ph=lambda name: U.Uint8Input(observation_space.shape, name=name), q_func=model, num_actions=action_space.n, gamma=config.gamma, optimizer=tf.train.AdamOptimizer(learning_rate=config.learning_rate, epsilon=1e-4), train_inputs=dequeue_op, scope="learner", grad_norm_clipping=10, reuse=False) self.num_iters = 0 self.max_iteration_count = self.config.num_iterations self.checkpoint_frequency = max(self.max_iteration_count / 1000, 10000) self.log_frequency = 300
def main(): state = bk.create_default_state() game = state.game_num frame = 3 #TODO Change for your own file structure directory = "gameImages/" + str(game).zfill(4) filepaths = [ directory + "/" + str(i).zfill(5) + ".png" for i in range(int(frame - 3), int(frame + 1)) ] observations = [] for i in filepaths: observations.append(process_observation(cv2.imread(i))) observations = np.reshape(np.asarray(observations), (84, 84, 4)) print(observations, observations.shape) #TODO Load act function. See XAI_IS_test.py for guidance. with U.make_session(4) as sess: n_actions = 6 act = build_act(make_obs_ph=lambda name: U.Uint8Input( observations.shape, name=name), q_func=dueling_model, num_actions=n_actions) saver = tf.train.Saver() saver.restore(sess, "model-atari-prior-duel-breakout-1/saved") play(observations, act)
def __init__(self, is_chief, env, model, config, should_render=True): self.config = config self.is_chief = is_chief self.env = env self.should_render = should_render self.act, self.train, self.update_target, self.debug = multi_deepq.build_train( make_obs_ph=lambda name: U.Uint8Input(env.observation_space.shape, name=name), q_func=model, num_actions=env.action_space.n, gamma=config.gamma, optimizer=tf.train.AdamOptimizer(learning_rate=config.learning_rate), reuse=(not is_chief), ) self.max_iteraction_count = int(self.config.num_iterations) # Create the replay buffer self.replay_buffer = ReplayBuffer(config.replay_size) if self.config.exploration_schedule == "constant": self.exploration = ConstantSchedule(0.1) elif self.config.exploration_schedule == "linear": # Create the schedule for exploration starting from 1 (every action is random) down to # 0.02 (98% of actions are selected according to values predicted by the model). self.exploration = LinearSchedule( schedule_timesteps=self.config.num_iterations / 4, initial_p=1.0, final_p=0.02) elif self.config.exploration_schedule == "piecewise": approximate_num_iters = self.config.num_iterations self.exploration = PiecewiseSchedule([ (0, 1.0), (approximate_num_iters / 50, 0.1), (approximate_num_iters / 5, 0.01) ], outside_value=0.01) else: raise ValueError("Bad exploration schedule")
def main(): set_global_seeds(1) args = parse_args() with U.make_session(4): # noqa _, env = make_env(args.env) act = deepq.build_act(make_obs_ph=lambda name: U.Uint8Input( env.observation_space.shape, name=name), q_func=dueling_model if args.dueling else model, num_actions=env.action_space.n) U.load_state(os.path.join(args.model_dir, "saved")) wang2015_eval(args.env, act, stochastic=args.stochastic)
def __init__(self, index, is_chief, env, model, queue, config, logger, episode_logger, should_render=False): self.config = config self.is_chief = is_chief self.env = env self.global_step = tf.train.get_global_step() self.should_render = should_render self.logger = logger self.episode_logger = episode_logger self.log_frequency = 10 with tf.device('/cpu:0'): self.act, self.update_params, self.debug = qdqn.build_act( make_obs_ph=lambda name: U.Uint8Input(self.env.observation_space.shape, name=name), q_func=model, num_actions=self.env.action_space.n, scope="actor_{}".format(index), learner_scope="learner", reuse=False) with tf.device('/cpu:0'): obs_t_input = tf.placeholder(tf.uint8, self.env.observation_space.shape, name="obs_t") act_t_ph = tf.placeholder(tf.int32, self.env.action_space.shape, name="action") rew_t_ph = tf.placeholder(tf.float32, [], name="reward") obs_tp1_input = tf.placeholder(tf.uint8, self.env.observation_space.shape, name="obs_tp1") done_mask_ph = tf.placeholder(tf.float32, [], name="done") global_step_ph = tf.placeholder(tf.int32, [], name="sample_global_step") enqueue_op = queue.enqueue( [obs_t_input, act_t_ph, rew_t_ph, obs_tp1_input, done_mask_ph, global_step_ph]) self.enqueue = U.function( [obs_t_input, act_t_ph, rew_t_ph, obs_tp1_input, done_mask_ph, global_step_ph], enqueue_op) self.max_iteration_count = self.config.num_iterations if self.config.exploration_schedule == "constant": self.exploration = ConstantSchedule(0.1) elif self.config.exploration_schedule == "linear": # Create the schedule for exploration starting from 1 (every action is random) down to # 0.02 (98% of actions are selected according to values predicted by the model). self.exploration = LinearSchedule( schedule_timesteps=self.config.num_iterations / 4, initial_p=1.0, final_p=0.02) elif self.config.exploration_schedule == "piecewise": approximate_num_iters = self.config.num_iterations self.exploration = PiecewiseSchedule([ (0, 1.0), (approximate_num_iters / 50, 0.1), (approximate_num_iters / 5, 0.01) ], outside_value=0.01) else: raise ValueError("Bad exploration schedule")
def main(): with U.make_session(4) as sess: env = make_env(args.env_name) n_actions = env.action_space.n print(env.observation_space.shape) if args.env_name == "Breakout": n_actions = 6 act = build_act(make_obs_ph=lambda name: U.Uint8Input( env.observation_space.shape, name=name), q_func=dueling_model, num_actions=n_actions) saver = tf.train.Saver() saver.restore(sess, args.model_path) play(args.env_name, env, act)
def main(): set_global_seeds(1) args = parse_args() with U.make_session(4) as sess: # noqa _, env = make_env(args.env) model_parent_path = distdeepq.parent_path(args.model_dir) old_args = json.load(open(model_parent_path + '/args.json')) act = distdeepq.build_act(make_obs_ph=lambda name: U.Uint8Input( env.observation_space.shape, name=name), p_dist_func=distdeepq.models.atari_model(), num_actions=env.action_space.n, dist_params={ 'Vmin': old_args['vmin'], 'Vmax': old_args['vmax'], 'nb_atoms': old_args['nb_atoms'] }) U.load_state(os.path.join(args.model_dir, "saved")) wang2015_eval(args.env, act, stochastic=args.stochastic)
inRtd = inr + args.gamma * inRtd z = np.array(z).reshape((args.latent_dim)) # q, _ = ec_buffer[a].peek(z, exRtd, inRtd, True) qs, inrs = zip(*[ ec_buffer[i].peek(z, exRtd, inRtd, False) for i in range(env.action_space.n) ]) q = qs[a] inr = np.max(inrs) if q is None: # new action ec_buffer[a].add(z, exRtd, inRtd) inr = ec_buffer[a].rmax # Create training graph and replay buffer act, train, update_target = deepq.build_train_dueling_true( make_obs_ph=lambda name: U.Uint8Input(env.observation_space.shape, name=name), model_func=rp_model if args.rp else contrastive_model, q_func=model, imitate=args.imitate, num_actions=env.action_space.n, optimizer=tf.train.AdamOptimizer(learning_rate=args.lr, epsilon=1e-4), gamma=args.gamma, grad_norm_clipping=10, ) approximate_num_iters = args.num_steps exploration = PiecewiseSchedule( [ (0, 1),
video_path, enabled=video_path is not None) obs = env.reset() while True: env.unwrapped.render() video_recorder.capture_frame() action = act(np.array(obs)[None], stochastic=stochastic)[0] obs, rew, done, info = env.step(action) if done: obs = env.reset() if len(info["rewards"]) > num_episodes: if len(info["rewards"]) == 1 and video_recorder.enabled: # save video of first episode print("Saved video.") video_recorder.close() video_recorder.enabled = False print(info["rewards"][-1]) num_episodes = len(info["rewards"]) if __name__ == '__main__': with U.make_session(4) as sess: args = parse_args() env = make_env(args.env) act = deepq.build_act(make_obs_ph=lambda name: U.Uint8Input( env.observation_space.shape, name=name), q_func=dueling_model if args.dueling else model, num_actions=env.action_space.n) U.load_state(os.path.join(args.model_dir, "saved")) play(env, act, args.stochastic, args.video)
def learn(env, q_func, lr=5e-4, max_timesteps=100000, buffer_size=50000, exploration_fraction=0.1, exploration_final_eps=0.02, train_freq=1, batch_size=32, print_freq=100, checkpoint_freq=10000, checkpoint_path=None, learning_starts=1000, gamma=1.0, target_network_update_freq=500, prioritized_replay=False, prioritized_replay_alpha=0.6, prioritized_replay_beta0=0.4, prioritized_replay_beta_iters=None, prioritized_replay_eps=1e-6, param_noise=False, callback=None, bootstrap=False, noisy=False, greedy=False): """Train a deepq model. Parameters ------- env: gym.Env environment to train on q_func: (tf.Variable, int, str, bool) -> tf.Variable the model that takes the following inputs: observation_in: object the output of observation placeholder num_actions: int number of actions scope: str reuse: bool should be passed to outer variable scope and returns a tensor of shape (batch_size, num_actions) with values of every action. lr: float learning rate for adam optimizer max_timesteps: int number of env steps to optimizer for buffer_size: int size of the replay buffer exploration_fraction: float fraction of entire training period over which the exploration rate is annealed exploration_final_eps: float final value of random action probability train_freq: int update the model every `train_freq` steps. set to None to disable printing batch_size: int size of a batched sampled from replay buffer for training print_freq: int how often to print out training progress set to None to disable printing checkpoint_freq: int how often to save the model. This is so that the best version is restored at the end of the training. If you do not wish to restore the best version at the end of the training set this variable to None. learning_starts: int how many steps of the model to collect transitions for before learning starts gamma: float discount factor target_network_update_freq: int update the target network every `target_network_update_freq` steps. prioritized_replay: True if True prioritized replay buffer will be used. prioritized_replay_alpha: float alpha parameter for prioritized replay buffer prioritized_replay_beta0: float initial value of beta for prioritized replay buffer prioritized_replay_beta_iters: int number of iterations over which beta will be annealed from initial value to 1.0. If set to None equals to max_timesteps. prioritized_replay_eps: float epsilon to add to the TD errors when updating priorities. callback: (locals, globals) -> None function called at every steps with state of the algorithm. If callback returns true training stops. Returns ------- act: ActWrapper Wrapper over act function. Adds ability to save it and load it. See header of baselines/deepq/categorical.py for details on the act function. """ # Create all the functions necessary to train the model sess = tf.Session() sess.__enter__() # capture the shape outside the closure so that the env object is not serialized # by cloudpickle when serializing make_obs_ph act, train, update_target, debug = deepq.build_train( make_obs_ph=lambda name: U.Uint8Input(env.observation_space.shape, name=name), q_func=q_func, num_actions=env.action_space.n, optimizer=tf.train.AdamOptimizer(learning_rate=lr), gamma=gamma, grad_norm_clipping=10, noisy=noisy, bootstrap=bootstrap) logger.configure('models', ['json', 'stdout']) # Create the replay buffer if prioritized_replay: replay_buffer = PrioritizedReplayBuffer(buffer_size, alpha=prioritized_replay_alpha) if prioritized_replay_beta_iters is None: prioritized_replay_beta_iters = max_timesteps beta_schedule = LinearSchedule(prioritized_replay_beta_iters, initial_p=prioritized_replay_beta0, final_p=1.0) else: replay_buffer = ReplayBuffer(buffer_size) beta_schedule = None # Create the schedule for exploration starting from 1. exploration = LinearSchedule(schedule_timesteps=int(exploration_fraction * max_timesteps), initial_p=1.0, final_p=exploration_final_eps) # Initialize the parameters and copy them to the target network. U.initialize() update_target() episode_rewards = [0.0] saved_mean_reward = None obs = env.reset() reset = True head = np.random.randint(10) #Initial head initialisation with tempfile.TemporaryDirectory() as td: td = checkpoint_path or td model_file = os.path.join(td, "model") model_saved = False if tf.train.latest_checkpoint(td) is not None: load_state(model_file) logger.log('Loaded model from {}'.format(model_file)) model_saved = True for t in range(max_timesteps): if callback is not None: if callback(locals(), globals()): break # Take action and update exploration to the newest value kwargs = {} if not param_noise: update_eps = exploration.value(t) update_param_noise_threshold = 0. else: update_eps = 0. # Compute the threshold such that the KL divergence between perturbed and non-perturbed # policy is comparable to eps-greedy exploration with eps = exploration.value(t). # See Appendix C.1 in Parameter Space Noise for Exploration, Plappert et al., 2017 # for detailed explanation. update_param_noise_threshold = -np.log(1. - exploration.value( t) + exploration.value(t) / float(env.action_space.n)) kwargs['reset'] = reset kwargs[ 'update_param_noise_threshold'] = update_param_noise_threshold kwargs['update_param_noise_scale'] = True if bootstrap: action = act(np.array(obs)[None], head=head, update_eps=update_eps)[0] elif noisy: action = act(np.array(obs)[None], stochastic=False)[0] elif greedy: action = act(np.array(obs)[None], stochastic=False)[0] else: action = act(np.array(obs)[None], update_eps=update_eps)[0] env_action = action reset = False new_obs, rew, done, _ = env.step(env_action) # Store transition in the replay buffer. replay_buffer.add(obs, action, rew, new_obs, float(done)) obs = new_obs episode_rewards[-1] += rew if done: ep_rew = episode_rewards[-1] obs = env.reset() episode_rewards.append(0.0) reset = True if t > learning_starts and t % train_freq == 0: # Minimize the error in Bellman's equation on a batch sampled from replay buffer. if prioritized_replay: experience = replay_buffer.sample( batch_size, beta=beta_schedule.value(t)) (obses_t, actions, rewards, obses_tp1, dones, weights, batch_idxes) = experience else: obses_t, actions, rewards, obses_tp1, dones = replay_buffer.sample( batch_size) weights, batch_idxes = np.ones_like(rewards), None if bootstrap: td_errors = train(obses_t, actions, rewards, obses_tp1, dones, weights, lr) else: td_errors = train(obses_t, actions, rewards, obses_tp1, dones, weights) if prioritized_replay: new_priorities = np.abs(td_errors) + prioritized_replay_eps replay_buffer.update_priorities(batch_idxes, new_priorities) if t > learning_starts and t % target_network_update_freq == 0: # Update target network periodically. update_target() mean_100ep_reward = round(np.mean(episode_rewards[-101:-1]), 1) num_episodes = len(episode_rewards) if done and print_freq is not None and len( episode_rewards) % print_freq == 0: logger.record_tabular("steps", t) logger.record_tabular("episodes", num_episodes) logger.record_tabular("reward", ep_rew) logger.record_tabular("mean 100 episode reward", mean_100ep_reward) logger.record_tabular("% time spent exploring", int(100 * exploration.value(t))) if bootstrap: logger.record_tabular("head for episode", (head + 1)) logger.dump_tabular() head = np.random.randint(10) if (checkpoint_freq is not None and t > learning_starts and num_episodes > 100 and t % checkpoint_freq == 0): if saved_mean_reward is None or mean_100ep_reward > saved_mean_reward: if print_freq is not None: logger.log( "Saving model due to mean reward increase: {} -> {}" .format(saved_mean_reward, mean_100ep_reward)) save_state(model_file) model_saved = True saved_mean_reward = mean_100ep_reward if model_saved: if print_freq is not None: logger.log("Restored model with mean reward: {}".format( saved_mean_reward)) load_state(model_file) return act
account_key=account_key, container_name=container_name, maybe_create=True) if savedir is None: # Careful! This will not get cleaned up. Docker spoils the developers. savedir = tempfile.TemporaryDirectory().name else: container = None env = multidim_mdp(args.mdp_arity, args.mdp_dimension, args.mdp_state_size) with U.make_session(120) as sess: # Create training graph and replay buffer if args.bootstrap: act, train, update_target, debug = deepq.build_train( make_obs_ph=lambda name: U.Uint8Input( (args.mdp_arity**args.mdp_dimension, ), name=name), q_func=simple_bootstrap_model, bootstrap=args.bootstrap, num_actions=2 * args.mdp_dimension, optimizer=tf.train.AdamOptimizer(learning_rate=args.lr, epsilon=1e-4), gamma=0.99, grad_norm_clipping=10, double_q=args.double_q, heads=args.heads, swarm=args.swarm, device=args.device, voting=args.voting) else: act, train, update_target, debug = deepq.build_train( make_obs_ph=lambda name: U.Uint8Input(