2017-05-14 17:53:51 -07:00
|
|
|
# Code in this file is copied and adapted from
|
|
|
|
# https://github.com/openai/evolution-strategies-starter.
|
|
|
|
|
|
|
|
from collections import namedtuple
|
2018-10-21 23:43:57 -07:00
|
|
|
import logging
|
2017-05-14 17:53:51 -07:00
|
|
|
import numpy as np
|
|
|
|
import time
|
|
|
|
|
2017-06-25 15:13:03 -07:00
|
|
|
import ray
|
2019-04-07 00:36:18 -07:00
|
|
|
from ray.rllib.agents import Trainer, with_common_config
|
2017-06-25 15:13:03 -07:00
|
|
|
|
2018-07-01 00:05:08 -07:00
|
|
|
from ray.rllib.agents.es import optimizers
|
|
|
|
from ray.rllib.agents.es import policies
|
|
|
|
from ray.rllib.agents.es import utils
|
2019-05-20 16:46:05 -07:00
|
|
|
from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID
|
2018-12-08 16:28:58 -08:00
|
|
|
from ray.rllib.utils.annotations import override
|
2019-04-17 20:30:03 -04:00
|
|
|
from ray.rllib.utils.memory import ray_get_and_free
|
2018-11-06 17:09:34 -10:00
|
|
|
from ray.rllib.utils import FilterManager
|
2017-05-14 17:53:51 -07:00
|
|
|
|
2018-10-21 23:43:57 -07:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2017-05-14 17:53:51 -07:00
|
|
|
Result = namedtuple("Result", [
|
2017-11-16 21:58:30 -08:00
|
|
|
"noise_indices", "noisy_returns", "sign_noisy_returns", "noisy_lengths",
|
|
|
|
"eval_returns", "eval_lengths"
|
2017-05-14 17:53:51 -07:00
|
|
|
])
|
|
|
|
|
2018-10-21 23:43:57 -07:00
|
|
|
# yapf: disable
|
2018-10-16 15:55:11 -07:00
|
|
|
# __sphinx_doc_begin__
|
2018-10-01 12:49:39 -07:00
|
|
|
DEFAULT_CONFIG = with_common_config({
|
2018-07-30 13:25:35 -07:00
|
|
|
"l2_coeff": 0.005,
|
|
|
|
"noise_stdev": 0.02,
|
|
|
|
"episodes_per_batch": 1000,
|
2018-09-05 12:06:13 -07:00
|
|
|
"train_batch_size": 10000,
|
2018-07-30 13:25:35 -07:00
|
|
|
"eval_prob": 0.003,
|
|
|
|
"return_proc_mode": "centered_rank",
|
|
|
|
"num_workers": 10,
|
|
|
|
"stepsize": 0.01,
|
|
|
|
"observation_filter": "MeanStdFilter",
|
|
|
|
"noise_size": 250000000,
|
2018-09-26 22:32:26 -07:00
|
|
|
"report_length": 10,
|
2018-10-01 12:49:39 -07:00
|
|
|
})
|
2018-10-16 15:55:11 -07:00
|
|
|
# __sphinx_doc_end__
|
2018-10-21 23:43:57 -07:00
|
|
|
# yapf: enable
|
2017-06-25 15:13:03 -07:00
|
|
|
|
|
|
|
|
2017-05-14 17:53:51 -07:00
|
|
|
@ray.remote
|
2018-01-24 11:03:43 -08:00
|
|
|
def create_shared_noise(count):
|
2017-07-13 14:53:57 -07:00
|
|
|
"""Create a large array of noise to be shared by all workers."""
|
|
|
|
seed = 123
|
|
|
|
noise = np.random.RandomState(seed).randn(count).astype(np.float32)
|
|
|
|
return noise
|
2017-05-14 17:53:51 -07:00
|
|
|
|
|
|
|
|
2020-01-02 17:42:13 -08:00
|
|
|
class SharedNoiseTable:
|
2017-07-13 14:53:57 -07:00
|
|
|
def __init__(self, noise):
|
|
|
|
self.noise = noise
|
|
|
|
assert self.noise.dtype == np.float32
|
2017-05-14 17:53:51 -07:00
|
|
|
|
2017-07-13 14:53:57 -07:00
|
|
|
def get(self, i, dim):
|
|
|
|
return self.noise[i:i + dim]
|
2017-05-14 17:53:51 -07:00
|
|
|
|
2017-11-16 21:58:30 -08:00
|
|
|
def sample_index(self, dim):
|
|
|
|
return np.random.randint(0, len(self.noise) - dim + 1)
|
2017-05-14 17:53:51 -07:00
|
|
|
|
|
|
|
|
|
|
|
@ray.remote
|
2020-01-02 17:42:13 -08:00
|
|
|
class Worker:
|
2018-07-19 15:30:36 -07:00
|
|
|
def __init__(self,
|
|
|
|
config,
|
|
|
|
policy_params,
|
|
|
|
env_creator,
|
|
|
|
noise,
|
2017-07-13 14:53:57 -07:00
|
|
|
min_task_runtime=0.2):
|
|
|
|
self.min_task_runtime = min_task_runtime
|
|
|
|
self.config = config
|
|
|
|
self.policy_params = policy_params
|
|
|
|
self.noise = SharedNoiseTable(noise)
|
|
|
|
|
2018-01-05 21:32:41 -08:00
|
|
|
self.env = env_creator(config["env_config"])
|
2018-03-23 05:54:31 -07:00
|
|
|
from ray.rllib import models
|
2018-10-16 15:55:11 -07:00
|
|
|
self.preprocessor = models.ModelCatalog.get_preprocessor(
|
|
|
|
self.env, config["model"])
|
2017-08-22 03:51:49 +02:00
|
|
|
|
2017-07-13 14:53:57 -07:00
|
|
|
self.sess = utils.make_session(single_threaded=True)
|
2017-12-28 13:19:04 -08:00
|
|
|
self.policy = policies.GenericPolicy(
|
2018-10-20 15:21:22 -07:00
|
|
|
self.sess, self.env.action_space, self.env.observation_space,
|
|
|
|
self.preprocessor, config["observation_filter"], config["model"],
|
|
|
|
**policy_params)
|
2017-11-16 21:58:30 -08:00
|
|
|
|
2018-11-06 17:09:34 -10:00
|
|
|
@property
|
|
|
|
def filters(self):
|
2019-03-26 00:27:59 -07:00
|
|
|
return {DEFAULT_POLICY_ID: self.policy.get_filter()}
|
2018-11-06 17:09:34 -10:00
|
|
|
|
|
|
|
def sync_filters(self, new_filters):
|
|
|
|
for k in self.filters:
|
|
|
|
self.filters[k].sync(new_filters[k])
|
|
|
|
|
|
|
|
def get_filters(self, flush_after=False):
|
|
|
|
return_filters = {}
|
|
|
|
for k, f in self.filters.items():
|
|
|
|
return_filters[k] = f.as_serializable()
|
|
|
|
if flush_after:
|
|
|
|
f.clear_buffer()
|
|
|
|
return return_filters
|
|
|
|
|
2017-11-16 21:58:30 -08:00
|
|
|
def rollout(self, timestep_limit, add_noise=True):
|
|
|
|
rollout_rewards, rollout_length = policies.rollout(
|
2018-07-19 15:30:36 -07:00
|
|
|
self.policy,
|
|
|
|
self.env,
|
|
|
|
timestep_limit=timestep_limit,
|
2017-11-16 21:58:30 -08:00
|
|
|
add_noise=add_noise)
|
|
|
|
return rollout_rewards, rollout_length
|
|
|
|
|
|
|
|
def do_rollouts(self, params, timestep_limit=None):
|
2017-07-13 14:53:57 -07:00
|
|
|
# Set the network weights.
|
2017-11-16 21:58:30 -08:00
|
|
|
self.policy.set_weights(params)
|
2017-07-13 14:53:57 -07:00
|
|
|
|
2017-11-16 21:58:30 -08:00
|
|
|
noise_indices, returns, sign_returns, lengths = [], [], [], []
|
|
|
|
eval_returns, eval_lengths = [], []
|
2017-07-13 14:53:57 -07:00
|
|
|
|
|
|
|
# Perform some rollouts with noise.
|
|
|
|
task_tstart = time.time()
|
2018-07-19 15:30:36 -07:00
|
|
|
while (len(noise_indices) == 0
|
|
|
|
or time.time() - task_tstart < self.min_task_runtime):
|
2017-11-16 21:58:30 -08:00
|
|
|
|
|
|
|
if np.random.uniform() < self.config["eval_prob"]:
|
|
|
|
# Do an evaluation run with no perturbation.
|
|
|
|
self.policy.set_weights(params)
|
|
|
|
rewards, length = self.rollout(timestep_limit, add_noise=False)
|
|
|
|
eval_returns.append(rewards.sum())
|
|
|
|
eval_lengths.append(length)
|
|
|
|
else:
|
|
|
|
# Do a regular run with parameter perturbations.
|
|
|
|
noise_index = self.noise.sample_index(self.policy.num_params)
|
|
|
|
|
|
|
|
perturbation = self.config["noise_stdev"] * self.noise.get(
|
|
|
|
noise_index, self.policy.num_params)
|
|
|
|
|
|
|
|
# These two sampling steps could be done in parallel on
|
|
|
|
# different actors letting us update twice as frequently.
|
|
|
|
self.policy.set_weights(params + perturbation)
|
|
|
|
rewards_pos, lengths_pos = self.rollout(timestep_limit)
|
|
|
|
|
|
|
|
self.policy.set_weights(params - perturbation)
|
|
|
|
rewards_neg, lengths_neg = self.rollout(timestep_limit)
|
|
|
|
|
|
|
|
noise_indices.append(noise_index)
|
|
|
|
returns.append([rewards_pos.sum(), rewards_neg.sum()])
|
|
|
|
sign_returns.append(
|
2018-07-19 15:30:36 -07:00
|
|
|
[np.sign(rewards_pos).sum(),
|
|
|
|
np.sign(rewards_neg).sum()])
|
2017-11-16 21:58:30 -08:00
|
|
|
lengths.append([lengths_pos, lengths_neg])
|
2017-07-13 14:53:57 -07:00
|
|
|
|
2018-01-31 17:22:39 -08:00
|
|
|
return Result(
|
|
|
|
noise_indices=noise_indices,
|
|
|
|
noisy_returns=returns,
|
|
|
|
sign_noisy_returns=sign_returns,
|
|
|
|
noisy_lengths=lengths,
|
|
|
|
eval_returns=eval_returns,
|
|
|
|
eval_lengths=eval_lengths)
|
2017-05-14 17:53:51 -07:00
|
|
|
|
|
|
|
|
2019-04-07 00:36:18 -07:00
|
|
|
class ESTrainer(Trainer):
|
2018-07-01 00:05:08 -07:00
|
|
|
"""Large-scale implementation of Evolution Strategies in Ray."""
|
|
|
|
|
2019-04-07 00:36:18 -07:00
|
|
|
_name = "ES"
|
2017-10-13 16:18:16 -07:00
|
|
|
_default_config = DEFAULT_CONFIG
|
2017-08-27 18:56:52 -07:00
|
|
|
|
2019-04-07 00:36:18 -07:00
|
|
|
@override(Trainer)
|
2019-03-29 12:44:23 -07:00
|
|
|
def _init(self, config, env_creator):
|
2018-07-19 15:30:36 -07:00
|
|
|
policy_params = {"action_noise_std": 0.01}
|
2017-07-13 14:53:57 -07:00
|
|
|
|
2019-03-29 12:44:23 -07:00
|
|
|
env = env_creator(config["env_config"])
|
2018-03-23 05:54:31 -07:00
|
|
|
from ray.rllib import models
|
2018-06-19 22:47:00 -07:00
|
|
|
preprocessor = models.ModelCatalog.get_preprocessor(env)
|
2017-08-22 03:51:49 +02:00
|
|
|
|
2017-08-27 18:56:52 -07:00
|
|
|
self.sess = utils.make_session(single_threaded=False)
|
2017-07-17 01:58:54 -07:00
|
|
|
self.policy = policies.GenericPolicy(
|
2018-10-20 15:21:22 -07:00
|
|
|
self.sess, env.action_space, env.observation_space, preprocessor,
|
2019-03-29 12:44:23 -07:00
|
|
|
config["observation_filter"], config["model"], **policy_params)
|
|
|
|
self.optimizer = optimizers.Adam(self.policy, config["stepsize"])
|
|
|
|
self.report_length = config["report_length"]
|
2017-07-17 01:58:54 -07:00
|
|
|
|
2017-07-13 14:53:57 -07:00
|
|
|
# Create the shared noise table.
|
2018-10-21 23:43:57 -07:00
|
|
|
logger.info("Creating shared noise table.")
|
2019-03-29 12:44:23 -07:00
|
|
|
noise_id = create_shared_noise.remote(config["noise_size"])
|
2017-07-13 14:53:57 -07:00
|
|
|
self.noise = SharedNoiseTable(ray.get(noise_id))
|
|
|
|
|
|
|
|
# Create the actors.
|
2018-10-21 23:43:57 -07:00
|
|
|
logger.info("Creating actors.")
|
2019-06-03 06:49:24 +08:00
|
|
|
self._workers = [
|
2019-03-29 12:44:23 -07:00
|
|
|
Worker.remote(config, policy_params, env_creator, noise_id)
|
|
|
|
for _ in range(config["num_workers"])
|
2018-07-19 15:30:36 -07:00
|
|
|
]
|
2017-07-13 14:53:57 -07:00
|
|
|
|
|
|
|
self.episodes_so_far = 0
|
2018-09-26 22:32:26 -07:00
|
|
|
self.reward_list = []
|
2017-07-13 14:53:57 -07:00
|
|
|
self.tstart = time.time()
|
|
|
|
|
2019-04-07 00:36:18 -07:00
|
|
|
@override(Trainer)
|
2017-09-12 14:28:16 -07:00
|
|
|
def _train(self):
|
2017-07-13 14:53:57 -07:00
|
|
|
config = self.config
|
|
|
|
|
2017-11-16 21:58:30 -08:00
|
|
|
theta = self.policy.get_weights()
|
2017-07-13 14:53:57 -07:00
|
|
|
assert theta.dtype == np.float32
|
|
|
|
|
|
|
|
# Put the current policy weights in the object store.
|
|
|
|
theta_id = ray.put(theta)
|
|
|
|
# Use the actors to do rollouts, note that we pass in the ID of the
|
|
|
|
# policy weights.
|
2017-11-16 21:58:30 -08:00
|
|
|
results, num_episodes, num_timesteps = self._collect_results(
|
2018-09-05 12:06:13 -07:00
|
|
|
theta_id, config["episodes_per_batch"], config["train_batch_size"])
|
2017-07-13 14:53:57 -07:00
|
|
|
|
2017-11-16 21:58:30 -08:00
|
|
|
all_noise_indices = []
|
|
|
|
all_training_returns = []
|
|
|
|
all_training_lengths = []
|
|
|
|
all_eval_returns = []
|
|
|
|
all_eval_lengths = []
|
|
|
|
|
|
|
|
# Loop over the results.
|
2017-07-13 14:53:57 -07:00
|
|
|
for result in results:
|
2017-11-16 21:58:30 -08:00
|
|
|
all_eval_returns += result.eval_returns
|
|
|
|
all_eval_lengths += result.eval_lengths
|
|
|
|
|
|
|
|
all_noise_indices += result.noise_indices
|
|
|
|
all_training_returns += result.noisy_returns
|
|
|
|
all_training_lengths += result.noisy_lengths
|
|
|
|
|
|
|
|
assert len(all_eval_returns) == len(all_eval_lengths)
|
|
|
|
assert (len(all_noise_indices) == len(all_training_returns) ==
|
|
|
|
len(all_training_lengths))
|
|
|
|
|
|
|
|
self.episodes_so_far += num_episodes
|
2017-07-13 14:53:57 -07:00
|
|
|
|
|
|
|
# Assemble the results.
|
2017-11-16 21:58:30 -08:00
|
|
|
eval_returns = np.array(all_eval_returns)
|
|
|
|
eval_lengths = np.array(all_eval_lengths)
|
|
|
|
noise_indices = np.array(all_noise_indices)
|
|
|
|
noisy_returns = np.array(all_training_returns)
|
|
|
|
noisy_lengths = np.array(all_training_lengths)
|
|
|
|
|
2017-07-13 14:53:57 -07:00
|
|
|
# Process the returns.
|
|
|
|
if config["return_proc_mode"] == "centered_rank":
|
2017-11-16 21:58:30 -08:00
|
|
|
proc_noisy_returns = utils.compute_centered_ranks(noisy_returns)
|
2017-07-13 14:53:57 -07:00
|
|
|
else:
|
|
|
|
raise NotImplementedError(config["return_proc_mode"])
|
|
|
|
|
|
|
|
# Compute and take a step.
|
|
|
|
g, count = utils.batched_weighted_sum(
|
2017-11-16 21:58:30 -08:00
|
|
|
proc_noisy_returns[:, 0] - proc_noisy_returns[:, 1],
|
|
|
|
(self.noise.get(index, self.policy.num_params)
|
|
|
|
for index in noise_indices),
|
2017-07-13 14:53:57 -07:00
|
|
|
batch_size=500)
|
2017-11-16 21:58:30 -08:00
|
|
|
g /= noisy_returns.size
|
2018-07-19 15:30:36 -07:00
|
|
|
assert (g.shape == (self.policy.num_params, ) and g.dtype == np.float32
|
|
|
|
and count == len(noise_indices))
|
2017-11-16 21:58:30 -08:00
|
|
|
# Compute the new weights theta.
|
2018-07-19 15:30:36 -07:00
|
|
|
theta, update_ratio = self.optimizer.update(-g +
|
|
|
|
config["l2_coeff"] * theta)
|
2017-11-16 21:58:30 -08:00
|
|
|
# Set the new weights in the local copy of the policy.
|
|
|
|
self.policy.set_weights(theta)
|
2018-09-26 22:32:26 -07:00
|
|
|
# Store the rewards
|
|
|
|
if len(all_eval_returns) > 0:
|
|
|
|
self.reward_list.append(np.mean(eval_returns))
|
2017-07-13 14:53:57 -07:00
|
|
|
|
2018-11-06 17:09:34 -10:00
|
|
|
# Now sync the filters
|
|
|
|
FilterManager.synchronize({
|
2019-03-26 00:27:59 -07:00
|
|
|
DEFAULT_POLICY_ID: self.policy.get_filter()
|
2019-06-03 06:49:24 +08:00
|
|
|
}, self._workers)
|
2018-11-06 17:09:34 -10:00
|
|
|
|
2017-07-13 14:53:57 -07:00
|
|
|
info = {
|
2017-11-16 21:58:30 -08:00
|
|
|
"weights_norm": np.square(theta).sum(),
|
2017-07-13 14:53:57 -07:00
|
|
|
"grad_norm": np.square(g).sum(),
|
|
|
|
"update_ratio": update_ratio,
|
2017-11-16 21:58:30 -08:00
|
|
|
"episodes_this_iter": noisy_lengths.size,
|
2017-07-13 14:53:57 -07:00
|
|
|
"episodes_so_far": self.episodes_so_far,
|
|
|
|
}
|
|
|
|
|
2018-09-26 22:32:26 -07:00
|
|
|
reward_mean = np.mean(self.reward_list[-self.report_length:])
|
2018-08-07 12:17:44 -07:00
|
|
|
result = dict(
|
2018-09-26 22:32:26 -07:00
|
|
|
episode_reward_mean=reward_mean,
|
2017-11-16 21:58:30 -08:00
|
|
|
episode_len_mean=eval_lengths.mean(),
|
|
|
|
timesteps_this_iter=noisy_lengths.sum(),
|
2017-09-12 14:28:16 -07:00
|
|
|
info=info)
|
2017-07-13 14:53:57 -07:00
|
|
|
|
2017-09-12 14:28:16 -07:00
|
|
|
return result
|
2017-08-24 00:09:33 -07:00
|
|
|
|
2019-04-07 00:36:18 -07:00
|
|
|
@override(Trainer)
|
2018-12-08 16:28:58 -08:00
|
|
|
def compute_action(self, observation):
|
|
|
|
return self.policy.compute(observation, update=False)[0]
|
|
|
|
|
2019-04-07 00:36:18 -07:00
|
|
|
@override(Trainer)
|
2018-02-11 19:14:51 -08:00
|
|
|
def _stop(self):
|
|
|
|
# workaround for https://github.com/ray-project/ray/issues/1516
|
2019-06-03 06:49:24 +08:00
|
|
|
for w in self._workers:
|
2018-05-08 19:19:07 -07:00
|
|
|
w.__ray_terminate__.remote()
|
2018-02-11 19:14:51 -08:00
|
|
|
|
2018-12-08 16:28:58 -08:00
|
|
|
def _collect_results(self, theta_id, min_episodes, min_timesteps):
|
|
|
|
num_episodes, num_timesteps = 0, 0
|
|
|
|
results = []
|
|
|
|
while num_episodes < min_episodes or num_timesteps < min_timesteps:
|
|
|
|
logger.info(
|
|
|
|
"Collected {} episodes {} timesteps so far this iter".format(
|
|
|
|
num_episodes, num_timesteps))
|
|
|
|
rollout_ids = [
|
2019-06-03 06:49:24 +08:00
|
|
|
worker.do_rollouts.remote(theta_id) for worker in self._workers
|
2018-12-08 16:28:58 -08:00
|
|
|
]
|
|
|
|
# Get the results of the rollouts.
|
2019-04-17 20:30:03 -04:00
|
|
|
for result in ray_get_and_free(rollout_ids):
|
2018-12-08 16:28:58 -08:00
|
|
|
results.append(result)
|
|
|
|
# Update the number of episodes and the number of timesteps
|
|
|
|
# keeping in mind that result.noisy_lengths is a list of lists,
|
|
|
|
# where the inner lists have length 2.
|
|
|
|
num_episodes += sum(len(pair) for pair in result.noisy_lengths)
|
|
|
|
num_timesteps += sum(
|
|
|
|
sum(pair) for pair in result.noisy_lengths)
|
|
|
|
|
|
|
|
return results, num_episodes, num_timesteps
|
|
|
|
|
2018-09-30 01:15:13 -07:00
|
|
|
def __getstate__(self):
|
|
|
|
return {
|
|
|
|
"weights": self.policy.get_weights(),
|
2018-11-06 17:09:34 -10:00
|
|
|
"filter": self.policy.get_filter(),
|
2018-09-30 01:15:13 -07:00
|
|
|
"episodes_so_far": self.episodes_so_far,
|
|
|
|
}
|
|
|
|
|
|
|
|
def __setstate__(self, state):
|
|
|
|
self.episodes_so_far = state["episodes_so_far"]
|
2018-11-06 17:09:34 -10:00
|
|
|
self.policy.set_weights(state["weights"])
|
|
|
|
self.policy.set_filter(state["filter"])
|
|
|
|
FilterManager.synchronize({
|
2019-03-26 00:27:59 -07:00
|
|
|
DEFAULT_POLICY_ID: self.policy.get_filter()
|
2019-06-03 06:49:24 +08:00
|
|
|
}, self._workers)
|