main.py 10 KB

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