code
stringlengths
17
6.64M
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 ' ...
def explained_variance_2d(ypred, y): assert ((y.ndim == 2) and (ypred.ndim == 2)) vary = np.var(y, axis=0) out = (1 - (np.var((y - ypred)) / vary)) out[(vary < 1e-10)] = 0 return out
def ncc(ypred, y): return np.corrcoef(ypred, y)[(1, 0)]
def flatten_arrays(arrs): return np.concatenate([arr.flat for arr in arrs])
def unflatten_vector(vec, shapes): i = 0 arrs = [] for shape in shapes: size = np.prod(shape) arr = vec[i:(i + size)].reshape(shape) arrs.append(arr) i += size return arrs
def discount_with_boundaries(X, New, gamma): '\n X: 2d array of floats, time x features\n New: 2d array of bools, indicating when a new episode has started\n ' Y = np.zeros_like(X) T = X.shape[0] Y[(T - 1)] = X[(T - 1)] for t in range((T - 2), (- 1), (- 1)): Y[t] = (X[t] + ((gamma...
def test_discount_with_boundaries(): gamma = 0.9 x = np.array([1.0, 2.0, 3.0, 4.0], 'float32') starts = [1.0, 0.0, 0.0, 1.0] y = discount_with_boundaries(x, starts, gamma) assert np.allclose(y, [((1 + (gamma * 2)) + ((gamma ** 2) * 3)), (2 + (gamma * 3)), 3, 4])
def zipsame(*seqs): L = len(seqs[0]) assert all(((len(seq) == L) for seq in seqs[1:])) return zip(*seqs)
def unpack(seq, sizes): "\n Unpack 'seq' into a sequence of lists, with lengths specified by 'sizes'.\n None = just one bare element, not a list\n\n Example:\n unpack([1,2,3,4,5,6], [3,None,2]) -> ([1,2,3], 4, [5,6])\n " seq = list(seq) it = iter(seq) assert (sum(((1 if (s is None) else...
class EzPickle(object): 'Objects that are pickled and unpickled via their constructor\n arguments.\n\n Example usage:\n\n class Dog(Animal, EzPickle):\n def __init__(self, furcolor, tailkind="bushy"):\n Animal.__init__()\n EzPickle.__init__(furcolor, tailkind)...
def set_global_seeds(i): try: import tensorflow as tf except ImportError: pass else: tf.set_random_seed(i) np.random.seed(i) random.seed(i)
def pretty_eta(seconds_left): 'Print the number of seconds in human readable format.\n\n Examples:\n 2 days\n 2 hours and 37 minutes\n less than a minute\n\n Paramters\n ---------\n seconds_left: int\n Number of seconds to be converted to the ETA\n Returns\n -------\n eta: str...
class RunningAvg(object): def __init__(self, gamma, init_value=None): 'Keep a running estimate of a quantity. This is a bit like mean\n but more sensitive to recent changes.\n\n Parameters\n ----------\n gamma: float\n Must be between 0 and 1, where 0 is the most se...
def boolean_flag(parser, name, default=False, help=None): 'Add a boolean flag to argparse parser.\n\n Parameters\n ----------\n parser: argparse.Parser\n parser to add the flag to\n name: str\n --<name> will enable the flag, while --no-<name> will disable it\n default: bool or None\n ...
def get_wrapper_by_name(env, classname): 'Given an a gym environment possibly wrapped multiple times, returns a wrapper\n of class named classname or raises ValueError if no such wrapper was applied\n\n Parameters\n ----------\n env: gym.Env of gym.Wrapper\n gym environment\n classname: str\...
def relatively_safe_pickle_dump(obj, path, compression=False): "This is just like regular pickle dump, except from the fact that failure cases are\n different:\n\n - It's never possible that we end up with a pickle in corrupted state.\n - If a there was a different file at the path, that file wil...
def pickle_load(path, compression=False): 'Unpickle a possible compressed pickle.\n\n Parameters\n ----------\n path: str\n path to the output file\n compression: bool\n if true assumes that pickle was compressed when created and attempts decompression.\n\n Returns\n -------\n o...
class MpiAdam(object): def __init__(self, var_list, *, beta1=0.9, beta2=0.999, epsilon=1e-08, scale_grad_by_procs=True, comm=None): self.var_list = var_list self.beta1 = beta1 self.beta2 = beta2 self.epsilon = epsilon self.scale_grad_by_procs = scale_grad_by_procs ...
@U.in_session def test_MpiAdam(): np.random.seed(0) tf.set_random_seed(0) a = tf.Variable(np.random.randn(3).astype('float32')) b = tf.Variable(np.random.randn(2, 5).astype('float32')) loss = (tf.reduce_sum(tf.square(a)) + tf.reduce_sum(tf.sin(b))) stepsize = 0.01 update_op = tf.train.Adam...
def mpi_fork(n, bind_to_core=False): '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...
def mpi_mean(x, axis=0, comm=None, keepdims=False): x = np.asarray(x) assert (x.ndim > 0) if (comm is None): comm = MPI.COMM_WORLD xsum = x.sum(axis=axis, keepdims=keepdims) n = xsum.size localsum = np.zeros((n + 1), x.dtype) localsum[:n] = xsum.ravel() localsum[n] = x.shape[ax...
def mpi_moments(x, axis=0, comm=None, keepdims=False): x = np.asarray(x) assert (x.ndim > 0) (mean, count) = mpi_mean(x, axis=axis, comm=comm, keepdims=True) sqdiffs = np.square((x - mean)) (meansqdiff, count1) = mpi_mean(sqdiffs, axis=axis, comm=comm, keepdims=True) assert (count1 == count) ...
def test_runningmeanstd(): import subprocess subprocess.check_call(['mpirun', '-np', '3', 'python', '-c', 'from baselines.common.mpi_moments import _helper_runningmeanstd; _helper_runningmeanstd()'])
def _helper_runningmeanstd(): comm = MPI.COMM_WORLD np.random.seed(0) for (triple, axis) in [((np.random.randn(3), np.random.randn(4), np.random.randn(5)), 0), ((np.random.randn(3, 2), np.random.randn(4, 2), np.random.randn(5, 2)), 0), ((np.random.randn(2, 3), np.random.randn(2, 4), np.random.randn(2, 4))...
class RunningMeanStd(object): def __init__(self, epsilon=0.01, shape=()): self._sum = tf.get_variable(dtype=tf.float64, shape=shape, initializer=tf.constant_initializer(0.0), name='runningsum', trainable=False) self._sumsq = tf.get_variable(dtype=tf.float64, shape=shape, initializer=tf.constant_i...
@U.in_session def test_runningmeanstd(): for (x1, x2, x3) in [(np.random.randn(3), np.random.randn(4), np.random.randn(5)), (np.random.randn(3, 2), np.random.randn(4, 2), np.random.randn(5, 2))]: rms = RunningMeanStd(epsilon=0.0, shape=x1.shape[1:]) U.initialize() x = np.concatenate([x1, x...
@U.in_session def test_dist(): np.random.seed(0) (p1, p2, p3) = (np.random.randn(3, 1), np.random.randn(4, 1), np.random.randn(5, 1)) (q1, q2, q3) = (np.random.randn(6, 1), np.random.randn(7, 1), np.random.randn(8, 1)) comm = MPI.COMM_WORLD assert (comm.Get_size() == 2) if (comm.Get_rank() == ...
class AbstractEnvRunner(ABC): def __init__(self, *, env, model, nsteps): self.env = env self.model = model nenv = env.num_envs self.batch_ob_shape = (((nenv * nsteps),) + env.observation_space.shape) self.obs = np.zeros(((nenv,) + env.observation_space.shape), dtype=model....
class RunningMeanStd(object): def __init__(self, epsilon=0.0001, shape=()): self.mean = np.zeros(shape, 'float64') self.var = np.ones(shape, 'float64') self.count = epsilon def update(self, x): batch_mean = np.mean(x, axis=0) batch_var = np.var(x, axis=0) batc...
def test_runningmeanstd(): for (x1, x2, x3) in [(np.random.randn(3), np.random.randn(4), np.random.randn(5)), (np.random.randn(3, 2), np.random.randn(4, 2), np.random.randn(5, 2))]: rms = RunningMeanStd(epsilon=0.0, shape=x1.shape[1:]) x = np.concatenate([x1, x2, x3], axis=0) ms1 = [x.mean...
class RunningStat(object): def __init__(self, shape): self._n = 0 self._M = np.zeros(shape) self._S = np.zeros(shape) def push(self, x): x = np.asarray(x) assert (x.shape == self._M.shape) self._n += 1 if (self._n == 1): self._M[...] = x ...
def test_running_stat(): for shp in ((), (3,), (3, 4)): li = [] rs = RunningStat(shp) for _ in range(5): val = np.random.randn(*shp) rs.push(val) li.append(val) m = np.mean(li, axis=0) assert np.allclose(rs.mean, m) v ...
class Schedule(object): def value(self, t): 'Value of the schedule at time t' raise NotImplementedError()
class ConstantSchedule(object): def __init__(self, value): 'Value remains constant over time.\n\n Parameters\n ----------\n value: float\n Constant value of the schedule\n ' self._v = value def value(self, t): 'See Schedule.value' return...
def linear_interpolation(l, r, alpha): return (l + (alpha * (r - l)))
class PiecewiseSchedule(object): def __init__(self, endpoints, interpolation=linear_interpolation, outside_value=None): 'Piecewise schedule.\n\n endpoints: [(int, int)]\n list of pairs `(time, value)` meanining that schedule should output\n `value` when `t==time`. All the val...
class LinearSchedule(object): def __init__(self, schedule_timesteps, final_p, initial_p=1.0): 'Linear interpolation between initial_p and final_p over\n schedule_timesteps. After this many timesteps pass final_p is\n returned.\n\n Parameters\n ----------\n schedule_time...
class SegmentTree(object): def __init__(self, capacity, operation, neutral_element): "Build a Segment Tree data structure.\n\n https://en.wikipedia.org/wiki/Segment_tree\n\n Can be used as regular array, but with two\n important differences:\n\n a) setting item's value is ...
class SumSegmentTree(SegmentTree): def __init__(self, capacity): super(SumSegmentTree, self).__init__(capacity=capacity, operation=operator.add, neutral_element=0.0) def sum(self, start=0, end=None): 'Returns arr[start] + ... + arr[end]' return super(SumSegmentTree, self).reduce(star...
class MinSegmentTree(SegmentTree): def __init__(self, capacity): super(MinSegmentTree, self).__init__(capacity=capacity, operation=min, neutral_element=float('inf')) def min(self, start=0, end=None): 'Returns min(arr[start], ..., arr[end])' return super(MinSegmentTree, self).reduce(...
def test_piecewise_schedule(): ps = PiecewiseSchedule([((- 5), 100), (5, 200), (10, 50), (100, 50), (200, (- 50))], outside_value=500) assert np.isclose(ps.value((- 10)), 500) assert np.isclose(ps.value(0), 150) assert np.isclose(ps.value(5), 200) assert np.isclose(ps.value(9), 80) assert np.i...
def test_constant_schedule(): cs = ConstantSchedule(5) for i in range((- 100), 100): assert np.isclose(cs.value(i), 5)
def test_tree_set(): tree = SumSegmentTree(4) tree[2] = 1.0 tree[3] = 3.0 assert np.isclose(tree.sum(), 4.0) assert np.isclose(tree.sum(0, 2), 0.0) assert np.isclose(tree.sum(0, 3), 1.0) assert np.isclose(tree.sum(2, 3), 1.0) assert np.isclose(tree.sum(2, (- 1)), 1.0) assert np.isc...
def test_tree_set_overlap(): tree = SumSegmentTree(4) tree[2] = 1.0 tree[2] = 3.0 assert np.isclose(tree.sum(), 3.0) assert np.isclose(tree.sum(2, 3), 3.0) assert np.isclose(tree.sum(2, (- 1)), 3.0) assert np.isclose(tree.sum(2, 4), 3.0) assert np.isclose(tree.sum(1, 2), 0.0)
def test_prefixsum_idx(): tree = SumSegmentTree(4) tree[2] = 1.0 tree[3] = 3.0 assert (tree.find_prefixsum_idx(0.0) == 2) assert (tree.find_prefixsum_idx(0.5) == 2) assert (tree.find_prefixsum_idx(0.99) == 2) assert (tree.find_prefixsum_idx(1.01) == 3) assert (tree.find_prefixsum_idx(3...
def test_prefixsum_idx2(): tree = SumSegmentTree(4) tree[0] = 0.5 tree[1] = 1.0 tree[2] = 1.0 tree[3] = 3.0 assert (tree.find_prefixsum_idx(0.0) == 0) assert (tree.find_prefixsum_idx(0.55) == 1) assert (tree.find_prefixsum_idx(0.99) == 1) assert (tree.find_prefixsum_idx(1.51) == 2)...
def test_max_interval_tree(): tree = MinSegmentTree(4) tree[0] = 1.0 tree[2] = 0.5 tree[3] = 3.0 assert np.isclose(tree.min(), 0.5) assert np.isclose(tree.min(0, 2), 1.0) assert np.isclose(tree.min(0, 3), 0.5) assert np.isclose(tree.min(0, (- 1)), 0.5) assert np.isclose(tree.min(2,...
def test_function(): with tf.Graph().as_default(): x = tf.placeholder(tf.int32, (), name='x') y = tf.placeholder(tf.int32, (), name='y') z = ((3 * x) + (2 * y)) lin = function([x, y], z, givens={y: 0}) with single_threaded_session(): initialize() ass...
def test_multikwargs(): with tf.Graph().as_default(): x = tf.placeholder(tf.int32, (), name='x') with tf.variable_scope('other'): x2 = tf.placeholder(tf.int32, (), name='x') z = ((3 * x) + (2 * x2)) lin = function([x, x2], z, givens={x2: 0}) with single_threaded...
def switch(condition, then_expression, else_expression): 'Switches between two operations depending on a scalar value (int or bool).\n Note that both `then_expression` and `else_expression`\n should be symbolic tensors of the *same shape*.\n\n # Arguments\n condition: scalar tensor.\n then_...
def lrelu(x, leak=0.2): f1 = (0.5 * (1 + leak)) f2 = (0.5 * (1 - leak)) return ((f1 * x) + (f2 * abs(x)))
def huber_loss(x, delta=1.0): 'Reference: https://en.wikipedia.org/wiki/Huber_loss' return tf.where((tf.abs(x) < delta), (tf.square(x) * 0.5), (delta * (tf.abs(x) - (0.5 * delta))))
def make_session(num_cpu=None, make_default=False, graph=None): "Returns a session that will use <num_cpu> CPU's only" if (num_cpu is None): num_cpu = int(os.getenv('RCALL_NUM_CPU', multiprocessing.cpu_count())) tf_config = tf.ConfigProto(inter_op_parallelism_threads=num_cpu, intra_op_parallelism_...
def single_threaded_session(): 'Returns a session which will only use a single CPU' return make_session(num_cpu=1)
def in_session(f): @functools.wraps(f) def newfunc(*args, **kwargs): with tf.Session(): f(*args, **kwargs) return newfunc
def initialize(): 'Initialize all the uninitialized variables in the global scope.' new_variables = (set(tf.global_variables()) - ALREADY_INITIALIZED) tf.get_default_session().run(tf.variables_initializer(new_variables)) ALREADY_INITIALIZED.update(new_variables)
def normc_initializer(std=1.0, axis=0): def _initializer(shape, dtype=None, partition_info=None): out = np.random.randn(*shape).astype(np.float32) out *= (std / np.sqrt(np.square(out).sum(axis=axis, keepdims=True))) return tf.constant(out) return _initializer
def conv2d(x, num_filters, name, filter_size=(3, 3), stride=(1, 1), pad='SAME', dtype=tf.float32, collections=None, summary_tag=None): with tf.variable_scope(name): stride_shape = [1, stride[0], stride[1], 1] filter_shape = [filter_size[0], filter_size[1], int(x.get_shape()[3]), num_filters] ...
def function(inputs, outputs, updates=None, givens=None): 'Just like Theano function. Take a bunch of tensorflow placeholders and expressions\n computed based on those placeholders and produces f(inputs) -> outputs. Function f takes\n values to be fed to the input\'s placeholders and produces the values of ...
class _Function(object): def __init__(self, inputs, outputs, updates, givens): for inpt in inputs: if ((not hasattr(inpt, 'make_feed_dict')) and (not ((type(inpt) is tf.Tensor) and (len(inpt.op.inputs) == 0)))): assert False, 'inputs should all be placeholders, constants, or h...
def var_shape(x): out = x.get_shape().as_list() assert all((isinstance(a, int) for a in out)), 'shape function assumes that shape is fully known' return out
def numel(x): return intprod(var_shape(x))
def intprod(x): return int(np.prod(x))
def flatgrad(loss, var_list, clip_norm=None): grads = tf.gradients(loss, var_list) if (clip_norm is not None): grads = [tf.clip_by_norm(grad, clip_norm=clip_norm) for grad in grads] return tf.concat(axis=0, values=[tf.reshape((grad if (grad is not None) else tf.zeros_like(v)), [numel(v)]) for (v, ...
class SetFromFlat(object): def __init__(self, var_list, dtype=tf.float32): assigns = [] shapes = list(map(var_shape, var_list)) total_size = np.sum([intprod(shape) for shape in shapes]) self.theta = theta = tf.placeholder(dtype, [total_size]) start = 0 assigns = []...
class GetFlat(object): def __init__(self, var_list): self.op = tf.concat(axis=0, values=[tf.reshape(v, [numel(v)]) for v in var_list]) def __call__(self): return tf.get_default_session().run(self.op)
def get_placeholder(name, dtype, shape): if (name in _PLACEHOLDER_CACHE): (out, dtype1, shape1) = _PLACEHOLDER_CACHE[name] assert ((dtype1 == dtype) and (shape1 == shape)) return out else: out = tf.placeholder(dtype=dtype, shape=shape, name=name) _PLACEHOLDER_CACHE[name...
def get_placeholder_cached(name): return _PLACEHOLDER_CACHE[name][0]
def flattenallbut0(x): return tf.reshape(x, [(- 1), intprod(x.get_shape().as_list()[1:])])
def display_var_info(vars): from baselines import logger count_params = 0 for v in vars: name = v.name if (('/Adam' in name) or ('beta1_power' in name) or ('beta2_power' in name)): continue v_params = np.prod(v.shape.as_list()) count_params += v_params i...
class AlreadySteppingError(Exception): '\n Raised when an asynchronous step is running while\n step_async() is called again.\n ' def __init__(self): msg = 'already running an async step' Exception.__init__(self, msg)
class NotSteppingError(Exception): '\n Raised when an asynchronous step is not running but\n step_wait() is called.\n ' def __init__(self): msg = 'not running an async step' Exception.__init__(self, msg)
class VecEnv(ABC): '\n An abstract asynchronous, vectorized environment.\n ' def __init__(self, num_envs, observation_space, action_space): self.num_envs = num_envs self.observation_space = observation_space self.action_space = action_space @abstractmethod def reset(sel...
class VecEnvWrapper(VecEnv): def __init__(self, venv, observation_space=None, action_space=None): self.venv = venv VecEnv.__init__(self, num_envs=venv.num_envs, observation_space=(observation_space or venv.observation_space), action_space=(action_space or venv.action_space)) def step_async(s...
class CloudpickleWrapper(object): '\n Uses cloudpickle to serialize contents (otherwise multiprocessing tries to use pickle)\n ' def __init__(self, x): self.x = x def __getstate__(self): import cloudpickle return cloudpickle.dumps(self.x) def __setstate__(self, ob): ...
class DummyVecEnv(VecEnv): def __init__(self, env_fns): self.envs = [fn() for fn in env_fns] env = self.envs[0] VecEnv.__init__(self, len(env_fns), env.observation_space, env.action_space) (shapes, dtypes) = ({}, {}) self.keys = [] obs_space = env.observation_space...
def worker(remote, parent_remote, env_fn_wrapper): parent_remote.close() env = env_fn_wrapper.x() while True: (cmd, data) = remote.recv() if (cmd == 'step'): (ob, reward, done, info) = env.step(data) if done: ob = env.reset() remote.send(...
class SubprocVecEnv(VecEnv): def __init__(self, env_fns, spaces=None): '\n envs: list of gym environments to run in subprocesses\n ' self.waiting = False self.closed = False nenvs = len(env_fns) (self.remotes, self.work_remotes) = zip(*[Pipe() for _ in range(...
class VecNormalize(VecEnvWrapper): '\n Vectorized environment base class\n ' def __init__(self, venv, ob=True, ret=True, clipob=10.0, cliprew=10.0, gamma=0.99, epsilon=1e-08): VecEnvWrapper.__init__(self, venv) self.ob_rms = (RunningMeanStd(shape=self.observation_space.shape) if ob else...
class ActorCritic(): @store_args def __init__(self, inputs_tf, dimo, dimg, dimu, max_u, o_stats, g_stats, hidden, layers, **kwargs): 'The actor-critic network and related training code.\n\n Args:\n inputs_tf (dict of tensors): all necessary inputs for the network: the\n ...
def cached_make_env(make_env): '\n Only creates a new environment from the provided function if one has not yet already been\n created. This is useful here because we need to infer certain properties of the env, e.g.\n its observation and action spaces, without any intend of actually using it.\n ' ...