code stringlengths 17 6.64M |
|---|
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 Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
self.conv1 = nn.Sequential(nn.Conv2d(3, 8, 5, 1, 2), nn.ReLU())
self.conv2 = nn.Sequential(nn.Conv2d(8, 16, 5, 1, 2), nn.ReLU())
self.conv3 = nn.Sequential(nn.Conv2d(16, 64, 5, 1, 2), nn.ReLU... |
class Generator(nn.Module):
def __init__(self):
super(Generator, self).__init__()
self.det_conv0 = nn.Sequential(nn.Conv2d(4, 32, 3, 1, 1), nn.ReLU())
self.det_conv1 = nn.Sequential(nn.Conv2d(32, 32, 3, 1, 1), nn.ReLU(), nn.Conv2d(32, 32, 3, 1, 1), nn.ReLU())
self.det_conv2 = nn.S... |
def trainable(net, trainable):
for para in net.parameters():
para.requires_grad = trainable
|
def vgg_init():
vgg_model = torchvision.models.vgg16(pretrained=True).cuda()
trainable(vgg_model, False)
return vgg_model
|
class vgg(nn.Module):
def __init__(self, vgg_model):
super(vgg, self).__init__()
self.vgg_layers = vgg_model.features
self.layer_name_mapping = {'1': 'relu1_1', '3': 'relu1_2', '6': 'relu2_1', '8': 'relu2_2'}
def forward(self, x):
output = []
for (name, module) in sel... |
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 get_session(config=None):
'Get default session or create one with a given config'
sess = tf.get_default_session()
if (sess is None):
sess = make_session(config=config, make_default=True)
return sess
|
def make_session(config=None, 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()))
if (config is None):
config = tf.ConfigProto(allow_soft_placement... |
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)
get_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(dtype.as_numpy_dtype)
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 flattenallbut0(x):
return tf.reshape(x, [(- 1), intprod(x.get_shape().as_list()[1:])])
|
def get_placeholder(name, dtype, shape):
if (name in _PLACEHOLDER_CACHE):
(out, dtype1, shape1) = _PLACEHOLDER_CACHE[name]
if (out.graph == tf.get_default_graph()):
assert ((dtype1 == dtype) and (shape1 == shape)), 'Placeholder with name {} has already been registered and has shape {},... |
def get_placeholder_cached(name):
return _PLACEHOLDER_CACHE[name][0]
|
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... |
def get_available_gpus(session_config=None):
if (session_config is None):
session_config = get_session()._config
from tensorflow.python.client import device_lib
local_device_protos = device_lib.list_local_devices(session_config)
return [x.name for x in local_device_protos if (x.device_type == ... |
def load_state(fname, sess=None):
from baselines import logger
logger.warn('load_state method is deprecated, please use load_variables instead')
sess = (sess or get_session())
saver = tf.train.Saver()
saver.restore(tf.get_default_session(), fname)
|
def save_state(fname, sess=None):
from baselines import logger
logger.warn('save_state method is deprecated, please use save_variables instead')
sess = (sess or get_session())
dirname = os.path.dirname(fname)
if any(dirname):
os.makedirs(dirname, exist_ok=True)
saver = tf.train.Saver()... |
def save_variables(save_path, variables=None, sess=None):
import joblib
sess = (sess or get_session())
variables = (variables or tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES))
ps = sess.run(variables)
save_dict = {v.name: value for (v, value) in zip(variables, ps)}
dirname = os.path.dirname... |
def load_variables(load_path, variables=None, sess=None, scope=None):
import joblib
sess = (sess or get_session())
variables = (variables or tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES))
loaded_params = joblib.load(os.path.expanduser(load_path))
restores = []
if isinstance(loaded_params, l... |
def adjust_shape(placeholder, data):
'\n adjust shape of the data to the shape of the placeholder if possible.\n If shape is incompatible, AssertionError is thrown\n\n Parameters:\n placeholder tensorflow input placeholder\n\n data input data to be (potentially) reshaped to b... |
def _check_shape(placeholder_shape, data_shape):
' check if two shapes are compatible (i.e. differ only by dimensions of size 1, or by the batch dimension)'
return True
squeezed_placeholder_shape = _squeeze_shape(placeholder_shape)
squeezed_data_shape = _squeeze_shape(data_shape)
for (i, s_data) i... |
def _squeeze_shape(shape):
return [x for x in shape if (x != 1)]
|
def launch_tensorboard_in_background(log_dir):
"\n To log the Tensorflow graph when using rl-algs\n algorithms, you can run the following code\n in your main script:\n import threading, time\n def start_tensorboard(session):\n time.sleep(10) # Wait until graph is setup\n ... |
def worker(remote, parent_remote, env_fn_wrapper):
parent_remote.close()
env = env_fn_wrapper.x()
try:
while True:
(cmd, data) = remote.recv()
if (cmd == 'step'):
(ob, reward, done, info) = env.step(data)
if done:
ob = env... |
class SubprocVecEnv(VecEnv):
'\n VecEnv that runs multiple environments in parallel in subproceses and communicates with them via pipes.\n Recommended to use when num_envs > 1 and step() can be a bottleneck.\n '
def __init__(self, env_fns, spaces=None, context='spawn'):
'\n Arguments:... |
def _flatten_obs(obs):
assert isinstance(obs, (list, tuple))
assert (len(obs) > 0)
if isinstance(obs[0], dict):
keys = obs[0].keys()
return {k: np.stack([o[k] for o in obs]) for k in keys}
else:
return np.stack(obs)
|
class Model(object):
'\n We use this object to :\n __init__:\n - Creates the step_model\n - Creates the train_model\n\n train():\n - Make the training part (feedforward and retropropagation of gradients)\n\n save/load():\n - Save load the model\n '
def __init__(self, *, policy, ob_... |
def constfn(val):
def f(_):
return val
return f
|
def learn(*, network, env, total_timesteps, early_stopping=False, eval_env=None, seed=None, nsteps=2048, ent_coef=0.0, ent_pool_coef=0.0, ent_version=1, lr=0.0003, vf_coef=0.5, max_grad_norm=0.5, gamma=0.99, lam=0.95, log_interval=10, nminibatches=4, noptepochs=4, cliprange=0.2, save_interval=0, load_path=None, model... |
def safemean(xs):
return (np.nan if (len(xs) == 0) else np.mean(xs))
|
class RewardShapingEnv(VecEnvWrapper):
'\n Wrapper for the Baselines vectorized environment, which\n modifies the reward obtained to be a combination of intrinsic\n (dense, shaped) and extrinsic (sparse, from environment) reward'
def __init__(self, env, reward_shaping_factor=0.0):
super().__... |
class LinearAnnealer():
'Anneals a parameter from 1 to 0 over the course of training,\n over a specified horizon.'
def __init__(self, horizon):
self.horizon = horizon
def param_value(self, timestep):
if (self.horizon == 0):
return 0
curr_value = max((1 - (timestep ... |
class DummyEnv(object):
'\n Class used to save number of envs, observation space and action \n space data, when loading and saving baselines models\n '
def __init__(self, num_envs, observation_space, action_space):
self.num_envs = num_envs
self.observation_space = observation_space
... |
@register('conv_and_mlp')
def conv_network_fn(**kwargs):
'Used to register custom network type used by Baselines for Overcooked'
if ('network_kwargs' in kwargs.keys()):
params = kwargs['network_kwargs']
else:
params = kwargs
num_hidden_layers = params['NUM_HIDDEN_LAYERS']
size_hidd... |
def get_vectorized_gym_env(base_env, gym_env_name, agent_idx, featurize_fn=None, **kwargs):
'\n Create a one-player overcooked gym environment in which the other player is fixed (embedded in the environment)\n \n base_env: A OvercookedEnv instance (fixed or variable map)\n sim_threads: number of threa... |
def get_pbt_agent_from_config(save_dir=None, sim_threads=0, seed=0, agent_idx=0, best=False, agent_to_load_path=None):
if (agent_to_load_path is None):
agent_folder = (save_dir + 'seed_{}/agent{}'.format(seed, agent_idx))
if best:
agent_to_load_path = (agent_folder + '/best')
e... |
def get_agent_from_saved_model(save_dir, sim_threads):
'Get Agent corresponding to a saved model'
(state_policy, processed_obs_policy) = get_model_policy_from_saved_model(save_dir, sim_threads)
return AgentFromPolicy(state_policy, processed_obs_policy)
|
def get_agent_from_model(model, sim_threads, is_joint_action=False):
'Get Agent corresponding to a loaded model'
(state_policy, processed_obs_policy) = get_model_policy_from_model(model, sim_threads, is_joint_action=is_joint_action)
return AgentFromPolicy(state_policy, processed_obs_policy)
|
def get_random_agent_model(sim_threads):
'Get RandomAgent'
return RandomAgent(sim_threads)
|
def get_model_policy_from_saved_model(save_dir, sim_threads):
'Get a policy function from a saved model'
predictor = tf.contrib.predictor.from_saved_model(save_dir)
step_fn = (lambda obs: predictor({'obs': obs})['action_probs'])
return get_model_policy(step_fn, sim_threads)
|
def get_model_policy_from_model(model, sim_threads, is_joint_action=False):
def step_fn(obs):
action_probs = model.act_model.step(obs, return_action_probs=True)
return action_probs
return get_model_policy(step_fn, sim_threads, is_joint_action=is_joint_action)
|
def get_model_policy(step_fn, sim_threads, is_joint_action=False):
'\n Returns the policy function `p(s, index)` from a saved model at `save_dir`.\n \n step_fn: a function that takes in observations and returns the corresponding\n action probabilities of the agent\n '
def encoded_stat... |
def create_model(env, agent_name, use_pretrained_weights=False, **kwargs):
'Creates a model and saves it at a location\n \n env: a dummy environment that is used to determine observation and action spaces\n agent_name: the scope under which the weights of the agent are saved\n '
(model, _) = learn... |
def save_baselines_model(model, save_dir):
'\n Saves Model (from baselines) into `path/model` file, \n and saves the tensorflow graph in the `path` directory\n \n NOTE: Overwrites previously saved models at the location\n '
create_dir_if_not_exists(save_dir)
model.save((save_dir + '/model')... |
def load_baselines_model(save_dir, agent_name, config):
'\n NOTE: Before using load it might be necessary to clear the tensorflow graph\n if there are already other variables defined\n '
dummy_env = load_pickle((save_dir + '/dummy_env'))
(model, _) = learn(network='conv_and_mlp', env=dummy_env, t... |
def update_model(env, model, population=None, ent_version=1, metric_np=None, **kwargs):
'\n Train agent defined by a model using the specified environment.\n\n The idea is that one can update model on a different environment than the one \n that was used to create the model (vs a different agent for exam... |
def overwrite_model(model_from, model_to):
model_from_vars = tf.trainable_variables(model_from.scope)
model_to_vars = tf.trainable_variables(model_to.scope)
overwrite_variables(model_from_vars, model_to_vars)
|
def overwrite_variables(variables_to_copy, variables_to_overwrite):
sess = tf.get_default_session()
restores = []
assert (len(variables_to_copy) == len(variables_to_overwrite)), 'number of variables loaded mismatches len(variables)'
for (d, v) in zip(variables_to_copy, variables_to_overwrite):
... |
def get_model_value_fn(model, sim_threads, debug=False):
'Returns the estimated value function `V(s, index)` from a saved model at `save_dir`.'
print(model)
def value_fn(mdp_state, mdp, agent_index):
obs = mdp.lossless_state_encoding(mdp_state, debug=debug)[agent_index]
padded_obs = np.ar... |
def get_model_value_fn_policy(model, sim_threads, boltzmann_rationality=1):
'Returns a policy based on the value function approximation of the model'
v_fn = get_model_value_fn(model, sim_threads)
def v_policy(mdp_state, mdp, agent_index):
successor_vals = []
for a in Action.INDEX_TO_ACTIO... |
def get_boltzmann_rational_agent_from_model(model, sim_threads, boltzmann_rationality):
p = get_model_value_fn_policy(model, sim_threads, boltzmann_rationality=boltzmann_rationality)
trained_agent = AgentFromPolicy(p, None)
return trained_agent
|
class PBTAgent(object):
'An agent that can be saved and loaded and all and the main data it contains is the self.model\n \n Goal is to be able to pass in save_locations or PBTAgents to workers that will load such agents\n and train them together.\n '
def __init__(self, agent_name, start_params, s... |
@ex.config
def my_config():
TIMESTAMP_DIR = True
EX_NAME = 'undefined_name'
if TIMESTAMP_DIR:
SAVE_DIR = (((PBT_DATA_DIR + time.strftime('%Y_%m_%d-%H_%M_%S_')) + EX_NAME) + '/')
else:
SAVE_DIR = ((PBT_DATA_DIR + EX_NAME) + '/')
print('Saving data to ', SAVE_DIR)
RUN_TYPE = 'pbt... |
@ex.named_config
def fixed_mdp():
LOCAL_TESTING = False
layout_name = 'simple'
sim_threads = (30 if (not LOCAL_TESTING) else 2)
PPO_RUN_TOT_TIMESTEPS = (36000 if (not LOCAL_TESTING) else 1000)
TOTAL_BATCH_SIZE = (12000 if (not LOCAL_TESTING) else 1000)
STEPS_PER_UPDATE = 5
MINIBATCHES = (6... |
@ex.named_config
def fixed_mdp_rnd_init():
LOCAL_TESTING = False
fixed_mdp = True
layout_name = 'scenario2'
sim_threads = (10 if LOCAL_TESTING else 50)
PPO_RUN_TOT_TIMESTEPS = 24000
TOTAL_BATCH_SIZE = 8000
STEPS_PER_UPDATE = 4
MINIBATCHES = 4
LR = 0.0005
|
@ex.named_config
def padded_all_scenario():
LOCAL_TESTING = False
fixed_mdp = ['scenario2', 'simple', 'schelling_s', 'unident_s']
PADDED_MDP_SHAPE = (10, 5)
sim_threads = (10 if LOCAL_TESTING else 60)
PPO_RUN_TOT_TIMESTEPS = (40000 if (not LOCAL_TESTING) else 1000)
TOTAL_BATCH_SIZE = (20000 if... |
def pbt_one_run(params, seed):
create_dir_if_not_exists(params['SAVE_DIR'])
save_dict_to_file(params, (params['SAVE_DIR'] + 'config'))
mdp = OvercookedGridworld.from_layout_name(**params['mdp_params'])
overcooked_env = OvercookedEnv(mdp, **params['env_params'])
print('Sample training environments:... |
@ex.automain
def run_pbt(params):
create_dir_if_not_exists(params['SAVE_DIR'])
save_dict_to_file(params, (params['SAVE_DIR'] + 'config'))
for seed in params['SEEDS']:
set_global_seed(seed)
curr_seed_params = params.copy()
curr_seed_params['SAVE_DIR'] += 'seed_{}/'.format(seed)
... |
class PBTAgent(object):
'An agent that can be saved and loaded and all and the main data it contains is the self.model\n \n Goal is to be able to pass in save_locations or PBTAgents to workers that will load such agents\n and train them together.\n '
def __init__(self, agent_name, start_params, s... |
@ex.config
def my_config():
TIMESTAMP_DIR = True
EX_NAME = 'undefined_name'
if TIMESTAMP_DIR:
SAVE_DIR = (((PBT_DATA_DIR + time.strftime('%Y_%m_%d-%H_%M_%S_')) + EX_NAME) + '/')
else:
SAVE_DIR = ((PBT_DATA_DIR + EX_NAME) + '/')
print('Saving data to ', SAVE_DIR)
RUN_TYPE = 'pbt... |
@ex.named_config
def fixed_mdp():
LOCAL_TESTING = False
layout_name = 'simple'
sim_threads = (30 if (not LOCAL_TESTING) else 2)
PPO_RUN_TOT_TIMESTEPS = (36000 if (not LOCAL_TESTING) else 1000)
TOTAL_BATCH_SIZE = (12000 if (not LOCAL_TESTING) else 1000)
STEPS_PER_UPDATE = 5
MINIBATCHES = (6... |
@ex.named_config
def fixed_mdp_rnd_init():
LOCAL_TESTING = False
fixed_mdp = True
layout_name = 'scenario2'
sim_threads = (10 if LOCAL_TESTING else 50)
PPO_RUN_TOT_TIMESTEPS = 24000
TOTAL_BATCH_SIZE = 8000
STEPS_PER_UPDATE = 4
MINIBATCHES = 4
LR = 0.0005
|
@ex.named_config
def padded_all_scenario():
LOCAL_TESTING = False
fixed_mdp = ['scenario2', 'simple', 'schelling_s', 'unident_s']
PADDED_MDP_SHAPE = (10, 5)
sim_threads = (10 if LOCAL_TESTING else 60)
PPO_RUN_TOT_TIMESTEPS = (40000 if (not LOCAL_TESTING) else 1000)
TOTAL_BATCH_SIZE = (20000 if... |
def pbt_one_run(params, seed):
create_dir_if_not_exists(params['SAVE_DIR'])
save_dict_to_file(params, (params['SAVE_DIR'] + 'config'))
mdp = OvercookedGridworld.from_layout_name(**params['mdp_params'])
overcooked_env = OvercookedEnv(mdp, **params['env_params'])
print('Sample training environments:... |
@ex.automain
def run_pbt(params):
create_dir_if_not_exists(params['SAVE_DIR'])
save_dict_to_file(params, (params['SAVE_DIR'] + 'config'))
for seed in params['SEEDS']:
set_global_seed(seed)
curr_seed_params = params.copy()
curr_seed_params['SAVE_DIR'] += 'seed_{}/'.format(seed)
... |
class OvercookedEnv(object):
'An environment wrapper for the OvercookedGridworld Markov Decision Process.\n\n The environment keeps track of the current state of the agent, updates\n it as the agent takes actions, and provides rewards to the agent.\n '
def __init__(self, mdp, start_state_fn=None, ho... |
class Overcooked(gym.Env):
'\n Wrapper for the Env class above that is SOMEWHAT compatible with the standard gym API.\n\n NOTE: Observations returned are in a dictionary format with various information that is\n necessary to be able to handle the multi-agent nature of the environment. There are probably\... |
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)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.