code
stringlengths
17
6.64M
def prepare_params(kwargs): ddpg_params = dict() env_name = kwargs['env_name'] def make_env(): return gym.make(env_name) kwargs['make_env'] = make_env tmp_env = cached_make_env(kwargs['make_env']) assert hasattr(tmp_env, '_max_episode_steps') kwargs['T'] = tmp_env._max_episode_ste...
def log_params(params, logger=logger): for key in sorted(params.keys()): logger.info('{}: {}'.format(key, params[key]))
def goal_distance(goal_a, goal_b): assert (goal_a.shape == goal_b.shape) return np.linalg.norm((np.abs(goal_a) - np.abs(goal_b)), axis=(- 1))
def compute_reward(achieved_goal, desired_goal, info): (distance_threshold, reward_type) = ((0.05 * 6), 'sparse') d = goal_distance(achieved_goal, desired_goal) if (reward_type == 'sparse'): return (- (d > distance_threshold).astype(np.float32)) else: return (- d)
def configure_her(params): env = cached_make_env(params['make_env']) env.reset() if ('Pendulum' in str(env)): def reward_fun(ag_2, g, info): return compute_reward(achieved_goal=ag_2, desired_goal=g, info=info) else: def reward_fun(ag_2, g, info): return env.co...
def simple_goal_subtract(a, b): assert (a.shape == b.shape) return (a - b)
def configure_ddpg(dims, params, reuse=False, use_mpi=True, clip_return=True): sample_her_transitions = configure_her(params) gamma = params['gamma'] rollout_batch_size = params['rollout_batch_size'] ddpg_params = params['ddpg_params'] temperature = params['temperature'] prioritization = param...
def configure_dims(params): env = cached_make_env(params['make_env']) env.reset() (obs, _, _, info) = env.step(env.action_space.sample()) if ('Pendulum' in str(env)): (obs, info) = wrap_pendulum_obs(obs) dims = {'o': obs['observation'].shape[0], 'u': env.action_space.shape[0], 'g': obs['de...
@click.command() @click.argument('policy_file', type=str) @click.option('--seed', type=int, default=0) @click.option('--n_test_rollouts', type=int, default=20) @click.option('--render', type=int, default=1) def main(policy_file, seed, n_test_rollouts, render): set_global_seeds(seed) with open(policy_file, 'rb...
def mpi_average(value): if (value == []): value = [0.0] if (not isinstance(value, list)): value = [value] return mpi_moments(np.array(value))[0]
def train(policy, rollout_worker, evaluator, n_epochs, n_test_rollouts, n_cycles, n_batches, policy_save_interval, save_policies, num_cpu, dump_buffer, rank_method, fit_interval, prioritization, **kwargs): rank = MPI.COMM_WORLD.Get_rank() latest_policy_path = os.path.join(logger.get_dir(), 'policy_latest.pkl'...
def launch(env_name, n_epochs, num_cpu, seed, replay_strategy, policy_save_interval, clip_return, temperature, prioritization, binding, logging, version, dump_buffer, n_cycles, rank_method, fit_interval, override_params={}, save_policies=True): if (num_cpu > 1): whoami = mpi_fork(num_cpu, binding) ...
@click.command() @click.option('--env_name', type=click.Choice(['FetchPickAndPlace-v0', 'FetchSlide-v0', 'FetchPush-v0', 'HandManipulateBlockFull-v0', 'HandManipulateEggFull-v0', 'HandManipulatePenRotate-v0']), default='FetchPickAndPlace-v0', help='the name of the OpenAI Gym environment that you want to train ...
def make_sample_her_transitions(replay_strategy, replay_k, reward_fun): "Creates a sample function that can be used for HER experience replay.\n\n Args:\n replay_strategy (in ['future', 'none']): the HER replay strategy; if set to 'none',\n regular DDPG experience replay is used\n repl...
def make_sample_her_transitions_entropy(replay_strategy, replay_k, reward_fun): if ((replay_strategy == 'future') or (replay_strategy == 'final')): future_p = (1 - (1.0 / (1 + replay_k))) else: future_p = 0 def _sample_her_transitions(episode_batch, batch_size_in_transitions, rank_method,...
def make_sample_her_transitions_prioritized_replay(replay_strategy, replay_k, reward_fun): if ((replay_strategy == 'future') or (replay_strategy == 'final')): future_p = (1 - (1.0 / (1 + replay_k))) else: future_p = 0 def _sample_proportional(self, rollout_batch_size, batch_size, T): ...
class Normalizer(): def __init__(self, size, eps=0.01, default_clip_range=np.inf, sess=None): 'A normalizer that ensures that observations are approximately distributed according to\n a standard Normal distribution (i.e. have mean zero and variance one).\n\n Args:\n size (int): t...
class IdentityNormalizer(): def __init__(self, size, std=1.0): self.size = size self.mean = tf.zeros(self.size, tf.float32) self.std = (std * tf.ones(self.size, tf.float32)) def update(self, x): pass def normalize(self, x, clip_range=None): return (x / self.std) ...
def store_args(method): 'Stores provided method args as instance attributes.\n ' argspec = inspect.getfullargspec(method) defaults = {} if (argspec.defaults is not None): defaults = dict(zip(argspec.args[(- len(argspec.defaults)):], argspec.defaults)) if (argspec.kwonlydefaults is not N...
def import_function(spec): 'Import a function identified by a string like "pkg.module:fn_name".\n ' (mod_name, fn_name) = spec.split(':') module = importlib.import_module(mod_name) fn = getattr(module, fn_name) return fn
def flatten_grads(var_list, grads): 'Flattens a variables and their gradients.\n ' return tf.concat([tf.reshape(grad, [U.numel(v)]) for (v, grad) in zip(var_list, grads)], 0)
def nn(input, layers_sizes, reuse=None, flatten=False, name=''): 'Creates a simple neural network\n ' for (i, size) in enumerate(layers_sizes): activation = (tf.nn.relu if (i < (len(layers_sizes) - 1)) else None) input = tf.layers.dense(inputs=input, units=size, kernel_initializer=tf.contri...
def install_mpi_excepthook(): import sys from mpi4py import MPI old_hook = sys.excepthook def new_hook(a, b, c): old_hook(a, b, c) sys.stdout.flush() sys.stderr.flush() MPI.COMM_WORLD.Abort() sys.excepthook = new_hook
def mpi_fork(n, binding='core'): 'Re-launches the current script with workers\n Returns "parent" for original parent, "child" for MPI children\n ' if (n <= 1): return 'child' if (os.getenv('IN_MPI') is None): env = os.environ.copy() env.update(MKL_NUM_THREADS='1', OMP_NUM_THR...
def convert_episode_to_batch_major(episode): 'Converts an episode to have the batch dimension in the major (first)\n dimension.\n ' episode_batch = {} for key in episode.keys(): val = np.array(episode[key]).copy() episode_batch[key] = val.swapaxes(0, 1) return episode_batch
def transitions_in_episode_batch(episode_batch): 'Number of transitions in a given episode batch.\n ' shape = episode_batch['u'].shape return (shape[0] * shape[1])
def reshape_for_broadcasting(source, target): 'Reshapes a tensor (source) to have the correct shape and dtype of the target\n before broadcasting it with MPI.\n ' dim = len(target.get_shape()) shape = (([1] * (dim - 1)) + [(- 1)]) return tf.reshape(tf.cast(source, target.dtype), shape)
def wrap_pendulum_obs(obs): distance_threshold = (0.05 * 6) obs_dict = {} observation = obs.copy() costh = observation[0] sinth = observation[1] theta = math.atan2(sinth, costh) theta = (((theta + np.pi) % (2 * np.pi)) - np.pi) observation = np.array([theta, obs[2]]) desired_goal =...
class KVWriter(object): def writekvs(self, kvs): raise NotImplementedError
class SeqWriter(object): def writeseq(self, seq): raise NotImplementedError
class HumanOutputFormat(KVWriter, SeqWriter): def __init__(self, filename_or_file): if isinstance(filename_or_file, str): self.file = open(filename_or_file, 'wt') self.own_file = True else: assert hasattr(filename_or_file, 'read'), ('expected file or str, got %...
class JSONOutputFormat(KVWriter): def __init__(self, filename): self.file = open(filename, 'wt') def writekvs(self, kvs): for (k, v) in sorted(kvs.items()): if hasattr(v, 'dtype'): v = v.tolist() kvs[k] = float(v) self.file.write((json.dump...
class CSVOutputFormat(KVWriter): def __init__(self, filename): self.file = open(filename, 'w+t') self.keys = [] self.sep = ',' def writekvs(self, kvs): extra_keys = (kvs.keys() - self.keys) if extra_keys: self.keys.extend(extra_keys) self.file....
class TensorBoardOutputFormat(KVWriter): "\n Dumps key/value pairs into TensorBoard's numeric format.\n " def __init__(self, dir): os.makedirs(dir, exist_ok=True) self.dir = dir self.step = 1 prefix = 'events' path = osp.join(osp.abspath(dir), prefix) imp...
def make_output_format(format, ev_dir, log_suffix=''): os.makedirs(ev_dir, exist_ok=True) if (format == 'stdout'): return HumanOutputFormat(sys.stdout) elif (format == 'log'): return HumanOutputFormat(osp.join(ev_dir, ('log%s.txt' % log_suffix))) elif (format == 'json'): return...
def logkv(key, val): '\n Log a value of some diagnostic\n Call this once for each diagnostic quantity, each iteration\n If called many times, last value will be used.\n ' Logger.CURRENT.logkv(key, val)
def logkv_mean(key, val): '\n The same as logkv(), but if called many times, values averaged.\n ' Logger.CURRENT.logkv_mean(key, val)
def logkvs(d): '\n Log a dictionary of key-value pairs\n ' for (k, v) in d.items(): logkv(k, v)
def dumpkvs(): "\n Write all of the diagnostics from the current iteration\n\n level: int. (see logger.py docs) If the global logger level is higher than\n the level argument here, don't print to stdout.\n " Logger.CURRENT.dumpkvs()
def getkvs(): return Logger.CURRENT.name2val
def log(*args, level=INFO): "\n Write the sequence of args, with no separators, to the console and output files (if you've configured an output file).\n " Logger.CURRENT.log(*args, level=level)
def debug(*args): log(*args, level=DEBUG)
def info(*args): log(*args, level=INFO)
def warn(*args): log(*args, level=WARN)
def error(*args): log(*args, level=ERROR)
def set_level(level): '\n Set logging threshold on current logger.\n ' Logger.CURRENT.set_level(level)
def get_dir(): "\n Get directory that log files are being written to.\n will be None if there is no output directory (i.e., if you didn't call start)\n " return Logger.CURRENT.get_dir()
class ProfileKV(): '\n Usage:\n with logger.ProfileKV("interesting_scope"):\n code\n ' def __init__(self, n): self.n = ('wait_' + n) def __enter__(self): self.t1 = time.time() def __exit__(self, type, value, traceback): Logger.CURRENT.name2val[self.n] += (tim...
def profile(n): '\n Usage:\n @profile("my_func")\n def my_func(): code\n ' def decorator_with_name(func): def func_wrapper(*args, **kwargs): with ProfileKV(n): return func(*args, **kwargs) return func_wrapper return decorator_with_name
class Logger(object): DEFAULT = None CURRENT = None def __init__(self, dir, output_formats): self.name2val = defaultdict(float) self.name2cnt = defaultdict(int) self.level = INFO self.dir = dir self.output_formats = output_formats def logkv(self, key, val): ...
def configure(dir=None, format_strs=None): if (dir is None): dir = os.getenv('OPENAI_LOGDIR') if (dir is None): dir = osp.join(tempfile.gettempdir(), datetime.datetime.now().strftime('openai-%Y-%m-%d-%H-%M-%S-%f')) assert isinstance(dir, str) os.makedirs(dir, exist_ok=True) log_suf...
def reset(): if (Logger.CURRENT is not Logger.DEFAULT): Logger.CURRENT.close() Logger.CURRENT = Logger.DEFAULT log('Reset logger')
class scoped_configure(object): def __init__(self, dir=None, format_strs=None): self.dir = dir self.format_strs = format_strs self.prevlogger = None def __enter__(self): self.prevlogger = Logger.CURRENT configure(dir=self.dir, format_strs=self.format_strs) def __...
def _demo(): info('hi') debug("shouldn't appear") set_level(DEBUG) debug('should appear') dir = '/tmp/testlogging' if os.path.exists(dir): shutil.rmtree(dir) configure(dir=dir) logkv('a', 3) logkv('b', 2.5) dumpkvs() logkv('b', (- 2.5)) logkv('a', 5.5) dumpk...
def read_json(fname): import pandas ds = [] with open(fname, 'rt') as fh: for line in fh: ds.append(json.loads(line)) return pandas.DataFrame(ds)
def read_csv(fname): import pandas return pandas.read_csv(fname, index_col=None, comment='#')
def read_tb(path): '\n path : a tensorboard file OR a directory, where we will find all TB files\n of the form events.*\n ' import pandas import numpy as np from glob import glob from collections import defaultdict import tensorflow as tf if osp.isdir(path): fnames ...
def rolling_window(a, window): shape = (a.shape[:(- 1)] + (((a.shape[(- 1)] - window) + 1), window)) strides = (a.strides + (a.strides[(- 1)],)) return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
def window_func(x, y, window, func): yw = rolling_window(y, window) yw_func = func(yw, axis=(- 1)) return (x[(window - 1):], yw_func)
def ts2xy(ts, xaxis): if (xaxis == X_TIMESTEPS): x = np.cumsum(ts.l.values) y = ts.r.values elif (xaxis == X_EPISODES): x = np.arange(len(ts)) y = ts.r.values elif (xaxis == X_WALLTIME): x = (ts.t.values / 3600.0) y = ts.r.values else: raise NotI...
def plot_curves(xy_list, xaxis, title): plt.figure(figsize=(8, 2)) maxx = max((xy[0][(- 1)] for xy in xy_list)) minx = 0 for (i, (x, y)) in enumerate(xy_list): color = COLORS[i] plt.scatter(x, y, s=2) (x, y_mean) = window_func(x, y, EPISODES_WINDOW, np.mean) plt.plot(x,...
def plot_results(dirs, num_timesteps, xaxis, task_name): tslist = [] for dir in dirs: ts = load_results(dir) ts = ts[(ts.l.cumsum() <= num_timesteps)] tslist.append(ts) xy_list = [ts2xy(ts, xaxis) for ts in tslist] plot_curves(xy_list, xaxis, task_name)
def main(): import argparse import os parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--dirs', help='List of log directories', nargs='*', default=['./log']) parser.add_argument('--num_timesteps', type=int, default=int(10000000.0)) p...
class AlexNet(nn.Module): def __init__(self, num_classes=1000, ratioInfl=1): super(AlexNet, self).__init__() self.ratioInfl = ratioInfl self.activation_func = HardTanh_bin self.channels = [3, int((96 * self.ratioInfl)), int((256 * self.ratioInfl)), int((384 * self.ratioInfl)), int...
def alexnet_binary_vs_xnor(**kwargs): num_classes = getattr(kwargs, 'num_classes', 1000) infl_ratio = 1.0 if ('infl_ratio' in kwargs): infl_ratio = kwargs['infl_ratio'] return AlexNet(num_classes, infl_ratio)
class BinarizeF(Function): @staticmethod def forward(ctx, input): return torch.sign(input) @staticmethod def backward(ctx, grad_output): grad_input = grad_output.clone() return grad_input
class HardTanh_bin(nn.Module): def __init__(self): super(HardTanh_bin, self).__init__() self.hardtanh = nn.Hardtanh(inplace=False) self.binarize = BinarizeF.apply def forward(self, input): output = self.hardtanh(input) output = self.binarize(output) return out...
class BinarizeLinear(nn.Linear): def __init__(self, *kargs, **kwargs): super(BinarizeLinear, self).__init__(*kargs, **kwargs) def forward(self, input): if (not hasattr(self.weight, 'org')): self.weight.org = self.weight.data.clone() self.weight.data = self.weight.org.sign...
class BinarizeConv2d(nn.Conv2d): def __init__(self, *kargs, **kwargs): super(BinarizeConv2d, self).__init__(*kargs, **kwargs) def forward(self, input): if (not hasattr(self.weight, 'org')): self.weight.org = self.weight.data.clone() self.weight.data = self.weight.org.sign...
class Distrloss_layer(nn.Module): def __init__(self, channels): super(Distrloss_layer, self).__init__() self._channels = channels def forward(self, input): if ((input.dim() != 4) and (input.dim() != 2)): raise ValueError('expected 4D or 2D input (got {}D input)'.format(in...
def setup_logging(log_file='log.txt'): 'Setup logging configuration\n ' logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', filename=log_file, filemode='w') console = logging.StreamHandler() console.setLevel(logging.INFO) for...
def save_checkpoint(state, is_best, path='.', filename='checkpoint.pth.tar', save_all=False): filename = os.path.join(path, filename) torch.save(state, filename) if is_best: shutil.copyfile(filename, os.path.join(path, 'model_best.pth.tar')) if save_all: shutil.copyfile(filename, os.pa...
class AverageMeter(object): 'Computes and stores the average and current value' def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += (val...
def adjust_optimizer(optimizer, epoch, config): 'Reconfigures the optimizer according to epoch and config dict' def modify_optimizer(optimizer, setting): if ('optimizer' in setting): optimizer = __optimizers[setting['optimizer']](optimizer.param_groups) logging.debug(('OPTIMIZ...
def accuracy(output, target, topk=(1,)): 'Computes the precision@k for the specified values of k' maxk = max(topk) batch_size = target.size(0) (_, pred) = output.float().topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, (- 1)).expand_as(pred)) res = [] for k in...
def cg(f_Ax, b, cg_iters=10, callback=None, verbose=False, residual_tol=1e-10): '\n Demmel p 312\n ' p = b.copy() r = b.copy() x = np.zeros_like(b) rdotr = r.dot(r) fmtstr = '%10i %10.3g %10.3g' titlestr = '%10s %10s %10s' if verbose: print((titlestr % ('iter', 'residual ...
def make_atari_env(env_id, num_env, seed, wrapper_kwargs=None, start_index=0): '\n Create a wrapped, monitored SubprocVecEnv for Atari.\n ' if (wrapper_kwargs is None): wrapper_kwargs = {} def make_env(rank): def _thunk(): env = make_atari(env_id) env.seed((...
def make_mujoco_env(env_id, seed): '\n Create a wrapped, monitored gym.Env for MuJoCo.\n ' set_global_seeds(seed) env = gym.make(env_id) env = Monitor(env, logger.get_dir()) env.seed(seed) return env
def make_robotics_env(env_id, seed, rank=0): '\n Create a wrapped, monitored gym.Env for MuJoCo.\n ' set_global_seeds(seed) env = gym.make(env_id) env = FlattenDictWrapper(env, ['observation', 'desired_goal']) env = Monitor(env, (logger.get_dir() and os.path.join(logger.get_dir(), str(rank))...
def arg_parser(): '\n Create an empty argparse.ArgumentParser.\n ' import argparse return argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
def atari_arg_parser(): '\n Create an argparse.ArgumentParser for run_atari.py.\n ' parser = arg_parser() parser.add_argument('--env', help='environment ID', default='BreakoutNoFrameskip-v4') parser.add_argument('--seed', help='RNG seed', type=int, default=0) parser.add_argument('--num-times...
def mujoco_arg_parser(): '\n Create an argparse.ArgumentParser for run_mujoco.py.\n ' parser = arg_parser() parser.add_argument('--env', help='environment ID', type=str, default='Reacher-v2') parser.add_argument('--seed', help='RNG seed', type=int, default=0) parser.add_argument('--num-times...
def robotics_arg_parser(): '\n Create an argparse.ArgumentParser for run_mujoco.py.\n ' parser = arg_parser() parser.add_argument('--env', help='environment ID', type=str, default='FetchReach-v0') parser.add_argument('--seed', help='RNG seed', type=int, default=0) parser.add_argument('--num-...
def fmt_row(width, row, header=False): out = ' | '.join((fmt_item(x, width) for x in row)) if header: out = ((out + '\n') + ('-' * len(out))) return out
def fmt_item(x, l): if isinstance(x, np.ndarray): assert (x.ndim == 0) x = x.item() if isinstance(x, (float, np.float32, np.float64)): v = abs(x) if (((v < 0.0001) or (v > 10000.0)) and (v > 0)): rep = ('%7.2e' % x) else: rep = ('%7.5f' % x) ...
def colorize(string, color, bold=False, highlight=False): attr = [] num = color2num[color] if highlight: num += 10 attr.append(str(num)) if bold: attr.append('1') return ('\x1b[%sm%s\x1b[0m' % (';'.join(attr), string))
@contextmanager def timed(msg): global MESSAGE_DEPTH print(colorize(((('\t' * MESSAGE_DEPTH) + '=: ') + msg), color='magenta')) tstart = time.time() MESSAGE_DEPTH += 1 (yield) MESSAGE_DEPTH -= 1 print(colorize((('\t' * MESSAGE_DEPTH) + ('done in %.3f seconds' % (time.time() - tstart))), co...
class Dataset(object): def __init__(self, data_map, deterministic=False, shuffle=True): self.data_map = data_map self.deterministic = deterministic self.enable_shuffle = shuffle self.n = next(iter(data_map.values())).shape[0] self._next_id = 0 self.shuffle() d...
def iterbatches(arrays, *, num_batches=None, batch_size=None, shuffle=True, include_final_partial_batch=True): assert ((num_batches is None) != (batch_size is None)), 'Provide num_batches or batch_size, but not both' arrays = tuple(map(np.asarray, arrays)) n = arrays[0].shape[0] assert all(((a.shape[0...
class Filter(object): def __call__(self, x, update=True): raise NotImplementedError def reset(self): pass
class IdentityFilter(Filter): def __call__(self, x, update=True): return x
class CompositionFilter(Filter): def __init__(self, fs): self.fs = fs def __call__(self, x, update=True): for f in self.fs: x = f(x) return x def output_shape(self, input_space): out = input_space.shape for f in self.fs: out = f.output_sha...
class ZFilter(Filter): '\n y = (x-mean)/std\n using running estimates of mean,std\n ' def __init__(self, shape, demean=True, destd=True, clip=10.0): self.demean = demean self.destd = destd self.clip = clip self.rs = RunningStat(shape) def __call__(self, x, update...
class AddClock(Filter): def __init__(self): self.count = 0 def reset(self): self.count = 0 def __call__(self, x, update=True): return np.append(x, (self.count / 100.0)) def output_shape(self, input_space): return ((input_space.shape[0] + 1),)
class FlattenFilter(Filter): def __call__(self, x, update=True): return x.ravel() def output_shape(self, input_space): return (int(np.prod(input_space.shape)),)
class Ind2OneHotFilter(Filter): def __init__(self, n): self.n = n def __call__(self, x, update=True): out = np.zeros(self.n) out[x] = 1 return out def output_shape(self, input_space): return (input_space.n,)
class DivFilter(Filter): def __init__(self, divisor): self.divisor = divisor def __call__(self, x, update=True): return (x / self.divisor) def output_shape(self, input_space): return input_space.shape
class StackFilter(Filter): def __init__(self, length): self.stack = deque(maxlen=length) def reset(self): self.stack.clear() def __call__(self, x, update=True): self.stack.append(x) while (len(self.stack) < self.stack.maxlen): self.stack.append(x) ret...
def discount(x, gamma): '\n computes discounted sums along 0th dimension of x.\n\n inputs\n ------\n x: ndarray\n gamma: float\n\n outputs\n -------\n y: ndarray with same shape as x, satisfying\n\n y[t] = x[t] + gamma*x[t+1] + gamma^2*x[t+2] + ... + gamma^k x[t+k],\n ...
def explained_variance(ypred, y): '\n Computes fraction of variance that ypred explains about y.\n Returns 1 - Var[y-ypred] / Var[y]\n\n interpretation:\n ev=0 => might as well have predicted zero\n ev=1 => perfect prediction\n ev<0 => worse than just predicting zero\n\n ' ...