INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Returns a batch of sequences.
Returns:
obs: np.int32 array of size [Time, Batch]
target: np.int32 array of size [Time, Batch] | def _get_batch(self):
"""Returns a batch of sequences.
Returns:
obs: np.int32 array of size [Time, Batch]
target: np.int32 array of size [Time, Batch]
"""
batch_indices = np.mod(
np.array([
np.arange(head_index, head_index + self._num_steps + 1) for
head_inde... |
Returns a tuple containing observation and target one-hot tensors. | def _build(self):
"""Returns a tuple containing observation and target one-hot tensors."""
q = tf.FIFOQueue(
self._queue_capacity, [self._dtype, self._dtype],
shapes=[[self._num_steps, self._batch_size, self._vocab_size]]*2)
obs, target = tf.py_func(self._get_batch, [], [tf.int32, tf.int32])... |
Returns cost.
Args:
logits: model output.
target: target.
Returns:
Cross-entropy loss for a sequence of logits. The loss will be averaged
across time steps if time_average_cost was enabled at construction time. | def cost(self, logits, target):
"""Returns cost.
Args:
logits: model output.
target: target.
Returns:
Cross-entropy loss for a sequence of logits. The loss will be averaged
across time steps if time_average_cost was enabled at construction time.
"""
logits = tf.reshape(logi... |
Returns a human-readable version of a one-hot encoding of words.
Args:
data: A tuple with (obs, target). `obs` is a numpy array with one-hot
encoding of words.
label_batch_entries: bool. Whether to add numerical label before each
batch element in the output string.
indices: Li... | def to_human_readable(self,
data,
label_batch_entries=True,
indices=None,
sep="\n"):
"""Returns a human-readable version of a one-hot encoding of words.
Args:
data: A tuple with (obs, target). `obs` is a numpy... |
Gets training and testing dataset iterators.
Args:
name: String. Name of dataset, either 'mnist' or 'cifar10'.
train_batch_size: Integer. Batch size for training.
test_batch_size: Integer. Batch size for testing.
Returns:
Dict containing:
train_iterator: A tf.data.Iterator, over training dat... | def get_data(name, train_batch_size, test_batch_size):
"""Gets training and testing dataset iterators.
Args:
name: String. Name of dataset, either 'mnist' or 'cifar10'.
train_batch_size: Integer. Batch size for training.
test_batch_size: Integer. Batch size for testing.
Returns:
Dict containing:... |
Returns the name of the variable scope indicated by the given value.
Args:
value: String, variable scope, or object with `variable_scope` attribute
(e.g., Sonnet module).
Returns:
The name (a string) of the corresponding variable scope.
Raises:
ValueError: If `value` does not identify a variabl... | def get_variable_scope_name(value):
"""Returns the name of the variable scope indicated by the given value.
Args:
value: String, variable scope, or object with `variable_scope` attribute
(e.g., Sonnet module).
Returns:
The name (a string) of the corresponding variable scope.
Raises:
ValueErro... |
Returns a tuple `tf.Variable`s in a scope for a given collection.
Args:
scope: `tf.VariableScope` or string to retrieve variables from.
collection: Collection to restrict query to. By default this is
`tf.Graphkeys.TRAINABLE_VARIABLES`, which doesn't include non-trainable
variables such as mov... | def get_variables_in_scope(scope, collection=tf.GraphKeys.TRAINABLE_VARIABLES):
"""Returns a tuple `tf.Variable`s in a scope for a given collection.
Args:
scope: `tf.VariableScope` or string to retrieve variables from.
collection: Collection to restrict query to. By default this is
`tf.Graphkeys.TR... |
Returns tuple of `tf.Variable`s declared inside an `snt.Module`.
Note that this operates by searching the variable scope a module contains,
and so does not know about any modules which were constructed elsewhere but
used inside this module.
Args:
module: `snt.Module` instance to query the scope of.
co... | def get_variables_in_module(module,
collection=tf.GraphKeys.TRAINABLE_VARIABLES):
"""Returns tuple of `tf.Variable`s declared inside an `snt.Module`.
Note that this operates by searching the variable scope a module contains,
and so does not know about any modules which were constructe... |
Checks if all items in the dictionary and in subdictionaries are callables.
Args:
dictionary: Dictionary of callables or other dictionaries with callables.
object_name: The name of the object that is expected in the dictionary.
E.g. 'Initializer', 'Partitioner' or 'Regularizer'. The first letter
... | def _check_nested_callables(dictionary, object_name):
"""Checks if all items in the dictionary and in subdictionaries are callables.
Args:
dictionary: Dictionary of callables or other dictionaries with callables.
object_name: The name of the object that is expected in the dictionary.
E.g. 'Initialize... |
Checks the given initializers.
This checks that `initializers` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `initializers` are functions or
further dictionaries (the latter used, for example, in passing initializers
to modules inside modules) that must satisfy the same cons... | def check_initializers(initializers, keys):
"""Checks the given initializers.
This checks that `initializers` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `initializers` are functions or
further dictionaries (the latter used, for example, in passing initializers
to module... |
Raises a TypeError iff `maybe_dictlike` is not a dictlike object. | def _assert_is_dictlike(maybe_dictlike, valid_keys):
"""Raises a TypeError iff `maybe_dictlike` is not a dictlike object."""
# This covers a common mistake when people use incorrect dictionary nesting
# for initializers / partitioners etc. The previous error message was quite
# opaque, this should be much clear... |
Checks the given partitioners.
This checks that `partitioners` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `partitioners` are functions or
further dictionaries (the latter used, for example, in passing partitioners
to modules inside modules) that must satisfy the same cons... | def check_partitioners(partitioners, keys):
"""Checks the given partitioners.
This checks that `partitioners` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `partitioners` are functions or
further dictionaries (the latter used, for example, in passing partitioners
to module... |
Checks the given regularizers.
This checks that `regularizers` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `regularizers` are functions or
further dictionaries (the latter used, for example, in passing regularizers
to modules inside modules) that must satisfy the same cons... | def check_regularizers(regularizers, keys):
"""Checks the given regularizers.
This checks that `regularizers` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `regularizers` are functions or
further dictionaries (the latter used, for example, in passing regularizers
to module... |
Checks that `prefix_name` is a proper scope prefix of `scope_name`. | def _is_scope_prefix(scope_name, prefix_name):
"""Checks that `prefix_name` is a proper scope prefix of `scope_name`."""
if not prefix_name:
return True
if not scope_name.endswith("/"):
scope_name += "/"
if not prefix_name.endswith("/"):
prefix_name += "/"
return scope_name.startswith(prefix_n... |
Separates the sliced (partitioned) and unsliced variables in var_list.
Args:
var_list: a list of variables.
Returns:
A list of unsliced variables in var_list, and a dict mapping names to parts
for the sliced variables in var_list. | def _get_sliced_variables(var_list):
"""Separates the sliced (partitioned) and unsliced variables in var_list.
Args:
var_list: a list of variables.
Returns:
A list of unsliced variables in var_list, and a dict mapping names to parts
for the sliced variables in var_list.
"""
unsliced_variables = ... |
Creates a custom getter than matches requests to dict of custom getters.
Custom getters are callables which implement the
[custom getter API]
(https://www.tensorflow.org/versions/r1.0/api_docs/python/tf/get_variable).
The returned custom getter dispatches calls based on pattern matching the
name of the requ... | def custom_getter_router(custom_getter_map, name_fn):
"""Creates a custom getter than matches requests to dict of custom getters.
Custom getters are callables which implement the
[custom getter API]
(https://www.tensorflow.org/versions/r1.0/api_docs/python/tf/get_variable).
The returned custom getter dispat... |
Builds map of `tf.Variable`s in scope or module with normalized names.
The names of the variables are normalized to remove the scope prefix.
Args:
scope_or_module: Scope or module to build map from.
collection: Collection to restrict query to. By default this is
`tf.Graphkeys.GLOBAL_VARIABLES`, wh... | def get_normalized_variable_map(scope_or_module,
collection=tf.GraphKeys.GLOBAL_VARIABLES,
context=None,
group_sliced_variables=True):
"""Builds map of `tf.Variable`s in scope or module with normalized names.
The names ... |
Builds a `tf.train.Saver` for the scope or module, with normalized names.
The names of the variables are normalized to remove the scope prefix.
This allows the same variables to be restored into another similar scope or
module using a complementary `tf.train.Saver` object.
Args:
scope: Scope or module. Va... | def get_saver(scope, collections=(tf.GraphKeys.GLOBAL_VARIABLES,), # pylint: disable=redefined-outer-name
context=None, **kwargs):
"""Builds a `tf.train.Saver` for the scope or module, with normalized names.
The names of the variables are normalized to remove the scope prefix.
This allows the same... |
Yields an iterator over (string, variable) pairs in the variable map.
In general, variable maps map variable names to either a `tf.Variable`, or
list of `tf.Variable`s (in case of sliced variables).
Args:
variable_map: dict, variable map over which to iterate.
Yields:
(string, tf.Variable) pairs. | def variable_map_items(variable_map):
"""Yields an iterator over (string, variable) pairs in the variable map.
In general, variable maps map variable names to either a `tf.Variable`, or
list of `tf.Variable`s (in case of sliced variables).
Args:
variable_map: dict, variable map over which to iterate.
Y... |
Returns a dict mapping variables to the collections they appear in. | def _get_vars_to_collections(variables):
"""Returns a dict mapping variables to the collections they appear in."""
var_to_collections = collections.defaultdict(lambda: [])
if isinstance(variables, dict):
variables = list(v for _, v in variable_map_items(variables))
for graph in set(v.graph for v in variable... |
Returns the device with an annotation specifying `ResourceVariable`.
"legacy" means a normal tf.Variable while "resource" means a ResourceVariable.
For example:
`(legacy)`
`(resource)`
`/job:learner/task:0/device:CPU:* (legacy)`
`/job:learner/task:0/device:CPU:* (resource)`
Args:
var: The Tensorflo... | def _format_device(var):
"""Returns the device with an annotation specifying `ResourceVariable`.
"legacy" means a normal tf.Variable while "resource" means a ResourceVariable.
For example:
`(legacy)`
`(resource)`
`/job:learner/task:0/device:CPU:* (legacy)`
`/job:learner/task:0/device:CPU:* (resource)`
... |
Takes a collection of variables and formats it as a table. | def format_variables(variables, join_lines=True):
"""Takes a collection of variables and formats it as a table."""
rows = []
rows.append(("Variable", "Shape", "Type", "Collections", "Device"))
var_to_collections = _get_vars_to_collections(variables)
for var in sorted(variables, key=lambda var: var.op.name):
... |
Takes a key-to-variable map and formats it as a table. | def format_variable_map(variable_map, join_lines=True):
"""Takes a key-to-variable map and formats it as a table."""
rows = []
rows.append(("Key", "Variable", "Shape", "Type", "Collections", "Device"))
var_to_collections = _get_vars_to_collections(variable_map)
sort_key = lambda item: (item[0], item[1].name)... |
Logs variable information.
This function logs the name, shape, type, collections, and device for either
all variables or a given iterable of variables. In the "Device" columns,
the nature of the variable (legacy or resource (for ResourceVariables)) is
also specified in parenthesis.
Args:
variables: iter... | def log_variables(variables=None):
"""Logs variable information.
This function logs the name, shape, type, collections, and device for either
all variables or a given iterable of variables. In the "Device" columns,
the nature of the variable (legacy or resource (for ResourceVariables)) is
also specified in p... |
Returns human readable string of how much memory `num_bytes` fills. | def _num_bytes_to_human_readable(num_bytes):
"""Returns human readable string of how much memory `num_bytes` fills."""
if num_bytes < (2 ** 10):
return "%d B" % num_bytes
elif num_bytes < (2 ** 20):
return "%.3f KB" % (float(num_bytes) / (2 ** 10))
elif num_bytes < (2 ** 30):
return "%.3f MB" % (flo... |
Logs a summary of variable information.
This function groups Variables by dtype and prints out the number of Variables
and the total number of scalar values for each datatype, as well as the total
memory consumed.
For Variables of type tf.string, the memory usage cannot be accurately
calculated from the Gra... | def summarize_variables(variables=None):
"""Logs a summary of variable information.
This function groups Variables by dtype and prints out the number of Variables
and the total number of scalar values for each datatype, as well as the total
memory consumed.
For Variables of type tf.string, the memory usage ... |
Returns a dict mapping dtypes to number of variables and scalars.
Args:
variables: iterable of `tf.Variable`s, or None. If None is passed, then all
global and local variables in the current graph are used.
Returns:
A dict mapping tf.dtype keys to a dict containing the keys 'num_scalars' and
'n... | def count_variables_by_type(variables=None):
"""Returns a dict mapping dtypes to number of variables and scalars.
Args:
variables: iterable of `tf.Variable`s, or None. If None is passed, then all
global and local variables in the current graph are used.
Returns:
A dict mapping tf.dtype keys to a d... |
Wraps an arbitrary method so it does variable sharing.
This decorator creates variables the first time it calls `method`, and reuses
them for subsequent calls. The object that calls `method` provides a
`tf.VariableScope`, either as a `variable_scope` attribute or as the return
value of an `_enter_variable_scop... | def reuse_variables(method):
"""Wraps an arbitrary method so it does variable sharing.
This decorator creates variables the first time it calls `method`, and reuses
them for subsequent calls. The object that calls `method` provides a
`tf.VariableScope`, either as a `variable_scope` attribute or as the return
... |
Returns a module name for a callable or `None` if no name can be found. | def name_for_callable(func):
"""Returns a module name for a callable or `None` if no name can be found."""
if isinstance(func, functools.partial):
return name_for_callable(func.func)
try:
name = func.__name__
except AttributeError:
return None
if name == "<lambda>":
return None
else:
r... |
Returns a CamelCase string as a snake_case string. | def to_snake_case(camel_case):
"""Returns a CamelCase string as a snake_case string."""
if not re.match(r"^[A-Za-z_]\w*$", camel_case):
raise ValueError(
"Input string %s is not a valid Python identifier." % camel_case)
# Add underscore at word start and ends.
underscored = re.sub(r"([A-Z][a-z])", ... |
Calls `callback(var)` for all newly created variables.
Callback should not modify the variable passed in. Use cases that require
variables to be modified should use `variable_creator_scope` directly and sit
within the variable creator stack.
>>> variables = []
>>> with notify_about_variables(variables.appen... | def notify_about_new_variables(callback):
"""Calls `callback(var)` for all newly created variables.
Callback should not modify the variable passed in. Use cases that require
variables to be modified should use `variable_creator_scope` directly and sit
within the variable creator stack.
>>> variables = []
... |
Recursively gets attributes inside `module` as specified by `path`. | def _recursive_getattr(module, path):
"""Recursively gets attributes inside `module` as specified by `path`."""
if "." not in path:
return getattr(module, path)
else:
first, rest = path.split(".", 1)
return _recursive_getattr(getattr(module, first), rest) |
Returns a callable which corresponds to the constructor string.
Various modules (eg, ConvNet2D) take constructor arguments which are
callables, indicating a submodule to build. These can be passed as
actual constructors, eg `snt.LayerNorm`, however that makes the config
for that module not trivially serializab... | def parse_string_to_constructor(ctor_string):
"""Returns a callable which corresponds to the constructor string.
Various modules (eg, ConvNet2D) take constructor arguments which are
callables, indicating a submodule to build. These can be passed as
actual constructors, eg `snt.LayerNorm`, however that makes th... |
Determines whether the provided callable supports all the kwargs.
This is useful when you have a module that might or might not support a
kwarg such as `is_training`. Rather than calling the module and catching the
error, risking the potential modification of underlying state, this function
introspects the mod... | def supports_kwargs(module_or_fn, kwargs_list):
"""Determines whether the provided callable supports all the kwargs.
This is useful when you have a module that might or might not support a
kwarg such as `is_training`. Rather than calling the module and catching the
error, risking the potential modification of ... |
Removes any kwargs not supported by `module_or_fn` from `all_kwargs_dict`.
A new dict is return with shallow copies of keys & values from
`all_kwargs_dict`, as long as the key is accepted by module_or_fn. The
returned dict can then be used to connect `module_or_fn` (along with some
other inputs, ie non-keyword... | def remove_unsupported_kwargs(module_or_fn, all_kwargs_dict):
"""Removes any kwargs not supported by `module_or_fn` from `all_kwargs_dict`.
A new dict is return with shallow copies of keys & values from
`all_kwargs_dict`, as long as the key is accepted by module_or_fn. The
returned dict can then be used to con... |
Merge the first dimensions of a tensor.
Args:
array_or_tensor: Tensor to have its first dimensions merged. Can also
be an array or numerical value, which will be converted to a tensor
for batch application, if needed.
n_dims: Number of dimensions to merge.
Returns:
Either the input val... | def merge_leading_dims(array_or_tensor, n_dims=2):
"""Merge the first dimensions of a tensor.
Args:
array_or_tensor: Tensor to have its first dimensions merged. Can also
be an array or numerical value, which will be converted to a tensor
for batch application, if needed.
n_dims: Number of d... |
Split the first dimension of a tensor.
Args:
tensor: Tensor to have its first dimension split.
inputs: Original reference input to look the dimensions of.
n_dims: Number of dimensions to split.
Returns:
The input tensor, with its first dimension split. | def split_leading_dim(tensor, inputs, n_dims=2):
"""Split the first dimension of a tensor.
Args:
tensor: Tensor to have its first dimension split.
inputs: Original reference input to look the dimensions of.
n_dims: Number of dimensions to split.
Returns:
The input tensor, with its first dimensio... |
Returns a default initializer for weights of a linear module. | def create_linear_initializer(input_size, dtype=tf.float32):
"""Returns a default initializer for weights of a linear module."""
stddev = 1 / math.sqrt(input_size)
return tf.truncated_normal_initializer(stddev=stddev, dtype=dtype) |
Calculate `bias_shape` based on the `input_shape` and `bias_dims`.
Args:
input_shape: Shape of the input being passed into the module. The leading
dimension is the minibatch size.
bias_dims: The dimensions that bias should be applied over. The remaining
dimensions will get broadcasted over.
... | def calculate_bias_shape(input_shape, bias_dims):
"""Calculate `bias_shape` based on the `input_shape` and `bias_dims`.
Args:
input_shape: Shape of the input being passed into the module. The leading
dimension is the minibatch size.
bias_dims: The dimensions that bias should be applied over. The re... |
Connects the Linear module into the graph, with input Tensor `inputs`.
If this is not the first time the module has been connected to the graph,
the Tensor provided here must have the same final dimension, in order for
the existing variables to be the correct size for the multiplication. The
batch size... | def _build(self, inputs):
"""Connects the Linear module into the graph, with input Tensor `inputs`.
If this is not the first time the module has been connected to the graph,
the Tensor provided here must have the same final dimension, in order for
the existing variables to be the correct size for the m... |
Returns the module output size. | def output_size(self):
"""Returns the module output size."""
if callable(self._output_size):
self._output_size = self._output_size()
return self._output_size |
Returns a cloned `Linear` module.
Args:
name: Optional string assigning name of cloned module. The default name
is constructed by appending "_clone" to `self.module_name`.
Returns:
Cloned `Linear` module. | def clone(self, name=None):
"""Returns a cloned `Linear` module.
Args:
name: Optional string assigning name of cloned module. The default name
is constructed by appending "_clone" to `self.module_name`.
Returns:
Cloned `Linear` module.
"""
if name is None:
name = self.m... |
Connects the module into the graph.
If this is not the first time the module has been connected to the graph,
the Tensors provided here must have the same final dimensions as when called
the first time, in order for the existing variables to be the correct size
for the multiplication. The batch size ma... | def _build(self, inputs_list):
"""Connects the module into the graph.
If this is not the first time the module has been connected to the graph,
the Tensors provided here must have the same final dimensions as when called
the first time, in order for the existing variables to be the correct size
for... |
Connects the Add module into the graph, with input Tensor `inputs`.
Args:
inputs: A Tensor of size `[batch_size, input_size1, ...]`.
multiplier: A scalar or Tensor which the bias term is multiplied by
before adding it to `inputs`. Anything which works in the expression
`bias * multiplie... | def _build(self, inputs, multiplier=1):
"""Connects the Add module into the graph, with input Tensor `inputs`.
Args:
inputs: A Tensor of size `[batch_size, input_size1, ...]`.
multiplier: A scalar or Tensor which the bias term is multiplied by
before adding it to `inputs`. Anything which wo... |
Returns transposed `AddBias` module.
Args:
name: Optional string assigning name of transpose module. The default name
is constructed by appending "_transpose" to `self.module_name`.
Returns:
Transposed `AddBias` module. | def transpose(self, name=None):
"""Returns transposed `AddBias` module.
Args:
name: Optional string assigning name of transpose module. The default name
is constructed by appending "_transpose" to `self.module_name`.
Returns:
Transposed `AddBias` module.
"""
if name is None:... |
Replaces the -1 wildcard in the output shape vector.
This function infers the correct output shape given the input dimensions.
Args:
dimensions: List of input non-batch dimensions.
Returns:
Tuple of non-batch output dimensions. | def _infer_shape(self, dimensions):
"""Replaces the -1 wildcard in the output shape vector.
This function infers the correct output shape given the input dimensions.
Args:
dimensions: List of input non-batch dimensions.
Returns:
Tuple of non-batch output dimensions.
"""
# Size of ... |
Connects the module into the graph, with input Tensor `inputs`.
Args:
inputs: A Tensor of shape [b_1, b_2, ..., b_preserve_dims,
b_preserve_dims+1, ...].
Returns:
A Tensor of shape [b_1, b_2, ..., b_preserve_dims,
b_reshape_1, b_reshape_2, ... | def _build(self, inputs):
"""Connects the module into the graph, with input Tensor `inputs`.
Args:
inputs: A Tensor of shape [b_1, b_2, ..., b_preserve_dims,
b_preserve_dims+1, ...].
Returns:
A Tensor of shape [b_1, b_2, ..., b_preserve_dims,
... |
Returns transpose batch reshape. | def transpose(self, name=None):
"""Returns transpose batch reshape."""
if name is None:
name = self.module_name + "_transpose"
return BatchReshape(shape=lambda: self.input_shape,
preserve_dims=self._preserve_dims,
name=name) |
Connects the TrainableTensor module into the graph.
Returns:
A Tensor of shape as determined in the constructor. | def _build(self):
"""Connects the TrainableTensor module into the graph.
Returns:
A Tensor of shape as determined in the constructor.
"""
if "w" not in self._initializers:
stddev = 1 / math.sqrt(np.prod(self._shape))
self._initializers["w"] = tf.truncated_normal_initializer(stddev=std... |
Connects the BatchApply module into the graph.
Args:
*args: a Tensor or a nested list or dictionary of Tensors. The input
tensors will have their first dimensions merged, then an op or a
module will be called on the input. The first dimension of the output
tensor(s) will be spli... | def _build(self, *args, **kwargs):
"""Connects the BatchApply module into the graph.
Args:
*args: a Tensor or a nested list or dictionary of Tensors. The input
tensors will have their first dimensions merged, then an op or a
module will be called on the input. The first dimension of t... |
Connects the SliceByDim module into the graph.
Args:
inputs: `Tensor` to slice. Its rank must be greater than the maximum
dimension specified in `dims` (plus one as python is 0 indexed).
Returns:
The sliced tensor.
Raises:
ValueError: If `inputs` tensor has insufficient rank. | def _build(self, inputs):
"""Connects the SliceByDim module into the graph.
Args:
inputs: `Tensor` to slice. Its rank must be greater than the maximum
dimension specified in `dims` (plus one as python is 0 indexed).
Returns:
The sliced tensor.
Raises:
ValueError: If `input... |
Connects the `TileByDim` module into the graph.
Args:
inputs: `Tensor` to tile.
Returns:
The tiled tensor. | def _build(self, inputs):
"""Connects the `TileByDim` module into the graph.
Args:
inputs: `Tensor` to tile.
Returns:
The tiled tensor.
"""
shape_inputs = inputs.get_shape().as_list()
rank = len(shape_inputs)
# Builds default lists for multiples to pass to `tf.tile`.
full_... |
Connects the MergeDims module into the graph.
Args:
inputs: Tensor or a nested list of Tensors to merge. Its rank must be
greater than or equal to `start` + `size`.
Returns:
The merged Tensor or a nested list of merged Tensors.
Raises:
ValueError: If any of the `inputs` tensor... | def _build(self, inputs):
"""Connects the MergeDims module into the graph.
Args:
inputs: Tensor or a nested list of Tensors to merge. Its rank must be
greater than or equal to `start` + `size`.
Returns:
The merged Tensor or a nested list of merged Tensors.
Raises:
ValueErr... |
Creates the initial memory.
We should ensure each row of the memory is initialized to be unique,
so initialize the matrix to be the identity. We then pad or truncate
as necessary so that init_state is of size
(batch_size, self._mem_slots, self._mem_size).
Args:
batch_size: The size of the ba... | def initial_state(self, batch_size, trainable=False):
"""Creates the initial memory.
We should ensure each row of the memory is initialized to be unique,
so initialize the matrix to be the identity. We then pad or truncate
as necessary so that init_state is of size
(batch_size, self._mem_slots, sel... |
Perform multi-head attention from 'Attention is All You Need'.
Implementation of the attention mechanism from
https://arxiv.org/abs/1706.03762.
Args:
memory: Memory tensor to perform attention on.
Returns:
new_memory: New memory tensor. | def _multihead_attention(self, memory):
"""Perform multi-head attention from 'Attention is All You Need'.
Implementation of the attention mechanism from
https://arxiv.org/abs/1706.03762.
Args:
memory: Memory tensor to perform attention on.
Returns:
new_memory: New memory tensor.
"... |
Create input and forget gates for this step using `inputs` and `memory`.
Args:
inputs: Tensor input.
memory: The current state of memory.
Returns:
input_gate: A LSTM-like insert gate.
forget_gate: A LSTM-like forget gate. | def _create_gates(self, inputs, memory):
"""Create input and forget gates for this step using `inputs` and `memory`.
Args:
inputs: Tensor input.
memory: The current state of memory.
Returns:
input_gate: A LSTM-like insert gate.
forget_gate: A LSTM-like forget gate.
"""
# We... |
Perform multiheaded attention over `memory`.
Args:
memory: Current relational memory.
Returns:
The attended-over memory. | def _attend_over_memory(self, memory):
"""Perform multiheaded attention over `memory`.
Args:
memory: Current relational memory.
Returns:
The attended-over memory.
"""
attention_mlp = basic.BatchApply(
mlp.MLP([self._mem_size] * self._attention_mlp_layers))
for _ in range(se... |
Adds relational memory to the TensorFlow graph.
Args:
inputs: Tensor input.
memory: Memory output from the previous time step.
treat_input_as_matrix: Optional, whether to treat `input` as a sequence
of matrices. Defaulta to False, in which case the input is flattened
into a vector... | def _build(self, inputs, memory, treat_input_as_matrix=False):
"""Adds relational memory to the TensorFlow graph.
Args:
inputs: Tensor input.
memory: Memory output from the previous time step.
treat_input_as_matrix: Optional, whether to treat `input` as a sequence
of matrices. Default... |
Creates a basic MNIST model using Sonnet, then trains and evaluates it. | def train_and_eval(train_batch_size, test_batch_size, num_hidden, learning_rate,
num_train_steps, report_every, test_every):
"""Creates a basic MNIST model using Sonnet, then trains and evaluates it."""
data_dict = dataset_mnist.get_data("mnist", train_batch_size, test_batch_size)
train_data =... |
Returns an initial (maybe learnable) state.
This function does not create any variable scopes, and it should be called
from a Sonnet module. This function also makes sure that all the rows of its
`state` argument have the same value.
Args:
state: initial value of the initial state. It should be a tensor o... | def _single_learnable_state(state, state_id=0, learnable=True):
"""Returns an initial (maybe learnable) state.
This function does not create any variable scopes, and it should be called
from a Sonnet module. This function also makes sure that all the rows of its
`state` argument have the same value.
Args:
... |
Creates an initial state consisting of trainable variables.
The trainable variables are created with the same shapes as the elements of
`state_size` and are tiled to produce an initial state.
Args:
batch_size: An int, or scalar int32 Tensor representing the batch size.
state_size: A `TensorShape` or nes... | def trainable_initial_state(batch_size, state_size, dtype, initializers=None,
regularizers=None, name=None):
"""Creates an initial state consisting of trainable variables.
The trainable variables are created with the same shapes as the elements of
`state_size` and are tiled to produce... |
Returns a decorator to copy documentation from the given function.
Docstring is copied, including *args and **kwargs documentation.
Args:
fn_with_doc_to_copy: Function whose docstring, including *args and
**kwargs documentation, is to be copied.
Returns:
Decorated version of `wrapper_init` with d... | def with_doc(fn_with_doc_to_copy):
"""Returns a decorator to copy documentation from the given function.
Docstring is copied, including *args and **kwargs documentation.
Args:
fn_with_doc_to_copy: Function whose docstring, including *args and
**kwargs documentation, is to be copied.
Returns:
De... |
Connects the module to the graph.
Returns:
The learnable state, which has the same type, structure and shape as
the `initial_state` passed to the constructor. | def _build(self):
"""Connects the module to the graph.
Returns:
The learnable state, which has the same type, structure and shape as
the `initial_state` passed to the constructor.
"""
flat_initial_state = nest.flatten(self._initial_state)
if self._mask is not None:
flat_mask = n... |
Connects the LayerNorm module into the graph.
Args:
inputs: a Tensor of dimensionality >= 2.
Returns:
normalized: layer normalized outputs with same shape as inputs.
Raises:
base.NotSupportedError: If `inputs` has less than 2 dimensions. | def _build(self, inputs):
"""Connects the LayerNorm module into the graph.
Args:
inputs: a Tensor of dimensionality >= 2.
Returns:
normalized: layer normalized outputs with same shape as inputs.
Raises:
base.NotSupportedError: If `inputs` has less than 2 dimensions.
"""
if ... |
Perform a differentiable read.
Args:
memory: [batch_size, memory_size, memory_word_size]-shaped Tensor of
dtype float32. This represents, for each example and memory slot, a
single embedding to attend over.
query: [batch_size, query_word_size]-shaped Tensor of dtype float32.
Rep... | def _build(self, memory, query, memory_mask=None):
"""Perform a differentiable read.
Args:
memory: [batch_size, memory_size, memory_word_size]-shaped Tensor of
dtype float32. This represents, for each example and memory slot, a
single embedding to attend over.
query: [batch_size, qu... |
Builds the statistics part of the graph when using moving variance.
Args:
input_batch: Input batch Tensor.
use_batch_stats: Boolean to indicate if batch statistics should be
calculated, otherwise moving averages are returned.
stat_dtype: TensorFlow datatype to use for the moving mean and ... | def _build_statistics(self, input_batch, use_batch_stats, stat_dtype):
"""Builds the statistics part of the graph when using moving variance.
Args:
input_batch: Input batch Tensor.
use_batch_stats: Boolean to indicate if batch statistics should be
calculated, otherwise moving averages are r... |
Builds the moving average update ops when using moving variance.
Args:
mean: The mean value to update with.
variance: The variance value to update with.
is_training: Boolean Tensor to indicate if we're currently in
training mode.
Returns:
Tuple of `(update_mean_op, update_varia... | def _build_update_ops(self, mean, variance, is_training):
"""Builds the moving average update ops when using moving variance.
Args:
mean: The mean value to update with.
variance: The variance value to update with.
is_training: Boolean Tensor to indicate if we're currently in
training ... |
Creates a fused batch normalization op. | def _fused_batch_norm_op(self, input_batch, mean, variance, use_batch_stats):
"""Creates a fused batch normalization op."""
# Store the original shape of the mean and variance.
mean_shape = mean.get_shape()
variance_shape = variance.get_shape()
# The fused batch norm expects the mean, variance, gamm... |
Connects the BatchNormV2 module into the graph.
Args:
input_batch: A Tensor of the same dimension as `len(data_format)`.
is_training: A boolean to indicate if the module should be connected in
training mode, meaning the moving averages are updated. Can be a Tensor.
test_local_stats: A boo... | def _build(self,
input_batch,
is_training,
test_local_stats=False):
"""Connects the BatchNormV2 module into the graph.
Args:
input_batch: A Tensor of the same dimension as `len(data_format)`.
is_training: A boolean to indicate if the module should be connected... |
Construct a Tensor whose values are the index along a dimension.
Construct a Tensor that counts the distance along a single dimension. This is
useful, for example, when constructing an identity matrix,
>>> x = _range_along_dimension(0, [2, 2]).eval()
>>> x
array([[0, 0],
[1, 1]], dtype=int3... | def _range_along_dimension(range_dim, shape):
"""Construct a Tensor whose values are the index along a dimension.
Construct a Tensor that counts the distance along a single dimension. This is
useful, for example, when constructing an identity matrix,
>>> x = _range_along_dimension(0, [2, 2]).eval()
>>> ... |
An initializer for constructing identity convolution kernels.
Constructs a convolution kernel such that applying it is the same as an
identity operation on the input. Formally, the kernel has entry [i, j, in,
out] = 1 if in equals out and i and j are the middle of the kernel and 0
otherwise.
Args:
shape... | def identity_kernel_initializer(shape, dtype=tf.float32, partition_info=None):
"""An initializer for constructing identity convolution kernels.
Constructs a convolution kernel such that applying it is the same as an
identity operation on the input. Formally, the kernel has entry [i, j, in,
out] = 1 if in equal... |
Build an initializer for constructing near-identity convolution kernels.
Construct a convolution kernel where in_channels and out_channels are
multiples of base_num_channels, but need not be equal. This initializer is
essentially the same as identity_kernel_initializer, except that magnitude
is "spread out" ac... | def noisy_identity_kernel_initializer(base_num_channels, stddev=1e-8):
"""Build an initializer for constructing near-identity convolution kernels.
Construct a convolution kernel where in_channels and out_channels are
multiples of base_num_channels, but need not be equal. This initializer is
essentially the sam... |
Build dilation module.
Args:
images: Tensor of shape [batch_size, height, width, depth]
and dtype float32. Represents a set of images with an arbitrary depth.
Note that when using the default initializer, depth must equal
num_output_classes.
Returns:
Tensor of shape [batch_... | def _build(self, images):
"""Build dilation module.
Args:
images: Tensor of shape [batch_size, height, width, depth]
and dtype float32. Represents a set of images with an arbitrary depth.
Note that when using the default initializer, depth must equal
num_output_classes.
Retur... |
Create a dilated convolution layer.
Args:
output_channels: int. Number of output channels for each pixel.
dilation_rate: int. Represents how many pixels each stride offset will
move. A value of 1 indicates a standard convolution.
apply_relu: bool. If True, a ReLU non-linearlity is added.
... | def _dilated_conv_layer(self, output_channels, dilation_rate, apply_relu,
name):
"""Create a dilated convolution layer.
Args:
output_channels: int. Number of output channels for each pixel.
dilation_rate: int. Represents how many pixels each stride offset will
move... |
Wraps the function and prints a warn-once (per `extra_message`) warning. | def with_deprecation_warning(fn, extra_message=''):
"""Wraps the function and prints a warn-once (per `extra_message`) warning."""
def new_fn(*args, **kwargs):
if extra_message not in _DONE_WARN:
tf.logging.warning(
'Sonnet nest is deprecated. Please use '
'tf.contrib.framework.nest in... |
A custom build method to wrap into a sonnet Module. | def custom_build(inputs, is_training, keep_prob):
"""A custom build method to wrap into a sonnet Module."""
outputs = snt.Conv2D(output_channels=32, kernel_shape=4, stride=2)(inputs)
outputs = snt.BatchNorm()(outputs, is_training=is_training)
outputs = tf.nn.relu(outputs)
outputs = snt.Conv2D(output_channels=... |
Returns a thread local stack uniquified by the given name. | def _get_or_create_stack(name):
"""Returns a thread local stack uniquified by the given name."""
stack = getattr(_LOCAL_STACKS, name, None)
if stack is None:
stack = []
setattr(_LOCAL_STACKS, name, stack)
return stack |
A pre-canned builder for diagonal gaussian posterior distributions.
Given a true `getter` function and arguments forwarded from `tf.get_variable`,
return a distribution object for a diagonal posterior over a variable of the
requisite shape.
Args:
getter: The `getter` passed to a `custom_getter`. Please se... | def diagonal_gaussian_posterior_builder(
getter, name, shape=None, *args, **kwargs):
"""A pre-canned builder for diagonal gaussian posterior distributions.
Given a true `getter` function and arguments forwarded from `tf.get_variable`,
return a distribution object for a diagonal posterior over a variable of t... |
A pre-canned builder for fixed gaussian prior distributions.
Given a true `getter` function and arguments forwarded from `tf.get_variable`,
return a distribution object for a scalar-valued fixed gaussian prior which
will be broadcast over a variable of the requisite shape.
Args:
getter: The `getter` passe... | def fixed_gaussian_prior_builder(
getter, name, dtype=None, *args, **kwargs):
"""A pre-canned builder for fixed gaussian prior distributions.
Given a true `getter` function and arguments forwarded from `tf.get_variable`,
return a distribution object for a scalar-valued fixed gaussian prior which
will be br... |
A pre-canned builder for adaptive scalar gaussian prior distributions.
Given a true `getter` function and arguments forwarded from `tf.get_variable`,
return a distribution object for a scalar-valued adaptive gaussian prior
which will be broadcast over a variable of the requisite shape. This prior's
parameters ... | def adaptive_gaussian_prior_builder(
getter, name, *args, **kwargs):
"""A pre-canned builder for adaptive scalar gaussian prior distributions.
Given a true `getter` function and arguments forwarded from `tf.get_variable`,
return a distribution object for a scalar-valued adaptive gaussian prior
which will b... |
A pre-canned builder for a ubiquitous stochastic KL estimator. | def stochastic_kl_builder(posterior, prior, sample):
"""A pre-canned builder for a ubiquitous stochastic KL estimator."""
return tf.subtract(
tf.reduce_sum(posterior.log_prob(sample)),
tf.reduce_sum(prior.log_prob(sample))) |
A pre-canned builder for the analytic kl divergence. | def analytic_kl_builder(posterior, prior, sample):
"""A pre-canned builder for the analytic kl divergence."""
del sample
return tf.reduce_sum(tfp.distributions.kl_divergence(posterior, prior)) |
Creates a custom getter which does Bayes by Backprop.
Please see `tf.get_variable` for general documentation on custom getters.
All arguments are optional. If nothing is configued, then a diagonal gaussian
posterior will be used, and a fixed N(0, 0.01) prior will be used. Please
see the default `posterior_bui... | def bayes_by_backprop_getter(
posterior_builder=diagonal_gaussian_posterior_builder,
prior_builder=fixed_gaussian_prior_builder,
kl_builder=stochastic_kl_builder,
sampling_mode_tensor=None,
fresh_noise_per_connection=True,
keep_control_dependencies=False):
"""Creates a custom getter which does... |
Create tensor representing estimate of posterior.
Args:
posterior_dist: An instance of `tfp.distributions.Distribution`.
The variational posterior from which to produce an estimate of the
variable in question.
posterior_estimate_mode: A `Tensor` of dtype `tf.string`, which
determines ... | def _produce_posterior_estimate(posterior_dist, posterior_estimate_mode,
raw_var_name):
"""Create tensor representing estimate of posterior.
Args:
posterior_dist: An instance of `tfp.distributions.Distribution`.
The variational posterior from which to produce an estimate... |
Get the total cost for all (or a subset of) the stochastic variables.
Args:
name: A name for the tensor representing the total kl cost.
filter_by_name_substring: A string used to filter which variables count
toward the total KL cost. By default, this argument is `None`, and all
variables trained ... | def get_total_kl_cost(name="total_kl_cost", filter_by_name_substring=None):
"""Get the total cost for all (or a subset of) the stochastic variables.
Args:
name: A name for the tensor representing the total kl cost.
filter_by_name_substring: A string used to filter which variables count
toward the tot... |
The shape of the output matrix. | def output_shape(self):
"""The shape of the output matrix."""
return (self._block_shape[0] * self._block_rows,
self._block_shape[1] * self._block_rows) |
Number of blocks with zeros from the left in block row `r`. | def _left_zero_blocks(self, r):
"""Number of blocks with zeros from the left in block row `r`."""
if not self._include_off_diagonal:
return r
elif not self._upper:
return 0
elif self._include_diagonal:
return r
else:
return r + 1 |
Number of blocks with zeros from the right in block row `r`. | def _right_zero_blocks(self, r):
"""Number of blocks with zeros from the right in block row `r`."""
if not self._include_off_diagonal:
return self._block_rows - r - 1
elif self._upper:
return 0
elif self._include_diagonal:
return self._block_rows - r - 1
else:
return self._bl... |
Number of content blocks in block row `r`. | def _content_blocks(self, r):
"""Number of content blocks in block row `r`."""
return (self._block_rows - self._left_zero_blocks(r)
- self._right_zero_blocks(r)) |
Construct the data, model, loss and optimizer then train. | def build_and_train(iterations, log_stride, test=False):
"""Construct the data, model, loss and optimizer then train."""
# Test mode settings.
batch_size = 2 if test else FLAGS.batch_size
num_mems = 2 if test else FLAGS.num_mems
num_heads = 1 if test else FLAGS.num_mems
num_blocks = 1 if test else FLAGS.nu... |
Dynamic unroll across input objects.
Args:
inputs: tensor (batch x num_objects x feature). Objects to sort.
Returns:
Tensor (batch x num_objects); logits indicating the reference objects. | def _build(self, inputs):
"""Dynamic unroll across input objects.
Args:
inputs: tensor (batch x num_objects x feature). Objects to sort.
Returns:
Tensor (batch x num_objects); logits indicating the reference objects.
"""
batch_size = inputs.get_shape()[0]
output_sequence, _ = tf.nn... |
Create an op that clips gradients using a Defun.
The tensorflow Defun decorator creates an op and tensorflow caches these op
automatically according to `func_name`. Using a Defun decorator twice with the
same `func_name` does not create a new op, instead the cached op is used.
This method produces a new op th... | def _clip_gradient_op(dtype):
"""Create an op that clips gradients using a Defun.
The tensorflow Defun decorator creates an op and tensorflow caches these op
automatically according to `func_name`. Using a Defun decorator twice with the
same `func_name` does not create a new op, instead the cached op is used.
... |
Clips respective gradients of a given tensor.
Acts as identity for the forward pass, but clips gradient tensor element-wise
by value during the backward pass. Any gradient values less than
`clip_value_min` or greater than `clip_values_max` are set to the respective
limit values.
Args:
net: A `tf.Tensor`... | def clip_gradient(net, clip_value_min, clip_value_max, name=None):
"""Clips respective gradients of a given tensor.
Acts as identity for the forward pass, but clips gradient tensor element-wise
by value during the backward pass. Any gradient values less than
`clip_value_min` or greater than `clip_values_max` a... |
Load PTB raw data from data directory "data_path".
Reads PTB text files, converts strings to integer ids,
and performs mini-batching of the inputs.
The PTB dataset comes from Tomas Mikolov's webpage:
http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz
Args:
data_path: string path to the direct... | def ptb_raw_data(data_path):
"""Load PTB raw data from data directory "data_path".
Reads PTB text files, converts strings to integer ids,
and performs mini-batching of the inputs.
The PTB dataset comes from Tomas Mikolov's webpage:
http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz
Args:
da... |
Checks that the normalization constructor is callable. | def _check_and_assign_normalization_members(self, normalization_ctor,
normalization_kwargs):
"""Checks that the normalization constructor is callable."""
if isinstance(normalization_ctor, six.string_types):
normalization_ctor = util.parse_string_to_constructor... |
Sets up normalization, checking old and new flags. | def _parse_normalization_kwargs(self, use_batch_norm, batch_norm_config,
normalization_ctor, normalization_kwargs):
"""Sets up normalization, checking old and new flags."""
if use_batch_norm is not None:
# Delete this whole block when deprecation is done.
util.depre... |
Instantiates all the convolutional modules used in the network. | def _instantiate_layers(self):
"""Instantiates all the convolutional modules used in the network."""
# Here we are entering the module's variable scope to name our submodules
# correctly (not to create variables). As such it's safe to not check
# whether we're in the same graph. This is important if we... |
Assembles the `ConvNet2D` and connects it to the graph.
Args:
inputs: A 4D Tensor of shape `[batch_size, input_height, input_width,
input_channels]`.
**normalization_build_kwargs: kwargs passed to the normalization module
at _build time.
Returns:
A 4D Tensor of shape `[batch_... | def _build(self, inputs, **normalization_build_kwargs):
"""Assembles the `ConvNet2D` and connects it to the graph.
Args:
inputs: A 4D Tensor of shape `[batch_size, input_height, input_width,
input_channels]`.
**normalization_build_kwargs: kwargs passed to the normalization module
at... |
Returns transposed version of this network.
Args:
transpose_constructor: A method that creates an instance of the transposed
network type. The method must accept the same kwargs as this methods
with the exception of the `transpose_constructor` argument.
name: Optional string specifying ... | def _transpose(self,
transpose_constructor,
name=None,
output_channels=None,
kernel_shapes=None,
strides=None,
paddings=None,
activation=None,
activate_final=None,
nor... |
Returns transposed version of this network.
Args:
name: Optional string specifying the name of the transposed module. The
default name is constructed by appending "_transpose"
to `self.module_name`.
output_channels: Optional iterable of numbers of output channels.
kernel_shapes: O... | def transpose(self,
name=None,
output_channels=None,
kernel_shapes=None,
strides=None,
paddings=None,
activation=None,
activate_final=None,
normalization_ctor=None,
normalizati... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.