main.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import copy
  2. import glob
  3. import os
  4. import time
  5. import operator
  6. from functools import reduce
  7. import gym
  8. import numpy as np
  9. import torch
  10. import torch.nn as nn
  11. import torch.nn.functional as F
  12. import torch.optim as optim
  13. from torch.autograd import Variable
  14. from arguments import get_args
  15. from baselines.common.vec_env.dummy_vec_env import DummyVecEnv
  16. from baselines.common.vec_env.subproc_vec_env import SubprocVecEnv
  17. from baselines.common.vec_env.vec_normalize import VecNormalize
  18. from envs import make_env
  19. from kfac import KFACOptimizer
  20. from model import CNNPolicy, MLPPolicy
  21. from storage import RolloutStorage
  22. from visualize import visdom_plot
  23. args = get_args()
  24. assert args.algo in ['a2c', 'ppo', 'acktr']
  25. if args.recurrent_policy:
  26. assert args.algo in ['a2c', 'ppo'], \
  27. 'Recurrent policy is not implemented for ACKTR'
  28. num_updates = int(args.num_frames) // args.num_steps // args.num_processes
  29. torch.manual_seed(args.seed)
  30. if args.cuda:
  31. torch.cuda.manual_seed(args.seed)
  32. try:
  33. os.makedirs(args.log_dir)
  34. except OSError:
  35. files = glob.glob(os.path.join(args.log_dir, '*.monitor.csv'))
  36. for f in files:
  37. os.remove(f)
  38. def main():
  39. print("#######")
  40. print("WARNING: All rewards are clipped or normalized so you need to use a monitor (see envs.py) or visdom plot to get true rewards")
  41. print("#######")
  42. os.environ['OMP_NUM_THREADS'] = '1'
  43. if args.vis:
  44. from visdom import Visdom
  45. viz = Visdom()
  46. win = None
  47. paramSteps = [5,6,7,8,9,10,11,12,13,14,15,16]
  48. roomSize = paramSteps[0]
  49. paramSteps = paramSteps[1:]
  50. envs = [make_env(args.env_name, args.seed, i, args.log_dir, roomSize)
  51. for i in range(args.num_processes)]
  52. if args.num_processes > 1:
  53. envs = SubprocVecEnv(envs)
  54. else:
  55. envs = DummyVecEnv(envs)
  56. if len(envs.observation_space.shape) == 1:
  57. envs = VecNormalize(envs)
  58. obs_shape = envs.observation_space.shape
  59. obs_shape = (obs_shape[0] * args.num_stack, *obs_shape[1:])
  60. obs_numel = reduce(operator.mul, obs_shape, 1)
  61. if len(obs_shape) == 3 and obs_numel > 1024:
  62. actor_critic = CNNPolicy(obs_shape[0], envs.action_space, args.recurrent_policy)
  63. else:
  64. assert not args.recurrent_policy, \
  65. "Recurrent policy is not implemented for the MLP controller"
  66. actor_critic = MLPPolicy(obs_numel, envs.action_space)
  67. if envs.action_space.__class__.__name__ == "Discrete":
  68. action_shape = 1
  69. else:
  70. action_shape = envs.action_space.shape[0]
  71. if args.cuda:
  72. actor_critic.cuda()
  73. if args.algo == 'a2c':
  74. optimizer = optim.RMSprop(actor_critic.parameters(), args.lr, eps=args.eps, alpha=args.alpha)
  75. elif args.algo == 'ppo':
  76. optimizer = optim.Adam(actor_critic.parameters(), args.lr, eps=args.eps)
  77. elif args.algo == 'acktr':
  78. optimizer = KFACOptimizer(actor_critic)
  79. rollouts = RolloutStorage(args.num_steps, args.num_processes, obs_shape, envs.action_space, actor_critic.state_size)
  80. current_obs = torch.zeros(args.num_processes, *obs_shape)
  81. def update_current_obs(obs):
  82. shape_dim0 = envs.observation_space.shape[0]
  83. obs = torch.from_numpy(obs).float()
  84. if args.num_stack > 1:
  85. current_obs[:, :-shape_dim0] = current_obs[:, shape_dim0:]
  86. current_obs[:, -shape_dim0:] = obs
  87. obs = envs.reset()
  88. update_current_obs(obs)
  89. rollouts.observations[0].copy_(current_obs)
  90. # These variables are used to compute average rewards for all processes.
  91. episode_rewards = torch.zeros([args.num_processes, 1])
  92. final_rewards = torch.zeros([args.num_processes, 1])
  93. if args.cuda:
  94. current_obs = current_obs.cuda()
  95. rollouts.cuda()
  96. start = time.time()
  97. for j in range(num_updates):
  98. for step in range(args.num_steps):
  99. # Sample actions
  100. value, action, action_log_prob, states = actor_critic.act(Variable(rollouts.observations[step], volatile=True),
  101. Variable(rollouts.states[step], volatile=True),
  102. Variable(rollouts.masks[step], volatile=True))
  103. cpu_actions = action.data.squeeze(1).cpu().numpy()
  104. # Obser reward and next obs
  105. obs, reward, done, info = envs.step(cpu_actions)
  106. reward = torch.from_numpy(np.expand_dims(np.stack(reward), 1)).float()
  107. episode_rewards += reward
  108. # If done then clean the history of observations.
  109. masks = torch.FloatTensor([[0.0] if done_ else [1.0] for done_ in done])
  110. final_rewards *= masks
  111. final_rewards += (1 - masks) * episode_rewards
  112. episode_rewards *= masks
  113. if args.cuda:
  114. masks = masks.cuda()
  115. if current_obs.dim() == 4:
  116. current_obs *= masks.unsqueeze(2).unsqueeze(2)
  117. else:
  118. current_obs *= masks
  119. update_current_obs(obs)
  120. rollouts.insert(step, current_obs, states.data, action.data, action_log_prob.data, value.data, reward, masks)
  121. next_value = actor_critic(Variable(rollouts.observations[-1], volatile=True),
  122. Variable(rollouts.states[-1], volatile=True),
  123. Variable(rollouts.masks[-1], volatile=True))[0].data
  124. rollouts.compute_returns(next_value, args.use_gae, args.gamma, args.tau)
  125. if args.algo in ['a2c', 'acktr']:
  126. values, action_log_probs, dist_entropy, states = actor_critic.evaluate_actions(Variable(rollouts.observations[:-1].view(-1, *obs_shape)),
  127. Variable(rollouts.states[0].view(-1, actor_critic.state_size)),
  128. Variable(rollouts.masks[:-1].view(-1, 1)),
  129. Variable(rollouts.actions.view(-1, action_shape)))
  130. values = values.view(args.num_steps, args.num_processes, 1)
  131. action_log_probs = action_log_probs.view(args.num_steps, args.num_processes, 1)
  132. advantages = Variable(rollouts.returns[:-1]) - values
  133. value_loss = advantages.pow(2).mean()
  134. action_loss = -(Variable(advantages.data) * action_log_probs).mean()
  135. if args.algo == 'acktr' and optimizer.steps % optimizer.Ts == 0:
  136. # Sampled fisher, see Martens 2014
  137. actor_critic.zero_grad()
  138. pg_fisher_loss = -action_log_probs.mean()
  139. value_noise = Variable(torch.randn(values.size()))
  140. if args.cuda:
  141. value_noise = value_noise.cuda()
  142. sample_values = values + value_noise
  143. vf_fisher_loss = -(values - Variable(sample_values.data)).pow(2).mean()
  144. fisher_loss = pg_fisher_loss + vf_fisher_loss
  145. optimizer.acc_stats = True
  146. fisher_loss.backward(retain_graph=True)
  147. optimizer.acc_stats = False
  148. optimizer.zero_grad()
  149. (value_loss * args.value_loss_coef + action_loss - dist_entropy * args.entropy_coef).backward()
  150. if args.algo == 'a2c':
  151. nn.utils.clip_grad_norm(actor_critic.parameters(), args.max_grad_norm)
  152. optimizer.step()
  153. elif args.algo == 'ppo':
  154. advantages = rollouts.returns[:-1] - rollouts.value_preds[:-1]
  155. advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-5)
  156. for e in range(args.ppo_epoch):
  157. if args.recurrent_policy:
  158. data_generator = rollouts.recurrent_generator(advantages,
  159. args.num_mini_batch)
  160. else:
  161. data_generator = rollouts.feed_forward_generator(advantages,
  162. args.num_mini_batch)
  163. for sample in data_generator:
  164. observations_batch, states_batch, actions_batch, \
  165. return_batch, masks_batch, old_action_log_probs_batch, \
  166. adv_targ = sample
  167. # Reshape to do in a single forward pass for all steps
  168. values, action_log_probs, dist_entropy, states = actor_critic.evaluate_actions(Variable(observations_batch),
  169. Variable(states_batch),
  170. Variable(masks_batch),
  171. Variable(actions_batch))
  172. adv_targ = Variable(adv_targ)
  173. ratio = torch.exp(action_log_probs - Variable(old_action_log_probs_batch))
  174. surr1 = ratio * adv_targ
  175. surr2 = torch.clamp(ratio, 1.0 - args.clip_param, 1.0 + args.clip_param) * adv_targ
  176. action_loss = -torch.min(surr1, surr2).mean() # PPO's pessimistic surrogate (L^CLIP)
  177. value_loss = (Variable(return_batch) - values).pow(2).mean()
  178. optimizer.zero_grad()
  179. (value_loss + action_loss - dist_entropy * args.entropy_coef).backward()
  180. nn.utils.clip_grad_norm(actor_critic.parameters(), args.max_grad_norm)
  181. optimizer.step()
  182. rollouts.after_update()
  183. if j % args.save_interval == 0 and args.save_dir != "":
  184. save_path = os.path.join(args.save_dir, args.algo)
  185. try:
  186. os.makedirs(save_path)
  187. except OSError:
  188. pass
  189. # A really ugly way to save a model to CPU
  190. save_model = actor_critic
  191. if args.cuda:
  192. save_model = copy.deepcopy(actor_critic).cpu()
  193. save_model = [save_model,
  194. hasattr(envs, 'ob_rms') and envs.ob_rms or None]
  195. torch.save(save_model, os.path.join(save_path, args.env_name + ".pt"))
  196. if j % args.log_interval == 0:
  197. end = time.time()
  198. total_num_steps = (j + 1) * args.num_processes * args.num_steps
  199. print('roomSize=%s' % roomSize)
  200. print("Updates {}, num timesteps {}, FPS {}, mean/median reward {:.1f}/{:.1f}, min/max reward {:.1f}/{:.1f}, entropy {:.5f}, value loss {:.5f}, policy loss {:.5f}".
  201. format(j, total_num_steps,
  202. int(total_num_steps / (end - start)),
  203. final_rewards.mean(),
  204. final_rewards.median(),
  205. final_rewards.min(),
  206. final_rewards.max(), dist_entropy.data[0],
  207. value_loss.data[0], action_loss.data[0]))
  208. #print(final_rewards.min())
  209. if final_rewards.min() > 950 and len(paramSteps) > 0:
  210. roomSize = paramSteps[0]
  211. paramSteps = paramSteps[1:]
  212. envs.close()
  213. envs = [make_env(args.env_name, args.seed, i, args.log_dir, roomSize) for i in range(args.num_processes)]
  214. envs = SubprocVecEnv(envs)
  215. obs = envs.reset()
  216. update_current_obs(obs)
  217. # Reset the rewards
  218. final_rewards = torch.zeros([args.num_processes, 1])
  219. if args.vis and j % args.vis_interval == 0:
  220. try:
  221. # Sometimes monitor doesn't properly flush the outputs
  222. win = visdom_plot(viz, win, args.log_dir, args.env_name, args.algo)
  223. except IOError:
  224. pass
  225. if __name__ == "__main__":
  226. main()