partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | TokenDataSource.generate_flat_data | Generates batched data in flat numpy arrays.
Raises:
ValueError: When too many generate calls are required. | sonnet/examples/learn_to_execute.py | def generate_flat_data(self):
"""Generates batched data in flat numpy arrays.
Raises:
ValueError: When too many generate calls are required.
"""
# Construct the string statements.
all_statements = []
all_targets = []
self.sequence_sizes_in = []
self.sequence_sizes_out = []
for... | def generate_flat_data(self):
"""Generates batched data in flat numpy arrays.
Raises:
ValueError: When too many generate calls are required.
"""
# Construct the string statements.
all_statements = []
all_targets = []
self.sequence_sizes_in = []
self.sequence_sizes_out = []
for... | [
"Generates",
"batched",
"data",
"in",
"flat",
"numpy",
"arrays",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/learn_to_execute.py#L656-L699 | [
"def",
"generate_flat_data",
"(",
"self",
")",
":",
"# Construct the string statements.",
"all_statements",
"=",
"[",
"]",
"all_targets",
"=",
"[",
"]",
"self",
".",
"sequence_sizes_in",
"=",
"[",
"]",
"self",
".",
"sequence_sizes_out",
"=",
"[",
"]",
"for",
"... | 00612ca3178964d86b556e062694d808ff81fcca |
train | TokenDataSource.tokenize | Produces the list of integer indices corresponding to a token list.
Args:
char_input: The character string to be tokenized.
max_len: Truncation length.
by_char: If true each character is a token - otherwise alpha-numeric
groupings are tokens.
Returns:
A padded list of st... | sonnet/examples/learn_to_execute.py | def tokenize(self, char_input, max_len, by_char=False):
"""Produces the list of integer indices corresponding to a token list.
Args:
char_input: The character string to be tokenized.
max_len: Truncation length.
by_char: If true each character is a token - otherwise alpha-numeric
... | def tokenize(self, char_input, max_len, by_char=False):
"""Produces the list of integer indices corresponding to a token list.
Args:
char_input: The character string to be tokenized.
max_len: Truncation length.
by_char: If true each character is a token - otherwise alpha-numeric
... | [
"Produces",
"the",
"list",
"of",
"integer",
"indices",
"corresponding",
"to",
"a",
"token",
"list",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/learn_to_execute.py#L701-L747 | [
"def",
"tokenize",
"(",
"self",
",",
"char_input",
",",
"max_len",
",",
"by_char",
"=",
"False",
")",
":",
"if",
"by_char",
":",
"tokenized_list",
"=",
"[",
"self",
".",
"_vocab_dict",
"[",
"token",
"]",
"for",
"token",
"in",
"char_input",
"]",
"else",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | LearnToExecuteState.get_task_ops | Returns an operations list based on the specified task index.
Args:
task_type: indicates the task type used.
Returns:
List of the eligible ops. | sonnet/examples/learn_to_execute.py | def get_task_ops(task_type=TaskType.ALG_CTRL):
"""Returns an operations list based on the specified task index.
Args:
task_type: indicates the task type used.
Returns:
List of the eligible ops.
"""
try:
return LearnToExecuteState.TASK_TYPE_OPS[task_type]
except KeyError:
... | def get_task_ops(task_type=TaskType.ALG_CTRL):
"""Returns an operations list based on the specified task index.
Args:
task_type: indicates the task type used.
Returns:
List of the eligible ops.
"""
try:
return LearnToExecuteState.TASK_TYPE_OPS[task_type]
except KeyError:
... | [
"Returns",
"an",
"operations",
"list",
"based",
"on",
"the",
"specified",
"task",
"index",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/learn_to_execute.py#L863-L875 | [
"def",
"get_task_ops",
"(",
"task_type",
"=",
"TaskType",
".",
"ALG_CTRL",
")",
":",
"try",
":",
"return",
"LearnToExecuteState",
".",
"TASK_TYPE_OPS",
"[",
"task_type",
"]",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"\"Bad task_type '%s', check config.\"... | 00612ca3178964d86b556e062694d808ff81fcca |
train | LearnToExecuteState.make_batch | Generator function for batchifying data for learning to execute.
Yields:
tuple:
1. one-hot input tensor, representing programmatic input
2. one-hot target tensor, the vealuation result.
3. one-hot decoder target, start symbol added for sequence decoding.
4. batch size tensor c... | sonnet/examples/learn_to_execute.py | def make_batch(self):
"""Generator function for batchifying data for learning to execute.
Yields:
tuple:
1. one-hot input tensor, representing programmatic input
2. one-hot target tensor, the vealuation result.
3. one-hot decoder target, start symbol added for sequence decoding.
... | def make_batch(self):
"""Generator function for batchifying data for learning to execute.
Yields:
tuple:
1. one-hot input tensor, representing programmatic input
2. one-hot target tensor, the vealuation result.
3. one-hot decoder target, start symbol added for sequence decoding.
... | [
"Generator",
"function",
"for",
"batchifying",
"data",
"for",
"learning",
"to",
"execute",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/learn_to_execute.py#L932-L957 | [
"def",
"make_batch",
"(",
"self",
")",
":",
"while",
"True",
":",
"self",
".",
"reset_data_source",
"(",
")",
"obs",
"=",
"np",
".",
"reshape",
"(",
"self",
".",
"_data_source",
".",
"flat_data",
",",
"[",
"self",
".",
"batch_size",
",",
"-",
"1",
"]... | 00612ca3178964d86b556e062694d808ff81fcca |
train | LearnToExecuteState.to_human_readable | Returns a human-readable version of a one-hot encoding of words.
Args:
data: (numpy.ndarray S x B x OH). One-hot encoding of words. S is
sequence length, B is batch size, OH is one hot dimensionality.
label_batch_entries: (bool). Whether to add numerical label before each
batch elem... | sonnet/examples/learn_to_execute.py | 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: (numpy.ndarray S x B x OH). One-hot encoding of words. S is
sequence length, B is batch size, OH is one ho... | 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: (numpy.ndarray S x B x OH). One-hot encoding of words. S is
sequence length, B is batch size, OH is one ho... | [
"Returns",
"a",
"human",
"-",
"readable",
"version",
"of",
"a",
"one",
"-",
"hot",
"encoding",
"of",
"words",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/learn_to_execute.py#L959-L983 | [
"def",
"to_human_readable",
"(",
"self",
",",
"data",
",",
"label_batch_entries",
"=",
"True",
",",
"indices",
"=",
"None",
",",
"sep",
"=",
"\"\\n\"",
")",
":",
"batch_size",
"=",
"data",
".",
"shape",
"[",
"1",
"]",
"result",
"=",
"[",
"]",
"indices"... | 00612ca3178964d86b556e062694d808ff81fcca |
train | BatchNorm._infer_fused_data_format | Infers the data format for the fused batch norm.
It uses the axis option to infer this information. Specifically, the
axis value (0, 1, 2) corresponds to data format NHWC and the
axis value (0, 2, 3) to data format NCHW.
Args:
input_batch: A Tensor of arbitrary dimension.
Returns:
A s... | sonnet/python/modules/batch_norm.py | def _infer_fused_data_format(self, input_batch):
"""Infers the data format for the fused batch norm.
It uses the axis option to infer this information. Specifically, the
axis value (0, 1, 2) corresponds to data format NHWC and the
axis value (0, 2, 3) to data format NCHW.
Args:
input_batch: ... | def _infer_fused_data_format(self, input_batch):
"""Infers the data format for the fused batch norm.
It uses the axis option to infer this information. Specifically, the
axis value (0, 1, 2) corresponds to data format NHWC and the
axis value (0, 2, 3) to data format NCHW.
Args:
input_batch: ... | [
"Infers",
"the",
"data",
"format",
"for",
"the",
"fused",
"batch",
"norm",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm.py#L325-L359 | [
"def",
"_infer_fused_data_format",
"(",
"self",
",",
"input_batch",
")",
":",
"input_shape",
"=",
"input_batch",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"input_shape_len",
"=",
"len",
"(",
"input_shape",
")",
"if",
"input_shape_len",
"!=",
"4",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | BatchNorm._fused_batch_norm_op | Creates a fused batch normalization op. | sonnet/python/modules/batch_norm.py | 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... | 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... | [
"Creates",
"a",
"fused",
"batch",
"normalization",
"op",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm.py#L361-L398 | [
"def",
"_fused_batch_norm_op",
"(",
"self",
",",
"input_batch",
",",
"mean",
",",
"variance",
",",
"use_batch_stats",
")",
":",
"# Store the original shape of the mean and variance.",
"mean_shape",
"=",
"mean",
".",
"get_shape",
"(",
")",
"variance_shape",
"=",
"varia... | 00612ca3178964d86b556e062694d808ff81fcca |
train | BatchNorm._batch_norm_op | Creates a batch normalization op.
It uses the tf.nn.batch_normalization op by default and the
tf.nn.fused_batch_norm op to support fused batch normalization.
Args:
input_batch: A input Tensor of arbitrary dimension.
mean: A mean tensor, of the same dtype as `input_batch`.
variance: A var... | sonnet/python/modules/batch_norm.py | def _batch_norm_op(self, input_batch, mean, variance, use_batch_stats,
stat_dtype):
"""Creates a batch normalization op.
It uses the tf.nn.batch_normalization op by default and the
tf.nn.fused_batch_norm op to support fused batch normalization.
Args:
input_batch: A input Ten... | def _batch_norm_op(self, input_batch, mean, variance, use_batch_stats,
stat_dtype):
"""Creates a batch normalization op.
It uses the tf.nn.batch_normalization op by default and the
tf.nn.fused_batch_norm op to support fused batch normalization.
Args:
input_batch: A input Ten... | [
"Creates",
"a",
"batch",
"normalization",
"op",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm.py#L400-L442 | [
"def",
"_batch_norm_op",
"(",
"self",
",",
"input_batch",
",",
"mean",
",",
"variance",
",",
"use_batch_stats",
",",
"stat_dtype",
")",
":",
"if",
"self",
".",
"_fused",
":",
"# For the non-training case where not using batch stats,",
"# pass in the moving statistic varia... | 00612ca3178964d86b556e062694d808ff81fcca |
train | BatchNorm._build_scale_offset | Sets up optional scale and offset factors. | sonnet/python/modules/batch_norm.py | def _build_scale_offset(self, dtype):
"""Sets up optional scale and offset factors."""
# tf.nn.fused_batch_norm accepts float16 batch data, but not scale/offset.
if self._fused and dtype == tf.float16:
dtype = tf.float32
# The fused batch norm operation needs the beta, gamma variables,
# so ... | def _build_scale_offset(self, dtype):
"""Sets up optional scale and offset factors."""
# tf.nn.fused_batch_norm accepts float16 batch data, but not scale/offset.
if self._fused and dtype == tf.float16:
dtype = tf.float32
# The fused batch norm operation needs the beta, gamma variables,
# so ... | [
"Sets",
"up",
"optional",
"scale",
"and",
"offset",
"factors",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm.py#L444-L478 | [
"def",
"_build_scale_offset",
"(",
"self",
",",
"dtype",
")",
":",
"# tf.nn.fused_batch_norm accepts float16 batch data, but not scale/offset.",
"if",
"self",
".",
"_fused",
"and",
"dtype",
"==",
"tf",
".",
"float16",
":",
"dtype",
"=",
"tf",
".",
"float32",
"# The ... | 00612ca3178964d86b556e062694d808ff81fcca |
train | BatchNorm._build | Connects the BatchNorm module into the graph.
Args:
input_batch: A Tensor of arbitrary dimension. By default, the final
dimension is not reduced over when computing the minibatch statistics.
is_training: A boolean to indicate if the module should be connected in
training mode, meaning t... | sonnet/python/modules/batch_norm.py | def _build(self, input_batch, is_training, test_local_stats=True):
"""Connects the BatchNorm module into the graph.
Args:
input_batch: A Tensor of arbitrary dimension. By default, the final
dimension is not reduced over when computing the minibatch statistics.
is_training: A boolean to indi... | def _build(self, input_batch, is_training, test_local_stats=True):
"""Connects the BatchNorm module into the graph.
Args:
input_batch: A Tensor of arbitrary dimension. By default, the final
dimension is not reduced over when computing the minibatch statistics.
is_training: A boolean to indi... | [
"Connects",
"the",
"BatchNorm",
"module",
"into",
"the",
"graph",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm.py#L480-L557 | [
"def",
"_build",
"(",
"self",
",",
"input_batch",
",",
"is_training",
",",
"test_local_stats",
"=",
"True",
")",
":",
"input_shape",
"=",
"input_batch",
".",
"get_shape",
"(",
")",
"if",
"self",
".",
"_axis",
"is",
"not",
"None",
":",
"if",
"len",
"(",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | TokenDataSource.tokenize | Produces the list of integer indices corresponding to a token list. | sonnet/examples/dataset_shakespeare.py | def tokenize(self, token_list):
"""Produces the list of integer indices corresponding to a token list."""
return [
self._vocab_dict.get(token, self._vocab_dict[self.UNK])
for token in token_list
] | def tokenize(self, token_list):
"""Produces the list of integer indices corresponding to a token list."""
return [
self._vocab_dict.get(token, self._vocab_dict[self.UNK])
for token in token_list
] | [
"Produces",
"the",
"list",
"of",
"integer",
"indices",
"corresponding",
"to",
"a",
"token",
"list",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/dataset_shakespeare.py#L81-L86 | [
"def",
"tokenize",
"(",
"self",
",",
"token_list",
")",
":",
"return",
"[",
"self",
".",
"_vocab_dict",
".",
"get",
"(",
"token",
",",
"self",
".",
"_vocab_dict",
"[",
"self",
".",
"UNK",
"]",
")",
"for",
"token",
"in",
"token_list",
"]"
] | 00612ca3178964d86b556e062694d808ff81fcca |
train | TinyShakespeareDataset._get_batch | Returns a batch of sequences.
Returns:
obs: np.int32 array of size [Time, Batch]
target: np.int32 array of size [Time, Batch] | sonnet/examples/dataset_shakespeare.py | 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... | 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",
"batch",
"of",
"sequences",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/dataset_shakespeare.py#L156-L181 | [
"def",
"_get_batch",
"(",
"self",
")",
":",
"batch_indices",
"=",
"np",
".",
"mod",
"(",
"np",
".",
"array",
"(",
"[",
"np",
".",
"arange",
"(",
"head_index",
",",
"head_index",
"+",
"self",
".",
"_num_steps",
"+",
"1",
")",
"for",
"head_index",
"in"... | 00612ca3178964d86b556e062694d808ff81fcca |
train | TinyShakespeareDataset._build | Returns a tuple containing observation and target one-hot tensors. | sonnet/examples/dataset_shakespeare.py | 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])... | 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",
"a",
"tuple",
"containing",
"observation",
"and",
"target",
"one",
"-",
"hot",
"tensors",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/dataset_shakespeare.py#L183-L194 | [
"def",
"_build",
"(",
"self",
")",
":",
"q",
"=",
"tf",
".",
"FIFOQueue",
"(",
"self",
".",
"_queue_capacity",
",",
"[",
"self",
".",
"_dtype",
",",
"self",
".",
"_dtype",
"]",
",",
"shapes",
"=",
"[",
"[",
"self",
".",
"_num_steps",
",",
"self",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | TinyShakespeareDataset.cost | 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. | sonnet/examples/dataset_shakespeare.py | 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... | 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",
"cost",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/dataset_shakespeare.py#L196-L212 | [
"def",
"cost",
"(",
"self",
",",
"logits",
",",
"target",
")",
":",
"logits",
"=",
"tf",
".",
"reshape",
"(",
"logits",
",",
"[",
"self",
".",
"_num_steps",
"*",
"self",
".",
"_batch_size",
",",
"-",
"1",
"]",
")",
"target",
"=",
"tf",
".",
"resh... | 00612ca3178964d86b556e062694d808ff81fcca |
train | TinyShakespeareDataset.to_human_readable | 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... | sonnet/examples/dataset_shakespeare.py | 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... | 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... | [
"Returns",
"a",
"human",
"-",
"readable",
"version",
"of",
"a",
"one",
"-",
"hot",
"encoding",
"of",
"words",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/dataset_shakespeare.py#L214-L242 | [
"def",
"to_human_readable",
"(",
"self",
",",
"data",
",",
"label_batch_entries",
"=",
"True",
",",
"indices",
"=",
"None",
",",
"sep",
"=",
"\"\\n\"",
")",
":",
"obs",
"=",
"data",
"[",
"0",
"]",
"batch_size",
"=",
"obs",
".",
"shape",
"[",
"1",
"]"... | 00612ca3178964d86b556e062694d808ff81fcca |
train | get_data | 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... | sonnet/examples/dataset_mnist_cifar10.py | 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:... | 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:... | [
"Gets",
"training",
"and",
"testing",
"dataset",
"iterators",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/dataset_mnist_cifar10.py#L34-L87 | [
"def",
"get_data",
"(",
"name",
",",
"train_batch_size",
",",
"test_batch_size",
")",
":",
"if",
"name",
"not",
"in",
"[",
"'mnist'",
",",
"'cifar10'",
"]",
":",
"raise",
"ValueError",
"(",
"'Expected dataset \\'mnist\\' or \\'cifar10\\', but got %s'",
"%",
"name",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | get_variable_scope_name | 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... | sonnet/python/modules/util.py | 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... | 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",
"the",
"name",
"of",
"the",
"variable",
"scope",
"indicated",
"by",
"the",
"given",
"value",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L38-L58 | [
"def",
"get_variable_scope_name",
"(",
"value",
")",
":",
"# If the object has a \"variable_scope\" property, use it.",
"value",
"=",
"getattr",
"(",
"value",
",",
"\"variable_scope\"",
",",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"tf",
".",
"VariableScop... | 00612ca3178964d86b556e062694d808ff81fcca |
train | get_variables_in_scope | 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... | sonnet/python/modules/util.py | 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... | 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",
"a",
"tuple",
"tf",
".",
"Variable",
"s",
"in",
"a",
"scope",
"for",
"a",
"given",
"collection",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L61-L81 | [
"def",
"get_variables_in_scope",
"(",
"scope",
",",
"collection",
"=",
"tf",
".",
"GraphKeys",
".",
"TRAINABLE_VARIABLES",
")",
":",
"scope_name",
"=",
"get_variable_scope_name",
"(",
"scope",
")",
"if",
"scope_name",
":",
"# Escape the name in case it contains any \".\... | 00612ca3178964d86b556e062694d808ff81fcca |
train | get_variables_in_module | 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... | sonnet/python/modules/util.py | 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... | 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... | [
"Returns",
"tuple",
"of",
"tf",
".",
"Variable",
"s",
"declared",
"inside",
"an",
"snt",
".",
"Module",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L84-L104 | [
"def",
"get_variables_in_module",
"(",
"module",
",",
"collection",
"=",
"tf",
".",
"GraphKeys",
".",
"TRAINABLE_VARIABLES",
")",
":",
"return",
"module",
".",
"get_variables",
"(",
"collection",
"=",
"collection",
")"
] | 00612ca3178964d86b556e062694d808ff81fcca |
train | _check_nested_callables | 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
... | sonnet/python/modules/util.py | 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... | 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",
"if",
"all",
"items",
"in",
"the",
"dictionary",
"and",
"in",
"subdictionaries",
"are",
"callables",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L107-L126 | [
"def",
"_check_nested_callables",
"(",
"dictionary",
",",
"object_name",
")",
":",
"for",
"key",
",",
"entry",
"in",
"six",
".",
"iteritems",
"(",
"dictionary",
")",
":",
"if",
"hasattr",
"(",
"entry",
",",
"\"items\"",
")",
":",
"_check_nested_callables",
"... | 00612ca3178964d86b556e062694d808ff81fcca |
train | _assert_is_dictlike | Raises a TypeError iff `maybe_dictlike` is not a dictlike object. | sonnet/python/modules/util.py | 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... | 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... | [
"Raises",
"a",
"TypeError",
"iff",
"maybe_dictlike",
"is",
"not",
"a",
"dictlike",
"object",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L129-L137 | [
"def",
"_assert_is_dictlike",
"(",
"maybe_dictlike",
",",
"valid_keys",
")",
":",
"# 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 clearer.",
"if",
"not... | 00612ca3178964d86b556e062694d808ff81fcca |
train | check_initializers | 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... | sonnet/python/modules/util.py | 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... | 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... | [
"Checks",
"the",
"given",
"initializers",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L140-L178 | [
"def",
"check_initializers",
"(",
"initializers",
",",
"keys",
")",
":",
"if",
"initializers",
"is",
"None",
":",
"return",
"{",
"}",
"_assert_is_dictlike",
"(",
"initializers",
",",
"valid_keys",
"=",
"keys",
")",
"keys",
"=",
"set",
"(",
"keys",
")",
"if... | 00612ca3178964d86b556e062694d808ff81fcca |
train | check_partitioners | 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... | sonnet/python/modules/util.py | 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... | 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",
"partitioners",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L181-L219 | [
"def",
"check_partitioners",
"(",
"partitioners",
",",
"keys",
")",
":",
"if",
"partitioners",
"is",
"None",
":",
"return",
"{",
"}",
"_assert_is_dictlike",
"(",
"partitioners",
",",
"valid_keys",
"=",
"keys",
")",
"keys",
"=",
"set",
"(",
"keys",
")",
"if... | 00612ca3178964d86b556e062694d808ff81fcca |
train | check_regularizers | 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... | sonnet/python/modules/util.py | 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... | 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",
"the",
"given",
"regularizers",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L222-L260 | [
"def",
"check_regularizers",
"(",
"regularizers",
",",
"keys",
")",
":",
"if",
"regularizers",
"is",
"None",
":",
"return",
"{",
"}",
"_assert_is_dictlike",
"(",
"regularizers",
",",
"valid_keys",
"=",
"keys",
")",
"keys",
"=",
"set",
"(",
"keys",
")",
"if... | 00612ca3178964d86b556e062694d808ff81fcca |
train | _is_scope_prefix | Checks that `prefix_name` is a proper scope prefix of `scope_name`. | sonnet/python/modules/util.py | 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... | 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... | [
"Checks",
"that",
"prefix_name",
"is",
"a",
"proper",
"scope",
"prefix",
"of",
"scope_name",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L263-L275 | [
"def",
"_is_scope_prefix",
"(",
"scope_name",
",",
"prefix_name",
")",
":",
"if",
"not",
"prefix_name",
":",
"return",
"True",
"if",
"not",
"scope_name",
".",
"endswith",
"(",
"\"/\"",
")",
":",
"scope_name",
"+=",
"\"/\"",
"if",
"not",
"prefix_name",
".",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | _get_sliced_variables | 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. | sonnet/python/modules/util.py | 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 = ... | 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 = ... | [
"Separates",
"the",
"sliced",
"(",
"partitioned",
")",
"and",
"unsliced",
"variables",
"in",
"var_list",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L279-L296 | [
"def",
"_get_sliced_variables",
"(",
"var_list",
")",
":",
"unsliced_variables",
"=",
"[",
"]",
"sliced_variables",
"=",
"collections",
".",
"defaultdict",
"(",
"lambda",
":",
"[",
"]",
")",
"for",
"var",
"in",
"var_list",
":",
"if",
"var",
".",
"_save_slice... | 00612ca3178964d86b556e062694d808ff81fcca |
train | custom_getter_router | 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... | sonnet/python/modules/util.py | 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... | 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... | [
"Creates",
"a",
"custom",
"getter",
"than",
"matches",
"requests",
"to",
"dict",
"of",
"custom",
"getters",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L300-L368 | [
"def",
"custom_getter_router",
"(",
"custom_getter_map",
",",
"name_fn",
")",
":",
"for",
"custom_getter",
"in",
"custom_getter_map",
".",
"values",
"(",
")",
":",
"if",
"not",
"callable",
"(",
"custom_getter",
")",
":",
"raise",
"TypeError",
"(",
"\"Given custo... | 00612ca3178964d86b556e062694d808ff81fcca |
train | get_normalized_variable_map | 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... | sonnet/python/modules/util.py | 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 ... | 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",
"map",
"of",
"tf",
".",
"Variable",
"s",
"in",
"scope",
"or",
"module",
"with",
"normalized",
"names",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L371-L425 | [
"def",
"get_normalized_variable_map",
"(",
"scope_or_module",
",",
"collection",
"=",
"tf",
".",
"GraphKeys",
".",
"GLOBAL_VARIABLES",
",",
"context",
"=",
"None",
",",
"group_sliced_variables",
"=",
"True",
")",
":",
"scope_name",
"=",
"get_variable_scope_name",
"(... | 00612ca3178964d86b556e062694d808ff81fcca |
train | get_saver | 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... | sonnet/python/modules/util.py | 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... | 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... | [
"Builds",
"a",
"tf",
".",
"train",
".",
"Saver",
"for",
"the",
"scope",
"or",
"module",
"with",
"normalized",
"names",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L428-L453 | [
"def",
"get_saver",
"(",
"scope",
",",
"collections",
"=",
"(",
"tf",
".",
"GraphKeys",
".",
"GLOBAL_VARIABLES",
",",
")",
",",
"# pylint: disable=redefined-outer-name",
"context",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"variable_map",
"=",
"{",
"}"... | 00612ca3178964d86b556e062694d808ff81fcca |
train | variable_map_items | 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. | sonnet/python/modules/util.py | 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... | 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... | [
"Yields",
"an",
"iterator",
"over",
"(",
"string",
"variable",
")",
"pairs",
"in",
"the",
"variable",
"map",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L471-L488 | [
"def",
"variable_map_items",
"(",
"variable_map",
")",
":",
"for",
"key",
",",
"var_or_vars",
"in",
"six",
".",
"iteritems",
"(",
"variable_map",
")",
":",
"if",
"isinstance",
"(",
"var_or_vars",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"var... | 00612ca3178964d86b556e062694d808ff81fcca |
train | _get_vars_to_collections | Returns a dict mapping variables to the collections they appear in. | sonnet/python/modules/util.py | 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... | 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",
"a",
"dict",
"mapping",
"variables",
"to",
"the",
"collections",
"they",
"appear",
"in",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L491-L506 | [
"def",
"_get_vars_to_collections",
"(",
"variables",
")",
":",
"var_to_collections",
"=",
"collections",
".",
"defaultdict",
"(",
"lambda",
":",
"[",
"]",
")",
"if",
"isinstance",
"(",
"variables",
",",
"dict",
")",
":",
"variables",
"=",
"list",
"(",
"v",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | _format_device | 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... | sonnet/python/modules/util.py | 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)`
... | 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)`
... | [
"Returns",
"the",
"device",
"with",
"an",
"annotation",
"specifying",
"ResourceVariable",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L509-L531 | [
"def",
"_format_device",
"(",
"var",
")",
":",
"if",
"var",
".",
"dtype",
".",
"name",
".",
"endswith",
"(",
"\"_ref\"",
")",
":",
"resource_var_annotation",
"=",
"\"(legacy)\"",
"else",
":",
"resource_var_annotation",
"=",
"\"(resource)\"",
"if",
"var",
".",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | format_variables | Takes a collection of variables and formats it as a table. | sonnet/python/modules/util.py | 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):
... | 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",
"collection",
"of",
"variables",
"and",
"formats",
"it",
"as",
"a",
"table",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L534-L547 | [
"def",
"format_variables",
"(",
"variables",
",",
"join_lines",
"=",
"True",
")",
":",
"rows",
"=",
"[",
"]",
"rows",
".",
"append",
"(",
"(",
"\"Variable\"",
",",
"\"Shape\"",
",",
"\"Type\"",
",",
"\"Collections\"",
",",
"\"Device\"",
")",
")",
"var_to_c... | 00612ca3178964d86b556e062694d808ff81fcca |
train | format_variable_map | Takes a key-to-variable map and formats it as a table. | sonnet/python/modules/util.py | 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)... | 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)... | [
"Takes",
"a",
"key",
"-",
"to",
"-",
"variable",
"map",
"and",
"formats",
"it",
"as",
"a",
"table",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L550-L562 | [
"def",
"format_variable_map",
"(",
"variable_map",
",",
"join_lines",
"=",
"True",
")",
":",
"rows",
"=",
"[",
"]",
"rows",
".",
"append",
"(",
"(",
"\"Key\"",
",",
"\"Variable\"",
",",
"\"Shape\"",
",",
"\"Type\"",
",",
"\"Collections\"",
",",
"\"Device\"",... | 00612ca3178964d86b556e062694d808ff81fcca |
train | log_variables | 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... | sonnet/python/modules/util.py | 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... | 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... | [
"Logs",
"variable",
"information",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L565-L580 | [
"def",
"log_variables",
"(",
"variables",
"=",
"None",
")",
":",
"if",
"variables",
"is",
"None",
":",
"variables",
"=",
"tf",
".",
"global_variables",
"(",
")",
"+",
"tf",
".",
"local_variables",
"(",
")",
"for",
"row",
"in",
"format_variables",
"(",
"v... | 00612ca3178964d86b556e062694d808ff81fcca |
train | _num_bytes_to_human_readable | Returns human readable string of how much memory `num_bytes` fills. | sonnet/python/modules/util.py | 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... | 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... | [
"Returns",
"human",
"readable",
"string",
"of",
"how",
"much",
"memory",
"num_bytes",
"fills",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L583-L592 | [
"def",
"_num_bytes_to_human_readable",
"(",
"num_bytes",
")",
":",
"if",
"num_bytes",
"<",
"(",
"2",
"**",
"10",
")",
":",
"return",
"\"%d B\"",
"%",
"num_bytes",
"elif",
"num_bytes",
"<",
"(",
"2",
"**",
"20",
")",
":",
"return",
"\"%.3f KB\"",
"%",
"("... | 00612ca3178964d86b556e062694d808ff81fcca |
train | summarize_variables | 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... | sonnet/python/modules/util.py | 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 ... | 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 ... | [
"Logs",
"a",
"summary",
"of",
"variable",
"information",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L595-L627 | [
"def",
"summarize_variables",
"(",
"variables",
"=",
"None",
")",
":",
"variable_counts",
"=",
"count_variables_by_type",
"(",
"variables",
"=",
"variables",
")",
"total_num_scalars",
"=",
"0",
"total_num_bytes",
"=",
"0",
"# Sort by string representation of type name, so... | 00612ca3178964d86b556e062694d808ff81fcca |
train | count_variables_by_type | 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... | sonnet/python/modules/util.py | 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... | 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... | [
"Returns",
"a",
"dict",
"mapping",
"dtypes",
"to",
"number",
"of",
"variables",
"and",
"scalars",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L630-L657 | [
"def",
"count_variables_by_type",
"(",
"variables",
"=",
"None",
")",
":",
"if",
"variables",
"is",
"None",
":",
"variables",
"=",
"tf",
".",
"global_variables",
"(",
")",
"+",
"tf",
".",
"local_variables",
"(",
")",
"unique_types",
"=",
"set",
"(",
"v",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | reuse_variables | 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... | sonnet/python/modules/util.py | 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
... | 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
... | [
"Wraps",
"an",
"arbitrary",
"method",
"so",
"it",
"does",
"variable",
"sharing",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L660-L878 | [
"def",
"reuse_variables",
"(",
"method",
")",
":",
"initialized_variable_scopes_eager",
"=",
"set",
"(",
")",
"initialized_variable_scopes_graph",
"=",
"weakref",
".",
"WeakKeyDictionary",
"(",
")",
"# Ensure that the argument passed in is really a method by checking that the",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | name_for_callable | Returns a module name for a callable or `None` if no name can be found. | sonnet/python/modules/util.py | 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... | 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",
"module",
"name",
"for",
"a",
"callable",
"or",
"None",
"if",
"no",
"name",
"can",
"be",
"found",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L881-L894 | [
"def",
"name_for_callable",
"(",
"func",
")",
":",
"if",
"isinstance",
"(",
"func",
",",
"functools",
".",
"partial",
")",
":",
"return",
"name_for_callable",
"(",
"func",
".",
"func",
")",
"try",
":",
"name",
"=",
"func",
".",
"__name__",
"except",
"Att... | 00612ca3178964d86b556e062694d808ff81fcca |
train | to_snake_case | Returns a CamelCase string as a snake_case string. | sonnet/python/modules/util.py | 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])", ... | 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])", ... | [
"Returns",
"a",
"CamelCase",
"string",
"as",
"a",
"snake_case",
"string",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L897-L909 | [
"def",
"to_snake_case",
"(",
"camel_case",
")",
":",
"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 undersco... | 00612ca3178964d86b556e062694d808ff81fcca |
train | notify_about_new_variables | 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... | sonnet/python/modules/util.py | 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 = []
... | 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 = []
... | [
"Calls",
"callback",
"(",
"var",
")",
"for",
"all",
"newly",
"created",
"variables",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L941-L966 | [
"def",
"notify_about_new_variables",
"(",
"callback",
")",
":",
"def",
"_tracking_creator",
"(",
"getter",
",",
"*",
"*",
"kwargs",
")",
":",
"v",
"=",
"getter",
"(",
"*",
"*",
"kwargs",
")",
"callback",
"(",
"v",
")",
"return",
"v",
"with",
"tf",
".",... | 00612ca3178964d86b556e062694d808ff81fcca |
train | _recursive_getattr | Recursively gets attributes inside `module` as specified by `path`. | sonnet/python/modules/util.py | 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) | 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) | [
"Recursively",
"gets",
"attributes",
"inside",
"module",
"as",
"specified",
"by",
"path",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L975-L981 | [
"def",
"_recursive_getattr",
"(",
"module",
",",
"path",
")",
":",
"if",
"\".\"",
"not",
"in",
"path",
":",
"return",
"getattr",
"(",
"module",
",",
"path",
")",
"else",
":",
"first",
",",
"rest",
"=",
"path",
".",
"split",
"(",
"\".\"",
",",
"1",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | parse_string_to_constructor | 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... | sonnet/python/modules/util.py | 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... | 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... | [
"Returns",
"a",
"callable",
"which",
"corresponds",
"to",
"the",
"constructor",
"string",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L984-L1024 | [
"def",
"parse_string_to_constructor",
"(",
"ctor_string",
")",
":",
"orig_ctor_string",
"=",
"ctor_string",
"if",
"\".\"",
"not",
"in",
"ctor_string",
":",
"# No module specified - assume part of Sonnet",
"ctor_string",
"=",
"\"sonnet.\"",
"+",
"ctor_string",
"if",
"ctor_... | 00612ca3178964d86b556e062694d808ff81fcca |
train | supports_kwargs | 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... | sonnet/python/modules/util.py | 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 ... | 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 ... | [
"Determines",
"whether",
"the",
"provided",
"callable",
"supports",
"all",
"the",
"kwargs",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L1039-L1099 | [
"def",
"supports_kwargs",
"(",
"module_or_fn",
",",
"kwargs_list",
")",
":",
"if",
"isinstance",
"(",
"kwargs_list",
",",
"six",
".",
"string_types",
")",
":",
"kwargs_list",
"=",
"[",
"kwargs_list",
"]",
"# If it's not a function or method, then assume it's a module, s... | 00612ca3178964d86b556e062694d808ff81fcca |
train | remove_unsupported_kwargs | 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... | sonnet/python/modules/util.py | 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... | 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... | [
"Removes",
"any",
"kwargs",
"not",
"supported",
"by",
"module_or_fn",
"from",
"all_kwargs_dict",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L1102-L1137 | [
"def",
"remove_unsupported_kwargs",
"(",
"module_or_fn",
",",
"all_kwargs_dict",
")",
":",
"if",
"all_kwargs_dict",
"is",
"None",
":",
"all_kwargs_dict",
"=",
"{",
"}",
"if",
"not",
"isinstance",
"(",
"all_kwargs_dict",
",",
"dict",
")",
":",
"raise",
"ValueErro... | 00612ca3178964d86b556e062694d808ff81fcca |
train | merge_leading_dims | 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... | sonnet/python/modules/basic.py | 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... | 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... | [
"Merge",
"the",
"first",
"dimensions",
"of",
"a",
"tensor",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L38-L89 | [
"def",
"merge_leading_dims",
"(",
"array_or_tensor",
",",
"n_dims",
"=",
"2",
")",
":",
"tensor",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"array_or_tensor",
")",
"tensor_shape_static",
"=",
"tensor",
".",
"get_shape",
"(",
")",
"# Check if the rank of the input te... | 00612ca3178964d86b556e062694d808ff81fcca |
train | split_leading_dim | 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. | sonnet/python/modules/basic.py | 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... | 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... | [
"Split",
"the",
"first",
"dimension",
"of",
"a",
"tensor",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L92-L120 | [
"def",
"split_leading_dim",
"(",
"tensor",
",",
"inputs",
",",
"n_dims",
"=",
"2",
")",
":",
"input_shape_static",
"=",
"inputs",
".",
"get_shape",
"(",
")",
"input_shape_list",
"=",
"input_shape_static",
".",
"as_list",
"(",
")",
"tensor_shape_static",
"=",
"... | 00612ca3178964d86b556e062694d808ff81fcca |
train | create_linear_initializer | Returns a default initializer for weights of a linear module. | sonnet/python/modules/basic.py | 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) | 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) | [
"Returns",
"a",
"default",
"initializer",
"for",
"weights",
"of",
"a",
"linear",
"module",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L123-L126 | [
"def",
"create_linear_initializer",
"(",
"input_size",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
":",
"stddev",
"=",
"1",
"/",
"math",
".",
"sqrt",
"(",
"input_size",
")",
"return",
"tf",
".",
"truncated_normal_initializer",
"(",
"stddev",
"=",
"stddev",... | 00612ca3178964d86b556e062694d808ff81fcca |
train | calculate_bias_shape | 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.
... | sonnet/python/modules/basic.py | 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... | 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... | [
"Calculate",
"bias_shape",
"based",
"on",
"the",
"input_shape",
"and",
"bias_dims",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L464-L502 | [
"def",
"calculate_bias_shape",
"(",
"input_shape",
",",
"bias_dims",
")",
":",
"input_rank",
"=",
"len",
"(",
"input_shape",
")",
"# If None, default is to use all dimensions.",
"if",
"bias_dims",
"is",
"None",
":",
"return",
"input_shape",
"[",
"1",
":",
"]",
"# ... | 00612ca3178964d86b556e062694d808ff81fcca |
train | Linear._build | 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... | sonnet/python/modules/basic.py | 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... | 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... | [
"Connects",
"the",
"Linear",
"module",
"into",
"the",
"graph",
"with",
"input",
"Tensor",
"inputs",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L197-L265 | [
"def",
"_build",
"(",
"self",
",",
"inputs",
")",
":",
"input_shape",
"=",
"tuple",
"(",
"inputs",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
")",
"if",
"len",
"(",
"input_shape",
")",
"!=",
"2",
":",
"raise",
"base",
".",
"IncompatibleSha... | 00612ca3178964d86b556e062694d808ff81fcca |
train | Linear.output_size | Returns the module output size. | sonnet/python/modules/basic.py | def output_size(self):
"""Returns the module output size."""
if callable(self._output_size):
self._output_size = self._output_size()
return self._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",
"the",
"module",
"output",
"size",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L300-L304 | [
"def",
"output_size",
"(",
"self",
")",
":",
"if",
"callable",
"(",
"self",
".",
"_output_size",
")",
":",
"self",
".",
"_output_size",
"=",
"self",
".",
"_output_size",
"(",
")",
"return",
"self",
".",
"_output_size"
] | 00612ca3178964d86b556e062694d808ff81fcca |
train | Linear.clone | 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. | sonnet/python/modules/basic.py | 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... | 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... | [
"Returns",
"a",
"cloned",
"Linear",
"module",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L326-L343 | [
"def",
"clone",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"self",
".",
"module_name",
"+",
"\"_clone\"",
"return",
"Linear",
"(",
"output_size",
"=",
"self",
".",
"output_size",
",",
"use_bias",
"=",... | 00612ca3178964d86b556e062694d808ff81fcca |
train | ConcatLinear._build | 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... | sonnet/python/modules/basic.py | 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... | 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",
"module",
"into",
"the",
"graph",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L436-L461 | [
"def",
"_build",
"(",
"self",
",",
"inputs_list",
")",
":",
"outputs",
"=",
"[",
"]",
"for",
"idx",
",",
"tensor",
"in",
"enumerate",
"(",
"inputs_list",
")",
":",
"outputs",
".",
"append",
"(",
"Linear",
"(",
"self",
".",
"_output_size",
",",
"initial... | 00612ca3178964d86b556e062694d808ff81fcca |
train | AddBias._build | 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... | sonnet/python/modules/basic.py | 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... | 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... | [
"Connects",
"the",
"Add",
"module",
"into",
"the",
"graph",
"with",
"input",
"Tensor",
"inputs",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L603-L672 | [
"def",
"_build",
"(",
"self",
",",
"inputs",
",",
"multiplier",
"=",
"1",
")",
":",
"input_shape",
"=",
"tuple",
"(",
"inputs",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
")",
"bias_shape",
"=",
"calculate_bias_shape",
"(",
"input_shape",
",",... | 00612ca3178964d86b556e062694d808ff81fcca |
train | AddBias.transpose | 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. | sonnet/python/modules/basic.py | 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:... | 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:... | [
"Returns",
"transposed",
"AddBias",
"module",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L696-L713 | [
"def",
"transpose",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"self",
".",
"module_name",
"+",
"\"_transpose\"",
"return",
"AddBias",
"(",
"output_shape",
"=",
"lambda",
":",
"self",
".",
"_input_shape... | 00612ca3178964d86b556e062694d808ff81fcca |
train | BatchReshape._infer_shape | 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. | sonnet/python/modules/basic.py | 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 ... | 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 ... | [
"Replaces",
"the",
"-",
"1",
"wildcard",
"in",
"the",
"output",
"shape",
"vector",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L759-L777 | [
"def",
"_infer_shape",
"(",
"self",
",",
"dimensions",
")",
":",
"# Size of input",
"n",
"=",
"np",
".",
"prod",
"(",
"dimensions",
")",
"# Size of output where defined",
"m",
"=",
"np",
".",
"prod",
"(",
"abs",
"(",
"np",
".",
"array",
"(",
"self",
".",... | 00612ca3178964d86b556e062694d808ff81fcca |
train | BatchReshape._build | 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, ... | sonnet/python/modules/basic.py | 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,
... | 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,
... | [
"Connects",
"the",
"module",
"into",
"the",
"graph",
"with",
"input",
"Tensor",
"inputs",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L779-L860 | [
"def",
"_build",
"(",
"self",
",",
"inputs",
")",
":",
"full_input_shape",
"=",
"inputs",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"if",
"len",
"(",
"full_input_shape",
")",
"<",
"self",
".",
"_preserve_dims",
":",
"raise",
"ValueError",
"("... | 00612ca3178964d86b556e062694d808ff81fcca |
train | BatchReshape.transpose | Returns transpose batch reshape. | sonnet/python/modules/basic.py | 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) | 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) | [
"Returns",
"transpose",
"batch",
"reshape",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L868-L874 | [
"def",
"transpose",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"self",
".",
"module_name",
"+",
"\"_transpose\"",
"return",
"BatchReshape",
"(",
"shape",
"=",
"lambda",
":",
"self",
".",
"input_shape",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | TrainableVariable._build | Connects the TrainableTensor module into the graph.
Returns:
A Tensor of shape as determined in the constructor. | sonnet/python/modules/basic.py | 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... | 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",
"TrainableTensor",
"module",
"into",
"the",
"graph",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L983-L999 | [
"def",
"_build",
"(",
"self",
")",
":",
"if",
"\"w\"",
"not",
"in",
"self",
".",
"_initializers",
":",
"stddev",
"=",
"1",
"/",
"math",
".",
"sqrt",
"(",
"np",
".",
"prod",
"(",
"self",
".",
"_shape",
")",
")",
"self",
".",
"_initializers",
"[",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | BatchApply._build | 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... | sonnet/python/modules/basic.py | 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... | 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",
"BatchApply",
"module",
"into",
"the",
"graph",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L1063-L1100 | [
"def",
"_build",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"flattened",
"=",
"nest",
".",
"flatten",
"(",
"[",
"args",
",",
"kwargs",
"]",
")",
"merged_flattened",
"=",
"[",
"merge_leading_dims",
"(",
"inp",
",",
"self",
".",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | SliceByDim._build | 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. | sonnet/python/modules/basic.py | 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... | 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",
"SliceByDim",
"module",
"into",
"the",
"graph",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L1167-L1197 | [
"def",
"_build",
"(",
"self",
",",
"inputs",
")",
":",
"shape_inputs",
"=",
"inputs",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"rank",
"=",
"len",
"(",
"shape_inputs",
")",
"# Checks that the rank of the tensor.",
"max_dim",
"=",
"np",
".",
"m... | 00612ca3178964d86b556e062694d808ff81fcca |
train | TileByDim._build | Connects the `TileByDim` module into the graph.
Args:
inputs: `Tensor` to tile.
Returns:
The tiled tensor. | sonnet/python/modules/basic.py | 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_... | 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",
"TileByDim",
"module",
"into",
"the",
"graph",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L1252-L1271 | [
"def",
"_build",
"(",
"self",
",",
"inputs",
")",
":",
"shape_inputs",
"=",
"inputs",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"rank",
"=",
"len",
"(",
"shape_inputs",
")",
"# Builds default lists for multiples to pass to `tf.tile`.",
"full_multiples"... | 00612ca3178964d86b556e062694d808ff81fcca |
train | MergeDims._build | 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... | sonnet/python/modules/basic.py | 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... | 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... | [
"Connects",
"the",
"MergeDims",
"module",
"into",
"the",
"graph",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L1354-L1372 | [
"def",
"_build",
"(",
"self",
",",
"inputs",
")",
":",
"if",
"nest",
".",
"is_sequence",
"(",
"inputs",
")",
":",
"merged_tensors",
"=",
"[",
"self",
".",
"_merge",
"(",
"tensor",
")",
"for",
"tensor",
"in",
"nest",
".",
"flatten",
"(",
"inputs",
")"... | 00612ca3178964d86b556e062694d808ff81fcca |
train | RelationalMemory.initial_state | 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... | sonnet/python/modules/relational_memory.py | 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... | 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... | [
"Creates",
"the",
"initial",
"memory",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/relational_memory.py#L92-L118 | [
"def",
"initial_state",
"(",
"self",
",",
"batch_size",
",",
"trainable",
"=",
"False",
")",
":",
"init_state",
"=",
"tf",
".",
"eye",
"(",
"self",
".",
"_mem_slots",
",",
"batch_shape",
"=",
"[",
"batch_size",
"]",
")",
"# Pad the matrix with zeros.",
"if",... | 00612ca3178964d86b556e062694d808ff81fcca |
train | RelationalMemory._multihead_attention | 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. | sonnet/python/modules/relational_memory.py | 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.
"... | 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.
"... | [
"Perform",
"multi",
"-",
"head",
"attention",
"from",
"Attention",
"is",
"All",
"You",
"Need",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/relational_memory.py#L120-L161 | [
"def",
"_multihead_attention",
"(",
"self",
",",
"memory",
")",
":",
"key_size",
"=",
"self",
".",
"_key_size",
"value_size",
"=",
"self",
".",
"_head_size",
"qkv_size",
"=",
"2",
"*",
"key_size",
"+",
"value_size",
"total_size",
"=",
"qkv_size",
"*",
"self"... | 00612ca3178964d86b556e062694d808ff81fcca |
train | RelationalMemory._create_gates | 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. | sonnet/python/modules/relational_memory.py | 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... | 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... | [
"Create",
"input",
"and",
"forget",
"gates",
"for",
"this",
"step",
"using",
"inputs",
"and",
"memory",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/relational_memory.py#L184-L210 | [
"def",
"_create_gates",
"(",
"self",
",",
"inputs",
",",
"memory",
")",
":",
"# We'll create the input and forget gates at once. Hence, calculate double",
"# the gate size.",
"num_gates",
"=",
"2",
"*",
"self",
".",
"_calculate_gate_size",
"(",
")",
"memory",
"=",
"tf",... | 00612ca3178964d86b556e062694d808ff81fcca |
train | RelationalMemory._attend_over_memory | Perform multiheaded attention over `memory`.
Args:
memory: Current relational memory.
Returns:
The attended-over memory. | sonnet/python/modules/relational_memory.py | 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... | 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... | [
"Perform",
"multiheaded",
"attention",
"over",
"memory",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/relational_memory.py#L212-L234 | [
"def",
"_attend_over_memory",
"(",
"self",
",",
"memory",
")",
":",
"attention_mlp",
"=",
"basic",
".",
"BatchApply",
"(",
"mlp",
".",
"MLP",
"(",
"[",
"self",
".",
"_mem_size",
"]",
"*",
"self",
".",
"_attention_mlp_layers",
")",
")",
"for",
"_",
"in",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | RelationalMemory._build | 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... | sonnet/python/modules/relational_memory.py | 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... | 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... | [
"Adds",
"relational",
"memory",
"to",
"the",
"TensorFlow",
"graph",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/relational_memory.py#L236-L272 | [
"def",
"_build",
"(",
"self",
",",
"inputs",
",",
"memory",
",",
"treat_input_as_matrix",
"=",
"False",
")",
":",
"if",
"treat_input_as_matrix",
":",
"inputs",
"=",
"basic",
".",
"BatchFlatten",
"(",
"preserve_dims",
"=",
"2",
")",
"(",
"inputs",
")",
"inp... | 00612ca3178964d86b556e062694d808ff81fcca |
train | train_and_eval | Creates a basic MNIST model using Sonnet, then trains and evaluates it. | sonnet/examples/mnist_mlp.py | 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 =... | 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 =... | [
"Creates",
"a",
"basic",
"MNIST",
"model",
"using",
"Sonnet",
"then",
"trains",
"and",
"evaluates",
"it",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/mnist_mlp.py#L43-L96 | [
"def",
"train_and_eval",
"(",
"train_batch_size",
",",
"test_batch_size",
",",
"num_hidden",
",",
"learning_rate",
",",
"num_train_steps",
",",
"report_every",
",",
"test_every",
")",
":",
"data_dict",
"=",
"dataset_mnist",
".",
"get_data",
"(",
"\"mnist\"",
",",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | _single_learnable_state | 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... | sonnet/python/modules/rnn_core.py | 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:
... | 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:
... | [
"Returns",
"an",
"initial",
"(",
"maybe",
"learnable",
")",
"state",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/rnn_core.py#L44-L89 | [
"def",
"_single_learnable_state",
"(",
"state",
",",
"state_id",
"=",
"0",
",",
"learnable",
"=",
"True",
")",
":",
"unpacked_state",
"=",
"tf",
".",
"unstack",
"(",
"state",
")",
"# Assert that all rows have the same values.",
"assert_rows_equal",
"=",
"[",
"tf",... | 00612ca3178964d86b556e062694d808ff81fcca |
train | trainable_initial_state | 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... | sonnet/python/modules/rnn_core.py | 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... | 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... | [
"Creates",
"an",
"initial",
"state",
"consisting",
"of",
"trainable",
"variables",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/rnn_core.py#L92-L167 | [
"def",
"trainable_initial_state",
"(",
"batch_size",
",",
"state_size",
",",
"dtype",
",",
"initializers",
"=",
"None",
",",
"regularizers",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"flat_state_size",
"=",
"nest",
".",
"flatten",
"(",
"state_size",
"... | 00612ca3178964d86b556e062694d808ff81fcca |
train | with_doc | 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... | sonnet/python/modules/rnn_core.py | 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... | 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... | [
"Returns",
"a",
"decorator",
"to",
"copy",
"documentation",
"from",
"the",
"given",
"function",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/rnn_core.py#L385-L407 | [
"def",
"with_doc",
"(",
"fn_with_doc_to_copy",
")",
":",
"def",
"decorator",
"(",
"wrapper_init",
")",
":",
"# Wrap the target class's constructor (to assume its docstring),",
"# but invoke the wrapper class's constructor.",
"@",
"wrapt",
".",
"decorator",
"def",
"wrapping_fn",... | 00612ca3178964d86b556e062694d808ff81fcca |
train | TrainableInitialState._build | 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. | sonnet/python/modules/rnn_core.py | 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... | 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",
"module",
"to",
"the",
"graph",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/rnn_core.py#L331-L349 | [
"def",
"_build",
"(",
"self",
")",
":",
"flat_initial_state",
"=",
"nest",
".",
"flatten",
"(",
"self",
".",
"_initial_state",
")",
"if",
"self",
".",
"_mask",
"is",
"not",
"None",
":",
"flat_mask",
"=",
"nest",
".",
"flatten",
"(",
"self",
".",
"_mask... | 00612ca3178964d86b556e062694d808ff81fcca |
train | LayerNorm._build | 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. | sonnet/python/modules/layer_norm.py | 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 ... | 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 ... | [
"Connects",
"the",
"LayerNorm",
"module",
"into",
"the",
"graph",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/layer_norm.py#L115-L179 | [
"def",
"_build",
"(",
"self",
",",
"inputs",
")",
":",
"if",
"self",
".",
"_axis",
"is",
"None",
":",
"axis",
"=",
"list",
"(",
"range",
"(",
"1",
",",
"inputs",
".",
"shape",
".",
"ndims",
")",
")",
"else",
":",
"axis",
"=",
"self",
".",
"_axi... | 00612ca3178964d86b556e062694d808ff81fcca |
train | AttentiveRead._build | 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... | sonnet/python/modules/attention.py | 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... | 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... | [
"Perform",
"a",
"differentiable",
"read",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/attention.py#L60-L183 | [
"def",
"_build",
"(",
"self",
",",
"memory",
",",
"query",
",",
"memory_mask",
"=",
"None",
")",
":",
"if",
"len",
"(",
"memory",
".",
"get_shape",
"(",
")",
")",
"!=",
"3",
":",
"raise",
"base",
".",
"IncompatibleShapeError",
"(",
"\"memory must have sh... | 00612ca3178964d86b556e062694d808ff81fcca |
train | BatchNormV2._build_statistics | 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 ... | sonnet/python/modules/batch_norm_v2.py | 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... | 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",
"statistics",
"part",
"of",
"the",
"graph",
"when",
"using",
"moving",
"variance",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm_v2.py#L217-L285 | [
"def",
"_build_statistics",
"(",
"self",
",",
"input_batch",
",",
"use_batch_stats",
",",
"stat_dtype",
")",
":",
"# Set up our moving statistics. When connecting in parallel, this is shared.",
"if",
"self",
".",
"MOVING_MEAN",
"not",
"in",
"self",
".",
"_initializers",
"... | 00612ca3178964d86b556e062694d808ff81fcca |
train | BatchNormV2._build_update_ops | 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... | sonnet/python/modules/batch_norm_v2.py | 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 ... | 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 ... | [
"Builds",
"the",
"moving",
"average",
"update",
"ops",
"when",
"using",
"moving",
"variance",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm_v2.py#L287-L334 | [
"def",
"_build_update_ops",
"(",
"self",
",",
"mean",
",",
"variance",
",",
"is_training",
")",
":",
"def",
"build_update_ops",
"(",
")",
":",
"\"\"\"Builds the exponential moving average update ops.\"\"\"",
"update_mean_op",
"=",
"moving_averages",
".",
"assign_moving_av... | 00612ca3178964d86b556e062694d808ff81fcca |
train | BatchNormV2._fused_batch_norm_op | Creates a fused batch normalization op. | sonnet/python/modules/batch_norm_v2.py | 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... | 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... | [
"Creates",
"a",
"fused",
"batch",
"normalization",
"op",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm_v2.py#L336-L404 | [
"def",
"_fused_batch_norm_op",
"(",
"self",
",",
"input_batch",
",",
"mean",
",",
"variance",
",",
"use_batch_stats",
")",
":",
"# Store the original shape of the mean and variance.",
"mean_shape",
"=",
"mean",
".",
"get_shape",
"(",
")",
"variance_shape",
"=",
"varia... | 00612ca3178964d86b556e062694d808ff81fcca |
train | BatchNormV2._build | 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... | sonnet/python/modules/batch_norm_v2.py | 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... | 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... | [
"Connects",
"the",
"BatchNormV2",
"module",
"into",
"the",
"graph",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm_v2.py#L496-L583 | [
"def",
"_build",
"(",
"self",
",",
"input_batch",
",",
"is_training",
",",
"test_local_stats",
"=",
"False",
")",
":",
"input_shape",
"=",
"input_batch",
".",
"get_shape",
"(",
")",
"if",
"not",
"self",
".",
"_data_format",
":",
"if",
"len",
"(",
"input_sh... | 00612ca3178964d86b556e062694d808ff81fcca |
train | _range_along_dimension | 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... | sonnet/python/modules/nets/dilation.py | 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()
>>> ... | 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()
>>> ... | [
"Construct",
"a",
"Tensor",
"whose",
"values",
"are",
"the",
"index",
"along",
"a",
"dimension",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/dilation.py#L32-L70 | [
"def",
"_range_along_dimension",
"(",
"range_dim",
",",
"shape",
")",
":",
"rank",
"=",
"len",
"(",
"shape",
")",
"if",
"range_dim",
">=",
"rank",
":",
"raise",
"ValueError",
"(",
"\"Cannot calculate range along non-existent index.\"",
")",
"indices",
"=",
"tf",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | identity_kernel_initializer | 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... | sonnet/python/modules/nets/dilation.py | 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... | 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... | [
"An",
"initializer",
"for",
"constructing",
"identity",
"convolution",
"kernels",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/dilation.py#L74-L118 | [
"def",
"identity_kernel_initializer",
"(",
"shape",
",",
"dtype",
"=",
"tf",
".",
"float32",
",",
"partition_info",
"=",
"None",
")",
":",
"if",
"len",
"(",
"shape",
")",
"!=",
"4",
":",
"raise",
"ValueError",
"(",
"\"Convolution kernels must be rank 4.\"",
")... | 00612ca3178964d86b556e062694d808ff81fcca |
train | noisy_identity_kernel_initializer | 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... | sonnet/python/modules/nets/dilation.py | 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... | 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",
"an",
"initializer",
"for",
"constructing",
"near",
"-",
"identity",
"convolution",
"kernels",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/dilation.py#L121-L194 | [
"def",
"noisy_identity_kernel_initializer",
"(",
"base_num_channels",
",",
"stddev",
"=",
"1e-8",
")",
":",
"# pylint: disable=unused-argument",
"def",
"_noisy_identity_kernel_initializer",
"(",
"shape",
",",
"dtype",
"=",
"tf",
".",
"float32",
",",
"partition_info",
"=... | 00612ca3178964d86b556e062694d808ff81fcca |
train | Dilation._build | 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_... | sonnet/python/modules/nets/dilation.py | 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... | 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... | [
"Build",
"dilation",
"module",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/dilation.py#L257-L319 | [
"def",
"_build",
"(",
"self",
",",
"images",
")",
":",
"num_classes",
"=",
"self",
".",
"_num_output_classes",
"if",
"len",
"(",
"images",
".",
"get_shape",
"(",
")",
")",
"!=",
"4",
":",
"raise",
"base",
".",
"IncompatibleShapeError",
"(",
"\"'images' mus... | 00612ca3178964d86b556e062694d808ff81fcca |
train | Dilation._dilated_conv_layer | 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.
... | sonnet/python/modules/nets/dilation.py | 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... | 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... | [
"Create",
"a",
"dilated",
"convolution",
"layer",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/dilation.py#L321-L345 | [
"def",
"_dilated_conv_layer",
"(",
"self",
",",
"output_channels",
",",
"dilation_rate",
",",
"apply_relu",
",",
"name",
")",
":",
"layer_components",
"=",
"[",
"conv",
".",
"Conv2D",
"(",
"output_channels",
",",
"[",
"3",
",",
"3",
"]",
",",
"initializers",... | 00612ca3178964d86b556e062694d808ff81fcca |
train | with_deprecation_warning | Wraps the function and prints a warn-once (per `extra_message`) warning. | sonnet/python/ops/nest.py | 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... | 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... | [
"Wraps",
"the",
"function",
"and",
"prints",
"a",
"warn",
"-",
"once",
"(",
"per",
"extra_message",
")",
"warning",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/ops/nest.py#L33-L44 | [
"def",
"with_deprecation_warning",
"(",
"fn",
",",
"extra_message",
"=",
"''",
")",
":",
"def",
"new_fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"extra_message",
"not",
"in",
"_DONE_WARN",
":",
"tf",
".",
"logging",
".",
"warning",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | custom_build | A custom build method to wrap into a sonnet Module. | sonnet/examples/module_with_build_args.py | 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=... | 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=... | [
"A",
"custom",
"build",
"method",
"to",
"wrap",
"into",
"a",
"sonnet",
"Module",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/examples/module_with_build_args.py#L41-L52 | [
"def",
"custom_build",
"(",
"inputs",
",",
"is_training",
",",
"keep_prob",
")",
":",
"outputs",
"=",
"snt",
".",
"Conv2D",
"(",
"output_channels",
"=",
"32",
",",
"kernel_shape",
"=",
"4",
",",
"stride",
"=",
"2",
")",
"(",
"inputs",
")",
"outputs",
"... | 00612ca3178964d86b556e062694d808ff81fcca |
train | _get_or_create_stack | Returns a thread local stack uniquified by the given name. | sonnet/python/modules/base.py | 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 | 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 | [
"Returns",
"a",
"thread",
"local",
"stack",
"uniquified",
"by",
"the",
"given",
"name",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/base.py#L60-L66 | [
"def",
"_get_or_create_stack",
"(",
"name",
")",
":",
"stack",
"=",
"getattr",
"(",
"_LOCAL_STACKS",
",",
"name",
",",
"None",
")",
"if",
"stack",
"is",
"None",
":",
"stack",
"=",
"[",
"]",
"setattr",
"(",
"_LOCAL_STACKS",
",",
"name",
",",
"stack",
")... | 00612ca3178964d86b556e062694d808ff81fcca |
train | diagonal_gaussian_posterior_builder | 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... | sonnet/python/custom_getters/bayes_by_backprop.py | 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... | 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",
"diagonal",
"gaussian",
"posterior",
"distributions",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/custom_getters/bayes_by_backprop.py#L148-L183 | [
"def",
"diagonal_gaussian_posterior_builder",
"(",
"getter",
",",
"name",
",",
"shape",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Please see the documentation for",
"# `tfp.distributions.param_static_shapes`.",
"parameter_shapes",
"=",
"tfp",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | fixed_gaussian_prior_builder | 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... | sonnet/python/custom_getters/bayes_by_backprop.py | 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... | 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",
"fixed",
"gaussian",
"prior",
"distributions",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/custom_getters/bayes_by_backprop.py#L188-L214 | [
"def",
"fixed_gaussian_prior_builder",
"(",
"getter",
",",
"name",
",",
"dtype",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"getter",
"# Unused.",
"del",
"args",
"# Unused.",
"del",
"kwargs",
"# Unused.",
"loc",
"=",
"tf",
"... | 00612ca3178964d86b556e062694d808ff81fcca |
train | adaptive_gaussian_prior_builder | 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 ... | sonnet/python/custom_getters/bayes_by_backprop.py | 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... | 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",
"adaptive",
"scalar",
"gaussian",
"prior",
"distributions",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/custom_getters/bayes_by_backprop.py#L218-L247 | [
"def",
"adaptive_gaussian_prior_builder",
"(",
"getter",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"\"shape\"",
"]",
"=",
"(",
")",
"loc_var",
"=",
"getter",
"(",
"name",
"+",
"\"_prior_loc\"",
",",
"*",
"args",
"... | 00612ca3178964d86b556e062694d808ff81fcca |
train | stochastic_kl_builder | A pre-canned builder for a ubiquitous stochastic KL estimator. | sonnet/python/custom_getters/bayes_by_backprop.py | 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))) | 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",
"a",
"ubiquitous",
"stochastic",
"KL",
"estimator",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/custom_getters/bayes_by_backprop.py#L250-L254 | [
"def",
"stochastic_kl_builder",
"(",
"posterior",
",",
"prior",
",",
"sample",
")",
":",
"return",
"tf",
".",
"subtract",
"(",
"tf",
".",
"reduce_sum",
"(",
"posterior",
".",
"log_prob",
"(",
"sample",
")",
")",
",",
"tf",
".",
"reduce_sum",
"(",
"prior"... | 00612ca3178964d86b556e062694d808ff81fcca |
train | analytic_kl_builder | A pre-canned builder for the analytic kl divergence. | sonnet/python/custom_getters/bayes_by_backprop.py | 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)) | 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)) | [
"A",
"pre",
"-",
"canned",
"builder",
"for",
"the",
"analytic",
"kl",
"divergence",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/custom_getters/bayes_by_backprop.py#L257-L260 | [
"def",
"analytic_kl_builder",
"(",
"posterior",
",",
"prior",
",",
"sample",
")",
":",
"del",
"sample",
"return",
"tf",
".",
"reduce_sum",
"(",
"tfp",
".",
"distributions",
".",
"kl_divergence",
"(",
"posterior",
",",
"prior",
")",
")"
] | 00612ca3178964d86b556e062694d808ff81fcca |
train | bayes_by_backprop_getter | 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... | sonnet/python/custom_getters/bayes_by_backprop.py | 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... | 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... | [
"Creates",
"a",
"custom",
"getter",
"which",
"does",
"Bayes",
"by",
"Backprop",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/custom_getters/bayes_by_backprop.py#L263-L452 | [
"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_c... | 00612ca3178964d86b556e062694d808ff81fcca |
train | _produce_posterior_estimate | 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 ... | sonnet/python/custom_getters/bayes_by_backprop.py | 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... | 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... | [
"Create",
"tensor",
"representing",
"estimate",
"of",
"posterior",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/custom_getters/bayes_by_backprop.py#L455-L505 | [
"def",
"_produce_posterior_estimate",
"(",
"posterior_dist",
",",
"posterior_estimate_mode",
",",
"raw_var_name",
")",
":",
"conds",
"=",
"[",
"tf",
".",
"equal",
"(",
"posterior_estimate_mode",
",",
"tf",
".",
"constant",
"(",
"EstimatorModes",
".",
"sample",
")"... | 00612ca3178964d86b556e062694d808ff81fcca |
train | get_total_kl_cost | 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 ... | sonnet/python/custom_getters/bayes_by_backprop.py | 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... | 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... | [
"Get",
"the",
"total",
"cost",
"for",
"all",
"(",
"or",
"a",
"subset",
"of",
")",
"the",
"stochastic",
"variables",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/custom_getters/bayes_by_backprop.py#L508-L527 | [
"def",
"get_total_kl_cost",
"(",
"name",
"=",
"\"total_kl_cost\"",
",",
"filter_by_name_substring",
"=",
"None",
")",
":",
"all_variable_metadata",
"=",
"get_variable_metadata",
"(",
"filter_by_name_substring",
")",
"if",
"not",
"all_variable_metadata",
":",
"tf",
".",
... | 00612ca3178964d86b556e062694d808ff81fcca |
train | BlockTriangularMatrix.output_shape | The shape of the output matrix. | sonnet/python/modules/block_matrix.py | 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) | 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) | [
"The",
"shape",
"of",
"the",
"output",
"matrix",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/block_matrix.py#L106-L109 | [
"def",
"output_shape",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_block_shape",
"[",
"0",
"]",
"*",
"self",
".",
"_block_rows",
",",
"self",
".",
"_block_shape",
"[",
"1",
"]",
"*",
"self",
".",
"_block_rows",
")"
] | 00612ca3178964d86b556e062694d808ff81fcca |
train | BlockTriangularMatrix._left_zero_blocks | Number of blocks with zeros from the left in block row `r`. | sonnet/python/modules/block_matrix.py | 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 | 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",
"left",
"in",
"block",
"row",
"r",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/block_matrix.py#L160-L169 | [
"def",
"_left_zero_blocks",
"(",
"self",
",",
"r",
")",
":",
"if",
"not",
"self",
".",
"_include_off_diagonal",
":",
"return",
"r",
"elif",
"not",
"self",
".",
"_upper",
":",
"return",
"0",
"elif",
"self",
".",
"_include_diagonal",
":",
"return",
"r",
"e... | 00612ca3178964d86b556e062694d808ff81fcca |
train | BlockTriangularMatrix._right_zero_blocks | Number of blocks with zeros from the right in block row `r`. | sonnet/python/modules/block_matrix.py | 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... | 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",
"blocks",
"with",
"zeros",
"from",
"the",
"right",
"in",
"block",
"row",
"r",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/block_matrix.py#L171-L180 | [
"def",
"_right_zero_blocks",
"(",
"self",
",",
"r",
")",
":",
"if",
"not",
"self",
".",
"_include_off_diagonal",
":",
"return",
"self",
".",
"_block_rows",
"-",
"r",
"-",
"1",
"elif",
"self",
".",
"_upper",
":",
"return",
"0",
"elif",
"self",
".",
"_in... | 00612ca3178964d86b556e062694d808ff81fcca |
train | BlockTriangularMatrix._content_blocks | Number of content blocks in block row `r`. | sonnet/python/modules/block_matrix.py | 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)) | 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)) | [
"Number",
"of",
"content",
"blocks",
"in",
"block",
"row",
"r",
"."
] | deepmind/sonnet | python | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/block_matrix.py#L182-L185 | [
"def",
"_content_blocks",
"(",
"self",
",",
"r",
")",
":",
"return",
"(",
"self",
".",
"_block_rows",
"-",
"self",
".",
"_left_zero_blocks",
"(",
"r",
")",
"-",
"self",
".",
"_right_zero_blocks",
"(",
"r",
")",
")"
] | 00612ca3178964d86b556e062694d808ff81fcca |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.