code stringlengths 17 6.64M |
|---|
@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 '
... |
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 configure_her(params):
env = cached_make_env(params['make_env'])
env.reset()
def reward_fun(ag_2, g, info):
return env.compute_reward(achieved_goal=ag_2, desired_goal=g, info=info)
her_params = {'reward_fun': reward_fun}
for name in ['replay_strategy', 'replay_k']:
her_params[... |
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())
dims = {'o': obs['observation'].shape[0], 'u': env.action_space.shape[0], 'g': obs['desired_goal'].shape[0]}
for (key, value) in info.items():
value = n... |
@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, w_potential, w_linear, w_rotational, rank_method, clip_energy, **kwargs):
rank = MPI.COMM_WORLD.Get_rank()
latest_policy_path = os.path.join(logger.get_dir(),... |
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, w_potential, w_linear, w_rotational, clip_energy, override_params={}, save_policies=True):
if (num_cpu > 1):
whoami ... |
@click.command()
@click.option('--env_name', type=click.Choice(['FetchPickAndPlace-v0', 'HandManipulateBlockFull-v0', 'HandManipulateEggFull-v0', 'HandManipulatePenRotate-v0']), default='FetchPickAndPlace-v0', help='the name of the OpenAI Gym environment that you want to train on. We tested EBP on four challe... |
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_energy(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)
|
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.