id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
27,300 | tensorpack/tensorpack | tensorpack/tfutils/varreplace.py | freeze_variables | def freeze_variables(stop_gradient=True, skip_collection=False):
"""
Return a context to freeze variables,
by wrapping ``tf.get_variable`` with a custom getter.
It works by either applying ``tf.stop_gradient`` on the variables,
or by keeping them out of the ``TRAINABLE_VARIABLES`` collection, or
both.
Example:
.. code-block:: python
with varreplace.freeze_variable(stop_gradient=False, skip_collection=True):
x = FullyConnected('fc', x, 1000) # fc/* will not be trained
Args:
stop_gradient (bool): if True, variables returned from `get_variable`
will be wrapped with `tf.stop_gradient` and therefore has no
gradient when used later.
Note that the created variables may still have gradient when accessed
by other approaches (e.g. by name, or by collection).
Also note that this makes `tf.get_variable` returns a Tensor instead of a Variable,
which may break existing code.
Therefore, it's recommended to use the `skip_collection` option instead.
skip_collection (bool): if True, do not add the variable to
``TRAINABLE_VARIABLES`` collection, but to ``MODEL_VARIABLES``
collection. As a result they will not be trained by default.
"""
def custom_getter(getter, *args, **kwargs):
trainable = kwargs.get('trainable', True)
name = args[0] if len(args) else kwargs.get('name')
if skip_collection:
kwargs['trainable'] = False
v = getter(*args, **kwargs)
if skip_collection:
tf.add_to_collection(tf.GraphKeys.MODEL_VARIABLES, v)
if trainable and stop_gradient:
v = tf.stop_gradient(v, name='freezed_' + name)
return v
return custom_getter_scope(custom_getter) | python | def freeze_variables(stop_gradient=True, skip_collection=False):
"""
Return a context to freeze variables,
by wrapping ``tf.get_variable`` with a custom getter.
It works by either applying ``tf.stop_gradient`` on the variables,
or by keeping them out of the ``TRAINABLE_VARIABLES`` collection, or
both.
Example:
.. code-block:: python
with varreplace.freeze_variable(stop_gradient=False, skip_collection=True):
x = FullyConnected('fc', x, 1000) # fc/* will not be trained
Args:
stop_gradient (bool): if True, variables returned from `get_variable`
will be wrapped with `tf.stop_gradient` and therefore has no
gradient when used later.
Note that the created variables may still have gradient when accessed
by other approaches (e.g. by name, or by collection).
Also note that this makes `tf.get_variable` returns a Tensor instead of a Variable,
which may break existing code.
Therefore, it's recommended to use the `skip_collection` option instead.
skip_collection (bool): if True, do not add the variable to
``TRAINABLE_VARIABLES`` collection, but to ``MODEL_VARIABLES``
collection. As a result they will not be trained by default.
"""
def custom_getter(getter, *args, **kwargs):
trainable = kwargs.get('trainable', True)
name = args[0] if len(args) else kwargs.get('name')
if skip_collection:
kwargs['trainable'] = False
v = getter(*args, **kwargs)
if skip_collection:
tf.add_to_collection(tf.GraphKeys.MODEL_VARIABLES, v)
if trainable and stop_gradient:
v = tf.stop_gradient(v, name='freezed_' + name)
return v
return custom_getter_scope(custom_getter) | [
"def",
"freeze_variables",
"(",
"stop_gradient",
"=",
"True",
",",
"skip_collection",
"=",
"False",
")",
":",
"def",
"custom_getter",
"(",
"getter",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"trainable",
"=",
"kwargs",
".",
"get",
"(",
"'trainable'",
",",
"True",
")",
"name",
"=",
"args",
"[",
"0",
"]",
"if",
"len",
"(",
"args",
")",
"else",
"kwargs",
".",
"get",
"(",
"'name'",
")",
"if",
"skip_collection",
":",
"kwargs",
"[",
"'trainable'",
"]",
"=",
"False",
"v",
"=",
"getter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"skip_collection",
":",
"tf",
".",
"add_to_collection",
"(",
"tf",
".",
"GraphKeys",
".",
"MODEL_VARIABLES",
",",
"v",
")",
"if",
"trainable",
"and",
"stop_gradient",
":",
"v",
"=",
"tf",
".",
"stop_gradient",
"(",
"v",
",",
"name",
"=",
"'freezed_'",
"+",
"name",
")",
"return",
"v",
"return",
"custom_getter_scope",
"(",
"custom_getter",
")"
] | Return a context to freeze variables,
by wrapping ``tf.get_variable`` with a custom getter.
It works by either applying ``tf.stop_gradient`` on the variables,
or by keeping them out of the ``TRAINABLE_VARIABLES`` collection, or
both.
Example:
.. code-block:: python
with varreplace.freeze_variable(stop_gradient=False, skip_collection=True):
x = FullyConnected('fc', x, 1000) # fc/* will not be trained
Args:
stop_gradient (bool): if True, variables returned from `get_variable`
will be wrapped with `tf.stop_gradient` and therefore has no
gradient when used later.
Note that the created variables may still have gradient when accessed
by other approaches (e.g. by name, or by collection).
Also note that this makes `tf.get_variable` returns a Tensor instead of a Variable,
which may break existing code.
Therefore, it's recommended to use the `skip_collection` option instead.
skip_collection (bool): if True, do not add the variable to
``TRAINABLE_VARIABLES`` collection, but to ``MODEL_VARIABLES``
collection. As a result they will not be trained by default. | [
"Return",
"a",
"context",
"to",
"freeze",
"variables",
"by",
"wrapping",
"tf",
".",
"get_variable",
"with",
"a",
"custom",
"getter",
".",
"It",
"works",
"by",
"either",
"applying",
"tf",
".",
"stop_gradient",
"on",
"the",
"variables",
"or",
"by",
"keeping",
"them",
"out",
"of",
"the",
"TRAINABLE_VARIABLES",
"collection",
"or",
"both",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varreplace.py#L59-L97 |
27,301 | tensorpack/tensorpack | examples/FasterRCNN/config.py | AttrDict.to_dict | def to_dict(self):
"""Convert to a nested dict. """
return {k: v.to_dict() if isinstance(v, AttrDict) else v
for k, v in self.__dict__.items() if not k.startswith('_')} | python | def to_dict(self):
"""Convert to a nested dict. """
return {k: v.to_dict() if isinstance(v, AttrDict) else v
for k, v in self.__dict__.items() if not k.startswith('_')} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"v",
".",
"to_dict",
"(",
")",
"if",
"isinstance",
"(",
"v",
",",
"AttrDict",
")",
"else",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
"if",
"not",
"k",
".",
"startswith",
"(",
"'_'",
")",
"}"
] | Convert to a nested dict. | [
"Convert",
"to",
"a",
"nested",
"dict",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/config.py#L41-L44 |
27,302 | tensorpack/tensorpack | examples/FasterRCNN/config.py | AttrDict.update_args | def update_args(self, args):
"""Update from command line args. """
for cfg in args:
keys, v = cfg.split('=', maxsplit=1)
keylist = keys.split('.')
dic = self
for i, k in enumerate(keylist[:-1]):
assert k in dir(dic), "Unknown config key: {}".format(keys)
dic = getattr(dic, k)
key = keylist[-1]
oldv = getattr(dic, key)
if not isinstance(oldv, str):
v = eval(v)
setattr(dic, key, v) | python | def update_args(self, args):
"""Update from command line args. """
for cfg in args:
keys, v = cfg.split('=', maxsplit=1)
keylist = keys.split('.')
dic = self
for i, k in enumerate(keylist[:-1]):
assert k in dir(dic), "Unknown config key: {}".format(keys)
dic = getattr(dic, k)
key = keylist[-1]
oldv = getattr(dic, key)
if not isinstance(oldv, str):
v = eval(v)
setattr(dic, key, v) | [
"def",
"update_args",
"(",
"self",
",",
"args",
")",
":",
"for",
"cfg",
"in",
"args",
":",
"keys",
",",
"v",
"=",
"cfg",
".",
"split",
"(",
"'='",
",",
"maxsplit",
"=",
"1",
")",
"keylist",
"=",
"keys",
".",
"split",
"(",
"'.'",
")",
"dic",
"=",
"self",
"for",
"i",
",",
"k",
"in",
"enumerate",
"(",
"keylist",
"[",
":",
"-",
"1",
"]",
")",
":",
"assert",
"k",
"in",
"dir",
"(",
"dic",
")",
",",
"\"Unknown config key: {}\"",
".",
"format",
"(",
"keys",
")",
"dic",
"=",
"getattr",
"(",
"dic",
",",
"k",
")",
"key",
"=",
"keylist",
"[",
"-",
"1",
"]",
"oldv",
"=",
"getattr",
"(",
"dic",
",",
"key",
")",
"if",
"not",
"isinstance",
"(",
"oldv",
",",
"str",
")",
":",
"v",
"=",
"eval",
"(",
"v",
")",
"setattr",
"(",
"dic",
",",
"key",
",",
"v",
")"
] | Update from command line args. | [
"Update",
"from",
"command",
"line",
"args",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/config.py#L46-L61 |
27,303 | tensorpack/tensorpack | tensorpack/tfutils/sessinit.py | get_model_loader | def get_model_loader(filename):
"""
Get a corresponding model loader by looking at the file name.
Returns:
SessInit: either a :class:`DictRestore` (if name ends with 'npy/npz') or
:class:`SaverRestore` (otherwise).
"""
assert isinstance(filename, six.string_types), filename
filename = os.path.expanduser(filename)
if filename.endswith('.npy'):
assert tf.gfile.Exists(filename), filename
return DictRestore(np.load(filename, encoding='latin1').item())
elif filename.endswith('.npz'):
assert tf.gfile.Exists(filename), filename
obj = np.load(filename)
return DictRestore(dict(obj))
else:
return SaverRestore(filename) | python | def get_model_loader(filename):
"""
Get a corresponding model loader by looking at the file name.
Returns:
SessInit: either a :class:`DictRestore` (if name ends with 'npy/npz') or
:class:`SaverRestore` (otherwise).
"""
assert isinstance(filename, six.string_types), filename
filename = os.path.expanduser(filename)
if filename.endswith('.npy'):
assert tf.gfile.Exists(filename), filename
return DictRestore(np.load(filename, encoding='latin1').item())
elif filename.endswith('.npz'):
assert tf.gfile.Exists(filename), filename
obj = np.load(filename)
return DictRestore(dict(obj))
else:
return SaverRestore(filename) | [
"def",
"get_model_loader",
"(",
"filename",
")",
":",
"assert",
"isinstance",
"(",
"filename",
",",
"six",
".",
"string_types",
")",
",",
"filename",
"filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
"if",
"filename",
".",
"endswith",
"(",
"'.npy'",
")",
":",
"assert",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"filename",
")",
",",
"filename",
"return",
"DictRestore",
"(",
"np",
".",
"load",
"(",
"filename",
",",
"encoding",
"=",
"'latin1'",
")",
".",
"item",
"(",
")",
")",
"elif",
"filename",
".",
"endswith",
"(",
"'.npz'",
")",
":",
"assert",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"filename",
")",
",",
"filename",
"obj",
"=",
"np",
".",
"load",
"(",
"filename",
")",
"return",
"DictRestore",
"(",
"dict",
"(",
"obj",
")",
")",
"else",
":",
"return",
"SaverRestore",
"(",
"filename",
")"
] | Get a corresponding model loader by looking at the file name.
Returns:
SessInit: either a :class:`DictRestore` (if name ends with 'npy/npz') or
:class:`SaverRestore` (otherwise). | [
"Get",
"a",
"corresponding",
"model",
"loader",
"by",
"looking",
"at",
"the",
"file",
"name",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/sessinit.py#L245-L263 |
27,304 | tensorpack/tensorpack | tensorpack/tfutils/sessinit.py | SaverRestore._read_checkpoint_vars | def _read_checkpoint_vars(model_path):
""" return a set of strings """
reader = tf.train.NewCheckpointReader(model_path)
reader = CheckpointReaderAdapter(reader) # use an adapter to standardize the name
ckpt_vars = reader.get_variable_to_shape_map().keys()
return reader, set(ckpt_vars) | python | def _read_checkpoint_vars(model_path):
""" return a set of strings """
reader = tf.train.NewCheckpointReader(model_path)
reader = CheckpointReaderAdapter(reader) # use an adapter to standardize the name
ckpt_vars = reader.get_variable_to_shape_map().keys()
return reader, set(ckpt_vars) | [
"def",
"_read_checkpoint_vars",
"(",
"model_path",
")",
":",
"reader",
"=",
"tf",
".",
"train",
".",
"NewCheckpointReader",
"(",
"model_path",
")",
"reader",
"=",
"CheckpointReaderAdapter",
"(",
"reader",
")",
"# use an adapter to standardize the name",
"ckpt_vars",
"=",
"reader",
".",
"get_variable_to_shape_map",
"(",
")",
".",
"keys",
"(",
")",
"return",
"reader",
",",
"set",
"(",
"ckpt_vars",
")"
] | return a set of strings | [
"return",
"a",
"set",
"of",
"strings"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/sessinit.py#L118-L123 |
27,305 | tensorpack/tensorpack | tensorpack/tfutils/argscope.py | enable_argscope_for_function | def enable_argscope_for_function(func, log_shape=True):
"""Decorator for function to support argscope
Example:
.. code-block:: python
from mylib import myfunc
myfunc = enable_argscope_for_function(myfunc)
Args:
func: A function mapping one or multiple tensors to one or multiple
tensors.
log_shape (bool): Specify whether the first input resp. output tensor
shape should be printed once.
Remarks:
If the function ``func`` returns multiple input or output tensors,
only the first input/output tensor shape is displayed during logging.
Returns:
The decorated function.
"""
assert callable(func), "func should be a callable"
@wraps(func)
def wrapped_func(*args, **kwargs):
actual_args = copy.copy(get_arg_scope()[func.__name__])
actual_args.update(kwargs)
out_tensor = func(*args, **actual_args)
in_tensor = args[0]
ctx = get_current_tower_context()
name = func.__name__ if 'name' not in kwargs else kwargs['name']
if log_shape:
if ('tower' not in ctx.ns_name.lower()) or ctx.is_main_training_tower:
# we assume the first parameter is the most interesting
if isinstance(out_tensor, tuple):
out_tensor_descr = out_tensor[0]
else:
out_tensor_descr = out_tensor
logger.info('%20s: %20s -> %20s' %
(name, in_tensor.shape.as_list(),
out_tensor_descr.shape.as_list()))
return out_tensor
# argscope requires this property
wrapped_func.symbolic_function = None
return wrapped_func | python | def enable_argscope_for_function(func, log_shape=True):
"""Decorator for function to support argscope
Example:
.. code-block:: python
from mylib import myfunc
myfunc = enable_argscope_for_function(myfunc)
Args:
func: A function mapping one or multiple tensors to one or multiple
tensors.
log_shape (bool): Specify whether the first input resp. output tensor
shape should be printed once.
Remarks:
If the function ``func`` returns multiple input or output tensors,
only the first input/output tensor shape is displayed during logging.
Returns:
The decorated function.
"""
assert callable(func), "func should be a callable"
@wraps(func)
def wrapped_func(*args, **kwargs):
actual_args = copy.copy(get_arg_scope()[func.__name__])
actual_args.update(kwargs)
out_tensor = func(*args, **actual_args)
in_tensor = args[0]
ctx = get_current_tower_context()
name = func.__name__ if 'name' not in kwargs else kwargs['name']
if log_shape:
if ('tower' not in ctx.ns_name.lower()) or ctx.is_main_training_tower:
# we assume the first parameter is the most interesting
if isinstance(out_tensor, tuple):
out_tensor_descr = out_tensor[0]
else:
out_tensor_descr = out_tensor
logger.info('%20s: %20s -> %20s' %
(name, in_tensor.shape.as_list(),
out_tensor_descr.shape.as_list()))
return out_tensor
# argscope requires this property
wrapped_func.symbolic_function = None
return wrapped_func | [
"def",
"enable_argscope_for_function",
"(",
"func",
",",
"log_shape",
"=",
"True",
")",
":",
"assert",
"callable",
"(",
"func",
")",
",",
"\"func should be a callable\"",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"actual_args",
"=",
"copy",
".",
"copy",
"(",
"get_arg_scope",
"(",
")",
"[",
"func",
".",
"__name__",
"]",
")",
"actual_args",
".",
"update",
"(",
"kwargs",
")",
"out_tensor",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"actual_args",
")",
"in_tensor",
"=",
"args",
"[",
"0",
"]",
"ctx",
"=",
"get_current_tower_context",
"(",
")",
"name",
"=",
"func",
".",
"__name__",
"if",
"'name'",
"not",
"in",
"kwargs",
"else",
"kwargs",
"[",
"'name'",
"]",
"if",
"log_shape",
":",
"if",
"(",
"'tower'",
"not",
"in",
"ctx",
".",
"ns_name",
".",
"lower",
"(",
")",
")",
"or",
"ctx",
".",
"is_main_training_tower",
":",
"# we assume the first parameter is the most interesting",
"if",
"isinstance",
"(",
"out_tensor",
",",
"tuple",
")",
":",
"out_tensor_descr",
"=",
"out_tensor",
"[",
"0",
"]",
"else",
":",
"out_tensor_descr",
"=",
"out_tensor",
"logger",
".",
"info",
"(",
"'%20s: %20s -> %20s'",
"%",
"(",
"name",
",",
"in_tensor",
".",
"shape",
".",
"as_list",
"(",
")",
",",
"out_tensor_descr",
".",
"shape",
".",
"as_list",
"(",
")",
")",
")",
"return",
"out_tensor",
"# argscope requires this property",
"wrapped_func",
".",
"symbolic_function",
"=",
"None",
"return",
"wrapped_func"
] | Decorator for function to support argscope
Example:
.. code-block:: python
from mylib import myfunc
myfunc = enable_argscope_for_function(myfunc)
Args:
func: A function mapping one or multiple tensors to one or multiple
tensors.
log_shape (bool): Specify whether the first input resp. output tensor
shape should be printed once.
Remarks:
If the function ``func`` returns multiple input or output tensors,
only the first input/output tensor shape is displayed during logging.
Returns:
The decorated function. | [
"Decorator",
"for",
"function",
"to",
"support",
"argscope"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/argscope.py#L73-L123 |
27,306 | tensorpack/tensorpack | tensorpack/tfutils/argscope.py | enable_argscope_for_module | def enable_argscope_for_module(module, log_shape=True):
"""
Overwrite all functions of a given module to support argscope.
Note that this function monkey-patches the module and therefore could
have unexpected consequences.
It has been only tested to work well with ``tf.layers`` module.
Example:
.. code-block:: python
import tensorflow as tf
enable_argscope_for_module(tf.layers)
Args:
log_shape (bool): print input/output shapes of each function.
"""
if is_tfv2() and module == tf.layers:
module = tf.compat.v1.layers
for name, obj in getmembers(module):
if isfunction(obj):
setattr(module, name, enable_argscope_for_function(obj,
log_shape=log_shape)) | python | def enable_argscope_for_module(module, log_shape=True):
"""
Overwrite all functions of a given module to support argscope.
Note that this function monkey-patches the module and therefore could
have unexpected consequences.
It has been only tested to work well with ``tf.layers`` module.
Example:
.. code-block:: python
import tensorflow as tf
enable_argscope_for_module(tf.layers)
Args:
log_shape (bool): print input/output shapes of each function.
"""
if is_tfv2() and module == tf.layers:
module = tf.compat.v1.layers
for name, obj in getmembers(module):
if isfunction(obj):
setattr(module, name, enable_argscope_for_function(obj,
log_shape=log_shape)) | [
"def",
"enable_argscope_for_module",
"(",
"module",
",",
"log_shape",
"=",
"True",
")",
":",
"if",
"is_tfv2",
"(",
")",
"and",
"module",
"==",
"tf",
".",
"layers",
":",
"module",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"layers",
"for",
"name",
",",
"obj",
"in",
"getmembers",
"(",
"module",
")",
":",
"if",
"isfunction",
"(",
"obj",
")",
":",
"setattr",
"(",
"module",
",",
"name",
",",
"enable_argscope_for_function",
"(",
"obj",
",",
"log_shape",
"=",
"log_shape",
")",
")"
] | Overwrite all functions of a given module to support argscope.
Note that this function monkey-patches the module and therefore could
have unexpected consequences.
It has been only tested to work well with ``tf.layers`` module.
Example:
.. code-block:: python
import tensorflow as tf
enable_argscope_for_module(tf.layers)
Args:
log_shape (bool): print input/output shapes of each function. | [
"Overwrite",
"all",
"functions",
"of",
"a",
"given",
"module",
"to",
"support",
"argscope",
".",
"Note",
"that",
"this",
"function",
"monkey",
"-",
"patches",
"the",
"module",
"and",
"therefore",
"could",
"have",
"unexpected",
"consequences",
".",
"It",
"has",
"been",
"only",
"tested",
"to",
"work",
"well",
"with",
"tf",
".",
"layers",
"module",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/argscope.py#L126-L148 |
27,307 | tensorpack/tensorpack | examples/OpticalFlow/flownet_models.py | pad | def pad(x, p=3):
"""Pad tensor in H, W
Remarks:
TensorFlow uses "ceil(input_spatial_shape[i] / strides[i])" rather than explicit padding
like Caffe, pyTorch does. Hence, we need to pad here beforehand.
Args:
x (tf.tensor): incoming tensor
p (int, optional): padding for H, W
Returns:
tf.tensor: padded tensor
"""
return tf.pad(x, [[0, 0], [0, 0], [p, p], [p, p]]) | python | def pad(x, p=3):
"""Pad tensor in H, W
Remarks:
TensorFlow uses "ceil(input_spatial_shape[i] / strides[i])" rather than explicit padding
like Caffe, pyTorch does. Hence, we need to pad here beforehand.
Args:
x (tf.tensor): incoming tensor
p (int, optional): padding for H, W
Returns:
tf.tensor: padded tensor
"""
return tf.pad(x, [[0, 0], [0, 0], [p, p], [p, p]]) | [
"def",
"pad",
"(",
"x",
",",
"p",
"=",
"3",
")",
":",
"return",
"tf",
".",
"pad",
"(",
"x",
",",
"[",
"[",
"0",
",",
"0",
"]",
",",
"[",
"0",
",",
"0",
"]",
",",
"[",
"p",
",",
"p",
"]",
",",
"[",
"p",
",",
"p",
"]",
"]",
")"
] | Pad tensor in H, W
Remarks:
TensorFlow uses "ceil(input_spatial_shape[i] / strides[i])" rather than explicit padding
like Caffe, pyTorch does. Hence, we need to pad here beforehand.
Args:
x (tf.tensor): incoming tensor
p (int, optional): padding for H, W
Returns:
tf.tensor: padded tensor | [
"Pad",
"tensor",
"in",
"H",
"W"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L17-L31 |
27,308 | tensorpack/tensorpack | examples/OpticalFlow/flownet_models.py | correlation | def correlation(ina, inb,
kernel_size, max_displacement,
stride_1, stride_2,
pad, data_format):
"""
Correlation Cost Volume computation.
This is a fallback Python-only implementation, specialized just for FlowNet2.
It takes a lot of memory and is slow.
If you know to compile a custom op yourself, it's better to use the cuda implementation here:
https://github.com/PatWie/tensorflow-recipes/tree/master/OpticalFlow/user_ops
"""
assert pad == max_displacement
assert kernel_size == 1
assert data_format == 'NCHW'
assert max_displacement % stride_2 == 0
assert stride_1 == 1
D = int(max_displacement / stride_2 * 2) + 1 # D^2 == number of correlations per spatial location
b, c, h, w = ina.shape.as_list()
inb = tf.pad(inb, [[0, 0], [0, 0], [pad, pad], [pad, pad]])
res = []
for k1 in range(0, D):
start_h = k1 * stride_2
for k2 in range(0, D):
start_w = k2 * stride_2
s = tf.slice(inb, [0, 0, start_h, start_w], [-1, -1, h, w])
ans = tf.reduce_mean(ina * s, axis=1, keepdims=True)
res.append(ans)
res = tf.concat(res, axis=1) # ND^2HW
return res | python | def correlation(ina, inb,
kernel_size, max_displacement,
stride_1, stride_2,
pad, data_format):
"""
Correlation Cost Volume computation.
This is a fallback Python-only implementation, specialized just for FlowNet2.
It takes a lot of memory and is slow.
If you know to compile a custom op yourself, it's better to use the cuda implementation here:
https://github.com/PatWie/tensorflow-recipes/tree/master/OpticalFlow/user_ops
"""
assert pad == max_displacement
assert kernel_size == 1
assert data_format == 'NCHW'
assert max_displacement % stride_2 == 0
assert stride_1 == 1
D = int(max_displacement / stride_2 * 2) + 1 # D^2 == number of correlations per spatial location
b, c, h, w = ina.shape.as_list()
inb = tf.pad(inb, [[0, 0], [0, 0], [pad, pad], [pad, pad]])
res = []
for k1 in range(0, D):
start_h = k1 * stride_2
for k2 in range(0, D):
start_w = k2 * stride_2
s = tf.slice(inb, [0, 0, start_h, start_w], [-1, -1, h, w])
ans = tf.reduce_mean(ina * s, axis=1, keepdims=True)
res.append(ans)
res = tf.concat(res, axis=1) # ND^2HW
return res | [
"def",
"correlation",
"(",
"ina",
",",
"inb",
",",
"kernel_size",
",",
"max_displacement",
",",
"stride_1",
",",
"stride_2",
",",
"pad",
",",
"data_format",
")",
":",
"assert",
"pad",
"==",
"max_displacement",
"assert",
"kernel_size",
"==",
"1",
"assert",
"data_format",
"==",
"'NCHW'",
"assert",
"max_displacement",
"%",
"stride_2",
"==",
"0",
"assert",
"stride_1",
"==",
"1",
"D",
"=",
"int",
"(",
"max_displacement",
"/",
"stride_2",
"*",
"2",
")",
"+",
"1",
"# D^2 == number of correlations per spatial location",
"b",
",",
"c",
",",
"h",
",",
"w",
"=",
"ina",
".",
"shape",
".",
"as_list",
"(",
")",
"inb",
"=",
"tf",
".",
"pad",
"(",
"inb",
",",
"[",
"[",
"0",
",",
"0",
"]",
",",
"[",
"0",
",",
"0",
"]",
",",
"[",
"pad",
",",
"pad",
"]",
",",
"[",
"pad",
",",
"pad",
"]",
"]",
")",
"res",
"=",
"[",
"]",
"for",
"k1",
"in",
"range",
"(",
"0",
",",
"D",
")",
":",
"start_h",
"=",
"k1",
"*",
"stride_2",
"for",
"k2",
"in",
"range",
"(",
"0",
",",
"D",
")",
":",
"start_w",
"=",
"k2",
"*",
"stride_2",
"s",
"=",
"tf",
".",
"slice",
"(",
"inb",
",",
"[",
"0",
",",
"0",
",",
"start_h",
",",
"start_w",
"]",
",",
"[",
"-",
"1",
",",
"-",
"1",
",",
"h",
",",
"w",
"]",
")",
"ans",
"=",
"tf",
".",
"reduce_mean",
"(",
"ina",
"*",
"s",
",",
"axis",
"=",
"1",
",",
"keepdims",
"=",
"True",
")",
"res",
".",
"append",
"(",
"ans",
")",
"res",
"=",
"tf",
".",
"concat",
"(",
"res",
",",
"axis",
"=",
"1",
")",
"# ND^2HW",
"return",
"res"
] | Correlation Cost Volume computation.
This is a fallback Python-only implementation, specialized just for FlowNet2.
It takes a lot of memory and is slow.
If you know to compile a custom op yourself, it's better to use the cuda implementation here:
https://github.com/PatWie/tensorflow-recipes/tree/master/OpticalFlow/user_ops | [
"Correlation",
"Cost",
"Volume",
"computation",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L38-L72 |
27,309 | tensorpack/tensorpack | examples/OpticalFlow/flownet_models.py | resize | def resize(x, mode, factor=4):
"""Resize input tensor with unkown input-shape by a factor
Args:
x (tf.Tensor): tensor NCHW
factor (int, optional): resize factor for H, W
Note:
Differences here against Caffe have huge impacts on the
quality of the predictions.
Returns:
tf.Tensor: resized tensor NCHW
"""
assert mode in ['bilinear', 'nearest'], mode
shp = tf.shape(x)[2:] * factor
# NCHW -> NHWC
x = tf.transpose(x, [0, 2, 3, 1])
if mode == 'bilinear':
x = tf.image.resize_bilinear(x, shp, align_corners=True)
else:
# better approximation of what Caffe is doing
x = tf.image.resize_nearest_neighbor(x, shp, align_corners=False)
# NHWC -> NCHW
return tf.transpose(x, [0, 3, 1, 2]) | python | def resize(x, mode, factor=4):
"""Resize input tensor with unkown input-shape by a factor
Args:
x (tf.Tensor): tensor NCHW
factor (int, optional): resize factor for H, W
Note:
Differences here against Caffe have huge impacts on the
quality of the predictions.
Returns:
tf.Tensor: resized tensor NCHW
"""
assert mode in ['bilinear', 'nearest'], mode
shp = tf.shape(x)[2:] * factor
# NCHW -> NHWC
x = tf.transpose(x, [0, 2, 3, 1])
if mode == 'bilinear':
x = tf.image.resize_bilinear(x, shp, align_corners=True)
else:
# better approximation of what Caffe is doing
x = tf.image.resize_nearest_neighbor(x, shp, align_corners=False)
# NHWC -> NCHW
return tf.transpose(x, [0, 3, 1, 2]) | [
"def",
"resize",
"(",
"x",
",",
"mode",
",",
"factor",
"=",
"4",
")",
":",
"assert",
"mode",
"in",
"[",
"'bilinear'",
",",
"'nearest'",
"]",
",",
"mode",
"shp",
"=",
"tf",
".",
"shape",
"(",
"x",
")",
"[",
"2",
":",
"]",
"*",
"factor",
"# NCHW -> NHWC",
"x",
"=",
"tf",
".",
"transpose",
"(",
"x",
",",
"[",
"0",
",",
"2",
",",
"3",
",",
"1",
"]",
")",
"if",
"mode",
"==",
"'bilinear'",
":",
"x",
"=",
"tf",
".",
"image",
".",
"resize_bilinear",
"(",
"x",
",",
"shp",
",",
"align_corners",
"=",
"True",
")",
"else",
":",
"# better approximation of what Caffe is doing",
"x",
"=",
"tf",
".",
"image",
".",
"resize_nearest_neighbor",
"(",
"x",
",",
"shp",
",",
"align_corners",
"=",
"False",
")",
"# NHWC -> NCHW",
"return",
"tf",
".",
"transpose",
"(",
"x",
",",
"[",
"0",
",",
"3",
",",
"1",
",",
"2",
"]",
")"
] | Resize input tensor with unkown input-shape by a factor
Args:
x (tf.Tensor): tensor NCHW
factor (int, optional): resize factor for H, W
Note:
Differences here against Caffe have huge impacts on the
quality of the predictions.
Returns:
tf.Tensor: resized tensor NCHW | [
"Resize",
"input",
"tensor",
"with",
"unkown",
"input",
"-",
"shape",
"by",
"a",
"factor"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L115-L139 |
27,310 | tensorpack/tensorpack | examples/OpticalFlow/flownet_models.py | FlowNet2.flownet2_fusion | def flownet2_fusion(self, x):
"""
Architecture in Table 4 of FlowNet 2.0.
Args:
x: NCHW tensor, where C=11 is the concatenation of 7 items of [3, 2, 2, 1, 1, 1, 1] channels.
"""
with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1),
padding='valid', strides=2, kernel_size=3,
data_format='channels_first'), \
argscope([tf.layers.conv2d_transpose], padding='same', activation=tf.identity,
data_format='channels_first', strides=2, kernel_size=4):
conv0 = tf.layers.conv2d(pad(x, 1), 64, name='conv0', strides=1)
x = tf.layers.conv2d(pad(conv0, 1), 64, name='conv1')
conv1 = tf.layers.conv2d(pad(x, 1), 128, name='conv1_1', strides=1)
x = tf.layers.conv2d(pad(conv1, 1), 128, name='conv2')
conv2 = tf.layers.conv2d(pad(x, 1), 128, name='conv2_1', strides=1)
flow2 = tf.layers.conv2d(pad(conv2, 1), 2, name='predict_flow2', strides=1, activation=tf.identity)
flow2_up = tf.layers.conv2d_transpose(flow2, 2, name='upsampled_flow2_to_1')
x = tf.layers.conv2d_transpose(conv2, 32, name='deconv1', activation=lambda x: tf.nn.leaky_relu(x, 0.1))
concat1 = tf.concat([conv1, x, flow2_up], axis=1, name='concat1')
interconv1 = tf.layers.conv2d(pad(concat1, 1), 32, strides=1, name='inter_conv1', activation=tf.identity)
flow1 = tf.layers.conv2d(pad(interconv1, 1), 2, name='predict_flow1', strides=1, activation=tf.identity)
flow1_up = tf.layers.conv2d_transpose(flow1, 2, name='upsampled_flow1_to_0')
x = tf.layers.conv2d_transpose(concat1, 16, name='deconv0', activation=lambda x: tf.nn.leaky_relu(x, 0.1))
concat0 = tf.concat([conv0, x, flow1_up], axis=1, name='concat0')
interconv0 = tf.layers.conv2d(pad(concat0, 1), 16, strides=1, name='inter_conv0', activation=tf.identity)
flow0 = tf.layers.conv2d(pad(interconv0, 1), 2, name='predict_flow0', strides=1, activation=tf.identity)
return tf.identity(flow0, name='flow2') | python | def flownet2_fusion(self, x):
"""
Architecture in Table 4 of FlowNet 2.0.
Args:
x: NCHW tensor, where C=11 is the concatenation of 7 items of [3, 2, 2, 1, 1, 1, 1] channels.
"""
with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1),
padding='valid', strides=2, kernel_size=3,
data_format='channels_first'), \
argscope([tf.layers.conv2d_transpose], padding='same', activation=tf.identity,
data_format='channels_first', strides=2, kernel_size=4):
conv0 = tf.layers.conv2d(pad(x, 1), 64, name='conv0', strides=1)
x = tf.layers.conv2d(pad(conv0, 1), 64, name='conv1')
conv1 = tf.layers.conv2d(pad(x, 1), 128, name='conv1_1', strides=1)
x = tf.layers.conv2d(pad(conv1, 1), 128, name='conv2')
conv2 = tf.layers.conv2d(pad(x, 1), 128, name='conv2_1', strides=1)
flow2 = tf.layers.conv2d(pad(conv2, 1), 2, name='predict_flow2', strides=1, activation=tf.identity)
flow2_up = tf.layers.conv2d_transpose(flow2, 2, name='upsampled_flow2_to_1')
x = tf.layers.conv2d_transpose(conv2, 32, name='deconv1', activation=lambda x: tf.nn.leaky_relu(x, 0.1))
concat1 = tf.concat([conv1, x, flow2_up], axis=1, name='concat1')
interconv1 = tf.layers.conv2d(pad(concat1, 1), 32, strides=1, name='inter_conv1', activation=tf.identity)
flow1 = tf.layers.conv2d(pad(interconv1, 1), 2, name='predict_flow1', strides=1, activation=tf.identity)
flow1_up = tf.layers.conv2d_transpose(flow1, 2, name='upsampled_flow1_to_0')
x = tf.layers.conv2d_transpose(concat1, 16, name='deconv0', activation=lambda x: tf.nn.leaky_relu(x, 0.1))
concat0 = tf.concat([conv0, x, flow1_up], axis=1, name='concat0')
interconv0 = tf.layers.conv2d(pad(concat0, 1), 16, strides=1, name='inter_conv0', activation=tf.identity)
flow0 = tf.layers.conv2d(pad(interconv0, 1), 2, name='predict_flow0', strides=1, activation=tf.identity)
return tf.identity(flow0, name='flow2') | [
"def",
"flownet2_fusion",
"(",
"self",
",",
"x",
")",
":",
"with",
"argscope",
"(",
"[",
"tf",
".",
"layers",
".",
"conv2d",
"]",
",",
"activation",
"=",
"lambda",
"x",
":",
"tf",
".",
"nn",
".",
"leaky_relu",
"(",
"x",
",",
"0.1",
")",
",",
"padding",
"=",
"'valid'",
",",
"strides",
"=",
"2",
",",
"kernel_size",
"=",
"3",
",",
"data_format",
"=",
"'channels_first'",
")",
",",
"argscope",
"(",
"[",
"tf",
".",
"layers",
".",
"conv2d_transpose",
"]",
",",
"padding",
"=",
"'same'",
",",
"activation",
"=",
"tf",
".",
"identity",
",",
"data_format",
"=",
"'channels_first'",
",",
"strides",
"=",
"2",
",",
"kernel_size",
"=",
"4",
")",
":",
"conv0",
"=",
"tf",
".",
"layers",
".",
"conv2d",
"(",
"pad",
"(",
"x",
",",
"1",
")",
",",
"64",
",",
"name",
"=",
"'conv0'",
",",
"strides",
"=",
"1",
")",
"x",
"=",
"tf",
".",
"layers",
".",
"conv2d",
"(",
"pad",
"(",
"conv0",
",",
"1",
")",
",",
"64",
",",
"name",
"=",
"'conv1'",
")",
"conv1",
"=",
"tf",
".",
"layers",
".",
"conv2d",
"(",
"pad",
"(",
"x",
",",
"1",
")",
",",
"128",
",",
"name",
"=",
"'conv1_1'",
",",
"strides",
"=",
"1",
")",
"x",
"=",
"tf",
".",
"layers",
".",
"conv2d",
"(",
"pad",
"(",
"conv1",
",",
"1",
")",
",",
"128",
",",
"name",
"=",
"'conv2'",
")",
"conv2",
"=",
"tf",
".",
"layers",
".",
"conv2d",
"(",
"pad",
"(",
"x",
",",
"1",
")",
",",
"128",
",",
"name",
"=",
"'conv2_1'",
",",
"strides",
"=",
"1",
")",
"flow2",
"=",
"tf",
".",
"layers",
".",
"conv2d",
"(",
"pad",
"(",
"conv2",
",",
"1",
")",
",",
"2",
",",
"name",
"=",
"'predict_flow2'",
",",
"strides",
"=",
"1",
",",
"activation",
"=",
"tf",
".",
"identity",
")",
"flow2_up",
"=",
"tf",
".",
"layers",
".",
"conv2d_transpose",
"(",
"flow2",
",",
"2",
",",
"name",
"=",
"'upsampled_flow2_to_1'",
")",
"x",
"=",
"tf",
".",
"layers",
".",
"conv2d_transpose",
"(",
"conv2",
",",
"32",
",",
"name",
"=",
"'deconv1'",
",",
"activation",
"=",
"lambda",
"x",
":",
"tf",
".",
"nn",
".",
"leaky_relu",
"(",
"x",
",",
"0.1",
")",
")",
"concat1",
"=",
"tf",
".",
"concat",
"(",
"[",
"conv1",
",",
"x",
",",
"flow2_up",
"]",
",",
"axis",
"=",
"1",
",",
"name",
"=",
"'concat1'",
")",
"interconv1",
"=",
"tf",
".",
"layers",
".",
"conv2d",
"(",
"pad",
"(",
"concat1",
",",
"1",
")",
",",
"32",
",",
"strides",
"=",
"1",
",",
"name",
"=",
"'inter_conv1'",
",",
"activation",
"=",
"tf",
".",
"identity",
")",
"flow1",
"=",
"tf",
".",
"layers",
".",
"conv2d",
"(",
"pad",
"(",
"interconv1",
",",
"1",
")",
",",
"2",
",",
"name",
"=",
"'predict_flow1'",
",",
"strides",
"=",
"1",
",",
"activation",
"=",
"tf",
".",
"identity",
")",
"flow1_up",
"=",
"tf",
".",
"layers",
".",
"conv2d_transpose",
"(",
"flow1",
",",
"2",
",",
"name",
"=",
"'upsampled_flow1_to_0'",
")",
"x",
"=",
"tf",
".",
"layers",
".",
"conv2d_transpose",
"(",
"concat1",
",",
"16",
",",
"name",
"=",
"'deconv0'",
",",
"activation",
"=",
"lambda",
"x",
":",
"tf",
".",
"nn",
".",
"leaky_relu",
"(",
"x",
",",
"0.1",
")",
")",
"concat0",
"=",
"tf",
".",
"concat",
"(",
"[",
"conv0",
",",
"x",
",",
"flow1_up",
"]",
",",
"axis",
"=",
"1",
",",
"name",
"=",
"'concat0'",
")",
"interconv0",
"=",
"tf",
".",
"layers",
".",
"conv2d",
"(",
"pad",
"(",
"concat0",
",",
"1",
")",
",",
"16",
",",
"strides",
"=",
"1",
",",
"name",
"=",
"'inter_conv0'",
",",
"activation",
"=",
"tf",
".",
"identity",
")",
"flow0",
"=",
"tf",
".",
"layers",
".",
"conv2d",
"(",
"pad",
"(",
"interconv0",
",",
"1",
")",
",",
"2",
",",
"name",
"=",
"'predict_flow0'",
",",
"strides",
"=",
"1",
",",
"activation",
"=",
"tf",
".",
"identity",
")",
"return",
"tf",
".",
"identity",
"(",
"flow0",
",",
"name",
"=",
"'flow2'",
")"
] | Architecture in Table 4 of FlowNet 2.0.
Args:
x: NCHW tensor, where C=11 is the concatenation of 7 items of [3, 2, 2, 1, 1, 1, 1] channels. | [
"Architecture",
"in",
"Table",
"4",
"of",
"FlowNet",
"2",
".",
"0",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L230-L264 |
27,311 | tensorpack/tensorpack | examples/FasterRCNN/viz.py | draw_annotation | def draw_annotation(img, boxes, klass, is_crowd=None):
"""Will not modify img"""
labels = []
assert len(boxes) == len(klass)
if is_crowd is not None:
assert len(boxes) == len(is_crowd)
for cls, crd in zip(klass, is_crowd):
clsname = cfg.DATA.CLASS_NAMES[cls]
if crd == 1:
clsname += ';Crowd'
labels.append(clsname)
else:
for cls in klass:
labels.append(cfg.DATA.CLASS_NAMES[cls])
img = viz.draw_boxes(img, boxes, labels)
return img | python | def draw_annotation(img, boxes, klass, is_crowd=None):
"""Will not modify img"""
labels = []
assert len(boxes) == len(klass)
if is_crowd is not None:
assert len(boxes) == len(is_crowd)
for cls, crd in zip(klass, is_crowd):
clsname = cfg.DATA.CLASS_NAMES[cls]
if crd == 1:
clsname += ';Crowd'
labels.append(clsname)
else:
for cls in klass:
labels.append(cfg.DATA.CLASS_NAMES[cls])
img = viz.draw_boxes(img, boxes, labels)
return img | [
"def",
"draw_annotation",
"(",
"img",
",",
"boxes",
",",
"klass",
",",
"is_crowd",
"=",
"None",
")",
":",
"labels",
"=",
"[",
"]",
"assert",
"len",
"(",
"boxes",
")",
"==",
"len",
"(",
"klass",
")",
"if",
"is_crowd",
"is",
"not",
"None",
":",
"assert",
"len",
"(",
"boxes",
")",
"==",
"len",
"(",
"is_crowd",
")",
"for",
"cls",
",",
"crd",
"in",
"zip",
"(",
"klass",
",",
"is_crowd",
")",
":",
"clsname",
"=",
"cfg",
".",
"DATA",
".",
"CLASS_NAMES",
"[",
"cls",
"]",
"if",
"crd",
"==",
"1",
":",
"clsname",
"+=",
"';Crowd'",
"labels",
".",
"append",
"(",
"clsname",
")",
"else",
":",
"for",
"cls",
"in",
"klass",
":",
"labels",
".",
"append",
"(",
"cfg",
".",
"DATA",
".",
"CLASS_NAMES",
"[",
"cls",
"]",
")",
"img",
"=",
"viz",
".",
"draw_boxes",
"(",
"img",
",",
"boxes",
",",
"labels",
")",
"return",
"img"
] | Will not modify img | [
"Will",
"not",
"modify",
"img"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/viz.py#L15-L30 |
27,312 | tensorpack/tensorpack | examples/FasterRCNN/viz.py | draw_mask | def draw_mask(im, mask, alpha=0.5, color=None):
"""
Overlay a mask on top of the image.
Args:
im: a 3-channel uint8 image in BGR
mask: a binary 1-channel image of the same size
color: if None, will choose automatically
"""
if color is None:
color = PALETTE_RGB[np.random.choice(len(PALETTE_RGB))][::-1]
im = np.where(np.repeat((mask > 0)[:, :, None], 3, axis=2),
im * (1 - alpha) + color * alpha, im)
im = im.astype('uint8')
return im | python | def draw_mask(im, mask, alpha=0.5, color=None):
"""
Overlay a mask on top of the image.
Args:
im: a 3-channel uint8 image in BGR
mask: a binary 1-channel image of the same size
color: if None, will choose automatically
"""
if color is None:
color = PALETTE_RGB[np.random.choice(len(PALETTE_RGB))][::-1]
im = np.where(np.repeat((mask > 0)[:, :, None], 3, axis=2),
im * (1 - alpha) + color * alpha, im)
im = im.astype('uint8')
return im | [
"def",
"draw_mask",
"(",
"im",
",",
"mask",
",",
"alpha",
"=",
"0.5",
",",
"color",
"=",
"None",
")",
":",
"if",
"color",
"is",
"None",
":",
"color",
"=",
"PALETTE_RGB",
"[",
"np",
".",
"random",
".",
"choice",
"(",
"len",
"(",
"PALETTE_RGB",
")",
")",
"]",
"[",
":",
":",
"-",
"1",
"]",
"im",
"=",
"np",
".",
"where",
"(",
"np",
".",
"repeat",
"(",
"(",
"mask",
">",
"0",
")",
"[",
":",
",",
":",
",",
"None",
"]",
",",
"3",
",",
"axis",
"=",
"2",
")",
",",
"im",
"*",
"(",
"1",
"-",
"alpha",
")",
"+",
"color",
"*",
"alpha",
",",
"im",
")",
"im",
"=",
"im",
".",
"astype",
"(",
"'uint8'",
")",
"return",
"im"
] | Overlay a mask on top of the image.
Args:
im: a 3-channel uint8 image in BGR
mask: a binary 1-channel image of the same size
color: if None, will choose automatically | [
"Overlay",
"a",
"mask",
"on",
"top",
"of",
"the",
"image",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/viz.py#L94-L108 |
27,313 | tensorpack/tensorpack | tensorpack/dataflow/remote.py | send_dataflow_zmq | def send_dataflow_zmq(df, addr, hwm=50, format=None, bind=False):
"""
Run DataFlow and send data to a ZMQ socket addr.
It will serialize and send each datapoint to this address with a PUSH socket.
This function never returns.
Args:
df (DataFlow): Will infinitely loop over the DataFlow.
addr: a ZMQ socket endpoint.
hwm (int): ZMQ high-water mark (buffer size)
format (str): The serialization format.
Default format uses :mod:`tensorpack.utils.serialize`.
This format works with :class:`dataflow.RemoteDataZMQ`.
An alternate format is 'zmq_ops', used by https://github.com/tensorpack/zmq_ops
and :class:`input_source.ZMQInput`.
bind (bool): whether to bind or connect to the endpoint address.
"""
assert format in [None, 'zmq_op', 'zmq_ops']
if format is None:
dump_fn = dumps
else:
from zmq_ops import dump_arrays
dump_fn = dump_arrays
ctx = zmq.Context()
socket = ctx.socket(zmq.PUSH)
socket.set_hwm(hwm)
if bind:
socket.bind(addr)
else:
socket.connect(addr)
try:
df.reset_state()
logger.info("Serving data to {} with {} format ...".format(
addr, 'default' if format is None else 'zmq_ops'))
INTERVAL = 200
q = deque(maxlen=INTERVAL)
try:
total = len(df)
except NotImplementedError:
total = 0
tqdm_args = get_tqdm_kwargs(leave=True, smoothing=0.8)
tqdm_args['bar_format'] = tqdm_args['bar_format'] + "{postfix}"
while True:
with tqdm.trange(total, **tqdm_args) as pbar:
for dp in df:
start = time.time()
socket.send(dump_fn(dp), copy=False)
q.append(time.time() - start)
pbar.update(1)
if pbar.n % INTERVAL == 0:
avg = "{:.3f}".format(sum(q) / len(q))
pbar.set_postfix({'AvgSendLat': avg})
finally:
logger.info("Exiting send_dataflow_zmq ...")
socket.setsockopt(zmq.LINGER, 0)
socket.close()
if not ctx.closed:
ctx.destroy(0) | python | def send_dataflow_zmq(df, addr, hwm=50, format=None, bind=False):
"""
Run DataFlow and send data to a ZMQ socket addr.
It will serialize and send each datapoint to this address with a PUSH socket.
This function never returns.
Args:
df (DataFlow): Will infinitely loop over the DataFlow.
addr: a ZMQ socket endpoint.
hwm (int): ZMQ high-water mark (buffer size)
format (str): The serialization format.
Default format uses :mod:`tensorpack.utils.serialize`.
This format works with :class:`dataflow.RemoteDataZMQ`.
An alternate format is 'zmq_ops', used by https://github.com/tensorpack/zmq_ops
and :class:`input_source.ZMQInput`.
bind (bool): whether to bind or connect to the endpoint address.
"""
assert format in [None, 'zmq_op', 'zmq_ops']
if format is None:
dump_fn = dumps
else:
from zmq_ops import dump_arrays
dump_fn = dump_arrays
ctx = zmq.Context()
socket = ctx.socket(zmq.PUSH)
socket.set_hwm(hwm)
if bind:
socket.bind(addr)
else:
socket.connect(addr)
try:
df.reset_state()
logger.info("Serving data to {} with {} format ...".format(
addr, 'default' if format is None else 'zmq_ops'))
INTERVAL = 200
q = deque(maxlen=INTERVAL)
try:
total = len(df)
except NotImplementedError:
total = 0
tqdm_args = get_tqdm_kwargs(leave=True, smoothing=0.8)
tqdm_args['bar_format'] = tqdm_args['bar_format'] + "{postfix}"
while True:
with tqdm.trange(total, **tqdm_args) as pbar:
for dp in df:
start = time.time()
socket.send(dump_fn(dp), copy=False)
q.append(time.time() - start)
pbar.update(1)
if pbar.n % INTERVAL == 0:
avg = "{:.3f}".format(sum(q) / len(q))
pbar.set_postfix({'AvgSendLat': avg})
finally:
logger.info("Exiting send_dataflow_zmq ...")
socket.setsockopt(zmq.LINGER, 0)
socket.close()
if not ctx.closed:
ctx.destroy(0) | [
"def",
"send_dataflow_zmq",
"(",
"df",
",",
"addr",
",",
"hwm",
"=",
"50",
",",
"format",
"=",
"None",
",",
"bind",
"=",
"False",
")",
":",
"assert",
"format",
"in",
"[",
"None",
",",
"'zmq_op'",
",",
"'zmq_ops'",
"]",
"if",
"format",
"is",
"None",
":",
"dump_fn",
"=",
"dumps",
"else",
":",
"from",
"zmq_ops",
"import",
"dump_arrays",
"dump_fn",
"=",
"dump_arrays",
"ctx",
"=",
"zmq",
".",
"Context",
"(",
")",
"socket",
"=",
"ctx",
".",
"socket",
"(",
"zmq",
".",
"PUSH",
")",
"socket",
".",
"set_hwm",
"(",
"hwm",
")",
"if",
"bind",
":",
"socket",
".",
"bind",
"(",
"addr",
")",
"else",
":",
"socket",
".",
"connect",
"(",
"addr",
")",
"try",
":",
"df",
".",
"reset_state",
"(",
")",
"logger",
".",
"info",
"(",
"\"Serving data to {} with {} format ...\"",
".",
"format",
"(",
"addr",
",",
"'default'",
"if",
"format",
"is",
"None",
"else",
"'zmq_ops'",
")",
")",
"INTERVAL",
"=",
"200",
"q",
"=",
"deque",
"(",
"maxlen",
"=",
"INTERVAL",
")",
"try",
":",
"total",
"=",
"len",
"(",
"df",
")",
"except",
"NotImplementedError",
":",
"total",
"=",
"0",
"tqdm_args",
"=",
"get_tqdm_kwargs",
"(",
"leave",
"=",
"True",
",",
"smoothing",
"=",
"0.8",
")",
"tqdm_args",
"[",
"'bar_format'",
"]",
"=",
"tqdm_args",
"[",
"'bar_format'",
"]",
"+",
"\"{postfix}\"",
"while",
"True",
":",
"with",
"tqdm",
".",
"trange",
"(",
"total",
",",
"*",
"*",
"tqdm_args",
")",
"as",
"pbar",
":",
"for",
"dp",
"in",
"df",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"socket",
".",
"send",
"(",
"dump_fn",
"(",
"dp",
")",
",",
"copy",
"=",
"False",
")",
"q",
".",
"append",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start",
")",
"pbar",
".",
"update",
"(",
"1",
")",
"if",
"pbar",
".",
"n",
"%",
"INTERVAL",
"==",
"0",
":",
"avg",
"=",
"\"{:.3f}\"",
".",
"format",
"(",
"sum",
"(",
"q",
")",
"/",
"len",
"(",
"q",
")",
")",
"pbar",
".",
"set_postfix",
"(",
"{",
"'AvgSendLat'",
":",
"avg",
"}",
")",
"finally",
":",
"logger",
".",
"info",
"(",
"\"Exiting send_dataflow_zmq ...\"",
")",
"socket",
".",
"setsockopt",
"(",
"zmq",
".",
"LINGER",
",",
"0",
")",
"socket",
".",
"close",
"(",
")",
"if",
"not",
"ctx",
".",
"closed",
":",
"ctx",
".",
"destroy",
"(",
"0",
")"
] | Run DataFlow and send data to a ZMQ socket addr.
It will serialize and send each datapoint to this address with a PUSH socket.
This function never returns.
Args:
df (DataFlow): Will infinitely loop over the DataFlow.
addr: a ZMQ socket endpoint.
hwm (int): ZMQ high-water mark (buffer size)
format (str): The serialization format.
Default format uses :mod:`tensorpack.utils.serialize`.
This format works with :class:`dataflow.RemoteDataZMQ`.
An alternate format is 'zmq_ops', used by https://github.com/tensorpack/zmq_ops
and :class:`input_source.ZMQInput`.
bind (bool): whether to bind or connect to the endpoint address. | [
"Run",
"DataFlow",
"and",
"send",
"data",
"to",
"a",
"ZMQ",
"socket",
"addr",
".",
"It",
"will",
"serialize",
"and",
"send",
"each",
"datapoint",
"to",
"this",
"address",
"with",
"a",
"PUSH",
"socket",
".",
"This",
"function",
"never",
"returns",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/remote.py#L26-L85 |
27,314 | tensorpack/tensorpack | examples/FasterRCNN/model_box.py | crop_and_resize | def crop_and_resize(image, boxes, box_ind, crop_size, pad_border=True):
"""
Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes.
Args:
image: NCHW
boxes: nx4, x1y1x2y2
box_ind: (n,)
crop_size (int):
Returns:
n,C,size,size
"""
assert isinstance(crop_size, int), crop_size
boxes = tf.stop_gradient(boxes)
# TF's crop_and_resize produces zeros on border
if pad_border:
# this can be quite slow
image = tf.pad(image, [[0, 0], [0, 0], [1, 1], [1, 1]], mode='SYMMETRIC')
boxes = boxes + 1
@under_name_scope()
def transform_fpcoor_for_tf(boxes, image_shape, crop_shape):
"""
The way tf.image.crop_and_resize works (with normalized box):
Initial point (the value of output[0]): x0_box * (W_img - 1)
Spacing: w_box * (W_img - 1) / (W_crop - 1)
Use the above grid to bilinear sample.
However, what we want is (with fpcoor box):
Spacing: w_box / W_crop
Initial point: x0_box + spacing/2 - 0.5
(-0.5 because bilinear sample (in my definition) assumes floating point coordinate
(0.0, 0.0) is the same as pixel value (0, 0))
This function transform fpcoor boxes to a format to be used by tf.image.crop_and_resize
Returns:
y1x1y2x2
"""
x0, y0, x1, y1 = tf.split(boxes, 4, axis=1)
spacing_w = (x1 - x0) / tf.cast(crop_shape[1], tf.float32)
spacing_h = (y1 - y0) / tf.cast(crop_shape[0], tf.float32)
imshape = [tf.cast(image_shape[0] - 1, tf.float32), tf.cast(image_shape[1] - 1, tf.float32)]
nx0 = (x0 + spacing_w / 2 - 0.5) / imshape[1]
ny0 = (y0 + spacing_h / 2 - 0.5) / imshape[0]
nw = spacing_w * tf.cast(crop_shape[1] - 1, tf.float32) / imshape[1]
nh = spacing_h * tf.cast(crop_shape[0] - 1, tf.float32) / imshape[0]
return tf.concat([ny0, nx0, ny0 + nh, nx0 + nw], axis=1)
# Expand bbox to a minium size of 1
# boxes_x1y1, boxes_x2y2 = tf.split(boxes, 2, axis=1)
# boxes_wh = boxes_x2y2 - boxes_x1y1
# boxes_center = tf.reshape((boxes_x2y2 + boxes_x1y1) * 0.5, [-1, 2])
# boxes_newwh = tf.maximum(boxes_wh, 1.)
# boxes_x1y1new = boxes_center - boxes_newwh * 0.5
# boxes_x2y2new = boxes_center + boxes_newwh * 0.5
# boxes = tf.concat([boxes_x1y1new, boxes_x2y2new], axis=1)
image_shape = tf.shape(image)[2:]
boxes = transform_fpcoor_for_tf(boxes, image_shape, [crop_size, crop_size])
image = tf.transpose(image, [0, 2, 3, 1]) # nhwc
ret = tf.image.crop_and_resize(
image, boxes, tf.cast(box_ind, tf.int32),
crop_size=[crop_size, crop_size])
ret = tf.transpose(ret, [0, 3, 1, 2]) # ncss
return ret | python | def crop_and_resize(image, boxes, box_ind, crop_size, pad_border=True):
"""
Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes.
Args:
image: NCHW
boxes: nx4, x1y1x2y2
box_ind: (n,)
crop_size (int):
Returns:
n,C,size,size
"""
assert isinstance(crop_size, int), crop_size
boxes = tf.stop_gradient(boxes)
# TF's crop_and_resize produces zeros on border
if pad_border:
# this can be quite slow
image = tf.pad(image, [[0, 0], [0, 0], [1, 1], [1, 1]], mode='SYMMETRIC')
boxes = boxes + 1
@under_name_scope()
def transform_fpcoor_for_tf(boxes, image_shape, crop_shape):
"""
The way tf.image.crop_and_resize works (with normalized box):
Initial point (the value of output[0]): x0_box * (W_img - 1)
Spacing: w_box * (W_img - 1) / (W_crop - 1)
Use the above grid to bilinear sample.
However, what we want is (with fpcoor box):
Spacing: w_box / W_crop
Initial point: x0_box + spacing/2 - 0.5
(-0.5 because bilinear sample (in my definition) assumes floating point coordinate
(0.0, 0.0) is the same as pixel value (0, 0))
This function transform fpcoor boxes to a format to be used by tf.image.crop_and_resize
Returns:
y1x1y2x2
"""
x0, y0, x1, y1 = tf.split(boxes, 4, axis=1)
spacing_w = (x1 - x0) / tf.cast(crop_shape[1], tf.float32)
spacing_h = (y1 - y0) / tf.cast(crop_shape[0], tf.float32)
imshape = [tf.cast(image_shape[0] - 1, tf.float32), tf.cast(image_shape[1] - 1, tf.float32)]
nx0 = (x0 + spacing_w / 2 - 0.5) / imshape[1]
ny0 = (y0 + spacing_h / 2 - 0.5) / imshape[0]
nw = spacing_w * tf.cast(crop_shape[1] - 1, tf.float32) / imshape[1]
nh = spacing_h * tf.cast(crop_shape[0] - 1, tf.float32) / imshape[0]
return tf.concat([ny0, nx0, ny0 + nh, nx0 + nw], axis=1)
# Expand bbox to a minium size of 1
# boxes_x1y1, boxes_x2y2 = tf.split(boxes, 2, axis=1)
# boxes_wh = boxes_x2y2 - boxes_x1y1
# boxes_center = tf.reshape((boxes_x2y2 + boxes_x1y1) * 0.5, [-1, 2])
# boxes_newwh = tf.maximum(boxes_wh, 1.)
# boxes_x1y1new = boxes_center - boxes_newwh * 0.5
# boxes_x2y2new = boxes_center + boxes_newwh * 0.5
# boxes = tf.concat([boxes_x1y1new, boxes_x2y2new], axis=1)
image_shape = tf.shape(image)[2:]
boxes = transform_fpcoor_for_tf(boxes, image_shape, [crop_size, crop_size])
image = tf.transpose(image, [0, 2, 3, 1]) # nhwc
ret = tf.image.crop_and_resize(
image, boxes, tf.cast(box_ind, tf.int32),
crop_size=[crop_size, crop_size])
ret = tf.transpose(ret, [0, 3, 1, 2]) # ncss
return ret | [
"def",
"crop_and_resize",
"(",
"image",
",",
"boxes",
",",
"box_ind",
",",
"crop_size",
",",
"pad_border",
"=",
"True",
")",
":",
"assert",
"isinstance",
"(",
"crop_size",
",",
"int",
")",
",",
"crop_size",
"boxes",
"=",
"tf",
".",
"stop_gradient",
"(",
"boxes",
")",
"# TF's crop_and_resize produces zeros on border",
"if",
"pad_border",
":",
"# this can be quite slow",
"image",
"=",
"tf",
".",
"pad",
"(",
"image",
",",
"[",
"[",
"0",
",",
"0",
"]",
",",
"[",
"0",
",",
"0",
"]",
",",
"[",
"1",
",",
"1",
"]",
",",
"[",
"1",
",",
"1",
"]",
"]",
",",
"mode",
"=",
"'SYMMETRIC'",
")",
"boxes",
"=",
"boxes",
"+",
"1",
"@",
"under_name_scope",
"(",
")",
"def",
"transform_fpcoor_for_tf",
"(",
"boxes",
",",
"image_shape",
",",
"crop_shape",
")",
":",
"\"\"\"\n The way tf.image.crop_and_resize works (with normalized box):\n Initial point (the value of output[0]): x0_box * (W_img - 1)\n Spacing: w_box * (W_img - 1) / (W_crop - 1)\n Use the above grid to bilinear sample.\n\n However, what we want is (with fpcoor box):\n Spacing: w_box / W_crop\n Initial point: x0_box + spacing/2 - 0.5\n (-0.5 because bilinear sample (in my definition) assumes floating point coordinate\n (0.0, 0.0) is the same as pixel value (0, 0))\n\n This function transform fpcoor boxes to a format to be used by tf.image.crop_and_resize\n\n Returns:\n y1x1y2x2\n \"\"\"",
"x0",
",",
"y0",
",",
"x1",
",",
"y1",
"=",
"tf",
".",
"split",
"(",
"boxes",
",",
"4",
",",
"axis",
"=",
"1",
")",
"spacing_w",
"=",
"(",
"x1",
"-",
"x0",
")",
"/",
"tf",
".",
"cast",
"(",
"crop_shape",
"[",
"1",
"]",
",",
"tf",
".",
"float32",
")",
"spacing_h",
"=",
"(",
"y1",
"-",
"y0",
")",
"/",
"tf",
".",
"cast",
"(",
"crop_shape",
"[",
"0",
"]",
",",
"tf",
".",
"float32",
")",
"imshape",
"=",
"[",
"tf",
".",
"cast",
"(",
"image_shape",
"[",
"0",
"]",
"-",
"1",
",",
"tf",
".",
"float32",
")",
",",
"tf",
".",
"cast",
"(",
"image_shape",
"[",
"1",
"]",
"-",
"1",
",",
"tf",
".",
"float32",
")",
"]",
"nx0",
"=",
"(",
"x0",
"+",
"spacing_w",
"/",
"2",
"-",
"0.5",
")",
"/",
"imshape",
"[",
"1",
"]",
"ny0",
"=",
"(",
"y0",
"+",
"spacing_h",
"/",
"2",
"-",
"0.5",
")",
"/",
"imshape",
"[",
"0",
"]",
"nw",
"=",
"spacing_w",
"*",
"tf",
".",
"cast",
"(",
"crop_shape",
"[",
"1",
"]",
"-",
"1",
",",
"tf",
".",
"float32",
")",
"/",
"imshape",
"[",
"1",
"]",
"nh",
"=",
"spacing_h",
"*",
"tf",
".",
"cast",
"(",
"crop_shape",
"[",
"0",
"]",
"-",
"1",
",",
"tf",
".",
"float32",
")",
"/",
"imshape",
"[",
"0",
"]",
"return",
"tf",
".",
"concat",
"(",
"[",
"ny0",
",",
"nx0",
",",
"ny0",
"+",
"nh",
",",
"nx0",
"+",
"nw",
"]",
",",
"axis",
"=",
"1",
")",
"# Expand bbox to a minium size of 1",
"# boxes_x1y1, boxes_x2y2 = tf.split(boxes, 2, axis=1)",
"# boxes_wh = boxes_x2y2 - boxes_x1y1",
"# boxes_center = tf.reshape((boxes_x2y2 + boxes_x1y1) * 0.5, [-1, 2])",
"# boxes_newwh = tf.maximum(boxes_wh, 1.)",
"# boxes_x1y1new = boxes_center - boxes_newwh * 0.5",
"# boxes_x2y2new = boxes_center + boxes_newwh * 0.5",
"# boxes = tf.concat([boxes_x1y1new, boxes_x2y2new], axis=1)",
"image_shape",
"=",
"tf",
".",
"shape",
"(",
"image",
")",
"[",
"2",
":",
"]",
"boxes",
"=",
"transform_fpcoor_for_tf",
"(",
"boxes",
",",
"image_shape",
",",
"[",
"crop_size",
",",
"crop_size",
"]",
")",
"image",
"=",
"tf",
".",
"transpose",
"(",
"image",
",",
"[",
"0",
",",
"2",
",",
"3",
",",
"1",
"]",
")",
"# nhwc",
"ret",
"=",
"tf",
".",
"image",
".",
"crop_and_resize",
"(",
"image",
",",
"boxes",
",",
"tf",
".",
"cast",
"(",
"box_ind",
",",
"tf",
".",
"int32",
")",
",",
"crop_size",
"=",
"[",
"crop_size",
",",
"crop_size",
"]",
")",
"ret",
"=",
"tf",
".",
"transpose",
"(",
"ret",
",",
"[",
"0",
",",
"3",
",",
"1",
",",
"2",
"]",
")",
"# ncss",
"return",
"ret"
] | Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes.
Args:
image: NCHW
boxes: nx4, x1y1x2y2
box_ind: (n,)
crop_size (int):
Returns:
n,C,size,size | [
"Aligned",
"version",
"of",
"tf",
".",
"image",
".",
"crop_and_resize",
"following",
"our",
"definition",
"of",
"floating",
"point",
"boxes",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_box.py#L83-L153 |
27,315 | tensorpack/tensorpack | examples/FasterRCNN/model_box.py | RPNAnchors.narrow_to | def narrow_to(self, featuremap):
"""
Slice anchors to the spatial size of this featuremap.
"""
shape2d = tf.shape(featuremap)[2:] # h,w
slice3d = tf.concat([shape2d, [-1]], axis=0)
slice4d = tf.concat([shape2d, [-1, -1]], axis=0)
boxes = tf.slice(self.boxes, [0, 0, 0, 0], slice4d)
gt_labels = tf.slice(self.gt_labels, [0, 0, 0], slice3d)
gt_boxes = tf.slice(self.gt_boxes, [0, 0, 0, 0], slice4d)
return RPNAnchors(boxes, gt_labels, gt_boxes) | python | def narrow_to(self, featuremap):
"""
Slice anchors to the spatial size of this featuremap.
"""
shape2d = tf.shape(featuremap)[2:] # h,w
slice3d = tf.concat([shape2d, [-1]], axis=0)
slice4d = tf.concat([shape2d, [-1, -1]], axis=0)
boxes = tf.slice(self.boxes, [0, 0, 0, 0], slice4d)
gt_labels = tf.slice(self.gt_labels, [0, 0, 0], slice3d)
gt_boxes = tf.slice(self.gt_boxes, [0, 0, 0, 0], slice4d)
return RPNAnchors(boxes, gt_labels, gt_boxes) | [
"def",
"narrow_to",
"(",
"self",
",",
"featuremap",
")",
":",
"shape2d",
"=",
"tf",
".",
"shape",
"(",
"featuremap",
")",
"[",
"2",
":",
"]",
"# h,w",
"slice3d",
"=",
"tf",
".",
"concat",
"(",
"[",
"shape2d",
",",
"[",
"-",
"1",
"]",
"]",
",",
"axis",
"=",
"0",
")",
"slice4d",
"=",
"tf",
".",
"concat",
"(",
"[",
"shape2d",
",",
"[",
"-",
"1",
",",
"-",
"1",
"]",
"]",
",",
"axis",
"=",
"0",
")",
"boxes",
"=",
"tf",
".",
"slice",
"(",
"self",
".",
"boxes",
",",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
",",
"slice4d",
")",
"gt_labels",
"=",
"tf",
".",
"slice",
"(",
"self",
".",
"gt_labels",
",",
"[",
"0",
",",
"0",
",",
"0",
"]",
",",
"slice3d",
")",
"gt_boxes",
"=",
"tf",
".",
"slice",
"(",
"self",
".",
"gt_boxes",
",",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
",",
"slice4d",
")",
"return",
"RPNAnchors",
"(",
"boxes",
",",
"gt_labels",
",",
"gt_boxes",
")"
] | Slice anchors to the spatial size of this featuremap. | [
"Slice",
"anchors",
"to",
"the",
"spatial",
"size",
"of",
"this",
"featuremap",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_box.py#L189-L199 |
27,316 | tensorpack/tensorpack | tensorpack/utils/argtools.py | map_arg | def map_arg(**maps):
"""
Apply a mapping on certain argument before calling the original function.
Args:
maps (dict): {argument_name: map_func}
"""
def deco(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if six.PY2:
argmap = inspect.getcallargs(func, *args, **kwargs)
else:
# getcallargs was deprecated since 3.5
sig = inspect.signature(func)
argmap = sig.bind_partial(*args, **kwargs).arguments
for k, map_func in six.iteritems(maps):
if k in argmap:
argmap[k] = map_func(argmap[k])
return func(**argmap)
return wrapper
return deco | python | def map_arg(**maps):
"""
Apply a mapping on certain argument before calling the original function.
Args:
maps (dict): {argument_name: map_func}
"""
def deco(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if six.PY2:
argmap = inspect.getcallargs(func, *args, **kwargs)
else:
# getcallargs was deprecated since 3.5
sig = inspect.signature(func)
argmap = sig.bind_partial(*args, **kwargs).arguments
for k, map_func in six.iteritems(maps):
if k in argmap:
argmap[k] = map_func(argmap[k])
return func(**argmap)
return wrapper
return deco | [
"def",
"map_arg",
"(",
"*",
"*",
"maps",
")",
":",
"def",
"deco",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"six",
".",
"PY2",
":",
"argmap",
"=",
"inspect",
".",
"getcallargs",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"# getcallargs was deprecated since 3.5",
"sig",
"=",
"inspect",
".",
"signature",
"(",
"func",
")",
"argmap",
"=",
"sig",
".",
"bind_partial",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
".",
"arguments",
"for",
"k",
",",
"map_func",
"in",
"six",
".",
"iteritems",
"(",
"maps",
")",
":",
"if",
"k",
"in",
"argmap",
":",
"argmap",
"[",
"k",
"]",
"=",
"map_func",
"(",
"argmap",
"[",
"k",
"]",
")",
"return",
"func",
"(",
"*",
"*",
"argmap",
")",
"return",
"wrapper",
"return",
"deco"
] | Apply a mapping on certain argument before calling the original function.
Args:
maps (dict): {argument_name: map_func} | [
"Apply",
"a",
"mapping",
"on",
"certain",
"argument",
"before",
"calling",
"the",
"original",
"function",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L19-L40 |
27,317 | tensorpack/tensorpack | tensorpack/utils/argtools.py | graph_memoized | def graph_memoized(func):
"""
Like memoized, but keep one cache per default graph.
"""
# TODO it keeps the graph alive
from ..compat import tfv1
GRAPH_ARG_NAME = '__IMPOSSIBLE_NAME_FOR_YOU__'
@memoized
def func_with_graph_arg(*args, **kwargs):
kwargs.pop(GRAPH_ARG_NAME)
return func(*args, **kwargs)
@functools.wraps(func)
def wrapper(*args, **kwargs):
assert GRAPH_ARG_NAME not in kwargs, "No Way!!"
graph = tfv1.get_default_graph()
kwargs[GRAPH_ARG_NAME] = graph
return func_with_graph_arg(*args, **kwargs)
return wrapper | python | def graph_memoized(func):
"""
Like memoized, but keep one cache per default graph.
"""
# TODO it keeps the graph alive
from ..compat import tfv1
GRAPH_ARG_NAME = '__IMPOSSIBLE_NAME_FOR_YOU__'
@memoized
def func_with_graph_arg(*args, **kwargs):
kwargs.pop(GRAPH_ARG_NAME)
return func(*args, **kwargs)
@functools.wraps(func)
def wrapper(*args, **kwargs):
assert GRAPH_ARG_NAME not in kwargs, "No Way!!"
graph = tfv1.get_default_graph()
kwargs[GRAPH_ARG_NAME] = graph
return func_with_graph_arg(*args, **kwargs)
return wrapper | [
"def",
"graph_memoized",
"(",
"func",
")",
":",
"# TODO it keeps the graph alive",
"from",
".",
".",
"compat",
"import",
"tfv1",
"GRAPH_ARG_NAME",
"=",
"'__IMPOSSIBLE_NAME_FOR_YOU__'",
"@",
"memoized",
"def",
"func_with_graph_arg",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"pop",
"(",
"GRAPH_ARG_NAME",
")",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"GRAPH_ARG_NAME",
"not",
"in",
"kwargs",
",",
"\"No Way!!\"",
"graph",
"=",
"tfv1",
".",
"get_default_graph",
"(",
")",
"kwargs",
"[",
"GRAPH_ARG_NAME",
"]",
"=",
"graph",
"return",
"func_with_graph_arg",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] | Like memoized, but keep one cache per default graph. | [
"Like",
"memoized",
"but",
"keep",
"one",
"cache",
"per",
"default",
"graph",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L49-L69 |
27,318 | tensorpack/tensorpack | tensorpack/utils/argtools.py | memoized_ignoreargs | def memoized_ignoreargs(func):
"""
A decorator. It performs memoization ignoring the arguments used to call
the function.
"""
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 | python | def memoized_ignoreargs(func):
"""
A decorator. It performs memoization ignoring the arguments used to call
the function.
"""
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 | [
"def",
"memoized_ignoreargs",
"(",
"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"
] | A decorator. It performs memoization ignoring the arguments used to call
the function. | [
"A",
"decorator",
".",
"It",
"performs",
"memoization",
"ignoring",
"the",
"arguments",
"used",
"to",
"call",
"the",
"function",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L75-L86 |
27,319 | tensorpack/tensorpack | tensorpack/utils/argtools.py | shape2d | def shape2d(a):
"""
Ensure a 2D shape.
Args:
a: a int or tuple/list of length 2
Returns:
list: of length 2. if ``a`` is a int, return ``[a, a]``.
"""
if type(a) == int:
return [a, a]
if isinstance(a, (list, tuple)):
assert len(a) == 2
return list(a)
raise RuntimeError("Illegal shape: {}".format(a)) | python | def shape2d(a):
"""
Ensure a 2D shape.
Args:
a: a int or tuple/list of length 2
Returns:
list: of length 2. if ``a`` is a int, return ``[a, a]``.
"""
if type(a) == int:
return [a, a]
if isinstance(a, (list, tuple)):
assert len(a) == 2
return list(a)
raise RuntimeError("Illegal shape: {}".format(a)) | [
"def",
"shape2d",
"(",
"a",
")",
":",
"if",
"type",
"(",
"a",
")",
"==",
"int",
":",
"return",
"[",
"a",
",",
"a",
"]",
"if",
"isinstance",
"(",
"a",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"assert",
"len",
"(",
"a",
")",
"==",
"2",
"return",
"list",
"(",
"a",
")",
"raise",
"RuntimeError",
"(",
"\"Illegal shape: {}\"",
".",
"format",
"(",
"a",
")",
")"
] | Ensure a 2D shape.
Args:
a: a int or tuple/list of length 2
Returns:
list: of length 2. if ``a`` is a int, return ``[a, a]``. | [
"Ensure",
"a",
"2D",
"shape",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L89-L104 |
27,320 | tensorpack/tensorpack | tensorpack/utils/argtools.py | shape4d | def shape4d(a, data_format='NHWC'):
"""
Ensuer a 4D shape, to use with 4D symbolic functions.
Args:
a: a int or tuple/list of length 2
Returns:
list: of length 4. if ``a`` is a int, return ``[1, a, a, 1]``
or ``[1, 1, a, a]`` depending on data_format.
"""
s2d = shape2d(a)
if get_data_format(data_format, False) == 'NHWC':
return [1] + s2d + [1]
else:
return [1, 1] + s2d | python | def shape4d(a, data_format='NHWC'):
"""
Ensuer a 4D shape, to use with 4D symbolic functions.
Args:
a: a int or tuple/list of length 2
Returns:
list: of length 4. if ``a`` is a int, return ``[1, a, a, 1]``
or ``[1, 1, a, a]`` depending on data_format.
"""
s2d = shape2d(a)
if get_data_format(data_format, False) == 'NHWC':
return [1] + s2d + [1]
else:
return [1, 1] + s2d | [
"def",
"shape4d",
"(",
"a",
",",
"data_format",
"=",
"'NHWC'",
")",
":",
"s2d",
"=",
"shape2d",
"(",
"a",
")",
"if",
"get_data_format",
"(",
"data_format",
",",
"False",
")",
"==",
"'NHWC'",
":",
"return",
"[",
"1",
"]",
"+",
"s2d",
"+",
"[",
"1",
"]",
"else",
":",
"return",
"[",
"1",
",",
"1",
"]",
"+",
"s2d"
] | Ensuer a 4D shape, to use with 4D symbolic functions.
Args:
a: a int or tuple/list of length 2
Returns:
list: of length 4. if ``a`` is a int, return ``[1, a, a, 1]``
or ``[1, 1, a, a]`` depending on data_format. | [
"Ensuer",
"a",
"4D",
"shape",
"to",
"use",
"with",
"4D",
"symbolic",
"functions",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L118-L133 |
27,321 | tensorpack/tensorpack | tensorpack/utils/argtools.py | call_only_once | def call_only_once(func):
"""
Decorate a method or property of a class, so that this method can only
be called once for every instance.
Calling it more than once will result in exception.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
# cannot use hasattr here, because hasattr tries to getattr, which
# fails if func is a property
assert func.__name__ in dir(self), "call_only_once can only be used on method or property!"
if not hasattr(self, '_CALL_ONLY_ONCE_CACHE'):
cache = self._CALL_ONLY_ONCE_CACHE = set()
else:
cache = self._CALL_ONLY_ONCE_CACHE
cls = type(self)
# cannot use ismethod(), because decorated method becomes a function
is_method = inspect.isfunction(getattr(cls, func.__name__))
assert func not in cache, \
"{} {}.{} can only be called once per object!".format(
'Method' if is_method else 'Property',
cls.__name__, func.__name__)
cache.add(func)
return func(*args, **kwargs)
return wrapper | python | def call_only_once(func):
"""
Decorate a method or property of a class, so that this method can only
be called once for every instance.
Calling it more than once will result in exception.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
# cannot use hasattr here, because hasattr tries to getattr, which
# fails if func is a property
assert func.__name__ in dir(self), "call_only_once can only be used on method or property!"
if not hasattr(self, '_CALL_ONLY_ONCE_CACHE'):
cache = self._CALL_ONLY_ONCE_CACHE = set()
else:
cache = self._CALL_ONLY_ONCE_CACHE
cls = type(self)
# cannot use ismethod(), because decorated method becomes a function
is_method = inspect.isfunction(getattr(cls, func.__name__))
assert func not in cache, \
"{} {}.{} can only be called once per object!".format(
'Method' if is_method else 'Property',
cls.__name__, func.__name__)
cache.add(func)
return func(*args, **kwargs)
return wrapper | [
"def",
"call_only_once",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"args",
"[",
"0",
"]",
"# cannot use hasattr here, because hasattr tries to getattr, which",
"# fails if func is a property",
"assert",
"func",
".",
"__name__",
"in",
"dir",
"(",
"self",
")",
",",
"\"call_only_once can only be used on method or property!\"",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_CALL_ONLY_ONCE_CACHE'",
")",
":",
"cache",
"=",
"self",
".",
"_CALL_ONLY_ONCE_CACHE",
"=",
"set",
"(",
")",
"else",
":",
"cache",
"=",
"self",
".",
"_CALL_ONLY_ONCE_CACHE",
"cls",
"=",
"type",
"(",
"self",
")",
"# cannot use ismethod(), because decorated method becomes a function",
"is_method",
"=",
"inspect",
".",
"isfunction",
"(",
"getattr",
"(",
"cls",
",",
"func",
".",
"__name__",
")",
")",
"assert",
"func",
"not",
"in",
"cache",
",",
"\"{} {}.{} can only be called once per object!\"",
".",
"format",
"(",
"'Method'",
"if",
"is_method",
"else",
"'Property'",
",",
"cls",
".",
"__name__",
",",
"func",
".",
"__name__",
")",
"cache",
".",
"add",
"(",
"func",
")",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] | Decorate a method or property of a class, so that this method can only
be called once for every instance.
Calling it more than once will result in exception. | [
"Decorate",
"a",
"method",
"or",
"property",
"of",
"a",
"class",
"so",
"that",
"this",
"method",
"can",
"only",
"be",
"called",
"once",
"for",
"every",
"instance",
".",
"Calling",
"it",
"more",
"than",
"once",
"will",
"result",
"in",
"exception",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L149-L178 |
27,322 | tensorpack/tensorpack | tensorpack/utils/argtools.py | memoized_method | def memoized_method(func):
"""
A decorator that performs memoization on methods. It stores the cache on the object instance itself.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
assert func.__name__ in dir(self), "memoized_method can only be used on method!"
if not hasattr(self, '_MEMOIZED_CACHE'):
cache = self._MEMOIZED_CACHE = {}
else:
cache = self._MEMOIZED_CACHE
key = (func, ) + args[1:] + tuple(kwargs)
ret = cache.get(key, None)
if ret is not None:
return ret
value = func(*args, **kwargs)
cache[key] = value
return value
return wrapper | python | def memoized_method(func):
"""
A decorator that performs memoization on methods. It stores the cache on the object instance itself.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
assert func.__name__ in dir(self), "memoized_method can only be used on method!"
if not hasattr(self, '_MEMOIZED_CACHE'):
cache = self._MEMOIZED_CACHE = {}
else:
cache = self._MEMOIZED_CACHE
key = (func, ) + args[1:] + tuple(kwargs)
ret = cache.get(key, None)
if ret is not None:
return ret
value = func(*args, **kwargs)
cache[key] = value
return value
return wrapper | [
"def",
"memoized_method",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"args",
"[",
"0",
"]",
"assert",
"func",
".",
"__name__",
"in",
"dir",
"(",
"self",
")",
",",
"\"memoized_method can only be used on method!\"",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_MEMOIZED_CACHE'",
")",
":",
"cache",
"=",
"self",
".",
"_MEMOIZED_CACHE",
"=",
"{",
"}",
"else",
":",
"cache",
"=",
"self",
".",
"_MEMOIZED_CACHE",
"key",
"=",
"(",
"func",
",",
")",
"+",
"args",
"[",
"1",
":",
"]",
"+",
"tuple",
"(",
"kwargs",
")",
"ret",
"=",
"cache",
".",
"get",
"(",
"key",
",",
"None",
")",
"if",
"ret",
"is",
"not",
"None",
":",
"return",
"ret",
"value",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"cache",
"[",
"key",
"]",
"=",
"value",
"return",
"value",
"return",
"wrapper"
] | A decorator that performs memoization on methods. It stores the cache on the object instance itself. | [
"A",
"decorator",
"that",
"performs",
"memoization",
"on",
"methods",
".",
"It",
"stores",
"the",
"cache",
"on",
"the",
"object",
"instance",
"itself",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L181-L204 |
27,323 | tensorpack/tensorpack | tensorpack/tfutils/scope_utils.py | auto_reuse_variable_scope | def auto_reuse_variable_scope(func):
"""
A decorator which automatically reuses the current variable scope if the
function has been called with the same variable scope before.
Example:
.. code-block:: python
@auto_reuse_variable_scope
def myfunc(x):
return tf.layers.conv2d(x, 128, 3)
myfunc(x1) # will inherit parent scope reuse
myfunc(x2) # will reuse
with tf.variable_scope('newscope'):
myfunc(x3) # will inherit parent scope reuse
myfunc(x4) # will reuse
"""
used_scope = set()
@functools.wraps(func)
def wrapper(*args, **kwargs):
scope = tf.get_variable_scope()
h = hash((tf.get_default_graph(), scope.name))
# print("Entering " + scope.name + " reuse: " + str(h in used_scope))
if h in used_scope:
if get_tf_version_tuple() >= (1, 5):
with tf.variable_scope(scope, reuse=True, auxiliary_name_scope=False):
return func(*args, **kwargs)
else:
ns = tf.get_default_graph().get_name_scope()
with tf.variable_scope(scope, reuse=True), \
tf.name_scope(ns + '/' if ns else ''):
return func(*args, **kwargs)
else:
used_scope.add(h)
return func(*args, **kwargs)
return wrapper | python | def auto_reuse_variable_scope(func):
"""
A decorator which automatically reuses the current variable scope if the
function has been called with the same variable scope before.
Example:
.. code-block:: python
@auto_reuse_variable_scope
def myfunc(x):
return tf.layers.conv2d(x, 128, 3)
myfunc(x1) # will inherit parent scope reuse
myfunc(x2) # will reuse
with tf.variable_scope('newscope'):
myfunc(x3) # will inherit parent scope reuse
myfunc(x4) # will reuse
"""
used_scope = set()
@functools.wraps(func)
def wrapper(*args, **kwargs):
scope = tf.get_variable_scope()
h = hash((tf.get_default_graph(), scope.name))
# print("Entering " + scope.name + " reuse: " + str(h in used_scope))
if h in used_scope:
if get_tf_version_tuple() >= (1, 5):
with tf.variable_scope(scope, reuse=True, auxiliary_name_scope=False):
return func(*args, **kwargs)
else:
ns = tf.get_default_graph().get_name_scope()
with tf.variable_scope(scope, reuse=True), \
tf.name_scope(ns + '/' if ns else ''):
return func(*args, **kwargs)
else:
used_scope.add(h)
return func(*args, **kwargs)
return wrapper | [
"def",
"auto_reuse_variable_scope",
"(",
"func",
")",
":",
"used_scope",
"=",
"set",
"(",
")",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"scope",
"=",
"tf",
".",
"get_variable_scope",
"(",
")",
"h",
"=",
"hash",
"(",
"(",
"tf",
".",
"get_default_graph",
"(",
")",
",",
"scope",
".",
"name",
")",
")",
"# print(\"Entering \" + scope.name + \" reuse: \" + str(h in used_scope))",
"if",
"h",
"in",
"used_scope",
":",
"if",
"get_tf_version_tuple",
"(",
")",
">=",
"(",
"1",
",",
"5",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"scope",
",",
"reuse",
"=",
"True",
",",
"auxiliary_name_scope",
"=",
"False",
")",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"ns",
"=",
"tf",
".",
"get_default_graph",
"(",
")",
".",
"get_name_scope",
"(",
")",
"with",
"tf",
".",
"variable_scope",
"(",
"scope",
",",
"reuse",
"=",
"True",
")",
",",
"tf",
".",
"name_scope",
"(",
"ns",
"+",
"'/'",
"if",
"ns",
"else",
"''",
")",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"used_scope",
".",
"add",
"(",
"h",
")",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] | A decorator which automatically reuses the current variable scope if the
function has been called with the same variable scope before.
Example:
.. code-block:: python
@auto_reuse_variable_scope
def myfunc(x):
return tf.layers.conv2d(x, 128, 3)
myfunc(x1) # will inherit parent scope reuse
myfunc(x2) # will reuse
with tf.variable_scope('newscope'):
myfunc(x3) # will inherit parent scope reuse
myfunc(x4) # will reuse | [
"A",
"decorator",
"which",
"automatically",
"reuses",
"the",
"current",
"variable",
"scope",
"if",
"the",
"function",
"has",
"been",
"called",
"with",
"the",
"same",
"variable",
"scope",
"before",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/scope_utils.py#L15-L54 |
27,324 | tensorpack/tensorpack | tensorpack/tfutils/scope_utils.py | cached_name_scope | def cached_name_scope(name, top_level=True):
"""
Return a context which either opens and caches a new name scope,
or reenter an existing one.
Args:
top_level(bool): if True, the name scope will always be top-level.
It will not be nested under any existing name scope of the caller.
"""
if not top_level:
current_ns = tf.get_default_graph().get_name_scope()
if current_ns:
name = current_ns + '/' + name
ns = _get_cached_ns(name)
with tf.name_scope(ns):
yield ns | python | def cached_name_scope(name, top_level=True):
"""
Return a context which either opens and caches a new name scope,
or reenter an existing one.
Args:
top_level(bool): if True, the name scope will always be top-level.
It will not be nested under any existing name scope of the caller.
"""
if not top_level:
current_ns = tf.get_default_graph().get_name_scope()
if current_ns:
name = current_ns + '/' + name
ns = _get_cached_ns(name)
with tf.name_scope(ns):
yield ns | [
"def",
"cached_name_scope",
"(",
"name",
",",
"top_level",
"=",
"True",
")",
":",
"if",
"not",
"top_level",
":",
"current_ns",
"=",
"tf",
".",
"get_default_graph",
"(",
")",
".",
"get_name_scope",
"(",
")",
"if",
"current_ns",
":",
"name",
"=",
"current_ns",
"+",
"'/'",
"+",
"name",
"ns",
"=",
"_get_cached_ns",
"(",
"name",
")",
"with",
"tf",
".",
"name_scope",
"(",
"ns",
")",
":",
"yield",
"ns"
] | Return a context which either opens and caches a new name scope,
or reenter an existing one.
Args:
top_level(bool): if True, the name scope will always be top-level.
It will not be nested under any existing name scope of the caller. | [
"Return",
"a",
"context",
"which",
"either",
"opens",
"and",
"caches",
"a",
"new",
"name",
"scope",
"or",
"reenter",
"an",
"existing",
"one",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/scope_utils.py#L136-L151 |
27,325 | tensorpack/tensorpack | tensorpack/graph_builder/training.py | SyncMultiGPUReplicatedBuilder.get_post_init_ops | def get_post_init_ops():
"""
Copy values of variables on GPU 0 to other GPUs.
"""
# literally all variables, because it's better to sync optimizer-internal variables as well
all_vars = tf.global_variables() + tf.local_variables()
var_by_name = dict([(v.name, v) for v in all_vars])
trainable_names = set([x.name for x in tf.trainable_variables()])
post_init_ops = []
def log_failure(name, reason):
logger.warn("[ReplicatedTrainer] Do not know how to sync variable '{}' across GPUs. "
"Reason: {} ".format(name, reason))
assert name not in trainable_names, \
"The aforementioned variable is trainable, so this is probably a fatal error."
logger.warn(
"[ReplicatedTrainer] This variable is non-trainable. "
"Ignore this warning if you know it's OK to leave it out-of-sync.")
for v in all_vars:
if not v.name.startswith('tower'):
continue
if v.name.startswith('tower0'):
# in this trainer, the master name doesn't have the towerx/ prefix
log_failure(v.name, "Name should not have prefix 'tower0' in this trainer!")
continue # TODO some vars (EMA) may still startswith tower0
split_name = v.name.split('/')
prefix = split_name[0]
realname = '/'.join(split_name[1:])
if prefix in realname:
log_failure(v.name, "Prefix {} appears multiple times in its name!".format(prefix))
continue
copy_from = var_by_name.get(realname)
if copy_from is not None:
post_init_ops.append(v.assign(copy_from.read_value()))
else:
log_failure(v.name, "Cannot find {} in the graph!".format(realname))
logger.info(
"'sync_variables_from_main_tower' includes {} operations.".format(len(post_init_ops)))
return tf.group(*post_init_ops, name='sync_variables_from_main_tower') | python | def get_post_init_ops():
"""
Copy values of variables on GPU 0 to other GPUs.
"""
# literally all variables, because it's better to sync optimizer-internal variables as well
all_vars = tf.global_variables() + tf.local_variables()
var_by_name = dict([(v.name, v) for v in all_vars])
trainable_names = set([x.name for x in tf.trainable_variables()])
post_init_ops = []
def log_failure(name, reason):
logger.warn("[ReplicatedTrainer] Do not know how to sync variable '{}' across GPUs. "
"Reason: {} ".format(name, reason))
assert name not in trainable_names, \
"The aforementioned variable is trainable, so this is probably a fatal error."
logger.warn(
"[ReplicatedTrainer] This variable is non-trainable. "
"Ignore this warning if you know it's OK to leave it out-of-sync.")
for v in all_vars:
if not v.name.startswith('tower'):
continue
if v.name.startswith('tower0'):
# in this trainer, the master name doesn't have the towerx/ prefix
log_failure(v.name, "Name should not have prefix 'tower0' in this trainer!")
continue # TODO some vars (EMA) may still startswith tower0
split_name = v.name.split('/')
prefix = split_name[0]
realname = '/'.join(split_name[1:])
if prefix in realname:
log_failure(v.name, "Prefix {} appears multiple times in its name!".format(prefix))
continue
copy_from = var_by_name.get(realname)
if copy_from is not None:
post_init_ops.append(v.assign(copy_from.read_value()))
else:
log_failure(v.name, "Cannot find {} in the graph!".format(realname))
logger.info(
"'sync_variables_from_main_tower' includes {} operations.".format(len(post_init_ops)))
return tf.group(*post_init_ops, name='sync_variables_from_main_tower') | [
"def",
"get_post_init_ops",
"(",
")",
":",
"# literally all variables, because it's better to sync optimizer-internal variables as well",
"all_vars",
"=",
"tf",
".",
"global_variables",
"(",
")",
"+",
"tf",
".",
"local_variables",
"(",
")",
"var_by_name",
"=",
"dict",
"(",
"[",
"(",
"v",
".",
"name",
",",
"v",
")",
"for",
"v",
"in",
"all_vars",
"]",
")",
"trainable_names",
"=",
"set",
"(",
"[",
"x",
".",
"name",
"for",
"x",
"in",
"tf",
".",
"trainable_variables",
"(",
")",
"]",
")",
"post_init_ops",
"=",
"[",
"]",
"def",
"log_failure",
"(",
"name",
",",
"reason",
")",
":",
"logger",
".",
"warn",
"(",
"\"[ReplicatedTrainer] Do not know how to sync variable '{}' across GPUs. \"",
"\"Reason: {} \"",
".",
"format",
"(",
"name",
",",
"reason",
")",
")",
"assert",
"name",
"not",
"in",
"trainable_names",
",",
"\"The aforementioned variable is trainable, so this is probably a fatal error.\"",
"logger",
".",
"warn",
"(",
"\"[ReplicatedTrainer] This variable is non-trainable. \"",
"\"Ignore this warning if you know it's OK to leave it out-of-sync.\"",
")",
"for",
"v",
"in",
"all_vars",
":",
"if",
"not",
"v",
".",
"name",
".",
"startswith",
"(",
"'tower'",
")",
":",
"continue",
"if",
"v",
".",
"name",
".",
"startswith",
"(",
"'tower0'",
")",
":",
"# in this trainer, the master name doesn't have the towerx/ prefix",
"log_failure",
"(",
"v",
".",
"name",
",",
"\"Name should not have prefix 'tower0' in this trainer!\"",
")",
"continue",
"# TODO some vars (EMA) may still startswith tower0",
"split_name",
"=",
"v",
".",
"name",
".",
"split",
"(",
"'/'",
")",
"prefix",
"=",
"split_name",
"[",
"0",
"]",
"realname",
"=",
"'/'",
".",
"join",
"(",
"split_name",
"[",
"1",
":",
"]",
")",
"if",
"prefix",
"in",
"realname",
":",
"log_failure",
"(",
"v",
".",
"name",
",",
"\"Prefix {} appears multiple times in its name!\"",
".",
"format",
"(",
"prefix",
")",
")",
"continue",
"copy_from",
"=",
"var_by_name",
".",
"get",
"(",
"realname",
")",
"if",
"copy_from",
"is",
"not",
"None",
":",
"post_init_ops",
".",
"append",
"(",
"v",
".",
"assign",
"(",
"copy_from",
".",
"read_value",
"(",
")",
")",
")",
"else",
":",
"log_failure",
"(",
"v",
".",
"name",
",",
"\"Cannot find {} in the graph!\"",
".",
"format",
"(",
"realname",
")",
")",
"logger",
".",
"info",
"(",
"\"'sync_variables_from_main_tower' includes {} operations.\"",
".",
"format",
"(",
"len",
"(",
"post_init_ops",
")",
")",
")",
"return",
"tf",
".",
"group",
"(",
"*",
"post_init_ops",
",",
"name",
"=",
"'sync_variables_from_main_tower'",
")"
] | Copy values of variables on GPU 0 to other GPUs. | [
"Copy",
"values",
"of",
"variables",
"on",
"GPU",
"0",
"to",
"other",
"GPUs",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/training.py#L309-L349 |
27,326 | tensorpack/tensorpack | tensorpack/utils/utils.py | humanize_time_delta | def humanize_time_delta(sec):
"""Humanize timedelta given in seconds
Args:
sec (float): time difference in seconds. Must be positive.
Returns:
str - time difference as a readable string
Example:
.. code-block:: python
print(humanize_time_delta(1)) # 1 second
print(humanize_time_delta(60 + 1)) # 1 minute 1 second
print(humanize_time_delta(87.6)) # 1 minute 27 seconds
print(humanize_time_delta(0.01)) # 0.01 seconds
print(humanize_time_delta(60 * 60 + 1)) # 1 hour 1 second
print(humanize_time_delta(60 * 60 * 24 + 1)) # 1 day 1 second
print(humanize_time_delta(60 * 60 * 24 + 60 * 2 + 60*60*9 + 3)) # 1 day 9 hours 2 minutes 3 seconds
"""
if sec < 0:
logger.warn("humanize_time_delta() obtains negative seconds!")
return "{:.3g} seconds".format(sec)
if sec == 0:
return "0 second"
time = datetime(2000, 1, 1) + timedelta(seconds=int(sec))
units = ['day', 'hour', 'minute', 'second']
vals = [int(sec // 86400), time.hour, time.minute, time.second]
if sec < 60:
vals[-1] = sec
def _format(v, u):
return "{:.3g} {}{}".format(v, u, "s" if v > 1 else "")
ans = []
for v, u in zip(vals, units):
if v > 0:
ans.append(_format(v, u))
return " ".join(ans) | python | def humanize_time_delta(sec):
"""Humanize timedelta given in seconds
Args:
sec (float): time difference in seconds. Must be positive.
Returns:
str - time difference as a readable string
Example:
.. code-block:: python
print(humanize_time_delta(1)) # 1 second
print(humanize_time_delta(60 + 1)) # 1 minute 1 second
print(humanize_time_delta(87.6)) # 1 minute 27 seconds
print(humanize_time_delta(0.01)) # 0.01 seconds
print(humanize_time_delta(60 * 60 + 1)) # 1 hour 1 second
print(humanize_time_delta(60 * 60 * 24 + 1)) # 1 day 1 second
print(humanize_time_delta(60 * 60 * 24 + 60 * 2 + 60*60*9 + 3)) # 1 day 9 hours 2 minutes 3 seconds
"""
if sec < 0:
logger.warn("humanize_time_delta() obtains negative seconds!")
return "{:.3g} seconds".format(sec)
if sec == 0:
return "0 second"
time = datetime(2000, 1, 1) + timedelta(seconds=int(sec))
units = ['day', 'hour', 'minute', 'second']
vals = [int(sec // 86400), time.hour, time.minute, time.second]
if sec < 60:
vals[-1] = sec
def _format(v, u):
return "{:.3g} {}{}".format(v, u, "s" if v > 1 else "")
ans = []
for v, u in zip(vals, units):
if v > 0:
ans.append(_format(v, u))
return " ".join(ans) | [
"def",
"humanize_time_delta",
"(",
"sec",
")",
":",
"if",
"sec",
"<",
"0",
":",
"logger",
".",
"warn",
"(",
"\"humanize_time_delta() obtains negative seconds!\"",
")",
"return",
"\"{:.3g} seconds\"",
".",
"format",
"(",
"sec",
")",
"if",
"sec",
"==",
"0",
":",
"return",
"\"0 second\"",
"time",
"=",
"datetime",
"(",
"2000",
",",
"1",
",",
"1",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"int",
"(",
"sec",
")",
")",
"units",
"=",
"[",
"'day'",
",",
"'hour'",
",",
"'minute'",
",",
"'second'",
"]",
"vals",
"=",
"[",
"int",
"(",
"sec",
"//",
"86400",
")",
",",
"time",
".",
"hour",
",",
"time",
".",
"minute",
",",
"time",
".",
"second",
"]",
"if",
"sec",
"<",
"60",
":",
"vals",
"[",
"-",
"1",
"]",
"=",
"sec",
"def",
"_format",
"(",
"v",
",",
"u",
")",
":",
"return",
"\"{:.3g} {}{}\"",
".",
"format",
"(",
"v",
",",
"u",
",",
"\"s\"",
"if",
"v",
">",
"1",
"else",
"\"\"",
")",
"ans",
"=",
"[",
"]",
"for",
"v",
",",
"u",
"in",
"zip",
"(",
"vals",
",",
"units",
")",
":",
"if",
"v",
">",
"0",
":",
"ans",
".",
"append",
"(",
"_format",
"(",
"v",
",",
"u",
")",
")",
"return",
"\" \"",
".",
"join",
"(",
"ans",
")"
] | Humanize timedelta given in seconds
Args:
sec (float): time difference in seconds. Must be positive.
Returns:
str - time difference as a readable string
Example:
.. code-block:: python
print(humanize_time_delta(1)) # 1 second
print(humanize_time_delta(60 + 1)) # 1 minute 1 second
print(humanize_time_delta(87.6)) # 1 minute 27 seconds
print(humanize_time_delta(0.01)) # 0.01 seconds
print(humanize_time_delta(60 * 60 + 1)) # 1 hour 1 second
print(humanize_time_delta(60 * 60 * 24 + 1)) # 1 day 1 second
print(humanize_time_delta(60 * 60 * 24 + 60 * 2 + 60*60*9 + 3)) # 1 day 9 hours 2 minutes 3 seconds | [
"Humanize",
"timedelta",
"given",
"in",
"seconds"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L26-L65 |
27,327 | tensorpack/tensorpack | tensorpack/utils/utils.py | get_rng | def get_rng(obj=None):
"""
Get a good RNG seeded with time, pid and the object.
Args:
obj: some object to use to generate random seed.
Returns:
np.random.RandomState: the RNG.
"""
seed = (id(obj) + os.getpid() +
int(datetime.now().strftime("%Y%m%d%H%M%S%f"))) % 4294967295
if _RNG_SEED is not None:
seed = _RNG_SEED
return np.random.RandomState(seed) | python | def get_rng(obj=None):
"""
Get a good RNG seeded with time, pid and the object.
Args:
obj: some object to use to generate random seed.
Returns:
np.random.RandomState: the RNG.
"""
seed = (id(obj) + os.getpid() +
int(datetime.now().strftime("%Y%m%d%H%M%S%f"))) % 4294967295
if _RNG_SEED is not None:
seed = _RNG_SEED
return np.random.RandomState(seed) | [
"def",
"get_rng",
"(",
"obj",
"=",
"None",
")",
":",
"seed",
"=",
"(",
"id",
"(",
"obj",
")",
"+",
"os",
".",
"getpid",
"(",
")",
"+",
"int",
"(",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\"%Y%m%d%H%M%S%f\"",
")",
")",
")",
"%",
"4294967295",
"if",
"_RNG_SEED",
"is",
"not",
"None",
":",
"seed",
"=",
"_RNG_SEED",
"return",
"np",
".",
"random",
".",
"RandomState",
"(",
"seed",
")"
] | Get a good RNG seeded with time, pid and the object.
Args:
obj: some object to use to generate random seed.
Returns:
np.random.RandomState: the RNG. | [
"Get",
"a",
"good",
"RNG",
"seeded",
"with",
"time",
"pid",
"and",
"the",
"object",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L117-L130 |
27,328 | tensorpack/tensorpack | tensorpack/utils/utils.py | execute_only_once | def execute_only_once():
"""
Each called in the code to this function is guaranteed to return True the
first time and False afterwards.
Returns:
bool: whether this is the first time this function gets called from this line of code.
Example:
.. code-block:: python
if execute_only_once():
# do something only once
"""
f = inspect.currentframe().f_back
ident = (f.f_code.co_filename, f.f_lineno)
if ident in _EXECUTE_HISTORY:
return False
_EXECUTE_HISTORY.add(ident)
return True | python | def execute_only_once():
"""
Each called in the code to this function is guaranteed to return True the
first time and False afterwards.
Returns:
bool: whether this is the first time this function gets called from this line of code.
Example:
.. code-block:: python
if execute_only_once():
# do something only once
"""
f = inspect.currentframe().f_back
ident = (f.f_code.co_filename, f.f_lineno)
if ident in _EXECUTE_HISTORY:
return False
_EXECUTE_HISTORY.add(ident)
return True | [
"def",
"execute_only_once",
"(",
")",
":",
"f",
"=",
"inspect",
".",
"currentframe",
"(",
")",
".",
"f_back",
"ident",
"=",
"(",
"f",
".",
"f_code",
".",
"co_filename",
",",
"f",
".",
"f_lineno",
")",
"if",
"ident",
"in",
"_EXECUTE_HISTORY",
":",
"return",
"False",
"_EXECUTE_HISTORY",
".",
"add",
"(",
"ident",
")",
"return",
"True"
] | Each called in the code to this function is guaranteed to return True the
first time and False afterwards.
Returns:
bool: whether this is the first time this function gets called from this line of code.
Example:
.. code-block:: python
if execute_only_once():
# do something only once | [
"Each",
"called",
"in",
"the",
"code",
"to",
"this",
"function",
"is",
"guaranteed",
"to",
"return",
"True",
"the",
"first",
"time",
"and",
"False",
"afterwards",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L136-L155 |
27,329 | tensorpack/tensorpack | tensorpack/utils/utils.py | get_tqdm_kwargs | def get_tqdm_kwargs(**kwargs):
"""
Return default arguments to be used with tqdm.
Args:
kwargs: extra arguments to be used.
Returns:
dict:
"""
default = dict(
smoothing=0.5,
dynamic_ncols=True,
ascii=True,
bar_format='{l_bar}{bar}|{n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_noinv_fmt}]'
)
try:
# Use this env var to override the refresh interval setting
interval = float(os.environ['TENSORPACK_PROGRESS_REFRESH'])
except KeyError:
interval = _pick_tqdm_interval(kwargs.get('file', sys.stderr))
default['mininterval'] = interval
default.update(kwargs)
return default | python | def get_tqdm_kwargs(**kwargs):
"""
Return default arguments to be used with tqdm.
Args:
kwargs: extra arguments to be used.
Returns:
dict:
"""
default = dict(
smoothing=0.5,
dynamic_ncols=True,
ascii=True,
bar_format='{l_bar}{bar}|{n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_noinv_fmt}]'
)
try:
# Use this env var to override the refresh interval setting
interval = float(os.environ['TENSORPACK_PROGRESS_REFRESH'])
except KeyError:
interval = _pick_tqdm_interval(kwargs.get('file', sys.stderr))
default['mininterval'] = interval
default.update(kwargs)
return default | [
"def",
"get_tqdm_kwargs",
"(",
"*",
"*",
"kwargs",
")",
":",
"default",
"=",
"dict",
"(",
"smoothing",
"=",
"0.5",
",",
"dynamic_ncols",
"=",
"True",
",",
"ascii",
"=",
"True",
",",
"bar_format",
"=",
"'{l_bar}{bar}|{n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_noinv_fmt}]'",
")",
"try",
":",
"# Use this env var to override the refresh interval setting",
"interval",
"=",
"float",
"(",
"os",
".",
"environ",
"[",
"'TENSORPACK_PROGRESS_REFRESH'",
"]",
")",
"except",
"KeyError",
":",
"interval",
"=",
"_pick_tqdm_interval",
"(",
"kwargs",
".",
"get",
"(",
"'file'",
",",
"sys",
".",
"stderr",
")",
")",
"default",
"[",
"'mininterval'",
"]",
"=",
"interval",
"default",
".",
"update",
"(",
"kwargs",
")",
"return",
"default"
] | Return default arguments to be used with tqdm.
Args:
kwargs: extra arguments to be used.
Returns:
dict: | [
"Return",
"default",
"arguments",
"to",
"be",
"used",
"with",
"tqdm",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L190-L214 |
27,330 | tensorpack/tensorpack | tensorpack/utils/utils.py | find_library_full_path | def find_library_full_path(name):
"""
Similar to `from ctypes.util import find_library`, but try
to return full path if possible.
"""
from ctypes.util import find_library
if os.name == "posix" and sys.platform == "darwin":
# on Mac, ctypes already returns full path
return find_library(name)
def _use_proc_maps(name):
"""
Find so from /proc/pid/maps
Only works with libraries that has already been loaded.
But this is the most accurate method -- it finds the exact library that's being used.
"""
procmap = os.path.join('/proc', str(os.getpid()), 'maps')
if not os.path.isfile(procmap):
return None
with open(procmap, 'r') as f:
for line in f:
line = line.strip().split(' ')
sofile = line[-1]
basename = os.path.basename(sofile)
if 'lib' + name + '.so' in basename:
if os.path.isfile(sofile):
return os.path.realpath(sofile)
# The following two methods come from https://github.com/python/cpython/blob/master/Lib/ctypes/util.py
def _use_ld(name):
"""
Find so with `ld -lname -Lpath`.
It will search for files in LD_LIBRARY_PATH, but not in ldconfig.
"""
cmd = "ld -t -l{} -o {}".format(name, os.devnull)
ld_lib_path = os.environ.get('LD_LIBRARY_PATH', '')
for d in ld_lib_path.split(':'):
cmd = cmd + " -L " + d
result, ret = subproc_call(cmd + '|| true')
expr = r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name)
res = re.search(expr, result.decode('utf-8'))
if res:
res = res.group(0)
if not os.path.isfile(res):
return None
return os.path.realpath(res)
def _use_ldconfig(name):
"""
Find so in `ldconfig -p`.
It does not handle LD_LIBRARY_PATH.
"""
with change_env('LC_ALL', 'C'), change_env('LANG', 'C'):
ldconfig, ret = subproc_call("ldconfig -p")
ldconfig = ldconfig.decode('utf-8')
if ret != 0:
return None
expr = r'\s+(lib%s\.[^\s]+)\s+\(.*=>\s+(.*)' % (re.escape(name))
res = re.search(expr, ldconfig)
if not res:
return None
else:
ret = res.group(2)
return os.path.realpath(ret)
if sys.platform.startswith('linux'):
return _use_proc_maps(name) or _use_ld(name) or _use_ldconfig(name) or find_library(name)
return find_library(name) | python | def find_library_full_path(name):
"""
Similar to `from ctypes.util import find_library`, but try
to return full path if possible.
"""
from ctypes.util import find_library
if os.name == "posix" and sys.platform == "darwin":
# on Mac, ctypes already returns full path
return find_library(name)
def _use_proc_maps(name):
"""
Find so from /proc/pid/maps
Only works with libraries that has already been loaded.
But this is the most accurate method -- it finds the exact library that's being used.
"""
procmap = os.path.join('/proc', str(os.getpid()), 'maps')
if not os.path.isfile(procmap):
return None
with open(procmap, 'r') as f:
for line in f:
line = line.strip().split(' ')
sofile = line[-1]
basename = os.path.basename(sofile)
if 'lib' + name + '.so' in basename:
if os.path.isfile(sofile):
return os.path.realpath(sofile)
# The following two methods come from https://github.com/python/cpython/blob/master/Lib/ctypes/util.py
def _use_ld(name):
"""
Find so with `ld -lname -Lpath`.
It will search for files in LD_LIBRARY_PATH, but not in ldconfig.
"""
cmd = "ld -t -l{} -o {}".format(name, os.devnull)
ld_lib_path = os.environ.get('LD_LIBRARY_PATH', '')
for d in ld_lib_path.split(':'):
cmd = cmd + " -L " + d
result, ret = subproc_call(cmd + '|| true')
expr = r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name)
res = re.search(expr, result.decode('utf-8'))
if res:
res = res.group(0)
if not os.path.isfile(res):
return None
return os.path.realpath(res)
def _use_ldconfig(name):
"""
Find so in `ldconfig -p`.
It does not handle LD_LIBRARY_PATH.
"""
with change_env('LC_ALL', 'C'), change_env('LANG', 'C'):
ldconfig, ret = subproc_call("ldconfig -p")
ldconfig = ldconfig.decode('utf-8')
if ret != 0:
return None
expr = r'\s+(lib%s\.[^\s]+)\s+\(.*=>\s+(.*)' % (re.escape(name))
res = re.search(expr, ldconfig)
if not res:
return None
else:
ret = res.group(2)
return os.path.realpath(ret)
if sys.platform.startswith('linux'):
return _use_proc_maps(name) or _use_ld(name) or _use_ldconfig(name) or find_library(name)
return find_library(name) | [
"def",
"find_library_full_path",
"(",
"name",
")",
":",
"from",
"ctypes",
".",
"util",
"import",
"find_library",
"if",
"os",
".",
"name",
"==",
"\"posix\"",
"and",
"sys",
".",
"platform",
"==",
"\"darwin\"",
":",
"# on Mac, ctypes already returns full path",
"return",
"find_library",
"(",
"name",
")",
"def",
"_use_proc_maps",
"(",
"name",
")",
":",
"\"\"\"\n Find so from /proc/pid/maps\n Only works with libraries that has already been loaded.\n But this is the most accurate method -- it finds the exact library that's being used.\n \"\"\"",
"procmap",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'/proc'",
",",
"str",
"(",
"os",
".",
"getpid",
"(",
")",
")",
",",
"'maps'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"procmap",
")",
":",
"return",
"None",
"with",
"open",
"(",
"procmap",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"' '",
")",
"sofile",
"=",
"line",
"[",
"-",
"1",
"]",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"sofile",
")",
"if",
"'lib'",
"+",
"name",
"+",
"'.so'",
"in",
"basename",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"sofile",
")",
":",
"return",
"os",
".",
"path",
".",
"realpath",
"(",
"sofile",
")",
"# The following two methods come from https://github.com/python/cpython/blob/master/Lib/ctypes/util.py",
"def",
"_use_ld",
"(",
"name",
")",
":",
"\"\"\"\n Find so with `ld -lname -Lpath`.\n It will search for files in LD_LIBRARY_PATH, but not in ldconfig.\n \"\"\"",
"cmd",
"=",
"\"ld -t -l{} -o {}\"",
".",
"format",
"(",
"name",
",",
"os",
".",
"devnull",
")",
"ld_lib_path",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'LD_LIBRARY_PATH'",
",",
"''",
")",
"for",
"d",
"in",
"ld_lib_path",
".",
"split",
"(",
"':'",
")",
":",
"cmd",
"=",
"cmd",
"+",
"\" -L \"",
"+",
"d",
"result",
",",
"ret",
"=",
"subproc_call",
"(",
"cmd",
"+",
"'|| true'",
")",
"expr",
"=",
"r'[^\\(\\)\\s]*lib%s\\.[^\\(\\)\\s]*'",
"%",
"re",
".",
"escape",
"(",
"name",
")",
"res",
"=",
"re",
".",
"search",
"(",
"expr",
",",
"result",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"if",
"res",
":",
"res",
"=",
"res",
".",
"group",
"(",
"0",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"res",
")",
":",
"return",
"None",
"return",
"os",
".",
"path",
".",
"realpath",
"(",
"res",
")",
"def",
"_use_ldconfig",
"(",
"name",
")",
":",
"\"\"\"\n Find so in `ldconfig -p`.\n It does not handle LD_LIBRARY_PATH.\n \"\"\"",
"with",
"change_env",
"(",
"'LC_ALL'",
",",
"'C'",
")",
",",
"change_env",
"(",
"'LANG'",
",",
"'C'",
")",
":",
"ldconfig",
",",
"ret",
"=",
"subproc_call",
"(",
"\"ldconfig -p\"",
")",
"ldconfig",
"=",
"ldconfig",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"ret",
"!=",
"0",
":",
"return",
"None",
"expr",
"=",
"r'\\s+(lib%s\\.[^\\s]+)\\s+\\(.*=>\\s+(.*)'",
"%",
"(",
"re",
".",
"escape",
"(",
"name",
")",
")",
"res",
"=",
"re",
".",
"search",
"(",
"expr",
",",
"ldconfig",
")",
"if",
"not",
"res",
":",
"return",
"None",
"else",
":",
"ret",
"=",
"res",
".",
"group",
"(",
"2",
")",
"return",
"os",
".",
"path",
".",
"realpath",
"(",
"ret",
")",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'linux'",
")",
":",
"return",
"_use_proc_maps",
"(",
"name",
")",
"or",
"_use_ld",
"(",
"name",
")",
"or",
"_use_ldconfig",
"(",
"name",
")",
"or",
"find_library",
"(",
"name",
")",
"return",
"find_library",
"(",
"name",
")"
] | Similar to `from ctypes.util import find_library`, but try
to return full path if possible. | [
"Similar",
"to",
"from",
"ctypes",
".",
"util",
"import",
"find_library",
"but",
"try",
"to",
"return",
"full",
"path",
"if",
"possible",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L223-L293 |
27,331 | tensorpack/tensorpack | examples/DoReFa-Net/dorefa.py | get_dorefa | def get_dorefa(bitW, bitA, bitG):
"""
Return the three quantization functions fw, fa, fg, for weights, activations and gradients respectively
"""
def quantize(x, k):
n = float(2 ** k - 1)
@tf.custom_gradient
def _quantize(x):
return tf.round(x * n) / n, lambda dy: dy
return _quantize(x)
def fw(x):
if bitW == 32:
return x
if bitW == 1: # BWN
E = tf.stop_gradient(tf.reduce_mean(tf.abs(x)))
@tf.custom_gradient
def _sign(x):
return tf.where(tf.equal(x, 0), tf.ones_like(x), tf.sign(x / E)) * E, lambda dy: dy
return _sign(x)
x = tf.tanh(x)
x = x / tf.reduce_max(tf.abs(x)) * 0.5 + 0.5
return 2 * quantize(x, bitW) - 1
def fa(x):
if bitA == 32:
return x
return quantize(x, bitA)
def fg(x):
if bitG == 32:
return x
@tf.custom_gradient
def _identity(input):
def grad_fg(x):
rank = x.get_shape().ndims
assert rank is not None
maxx = tf.reduce_max(tf.abs(x), list(range(1, rank)), keep_dims=True)
x = x / maxx
n = float(2**bitG - 1)
x = x * 0.5 + 0.5 + tf.random_uniform(
tf.shape(x), minval=-0.5 / n, maxval=0.5 / n)
x = tf.clip_by_value(x, 0.0, 1.0)
x = quantize(x, bitG) - 0.5
return x * maxx * 2
return input, grad_fg
return _identity(x)
return fw, fa, fg | python | def get_dorefa(bitW, bitA, bitG):
"""
Return the three quantization functions fw, fa, fg, for weights, activations and gradients respectively
"""
def quantize(x, k):
n = float(2 ** k - 1)
@tf.custom_gradient
def _quantize(x):
return tf.round(x * n) / n, lambda dy: dy
return _quantize(x)
def fw(x):
if bitW == 32:
return x
if bitW == 1: # BWN
E = tf.stop_gradient(tf.reduce_mean(tf.abs(x)))
@tf.custom_gradient
def _sign(x):
return tf.where(tf.equal(x, 0), tf.ones_like(x), tf.sign(x / E)) * E, lambda dy: dy
return _sign(x)
x = tf.tanh(x)
x = x / tf.reduce_max(tf.abs(x)) * 0.5 + 0.5
return 2 * quantize(x, bitW) - 1
def fa(x):
if bitA == 32:
return x
return quantize(x, bitA)
def fg(x):
if bitG == 32:
return x
@tf.custom_gradient
def _identity(input):
def grad_fg(x):
rank = x.get_shape().ndims
assert rank is not None
maxx = tf.reduce_max(tf.abs(x), list(range(1, rank)), keep_dims=True)
x = x / maxx
n = float(2**bitG - 1)
x = x * 0.5 + 0.5 + tf.random_uniform(
tf.shape(x), minval=-0.5 / n, maxval=0.5 / n)
x = tf.clip_by_value(x, 0.0, 1.0)
x = quantize(x, bitG) - 0.5
return x * maxx * 2
return input, grad_fg
return _identity(x)
return fw, fa, fg | [
"def",
"get_dorefa",
"(",
"bitW",
",",
"bitA",
",",
"bitG",
")",
":",
"def",
"quantize",
"(",
"x",
",",
"k",
")",
":",
"n",
"=",
"float",
"(",
"2",
"**",
"k",
"-",
"1",
")",
"@",
"tf",
".",
"custom_gradient",
"def",
"_quantize",
"(",
"x",
")",
":",
"return",
"tf",
".",
"round",
"(",
"x",
"*",
"n",
")",
"/",
"n",
",",
"lambda",
"dy",
":",
"dy",
"return",
"_quantize",
"(",
"x",
")",
"def",
"fw",
"(",
"x",
")",
":",
"if",
"bitW",
"==",
"32",
":",
"return",
"x",
"if",
"bitW",
"==",
"1",
":",
"# BWN",
"E",
"=",
"tf",
".",
"stop_gradient",
"(",
"tf",
".",
"reduce_mean",
"(",
"tf",
".",
"abs",
"(",
"x",
")",
")",
")",
"@",
"tf",
".",
"custom_gradient",
"def",
"_sign",
"(",
"x",
")",
":",
"return",
"tf",
".",
"where",
"(",
"tf",
".",
"equal",
"(",
"x",
",",
"0",
")",
",",
"tf",
".",
"ones_like",
"(",
"x",
")",
",",
"tf",
".",
"sign",
"(",
"x",
"/",
"E",
")",
")",
"*",
"E",
",",
"lambda",
"dy",
":",
"dy",
"return",
"_sign",
"(",
"x",
")",
"x",
"=",
"tf",
".",
"tanh",
"(",
"x",
")",
"x",
"=",
"x",
"/",
"tf",
".",
"reduce_max",
"(",
"tf",
".",
"abs",
"(",
"x",
")",
")",
"*",
"0.5",
"+",
"0.5",
"return",
"2",
"*",
"quantize",
"(",
"x",
",",
"bitW",
")",
"-",
"1",
"def",
"fa",
"(",
"x",
")",
":",
"if",
"bitA",
"==",
"32",
":",
"return",
"x",
"return",
"quantize",
"(",
"x",
",",
"bitA",
")",
"def",
"fg",
"(",
"x",
")",
":",
"if",
"bitG",
"==",
"32",
":",
"return",
"x",
"@",
"tf",
".",
"custom_gradient",
"def",
"_identity",
"(",
"input",
")",
":",
"def",
"grad_fg",
"(",
"x",
")",
":",
"rank",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"ndims",
"assert",
"rank",
"is",
"not",
"None",
"maxx",
"=",
"tf",
".",
"reduce_max",
"(",
"tf",
".",
"abs",
"(",
"x",
")",
",",
"list",
"(",
"range",
"(",
"1",
",",
"rank",
")",
")",
",",
"keep_dims",
"=",
"True",
")",
"x",
"=",
"x",
"/",
"maxx",
"n",
"=",
"float",
"(",
"2",
"**",
"bitG",
"-",
"1",
")",
"x",
"=",
"x",
"*",
"0.5",
"+",
"0.5",
"+",
"tf",
".",
"random_uniform",
"(",
"tf",
".",
"shape",
"(",
"x",
")",
",",
"minval",
"=",
"-",
"0.5",
"/",
"n",
",",
"maxval",
"=",
"0.5",
"/",
"n",
")",
"x",
"=",
"tf",
".",
"clip_by_value",
"(",
"x",
",",
"0.0",
",",
"1.0",
")",
"x",
"=",
"quantize",
"(",
"x",
",",
"bitG",
")",
"-",
"0.5",
"return",
"x",
"*",
"maxx",
"*",
"2",
"return",
"input",
",",
"grad_fg",
"return",
"_identity",
"(",
"x",
")",
"return",
"fw",
",",
"fa",
",",
"fg"
] | Return the three quantization functions fw, fa, fg, for weights, activations and gradients respectively | [
"Return",
"the",
"three",
"quantization",
"functions",
"fw",
"fa",
"fg",
"for",
"weights",
"activations",
"and",
"gradients",
"respectively"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DoReFa-Net/dorefa.py#L8-L64 |
27,332 | tensorpack/tensorpack | tensorpack/utils/viz.py | draw_text | def draw_text(img, pos, text, color, font_scale=0.4):
"""
Draw text on an image.
Args:
pos (tuple): x, y; the position of the text
text (str):
font_scale (float):
color (tuple): a 3-tuple BGR color in [0, 255]
"""
img = img.astype(np.uint8)
x0, y0 = int(pos[0]), int(pos[1])
# Compute text size.
font = cv2.FONT_HERSHEY_SIMPLEX
((text_w, text_h), _) = cv2.getTextSize(text, font, font_scale, 1)
# Place text background.
if x0 + text_w > img.shape[1]:
x0 = img.shape[1] - text_w
if y0 - int(1.15 * text_h) < 0:
y0 = int(1.15 * text_h)
back_topleft = x0, y0 - int(1.3 * text_h)
back_bottomright = x0 + text_w, y0
cv2.rectangle(img, back_topleft, back_bottomright, color, -1)
# Show text.
text_bottomleft = x0, y0 - int(0.25 * text_h)
cv2.putText(img, text, text_bottomleft, font, font_scale, (222, 222, 222), lineType=cv2.LINE_AA)
return img | python | def draw_text(img, pos, text, color, font_scale=0.4):
"""
Draw text on an image.
Args:
pos (tuple): x, y; the position of the text
text (str):
font_scale (float):
color (tuple): a 3-tuple BGR color in [0, 255]
"""
img = img.astype(np.uint8)
x0, y0 = int(pos[0]), int(pos[1])
# Compute text size.
font = cv2.FONT_HERSHEY_SIMPLEX
((text_w, text_h), _) = cv2.getTextSize(text, font, font_scale, 1)
# Place text background.
if x0 + text_w > img.shape[1]:
x0 = img.shape[1] - text_w
if y0 - int(1.15 * text_h) < 0:
y0 = int(1.15 * text_h)
back_topleft = x0, y0 - int(1.3 * text_h)
back_bottomright = x0 + text_w, y0
cv2.rectangle(img, back_topleft, back_bottomright, color, -1)
# Show text.
text_bottomleft = x0, y0 - int(0.25 * text_h)
cv2.putText(img, text, text_bottomleft, font, font_scale, (222, 222, 222), lineType=cv2.LINE_AA)
return img | [
"def",
"draw_text",
"(",
"img",
",",
"pos",
",",
"text",
",",
"color",
",",
"font_scale",
"=",
"0.4",
")",
":",
"img",
"=",
"img",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
"x0",
",",
"y0",
"=",
"int",
"(",
"pos",
"[",
"0",
"]",
")",
",",
"int",
"(",
"pos",
"[",
"1",
"]",
")",
"# Compute text size.",
"font",
"=",
"cv2",
".",
"FONT_HERSHEY_SIMPLEX",
"(",
"(",
"text_w",
",",
"text_h",
")",
",",
"_",
")",
"=",
"cv2",
".",
"getTextSize",
"(",
"text",
",",
"font",
",",
"font_scale",
",",
"1",
")",
"# Place text background.",
"if",
"x0",
"+",
"text_w",
">",
"img",
".",
"shape",
"[",
"1",
"]",
":",
"x0",
"=",
"img",
".",
"shape",
"[",
"1",
"]",
"-",
"text_w",
"if",
"y0",
"-",
"int",
"(",
"1.15",
"*",
"text_h",
")",
"<",
"0",
":",
"y0",
"=",
"int",
"(",
"1.15",
"*",
"text_h",
")",
"back_topleft",
"=",
"x0",
",",
"y0",
"-",
"int",
"(",
"1.3",
"*",
"text_h",
")",
"back_bottomright",
"=",
"x0",
"+",
"text_w",
",",
"y0",
"cv2",
".",
"rectangle",
"(",
"img",
",",
"back_topleft",
",",
"back_bottomright",
",",
"color",
",",
"-",
"1",
")",
"# Show text.",
"text_bottomleft",
"=",
"x0",
",",
"y0",
"-",
"int",
"(",
"0.25",
"*",
"text_h",
")",
"cv2",
".",
"putText",
"(",
"img",
",",
"text",
",",
"text_bottomleft",
",",
"font",
",",
"font_scale",
",",
"(",
"222",
",",
"222",
",",
"222",
")",
",",
"lineType",
"=",
"cv2",
".",
"LINE_AA",
")",
"return",
"img"
] | Draw text on an image.
Args:
pos (tuple): x, y; the position of the text
text (str):
font_scale (float):
color (tuple): a 3-tuple BGR color in [0, 255] | [
"Draw",
"text",
"on",
"an",
"image",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/viz.py#L353-L379 |
27,333 | tensorpack/tensorpack | examples/FasterRCNN/common.py | segmentation_to_mask | def segmentation_to_mask(polys, height, width):
"""
Convert polygons to binary masks.
Args:
polys: a list of nx2 float array. Each array contains many (x, y) coordinates.
Returns:
a binary matrix of (height, width)
"""
polys = [p.flatten().tolist() for p in polys]
assert len(polys) > 0, "Polygons are empty!"
import pycocotools.mask as cocomask
rles = cocomask.frPyObjects(polys, height, width)
rle = cocomask.merge(rles)
return cocomask.decode(rle) | python | def segmentation_to_mask(polys, height, width):
"""
Convert polygons to binary masks.
Args:
polys: a list of nx2 float array. Each array contains many (x, y) coordinates.
Returns:
a binary matrix of (height, width)
"""
polys = [p.flatten().tolist() for p in polys]
assert len(polys) > 0, "Polygons are empty!"
import pycocotools.mask as cocomask
rles = cocomask.frPyObjects(polys, height, width)
rle = cocomask.merge(rles)
return cocomask.decode(rle) | [
"def",
"segmentation_to_mask",
"(",
"polys",
",",
"height",
",",
"width",
")",
":",
"polys",
"=",
"[",
"p",
".",
"flatten",
"(",
")",
".",
"tolist",
"(",
")",
"for",
"p",
"in",
"polys",
"]",
"assert",
"len",
"(",
"polys",
")",
">",
"0",
",",
"\"Polygons are empty!\"",
"import",
"pycocotools",
".",
"mask",
"as",
"cocomask",
"rles",
"=",
"cocomask",
".",
"frPyObjects",
"(",
"polys",
",",
"height",
",",
"width",
")",
"rle",
"=",
"cocomask",
".",
"merge",
"(",
"rles",
")",
"return",
"cocomask",
".",
"decode",
"(",
"rle",
")"
] | Convert polygons to binary masks.
Args:
polys: a list of nx2 float array. Each array contains many (x, y) coordinates.
Returns:
a binary matrix of (height, width) | [
"Convert",
"polygons",
"to",
"binary",
"masks",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/common.py#L91-L107 |
27,334 | tensorpack/tensorpack | tensorpack/models/pool.py | MaxPooling | def MaxPooling(
inputs,
pool_size,
strides=None,
padding='valid',
data_format='channels_last'):
"""
Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size.
"""
if strides is None:
strides = pool_size
layer = tf.layers.MaxPooling2D(pool_size, strides, padding=padding, data_format=data_format)
ret = layer.apply(inputs, scope=tf.get_variable_scope())
return tf.identity(ret, name='output') | python | def MaxPooling(
inputs,
pool_size,
strides=None,
padding='valid',
data_format='channels_last'):
"""
Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size.
"""
if strides is None:
strides = pool_size
layer = tf.layers.MaxPooling2D(pool_size, strides, padding=padding, data_format=data_format)
ret = layer.apply(inputs, scope=tf.get_variable_scope())
return tf.identity(ret, name='output') | [
"def",
"MaxPooling",
"(",
"inputs",
",",
"pool_size",
",",
"strides",
"=",
"None",
",",
"padding",
"=",
"'valid'",
",",
"data_format",
"=",
"'channels_last'",
")",
":",
"if",
"strides",
"is",
"None",
":",
"strides",
"=",
"pool_size",
"layer",
"=",
"tf",
".",
"layers",
".",
"MaxPooling2D",
"(",
"pool_size",
",",
"strides",
",",
"padding",
"=",
"padding",
",",
"data_format",
"=",
"data_format",
")",
"ret",
"=",
"layer",
".",
"apply",
"(",
"inputs",
",",
"scope",
"=",
"tf",
".",
"get_variable_scope",
"(",
")",
")",
"return",
"tf",
".",
"identity",
"(",
"ret",
",",
"name",
"=",
"'output'",
")"
] | Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size. | [
"Same",
"as",
"tf",
".",
"layers",
".",
"MaxPooling2D",
".",
"Default",
"strides",
"is",
"equal",
"to",
"pool_size",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/pool.py#L21-L34 |
27,335 | tensorpack/tensorpack | tensorpack/models/pool.py | AvgPooling | def AvgPooling(
inputs,
pool_size,
strides=None,
padding='valid',
data_format='channels_last'):
"""
Same as `tf.layers.AveragePooling2D`. Default strides is equal to pool_size.
"""
if strides is None:
strides = pool_size
layer = tf.layers.AveragePooling2D(pool_size, strides, padding=padding, data_format=data_format)
ret = layer.apply(inputs, scope=tf.get_variable_scope())
return tf.identity(ret, name='output') | python | def AvgPooling(
inputs,
pool_size,
strides=None,
padding='valid',
data_format='channels_last'):
"""
Same as `tf.layers.AveragePooling2D`. Default strides is equal to pool_size.
"""
if strides is None:
strides = pool_size
layer = tf.layers.AveragePooling2D(pool_size, strides, padding=padding, data_format=data_format)
ret = layer.apply(inputs, scope=tf.get_variable_scope())
return tf.identity(ret, name='output') | [
"def",
"AvgPooling",
"(",
"inputs",
",",
"pool_size",
",",
"strides",
"=",
"None",
",",
"padding",
"=",
"'valid'",
",",
"data_format",
"=",
"'channels_last'",
")",
":",
"if",
"strides",
"is",
"None",
":",
"strides",
"=",
"pool_size",
"layer",
"=",
"tf",
".",
"layers",
".",
"AveragePooling2D",
"(",
"pool_size",
",",
"strides",
",",
"padding",
"=",
"padding",
",",
"data_format",
"=",
"data_format",
")",
"ret",
"=",
"layer",
".",
"apply",
"(",
"inputs",
",",
"scope",
"=",
"tf",
".",
"get_variable_scope",
"(",
")",
")",
"return",
"tf",
".",
"identity",
"(",
"ret",
",",
"name",
"=",
"'output'",
")"
] | Same as `tf.layers.AveragePooling2D`. Default strides is equal to pool_size. | [
"Same",
"as",
"tf",
".",
"layers",
".",
"AveragePooling2D",
".",
"Default",
"strides",
"is",
"equal",
"to",
"pool_size",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/pool.py#L41-L54 |
27,336 | tensorpack/tensorpack | tensorpack/models/pool.py | FixedUnPooling | def FixedUnPooling(x, shape, unpool_mat=None, data_format='channels_last'):
"""
Unpool the input with a fixed matrix to perform kronecker product with.
Args:
x (tf.Tensor): a 4D image tensor
shape: int or (h, w) tuple
unpool_mat: a tf.Tensor or np.ndarray 2D matrix with size=shape.
If is None, will use a matrix with 1 at top-left corner.
Returns:
tf.Tensor: a 4D image tensor.
"""
data_format = get_data_format(data_format, keras_mode=False)
shape = shape2d(shape)
output_shape = StaticDynamicShape(x)
output_shape.apply(1 if data_format == 'NHWC' else 2, lambda x: x * shape[0])
output_shape.apply(2 if data_format == 'NHWC' else 3, lambda x: x * shape[1])
# a faster implementation for this special case
if shape[0] == 2 and shape[1] == 2 and unpool_mat is None and data_format == 'NHWC':
ret = UnPooling2x2ZeroFilled(x)
else:
# check unpool_mat
if unpool_mat is None:
mat = np.zeros(shape, dtype='float32')
mat[0][0] = 1
unpool_mat = tf.constant(mat, name='unpool_mat')
elif isinstance(unpool_mat, np.ndarray):
unpool_mat = tf.constant(unpool_mat, name='unpool_mat')
assert unpool_mat.shape.as_list() == list(shape)
if data_format == 'NHWC':
x = tf.transpose(x, [0, 3, 1, 2])
# perform a tensor-matrix kronecker product
x = tf.expand_dims(x, -1) # bchwx1
mat = tf.expand_dims(unpool_mat, 0) # 1xshxsw
ret = tf.tensordot(x, mat, axes=1) # bxcxhxwxshxsw
if data_format == 'NHWC':
ret = tf.transpose(ret, [0, 2, 4, 3, 5, 1])
else:
ret = tf.transpose(ret, [0, 1, 2, 4, 3, 5])
shape3_dyn = [output_shape.get_dynamic(k) for k in range(1, 4)]
ret = tf.reshape(ret, tf.stack([-1] + shape3_dyn))
ret.set_shape(tf.TensorShape(output_shape.get_static()))
return ret | python | def FixedUnPooling(x, shape, unpool_mat=None, data_format='channels_last'):
"""
Unpool the input with a fixed matrix to perform kronecker product with.
Args:
x (tf.Tensor): a 4D image tensor
shape: int or (h, w) tuple
unpool_mat: a tf.Tensor or np.ndarray 2D matrix with size=shape.
If is None, will use a matrix with 1 at top-left corner.
Returns:
tf.Tensor: a 4D image tensor.
"""
data_format = get_data_format(data_format, keras_mode=False)
shape = shape2d(shape)
output_shape = StaticDynamicShape(x)
output_shape.apply(1 if data_format == 'NHWC' else 2, lambda x: x * shape[0])
output_shape.apply(2 if data_format == 'NHWC' else 3, lambda x: x * shape[1])
# a faster implementation for this special case
if shape[0] == 2 and shape[1] == 2 and unpool_mat is None and data_format == 'NHWC':
ret = UnPooling2x2ZeroFilled(x)
else:
# check unpool_mat
if unpool_mat is None:
mat = np.zeros(shape, dtype='float32')
mat[0][0] = 1
unpool_mat = tf.constant(mat, name='unpool_mat')
elif isinstance(unpool_mat, np.ndarray):
unpool_mat = tf.constant(unpool_mat, name='unpool_mat')
assert unpool_mat.shape.as_list() == list(shape)
if data_format == 'NHWC':
x = tf.transpose(x, [0, 3, 1, 2])
# perform a tensor-matrix kronecker product
x = tf.expand_dims(x, -1) # bchwx1
mat = tf.expand_dims(unpool_mat, 0) # 1xshxsw
ret = tf.tensordot(x, mat, axes=1) # bxcxhxwxshxsw
if data_format == 'NHWC':
ret = tf.transpose(ret, [0, 2, 4, 3, 5, 1])
else:
ret = tf.transpose(ret, [0, 1, 2, 4, 3, 5])
shape3_dyn = [output_shape.get_dynamic(k) for k in range(1, 4)]
ret = tf.reshape(ret, tf.stack([-1] + shape3_dyn))
ret.set_shape(tf.TensorShape(output_shape.get_static()))
return ret | [
"def",
"FixedUnPooling",
"(",
"x",
",",
"shape",
",",
"unpool_mat",
"=",
"None",
",",
"data_format",
"=",
"'channels_last'",
")",
":",
"data_format",
"=",
"get_data_format",
"(",
"data_format",
",",
"keras_mode",
"=",
"False",
")",
"shape",
"=",
"shape2d",
"(",
"shape",
")",
"output_shape",
"=",
"StaticDynamicShape",
"(",
"x",
")",
"output_shape",
".",
"apply",
"(",
"1",
"if",
"data_format",
"==",
"'NHWC'",
"else",
"2",
",",
"lambda",
"x",
":",
"x",
"*",
"shape",
"[",
"0",
"]",
")",
"output_shape",
".",
"apply",
"(",
"2",
"if",
"data_format",
"==",
"'NHWC'",
"else",
"3",
",",
"lambda",
"x",
":",
"x",
"*",
"shape",
"[",
"1",
"]",
")",
"# a faster implementation for this special case",
"if",
"shape",
"[",
"0",
"]",
"==",
"2",
"and",
"shape",
"[",
"1",
"]",
"==",
"2",
"and",
"unpool_mat",
"is",
"None",
"and",
"data_format",
"==",
"'NHWC'",
":",
"ret",
"=",
"UnPooling2x2ZeroFilled",
"(",
"x",
")",
"else",
":",
"# check unpool_mat",
"if",
"unpool_mat",
"is",
"None",
":",
"mat",
"=",
"np",
".",
"zeros",
"(",
"shape",
",",
"dtype",
"=",
"'float32'",
")",
"mat",
"[",
"0",
"]",
"[",
"0",
"]",
"=",
"1",
"unpool_mat",
"=",
"tf",
".",
"constant",
"(",
"mat",
",",
"name",
"=",
"'unpool_mat'",
")",
"elif",
"isinstance",
"(",
"unpool_mat",
",",
"np",
".",
"ndarray",
")",
":",
"unpool_mat",
"=",
"tf",
".",
"constant",
"(",
"unpool_mat",
",",
"name",
"=",
"'unpool_mat'",
")",
"assert",
"unpool_mat",
".",
"shape",
".",
"as_list",
"(",
")",
"==",
"list",
"(",
"shape",
")",
"if",
"data_format",
"==",
"'NHWC'",
":",
"x",
"=",
"tf",
".",
"transpose",
"(",
"x",
",",
"[",
"0",
",",
"3",
",",
"1",
",",
"2",
"]",
")",
"# perform a tensor-matrix kronecker product",
"x",
"=",
"tf",
".",
"expand_dims",
"(",
"x",
",",
"-",
"1",
")",
"# bchwx1",
"mat",
"=",
"tf",
".",
"expand_dims",
"(",
"unpool_mat",
",",
"0",
")",
"# 1xshxsw",
"ret",
"=",
"tf",
".",
"tensordot",
"(",
"x",
",",
"mat",
",",
"axes",
"=",
"1",
")",
"# bxcxhxwxshxsw",
"if",
"data_format",
"==",
"'NHWC'",
":",
"ret",
"=",
"tf",
".",
"transpose",
"(",
"ret",
",",
"[",
"0",
",",
"2",
",",
"4",
",",
"3",
",",
"5",
",",
"1",
"]",
")",
"else",
":",
"ret",
"=",
"tf",
".",
"transpose",
"(",
"ret",
",",
"[",
"0",
",",
"1",
",",
"2",
",",
"4",
",",
"3",
",",
"5",
"]",
")",
"shape3_dyn",
"=",
"[",
"output_shape",
".",
"get_dynamic",
"(",
"k",
")",
"for",
"k",
"in",
"range",
"(",
"1",
",",
"4",
")",
"]",
"ret",
"=",
"tf",
".",
"reshape",
"(",
"ret",
",",
"tf",
".",
"stack",
"(",
"[",
"-",
"1",
"]",
"+",
"shape3_dyn",
")",
")",
"ret",
".",
"set_shape",
"(",
"tf",
".",
"TensorShape",
"(",
"output_shape",
".",
"get_static",
"(",
")",
")",
")",
"return",
"ret"
] | Unpool the input with a fixed matrix to perform kronecker product with.
Args:
x (tf.Tensor): a 4D image tensor
shape: int or (h, w) tuple
unpool_mat: a tf.Tensor or np.ndarray 2D matrix with size=shape.
If is None, will use a matrix with 1 at top-left corner.
Returns:
tf.Tensor: a 4D image tensor. | [
"Unpool",
"the",
"input",
"with",
"a",
"fixed",
"matrix",
"to",
"perform",
"kronecker",
"product",
"with",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/pool.py#L91-L140 |
27,337 | tensorpack/tensorpack | tensorpack/tfutils/varmanip.py | save_chkpt_vars | def save_chkpt_vars(dic, path):
"""
Save variables in dic to path.
Args:
dic: {name: value}
path: save as npz if the name ends with '.npz', otherwise save as a checkpoint.
"""
logger.info("Variables to save to {}:".format(path))
keys = sorted(list(dic.keys()))
logger.info(pprint.pformat(keys))
assert not path.endswith('.npy')
if path.endswith('.npz'):
np.savez_compressed(path, **dic)
else:
with tf.Graph().as_default(), \
tf.Session() as sess:
for k, v in six.iteritems(dic):
k = get_op_tensor_name(k)[0]
_ = tf.Variable(name=k, initial_value=v) # noqa
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver()
saver.save(sess, path, write_meta_graph=False) | python | def save_chkpt_vars(dic, path):
"""
Save variables in dic to path.
Args:
dic: {name: value}
path: save as npz if the name ends with '.npz', otherwise save as a checkpoint.
"""
logger.info("Variables to save to {}:".format(path))
keys = sorted(list(dic.keys()))
logger.info(pprint.pformat(keys))
assert not path.endswith('.npy')
if path.endswith('.npz'):
np.savez_compressed(path, **dic)
else:
with tf.Graph().as_default(), \
tf.Session() as sess:
for k, v in six.iteritems(dic):
k = get_op_tensor_name(k)[0]
_ = tf.Variable(name=k, initial_value=v) # noqa
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver()
saver.save(sess, path, write_meta_graph=False) | [
"def",
"save_chkpt_vars",
"(",
"dic",
",",
"path",
")",
":",
"logger",
".",
"info",
"(",
"\"Variables to save to {}:\"",
".",
"format",
"(",
"path",
")",
")",
"keys",
"=",
"sorted",
"(",
"list",
"(",
"dic",
".",
"keys",
"(",
")",
")",
")",
"logger",
".",
"info",
"(",
"pprint",
".",
"pformat",
"(",
"keys",
")",
")",
"assert",
"not",
"path",
".",
"endswith",
"(",
"'.npy'",
")",
"if",
"path",
".",
"endswith",
"(",
"'.npz'",
")",
":",
"np",
".",
"savez_compressed",
"(",
"path",
",",
"*",
"*",
"dic",
")",
"else",
":",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
",",
"tf",
".",
"Session",
"(",
")",
"as",
"sess",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"dic",
")",
":",
"k",
"=",
"get_op_tensor_name",
"(",
"k",
")",
"[",
"0",
"]",
"_",
"=",
"tf",
".",
"Variable",
"(",
"name",
"=",
"k",
",",
"initial_value",
"=",
"v",
")",
"# noqa",
"sess",
".",
"run",
"(",
"tf",
".",
"global_variables_initializer",
"(",
")",
")",
"saver",
"=",
"tf",
".",
"train",
".",
"Saver",
"(",
")",
"saver",
".",
"save",
"(",
"sess",
",",
"path",
",",
"write_meta_graph",
"=",
"False",
")"
] | Save variables in dic to path.
Args:
dic: {name: value}
path: save as npz if the name ends with '.npz', otherwise save as a checkpoint. | [
"Save",
"variables",
"in",
"dic",
"to",
"path",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L140-L163 |
27,338 | tensorpack/tensorpack | tensorpack/tfutils/varmanip.py | get_checkpoint_path | def get_checkpoint_path(model_path):
"""
Work around TF problems in checkpoint path handling.
Args:
model_path: a user-input path
Returns:
str: the argument that can be passed to NewCheckpointReader
"""
if os.path.basename(model_path) == model_path:
model_path = os.path.join('.', model_path) # avoid #4921 and #6142
if os.path.basename(model_path) == 'checkpoint':
assert tfv1.gfile.Exists(model_path), model_path
model_path = tf.train.latest_checkpoint(os.path.dirname(model_path))
# to be consistent with either v1 or v2
# fix paths if provided a wrong one
new_path = model_path
if '00000-of-00001' in model_path:
new_path = model_path.split('.data')[0]
elif model_path.endswith('.index'):
new_path = model_path.split('.index')[0]
if new_path != model_path:
logger.info(
"Checkpoint path {} is auto-corrected to {}.".format(model_path, new_path))
model_path = new_path
assert tfv1.gfile.Exists(model_path) or tfv1.gfile.Exists(model_path + '.index'), model_path
return model_path | python | def get_checkpoint_path(model_path):
"""
Work around TF problems in checkpoint path handling.
Args:
model_path: a user-input path
Returns:
str: the argument that can be passed to NewCheckpointReader
"""
if os.path.basename(model_path) == model_path:
model_path = os.path.join('.', model_path) # avoid #4921 and #6142
if os.path.basename(model_path) == 'checkpoint':
assert tfv1.gfile.Exists(model_path), model_path
model_path = tf.train.latest_checkpoint(os.path.dirname(model_path))
# to be consistent with either v1 or v2
# fix paths if provided a wrong one
new_path = model_path
if '00000-of-00001' in model_path:
new_path = model_path.split('.data')[0]
elif model_path.endswith('.index'):
new_path = model_path.split('.index')[0]
if new_path != model_path:
logger.info(
"Checkpoint path {} is auto-corrected to {}.".format(model_path, new_path))
model_path = new_path
assert tfv1.gfile.Exists(model_path) or tfv1.gfile.Exists(model_path + '.index'), model_path
return model_path | [
"def",
"get_checkpoint_path",
"(",
"model_path",
")",
":",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"model_path",
")",
"==",
"model_path",
":",
"model_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'.'",
",",
"model_path",
")",
"# avoid #4921 and #6142",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"model_path",
")",
"==",
"'checkpoint'",
":",
"assert",
"tfv1",
".",
"gfile",
".",
"Exists",
"(",
"model_path",
")",
",",
"model_path",
"model_path",
"=",
"tf",
".",
"train",
".",
"latest_checkpoint",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"model_path",
")",
")",
"# to be consistent with either v1 or v2",
"# fix paths if provided a wrong one",
"new_path",
"=",
"model_path",
"if",
"'00000-of-00001'",
"in",
"model_path",
":",
"new_path",
"=",
"model_path",
".",
"split",
"(",
"'.data'",
")",
"[",
"0",
"]",
"elif",
"model_path",
".",
"endswith",
"(",
"'.index'",
")",
":",
"new_path",
"=",
"model_path",
".",
"split",
"(",
"'.index'",
")",
"[",
"0",
"]",
"if",
"new_path",
"!=",
"model_path",
":",
"logger",
".",
"info",
"(",
"\"Checkpoint path {} is auto-corrected to {}.\"",
".",
"format",
"(",
"model_path",
",",
"new_path",
")",
")",
"model_path",
"=",
"new_path",
"assert",
"tfv1",
".",
"gfile",
".",
"Exists",
"(",
"model_path",
")",
"or",
"tfv1",
".",
"gfile",
".",
"Exists",
"(",
"model_path",
"+",
"'.index'",
")",
",",
"model_path",
"return",
"model_path"
] | Work around TF problems in checkpoint path handling.
Args:
model_path: a user-input path
Returns:
str: the argument that can be passed to NewCheckpointReader | [
"Work",
"around",
"TF",
"problems",
"in",
"checkpoint",
"path",
"handling",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L166-L193 |
27,339 | tensorpack/tensorpack | tensorpack/tfutils/varmanip.py | load_chkpt_vars | def load_chkpt_vars(model_path):
""" Load all variables from a checkpoint to a dict.
Args:
model_path(str): path to a checkpoint.
Returns:
dict: a name:value dict
"""
model_path = get_checkpoint_path(model_path)
reader = tfv1.train.NewCheckpointReader(model_path)
var_names = reader.get_variable_to_shape_map().keys()
result = {}
for n in var_names:
result[n] = reader.get_tensor(n)
return result | python | def load_chkpt_vars(model_path):
""" Load all variables from a checkpoint to a dict.
Args:
model_path(str): path to a checkpoint.
Returns:
dict: a name:value dict
"""
model_path = get_checkpoint_path(model_path)
reader = tfv1.train.NewCheckpointReader(model_path)
var_names = reader.get_variable_to_shape_map().keys()
result = {}
for n in var_names:
result[n] = reader.get_tensor(n)
return result | [
"def",
"load_chkpt_vars",
"(",
"model_path",
")",
":",
"model_path",
"=",
"get_checkpoint_path",
"(",
"model_path",
")",
"reader",
"=",
"tfv1",
".",
"train",
".",
"NewCheckpointReader",
"(",
"model_path",
")",
"var_names",
"=",
"reader",
".",
"get_variable_to_shape_map",
"(",
")",
".",
"keys",
"(",
")",
"result",
"=",
"{",
"}",
"for",
"n",
"in",
"var_names",
":",
"result",
"[",
"n",
"]",
"=",
"reader",
".",
"get_tensor",
"(",
"n",
")",
"return",
"result"
] | Load all variables from a checkpoint to a dict.
Args:
model_path(str): path to a checkpoint.
Returns:
dict: a name:value dict | [
"Load",
"all",
"variables",
"from",
"a",
"checkpoint",
"to",
"a",
"dict",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L196-L211 |
27,340 | tensorpack/tensorpack | tensorpack/callbacks/monitor.py | Monitors.put_summary | def put_summary(self, summary):
"""
Put a `tf.Summary`.
"""
if isinstance(summary, six.binary_type):
summary = tf.Summary.FromString(summary)
assert isinstance(summary, tf.Summary), type(summary)
# TODO other types
for val in summary.value:
if val.WhichOneof('value') == 'simple_value':
val.tag = re.sub('tower[0-9]+/', '', val.tag) # TODO move to subclasses
# TODO This hack is still needed, seem to disappear only when
# compiled from source.
suffix = '-summary' # tensorflow#6150, tensorboard#59
if val.tag.endswith(suffix):
val.tag = val.tag[:-len(suffix)]
self._dispatch(lambda m: m.process_scalar(val.tag, val.simple_value))
self._dispatch(lambda m: m.process_summary(summary)) | python | def put_summary(self, summary):
"""
Put a `tf.Summary`.
"""
if isinstance(summary, six.binary_type):
summary = tf.Summary.FromString(summary)
assert isinstance(summary, tf.Summary), type(summary)
# TODO other types
for val in summary.value:
if val.WhichOneof('value') == 'simple_value':
val.tag = re.sub('tower[0-9]+/', '', val.tag) # TODO move to subclasses
# TODO This hack is still needed, seem to disappear only when
# compiled from source.
suffix = '-summary' # tensorflow#6150, tensorboard#59
if val.tag.endswith(suffix):
val.tag = val.tag[:-len(suffix)]
self._dispatch(lambda m: m.process_scalar(val.tag, val.simple_value))
self._dispatch(lambda m: m.process_summary(summary)) | [
"def",
"put_summary",
"(",
"self",
",",
"summary",
")",
":",
"if",
"isinstance",
"(",
"summary",
",",
"six",
".",
"binary_type",
")",
":",
"summary",
"=",
"tf",
".",
"Summary",
".",
"FromString",
"(",
"summary",
")",
"assert",
"isinstance",
"(",
"summary",
",",
"tf",
".",
"Summary",
")",
",",
"type",
"(",
"summary",
")",
"# TODO other types",
"for",
"val",
"in",
"summary",
".",
"value",
":",
"if",
"val",
".",
"WhichOneof",
"(",
"'value'",
")",
"==",
"'simple_value'",
":",
"val",
".",
"tag",
"=",
"re",
".",
"sub",
"(",
"'tower[0-9]+/'",
",",
"''",
",",
"val",
".",
"tag",
")",
"# TODO move to subclasses",
"# TODO This hack is still needed, seem to disappear only when",
"# compiled from source.",
"suffix",
"=",
"'-summary'",
"# tensorflow#6150, tensorboard#59",
"if",
"val",
".",
"tag",
".",
"endswith",
"(",
"suffix",
")",
":",
"val",
".",
"tag",
"=",
"val",
".",
"tag",
"[",
":",
"-",
"len",
"(",
"suffix",
")",
"]",
"self",
".",
"_dispatch",
"(",
"lambda",
"m",
":",
"m",
".",
"process_scalar",
"(",
"val",
".",
"tag",
",",
"val",
".",
"simple_value",
")",
")",
"self",
".",
"_dispatch",
"(",
"lambda",
"m",
":",
"m",
".",
"process_summary",
"(",
"summary",
")",
")"
] | Put a `tf.Summary`. | [
"Put",
"a",
"tf",
".",
"Summary",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L143-L164 |
27,341 | tensorpack/tensorpack | tensorpack/callbacks/monitor.py | Monitors.put_scalar | def put_scalar(self, name, val):
"""
Put a scalar.
"""
if isinstance(val, np.floating):
val = float(val)
if isinstance(val, np.integer):
val = int(val)
self._dispatch(lambda m: m.process_scalar(name, val))
s = create_scalar_summary(name, val)
self._dispatch(lambda m: m.process_summary(s)) | python | def put_scalar(self, name, val):
"""
Put a scalar.
"""
if isinstance(val, np.floating):
val = float(val)
if isinstance(val, np.integer):
val = int(val)
self._dispatch(lambda m: m.process_scalar(name, val))
s = create_scalar_summary(name, val)
self._dispatch(lambda m: m.process_summary(s)) | [
"def",
"put_scalar",
"(",
"self",
",",
"name",
",",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"np",
".",
"floating",
")",
":",
"val",
"=",
"float",
"(",
"val",
")",
"if",
"isinstance",
"(",
"val",
",",
"np",
".",
"integer",
")",
":",
"val",
"=",
"int",
"(",
"val",
")",
"self",
".",
"_dispatch",
"(",
"lambda",
"m",
":",
"m",
".",
"process_scalar",
"(",
"name",
",",
"val",
")",
")",
"s",
"=",
"create_scalar_summary",
"(",
"name",
",",
"val",
")",
"self",
".",
"_dispatch",
"(",
"lambda",
"m",
":",
"m",
".",
"process_summary",
"(",
"s",
")",
")"
] | Put a scalar. | [
"Put",
"a",
"scalar",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L166-L176 |
27,342 | tensorpack/tensorpack | tensorpack/callbacks/monitor.py | Monitors.put_image | def put_image(self, name, val):
"""
Put an image.
Args:
name (str):
val (np.ndarray): 2D, 3D (HWC) or 4D (NHWC) numpy array of images
in range [0,255]. If channel is 3, assumed to be RGB.
"""
assert isinstance(val, np.ndarray)
arr = image_to_nhwc(val)
self._dispatch(lambda m: m.process_image(name, arr))
s = create_image_summary(name, arr)
self._dispatch(lambda m: m.process_summary(s)) | python | def put_image(self, name, val):
"""
Put an image.
Args:
name (str):
val (np.ndarray): 2D, 3D (HWC) or 4D (NHWC) numpy array of images
in range [0,255]. If channel is 3, assumed to be RGB.
"""
assert isinstance(val, np.ndarray)
arr = image_to_nhwc(val)
self._dispatch(lambda m: m.process_image(name, arr))
s = create_image_summary(name, arr)
self._dispatch(lambda m: m.process_summary(s)) | [
"def",
"put_image",
"(",
"self",
",",
"name",
",",
"val",
")",
":",
"assert",
"isinstance",
"(",
"val",
",",
"np",
".",
"ndarray",
")",
"arr",
"=",
"image_to_nhwc",
"(",
"val",
")",
"self",
".",
"_dispatch",
"(",
"lambda",
"m",
":",
"m",
".",
"process_image",
"(",
"name",
",",
"arr",
")",
")",
"s",
"=",
"create_image_summary",
"(",
"name",
",",
"arr",
")",
"self",
".",
"_dispatch",
"(",
"lambda",
"m",
":",
"m",
".",
"process_summary",
"(",
"s",
")",
")"
] | Put an image.
Args:
name (str):
val (np.ndarray): 2D, 3D (HWC) or 4D (NHWC) numpy array of images
in range [0,255]. If channel is 3, assumed to be RGB. | [
"Put",
"an",
"image",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L178-L191 |
27,343 | tensorpack/tensorpack | tensorpack/callbacks/monitor.py | JSONWriter._trigger | def _trigger(self):
"""
Add stats to json and dump to disk.
Note that this method is idempotent.
"""
if len(self._stat_now):
self._stat_now['epoch_num'] = self.epoch_num
self._stat_now['global_step'] = self.global_step
self._stats.append(self._stat_now)
self._stat_now = {}
self._write_stat() | python | def _trigger(self):
"""
Add stats to json and dump to disk.
Note that this method is idempotent.
"""
if len(self._stat_now):
self._stat_now['epoch_num'] = self.epoch_num
self._stat_now['global_step'] = self.global_step
self._stats.append(self._stat_now)
self._stat_now = {}
self._write_stat() | [
"def",
"_trigger",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_stat_now",
")",
":",
"self",
".",
"_stat_now",
"[",
"'epoch_num'",
"]",
"=",
"self",
".",
"epoch_num",
"self",
".",
"_stat_now",
"[",
"'global_step'",
"]",
"=",
"self",
".",
"global_step",
"self",
".",
"_stats",
".",
"append",
"(",
"self",
".",
"_stat_now",
")",
"self",
".",
"_stat_now",
"=",
"{",
"}",
"self",
".",
"_write_stat",
"(",
")"
] | Add stats to json and dump to disk.
Note that this method is idempotent. | [
"Add",
"stats",
"to",
"json",
"and",
"dump",
"to",
"disk",
".",
"Note",
"that",
"this",
"method",
"is",
"idempotent",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L378-L389 |
27,344 | tensorpack/tensorpack | tensorpack/utils/debug.py | enable_call_trace | def enable_call_trace():
""" Enable trace for calls to any function. """
def tracer(frame, event, arg):
if event == 'call':
co = frame.f_code
func_name = co.co_name
if func_name == 'write' or func_name == 'print':
# ignore write() calls from print statements
return
func_line_no = frame.f_lineno
func_filename = co.co_filename
caller = frame.f_back
if caller:
caller_line_no = caller.f_lineno
caller_filename = caller.f_code.co_filename
print('Call to `%s` on line %s:%s from %s:%s' %
(func_name, func_filename, func_line_no,
caller_filename, caller_line_no))
return
sys.settrace(tracer) | python | def enable_call_trace():
""" Enable trace for calls to any function. """
def tracer(frame, event, arg):
if event == 'call':
co = frame.f_code
func_name = co.co_name
if func_name == 'write' or func_name == 'print':
# ignore write() calls from print statements
return
func_line_no = frame.f_lineno
func_filename = co.co_filename
caller = frame.f_back
if caller:
caller_line_no = caller.f_lineno
caller_filename = caller.f_code.co_filename
print('Call to `%s` on line %s:%s from %s:%s' %
(func_name, func_filename, func_line_no,
caller_filename, caller_line_no))
return
sys.settrace(tracer) | [
"def",
"enable_call_trace",
"(",
")",
":",
"def",
"tracer",
"(",
"frame",
",",
"event",
",",
"arg",
")",
":",
"if",
"event",
"==",
"'call'",
":",
"co",
"=",
"frame",
".",
"f_code",
"func_name",
"=",
"co",
".",
"co_name",
"if",
"func_name",
"==",
"'write'",
"or",
"func_name",
"==",
"'print'",
":",
"# ignore write() calls from print statements",
"return",
"func_line_no",
"=",
"frame",
".",
"f_lineno",
"func_filename",
"=",
"co",
".",
"co_filename",
"caller",
"=",
"frame",
".",
"f_back",
"if",
"caller",
":",
"caller_line_no",
"=",
"caller",
".",
"f_lineno",
"caller_filename",
"=",
"caller",
".",
"f_code",
".",
"co_filename",
"print",
"(",
"'Call to `%s` on line %s:%s from %s:%s'",
"%",
"(",
"func_name",
",",
"func_filename",
",",
"func_line_no",
",",
"caller_filename",
",",
"caller_line_no",
")",
")",
"return",
"sys",
".",
"settrace",
"(",
"tracer",
")"
] | Enable trace for calls to any function. | [
"Enable",
"trace",
"for",
"calls",
"to",
"any",
"function",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/debug.py#L8-L27 |
27,345 | tensorpack/tensorpack | tensorpack/train/base.py | _get_property | def _get_property(name):
"""
Delegate property to self.loop
"""
ret = property(
lambda self: getattr(self.loop, name))
if six.PY3: # __doc__ is readonly in Py2
try:
ret.__doc__ = getattr(TrainLoop, name).__doc__
except AttributeError:
pass
return ret | python | def _get_property(name):
"""
Delegate property to self.loop
"""
ret = property(
lambda self: getattr(self.loop, name))
if six.PY3: # __doc__ is readonly in Py2
try:
ret.__doc__ = getattr(TrainLoop, name).__doc__
except AttributeError:
pass
return ret | [
"def",
"_get_property",
"(",
"name",
")",
":",
"ret",
"=",
"property",
"(",
"lambda",
"self",
":",
"getattr",
"(",
"self",
".",
"loop",
",",
"name",
")",
")",
"if",
"six",
".",
"PY3",
":",
"# __doc__ is readonly in Py2",
"try",
":",
"ret",
".",
"__doc__",
"=",
"getattr",
"(",
"TrainLoop",
",",
"name",
")",
".",
"__doc__",
"except",
"AttributeError",
":",
"pass",
"return",
"ret"
] | Delegate property to self.loop | [
"Delegate",
"property",
"to",
"self",
".",
"loop"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L357-L368 |
27,346 | tensorpack/tensorpack | tensorpack/train/base.py | TrainLoop.config | def config(self, steps_per_epoch, starting_epoch, max_epoch):
"""
Configure the loop given the settings.
"""
self.starting_epoch = int(starting_epoch)
self.max_epoch = int(max_epoch)
self.steps_per_epoch = int(steps_per_epoch)
# Allow empty epoch (no steps), if we want to run the callbacks only.
assert self.steps_per_epoch >= 0 and self.max_epoch >= 0
self._epoch_num = starting_epoch - 1 | python | def config(self, steps_per_epoch, starting_epoch, max_epoch):
"""
Configure the loop given the settings.
"""
self.starting_epoch = int(starting_epoch)
self.max_epoch = int(max_epoch)
self.steps_per_epoch = int(steps_per_epoch)
# Allow empty epoch (no steps), if we want to run the callbacks only.
assert self.steps_per_epoch >= 0 and self.max_epoch >= 0
self._epoch_num = starting_epoch - 1 | [
"def",
"config",
"(",
"self",
",",
"steps_per_epoch",
",",
"starting_epoch",
",",
"max_epoch",
")",
":",
"self",
".",
"starting_epoch",
"=",
"int",
"(",
"starting_epoch",
")",
"self",
".",
"max_epoch",
"=",
"int",
"(",
"max_epoch",
")",
"self",
".",
"steps_per_epoch",
"=",
"int",
"(",
"steps_per_epoch",
")",
"# Allow empty epoch (no steps), if we want to run the callbacks only.",
"assert",
"self",
".",
"steps_per_epoch",
">=",
"0",
"and",
"self",
".",
"max_epoch",
">=",
"0",
"self",
".",
"_epoch_num",
"=",
"starting_epoch",
"-",
"1"
] | Configure the loop given the settings. | [
"Configure",
"the",
"loop",
"given",
"the",
"settings",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L43-L53 |
27,347 | tensorpack/tensorpack | tensorpack/train/base.py | Trainer.setup_callbacks | def setup_callbacks(self, callbacks, monitors):
"""
Setup callbacks and monitors. Must be called after the main graph is built.
Args:
callbacks ([Callback]):
monitors ([MonitorBase]):
"""
assert isinstance(callbacks, list), callbacks
assert isinstance(monitors, list), monitors
describe_trainable_vars() # TODO weird
self.register_callback(MaintainStepCounter())
for cb in callbacks:
self.register_callback(cb)
for cb in self._callbacks:
assert not isinstance(cb, MonitorBase), "Monitor cannot be pre-registered for now!"
registered_monitors = []
for m in monitors:
if self.register_callback(m):
registered_monitors.append(m)
self.monitors = Monitors(registered_monitors)
self.register_callback(self.monitors) # monitors is also a callback
# some final operations that might modify the graph
logger.info("Setup callbacks graph ...")
self._callbacks = Callbacks(self._callbacks)
self._callbacks.setup_graph(weakref.proxy(self)) | python | def setup_callbacks(self, callbacks, monitors):
"""
Setup callbacks and monitors. Must be called after the main graph is built.
Args:
callbacks ([Callback]):
monitors ([MonitorBase]):
"""
assert isinstance(callbacks, list), callbacks
assert isinstance(monitors, list), monitors
describe_trainable_vars() # TODO weird
self.register_callback(MaintainStepCounter())
for cb in callbacks:
self.register_callback(cb)
for cb in self._callbacks:
assert not isinstance(cb, MonitorBase), "Monitor cannot be pre-registered for now!"
registered_monitors = []
for m in monitors:
if self.register_callback(m):
registered_monitors.append(m)
self.monitors = Monitors(registered_monitors)
self.register_callback(self.monitors) # monitors is also a callback
# some final operations that might modify the graph
logger.info("Setup callbacks graph ...")
self._callbacks = Callbacks(self._callbacks)
self._callbacks.setup_graph(weakref.proxy(self)) | [
"def",
"setup_callbacks",
"(",
"self",
",",
"callbacks",
",",
"monitors",
")",
":",
"assert",
"isinstance",
"(",
"callbacks",
",",
"list",
")",
",",
"callbacks",
"assert",
"isinstance",
"(",
"monitors",
",",
"list",
")",
",",
"monitors",
"describe_trainable_vars",
"(",
")",
"# TODO weird",
"self",
".",
"register_callback",
"(",
"MaintainStepCounter",
"(",
")",
")",
"for",
"cb",
"in",
"callbacks",
":",
"self",
".",
"register_callback",
"(",
"cb",
")",
"for",
"cb",
"in",
"self",
".",
"_callbacks",
":",
"assert",
"not",
"isinstance",
"(",
"cb",
",",
"MonitorBase",
")",
",",
"\"Monitor cannot be pre-registered for now!\"",
"registered_monitors",
"=",
"[",
"]",
"for",
"m",
"in",
"monitors",
":",
"if",
"self",
".",
"register_callback",
"(",
"m",
")",
":",
"registered_monitors",
".",
"append",
"(",
"m",
")",
"self",
".",
"monitors",
"=",
"Monitors",
"(",
"registered_monitors",
")",
"self",
".",
"register_callback",
"(",
"self",
".",
"monitors",
")",
"# monitors is also a callback",
"# some final operations that might modify the graph",
"logger",
".",
"info",
"(",
"\"Setup callbacks graph ...\"",
")",
"self",
".",
"_callbacks",
"=",
"Callbacks",
"(",
"self",
".",
"_callbacks",
")",
"self",
".",
"_callbacks",
".",
"setup_graph",
"(",
"weakref",
".",
"proxy",
"(",
"self",
")",
")"
] | Setup callbacks and monitors. Must be called after the main graph is built.
Args:
callbacks ([Callback]):
monitors ([MonitorBase]): | [
"Setup",
"callbacks",
"and",
"monitors",
".",
"Must",
"be",
"called",
"after",
"the",
"main",
"graph",
"is",
"built",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L184-L211 |
27,348 | tensorpack/tensorpack | tensorpack/train/base.py | Trainer.initialize_hooks | def initialize_hooks(self):
"""
Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`.
A new trainer may override this method to create multiple groups of hooks,
which can be useful when the training is not done by a single `train_op`.
"""
hooks = self._callbacks.get_hooks()
self.hooked_sess = tfv1.train.MonitoredSession(
session_creator=ReuseSessionCreator(self.sess), hooks=hooks) | python | def initialize_hooks(self):
"""
Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`.
A new trainer may override this method to create multiple groups of hooks,
which can be useful when the training is not done by a single `train_op`.
"""
hooks = self._callbacks.get_hooks()
self.hooked_sess = tfv1.train.MonitoredSession(
session_creator=ReuseSessionCreator(self.sess), hooks=hooks) | [
"def",
"initialize_hooks",
"(",
"self",
")",
":",
"hooks",
"=",
"self",
".",
"_callbacks",
".",
"get_hooks",
"(",
")",
"self",
".",
"hooked_sess",
"=",
"tfv1",
".",
"train",
".",
"MonitoredSession",
"(",
"session_creator",
"=",
"ReuseSessionCreator",
"(",
"self",
".",
"sess",
")",
",",
"hooks",
"=",
"hooks",
")"
] | Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`.
A new trainer may override this method to create multiple groups of hooks,
which can be useful when the training is not done by a single `train_op`. | [
"Create",
"SessionRunHooks",
"for",
"all",
"callbacks",
"and",
"hook",
"it",
"onto",
"self",
".",
"sess",
"to",
"create",
"self",
".",
"hooked_sess",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L246-L255 |
27,349 | tensorpack/tensorpack | tensorpack/tfutils/common.py | get_default_sess_config | def get_default_sess_config(mem_fraction=0.99):
"""
Return a tf.ConfigProto to use as default session config.
You can modify the returned config to fit your needs.
Args:
mem_fraction(float): see the `per_process_gpu_memory_fraction` option
in TensorFlow's GPUOptions protobuf:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/protobuf/config.proto
Returns:
tf.ConfigProto: the config to use.
"""
conf = tfv1.ConfigProto()
conf.allow_soft_placement = True
# conf.log_device_placement = True
conf.intra_op_parallelism_threads = 1
conf.inter_op_parallelism_threads = 0
# TF benchmark use cpu_count() - gpu_thread_count(), e.g. 80 - 8 * 2
# Didn't see much difference.
conf.gpu_options.per_process_gpu_memory_fraction = mem_fraction
# This hurt performance of large data pipeline:
# https://github.com/tensorflow/benchmarks/commit/1528c46499cdcff669b5d7c006b7b971884ad0e6
# conf.gpu_options.force_gpu_compatible = True
conf.gpu_options.allow_growth = True
# from tensorflow.core.protobuf import rewriter_config_pb2 as rwc
# conf.graph_options.rewrite_options.memory_optimization = \
# rwc.RewriterConfig.HEURISTICS
# May hurt performance?
# conf.graph_options.optimizer_options.global_jit_level = tf.OptimizerOptions.ON_1
# conf.graph_options.place_pruned_graph = True
return conf | python | def get_default_sess_config(mem_fraction=0.99):
"""
Return a tf.ConfigProto to use as default session config.
You can modify the returned config to fit your needs.
Args:
mem_fraction(float): see the `per_process_gpu_memory_fraction` option
in TensorFlow's GPUOptions protobuf:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/protobuf/config.proto
Returns:
tf.ConfigProto: the config to use.
"""
conf = tfv1.ConfigProto()
conf.allow_soft_placement = True
# conf.log_device_placement = True
conf.intra_op_parallelism_threads = 1
conf.inter_op_parallelism_threads = 0
# TF benchmark use cpu_count() - gpu_thread_count(), e.g. 80 - 8 * 2
# Didn't see much difference.
conf.gpu_options.per_process_gpu_memory_fraction = mem_fraction
# This hurt performance of large data pipeline:
# https://github.com/tensorflow/benchmarks/commit/1528c46499cdcff669b5d7c006b7b971884ad0e6
# conf.gpu_options.force_gpu_compatible = True
conf.gpu_options.allow_growth = True
# from tensorflow.core.protobuf import rewriter_config_pb2 as rwc
# conf.graph_options.rewrite_options.memory_optimization = \
# rwc.RewriterConfig.HEURISTICS
# May hurt performance?
# conf.graph_options.optimizer_options.global_jit_level = tf.OptimizerOptions.ON_1
# conf.graph_options.place_pruned_graph = True
return conf | [
"def",
"get_default_sess_config",
"(",
"mem_fraction",
"=",
"0.99",
")",
":",
"conf",
"=",
"tfv1",
".",
"ConfigProto",
"(",
")",
"conf",
".",
"allow_soft_placement",
"=",
"True",
"# conf.log_device_placement = True",
"conf",
".",
"intra_op_parallelism_threads",
"=",
"1",
"conf",
".",
"inter_op_parallelism_threads",
"=",
"0",
"# TF benchmark use cpu_count() - gpu_thread_count(), e.g. 80 - 8 * 2",
"# Didn't see much difference.",
"conf",
".",
"gpu_options",
".",
"per_process_gpu_memory_fraction",
"=",
"mem_fraction",
"# This hurt performance of large data pipeline:",
"# https://github.com/tensorflow/benchmarks/commit/1528c46499cdcff669b5d7c006b7b971884ad0e6",
"# conf.gpu_options.force_gpu_compatible = True",
"conf",
".",
"gpu_options",
".",
"allow_growth",
"=",
"True",
"# from tensorflow.core.protobuf import rewriter_config_pb2 as rwc",
"# conf.graph_options.rewrite_options.memory_optimization = \\",
"# rwc.RewriterConfig.HEURISTICS",
"# May hurt performance?",
"# conf.graph_options.optimizer_options.global_jit_level = tf.OptimizerOptions.ON_1",
"# conf.graph_options.place_pruned_graph = True",
"return",
"conf"
] | Return a tf.ConfigProto to use as default session config.
You can modify the returned config to fit your needs.
Args:
mem_fraction(float): see the `per_process_gpu_memory_fraction` option
in TensorFlow's GPUOptions protobuf:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/protobuf/config.proto
Returns:
tf.ConfigProto: the config to use. | [
"Return",
"a",
"tf",
".",
"ConfigProto",
"to",
"use",
"as",
"default",
"session",
"config",
".",
"You",
"can",
"modify",
"the",
"returned",
"config",
"to",
"fit",
"your",
"needs",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/common.py#L30-L68 |
27,350 | tensorpack/tensorpack | tensorpack/tfutils/common.py | get_tensors_by_names | def get_tensors_by_names(names):
"""
Get a list of tensors in the default graph by a list of names.
Args:
names (list):
"""
ret = []
G = tfv1.get_default_graph()
for n in names:
opn, varn = get_op_tensor_name(n)
ret.append(G.get_tensor_by_name(varn))
return ret | python | def get_tensors_by_names(names):
"""
Get a list of tensors in the default graph by a list of names.
Args:
names (list):
"""
ret = []
G = tfv1.get_default_graph()
for n in names:
opn, varn = get_op_tensor_name(n)
ret.append(G.get_tensor_by_name(varn))
return ret | [
"def",
"get_tensors_by_names",
"(",
"names",
")",
":",
"ret",
"=",
"[",
"]",
"G",
"=",
"tfv1",
".",
"get_default_graph",
"(",
")",
"for",
"n",
"in",
"names",
":",
"opn",
",",
"varn",
"=",
"get_op_tensor_name",
"(",
"n",
")",
"ret",
".",
"append",
"(",
"G",
".",
"get_tensor_by_name",
"(",
"varn",
")",
")",
"return",
"ret"
] | Get a list of tensors in the default graph by a list of names.
Args:
names (list): | [
"Get",
"a",
"list",
"of",
"tensors",
"in",
"the",
"default",
"graph",
"by",
"a",
"list",
"of",
"names",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/common.py#L113-L125 |
27,351 | tensorpack/tensorpack | tensorpack/tfutils/common.py | get_op_or_tensor_by_name | def get_op_or_tensor_by_name(name):
"""
Get either tf.Operation of tf.Tensor from names.
Args:
name (list[str] or str): names of operations or tensors.
Raises:
KeyError, if the name doesn't exist
"""
G = tfv1.get_default_graph()
def f(n):
if len(n) >= 3 and n[-2] == ':':
return G.get_tensor_by_name(n)
else:
return G.get_operation_by_name(n)
if not isinstance(name, list):
return f(name)
else:
return list(map(f, name)) | python | def get_op_or_tensor_by_name(name):
"""
Get either tf.Operation of tf.Tensor from names.
Args:
name (list[str] or str): names of operations or tensors.
Raises:
KeyError, if the name doesn't exist
"""
G = tfv1.get_default_graph()
def f(n):
if len(n) >= 3 and n[-2] == ':':
return G.get_tensor_by_name(n)
else:
return G.get_operation_by_name(n)
if not isinstance(name, list):
return f(name)
else:
return list(map(f, name)) | [
"def",
"get_op_or_tensor_by_name",
"(",
"name",
")",
":",
"G",
"=",
"tfv1",
".",
"get_default_graph",
"(",
")",
"def",
"f",
"(",
"n",
")",
":",
"if",
"len",
"(",
"n",
")",
">=",
"3",
"and",
"n",
"[",
"-",
"2",
"]",
"==",
"':'",
":",
"return",
"G",
".",
"get_tensor_by_name",
"(",
"n",
")",
"else",
":",
"return",
"G",
".",
"get_operation_by_name",
"(",
"n",
")",
"if",
"not",
"isinstance",
"(",
"name",
",",
"list",
")",
":",
"return",
"f",
"(",
"name",
")",
"else",
":",
"return",
"list",
"(",
"map",
"(",
"f",
",",
"name",
")",
")"
] | Get either tf.Operation of tf.Tensor from names.
Args:
name (list[str] or str): names of operations or tensors.
Raises:
KeyError, if the name doesn't exist | [
"Get",
"either",
"tf",
".",
"Operation",
"of",
"tf",
".",
"Tensor",
"from",
"names",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/common.py#L128-L149 |
27,352 | tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | DistributedBuilderBase._add_sync_queues_and_barrier | def _add_sync_queues_and_barrier(self, name, dependencies):
"""Adds ops to enqueue on all worker queues.
Args:
name: prefixed for the shared_name of ops.
dependencies: control dependency from ops.
Returns:
an op that should be used as control dependency before starting next step.
"""
self._sync_queue_counter += 1
with tf.device(self.sync_queue_devices[self._sync_queue_counter % len(self.sync_queue_devices)]):
sync_queues = [
tf.FIFOQueue(self.num_worker, [tf.bool], shapes=[[]],
shared_name='%s%s' % (name, i))
for i in range(self.num_worker)]
queue_ops = []
# For each other worker, add an entry in a queue, signaling that it can finish this step.
token = tf.constant(False)
with tf.control_dependencies(dependencies):
for i, q in enumerate(sync_queues):
if i != self.task_index:
queue_ops.append(q.enqueue(token))
# Drain tokens off queue for this worker, one for each other worker.
queue_ops.append(
sync_queues[self.task_index].dequeue_many(len(sync_queues) - 1))
return tf.group(*queue_ops, name=name) | python | def _add_sync_queues_and_barrier(self, name, dependencies):
"""Adds ops to enqueue on all worker queues.
Args:
name: prefixed for the shared_name of ops.
dependencies: control dependency from ops.
Returns:
an op that should be used as control dependency before starting next step.
"""
self._sync_queue_counter += 1
with tf.device(self.sync_queue_devices[self._sync_queue_counter % len(self.sync_queue_devices)]):
sync_queues = [
tf.FIFOQueue(self.num_worker, [tf.bool], shapes=[[]],
shared_name='%s%s' % (name, i))
for i in range(self.num_worker)]
queue_ops = []
# For each other worker, add an entry in a queue, signaling that it can finish this step.
token = tf.constant(False)
with tf.control_dependencies(dependencies):
for i, q in enumerate(sync_queues):
if i != self.task_index:
queue_ops.append(q.enqueue(token))
# Drain tokens off queue for this worker, one for each other worker.
queue_ops.append(
sync_queues[self.task_index].dequeue_many(len(sync_queues) - 1))
return tf.group(*queue_ops, name=name) | [
"def",
"_add_sync_queues_and_barrier",
"(",
"self",
",",
"name",
",",
"dependencies",
")",
":",
"self",
".",
"_sync_queue_counter",
"+=",
"1",
"with",
"tf",
".",
"device",
"(",
"self",
".",
"sync_queue_devices",
"[",
"self",
".",
"_sync_queue_counter",
"%",
"len",
"(",
"self",
".",
"sync_queue_devices",
")",
"]",
")",
":",
"sync_queues",
"=",
"[",
"tf",
".",
"FIFOQueue",
"(",
"self",
".",
"num_worker",
",",
"[",
"tf",
".",
"bool",
"]",
",",
"shapes",
"=",
"[",
"[",
"]",
"]",
",",
"shared_name",
"=",
"'%s%s'",
"%",
"(",
"name",
",",
"i",
")",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"num_worker",
")",
"]",
"queue_ops",
"=",
"[",
"]",
"# For each other worker, add an entry in a queue, signaling that it can finish this step.",
"token",
"=",
"tf",
".",
"constant",
"(",
"False",
")",
"with",
"tf",
".",
"control_dependencies",
"(",
"dependencies",
")",
":",
"for",
"i",
",",
"q",
"in",
"enumerate",
"(",
"sync_queues",
")",
":",
"if",
"i",
"!=",
"self",
".",
"task_index",
":",
"queue_ops",
".",
"append",
"(",
"q",
".",
"enqueue",
"(",
"token",
")",
")",
"# Drain tokens off queue for this worker, one for each other worker.",
"queue_ops",
".",
"append",
"(",
"sync_queues",
"[",
"self",
".",
"task_index",
"]",
".",
"dequeue_many",
"(",
"len",
"(",
"sync_queues",
")",
"-",
"1",
")",
")",
"return",
"tf",
".",
"group",
"(",
"*",
"queue_ops",
",",
"name",
"=",
"name",
")"
] | Adds ops to enqueue on all worker queues.
Args:
name: prefixed for the shared_name of ops.
dependencies: control dependency from ops.
Returns:
an op that should be used as control dependency before starting next step. | [
"Adds",
"ops",
"to",
"enqueue",
"on",
"all",
"worker",
"queues",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L30-L58 |
27,353 | tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | DistributedReplicatedBuilder._apply_shadow_vars | def _apply_shadow_vars(avg_grads):
"""
Create shadow variables on PS, and replace variables in avg_grads
by these shadow variables.
Args:
avg_grads: list of (grad, var) tuples
"""
ps_var_grads = []
for grad, var in avg_grads:
assert var.name.startswith('tower'), var.name
my_name = '/'.join(var.name.split('/')[1:])
my_name = get_op_tensor_name(my_name)[0]
new_v = tf.get_variable(my_name, dtype=var.dtype.base_dtype,
initializer=var.initial_value,
trainable=True)
# (g, v) to be applied, where v is global (ps vars)
ps_var_grads.append((grad, new_v))
return ps_var_grads | python | def _apply_shadow_vars(avg_grads):
"""
Create shadow variables on PS, and replace variables in avg_grads
by these shadow variables.
Args:
avg_grads: list of (grad, var) tuples
"""
ps_var_grads = []
for grad, var in avg_grads:
assert var.name.startswith('tower'), var.name
my_name = '/'.join(var.name.split('/')[1:])
my_name = get_op_tensor_name(my_name)[0]
new_v = tf.get_variable(my_name, dtype=var.dtype.base_dtype,
initializer=var.initial_value,
trainable=True)
# (g, v) to be applied, where v is global (ps vars)
ps_var_grads.append((grad, new_v))
return ps_var_grads | [
"def",
"_apply_shadow_vars",
"(",
"avg_grads",
")",
":",
"ps_var_grads",
"=",
"[",
"]",
"for",
"grad",
",",
"var",
"in",
"avg_grads",
":",
"assert",
"var",
".",
"name",
".",
"startswith",
"(",
"'tower'",
")",
",",
"var",
".",
"name",
"my_name",
"=",
"'/'",
".",
"join",
"(",
"var",
".",
"name",
".",
"split",
"(",
"'/'",
")",
"[",
"1",
":",
"]",
")",
"my_name",
"=",
"get_op_tensor_name",
"(",
"my_name",
")",
"[",
"0",
"]",
"new_v",
"=",
"tf",
".",
"get_variable",
"(",
"my_name",
",",
"dtype",
"=",
"var",
".",
"dtype",
".",
"base_dtype",
",",
"initializer",
"=",
"var",
".",
"initial_value",
",",
"trainable",
"=",
"True",
")",
"# (g, v) to be applied, where v is global (ps vars)",
"ps_var_grads",
".",
"append",
"(",
"(",
"grad",
",",
"new_v",
")",
")",
"return",
"ps_var_grads"
] | Create shadow variables on PS, and replace variables in avg_grads
by these shadow variables.
Args:
avg_grads: list of (grad, var) tuples | [
"Create",
"shadow",
"variables",
"on",
"PS",
"and",
"replace",
"variables",
"in",
"avg_grads",
"by",
"these",
"shadow",
"variables",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L205-L223 |
27,354 | tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | DistributedReplicatedBuilder._shadow_model_variables | def _shadow_model_variables(shadow_vars):
"""
Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``.
Returns:
list of (shadow_model_var, local_model_var) used for syncing.
"""
G = tf.get_default_graph()
curr_shadow_vars = set([v.name for v in shadow_vars])
model_vars = tf.model_variables()
shadow_model_vars = []
for v in model_vars:
assert v.name.startswith('tower'), "Found some MODEL_VARIABLES created outside of the tower function!"
stripped_op_name, stripped_var_name = get_op_tensor_name(re.sub('^tower[0-9]+/', '', v.name))
if stripped_op_name in curr_shadow_vars:
continue
try:
G.get_tensor_by_name(stripped_var_name)
logger.warn("Model Variable {} also appears in other collections.".format(stripped_var_name))
continue
except KeyError:
pass
new_v = tf.get_variable(stripped_op_name, dtype=v.dtype.base_dtype,
initializer=v.initial_value,
trainable=False)
curr_shadow_vars.add(stripped_op_name) # avoid duplicated shadow_model_vars
shadow_vars.append(new_v)
shadow_model_vars.append((new_v, v)) # only need to sync model_var from one tower
return shadow_model_vars | python | def _shadow_model_variables(shadow_vars):
"""
Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``.
Returns:
list of (shadow_model_var, local_model_var) used for syncing.
"""
G = tf.get_default_graph()
curr_shadow_vars = set([v.name for v in shadow_vars])
model_vars = tf.model_variables()
shadow_model_vars = []
for v in model_vars:
assert v.name.startswith('tower'), "Found some MODEL_VARIABLES created outside of the tower function!"
stripped_op_name, stripped_var_name = get_op_tensor_name(re.sub('^tower[0-9]+/', '', v.name))
if stripped_op_name in curr_shadow_vars:
continue
try:
G.get_tensor_by_name(stripped_var_name)
logger.warn("Model Variable {} also appears in other collections.".format(stripped_var_name))
continue
except KeyError:
pass
new_v = tf.get_variable(stripped_op_name, dtype=v.dtype.base_dtype,
initializer=v.initial_value,
trainable=False)
curr_shadow_vars.add(stripped_op_name) # avoid duplicated shadow_model_vars
shadow_vars.append(new_v)
shadow_model_vars.append((new_v, v)) # only need to sync model_var from one tower
return shadow_model_vars | [
"def",
"_shadow_model_variables",
"(",
"shadow_vars",
")",
":",
"G",
"=",
"tf",
".",
"get_default_graph",
"(",
")",
"curr_shadow_vars",
"=",
"set",
"(",
"[",
"v",
".",
"name",
"for",
"v",
"in",
"shadow_vars",
"]",
")",
"model_vars",
"=",
"tf",
".",
"model_variables",
"(",
")",
"shadow_model_vars",
"=",
"[",
"]",
"for",
"v",
"in",
"model_vars",
":",
"assert",
"v",
".",
"name",
".",
"startswith",
"(",
"'tower'",
")",
",",
"\"Found some MODEL_VARIABLES created outside of the tower function!\"",
"stripped_op_name",
",",
"stripped_var_name",
"=",
"get_op_tensor_name",
"(",
"re",
".",
"sub",
"(",
"'^tower[0-9]+/'",
",",
"''",
",",
"v",
".",
"name",
")",
")",
"if",
"stripped_op_name",
"in",
"curr_shadow_vars",
":",
"continue",
"try",
":",
"G",
".",
"get_tensor_by_name",
"(",
"stripped_var_name",
")",
"logger",
".",
"warn",
"(",
"\"Model Variable {} also appears in other collections.\"",
".",
"format",
"(",
"stripped_var_name",
")",
")",
"continue",
"except",
"KeyError",
":",
"pass",
"new_v",
"=",
"tf",
".",
"get_variable",
"(",
"stripped_op_name",
",",
"dtype",
"=",
"v",
".",
"dtype",
".",
"base_dtype",
",",
"initializer",
"=",
"v",
".",
"initial_value",
",",
"trainable",
"=",
"False",
")",
"curr_shadow_vars",
".",
"add",
"(",
"stripped_op_name",
")",
"# avoid duplicated shadow_model_vars",
"shadow_vars",
".",
"append",
"(",
"new_v",
")",
"shadow_model_vars",
".",
"append",
"(",
"(",
"new_v",
",",
"v",
")",
")",
"# only need to sync model_var from one tower",
"return",
"shadow_model_vars"
] | Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``.
Returns:
list of (shadow_model_var, local_model_var) used for syncing. | [
"Create",
"shadow",
"vars",
"for",
"model_variables",
"as",
"well",
"and",
"add",
"to",
"the",
"list",
"of",
"shadow_vars",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L226-L255 |
27,355 | tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | DistributedReplicatedBuilder._apply_gradients_and_copy | def _apply_gradients_and_copy(self, opt, raw_grad_list, ps_var_grads):
"""
Apply averaged gradients to ps vars, and then copy the updated
variables back to each tower.
Args:
raw_grad_list: Ngpu x Nvar x 2 gradient list from all towers
ps_var_grads: Nvar x 2 (grad, ps_var)
Returns:
list of copy ops
"""
# TODO do this for variables together?
with tf.name_scope('apply_gradients'):
var_update_ops = []
for vid, (g, v) in enumerate(ps_var_grads):
# TODO do we put momentum variables into local or global?
apply_gradient_op = opt.apply_gradients([(g, v)])
barrier = self._add_sync_queues_and_barrier(
'param_update_barrier_{}'.format(vid), [apply_gradient_op])
with tf.control_dependencies([barrier]), \
tf.device(self.cpu_device):
updated_value = v.read_value()
for towerid in range(self.nr_gpu):
var_update_ops.append(
raw_grad_list[towerid][vid][1].assign(updated_value))
return var_update_ops | python | def _apply_gradients_and_copy(self, opt, raw_grad_list, ps_var_grads):
"""
Apply averaged gradients to ps vars, and then copy the updated
variables back to each tower.
Args:
raw_grad_list: Ngpu x Nvar x 2 gradient list from all towers
ps_var_grads: Nvar x 2 (grad, ps_var)
Returns:
list of copy ops
"""
# TODO do this for variables together?
with tf.name_scope('apply_gradients'):
var_update_ops = []
for vid, (g, v) in enumerate(ps_var_grads):
# TODO do we put momentum variables into local or global?
apply_gradient_op = opt.apply_gradients([(g, v)])
barrier = self._add_sync_queues_and_barrier(
'param_update_barrier_{}'.format(vid), [apply_gradient_op])
with tf.control_dependencies([barrier]), \
tf.device(self.cpu_device):
updated_value = v.read_value()
for towerid in range(self.nr_gpu):
var_update_ops.append(
raw_grad_list[towerid][vid][1].assign(updated_value))
return var_update_ops | [
"def",
"_apply_gradients_and_copy",
"(",
"self",
",",
"opt",
",",
"raw_grad_list",
",",
"ps_var_grads",
")",
":",
"# TODO do this for variables together?",
"with",
"tf",
".",
"name_scope",
"(",
"'apply_gradients'",
")",
":",
"var_update_ops",
"=",
"[",
"]",
"for",
"vid",
",",
"(",
"g",
",",
"v",
")",
"in",
"enumerate",
"(",
"ps_var_grads",
")",
":",
"# TODO do we put momentum variables into local or global?",
"apply_gradient_op",
"=",
"opt",
".",
"apply_gradients",
"(",
"[",
"(",
"g",
",",
"v",
")",
"]",
")",
"barrier",
"=",
"self",
".",
"_add_sync_queues_and_barrier",
"(",
"'param_update_barrier_{}'",
".",
"format",
"(",
"vid",
")",
",",
"[",
"apply_gradient_op",
"]",
")",
"with",
"tf",
".",
"control_dependencies",
"(",
"[",
"barrier",
"]",
")",
",",
"tf",
".",
"device",
"(",
"self",
".",
"cpu_device",
")",
":",
"updated_value",
"=",
"v",
".",
"read_value",
"(",
")",
"for",
"towerid",
"in",
"range",
"(",
"self",
".",
"nr_gpu",
")",
":",
"var_update_ops",
".",
"append",
"(",
"raw_grad_list",
"[",
"towerid",
"]",
"[",
"vid",
"]",
"[",
"1",
"]",
".",
"assign",
"(",
"updated_value",
")",
")",
"return",
"var_update_ops"
] | Apply averaged gradients to ps vars, and then copy the updated
variables back to each tower.
Args:
raw_grad_list: Ngpu x Nvar x 2 gradient list from all towers
ps_var_grads: Nvar x 2 (grad, ps_var)
Returns:
list of copy ops | [
"Apply",
"averaged",
"gradients",
"to",
"ps",
"vars",
"and",
"then",
"copy",
"the",
"updated",
"variables",
"back",
"to",
"each",
"tower",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L313-L339 |
27,356 | tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | DistributedReplicatedBuilder._get_initial_sync_op | def _get_initial_sync_op(self):
"""
Get the op to copy-initialized all local variables from PS.
"""
def strip_port(s):
if s.endswith(':0'):
return s[:-2]
return s
local_vars = tf.local_variables()
local_var_by_name = dict([(strip_port(v.name), v) for v in local_vars])
ops = []
nr_shadow_vars = len(self._shadow_vars)
for v in self._shadow_vars:
vname = strip_port(v.name)
for i in range(self.nr_gpu):
name = 'tower%s/%s' % (i, vname)
assert name in local_var_by_name, \
"Shadow variable {} doesn't match a corresponding local variable!".format(v.name)
copy_to = local_var_by_name[name]
# logger.info("{} -> {}".format(v.name, copy_to.name))
ops.append(copy_to.assign(v.read_value()))
return tf.group(*ops, name='sync_{}_variables_from_ps'.format(nr_shadow_vars)) | python | def _get_initial_sync_op(self):
"""
Get the op to copy-initialized all local variables from PS.
"""
def strip_port(s):
if s.endswith(':0'):
return s[:-2]
return s
local_vars = tf.local_variables()
local_var_by_name = dict([(strip_port(v.name), v) for v in local_vars])
ops = []
nr_shadow_vars = len(self._shadow_vars)
for v in self._shadow_vars:
vname = strip_port(v.name)
for i in range(self.nr_gpu):
name = 'tower%s/%s' % (i, vname)
assert name in local_var_by_name, \
"Shadow variable {} doesn't match a corresponding local variable!".format(v.name)
copy_to = local_var_by_name[name]
# logger.info("{} -> {}".format(v.name, copy_to.name))
ops.append(copy_to.assign(v.read_value()))
return tf.group(*ops, name='sync_{}_variables_from_ps'.format(nr_shadow_vars)) | [
"def",
"_get_initial_sync_op",
"(",
"self",
")",
":",
"def",
"strip_port",
"(",
"s",
")",
":",
"if",
"s",
".",
"endswith",
"(",
"':0'",
")",
":",
"return",
"s",
"[",
":",
"-",
"2",
"]",
"return",
"s",
"local_vars",
"=",
"tf",
".",
"local_variables",
"(",
")",
"local_var_by_name",
"=",
"dict",
"(",
"[",
"(",
"strip_port",
"(",
"v",
".",
"name",
")",
",",
"v",
")",
"for",
"v",
"in",
"local_vars",
"]",
")",
"ops",
"=",
"[",
"]",
"nr_shadow_vars",
"=",
"len",
"(",
"self",
".",
"_shadow_vars",
")",
"for",
"v",
"in",
"self",
".",
"_shadow_vars",
":",
"vname",
"=",
"strip_port",
"(",
"v",
".",
"name",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"nr_gpu",
")",
":",
"name",
"=",
"'tower%s/%s'",
"%",
"(",
"i",
",",
"vname",
")",
"assert",
"name",
"in",
"local_var_by_name",
",",
"\"Shadow variable {} doesn't match a corresponding local variable!\"",
".",
"format",
"(",
"v",
".",
"name",
")",
"copy_to",
"=",
"local_var_by_name",
"[",
"name",
"]",
"# logger.info(\"{} -> {}\".format(v.name, copy_to.name))",
"ops",
".",
"append",
"(",
"copy_to",
".",
"assign",
"(",
"v",
".",
"read_value",
"(",
")",
")",
")",
"return",
"tf",
".",
"group",
"(",
"*",
"ops",
",",
"name",
"=",
"'sync_{}_variables_from_ps'",
".",
"format",
"(",
"nr_shadow_vars",
")",
")"
] | Get the op to copy-initialized all local variables from PS. | [
"Get",
"the",
"op",
"to",
"copy",
"-",
"initialized",
"all",
"local",
"variables",
"from",
"PS",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L341-L362 |
27,357 | tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | DistributedReplicatedBuilder._get_sync_model_vars_op | def _get_sync_model_vars_op(self):
"""
Get the op to sync local model_variables to PS.
"""
ops = []
for (shadow_v, local_v) in self._shadow_model_vars:
ops.append(shadow_v.assign(local_v.read_value()))
assert len(ops)
return tf.group(*ops, name='sync_{}_model_variables_to_ps'.format(len(ops))) | python | def _get_sync_model_vars_op(self):
"""
Get the op to sync local model_variables to PS.
"""
ops = []
for (shadow_v, local_v) in self._shadow_model_vars:
ops.append(shadow_v.assign(local_v.read_value()))
assert len(ops)
return tf.group(*ops, name='sync_{}_model_variables_to_ps'.format(len(ops))) | [
"def",
"_get_sync_model_vars_op",
"(",
"self",
")",
":",
"ops",
"=",
"[",
"]",
"for",
"(",
"shadow_v",
",",
"local_v",
")",
"in",
"self",
".",
"_shadow_model_vars",
":",
"ops",
".",
"append",
"(",
"shadow_v",
".",
"assign",
"(",
"local_v",
".",
"read_value",
"(",
")",
")",
")",
"assert",
"len",
"(",
"ops",
")",
"return",
"tf",
".",
"group",
"(",
"*",
"ops",
",",
"name",
"=",
"'sync_{}_model_variables_to_ps'",
".",
"format",
"(",
"len",
"(",
"ops",
")",
")",
")"
] | Get the op to sync local model_variables to PS. | [
"Get",
"the",
"op",
"to",
"sync",
"local",
"model_variables",
"to",
"PS",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L364-L372 |
27,358 | tensorpack/tensorpack | tensorpack/callbacks/summary.py | MergeAllSummaries | def MergeAllSummaries(period=0, run_alone=False, key=None):
"""
This callback is enabled by default.
Evaluate all summaries by ``tf.summary.merge_all``, and write them to logs.
Args:
period (int): by default the callback summarizes once every epoch.
This option (if not set to 0) makes it additionally summarize every ``period`` steps.
run_alone (bool): whether to evaluate the summaries alone.
If True, summaries will be evaluated after each epoch alone.
If False, summaries will be evaluated together with the
`sess.run` calls, in the last step of each epoch.
For :class:`SimpleTrainer`, it needs to be False because summary may
depend on inputs.
key (str): the collection of summary tensors. Same as in ``tf.summary.merge_all``.
Default is ``tf.GraphKeys.SUMMARIES``.
"""
if key is None:
key = tf.GraphKeys.SUMMARIES
period = int(period)
if run_alone:
return MergeAllSummaries_RunAlone(period, key)
else:
return MergeAllSummaries_RunWithOp(period, key) | python | def MergeAllSummaries(period=0, run_alone=False, key=None):
"""
This callback is enabled by default.
Evaluate all summaries by ``tf.summary.merge_all``, and write them to logs.
Args:
period (int): by default the callback summarizes once every epoch.
This option (if not set to 0) makes it additionally summarize every ``period`` steps.
run_alone (bool): whether to evaluate the summaries alone.
If True, summaries will be evaluated after each epoch alone.
If False, summaries will be evaluated together with the
`sess.run` calls, in the last step of each epoch.
For :class:`SimpleTrainer`, it needs to be False because summary may
depend on inputs.
key (str): the collection of summary tensors. Same as in ``tf.summary.merge_all``.
Default is ``tf.GraphKeys.SUMMARIES``.
"""
if key is None:
key = tf.GraphKeys.SUMMARIES
period = int(period)
if run_alone:
return MergeAllSummaries_RunAlone(period, key)
else:
return MergeAllSummaries_RunWithOp(period, key) | [
"def",
"MergeAllSummaries",
"(",
"period",
"=",
"0",
",",
"run_alone",
"=",
"False",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"key",
"=",
"tf",
".",
"GraphKeys",
".",
"SUMMARIES",
"period",
"=",
"int",
"(",
"period",
")",
"if",
"run_alone",
":",
"return",
"MergeAllSummaries_RunAlone",
"(",
"period",
",",
"key",
")",
"else",
":",
"return",
"MergeAllSummaries_RunWithOp",
"(",
"period",
",",
"key",
")"
] | This callback is enabled by default.
Evaluate all summaries by ``tf.summary.merge_all``, and write them to logs.
Args:
period (int): by default the callback summarizes once every epoch.
This option (if not set to 0) makes it additionally summarize every ``period`` steps.
run_alone (bool): whether to evaluate the summaries alone.
If True, summaries will be evaluated after each epoch alone.
If False, summaries will be evaluated together with the
`sess.run` calls, in the last step of each epoch.
For :class:`SimpleTrainer`, it needs to be False because summary may
depend on inputs.
key (str): the collection of summary tensors. Same as in ``tf.summary.merge_all``.
Default is ``tf.GraphKeys.SUMMARIES``. | [
"This",
"callback",
"is",
"enabled",
"by",
"default",
".",
"Evaluate",
"all",
"summaries",
"by",
"tf",
".",
"summary",
".",
"merge_all",
"and",
"write",
"them",
"to",
"logs",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/summary.py#L119-L142 |
27,359 | tensorpack/tensorpack | examples/DeepQNetwork/expreplay.py | EnvRunner.step | def step(self, exploration):
"""
Run the environment for one step.
If the episode ends, store the entire episode to the replay memory.
"""
old_s = self._current_ob
if self.rng.rand() <= exploration:
act = self.rng.choice(range(self.num_actions))
else:
history = self.recent_state()
history.append(old_s)
history = np.stack(history, axis=-1) # state_shape + (Hist,)
# assume batched network
history = np.expand_dims(history, axis=0)
q_values = self.predictor(history)[0][0] # this is the bottleneck
act = np.argmax(q_values)
self._current_ob, reward, isOver, info = self.player.step(act)
self._current_game_score.feed(reward)
self._current_episode.append(Experience(old_s, act, reward, isOver))
if isOver:
flush_experience = True
if 'ale.lives' in info: # if running Atari, do something special
if info['ale.lives'] != 0:
# only record score and flush experience
# when a whole game is over (not when an episode is over)
flush_experience = False
self.player.reset()
if flush_experience:
self.total_scores.append(self._current_game_score.sum)
self._current_game_score.reset()
# Ensure that the whole episode of experience is continuous in the replay buffer
with self.memory.writer_lock:
for exp in self._current_episode:
self.memory.append(exp)
self._current_episode.clear() | python | def step(self, exploration):
"""
Run the environment for one step.
If the episode ends, store the entire episode to the replay memory.
"""
old_s = self._current_ob
if self.rng.rand() <= exploration:
act = self.rng.choice(range(self.num_actions))
else:
history = self.recent_state()
history.append(old_s)
history = np.stack(history, axis=-1) # state_shape + (Hist,)
# assume batched network
history = np.expand_dims(history, axis=0)
q_values = self.predictor(history)[0][0] # this is the bottleneck
act = np.argmax(q_values)
self._current_ob, reward, isOver, info = self.player.step(act)
self._current_game_score.feed(reward)
self._current_episode.append(Experience(old_s, act, reward, isOver))
if isOver:
flush_experience = True
if 'ale.lives' in info: # if running Atari, do something special
if info['ale.lives'] != 0:
# only record score and flush experience
# when a whole game is over (not when an episode is over)
flush_experience = False
self.player.reset()
if flush_experience:
self.total_scores.append(self._current_game_score.sum)
self._current_game_score.reset()
# Ensure that the whole episode of experience is continuous in the replay buffer
with self.memory.writer_lock:
for exp in self._current_episode:
self.memory.append(exp)
self._current_episode.clear() | [
"def",
"step",
"(",
"self",
",",
"exploration",
")",
":",
"old_s",
"=",
"self",
".",
"_current_ob",
"if",
"self",
".",
"rng",
".",
"rand",
"(",
")",
"<=",
"exploration",
":",
"act",
"=",
"self",
".",
"rng",
".",
"choice",
"(",
"range",
"(",
"self",
".",
"num_actions",
")",
")",
"else",
":",
"history",
"=",
"self",
".",
"recent_state",
"(",
")",
"history",
".",
"append",
"(",
"old_s",
")",
"history",
"=",
"np",
".",
"stack",
"(",
"history",
",",
"axis",
"=",
"-",
"1",
")",
"# state_shape + (Hist,)",
"# assume batched network",
"history",
"=",
"np",
".",
"expand_dims",
"(",
"history",
",",
"axis",
"=",
"0",
")",
"q_values",
"=",
"self",
".",
"predictor",
"(",
"history",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"# this is the bottleneck",
"act",
"=",
"np",
".",
"argmax",
"(",
"q_values",
")",
"self",
".",
"_current_ob",
",",
"reward",
",",
"isOver",
",",
"info",
"=",
"self",
".",
"player",
".",
"step",
"(",
"act",
")",
"self",
".",
"_current_game_score",
".",
"feed",
"(",
"reward",
")",
"self",
".",
"_current_episode",
".",
"append",
"(",
"Experience",
"(",
"old_s",
",",
"act",
",",
"reward",
",",
"isOver",
")",
")",
"if",
"isOver",
":",
"flush_experience",
"=",
"True",
"if",
"'ale.lives'",
"in",
"info",
":",
"# if running Atari, do something special",
"if",
"info",
"[",
"'ale.lives'",
"]",
"!=",
"0",
":",
"# only record score and flush experience",
"# when a whole game is over (not when an episode is over)",
"flush_experience",
"=",
"False",
"self",
".",
"player",
".",
"reset",
"(",
")",
"if",
"flush_experience",
":",
"self",
".",
"total_scores",
".",
"append",
"(",
"self",
".",
"_current_game_score",
".",
"sum",
")",
"self",
".",
"_current_game_score",
".",
"reset",
"(",
")",
"# Ensure that the whole episode of experience is continuous in the replay buffer",
"with",
"self",
".",
"memory",
".",
"writer_lock",
":",
"for",
"exp",
"in",
"self",
".",
"_current_episode",
":",
"self",
".",
"memory",
".",
"append",
"(",
"exp",
")",
"self",
".",
"_current_episode",
".",
"clear",
"(",
")"
] | Run the environment for one step.
If the episode ends, store the entire episode to the replay memory. | [
"Run",
"the",
"environment",
"for",
"one",
"step",
".",
"If",
"the",
"episode",
"ends",
"store",
"the",
"entire",
"episode",
"to",
"the",
"replay",
"memory",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/expreplay.py#L143-L182 |
27,360 | tensorpack/tensorpack | examples/DeepQNetwork/expreplay.py | EnvRunnerManager.step | def step(self, exploration):
"""
Execute one step in any of the runners.
"""
if len(self._runners) > 1:
self._populate_job_queue.put(exploration)
else:
self._runners[0].step(exploration) | python | def step(self, exploration):
"""
Execute one step in any of the runners.
"""
if len(self._runners) > 1:
self._populate_job_queue.put(exploration)
else:
self._runners[0].step(exploration) | [
"def",
"step",
"(",
"self",
",",
"exploration",
")",
":",
"if",
"len",
"(",
"self",
".",
"_runners",
")",
">",
"1",
":",
"self",
".",
"_populate_job_queue",
".",
"put",
"(",
"exploration",
")",
"else",
":",
"self",
".",
"_runners",
"[",
"0",
"]",
".",
"step",
"(",
"exploration",
")"
] | Execute one step in any of the runners. | [
"Execute",
"one",
"step",
"in",
"any",
"of",
"the",
"runners",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/expreplay.py#L233-L240 |
27,361 | tensorpack/tensorpack | tensorpack/callbacks/group.py | CallbackTimeLogger.log | def log(self):
""" log the time of some heavy callbacks """
if self.tot < 3:
return
msgs = []
for name, t in self.times:
if t / self.tot > 0.3 and t > 1:
msgs.append(name + ": " + humanize_time_delta(t))
logger.info(
"Callbacks took {:.3f} sec in total. {}".format(
self.tot, '; '.join(msgs))) | python | def log(self):
""" log the time of some heavy callbacks """
if self.tot < 3:
return
msgs = []
for name, t in self.times:
if t / self.tot > 0.3 and t > 1:
msgs.append(name + ": " + humanize_time_delta(t))
logger.info(
"Callbacks took {:.3f} sec in total. {}".format(
self.tot, '; '.join(msgs))) | [
"def",
"log",
"(",
"self",
")",
":",
"if",
"self",
".",
"tot",
"<",
"3",
":",
"return",
"msgs",
"=",
"[",
"]",
"for",
"name",
",",
"t",
"in",
"self",
".",
"times",
":",
"if",
"t",
"/",
"self",
".",
"tot",
">",
"0.3",
"and",
"t",
">",
"1",
":",
"msgs",
".",
"append",
"(",
"name",
"+",
"\": \"",
"+",
"humanize_time_delta",
"(",
"t",
")",
")",
"logger",
".",
"info",
"(",
"\"Callbacks took {:.3f} sec in total. {}\"",
".",
"format",
"(",
"self",
".",
"tot",
",",
"'; '",
".",
"join",
"(",
"msgs",
")",
")",
")"
] | log the time of some heavy callbacks | [
"log",
"the",
"time",
"of",
"some",
"heavy",
"callbacks"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/group.py#L37-L48 |
27,362 | tensorpack/tensorpack | tensorpack/tfutils/tower.py | TowerTensorHandle.get_variable | def get_variable(self, name):
"""
Get a variable used in this tower.
The name should not contain the variable scope prefix of the tower.
When the tower has the same variable scope and name scope, this is equivalent to
:meth:`get_tensor`.
"""
name = get_op_tensor_name(name)[1]
if len(self.vs_name):
name_with_vs = self.vs_name + "/" + name
else:
name_with_vs = name
return get_op_or_tensor_by_name(name_with_vs) | python | def get_variable(self, name):
"""
Get a variable used in this tower.
The name should not contain the variable scope prefix of the tower.
When the tower has the same variable scope and name scope, this is equivalent to
:meth:`get_tensor`.
"""
name = get_op_tensor_name(name)[1]
if len(self.vs_name):
name_with_vs = self.vs_name + "/" + name
else:
name_with_vs = name
return get_op_or_tensor_by_name(name_with_vs) | [
"def",
"get_variable",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"get_op_tensor_name",
"(",
"name",
")",
"[",
"1",
"]",
"if",
"len",
"(",
"self",
".",
"vs_name",
")",
":",
"name_with_vs",
"=",
"self",
".",
"vs_name",
"+",
"\"/\"",
"+",
"name",
"else",
":",
"name_with_vs",
"=",
"name",
"return",
"get_op_or_tensor_by_name",
"(",
"name_with_vs",
")"
] | Get a variable used in this tower.
The name should not contain the variable scope prefix of the tower.
When the tower has the same variable scope and name scope, this is equivalent to
:meth:`get_tensor`. | [
"Get",
"a",
"variable",
"used",
"in",
"this",
"tower",
".",
"The",
"name",
"should",
"not",
"contain",
"the",
"variable",
"scope",
"prefix",
"of",
"the",
"tower",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/tower.py#L429-L442 |
27,363 | tensorpack/tensorpack | tensorpack/utils/fs.py | mkdir_p | def mkdir_p(dirname):
""" Like "mkdir -p", make a dir recursively, but do nothing if the dir exists
Args:
dirname(str):
"""
assert dirname is not None
if dirname == '' or os.path.isdir(dirname):
return
try:
os.makedirs(dirname)
except OSError as e:
if e.errno != errno.EEXIST:
raise e | python | def mkdir_p(dirname):
""" Like "mkdir -p", make a dir recursively, but do nothing if the dir exists
Args:
dirname(str):
"""
assert dirname is not None
if dirname == '' or os.path.isdir(dirname):
return
try:
os.makedirs(dirname)
except OSError as e:
if e.errno != errno.EEXIST:
raise e | [
"def",
"mkdir_p",
"(",
"dirname",
")",
":",
"assert",
"dirname",
"is",
"not",
"None",
"if",
"dirname",
"==",
"''",
"or",
"os",
".",
"path",
".",
"isdir",
"(",
"dirname",
")",
":",
"return",
"try",
":",
"os",
".",
"makedirs",
"(",
"dirname",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
":",
"raise",
"e"
] | Like "mkdir -p", make a dir recursively, but do nothing if the dir exists
Args:
dirname(str): | [
"Like",
"mkdir",
"-",
"p",
"make",
"a",
"dir",
"recursively",
"but",
"do",
"nothing",
"if",
"the",
"dir",
"exists"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/fs.py#L16-L29 |
27,364 | tensorpack/tensorpack | tensorpack/utils/fs.py | download | def download(url, dir, filename=None, expect_size=None):
"""
Download URL to a directory.
Will figure out the filename automatically from URL, if not given.
"""
mkdir_p(dir)
if filename is None:
filename = url.split('/')[-1]
fpath = os.path.join(dir, filename)
if os.path.isfile(fpath):
if expect_size is not None and os.stat(fpath).st_size == expect_size:
logger.info("File {} exists! Skip download.".format(filename))
return fpath
else:
logger.warn("File {} exists. Will overwrite with a new download!".format(filename))
def hook(t):
last_b = [0]
def inner(b, bsize, tsize=None):
if tsize is not None:
t.total = tsize
t.update((b - last_b[0]) * bsize)
last_b[0] = b
return inner
try:
with tqdm.tqdm(unit='B', unit_scale=True, miniters=1, desc=filename) as t:
fpath, _ = urllib.request.urlretrieve(url, fpath, reporthook=hook(t))
statinfo = os.stat(fpath)
size = statinfo.st_size
except IOError:
logger.error("Failed to download {}".format(url))
raise
assert size > 0, "Downloaded an empty file from {}!".format(url)
if expect_size is not None and size != expect_size:
logger.error("File downloaded from {} does not match the expected size!".format(url))
logger.error("You may have downloaded a broken file, or the upstream may have modified the file.")
# TODO human-readable size
logger.info('Succesfully downloaded ' + filename + ". " + str(size) + ' bytes.')
return fpath | python | def download(url, dir, filename=None, expect_size=None):
"""
Download URL to a directory.
Will figure out the filename automatically from URL, if not given.
"""
mkdir_p(dir)
if filename is None:
filename = url.split('/')[-1]
fpath = os.path.join(dir, filename)
if os.path.isfile(fpath):
if expect_size is not None and os.stat(fpath).st_size == expect_size:
logger.info("File {} exists! Skip download.".format(filename))
return fpath
else:
logger.warn("File {} exists. Will overwrite with a new download!".format(filename))
def hook(t):
last_b = [0]
def inner(b, bsize, tsize=None):
if tsize is not None:
t.total = tsize
t.update((b - last_b[0]) * bsize)
last_b[0] = b
return inner
try:
with tqdm.tqdm(unit='B', unit_scale=True, miniters=1, desc=filename) as t:
fpath, _ = urllib.request.urlretrieve(url, fpath, reporthook=hook(t))
statinfo = os.stat(fpath)
size = statinfo.st_size
except IOError:
logger.error("Failed to download {}".format(url))
raise
assert size > 0, "Downloaded an empty file from {}!".format(url)
if expect_size is not None and size != expect_size:
logger.error("File downloaded from {} does not match the expected size!".format(url))
logger.error("You may have downloaded a broken file, or the upstream may have modified the file.")
# TODO human-readable size
logger.info('Succesfully downloaded ' + filename + ". " + str(size) + ' bytes.')
return fpath | [
"def",
"download",
"(",
"url",
",",
"dir",
",",
"filename",
"=",
"None",
",",
"expect_size",
"=",
"None",
")",
":",
"mkdir_p",
"(",
"dir",
")",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"url",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"fpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"filename",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"fpath",
")",
":",
"if",
"expect_size",
"is",
"not",
"None",
"and",
"os",
".",
"stat",
"(",
"fpath",
")",
".",
"st_size",
"==",
"expect_size",
":",
"logger",
".",
"info",
"(",
"\"File {} exists! Skip download.\"",
".",
"format",
"(",
"filename",
")",
")",
"return",
"fpath",
"else",
":",
"logger",
".",
"warn",
"(",
"\"File {} exists. Will overwrite with a new download!\"",
".",
"format",
"(",
"filename",
")",
")",
"def",
"hook",
"(",
"t",
")",
":",
"last_b",
"=",
"[",
"0",
"]",
"def",
"inner",
"(",
"b",
",",
"bsize",
",",
"tsize",
"=",
"None",
")",
":",
"if",
"tsize",
"is",
"not",
"None",
":",
"t",
".",
"total",
"=",
"tsize",
"t",
".",
"update",
"(",
"(",
"b",
"-",
"last_b",
"[",
"0",
"]",
")",
"*",
"bsize",
")",
"last_b",
"[",
"0",
"]",
"=",
"b",
"return",
"inner",
"try",
":",
"with",
"tqdm",
".",
"tqdm",
"(",
"unit",
"=",
"'B'",
",",
"unit_scale",
"=",
"True",
",",
"miniters",
"=",
"1",
",",
"desc",
"=",
"filename",
")",
"as",
"t",
":",
"fpath",
",",
"_",
"=",
"urllib",
".",
"request",
".",
"urlretrieve",
"(",
"url",
",",
"fpath",
",",
"reporthook",
"=",
"hook",
"(",
"t",
")",
")",
"statinfo",
"=",
"os",
".",
"stat",
"(",
"fpath",
")",
"size",
"=",
"statinfo",
".",
"st_size",
"except",
"IOError",
":",
"logger",
".",
"error",
"(",
"\"Failed to download {}\"",
".",
"format",
"(",
"url",
")",
")",
"raise",
"assert",
"size",
">",
"0",
",",
"\"Downloaded an empty file from {}!\"",
".",
"format",
"(",
"url",
")",
"if",
"expect_size",
"is",
"not",
"None",
"and",
"size",
"!=",
"expect_size",
":",
"logger",
".",
"error",
"(",
"\"File downloaded from {} does not match the expected size!\"",
".",
"format",
"(",
"url",
")",
")",
"logger",
".",
"error",
"(",
"\"You may have downloaded a broken file, or the upstream may have modified the file.\"",
")",
"# TODO human-readable size",
"logger",
".",
"info",
"(",
"'Succesfully downloaded '",
"+",
"filename",
"+",
"\". \"",
"+",
"str",
"(",
"size",
")",
"+",
"' bytes.'",
")",
"return",
"fpath"
] | Download URL to a directory.
Will figure out the filename automatically from URL, if not given. | [
"Download",
"URL",
"to",
"a",
"directory",
".",
"Will",
"figure",
"out",
"the",
"filename",
"automatically",
"from",
"URL",
"if",
"not",
"given",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/fs.py#L32-L74 |
27,365 | tensorpack/tensorpack | tensorpack/tfutils/collection.py | restore_collection | def restore_collection(backup):
"""
Restore from a collection backup.
Args:
backup (dict):
"""
for k, v in six.iteritems(backup):
del tf.get_collection_ref(k)[:]
tf.get_collection_ref(k).extend(v) | python | def restore_collection(backup):
"""
Restore from a collection backup.
Args:
backup (dict):
"""
for k, v in six.iteritems(backup):
del tf.get_collection_ref(k)[:]
tf.get_collection_ref(k).extend(v) | [
"def",
"restore_collection",
"(",
"backup",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"backup",
")",
":",
"del",
"tf",
".",
"get_collection_ref",
"(",
"k",
")",
"[",
":",
"]",
"tf",
".",
"get_collection_ref",
"(",
"k",
")",
".",
"extend",
"(",
"v",
")"
] | Restore from a collection backup.
Args:
backup (dict): | [
"Restore",
"from",
"a",
"collection",
"backup",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/collection.py#L37-L46 |
27,366 | tensorpack/tensorpack | tensorpack/tfutils/collection.py | CollectionGuard.get_collection_in_tower | def get_collection_in_tower(self, key):
"""
Get items from this collection that are added in the current tower.
"""
new = tf.get_collection(key)
old = set(self.original.get(key, []))
# persist the order in new
return [x for x in new if x not in old] | python | def get_collection_in_tower(self, key):
"""
Get items from this collection that are added in the current tower.
"""
new = tf.get_collection(key)
old = set(self.original.get(key, []))
# persist the order in new
return [x for x in new if x not in old] | [
"def",
"get_collection_in_tower",
"(",
"self",
",",
"key",
")",
":",
"new",
"=",
"tf",
".",
"get_collection",
"(",
"key",
")",
"old",
"=",
"set",
"(",
"self",
".",
"original",
".",
"get",
"(",
"key",
",",
"[",
"]",
")",
")",
"# persist the order in new",
"return",
"[",
"x",
"for",
"x",
"in",
"new",
"if",
"x",
"not",
"in",
"old",
"]"
] | Get items from this collection that are added in the current tower. | [
"Get",
"items",
"from",
"this",
"collection",
"that",
"are",
"added",
"in",
"the",
"current",
"tower",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/collection.py#L168-L175 |
27,367 | tensorpack/tensorpack | examples/PennTreebank/reader.py | ptb_producer | def ptb_producer(raw_data, batch_size, num_steps, name=None):
"""Iterate on the raw PTB data.
This chunks up raw_data into batches of examples and returns Tensors that
are drawn from these batches.
Args:
raw_data: one of the raw data outputs from ptb_raw_data.
batch_size: int, the batch size.
num_steps: int, the number of unrolls.
name: the name of this operation (optional).
Returns:
A pair of Tensors, each shaped [batch_size, num_steps]. The second element
of the tuple is the same data time-shifted to the right by one.
Raises:
tf.errors.InvalidArgumentError: if batch_size or num_steps are too high.
"""
with tf.name_scope(name, "PTBProducer", [raw_data, batch_size, num_steps]):
raw_data = tf.convert_to_tensor(raw_data, name="raw_data", dtype=tf.int32)
data_len = tf.size(raw_data)
batch_len = data_len // batch_size
data = tf.reshape(raw_data[0 : batch_size * batch_len],
[batch_size, batch_len])
epoch_size = (batch_len - 1) // num_steps
assertion = tf.assert_positive(
epoch_size,
message="epoch_size == 0, decrease batch_size or num_steps")
with tf.control_dependencies([assertion]):
epoch_size = tf.identity(epoch_size, name="epoch_size")
i = tf.train.range_input_producer(epoch_size, shuffle=False).dequeue()
x = tf.strided_slice(data, [0, i * num_steps],
[batch_size, (i + 1) * num_steps])
x.set_shape([batch_size, num_steps])
y = tf.strided_slice(data, [0, i * num_steps + 1],
[batch_size, (i + 1) * num_steps + 1])
y.set_shape([batch_size, num_steps])
return x, y | python | def ptb_producer(raw_data, batch_size, num_steps, name=None):
"""Iterate on the raw PTB data.
This chunks up raw_data into batches of examples and returns Tensors that
are drawn from these batches.
Args:
raw_data: one of the raw data outputs from ptb_raw_data.
batch_size: int, the batch size.
num_steps: int, the number of unrolls.
name: the name of this operation (optional).
Returns:
A pair of Tensors, each shaped [batch_size, num_steps]. The second element
of the tuple is the same data time-shifted to the right by one.
Raises:
tf.errors.InvalidArgumentError: if batch_size or num_steps are too high.
"""
with tf.name_scope(name, "PTBProducer", [raw_data, batch_size, num_steps]):
raw_data = tf.convert_to_tensor(raw_data, name="raw_data", dtype=tf.int32)
data_len = tf.size(raw_data)
batch_len = data_len // batch_size
data = tf.reshape(raw_data[0 : batch_size * batch_len],
[batch_size, batch_len])
epoch_size = (batch_len - 1) // num_steps
assertion = tf.assert_positive(
epoch_size,
message="epoch_size == 0, decrease batch_size or num_steps")
with tf.control_dependencies([assertion]):
epoch_size = tf.identity(epoch_size, name="epoch_size")
i = tf.train.range_input_producer(epoch_size, shuffle=False).dequeue()
x = tf.strided_slice(data, [0, i * num_steps],
[batch_size, (i + 1) * num_steps])
x.set_shape([batch_size, num_steps])
y = tf.strided_slice(data, [0, i * num_steps + 1],
[batch_size, (i + 1) * num_steps + 1])
y.set_shape([batch_size, num_steps])
return x, y | [
"def",
"ptb_producer",
"(",
"raw_data",
",",
"batch_size",
",",
"num_steps",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"\"PTBProducer\"",
",",
"[",
"raw_data",
",",
"batch_size",
",",
"num_steps",
"]",
")",
":",
"raw_data",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"raw_data",
",",
"name",
"=",
"\"raw_data\"",
",",
"dtype",
"=",
"tf",
".",
"int32",
")",
"data_len",
"=",
"tf",
".",
"size",
"(",
"raw_data",
")",
"batch_len",
"=",
"data_len",
"//",
"batch_size",
"data",
"=",
"tf",
".",
"reshape",
"(",
"raw_data",
"[",
"0",
":",
"batch_size",
"*",
"batch_len",
"]",
",",
"[",
"batch_size",
",",
"batch_len",
"]",
")",
"epoch_size",
"=",
"(",
"batch_len",
"-",
"1",
")",
"//",
"num_steps",
"assertion",
"=",
"tf",
".",
"assert_positive",
"(",
"epoch_size",
",",
"message",
"=",
"\"epoch_size == 0, decrease batch_size or num_steps\"",
")",
"with",
"tf",
".",
"control_dependencies",
"(",
"[",
"assertion",
"]",
")",
":",
"epoch_size",
"=",
"tf",
".",
"identity",
"(",
"epoch_size",
",",
"name",
"=",
"\"epoch_size\"",
")",
"i",
"=",
"tf",
".",
"train",
".",
"range_input_producer",
"(",
"epoch_size",
",",
"shuffle",
"=",
"False",
")",
".",
"dequeue",
"(",
")",
"x",
"=",
"tf",
".",
"strided_slice",
"(",
"data",
",",
"[",
"0",
",",
"i",
"*",
"num_steps",
"]",
",",
"[",
"batch_size",
",",
"(",
"i",
"+",
"1",
")",
"*",
"num_steps",
"]",
")",
"x",
".",
"set_shape",
"(",
"[",
"batch_size",
",",
"num_steps",
"]",
")",
"y",
"=",
"tf",
".",
"strided_slice",
"(",
"data",
",",
"[",
"0",
",",
"i",
"*",
"num_steps",
"+",
"1",
"]",
",",
"[",
"batch_size",
",",
"(",
"i",
"+",
"1",
")",
"*",
"num_steps",
"+",
"1",
"]",
")",
"y",
".",
"set_shape",
"(",
"[",
"batch_size",
",",
"num_steps",
"]",
")",
"return",
"x",
",",
"y"
] | Iterate on the raw PTB data.
This chunks up raw_data into batches of examples and returns Tensors that
are drawn from these batches.
Args:
raw_data: one of the raw data outputs from ptb_raw_data.
batch_size: int, the batch size.
num_steps: int, the number of unrolls.
name: the name of this operation (optional).
Returns:
A pair of Tensors, each shaped [batch_size, num_steps]. The second element
of the tuple is the same data time-shifted to the right by one.
Raises:
tf.errors.InvalidArgumentError: if batch_size or num_steps are too high. | [
"Iterate",
"on",
"the",
"raw",
"PTB",
"data",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/PennTreebank/reader.py#L78-L119 |
27,368 | tensorpack/tensorpack | examples/HED/hed.py | CaffeBilinearUpSample | def CaffeBilinearUpSample(x, shape):
"""
Deterministic bilinearly-upsample the input images.
It is implemented by deconvolution with "BilinearFiller" in Caffe.
It is aimed to mimic caffe behavior.
Args:
x (tf.Tensor): a NCHW tensor
shape (int): the upsample factor
Returns:
tf.Tensor: a NCHW tensor.
"""
inp_shape = x.shape.as_list()
ch = inp_shape[1]
assert ch == 1, "This layer only works for channel=1"
# for a version that supports >1 channels, see:
# https://github.com/tensorpack/tensorpack/issues/1040#issuecomment-452798180
shape = int(shape)
filter_shape = 2 * shape
def bilinear_conv_filler(s):
"""
s: width, height of the conv filter
https://github.com/BVLC/caffe/blob/99bd99795dcdf0b1d3086a8d67ab1782a8a08383/include/caffe/filler.hpp#L219-L268
"""
f = np.ceil(float(s) / 2)
c = float(2 * f - 1 - f % 2) / (2 * f)
ret = np.zeros((s, s), dtype='float32')
for x in range(s):
for y in range(s):
ret[x, y] = (1 - abs(x / f - c)) * (1 - abs(y / f - c))
return ret
w = bilinear_conv_filler(filter_shape)
w = np.repeat(w, ch * ch).reshape((filter_shape, filter_shape, ch, ch))
weight_var = tf.constant(w, tf.float32,
shape=(filter_shape, filter_shape, ch, ch),
name='bilinear_upsample_filter')
x = tf.pad(x, [[0, 0], [0, 0], [shape - 1, shape - 1], [shape - 1, shape - 1]], mode='SYMMETRIC')
out_shape = tf.shape(x) * tf.constant([1, 1, shape, shape], tf.int32)
deconv = tf.nn.conv2d_transpose(x, weight_var, out_shape,
[1, 1, shape, shape], 'SAME', data_format='NCHW')
edge = shape * (shape - 1)
deconv = deconv[:, :, edge:-edge, edge:-edge]
if inp_shape[2]:
inp_shape[2] *= shape
if inp_shape[3]:
inp_shape[3] *= shape
deconv.set_shape(inp_shape)
return deconv | python | def CaffeBilinearUpSample(x, shape):
"""
Deterministic bilinearly-upsample the input images.
It is implemented by deconvolution with "BilinearFiller" in Caffe.
It is aimed to mimic caffe behavior.
Args:
x (tf.Tensor): a NCHW tensor
shape (int): the upsample factor
Returns:
tf.Tensor: a NCHW tensor.
"""
inp_shape = x.shape.as_list()
ch = inp_shape[1]
assert ch == 1, "This layer only works for channel=1"
# for a version that supports >1 channels, see:
# https://github.com/tensorpack/tensorpack/issues/1040#issuecomment-452798180
shape = int(shape)
filter_shape = 2 * shape
def bilinear_conv_filler(s):
"""
s: width, height of the conv filter
https://github.com/BVLC/caffe/blob/99bd99795dcdf0b1d3086a8d67ab1782a8a08383/include/caffe/filler.hpp#L219-L268
"""
f = np.ceil(float(s) / 2)
c = float(2 * f - 1 - f % 2) / (2 * f)
ret = np.zeros((s, s), dtype='float32')
for x in range(s):
for y in range(s):
ret[x, y] = (1 - abs(x / f - c)) * (1 - abs(y / f - c))
return ret
w = bilinear_conv_filler(filter_shape)
w = np.repeat(w, ch * ch).reshape((filter_shape, filter_shape, ch, ch))
weight_var = tf.constant(w, tf.float32,
shape=(filter_shape, filter_shape, ch, ch),
name='bilinear_upsample_filter')
x = tf.pad(x, [[0, 0], [0, 0], [shape - 1, shape - 1], [shape - 1, shape - 1]], mode='SYMMETRIC')
out_shape = tf.shape(x) * tf.constant([1, 1, shape, shape], tf.int32)
deconv = tf.nn.conv2d_transpose(x, weight_var, out_shape,
[1, 1, shape, shape], 'SAME', data_format='NCHW')
edge = shape * (shape - 1)
deconv = deconv[:, :, edge:-edge, edge:-edge]
if inp_shape[2]:
inp_shape[2] *= shape
if inp_shape[3]:
inp_shape[3] *= shape
deconv.set_shape(inp_shape)
return deconv | [
"def",
"CaffeBilinearUpSample",
"(",
"x",
",",
"shape",
")",
":",
"inp_shape",
"=",
"x",
".",
"shape",
".",
"as_list",
"(",
")",
"ch",
"=",
"inp_shape",
"[",
"1",
"]",
"assert",
"ch",
"==",
"1",
",",
"\"This layer only works for channel=1\"",
"# for a version that supports >1 channels, see:",
"# https://github.com/tensorpack/tensorpack/issues/1040#issuecomment-452798180",
"shape",
"=",
"int",
"(",
"shape",
")",
"filter_shape",
"=",
"2",
"*",
"shape",
"def",
"bilinear_conv_filler",
"(",
"s",
")",
":",
"\"\"\"\n s: width, height of the conv filter\n https://github.com/BVLC/caffe/blob/99bd99795dcdf0b1d3086a8d67ab1782a8a08383/include/caffe/filler.hpp#L219-L268\n \"\"\"",
"f",
"=",
"np",
".",
"ceil",
"(",
"float",
"(",
"s",
")",
"/",
"2",
")",
"c",
"=",
"float",
"(",
"2",
"*",
"f",
"-",
"1",
"-",
"f",
"%",
"2",
")",
"/",
"(",
"2",
"*",
"f",
")",
"ret",
"=",
"np",
".",
"zeros",
"(",
"(",
"s",
",",
"s",
")",
",",
"dtype",
"=",
"'float32'",
")",
"for",
"x",
"in",
"range",
"(",
"s",
")",
":",
"for",
"y",
"in",
"range",
"(",
"s",
")",
":",
"ret",
"[",
"x",
",",
"y",
"]",
"=",
"(",
"1",
"-",
"abs",
"(",
"x",
"/",
"f",
"-",
"c",
")",
")",
"*",
"(",
"1",
"-",
"abs",
"(",
"y",
"/",
"f",
"-",
"c",
")",
")",
"return",
"ret",
"w",
"=",
"bilinear_conv_filler",
"(",
"filter_shape",
")",
"w",
"=",
"np",
".",
"repeat",
"(",
"w",
",",
"ch",
"*",
"ch",
")",
".",
"reshape",
"(",
"(",
"filter_shape",
",",
"filter_shape",
",",
"ch",
",",
"ch",
")",
")",
"weight_var",
"=",
"tf",
".",
"constant",
"(",
"w",
",",
"tf",
".",
"float32",
",",
"shape",
"=",
"(",
"filter_shape",
",",
"filter_shape",
",",
"ch",
",",
"ch",
")",
",",
"name",
"=",
"'bilinear_upsample_filter'",
")",
"x",
"=",
"tf",
".",
"pad",
"(",
"x",
",",
"[",
"[",
"0",
",",
"0",
"]",
",",
"[",
"0",
",",
"0",
"]",
",",
"[",
"shape",
"-",
"1",
",",
"shape",
"-",
"1",
"]",
",",
"[",
"shape",
"-",
"1",
",",
"shape",
"-",
"1",
"]",
"]",
",",
"mode",
"=",
"'SYMMETRIC'",
")",
"out_shape",
"=",
"tf",
".",
"shape",
"(",
"x",
")",
"*",
"tf",
".",
"constant",
"(",
"[",
"1",
",",
"1",
",",
"shape",
",",
"shape",
"]",
",",
"tf",
".",
"int32",
")",
"deconv",
"=",
"tf",
".",
"nn",
".",
"conv2d_transpose",
"(",
"x",
",",
"weight_var",
",",
"out_shape",
",",
"[",
"1",
",",
"1",
",",
"shape",
",",
"shape",
"]",
",",
"'SAME'",
",",
"data_format",
"=",
"'NCHW'",
")",
"edge",
"=",
"shape",
"*",
"(",
"shape",
"-",
"1",
")",
"deconv",
"=",
"deconv",
"[",
":",
",",
":",
",",
"edge",
":",
"-",
"edge",
",",
"edge",
":",
"-",
"edge",
"]",
"if",
"inp_shape",
"[",
"2",
"]",
":",
"inp_shape",
"[",
"2",
"]",
"*=",
"shape",
"if",
"inp_shape",
"[",
"3",
"]",
":",
"inp_shape",
"[",
"3",
"]",
"*=",
"shape",
"deconv",
".",
"set_shape",
"(",
"inp_shape",
")",
"return",
"deconv"
] | Deterministic bilinearly-upsample the input images.
It is implemented by deconvolution with "BilinearFiller" in Caffe.
It is aimed to mimic caffe behavior.
Args:
x (tf.Tensor): a NCHW tensor
shape (int): the upsample factor
Returns:
tf.Tensor: a NCHW tensor. | [
"Deterministic",
"bilinearly",
"-",
"upsample",
"the",
"input",
"images",
".",
"It",
"is",
"implemented",
"by",
"deconvolution",
"with",
"BilinearFiller",
"in",
"Caffe",
".",
"It",
"is",
"aimed",
"to",
"mimic",
"caffe",
"behavior",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/HED/hed.py#L48-L101 |
27,369 | tensorpack/tensorpack | tensorpack/compat/tensor_spec.py | TensorSpec.is_compatible_with | def is_compatible_with(self, spec_or_tensor):
"""Returns True if spec_or_tensor is compatible with this TensorSpec.
Two tensors are considered compatible if they have the same dtype
and their shapes are compatible (see `tf.TensorShape.is_compatible_with`).
Args:
spec_or_tensor: A tf.TensorSpec or a tf.Tensor
Returns:
True if spec_or_tensor is compatible with self.
"""
return (self._dtype.is_compatible_with(spec_or_tensor.dtype) and
self._shape.is_compatible_with(spec_or_tensor.shape)) | python | def is_compatible_with(self, spec_or_tensor):
"""Returns True if spec_or_tensor is compatible with this TensorSpec.
Two tensors are considered compatible if they have the same dtype
and their shapes are compatible (see `tf.TensorShape.is_compatible_with`).
Args:
spec_or_tensor: A tf.TensorSpec or a tf.Tensor
Returns:
True if spec_or_tensor is compatible with self.
"""
return (self._dtype.is_compatible_with(spec_or_tensor.dtype) and
self._shape.is_compatible_with(spec_or_tensor.shape)) | [
"def",
"is_compatible_with",
"(",
"self",
",",
"spec_or_tensor",
")",
":",
"return",
"(",
"self",
".",
"_dtype",
".",
"is_compatible_with",
"(",
"spec_or_tensor",
".",
"dtype",
")",
"and",
"self",
".",
"_shape",
".",
"is_compatible_with",
"(",
"spec_or_tensor",
".",
"shape",
")",
")"
] | Returns True if spec_or_tensor is compatible with this TensorSpec.
Two tensors are considered compatible if they have the same dtype
and their shapes are compatible (see `tf.TensorShape.is_compatible_with`).
Args:
spec_or_tensor: A tf.TensorSpec or a tf.Tensor
Returns:
True if spec_or_tensor is compatible with self. | [
"Returns",
"True",
"if",
"spec_or_tensor",
"is",
"compatible",
"with",
"this",
"TensorSpec",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/compat/tensor_spec.py#L75-L88 |
27,370 | tensorpack/tensorpack | tensorpack/tfutils/model_utils.py | describe_trainable_vars | def describe_trainable_vars():
"""
Print a description of the current model parameters.
Skip variables starting with "tower", as they are just duplicates built by data-parallel logic.
"""
train_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
if len(train_vars) == 0:
logger.warn("No trainable variables in the graph!")
return
total = 0
total_bytes = 0
data = []
for v in train_vars:
if v.name.startswith('tower'):
continue
shape = v.get_shape()
ele = shape.num_elements()
if ele is None:
logger.warn("Shape of variable {} is not fully defined but {}.".format(v.name, shape))
ele = 0
try:
shape = shape.as_list()
except ValueError:
shape = '<unknown>'
total += ele
total_bytes += ele * v.dtype.size
data.append([v.name, shape, ele, v.device, v.dtype.base_dtype.name])
headers = ['name', 'shape', '#elements', 'device', 'dtype']
dtypes = list(set([x[4] for x in data]))
if len(dtypes) == 1 and dtypes[0] == "float32":
# don't log the dtype if all vars are float32 (default dtype)
for x in data:
del x[4]
del headers[4]
devices = set([x[3] for x in data])
if len(devices) == 1:
# don't log the device if all vars on the same device
for x in data:
del x[3]
del headers[3]
table = tabulate(data, headers=headers)
size_mb = total_bytes / 1024.0**2
summary_msg = colored(
"\nNumber of trainable variables: {}".format(len(data)) +
"\nNumber of parameters (elements): {}".format(total) +
"\nStorage space needed for all trainable variables: {:.02f}MB".format(size_mb),
'cyan')
logger.info(colored("List of Trainable Variables: \n", 'cyan') + table + summary_msg) | python | def describe_trainable_vars():
"""
Print a description of the current model parameters.
Skip variables starting with "tower", as they are just duplicates built by data-parallel logic.
"""
train_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
if len(train_vars) == 0:
logger.warn("No trainable variables in the graph!")
return
total = 0
total_bytes = 0
data = []
for v in train_vars:
if v.name.startswith('tower'):
continue
shape = v.get_shape()
ele = shape.num_elements()
if ele is None:
logger.warn("Shape of variable {} is not fully defined but {}.".format(v.name, shape))
ele = 0
try:
shape = shape.as_list()
except ValueError:
shape = '<unknown>'
total += ele
total_bytes += ele * v.dtype.size
data.append([v.name, shape, ele, v.device, v.dtype.base_dtype.name])
headers = ['name', 'shape', '#elements', 'device', 'dtype']
dtypes = list(set([x[4] for x in data]))
if len(dtypes) == 1 and dtypes[0] == "float32":
# don't log the dtype if all vars are float32 (default dtype)
for x in data:
del x[4]
del headers[4]
devices = set([x[3] for x in data])
if len(devices) == 1:
# don't log the device if all vars on the same device
for x in data:
del x[3]
del headers[3]
table = tabulate(data, headers=headers)
size_mb = total_bytes / 1024.0**2
summary_msg = colored(
"\nNumber of trainable variables: {}".format(len(data)) +
"\nNumber of parameters (elements): {}".format(total) +
"\nStorage space needed for all trainable variables: {:.02f}MB".format(size_mb),
'cyan')
logger.info(colored("List of Trainable Variables: \n", 'cyan') + table + summary_msg) | [
"def",
"describe_trainable_vars",
"(",
")",
":",
"train_vars",
"=",
"tf",
".",
"get_collection",
"(",
"tf",
".",
"GraphKeys",
".",
"TRAINABLE_VARIABLES",
")",
"if",
"len",
"(",
"train_vars",
")",
"==",
"0",
":",
"logger",
".",
"warn",
"(",
"\"No trainable variables in the graph!\"",
")",
"return",
"total",
"=",
"0",
"total_bytes",
"=",
"0",
"data",
"=",
"[",
"]",
"for",
"v",
"in",
"train_vars",
":",
"if",
"v",
".",
"name",
".",
"startswith",
"(",
"'tower'",
")",
":",
"continue",
"shape",
"=",
"v",
".",
"get_shape",
"(",
")",
"ele",
"=",
"shape",
".",
"num_elements",
"(",
")",
"if",
"ele",
"is",
"None",
":",
"logger",
".",
"warn",
"(",
"\"Shape of variable {} is not fully defined but {}.\"",
".",
"format",
"(",
"v",
".",
"name",
",",
"shape",
")",
")",
"ele",
"=",
"0",
"try",
":",
"shape",
"=",
"shape",
".",
"as_list",
"(",
")",
"except",
"ValueError",
":",
"shape",
"=",
"'<unknown>'",
"total",
"+=",
"ele",
"total_bytes",
"+=",
"ele",
"*",
"v",
".",
"dtype",
".",
"size",
"data",
".",
"append",
"(",
"[",
"v",
".",
"name",
",",
"shape",
",",
"ele",
",",
"v",
".",
"device",
",",
"v",
".",
"dtype",
".",
"base_dtype",
".",
"name",
"]",
")",
"headers",
"=",
"[",
"'name'",
",",
"'shape'",
",",
"'#elements'",
",",
"'device'",
",",
"'dtype'",
"]",
"dtypes",
"=",
"list",
"(",
"set",
"(",
"[",
"x",
"[",
"4",
"]",
"for",
"x",
"in",
"data",
"]",
")",
")",
"if",
"len",
"(",
"dtypes",
")",
"==",
"1",
"and",
"dtypes",
"[",
"0",
"]",
"==",
"\"float32\"",
":",
"# don't log the dtype if all vars are float32 (default dtype)",
"for",
"x",
"in",
"data",
":",
"del",
"x",
"[",
"4",
"]",
"del",
"headers",
"[",
"4",
"]",
"devices",
"=",
"set",
"(",
"[",
"x",
"[",
"3",
"]",
"for",
"x",
"in",
"data",
"]",
")",
"if",
"len",
"(",
"devices",
")",
"==",
"1",
":",
"# don't log the device if all vars on the same device",
"for",
"x",
"in",
"data",
":",
"del",
"x",
"[",
"3",
"]",
"del",
"headers",
"[",
"3",
"]",
"table",
"=",
"tabulate",
"(",
"data",
",",
"headers",
"=",
"headers",
")",
"size_mb",
"=",
"total_bytes",
"/",
"1024.0",
"**",
"2",
"summary_msg",
"=",
"colored",
"(",
"\"\\nNumber of trainable variables: {}\"",
".",
"format",
"(",
"len",
"(",
"data",
")",
")",
"+",
"\"\\nNumber of parameters (elements): {}\"",
".",
"format",
"(",
"total",
")",
"+",
"\"\\nStorage space needed for all trainable variables: {:.02f}MB\"",
".",
"format",
"(",
"size_mb",
")",
",",
"'cyan'",
")",
"logger",
".",
"info",
"(",
"colored",
"(",
"\"List of Trainable Variables: \\n\"",
",",
"'cyan'",
")",
"+",
"table",
"+",
"summary_msg",
")"
] | Print a description of the current model parameters.
Skip variables starting with "tower", as they are just duplicates built by data-parallel logic. | [
"Print",
"a",
"description",
"of",
"the",
"current",
"model",
"parameters",
".",
"Skip",
"variables",
"starting",
"with",
"tower",
"as",
"they",
"are",
"just",
"duplicates",
"built",
"by",
"data",
"-",
"parallel",
"logic",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/model_utils.py#L15-L67 |
27,371 | tensorpack/tensorpack | examples/SimilarityLearning/mnist-embeddings.py | EmbeddingModel.embed | def embed(self, x, nfeatures=2):
"""Embed all given tensors into an nfeatures-dim space. """
list_split = 0
if isinstance(x, list):
list_split = len(x)
x = tf.concat(x, 0)
# pre-process MNIST dataflow data
x = tf.expand_dims(x, 3)
x = x * 2 - 1
# the embedding network
net = slim.layers.conv2d(x, 20, 5, scope='conv1')
net = slim.layers.max_pool2d(net, 2, scope='pool1')
net = slim.layers.conv2d(net, 50, 5, scope='conv2')
net = slim.layers.max_pool2d(net, 2, scope='pool2')
net = slim.layers.flatten(net, scope='flatten3')
net = slim.layers.fully_connected(net, 500, scope='fully_connected4')
embeddings = slim.layers.fully_connected(net, nfeatures, activation_fn=None, scope='fully_connected5')
# if "x" was a list of tensors, then split the embeddings
if list_split > 0:
embeddings = tf.split(embeddings, list_split, 0)
return embeddings | python | def embed(self, x, nfeatures=2):
"""Embed all given tensors into an nfeatures-dim space. """
list_split = 0
if isinstance(x, list):
list_split = len(x)
x = tf.concat(x, 0)
# pre-process MNIST dataflow data
x = tf.expand_dims(x, 3)
x = x * 2 - 1
# the embedding network
net = slim.layers.conv2d(x, 20, 5, scope='conv1')
net = slim.layers.max_pool2d(net, 2, scope='pool1')
net = slim.layers.conv2d(net, 50, 5, scope='conv2')
net = slim.layers.max_pool2d(net, 2, scope='pool2')
net = slim.layers.flatten(net, scope='flatten3')
net = slim.layers.fully_connected(net, 500, scope='fully_connected4')
embeddings = slim.layers.fully_connected(net, nfeatures, activation_fn=None, scope='fully_connected5')
# if "x" was a list of tensors, then split the embeddings
if list_split > 0:
embeddings = tf.split(embeddings, list_split, 0)
return embeddings | [
"def",
"embed",
"(",
"self",
",",
"x",
",",
"nfeatures",
"=",
"2",
")",
":",
"list_split",
"=",
"0",
"if",
"isinstance",
"(",
"x",
",",
"list",
")",
":",
"list_split",
"=",
"len",
"(",
"x",
")",
"x",
"=",
"tf",
".",
"concat",
"(",
"x",
",",
"0",
")",
"# pre-process MNIST dataflow data",
"x",
"=",
"tf",
".",
"expand_dims",
"(",
"x",
",",
"3",
")",
"x",
"=",
"x",
"*",
"2",
"-",
"1",
"# the embedding network",
"net",
"=",
"slim",
".",
"layers",
".",
"conv2d",
"(",
"x",
",",
"20",
",",
"5",
",",
"scope",
"=",
"'conv1'",
")",
"net",
"=",
"slim",
".",
"layers",
".",
"max_pool2d",
"(",
"net",
",",
"2",
",",
"scope",
"=",
"'pool1'",
")",
"net",
"=",
"slim",
".",
"layers",
".",
"conv2d",
"(",
"net",
",",
"50",
",",
"5",
",",
"scope",
"=",
"'conv2'",
")",
"net",
"=",
"slim",
".",
"layers",
".",
"max_pool2d",
"(",
"net",
",",
"2",
",",
"scope",
"=",
"'pool2'",
")",
"net",
"=",
"slim",
".",
"layers",
".",
"flatten",
"(",
"net",
",",
"scope",
"=",
"'flatten3'",
")",
"net",
"=",
"slim",
".",
"layers",
".",
"fully_connected",
"(",
"net",
",",
"500",
",",
"scope",
"=",
"'fully_connected4'",
")",
"embeddings",
"=",
"slim",
".",
"layers",
".",
"fully_connected",
"(",
"net",
",",
"nfeatures",
",",
"activation_fn",
"=",
"None",
",",
"scope",
"=",
"'fully_connected5'",
")",
"# if \"x\" was a list of tensors, then split the embeddings",
"if",
"list_split",
">",
"0",
":",
"embeddings",
"=",
"tf",
".",
"split",
"(",
"embeddings",
",",
"list_split",
",",
"0",
")",
"return",
"embeddings"
] | Embed all given tensors into an nfeatures-dim space. | [
"Embed",
"all",
"given",
"tensors",
"into",
"an",
"nfeatures",
"-",
"dim",
"space",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/SimilarityLearning/mnist-embeddings.py#L200-L224 |
27,372 | tensorpack/tensorpack | tensorpack/graph_builder/utils.py | allreduce_grads | def allreduce_grads(all_grads, average):
"""
All-reduce average the gradients among K devices. Results are broadcasted to all devices.
Args:
all_grads (K x N): List of list of gradients. N is the number of variables.
average (bool): average gradients or not.
Returns:
K x N: same as input, but each grad is replaced by the average over K devices.
"""
if get_tf_version_tuple() <= (1, 12):
from tensorflow.contrib import nccl
else:
from tensorflow.python.ops import nccl_ops as nccl
nr_tower = len(all_grads)
if nr_tower == 1:
return all_grads
new_all_grads = [] # N x K
for grads in zip(*all_grads):
summed = nccl.all_sum(grads)
grads_for_devices = [] # K
for g in summed:
with tf.device(g.device):
# tensorflow/benchmarks didn't average gradients
if average:
g = tf.multiply(g, 1.0 / nr_tower)
grads_for_devices.append(g)
new_all_grads.append(grads_for_devices)
# transpose to K x N
ret = list(zip(*new_all_grads))
return ret | python | def allreduce_grads(all_grads, average):
"""
All-reduce average the gradients among K devices. Results are broadcasted to all devices.
Args:
all_grads (K x N): List of list of gradients. N is the number of variables.
average (bool): average gradients or not.
Returns:
K x N: same as input, but each grad is replaced by the average over K devices.
"""
if get_tf_version_tuple() <= (1, 12):
from tensorflow.contrib import nccl
else:
from tensorflow.python.ops import nccl_ops as nccl
nr_tower = len(all_grads)
if nr_tower == 1:
return all_grads
new_all_grads = [] # N x K
for grads in zip(*all_grads):
summed = nccl.all_sum(grads)
grads_for_devices = [] # K
for g in summed:
with tf.device(g.device):
# tensorflow/benchmarks didn't average gradients
if average:
g = tf.multiply(g, 1.0 / nr_tower)
grads_for_devices.append(g)
new_all_grads.append(grads_for_devices)
# transpose to K x N
ret = list(zip(*new_all_grads))
return ret | [
"def",
"allreduce_grads",
"(",
"all_grads",
",",
"average",
")",
":",
"if",
"get_tf_version_tuple",
"(",
")",
"<=",
"(",
"1",
",",
"12",
")",
":",
"from",
"tensorflow",
".",
"contrib",
"import",
"nccl",
"else",
":",
"from",
"tensorflow",
".",
"python",
".",
"ops",
"import",
"nccl_ops",
"as",
"nccl",
"nr_tower",
"=",
"len",
"(",
"all_grads",
")",
"if",
"nr_tower",
"==",
"1",
":",
"return",
"all_grads",
"new_all_grads",
"=",
"[",
"]",
"# N x K",
"for",
"grads",
"in",
"zip",
"(",
"*",
"all_grads",
")",
":",
"summed",
"=",
"nccl",
".",
"all_sum",
"(",
"grads",
")",
"grads_for_devices",
"=",
"[",
"]",
"# K",
"for",
"g",
"in",
"summed",
":",
"with",
"tf",
".",
"device",
"(",
"g",
".",
"device",
")",
":",
"# tensorflow/benchmarks didn't average gradients",
"if",
"average",
":",
"g",
"=",
"tf",
".",
"multiply",
"(",
"g",
",",
"1.0",
"/",
"nr_tower",
")",
"grads_for_devices",
".",
"append",
"(",
"g",
")",
"new_all_grads",
".",
"append",
"(",
"grads_for_devices",
")",
"# transpose to K x N",
"ret",
"=",
"list",
"(",
"zip",
"(",
"*",
"new_all_grads",
")",
")",
"return",
"ret"
] | All-reduce average the gradients among K devices. Results are broadcasted to all devices.
Args:
all_grads (K x N): List of list of gradients. N is the number of variables.
average (bool): average gradients or not.
Returns:
K x N: same as input, but each grad is replaced by the average over K devices. | [
"All",
"-",
"reduce",
"average",
"the",
"gradients",
"among",
"K",
"devices",
".",
"Results",
"are",
"broadcasted",
"to",
"all",
"devices",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L139-L173 |
27,373 | tensorpack/tensorpack | tensorpack/graph_builder/utils.py | allreduce_grads_hierarchical | def allreduce_grads_hierarchical(all_grads, devices, average=False):
"""
Hierarchical allreduce for DGX-1 system.
Args:
all_grads (K x N): List of list of gradients. N is the number of variables.
devices ([str]): K str for the K devices.
average (bool): average gradients or not.
Returns:
(K x N): same as input, but each grad is replaced by the average over K lists.
"""
num_gpu = len(devices)
assert num_gpu == 8, num_gpu
assert len(all_grads) == num_gpu, len(all_grads)
group_size = num_gpu // 2
agg_all_grads = [] # N x K
for varid, grads in enumerate(zip(*all_grads)):
# grads: K gradients
g0_main_gpu = varid % num_gpu
g1_main_gpu = (g0_main_gpu + group_size) % num_gpu
g0_start = 0 if g0_main_gpu < group_size else group_size
g1_start = 0 if g1_main_gpu < group_size else group_size
assert g0_start != g1_start
g0_grads = grads[g0_start: g0_start + group_size]
g1_grads = grads[g1_start: g1_start + group_size]
with tf.device(devices[g0_main_gpu]):
g0_agg = tf.add_n(g0_grads, name='group0_agg')
with tf.device(devices[g1_main_gpu]):
g1_agg = tf.add_n(g1_grads, name='group1_agg')
g1_total_agg = tf.add(g0_agg, g1_agg, name='group1_total_agg')
with tf.device(devices[g0_main_gpu]):
g0_total_agg = tf.identity(g1_total_agg, name='group0_total_agg')
agg_grads = [] # K aggregated grads
for k in range(num_gpu):
if (k < group_size) == (g0_main_gpu < group_size):
main_gpu = g0_total_agg
else:
main_gpu = g1_total_agg
with tf.device(devices[k]):
if not average:
device_total_agg = tf.identity(
main_gpu, name='device{}_total_agg'.format(k))
else:
# TODO where to put average?
device_total_agg = tf.multiply(
main_gpu, 1.0 / num_gpu, name='device{}_total_agg'.format(k))
agg_grads.append(device_total_agg)
agg_all_grads.append(agg_grads)
# transpose
agg_all_grads = list(zip(*agg_all_grads)) # K x Nvar
return agg_all_grads | python | def allreduce_grads_hierarchical(all_grads, devices, average=False):
"""
Hierarchical allreduce for DGX-1 system.
Args:
all_grads (K x N): List of list of gradients. N is the number of variables.
devices ([str]): K str for the K devices.
average (bool): average gradients or not.
Returns:
(K x N): same as input, but each grad is replaced by the average over K lists.
"""
num_gpu = len(devices)
assert num_gpu == 8, num_gpu
assert len(all_grads) == num_gpu, len(all_grads)
group_size = num_gpu // 2
agg_all_grads = [] # N x K
for varid, grads in enumerate(zip(*all_grads)):
# grads: K gradients
g0_main_gpu = varid % num_gpu
g1_main_gpu = (g0_main_gpu + group_size) % num_gpu
g0_start = 0 if g0_main_gpu < group_size else group_size
g1_start = 0 if g1_main_gpu < group_size else group_size
assert g0_start != g1_start
g0_grads = grads[g0_start: g0_start + group_size]
g1_grads = grads[g1_start: g1_start + group_size]
with tf.device(devices[g0_main_gpu]):
g0_agg = tf.add_n(g0_grads, name='group0_agg')
with tf.device(devices[g1_main_gpu]):
g1_agg = tf.add_n(g1_grads, name='group1_agg')
g1_total_agg = tf.add(g0_agg, g1_agg, name='group1_total_agg')
with tf.device(devices[g0_main_gpu]):
g0_total_agg = tf.identity(g1_total_agg, name='group0_total_agg')
agg_grads = [] # K aggregated grads
for k in range(num_gpu):
if (k < group_size) == (g0_main_gpu < group_size):
main_gpu = g0_total_agg
else:
main_gpu = g1_total_agg
with tf.device(devices[k]):
if not average:
device_total_agg = tf.identity(
main_gpu, name='device{}_total_agg'.format(k))
else:
# TODO where to put average?
device_total_agg = tf.multiply(
main_gpu, 1.0 / num_gpu, name='device{}_total_agg'.format(k))
agg_grads.append(device_total_agg)
agg_all_grads.append(agg_grads)
# transpose
agg_all_grads = list(zip(*agg_all_grads)) # K x Nvar
return agg_all_grads | [
"def",
"allreduce_grads_hierarchical",
"(",
"all_grads",
",",
"devices",
",",
"average",
"=",
"False",
")",
":",
"num_gpu",
"=",
"len",
"(",
"devices",
")",
"assert",
"num_gpu",
"==",
"8",
",",
"num_gpu",
"assert",
"len",
"(",
"all_grads",
")",
"==",
"num_gpu",
",",
"len",
"(",
"all_grads",
")",
"group_size",
"=",
"num_gpu",
"//",
"2",
"agg_all_grads",
"=",
"[",
"]",
"# N x K",
"for",
"varid",
",",
"grads",
"in",
"enumerate",
"(",
"zip",
"(",
"*",
"all_grads",
")",
")",
":",
"# grads: K gradients",
"g0_main_gpu",
"=",
"varid",
"%",
"num_gpu",
"g1_main_gpu",
"=",
"(",
"g0_main_gpu",
"+",
"group_size",
")",
"%",
"num_gpu",
"g0_start",
"=",
"0",
"if",
"g0_main_gpu",
"<",
"group_size",
"else",
"group_size",
"g1_start",
"=",
"0",
"if",
"g1_main_gpu",
"<",
"group_size",
"else",
"group_size",
"assert",
"g0_start",
"!=",
"g1_start",
"g0_grads",
"=",
"grads",
"[",
"g0_start",
":",
"g0_start",
"+",
"group_size",
"]",
"g1_grads",
"=",
"grads",
"[",
"g1_start",
":",
"g1_start",
"+",
"group_size",
"]",
"with",
"tf",
".",
"device",
"(",
"devices",
"[",
"g0_main_gpu",
"]",
")",
":",
"g0_agg",
"=",
"tf",
".",
"add_n",
"(",
"g0_grads",
",",
"name",
"=",
"'group0_agg'",
")",
"with",
"tf",
".",
"device",
"(",
"devices",
"[",
"g1_main_gpu",
"]",
")",
":",
"g1_agg",
"=",
"tf",
".",
"add_n",
"(",
"g1_grads",
",",
"name",
"=",
"'group1_agg'",
")",
"g1_total_agg",
"=",
"tf",
".",
"add",
"(",
"g0_agg",
",",
"g1_agg",
",",
"name",
"=",
"'group1_total_agg'",
")",
"with",
"tf",
".",
"device",
"(",
"devices",
"[",
"g0_main_gpu",
"]",
")",
":",
"g0_total_agg",
"=",
"tf",
".",
"identity",
"(",
"g1_total_agg",
",",
"name",
"=",
"'group0_total_agg'",
")",
"agg_grads",
"=",
"[",
"]",
"# K aggregated grads",
"for",
"k",
"in",
"range",
"(",
"num_gpu",
")",
":",
"if",
"(",
"k",
"<",
"group_size",
")",
"==",
"(",
"g0_main_gpu",
"<",
"group_size",
")",
":",
"main_gpu",
"=",
"g0_total_agg",
"else",
":",
"main_gpu",
"=",
"g1_total_agg",
"with",
"tf",
".",
"device",
"(",
"devices",
"[",
"k",
"]",
")",
":",
"if",
"not",
"average",
":",
"device_total_agg",
"=",
"tf",
".",
"identity",
"(",
"main_gpu",
",",
"name",
"=",
"'device{}_total_agg'",
".",
"format",
"(",
"k",
")",
")",
"else",
":",
"# TODO where to put average?",
"device_total_agg",
"=",
"tf",
".",
"multiply",
"(",
"main_gpu",
",",
"1.0",
"/",
"num_gpu",
",",
"name",
"=",
"'device{}_total_agg'",
".",
"format",
"(",
"k",
")",
")",
"agg_grads",
".",
"append",
"(",
"device_total_agg",
")",
"agg_all_grads",
".",
"append",
"(",
"agg_grads",
")",
"# transpose",
"agg_all_grads",
"=",
"list",
"(",
"zip",
"(",
"*",
"agg_all_grads",
")",
")",
"# K x Nvar",
"return",
"agg_all_grads"
] | Hierarchical allreduce for DGX-1 system.
Args:
all_grads (K x N): List of list of gradients. N is the number of variables.
devices ([str]): K str for the K devices.
average (bool): average gradients or not.
Returns:
(K x N): same as input, but each grad is replaced by the average over K lists. | [
"Hierarchical",
"allreduce",
"for",
"DGX",
"-",
"1",
"system",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L177-L235 |
27,374 | tensorpack/tensorpack | tensorpack/graph_builder/utils.py | aggregate_grads | def aggregate_grads(all_grads,
colocation=False,
devices=None,
average=True):
"""
Average the gradients.
Args:
all_grads (K x N x 2): A list of K lists. Each of the list is a list of N (grad, var) tuples.
The variables have to be the same across the K lists.
colocation (bool): colocate gradient averaging on the device of the variable.
devices (list[str]): assign the averaging to these device in
round-robin. Cannot be used together with ``colocation``.
average (bool): do average or sum
Returns:
(N x 2): A list of N (grad, var) tuples, where grad is averaged or summed over K.
"""
assert not (devices is not None and colocation)
if devices is not None:
assert isinstance(devices, list), devices
nr_tower = len(all_grads)
if nr_tower == 1:
return all_grads[0]
def aggregate(grads):
if average:
return tf.multiply(tf.add_n(grads), 1.0 / nr_tower)
else:
return tf.add_n(grads)
ret = []
for idx, grad_and_vars in enumerate(zip(*all_grads)):
# Ngpu * 2
v = grad_and_vars[0][1]
grads = [g for (g, _) in grad_and_vars]
if colocation:
with tf.device(v.device): # colocate summed grad with var
grad = aggregate(grads)
elif devices is None:
grad = aggregate(grads)
else:
dev = devices[idx % len(devices)]
with tf.device(dev):
grad = aggregate(grads)
ret.append((grad, v))
return ret | python | def aggregate_grads(all_grads,
colocation=False,
devices=None,
average=True):
"""
Average the gradients.
Args:
all_grads (K x N x 2): A list of K lists. Each of the list is a list of N (grad, var) tuples.
The variables have to be the same across the K lists.
colocation (bool): colocate gradient averaging on the device of the variable.
devices (list[str]): assign the averaging to these device in
round-robin. Cannot be used together with ``colocation``.
average (bool): do average or sum
Returns:
(N x 2): A list of N (grad, var) tuples, where grad is averaged or summed over K.
"""
assert not (devices is not None and colocation)
if devices is not None:
assert isinstance(devices, list), devices
nr_tower = len(all_grads)
if nr_tower == 1:
return all_grads[0]
def aggregate(grads):
if average:
return tf.multiply(tf.add_n(grads), 1.0 / nr_tower)
else:
return tf.add_n(grads)
ret = []
for idx, grad_and_vars in enumerate(zip(*all_grads)):
# Ngpu * 2
v = grad_and_vars[0][1]
grads = [g for (g, _) in grad_and_vars]
if colocation:
with tf.device(v.device): # colocate summed grad with var
grad = aggregate(grads)
elif devices is None:
grad = aggregate(grads)
else:
dev = devices[idx % len(devices)]
with tf.device(dev):
grad = aggregate(grads)
ret.append((grad, v))
return ret | [
"def",
"aggregate_grads",
"(",
"all_grads",
",",
"colocation",
"=",
"False",
",",
"devices",
"=",
"None",
",",
"average",
"=",
"True",
")",
":",
"assert",
"not",
"(",
"devices",
"is",
"not",
"None",
"and",
"colocation",
")",
"if",
"devices",
"is",
"not",
"None",
":",
"assert",
"isinstance",
"(",
"devices",
",",
"list",
")",
",",
"devices",
"nr_tower",
"=",
"len",
"(",
"all_grads",
")",
"if",
"nr_tower",
"==",
"1",
":",
"return",
"all_grads",
"[",
"0",
"]",
"def",
"aggregate",
"(",
"grads",
")",
":",
"if",
"average",
":",
"return",
"tf",
".",
"multiply",
"(",
"tf",
".",
"add_n",
"(",
"grads",
")",
",",
"1.0",
"/",
"nr_tower",
")",
"else",
":",
"return",
"tf",
".",
"add_n",
"(",
"grads",
")",
"ret",
"=",
"[",
"]",
"for",
"idx",
",",
"grad_and_vars",
"in",
"enumerate",
"(",
"zip",
"(",
"*",
"all_grads",
")",
")",
":",
"# Ngpu * 2",
"v",
"=",
"grad_and_vars",
"[",
"0",
"]",
"[",
"1",
"]",
"grads",
"=",
"[",
"g",
"for",
"(",
"g",
",",
"_",
")",
"in",
"grad_and_vars",
"]",
"if",
"colocation",
":",
"with",
"tf",
".",
"device",
"(",
"v",
".",
"device",
")",
":",
"# colocate summed grad with var",
"grad",
"=",
"aggregate",
"(",
"grads",
")",
"elif",
"devices",
"is",
"None",
":",
"grad",
"=",
"aggregate",
"(",
"grads",
")",
"else",
":",
"dev",
"=",
"devices",
"[",
"idx",
"%",
"len",
"(",
"devices",
")",
"]",
"with",
"tf",
".",
"device",
"(",
"dev",
")",
":",
"grad",
"=",
"aggregate",
"(",
"grads",
")",
"ret",
".",
"append",
"(",
"(",
"grad",
",",
"v",
")",
")",
"return",
"ret"
] | Average the gradients.
Args:
all_grads (K x N x 2): A list of K lists. Each of the list is a list of N (grad, var) tuples.
The variables have to be the same across the K lists.
colocation (bool): colocate gradient averaging on the device of the variable.
devices (list[str]): assign the averaging to these device in
round-robin. Cannot be used together with ``colocation``.
average (bool): do average or sum
Returns:
(N x 2): A list of N (grad, var) tuples, where grad is averaged or summed over K. | [
"Average",
"the",
"gradients",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L239-L287 |
27,375 | tensorpack/tensorpack | examples/FasterRCNN/model_fpn.py | fpn_map_rois_to_levels | def fpn_map_rois_to_levels(boxes):
"""
Assign boxes to level 2~5.
Args:
boxes (nx4):
Returns:
[tf.Tensor]: 4 tensors for level 2-5. Each tensor is a vector of indices of boxes in its level.
[tf.Tensor]: 4 tensors, the gathered boxes in each level.
Be careful that the returned tensor could be empty.
"""
sqrtarea = tf.sqrt(tf_area(boxes))
level = tf.cast(tf.floor(
4 + tf.log(sqrtarea * (1. / 224) + 1e-6) * (1.0 / np.log(2))), tf.int32)
# RoI levels range from 2~5 (not 6)
level_ids = [
tf.where(level <= 2),
tf.where(tf.equal(level, 3)), # == is not supported
tf.where(tf.equal(level, 4)),
tf.where(level >= 5)]
level_ids = [tf.reshape(x, [-1], name='roi_level{}_id'.format(i + 2))
for i, x in enumerate(level_ids)]
num_in_levels = [tf.size(x, name='num_roi_level{}'.format(i + 2))
for i, x in enumerate(level_ids)]
add_moving_summary(*num_in_levels)
level_boxes = [tf.gather(boxes, ids) for ids in level_ids]
return level_ids, level_boxes | python | def fpn_map_rois_to_levels(boxes):
"""
Assign boxes to level 2~5.
Args:
boxes (nx4):
Returns:
[tf.Tensor]: 4 tensors for level 2-5. Each tensor is a vector of indices of boxes in its level.
[tf.Tensor]: 4 tensors, the gathered boxes in each level.
Be careful that the returned tensor could be empty.
"""
sqrtarea = tf.sqrt(tf_area(boxes))
level = tf.cast(tf.floor(
4 + tf.log(sqrtarea * (1. / 224) + 1e-6) * (1.0 / np.log(2))), tf.int32)
# RoI levels range from 2~5 (not 6)
level_ids = [
tf.where(level <= 2),
tf.where(tf.equal(level, 3)), # == is not supported
tf.where(tf.equal(level, 4)),
tf.where(level >= 5)]
level_ids = [tf.reshape(x, [-1], name='roi_level{}_id'.format(i + 2))
for i, x in enumerate(level_ids)]
num_in_levels = [tf.size(x, name='num_roi_level{}'.format(i + 2))
for i, x in enumerate(level_ids)]
add_moving_summary(*num_in_levels)
level_boxes = [tf.gather(boxes, ids) for ids in level_ids]
return level_ids, level_boxes | [
"def",
"fpn_map_rois_to_levels",
"(",
"boxes",
")",
":",
"sqrtarea",
"=",
"tf",
".",
"sqrt",
"(",
"tf_area",
"(",
"boxes",
")",
")",
"level",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"floor",
"(",
"4",
"+",
"tf",
".",
"log",
"(",
"sqrtarea",
"*",
"(",
"1.",
"/",
"224",
")",
"+",
"1e-6",
")",
"*",
"(",
"1.0",
"/",
"np",
".",
"log",
"(",
"2",
")",
")",
")",
",",
"tf",
".",
"int32",
")",
"# RoI levels range from 2~5 (not 6)",
"level_ids",
"=",
"[",
"tf",
".",
"where",
"(",
"level",
"<=",
"2",
")",
",",
"tf",
".",
"where",
"(",
"tf",
".",
"equal",
"(",
"level",
",",
"3",
")",
")",
",",
"# == is not supported",
"tf",
".",
"where",
"(",
"tf",
".",
"equal",
"(",
"level",
",",
"4",
")",
")",
",",
"tf",
".",
"where",
"(",
"level",
">=",
"5",
")",
"]",
"level_ids",
"=",
"[",
"tf",
".",
"reshape",
"(",
"x",
",",
"[",
"-",
"1",
"]",
",",
"name",
"=",
"'roi_level{}_id'",
".",
"format",
"(",
"i",
"+",
"2",
")",
")",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"level_ids",
")",
"]",
"num_in_levels",
"=",
"[",
"tf",
".",
"size",
"(",
"x",
",",
"name",
"=",
"'num_roi_level{}'",
".",
"format",
"(",
"i",
"+",
"2",
")",
")",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"level_ids",
")",
"]",
"add_moving_summary",
"(",
"*",
"num_in_levels",
")",
"level_boxes",
"=",
"[",
"tf",
".",
"gather",
"(",
"boxes",
",",
"ids",
")",
"for",
"ids",
"in",
"level_ids",
"]",
"return",
"level_ids",
",",
"level_boxes"
] | Assign boxes to level 2~5.
Args:
boxes (nx4):
Returns:
[tf.Tensor]: 4 tensors for level 2-5. Each tensor is a vector of indices of boxes in its level.
[tf.Tensor]: 4 tensors, the gathered boxes in each level.
Be careful that the returned tensor could be empty. | [
"Assign",
"boxes",
"to",
"level",
"2~5",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_fpn.py#L70-L100 |
27,376 | tensorpack/tensorpack | examples/FasterRCNN/model_frcnn.py | proposal_metrics | def proposal_metrics(iou):
"""
Add summaries for RPN proposals.
Args:
iou: nxm, #proposal x #gt
"""
# find best roi for each gt, for summary only
best_iou = tf.reduce_max(iou, axis=0)
mean_best_iou = tf.reduce_mean(best_iou, name='best_iou_per_gt')
summaries = [mean_best_iou]
with tf.device('/cpu:0'):
for th in [0.3, 0.5]:
recall = tf.truediv(
tf.count_nonzero(best_iou >= th),
tf.size(best_iou, out_type=tf.int64),
name='recall_iou{}'.format(th))
summaries.append(recall)
add_moving_summary(*summaries) | python | def proposal_metrics(iou):
"""
Add summaries for RPN proposals.
Args:
iou: nxm, #proposal x #gt
"""
# find best roi for each gt, for summary only
best_iou = tf.reduce_max(iou, axis=0)
mean_best_iou = tf.reduce_mean(best_iou, name='best_iou_per_gt')
summaries = [mean_best_iou]
with tf.device('/cpu:0'):
for th in [0.3, 0.5]:
recall = tf.truediv(
tf.count_nonzero(best_iou >= th),
tf.size(best_iou, out_type=tf.int64),
name='recall_iou{}'.format(th))
summaries.append(recall)
add_moving_summary(*summaries) | [
"def",
"proposal_metrics",
"(",
"iou",
")",
":",
"# find best roi for each gt, for summary only",
"best_iou",
"=",
"tf",
".",
"reduce_max",
"(",
"iou",
",",
"axis",
"=",
"0",
")",
"mean_best_iou",
"=",
"tf",
".",
"reduce_mean",
"(",
"best_iou",
",",
"name",
"=",
"'best_iou_per_gt'",
")",
"summaries",
"=",
"[",
"mean_best_iou",
"]",
"with",
"tf",
".",
"device",
"(",
"'/cpu:0'",
")",
":",
"for",
"th",
"in",
"[",
"0.3",
",",
"0.5",
"]",
":",
"recall",
"=",
"tf",
".",
"truediv",
"(",
"tf",
".",
"count_nonzero",
"(",
"best_iou",
">=",
"th",
")",
",",
"tf",
".",
"size",
"(",
"best_iou",
",",
"out_type",
"=",
"tf",
".",
"int64",
")",
",",
"name",
"=",
"'recall_iou{}'",
".",
"format",
"(",
"th",
")",
")",
"summaries",
".",
"append",
"(",
"recall",
")",
"add_moving_summary",
"(",
"*",
"summaries",
")"
] | Add summaries for RPN proposals.
Args:
iou: nxm, #proposal x #gt | [
"Add",
"summaries",
"for",
"RPN",
"proposals",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L20-L38 |
27,377 | tensorpack/tensorpack | examples/FasterRCNN/model_frcnn.py | fastrcnn_predictions | def fastrcnn_predictions(boxes, scores):
"""
Generate final results from predictions of all proposals.
Args:
boxes: n#classx4 floatbox in float32
scores: nx#class
Returns:
boxes: Kx4
scores: K
labels: K
"""
assert boxes.shape[1] == cfg.DATA.NUM_CLASS
assert scores.shape[1] == cfg.DATA.NUM_CLASS
boxes = tf.transpose(boxes, [1, 0, 2])[1:, :, :] # #catxnx4
scores = tf.transpose(scores[:, 1:], [1, 0]) # #catxn
def f(X):
"""
prob: n probabilities
box: nx4 boxes
Returns: n boolean, the selection
"""
prob, box = X
output_shape = tf.shape(prob, out_type=tf.int64)
# filter by score threshold
ids = tf.reshape(tf.where(prob > cfg.TEST.RESULT_SCORE_THRESH), [-1])
prob = tf.gather(prob, ids)
box = tf.gather(box, ids)
# NMS within each class
selection = tf.image.non_max_suppression(
box, prob, cfg.TEST.RESULTS_PER_IM, cfg.TEST.FRCNN_NMS_THRESH)
selection = tf.gather(ids, selection)
if get_tf_version_tuple() >= (1, 13):
sorted_selection = tf.sort(selection, direction='ASCENDING')
mask = tf.sparse.SparseTensor(indices=tf.expand_dims(sorted_selection, 1),
values=tf.ones_like(sorted_selection, dtype=tf.bool),
dense_shape=output_shape)
mask = tf.sparse.to_dense(mask, default_value=False)
else:
# this function is deprecated by TF
sorted_selection = -tf.nn.top_k(-selection, k=tf.size(selection))[0]
mask = tf.sparse_to_dense(
sparse_indices=sorted_selection,
output_shape=output_shape,
sparse_values=True,
default_value=False)
return mask
# TF bug in version 1.11, 1.12: https://github.com/tensorflow/tensorflow/issues/22750
buggy_tf = get_tf_version_tuple() in [(1, 11), (1, 12)]
masks = tf.map_fn(f, (scores, boxes), dtype=tf.bool,
parallel_iterations=1 if buggy_tf else 10) # #cat x N
selected_indices = tf.where(masks) # #selection x 2, each is (cat_id, box_id)
scores = tf.boolean_mask(scores, masks)
# filter again by sorting scores
topk_scores, topk_indices = tf.nn.top_k(
scores,
tf.minimum(cfg.TEST.RESULTS_PER_IM, tf.size(scores)),
sorted=False)
filtered_selection = tf.gather(selected_indices, topk_indices)
cat_ids, box_ids = tf.unstack(filtered_selection, axis=1)
final_scores = tf.identity(topk_scores, name='scores')
final_labels = tf.add(cat_ids, 1, name='labels')
final_ids = tf.stack([cat_ids, box_ids], axis=1, name='all_ids')
final_boxes = tf.gather_nd(boxes, final_ids, name='boxes')
return final_boxes, final_scores, final_labels | python | def fastrcnn_predictions(boxes, scores):
"""
Generate final results from predictions of all proposals.
Args:
boxes: n#classx4 floatbox in float32
scores: nx#class
Returns:
boxes: Kx4
scores: K
labels: K
"""
assert boxes.shape[1] == cfg.DATA.NUM_CLASS
assert scores.shape[1] == cfg.DATA.NUM_CLASS
boxes = tf.transpose(boxes, [1, 0, 2])[1:, :, :] # #catxnx4
scores = tf.transpose(scores[:, 1:], [1, 0]) # #catxn
def f(X):
"""
prob: n probabilities
box: nx4 boxes
Returns: n boolean, the selection
"""
prob, box = X
output_shape = tf.shape(prob, out_type=tf.int64)
# filter by score threshold
ids = tf.reshape(tf.where(prob > cfg.TEST.RESULT_SCORE_THRESH), [-1])
prob = tf.gather(prob, ids)
box = tf.gather(box, ids)
# NMS within each class
selection = tf.image.non_max_suppression(
box, prob, cfg.TEST.RESULTS_PER_IM, cfg.TEST.FRCNN_NMS_THRESH)
selection = tf.gather(ids, selection)
if get_tf_version_tuple() >= (1, 13):
sorted_selection = tf.sort(selection, direction='ASCENDING')
mask = tf.sparse.SparseTensor(indices=tf.expand_dims(sorted_selection, 1),
values=tf.ones_like(sorted_selection, dtype=tf.bool),
dense_shape=output_shape)
mask = tf.sparse.to_dense(mask, default_value=False)
else:
# this function is deprecated by TF
sorted_selection = -tf.nn.top_k(-selection, k=tf.size(selection))[0]
mask = tf.sparse_to_dense(
sparse_indices=sorted_selection,
output_shape=output_shape,
sparse_values=True,
default_value=False)
return mask
# TF bug in version 1.11, 1.12: https://github.com/tensorflow/tensorflow/issues/22750
buggy_tf = get_tf_version_tuple() in [(1, 11), (1, 12)]
masks = tf.map_fn(f, (scores, boxes), dtype=tf.bool,
parallel_iterations=1 if buggy_tf else 10) # #cat x N
selected_indices = tf.where(masks) # #selection x 2, each is (cat_id, box_id)
scores = tf.boolean_mask(scores, masks)
# filter again by sorting scores
topk_scores, topk_indices = tf.nn.top_k(
scores,
tf.minimum(cfg.TEST.RESULTS_PER_IM, tf.size(scores)),
sorted=False)
filtered_selection = tf.gather(selected_indices, topk_indices)
cat_ids, box_ids = tf.unstack(filtered_selection, axis=1)
final_scores = tf.identity(topk_scores, name='scores')
final_labels = tf.add(cat_ids, 1, name='labels')
final_ids = tf.stack([cat_ids, box_ids], axis=1, name='all_ids')
final_boxes = tf.gather_nd(boxes, final_ids, name='boxes')
return final_boxes, final_scores, final_labels | [
"def",
"fastrcnn_predictions",
"(",
"boxes",
",",
"scores",
")",
":",
"assert",
"boxes",
".",
"shape",
"[",
"1",
"]",
"==",
"cfg",
".",
"DATA",
".",
"NUM_CLASS",
"assert",
"scores",
".",
"shape",
"[",
"1",
"]",
"==",
"cfg",
".",
"DATA",
".",
"NUM_CLASS",
"boxes",
"=",
"tf",
".",
"transpose",
"(",
"boxes",
",",
"[",
"1",
",",
"0",
",",
"2",
"]",
")",
"[",
"1",
":",
",",
":",
",",
":",
"]",
"# #catxnx4",
"scores",
"=",
"tf",
".",
"transpose",
"(",
"scores",
"[",
":",
",",
"1",
":",
"]",
",",
"[",
"1",
",",
"0",
"]",
")",
"# #catxn",
"def",
"f",
"(",
"X",
")",
":",
"\"\"\"\n prob: n probabilities\n box: nx4 boxes\n\n Returns: n boolean, the selection\n \"\"\"",
"prob",
",",
"box",
"=",
"X",
"output_shape",
"=",
"tf",
".",
"shape",
"(",
"prob",
",",
"out_type",
"=",
"tf",
".",
"int64",
")",
"# filter by score threshold",
"ids",
"=",
"tf",
".",
"reshape",
"(",
"tf",
".",
"where",
"(",
"prob",
">",
"cfg",
".",
"TEST",
".",
"RESULT_SCORE_THRESH",
")",
",",
"[",
"-",
"1",
"]",
")",
"prob",
"=",
"tf",
".",
"gather",
"(",
"prob",
",",
"ids",
")",
"box",
"=",
"tf",
".",
"gather",
"(",
"box",
",",
"ids",
")",
"# NMS within each class",
"selection",
"=",
"tf",
".",
"image",
".",
"non_max_suppression",
"(",
"box",
",",
"prob",
",",
"cfg",
".",
"TEST",
".",
"RESULTS_PER_IM",
",",
"cfg",
".",
"TEST",
".",
"FRCNN_NMS_THRESH",
")",
"selection",
"=",
"tf",
".",
"gather",
"(",
"ids",
",",
"selection",
")",
"if",
"get_tf_version_tuple",
"(",
")",
">=",
"(",
"1",
",",
"13",
")",
":",
"sorted_selection",
"=",
"tf",
".",
"sort",
"(",
"selection",
",",
"direction",
"=",
"'ASCENDING'",
")",
"mask",
"=",
"tf",
".",
"sparse",
".",
"SparseTensor",
"(",
"indices",
"=",
"tf",
".",
"expand_dims",
"(",
"sorted_selection",
",",
"1",
")",
",",
"values",
"=",
"tf",
".",
"ones_like",
"(",
"sorted_selection",
",",
"dtype",
"=",
"tf",
".",
"bool",
")",
",",
"dense_shape",
"=",
"output_shape",
")",
"mask",
"=",
"tf",
".",
"sparse",
".",
"to_dense",
"(",
"mask",
",",
"default_value",
"=",
"False",
")",
"else",
":",
"# this function is deprecated by TF",
"sorted_selection",
"=",
"-",
"tf",
".",
"nn",
".",
"top_k",
"(",
"-",
"selection",
",",
"k",
"=",
"tf",
".",
"size",
"(",
"selection",
")",
")",
"[",
"0",
"]",
"mask",
"=",
"tf",
".",
"sparse_to_dense",
"(",
"sparse_indices",
"=",
"sorted_selection",
",",
"output_shape",
"=",
"output_shape",
",",
"sparse_values",
"=",
"True",
",",
"default_value",
"=",
"False",
")",
"return",
"mask",
"# TF bug in version 1.11, 1.12: https://github.com/tensorflow/tensorflow/issues/22750",
"buggy_tf",
"=",
"get_tf_version_tuple",
"(",
")",
"in",
"[",
"(",
"1",
",",
"11",
")",
",",
"(",
"1",
",",
"12",
")",
"]",
"masks",
"=",
"tf",
".",
"map_fn",
"(",
"f",
",",
"(",
"scores",
",",
"boxes",
")",
",",
"dtype",
"=",
"tf",
".",
"bool",
",",
"parallel_iterations",
"=",
"1",
"if",
"buggy_tf",
"else",
"10",
")",
"# #cat x N",
"selected_indices",
"=",
"tf",
".",
"where",
"(",
"masks",
")",
"# #selection x 2, each is (cat_id, box_id)",
"scores",
"=",
"tf",
".",
"boolean_mask",
"(",
"scores",
",",
"masks",
")",
"# filter again by sorting scores",
"topk_scores",
",",
"topk_indices",
"=",
"tf",
".",
"nn",
".",
"top_k",
"(",
"scores",
",",
"tf",
".",
"minimum",
"(",
"cfg",
".",
"TEST",
".",
"RESULTS_PER_IM",
",",
"tf",
".",
"size",
"(",
"scores",
")",
")",
",",
"sorted",
"=",
"False",
")",
"filtered_selection",
"=",
"tf",
".",
"gather",
"(",
"selected_indices",
",",
"topk_indices",
")",
"cat_ids",
",",
"box_ids",
"=",
"tf",
".",
"unstack",
"(",
"filtered_selection",
",",
"axis",
"=",
"1",
")",
"final_scores",
"=",
"tf",
".",
"identity",
"(",
"topk_scores",
",",
"name",
"=",
"'scores'",
")",
"final_labels",
"=",
"tf",
".",
"add",
"(",
"cat_ids",
",",
"1",
",",
"name",
"=",
"'labels'",
")",
"final_ids",
"=",
"tf",
".",
"stack",
"(",
"[",
"cat_ids",
",",
"box_ids",
"]",
",",
"axis",
"=",
"1",
",",
"name",
"=",
"'all_ids'",
")",
"final_boxes",
"=",
"tf",
".",
"gather_nd",
"(",
"boxes",
",",
"final_ids",
",",
"name",
"=",
"'boxes'",
")",
"return",
"final_boxes",
",",
"final_scores",
",",
"final_labels"
] | Generate final results from predictions of all proposals.
Args:
boxes: n#classx4 floatbox in float32
scores: nx#class
Returns:
boxes: Kx4
scores: K
labels: K | [
"Generate",
"final",
"results",
"from",
"predictions",
"of",
"all",
"proposals",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L176-L247 |
27,378 | tensorpack/tensorpack | examples/A3C-Gym/train-atari.py | MySimulatorMaster._on_state | def _on_state(self, state, client):
"""
Launch forward prediction for the new state given by some client.
"""
def cb(outputs):
try:
distrib, value = outputs.result()
except CancelledError:
logger.info("Client {} cancelled.".format(client.ident))
return
assert np.all(np.isfinite(distrib)), distrib
action = np.random.choice(len(distrib), p=distrib)
client.memory.append(TransitionExperience(
state, action, reward=None, value=value, prob=distrib[action]))
self.send_queue.put([client.ident, dumps(action)])
self.async_predictor.put_task([state], cb) | python | def _on_state(self, state, client):
"""
Launch forward prediction for the new state given by some client.
"""
def cb(outputs):
try:
distrib, value = outputs.result()
except CancelledError:
logger.info("Client {} cancelled.".format(client.ident))
return
assert np.all(np.isfinite(distrib)), distrib
action = np.random.choice(len(distrib), p=distrib)
client.memory.append(TransitionExperience(
state, action, reward=None, value=value, prob=distrib[action]))
self.send_queue.put([client.ident, dumps(action)])
self.async_predictor.put_task([state], cb) | [
"def",
"_on_state",
"(",
"self",
",",
"state",
",",
"client",
")",
":",
"def",
"cb",
"(",
"outputs",
")",
":",
"try",
":",
"distrib",
",",
"value",
"=",
"outputs",
".",
"result",
"(",
")",
"except",
"CancelledError",
":",
"logger",
".",
"info",
"(",
"\"Client {} cancelled.\"",
".",
"format",
"(",
"client",
".",
"ident",
")",
")",
"return",
"assert",
"np",
".",
"all",
"(",
"np",
".",
"isfinite",
"(",
"distrib",
")",
")",
",",
"distrib",
"action",
"=",
"np",
".",
"random",
".",
"choice",
"(",
"len",
"(",
"distrib",
")",
",",
"p",
"=",
"distrib",
")",
"client",
".",
"memory",
".",
"append",
"(",
"TransitionExperience",
"(",
"state",
",",
"action",
",",
"reward",
"=",
"None",
",",
"value",
"=",
"value",
",",
"prob",
"=",
"distrib",
"[",
"action",
"]",
")",
")",
"self",
".",
"send_queue",
".",
"put",
"(",
"[",
"client",
".",
"ident",
",",
"dumps",
"(",
"action",
")",
"]",
")",
"self",
".",
"async_predictor",
".",
"put_task",
"(",
"[",
"state",
"]",
",",
"cb",
")"
] | Launch forward prediction for the new state given by some client. | [
"Launch",
"forward",
"prediction",
"for",
"the",
"new",
"state",
"given",
"by",
"some",
"client",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/A3C-Gym/train-atari.py#L159-L174 |
27,379 | tensorpack/tensorpack | examples/A3C-Gym/train-atari.py | MySimulatorMaster._process_msg | def _process_msg(self, client, state, reward, isOver):
"""
Process a message sent from some client.
"""
# in the first message, only state is valid,
# reward&isOver should be discarded
if len(client.memory) > 0:
client.memory[-1].reward = reward
if isOver:
# should clear client's memory and put to queue
self._parse_memory(0, client, True)
else:
if len(client.memory) == LOCAL_TIME_MAX + 1:
R = client.memory[-1].value
self._parse_memory(R, client, False)
# feed state and return action
self._on_state(state, client) | python | def _process_msg(self, client, state, reward, isOver):
"""
Process a message sent from some client.
"""
# in the first message, only state is valid,
# reward&isOver should be discarded
if len(client.memory) > 0:
client.memory[-1].reward = reward
if isOver:
# should clear client's memory and put to queue
self._parse_memory(0, client, True)
else:
if len(client.memory) == LOCAL_TIME_MAX + 1:
R = client.memory[-1].value
self._parse_memory(R, client, False)
# feed state and return action
self._on_state(state, client) | [
"def",
"_process_msg",
"(",
"self",
",",
"client",
",",
"state",
",",
"reward",
",",
"isOver",
")",
":",
"# in the first message, only state is valid,",
"# reward&isOver should be discarded",
"if",
"len",
"(",
"client",
".",
"memory",
")",
">",
"0",
":",
"client",
".",
"memory",
"[",
"-",
"1",
"]",
".",
"reward",
"=",
"reward",
"if",
"isOver",
":",
"# should clear client's memory and put to queue",
"self",
".",
"_parse_memory",
"(",
"0",
",",
"client",
",",
"True",
")",
"else",
":",
"if",
"len",
"(",
"client",
".",
"memory",
")",
"==",
"LOCAL_TIME_MAX",
"+",
"1",
":",
"R",
"=",
"client",
".",
"memory",
"[",
"-",
"1",
"]",
".",
"value",
"self",
".",
"_parse_memory",
"(",
"R",
",",
"client",
",",
"False",
")",
"# feed state and return action",
"self",
".",
"_on_state",
"(",
"state",
",",
"client",
")"
] | Process a message sent from some client. | [
"Process",
"a",
"message",
"sent",
"from",
"some",
"client",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/A3C-Gym/train-atari.py#L176-L192 |
27,380 | tensorpack/tensorpack | tensorpack/tfutils/export.py | ModelExporter.export_serving | def export_serving(self, filename,
tags=[tf.saved_model.SERVING if is_tfv2() else tf.saved_model.tag_constants.SERVING],
signature_name='prediction_pipeline'):
"""
Converts a checkpoint and graph to a servable for TensorFlow Serving.
Use TF's `SavedModelBuilder` to export a trained model without tensorpack dependency.
Args:
filename (str): path for export directory
tags (list): list of user specified tags
signature_name (str): name of signature for prediction
Note:
This produces
.. code-block:: none
variables/ # output from the vanilla Saver
variables.data-?????-of-?????
variables.index
saved_model.pb # a `SavedModel` protobuf
Currently, we only support a single signature, which is the general PredictSignatureDef:
https://github.com/tensorflow/serving/blob/master/tensorflow_serving/g3doc/signature_defs.md
"""
self.graph = self.config._maybe_create_graph()
with self.graph.as_default():
input = PlaceholderInput()
input.setup(self.config.input_signature)
with PredictTowerContext(''):
self.config.tower_func(*input.get_input_tensors())
input_tensors = get_tensors_by_names(self.config.input_names)
saved_model = tfv1.saved_model.utils
inputs_signatures = {t.name: saved_model.build_tensor_info(t) for t in input_tensors}
output_tensors = get_tensors_by_names(self.config.output_names)
outputs_signatures = {t.name: saved_model.build_tensor_info(t) for t in output_tensors}
self.config.session_init._setup_graph()
# we cannot use "self.config.session_creator.create_session()" here since it finalizes the graph
sess = tfv1.Session(config=tfv1.ConfigProto(allow_soft_placement=True))
self.config.session_init._run_init(sess)
builder = tfv1.saved_model.builder.SavedModelBuilder(filename)
prediction_signature = tfv1.saved_model.signature_def_utils.build_signature_def(
inputs=inputs_signatures,
outputs=outputs_signatures,
method_name=tfv1.saved_model.signature_constants.PREDICT_METHOD_NAME)
builder.add_meta_graph_and_variables(
sess, tags,
signature_def_map={signature_name: prediction_signature})
builder.save()
logger.info("SavedModel created at {}.".format(filename)) | python | def export_serving(self, filename,
tags=[tf.saved_model.SERVING if is_tfv2() else tf.saved_model.tag_constants.SERVING],
signature_name='prediction_pipeline'):
"""
Converts a checkpoint and graph to a servable for TensorFlow Serving.
Use TF's `SavedModelBuilder` to export a trained model without tensorpack dependency.
Args:
filename (str): path for export directory
tags (list): list of user specified tags
signature_name (str): name of signature for prediction
Note:
This produces
.. code-block:: none
variables/ # output from the vanilla Saver
variables.data-?????-of-?????
variables.index
saved_model.pb # a `SavedModel` protobuf
Currently, we only support a single signature, which is the general PredictSignatureDef:
https://github.com/tensorflow/serving/blob/master/tensorflow_serving/g3doc/signature_defs.md
"""
self.graph = self.config._maybe_create_graph()
with self.graph.as_default():
input = PlaceholderInput()
input.setup(self.config.input_signature)
with PredictTowerContext(''):
self.config.tower_func(*input.get_input_tensors())
input_tensors = get_tensors_by_names(self.config.input_names)
saved_model = tfv1.saved_model.utils
inputs_signatures = {t.name: saved_model.build_tensor_info(t) for t in input_tensors}
output_tensors = get_tensors_by_names(self.config.output_names)
outputs_signatures = {t.name: saved_model.build_tensor_info(t) for t in output_tensors}
self.config.session_init._setup_graph()
# we cannot use "self.config.session_creator.create_session()" here since it finalizes the graph
sess = tfv1.Session(config=tfv1.ConfigProto(allow_soft_placement=True))
self.config.session_init._run_init(sess)
builder = tfv1.saved_model.builder.SavedModelBuilder(filename)
prediction_signature = tfv1.saved_model.signature_def_utils.build_signature_def(
inputs=inputs_signatures,
outputs=outputs_signatures,
method_name=tfv1.saved_model.signature_constants.PREDICT_METHOD_NAME)
builder.add_meta_graph_and_variables(
sess, tags,
signature_def_map={signature_name: prediction_signature})
builder.save()
logger.info("SavedModel created at {}.".format(filename)) | [
"def",
"export_serving",
"(",
"self",
",",
"filename",
",",
"tags",
"=",
"[",
"tf",
".",
"saved_model",
".",
"SERVING",
"if",
"is_tfv2",
"(",
")",
"else",
"tf",
".",
"saved_model",
".",
"tag_constants",
".",
"SERVING",
"]",
",",
"signature_name",
"=",
"'prediction_pipeline'",
")",
":",
"self",
".",
"graph",
"=",
"self",
".",
"config",
".",
"_maybe_create_graph",
"(",
")",
"with",
"self",
".",
"graph",
".",
"as_default",
"(",
")",
":",
"input",
"=",
"PlaceholderInput",
"(",
")",
"input",
".",
"setup",
"(",
"self",
".",
"config",
".",
"input_signature",
")",
"with",
"PredictTowerContext",
"(",
"''",
")",
":",
"self",
".",
"config",
".",
"tower_func",
"(",
"*",
"input",
".",
"get_input_tensors",
"(",
")",
")",
"input_tensors",
"=",
"get_tensors_by_names",
"(",
"self",
".",
"config",
".",
"input_names",
")",
"saved_model",
"=",
"tfv1",
".",
"saved_model",
".",
"utils",
"inputs_signatures",
"=",
"{",
"t",
".",
"name",
":",
"saved_model",
".",
"build_tensor_info",
"(",
"t",
")",
"for",
"t",
"in",
"input_tensors",
"}",
"output_tensors",
"=",
"get_tensors_by_names",
"(",
"self",
".",
"config",
".",
"output_names",
")",
"outputs_signatures",
"=",
"{",
"t",
".",
"name",
":",
"saved_model",
".",
"build_tensor_info",
"(",
"t",
")",
"for",
"t",
"in",
"output_tensors",
"}",
"self",
".",
"config",
".",
"session_init",
".",
"_setup_graph",
"(",
")",
"# we cannot use \"self.config.session_creator.create_session()\" here since it finalizes the graph",
"sess",
"=",
"tfv1",
".",
"Session",
"(",
"config",
"=",
"tfv1",
".",
"ConfigProto",
"(",
"allow_soft_placement",
"=",
"True",
")",
")",
"self",
".",
"config",
".",
"session_init",
".",
"_run_init",
"(",
"sess",
")",
"builder",
"=",
"tfv1",
".",
"saved_model",
".",
"builder",
".",
"SavedModelBuilder",
"(",
"filename",
")",
"prediction_signature",
"=",
"tfv1",
".",
"saved_model",
".",
"signature_def_utils",
".",
"build_signature_def",
"(",
"inputs",
"=",
"inputs_signatures",
",",
"outputs",
"=",
"outputs_signatures",
",",
"method_name",
"=",
"tfv1",
".",
"saved_model",
".",
"signature_constants",
".",
"PREDICT_METHOD_NAME",
")",
"builder",
".",
"add_meta_graph_and_variables",
"(",
"sess",
",",
"tags",
",",
"signature_def_map",
"=",
"{",
"signature_name",
":",
"prediction_signature",
"}",
")",
"builder",
".",
"save",
"(",
")",
"logger",
".",
"info",
"(",
"\"SavedModel created at {}.\"",
".",
"format",
"(",
"filename",
")",
")"
] | Converts a checkpoint and graph to a servable for TensorFlow Serving.
Use TF's `SavedModelBuilder` to export a trained model without tensorpack dependency.
Args:
filename (str): path for export directory
tags (list): list of user specified tags
signature_name (str): name of signature for prediction
Note:
This produces
.. code-block:: none
variables/ # output from the vanilla Saver
variables.data-?????-of-?????
variables.index
saved_model.pb # a `SavedModel` protobuf
Currently, we only support a single signature, which is the general PredictSignatureDef:
https://github.com/tensorflow/serving/blob/master/tensorflow_serving/g3doc/signature_defs.md | [
"Converts",
"a",
"checkpoint",
"and",
"graph",
"to",
"a",
"servable",
"for",
"TensorFlow",
"Serving",
".",
"Use",
"TF",
"s",
"SavedModelBuilder",
"to",
"export",
"a",
"trained",
"model",
"without",
"tensorpack",
"dependency",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/export.py#L91-L146 |
27,381 | modin-project/modin | ci/benchmarks/utils.py | time_logger | def time_logger(name):
"""This logs the time usage of a code block"""
start_time = time.time()
yield
end_time = time.time()
total_time = end_time - start_time
logging.info("%s; time: %ss", name, total_time) | python | def time_logger(name):
"""This logs the time usage of a code block"""
start_time = time.time()
yield
end_time = time.time()
total_time = end_time - start_time
logging.info("%s; time: %ss", name, total_time) | [
"def",
"time_logger",
"(",
"name",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"yield",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"total_time",
"=",
"end_time",
"-",
"start_time",
"logging",
".",
"info",
"(",
"\"%s; time: %ss\"",
",",
"name",
",",
"total_time",
")"
] | This logs the time usage of a code block | [
"This",
"logs",
"the",
"time",
"usage",
"of",
"a",
"code",
"block"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/ci/benchmarks/utils.py#L12-L19 |
27,382 | modin-project/modin | modin/pandas/__init__.py | initialize_ray | def initialize_ray():
"""Initializes ray based on environment variables and internal defaults."""
if threading.current_thread().name == "MainThread":
plasma_directory = None
object_store_memory = os.environ.get("MODIN_MEMORY", None)
if os.environ.get("MODIN_OUT_OF_CORE", "False").title() == "True":
from tempfile import gettempdir
plasma_directory = gettempdir()
# We may have already set the memory from the environment variable, we don't
# want to overwrite that value if we have.
if object_store_memory is None:
# Round down to the nearest Gigabyte.
mem_bytes = ray.utils.get_system_memory() // 10 ** 9 * 10 ** 9
# Default to 8x memory for out of core
object_store_memory = 8 * mem_bytes
# In case anything failed above, we can still improve the memory for Modin.
if object_store_memory is None:
# Round down to the nearest Gigabyte.
object_store_memory = int(
0.6 * ray.utils.get_system_memory() // 10 ** 9 * 10 ** 9
)
# If the memory pool is smaller than 2GB, just use the default in ray.
if object_store_memory == 0:
object_store_memory = None
else:
object_store_memory = int(object_store_memory)
ray.init(
include_webui=False,
ignore_reinit_error=True,
plasma_directory=plasma_directory,
object_store_memory=object_store_memory,
)
# Register custom serializer for method objects to avoid warning message.
# We serialize `MethodType` objects when we use AxisPartition operations.
ray.register_custom_serializer(types.MethodType, use_pickle=True) | python | def initialize_ray():
"""Initializes ray based on environment variables and internal defaults."""
if threading.current_thread().name == "MainThread":
plasma_directory = None
object_store_memory = os.environ.get("MODIN_MEMORY", None)
if os.environ.get("MODIN_OUT_OF_CORE", "False").title() == "True":
from tempfile import gettempdir
plasma_directory = gettempdir()
# We may have already set the memory from the environment variable, we don't
# want to overwrite that value if we have.
if object_store_memory is None:
# Round down to the nearest Gigabyte.
mem_bytes = ray.utils.get_system_memory() // 10 ** 9 * 10 ** 9
# Default to 8x memory for out of core
object_store_memory = 8 * mem_bytes
# In case anything failed above, we can still improve the memory for Modin.
if object_store_memory is None:
# Round down to the nearest Gigabyte.
object_store_memory = int(
0.6 * ray.utils.get_system_memory() // 10 ** 9 * 10 ** 9
)
# If the memory pool is smaller than 2GB, just use the default in ray.
if object_store_memory == 0:
object_store_memory = None
else:
object_store_memory = int(object_store_memory)
ray.init(
include_webui=False,
ignore_reinit_error=True,
plasma_directory=plasma_directory,
object_store_memory=object_store_memory,
)
# Register custom serializer for method objects to avoid warning message.
# We serialize `MethodType` objects when we use AxisPartition operations.
ray.register_custom_serializer(types.MethodType, use_pickle=True) | [
"def",
"initialize_ray",
"(",
")",
":",
"if",
"threading",
".",
"current_thread",
"(",
")",
".",
"name",
"==",
"\"MainThread\"",
":",
"plasma_directory",
"=",
"None",
"object_store_memory",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"MODIN_MEMORY\"",
",",
"None",
")",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"MODIN_OUT_OF_CORE\"",
",",
"\"False\"",
")",
".",
"title",
"(",
")",
"==",
"\"True\"",
":",
"from",
"tempfile",
"import",
"gettempdir",
"plasma_directory",
"=",
"gettempdir",
"(",
")",
"# We may have already set the memory from the environment variable, we don't",
"# want to overwrite that value if we have.",
"if",
"object_store_memory",
"is",
"None",
":",
"# Round down to the nearest Gigabyte.",
"mem_bytes",
"=",
"ray",
".",
"utils",
".",
"get_system_memory",
"(",
")",
"//",
"10",
"**",
"9",
"*",
"10",
"**",
"9",
"# Default to 8x memory for out of core",
"object_store_memory",
"=",
"8",
"*",
"mem_bytes",
"# In case anything failed above, we can still improve the memory for Modin.",
"if",
"object_store_memory",
"is",
"None",
":",
"# Round down to the nearest Gigabyte.",
"object_store_memory",
"=",
"int",
"(",
"0.6",
"*",
"ray",
".",
"utils",
".",
"get_system_memory",
"(",
")",
"//",
"10",
"**",
"9",
"*",
"10",
"**",
"9",
")",
"# If the memory pool is smaller than 2GB, just use the default in ray.",
"if",
"object_store_memory",
"==",
"0",
":",
"object_store_memory",
"=",
"None",
"else",
":",
"object_store_memory",
"=",
"int",
"(",
"object_store_memory",
")",
"ray",
".",
"init",
"(",
"include_webui",
"=",
"False",
",",
"ignore_reinit_error",
"=",
"True",
",",
"plasma_directory",
"=",
"plasma_directory",
",",
"object_store_memory",
"=",
"object_store_memory",
",",
")",
"# Register custom serializer for method objects to avoid warning message.",
"# We serialize `MethodType` objects when we use AxisPartition operations.",
"ray",
".",
"register_custom_serializer",
"(",
"types",
".",
"MethodType",
",",
"use_pickle",
"=",
"True",
")"
] | Initializes ray based on environment variables and internal defaults. | [
"Initializes",
"ray",
"based",
"on",
"environment",
"variables",
"and",
"internal",
"defaults",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/__init__.py#L133-L168 |
27,383 | modin-project/modin | modin/engines/dask/pandas_on_dask_delayed/frame/axis_partition.py | DaskFrameAxisPartition.apply | def apply(
self,
func,
num_splits=None,
other_axis_partition=None,
maintain_partitioning=True,
**kwargs
):
"""Applies func to the object.
See notes in Parent class about this method.
Args:
func: The function to apply.
num_splits: The number of times to split the result object.
other_axis_partition: Another `DaskFrameAxisPartition` object to apply to
func with this one.
Returns:
A list of `DaskFramePartition` objects.
"""
import dask
if num_splits is None:
num_splits = len(self.list_of_blocks)
if other_axis_partition is not None:
return [
DaskFramePartition(dask.delayed(obj))
for obj in deploy_func_between_two_axis_partitions(
self.axis,
func,
num_splits,
len(self.list_of_blocks),
kwargs,
*dask.compute(
*tuple(
self.list_of_blocks + other_axis_partition.list_of_blocks
)
)
)
]
args = [self.axis, func, num_splits, kwargs, maintain_partitioning]
args.extend(dask.compute(*self.list_of_blocks))
return [
DaskFramePartition(dask.delayed(obj)) for obj in deploy_axis_func(*args)
] | python | def apply(
self,
func,
num_splits=None,
other_axis_partition=None,
maintain_partitioning=True,
**kwargs
):
"""Applies func to the object.
See notes in Parent class about this method.
Args:
func: The function to apply.
num_splits: The number of times to split the result object.
other_axis_partition: Another `DaskFrameAxisPartition` object to apply to
func with this one.
Returns:
A list of `DaskFramePartition` objects.
"""
import dask
if num_splits is None:
num_splits = len(self.list_of_blocks)
if other_axis_partition is not None:
return [
DaskFramePartition(dask.delayed(obj))
for obj in deploy_func_between_two_axis_partitions(
self.axis,
func,
num_splits,
len(self.list_of_blocks),
kwargs,
*dask.compute(
*tuple(
self.list_of_blocks + other_axis_partition.list_of_blocks
)
)
)
]
args = [self.axis, func, num_splits, kwargs, maintain_partitioning]
args.extend(dask.compute(*self.list_of_blocks))
return [
DaskFramePartition(dask.delayed(obj)) for obj in deploy_axis_func(*args)
] | [
"def",
"apply",
"(",
"self",
",",
"func",
",",
"num_splits",
"=",
"None",
",",
"other_axis_partition",
"=",
"None",
",",
"maintain_partitioning",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"dask",
"if",
"num_splits",
"is",
"None",
":",
"num_splits",
"=",
"len",
"(",
"self",
".",
"list_of_blocks",
")",
"if",
"other_axis_partition",
"is",
"not",
"None",
":",
"return",
"[",
"DaskFramePartition",
"(",
"dask",
".",
"delayed",
"(",
"obj",
")",
")",
"for",
"obj",
"in",
"deploy_func_between_two_axis_partitions",
"(",
"self",
".",
"axis",
",",
"func",
",",
"num_splits",
",",
"len",
"(",
"self",
".",
"list_of_blocks",
")",
",",
"kwargs",
",",
"*",
"dask",
".",
"compute",
"(",
"*",
"tuple",
"(",
"self",
".",
"list_of_blocks",
"+",
"other_axis_partition",
".",
"list_of_blocks",
")",
")",
")",
"]",
"args",
"=",
"[",
"self",
".",
"axis",
",",
"func",
",",
"num_splits",
",",
"kwargs",
",",
"maintain_partitioning",
"]",
"args",
".",
"extend",
"(",
"dask",
".",
"compute",
"(",
"*",
"self",
".",
"list_of_blocks",
")",
")",
"return",
"[",
"DaskFramePartition",
"(",
"dask",
".",
"delayed",
"(",
"obj",
")",
")",
"for",
"obj",
"in",
"deploy_axis_func",
"(",
"*",
"args",
")",
"]"
] | Applies func to the object.
See notes in Parent class about this method.
Args:
func: The function to apply.
num_splits: The number of times to split the result object.
other_axis_partition: Another `DaskFrameAxisPartition` object to apply to
func with this one.
Returns:
A list of `DaskFramePartition` objects. | [
"Applies",
"func",
"to",
"the",
"object",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/engines/dask/pandas_on_dask_delayed/frame/axis_partition.py#L15-L63 |
27,384 | modin-project/modin | modin/pandas/reshape.py | get_dummies | def get_dummies(
data,
prefix=None,
prefix_sep="_",
dummy_na=False,
columns=None,
sparse=False,
drop_first=False,
dtype=None,
):
"""Convert categorical variable into indicator variables.
Args:
data (array-like, Series, or DataFrame): data to encode.
prefix (string, [string]): Prefix to apply to each encoded column
label.
prefix_sep (string, [string]): Separator between prefix and value.
dummy_na (bool): Add a column to indicate NaNs.
columns: Which columns to encode.
sparse (bool): Not Implemented: If True, returns SparseDataFrame.
drop_first (bool): Whether to remove the first level of encoded data.
dtype: The dtype for the get_dummies call.
Returns:
DataFrame or one-hot encoded data.
"""
if sparse:
raise NotImplementedError(
"SparseDataFrame is not implemented. "
"To contribute to Modin, please visit "
"github.com/modin-project/modin."
)
if not isinstance(data, DataFrame):
ErrorMessage.default_to_pandas("`get_dummies` on non-DataFrame")
return DataFrame(
pandas.get_dummies(
data,
prefix=prefix,
prefix_sep=prefix_sep,
dummy_na=dummy_na,
columns=columns,
sparse=sparse,
drop_first=drop_first,
dtype=dtype,
)
)
else:
new_manager = data._query_compiler.get_dummies(
columns,
prefix=prefix,
prefix_sep=prefix_sep,
dummy_na=dummy_na,
drop_first=drop_first,
dtype=dtype,
)
return DataFrame(query_compiler=new_manager) | python | def get_dummies(
data,
prefix=None,
prefix_sep="_",
dummy_na=False,
columns=None,
sparse=False,
drop_first=False,
dtype=None,
):
"""Convert categorical variable into indicator variables.
Args:
data (array-like, Series, or DataFrame): data to encode.
prefix (string, [string]): Prefix to apply to each encoded column
label.
prefix_sep (string, [string]): Separator between prefix and value.
dummy_na (bool): Add a column to indicate NaNs.
columns: Which columns to encode.
sparse (bool): Not Implemented: If True, returns SparseDataFrame.
drop_first (bool): Whether to remove the first level of encoded data.
dtype: The dtype for the get_dummies call.
Returns:
DataFrame or one-hot encoded data.
"""
if sparse:
raise NotImplementedError(
"SparseDataFrame is not implemented. "
"To contribute to Modin, please visit "
"github.com/modin-project/modin."
)
if not isinstance(data, DataFrame):
ErrorMessage.default_to_pandas("`get_dummies` on non-DataFrame")
return DataFrame(
pandas.get_dummies(
data,
prefix=prefix,
prefix_sep=prefix_sep,
dummy_na=dummy_na,
columns=columns,
sparse=sparse,
drop_first=drop_first,
dtype=dtype,
)
)
else:
new_manager = data._query_compiler.get_dummies(
columns,
prefix=prefix,
prefix_sep=prefix_sep,
dummy_na=dummy_na,
drop_first=drop_first,
dtype=dtype,
)
return DataFrame(query_compiler=new_manager) | [
"def",
"get_dummies",
"(",
"data",
",",
"prefix",
"=",
"None",
",",
"prefix_sep",
"=",
"\"_\"",
",",
"dummy_na",
"=",
"False",
",",
"columns",
"=",
"None",
",",
"sparse",
"=",
"False",
",",
"drop_first",
"=",
"False",
",",
"dtype",
"=",
"None",
",",
")",
":",
"if",
"sparse",
":",
"raise",
"NotImplementedError",
"(",
"\"SparseDataFrame is not implemented. \"",
"\"To contribute to Modin, please visit \"",
"\"github.com/modin-project/modin.\"",
")",
"if",
"not",
"isinstance",
"(",
"data",
",",
"DataFrame",
")",
":",
"ErrorMessage",
".",
"default_to_pandas",
"(",
"\"`get_dummies` on non-DataFrame\"",
")",
"return",
"DataFrame",
"(",
"pandas",
".",
"get_dummies",
"(",
"data",
",",
"prefix",
"=",
"prefix",
",",
"prefix_sep",
"=",
"prefix_sep",
",",
"dummy_na",
"=",
"dummy_na",
",",
"columns",
"=",
"columns",
",",
"sparse",
"=",
"sparse",
",",
"drop_first",
"=",
"drop_first",
",",
"dtype",
"=",
"dtype",
",",
")",
")",
"else",
":",
"new_manager",
"=",
"data",
".",
"_query_compiler",
".",
"get_dummies",
"(",
"columns",
",",
"prefix",
"=",
"prefix",
",",
"prefix_sep",
"=",
"prefix_sep",
",",
"dummy_na",
"=",
"dummy_na",
",",
"drop_first",
"=",
"drop_first",
",",
"dtype",
"=",
"dtype",
",",
")",
"return",
"DataFrame",
"(",
"query_compiler",
"=",
"new_manager",
")"
] | Convert categorical variable into indicator variables.
Args:
data (array-like, Series, or DataFrame): data to encode.
prefix (string, [string]): Prefix to apply to each encoded column
label.
prefix_sep (string, [string]): Separator between prefix and value.
dummy_na (bool): Add a column to indicate NaNs.
columns: Which columns to encode.
sparse (bool): Not Implemented: If True, returns SparseDataFrame.
drop_first (bool): Whether to remove the first level of encoded data.
dtype: The dtype for the get_dummies call.
Returns:
DataFrame or one-hot encoded data. | [
"Convert",
"categorical",
"variable",
"into",
"indicator",
"variables",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/reshape.py#L12-L67 |
27,385 | modin-project/modin | modin/engines/base/frame/axis_partition.py | PandasFrameAxisPartition.shuffle | def shuffle(self, func, lengths, **kwargs):
"""Shuffle the order of the data in this axis based on the `lengths`.
Extends `BaseFrameAxisPartition.shuffle`.
Args:
func: The function to apply before splitting.
lengths: The list of partition lengths to split the result into.
Returns:
A list of RemotePartition objects split by `lengths`.
"""
num_splits = len(lengths)
# We add these to kwargs and will pop them off before performing the operation.
kwargs["manual_partition"] = True
kwargs["_lengths"] = lengths
args = [self.axis, func, num_splits, kwargs, False]
args.extend(self.list_of_blocks)
return self._wrap_partitions(self.deploy_axis_func(*args)) | python | def shuffle(self, func, lengths, **kwargs):
"""Shuffle the order of the data in this axis based on the `lengths`.
Extends `BaseFrameAxisPartition.shuffle`.
Args:
func: The function to apply before splitting.
lengths: The list of partition lengths to split the result into.
Returns:
A list of RemotePartition objects split by `lengths`.
"""
num_splits = len(lengths)
# We add these to kwargs and will pop them off before performing the operation.
kwargs["manual_partition"] = True
kwargs["_lengths"] = lengths
args = [self.axis, func, num_splits, kwargs, False]
args.extend(self.list_of_blocks)
return self._wrap_partitions(self.deploy_axis_func(*args)) | [
"def",
"shuffle",
"(",
"self",
",",
"func",
",",
"lengths",
",",
"*",
"*",
"kwargs",
")",
":",
"num_splits",
"=",
"len",
"(",
"lengths",
")",
"# We add these to kwargs and will pop them off before performing the operation.",
"kwargs",
"[",
"\"manual_partition\"",
"]",
"=",
"True",
"kwargs",
"[",
"\"_lengths\"",
"]",
"=",
"lengths",
"args",
"=",
"[",
"self",
".",
"axis",
",",
"func",
",",
"num_splits",
",",
"kwargs",
",",
"False",
"]",
"args",
".",
"extend",
"(",
"self",
".",
"list_of_blocks",
")",
"return",
"self",
".",
"_wrap_partitions",
"(",
"self",
".",
"deploy_axis_func",
"(",
"*",
"args",
")",
")"
] | Shuffle the order of the data in this axis based on the `lengths`.
Extends `BaseFrameAxisPartition.shuffle`.
Args:
func: The function to apply before splitting.
lengths: The list of partition lengths to split the result into.
Returns:
A list of RemotePartition objects split by `lengths`. | [
"Shuffle",
"the",
"order",
"of",
"the",
"data",
"in",
"this",
"axis",
"based",
"on",
"the",
"lengths",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/engines/base/frame/axis_partition.py#L143-L161 |
27,386 | modin-project/modin | modin/experimental/engines/pyarrow_on_ray/frame/axis_partition.py | PyarrowOnRayFrameAxisPartition.shuffle | def shuffle(self, func, num_splits=None, **kwargs):
"""Shuffle the order of the data in this axis based on the `func`.
Extends `BaseFrameAxisPartition.shuffle`.
:param func:
:param num_splits:
:param kwargs:
:return:
"""
if num_splits is None:
num_splits = len(self.list_of_blocks)
args = [self.axis, func, num_splits, kwargs]
args.extend(self.list_of_blocks)
return [
PyarrowOnRayFramePartition(obj)
for obj in deploy_ray_axis_func._remote(args, num_return_vals=num_splits)
] | python | def shuffle(self, func, num_splits=None, **kwargs):
"""Shuffle the order of the data in this axis based on the `func`.
Extends `BaseFrameAxisPartition.shuffle`.
:param func:
:param num_splits:
:param kwargs:
:return:
"""
if num_splits is None:
num_splits = len(self.list_of_blocks)
args = [self.axis, func, num_splits, kwargs]
args.extend(self.list_of_blocks)
return [
PyarrowOnRayFramePartition(obj)
for obj in deploy_ray_axis_func._remote(args, num_return_vals=num_splits)
] | [
"def",
"shuffle",
"(",
"self",
",",
"func",
",",
"num_splits",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"num_splits",
"is",
"None",
":",
"num_splits",
"=",
"len",
"(",
"self",
".",
"list_of_blocks",
")",
"args",
"=",
"[",
"self",
".",
"axis",
",",
"func",
",",
"num_splits",
",",
"kwargs",
"]",
"args",
".",
"extend",
"(",
"self",
".",
"list_of_blocks",
")",
"return",
"[",
"PyarrowOnRayFramePartition",
"(",
"obj",
")",
"for",
"obj",
"in",
"deploy_ray_axis_func",
".",
"_remote",
"(",
"args",
",",
"num_return_vals",
"=",
"num_splits",
")",
"]"
] | Shuffle the order of the data in this axis based on the `func`.
Extends `BaseFrameAxisPartition.shuffle`.
:param func:
:param num_splits:
:param kwargs:
:return: | [
"Shuffle",
"the",
"order",
"of",
"the",
"data",
"in",
"this",
"axis",
"based",
"on",
"the",
"func",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pyarrow_on_ray/frame/axis_partition.py#L50-L68 |
27,387 | modin-project/modin | modin/experimental/engines/pyarrow_on_ray/frame/partition.py | PyarrowOnRayFramePartition.apply | def apply(self, func, **kwargs):
"""Apply a function to the object stored in this partition.
Note: It does not matter if func is callable or an ObjectID. Ray will
handle it correctly either way. The keyword arguments are sent as a
dictionary.
Args:
func: The function to apply.
Returns:
A RayRemotePartition object.
"""
oid = self.oid
self.call_queue.append((func, kwargs))
def call_queue_closure(oid_obj, call_queues):
for func, kwargs in call_queues:
if isinstance(func, ray.ObjectID):
func = ray.get(func)
if isinstance(kwargs, ray.ObjectID):
kwargs = ray.get(kwargs)
oid_obj = func(oid_obj, **kwargs)
return oid_obj
oid = deploy_ray_func.remote(
call_queue_closure, oid, kwargs={"call_queues": self.call_queue}
)
self.call_queue = []
return PyarrowOnRayFramePartition(oid) | python | def apply(self, func, **kwargs):
"""Apply a function to the object stored in this partition.
Note: It does not matter if func is callable or an ObjectID. Ray will
handle it correctly either way. The keyword arguments are sent as a
dictionary.
Args:
func: The function to apply.
Returns:
A RayRemotePartition object.
"""
oid = self.oid
self.call_queue.append((func, kwargs))
def call_queue_closure(oid_obj, call_queues):
for func, kwargs in call_queues:
if isinstance(func, ray.ObjectID):
func = ray.get(func)
if isinstance(kwargs, ray.ObjectID):
kwargs = ray.get(kwargs)
oid_obj = func(oid_obj, **kwargs)
return oid_obj
oid = deploy_ray_func.remote(
call_queue_closure, oid, kwargs={"call_queues": self.call_queue}
)
self.call_queue = []
return PyarrowOnRayFramePartition(oid) | [
"def",
"apply",
"(",
"self",
",",
"func",
",",
"*",
"*",
"kwargs",
")",
":",
"oid",
"=",
"self",
".",
"oid",
"self",
".",
"call_queue",
".",
"append",
"(",
"(",
"func",
",",
"kwargs",
")",
")",
"def",
"call_queue_closure",
"(",
"oid_obj",
",",
"call_queues",
")",
":",
"for",
"func",
",",
"kwargs",
"in",
"call_queues",
":",
"if",
"isinstance",
"(",
"func",
",",
"ray",
".",
"ObjectID",
")",
":",
"func",
"=",
"ray",
".",
"get",
"(",
"func",
")",
"if",
"isinstance",
"(",
"kwargs",
",",
"ray",
".",
"ObjectID",
")",
":",
"kwargs",
"=",
"ray",
".",
"get",
"(",
"kwargs",
")",
"oid_obj",
"=",
"func",
"(",
"oid_obj",
",",
"*",
"*",
"kwargs",
")",
"return",
"oid_obj",
"oid",
"=",
"deploy_ray_func",
".",
"remote",
"(",
"call_queue_closure",
",",
"oid",
",",
"kwargs",
"=",
"{",
"\"call_queues\"",
":",
"self",
".",
"call_queue",
"}",
")",
"self",
".",
"call_queue",
"=",
"[",
"]",
"return",
"PyarrowOnRayFramePartition",
"(",
"oid",
")"
] | Apply a function to the object stored in this partition.
Note: It does not matter if func is callable or an ObjectID. Ray will
handle it correctly either way. The keyword arguments are sent as a
dictionary.
Args:
func: The function to apply.
Returns:
A RayRemotePartition object. | [
"Apply",
"a",
"function",
"to",
"the",
"object",
"stored",
"in",
"this",
"partition",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pyarrow_on_ray/frame/partition.py#L30-L62 |
27,388 | modin-project/modin | modin/experimental/engines/pyarrow_on_ray/frame/partition.py | PyarrowOnRayFramePartition.to_pandas | def to_pandas(self):
"""Convert the object stored in this partition to a Pandas DataFrame.
Returns:
A Pandas DataFrame.
"""
dataframe = self.get().to_pandas()
assert type(dataframe) is pandas.DataFrame or type(dataframe) is pandas.Series
return dataframe | python | def to_pandas(self):
"""Convert the object stored in this partition to a Pandas DataFrame.
Returns:
A Pandas DataFrame.
"""
dataframe = self.get().to_pandas()
assert type(dataframe) is pandas.DataFrame or type(dataframe) is pandas.Series
return dataframe | [
"def",
"to_pandas",
"(",
"self",
")",
":",
"dataframe",
"=",
"self",
".",
"get",
"(",
")",
".",
"to_pandas",
"(",
")",
"assert",
"type",
"(",
"dataframe",
")",
"is",
"pandas",
".",
"DataFrame",
"or",
"type",
"(",
"dataframe",
")",
"is",
"pandas",
".",
"Series",
"return",
"dataframe"
] | Convert the object stored in this partition to a Pandas DataFrame.
Returns:
A Pandas DataFrame. | [
"Convert",
"the",
"object",
"stored",
"in",
"this",
"partition",
"to",
"a",
"Pandas",
"DataFrame",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pyarrow_on_ray/frame/partition.py#L71-L80 |
27,389 | modin-project/modin | modin/experimental/engines/pyarrow_on_ray/frame/partition.py | PyarrowOnRayFramePartition.put | def put(cls, obj):
"""Put an object in the Plasma store and wrap it in this object.
Args:
obj: The object to be put.
Returns:
A `RayRemotePartition` object.
"""
return PyarrowOnRayFramePartition(ray.put(pyarrow.Table.from_pandas(obj))) | python | def put(cls, obj):
"""Put an object in the Plasma store and wrap it in this object.
Args:
obj: The object to be put.
Returns:
A `RayRemotePartition` object.
"""
return PyarrowOnRayFramePartition(ray.put(pyarrow.Table.from_pandas(obj))) | [
"def",
"put",
"(",
"cls",
",",
"obj",
")",
":",
"return",
"PyarrowOnRayFramePartition",
"(",
"ray",
".",
"put",
"(",
"pyarrow",
".",
"Table",
".",
"from_pandas",
"(",
"obj",
")",
")",
")"
] | Put an object in the Plasma store and wrap it in this object.
Args:
obj: The object to be put.
Returns:
A `RayRemotePartition` object. | [
"Put",
"an",
"object",
"in",
"the",
"Plasma",
"store",
"and",
"wrap",
"it",
"in",
"this",
"object",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pyarrow_on_ray/frame/partition.py#L83-L92 |
27,390 | modin-project/modin | modin/pandas/general.py | merge | def merge(
left,
right,
how="inner",
on=None,
left_on=None,
right_on=None,
left_index=False,
right_index=False,
sort=False,
suffixes=("_x", "_y"),
copy=True,
indicator=False,
validate=None,
):
"""Database style join, where common columns in "on" are merged.
Args:
left: DataFrame.
right: DataFrame.
how: What type of join to use.
on: The common column name(s) to join on. If None, and left_on and
right_on are also None, will default to all commonly named
columns.
left_on: The column(s) on the left to use for the join.
right_on: The column(s) on the right to use for the join.
left_index: Use the index from the left as the join keys.
right_index: Use the index from the right as the join keys.
sort: Sort the join keys lexicographically in the result.
suffixes: Add this suffix to the common names not in the "on".
copy: Does nothing in our implementation
indicator: Adds a column named _merge to the DataFrame with
metadata from the merge about each row.
validate: Checks if merge is a specific type.
Returns:
A merged Dataframe
"""
if not isinstance(left, DataFrame):
raise ValueError(
"can not merge DataFrame with instance of type {}".format(type(right))
)
return left.merge(
right,
how=how,
on=on,
left_on=left_on,
right_on=right_on,
left_index=left_index,
right_index=right_index,
sort=sort,
suffixes=suffixes,
copy=copy,
indicator=indicator,
validate=validate,
) | python | def merge(
left,
right,
how="inner",
on=None,
left_on=None,
right_on=None,
left_index=False,
right_index=False,
sort=False,
suffixes=("_x", "_y"),
copy=True,
indicator=False,
validate=None,
):
"""Database style join, where common columns in "on" are merged.
Args:
left: DataFrame.
right: DataFrame.
how: What type of join to use.
on: The common column name(s) to join on. If None, and left_on and
right_on are also None, will default to all commonly named
columns.
left_on: The column(s) on the left to use for the join.
right_on: The column(s) on the right to use for the join.
left_index: Use the index from the left as the join keys.
right_index: Use the index from the right as the join keys.
sort: Sort the join keys lexicographically in the result.
suffixes: Add this suffix to the common names not in the "on".
copy: Does nothing in our implementation
indicator: Adds a column named _merge to the DataFrame with
metadata from the merge about each row.
validate: Checks if merge is a specific type.
Returns:
A merged Dataframe
"""
if not isinstance(left, DataFrame):
raise ValueError(
"can not merge DataFrame with instance of type {}".format(type(right))
)
return left.merge(
right,
how=how,
on=on,
left_on=left_on,
right_on=right_on,
left_index=left_index,
right_index=right_index,
sort=sort,
suffixes=suffixes,
copy=copy,
indicator=indicator,
validate=validate,
) | [
"def",
"merge",
"(",
"left",
",",
"right",
",",
"how",
"=",
"\"inner\"",
",",
"on",
"=",
"None",
",",
"left_on",
"=",
"None",
",",
"right_on",
"=",
"None",
",",
"left_index",
"=",
"False",
",",
"right_index",
"=",
"False",
",",
"sort",
"=",
"False",
",",
"suffixes",
"=",
"(",
"\"_x\"",
",",
"\"_y\"",
")",
",",
"copy",
"=",
"True",
",",
"indicator",
"=",
"False",
",",
"validate",
"=",
"None",
",",
")",
":",
"if",
"not",
"isinstance",
"(",
"left",
",",
"DataFrame",
")",
":",
"raise",
"ValueError",
"(",
"\"can not merge DataFrame with instance of type {}\"",
".",
"format",
"(",
"type",
"(",
"right",
")",
")",
")",
"return",
"left",
".",
"merge",
"(",
"right",
",",
"how",
"=",
"how",
",",
"on",
"=",
"on",
",",
"left_on",
"=",
"left_on",
",",
"right_on",
"=",
"right_on",
",",
"left_index",
"=",
"left_index",
",",
"right_index",
"=",
"right_index",
",",
"sort",
"=",
"sort",
",",
"suffixes",
"=",
"suffixes",
",",
"copy",
"=",
"copy",
",",
"indicator",
"=",
"indicator",
",",
"validate",
"=",
"validate",
",",
")"
] | Database style join, where common columns in "on" are merged.
Args:
left: DataFrame.
right: DataFrame.
how: What type of join to use.
on: The common column name(s) to join on. If None, and left_on and
right_on are also None, will default to all commonly named
columns.
left_on: The column(s) on the left to use for the join.
right_on: The column(s) on the right to use for the join.
left_index: Use the index from the left as the join keys.
right_index: Use the index from the right as the join keys.
sort: Sort the join keys lexicographically in the result.
suffixes: Add this suffix to the common names not in the "on".
copy: Does nothing in our implementation
indicator: Adds a column named _merge to the DataFrame with
metadata from the merge about each row.
validate: Checks if merge is a specific type.
Returns:
A merged Dataframe | [
"Database",
"style",
"join",
"where",
"common",
"columns",
"in",
"on",
"are",
"merged",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/general.py#L41-L97 |
27,391 | modin-project/modin | modin/experimental/engines/pandas_on_ray/sql.py | is_distributed | def is_distributed(partition_column, lower_bound, upper_bound):
""" Check if is possible distribute a query given that args
Args:
partition_column: column used to share the data between the workers
lower_bound: the minimum value to be requested from the partition_column
upper_bound: the maximum value to be requested from the partition_column
Returns:
True for distributed or False if not
"""
if (
(partition_column is not None)
and (lower_bound is not None)
and (upper_bound is not None)
):
if upper_bound > lower_bound:
return True
else:
raise InvalidArguments("upper_bound must be greater than lower_bound.")
elif (partition_column is None) and (lower_bound is None) and (upper_bound is None):
return False
else:
raise InvalidArguments(
"Invalid combination of partition_column, lower_bound, upper_bound."
"All these arguments should be passed (distributed) or none of them (standard pandas)."
) | python | def is_distributed(partition_column, lower_bound, upper_bound):
""" Check if is possible distribute a query given that args
Args:
partition_column: column used to share the data between the workers
lower_bound: the minimum value to be requested from the partition_column
upper_bound: the maximum value to be requested from the partition_column
Returns:
True for distributed or False if not
"""
if (
(partition_column is not None)
and (lower_bound is not None)
and (upper_bound is not None)
):
if upper_bound > lower_bound:
return True
else:
raise InvalidArguments("upper_bound must be greater than lower_bound.")
elif (partition_column is None) and (lower_bound is None) and (upper_bound is None):
return False
else:
raise InvalidArguments(
"Invalid combination of partition_column, lower_bound, upper_bound."
"All these arguments should be passed (distributed) or none of them (standard pandas)."
) | [
"def",
"is_distributed",
"(",
"partition_column",
",",
"lower_bound",
",",
"upper_bound",
")",
":",
"if",
"(",
"(",
"partition_column",
"is",
"not",
"None",
")",
"and",
"(",
"lower_bound",
"is",
"not",
"None",
")",
"and",
"(",
"upper_bound",
"is",
"not",
"None",
")",
")",
":",
"if",
"upper_bound",
">",
"lower_bound",
":",
"return",
"True",
"else",
":",
"raise",
"InvalidArguments",
"(",
"\"upper_bound must be greater than lower_bound.\"",
")",
"elif",
"(",
"partition_column",
"is",
"None",
")",
"and",
"(",
"lower_bound",
"is",
"None",
")",
"and",
"(",
"upper_bound",
"is",
"None",
")",
":",
"return",
"False",
"else",
":",
"raise",
"InvalidArguments",
"(",
"\"Invalid combination of partition_column, lower_bound, upper_bound.\"",
"\"All these arguments should be passed (distributed) or none of them (standard pandas).\"",
")"
] | Check if is possible distribute a query given that args
Args:
partition_column: column used to share the data between the workers
lower_bound: the minimum value to be requested from the partition_column
upper_bound: the maximum value to be requested from the partition_column
Returns:
True for distributed or False if not | [
"Check",
"if",
"is",
"possible",
"distribute",
"a",
"query",
"given",
"that",
"args"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L5-L31 |
27,392 | modin-project/modin | modin/experimental/engines/pandas_on_ray/sql.py | is_table | def is_table(engine, sql):
""" Check with the given sql arg is query or table
Args:
engine: SQLAlchemy connection engine
sql: SQL query or table name
Returns:
True for table or False if not
"""
if engine.dialect.has_table(engine, sql):
return True
return False | python | def is_table(engine, sql):
""" Check with the given sql arg is query or table
Args:
engine: SQLAlchemy connection engine
sql: SQL query or table name
Returns:
True for table or False if not
"""
if engine.dialect.has_table(engine, sql):
return True
return False | [
"def",
"is_table",
"(",
"engine",
",",
"sql",
")",
":",
"if",
"engine",
".",
"dialect",
".",
"has_table",
"(",
"engine",
",",
"sql",
")",
":",
"return",
"True",
"return",
"False"
] | Check with the given sql arg is query or table
Args:
engine: SQLAlchemy connection engine
sql: SQL query or table name
Returns:
True for table or False if not | [
"Check",
"with",
"the",
"given",
"sql",
"arg",
"is",
"query",
"or",
"table"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L34-L46 |
27,393 | modin-project/modin | modin/experimental/engines/pandas_on_ray/sql.py | get_table_metadata | def get_table_metadata(engine, table):
""" Extract all useful infos from the given table
Args:
engine: SQLAlchemy connection engine
table: table name
Returns:
Dictionary of infos
"""
metadata = MetaData()
metadata.reflect(bind=engine, only=[table])
table_metadata = Table(table, metadata, autoload=True)
return table_metadata | python | def get_table_metadata(engine, table):
""" Extract all useful infos from the given table
Args:
engine: SQLAlchemy connection engine
table: table name
Returns:
Dictionary of infos
"""
metadata = MetaData()
metadata.reflect(bind=engine, only=[table])
table_metadata = Table(table, metadata, autoload=True)
return table_metadata | [
"def",
"get_table_metadata",
"(",
"engine",
",",
"table",
")",
":",
"metadata",
"=",
"MetaData",
"(",
")",
"metadata",
".",
"reflect",
"(",
"bind",
"=",
"engine",
",",
"only",
"=",
"[",
"table",
"]",
")",
"table_metadata",
"=",
"Table",
"(",
"table",
",",
"metadata",
",",
"autoload",
"=",
"True",
")",
"return",
"table_metadata"
] | Extract all useful infos from the given table
Args:
engine: SQLAlchemy connection engine
table: table name
Returns:
Dictionary of infos | [
"Extract",
"all",
"useful",
"infos",
"from",
"the",
"given",
"table"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L49-L62 |
27,394 | modin-project/modin | modin/experimental/engines/pandas_on_ray/sql.py | get_table_columns | def get_table_columns(metadata):
""" Extract columns names and python typos from metadata
Args:
metadata: Table metadata
Returns:
dict with columns names and python types
"""
cols = OrderedDict()
for col in metadata.c:
name = str(col).rpartition(".")[2]
cols[name] = col.type.python_type.__name__
return cols | python | def get_table_columns(metadata):
""" Extract columns names and python typos from metadata
Args:
metadata: Table metadata
Returns:
dict with columns names and python types
"""
cols = OrderedDict()
for col in metadata.c:
name = str(col).rpartition(".")[2]
cols[name] = col.type.python_type.__name__
return cols | [
"def",
"get_table_columns",
"(",
"metadata",
")",
":",
"cols",
"=",
"OrderedDict",
"(",
")",
"for",
"col",
"in",
"metadata",
".",
"c",
":",
"name",
"=",
"str",
"(",
"col",
")",
".",
"rpartition",
"(",
"\".\"",
")",
"[",
"2",
"]",
"cols",
"[",
"name",
"]",
"=",
"col",
".",
"type",
".",
"python_type",
".",
"__name__",
"return",
"cols"
] | Extract columns names and python typos from metadata
Args:
metadata: Table metadata
Returns:
dict with columns names and python types | [
"Extract",
"columns",
"names",
"and",
"python",
"typos",
"from",
"metadata"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L65-L78 |
27,395 | modin-project/modin | modin/experimental/engines/pandas_on_ray/sql.py | check_query | def check_query(query):
""" Check query sanity
Args:
query: query string
Returns:
None
"""
q = query.lower()
if "select " not in q:
raise InvalidQuery("SELECT word not found in the query: {0}".format(query))
if " from " not in q:
raise InvalidQuery("FROM word not found in the query: {0}".format(query)) | python | def check_query(query):
""" Check query sanity
Args:
query: query string
Returns:
None
"""
q = query.lower()
if "select " not in q:
raise InvalidQuery("SELECT word not found in the query: {0}".format(query))
if " from " not in q:
raise InvalidQuery("FROM word not found in the query: {0}".format(query)) | [
"def",
"check_query",
"(",
"query",
")",
":",
"q",
"=",
"query",
".",
"lower",
"(",
")",
"if",
"\"select \"",
"not",
"in",
"q",
":",
"raise",
"InvalidQuery",
"(",
"\"SELECT word not found in the query: {0}\"",
".",
"format",
"(",
"query",
")",
")",
"if",
"\" from \"",
"not",
"in",
"q",
":",
"raise",
"InvalidQuery",
"(",
"\"FROM word not found in the query: {0}\"",
".",
"format",
"(",
"query",
")",
")"
] | Check query sanity
Args:
query: query string
Returns:
None | [
"Check",
"query",
"sanity"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L93-L106 |
27,396 | modin-project/modin | modin/experimental/engines/pandas_on_ray/sql.py | get_query_columns | def get_query_columns(engine, query):
""" Extract columns names and python typos from query
Args:
engine: SQLAlchemy connection engine
query: SQL query
Returns:
dict with columns names and python types
"""
con = engine.connect()
result = con.execute(query).fetchone()
values = list(result)
cols_names = result.keys()
cols = OrderedDict()
for i in range(len(cols_names)):
cols[cols_names[i]] = type(values[i]).__name__
return cols | python | def get_query_columns(engine, query):
""" Extract columns names and python typos from query
Args:
engine: SQLAlchemy connection engine
query: SQL query
Returns:
dict with columns names and python types
"""
con = engine.connect()
result = con.execute(query).fetchone()
values = list(result)
cols_names = result.keys()
cols = OrderedDict()
for i in range(len(cols_names)):
cols[cols_names[i]] = type(values[i]).__name__
return cols | [
"def",
"get_query_columns",
"(",
"engine",
",",
"query",
")",
":",
"con",
"=",
"engine",
".",
"connect",
"(",
")",
"result",
"=",
"con",
".",
"execute",
"(",
"query",
")",
".",
"fetchone",
"(",
")",
"values",
"=",
"list",
"(",
"result",
")",
"cols_names",
"=",
"result",
".",
"keys",
"(",
")",
"cols",
"=",
"OrderedDict",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"cols_names",
")",
")",
":",
"cols",
"[",
"cols_names",
"[",
"i",
"]",
"]",
"=",
"type",
"(",
"values",
"[",
"i",
"]",
")",
".",
"__name__",
"return",
"cols"
] | Extract columns names and python typos from query
Args:
engine: SQLAlchemy connection engine
query: SQL query
Returns:
dict with columns names and python types | [
"Extract",
"columns",
"names",
"and",
"python",
"typos",
"from",
"query"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L109-L126 |
27,397 | modin-project/modin | modin/experimental/engines/pandas_on_ray/sql.py | check_partition_column | def check_partition_column(partition_column, cols):
""" Check partition_column existence and type
Args:
partition_column: partition_column name
cols: dict with columns names and python types
Returns:
None
"""
for k, v in cols.items():
if k == partition_column:
if v == "int":
return
else:
raise InvalidPartitionColumn(
"partition_column must be int, and not {0}".format(v)
)
raise InvalidPartitionColumn(
"partition_column {0} not found in the query".format(partition_column)
) | python | def check_partition_column(partition_column, cols):
""" Check partition_column existence and type
Args:
partition_column: partition_column name
cols: dict with columns names and python types
Returns:
None
"""
for k, v in cols.items():
if k == partition_column:
if v == "int":
return
else:
raise InvalidPartitionColumn(
"partition_column must be int, and not {0}".format(v)
)
raise InvalidPartitionColumn(
"partition_column {0} not found in the query".format(partition_column)
) | [
"def",
"check_partition_column",
"(",
"partition_column",
",",
"cols",
")",
":",
"for",
"k",
",",
"v",
"in",
"cols",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"partition_column",
":",
"if",
"v",
"==",
"\"int\"",
":",
"return",
"else",
":",
"raise",
"InvalidPartitionColumn",
"(",
"\"partition_column must be int, and not {0}\"",
".",
"format",
"(",
"v",
")",
")",
"raise",
"InvalidPartitionColumn",
"(",
"\"partition_column {0} not found in the query\"",
".",
"format",
"(",
"partition_column",
")",
")"
] | Check partition_column existence and type
Args:
partition_column: partition_column name
cols: dict with columns names and python types
Returns:
None | [
"Check",
"partition_column",
"existence",
"and",
"type"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L129-L149 |
27,398 | modin-project/modin | modin/experimental/engines/pandas_on_ray/sql.py | get_query_info | def get_query_info(sql, con, partition_column):
""" Return a columns name list and the query string
Args:
sql: SQL query or table name
con: database connection or url string
partition_column: column used to share the data between the workers
Returns:
Columns name list and query string
"""
engine = create_engine(con)
if is_table(engine, sql):
table_metadata = get_table_metadata(engine, sql)
query = build_query_from_table(sql)
cols = get_table_columns(table_metadata)
else:
check_query(sql)
query = sql.replace(";", "")
cols = get_query_columns(engine, query)
# TODO allow validation that takes into account edge cases of pandas e.g. "[index]"
# check_partition_column(partition_column, cols)
cols_names = list(cols.keys())
return cols_names, query | python | def get_query_info(sql, con, partition_column):
""" Return a columns name list and the query string
Args:
sql: SQL query or table name
con: database connection or url string
partition_column: column used to share the data between the workers
Returns:
Columns name list and query string
"""
engine = create_engine(con)
if is_table(engine, sql):
table_metadata = get_table_metadata(engine, sql)
query = build_query_from_table(sql)
cols = get_table_columns(table_metadata)
else:
check_query(sql)
query = sql.replace(";", "")
cols = get_query_columns(engine, query)
# TODO allow validation that takes into account edge cases of pandas e.g. "[index]"
# check_partition_column(partition_column, cols)
cols_names = list(cols.keys())
return cols_names, query | [
"def",
"get_query_info",
"(",
"sql",
",",
"con",
",",
"partition_column",
")",
":",
"engine",
"=",
"create_engine",
"(",
"con",
")",
"if",
"is_table",
"(",
"engine",
",",
"sql",
")",
":",
"table_metadata",
"=",
"get_table_metadata",
"(",
"engine",
",",
"sql",
")",
"query",
"=",
"build_query_from_table",
"(",
"sql",
")",
"cols",
"=",
"get_table_columns",
"(",
"table_metadata",
")",
"else",
":",
"check_query",
"(",
"sql",
")",
"query",
"=",
"sql",
".",
"replace",
"(",
"\";\"",
",",
"\"\"",
")",
"cols",
"=",
"get_query_columns",
"(",
"engine",
",",
"query",
")",
"# TODO allow validation that takes into account edge cases of pandas e.g. \"[index]\"",
"# check_partition_column(partition_column, cols)",
"cols_names",
"=",
"list",
"(",
"cols",
".",
"keys",
"(",
")",
")",
"return",
"cols_names",
",",
"query"
] | Return a columns name list and the query string
Args:
sql: SQL query or table name
con: database connection or url string
partition_column: column used to share the data between the workers
Returns:
Columns name list and query string | [
"Return",
"a",
"columns",
"name",
"list",
"and",
"the",
"query",
"string"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L152-L175 |
27,399 | modin-project/modin | modin/experimental/engines/pandas_on_ray/sql.py | query_put_bounders | def query_put_bounders(query, partition_column, start, end):
""" Put bounders in the query
Args:
query: SQL query string
partition_column: partition_column name
start: lower_bound
end: upper_bound
Returns:
Query with bounders
"""
where = " WHERE TMP_TABLE.{0} >= {1} AND TMP_TABLE.{0} <= {2}".format(
partition_column, start, end
)
query_with_bounders = "SELECT * FROM ({0}) AS TMP_TABLE {1}".format(query, where)
return query_with_bounders | python | def query_put_bounders(query, partition_column, start, end):
""" Put bounders in the query
Args:
query: SQL query string
partition_column: partition_column name
start: lower_bound
end: upper_bound
Returns:
Query with bounders
"""
where = " WHERE TMP_TABLE.{0} >= {1} AND TMP_TABLE.{0} <= {2}".format(
partition_column, start, end
)
query_with_bounders = "SELECT * FROM ({0}) AS TMP_TABLE {1}".format(query, where)
return query_with_bounders | [
"def",
"query_put_bounders",
"(",
"query",
",",
"partition_column",
",",
"start",
",",
"end",
")",
":",
"where",
"=",
"\" WHERE TMP_TABLE.{0} >= {1} AND TMP_TABLE.{0} <= {2}\"",
".",
"format",
"(",
"partition_column",
",",
"start",
",",
"end",
")",
"query_with_bounders",
"=",
"\"SELECT * FROM ({0}) AS TMP_TABLE {1}\"",
".",
"format",
"(",
"query",
",",
"where",
")",
"return",
"query_with_bounders"
] | Put bounders in the query
Args:
query: SQL query string
partition_column: partition_column name
start: lower_bound
end: upper_bound
Returns:
Query with bounders | [
"Put",
"bounders",
"in",
"the",
"query"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L178-L194 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.