main.py 11 KB

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