def main(): args = parse_arg() tf.reset_default_graph() config = tf.ConfigProto() config.gpu_options.allow_growth = True with tf.Session(config=config) as sess: env = gym.make('FeedingCooperation-v0') set_global_seeds(int(args['random_seed'])) robot_actor_critic_entropy = Robot_Actor_Critic( sess, float(args['actor_lr']), float(args['critic_lr']), float(args['value_lr']), float(args['reg_factor']), float(args['gamma']), float(args['tau']), float(args['value_weight']), float(args['critic_weight']), float(args['actor_weight']), float(args['all_lr']), float(args['max_steps']), float(args['minibatch_size'])) human_actor_critic_entropy = Human_Actor_Critic( sess, float(args['actor_lr']), float(args['critic_lr']), float(args['value_lr']), float(args['reg_factor']), float(args['gamma']), float(args['tau']), float(args['value_weight']), float(args['critic_weight']), float(args['actor_weight']), float(args['all_lr']), float(args['max_steps']), float(args['minibatch_size'])) train(sess, env, args, robot_actor_critic_entropy, human_actor_critic_entropy) savepath = osp.join("my_model_sac_cop/", 'final') os.makedirs(savepath, exist_ok=True) savepath = osp.join(savepath, 'sacmodel') save_state(savepath)
def make_vec_env(num_env, seed,copeoperation=False): current_dir=os.getcwd() logger_dir=osp.join(current_dir, datetime.datetime.now().strftime("recoder-%Y-%m-%d-%H-%M-%S-%f")) os.makedirs(logger_dir, exist_ok=True) assert isinstance(logger_dir, str) def make_thunk(rank,cops=False): return lambda: create_env( subrank=rank, logger_dir=logger_dir,cop=cops) set_global_seeds(seed) return SubprocVecEnv([make_thunk(i,cops=copeoperation) for i in range(num_env)])
def main(args): # arguments arg_parser = common_arg_parser() args, unknown_args = arg_parser.parse_known_args(args) args.model = "_".join([args.agent, args.FA, str(args.T)]) # initialization set_global_seeds(args.seed) # os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu_no) # logger logger.configure("./log" + args.data_path.split("/")[-2] + "/" + "_".join([ args.model, datetime.now().strftime("%Y%m%d_%H%M%S"), args.data_path.split("/")[-2], str(args.learning_rate), str(args.T), str(args.ST), str(args.gamma) ])) logger.log("Training Model: " + args.model) # environments envs = get_objects(all_envs) env = envs[args.environment](args) # ipdb.set_trace() # policy network args.user_num = env.user_num args.item_num = env.item_num args.utype_num = env.utype_num # ipdb.set_trace() args.saved_path = os.path.join( os.path.abspath("./"), "saved_path_" + args.data_path.split("/")[-2] + "_" + str(args.FA) + "_" + str(args.learning_rate) + "_" + str(args.agent) + "_" + str(args.seed)) nets = get_objects(all_FA) fa = nets[args.FA].create_model_without_distributed(args) logger.log("Hype-Parameters: " + str(args)) # # agents agents = get_objects(all_agents) agents[args.agent](env, fa, args).train()
def make_vec_env(env_id, env_type, num_env, seed, wrapper_kwargs=None, start_index=0, reward_scale=1.0, flatten_dict_observations=True, gamestate=None): """ Create a wrapped, monitored SubprocVecEnv for Atari and MuJoCo. """ wrapper_kwargs = wrapper_kwargs or {} mpi_rank = MPI.COMM_WORLD.Get_rank() if MPI else 0 seed = seed + 10000 * mpi_rank if seed is not None else None logger_dir = logger.get_dir() def make_thunk(rank): return lambda: make_env(env_id=env_id, env_type=env_type, mpi_rank=mpi_rank, subrank=rank, seed=seed, reward_scale=reward_scale, gamestate=gamestate, flatten_dict_observations= flatten_dict_observations, wrapper_kwargs=wrapper_kwargs, logger_dir=logger_dir) set_global_seeds(seed) if num_env > 1: return SubprocVecEnv( [make_thunk(i + start_index) for i in range(num_env)]) else: return DummyVecEnv([make_thunk(start_index)])
import tensorflow as tf import numpy as np import gym import my_envs from util import set_global_seeds import os import time set_global_seeds(1001) with tf.Session() as sess: directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'my_model') file_pos = os.path.join(directory, '00350') meta_pos = os.path.join(file_pos, 'ppomodel.meta') saver = tf.train.import_meta_graph(meta_pos) saver.restore(sess, tf.train.latest_checkpoint(file_pos)) action_op = sess.graph.get_tensor_by_name('ppo_model/add_1:0') input = sess.graph.get_tensor_by_name('ppo_model/ob:0') num_env = action_op.shape[0] env = gym.make('Feeding-v0') env.play_show() state = env.reset() ep_reward = 0 total_step = 0 while True: state = np.expand_dims(state, axis=0) state = np.repeat(state, num_env, axis=0) action = sess.run(action_op, feed_dict={input: state}) action = action[0, :]
def learn(env, network, seed=None, lr=5e-4, total_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, load_path=None, save_path=None, **network_kwargs): """Train a deepq model. Parameters ------- env: gym.Env environment to train on network: string or a function neural network to use as a q function approximator. If string, has to be one of the names of registered models in baselines.common.models (mlp, cnn, conv_only). If a function, should take an observation tensor and return a latent variable tensor, which will be mapped to the Q function heads (see build_q_func in baselines.deepq.models for details on that) seed: int or None prng seed. The runs with the same seed "should" give the same results. If None, no seeding is used. lr: float learning rate for adam optimizer total_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 total_timesteps. prioritized_replay_eps: float epsilon to add to the TD errors when updating priorities. param_noise: bool whether or not to use parameter space noise (https://arxiv.org/abs/1706.01905) callback: (locals, globals) -> None function called at every steps with state of the algorithm. If callback returns true training stops. load_path: str path to load the model from. (default: None) **network_kwargs additional keyword arguments to pass to the network builder. 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 set_global_seeds(seed) q_func = build_q_func(network, **network_kwargs) # capture the shape outside the closure so that the env object is not serialized # by cloudpickle when serializing make_obs_ph observation_space = env.observation_space model = deepq.DEEPQ(q_func=q_func, observation_shape=env.observation_space.shape, num_actions=env.action_space.n, lr=lr, grad_norm_clipping=10, gamma=gamma, param_noise=param_noise) if load_path is not None: load_path = osp.expanduser(load_path) ckpt = tf.train.Checkpoint(model=model) manager = tf.train.CheckpointManager(ckpt, load_path, max_to_keep=None) ckpt.restore(manager.latest_checkpoint) print("Restoring from {}".format(manager.latest_checkpoint)) return model # 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 = total_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 * total_timesteps), initial_p=1.0, final_p=exploration_final_eps) model.update_target() episode_rewards = [0.0] saved_mean_reward = None obs = env.reset() # always mimic the vectorized env if not isinstance(env, VecEnv): obs = np.expand_dims(np.array(obs), axis=0) reset = True for t in range(total_timesteps): if callback is not None: if callback(locals(), globals()): break kwargs = {} if not param_noise: update_eps = tf.constant(exploration.value(t)) update_param_noise_threshold = 0. else: update_eps = tf.constant(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 action, _, _, _ = model.step(tf.constant(obs), update_eps=update_eps, **kwargs) action = action[0].numpy() reset = False new_obs, rew, done, _ = env.step(action) # Store transition in the replay buffer. if not isinstance(env, VecEnv): new_obs = np.expand_dims(np.array(new_obs), axis=0) replay_buffer.add(obs[0], action, rew, new_obs[0], float(done)) else: replay_buffer.add(obs[0], action, rew[0], new_obs[0], float(done[0])) # # 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: obs = env.reset() if not isinstance(env, VecEnv): obs = np.expand_dims(np.array(obs), axis=0) 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 obses_t, obses_tp1 = tf.constant(obses_t), tf.constant(obses_tp1) actions, rewards, dones = tf.constant(actions), tf.constant( rewards), tf.constant(dones) weights = tf.constant(weights) td_errors = model.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. model.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("mean 100 episode reward", mean_100ep_reward) logger.record_tabular("% time spent exploring", int(100 * exploration.value(t))) logger.dump_tabular() if save_path is not None: save_path = osp.expanduser(save_path) ckpt = tf.train.Checkpoint(model=model) manager = tf.train.CheckpointManager(ckpt, save_path, max_to_keep=None) manager.save() return model
def learn(env, total_timesteps, seed=None, nsteps=1024, ent_coef=0.01, lr=0.01, vf_coef=0.5, p_coef=1.0, max_grad_norm=None, gamma=0.99, lam=0.95, nminibatches=15, noptepochs=4, cliprange=0.2, save_interval=100, copeoperation=False, human_ent_coef=0.01, human_vf_coef=0.5, human_p_coef=1.0): set_global_seeds(seed) sess = get_session() global_summary = tf.summary.FileWriter( 'summaries/' + 'feeding' + datetime.datetime.now().strftime('%d-%m-%y%H%M'), sess.graph) if isinstance(lr, float): lr = constfn(lr) else: assert callable(lr) if isinstance(cliprange, float): cliprange = constfn(cliprange) else: assert callable(cliprange) # Get the nb of env nenvs = env.num_envs # Calculate the batch_size nbatch = nenvs * nsteps nbatch_train = nbatch // nminibatches if copeoperation == True: human_model = Model(env=env, nbatch_act=nenvs, nbatch_train=nbatch_train, ent_coef=human_ent_coef, vf_coef=human_vf_coef, p_coef=human_p_coef, max_grad_norm=max_grad_norm, human=True, robot=False) robot_model = Model(env=env, nbatch_act=nenvs, nbatch_train=nbatch_train, ent_coef=ent_coef, vf_coef=vf_coef, p_coef=p_coef, max_grad_norm=max_grad_norm, human=False, robot=True) if copeoperation == False: model = Model(env=env, nbatch_act=nenvs, nbatch_train=nbatch_train, ent_coef=ent_coef, vf_coef=vf_coef, p_coef=p_coef, max_grad_norm=max_grad_norm) initialize() # Instantiate the runner object if copeoperation == True: runner = Runner(env=env, model=None, nsteps=nsteps, gamma=gamma, lam=lam, human_model=human_model, robot_model=robot_model) if copeoperation == False: runner = Runner(env=env, model=model, nsteps=nsteps, gamma=gamma, lam=lam) epinfobuf = deque(maxlen=10) #recent 10 episode pbar = tqdm(total=total_timesteps, dynamic_ncols=True) tfirststart = time.perf_counter() nupdates = total_timesteps // nbatch for update in range(1, nupdates + 1): assert nbatch % nminibatches == 0 # Start timer frac = 1.0 - (update - 1.0) / nupdates # Calculate the learning rate lrnow = lr(frac) # Calculate the cliprange cliprangenow = cliprange(frac) # Get minibatch if copeoperation == False: obs, returns, masks, actions, values, neglogpacs, epinfos = runner.run( ) if copeoperation == True: obs, human_returns, robot_returns, masks, human_actions, robot_actions, human_values, robot_values, human_neglogpacs, robot_neglogpacs, epinfos = runner.coop_run( ) epinfobuf.extend(epinfos) mblossvals = [] human_mblossvals = [] robot_mblossvals = [] inds = np.arange(nbatch) for _ in range(noptepochs): # Randomize the indexes np.random.shuffle(inds) for start in range(0, nbatch, nbatch_train): end = start + nbatch_train mbinds = inds[start:end] if copeoperation == True: human_slices = (arr[mbinds] for arr in (obs[:, 24:], human_returns, human_actions, human_values, human_neglogpacs)) robot_slices = (arr[mbinds] for arr in (obs[:, :24], robot_returns, robot_actions, robot_values, robot_neglogpacs)) human_mblossvals.append( human_model.train(lrnow, cliprangenow, *human_slices)) robot_mblossvals.append( robot_model.train(lrnow, cliprangenow, *robot_slices)) if copeoperation == False: slices = (arr[mbinds] for arr in (obs, returns, actions, values, neglogpacs)) mblossvals.append(model.train(lrnow, cliprangenow, *slices)) #None # Feedforward --> get losses --> update if copeoperation == True: human_lossvals = np.mean(human_mblossvals, axis=0) robot_lossvals = np.mean(robot_mblossvals, axis=0) if copeoperation == False: lossvals = np.mean(mblossvals, axis=0) summary = tf.Summary() if copeoperation == True: human_ev = explained_variance(human_values, human_returns) robot_ev = explained_variance(robot_values, robot_returns) if copeoperation == False: ev = explained_variance(values, returns) performance_r = np.mean([epinfo['r'] for epinfo in epinfobuf]) performance_len = np.mean([epinfo['l'] for epinfo in epinfobuf]) success_time = np.mean( [epinfo['success_time'] for epinfo in epinfobuf]) fall_time = np.mean([epinfo['fall_time'] for epinfo in epinfobuf]) summary.value.add(tag='Perf/Reward', simple_value=performance_r) summary.value.add(tag='Perf/episode_len', simple_value=performance_len) summary.value.add(tag='Perf/success_time', simple_value=success_time) summary.value.add(tag='Perf/fall_time', simple_value=fall_time) if copeoperation == True: summary.value.add(tag='Perf/human_explained_variance', simple_value=float(human_ev)) summary.value.add(tag='Perf/robot_explained_variance', simple_value=float(robot_ev)) if copeoperation == False: summary.value.add(tag='Perf/explained_variance', simple_value=float(ev)) if copeoperation == True: for (human_lossval, human_lossname) in zip(human_lossvals, human_model.loss_names): if human_lossname == 'grad_norm': summary.value.add(tag='grad/' + human_lossname, simple_value=human_lossval) else: summary.value.add(tag='human_loss/' + human_lossname, simple_value=human_lossval) for (robot_lossval, robot_lossname) in zip(robot_lossvals, robot_model.loss_names): if robot_lossname == 'grad_norm': summary.value.add(tag='grad/' + robot_lossname, simple_value=robot_lossval) else: summary.value.add(tag='robot_loss/' + robot_lossname, simple_value=robot_lossval) if copeoperation == False: for (lossval, lossname) in zip(lossvals, model.loss_names): if lossname == 'grad_norm': summary.value.add(tag='grad/' + lossname, simple_value=lossval) else: summary.value.add(tag='loss/' + lossname, simple_value=lossval) global_summary.add_summary(summary, int(update * nbatch)) global_summary.flush() print('finish one update') if update % 10 == 0: msg = 'step: {},episode reward: {},episode len: {},success_time: {},fall_time: {}' pbar.update(update * nbatch) pbar.set_description( msg.format(update * nbatch, performance_r, performance_len, success_time, fall_time)) if update % save_interval == 0: tnow = time.perf_counter() print('consume time', tnow - tfirststart) if copeoperation == True: savepath = osp.join("my_model_cop/", '%.5i' % update) if copeoperation == False: savepath = osp.join("my_model/", '%.5i' % update) os.makedirs(savepath, exist_ok=True) savepath = osp.join(savepath, 'ppomodel') print('Saving to', savepath) save_state(savepath) pbar.close() return model
def main(): config = Config() set_global_seeds(config.seed) env = gym.make(config.env_name) env = CartPoleWrapper(env) # with tf.device("/gpu:0"): # gpuを使用する場合 with tf.device("/cpu:0"): ppo = PPO(num_actions=env.action_space.n, input_shape=env.observation_space.shape, config=config) num_episodes = 0 episode_rewards = deque([0] * 100, maxlen=100) memory = Memory(env.observation_space.shape, config) reward_sum = 0 obs = env.reset() for t in tqdm(range(config.num_update)): # ===== get samples ===== for _ in range(config.num_step): policy, value = ppo.step(obs[np.newaxis, :]) policy = policy.numpy() action = np.random.choice(2, p=policy) next_obs, reward, done, _ = env.step(action) memory.add(obs, action, reward, done, value, policy[action]) obs = next_obs reward_sum += reward if done: episode_rewards.append(env.steps) num_episodes += 1 reward_sum = 0 obs = env.reset() _, last_value = ppo.step(obs[np.newaxis, :]) memory.add(None, None, None, None, last_value, None) # ===== make mini-batch and update parameters ===== memory.compute_gae() for _ in range(config.num_epoch): idxes = [idx for idx in range(config.num_step)] random.shuffle(idxes) for start in range(0, len(memory), config.batch_size): minibatch_indexes = idxes[start:start + config.batch_size] batch_obs, batch_act, batch_adv, batch_sum, batch_pi_old = memory.sample( minibatch_indexes) loss, policy_loss, value_loss, entropy_loss, policy, kl, frac = ppo.train( batch_obs, batch_act, batch_pi_old, batch_adv, batch_sum) memory.reset() if t % config.log_step == 0: logger.info("\nnum episodes: {}".format(num_episodes)) logger.info("loss: {}".format(loss.numpy())) logger.info("policy loss: {}".format(policy_loss.numpy())) logger.info("value loss: {}".format(value_loss.numpy())) logger.info("entropy loss: {}".format(entropy_loss.numpy())) logger.info("kl: {}".format(kl.numpy())) logger.info("frac: {}".format(frac.numpy())) logger.info("mean 100 episode reward: {}".format( np.mean(episode_rewards))) logger.info("max 100 episode reward: {}".format( np.max(episode_rewards))) logger.info("min 100 episode reward: {}".format( np.min(episode_rewards))) # ===== finish training ===== if config.play: obs = env.reset() while True: action, _ = ppo.step(obs[np.newaxis, :]) action = int(action.numpy()[0]) obs, _, done, _ = env.step(action) env.render() if done: obs = env.reset()