code stringlengths 17 6.64M |
|---|
@layer_register(log_shape=False)
def PReLU(x, init=tf.constant_initializer(0.001), name=None):
'\n Parameterized relu as in `Delving Deep into Rectifiers: Surpassing\n Human-Level Performance on ImageNet Classification\n <http://arxiv.org/abs/1502.01852>`_.\n\n :param input: any tensor.\n :param in... |
@layer_register(use_scope=False, log_shape=False)
def LeakyReLU(x, alpha, name=None):
'\n Leaky relu as in `Rectifier Nonlinearities Improve Neural Network Acoustic\n Models\n <http://ai.stanford.edu/~amaas/papers/relu_hybrid_icml2013_final.pdf>`_.\n\n :param input: any tensor.\n :param alpha: the ... |
@layer_register(log_shape=False, use_scope=False)
def BNReLU(x, name=None):
x = BatchNorm('bn', x)
x = tf.nn.relu(x, name=name)
return x
|
@memoized
def _log_regularizer(name):
logger.info('Apply regularizer for {}'.format(name))
|
def regularize_cost(regex, func, name=None):
'\n Apply a regularizer on every trainable variable matching the regex.\n\n :param func: a function that takes a tensor and return a scalar.\n '
G = tf.get_default_graph()
params = G.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
costs = []
f... |
@layer_register(log_shape=False, use_scope=False)
def Dropout(x, keep_prob=0.5, is_training=None):
'\n :param is_training: if None, will use the current context by default.\n '
if (is_training is None):
is_training = get_current_tower_context().is_training
keep_prob = tf.constant((keep_prob ... |
@layer_register(use_scope=False, log_shape=False)
def ConcatWith(x, dim, tensor):
'\n A wrapper around `tf.concat` to support `LinearWrap`\n :param x: the input tensor\n :param dim: the dimension along which to concatenate\n :param tensor: a tensor or list of tensor to concatenate with x. x will be\n ... |
@layer_register()
def SoftMax(x, use_temperature=False, temperature_init=1.0):
'\n A SoftMax layer (no linear projection) with optional temperature\n :param x: a 2D tensor\n '
if use_temperature:
t = tf.get_variable('invtemp', [], initializer=tf.constant_initializer((1.0 / float(temperature_i... |
def global_import(name):
p = __import__(name, globals(), locals(), level=1)
lst = (p.__all__ if ('__all__' in dir(p)) else dir(p))
del globals()[name]
for k in lst:
globals()[k] = p.__dict__[k]
__all__.append(k)
|
@six.add_metaclass(ABCMeta)
class PredictorBase(object):
'\n Available attributes:\n session\n return_input\n '
def __call__(self, *args):
'\n if len(args) == 1, assume args[0] is a datapoint (a list)\n else, assume args is a datapoinnt\n '
if (len(args) != 1)... |
class AsyncPredictorBase(PredictorBase):
@abstractmethod
def put_task(self, dp, callback=None):
'\n :param dp: A data point (list of component) as inputs.\n (It should be either batched or not batched depending on the predictor implementation)\n :param callback: a thread-safe... |
class OnlinePredictor(PredictorBase):
def __init__(self, sess, input_tensors, output_tensors, return_input=False):
self.session = sess
self.return_input = return_input
self.input_tensors = input_tensors
self.output_tensors = output_tensors
def _do_call(self, dp):
asse... |
class OfflinePredictor(OnlinePredictor):
' Build a predictor from a given config, in an independent graph'
def __init__(self, config):
self.graph = tf.Graph()
with self.graph.as_default():
input_placehdrs = config.model.get_input_vars()
with TowerContext('', False):
... |
def build_multi_tower_prediction_graph(build_tower_fn, towers):
'\n :param build_tower_fn: the function to be called inside each tower, taking tower as the argument\n :param towers: a list of gpu relative id.\n '
for k in towers:
logger.info('Building graph for predictor tower {}...'.format(k... |
class MultiTowerOfflinePredictor(OnlinePredictor):
def __init__(self, config, towers):
self.graph = tf.Graph()
self.predictors = []
with self.graph.as_default():
fn = (lambda _: config.model.build_graph(config.model.get_input_vars()))
build_multi_tower_prediction_g... |
class DataParallelOfflinePredictor(OnlinePredictor):
def __init__(self, config, towers):
self.graph = tf.Graph()
with self.graph.as_default():
sess = tf.Session(config=config.session_config)
input_var_names = []
output_vars = []
for k in towers:
... |
class PredictConfig(object):
def __init__(self, **kwargs):
'\n The config used by `get_predict_func`.\n\n :param session_init: a `utils.sessinit.SessionInit` instance to\n initialize variables of a session.\n :param model: a `ModelDesc` instance\n :param input_names... |
def get_predict_func(config):
'\n Produce a offline predictor run inside a new session.\n\n :param config: a `PredictConfig` instance.\n :returns: A callable predictor that takes a list of input values, and return\n a list of output values defined in ``config.output_var_names``.\n '
return ... |
class MultiProcessPredictWorker(multiprocessing.Process):
' Base class for predict worker that runs offline in multiprocess'
def __init__(self, idx, config):
'\n :param idx: index of the worker. the 0th worker will print log.\n :param config: a `PredictConfig`\n '
super(M... |
class MultiProcessQueuePredictWorker(MultiProcessPredictWorker):
' An offline predictor worker that takes input and produces output by queue'
def __init__(self, idx, inqueue, outqueue, config):
'\n :param inqueue: input queue to get data point. elements are (task_id, dp)\n :param outque... |
class PredictorWorkerThread(threading.Thread):
def __init__(self, queue, pred_func, id, batch_size=5):
super(PredictorWorkerThread, self).__init__()
self.queue = queue
self.func = pred_func
self.daemon = True
self.batch_size = batch_size
self.id = id
def run(s... |
class MultiThreadAsyncPredictor(AsyncPredictorBase):
'\n An multithread online async predictor which run a list of PredictorBase.\n It would do an extra batching internally.\n '
def __init__(self, predictors, batch_size=5):
' :param predictors: a list of OnlinePredictor'
assert len(p... |
@six.add_metaclass(ABCMeta)
class DatasetPredictorBase(object):
def __init__(self, config, dataset):
'\n :param config: a `PredictConfig` instance.\n :param dataset: a `DataFlow` instance.\n '
assert isinstance(dataset, DataFlow)
assert isinstance(config, PredictConfi... |
class SimpleDatasetPredictor(DatasetPredictorBase):
'\n Run the predict_config on a given `DataFlow`.\n '
def __init__(self, config, dataset):
super(SimpleDatasetPredictor, self).__init__(config, dataset)
self.predictor = OfflinePredictor(config)
def get_result(self):
' A g... |
class MultiProcessDatasetPredictor(DatasetPredictorBase):
def __init__(self, config, dataset, nr_proc, use_gpu=True, ordered=True):
"\n Run prediction in multiprocesses, on either CPU or GPU. Mix mode not supported.\n\n :param nr_proc: number of processes to use\n :param use_gpu: use... |
def _global_import(name):
p = __import__(name, globals(), None, level=1)
lst = (p.__all__ if ('__all__' in dir(p)) else dir(p))
for k in lst:
globals()[k] = p.__dict__[k]
__all__.append(k)
|
@contextmanager
def argscope(layers, **param):
if (not isinstance(layers, list)):
layers = [layers]
def _check_args_exist(l):
args = inspect.getargspec(l).args
for (k, v) in six.iteritems(param):
assert (k in args), 'No argument {} in {}'.format(k, l.__name__)
for l in... |
def get_arg_scope():
'\n :returns: the current argscope.\n An argscope is a dict of dict: dict[layername] = {arg: val}\n '
if (len(_ArgScopeStack) > 0):
return _ArgScopeStack[(- 1)]
else:
return defaultdict(dict)
|
def get_default_sess_config(mem_fraction=0.99):
'\n Return a better session config to use as default.\n Tensorflow default session config consume too much resources.\n\n :param mem_fraction: fraction of memory to use. default to 0.99\n :returns: a `tf.ConfigProto` object.\n '
conf = tf.ConfigPr... |
def get_global_step_var():
' :returns: the global_step variable in the current graph. create if not existed'
try:
return tf.get_default_graph().get_tensor_by_name(GLOBAL_STEP_VAR_NAME)
except KeyError:
scope = tf.get_variable_scope()
assert (scope.name == ''), 'Creating global_step... |
def get_global_step():
' :returns: global_step value in current graph and session'
return tf.train.global_step(tf.get_default_session(), get_global_step_var())
|
def get_op_tensor_name(name):
"\n Tensor name is assumed to be ``op_name + ':0'``\n\n :param name: an op or a tensor name\n :returns: (op_name, tensor_name)\n "
if name.endswith(':0'):
return (name[:(- 2)], name)
else:
return (name, (name + ':0'))
|
def get_tensors_by_names(names):
'\n Get a list of tensors in the default graph by a list of names\n '
ret = []
G = tf.get_default_graph()
for n in names:
(opn, varn) = get_op_var_name(n)
ret.append(G.get_tensor_by_name(varn))
return ret
|
def backup_collection(keys):
ret = {}
for k in keys:
ret[k] = copy(tf.get_collection(k))
return ret
|
def restore_collection(backup):
for (k, v) in six.iteritems(backup):
del tf.get_collection_ref(k)[:]
tf.get_collection_ref(k).extend(v)
|
def clear_collection(keys):
for k in keys:
del tf.get_collection_ref(k)[:]
|
@contextmanager
def freeze_collection(keys):
backup = backup_collection(keys)
(yield)
restore_collection(backup)
|
def get_tf_version():
return int(tf.__version__.split('.')[1])
|
def apply_grad_processors(grads, gradprocs):
'\n :param grads: list of (grad, var).\n :param gradprocs: list of `GradientProcessor` instances.\n :returns: list of (grad, var) went through the processors\n '
g = []
for (grad, var) in grads:
if (grad is None):
logger.warn('No... |
@six.add_metaclass(ABCMeta)
class GradientProcessor(object):
def process(self, grads):
'\n Process the symbolic gradients.\n\n :param grads: list of (grad, var)\n :returns: symbolic gradients with the same type as input\n '
with tf.name_scope(type(self).__name__):
... |
class GlobalNormClip(GradientProcessor):
def __init__(self, global_norm):
' Clip by global norm\n Note that the global norm is the sum of norm for **all** gradients\n '
self._norm = global_norm
def _process(self, grads):
g = [k[0] for k in grads]
v = [k[1] f... |
class MapGradient(GradientProcessor):
'\n Apply a function on all gradient if the name matches regex.\n Keep the other gradients unchanged.\n '
def __init__(self, func, regex='.*'):
'\n :param func: takes a grad or (grad, var) pair and returns a grad. If return None, the\n ... |
class SummaryGradient(MapGradient):
'\n Summary history and RMS for each graident variable\n '
def __init__(self):
super(SummaryGradient, self).__init__(self._mapper)
def _mapper(self, grad, var):
name = var.op.name
if (name not in _summaried_gradient):
_summari... |
class CheckGradient(MapGradient):
'\n Check for numeric issue.\n '
def __init__(self):
super(CheckGradient, self).__init__(self._mapper)
def _mapper(self, grad, var):
grad = tf.check_numerics(grad, ('CheckGradient-' + var.op.name))
return grad
|
class ScaleGradient(MapGradient):
'\n Scale certain gradient by a multiplier\n '
def __init__(self, multipliers, log=True):
'\n :param multipliers: list of (regex, float)\n :param log: whether to do logging or not\n '
if (not isinstance(multipliers, list)):
... |
def describe_model():
' print a description of the current model parameters '
train_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
msg = ['']
total = 0
for v in train_vars:
shape = v.get_shape()
ele = shape.num_elements()
total += ele
msg.append('{}: sha... |
def get_shape_str(tensors):
'\n :param tensors: a tensor or a list of tensors\n :returns: a string to describe the shape\n '
if isinstance(tensors, (list, tuple)):
for v in tensors:
assert isinstance(v, (tf.Tensor, tf.Variable)), 'Not a tensor: {}'.format(type(v))
shape_st... |
@six.add_metaclass(ABCMeta)
class SessionInit(object):
' Base class for utilities to initialize a session'
def init(self, sess):
' Initialize a session\n\n :param sess: a `tf.Session`\n '
self._init(sess)
@abstractmethod
def _init(self, sess):
pass
|
class JustCurrentSession(SessionInit):
' Just use the current default session. This is a no-op placeholder'
def _init(self, sess):
pass
|
class NewSession(SessionInit):
'\n Create a new session. All variables will be initialized by their\n initializer.\n '
def _init(self, sess):
sess.run(tf.initialize_all_variables())
|
class SaverRestore(SessionInit):
'\n Restore an old model saved by `ModelSaver`.\n '
def __init__(self, model_path, prefix=None):
'\n :param model_path: a model name (model-xxxx) or a ``checkpoint`` file.\n :param prefix: add a `prefix/` for every variable in this checkpoint\n ... |
class ParamRestore(SessionInit):
'\n Restore variables from a dictionary.\n '
def __init__(self, param_dict):
'\n :param param_dict: a dict of {name: value}\n '
self.prms = {get_op_var_name(n)[1]: v for (n, v) in six.iteritems(param_dict)}
def _init(self, sess):
... |
class ChainInit(SessionInit):
' Init a session by a list of SessionInit instance.'
def __init__(self, sess_inits, new_session=True):
'\n :params sess_inits: list of `SessionInit` instances.\n :params new_session: add a `NewSession()` and the beginning, if not there\n '
if... |
def get_model_loader(filename):
'\n Get a corresponding model loader by looking at the file name\n :return: either a ParamRestore or SaverRestore\n '
if filename.endswith('.npy'):
assert os.path.isfile(filename), filename
return ParamRestore(np.load(filename, encoding='latin1').item()... |
def create_summary(name, v):
'\n Return a tf.Summary object with name and simple scalar value v\n '
assert isinstance(name, six.string_types), type(name)
v = float(v)
s = tf.Summary()
s.value.add(tag=name, simple_value=v)
return s
|
def add_activation_summary(x, name=None):
'\n Add summary to graph for an activation tensor x.\n If name is None, use x.name.\n '
ctx = get_current_tower_context()
if ((ctx is not None) and (not ctx.is_main_training_tower)):
return
ndim = x.get_shape().ndims
assert (ndim >= 2), 'S... |
def add_param_summary(summary_lists):
"\n Add summary for all trainable variables matching the regex\n\n :param summary_lists: list of (regex, [list of summary type to perform]).\n Type can be 'mean', 'scalar', 'histogram', 'sparsity', 'rms'\n "
ctx = get_current_tower_context()
if ((ctx i... |
def add_moving_summary(v, *args):
'\n :param v: tensor or list of tensor to summary\n :param args: tensors to summary\n '
ctx = get_current_tower_context()
if ((ctx is not None) and (not ctx.is_main_training_tower)):
return
if (not isinstance(v, list)):
v = [v]
v.extend(ar... |
@memoized
def summary_moving_average(tensors=None):
'\n Create a MovingAverage op and add summary for tensors\n :param tensors: list of tf.Tensor to summary. default to the collection MOVING_SUMMARY_VARS_KEY\n :returns: a op to maintain these average.\n '
if (tensors is None):
tensors = tf... |
def prediction_incorrect(logits, label, topk=1, name='incorrect_vector'):
'\n :param logits: NxC\n :param label: N\n :returns: a float32 vector of length N with 0/1 values. 1 means incorrect prediction\n '
return tf.cast(tf.logical_not(tf.nn.in_top_k(logits, label, topk)), tf.float32, name=name)
|
def flatten(x):
'\n Flatten the tensor.\n '
return tf.reshape(x, [(- 1)])
|
def batch_flatten(x):
'\n Flatten the tensor except the first dimension.\n '
shape = x.get_shape().as_list()[1:]
if (None not in shape):
return tf.reshape(x, [(- 1), int(np.prod(shape))])
return tf.reshape(x, tf.pack([tf.shape(x)[0], (- 1)]))
|
def class_balanced_cross_entropy(pred, label, name='cross_entropy_loss'):
'\n The class-balanced cross entropy loss,\n as in `Holistically-Nested Edge Detection\n <http://arxiv.org/abs/1504.06375>`_.\n\n :param pred: size: b x ANYTHING. the predictions in [0,1].\n :param label: size: b x ANYTHING. ... |
def class_balanced_sigmoid_cross_entropy(logits, label, name='cross_entropy_loss'):
'\n The class-balanced cross entropy loss,\n as in `Holistically-Nested Edge Detection\n <http://arxiv.org/abs/1504.06375>`_.\n This is more numerically stable than class_balanced_cross_entropy\n\n :param logits: si... |
def print_stat(x, message=None):
' a simple print op.\n Use it like: x = print_stat(x)\n '
if (message is None):
message = x.op.name
return tf.Print(x, [tf.shape(x), tf.reduce_mean(x), x], summarize=20, message=message, name=('print_' + x.op.name))
|
def rms(x, name=None):
if (name is None):
name = (x.op.name + '/rms')
with tf.name_scope(None):
return tf.sqrt(tf.reduce_mean(tf.square(x)), name=name)
return tf.sqrt(tf.reduce_mean(tf.square(x)), name=name)
|
def huber_loss(x, delta=1, name='huber_loss'):
sqrcost = tf.square(x)
abscost = tf.abs(x)
return tf.reduce_sum(tf.select((abscost < delta), (sqrcost * 0.5), ((abscost * delta) - (0.5 * (delta ** 2)))), name=name)
|
def get_scalar_var(name, init_value, summary=False, trainable=False):
'\n get a scalar variable with certain initial value\n :param summary: summary this variable\n '
ret = tf.get_variable(name, shape=[], initializer=tf.constant_initializer(init_value), trainable=trainable)
if summary:
tf... |
class TowerContext(object):
def __init__(self, tower_name, is_training=None):
" tower_name: 'tower0', 'towerp0', or '' "
self._name = tower_name
if (is_training is None):
is_training = (not self._name.startswith(PREDICT_TOWER))
self._is_training = is_training
@pro... |
def get_current_tower_context():
global _CurrentTowerContext
return _CurrentTowerContext
|
def get_savename_from_varname(varname, varname_prefix=None, savename_prefix=None):
'\n :param varname: a variable name in the graph\n :param varname_prefix: an optional prefix that may need to be removed in varname\n :param savename_prefix: an optional prefix to append to all savename\n :returns: the ... |
class SessionUpdate(object):
' Update the variables in a session '
def __init__(self, sess, vars_to_update):
'\n :param vars_to_update: a collection of variables to update\n '
self.sess = sess
self.assign_ops = defaultdict(list)
for v in vars_to_update:
... |
def dump_session_params(path):
' Dump value of all trainable + to_save variables to a dict and save to `path` as\n npy format, loadable by ParamRestore\n '
var = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
var.extend(tf.get_collection(tf.GraphKeys.MODEL_VARIABLES))
assert (len(set(var)) ... |
def dump_chkpt_vars(model_path):
' Dump all variables from a checkpoint to a dict'
if (os.path.basename(model_path) == model_path):
model_path = os.path.join('.', model_path)
reader = tf.train.NewCheckpointReader(model_path)
var_names = reader.get_variable_to_shape_map().keys()
result = {}... |
def is_training_name(name):
'\n This is only used to improve logging.\n :returns: guess whether this tensor is something only used in training.\n '
name = get_op_tensor_name(name)[0]
if (name.endswith('/Adam') or name.endswith('/Adam_1')):
return True
if name.endswith('/Momentum'):
... |
def global_import(name):
p = __import__(name, globals(), locals(), level=1)
lst = (p.__all__ if ('__all__' in dir(p)) else [])
del globals()[name]
for k in lst:
globals()[k] = p.__dict__[k]
__all__.append(k)
|
class StopTraining(BaseException):
pass
|
@six.add_metaclass(ABCMeta)
class Trainer(object):
' Base class for a trainer.'
'a `StatHolder` instance'
stat_holder = None
'`tf.SummaryWriter`'
summary_writer = None
'a tf.Tensor which returns summary string'
summary_op = None
' TrainConfig '
config = None
' a ModelDesc'
... |
class TrainConfig(object):
'\n Config for training a model with a single loss\n '
def __init__(self, **kwargs):
'\n :param dataset: the dataset to train. a `DataFlow` instance.\n :param data: an `InputData` instance\n\n :param optimizer: a `tf.train.Optimizer` instance defi... |
class FeedfreeTrainer(Trainer):
' A trainer which runs iteration without feed_dict (therefore faster) '
def _trigger_epoch(self):
if (self.summary_op is not None):
summary_str = self.summary_op.eval()
self._process_summary(summary_str)
def _get_input_tensors(self):
... |
class SingleCostFeedfreeTrainer(FeedfreeTrainer):
def _get_cost_and_grad(self):
' get the cost and gradient on a new tower'
actual_inputs = self._get_input_tensors()
self.model.build_graph(actual_inputs)
cost_var = self.model.get_cost()
grads = self.config.optimizer.comput... |
class SimpleFeedfreeTrainer(MultiPredictorTowerTrainer, SingleCostFeedfreeTrainer):
def __init__(self, config):
'\n A trainer with single cost, single training tower and feed-free input\n config.data must exists\n '
self._input_method = config.data
assert isinstance(s... |
class QueueInputTrainer(SimpleFeedfreeTrainer):
def __init__(self, config, input_queue=None, predict_tower=None):
'\n Single tower Trainer, takes input from a queue\n\n :param config: a `TrainConfig` instance. config.dataset must exist\n :param input_queue: a `tf.QueueBase` instance\... |
@six.add_metaclass(ABCMeta)
class InputData(object):
pass
|
class FeedInput(InputData):
def __init__(self, ds):
assert isinstance(ds, DataFlow), ds
self.ds = ds
def size(self):
return self.ds.size()
def _setup(self, trainer):
self.input_vars = trainer.model.get_input_vars()
rds = RepeatedData(self.ds, (- 1))
rds.r... |
class FeedfreeInput(InputData):
def get_input_tensors(self):
return self._get_input_tensors()
@abstractmethod
def _get_input_tensors(self):
'\n always create and return a list of new input tensors\n '
|
class EnqueueThread(threading.Thread):
def __init__(self, trainer, queue, ds, input_placehdrs):
super(EnqueueThread, self).__init__()
self.name = 'EnqueueThread'
self.daemon = True
self.dataflow = ds
self.queue = queue
self.sess = trainer.sess
self.coord = ... |
class QueueInput(FeedfreeInput):
def __init__(self, ds, queue=None):
'\n :param ds: a `DataFlow` instance\n :param queue: a `tf.QueueBase` instance to be used to buffer datapoints.\n Defaults to a FIFO queue of size 50.\n '
assert isinstance(ds, DataFlow), ds
... |
class DummyConstantInput(QueueInput):
' only for debugging performance issues '
def __init__(self, ds, shapes):
super(DummyConstantInput, self).__init__(ds)
self.shapes = shapes
logger.warn('Using dummy input for debug!')
def _get_input_tensors(self):
placehdrs = self.inp... |
class TensorInput(FeedfreeInput):
def __init__(self, get_tensor_fn, size=None):
self.get_tensor_fn = get_tensor_fn
self._size = size
def size(self):
if (self._size is None):
raise ValueError('size of TensorInput is undefined!')
return self._size
def _setup(se... |
class MultiGPUTrainer(Trainer):
' Base class for multi-gpu training'
@staticmethod
def _multi_tower_grads(towers, get_tower_grad_func):
' ret[i] is a lists of (grad,var) tuple for tower i'
logger.info('Training a model of {} tower'.format(len(towers)))
grad_list = []
globa... |
class SyncMultiGPUTrainer(MultiGPUTrainer, SingleCostFeedfreeTrainer, MultiPredictorTowerTrainer):
def __init__(self, config, input_queue=None, predict_tower=None):
if hasattr(config, 'dataset'):
self._input_method = QueueInput(config.dataset, input_queue)
else:
self._inpu... |
class AsyncMultiGPUTrainer(MultiGPUTrainer, SingleCostFeedfreeTrainer, MultiPredictorTowerTrainer):
def __init__(self, config, input_queue=None, average_gradient=True, predict_tower=None):
if hasattr(config, 'dataset'):
self._input_method = QueueInput(config.dataset, input_queue)
else... |
class PredictorFactory(object):
' Make predictors for a trainer'
def __init__(self, sess, model, towers):
'\n :param towers: list of gpu relative id\n '
self.sess = sess
self.model = model
self.towers = towers
self.tower_built = False
def get_predict... |
class SimpleTrainer(Trainer):
' A naive demo trainer '
def __init__(self, config):
super(SimpleTrainer, self).__init__(config)
self._predictor_factory = PredictorFactory(self.sess, self.model, [0])
if (not hasattr(config, 'dataset')):
self._input_method = config.data
... |
class MultiPredictorTowerTrainer(Trainer):
' A trainer with possibly multiple prediction tower '
def _setup_predictor_factory(self, predict_tower):
predict_tower = (predict_tower or [0])
self._predictor_factory = PredictorFactory(self.sess, self.model, predict_tower)
def get_predict_func... |
def _global_import(name):
p = __import__(name, globals(), None, level=1)
lst = (p.__all__ if ('__all__' in dir(p)) else dir(p))
for k in lst:
globals()[k] = p.__dict__[k]
__all__.append(k)
|
def map_arg(**maps):
'\n Apply a mapping on certains argument before calling original function.\n maps: {key: map_func}\n '
def deco(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
argmap = inspect.getcallargs(func, *args, **kwargs)
for (k, map_fu... |
class memoized(object):
"Decorator. Caches a function's return value each time it is called.\n If called later with the same arguments, the cached value is returned\n (not reevaluated).\n "
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args, **kw... |
def memoized_ignoreargs(func):
h = hash(func)
def wrapper(*args, **kwargs):
if (func not in _MEMOIZED_NOARGS):
res = func(*args, **kwargs)
_MEMOIZED_NOARGS[func] = res
return res
return _MEMOIZED_NOARGS[func]
return wrapper
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.