INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
A decorator which automatically reuses the current variable scope if the function has been called with the same variable scope before. | 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.co... |
Args: name_scope ( str ): the default scope to use. If None will use the name of the function. | def under_name_scope(name_scope=None):
"""
Args:
name_scope(str): the default scope to use. If None, will use the name of the function.
Returns:
A decorator which makes the function run under a name scope.
The name scope is obtained by the following:
1. The 'name_scope' keyw... |
Returns: A decorator which makes the function happen under a variable scope which is named by the function itself. | def under_variable_scope():
"""
Returns:
A decorator which makes the function happen under a variable scope,
which is named by the function itself.
Example:
.. code-block:: python
@under_variable_scope()
def mid_level(x):
with argscope(Conv2D, kernel_shape=... |
Return a context which either opens and caches a new name scope or reenter an existing one. | 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.
... |
Args: grad_list: list of list of tuples shape is Ngpu x Nvar x 2 | def _check_grad_list(grad_list):
"""
Args:
grad_list: list of list of tuples, shape is Ngpu x Nvar x 2
"""
nvars = [len(k) for k in grad_list]
def basename(x):
return re.sub('tower[0-9]+/', '', x.op.name)
if len(set(nvars)) != 1:
name... |
Run func on all GPUs ( towers ) and return the results. | def call_for_each_tower(
towers, func, devices=None, use_vs=None):
"""
Run `func` on all GPUs (towers) and return the results.
Args:
towers (list[int]): a list of GPU id.
func: a lambda to be called inside each tower
devices: a list of devices to ... |
Reduce the gradients apply them with the optimizer and set self. grads to a list of ( g v ) containing the averaged gradients. | def build(self, grad_list, get_opt_fn):
"""
Reduce the gradients, apply them with the optimizer,
and set self.grads to a list of (g, v), containing the averaged gradients.
Args:
grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed o... |
Call the function tower_fn under: class: TowerContext for each tower. | def call_for_each_tower(self, tower_fn):
"""
Call the function `tower_fn` under :class:`TowerContext` for each tower.
Returns:
a list, contains the return values of `tower_fn` on each tower.
"""
# if tower_fn returns [(grad, var), ...], this returns #GPU x #VAR x 2
... |
Reduce the gradients apply them with the optimizer and set self. grads to #GPU number of lists of ( g v ) containing the all - reduced gradients on each device. | def build(self, grad_list, get_opt_fn):
"""
Reduce the gradients, apply them with the optimizer,
and set self.grads to #GPU number of lists of (g, v), containing the all-reduced gradients on each device.
Args:
grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. ... |
Copy values of variables on GPU 0 to other GPUs. | 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 a... |
Call the function tower_fn under: class: TowerContext for each tower. | def call_for_each_tower(self, tower_fn):
"""
Call the function `tower_fn` under :class:`TowerContext` for each tower.
Returns:
a list, contains the return values of `tower_fn` on each tower.
"""
ps_device = 'cpu' if len(self.towers) >= 4 else 'gpu'
raw_devic... |
Args: grad_list ( [[ ( grad var )... ]... ] ): #GPU lists to be reduced. Each is the gradients computed on each GPU. get_opt_fn ( - > tf. train. Optimizer ): callable which returns an optimizer | def build(self, grad_list, get_opt_fn):
"""
Args:
grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU.
get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer
Returns:
tf.Operation: the t... |
Humanize timedelta given in seconds | 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)) ... |
Args: name ( str ) val ( str ): | def change_env(name, val):
"""
Args:
name(str), val(str):
Returns:
a context where the environment variable ``name`` being set to
``val``. It will be set back after the context exits.
"""
oldval = os.environ.get(name, None)
os.environ[name] = val
yield
if oldval ... |
Get a good RNG seeded with time pid and the object. | 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"))) % 42949... |
Each called in the code to this function is guaranteed to return True the first time and False afterwards. | 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 ex... |
Return default arguments to be used with tqdm. | 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_f... |
Similar to from ctypes. util import find_library but try to return full path if possible. | 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_l... |
Args: df ( DataFlow ): the DataFlow to serialize. path ( str ): output path. Either a directory or an lmdb file. write_frequency ( int ): the frequency to write back data to disk. | def save(df, path, write_frequency=5000):
"""
Args:
df (DataFlow): the DataFlow to serialize.
path (str): output path. Either a directory or an lmdb file.
write_frequency (int): the frequency to write back data to disk.
"""
assert isinstance(df, DataFl... |
Note: If you found deserialization being the bottleneck you can use: class: LMDBData as the reader and run deserialization as a mapper in parallel. | def load(path, shuffle=True):
"""
Note:
If you found deserialization being the bottleneck, you can use :class:`LMDBData` as the reader
and run deserialization as a mapper in parallel.
"""
df = LMDBData(path, shuffle=shuffle)
return MapData(df, lambda dp: l... |
Args: df ( DataFlow ): the DataFlow to serialize. path ( str ): output npz file. | def save(df, path):
"""
Args:
df (DataFlow): the DataFlow to serialize.
path (str): output npz file.
"""
buffer = []
size = _reset_df_and_get_size(df)
with get_tqdm(total=size) as pbar:
for dp in df:
buffer.append(dp)
... |
Args: df ( DataFlow ): the DataFlow to serialize. path ( str ): output tfrecord file. | def save(df, path):
"""
Args:
df (DataFlow): the DataFlow to serialize.
path (str): output tfrecord file.
"""
if os.environ.get('TENSORPACK_COMPATIBLE_SERIALIZE', 'msgpack') == 'msgpack':
def _dumps(dp):
return dumps(dp)
else:
... |
Args: size ( int ): total number of records. If not provided the returned dataflow will have no __len__ (). It s needed because this metadata is not stored in the TFRecord file. | def load(path, size=None):
"""
Args:
size (int): total number of records. If not provided, the returned dataflow will have no `__len__()`.
It's needed because this metadata is not stored in the TFRecord file.
"""
gen = tf.python_io.tf_record_iterator(path)
... |
Args: df ( DataFlow ): the DataFlow to serialize. path ( str ): output hdf5 file. data_paths ( list [ str ] ): list of h5 paths. It should have the same length as each datapoint and each path should correspond to one component of the datapoint. | def save(df, path, data_paths):
"""
Args:
df (DataFlow): the DataFlow to serialize.
path (str): output hdf5 file.
data_paths (list[str]): list of h5 paths. It should have the same
length as each datapoint, and each path should correspond to one
... |
Args: trainer ( SingleCostTrainer ): get_model ( input1 input2... - > tf. keras. Model ): A function which takes tensors builds and returns a Keras model. It will be part of the tower function. input ( InputSource ): optimizer ( tf. train. Optimizer ): loss metrics: list of strings | def setup_keras_trainer(
trainer, get_model,
input_signature, target_signature,
input, optimizer, loss, metrics):
"""
Args:
trainer (SingleCostTrainer):
get_model (input1, input2, ... -> tf.keras.Model):
A function which takes tensors, builds and returns a Ker... |
Args: optimizer ( tf. train. Optimizer ): loss metrics: string or list of strings | def compile(self, optimizer, loss, metrics=None):
"""
Args:
optimizer (tf.train.Optimizer):
loss, metrics: string or list of strings
"""
if isinstance(loss, six.string_types):
loss = [loss]
if metrics is None:
metrics = []
i... |
Args: validation_data ( DataFlow or InputSource ): to be used for inference. The inference callback is added as the first in the callback list. If you need to use it in a different order please write it in the callback list manually. kwargs: same arguments as: meth: Trainer. train_with_defaults. | def fit(self, validation_data=None, **kwargs):
"""
Args:
validation_data (DataFlow or InputSource): to be used for inference.
The inference callback is added as the first in the callback list.
If you need to use it in a different order, please write it in the ... |
Return the three quantization functions fw fa fg for weights activations and gradients respectively | 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... |
Implemented Trained Ternary Quantization: https:// arxiv. org/ abs/ 1612. 01064 | def ternarize(x, thresh=0.05):
"""
Implemented Trained Ternary Quantization:
https://arxiv.org/abs/1612.01064
Code modified from the authors' at:
https://github.com/czhu95/ternarynet/blob/master/examples/Ternary-Net/ternary.py
"""
shape = x.get_shape()
thre_x = tf.stop_gradient(tf.redu... |
Args: img ( np. ndarray ): an image ( expect BGR ) to show. lclick_cb rclick_cb: a callback func ( img x y ) for left/ right click event. kwargs: can be { key_cb_a: callback_img key_cb_b: callback_img } to specify a callback func ( img ) for keypress. | def interactive_imshow(img, lclick_cb=None, rclick_cb=None, **kwargs):
"""
Args:
img (np.ndarray): an image (expect BGR) to show.
lclick_cb, rclick_cb: a callback ``func(img, x, y)`` for left/right click event.
kwargs: can be {key_cb_a: callback_img, key_cb_b: callback_img}, to
... |
Stacked patches into grid to produce visualizations like the following: | def stack_patches(
patch_list, nr_row, nr_col, border=None,
pad=False, bgcolor=255, viz=False, lclick_cb=None):
"""
Stacked patches into grid, to produce visualizations like the following:
.. image:: https://github.com/tensorpack/tensorpack/raw/master/examples/GAN/demo/BEGAN-CelebA-samples.... |
Similar to: func: stack_patches but with a generator interface. It takes a much - longer list and yields stacked results one by one. For example if patch_list contains 1000 images and nr_row == nr_col == 10 this generator yields 10 stacked images. | def gen_stack_patches(patch_list,
nr_row=None, nr_col=None, border=None,
max_width=1000, max_height=1000,
bgcolor=255, viz=False, lclick_cb=None):
"""
Similar to :func:`stack_patches` but with a generator interface.
It takes a much-longer lis... |
Dump or visualize images of a: class: DataFlow. | def dump_dataflow_images(df, index=0, batched=True,
number=1000, output_dir=None,
scale=1, resize=None, viz=None,
flipRGB=False):
"""
Dump or visualize images of a :class:`DataFlow`.
Args:
df (DataFlow): the DataFlow.
... |
Convert a 1 - channel matrix of intensities to an RGB image employing a colormap. This function requires matplotlib. See matplotlib colormaps <http:// matplotlib. org/ examples/ color/ colormaps_reference. html > _ for a list of available colormap. | def intensity_to_rgb(intensity, cmap='cubehelix', normalize=False):
"""
Convert a 1-channel matrix of intensities to an RGB image employing a colormap.
This function requires matplotlib. See `matplotlib colormaps
<http://matplotlib.org/examples/color/colormaps_reference.html>`_ for a
list of availab... |
Draw text on an image. | 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]), ... |
Args: im ( np. ndarray ): a BGR image in range [ 0 255 ]. It will not be modified. boxes ( np. ndarray ): a numpy array of shape Nx4 where each row is [ x1 y1 x2 y2 ]. labels: ( list [ str ] or None ) color: a 3 - tuple BGR color ( in range [ 0 255 ] ) | def draw_boxes(im, boxes, labels=None, color=None):
"""
Args:
im (np.ndarray): a BGR image in range [0,255]. It will not be modified.
boxes (np.ndarray): a numpy array of shape Nx4 where each row is [x1, y1, x2, y2].
labels: (list[str] or None)
color: a 3-tuple BGR color (in rang... |
A wrapper around tf. concat to cooperate with: class: LinearWrap. | def ConcatWith(x, tensor, dim):
"""
A wrapper around ``tf.concat`` to cooperate with :class:`LinearWrap`.
Args:
x (tf.Tensor): input
tensor (list[tf.Tensor]): a tensor or list of tensors to concatenate with x.
x will be at the beginning
dim (int): the dimension along whi... |
Args: points: ( nx4 ) x2 Returns: nx4 boxes ( x1y1x2y2 ) | def point8_to_box(points):
"""
Args:
points: (nx4)x2
Returns:
nx4 boxes (x1y1x2y2)
"""
p = points.reshape((-1, 4, 2))
minxy = p.min(axis=1) # nx2
maxxy = p.max(axis=1) # nx2
return np.concatenate((minxy, maxxy), axis=1) |
Convert polygons to binary masks. | 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 le... |
Args: boxes: (... ) x4 float shape: h w | def clip_boxes(boxes, shape):
"""
Args:
boxes: (...)x4, float
shape: h, w
"""
orig_shape = boxes.shape
boxes = boxes.reshape([-1, 4])
h, w = shape
boxes[:, [0, 1]] = np.maximum(boxes[:, [0, 1]], 0)
boxes[:, 2] = np.minimum(boxes[:, 2], w)
boxes[:, 3] = np.minimum(boxe... |
Args: boxes: ( nx4 ) float shape: ( h w ) | def filter_boxes_inside_shape(boxes, shape):
"""
Args:
boxes: (nx4), float
shape: (h, w)
Returns:
indices: (k, )
selection: (kx4)
"""
assert boxes.ndim == 2, boxes.shape
assert len(shape) == 2, shape
h, w = shape
indices = np.where(
(boxes[:, 0] >... |
Same as tf. layers. MaxPooling2D. Default strides is equal to pool_size. | 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... |
Same as tf. layers. AveragePooling2D. Default strides is equal to pool_size. | 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.AveragePoolin... |
Global average pooling as in the paper Network In Network <http:// arxiv. org/ abs/ 1312. 4400 > _. | def GlobalAvgPooling(x, data_format='channels_last'):
"""
Global average pooling as in the paper `Network In Network
<http://arxiv.org/abs/1312.4400>`_.
Args:
x (tf.Tensor): a 4D tensor.
Returns:
tf.Tensor: a NC tensor named ``output``.
"""
assert x.shape.ndims == 4
dat... |
Unpool the input with a fixed matrix to perform kronecker product with. | 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.
... |
Args: varname ( str ): a variable name in the graph varname_prefix ( str ): an optional prefix that may need to be removed in varname savename_prefix ( str ): an optional prefix to append to all savename Returns: str: the name used to save the variable | def get_savename_from_varname(
varname, varname_prefix=None,
savename_prefix=None):
"""
Args:
varname(str): a variable name in the graph
varname_prefix(str): an optional prefix that may need to be removed in varname
savename_prefix(str): an optional prefix to append to al... |
Dump value of all TRAINABLE + MODEL variables to a dict and save as npz format ( loadable by: func: sessinit. get_model_loader ). | def dump_session_params(path):
"""
Dump value of all TRAINABLE + MODEL variables to a dict, and save as
npz format (loadable by :func:`sessinit.get_model_loader`).
Args:
path(str): the file name to save the parameters. Must ends with npz.
"""
# save variables that are GLOBAL, and either... |
Save variables in dic to path. | 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(pp... |
Work around TF problems in checkpoint path handling. | 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.... |
Load all variables from a checkpoint to a dict. | 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 ... |
** Guess ** if this variable is only used in training. Only used internally to avoid too many logging. Do not use it. | def is_training_name(name):
"""
**Guess** if this variable is only used in training.
Only used internally to avoid too many logging. Do not use it.
"""
# TODO: maybe simply check against TRAINABLE_VARIABLES and MODEL_VARIABLES?
# TODO or use get_slot_names()
name = get_op_tensor_name(name)[0... |
Returns a relaxed ( possibly reshaped/ upcast - ed ) version of value to be loaded to the given variable. | def relaxed_value_for_var(value, var):
"""
Returns a relaxed (possibly reshaped/upcast-ed) version of value,
to be loaded to the given variable.
Args:
value (ndarray): an numpy array to be loaded to var
var (tf.Variable):
Returns:
ndarray: a ... |
Args: prms ( dict ): dict of { variable name: value } Any name in prms must be in the graph and in vars_to_update. | def update(self, prms):
"""
Args:
prms(dict): dict of {variable name: value}
Any name in prms must be in the graph and in vars_to_update.
"""
with self.sess.as_default():
fetches = []
feeds = {}
for name, value in six.iterit... |
Args: server ( tf. train. Server ): | def get_distributed_session_creator(server):
"""
Args:
server (tf.train.Server):
Returns:
tf.train.SessionCreator
"""
server_def = server.server_def
is_chief = (server_def.job_name == 'worker') and (server_def.task_index == 0)
init_op = tf.global_variables_initializer()
... |
Returns: int: #available GPUs in CUDA_VISIBLE_DEVICES or in the system. | def get_num_gpu():
"""
Returns:
int: #available GPUs in CUDA_VISIBLE_DEVICES, or in the system.
"""
def warn_return(ret, message):
try:
import tensorflow as tf
except ImportError:
return ret
built_with_cuda = tf.test.is_built_with_cuda()
... |
Put a tf. 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:
... |
Put a 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, va... |
Put an 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 ... |
Put an: class: tf. Event. step and wall_time fields of: class: tf. Event will be filled automatically. | def put_event(self, evt):
"""
Put an :class:`tf.Event`.
`step` and `wall_time` fields of :class:`tf.Event` will be filled automatically.
Args:
evt (tf.Event):
"""
evt.step = self.global_step
evt.wall_time = time.time()
self._dispatch(lambda m:... |
Look for an existing json under: meth: logger. get_logger_dir () named stats. json and return the loaded list of statistics if found. Returns None otherwise. | def load_existing_json():
"""
Look for an existing json under :meth:`logger.get_logger_dir()` named "stats.json",
and return the loaded list of statistics if found. Returns None otherwise.
"""
dir = logger.get_logger_dir()
fname = os.path.join(dir, JSONWriter.FILENAME)
... |
Add stats to json and dump to disk. Note that this method is idempotent. | 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.... |
Args: img: bxhxwxc coords: bxh2xw2x2. each coordinate is ( y x ) integer. Out of boundary coordinates will be clipped. Return: bxh2xw2xc image | def sample(img, coords):
"""
Args:
img: bxhxwxc
coords: bxh2xw2x2. each coordinate is (y, x) integer.
Out of boundary coordinates will be clipped.
Return:
bxh2xw2xc image
"""
shape = img.get_shape().as_list()[1:] # h, w, c
batch = tf.shape(img)[0]
shape2... |
Sample the images using the given coordinates by bilinear interpolation. This was described in the paper: Spatial Transformer Networks <http:// arxiv. org/ abs/ 1506. 02025 > _. | def GridSample(inputs, borderMode='repeat'):
"""
Sample the images using the given coordinates, by bilinear interpolation.
This was described in the paper:
`Spatial Transformer Networks <http://arxiv.org/abs/1506.02025>`_.
This is equivalent to `torch.nn.functional.grid_sample`,
up to some non-... |
Enable trace for calls to any function. | 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 stat... |
Apply a set of default rules to make a fast: class: InputSource. | def apply_default_prefetch(input_source_or_dataflow, trainer):
"""
Apply a set of default rules to make a fast :class:`InputSource`.
Args:
input_source_or_dataflow(InputSource | DataFlow):
trainer (Trainer):
Returns:
InputSource
"""
if not isinstance(input_source_or_dat... |
Train with a: class: TrainConfig and a: class: Trainer to present the simple and old training interface. It basically does the following 3 things ( and you can easily do them by yourself if you need more control ): | def launch_train_with_config(config, trainer):
"""
Train with a :class:`TrainConfig` and a :class:`Trainer`, to
present the simple and old training interface. It basically does the following
3 things (and you can easily do them by yourself if you need more control):
1. Setup the input with automati... |
Delegate property to self. loop | 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
retu... |
Configure the loop given the settings. | 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... |
Register callbacks to the trainer. It can only be called before: meth: Trainer. train (). | def _register_callback(self, cb):
"""
Register callbacks to the trainer.
It can only be called before :meth:`Trainer.train()`.
Args:
cb (Callback or [Callback]): a callback or a list of callbacks
Returns:
succeed or not
"""
if isinstance(... |
Defines what to do in one iteration. The default is: self. hooked_sess. run ( self. train_op ). | def run_step(self):
"""
Defines what to do in one iteration. The default is:
``self.hooked_sess.run(self.train_op)``.
The behavior of each iteration can be changed by either setting ``trainer.train_op``,
or overriding this method.
"""
if not hasattr(self, 'train_... |
Setup callbacks and monitors. Must be called after the main graph is built. | 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 isinst... |
Create the session and set self. sess. Call self. initiailize_hooks () Finalize the graph. | def initialize(self, session_creator, session_init):
"""
Create the session and set `self.sess`.
Call `self.initiailize_hooks()`
Finalize the graph.
It must be called after callbacks are setup.
Args:
session_creator (tf.train.SessionCreator):
ses... |
Create SessionRunHooks for all callbacks and hook it onto self. sess to create self. hooked_sess. | 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`.
... |
Run the main training loop. | def main_loop(self, steps_per_epoch, starting_epoch, max_epoch):
"""
Run the main training loop.
Args:
steps_per_epoch, starting_epoch, max_epoch (int):
"""
with self.sess.as_default():
self.loop.config(steps_per_epoch, starting_epoch, max_epoch)
... |
Implemented by three lines: | def train(self,
callbacks, monitors,
session_creator, session_init,
steps_per_epoch, starting_epoch=1, max_epoch=9999999):
"""
Implemented by three lines:
.. code-block:: python
self.setup_callbacks(callbacks, monitors)
self.ini... |
Same as: meth: train () except: | def train_with_defaults(
self, _sentinel=None,
callbacks=None, monitors=None,
session_creator=None, session_init=None,
steps_per_epoch=None, starting_epoch=1, max_epoch=9999999,
extra_callbacks=None):
"""
Same as :meth:`train()`, except:
... |
Return a tf. ConfigProto to use as default session config. You can modify the returned config to fit your needs. | 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:
... |
Returns: tf. Tensor: the global_step variable in the current graph. Create if doesn t exist. | def get_global_step_var():
"""
Returns:
tf.Tensor: the global_step variable in the current graph. Create if doesn't exist.
"""
scope = tfv1.VariableScope(reuse=False, name='') # the root vs
with tfv1.variable_scope(scope):
var = tfv1.train.get_or_create_global_step()
return var |
Get a list of tensors in the default graph by a list of 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 |
Get either tf. Operation of tf. Tensor from names. | 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] =... |
Returns: str - a table contains important information about the environment | def collect_env_info():
"""
Returns:
str - a table contains important information about the environment
"""
data = []
data.append(("sys.platform", sys.platform))
data.append(("Python", sys.version.replace("\n", "")))
data.append(("Tensorpack", __git_version__))
data.append(("Nump... |
Adds ops to enqueue on all worker queues. | 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 befo... |
Create shadow variables on PS and replace variables in avg_grads by these shadow variables. | 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.na... |
Create shadow vars for model_variables as well and add to the list of shadow_vars. | 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(... |
Args: get_grad_fn ( - > [ ( grad var ) ] ): get_opt_fn ( - > tf. train. Optimizer ): callable which returns an optimizer | def build(self, get_grad_fn, get_opt_fn):
"""
Args:
get_grad_fn (-> [(grad, var)]):
get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer
Returns:
(tf.Operation, tf.Operation, tf.Operation):
1. the training op.
2. t... |
Apply averaged gradients to ps vars and then copy the updated variables back to each tower. | 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... |
Get the op to copy - initialized all local variables from PS. | 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_po... |
Get the op to sync local model_variables to PS. | 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_{... |
Args: placeholders ( list [ Tensor ] ): tensors ( list [ Tensor ] ): list of tf. Tensor names ( list [ str ] ): names matching the given tensors | def get_tensors_inputs(placeholders, tensors, names):
"""
Args:
placeholders (list[Tensor]):
tensors (list[Tensor]): list of tf.Tensor
names (list[str]): names matching the given tensors
Returns:
list[Tensor]: inputs to used for the tower function,
with the corre... |
Args: lst ( list ): list of objects with name property. | def get_sublist_by_names(lst, names):
"""
Args:
lst (list): list of objects with "name" property.
Returns:
list: a sublist of objects, matching names
"""
orig_names = [p.name for p in lst]
ret = []
for name in names:
try:
idx = orig_names.index(name)
... |
When you have some: class: InputSource which doesn t match the inputs of your tower function use RemapInputSource. It produces placeholders for all the inputs in your model except that the corresponding ones are replaced with the tensor produced by the given: class: InputSource. | def remap_input_source(input, names):
"""
When you have some :class:`InputSource` which doesn't match the inputs of
your tower function, use `RemapInputSource`.
It produces placeholders for all the inputs in your model,
except that the corresponding ones are replaced with the tensor produced
by ... |
Returns: label_logits: fHxfWxNA box_logits: fHxfWxNAx4 | def rpn_head(featuremap, channel, num_anchors):
"""
Returns:
label_logits: fHxfWxNA
box_logits: fHxfWxNAx4
"""
with argscope(Conv2D, data_format='channels_first',
kernel_initializer=tf.random_normal_initializer(stddev=0.01)):
hidden = Conv2D('conv0', featuremap,... |
Args: anchor_labels: fHxfWxNA anchor_boxes: fHxfWxNAx4 encoded label_logits: fHxfWxNA box_logits: fHxfWxNAx4 | def rpn_losses(anchor_labels, anchor_boxes, label_logits, box_logits):
"""
Args:
anchor_labels: fHxfWxNA
anchor_boxes: fHxfWxNAx4, encoded
label_logits: fHxfWxNA
box_logits: fHxfWxNAx4
Returns:
label_loss, box_loss
"""
with tf.device('/cpu:0'):
valid... |
Sample RPN proposals by the following steps: 1. Pick top k1 by scores 2. NMS them 3. Pick top k2 by scores. Default k2 == k1 i. e. does not filter the NMS output. | def generate_rpn_proposals(boxes, scores, img_shape,
pre_nms_topk, post_nms_topk=None):
"""
Sample RPN proposals by the following steps:
1. Pick top k1 by scores
2. NMS them
3. Pick top k2 by scores. Default k2 == k1, i.e. does not filter the NMS output.
Args:
... |
This callback is enabled by default. Evaluate all summaries by tf. summary. merge_all and write them to logs. | 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) mak... |
Args: exp ( Experience ): | def append(self, exp):
"""
Args:
exp (Experience):
"""
if self._curr_size < self.max_size:
self._assign(self._curr_pos, exp)
self._curr_pos = (self._curr_pos + 1) % self.max_size
self._curr_size += 1
else:
self._assign(s... |
return a tuple of ( s r a o ) where s is of shape self. _output_shape which is [ H W ( hist_len + 1 ) * channel ] if input is ( H W channel ) | def sample(self, idx):
""" return a tuple of (s,r,a,o),
where s is of shape self._output_shape, which is
[H, W, (hist_len+1) * channel] if input is (H, W, channel)"""
idx = (self._curr_pos + idx) % self._curr_size
k = self.history_len + 1
if idx + k <= self._curr_... |
Run the environment for one step. If the episode ends store the entire episode to the replay memory. | 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:
... |
Get the recent state ( with stacked history ) of the environment. | def recent_state(self):
"""
Get the recent state (with stacked history) of the environment.
Returns:
a list of ``hist_len-1`` elements, each of shape ``self.state_shape``
"""
expected_len = self.history_len - 1
if len(self._current_episode) >= expected_len:
... |
Execute one step in any of the runners. | 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) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.