main.py 11 KB

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