id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
227,800 | tensorflow/mesh | mesh_tensorflow/transformer/transformer_layers.py | attention_params | def attention_params(context,
kv_dim,
num_heads,
num_memory_heads=0,
shared_kv=False):
"""Attention Parameters for Transformer Layers.
The num_heads argument indicates the number of read-heads.
For the familiar behavior described in "Attention Is All You Need", set
num_memory_heads=0.
If num_memory_heads==1, then there is only a single write-head, and multiple
read-heads. This leads to faster incremental decoding, since the
recurrent state is smaller
If num_memory_heads > 1, then num_memory_heads indicates the number of
write-heads. A fraction of the read-heads read each write-head.
num_memory_heads must divide num_heads. This behavior has not yet been tested.
Args:
context: a transformer.Context
kv_dim: a dimension (for key and value channels)
num_heads: an integer
num_memory_heads: an optional integer
shared_kv: a boolean
Returns:
an attention.AttentionParams object
"""
if num_heads == 1:
query_heads_dims = None
memory_heads_dims = None
elif num_memory_heads == 0:
query_heads_dims = [mtf.Dimension("heads", num_heads)]
memory_heads_dims = query_heads_dims
elif num_memory_heads == 1:
query_heads_dims = [mtf.Dimension("heads", num_heads)]
memory_heads_dims = None
else:
if num_heads % num_memory_heads != 0:
raise ValueError("num_memory_heads must divide num_heads")
memory_heads_dims = [mtf.Dimension("heads", num_memory_heads)]
query_heads_dims = memory_heads_dims + [
mtf.Dimension("query_heads", num_heads // num_memory_heads)]
return attention.AttentionParams(
context.mesh,
query_input_dim=context.model_dim,
memory_input_dim=context.model_dim,
output_dim=context.model_dim,
key_dim=kv_dim,
value_dim=kv_dim,
query_heads_dims=query_heads_dims,
memory_heads_dims=memory_heads_dims,
variable_dtype=context.variable_dtype,
shared_kv=shared_kv) | python | def attention_params(context,
kv_dim,
num_heads,
num_memory_heads=0,
shared_kv=False):
"""Attention Parameters for Transformer Layers.
The num_heads argument indicates the number of read-heads.
For the familiar behavior described in "Attention Is All You Need", set
num_memory_heads=0.
If num_memory_heads==1, then there is only a single write-head, and multiple
read-heads. This leads to faster incremental decoding, since the
recurrent state is smaller
If num_memory_heads > 1, then num_memory_heads indicates the number of
write-heads. A fraction of the read-heads read each write-head.
num_memory_heads must divide num_heads. This behavior has not yet been tested.
Args:
context: a transformer.Context
kv_dim: a dimension (for key and value channels)
num_heads: an integer
num_memory_heads: an optional integer
shared_kv: a boolean
Returns:
an attention.AttentionParams object
"""
if num_heads == 1:
query_heads_dims = None
memory_heads_dims = None
elif num_memory_heads == 0:
query_heads_dims = [mtf.Dimension("heads", num_heads)]
memory_heads_dims = query_heads_dims
elif num_memory_heads == 1:
query_heads_dims = [mtf.Dimension("heads", num_heads)]
memory_heads_dims = None
else:
if num_heads % num_memory_heads != 0:
raise ValueError("num_memory_heads must divide num_heads")
memory_heads_dims = [mtf.Dimension("heads", num_memory_heads)]
query_heads_dims = memory_heads_dims + [
mtf.Dimension("query_heads", num_heads // num_memory_heads)]
return attention.AttentionParams(
context.mesh,
query_input_dim=context.model_dim,
memory_input_dim=context.model_dim,
output_dim=context.model_dim,
key_dim=kv_dim,
value_dim=kv_dim,
query_heads_dims=query_heads_dims,
memory_heads_dims=memory_heads_dims,
variable_dtype=context.variable_dtype,
shared_kv=shared_kv) | [
"def",
"attention_params",
"(",
"context",
",",
"kv_dim",
",",
"num_heads",
",",
"num_memory_heads",
"=",
"0",
",",
"shared_kv",
"=",
"False",
")",
":",
"if",
"num_heads",
"==",
"1",
":",
"query_heads_dims",
"=",
"None",
"memory_heads_dims",
"=",
"None",
"elif",
"num_memory_heads",
"==",
"0",
":",
"query_heads_dims",
"=",
"[",
"mtf",
".",
"Dimension",
"(",
"\"heads\"",
",",
"num_heads",
")",
"]",
"memory_heads_dims",
"=",
"query_heads_dims",
"elif",
"num_memory_heads",
"==",
"1",
":",
"query_heads_dims",
"=",
"[",
"mtf",
".",
"Dimension",
"(",
"\"heads\"",
",",
"num_heads",
")",
"]",
"memory_heads_dims",
"=",
"None",
"else",
":",
"if",
"num_heads",
"%",
"num_memory_heads",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"\"num_memory_heads must divide num_heads\"",
")",
"memory_heads_dims",
"=",
"[",
"mtf",
".",
"Dimension",
"(",
"\"heads\"",
",",
"num_memory_heads",
")",
"]",
"query_heads_dims",
"=",
"memory_heads_dims",
"+",
"[",
"mtf",
".",
"Dimension",
"(",
"\"query_heads\"",
",",
"num_heads",
"//",
"num_memory_heads",
")",
"]",
"return",
"attention",
".",
"AttentionParams",
"(",
"context",
".",
"mesh",
",",
"query_input_dim",
"=",
"context",
".",
"model_dim",
",",
"memory_input_dim",
"=",
"context",
".",
"model_dim",
",",
"output_dim",
"=",
"context",
".",
"model_dim",
",",
"key_dim",
"=",
"kv_dim",
",",
"value_dim",
"=",
"kv_dim",
",",
"query_heads_dims",
"=",
"query_heads_dims",
",",
"memory_heads_dims",
"=",
"memory_heads_dims",
",",
"variable_dtype",
"=",
"context",
".",
"variable_dtype",
",",
"shared_kv",
"=",
"shared_kv",
")"
] | Attention Parameters for Transformer Layers.
The num_heads argument indicates the number of read-heads.
For the familiar behavior described in "Attention Is All You Need", set
num_memory_heads=0.
If num_memory_heads==1, then there is only a single write-head, and multiple
read-heads. This leads to faster incremental decoding, since the
recurrent state is smaller
If num_memory_heads > 1, then num_memory_heads indicates the number of
write-heads. A fraction of the read-heads read each write-head.
num_memory_heads must divide num_heads. This behavior has not yet been tested.
Args:
context: a transformer.Context
kv_dim: a dimension (for key and value channels)
num_heads: an integer
num_memory_heads: an optional integer
shared_kv: a boolean
Returns:
an attention.AttentionParams object | [
"Attention",
"Parameters",
"for",
"Transformer",
"Layers",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/transformer_layers.py#L62-L116 |
227,801 | tensorflow/mesh | mesh_tensorflow/transformer/metric_utils.py | get_metric_fns | def get_metric_fns(metric_names, labels, outputs):
"""Generate a dictionary of metric name to metric function.
Args:
metric_names: list of strings in the format "prefix/metric_function_name".
metric_function_name should refer to a function name in metrics.py. The
prefix will be included in the key in the returned dict.
labels: a tensor where batch is the first dimension.
outputs: a tensor of model predictions, same dimensionality as labels.
Returns:
metric_fns: dict of metric functions keyed by their name.
"""
metric_fns = {}
for metric_name in metric_names:
metric_fn_name = metric_name.split("/")[-1]
if hasattr(metrics, metric_fn_name):
metric_fn = getattr(metrics, metric_fn_name)
metric_fns[metric_name] = metric_fn(labels, outputs)
else:
raise ValueError("Metric {} is not implemented".format(metric_fn_name))
return metric_fns | python | def get_metric_fns(metric_names, labels, outputs):
"""Generate a dictionary of metric name to metric function.
Args:
metric_names: list of strings in the format "prefix/metric_function_name".
metric_function_name should refer to a function name in metrics.py. The
prefix will be included in the key in the returned dict.
labels: a tensor where batch is the first dimension.
outputs: a tensor of model predictions, same dimensionality as labels.
Returns:
metric_fns: dict of metric functions keyed by their name.
"""
metric_fns = {}
for metric_name in metric_names:
metric_fn_name = metric_name.split("/")[-1]
if hasattr(metrics, metric_fn_name):
metric_fn = getattr(metrics, metric_fn_name)
metric_fns[metric_name] = metric_fn(labels, outputs)
else:
raise ValueError("Metric {} is not implemented".format(metric_fn_name))
return metric_fns | [
"def",
"get_metric_fns",
"(",
"metric_names",
",",
"labels",
",",
"outputs",
")",
":",
"metric_fns",
"=",
"{",
"}",
"for",
"metric_name",
"in",
"metric_names",
":",
"metric_fn_name",
"=",
"metric_name",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
"if",
"hasattr",
"(",
"metrics",
",",
"metric_fn_name",
")",
":",
"metric_fn",
"=",
"getattr",
"(",
"metrics",
",",
"metric_fn_name",
")",
"metric_fns",
"[",
"metric_name",
"]",
"=",
"metric_fn",
"(",
"labels",
",",
"outputs",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Metric {} is not implemented\"",
".",
"format",
"(",
"metric_fn_name",
")",
")",
"return",
"metric_fns"
] | Generate a dictionary of metric name to metric function.
Args:
metric_names: list of strings in the format "prefix/metric_function_name".
metric_function_name should refer to a function name in metrics.py. The
prefix will be included in the key in the returned dict.
labels: a tensor where batch is the first dimension.
outputs: a tensor of model predictions, same dimensionality as labels.
Returns:
metric_fns: dict of metric functions keyed by their name. | [
"Generate",
"a",
"dictionary",
"of",
"metric",
"name",
"to",
"metric",
"function",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/metric_utils.py#L28-L50 |
227,802 | tensorflow/mesh | mesh_tensorflow/auto_mtf/scheduler.py | minimize_peak_memory | def minimize_peak_memory(graph, scheduler_alg):
"""Computes a schedule to minimize peak memory.
Args:
graph: an mtf.auto_mtf.graph_interface.GraphInterface.
scheduler_alg: a string, one of 'NAIVE' or 'LIST'
Returns:
an iterable of integers representing the schedule.
"""
if scheduler_alg == 'NAIVE':
return _minimize_peak_memory_naive(graph)
elif scheduler_alg == 'LIST':
return _minimize_peak_memory_list(graph)
else:
raise NotImplementedError('{} is not a scheduler algorithm. It should be '
'one of NAIVE or LIST.'
.format(scheduler_alg)) | python | def minimize_peak_memory(graph, scheduler_alg):
"""Computes a schedule to minimize peak memory.
Args:
graph: an mtf.auto_mtf.graph_interface.GraphInterface.
scheduler_alg: a string, one of 'NAIVE' or 'LIST'
Returns:
an iterable of integers representing the schedule.
"""
if scheduler_alg == 'NAIVE':
return _minimize_peak_memory_naive(graph)
elif scheduler_alg == 'LIST':
return _minimize_peak_memory_list(graph)
else:
raise NotImplementedError('{} is not a scheduler algorithm. It should be '
'one of NAIVE or LIST.'
.format(scheduler_alg)) | [
"def",
"minimize_peak_memory",
"(",
"graph",
",",
"scheduler_alg",
")",
":",
"if",
"scheduler_alg",
"==",
"'NAIVE'",
":",
"return",
"_minimize_peak_memory_naive",
"(",
"graph",
")",
"elif",
"scheduler_alg",
"==",
"'LIST'",
":",
"return",
"_minimize_peak_memory_list",
"(",
"graph",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"'{} is not a scheduler algorithm. It should be '",
"'one of NAIVE or LIST.'",
".",
"format",
"(",
"scheduler_alg",
")",
")"
] | Computes a schedule to minimize peak memory.
Args:
graph: an mtf.auto_mtf.graph_interface.GraphInterface.
scheduler_alg: a string, one of 'NAIVE' or 'LIST'
Returns:
an iterable of integers representing the schedule. | [
"Computes",
"a",
"schedule",
"to",
"minimize",
"peak",
"memory",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/scheduler.py#L35-L52 |
227,803 | tensorflow/mesh | mesh_tensorflow/auto_mtf/scheduler.py | _minimize_peak_memory_list | def _minimize_peak_memory_list(graph):
"""Computes schedule according to the greedy list heuristic.
Greedy list heuristic: schedule the operation which results in the most bytes
of memory being (immediately) freed.
TODO(joshuawang): Experiment with tiebreaking by preferring more successors.
Args:
graph: an mtf.auto_mtf.graph_interface.GraphInterface.
Returns:
an iterable of integers representing the schedule.
"""
schedule = []
bytes_freed = {} # {operation_name: bytes freed}
users_of = collections.defaultdict(set) # {tensor_name: set(operation_name)}
in_degree = collections.defaultdict(int) # {operation_name: in degree}
operation_id = {} # {operation_name: id}
# We want an updatable priority queue, so we use the following workaround:
# docs.python.org/2/library/heapq.html#priority-queue-implementation-notes
priority_queue = [] # (negative bytes freed, operation name)
# Set up the (greedy) topological sort.
for i, operation_name in enumerate(graph.get_all_operation_names()):
operation_id[operation_name] = i
for input_name in graph.get_operation_input_names(operation_name):
# Note that in _HybridGraphInterface, an operation may use a tensor twice,
# but we deduplicate (with respect to in_degree) so that we can later use
# users_of to decrement in_degree.
if operation_name in users_of[input_name]:
continue
users_of[input_name].add(operation_name)
in_degree[operation_name] += 1
for operation_name in graph.get_all_operation_names():
bytes_freed[operation_name] = 0
# For each input, this operation frees memory if it is the final consumer.
for input_name in graph.get_operation_input_names(operation_name):
if len(users_of[input_name]) == 1 and not graph.is_tensor_final(
input_name):
bytes_freed[operation_name] += graph.get_tensor_size(input_name)
# For each output, this operation will require additional bytes of memory
# (hence negative bytes freed).
for output_name in graph.get_operation_output_names(operation_name):
# If the output is used (or is final), then it eats memory.
if users_of[output_name] or graph.is_tensor_final(output_name):
bytes_freed[operation_name] -= graph.get_tensor_size(output_name)
for operation_name in graph.get_all_operation_names():
if in_degree[operation_name] == 0:
heapq.heappush(priority_queue,
(-bytes_freed[operation_name], operation_name))
# Do the (greedy) topological sort.
while priority_queue:
neg_bytes_freed, operation_name = heapq.heappop(priority_queue)
if bytes_freed[operation_name] != -neg_bytes_freed:
continue
schedule.append(operation_id[operation_name])
bytes_freed[operation_name] = None
for output_name in graph.get_operation_output_names(operation_name):
for other_operation_name in users_of[output_name]:
in_degree[other_operation_name] -= 1
if in_degree[other_operation_name] == 0:
heapq.heappush(priority_queue,
(-bytes_freed[other_operation_name],
other_operation_name))
for input_name in graph.get_operation_input_names(operation_name):
if operation_name not in users_of[input_name]:
# Used twice by this operation and hence already removed.
continue
users_of[input_name].remove(operation_name)
if len(users_of[input_name]) != 1 or graph.is_tensor_final(output_name):
continue
(other_operation_name,) = users_of[input_name]
bytes_freed[other_operation_name] += graph.get_tensor_size(
input_name)
if in_degree[other_operation_name] > 0:
continue
# Push another copy into the priority queue with our updated value.
# The original copy will be ignored since it does not match bytes_freed.
heapq.heappush(priority_queue, (-bytes_freed[other_operation_name],
other_operation_name))
return schedule | python | def _minimize_peak_memory_list(graph):
"""Computes schedule according to the greedy list heuristic.
Greedy list heuristic: schedule the operation which results in the most bytes
of memory being (immediately) freed.
TODO(joshuawang): Experiment with tiebreaking by preferring more successors.
Args:
graph: an mtf.auto_mtf.graph_interface.GraphInterface.
Returns:
an iterable of integers representing the schedule.
"""
schedule = []
bytes_freed = {} # {operation_name: bytes freed}
users_of = collections.defaultdict(set) # {tensor_name: set(operation_name)}
in_degree = collections.defaultdict(int) # {operation_name: in degree}
operation_id = {} # {operation_name: id}
# We want an updatable priority queue, so we use the following workaround:
# docs.python.org/2/library/heapq.html#priority-queue-implementation-notes
priority_queue = [] # (negative bytes freed, operation name)
# Set up the (greedy) topological sort.
for i, operation_name in enumerate(graph.get_all_operation_names()):
operation_id[operation_name] = i
for input_name in graph.get_operation_input_names(operation_name):
# Note that in _HybridGraphInterface, an operation may use a tensor twice,
# but we deduplicate (with respect to in_degree) so that we can later use
# users_of to decrement in_degree.
if operation_name in users_of[input_name]:
continue
users_of[input_name].add(operation_name)
in_degree[operation_name] += 1
for operation_name in graph.get_all_operation_names():
bytes_freed[operation_name] = 0
# For each input, this operation frees memory if it is the final consumer.
for input_name in graph.get_operation_input_names(operation_name):
if len(users_of[input_name]) == 1 and not graph.is_tensor_final(
input_name):
bytes_freed[operation_name] += graph.get_tensor_size(input_name)
# For each output, this operation will require additional bytes of memory
# (hence negative bytes freed).
for output_name in graph.get_operation_output_names(operation_name):
# If the output is used (or is final), then it eats memory.
if users_of[output_name] or graph.is_tensor_final(output_name):
bytes_freed[operation_name] -= graph.get_tensor_size(output_name)
for operation_name in graph.get_all_operation_names():
if in_degree[operation_name] == 0:
heapq.heappush(priority_queue,
(-bytes_freed[operation_name], operation_name))
# Do the (greedy) topological sort.
while priority_queue:
neg_bytes_freed, operation_name = heapq.heappop(priority_queue)
if bytes_freed[operation_name] != -neg_bytes_freed:
continue
schedule.append(operation_id[operation_name])
bytes_freed[operation_name] = None
for output_name in graph.get_operation_output_names(operation_name):
for other_operation_name in users_of[output_name]:
in_degree[other_operation_name] -= 1
if in_degree[other_operation_name] == 0:
heapq.heappush(priority_queue,
(-bytes_freed[other_operation_name],
other_operation_name))
for input_name in graph.get_operation_input_names(operation_name):
if operation_name not in users_of[input_name]:
# Used twice by this operation and hence already removed.
continue
users_of[input_name].remove(operation_name)
if len(users_of[input_name]) != 1 or graph.is_tensor_final(output_name):
continue
(other_operation_name,) = users_of[input_name]
bytes_freed[other_operation_name] += graph.get_tensor_size(
input_name)
if in_degree[other_operation_name] > 0:
continue
# Push another copy into the priority queue with our updated value.
# The original copy will be ignored since it does not match bytes_freed.
heapq.heappush(priority_queue, (-bytes_freed[other_operation_name],
other_operation_name))
return schedule | [
"def",
"_minimize_peak_memory_list",
"(",
"graph",
")",
":",
"schedule",
"=",
"[",
"]",
"bytes_freed",
"=",
"{",
"}",
"# {operation_name: bytes freed}",
"users_of",
"=",
"collections",
".",
"defaultdict",
"(",
"set",
")",
"# {tensor_name: set(operation_name)}",
"in_degree",
"=",
"collections",
".",
"defaultdict",
"(",
"int",
")",
"# {operation_name: in degree}",
"operation_id",
"=",
"{",
"}",
"# {operation_name: id}",
"# We want an updatable priority queue, so we use the following workaround:",
"# docs.python.org/2/library/heapq.html#priority-queue-implementation-notes",
"priority_queue",
"=",
"[",
"]",
"# (negative bytes freed, operation name)",
"# Set up the (greedy) topological sort.",
"for",
"i",
",",
"operation_name",
"in",
"enumerate",
"(",
"graph",
".",
"get_all_operation_names",
"(",
")",
")",
":",
"operation_id",
"[",
"operation_name",
"]",
"=",
"i",
"for",
"input_name",
"in",
"graph",
".",
"get_operation_input_names",
"(",
"operation_name",
")",
":",
"# Note that in _HybridGraphInterface, an operation may use a tensor twice,",
"# but we deduplicate (with respect to in_degree) so that we can later use",
"# users_of to decrement in_degree.",
"if",
"operation_name",
"in",
"users_of",
"[",
"input_name",
"]",
":",
"continue",
"users_of",
"[",
"input_name",
"]",
".",
"add",
"(",
"operation_name",
")",
"in_degree",
"[",
"operation_name",
"]",
"+=",
"1",
"for",
"operation_name",
"in",
"graph",
".",
"get_all_operation_names",
"(",
")",
":",
"bytes_freed",
"[",
"operation_name",
"]",
"=",
"0",
"# For each input, this operation frees memory if it is the final consumer.",
"for",
"input_name",
"in",
"graph",
".",
"get_operation_input_names",
"(",
"operation_name",
")",
":",
"if",
"len",
"(",
"users_of",
"[",
"input_name",
"]",
")",
"==",
"1",
"and",
"not",
"graph",
".",
"is_tensor_final",
"(",
"input_name",
")",
":",
"bytes_freed",
"[",
"operation_name",
"]",
"+=",
"graph",
".",
"get_tensor_size",
"(",
"input_name",
")",
"# For each output, this operation will require additional bytes of memory",
"# (hence negative bytes freed).",
"for",
"output_name",
"in",
"graph",
".",
"get_operation_output_names",
"(",
"operation_name",
")",
":",
"# If the output is used (or is final), then it eats memory.",
"if",
"users_of",
"[",
"output_name",
"]",
"or",
"graph",
".",
"is_tensor_final",
"(",
"output_name",
")",
":",
"bytes_freed",
"[",
"operation_name",
"]",
"-=",
"graph",
".",
"get_tensor_size",
"(",
"output_name",
")",
"for",
"operation_name",
"in",
"graph",
".",
"get_all_operation_names",
"(",
")",
":",
"if",
"in_degree",
"[",
"operation_name",
"]",
"==",
"0",
":",
"heapq",
".",
"heappush",
"(",
"priority_queue",
",",
"(",
"-",
"bytes_freed",
"[",
"operation_name",
"]",
",",
"operation_name",
")",
")",
"# Do the (greedy) topological sort.",
"while",
"priority_queue",
":",
"neg_bytes_freed",
",",
"operation_name",
"=",
"heapq",
".",
"heappop",
"(",
"priority_queue",
")",
"if",
"bytes_freed",
"[",
"operation_name",
"]",
"!=",
"-",
"neg_bytes_freed",
":",
"continue",
"schedule",
".",
"append",
"(",
"operation_id",
"[",
"operation_name",
"]",
")",
"bytes_freed",
"[",
"operation_name",
"]",
"=",
"None",
"for",
"output_name",
"in",
"graph",
".",
"get_operation_output_names",
"(",
"operation_name",
")",
":",
"for",
"other_operation_name",
"in",
"users_of",
"[",
"output_name",
"]",
":",
"in_degree",
"[",
"other_operation_name",
"]",
"-=",
"1",
"if",
"in_degree",
"[",
"other_operation_name",
"]",
"==",
"0",
":",
"heapq",
".",
"heappush",
"(",
"priority_queue",
",",
"(",
"-",
"bytes_freed",
"[",
"other_operation_name",
"]",
",",
"other_operation_name",
")",
")",
"for",
"input_name",
"in",
"graph",
".",
"get_operation_input_names",
"(",
"operation_name",
")",
":",
"if",
"operation_name",
"not",
"in",
"users_of",
"[",
"input_name",
"]",
":",
"# Used twice by this operation and hence already removed.",
"continue",
"users_of",
"[",
"input_name",
"]",
".",
"remove",
"(",
"operation_name",
")",
"if",
"len",
"(",
"users_of",
"[",
"input_name",
"]",
")",
"!=",
"1",
"or",
"graph",
".",
"is_tensor_final",
"(",
"output_name",
")",
":",
"continue",
"(",
"other_operation_name",
",",
")",
"=",
"users_of",
"[",
"input_name",
"]",
"bytes_freed",
"[",
"other_operation_name",
"]",
"+=",
"graph",
".",
"get_tensor_size",
"(",
"input_name",
")",
"if",
"in_degree",
"[",
"other_operation_name",
"]",
">",
"0",
":",
"continue",
"# Push another copy into the priority queue with our updated value.",
"# The original copy will be ignored since it does not match bytes_freed.",
"heapq",
".",
"heappush",
"(",
"priority_queue",
",",
"(",
"-",
"bytes_freed",
"[",
"other_operation_name",
"]",
",",
"other_operation_name",
")",
")",
"return",
"schedule"
] | Computes schedule according to the greedy list heuristic.
Greedy list heuristic: schedule the operation which results in the most bytes
of memory being (immediately) freed.
TODO(joshuawang): Experiment with tiebreaking by preferring more successors.
Args:
graph: an mtf.auto_mtf.graph_interface.GraphInterface.
Returns:
an iterable of integers representing the schedule. | [
"Computes",
"schedule",
"according",
"to",
"the",
"greedy",
"list",
"heuristic",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/scheduler.py#L67-L154 |
227,804 | tensorflow/mesh | mesh_tensorflow/auto_mtf/layout.py | layout | def layout(mtf_graph, mesh_shape, mtf_outputs=()):
"""Compute layout rules based on a computational graph and mesh shape.
Args:
mtf_graph: a mtf.Graph.
mesh_shape: an mtf.Shape, str, or listlike of mtf.Dimension.
mtf_outputs: an optional iterable of mtf.Tensor, representing the outputs
of the computation.
Returns:
a mtf.LayoutRules
"""
mesh_shape = mtf.convert_to_shape(mesh_shape)
estimator = memory_estimator.MemoryEstimator(mtf_graph, mesh_shape,
mtf_outputs)
optimizer = layout_optimizer.LayoutOptimizer(estimator)
return mtf.convert_to_layout_rules(optimizer.solve()) | python | def layout(mtf_graph, mesh_shape, mtf_outputs=()):
"""Compute layout rules based on a computational graph and mesh shape.
Args:
mtf_graph: a mtf.Graph.
mesh_shape: an mtf.Shape, str, or listlike of mtf.Dimension.
mtf_outputs: an optional iterable of mtf.Tensor, representing the outputs
of the computation.
Returns:
a mtf.LayoutRules
"""
mesh_shape = mtf.convert_to_shape(mesh_shape)
estimator = memory_estimator.MemoryEstimator(mtf_graph, mesh_shape,
mtf_outputs)
optimizer = layout_optimizer.LayoutOptimizer(estimator)
return mtf.convert_to_layout_rules(optimizer.solve()) | [
"def",
"layout",
"(",
"mtf_graph",
",",
"mesh_shape",
",",
"mtf_outputs",
"=",
"(",
")",
")",
":",
"mesh_shape",
"=",
"mtf",
".",
"convert_to_shape",
"(",
"mesh_shape",
")",
"estimator",
"=",
"memory_estimator",
".",
"MemoryEstimator",
"(",
"mtf_graph",
",",
"mesh_shape",
",",
"mtf_outputs",
")",
"optimizer",
"=",
"layout_optimizer",
".",
"LayoutOptimizer",
"(",
"estimator",
")",
"return",
"mtf",
".",
"convert_to_layout_rules",
"(",
"optimizer",
".",
"solve",
"(",
")",
")"
] | Compute layout rules based on a computational graph and mesh shape.
Args:
mtf_graph: a mtf.Graph.
mesh_shape: an mtf.Shape, str, or listlike of mtf.Dimension.
mtf_outputs: an optional iterable of mtf.Tensor, representing the outputs
of the computation.
Returns:
a mtf.LayoutRules | [
"Compute",
"layout",
"rules",
"based",
"on",
"a",
"computational",
"graph",
"and",
"mesh",
"shape",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout.py#L47-L63 |
227,805 | tensorflow/mesh | mesh_tensorflow/optimize.py | Optimizer.apply_grads | def apply_grads(self, grads, variables):
"""Apply gradients to variables.
Call this function externally instead of apply_grad(). This causes the
operations to be combined, which is necessary for stacking variables
see mtf.rewrite_stack_variables().
Args:
grads: a list of Tensor
variables: a list of Variables
Returns:
a list of Operations
"""
ops = []
for grad, var in zip(grads, variables):
ops.extend(self.apply_grad(grad, var))
if not ops:
return ops
return variables[0].graph.combine_assignments(ops) | python | def apply_grads(self, grads, variables):
"""Apply gradients to variables.
Call this function externally instead of apply_grad(). This causes the
operations to be combined, which is necessary for stacking variables
see mtf.rewrite_stack_variables().
Args:
grads: a list of Tensor
variables: a list of Variables
Returns:
a list of Operations
"""
ops = []
for grad, var in zip(grads, variables):
ops.extend(self.apply_grad(grad, var))
if not ops:
return ops
return variables[0].graph.combine_assignments(ops) | [
"def",
"apply_grads",
"(",
"self",
",",
"grads",
",",
"variables",
")",
":",
"ops",
"=",
"[",
"]",
"for",
"grad",
",",
"var",
"in",
"zip",
"(",
"grads",
",",
"variables",
")",
":",
"ops",
".",
"extend",
"(",
"self",
".",
"apply_grad",
"(",
"grad",
",",
"var",
")",
")",
"if",
"not",
"ops",
":",
"return",
"ops",
"return",
"variables",
"[",
"0",
"]",
".",
"graph",
".",
"combine_assignments",
"(",
"ops",
")"
] | Apply gradients to variables.
Call this function externally instead of apply_grad(). This causes the
operations to be combined, which is necessary for stacking variables
see mtf.rewrite_stack_variables().
Args:
grads: a list of Tensor
variables: a list of Variables
Returns:
a list of Operations | [
"Apply",
"gradients",
"to",
"variables",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/optimize.py#L39-L57 |
227,806 | tensorflow/mesh | mesh_tensorflow/optimize.py | AdafactorOptimizer._factored_dims | def _factored_dims(self, shape):
"""Should we use a factored second moment estimator.
Based on the shape of the variable.
If we factor the accumulator, then this function returns a list of two
mtf.Dimensions to reduce over. We always pick the two largest dimensions.
If there are not two dimensions of size >= min_dim_size_to_factor, then we
do not factor.
Args:
shape: a Shape
Returns:
either a list of 2 Dimensions or None
"""
if not self._factored or shape.ndims < 2:
return None
sorted_dims = sorted(shape.dims, key=lambda d: -d.size)
if sorted_dims[1].size < self._min_dim_size_to_factor:
return None
return sorted_dims[:2] | python | def _factored_dims(self, shape):
"""Should we use a factored second moment estimator.
Based on the shape of the variable.
If we factor the accumulator, then this function returns a list of two
mtf.Dimensions to reduce over. We always pick the two largest dimensions.
If there are not two dimensions of size >= min_dim_size_to_factor, then we
do not factor.
Args:
shape: a Shape
Returns:
either a list of 2 Dimensions or None
"""
if not self._factored or shape.ndims < 2:
return None
sorted_dims = sorted(shape.dims, key=lambda d: -d.size)
if sorted_dims[1].size < self._min_dim_size_to_factor:
return None
return sorted_dims[:2] | [
"def",
"_factored_dims",
"(",
"self",
",",
"shape",
")",
":",
"if",
"not",
"self",
".",
"_factored",
"or",
"shape",
".",
"ndims",
"<",
"2",
":",
"return",
"None",
"sorted_dims",
"=",
"sorted",
"(",
"shape",
".",
"dims",
",",
"key",
"=",
"lambda",
"d",
":",
"-",
"d",
".",
"size",
")",
"if",
"sorted_dims",
"[",
"1",
"]",
".",
"size",
"<",
"self",
".",
"_min_dim_size_to_factor",
":",
"return",
"None",
"return",
"sorted_dims",
"[",
":",
"2",
"]"
] | Should we use a factored second moment estimator.
Based on the shape of the variable.
If we factor the accumulator, then this function returns a list of two
mtf.Dimensions to reduce over. We always pick the two largest dimensions.
If there are not two dimensions of size >= min_dim_size_to_factor, then we
do not factor.
Args:
shape: a Shape
Returns:
either a list of 2 Dimensions or None | [
"Should",
"we",
"use",
"a",
"factored",
"second",
"moment",
"estimator",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/optimize.py#L139-L158 |
227,807 | tensorflow/mesh | mesh_tensorflow/auto_mtf/valid_layouts.py | LayoutValidator.is_valid_assignment | def is_valid_assignment(self, mtf_dimension_name, mesh_dimension_name):
"""Whether this MTF dimension may be assigned to this mesh dimension.
Args:
mtf_dimension_name: string, the name of a Mesh TensorFlow dimension.
mesh_dimension_name: string, the name of a mesh dimension.
Returns:
A boolean indicating whether the assignment is valid.
"""
return ((mtf_dimension_name in self._splittable_mtf_dimension_names) and
(self._mtf_dimension_name_to_size_gcd[mtf_dimension_name] %
self._mesh_dimension_name_to_size[mesh_dimension_name] == 0)) | python | def is_valid_assignment(self, mtf_dimension_name, mesh_dimension_name):
"""Whether this MTF dimension may be assigned to this mesh dimension.
Args:
mtf_dimension_name: string, the name of a Mesh TensorFlow dimension.
mesh_dimension_name: string, the name of a mesh dimension.
Returns:
A boolean indicating whether the assignment is valid.
"""
return ((mtf_dimension_name in self._splittable_mtf_dimension_names) and
(self._mtf_dimension_name_to_size_gcd[mtf_dimension_name] %
self._mesh_dimension_name_to_size[mesh_dimension_name] == 0)) | [
"def",
"is_valid_assignment",
"(",
"self",
",",
"mtf_dimension_name",
",",
"mesh_dimension_name",
")",
":",
"return",
"(",
"(",
"mtf_dimension_name",
"in",
"self",
".",
"_splittable_mtf_dimension_names",
")",
"and",
"(",
"self",
".",
"_mtf_dimension_name_to_size_gcd",
"[",
"mtf_dimension_name",
"]",
"%",
"self",
".",
"_mesh_dimension_name_to_size",
"[",
"mesh_dimension_name",
"]",
"==",
"0",
")",
")"
] | Whether this MTF dimension may be assigned to this mesh dimension.
Args:
mtf_dimension_name: string, the name of a Mesh TensorFlow dimension.
mesh_dimension_name: string, the name of a mesh dimension.
Returns:
A boolean indicating whether the assignment is valid. | [
"Whether",
"this",
"MTF",
"dimension",
"may",
"be",
"assigned",
"to",
"this",
"mesh",
"dimension",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/valid_layouts.py#L83-L95 |
227,808 | tensorflow/mesh | mesh_tensorflow/auto_mtf/valid_layouts.py | LayoutValidator._initialize_splittable_dimensions | def _initialize_splittable_dimensions(self, mtf_graph):
"""Initializer for self._splittable_mtf_dimension_names.
Args:
mtf_graph: an mtf.Graph.
Returns:
A set(string) of the names of Mesh TensorFlow dimensions that may be
assigned in a layout.
"""
all_mtf_dimension_names = set() # set(string)
for mtf_operation in mtf_graph.operations:
for mtf_tensor in mtf_operation.outputs:
for mtf_dimension in mtf_tensor.shape.dims:
if not re.match(r"_anonymous_\d*", mtf_dimension.name):
all_mtf_dimension_names.add(mtf_dimension.name)
unsplittable_mtf_dimension_names = set() # set(string)
for mtf_operation in mtf_graph.operations:
unsplittable_mtf_dimension_names.update(mtf_operation.unsplittable_dims)
return all_mtf_dimension_names - unsplittable_mtf_dimension_names | python | def _initialize_splittable_dimensions(self, mtf_graph):
"""Initializer for self._splittable_mtf_dimension_names.
Args:
mtf_graph: an mtf.Graph.
Returns:
A set(string) of the names of Mesh TensorFlow dimensions that may be
assigned in a layout.
"""
all_mtf_dimension_names = set() # set(string)
for mtf_operation in mtf_graph.operations:
for mtf_tensor in mtf_operation.outputs:
for mtf_dimension in mtf_tensor.shape.dims:
if not re.match(r"_anonymous_\d*", mtf_dimension.name):
all_mtf_dimension_names.add(mtf_dimension.name)
unsplittable_mtf_dimension_names = set() # set(string)
for mtf_operation in mtf_graph.operations:
unsplittable_mtf_dimension_names.update(mtf_operation.unsplittable_dims)
return all_mtf_dimension_names - unsplittable_mtf_dimension_names | [
"def",
"_initialize_splittable_dimensions",
"(",
"self",
",",
"mtf_graph",
")",
":",
"all_mtf_dimension_names",
"=",
"set",
"(",
")",
"# set(string)",
"for",
"mtf_operation",
"in",
"mtf_graph",
".",
"operations",
":",
"for",
"mtf_tensor",
"in",
"mtf_operation",
".",
"outputs",
":",
"for",
"mtf_dimension",
"in",
"mtf_tensor",
".",
"shape",
".",
"dims",
":",
"if",
"not",
"re",
".",
"match",
"(",
"r\"_anonymous_\\d*\"",
",",
"mtf_dimension",
".",
"name",
")",
":",
"all_mtf_dimension_names",
".",
"add",
"(",
"mtf_dimension",
".",
"name",
")",
"unsplittable_mtf_dimension_names",
"=",
"set",
"(",
")",
"# set(string)",
"for",
"mtf_operation",
"in",
"mtf_graph",
".",
"operations",
":",
"unsplittable_mtf_dimension_names",
".",
"update",
"(",
"mtf_operation",
".",
"unsplittable_dims",
")",
"return",
"all_mtf_dimension_names",
"-",
"unsplittable_mtf_dimension_names"
] | Initializer for self._splittable_mtf_dimension_names.
Args:
mtf_graph: an mtf.Graph.
Returns:
A set(string) of the names of Mesh TensorFlow dimensions that may be
assigned in a layout. | [
"Initializer",
"for",
"self",
".",
"_splittable_mtf_dimension_names",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/valid_layouts.py#L97-L118 |
227,809 | tensorflow/mesh | mesh_tensorflow/auto_mtf/valid_layouts.py | LayoutValidator._initialize_mtf_dimension_name_to_size_gcd | def _initialize_mtf_dimension_name_to_size_gcd(self, mtf_graph):
"""Initializer for self._mtf_dimension_name_to_size_gcd.
Args:
mtf_graph: an mtf.Graph.
Returns:
A {string: int}, mapping the name of an MTF dimension to the greatest
common divisor of all the sizes it has. All these sizes being evenly
divisible by some x is equivalent to the GCD being divisible by x.
"""
mtf_dimension_name_to_size_gcd = {}
for mtf_operation in mtf_graph.operations:
for mtf_tensor in mtf_operation.outputs:
for mtf_dimension in mtf_tensor.shape.dims:
mtf_dimension_name_to_size_gcd[mtf_dimension.name] = fractions.gcd(
mtf_dimension_name_to_size_gcd.get(mtf_dimension.name,
mtf_dimension.size),
mtf_dimension.size)
return mtf_dimension_name_to_size_gcd | python | def _initialize_mtf_dimension_name_to_size_gcd(self, mtf_graph):
"""Initializer for self._mtf_dimension_name_to_size_gcd.
Args:
mtf_graph: an mtf.Graph.
Returns:
A {string: int}, mapping the name of an MTF dimension to the greatest
common divisor of all the sizes it has. All these sizes being evenly
divisible by some x is equivalent to the GCD being divisible by x.
"""
mtf_dimension_name_to_size_gcd = {}
for mtf_operation in mtf_graph.operations:
for mtf_tensor in mtf_operation.outputs:
for mtf_dimension in mtf_tensor.shape.dims:
mtf_dimension_name_to_size_gcd[mtf_dimension.name] = fractions.gcd(
mtf_dimension_name_to_size_gcd.get(mtf_dimension.name,
mtf_dimension.size),
mtf_dimension.size)
return mtf_dimension_name_to_size_gcd | [
"def",
"_initialize_mtf_dimension_name_to_size_gcd",
"(",
"self",
",",
"mtf_graph",
")",
":",
"mtf_dimension_name_to_size_gcd",
"=",
"{",
"}",
"for",
"mtf_operation",
"in",
"mtf_graph",
".",
"operations",
":",
"for",
"mtf_tensor",
"in",
"mtf_operation",
".",
"outputs",
":",
"for",
"mtf_dimension",
"in",
"mtf_tensor",
".",
"shape",
".",
"dims",
":",
"mtf_dimension_name_to_size_gcd",
"[",
"mtf_dimension",
".",
"name",
"]",
"=",
"fractions",
".",
"gcd",
"(",
"mtf_dimension_name_to_size_gcd",
".",
"get",
"(",
"mtf_dimension",
".",
"name",
",",
"mtf_dimension",
".",
"size",
")",
",",
"mtf_dimension",
".",
"size",
")",
"return",
"mtf_dimension_name_to_size_gcd"
] | Initializer for self._mtf_dimension_name_to_size_gcd.
Args:
mtf_graph: an mtf.Graph.
Returns:
A {string: int}, mapping the name of an MTF dimension to the greatest
common divisor of all the sizes it has. All these sizes being evenly
divisible by some x is equivalent to the GCD being divisible by x. | [
"Initializer",
"for",
"self",
".",
"_mtf_dimension_name_to_size_gcd",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/valid_layouts.py#L120-L140 |
227,810 | tensorflow/mesh | mesh_tensorflow/auto_mtf/valid_layouts.py | LayoutValidator._initialize_mesh_dimension_name_to_size | def _initialize_mesh_dimension_name_to_size(self, mesh_shape):
"""Initializer for self._mesh_dimension_name_to_size.
Args:
mesh_shape: an mtf.Shape.
Returns:
A {string: int} mapping mesh dimension names to their sizes.
"""
mesh_dimension_name_to_size = {} # {string: int}
for mesh_dimension in mesh_shape.dims:
mesh_dimension_name_to_size[mesh_dimension.name] = mesh_dimension.size
return mesh_dimension_name_to_size | python | def _initialize_mesh_dimension_name_to_size(self, mesh_shape):
"""Initializer for self._mesh_dimension_name_to_size.
Args:
mesh_shape: an mtf.Shape.
Returns:
A {string: int} mapping mesh dimension names to their sizes.
"""
mesh_dimension_name_to_size = {} # {string: int}
for mesh_dimension in mesh_shape.dims:
mesh_dimension_name_to_size[mesh_dimension.name] = mesh_dimension.size
return mesh_dimension_name_to_size | [
"def",
"_initialize_mesh_dimension_name_to_size",
"(",
"self",
",",
"mesh_shape",
")",
":",
"mesh_dimension_name_to_size",
"=",
"{",
"}",
"# {string: int}",
"for",
"mesh_dimension",
"in",
"mesh_shape",
".",
"dims",
":",
"mesh_dimension_name_to_size",
"[",
"mesh_dimension",
".",
"name",
"]",
"=",
"mesh_dimension",
".",
"size",
"return",
"mesh_dimension_name_to_size"
] | Initializer for self._mesh_dimension_name_to_size.
Args:
mesh_shape: an mtf.Shape.
Returns:
A {string: int} mapping mesh dimension names to their sizes. | [
"Initializer",
"for",
"self",
".",
"_mesh_dimension_name_to_size",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/valid_layouts.py#L142-L154 |
227,811 | tensorflow/mesh | mesh_tensorflow/placement_mesh_impl.py | allconcat_ring | def allconcat_ring(xs, devices, concat_axis):
"""Concatenate all Tensors everywhere.
Performance-optimized for a ring of devices.
Args:
xs: a list of n tf.Tensors
devices: a list of n strings
concat_axis: an integer
Returns:
a list of n Tensors
"""
n = len(xs)
if n == 1:
return xs
# [target, source]
parts = [[xs[target] if target == source else None for source in xrange(n)]
for target in xrange(n)]
for distance in xrange(1, n // 2 + 1):
for target in xrange(n):
source = (target + distance) % n
if parts[target][source] is None:
with tf.device(devices[target]):
parts[target][source] = tf.identity(parts[(target + 1) % n][source])
source = (target - distance) % n
if parts[target][source] is None:
with tf.device(devices[target]):
parts[target][source] = tf.identity(parts[(target - 1) % n][source])
return mtf.parallel(devices, tf.concat, parts, axis=[concat_axis] * n) | python | def allconcat_ring(xs, devices, concat_axis):
"""Concatenate all Tensors everywhere.
Performance-optimized for a ring of devices.
Args:
xs: a list of n tf.Tensors
devices: a list of n strings
concat_axis: an integer
Returns:
a list of n Tensors
"""
n = len(xs)
if n == 1:
return xs
# [target, source]
parts = [[xs[target] if target == source else None for source in xrange(n)]
for target in xrange(n)]
for distance in xrange(1, n // 2 + 1):
for target in xrange(n):
source = (target + distance) % n
if parts[target][source] is None:
with tf.device(devices[target]):
parts[target][source] = tf.identity(parts[(target + 1) % n][source])
source = (target - distance) % n
if parts[target][source] is None:
with tf.device(devices[target]):
parts[target][source] = tf.identity(parts[(target - 1) % n][source])
return mtf.parallel(devices, tf.concat, parts, axis=[concat_axis] * n) | [
"def",
"allconcat_ring",
"(",
"xs",
",",
"devices",
",",
"concat_axis",
")",
":",
"n",
"=",
"len",
"(",
"xs",
")",
"if",
"n",
"==",
"1",
":",
"return",
"xs",
"# [target, source]",
"parts",
"=",
"[",
"[",
"xs",
"[",
"target",
"]",
"if",
"target",
"==",
"source",
"else",
"None",
"for",
"source",
"in",
"xrange",
"(",
"n",
")",
"]",
"for",
"target",
"in",
"xrange",
"(",
"n",
")",
"]",
"for",
"distance",
"in",
"xrange",
"(",
"1",
",",
"n",
"//",
"2",
"+",
"1",
")",
":",
"for",
"target",
"in",
"xrange",
"(",
"n",
")",
":",
"source",
"=",
"(",
"target",
"+",
"distance",
")",
"%",
"n",
"if",
"parts",
"[",
"target",
"]",
"[",
"source",
"]",
"is",
"None",
":",
"with",
"tf",
".",
"device",
"(",
"devices",
"[",
"target",
"]",
")",
":",
"parts",
"[",
"target",
"]",
"[",
"source",
"]",
"=",
"tf",
".",
"identity",
"(",
"parts",
"[",
"(",
"target",
"+",
"1",
")",
"%",
"n",
"]",
"[",
"source",
"]",
")",
"source",
"=",
"(",
"target",
"-",
"distance",
")",
"%",
"n",
"if",
"parts",
"[",
"target",
"]",
"[",
"source",
"]",
"is",
"None",
":",
"with",
"tf",
".",
"device",
"(",
"devices",
"[",
"target",
"]",
")",
":",
"parts",
"[",
"target",
"]",
"[",
"source",
"]",
"=",
"tf",
".",
"identity",
"(",
"parts",
"[",
"(",
"target",
"-",
"1",
")",
"%",
"n",
"]",
"[",
"source",
"]",
")",
"return",
"mtf",
".",
"parallel",
"(",
"devices",
",",
"tf",
".",
"concat",
",",
"parts",
",",
"axis",
"=",
"[",
"concat_axis",
"]",
"*",
"n",
")"
] | Concatenate all Tensors everywhere.
Performance-optimized for a ring of devices.
Args:
xs: a list of n tf.Tensors
devices: a list of n strings
concat_axis: an integer
Returns:
a list of n Tensors | [
"Concatenate",
"all",
"Tensors",
"everywhere",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/placement_mesh_impl.py#L462-L491 |
227,812 | tensorflow/mesh | mesh_tensorflow/placement_mesh_impl.py | PlacementMeshImpl.Print | def Print(self, x, data, message, **kwargs): # pylint: disable=invalid-name
"""call tf.Print.
Args:
x: a LaidOutTensor
data: a list of LaidOutTensor
message: a string
**kwargs: keyword arguments to tf.print
Returns:
a LaidOutTensor
"""
tf.logging.info("PlacementMeshImpl::Print")
new_slices = x.tensor_list[:]
with tf.device(self._devices[0]):
new_slices[0] = tf.Print(
new_slices[0], [t for d in data for t in d.tensor_list],
message, **kwargs)
return self.LaidOutTensor(new_slices) | python | def Print(self, x, data, message, **kwargs): # pylint: disable=invalid-name
"""call tf.Print.
Args:
x: a LaidOutTensor
data: a list of LaidOutTensor
message: a string
**kwargs: keyword arguments to tf.print
Returns:
a LaidOutTensor
"""
tf.logging.info("PlacementMeshImpl::Print")
new_slices = x.tensor_list[:]
with tf.device(self._devices[0]):
new_slices[0] = tf.Print(
new_slices[0], [t for d in data for t in d.tensor_list],
message, **kwargs)
return self.LaidOutTensor(new_slices) | [
"def",
"Print",
"(",
"self",
",",
"x",
",",
"data",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=invalid-name",
"tf",
".",
"logging",
".",
"info",
"(",
"\"PlacementMeshImpl::Print\"",
")",
"new_slices",
"=",
"x",
".",
"tensor_list",
"[",
":",
"]",
"with",
"tf",
".",
"device",
"(",
"self",
".",
"_devices",
"[",
"0",
"]",
")",
":",
"new_slices",
"[",
"0",
"]",
"=",
"tf",
".",
"Print",
"(",
"new_slices",
"[",
"0",
"]",
",",
"[",
"t",
"for",
"d",
"in",
"data",
"for",
"t",
"in",
"d",
".",
"tensor_list",
"]",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"LaidOutTensor",
"(",
"new_slices",
")"
] | call tf.Print.
Args:
x: a LaidOutTensor
data: a list of LaidOutTensor
message: a string
**kwargs: keyword arguments to tf.print
Returns:
a LaidOutTensor | [
"call",
"tf",
".",
"Print",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/placement_mesh_impl.py#L185-L202 |
227,813 | tensorflow/mesh | mesh_tensorflow/placement_mesh_impl.py | PlacementMeshImpl.alltoall | def alltoall(self, x, mesh_axis, split_axis, concat_axis):
"""Grouped alltoall.
Args:
x: a LaidOutTensor
mesh_axis: an integer the mesh axis along which to group
split_axis: an integer (the Tensor axis along which to split)
concat_axis: an integer (the Tensor axis along which to concatenate)
Returns:
a LaidOutTensor
"""
return self._collective_with_groups(
x, [mesh_axis],
functools.partial(
alltoall_ring, split_axis=split_axis, concat_axis=concat_axis)) | python | def alltoall(self, x, mesh_axis, split_axis, concat_axis):
"""Grouped alltoall.
Args:
x: a LaidOutTensor
mesh_axis: an integer the mesh axis along which to group
split_axis: an integer (the Tensor axis along which to split)
concat_axis: an integer (the Tensor axis along which to concatenate)
Returns:
a LaidOutTensor
"""
return self._collective_with_groups(
x, [mesh_axis],
functools.partial(
alltoall_ring, split_axis=split_axis, concat_axis=concat_axis)) | [
"def",
"alltoall",
"(",
"self",
",",
"x",
",",
"mesh_axis",
",",
"split_axis",
",",
"concat_axis",
")",
":",
"return",
"self",
".",
"_collective_with_groups",
"(",
"x",
",",
"[",
"mesh_axis",
"]",
",",
"functools",
".",
"partial",
"(",
"alltoall_ring",
",",
"split_axis",
"=",
"split_axis",
",",
"concat_axis",
"=",
"concat_axis",
")",
")"
] | Grouped alltoall.
Args:
x: a LaidOutTensor
mesh_axis: an integer the mesh axis along which to group
split_axis: an integer (the Tensor axis along which to split)
concat_axis: an integer (the Tensor axis along which to concatenate)
Returns:
a LaidOutTensor | [
"Grouped",
"alltoall",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/placement_mesh_impl.py#L232-L246 |
227,814 | tensorflow/mesh | mesh_tensorflow/placement_mesh_impl.py | PlacementMeshImpl.import_tf_tensor | def import_tf_tensor(self, x, tf_x):
"""Import a tf.Tensor, producing a LaidOutTensor.
Args:
x: a Tensor
tf_x: a tf.Tensor
Returns:
a LaidOutTensor
"""
return self.LaidOutTensor(self.make_slices(tf_x, x.shape)) | python | def import_tf_tensor(self, x, tf_x):
"""Import a tf.Tensor, producing a LaidOutTensor.
Args:
x: a Tensor
tf_x: a tf.Tensor
Returns:
a LaidOutTensor
"""
return self.LaidOutTensor(self.make_slices(tf_x, x.shape)) | [
"def",
"import_tf_tensor",
"(",
"self",
",",
"x",
",",
"tf_x",
")",
":",
"return",
"self",
".",
"LaidOutTensor",
"(",
"self",
".",
"make_slices",
"(",
"tf_x",
",",
"x",
".",
"shape",
")",
")"
] | Import a tf.Tensor, producing a LaidOutTensor.
Args:
x: a Tensor
tf_x: a tf.Tensor
Returns:
a LaidOutTensor | [
"Import",
"a",
"tf",
".",
"Tensor",
"producing",
"a",
"LaidOutTensor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/placement_mesh_impl.py#L350-L359 |
227,815 | tensorflow/mesh | mesh_tensorflow/transformer/attention.py | attention | def attention(q,
k,
v,
memory_length_dim,
key_dim,
value_dim,
mask=None,
dropout_rate=0.0,
dropout_broadcast_dims=None,
extra_logit=None):
"""Dot-product attention - doesn't use positional dimensions.
key_dim is a Dimension representing the channels in the queries and keys
value_dim is a Dimension representing the channels in values
memory_length_dim is a Dimension representing the different key/value pairs.
Dimensions of q: other_query_dims + {key_dim}
Dimensions of k: other_memory_dims + {memory_length_dim, key_dim}
Dimensions of v: other_memory_dims + {memory_length_dim, value_dim}
other_memory_dims is a subset of other_query_dims
Typically, other_query_dims={batch, heads, length}
Typically, other_memory_dims={batch, heads}
Args:
q: a Tensor
k: a Tensor
v: a Tensor
memory_length_dim: a Dimension
key_dim: a Dimension
value_dim: a Dimension
mask: mask Tensor (see attention_mask())
dropout_rate: a float.
dropout_broadcast_dims: an optional list of mtf.Dimension
extra_logit: an optional scalar or tensor
Returns:
Tensor with shape q.shape - key_dim + value_dim
"""
logits = mtf.einsum([q, k], reduced_dims=[key_dim])
if mask is not None:
logits += mask
weights = mtf.softmax(logits, memory_length_dim, extra_logit=extra_logit)
if dropout_rate != 0.0:
weights = mtf.dropout(
weights, 1.0 - dropout_rate,
noise_shape=weights.shape - dropout_broadcast_dims)
outputs_shape = q.shape - key_dim + value_dim
outputs = mtf.einsum([weights, v], outputs_shape)
return outputs | python | def attention(q,
k,
v,
memory_length_dim,
key_dim,
value_dim,
mask=None,
dropout_rate=0.0,
dropout_broadcast_dims=None,
extra_logit=None):
"""Dot-product attention - doesn't use positional dimensions.
key_dim is a Dimension representing the channels in the queries and keys
value_dim is a Dimension representing the channels in values
memory_length_dim is a Dimension representing the different key/value pairs.
Dimensions of q: other_query_dims + {key_dim}
Dimensions of k: other_memory_dims + {memory_length_dim, key_dim}
Dimensions of v: other_memory_dims + {memory_length_dim, value_dim}
other_memory_dims is a subset of other_query_dims
Typically, other_query_dims={batch, heads, length}
Typically, other_memory_dims={batch, heads}
Args:
q: a Tensor
k: a Tensor
v: a Tensor
memory_length_dim: a Dimension
key_dim: a Dimension
value_dim: a Dimension
mask: mask Tensor (see attention_mask())
dropout_rate: a float.
dropout_broadcast_dims: an optional list of mtf.Dimension
extra_logit: an optional scalar or tensor
Returns:
Tensor with shape q.shape - key_dim + value_dim
"""
logits = mtf.einsum([q, k], reduced_dims=[key_dim])
if mask is not None:
logits += mask
weights = mtf.softmax(logits, memory_length_dim, extra_logit=extra_logit)
if dropout_rate != 0.0:
weights = mtf.dropout(
weights, 1.0 - dropout_rate,
noise_shape=weights.shape - dropout_broadcast_dims)
outputs_shape = q.shape - key_dim + value_dim
outputs = mtf.einsum([weights, v], outputs_shape)
return outputs | [
"def",
"attention",
"(",
"q",
",",
"k",
",",
"v",
",",
"memory_length_dim",
",",
"key_dim",
",",
"value_dim",
",",
"mask",
"=",
"None",
",",
"dropout_rate",
"=",
"0.0",
",",
"dropout_broadcast_dims",
"=",
"None",
",",
"extra_logit",
"=",
"None",
")",
":",
"logits",
"=",
"mtf",
".",
"einsum",
"(",
"[",
"q",
",",
"k",
"]",
",",
"reduced_dims",
"=",
"[",
"key_dim",
"]",
")",
"if",
"mask",
"is",
"not",
"None",
":",
"logits",
"+=",
"mask",
"weights",
"=",
"mtf",
".",
"softmax",
"(",
"logits",
",",
"memory_length_dim",
",",
"extra_logit",
"=",
"extra_logit",
")",
"if",
"dropout_rate",
"!=",
"0.0",
":",
"weights",
"=",
"mtf",
".",
"dropout",
"(",
"weights",
",",
"1.0",
"-",
"dropout_rate",
",",
"noise_shape",
"=",
"weights",
".",
"shape",
"-",
"dropout_broadcast_dims",
")",
"outputs_shape",
"=",
"q",
".",
"shape",
"-",
"key_dim",
"+",
"value_dim",
"outputs",
"=",
"mtf",
".",
"einsum",
"(",
"[",
"weights",
",",
"v",
"]",
",",
"outputs_shape",
")",
"return",
"outputs"
] | Dot-product attention - doesn't use positional dimensions.
key_dim is a Dimension representing the channels in the queries and keys
value_dim is a Dimension representing the channels in values
memory_length_dim is a Dimension representing the different key/value pairs.
Dimensions of q: other_query_dims + {key_dim}
Dimensions of k: other_memory_dims + {memory_length_dim, key_dim}
Dimensions of v: other_memory_dims + {memory_length_dim, value_dim}
other_memory_dims is a subset of other_query_dims
Typically, other_query_dims={batch, heads, length}
Typically, other_memory_dims={batch, heads}
Args:
q: a Tensor
k: a Tensor
v: a Tensor
memory_length_dim: a Dimension
key_dim: a Dimension
value_dim: a Dimension
mask: mask Tensor (see attention_mask())
dropout_rate: a float.
dropout_broadcast_dims: an optional list of mtf.Dimension
extra_logit: an optional scalar or tensor
Returns:
Tensor with shape q.shape - key_dim + value_dim | [
"Dot",
"-",
"product",
"attention",
"-",
"doesn",
"t",
"use",
"positional",
"dimensions",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/attention.py#L27-L76 |
227,816 | tensorflow/mesh | mesh_tensorflow/transformer/attention.py | attention_params_simple | def attention_params_simple(
mesh, io_dim, kv_dim, heads_dim, variable_dtype):
"""Common case attention parameters.
Args:
mesh: a Mesh
io_dim: a Dimension (channels dimension of inputs and outputs)
kv_dim: a Dimension (channels in keys and values)
heads_dim: a Dimension (number of attention "heads")
variable_dtype: a mtf.VariableDType
Returns:
an AttentionParams
"""
return AttentionParams(
mesh,
query_input_dim=io_dim,
memory_input_dim=io_dim,
output_dim=io_dim,
key_dim=kv_dim,
value_dim=kv_dim,
query_heads_dims=[heads_dim],
memory_heads_dims=[heads_dim],
variable_dtype=variable_dtype) | python | def attention_params_simple(
mesh, io_dim, kv_dim, heads_dim, variable_dtype):
"""Common case attention parameters.
Args:
mesh: a Mesh
io_dim: a Dimension (channels dimension of inputs and outputs)
kv_dim: a Dimension (channels in keys and values)
heads_dim: a Dimension (number of attention "heads")
variable_dtype: a mtf.VariableDType
Returns:
an AttentionParams
"""
return AttentionParams(
mesh,
query_input_dim=io_dim,
memory_input_dim=io_dim,
output_dim=io_dim,
key_dim=kv_dim,
value_dim=kv_dim,
query_heads_dims=[heads_dim],
memory_heads_dims=[heads_dim],
variable_dtype=variable_dtype) | [
"def",
"attention_params_simple",
"(",
"mesh",
",",
"io_dim",
",",
"kv_dim",
",",
"heads_dim",
",",
"variable_dtype",
")",
":",
"return",
"AttentionParams",
"(",
"mesh",
",",
"query_input_dim",
"=",
"io_dim",
",",
"memory_input_dim",
"=",
"io_dim",
",",
"output_dim",
"=",
"io_dim",
",",
"key_dim",
"=",
"kv_dim",
",",
"value_dim",
"=",
"kv_dim",
",",
"query_heads_dims",
"=",
"[",
"heads_dim",
"]",
",",
"memory_heads_dims",
"=",
"[",
"heads_dim",
"]",
",",
"variable_dtype",
"=",
"variable_dtype",
")"
] | Common case attention parameters.
Args:
mesh: a Mesh
io_dim: a Dimension (channels dimension of inputs and outputs)
kv_dim: a Dimension (channels in keys and values)
heads_dim: a Dimension (number of attention "heads")
variable_dtype: a mtf.VariableDType
Returns:
an AttentionParams | [
"Common",
"case",
"attention",
"parameters",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/attention.py#L264-L286 |
227,817 | tensorflow/mesh | mesh_tensorflow/transformer/attention.py | local_attention_1d | def local_attention_1d(q,
k,
v,
length_dim,
key_dim,
value_dim,
autoregressive=True,
length_dim_num_splits=1,
radius=128,
sequence_id=1,
attention_kwargs=None):
"""Attention to the a neighborood around the source.
If autoregressive, then query position p can only see memory positions
in the range (p - radius, p].
If not autoregressive, then query position p can only see memory positions
in the range (p - window_size, p + radius].
Args:
q: a Tensor containing length_dim
k: a Tensor containing length_dim
v: an optional Tensor containing length_dim. If none then uses v=k.
length_dim: a Dimension
key_dim: a Dimension (the channels dimension of q and k)
value_dim: a Dimension (the channels dimension of v)
autoregressive: a boolean
length_dim_num_splits: an optional integer indicating how many ways the
length dimension is split
radius: an integer
sequence_id: a Tensor or an integer
attention_kwargs: optional keyword arguments for attention()
Returns:
a Tensor with the shape x.shape - key_dim + value_dim
Raises:
ValueError: if channels or depth don't match.
"""
# Choose a suitable block size.
# We choose the greatest divisor of length_per_split less than or equal
# to max(window_size, 128)
length_per_split = length_dim.size // length_dim_num_splits
block_length = max(radius, 128)
while length_per_split % block_length != 0:
block_length -= 1
query_block_length = mtf.Dimension("query_block_length", block_length)
memory_block_length = mtf.Dimension("memory_block_length", block_length)
# The num_blocks dimension gets the same name as the length dimension,
# so it will be split in the same way.
num_blocks = mtf.Dimension(length_dim.name, length_dim.size // block_length)
def _reshape_query(x):
return mtf.replace_dimensions(
x, length_dim, [num_blocks, query_block_length])
def _reshape_memory(x):
x = mtf.replace_dimensions(
x, length_dim, [num_blocks, memory_block_length])
return (mtf.left_halo_exchange if autoregressive else mtf.halo_exchange)(
x, num_blocks, memory_block_length, radius)
q = _reshape_query(q)
k = _reshape_memory(k)
if v:
v = _reshape_memory(v)
else:
v = k
if sequence_id is None:
sequence_id = 1
if (not isinstance(sequence_id, mtf.Tensor) or
length_dim not in sequence_id.shape.dims):
sequence_id += mtf.zeros(q.mesh, [length_dim], tf.int32)
q_sequence_id = _reshape_query(sequence_id)
m_sequence_id = _reshape_memory(sequence_id)
pos = mtf.range(q.mesh, length_dim, dtype=tf.int32)
q_pos = _reshape_query(pos)
m_pos = _reshape_memory(pos)
padded_memory_block_length = mtf.Dimension(
"memory_block_length",
(1 if autoregressive else 2) * radius + block_length)
relative_position = m_pos - q_pos
illegal = mtf.not_equal(q_sequence_id, m_sequence_id)
illegal = mtf.logical_or(illegal, mtf.less_equal(relative_position, -radius))
illegal = mtf.logical_or(illegal, mtf.greater(
relative_position, 0 if autoregressive else radius))
mask = mtf.cast(illegal, q.dtype) * -1e9
o = attention(q, k, v, padded_memory_block_length,
key_dim, value_dim, mask, **attention_kwargs)
return mtf.replace_dimensions(o, [num_blocks, query_block_length], length_dim) | python | def local_attention_1d(q,
k,
v,
length_dim,
key_dim,
value_dim,
autoregressive=True,
length_dim_num_splits=1,
radius=128,
sequence_id=1,
attention_kwargs=None):
"""Attention to the a neighborood around the source.
If autoregressive, then query position p can only see memory positions
in the range (p - radius, p].
If not autoregressive, then query position p can only see memory positions
in the range (p - window_size, p + radius].
Args:
q: a Tensor containing length_dim
k: a Tensor containing length_dim
v: an optional Tensor containing length_dim. If none then uses v=k.
length_dim: a Dimension
key_dim: a Dimension (the channels dimension of q and k)
value_dim: a Dimension (the channels dimension of v)
autoregressive: a boolean
length_dim_num_splits: an optional integer indicating how many ways the
length dimension is split
radius: an integer
sequence_id: a Tensor or an integer
attention_kwargs: optional keyword arguments for attention()
Returns:
a Tensor with the shape x.shape - key_dim + value_dim
Raises:
ValueError: if channels or depth don't match.
"""
# Choose a suitable block size.
# We choose the greatest divisor of length_per_split less than or equal
# to max(window_size, 128)
length_per_split = length_dim.size // length_dim_num_splits
block_length = max(radius, 128)
while length_per_split % block_length != 0:
block_length -= 1
query_block_length = mtf.Dimension("query_block_length", block_length)
memory_block_length = mtf.Dimension("memory_block_length", block_length)
# The num_blocks dimension gets the same name as the length dimension,
# so it will be split in the same way.
num_blocks = mtf.Dimension(length_dim.name, length_dim.size // block_length)
def _reshape_query(x):
return mtf.replace_dimensions(
x, length_dim, [num_blocks, query_block_length])
def _reshape_memory(x):
x = mtf.replace_dimensions(
x, length_dim, [num_blocks, memory_block_length])
return (mtf.left_halo_exchange if autoregressive else mtf.halo_exchange)(
x, num_blocks, memory_block_length, radius)
q = _reshape_query(q)
k = _reshape_memory(k)
if v:
v = _reshape_memory(v)
else:
v = k
if sequence_id is None:
sequence_id = 1
if (not isinstance(sequence_id, mtf.Tensor) or
length_dim not in sequence_id.shape.dims):
sequence_id += mtf.zeros(q.mesh, [length_dim], tf.int32)
q_sequence_id = _reshape_query(sequence_id)
m_sequence_id = _reshape_memory(sequence_id)
pos = mtf.range(q.mesh, length_dim, dtype=tf.int32)
q_pos = _reshape_query(pos)
m_pos = _reshape_memory(pos)
padded_memory_block_length = mtf.Dimension(
"memory_block_length",
(1 if autoregressive else 2) * radius + block_length)
relative_position = m_pos - q_pos
illegal = mtf.not_equal(q_sequence_id, m_sequence_id)
illegal = mtf.logical_or(illegal, mtf.less_equal(relative_position, -radius))
illegal = mtf.logical_or(illegal, mtf.greater(
relative_position, 0 if autoregressive else radius))
mask = mtf.cast(illegal, q.dtype) * -1e9
o = attention(q, k, v, padded_memory_block_length,
key_dim, value_dim, mask, **attention_kwargs)
return mtf.replace_dimensions(o, [num_blocks, query_block_length], length_dim) | [
"def",
"local_attention_1d",
"(",
"q",
",",
"k",
",",
"v",
",",
"length_dim",
",",
"key_dim",
",",
"value_dim",
",",
"autoregressive",
"=",
"True",
",",
"length_dim_num_splits",
"=",
"1",
",",
"radius",
"=",
"128",
",",
"sequence_id",
"=",
"1",
",",
"attention_kwargs",
"=",
"None",
")",
":",
"# Choose a suitable block size.",
"# We choose the greatest divisor of length_per_split less than or equal",
"# to max(window_size, 128)",
"length_per_split",
"=",
"length_dim",
".",
"size",
"//",
"length_dim_num_splits",
"block_length",
"=",
"max",
"(",
"radius",
",",
"128",
")",
"while",
"length_per_split",
"%",
"block_length",
"!=",
"0",
":",
"block_length",
"-=",
"1",
"query_block_length",
"=",
"mtf",
".",
"Dimension",
"(",
"\"query_block_length\"",
",",
"block_length",
")",
"memory_block_length",
"=",
"mtf",
".",
"Dimension",
"(",
"\"memory_block_length\"",
",",
"block_length",
")",
"# The num_blocks dimension gets the same name as the length dimension,",
"# so it will be split in the same way.",
"num_blocks",
"=",
"mtf",
".",
"Dimension",
"(",
"length_dim",
".",
"name",
",",
"length_dim",
".",
"size",
"//",
"block_length",
")",
"def",
"_reshape_query",
"(",
"x",
")",
":",
"return",
"mtf",
".",
"replace_dimensions",
"(",
"x",
",",
"length_dim",
",",
"[",
"num_blocks",
",",
"query_block_length",
"]",
")",
"def",
"_reshape_memory",
"(",
"x",
")",
":",
"x",
"=",
"mtf",
".",
"replace_dimensions",
"(",
"x",
",",
"length_dim",
",",
"[",
"num_blocks",
",",
"memory_block_length",
"]",
")",
"return",
"(",
"mtf",
".",
"left_halo_exchange",
"if",
"autoregressive",
"else",
"mtf",
".",
"halo_exchange",
")",
"(",
"x",
",",
"num_blocks",
",",
"memory_block_length",
",",
"radius",
")",
"q",
"=",
"_reshape_query",
"(",
"q",
")",
"k",
"=",
"_reshape_memory",
"(",
"k",
")",
"if",
"v",
":",
"v",
"=",
"_reshape_memory",
"(",
"v",
")",
"else",
":",
"v",
"=",
"k",
"if",
"sequence_id",
"is",
"None",
":",
"sequence_id",
"=",
"1",
"if",
"(",
"not",
"isinstance",
"(",
"sequence_id",
",",
"mtf",
".",
"Tensor",
")",
"or",
"length_dim",
"not",
"in",
"sequence_id",
".",
"shape",
".",
"dims",
")",
":",
"sequence_id",
"+=",
"mtf",
".",
"zeros",
"(",
"q",
".",
"mesh",
",",
"[",
"length_dim",
"]",
",",
"tf",
".",
"int32",
")",
"q_sequence_id",
"=",
"_reshape_query",
"(",
"sequence_id",
")",
"m_sequence_id",
"=",
"_reshape_memory",
"(",
"sequence_id",
")",
"pos",
"=",
"mtf",
".",
"range",
"(",
"q",
".",
"mesh",
",",
"length_dim",
",",
"dtype",
"=",
"tf",
".",
"int32",
")",
"q_pos",
"=",
"_reshape_query",
"(",
"pos",
")",
"m_pos",
"=",
"_reshape_memory",
"(",
"pos",
")",
"padded_memory_block_length",
"=",
"mtf",
".",
"Dimension",
"(",
"\"memory_block_length\"",
",",
"(",
"1",
"if",
"autoregressive",
"else",
"2",
")",
"*",
"radius",
"+",
"block_length",
")",
"relative_position",
"=",
"m_pos",
"-",
"q_pos",
"illegal",
"=",
"mtf",
".",
"not_equal",
"(",
"q_sequence_id",
",",
"m_sequence_id",
")",
"illegal",
"=",
"mtf",
".",
"logical_or",
"(",
"illegal",
",",
"mtf",
".",
"less_equal",
"(",
"relative_position",
",",
"-",
"radius",
")",
")",
"illegal",
"=",
"mtf",
".",
"logical_or",
"(",
"illegal",
",",
"mtf",
".",
"greater",
"(",
"relative_position",
",",
"0",
"if",
"autoregressive",
"else",
"radius",
")",
")",
"mask",
"=",
"mtf",
".",
"cast",
"(",
"illegal",
",",
"q",
".",
"dtype",
")",
"*",
"-",
"1e9",
"o",
"=",
"attention",
"(",
"q",
",",
"k",
",",
"v",
",",
"padded_memory_block_length",
",",
"key_dim",
",",
"value_dim",
",",
"mask",
",",
"*",
"*",
"attention_kwargs",
")",
"return",
"mtf",
".",
"replace_dimensions",
"(",
"o",
",",
"[",
"num_blocks",
",",
"query_block_length",
"]",
",",
"length_dim",
")"
] | Attention to the a neighborood around the source.
If autoregressive, then query position p can only see memory positions
in the range (p - radius, p].
If not autoregressive, then query position p can only see memory positions
in the range (p - window_size, p + radius].
Args:
q: a Tensor containing length_dim
k: a Tensor containing length_dim
v: an optional Tensor containing length_dim. If none then uses v=k.
length_dim: a Dimension
key_dim: a Dimension (the channels dimension of q and k)
value_dim: a Dimension (the channels dimension of v)
autoregressive: a boolean
length_dim_num_splits: an optional integer indicating how many ways the
length dimension is split
radius: an integer
sequence_id: a Tensor or an integer
attention_kwargs: optional keyword arguments for attention()
Returns:
a Tensor with the shape x.shape - key_dim + value_dim
Raises:
ValueError: if channels or depth don't match. | [
"Attention",
"to",
"the",
"a",
"neighborood",
"around",
"the",
"source",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/attention.py#L289-L377 |
227,818 | tensorflow/mesh | mesh_tensorflow/transformer/attention.py | AttentionParams.compute_q | def compute_q(self, query_antecedent):
"""Compute query Tensor q.
Args:
query_antecedent: a Tensor with dimensions
{query_input_dim} + other_dims
Returns:
a Tensor with dimensions
query_heads_dims + {key_dim} + other_dims
"""
ret = mtf.einsum(
[query_antecedent, self.wq], reduced_dims=[self.query_input_dim])
if self.combine_dims:
ret = mtf.replace_dimensions(ret, ret.shape.dims[-1], self.q_dims)
return ret | python | def compute_q(self, query_antecedent):
"""Compute query Tensor q.
Args:
query_antecedent: a Tensor with dimensions
{query_input_dim} + other_dims
Returns:
a Tensor with dimensions
query_heads_dims + {key_dim} + other_dims
"""
ret = mtf.einsum(
[query_antecedent, self.wq], reduced_dims=[self.query_input_dim])
if self.combine_dims:
ret = mtf.replace_dimensions(ret, ret.shape.dims[-1], self.q_dims)
return ret | [
"def",
"compute_q",
"(",
"self",
",",
"query_antecedent",
")",
":",
"ret",
"=",
"mtf",
".",
"einsum",
"(",
"[",
"query_antecedent",
",",
"self",
".",
"wq",
"]",
",",
"reduced_dims",
"=",
"[",
"self",
".",
"query_input_dim",
"]",
")",
"if",
"self",
".",
"combine_dims",
":",
"ret",
"=",
"mtf",
".",
"replace_dimensions",
"(",
"ret",
",",
"ret",
".",
"shape",
".",
"dims",
"[",
"-",
"1",
"]",
",",
"self",
".",
"q_dims",
")",
"return",
"ret"
] | Compute query Tensor q.
Args:
query_antecedent: a Tensor with dimensions
{query_input_dim} + other_dims
Returns:
a Tensor with dimensions
query_heads_dims + {key_dim} + other_dims | [
"Compute",
"query",
"Tensor",
"q",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/attention.py#L153-L167 |
227,819 | tensorflow/mesh | mesh_tensorflow/transformer/attention.py | AttentionParams.compute_k | def compute_k(self, memory_antecedent):
"""Compute key Tensor k.
Args:
memory_antecedent: a Tensor with dimensions
{memory_input_dim} + other_dims
Returns:
a Tensor with dimensions
memory_heads_dims + {key_dim} + other_dims
"""
if self.shared_kv:
raise ValueError("compute_k cannot be called with shared_kv")
ret = mtf.einsum(
[memory_antecedent, self.wk], reduced_dims=[self.memory_input_dim])
if self.combine_dims:
ret = mtf.replace_dimensions(ret, ret.shape.dims[-1], self.k_dims)
return ret | python | def compute_k(self, memory_antecedent):
"""Compute key Tensor k.
Args:
memory_antecedent: a Tensor with dimensions
{memory_input_dim} + other_dims
Returns:
a Tensor with dimensions
memory_heads_dims + {key_dim} + other_dims
"""
if self.shared_kv:
raise ValueError("compute_k cannot be called with shared_kv")
ret = mtf.einsum(
[memory_antecedent, self.wk], reduced_dims=[self.memory_input_dim])
if self.combine_dims:
ret = mtf.replace_dimensions(ret, ret.shape.dims[-1], self.k_dims)
return ret | [
"def",
"compute_k",
"(",
"self",
",",
"memory_antecedent",
")",
":",
"if",
"self",
".",
"shared_kv",
":",
"raise",
"ValueError",
"(",
"\"compute_k cannot be called with shared_kv\"",
")",
"ret",
"=",
"mtf",
".",
"einsum",
"(",
"[",
"memory_antecedent",
",",
"self",
".",
"wk",
"]",
",",
"reduced_dims",
"=",
"[",
"self",
".",
"memory_input_dim",
"]",
")",
"if",
"self",
".",
"combine_dims",
":",
"ret",
"=",
"mtf",
".",
"replace_dimensions",
"(",
"ret",
",",
"ret",
".",
"shape",
".",
"dims",
"[",
"-",
"1",
"]",
",",
"self",
".",
"k_dims",
")",
"return",
"ret"
] | Compute key Tensor k.
Args:
memory_antecedent: a Tensor with dimensions
{memory_input_dim} + other_dims
Returns:
a Tensor with dimensions
memory_heads_dims + {key_dim} + other_dims | [
"Compute",
"key",
"Tensor",
"k",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/attention.py#L187-L203 |
227,820 | tensorflow/mesh | mesh_tensorflow/transformer/attention.py | AttentionParams.compute_v | def compute_v(self, memory_antecedent):
"""Compute value Tensor v.
Args:
memory_antecedent: a Tensor with dimensions
{memory_input_dim} + other_dims
Returns:
a Tensor with dimensions
memory_heads_dims + {value_dim} + other_dims
"""
if self.shared_kv:
raise ValueError("compute_v cannot be called with shared_kv")
ret = mtf.einsum(
[memory_antecedent, self.wv], reduced_dims=[self.memory_input_dim])
if self.combine_dims:
ret = mtf.replace_dimensions(ret, ret.shape.dims[-1], self.v_dims)
return ret | python | def compute_v(self, memory_antecedent):
"""Compute value Tensor v.
Args:
memory_antecedent: a Tensor with dimensions
{memory_input_dim} + other_dims
Returns:
a Tensor with dimensions
memory_heads_dims + {value_dim} + other_dims
"""
if self.shared_kv:
raise ValueError("compute_v cannot be called with shared_kv")
ret = mtf.einsum(
[memory_antecedent, self.wv], reduced_dims=[self.memory_input_dim])
if self.combine_dims:
ret = mtf.replace_dimensions(ret, ret.shape.dims[-1], self.v_dims)
return ret | [
"def",
"compute_v",
"(",
"self",
",",
"memory_antecedent",
")",
":",
"if",
"self",
".",
"shared_kv",
":",
"raise",
"ValueError",
"(",
"\"compute_v cannot be called with shared_kv\"",
")",
"ret",
"=",
"mtf",
".",
"einsum",
"(",
"[",
"memory_antecedent",
",",
"self",
".",
"wv",
"]",
",",
"reduced_dims",
"=",
"[",
"self",
".",
"memory_input_dim",
"]",
")",
"if",
"self",
".",
"combine_dims",
":",
"ret",
"=",
"mtf",
".",
"replace_dimensions",
"(",
"ret",
",",
"ret",
".",
"shape",
".",
"dims",
"[",
"-",
"1",
"]",
",",
"self",
".",
"v_dims",
")",
"return",
"ret"
] | Compute value Tensor v.
Args:
memory_antecedent: a Tensor with dimensions
{memory_input_dim} + other_dims
Returns:
a Tensor with dimensions
memory_heads_dims + {value_dim} + other_dims | [
"Compute",
"value",
"Tensor",
"v",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/attention.py#L205-L221 |
227,821 | tensorflow/mesh | mesh_tensorflow/transformer/attention.py | AttentionParams.compute_output | def compute_output(self, o, output_shape=None):
"""Compute output of multihead attention.
Args:
o: a Tensor with dimensions
query_heads_dims + {value_dim} + other_dims
output_shape: an optional Shape
Returns:
a Tensor with shape:
{output_dim} + other_dims
"""
if self.combine_dims:
o = mtf.transpose(o, o.shape - self.o_dims + self.o_dims)
o = mtf.replace_dimensions(o, self.o_dims, self.wo.shape.dims[0])
reduced_dims = [self.wo.shape.dims[0]]
else:
reduced_dims = self.o_dims
return mtf.einsum(
[o, self.wo], output_shape=output_shape, reduced_dims=reduced_dims) | python | def compute_output(self, o, output_shape=None):
"""Compute output of multihead attention.
Args:
o: a Tensor with dimensions
query_heads_dims + {value_dim} + other_dims
output_shape: an optional Shape
Returns:
a Tensor with shape:
{output_dim} + other_dims
"""
if self.combine_dims:
o = mtf.transpose(o, o.shape - self.o_dims + self.o_dims)
o = mtf.replace_dimensions(o, self.o_dims, self.wo.shape.dims[0])
reduced_dims = [self.wo.shape.dims[0]]
else:
reduced_dims = self.o_dims
return mtf.einsum(
[o, self.wo], output_shape=output_shape, reduced_dims=reduced_dims) | [
"def",
"compute_output",
"(",
"self",
",",
"o",
",",
"output_shape",
"=",
"None",
")",
":",
"if",
"self",
".",
"combine_dims",
":",
"o",
"=",
"mtf",
".",
"transpose",
"(",
"o",
",",
"o",
".",
"shape",
"-",
"self",
".",
"o_dims",
"+",
"self",
".",
"o_dims",
")",
"o",
"=",
"mtf",
".",
"replace_dimensions",
"(",
"o",
",",
"self",
".",
"o_dims",
",",
"self",
".",
"wo",
".",
"shape",
".",
"dims",
"[",
"0",
"]",
")",
"reduced_dims",
"=",
"[",
"self",
".",
"wo",
".",
"shape",
".",
"dims",
"[",
"0",
"]",
"]",
"else",
":",
"reduced_dims",
"=",
"self",
".",
"o_dims",
"return",
"mtf",
".",
"einsum",
"(",
"[",
"o",
",",
"self",
".",
"wo",
"]",
",",
"output_shape",
"=",
"output_shape",
",",
"reduced_dims",
"=",
"reduced_dims",
")"
] | Compute output of multihead attention.
Args:
o: a Tensor with dimensions
query_heads_dims + {value_dim} + other_dims
output_shape: an optional Shape
Returns:
a Tensor with shape:
{output_dim} + other_dims | [
"Compute",
"output",
"of",
"multihead",
"attention",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/attention.py#L223-L241 |
227,822 | tensorflow/mesh | mesh_tensorflow/transformer/t2t_vocabulary.py | T2tVocabulary.encode_tf | def encode_tf(self, s):
"""Encode a tf.Scalar string to a tf.Tensor.
This will be necessary for on-the-fly tokenization.
Args:
s: a tf.Scalar with dtype tf.string
Returns:
a 1d tf.Tensor with dtype tf.int32
"""
ids = subword_text_encoder_ops.subword_text_encoder_encode(
s, self._filepath)
# the c++ op apppends 1=EOS - drop it.
return ids[:-1] | python | def encode_tf(self, s):
"""Encode a tf.Scalar string to a tf.Tensor.
This will be necessary for on-the-fly tokenization.
Args:
s: a tf.Scalar with dtype tf.string
Returns:
a 1d tf.Tensor with dtype tf.int32
"""
ids = subword_text_encoder_ops.subword_text_encoder_encode(
s, self._filepath)
# the c++ op apppends 1=EOS - drop it.
return ids[:-1] | [
"def",
"encode_tf",
"(",
"self",
",",
"s",
")",
":",
"ids",
"=",
"subword_text_encoder_ops",
".",
"subword_text_encoder_encode",
"(",
"s",
",",
"self",
".",
"_filepath",
")",
"# the c++ op apppends 1=EOS - drop it.",
"return",
"ids",
"[",
":",
"-",
"1",
"]"
] | Encode a tf.Scalar string to a tf.Tensor.
This will be necessary for on-the-fly tokenization.
Args:
s: a tf.Scalar with dtype tf.string
Returns:
a 1d tf.Tensor with dtype tf.int32 | [
"Encode",
"a",
"tf",
".",
"Scalar",
"string",
"to",
"a",
"tf",
".",
"Tensor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/t2t_vocabulary.py#L79-L92 |
227,823 | tensorflow/mesh | mesh_tensorflow/transformer/model_builder.py | simple_layer_stack | def simple_layer_stack(include_encdec_attention,
num_layers=6,
d_ff=2048,
num_heads=8,
d_kv=128,
dropout_rate=0.1):
"""Create a layer stack.
Args:
include_encdec_attention: a boolean
num_layers: an integer
d_ff: an integer
num_heads: an integer
d_kv: an integer
dropout_rate: a float
Returns:
a LayerStack
"""
ret = []
for _ in xrange(num_layers):
ret.append(
transformer_layers.SelfAttention(
num_heads=num_heads,
key_value_size=d_kv,
attention_kwargs={"dropout_rate": dropout_rate}))
if include_encdec_attention:
ret.append(
transformer_layers.EncDecAttention(
num_heads=num_heads,
key_value_size=d_kv,
attention_kwargs={"dropout_rate": dropout_rate}))
ret.append(
transformer_layers.DenseReluDense(
hidden_size=d_ff,
dropout_rate=dropout_rate))
return transformer.LayerStack(ret) | python | def simple_layer_stack(include_encdec_attention,
num_layers=6,
d_ff=2048,
num_heads=8,
d_kv=128,
dropout_rate=0.1):
"""Create a layer stack.
Args:
include_encdec_attention: a boolean
num_layers: an integer
d_ff: an integer
num_heads: an integer
d_kv: an integer
dropout_rate: a float
Returns:
a LayerStack
"""
ret = []
for _ in xrange(num_layers):
ret.append(
transformer_layers.SelfAttention(
num_heads=num_heads,
key_value_size=d_kv,
attention_kwargs={"dropout_rate": dropout_rate}))
if include_encdec_attention:
ret.append(
transformer_layers.EncDecAttention(
num_heads=num_heads,
key_value_size=d_kv,
attention_kwargs={"dropout_rate": dropout_rate}))
ret.append(
transformer_layers.DenseReluDense(
hidden_size=d_ff,
dropout_rate=dropout_rate))
return transformer.LayerStack(ret) | [
"def",
"simple_layer_stack",
"(",
"include_encdec_attention",
",",
"num_layers",
"=",
"6",
",",
"d_ff",
"=",
"2048",
",",
"num_heads",
"=",
"8",
",",
"d_kv",
"=",
"128",
",",
"dropout_rate",
"=",
"0.1",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"_",
"in",
"xrange",
"(",
"num_layers",
")",
":",
"ret",
".",
"append",
"(",
"transformer_layers",
".",
"SelfAttention",
"(",
"num_heads",
"=",
"num_heads",
",",
"key_value_size",
"=",
"d_kv",
",",
"attention_kwargs",
"=",
"{",
"\"dropout_rate\"",
":",
"dropout_rate",
"}",
")",
")",
"if",
"include_encdec_attention",
":",
"ret",
".",
"append",
"(",
"transformer_layers",
".",
"EncDecAttention",
"(",
"num_heads",
"=",
"num_heads",
",",
"key_value_size",
"=",
"d_kv",
",",
"attention_kwargs",
"=",
"{",
"\"dropout_rate\"",
":",
"dropout_rate",
"}",
")",
")",
"ret",
".",
"append",
"(",
"transformer_layers",
".",
"DenseReluDense",
"(",
"hidden_size",
"=",
"d_ff",
",",
"dropout_rate",
"=",
"dropout_rate",
")",
")",
"return",
"transformer",
".",
"LayerStack",
"(",
"ret",
")"
] | Create a layer stack.
Args:
include_encdec_attention: a boolean
num_layers: an integer
d_ff: an integer
num_heads: an integer
d_kv: an integer
dropout_rate: a float
Returns:
a LayerStack | [
"Create",
"a",
"layer",
"stack",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/model_builder.py#L30-L66 |
227,824 | tensorflow/mesh | examples/toy_model_tpu.py | toy_model | def toy_model(features, mesh):
"""A toy model implemented by mesh tensorlfow."""
batch_dim = mtf.Dimension('batch', FLAGS.batch_size)
io_dim = mtf.Dimension('io', FLAGS.io_size)
master_dtype = tf.as_dtype(FLAGS.master_dtype)
slice_dtype = tf.as_dtype(FLAGS.slice_dtype)
activation_dtype = tf.as_dtype(FLAGS.activation_dtype)
x = mtf.import_tf_tensor(mesh, features, mtf.Shape([batch_dim, io_dim]))
x = mtf.cast(x, activation_dtype)
h = x
for lnum in xrange(1, FLAGS.num_hidden_layers + 2):
if lnum + 1 == FLAGS.num_hidden_layers + 2:
# output layer
dim = io_dim
elif lnum % 2 == 0:
dim = mtf.Dimension('hidden_even', FLAGS.hidden_size)
else:
dim = mtf.Dimension('hidden_odd', FLAGS.hidden_size)
h = mtf.layers.dense(
h, dim,
use_bias=False,
master_dtype=master_dtype,
slice_dtype=slice_dtype,
name='layer_%d' % lnum)
y = h
g = tf.train.get_global_step()
if FLAGS.step_with_nan >= 0:
# Trigger NaN in the forward pass, this is used for testing whether
# MeshTensorFlow can handle occasional NaN value.
y += mtf.import_tf_tensor(
mesh,
tf.divide(
0.0,
tf.cond(tf.equal(g, FLAGS.step_with_nan), lambda: 0., lambda: 1.)),
mtf.Shape([]))
loss = mtf.reduce_mean(mtf.square(y - x))
return y, loss | python | def toy_model(features, mesh):
"""A toy model implemented by mesh tensorlfow."""
batch_dim = mtf.Dimension('batch', FLAGS.batch_size)
io_dim = mtf.Dimension('io', FLAGS.io_size)
master_dtype = tf.as_dtype(FLAGS.master_dtype)
slice_dtype = tf.as_dtype(FLAGS.slice_dtype)
activation_dtype = tf.as_dtype(FLAGS.activation_dtype)
x = mtf.import_tf_tensor(mesh, features, mtf.Shape([batch_dim, io_dim]))
x = mtf.cast(x, activation_dtype)
h = x
for lnum in xrange(1, FLAGS.num_hidden_layers + 2):
if lnum + 1 == FLAGS.num_hidden_layers + 2:
# output layer
dim = io_dim
elif lnum % 2 == 0:
dim = mtf.Dimension('hidden_even', FLAGS.hidden_size)
else:
dim = mtf.Dimension('hidden_odd', FLAGS.hidden_size)
h = mtf.layers.dense(
h, dim,
use_bias=False,
master_dtype=master_dtype,
slice_dtype=slice_dtype,
name='layer_%d' % lnum)
y = h
g = tf.train.get_global_step()
if FLAGS.step_with_nan >= 0:
# Trigger NaN in the forward pass, this is used for testing whether
# MeshTensorFlow can handle occasional NaN value.
y += mtf.import_tf_tensor(
mesh,
tf.divide(
0.0,
tf.cond(tf.equal(g, FLAGS.step_with_nan), lambda: 0., lambda: 1.)),
mtf.Shape([]))
loss = mtf.reduce_mean(mtf.square(y - x))
return y, loss | [
"def",
"toy_model",
"(",
"features",
",",
"mesh",
")",
":",
"batch_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"'batch'",
",",
"FLAGS",
".",
"batch_size",
")",
"io_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"'io'",
",",
"FLAGS",
".",
"io_size",
")",
"master_dtype",
"=",
"tf",
".",
"as_dtype",
"(",
"FLAGS",
".",
"master_dtype",
")",
"slice_dtype",
"=",
"tf",
".",
"as_dtype",
"(",
"FLAGS",
".",
"slice_dtype",
")",
"activation_dtype",
"=",
"tf",
".",
"as_dtype",
"(",
"FLAGS",
".",
"activation_dtype",
")",
"x",
"=",
"mtf",
".",
"import_tf_tensor",
"(",
"mesh",
",",
"features",
",",
"mtf",
".",
"Shape",
"(",
"[",
"batch_dim",
",",
"io_dim",
"]",
")",
")",
"x",
"=",
"mtf",
".",
"cast",
"(",
"x",
",",
"activation_dtype",
")",
"h",
"=",
"x",
"for",
"lnum",
"in",
"xrange",
"(",
"1",
",",
"FLAGS",
".",
"num_hidden_layers",
"+",
"2",
")",
":",
"if",
"lnum",
"+",
"1",
"==",
"FLAGS",
".",
"num_hidden_layers",
"+",
"2",
":",
"# output layer",
"dim",
"=",
"io_dim",
"elif",
"lnum",
"%",
"2",
"==",
"0",
":",
"dim",
"=",
"mtf",
".",
"Dimension",
"(",
"'hidden_even'",
",",
"FLAGS",
".",
"hidden_size",
")",
"else",
":",
"dim",
"=",
"mtf",
".",
"Dimension",
"(",
"'hidden_odd'",
",",
"FLAGS",
".",
"hidden_size",
")",
"h",
"=",
"mtf",
".",
"layers",
".",
"dense",
"(",
"h",
",",
"dim",
",",
"use_bias",
"=",
"False",
",",
"master_dtype",
"=",
"master_dtype",
",",
"slice_dtype",
"=",
"slice_dtype",
",",
"name",
"=",
"'layer_%d'",
"%",
"lnum",
")",
"y",
"=",
"h",
"g",
"=",
"tf",
".",
"train",
".",
"get_global_step",
"(",
")",
"if",
"FLAGS",
".",
"step_with_nan",
">=",
"0",
":",
"# Trigger NaN in the forward pass, this is used for testing whether",
"# MeshTensorFlow can handle occasional NaN value.",
"y",
"+=",
"mtf",
".",
"import_tf_tensor",
"(",
"mesh",
",",
"tf",
".",
"divide",
"(",
"0.0",
",",
"tf",
".",
"cond",
"(",
"tf",
".",
"equal",
"(",
"g",
",",
"FLAGS",
".",
"step_with_nan",
")",
",",
"lambda",
":",
"0.",
",",
"lambda",
":",
"1.",
")",
")",
",",
"mtf",
".",
"Shape",
"(",
"[",
"]",
")",
")",
"loss",
"=",
"mtf",
".",
"reduce_mean",
"(",
"mtf",
".",
"square",
"(",
"y",
"-",
"x",
")",
")",
"return",
"y",
",",
"loss"
] | A toy model implemented by mesh tensorlfow. | [
"A",
"toy",
"model",
"implemented",
"by",
"mesh",
"tensorlfow",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/toy_model_tpu.py#L103-L142 |
227,825 | tensorflow/mesh | examples/toy_model_tpu.py | run_toy_model_tpu | def run_toy_model_tpu():
"""Run a toy model on TPU."""
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
iterations_per_loop = FLAGS.iterations
mesh_shape = mtf.convert_to_shape(FLAGS.mesh_shape)
config = tpu_config.RunConfig(
cluster=tpu_cluster_resolver,
model_dir=FLAGS.model_dir,
save_checkpoints_steps=None, # Disable the default saver
save_checkpoints_secs=None, # Disable the default saver
log_step_count_steps=iterations_per_loop,
save_summary_steps=iterations_per_loop,
tpu_config=tpu_config.TPUConfig(
num_shards=mesh_shape.size,
iterations_per_loop=iterations_per_loop,
num_cores_per_replica=1,
per_host_input_for_training=tpu_config.InputPipelineConfig.BROADCAST))
classifier = tpu_estimator.TPUEstimator(
use_tpu=True,
model_fn=model_fn,
config=config,
train_batch_size=FLAGS.batch_size,
eval_batch_size=FLAGS.batch_size)
current_step = estimator_lib._load_global_step_from_checkpoint_dir(FLAGS.model_dir) # pylint: disable=protected-access,line-too-long
logging.info('Current step %d', current_step)
if FLAGS.steps_per_checkpoint == 0:
classifier.train(input_fn=ToyModelInput(), max_steps=FLAGS.train_steps)
return
while current_step < FLAGS.train_steps:
next_checkpoint = min(current_step + FLAGS.steps_per_checkpoint,
FLAGS.train_steps)
classifier.train(input_fn=ToyModelInput(), max_steps=next_checkpoint)
current_step = next_checkpoint
logging.info('Starting to evaluate.')
eval_results = classifier.evaluate(
input_fn=ToyModelInput(),
steps=156) # since we have 10000 examples and batch_size = 64 per host
logging.info('Eval results: %s', eval_results) | python | def run_toy_model_tpu():
"""Run a toy model on TPU."""
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
iterations_per_loop = FLAGS.iterations
mesh_shape = mtf.convert_to_shape(FLAGS.mesh_shape)
config = tpu_config.RunConfig(
cluster=tpu_cluster_resolver,
model_dir=FLAGS.model_dir,
save_checkpoints_steps=None, # Disable the default saver
save_checkpoints_secs=None, # Disable the default saver
log_step_count_steps=iterations_per_loop,
save_summary_steps=iterations_per_loop,
tpu_config=tpu_config.TPUConfig(
num_shards=mesh_shape.size,
iterations_per_loop=iterations_per_loop,
num_cores_per_replica=1,
per_host_input_for_training=tpu_config.InputPipelineConfig.BROADCAST))
classifier = tpu_estimator.TPUEstimator(
use_tpu=True,
model_fn=model_fn,
config=config,
train_batch_size=FLAGS.batch_size,
eval_batch_size=FLAGS.batch_size)
current_step = estimator_lib._load_global_step_from_checkpoint_dir(FLAGS.model_dir) # pylint: disable=protected-access,line-too-long
logging.info('Current step %d', current_step)
if FLAGS.steps_per_checkpoint == 0:
classifier.train(input_fn=ToyModelInput(), max_steps=FLAGS.train_steps)
return
while current_step < FLAGS.train_steps:
next_checkpoint = min(current_step + FLAGS.steps_per_checkpoint,
FLAGS.train_steps)
classifier.train(input_fn=ToyModelInput(), max_steps=next_checkpoint)
current_step = next_checkpoint
logging.info('Starting to evaluate.')
eval_results = classifier.evaluate(
input_fn=ToyModelInput(),
steps=156) # since we have 10000 examples and batch_size = 64 per host
logging.info('Eval results: %s', eval_results) | [
"def",
"run_toy_model_tpu",
"(",
")",
":",
"tpu_cluster_resolver",
"=",
"tf",
".",
"contrib",
".",
"cluster_resolver",
".",
"TPUClusterResolver",
"(",
"FLAGS",
".",
"tpu",
",",
"zone",
"=",
"FLAGS",
".",
"tpu_zone",
",",
"project",
"=",
"FLAGS",
".",
"gcp_project",
")",
"iterations_per_loop",
"=",
"FLAGS",
".",
"iterations",
"mesh_shape",
"=",
"mtf",
".",
"convert_to_shape",
"(",
"FLAGS",
".",
"mesh_shape",
")",
"config",
"=",
"tpu_config",
".",
"RunConfig",
"(",
"cluster",
"=",
"tpu_cluster_resolver",
",",
"model_dir",
"=",
"FLAGS",
".",
"model_dir",
",",
"save_checkpoints_steps",
"=",
"None",
",",
"# Disable the default saver",
"save_checkpoints_secs",
"=",
"None",
",",
"# Disable the default saver",
"log_step_count_steps",
"=",
"iterations_per_loop",
",",
"save_summary_steps",
"=",
"iterations_per_loop",
",",
"tpu_config",
"=",
"tpu_config",
".",
"TPUConfig",
"(",
"num_shards",
"=",
"mesh_shape",
".",
"size",
",",
"iterations_per_loop",
"=",
"iterations_per_loop",
",",
"num_cores_per_replica",
"=",
"1",
",",
"per_host_input_for_training",
"=",
"tpu_config",
".",
"InputPipelineConfig",
".",
"BROADCAST",
")",
")",
"classifier",
"=",
"tpu_estimator",
".",
"TPUEstimator",
"(",
"use_tpu",
"=",
"True",
",",
"model_fn",
"=",
"model_fn",
",",
"config",
"=",
"config",
",",
"train_batch_size",
"=",
"FLAGS",
".",
"batch_size",
",",
"eval_batch_size",
"=",
"FLAGS",
".",
"batch_size",
")",
"current_step",
"=",
"estimator_lib",
".",
"_load_global_step_from_checkpoint_dir",
"(",
"FLAGS",
".",
"model_dir",
")",
"# pylint: disable=protected-access,line-too-long",
"logging",
".",
"info",
"(",
"'Current step %d'",
",",
"current_step",
")",
"if",
"FLAGS",
".",
"steps_per_checkpoint",
"==",
"0",
":",
"classifier",
".",
"train",
"(",
"input_fn",
"=",
"ToyModelInput",
"(",
")",
",",
"max_steps",
"=",
"FLAGS",
".",
"train_steps",
")",
"return",
"while",
"current_step",
"<",
"FLAGS",
".",
"train_steps",
":",
"next_checkpoint",
"=",
"min",
"(",
"current_step",
"+",
"FLAGS",
".",
"steps_per_checkpoint",
",",
"FLAGS",
".",
"train_steps",
")",
"classifier",
".",
"train",
"(",
"input_fn",
"=",
"ToyModelInput",
"(",
")",
",",
"max_steps",
"=",
"next_checkpoint",
")",
"current_step",
"=",
"next_checkpoint",
"logging",
".",
"info",
"(",
"'Starting to evaluate.'",
")",
"eval_results",
"=",
"classifier",
".",
"evaluate",
"(",
"input_fn",
"=",
"ToyModelInput",
"(",
")",
",",
"steps",
"=",
"156",
")",
"# since we have 10000 examples and batch_size = 64 per host",
"logging",
".",
"info",
"(",
"'Eval results: %s'",
",",
"eval_results",
")"
] | Run a toy model on TPU. | [
"Run",
"a",
"toy",
"model",
"on",
"TPU",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/toy_model_tpu.py#L243-L282 |
227,826 | tensorflow/mesh | examples/mnist.py | mnist_model | def mnist_model(image, labels, mesh):
"""The model.
Args:
image: tf.Tensor with shape [batch, 28*28]
labels: a tf.Tensor with shape [batch] and dtype tf.int32
mesh: a mtf.Mesh
Returns:
logits: a mtf.Tensor with shape [batch, 10]
loss: a mtf.Tensor with shape []
"""
batch_dim = mtf.Dimension("batch", FLAGS.batch_size)
row_blocks_dim = mtf.Dimension("row_blocks", 4)
col_blocks_dim = mtf.Dimension("col_blocks", 4)
rows_dim = mtf.Dimension("rows_size", 7)
cols_dim = mtf.Dimension("cols_size", 7)
classes_dim = mtf.Dimension("classes", 10)
one_channel_dim = mtf.Dimension("one_channel", 1)
x = mtf.import_tf_tensor(
mesh, tf.reshape(image, [FLAGS.batch_size, 4, 7, 4, 7, 1]),
mtf.Shape(
[batch_dim, row_blocks_dim, rows_dim,
col_blocks_dim, cols_dim, one_channel_dim]))
x = mtf.transpose(x, [
batch_dim, row_blocks_dim, col_blocks_dim,
rows_dim, cols_dim, one_channel_dim])
# add some convolutional layers to demonstrate that convolution works.
fh_dim = mtf.Dimension("fh", 9)
fw_dim = mtf.Dimension("fw", 9)
filters1_dim = mtf.Dimension("filters1", 16)
filters2_dim = mtf.Dimension("filters2", 16)
kernel1 = mtf.get_variable(
mesh, "kernel1", [fh_dim, fw_dim, one_channel_dim, filters1_dim])
kernel2 = mtf.get_variable(
mesh, "kernel2", [fh_dim, fw_dim, filters1_dim, filters2_dim])
f1 = mtf.relu(mtf.conv2d_with_blocks(
x, kernel1, strides=[1, 1, 1, 1], padding="SAME",
h_blocks_dim=row_blocks_dim, w_blocks_dim=col_blocks_dim))
f2 = mtf.relu(mtf.conv2d_with_blocks(
f1, kernel2, strides=[1, 1, 1, 1], padding="SAME",
h_blocks_dim=row_blocks_dim, w_blocks_dim=col_blocks_dim))
x = mtf.reduce_mean(f2, reduced_dim=filters2_dim)
# add some fully-connected dense layers.
hidden_dim1 = mtf.Dimension("hidden1", FLAGS.hidden_size)
hidden_dim2 = mtf.Dimension("hidden2", FLAGS.hidden_size)
h1 = mtf.layers.dense(
x, hidden_dim1,
reduced_dims=x.shape.dims[-4:],
activation=mtf.relu, name="hidden1")
h2 = mtf.layers.dense(
h1, hidden_dim2,
activation=mtf.relu, name="hidden2")
logits = mtf.layers.dense(h2, classes_dim, name="logits")
if labels is None:
loss = None
else:
labels = mtf.import_tf_tensor(
mesh, tf.reshape(labels, [FLAGS.batch_size]), mtf.Shape([batch_dim]))
loss = mtf.layers.softmax_cross_entropy_with_logits(
logits, mtf.one_hot(labels, classes_dim), classes_dim)
loss = mtf.reduce_mean(loss)
return logits, loss | python | def mnist_model(image, labels, mesh):
"""The model.
Args:
image: tf.Tensor with shape [batch, 28*28]
labels: a tf.Tensor with shape [batch] and dtype tf.int32
mesh: a mtf.Mesh
Returns:
logits: a mtf.Tensor with shape [batch, 10]
loss: a mtf.Tensor with shape []
"""
batch_dim = mtf.Dimension("batch", FLAGS.batch_size)
row_blocks_dim = mtf.Dimension("row_blocks", 4)
col_blocks_dim = mtf.Dimension("col_blocks", 4)
rows_dim = mtf.Dimension("rows_size", 7)
cols_dim = mtf.Dimension("cols_size", 7)
classes_dim = mtf.Dimension("classes", 10)
one_channel_dim = mtf.Dimension("one_channel", 1)
x = mtf.import_tf_tensor(
mesh, tf.reshape(image, [FLAGS.batch_size, 4, 7, 4, 7, 1]),
mtf.Shape(
[batch_dim, row_blocks_dim, rows_dim,
col_blocks_dim, cols_dim, one_channel_dim]))
x = mtf.transpose(x, [
batch_dim, row_blocks_dim, col_blocks_dim,
rows_dim, cols_dim, one_channel_dim])
# add some convolutional layers to demonstrate that convolution works.
fh_dim = mtf.Dimension("fh", 9)
fw_dim = mtf.Dimension("fw", 9)
filters1_dim = mtf.Dimension("filters1", 16)
filters2_dim = mtf.Dimension("filters2", 16)
kernel1 = mtf.get_variable(
mesh, "kernel1", [fh_dim, fw_dim, one_channel_dim, filters1_dim])
kernel2 = mtf.get_variable(
mesh, "kernel2", [fh_dim, fw_dim, filters1_dim, filters2_dim])
f1 = mtf.relu(mtf.conv2d_with_blocks(
x, kernel1, strides=[1, 1, 1, 1], padding="SAME",
h_blocks_dim=row_blocks_dim, w_blocks_dim=col_blocks_dim))
f2 = mtf.relu(mtf.conv2d_with_blocks(
f1, kernel2, strides=[1, 1, 1, 1], padding="SAME",
h_blocks_dim=row_blocks_dim, w_blocks_dim=col_blocks_dim))
x = mtf.reduce_mean(f2, reduced_dim=filters2_dim)
# add some fully-connected dense layers.
hidden_dim1 = mtf.Dimension("hidden1", FLAGS.hidden_size)
hidden_dim2 = mtf.Dimension("hidden2", FLAGS.hidden_size)
h1 = mtf.layers.dense(
x, hidden_dim1,
reduced_dims=x.shape.dims[-4:],
activation=mtf.relu, name="hidden1")
h2 = mtf.layers.dense(
h1, hidden_dim2,
activation=mtf.relu, name="hidden2")
logits = mtf.layers.dense(h2, classes_dim, name="logits")
if labels is None:
loss = None
else:
labels = mtf.import_tf_tensor(
mesh, tf.reshape(labels, [FLAGS.batch_size]), mtf.Shape([batch_dim]))
loss = mtf.layers.softmax_cross_entropy_with_logits(
logits, mtf.one_hot(labels, classes_dim), classes_dim)
loss = mtf.reduce_mean(loss)
return logits, loss | [
"def",
"mnist_model",
"(",
"image",
",",
"labels",
",",
"mesh",
")",
":",
"batch_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"\"batch\"",
",",
"FLAGS",
".",
"batch_size",
")",
"row_blocks_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"\"row_blocks\"",
",",
"4",
")",
"col_blocks_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"\"col_blocks\"",
",",
"4",
")",
"rows_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"\"rows_size\"",
",",
"7",
")",
"cols_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"\"cols_size\"",
",",
"7",
")",
"classes_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"\"classes\"",
",",
"10",
")",
"one_channel_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"\"one_channel\"",
",",
"1",
")",
"x",
"=",
"mtf",
".",
"import_tf_tensor",
"(",
"mesh",
",",
"tf",
".",
"reshape",
"(",
"image",
",",
"[",
"FLAGS",
".",
"batch_size",
",",
"4",
",",
"7",
",",
"4",
",",
"7",
",",
"1",
"]",
")",
",",
"mtf",
".",
"Shape",
"(",
"[",
"batch_dim",
",",
"row_blocks_dim",
",",
"rows_dim",
",",
"col_blocks_dim",
",",
"cols_dim",
",",
"one_channel_dim",
"]",
")",
")",
"x",
"=",
"mtf",
".",
"transpose",
"(",
"x",
",",
"[",
"batch_dim",
",",
"row_blocks_dim",
",",
"col_blocks_dim",
",",
"rows_dim",
",",
"cols_dim",
",",
"one_channel_dim",
"]",
")",
"# add some convolutional layers to demonstrate that convolution works.",
"fh_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"\"fh\"",
",",
"9",
")",
"fw_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"\"fw\"",
",",
"9",
")",
"filters1_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"\"filters1\"",
",",
"16",
")",
"filters2_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"\"filters2\"",
",",
"16",
")",
"kernel1",
"=",
"mtf",
".",
"get_variable",
"(",
"mesh",
",",
"\"kernel1\"",
",",
"[",
"fh_dim",
",",
"fw_dim",
",",
"one_channel_dim",
",",
"filters1_dim",
"]",
")",
"kernel2",
"=",
"mtf",
".",
"get_variable",
"(",
"mesh",
",",
"\"kernel2\"",
",",
"[",
"fh_dim",
",",
"fw_dim",
",",
"filters1_dim",
",",
"filters2_dim",
"]",
")",
"f1",
"=",
"mtf",
".",
"relu",
"(",
"mtf",
".",
"conv2d_with_blocks",
"(",
"x",
",",
"kernel1",
",",
"strides",
"=",
"[",
"1",
",",
"1",
",",
"1",
",",
"1",
"]",
",",
"padding",
"=",
"\"SAME\"",
",",
"h_blocks_dim",
"=",
"row_blocks_dim",
",",
"w_blocks_dim",
"=",
"col_blocks_dim",
")",
")",
"f2",
"=",
"mtf",
".",
"relu",
"(",
"mtf",
".",
"conv2d_with_blocks",
"(",
"f1",
",",
"kernel2",
",",
"strides",
"=",
"[",
"1",
",",
"1",
",",
"1",
",",
"1",
"]",
",",
"padding",
"=",
"\"SAME\"",
",",
"h_blocks_dim",
"=",
"row_blocks_dim",
",",
"w_blocks_dim",
"=",
"col_blocks_dim",
")",
")",
"x",
"=",
"mtf",
".",
"reduce_mean",
"(",
"f2",
",",
"reduced_dim",
"=",
"filters2_dim",
")",
"# add some fully-connected dense layers.",
"hidden_dim1",
"=",
"mtf",
".",
"Dimension",
"(",
"\"hidden1\"",
",",
"FLAGS",
".",
"hidden_size",
")",
"hidden_dim2",
"=",
"mtf",
".",
"Dimension",
"(",
"\"hidden2\"",
",",
"FLAGS",
".",
"hidden_size",
")",
"h1",
"=",
"mtf",
".",
"layers",
".",
"dense",
"(",
"x",
",",
"hidden_dim1",
",",
"reduced_dims",
"=",
"x",
".",
"shape",
".",
"dims",
"[",
"-",
"4",
":",
"]",
",",
"activation",
"=",
"mtf",
".",
"relu",
",",
"name",
"=",
"\"hidden1\"",
")",
"h2",
"=",
"mtf",
".",
"layers",
".",
"dense",
"(",
"h1",
",",
"hidden_dim2",
",",
"activation",
"=",
"mtf",
".",
"relu",
",",
"name",
"=",
"\"hidden2\"",
")",
"logits",
"=",
"mtf",
".",
"layers",
".",
"dense",
"(",
"h2",
",",
"classes_dim",
",",
"name",
"=",
"\"logits\"",
")",
"if",
"labels",
"is",
"None",
":",
"loss",
"=",
"None",
"else",
":",
"labels",
"=",
"mtf",
".",
"import_tf_tensor",
"(",
"mesh",
",",
"tf",
".",
"reshape",
"(",
"labels",
",",
"[",
"FLAGS",
".",
"batch_size",
"]",
")",
",",
"mtf",
".",
"Shape",
"(",
"[",
"batch_dim",
"]",
")",
")",
"loss",
"=",
"mtf",
".",
"layers",
".",
"softmax_cross_entropy_with_logits",
"(",
"logits",
",",
"mtf",
".",
"one_hot",
"(",
"labels",
",",
"classes_dim",
")",
",",
"classes_dim",
")",
"loss",
"=",
"mtf",
".",
"reduce_mean",
"(",
"loss",
")",
"return",
"logits",
",",
"loss"
] | The model.
Args:
image: tf.Tensor with shape [batch, 28*28]
labels: a tf.Tensor with shape [batch] and dtype tf.int32
mesh: a mtf.Mesh
Returns:
logits: a mtf.Tensor with shape [batch, 10]
loss: a mtf.Tensor with shape [] | [
"The",
"model",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/mnist.py#L50-L118 |
227,827 | tensorflow/mesh | examples/mnist.py | run_mnist | def run_mnist():
"""Run MNIST training and eval loop."""
mnist_classifier = tf.estimator.Estimator(
model_fn=model_fn,
model_dir=FLAGS.model_dir)
# Set up training and evaluation input functions.
def train_input_fn():
"""Prepare data for training."""
# When choosing shuffle buffer sizes, larger sizes result in better
# randomness, while smaller sizes use less memory. MNIST is a small
# enough dataset that we can easily shuffle the full epoch.
ds = dataset.train(FLAGS.data_dir)
ds_batched = ds.cache().shuffle(buffer_size=50000).batch(FLAGS.batch_size)
# Iterate through the dataset a set number (`epochs_between_evals`) of times
# during each training session.
ds = ds_batched.repeat(FLAGS.epochs_between_evals)
return ds
def eval_input_fn():
return dataset.test(FLAGS.data_dir).batch(
FLAGS.batch_size).make_one_shot_iterator().get_next()
# Train and evaluate model.
for _ in range(FLAGS.train_epochs // FLAGS.epochs_between_evals):
mnist_classifier.train(input_fn=train_input_fn, hooks=None)
eval_results = mnist_classifier.evaluate(input_fn=eval_input_fn)
print("\nEvaluation results:\n\t%s\n" % eval_results) | python | def run_mnist():
"""Run MNIST training and eval loop."""
mnist_classifier = tf.estimator.Estimator(
model_fn=model_fn,
model_dir=FLAGS.model_dir)
# Set up training and evaluation input functions.
def train_input_fn():
"""Prepare data for training."""
# When choosing shuffle buffer sizes, larger sizes result in better
# randomness, while smaller sizes use less memory. MNIST is a small
# enough dataset that we can easily shuffle the full epoch.
ds = dataset.train(FLAGS.data_dir)
ds_batched = ds.cache().shuffle(buffer_size=50000).batch(FLAGS.batch_size)
# Iterate through the dataset a set number (`epochs_between_evals`) of times
# during each training session.
ds = ds_batched.repeat(FLAGS.epochs_between_evals)
return ds
def eval_input_fn():
return dataset.test(FLAGS.data_dir).batch(
FLAGS.batch_size).make_one_shot_iterator().get_next()
# Train and evaluate model.
for _ in range(FLAGS.train_epochs // FLAGS.epochs_between_evals):
mnist_classifier.train(input_fn=train_input_fn, hooks=None)
eval_results = mnist_classifier.evaluate(input_fn=eval_input_fn)
print("\nEvaluation results:\n\t%s\n" % eval_results) | [
"def",
"run_mnist",
"(",
")",
":",
"mnist_classifier",
"=",
"tf",
".",
"estimator",
".",
"Estimator",
"(",
"model_fn",
"=",
"model_fn",
",",
"model_dir",
"=",
"FLAGS",
".",
"model_dir",
")",
"# Set up training and evaluation input functions.",
"def",
"train_input_fn",
"(",
")",
":",
"\"\"\"Prepare data for training.\"\"\"",
"# When choosing shuffle buffer sizes, larger sizes result in better",
"# randomness, while smaller sizes use less memory. MNIST is a small",
"# enough dataset that we can easily shuffle the full epoch.",
"ds",
"=",
"dataset",
".",
"train",
"(",
"FLAGS",
".",
"data_dir",
")",
"ds_batched",
"=",
"ds",
".",
"cache",
"(",
")",
".",
"shuffle",
"(",
"buffer_size",
"=",
"50000",
")",
".",
"batch",
"(",
"FLAGS",
".",
"batch_size",
")",
"# Iterate through the dataset a set number (`epochs_between_evals`) of times",
"# during each training session.",
"ds",
"=",
"ds_batched",
".",
"repeat",
"(",
"FLAGS",
".",
"epochs_between_evals",
")",
"return",
"ds",
"def",
"eval_input_fn",
"(",
")",
":",
"return",
"dataset",
".",
"test",
"(",
"FLAGS",
".",
"data_dir",
")",
".",
"batch",
"(",
"FLAGS",
".",
"batch_size",
")",
".",
"make_one_shot_iterator",
"(",
")",
".",
"get_next",
"(",
")",
"# Train and evaluate model.",
"for",
"_",
"in",
"range",
"(",
"FLAGS",
".",
"train_epochs",
"//",
"FLAGS",
".",
"epochs_between_evals",
")",
":",
"mnist_classifier",
".",
"train",
"(",
"input_fn",
"=",
"train_input_fn",
",",
"hooks",
"=",
"None",
")",
"eval_results",
"=",
"mnist_classifier",
".",
"evaluate",
"(",
"input_fn",
"=",
"eval_input_fn",
")",
"print",
"(",
"\"\\nEvaluation results:\\n\\t%s\\n\"",
"%",
"eval_results",
")"
] | Run MNIST training and eval loop. | [
"Run",
"MNIST",
"training",
"and",
"eval",
"loop",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/mnist.py#L207-L236 |
227,828 | tensorflow/mesh | mesh_tensorflow/transformer/moe.py | MoE2D.call | def call(self, context, x, losses=None):
"""Call the layer."""
has_length_dim = context.length_dim in x.shape.dims
if not has_length_dim:
x_shape = x.shape
shape_with_length = mtf.Shape(
x_shape.dims[:-1] + [mtf.Dimension("length", 1)]
+ x_shape.dims[-1:])
x = mtf.reshape(x, shape_with_length)
y, loss = transformer_moe_layer_v2(
x,
context.model_dim,
self._hparams,
context.train,
context.variable_dtype,
layout=context.layout,
mesh_shape=context.mesh_shape,
nonpadding=context.nonpadding)
if context.losses is not None:
context.losses.append(loss)
if not has_length_dim:
y = mtf.reshape(y, x_shape)
return y | python | def call(self, context, x, losses=None):
"""Call the layer."""
has_length_dim = context.length_dim in x.shape.dims
if not has_length_dim:
x_shape = x.shape
shape_with_length = mtf.Shape(
x_shape.dims[:-1] + [mtf.Dimension("length", 1)]
+ x_shape.dims[-1:])
x = mtf.reshape(x, shape_with_length)
y, loss = transformer_moe_layer_v2(
x,
context.model_dim,
self._hparams,
context.train,
context.variable_dtype,
layout=context.layout,
mesh_shape=context.mesh_shape,
nonpadding=context.nonpadding)
if context.losses is not None:
context.losses.append(loss)
if not has_length_dim:
y = mtf.reshape(y, x_shape)
return y | [
"def",
"call",
"(",
"self",
",",
"context",
",",
"x",
",",
"losses",
"=",
"None",
")",
":",
"has_length_dim",
"=",
"context",
".",
"length_dim",
"in",
"x",
".",
"shape",
".",
"dims",
"if",
"not",
"has_length_dim",
":",
"x_shape",
"=",
"x",
".",
"shape",
"shape_with_length",
"=",
"mtf",
".",
"Shape",
"(",
"x_shape",
".",
"dims",
"[",
":",
"-",
"1",
"]",
"+",
"[",
"mtf",
".",
"Dimension",
"(",
"\"length\"",
",",
"1",
")",
"]",
"+",
"x_shape",
".",
"dims",
"[",
"-",
"1",
":",
"]",
")",
"x",
"=",
"mtf",
".",
"reshape",
"(",
"x",
",",
"shape_with_length",
")",
"y",
",",
"loss",
"=",
"transformer_moe_layer_v2",
"(",
"x",
",",
"context",
".",
"model_dim",
",",
"self",
".",
"_hparams",
",",
"context",
".",
"train",
",",
"context",
".",
"variable_dtype",
",",
"layout",
"=",
"context",
".",
"layout",
",",
"mesh_shape",
"=",
"context",
".",
"mesh_shape",
",",
"nonpadding",
"=",
"context",
".",
"nonpadding",
")",
"if",
"context",
".",
"losses",
"is",
"not",
"None",
":",
"context",
".",
"losses",
".",
"append",
"(",
"loss",
")",
"if",
"not",
"has_length_dim",
":",
"y",
"=",
"mtf",
".",
"reshape",
"(",
"y",
",",
"x_shape",
")",
"return",
"y"
] | Call the layer. | [
"Call",
"the",
"layer",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/moe.py#L123-L145 |
227,829 | tensorflow/mesh | mesh_tensorflow/auto_mtf/print_cp_model_solution.py | print_solution | def print_solution(model, solver):
"""Prints the solution associated with solver.
If solver has already had Solve() called on it, prints the solution. This
includes each variable and its assignment, along with the objective function
and its optimal value.
If solver has not had Solve() called on it, or there is no feasible solution,
this will probably crash.
Args:
model: A pywrapcp.CpModel object.
solver: A pywrapcp.CpSolver object.
Returns:
Nothing, but prints the solution associated with solver.
"""
model_proto = model.Proto()
response_proto = solver.ResponseProto()
variables_in_objective_map = {}
maximization = False
if model_proto.HasField('objective'):
objective = model_proto.objective
for i in range(len(objective.vars)):
variables_in_objective_map[objective.vars[i]] = objective.coeffs[i]
if objective.scaling_factor < 0.0:
maximization = True
variable_assignments = []
variables_in_objective = []
num_vars = len(model_proto.variables)
for var_index in range(num_vars):
if not model_proto.variables[var_index].name:
continue
variable_name = model_proto.variables[var_index].name
if var_index in variables_in_objective_map:
coefficient = variables_in_objective_map[var_index]
if coefficient:
if maximization:
coefficient *= -1
if coefficient < 0:
variables_in_objective.append(' - {} * {}'.format(
-coefficient, variable_name))
elif coefficient > 0:
variables_in_objective.append(' + {} * {}'.format(
coefficient, variable_name))
variable_assignments.append(' {} = {}\n'.format(
variable_name, response_proto.solution[var_index]))
print(''.join(variable_assignments), end='')
# Strip the leading '+' if it exists.
if variables_in_objective and variables_in_objective[0][1] == '+':
variables_in_objective[0] = variables_in_objective[0][2:]
print('{}:{}'.format('Maximize' if maximization else 'Minimize',
''.join(variables_in_objective)))
print('Objective value: {}\n'.format(solver.ObjectiveValue())) | python | def print_solution(model, solver):
"""Prints the solution associated with solver.
If solver has already had Solve() called on it, prints the solution. This
includes each variable and its assignment, along with the objective function
and its optimal value.
If solver has not had Solve() called on it, or there is no feasible solution,
this will probably crash.
Args:
model: A pywrapcp.CpModel object.
solver: A pywrapcp.CpSolver object.
Returns:
Nothing, but prints the solution associated with solver.
"""
model_proto = model.Proto()
response_proto = solver.ResponseProto()
variables_in_objective_map = {}
maximization = False
if model_proto.HasField('objective'):
objective = model_proto.objective
for i in range(len(objective.vars)):
variables_in_objective_map[objective.vars[i]] = objective.coeffs[i]
if objective.scaling_factor < 0.0:
maximization = True
variable_assignments = []
variables_in_objective = []
num_vars = len(model_proto.variables)
for var_index in range(num_vars):
if not model_proto.variables[var_index].name:
continue
variable_name = model_proto.variables[var_index].name
if var_index in variables_in_objective_map:
coefficient = variables_in_objective_map[var_index]
if coefficient:
if maximization:
coefficient *= -1
if coefficient < 0:
variables_in_objective.append(' - {} * {}'.format(
-coefficient, variable_name))
elif coefficient > 0:
variables_in_objective.append(' + {} * {}'.format(
coefficient, variable_name))
variable_assignments.append(' {} = {}\n'.format(
variable_name, response_proto.solution[var_index]))
print(''.join(variable_assignments), end='')
# Strip the leading '+' if it exists.
if variables_in_objective and variables_in_objective[0][1] == '+':
variables_in_objective[0] = variables_in_objective[0][2:]
print('{}:{}'.format('Maximize' if maximization else 'Minimize',
''.join(variables_in_objective)))
print('Objective value: {}\n'.format(solver.ObjectiveValue())) | [
"def",
"print_solution",
"(",
"model",
",",
"solver",
")",
":",
"model_proto",
"=",
"model",
".",
"Proto",
"(",
")",
"response_proto",
"=",
"solver",
".",
"ResponseProto",
"(",
")",
"variables_in_objective_map",
"=",
"{",
"}",
"maximization",
"=",
"False",
"if",
"model_proto",
".",
"HasField",
"(",
"'objective'",
")",
":",
"objective",
"=",
"model_proto",
".",
"objective",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"objective",
".",
"vars",
")",
")",
":",
"variables_in_objective_map",
"[",
"objective",
".",
"vars",
"[",
"i",
"]",
"]",
"=",
"objective",
".",
"coeffs",
"[",
"i",
"]",
"if",
"objective",
".",
"scaling_factor",
"<",
"0.0",
":",
"maximization",
"=",
"True",
"variable_assignments",
"=",
"[",
"]",
"variables_in_objective",
"=",
"[",
"]",
"num_vars",
"=",
"len",
"(",
"model_proto",
".",
"variables",
")",
"for",
"var_index",
"in",
"range",
"(",
"num_vars",
")",
":",
"if",
"not",
"model_proto",
".",
"variables",
"[",
"var_index",
"]",
".",
"name",
":",
"continue",
"variable_name",
"=",
"model_proto",
".",
"variables",
"[",
"var_index",
"]",
".",
"name",
"if",
"var_index",
"in",
"variables_in_objective_map",
":",
"coefficient",
"=",
"variables_in_objective_map",
"[",
"var_index",
"]",
"if",
"coefficient",
":",
"if",
"maximization",
":",
"coefficient",
"*=",
"-",
"1",
"if",
"coefficient",
"<",
"0",
":",
"variables_in_objective",
".",
"append",
"(",
"' - {} * {}'",
".",
"format",
"(",
"-",
"coefficient",
",",
"variable_name",
")",
")",
"elif",
"coefficient",
">",
"0",
":",
"variables_in_objective",
".",
"append",
"(",
"' + {} * {}'",
".",
"format",
"(",
"coefficient",
",",
"variable_name",
")",
")",
"variable_assignments",
".",
"append",
"(",
"' {} = {}\\n'",
".",
"format",
"(",
"variable_name",
",",
"response_proto",
".",
"solution",
"[",
"var_index",
"]",
")",
")",
"print",
"(",
"''",
".",
"join",
"(",
"variable_assignments",
")",
",",
"end",
"=",
"''",
")",
"# Strip the leading '+' if it exists.",
"if",
"variables_in_objective",
"and",
"variables_in_objective",
"[",
"0",
"]",
"[",
"1",
"]",
"==",
"'+'",
":",
"variables_in_objective",
"[",
"0",
"]",
"=",
"variables_in_objective",
"[",
"0",
"]",
"[",
"2",
":",
"]",
"print",
"(",
"'{}:{}'",
".",
"format",
"(",
"'Maximize'",
"if",
"maximization",
"else",
"'Minimize'",
",",
"''",
".",
"join",
"(",
"variables_in_objective",
")",
")",
")",
"print",
"(",
"'Objective value: {}\\n'",
".",
"format",
"(",
"solver",
".",
"ObjectiveValue",
"(",
")",
")",
")"
] | Prints the solution associated with solver.
If solver has already had Solve() called on it, prints the solution. This
includes each variable and its assignment, along with the objective function
and its optimal value.
If solver has not had Solve() called on it, or there is no feasible solution,
this will probably crash.
Args:
model: A pywrapcp.CpModel object.
solver: A pywrapcp.CpSolver object.
Returns:
Nothing, but prints the solution associated with solver. | [
"Prints",
"the",
"solution",
"associated",
"with",
"solver",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/print_cp_model_solution.py#L32-L84 |
227,830 | tensorflow/mesh | mesh_tensorflow/auto_mtf/layout_optimizer.py | _local_var_name | def _local_var_name(splittable_dimensions, assignment):
"""Name for a local variable.
Args:
splittable_dimensions: frozenset of names of splittable dimensions.
assignment: dict from names of splittable dimensions to names of mesh
dimensions.
Returns:
A string, the variable name.
"""
assignment_string = []
for splittable in sorted(splittable_dimensions):
if splittable in assignment:
assignment_string.append("{}:{}".format(splittable,
assignment[splittable]))
else:
assignment_string.append("{}".format(splittable))
return "y_(" + ",".join(assignment_string) + ")" | python | def _local_var_name(splittable_dimensions, assignment):
"""Name for a local variable.
Args:
splittable_dimensions: frozenset of names of splittable dimensions.
assignment: dict from names of splittable dimensions to names of mesh
dimensions.
Returns:
A string, the variable name.
"""
assignment_string = []
for splittable in sorted(splittable_dimensions):
if splittable in assignment:
assignment_string.append("{}:{}".format(splittable,
assignment[splittable]))
else:
assignment_string.append("{}".format(splittable))
return "y_(" + ",".join(assignment_string) + ")" | [
"def",
"_local_var_name",
"(",
"splittable_dimensions",
",",
"assignment",
")",
":",
"assignment_string",
"=",
"[",
"]",
"for",
"splittable",
"in",
"sorted",
"(",
"splittable_dimensions",
")",
":",
"if",
"splittable",
"in",
"assignment",
":",
"assignment_string",
".",
"append",
"(",
"\"{}:{}\"",
".",
"format",
"(",
"splittable",
",",
"assignment",
"[",
"splittable",
"]",
")",
")",
"else",
":",
"assignment_string",
".",
"append",
"(",
"\"{}\"",
".",
"format",
"(",
"splittable",
")",
")",
"return",
"\"y_(\"",
"+",
"\",\"",
".",
"join",
"(",
"assignment_string",
")",
"+",
"\")\""
] | Name for a local variable.
Args:
splittable_dimensions: frozenset of names of splittable dimensions.
assignment: dict from names of splittable dimensions to names of mesh
dimensions.
Returns:
A string, the variable name. | [
"Name",
"for",
"a",
"local",
"variable",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout_optimizer.py#L383-L401 |
227,831 | tensorflow/mesh | mesh_tensorflow/auto_mtf/layout_optimizer.py | _generate_assignments | def _generate_assignments(splittable_dimensions, mesh_dimension_to_size):
"""Generates all ways to map splittable dimensions to mesh dimensions.
Args:
splittable_dimensions: a frozenset of the names of splittable dimensions.
mesh_dimension_to_size: a dictionary from mesh dimension name to size.
Returns:
A list of the valid assignments. Each assignment is a dict keyed by every
splittable dimension, whose value is either a mesh dimension or None.
"""
assignments = []
for assignment_size in six.moves.xrange(
1 + min(len(splittable_dimensions), len(mesh_dimension_to_size))):
for s_dims_chosen in itertools.combinations(splittable_dimensions,
assignment_size):
for m_dims_chosen in itertools.permutations(mesh_dimension_to_size,
assignment_size):
assignments.append(dict(zip(s_dims_chosen, m_dims_chosen)))
return assignments | python | def _generate_assignments(splittable_dimensions, mesh_dimension_to_size):
"""Generates all ways to map splittable dimensions to mesh dimensions.
Args:
splittable_dimensions: a frozenset of the names of splittable dimensions.
mesh_dimension_to_size: a dictionary from mesh dimension name to size.
Returns:
A list of the valid assignments. Each assignment is a dict keyed by every
splittable dimension, whose value is either a mesh dimension or None.
"""
assignments = []
for assignment_size in six.moves.xrange(
1 + min(len(splittable_dimensions), len(mesh_dimension_to_size))):
for s_dims_chosen in itertools.combinations(splittable_dimensions,
assignment_size):
for m_dims_chosen in itertools.permutations(mesh_dimension_to_size,
assignment_size):
assignments.append(dict(zip(s_dims_chosen, m_dims_chosen)))
return assignments | [
"def",
"_generate_assignments",
"(",
"splittable_dimensions",
",",
"mesh_dimension_to_size",
")",
":",
"assignments",
"=",
"[",
"]",
"for",
"assignment_size",
"in",
"six",
".",
"moves",
".",
"xrange",
"(",
"1",
"+",
"min",
"(",
"len",
"(",
"splittable_dimensions",
")",
",",
"len",
"(",
"mesh_dimension_to_size",
")",
")",
")",
":",
"for",
"s_dims_chosen",
"in",
"itertools",
".",
"combinations",
"(",
"splittable_dimensions",
",",
"assignment_size",
")",
":",
"for",
"m_dims_chosen",
"in",
"itertools",
".",
"permutations",
"(",
"mesh_dimension_to_size",
",",
"assignment_size",
")",
":",
"assignments",
".",
"append",
"(",
"dict",
"(",
"zip",
"(",
"s_dims_chosen",
",",
"m_dims_chosen",
")",
")",
")",
"return",
"assignments"
] | Generates all ways to map splittable dimensions to mesh dimensions.
Args:
splittable_dimensions: a frozenset of the names of splittable dimensions.
mesh_dimension_to_size: a dictionary from mesh dimension name to size.
Returns:
A list of the valid assignments. Each assignment is a dict keyed by every
splittable dimension, whose value is either a mesh dimension or None. | [
"Generates",
"all",
"ways",
"to",
"map",
"splittable",
"dimensions",
"to",
"mesh",
"dimensions",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout_optimizer.py#L404-L423 |
227,832 | tensorflow/mesh | mesh_tensorflow/auto_mtf/layout_optimizer.py | LayoutOptimizer._preprocess_input | def _preprocess_input(self):
"""Computing useful input data structures to ease IP construction."""
# Compute the sets of MTF dimensions used in operations/tensors.
# a {string: frozenset(string)}, mapping operation name to MTF dimension
# names.
self._operation_name_to_mtf_dimension_set = {}
# a {string: frozenset(string)}, mapping tensor name to MTF dimension names.
self._tensor_name_to_mtf_dimension_set = {}
for operation_name in self._graph.get_all_operation_names():
self._operation_name_to_mtf_dimension_set[operation_name] = frozenset(
set(self._graph.get_operation_mtf_dimension_names(
operation_name)).intersection(
self._layout_validator.splittable_mtf_dimension_names))
for tensor_name in self._graph.get_all_tensor_names():
self._tensor_name_to_mtf_dimension_set[tensor_name] = frozenset(
set(self._graph.get_tensor_mtf_dimension_names(tensor_name))
.intersection(self._layout_validator.splittable_mtf_dimension_names))
self._operation_mtf_dimension_sets = set(
self._operation_name_to_mtf_dimension_set.values())
self._mtf_dimension_sets = self._operation_mtf_dimension_sets | set(
self._tensor_name_to_mtf_dimension_set.values())
# Compute possible assignments for each set of MTF dimensions.
self._assignments = {} # indexed by MTF dimension set
for mtf_dimension_set in self._mtf_dimension_sets:
self._assignments[mtf_dimension_set] = _generate_assignments(
mtf_dimension_set, self._layout_validator.mesh_dimension_name_to_size) | python | def _preprocess_input(self):
"""Computing useful input data structures to ease IP construction."""
# Compute the sets of MTF dimensions used in operations/tensors.
# a {string: frozenset(string)}, mapping operation name to MTF dimension
# names.
self._operation_name_to_mtf_dimension_set = {}
# a {string: frozenset(string)}, mapping tensor name to MTF dimension names.
self._tensor_name_to_mtf_dimension_set = {}
for operation_name in self._graph.get_all_operation_names():
self._operation_name_to_mtf_dimension_set[operation_name] = frozenset(
set(self._graph.get_operation_mtf_dimension_names(
operation_name)).intersection(
self._layout_validator.splittable_mtf_dimension_names))
for tensor_name in self._graph.get_all_tensor_names():
self._tensor_name_to_mtf_dimension_set[tensor_name] = frozenset(
set(self._graph.get_tensor_mtf_dimension_names(tensor_name))
.intersection(self._layout_validator.splittable_mtf_dimension_names))
self._operation_mtf_dimension_sets = set(
self._operation_name_to_mtf_dimension_set.values())
self._mtf_dimension_sets = self._operation_mtf_dimension_sets | set(
self._tensor_name_to_mtf_dimension_set.values())
# Compute possible assignments for each set of MTF dimensions.
self._assignments = {} # indexed by MTF dimension set
for mtf_dimension_set in self._mtf_dimension_sets:
self._assignments[mtf_dimension_set] = _generate_assignments(
mtf_dimension_set, self._layout_validator.mesh_dimension_name_to_size) | [
"def",
"_preprocess_input",
"(",
"self",
")",
":",
"# Compute the sets of MTF dimensions used in operations/tensors.",
"# a {string: frozenset(string)}, mapping operation name to MTF dimension",
"# names.",
"self",
".",
"_operation_name_to_mtf_dimension_set",
"=",
"{",
"}",
"# a {string: frozenset(string)}, mapping tensor name to MTF dimension names.",
"self",
".",
"_tensor_name_to_mtf_dimension_set",
"=",
"{",
"}",
"for",
"operation_name",
"in",
"self",
".",
"_graph",
".",
"get_all_operation_names",
"(",
")",
":",
"self",
".",
"_operation_name_to_mtf_dimension_set",
"[",
"operation_name",
"]",
"=",
"frozenset",
"(",
"set",
"(",
"self",
".",
"_graph",
".",
"get_operation_mtf_dimension_names",
"(",
"operation_name",
")",
")",
".",
"intersection",
"(",
"self",
".",
"_layout_validator",
".",
"splittable_mtf_dimension_names",
")",
")",
"for",
"tensor_name",
"in",
"self",
".",
"_graph",
".",
"get_all_tensor_names",
"(",
")",
":",
"self",
".",
"_tensor_name_to_mtf_dimension_set",
"[",
"tensor_name",
"]",
"=",
"frozenset",
"(",
"set",
"(",
"self",
".",
"_graph",
".",
"get_tensor_mtf_dimension_names",
"(",
"tensor_name",
")",
")",
".",
"intersection",
"(",
"self",
".",
"_layout_validator",
".",
"splittable_mtf_dimension_names",
")",
")",
"self",
".",
"_operation_mtf_dimension_sets",
"=",
"set",
"(",
"self",
".",
"_operation_name_to_mtf_dimension_set",
".",
"values",
"(",
")",
")",
"self",
".",
"_mtf_dimension_sets",
"=",
"self",
".",
"_operation_mtf_dimension_sets",
"|",
"set",
"(",
"self",
".",
"_tensor_name_to_mtf_dimension_set",
".",
"values",
"(",
")",
")",
"# Compute possible assignments for each set of MTF dimensions.",
"self",
".",
"_assignments",
"=",
"{",
"}",
"# indexed by MTF dimension set",
"for",
"mtf_dimension_set",
"in",
"self",
".",
"_mtf_dimension_sets",
":",
"self",
".",
"_assignments",
"[",
"mtf_dimension_set",
"]",
"=",
"_generate_assignments",
"(",
"mtf_dimension_set",
",",
"self",
".",
"_layout_validator",
".",
"mesh_dimension_name_to_size",
")"
] | Computing useful input data structures to ease IP construction. | [
"Computing",
"useful",
"input",
"data",
"structures",
"to",
"ease",
"IP",
"construction",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout_optimizer.py#L123-L152 |
227,833 | tensorflow/mesh | mesh_tensorflow/auto_mtf/layout_optimizer.py | LayoutOptimizer._initialize_variables | def _initialize_variables(self):
"""Initializing the variables of the IP."""
# Initialize global variables.
self._global_vars = {} # Indexed by (MTF dimension, mesh dimension)
for mtf_dimension_name in (
self._layout_validator.splittable_mtf_dimension_names):
for mesh_dimension_name in (
self._layout_validator.mesh_dimension_name_to_size):
name = _global_var_name(mtf_dimension_name, mesh_dimension_name)
self._global_vars[(mtf_dimension_name, mesh_dimension_name)] = (
self._model.NewBoolVar(name))
# Initialize local variables.
self._local_vars = {} # Indexed by (tensorflow dimension set), then name of
# assignment.
for mtf_dimension_set in self._mtf_dimension_sets:
self._local_vars[mtf_dimension_set] = {}
for assignment in self._assignments[mtf_dimension_set]:
# TODO(joshuawang): Avoid hash collision no matter what dimension names
# are; don't hash by this local var name, swap to using a tuple encoding
# of the full assignment instead.
name = _local_var_name(mtf_dimension_set, assignment)
self._local_vars[mtf_dimension_set][name] = (
self._model.NewBoolVar(name))
# Initialize memory variable. We need a crude upper bound on memory, so we
# use the total size of all tensors under the empty assignment.
# NOTE(joshuawang): This bound could be improved by factoring in the
# schedule.
memory_upper_bound = 0
for tensor_name in self._graph.get_all_tensor_names():
if self._graph.is_tensor_on_canonical_device(tensor_name):
memory_upper_bound += int(self._graph.get_tensor_size(tensor_name))
self._memory_var = self._model.NewIntVar(0, memory_upper_bound, "z") | python | def _initialize_variables(self):
"""Initializing the variables of the IP."""
# Initialize global variables.
self._global_vars = {} # Indexed by (MTF dimension, mesh dimension)
for mtf_dimension_name in (
self._layout_validator.splittable_mtf_dimension_names):
for mesh_dimension_name in (
self._layout_validator.mesh_dimension_name_to_size):
name = _global_var_name(mtf_dimension_name, mesh_dimension_name)
self._global_vars[(mtf_dimension_name, mesh_dimension_name)] = (
self._model.NewBoolVar(name))
# Initialize local variables.
self._local_vars = {} # Indexed by (tensorflow dimension set), then name of
# assignment.
for mtf_dimension_set in self._mtf_dimension_sets:
self._local_vars[mtf_dimension_set] = {}
for assignment in self._assignments[mtf_dimension_set]:
# TODO(joshuawang): Avoid hash collision no matter what dimension names
# are; don't hash by this local var name, swap to using a tuple encoding
# of the full assignment instead.
name = _local_var_name(mtf_dimension_set, assignment)
self._local_vars[mtf_dimension_set][name] = (
self._model.NewBoolVar(name))
# Initialize memory variable. We need a crude upper bound on memory, so we
# use the total size of all tensors under the empty assignment.
# NOTE(joshuawang): This bound could be improved by factoring in the
# schedule.
memory_upper_bound = 0
for tensor_name in self._graph.get_all_tensor_names():
if self._graph.is_tensor_on_canonical_device(tensor_name):
memory_upper_bound += int(self._graph.get_tensor_size(tensor_name))
self._memory_var = self._model.NewIntVar(0, memory_upper_bound, "z") | [
"def",
"_initialize_variables",
"(",
"self",
")",
":",
"# Initialize global variables.",
"self",
".",
"_global_vars",
"=",
"{",
"}",
"# Indexed by (MTF dimension, mesh dimension)",
"for",
"mtf_dimension_name",
"in",
"(",
"self",
".",
"_layout_validator",
".",
"splittable_mtf_dimension_names",
")",
":",
"for",
"mesh_dimension_name",
"in",
"(",
"self",
".",
"_layout_validator",
".",
"mesh_dimension_name_to_size",
")",
":",
"name",
"=",
"_global_var_name",
"(",
"mtf_dimension_name",
",",
"mesh_dimension_name",
")",
"self",
".",
"_global_vars",
"[",
"(",
"mtf_dimension_name",
",",
"mesh_dimension_name",
")",
"]",
"=",
"(",
"self",
".",
"_model",
".",
"NewBoolVar",
"(",
"name",
")",
")",
"# Initialize local variables.",
"self",
".",
"_local_vars",
"=",
"{",
"}",
"# Indexed by (tensorflow dimension set), then name of",
"# assignment.",
"for",
"mtf_dimension_set",
"in",
"self",
".",
"_mtf_dimension_sets",
":",
"self",
".",
"_local_vars",
"[",
"mtf_dimension_set",
"]",
"=",
"{",
"}",
"for",
"assignment",
"in",
"self",
".",
"_assignments",
"[",
"mtf_dimension_set",
"]",
":",
"# TODO(joshuawang): Avoid hash collision no matter what dimension names",
"# are; don't hash by this local var name, swap to using a tuple encoding",
"# of the full assignment instead.",
"name",
"=",
"_local_var_name",
"(",
"mtf_dimension_set",
",",
"assignment",
")",
"self",
".",
"_local_vars",
"[",
"mtf_dimension_set",
"]",
"[",
"name",
"]",
"=",
"(",
"self",
".",
"_model",
".",
"NewBoolVar",
"(",
"name",
")",
")",
"# Initialize memory variable. We need a crude upper bound on memory, so we",
"# use the total size of all tensors under the empty assignment.",
"# NOTE(joshuawang): This bound could be improved by factoring in the",
"# schedule.",
"memory_upper_bound",
"=",
"0",
"for",
"tensor_name",
"in",
"self",
".",
"_graph",
".",
"get_all_tensor_names",
"(",
")",
":",
"if",
"self",
".",
"_graph",
".",
"is_tensor_on_canonical_device",
"(",
"tensor_name",
")",
":",
"memory_upper_bound",
"+=",
"int",
"(",
"self",
".",
"_graph",
".",
"get_tensor_size",
"(",
"tensor_name",
")",
")",
"self",
".",
"_memory_var",
"=",
"self",
".",
"_model",
".",
"NewIntVar",
"(",
"0",
",",
"memory_upper_bound",
",",
"\"z\"",
")"
] | Initializing the variables of the IP. | [
"Initializing",
"the",
"variables",
"of",
"the",
"IP",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout_optimizer.py#L154-L187 |
227,834 | tensorflow/mesh | mesh_tensorflow/auto_mtf/layout_optimizer.py | LayoutOptimizer._add_constraints | def _add_constraints(self):
"""Adding constraints to the IP."""
# Add operation constraints.
for mesh_dimension_name in (
self._layout_validator.mesh_dimension_name_to_size):
for mtf_dimension_set in self._operation_mtf_dimension_sets:
self._model.Add(
sum(self._global_vars[(mtf_dimension_name, mesh_dimension_name)]
for mtf_dimension_name in mtf_dimension_set) <= 1)
# Add global constraints.
for mtf_dimension_name in (
self._layout_validator.splittable_mtf_dimension_names):
self._model.Add(
sum(self._global_vars[(mtf_dimension_name, mesh_dimension_name)]
for mesh_dimension_name in (
self._layout_validator.mesh_dimension_name_to_size)) <= 1)
# Add divisibility constraints.
for mtf_dimension_name in (
self._layout_validator.splittable_mtf_dimension_names):
for mesh_dimension_name in (
self._layout_validator.mesh_dimension_name_to_size):
if not self._layout_validator.is_valid_assignment(mtf_dimension_name,
mesh_dimension_name):
self._model.Add(self._global_vars[(mtf_dimension_name,
mesh_dimension_name)] == 0)
# Add local constraints.
for mtf_dimension_set in self._mtf_dimension_sets:
self._model.Add(
sum(self._local_vars[mtf_dimension_set][_local_var_name(
mtf_dimension_set, assignment)]
for assignment in self._assignments[mtf_dimension_set]) == 1)
# Add local-to-global constraints.
for mtf_dimension_set in self._mtf_dimension_sets:
for assignment in self._assignments[mtf_dimension_set]:
name = _local_var_name(mtf_dimension_set, assignment)
for mtf_dimension_name in mtf_dimension_set:
if mtf_dimension_name in assignment:
mesh_dimension_name = assignment[mtf_dimension_name]
self._model.AddImplication(
self._local_vars[mtf_dimension_set][name],
self._global_vars[(mtf_dimension_name, mesh_dimension_name)])
else:
for mesh_dimension_name in (
self._layout_validator.mesh_dimension_name_to_size):
self._model.AddImplication(
self._global_vars[(mtf_dimension_name, mesh_dimension_name)],
self._local_vars[mtf_dimension_set][name].Not())
# Add memory constraints.
tensor_memory_sum = {}
for tensor_name in self._graph.get_all_tensor_names():
tensor_memory_sum[tensor_name] = 0
mtf_dimension_set = self._tensor_name_to_mtf_dimension_set[tensor_name]
if not self._graph.is_tensor_on_canonical_device(tensor_name):
continue
for assignment in self._assignments[mtf_dimension_set]:
size_under_assignment = self._graph.get_tensor_size(
tensor_name, assignment,
self._layout_validator.mesh_dimension_name_to_size)
name = _local_var_name(mtf_dimension_set, assignment)
tensor_memory_sum[tensor_name] += (
size_under_assignment * self._local_vars[mtf_dimension_set][name])
for tensor_names in self._get_memory_contents():
self._model.Add(
sum(tensor_memory_sum[tensor_name]
for tensor_name in tensor_names) <= self._memory_var) | python | def _add_constraints(self):
"""Adding constraints to the IP."""
# Add operation constraints.
for mesh_dimension_name in (
self._layout_validator.mesh_dimension_name_to_size):
for mtf_dimension_set in self._operation_mtf_dimension_sets:
self._model.Add(
sum(self._global_vars[(mtf_dimension_name, mesh_dimension_name)]
for mtf_dimension_name in mtf_dimension_set) <= 1)
# Add global constraints.
for mtf_dimension_name in (
self._layout_validator.splittable_mtf_dimension_names):
self._model.Add(
sum(self._global_vars[(mtf_dimension_name, mesh_dimension_name)]
for mesh_dimension_name in (
self._layout_validator.mesh_dimension_name_to_size)) <= 1)
# Add divisibility constraints.
for mtf_dimension_name in (
self._layout_validator.splittable_mtf_dimension_names):
for mesh_dimension_name in (
self._layout_validator.mesh_dimension_name_to_size):
if not self._layout_validator.is_valid_assignment(mtf_dimension_name,
mesh_dimension_name):
self._model.Add(self._global_vars[(mtf_dimension_name,
mesh_dimension_name)] == 0)
# Add local constraints.
for mtf_dimension_set in self._mtf_dimension_sets:
self._model.Add(
sum(self._local_vars[mtf_dimension_set][_local_var_name(
mtf_dimension_set, assignment)]
for assignment in self._assignments[mtf_dimension_set]) == 1)
# Add local-to-global constraints.
for mtf_dimension_set in self._mtf_dimension_sets:
for assignment in self._assignments[mtf_dimension_set]:
name = _local_var_name(mtf_dimension_set, assignment)
for mtf_dimension_name in mtf_dimension_set:
if mtf_dimension_name in assignment:
mesh_dimension_name = assignment[mtf_dimension_name]
self._model.AddImplication(
self._local_vars[mtf_dimension_set][name],
self._global_vars[(mtf_dimension_name, mesh_dimension_name)])
else:
for mesh_dimension_name in (
self._layout_validator.mesh_dimension_name_to_size):
self._model.AddImplication(
self._global_vars[(mtf_dimension_name, mesh_dimension_name)],
self._local_vars[mtf_dimension_set][name].Not())
# Add memory constraints.
tensor_memory_sum = {}
for tensor_name in self._graph.get_all_tensor_names():
tensor_memory_sum[tensor_name] = 0
mtf_dimension_set = self._tensor_name_to_mtf_dimension_set[tensor_name]
if not self._graph.is_tensor_on_canonical_device(tensor_name):
continue
for assignment in self._assignments[mtf_dimension_set]:
size_under_assignment = self._graph.get_tensor_size(
tensor_name, assignment,
self._layout_validator.mesh_dimension_name_to_size)
name = _local_var_name(mtf_dimension_set, assignment)
tensor_memory_sum[tensor_name] += (
size_under_assignment * self._local_vars[mtf_dimension_set][name])
for tensor_names in self._get_memory_contents():
self._model.Add(
sum(tensor_memory_sum[tensor_name]
for tensor_name in tensor_names) <= self._memory_var) | [
"def",
"_add_constraints",
"(",
"self",
")",
":",
"# Add operation constraints.",
"for",
"mesh_dimension_name",
"in",
"(",
"self",
".",
"_layout_validator",
".",
"mesh_dimension_name_to_size",
")",
":",
"for",
"mtf_dimension_set",
"in",
"self",
".",
"_operation_mtf_dimension_sets",
":",
"self",
".",
"_model",
".",
"Add",
"(",
"sum",
"(",
"self",
".",
"_global_vars",
"[",
"(",
"mtf_dimension_name",
",",
"mesh_dimension_name",
")",
"]",
"for",
"mtf_dimension_name",
"in",
"mtf_dimension_set",
")",
"<=",
"1",
")",
"# Add global constraints.",
"for",
"mtf_dimension_name",
"in",
"(",
"self",
".",
"_layout_validator",
".",
"splittable_mtf_dimension_names",
")",
":",
"self",
".",
"_model",
".",
"Add",
"(",
"sum",
"(",
"self",
".",
"_global_vars",
"[",
"(",
"mtf_dimension_name",
",",
"mesh_dimension_name",
")",
"]",
"for",
"mesh_dimension_name",
"in",
"(",
"self",
".",
"_layout_validator",
".",
"mesh_dimension_name_to_size",
")",
")",
"<=",
"1",
")",
"# Add divisibility constraints.",
"for",
"mtf_dimension_name",
"in",
"(",
"self",
".",
"_layout_validator",
".",
"splittable_mtf_dimension_names",
")",
":",
"for",
"mesh_dimension_name",
"in",
"(",
"self",
".",
"_layout_validator",
".",
"mesh_dimension_name_to_size",
")",
":",
"if",
"not",
"self",
".",
"_layout_validator",
".",
"is_valid_assignment",
"(",
"mtf_dimension_name",
",",
"mesh_dimension_name",
")",
":",
"self",
".",
"_model",
".",
"Add",
"(",
"self",
".",
"_global_vars",
"[",
"(",
"mtf_dimension_name",
",",
"mesh_dimension_name",
")",
"]",
"==",
"0",
")",
"# Add local constraints.",
"for",
"mtf_dimension_set",
"in",
"self",
".",
"_mtf_dimension_sets",
":",
"self",
".",
"_model",
".",
"Add",
"(",
"sum",
"(",
"self",
".",
"_local_vars",
"[",
"mtf_dimension_set",
"]",
"[",
"_local_var_name",
"(",
"mtf_dimension_set",
",",
"assignment",
")",
"]",
"for",
"assignment",
"in",
"self",
".",
"_assignments",
"[",
"mtf_dimension_set",
"]",
")",
"==",
"1",
")",
"# Add local-to-global constraints.",
"for",
"mtf_dimension_set",
"in",
"self",
".",
"_mtf_dimension_sets",
":",
"for",
"assignment",
"in",
"self",
".",
"_assignments",
"[",
"mtf_dimension_set",
"]",
":",
"name",
"=",
"_local_var_name",
"(",
"mtf_dimension_set",
",",
"assignment",
")",
"for",
"mtf_dimension_name",
"in",
"mtf_dimension_set",
":",
"if",
"mtf_dimension_name",
"in",
"assignment",
":",
"mesh_dimension_name",
"=",
"assignment",
"[",
"mtf_dimension_name",
"]",
"self",
".",
"_model",
".",
"AddImplication",
"(",
"self",
".",
"_local_vars",
"[",
"mtf_dimension_set",
"]",
"[",
"name",
"]",
",",
"self",
".",
"_global_vars",
"[",
"(",
"mtf_dimension_name",
",",
"mesh_dimension_name",
")",
"]",
")",
"else",
":",
"for",
"mesh_dimension_name",
"in",
"(",
"self",
".",
"_layout_validator",
".",
"mesh_dimension_name_to_size",
")",
":",
"self",
".",
"_model",
".",
"AddImplication",
"(",
"self",
".",
"_global_vars",
"[",
"(",
"mtf_dimension_name",
",",
"mesh_dimension_name",
")",
"]",
",",
"self",
".",
"_local_vars",
"[",
"mtf_dimension_set",
"]",
"[",
"name",
"]",
".",
"Not",
"(",
")",
")",
"# Add memory constraints.",
"tensor_memory_sum",
"=",
"{",
"}",
"for",
"tensor_name",
"in",
"self",
".",
"_graph",
".",
"get_all_tensor_names",
"(",
")",
":",
"tensor_memory_sum",
"[",
"tensor_name",
"]",
"=",
"0",
"mtf_dimension_set",
"=",
"self",
".",
"_tensor_name_to_mtf_dimension_set",
"[",
"tensor_name",
"]",
"if",
"not",
"self",
".",
"_graph",
".",
"is_tensor_on_canonical_device",
"(",
"tensor_name",
")",
":",
"continue",
"for",
"assignment",
"in",
"self",
".",
"_assignments",
"[",
"mtf_dimension_set",
"]",
":",
"size_under_assignment",
"=",
"self",
".",
"_graph",
".",
"get_tensor_size",
"(",
"tensor_name",
",",
"assignment",
",",
"self",
".",
"_layout_validator",
".",
"mesh_dimension_name_to_size",
")",
"name",
"=",
"_local_var_name",
"(",
"mtf_dimension_set",
",",
"assignment",
")",
"tensor_memory_sum",
"[",
"tensor_name",
"]",
"+=",
"(",
"size_under_assignment",
"*",
"self",
".",
"_local_vars",
"[",
"mtf_dimension_set",
"]",
"[",
"name",
"]",
")",
"for",
"tensor_names",
"in",
"self",
".",
"_get_memory_contents",
"(",
")",
":",
"self",
".",
"_model",
".",
"Add",
"(",
"sum",
"(",
"tensor_memory_sum",
"[",
"tensor_name",
"]",
"for",
"tensor_name",
"in",
"tensor_names",
")",
"<=",
"self",
".",
"_memory_var",
")"
] | Adding constraints to the IP. | [
"Adding",
"constraints",
"to",
"the",
"IP",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout_optimizer.py#L189-L262 |
227,835 | tensorflow/mesh | mesh_tensorflow/auto_mtf/layout_optimizer.py | LayoutOptimizer._get_memory_contents | def _get_memory_contents(self):
"""Runs the scheduler to determine memory contents at every point in time.
Returns:
a list of frozenset of strings, where the ith entry describes the tensors
in memory when executing operation i (where schedule[i] is an index into
GetAllOperationNames()).
"""
if self._memory_contents is not None:
return self._memory_contents
schedule = scheduler.minimize_peak_memory(self._graph, self._scheduler_alg)
self._memory_contents = self._graph.compute_memory_contents_under_schedule(
schedule)
return self._memory_contents | python | def _get_memory_contents(self):
"""Runs the scheduler to determine memory contents at every point in time.
Returns:
a list of frozenset of strings, where the ith entry describes the tensors
in memory when executing operation i (where schedule[i] is an index into
GetAllOperationNames()).
"""
if self._memory_contents is not None:
return self._memory_contents
schedule = scheduler.minimize_peak_memory(self._graph, self._scheduler_alg)
self._memory_contents = self._graph.compute_memory_contents_under_schedule(
schedule)
return self._memory_contents | [
"def",
"_get_memory_contents",
"(",
"self",
")",
":",
"if",
"self",
".",
"_memory_contents",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_memory_contents",
"schedule",
"=",
"scheduler",
".",
"minimize_peak_memory",
"(",
"self",
".",
"_graph",
",",
"self",
".",
"_scheduler_alg",
")",
"self",
".",
"_memory_contents",
"=",
"self",
".",
"_graph",
".",
"compute_memory_contents_under_schedule",
"(",
"schedule",
")",
"return",
"self",
".",
"_memory_contents"
] | Runs the scheduler to determine memory contents at every point in time.
Returns:
a list of frozenset of strings, where the ith entry describes the tensors
in memory when executing operation i (where schedule[i] is an index into
GetAllOperationNames()). | [
"Runs",
"the",
"scheduler",
"to",
"determine",
"memory",
"contents",
"at",
"every",
"point",
"in",
"time",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout_optimizer.py#L268-L283 |
227,836 | tensorflow/mesh | mesh_tensorflow/auto_mtf/layout_optimizer.py | LayoutOptimizer.solve | def solve(self, print_solution=False):
"""Solves the current integer program and returns the computed layout.
Args:
print_solution: An optional boolean indicating whether to print the full
solution in human-readable format.
Returns:
The computed layout (as a string).
Raises:
SolverError: the internal solver could not find a solution, or the
solution found is infeasible.
"""
# Solve and see how well the solver did.
self._cp_solver = cp_model.CpSolver()
status = self._cp_solver.Solve(self._model)
if status != cp_model.OPTIMAL:
if status == cp_model.FEASIBLE:
logging.warning("A potentially suboptimal solution was found.")
else:
logging.error("Solver returned status %d.", status)
raise SolverError("The solver could not solve the problem and returned "
"status {}.".format(status))
# TODO(joshuawang): Verify the solver's solution.
if print_solution:
print_cp_model_solution.print_solution(self._model, self._cp_solver)
# Reconstruct layout from solution.
layout = []
for mtf_dimension_name in (
self._layout_validator.splittable_mtf_dimension_names):
for mesh_dimension_name in (
self._layout_validator.mesh_dimension_name_to_size):
value = self._cp_solver.Value(self._global_vars[(mtf_dimension_name,
mesh_dimension_name)])
if value: # Value is integer.
layout.append(mtf_dimension_name + ":" + mesh_dimension_name)
layout.sort()
return ";".join(layout) | python | def solve(self, print_solution=False):
"""Solves the current integer program and returns the computed layout.
Args:
print_solution: An optional boolean indicating whether to print the full
solution in human-readable format.
Returns:
The computed layout (as a string).
Raises:
SolverError: the internal solver could not find a solution, or the
solution found is infeasible.
"""
# Solve and see how well the solver did.
self._cp_solver = cp_model.CpSolver()
status = self._cp_solver.Solve(self._model)
if status != cp_model.OPTIMAL:
if status == cp_model.FEASIBLE:
logging.warning("A potentially suboptimal solution was found.")
else:
logging.error("Solver returned status %d.", status)
raise SolverError("The solver could not solve the problem and returned "
"status {}.".format(status))
# TODO(joshuawang): Verify the solver's solution.
if print_solution:
print_cp_model_solution.print_solution(self._model, self._cp_solver)
# Reconstruct layout from solution.
layout = []
for mtf_dimension_name in (
self._layout_validator.splittable_mtf_dimension_names):
for mesh_dimension_name in (
self._layout_validator.mesh_dimension_name_to_size):
value = self._cp_solver.Value(self._global_vars[(mtf_dimension_name,
mesh_dimension_name)])
if value: # Value is integer.
layout.append(mtf_dimension_name + ":" + mesh_dimension_name)
layout.sort()
return ";".join(layout) | [
"def",
"solve",
"(",
"self",
",",
"print_solution",
"=",
"False",
")",
":",
"# Solve and see how well the solver did.",
"self",
".",
"_cp_solver",
"=",
"cp_model",
".",
"CpSolver",
"(",
")",
"status",
"=",
"self",
".",
"_cp_solver",
".",
"Solve",
"(",
"self",
".",
"_model",
")",
"if",
"status",
"!=",
"cp_model",
".",
"OPTIMAL",
":",
"if",
"status",
"==",
"cp_model",
".",
"FEASIBLE",
":",
"logging",
".",
"warning",
"(",
"\"A potentially suboptimal solution was found.\"",
")",
"else",
":",
"logging",
".",
"error",
"(",
"\"Solver returned status %d.\"",
",",
"status",
")",
"raise",
"SolverError",
"(",
"\"The solver could not solve the problem and returned \"",
"\"status {}.\"",
".",
"format",
"(",
"status",
")",
")",
"# TODO(joshuawang): Verify the solver's solution.",
"if",
"print_solution",
":",
"print_cp_model_solution",
".",
"print_solution",
"(",
"self",
".",
"_model",
",",
"self",
".",
"_cp_solver",
")",
"# Reconstruct layout from solution.",
"layout",
"=",
"[",
"]",
"for",
"mtf_dimension_name",
"in",
"(",
"self",
".",
"_layout_validator",
".",
"splittable_mtf_dimension_names",
")",
":",
"for",
"mesh_dimension_name",
"in",
"(",
"self",
".",
"_layout_validator",
".",
"mesh_dimension_name_to_size",
")",
":",
"value",
"=",
"self",
".",
"_cp_solver",
".",
"Value",
"(",
"self",
".",
"_global_vars",
"[",
"(",
"mtf_dimension_name",
",",
"mesh_dimension_name",
")",
"]",
")",
"if",
"value",
":",
"# Value is integer.",
"layout",
".",
"append",
"(",
"mtf_dimension_name",
"+",
"\":\"",
"+",
"mesh_dimension_name",
")",
"layout",
".",
"sort",
"(",
")",
"return",
"\";\"",
".",
"join",
"(",
"layout",
")"
] | Solves the current integer program and returns the computed layout.
Args:
print_solution: An optional boolean indicating whether to print the full
solution in human-readable format.
Returns:
The computed layout (as a string).
Raises:
SolverError: the internal solver could not find a solution, or the
solution found is infeasible. | [
"Solves",
"the",
"current",
"integer",
"program",
"and",
"returns",
"the",
"computed",
"layout",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout_optimizer.py#L285-L326 |
227,837 | tensorflow/mesh | mesh_tensorflow/auto_mtf/layout_optimizer.py | LayoutOptimizer.evaluate_layout | def evaluate_layout(self, layout):
"""The current objective value for the given layout.
TODO(joshuawang): The current function does not check that the given
layout is valid.
Args:
layout: a string, representing a layout to evaluate (e.g.
"d_ff:m1;heads:m2").
Returns:
A float, the objective value.
"""
layout_dict = {}
if layout:
for pair in layout.split(";"):
mtf_dimension_name, mesh_dimension_name = pair.split(":", 1)
if (mtf_dimension_name in
self._layout_validator.splittable_mtf_dimension_names):
layout_dict[mtf_dimension_name] = mesh_dimension_name
else:
logging.warning("Skipping unsplittable dimension %s.",
mtf_dimension_name)
tensor_memory = {} # {string: float}, size of each tensor under our layout
for tensor_name in self._graph.get_all_tensor_names():
if self._graph.is_tensor_on_canonical_device(tensor_name):
tensor_memory[tensor_name] = self._graph.get_tensor_size(
tensor_name, layout_dict,
self._layout_validator.mesh_dimension_name_to_size)
else:
tensor_memory[tensor_name] = 0.0
peak_memory_usage = 0.0
for tensor_names in self._get_memory_contents():
memory_usage = 0.0
for tensor_name in tensor_names:
memory_usage += tensor_memory[tensor_name]
peak_memory_usage = max(peak_memory_usage, memory_usage)
return peak_memory_usage | python | def evaluate_layout(self, layout):
"""The current objective value for the given layout.
TODO(joshuawang): The current function does not check that the given
layout is valid.
Args:
layout: a string, representing a layout to evaluate (e.g.
"d_ff:m1;heads:m2").
Returns:
A float, the objective value.
"""
layout_dict = {}
if layout:
for pair in layout.split(";"):
mtf_dimension_name, mesh_dimension_name = pair.split(":", 1)
if (mtf_dimension_name in
self._layout_validator.splittable_mtf_dimension_names):
layout_dict[mtf_dimension_name] = mesh_dimension_name
else:
logging.warning("Skipping unsplittable dimension %s.",
mtf_dimension_name)
tensor_memory = {} # {string: float}, size of each tensor under our layout
for tensor_name in self._graph.get_all_tensor_names():
if self._graph.is_tensor_on_canonical_device(tensor_name):
tensor_memory[tensor_name] = self._graph.get_tensor_size(
tensor_name, layout_dict,
self._layout_validator.mesh_dimension_name_to_size)
else:
tensor_memory[tensor_name] = 0.0
peak_memory_usage = 0.0
for tensor_names in self._get_memory_contents():
memory_usage = 0.0
for tensor_name in tensor_names:
memory_usage += tensor_memory[tensor_name]
peak_memory_usage = max(peak_memory_usage, memory_usage)
return peak_memory_usage | [
"def",
"evaluate_layout",
"(",
"self",
",",
"layout",
")",
":",
"layout_dict",
"=",
"{",
"}",
"if",
"layout",
":",
"for",
"pair",
"in",
"layout",
".",
"split",
"(",
"\";\"",
")",
":",
"mtf_dimension_name",
",",
"mesh_dimension_name",
"=",
"pair",
".",
"split",
"(",
"\":\"",
",",
"1",
")",
"if",
"(",
"mtf_dimension_name",
"in",
"self",
".",
"_layout_validator",
".",
"splittable_mtf_dimension_names",
")",
":",
"layout_dict",
"[",
"mtf_dimension_name",
"]",
"=",
"mesh_dimension_name",
"else",
":",
"logging",
".",
"warning",
"(",
"\"Skipping unsplittable dimension %s.\"",
",",
"mtf_dimension_name",
")",
"tensor_memory",
"=",
"{",
"}",
"# {string: float}, size of each tensor under our layout",
"for",
"tensor_name",
"in",
"self",
".",
"_graph",
".",
"get_all_tensor_names",
"(",
")",
":",
"if",
"self",
".",
"_graph",
".",
"is_tensor_on_canonical_device",
"(",
"tensor_name",
")",
":",
"tensor_memory",
"[",
"tensor_name",
"]",
"=",
"self",
".",
"_graph",
".",
"get_tensor_size",
"(",
"tensor_name",
",",
"layout_dict",
",",
"self",
".",
"_layout_validator",
".",
"mesh_dimension_name_to_size",
")",
"else",
":",
"tensor_memory",
"[",
"tensor_name",
"]",
"=",
"0.0",
"peak_memory_usage",
"=",
"0.0",
"for",
"tensor_names",
"in",
"self",
".",
"_get_memory_contents",
"(",
")",
":",
"memory_usage",
"=",
"0.0",
"for",
"tensor_name",
"in",
"tensor_names",
":",
"memory_usage",
"+=",
"tensor_memory",
"[",
"tensor_name",
"]",
"peak_memory_usage",
"=",
"max",
"(",
"peak_memory_usage",
",",
"memory_usage",
")",
"return",
"peak_memory_usage"
] | The current objective value for the given layout.
TODO(joshuawang): The current function does not check that the given
layout is valid.
Args:
layout: a string, representing a layout to evaluate (e.g.
"d_ff:m1;heads:m2").
Returns:
A float, the objective value. | [
"The",
"current",
"objective",
"value",
"for",
"the",
"given",
"layout",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout_optimizer.py#L328-L367 |
227,838 | tensorflow/mesh | mesh_tensorflow/utils.py | BalancedVariablePlacer.device_function | def device_function(self, var):
"""Choose a device for the input variable.
Args:
var: an Variable.
Returns:
The device for placing the var.
"""
if var.type not in ('Variable', 'VariableV2', 'VarHandleOp'):
tf.logging.debug('Place {} on last device: {}.'.format(
var.name, self._last_device))
return self._last_device
shape = tf.TensorShape(var.get_attr('shape'))
assert shape.num_elements() is not None
size = var.get_attr('dtype').size
mem, device = heapq.heappop(self._mem_device_heap)
mem += shape.num_elements() * size
heapq.heappush(self._mem_device_heap, (mem, device))
tf.logging.debug('Place variable {} on {} and consumes {} Bytes.'.format(
var.name, device, mem))
self._last_device = device
return device | python | def device_function(self, var):
"""Choose a device for the input variable.
Args:
var: an Variable.
Returns:
The device for placing the var.
"""
if var.type not in ('Variable', 'VariableV2', 'VarHandleOp'):
tf.logging.debug('Place {} on last device: {}.'.format(
var.name, self._last_device))
return self._last_device
shape = tf.TensorShape(var.get_attr('shape'))
assert shape.num_elements() is not None
size = var.get_attr('dtype').size
mem, device = heapq.heappop(self._mem_device_heap)
mem += shape.num_elements() * size
heapq.heappush(self._mem_device_heap, (mem, device))
tf.logging.debug('Place variable {} on {} and consumes {} Bytes.'.format(
var.name, device, mem))
self._last_device = device
return device | [
"def",
"device_function",
"(",
"self",
",",
"var",
")",
":",
"if",
"var",
".",
"type",
"not",
"in",
"(",
"'Variable'",
",",
"'VariableV2'",
",",
"'VarHandleOp'",
")",
":",
"tf",
".",
"logging",
".",
"debug",
"(",
"'Place {} on last device: {}.'",
".",
"format",
"(",
"var",
".",
"name",
",",
"self",
".",
"_last_device",
")",
")",
"return",
"self",
".",
"_last_device",
"shape",
"=",
"tf",
".",
"TensorShape",
"(",
"var",
".",
"get_attr",
"(",
"'shape'",
")",
")",
"assert",
"shape",
".",
"num_elements",
"(",
")",
"is",
"not",
"None",
"size",
"=",
"var",
".",
"get_attr",
"(",
"'dtype'",
")",
".",
"size",
"mem",
",",
"device",
"=",
"heapq",
".",
"heappop",
"(",
"self",
".",
"_mem_device_heap",
")",
"mem",
"+=",
"shape",
".",
"num_elements",
"(",
")",
"*",
"size",
"heapq",
".",
"heappush",
"(",
"self",
".",
"_mem_device_heap",
",",
"(",
"mem",
",",
"device",
")",
")",
"tf",
".",
"logging",
".",
"debug",
"(",
"'Place variable {} on {} and consumes {} Bytes.'",
".",
"format",
"(",
"var",
".",
"name",
",",
"device",
",",
"mem",
")",
")",
"self",
".",
"_last_device",
"=",
"device",
"return",
"device"
] | Choose a device for the input variable.
Args:
var: an Variable.
Returns:
The device for placing the var. | [
"Choose",
"a",
"device",
"for",
"the",
"input",
"variable",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/utils.py#L45-L70 |
227,839 | tensorflow/mesh | mesh_tensorflow/beam_search.py | greedy_decode | def greedy_decode(logits_fn,
initial_ids,
temperature=0.0,
initial_states=None,
eos_id=EOS_ID,
forced_ids=None,
use_tpu=True):
"""Greedy decoding.
Args:
logits_fn: Interface to the model, to provide logits.
Shoud take:
step_num - mtf Scalar
ids - mtf Tensor with shape [..., length]
states - list of mtf.Tensor
Should return:
logits - [batch, vocab_size]
new_states - list of mtf.Tensor
initial_ids: mtf.Tensor with shape [..., length], containing zeros.
temperature: a float between 0.0 (argmax) and 1.0 (random)
initial_states: list of mtf.Tensor
eos_id: ID for end of sentence.
forced_ids: optional mtf.Tensor with shape [..., length]
use_tpu: a boolean
Returns:
Tensor with shape [..., length]
"""
length_dim = initial_ids.shape.dims[-1]
mesh = initial_ids.mesh
num_steps = mtf.constant(mesh, length_dim.size, dtype=tf.int32)
def cond_fn(step_num, prev_ids, *unused_states):
"""Should we run another loop iteration."""
overflow = mtf.equal(step_num, num_steps)
has_eos = mtf.reduce_any(
mtf.equal(prev_ids, eos_id), reduced_dim=length_dim)
all_has_eos = mtf.reduce_all(has_eos)
return mtf.logical_not(mtf.logical_or(overflow, all_has_eos))
def body_fn(step_num, ids, *states):
"""Body function for greedy decoding.
Args:
step_num: a mtf.Tensor
ids: a mtf.Tensor
*states: additional mtf.Tensors
Returns:
new_step_num, new_ids, *new_states
"""
logits, new_states = logits_fn(step_num, ids, states)
vocab_dim = logits.shape.dims[-1]
new_ids = mtf.sample_with_temperature(
logits, vocab_dim, temperature)
if forced_ids is not None:
# force the new ids to equal the partial targets where specified
# (positions where partial_targets contain nonzero values)
forced = mtf.gather(forced_ids, step_num, length_dim)
new_ids = forced + new_ids * mtf.to_int32(mtf.equal(forced, 0))
ids += new_ids * mtf.one_hot(step_num, length_dim, dtype=tf.int32)
new_step_num = step_num + 1
return [new_step_num, ids] + new_states
initial_step_num = mtf.constant(mesh, 0, dtype=tf.int32)
while_loop_inputs = [initial_step_num, initial_ids] + initial_states
final_step_num, mtf_samples = mtf.while_loop(
cond_fn, body_fn, while_loop_inputs,
num_loop_vars=None if use_tpu else 2)[:2]
mtf_samples = mtf.Print(mtf_samples, [final_step_num], "output_length")
return mtf_samples | python | def greedy_decode(logits_fn,
initial_ids,
temperature=0.0,
initial_states=None,
eos_id=EOS_ID,
forced_ids=None,
use_tpu=True):
"""Greedy decoding.
Args:
logits_fn: Interface to the model, to provide logits.
Shoud take:
step_num - mtf Scalar
ids - mtf Tensor with shape [..., length]
states - list of mtf.Tensor
Should return:
logits - [batch, vocab_size]
new_states - list of mtf.Tensor
initial_ids: mtf.Tensor with shape [..., length], containing zeros.
temperature: a float between 0.0 (argmax) and 1.0 (random)
initial_states: list of mtf.Tensor
eos_id: ID for end of sentence.
forced_ids: optional mtf.Tensor with shape [..., length]
use_tpu: a boolean
Returns:
Tensor with shape [..., length]
"""
length_dim = initial_ids.shape.dims[-1]
mesh = initial_ids.mesh
num_steps = mtf.constant(mesh, length_dim.size, dtype=tf.int32)
def cond_fn(step_num, prev_ids, *unused_states):
"""Should we run another loop iteration."""
overflow = mtf.equal(step_num, num_steps)
has_eos = mtf.reduce_any(
mtf.equal(prev_ids, eos_id), reduced_dim=length_dim)
all_has_eos = mtf.reduce_all(has_eos)
return mtf.logical_not(mtf.logical_or(overflow, all_has_eos))
def body_fn(step_num, ids, *states):
"""Body function for greedy decoding.
Args:
step_num: a mtf.Tensor
ids: a mtf.Tensor
*states: additional mtf.Tensors
Returns:
new_step_num, new_ids, *new_states
"""
logits, new_states = logits_fn(step_num, ids, states)
vocab_dim = logits.shape.dims[-1]
new_ids = mtf.sample_with_temperature(
logits, vocab_dim, temperature)
if forced_ids is not None:
# force the new ids to equal the partial targets where specified
# (positions where partial_targets contain nonzero values)
forced = mtf.gather(forced_ids, step_num, length_dim)
new_ids = forced + new_ids * mtf.to_int32(mtf.equal(forced, 0))
ids += new_ids * mtf.one_hot(step_num, length_dim, dtype=tf.int32)
new_step_num = step_num + 1
return [new_step_num, ids] + new_states
initial_step_num = mtf.constant(mesh, 0, dtype=tf.int32)
while_loop_inputs = [initial_step_num, initial_ids] + initial_states
final_step_num, mtf_samples = mtf.while_loop(
cond_fn, body_fn, while_loop_inputs,
num_loop_vars=None if use_tpu else 2)[:2]
mtf_samples = mtf.Print(mtf_samples, [final_step_num], "output_length")
return mtf_samples | [
"def",
"greedy_decode",
"(",
"logits_fn",
",",
"initial_ids",
",",
"temperature",
"=",
"0.0",
",",
"initial_states",
"=",
"None",
",",
"eos_id",
"=",
"EOS_ID",
",",
"forced_ids",
"=",
"None",
",",
"use_tpu",
"=",
"True",
")",
":",
"length_dim",
"=",
"initial_ids",
".",
"shape",
".",
"dims",
"[",
"-",
"1",
"]",
"mesh",
"=",
"initial_ids",
".",
"mesh",
"num_steps",
"=",
"mtf",
".",
"constant",
"(",
"mesh",
",",
"length_dim",
".",
"size",
",",
"dtype",
"=",
"tf",
".",
"int32",
")",
"def",
"cond_fn",
"(",
"step_num",
",",
"prev_ids",
",",
"*",
"unused_states",
")",
":",
"\"\"\"Should we run another loop iteration.\"\"\"",
"overflow",
"=",
"mtf",
".",
"equal",
"(",
"step_num",
",",
"num_steps",
")",
"has_eos",
"=",
"mtf",
".",
"reduce_any",
"(",
"mtf",
".",
"equal",
"(",
"prev_ids",
",",
"eos_id",
")",
",",
"reduced_dim",
"=",
"length_dim",
")",
"all_has_eos",
"=",
"mtf",
".",
"reduce_all",
"(",
"has_eos",
")",
"return",
"mtf",
".",
"logical_not",
"(",
"mtf",
".",
"logical_or",
"(",
"overflow",
",",
"all_has_eos",
")",
")",
"def",
"body_fn",
"(",
"step_num",
",",
"ids",
",",
"*",
"states",
")",
":",
"\"\"\"Body function for greedy decoding.\n\n Args:\n step_num: a mtf.Tensor\n ids: a mtf.Tensor\n *states: additional mtf.Tensors\n Returns:\n new_step_num, new_ids, *new_states\n \"\"\"",
"logits",
",",
"new_states",
"=",
"logits_fn",
"(",
"step_num",
",",
"ids",
",",
"states",
")",
"vocab_dim",
"=",
"logits",
".",
"shape",
".",
"dims",
"[",
"-",
"1",
"]",
"new_ids",
"=",
"mtf",
".",
"sample_with_temperature",
"(",
"logits",
",",
"vocab_dim",
",",
"temperature",
")",
"if",
"forced_ids",
"is",
"not",
"None",
":",
"# force the new ids to equal the partial targets where specified",
"# (positions where partial_targets contain nonzero values)",
"forced",
"=",
"mtf",
".",
"gather",
"(",
"forced_ids",
",",
"step_num",
",",
"length_dim",
")",
"new_ids",
"=",
"forced",
"+",
"new_ids",
"*",
"mtf",
".",
"to_int32",
"(",
"mtf",
".",
"equal",
"(",
"forced",
",",
"0",
")",
")",
"ids",
"+=",
"new_ids",
"*",
"mtf",
".",
"one_hot",
"(",
"step_num",
",",
"length_dim",
",",
"dtype",
"=",
"tf",
".",
"int32",
")",
"new_step_num",
"=",
"step_num",
"+",
"1",
"return",
"[",
"new_step_num",
",",
"ids",
"]",
"+",
"new_states",
"initial_step_num",
"=",
"mtf",
".",
"constant",
"(",
"mesh",
",",
"0",
",",
"dtype",
"=",
"tf",
".",
"int32",
")",
"while_loop_inputs",
"=",
"[",
"initial_step_num",
",",
"initial_ids",
"]",
"+",
"initial_states",
"final_step_num",
",",
"mtf_samples",
"=",
"mtf",
".",
"while_loop",
"(",
"cond_fn",
",",
"body_fn",
",",
"while_loop_inputs",
",",
"num_loop_vars",
"=",
"None",
"if",
"use_tpu",
"else",
"2",
")",
"[",
":",
"2",
"]",
"mtf_samples",
"=",
"mtf",
".",
"Print",
"(",
"mtf_samples",
",",
"[",
"final_step_num",
"]",
",",
"\"output_length\"",
")",
"return",
"mtf_samples"
] | Greedy decoding.
Args:
logits_fn: Interface to the model, to provide logits.
Shoud take:
step_num - mtf Scalar
ids - mtf Tensor with shape [..., length]
states - list of mtf.Tensor
Should return:
logits - [batch, vocab_size]
new_states - list of mtf.Tensor
initial_ids: mtf.Tensor with shape [..., length], containing zeros.
temperature: a float between 0.0 (argmax) and 1.0 (random)
initial_states: list of mtf.Tensor
eos_id: ID for end of sentence.
forced_ids: optional mtf.Tensor with shape [..., length]
use_tpu: a boolean
Returns:
Tensor with shape [..., length] | [
"Greedy",
"decoding",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/beam_search.py#L577-L642 |
227,840 | tensorflow/mesh | mesh_tensorflow/transformer/dataset.py | pack_and_batch | def pack_and_batch(dataset, batch_size, length, pack=True):
"""Create a tf.data.Dataset which emits training batches.
The input dataset emits feature-dictionaries where each feature is a vector
of integers ending in EOS=1
The tensors in the returned tf.data.Dataset have shape
[batch_size, length]. Zeros indicate padding.
length indicates the length of the emitted examples. Examples with
inputs/targets longer than length get truncated.
TODO(noam): for text2self problems, we should just chop too-long
sequences into multiple parts and train on all of them.
If pack=False, then each emitted example will contain one
example emitted by load_internal().
If pack=True, then multiple examples emitted by load_internal() are
concatenated to form one combined example with the given length.
See comments in the function pack_dataset().
batch_size indicates the number of (combined) examples per batch,
across all cores.
Args:
dataset: a tf.data.Dataset
batch_size: an integer
length: an integer
pack: a boolean
Returns:
a tf.data.Dataset where all features have fixed shape [batch, length].
"""
if pack:
dataset = pack_dataset(dataset, length=length)
# Pad/trim length of each example to length
dataset = dataset.map(
functools.partial(trim_and_pad_all_features, length=length),
num_parallel_calls=tf.data.experimental.AUTOTUNE
)
dataset = dataset.batch(batch_size, drop_remainder=False)
# Pad batch size of each batch to batch_size
dataset = dataset.map(
functools.partial(trim_and_pad_all_features, length=batch_size),
num_parallel_calls=tf.data.experimental.AUTOTUNE
)
# Remind TensorFlow of the shape
dataset = dataset.map(
lambda x: {k: tf.reshape(v, (batch_size, length)) for k, v in x.items()},
num_parallel_calls=tf.data.experimental.AUTOTUNE
)
dataset = dataset.prefetch(100)
return dataset | python | def pack_and_batch(dataset, batch_size, length, pack=True):
"""Create a tf.data.Dataset which emits training batches.
The input dataset emits feature-dictionaries where each feature is a vector
of integers ending in EOS=1
The tensors in the returned tf.data.Dataset have shape
[batch_size, length]. Zeros indicate padding.
length indicates the length of the emitted examples. Examples with
inputs/targets longer than length get truncated.
TODO(noam): for text2self problems, we should just chop too-long
sequences into multiple parts and train on all of them.
If pack=False, then each emitted example will contain one
example emitted by load_internal().
If pack=True, then multiple examples emitted by load_internal() are
concatenated to form one combined example with the given length.
See comments in the function pack_dataset().
batch_size indicates the number of (combined) examples per batch,
across all cores.
Args:
dataset: a tf.data.Dataset
batch_size: an integer
length: an integer
pack: a boolean
Returns:
a tf.data.Dataset where all features have fixed shape [batch, length].
"""
if pack:
dataset = pack_dataset(dataset, length=length)
# Pad/trim length of each example to length
dataset = dataset.map(
functools.partial(trim_and_pad_all_features, length=length),
num_parallel_calls=tf.data.experimental.AUTOTUNE
)
dataset = dataset.batch(batch_size, drop_remainder=False)
# Pad batch size of each batch to batch_size
dataset = dataset.map(
functools.partial(trim_and_pad_all_features, length=batch_size),
num_parallel_calls=tf.data.experimental.AUTOTUNE
)
# Remind TensorFlow of the shape
dataset = dataset.map(
lambda x: {k: tf.reshape(v, (batch_size, length)) for k, v in x.items()},
num_parallel_calls=tf.data.experimental.AUTOTUNE
)
dataset = dataset.prefetch(100)
return dataset | [
"def",
"pack_and_batch",
"(",
"dataset",
",",
"batch_size",
",",
"length",
",",
"pack",
"=",
"True",
")",
":",
"if",
"pack",
":",
"dataset",
"=",
"pack_dataset",
"(",
"dataset",
",",
"length",
"=",
"length",
")",
"# Pad/trim length of each example to length",
"dataset",
"=",
"dataset",
".",
"map",
"(",
"functools",
".",
"partial",
"(",
"trim_and_pad_all_features",
",",
"length",
"=",
"length",
")",
",",
"num_parallel_calls",
"=",
"tf",
".",
"data",
".",
"experimental",
".",
"AUTOTUNE",
")",
"dataset",
"=",
"dataset",
".",
"batch",
"(",
"batch_size",
",",
"drop_remainder",
"=",
"False",
")",
"# Pad batch size of each batch to batch_size",
"dataset",
"=",
"dataset",
".",
"map",
"(",
"functools",
".",
"partial",
"(",
"trim_and_pad_all_features",
",",
"length",
"=",
"batch_size",
")",
",",
"num_parallel_calls",
"=",
"tf",
".",
"data",
".",
"experimental",
".",
"AUTOTUNE",
")",
"# Remind TensorFlow of the shape",
"dataset",
"=",
"dataset",
".",
"map",
"(",
"lambda",
"x",
":",
"{",
"k",
":",
"tf",
".",
"reshape",
"(",
"v",
",",
"(",
"batch_size",
",",
"length",
")",
")",
"for",
"k",
",",
"v",
"in",
"x",
".",
"items",
"(",
")",
"}",
",",
"num_parallel_calls",
"=",
"tf",
".",
"data",
".",
"experimental",
".",
"AUTOTUNE",
")",
"dataset",
"=",
"dataset",
".",
"prefetch",
"(",
"100",
")",
"return",
"dataset"
] | Create a tf.data.Dataset which emits training batches.
The input dataset emits feature-dictionaries where each feature is a vector
of integers ending in EOS=1
The tensors in the returned tf.data.Dataset have shape
[batch_size, length]. Zeros indicate padding.
length indicates the length of the emitted examples. Examples with
inputs/targets longer than length get truncated.
TODO(noam): for text2self problems, we should just chop too-long
sequences into multiple parts and train on all of them.
If pack=False, then each emitted example will contain one
example emitted by load_internal().
If pack=True, then multiple examples emitted by load_internal() are
concatenated to form one combined example with the given length.
See comments in the function pack_dataset().
batch_size indicates the number of (combined) examples per batch,
across all cores.
Args:
dataset: a tf.data.Dataset
batch_size: an integer
length: an integer
pack: a boolean
Returns:
a tf.data.Dataset where all features have fixed shape [batch, length]. | [
"Create",
"a",
"tf",
".",
"data",
".",
"Dataset",
"which",
"emits",
"training",
"batches",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L98-L150 |
227,841 | tensorflow/mesh | mesh_tensorflow/transformer/dataset.py | encode_dataset | def encode_dataset(dataset, vocabulary):
"""Encode from strings to token ids.
Args:
dataset: a tf.data.Dataset with string values.
vocabulary: a mesh_tensorflow.transformer.Vocabulary
Returns:
a tf.data.Dataset with integer-vector values ending in EOS=1
"""
def encode(features):
return {k: vocabulary.encode_tf(v) for k, v in features.items()}
return dataset.map(encode, num_parallel_calls=tf.data.experimental.AUTOTUNE) | python | def encode_dataset(dataset, vocabulary):
"""Encode from strings to token ids.
Args:
dataset: a tf.data.Dataset with string values.
vocabulary: a mesh_tensorflow.transformer.Vocabulary
Returns:
a tf.data.Dataset with integer-vector values ending in EOS=1
"""
def encode(features):
return {k: vocabulary.encode_tf(v) for k, v in features.items()}
return dataset.map(encode, num_parallel_calls=tf.data.experimental.AUTOTUNE) | [
"def",
"encode_dataset",
"(",
"dataset",
",",
"vocabulary",
")",
":",
"def",
"encode",
"(",
"features",
")",
":",
"return",
"{",
"k",
":",
"vocabulary",
".",
"encode_tf",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"features",
".",
"items",
"(",
")",
"}",
"return",
"dataset",
".",
"map",
"(",
"encode",
",",
"num_parallel_calls",
"=",
"tf",
".",
"data",
".",
"experimental",
".",
"AUTOTUNE",
")"
] | Encode from strings to token ids.
Args:
dataset: a tf.data.Dataset with string values.
vocabulary: a mesh_tensorflow.transformer.Vocabulary
Returns:
a tf.data.Dataset with integer-vector values ending in EOS=1 | [
"Encode",
"from",
"strings",
"to",
"token",
"ids",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L153-L164 |
227,842 | tensorflow/mesh | mesh_tensorflow/transformer/dataset.py | packed_parallel_tsv_dataset | def packed_parallel_tsv_dataset(filenames=gin.REQUIRED,
dataset_split=gin.REQUIRED,
batch_size=gin.REQUIRED,
sequence_length=gin.REQUIRED,
vocabulary=gin.REQUIRED,
append_eos=True,
shuffle_buffer_size=10000,
eos_id=1):
"""Reads parallel tab-separated text file. One example per line."""
dataset = tf.data.TextLineDataset(filenames)
if dataset_split == "train":
dataset = dataset.repeat()
dataset = dataset.shuffle(shuffle_buffer_size)
def _parse_fn(record): # pylint: disable=missing-docstring
tokens = tf.decode_csv(
record,
record_defaults=[""] * 2,
field_delim="\t",
use_quote_delim=False)
return {"inputs": tokens[0], "targets": tokens[1]}
def _encode_fn(features): # pylint: disable=missing-docstring
inputs_vocabulary = vocabulary[0] if isinstance(vocabulary,
tuple) else vocabulary
targets_vocabulary = vocabulary[1] if isinstance(vocabulary,
tuple) else vocabulary
inputs_enc = inputs_vocabulary.encode_tf(features["inputs"])
targets_enc = targets_vocabulary.encode_tf(features["targets"])
if append_eos:
inputs_enc = tf.concat([tf.to_int64(inputs_enc), [eos_id]], 0)
targets_enc = tf.concat([tf.to_int64(targets_enc), [eos_id]], 0)
return {"inputs": inputs_enc, "targets": targets_enc}
dataset = dataset.map(_parse_fn)
dataset = dataset.map(_encode_fn)
return pack_and_batch(dataset, batch_size, sequence_length) | python | def packed_parallel_tsv_dataset(filenames=gin.REQUIRED,
dataset_split=gin.REQUIRED,
batch_size=gin.REQUIRED,
sequence_length=gin.REQUIRED,
vocabulary=gin.REQUIRED,
append_eos=True,
shuffle_buffer_size=10000,
eos_id=1):
"""Reads parallel tab-separated text file. One example per line."""
dataset = tf.data.TextLineDataset(filenames)
if dataset_split == "train":
dataset = dataset.repeat()
dataset = dataset.shuffle(shuffle_buffer_size)
def _parse_fn(record): # pylint: disable=missing-docstring
tokens = tf.decode_csv(
record,
record_defaults=[""] * 2,
field_delim="\t",
use_quote_delim=False)
return {"inputs": tokens[0], "targets": tokens[1]}
def _encode_fn(features): # pylint: disable=missing-docstring
inputs_vocabulary = vocabulary[0] if isinstance(vocabulary,
tuple) else vocabulary
targets_vocabulary = vocabulary[1] if isinstance(vocabulary,
tuple) else vocabulary
inputs_enc = inputs_vocabulary.encode_tf(features["inputs"])
targets_enc = targets_vocabulary.encode_tf(features["targets"])
if append_eos:
inputs_enc = tf.concat([tf.to_int64(inputs_enc), [eos_id]], 0)
targets_enc = tf.concat([tf.to_int64(targets_enc), [eos_id]], 0)
return {"inputs": inputs_enc, "targets": targets_enc}
dataset = dataset.map(_parse_fn)
dataset = dataset.map(_encode_fn)
return pack_and_batch(dataset, batch_size, sequence_length) | [
"def",
"packed_parallel_tsv_dataset",
"(",
"filenames",
"=",
"gin",
".",
"REQUIRED",
",",
"dataset_split",
"=",
"gin",
".",
"REQUIRED",
",",
"batch_size",
"=",
"gin",
".",
"REQUIRED",
",",
"sequence_length",
"=",
"gin",
".",
"REQUIRED",
",",
"vocabulary",
"=",
"gin",
".",
"REQUIRED",
",",
"append_eos",
"=",
"True",
",",
"shuffle_buffer_size",
"=",
"10000",
",",
"eos_id",
"=",
"1",
")",
":",
"dataset",
"=",
"tf",
".",
"data",
".",
"TextLineDataset",
"(",
"filenames",
")",
"if",
"dataset_split",
"==",
"\"train\"",
":",
"dataset",
"=",
"dataset",
".",
"repeat",
"(",
")",
"dataset",
"=",
"dataset",
".",
"shuffle",
"(",
"shuffle_buffer_size",
")",
"def",
"_parse_fn",
"(",
"record",
")",
":",
"# pylint: disable=missing-docstring",
"tokens",
"=",
"tf",
".",
"decode_csv",
"(",
"record",
",",
"record_defaults",
"=",
"[",
"\"\"",
"]",
"*",
"2",
",",
"field_delim",
"=",
"\"\\t\"",
",",
"use_quote_delim",
"=",
"False",
")",
"return",
"{",
"\"inputs\"",
":",
"tokens",
"[",
"0",
"]",
",",
"\"targets\"",
":",
"tokens",
"[",
"1",
"]",
"}",
"def",
"_encode_fn",
"(",
"features",
")",
":",
"# pylint: disable=missing-docstring",
"inputs_vocabulary",
"=",
"vocabulary",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"vocabulary",
",",
"tuple",
")",
"else",
"vocabulary",
"targets_vocabulary",
"=",
"vocabulary",
"[",
"1",
"]",
"if",
"isinstance",
"(",
"vocabulary",
",",
"tuple",
")",
"else",
"vocabulary",
"inputs_enc",
"=",
"inputs_vocabulary",
".",
"encode_tf",
"(",
"features",
"[",
"\"inputs\"",
"]",
")",
"targets_enc",
"=",
"targets_vocabulary",
".",
"encode_tf",
"(",
"features",
"[",
"\"targets\"",
"]",
")",
"if",
"append_eos",
":",
"inputs_enc",
"=",
"tf",
".",
"concat",
"(",
"[",
"tf",
".",
"to_int64",
"(",
"inputs_enc",
")",
",",
"[",
"eos_id",
"]",
"]",
",",
"0",
")",
"targets_enc",
"=",
"tf",
".",
"concat",
"(",
"[",
"tf",
".",
"to_int64",
"(",
"targets_enc",
")",
",",
"[",
"eos_id",
"]",
"]",
",",
"0",
")",
"return",
"{",
"\"inputs\"",
":",
"inputs_enc",
",",
"\"targets\"",
":",
"targets_enc",
"}",
"dataset",
"=",
"dataset",
".",
"map",
"(",
"_parse_fn",
")",
"dataset",
"=",
"dataset",
".",
"map",
"(",
"_encode_fn",
")",
"return",
"pack_and_batch",
"(",
"dataset",
",",
"batch_size",
",",
"sequence_length",
")"
] | Reads parallel tab-separated text file. One example per line. | [
"Reads",
"parallel",
"tab",
"-",
"separated",
"text",
"file",
".",
"One",
"example",
"per",
"line",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L213-L250 |
227,843 | tensorflow/mesh | mesh_tensorflow/transformer/dataset.py | supervised_to_dict | def supervised_to_dict(dataset, text2self):
"""Turns a supervised dataset into a dataset with a feature dictionary.
if text2self, then the features dictionary contains a "targets" key.
else, the features dictionary contains "inputs" and "targets" keys.
Args:
dataset: a tf.data.Dataset
text2self: a boolean
Returns:
a tf.data.Dataset
"""
def my_fn(inputs, targets):
if text2self:
return {"targets": targets}
else:
return {"inputs": inputs, "targets": targets}
return dataset.map(my_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE) | python | def supervised_to_dict(dataset, text2self):
"""Turns a supervised dataset into a dataset with a feature dictionary.
if text2self, then the features dictionary contains a "targets" key.
else, the features dictionary contains "inputs" and "targets" keys.
Args:
dataset: a tf.data.Dataset
text2self: a boolean
Returns:
a tf.data.Dataset
"""
def my_fn(inputs, targets):
if text2self:
return {"targets": targets}
else:
return {"inputs": inputs, "targets": targets}
return dataset.map(my_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE) | [
"def",
"supervised_to_dict",
"(",
"dataset",
",",
"text2self",
")",
":",
"def",
"my_fn",
"(",
"inputs",
",",
"targets",
")",
":",
"if",
"text2self",
":",
"return",
"{",
"\"targets\"",
":",
"targets",
"}",
"else",
":",
"return",
"{",
"\"inputs\"",
":",
"inputs",
",",
"\"targets\"",
":",
"targets",
"}",
"return",
"dataset",
".",
"map",
"(",
"my_fn",
",",
"num_parallel_calls",
"=",
"tf",
".",
"data",
".",
"experimental",
".",
"AUTOTUNE",
")"
] | Turns a supervised dataset into a dataset with a feature dictionary.
if text2self, then the features dictionary contains a "targets" key.
else, the features dictionary contains "inputs" and "targets" keys.
Args:
dataset: a tf.data.Dataset
text2self: a boolean
Returns:
a tf.data.Dataset | [
"Turns",
"a",
"supervised",
"dataset",
"into",
"a",
"dataset",
"with",
"a",
"feature",
"dictionary",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L291-L308 |
227,844 | tensorflow/mesh | mesh_tensorflow/transformer/dataset.py | encode_all_features | def encode_all_features(dataset, vocabulary):
"""Encode all features.
Args:
dataset: a tf.data.Dataset
vocabulary: a vocabulary.Vocabulary
Returns:
a tf.data.Dataset
"""
def my_fn(features):
ret = {}
for k, v in features.items():
v = vocabulary.encode_tf(v)
v = tf.concat([tf.to_int64(v), [1]], 0)
ret[k] = v
return ret
return dataset.map(my_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE) | python | def encode_all_features(dataset, vocabulary):
"""Encode all features.
Args:
dataset: a tf.data.Dataset
vocabulary: a vocabulary.Vocabulary
Returns:
a tf.data.Dataset
"""
def my_fn(features):
ret = {}
for k, v in features.items():
v = vocabulary.encode_tf(v)
v = tf.concat([tf.to_int64(v), [1]], 0)
ret[k] = v
return ret
return dataset.map(my_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE) | [
"def",
"encode_all_features",
"(",
"dataset",
",",
"vocabulary",
")",
":",
"def",
"my_fn",
"(",
"features",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"features",
".",
"items",
"(",
")",
":",
"v",
"=",
"vocabulary",
".",
"encode_tf",
"(",
"v",
")",
"v",
"=",
"tf",
".",
"concat",
"(",
"[",
"tf",
".",
"to_int64",
"(",
"v",
")",
",",
"[",
"1",
"]",
"]",
",",
"0",
")",
"ret",
"[",
"k",
"]",
"=",
"v",
"return",
"ret",
"return",
"dataset",
".",
"map",
"(",
"my_fn",
",",
"num_parallel_calls",
"=",
"tf",
".",
"data",
".",
"experimental",
".",
"AUTOTUNE",
")"
] | Encode all features.
Args:
dataset: a tf.data.Dataset
vocabulary: a vocabulary.Vocabulary
Returns:
a tf.data.Dataset | [
"Encode",
"all",
"features",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L311-L327 |
227,845 | tensorflow/mesh | mesh_tensorflow/transformer/dataset.py | pretokenized_tfrecord_dataset | def pretokenized_tfrecord_dataset(filenames,
text2self,
eos_included,
repeat,
batch_size,
sequence_length):
"""Reads tensor2tensor-style data files.
The dataset is defined by sets of TFRecord files of TFExample protos.
There should be a "targets" feature (a 1d tensor of integers)
If not text2self, there should also be an "inputs" feature.
Other features get ignored.
eos_included specifies whether the inputs and targets were written with an
EOS token, as in tensor2tensor
Args:
filenames: a list of strings
text2self: a boolean
eos_included: a boolean
repeat: a boolean
batch_size: an integer
sequence_length: an integer
Returns:
A tf.data.Dataset of batches
"""
dataset = tf.data.TFRecordDataset(filenames, buffer_size=64 * 1024 * 1024)
if repeat:
dataset = dataset.repeat()
keys = ["targets"] if text2self else ["inputs", "targets"]
def decode_example(serialized_example):
"""Return a dict of Tensors from a serialized tensorflow.Example."""
data_fields = {}
data_items_to_decoders = {}
for k in keys:
data_fields[k] = tf.VarLenFeature(tf.int64)
data_items_to_decoders[k] = tf.contrib.slim.tfexample_decoder.Tensor(k)
decoder = tf.contrib.slim.tfexample_decoder.TFExampleDecoder(
data_fields, data_items_to_decoders)
decode_items = list(sorted(data_items_to_decoders))
decoded = decoder.decode(serialized_example, items=decode_items)
if not eos_included:
decoded = [tf.concat([v, [1]], 0) for v in decoded]
return dict(zip(decode_items, decoded))
dataset = dataset.map(decode_example,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
return pack_and_batch(dataset, batch_size, sequence_length) | python | def pretokenized_tfrecord_dataset(filenames,
text2self,
eos_included,
repeat,
batch_size,
sequence_length):
"""Reads tensor2tensor-style data files.
The dataset is defined by sets of TFRecord files of TFExample protos.
There should be a "targets" feature (a 1d tensor of integers)
If not text2self, there should also be an "inputs" feature.
Other features get ignored.
eos_included specifies whether the inputs and targets were written with an
EOS token, as in tensor2tensor
Args:
filenames: a list of strings
text2self: a boolean
eos_included: a boolean
repeat: a boolean
batch_size: an integer
sequence_length: an integer
Returns:
A tf.data.Dataset of batches
"""
dataset = tf.data.TFRecordDataset(filenames, buffer_size=64 * 1024 * 1024)
if repeat:
dataset = dataset.repeat()
keys = ["targets"] if text2self else ["inputs", "targets"]
def decode_example(serialized_example):
"""Return a dict of Tensors from a serialized tensorflow.Example."""
data_fields = {}
data_items_to_decoders = {}
for k in keys:
data_fields[k] = tf.VarLenFeature(tf.int64)
data_items_to_decoders[k] = tf.contrib.slim.tfexample_decoder.Tensor(k)
decoder = tf.contrib.slim.tfexample_decoder.TFExampleDecoder(
data_fields, data_items_to_decoders)
decode_items = list(sorted(data_items_to_decoders))
decoded = decoder.decode(serialized_example, items=decode_items)
if not eos_included:
decoded = [tf.concat([v, [1]], 0) for v in decoded]
return dict(zip(decode_items, decoded))
dataset = dataset.map(decode_example,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
return pack_and_batch(dataset, batch_size, sequence_length) | [
"def",
"pretokenized_tfrecord_dataset",
"(",
"filenames",
",",
"text2self",
",",
"eos_included",
",",
"repeat",
",",
"batch_size",
",",
"sequence_length",
")",
":",
"dataset",
"=",
"tf",
".",
"data",
".",
"TFRecordDataset",
"(",
"filenames",
",",
"buffer_size",
"=",
"64",
"*",
"1024",
"*",
"1024",
")",
"if",
"repeat",
":",
"dataset",
"=",
"dataset",
".",
"repeat",
"(",
")",
"keys",
"=",
"[",
"\"targets\"",
"]",
"if",
"text2self",
"else",
"[",
"\"inputs\"",
",",
"\"targets\"",
"]",
"def",
"decode_example",
"(",
"serialized_example",
")",
":",
"\"\"\"Return a dict of Tensors from a serialized tensorflow.Example.\"\"\"",
"data_fields",
"=",
"{",
"}",
"data_items_to_decoders",
"=",
"{",
"}",
"for",
"k",
"in",
"keys",
":",
"data_fields",
"[",
"k",
"]",
"=",
"tf",
".",
"VarLenFeature",
"(",
"tf",
".",
"int64",
")",
"data_items_to_decoders",
"[",
"k",
"]",
"=",
"tf",
".",
"contrib",
".",
"slim",
".",
"tfexample_decoder",
".",
"Tensor",
"(",
"k",
")",
"decoder",
"=",
"tf",
".",
"contrib",
".",
"slim",
".",
"tfexample_decoder",
".",
"TFExampleDecoder",
"(",
"data_fields",
",",
"data_items_to_decoders",
")",
"decode_items",
"=",
"list",
"(",
"sorted",
"(",
"data_items_to_decoders",
")",
")",
"decoded",
"=",
"decoder",
".",
"decode",
"(",
"serialized_example",
",",
"items",
"=",
"decode_items",
")",
"if",
"not",
"eos_included",
":",
"decoded",
"=",
"[",
"tf",
".",
"concat",
"(",
"[",
"v",
",",
"[",
"1",
"]",
"]",
",",
"0",
")",
"for",
"v",
"in",
"decoded",
"]",
"return",
"dict",
"(",
"zip",
"(",
"decode_items",
",",
"decoded",
")",
")",
"dataset",
"=",
"dataset",
".",
"map",
"(",
"decode_example",
",",
"num_parallel_calls",
"=",
"tf",
".",
"data",
".",
"experimental",
".",
"AUTOTUNE",
")",
"return",
"pack_and_batch",
"(",
"dataset",
",",
"batch_size",
",",
"sequence_length",
")"
] | Reads tensor2tensor-style data files.
The dataset is defined by sets of TFRecord files of TFExample protos.
There should be a "targets" feature (a 1d tensor of integers)
If not text2self, there should also be an "inputs" feature.
Other features get ignored.
eos_included specifies whether the inputs and targets were written with an
EOS token, as in tensor2tensor
Args:
filenames: a list of strings
text2self: a boolean
eos_included: a boolean
repeat: a boolean
batch_size: an integer
sequence_length: an integer
Returns:
A tf.data.Dataset of batches | [
"Reads",
"tensor2tensor",
"-",
"style",
"data",
"files",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L330-L376 |
227,846 | tensorflow/mesh | mesh_tensorflow/transformer/dataset.py | pretokenized_t2t_dataset | def pretokenized_t2t_dataset(dataset_name=gin.REQUIRED,
text2self=False,
data_dir=gin.REQUIRED,
dataset_split="train",
batch_size=gin.REQUIRED,
sequence_length=gin.REQUIRED,
vocabulary=None):
"""Loads the Tensor2tensor dataset specified by dataset_name.
Args:
dataset_name: TensorFlow Datasets dataset name.
text2self: a boolean
data_dir: string, data_dir for TensorFlow Datasets
dataset_split: a string - "train" or "dev"
batch_size: an integer
sequence_length: an integer
vocabulary: ignored
Returns:
A tf.data.Dataset of batches
"""
del vocabulary
filepattern = os.path.join(
data_dir, dataset_name + "-" + dataset_split + "-*")
filenames = tf.gfile.Glob(filepattern)
tf.logging.info("Found %s files matching %s" % (len(filenames), filepattern))
if not filenames:
raise ValueError("No matching files found")
dataset = pretokenized_tfrecord_dataset(
filenames=filenames,
text2self=text2self,
eos_included=True,
repeat=dataset_split == "train",
batch_size=batch_size,
sequence_length=sequence_length)
if dataset_split == "train":
dataset = dataset.shuffle(1000)
return dataset | python | def pretokenized_t2t_dataset(dataset_name=gin.REQUIRED,
text2self=False,
data_dir=gin.REQUIRED,
dataset_split="train",
batch_size=gin.REQUIRED,
sequence_length=gin.REQUIRED,
vocabulary=None):
"""Loads the Tensor2tensor dataset specified by dataset_name.
Args:
dataset_name: TensorFlow Datasets dataset name.
text2self: a boolean
data_dir: string, data_dir for TensorFlow Datasets
dataset_split: a string - "train" or "dev"
batch_size: an integer
sequence_length: an integer
vocabulary: ignored
Returns:
A tf.data.Dataset of batches
"""
del vocabulary
filepattern = os.path.join(
data_dir, dataset_name + "-" + dataset_split + "-*")
filenames = tf.gfile.Glob(filepattern)
tf.logging.info("Found %s files matching %s" % (len(filenames), filepattern))
if not filenames:
raise ValueError("No matching files found")
dataset = pretokenized_tfrecord_dataset(
filenames=filenames,
text2self=text2self,
eos_included=True,
repeat=dataset_split == "train",
batch_size=batch_size,
sequence_length=sequence_length)
if dataset_split == "train":
dataset = dataset.shuffle(1000)
return dataset | [
"def",
"pretokenized_t2t_dataset",
"(",
"dataset_name",
"=",
"gin",
".",
"REQUIRED",
",",
"text2self",
"=",
"False",
",",
"data_dir",
"=",
"gin",
".",
"REQUIRED",
",",
"dataset_split",
"=",
"\"train\"",
",",
"batch_size",
"=",
"gin",
".",
"REQUIRED",
",",
"sequence_length",
"=",
"gin",
".",
"REQUIRED",
",",
"vocabulary",
"=",
"None",
")",
":",
"del",
"vocabulary",
"filepattern",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
"dataset_name",
"+",
"\"-\"",
"+",
"dataset_split",
"+",
"\"-*\"",
")",
"filenames",
"=",
"tf",
".",
"gfile",
".",
"Glob",
"(",
"filepattern",
")",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Found %s files matching %s\"",
"%",
"(",
"len",
"(",
"filenames",
")",
",",
"filepattern",
")",
")",
"if",
"not",
"filenames",
":",
"raise",
"ValueError",
"(",
"\"No matching files found\"",
")",
"dataset",
"=",
"pretokenized_tfrecord_dataset",
"(",
"filenames",
"=",
"filenames",
",",
"text2self",
"=",
"text2self",
",",
"eos_included",
"=",
"True",
",",
"repeat",
"=",
"dataset_split",
"==",
"\"train\"",
",",
"batch_size",
"=",
"batch_size",
",",
"sequence_length",
"=",
"sequence_length",
")",
"if",
"dataset_split",
"==",
"\"train\"",
":",
"dataset",
"=",
"dataset",
".",
"shuffle",
"(",
"1000",
")",
"return",
"dataset"
] | Loads the Tensor2tensor dataset specified by dataset_name.
Args:
dataset_name: TensorFlow Datasets dataset name.
text2self: a boolean
data_dir: string, data_dir for TensorFlow Datasets
dataset_split: a string - "train" or "dev"
batch_size: an integer
sequence_length: an integer
vocabulary: ignored
Returns:
A tf.data.Dataset of batches | [
"Loads",
"the",
"Tensor2tensor",
"dataset",
"specified",
"by",
"dataset_name",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L380-L417 |
227,847 | tensorflow/mesh | mesh_tensorflow/transformer/dataset.py | pack_dataset | def pack_dataset(dataset, length, keys=None, use_custom_ops=False):
"""Creates a 'packed' version of a dataset on-the-fly.
Borrowed from the tensor2tensor library.
TODO(noam): make this faster
This is meant to replace the irritation of having to create a separate
"packed" version of a dataset to train efficiently on TPU.
Each example in the output dataset represents several examples in the
input dataset.
For each key in the input dataset, two additional keys are created:
<key>_segmentation: an int32 tensor identifying the parts
representing the original example.
<key>_position: an int32 tensor identifying the position within the original
example.
Example:
Two input examples get combined to form an output example.
The input examples are:
{"inputs": [8, 7, 1, 0], "targets":[4, 1, 0]}
{"inputs": [2, 3, 4, 1], "targets":[5, 6, 1]}
The output example is:
{
"inputs": [8, 7, 1, 2, 3, 4, 1, 0, 0, 0]
"inputs_segmentation": [1, 1, 1, 2, 2, 2, 2, 0, 0, 0]
"inputs_position": [0, 1, 2, 0, 1, 2, 3, 0, 0, 0]
"targets": [4, 1, 5, 6, 1, 0, 0, 0, 0, 0]
"targets_segmentation": [1, 1, 2, 2, 2, 0, 0, 0, 0, 0]
"targets_position": [0, 1, 0, 1, 2, 0, 0, 0, 0, 0]
}
0 represents padding in both the inputs and the outputs.
Sequences in the incoming examples are truncated to length "length", and the
sequences in the output examples all have fixed (padded) length "length".
Args:
dataset: a tf.data.Dataset
length: an integer
keys: a list of strings (e.g. ["inputs", "targets"])
use_custom_ops: a boolean - custom ops are faster but require a custom-built
binary, which is not currently possible on cloud-tpu.
Returns:
a tf.data.Dataset
"""
shapes = dataset.output_shapes
if keys is None:
keys = shapes.keys()
for k in keys:
if k not in shapes:
raise ValueError("Key %s not found in dataset. Available keys are %s"
% (k, shapes.keys()))
if not shapes[k].is_compatible_with(tf.TensorShape([None])):
raise ValueError("Tensors to be packed must be one-dimensional.")
# trim to length
dataset = dataset.map(lambda x: {k: x[k][:length] for k in keys},
num_parallel_calls=tf.data.experimental.AUTOTUNE)
# Setting batch_size=length ensures that the concatenated sequences (if they
# have length >=1) are sufficient to fill at least one packed example.
batch_size = length
dataset = dataset.padded_batch(
batch_size, padded_shapes={k: [-1] for k in keys})
if use_custom_ops and len(keys) <= 2:
return _pack_with_custom_ops(dataset, keys, length)
else:
return _pack_with_tf_ops(dataset, keys, length) | python | def pack_dataset(dataset, length, keys=None, use_custom_ops=False):
"""Creates a 'packed' version of a dataset on-the-fly.
Borrowed from the tensor2tensor library.
TODO(noam): make this faster
This is meant to replace the irritation of having to create a separate
"packed" version of a dataset to train efficiently on TPU.
Each example in the output dataset represents several examples in the
input dataset.
For each key in the input dataset, two additional keys are created:
<key>_segmentation: an int32 tensor identifying the parts
representing the original example.
<key>_position: an int32 tensor identifying the position within the original
example.
Example:
Two input examples get combined to form an output example.
The input examples are:
{"inputs": [8, 7, 1, 0], "targets":[4, 1, 0]}
{"inputs": [2, 3, 4, 1], "targets":[5, 6, 1]}
The output example is:
{
"inputs": [8, 7, 1, 2, 3, 4, 1, 0, 0, 0]
"inputs_segmentation": [1, 1, 1, 2, 2, 2, 2, 0, 0, 0]
"inputs_position": [0, 1, 2, 0, 1, 2, 3, 0, 0, 0]
"targets": [4, 1, 5, 6, 1, 0, 0, 0, 0, 0]
"targets_segmentation": [1, 1, 2, 2, 2, 0, 0, 0, 0, 0]
"targets_position": [0, 1, 0, 1, 2, 0, 0, 0, 0, 0]
}
0 represents padding in both the inputs and the outputs.
Sequences in the incoming examples are truncated to length "length", and the
sequences in the output examples all have fixed (padded) length "length".
Args:
dataset: a tf.data.Dataset
length: an integer
keys: a list of strings (e.g. ["inputs", "targets"])
use_custom_ops: a boolean - custom ops are faster but require a custom-built
binary, which is not currently possible on cloud-tpu.
Returns:
a tf.data.Dataset
"""
shapes = dataset.output_shapes
if keys is None:
keys = shapes.keys()
for k in keys:
if k not in shapes:
raise ValueError("Key %s not found in dataset. Available keys are %s"
% (k, shapes.keys()))
if not shapes[k].is_compatible_with(tf.TensorShape([None])):
raise ValueError("Tensors to be packed must be one-dimensional.")
# trim to length
dataset = dataset.map(lambda x: {k: x[k][:length] for k in keys},
num_parallel_calls=tf.data.experimental.AUTOTUNE)
# Setting batch_size=length ensures that the concatenated sequences (if they
# have length >=1) are sufficient to fill at least one packed example.
batch_size = length
dataset = dataset.padded_batch(
batch_size, padded_shapes={k: [-1] for k in keys})
if use_custom_ops and len(keys) <= 2:
return _pack_with_custom_ops(dataset, keys, length)
else:
return _pack_with_tf_ops(dataset, keys, length) | [
"def",
"pack_dataset",
"(",
"dataset",
",",
"length",
",",
"keys",
"=",
"None",
",",
"use_custom_ops",
"=",
"False",
")",
":",
"shapes",
"=",
"dataset",
".",
"output_shapes",
"if",
"keys",
"is",
"None",
":",
"keys",
"=",
"shapes",
".",
"keys",
"(",
")",
"for",
"k",
"in",
"keys",
":",
"if",
"k",
"not",
"in",
"shapes",
":",
"raise",
"ValueError",
"(",
"\"Key %s not found in dataset. Available keys are %s\"",
"%",
"(",
"k",
",",
"shapes",
".",
"keys",
"(",
")",
")",
")",
"if",
"not",
"shapes",
"[",
"k",
"]",
".",
"is_compatible_with",
"(",
"tf",
".",
"TensorShape",
"(",
"[",
"None",
"]",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Tensors to be packed must be one-dimensional.\"",
")",
"# trim to length",
"dataset",
"=",
"dataset",
".",
"map",
"(",
"lambda",
"x",
":",
"{",
"k",
":",
"x",
"[",
"k",
"]",
"[",
":",
"length",
"]",
"for",
"k",
"in",
"keys",
"}",
",",
"num_parallel_calls",
"=",
"tf",
".",
"data",
".",
"experimental",
".",
"AUTOTUNE",
")",
"# Setting batch_size=length ensures that the concatenated sequences (if they",
"# have length >=1) are sufficient to fill at least one packed example.",
"batch_size",
"=",
"length",
"dataset",
"=",
"dataset",
".",
"padded_batch",
"(",
"batch_size",
",",
"padded_shapes",
"=",
"{",
"k",
":",
"[",
"-",
"1",
"]",
"for",
"k",
"in",
"keys",
"}",
")",
"if",
"use_custom_ops",
"and",
"len",
"(",
"keys",
")",
"<=",
"2",
":",
"return",
"_pack_with_custom_ops",
"(",
"dataset",
",",
"keys",
",",
"length",
")",
"else",
":",
"return",
"_pack_with_tf_ops",
"(",
"dataset",
",",
"keys",
",",
"length",
")"
] | Creates a 'packed' version of a dataset on-the-fly.
Borrowed from the tensor2tensor library.
TODO(noam): make this faster
This is meant to replace the irritation of having to create a separate
"packed" version of a dataset to train efficiently on TPU.
Each example in the output dataset represents several examples in the
input dataset.
For each key in the input dataset, two additional keys are created:
<key>_segmentation: an int32 tensor identifying the parts
representing the original example.
<key>_position: an int32 tensor identifying the position within the original
example.
Example:
Two input examples get combined to form an output example.
The input examples are:
{"inputs": [8, 7, 1, 0], "targets":[4, 1, 0]}
{"inputs": [2, 3, 4, 1], "targets":[5, 6, 1]}
The output example is:
{
"inputs": [8, 7, 1, 2, 3, 4, 1, 0, 0, 0]
"inputs_segmentation": [1, 1, 1, 2, 2, 2, 2, 0, 0, 0]
"inputs_position": [0, 1, 2, 0, 1, 2, 3, 0, 0, 0]
"targets": [4, 1, 5, 6, 1, 0, 0, 0, 0, 0]
"targets_segmentation": [1, 1, 2, 2, 2, 0, 0, 0, 0, 0]
"targets_position": [0, 1, 0, 1, 2, 0, 0, 0, 0, 0]
}
0 represents padding in both the inputs and the outputs.
Sequences in the incoming examples are truncated to length "length", and the
sequences in the output examples all have fixed (padded) length "length".
Args:
dataset: a tf.data.Dataset
length: an integer
keys: a list of strings (e.g. ["inputs", "targets"])
use_custom_ops: a boolean - custom ops are faster but require a custom-built
binary, which is not currently possible on cloud-tpu.
Returns:
a tf.data.Dataset | [
"Creates",
"a",
"packed",
"version",
"of",
"a",
"dataset",
"on",
"-",
"the",
"-",
"fly",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L421-L490 |
227,848 | tensorflow/mesh | mesh_tensorflow/transformer/dataset.py | trim_and_pad_all_features | def trim_and_pad_all_features(features, length):
"""Trim and pad first dimension of all features to size length."""
return {k: _trim_and_pad(v, length) for k, v in features.items()} | python | def trim_and_pad_all_features(features, length):
"""Trim and pad first dimension of all features to size length."""
return {k: _trim_and_pad(v, length) for k, v in features.items()} | [
"def",
"trim_and_pad_all_features",
"(",
"features",
",",
"length",
")",
":",
"return",
"{",
"k",
":",
"_trim_and_pad",
"(",
"v",
",",
"length",
")",
"for",
"k",
",",
"v",
"in",
"features",
".",
"items",
"(",
")",
"}"
] | Trim and pad first dimension of all features to size length. | [
"Trim",
"and",
"pad",
"first",
"dimension",
"of",
"all",
"features",
"to",
"size",
"length",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L667-L669 |
227,849 | tensorflow/mesh | mesh_tensorflow/ops.py | convert_to_dimension | def convert_to_dimension(d):
"""Converts input to a Dimension.
Args:
d: Dimension, tuple (string, int), or None.
Returns:
Dimension or None.
Raises:
ValueError: If d cannot be converted to a Dimension.
"""
if d is None:
return None
if isinstance(d, Dimension):
if not isinstance(d.name, str) or not isinstance(d.size, int):
raise ValueError("Bad dimension %s" % (d,))
return d
name, size = d
if isinstance(name, str) and isinstance(size, int):
return Dimension(name, size)
else:
raise ValueError("could not convert %s to Dimension" % (d,)) | python | def convert_to_dimension(d):
"""Converts input to a Dimension.
Args:
d: Dimension, tuple (string, int), or None.
Returns:
Dimension or None.
Raises:
ValueError: If d cannot be converted to a Dimension.
"""
if d is None:
return None
if isinstance(d, Dimension):
if not isinstance(d.name, str) or not isinstance(d.size, int):
raise ValueError("Bad dimension %s" % (d,))
return d
name, size = d
if isinstance(name, str) and isinstance(size, int):
return Dimension(name, size)
else:
raise ValueError("could not convert %s to Dimension" % (d,)) | [
"def",
"convert_to_dimension",
"(",
"d",
")",
":",
"if",
"d",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"d",
",",
"Dimension",
")",
":",
"if",
"not",
"isinstance",
"(",
"d",
".",
"name",
",",
"str",
")",
"or",
"not",
"isinstance",
"(",
"d",
".",
"size",
",",
"int",
")",
":",
"raise",
"ValueError",
"(",
"\"Bad dimension %s\"",
"%",
"(",
"d",
",",
")",
")",
"return",
"d",
"name",
",",
"size",
"=",
"d",
"if",
"isinstance",
"(",
"name",
",",
"str",
")",
"and",
"isinstance",
"(",
"size",
",",
"int",
")",
":",
"return",
"Dimension",
"(",
"name",
",",
"size",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"could not convert %s to Dimension\"",
"%",
"(",
"d",
",",
")",
")"
] | Converts input to a Dimension.
Args:
d: Dimension, tuple (string, int), or None.
Returns:
Dimension or None.
Raises:
ValueError: If d cannot be converted to a Dimension. | [
"Converts",
"input",
"to",
"a",
"Dimension",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L38-L60 |
227,850 | tensorflow/mesh | mesh_tensorflow/ops.py | convert_to_shape | def convert_to_shape(x):
"""Converts input to a Shape.
Args:
x: Shape, str, or None.
Returns:
Shape or None.
Raises:
ValueError: If x cannot be converted to a Shape.
"""
if x is None:
return None
if isinstance(x, Shape):
return x
if isinstance(x, str):
x = _parse_string_to_list_of_pairs(x, seconds_to_int=True)
return Shape(x) | python | def convert_to_shape(x):
"""Converts input to a Shape.
Args:
x: Shape, str, or None.
Returns:
Shape or None.
Raises:
ValueError: If x cannot be converted to a Shape.
"""
if x is None:
return None
if isinstance(x, Shape):
return x
if isinstance(x, str):
x = _parse_string_to_list_of_pairs(x, seconds_to_int=True)
return Shape(x) | [
"def",
"convert_to_shape",
"(",
"x",
")",
":",
"if",
"x",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"x",
",",
"Shape",
")",
":",
"return",
"x",
"if",
"isinstance",
"(",
"x",
",",
"str",
")",
":",
"x",
"=",
"_parse_string_to_list_of_pairs",
"(",
"x",
",",
"seconds_to_int",
"=",
"True",
")",
"return",
"Shape",
"(",
"x",
")"
] | Converts input to a Shape.
Args:
x: Shape, str, or None.
Returns:
Shape or None.
Raises:
ValueError: If x cannot be converted to a Shape. | [
"Converts",
"input",
"to",
"a",
"Shape",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L182-L200 |
227,851 | tensorflow/mesh | mesh_tensorflow/ops.py | convert_to_layout_rules | def convert_to_layout_rules(x):
"""Converts input to a LayoutRules.
Args:
x: LayoutRules, str, or set-like of string pairs.
Returns:
LayoutRules.
"""
if isinstance(x, LayoutRules):
return x
if isinstance(x, str):
x = _parse_string_to_list_of_pairs(x)
return LayoutRules(x) | python | def convert_to_layout_rules(x):
"""Converts input to a LayoutRules.
Args:
x: LayoutRules, str, or set-like of string pairs.
Returns:
LayoutRules.
"""
if isinstance(x, LayoutRules):
return x
if isinstance(x, str):
x = _parse_string_to_list_of_pairs(x)
return LayoutRules(x) | [
"def",
"convert_to_layout_rules",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"LayoutRules",
")",
":",
"return",
"x",
"if",
"isinstance",
"(",
"x",
",",
"str",
")",
":",
"x",
"=",
"_parse_string_to_list_of_pairs",
"(",
"x",
")",
"return",
"LayoutRules",
"(",
"x",
")"
] | Converts input to a LayoutRules.
Args:
x: LayoutRules, str, or set-like of string pairs.
Returns:
LayoutRules. | [
"Converts",
"input",
"to",
"a",
"LayoutRules",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L271-L284 |
227,852 | tensorflow/mesh | mesh_tensorflow/ops.py | convert_args_to_laid_out_tensors | def convert_args_to_laid_out_tensors(xs):
"""Convert list elements to laid-out-tensors when possible.
Args:
xs: a list
Returns:
a list
"""
ret = []
for x in xs:
if hasattr(x, "to_laid_out_tensor"):
ret.append(x.to_laid_out_tensor())
else:
ret.append(x)
return ret | python | def convert_args_to_laid_out_tensors(xs):
"""Convert list elements to laid-out-tensors when possible.
Args:
xs: a list
Returns:
a list
"""
ret = []
for x in xs:
if hasattr(x, "to_laid_out_tensor"):
ret.append(x.to_laid_out_tensor())
else:
ret.append(x)
return ret | [
"def",
"convert_args_to_laid_out_tensors",
"(",
"xs",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"x",
"in",
"xs",
":",
"if",
"hasattr",
"(",
"x",
",",
"\"to_laid_out_tensor\"",
")",
":",
"ret",
".",
"append",
"(",
"x",
".",
"to_laid_out_tensor",
"(",
")",
")",
"else",
":",
"ret",
".",
"append",
"(",
"x",
")",
"return",
"ret"
] | Convert list elements to laid-out-tensors when possible.
Args:
xs: a list
Returns:
a list | [
"Convert",
"list",
"elements",
"to",
"laid",
"-",
"out",
"-",
"tensors",
"when",
"possible",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1254-L1268 |
227,853 | tensorflow/mesh | mesh_tensorflow/ops.py | slicewise | def slicewise(tf_fn,
xs,
output_shape=None,
output_dtype=None,
splittable_dims=None,
grad_function=None,
name=None):
"""Slice-wise call to any tensorflow function.
The output shape and dtype default to those of the first input.
splittable_dims is a list of Dimensions which can be split while keeping the
computation valid.
Args:
tf_fn: a function taking n tf.Tensors and returning a tf.Tensor
xs: a list of n Tensors
output_shape: a Shape (or list of shapes)
output_dtype: a dtype (or list of dtypes)
splittable_dims: a list of Dimensions which are ok to split
grad_function: an optional gradients function. If None, use tf gradient.
name: an optional string
Returns:
a Tensor (or a tuple of Tensors)
"""
multiple_outputs = isinstance(output_dtype, list)
output_shapes = output_shape if multiple_outputs else [output_shape]
output_dtypes = output_dtype if multiple_outputs else [output_dtype]
op = SlicewiseOperation(
tf_fn,
xs,
[convert_to_shape(shape) or xs[0].shape for shape in output_shapes],
[dtype or xs[0].dtype for dtype in output_dtypes],
splittable_dims,
grad_function,
name=name)
return tuple(op.outputs) if multiple_outputs else op.outputs[0] | python | def slicewise(tf_fn,
xs,
output_shape=None,
output_dtype=None,
splittable_dims=None,
grad_function=None,
name=None):
"""Slice-wise call to any tensorflow function.
The output shape and dtype default to those of the first input.
splittable_dims is a list of Dimensions which can be split while keeping the
computation valid.
Args:
tf_fn: a function taking n tf.Tensors and returning a tf.Tensor
xs: a list of n Tensors
output_shape: a Shape (or list of shapes)
output_dtype: a dtype (or list of dtypes)
splittable_dims: a list of Dimensions which are ok to split
grad_function: an optional gradients function. If None, use tf gradient.
name: an optional string
Returns:
a Tensor (or a tuple of Tensors)
"""
multiple_outputs = isinstance(output_dtype, list)
output_shapes = output_shape if multiple_outputs else [output_shape]
output_dtypes = output_dtype if multiple_outputs else [output_dtype]
op = SlicewiseOperation(
tf_fn,
xs,
[convert_to_shape(shape) or xs[0].shape for shape in output_shapes],
[dtype or xs[0].dtype for dtype in output_dtypes],
splittable_dims,
grad_function,
name=name)
return tuple(op.outputs) if multiple_outputs else op.outputs[0] | [
"def",
"slicewise",
"(",
"tf_fn",
",",
"xs",
",",
"output_shape",
"=",
"None",
",",
"output_dtype",
"=",
"None",
",",
"splittable_dims",
"=",
"None",
",",
"grad_function",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"multiple_outputs",
"=",
"isinstance",
"(",
"output_dtype",
",",
"list",
")",
"output_shapes",
"=",
"output_shape",
"if",
"multiple_outputs",
"else",
"[",
"output_shape",
"]",
"output_dtypes",
"=",
"output_dtype",
"if",
"multiple_outputs",
"else",
"[",
"output_dtype",
"]",
"op",
"=",
"SlicewiseOperation",
"(",
"tf_fn",
",",
"xs",
",",
"[",
"convert_to_shape",
"(",
"shape",
")",
"or",
"xs",
"[",
"0",
"]",
".",
"shape",
"for",
"shape",
"in",
"output_shapes",
"]",
",",
"[",
"dtype",
"or",
"xs",
"[",
"0",
"]",
".",
"dtype",
"for",
"dtype",
"in",
"output_dtypes",
"]",
",",
"splittable_dims",
",",
"grad_function",
",",
"name",
"=",
"name",
")",
"return",
"tuple",
"(",
"op",
".",
"outputs",
")",
"if",
"multiple_outputs",
"else",
"op",
".",
"outputs",
"[",
"0",
"]"
] | Slice-wise call to any tensorflow function.
The output shape and dtype default to those of the first input.
splittable_dims is a list of Dimensions which can be split while keeping the
computation valid.
Args:
tf_fn: a function taking n tf.Tensors and returning a tf.Tensor
xs: a list of n Tensors
output_shape: a Shape (or list of shapes)
output_dtype: a dtype (or list of dtypes)
splittable_dims: a list of Dimensions which are ok to split
grad_function: an optional gradients function. If None, use tf gradient.
name: an optional string
Returns:
a Tensor (or a tuple of Tensors) | [
"Slice",
"-",
"wise",
"call",
"to",
"any",
"tensorflow",
"function",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1568-L1605 |
227,854 | tensorflow/mesh | mesh_tensorflow/ops.py | cwise | def cwise(tf_fn, xs, output_dtype=None, grad_function=None, name=None):
"""Component-wise operation with no broadcasting.
Args:
tf_fn: a component-wise function taking n tf.Tensor inputs and producing
a tf.Tensor output
xs: n Tensors
output_dtype: an optional dtype
grad_function: an optional python function
name: an optional string
Returns:
a Tensor
"""
return slicewise(
tf_fn, xs, output_dtype=output_dtype, splittable_dims=xs[0].shape.dims,
grad_function=grad_function, name=name or "cwise") | python | def cwise(tf_fn, xs, output_dtype=None, grad_function=None, name=None):
"""Component-wise operation with no broadcasting.
Args:
tf_fn: a component-wise function taking n tf.Tensor inputs and producing
a tf.Tensor output
xs: n Tensors
output_dtype: an optional dtype
grad_function: an optional python function
name: an optional string
Returns:
a Tensor
"""
return slicewise(
tf_fn, xs, output_dtype=output_dtype, splittable_dims=xs[0].shape.dims,
grad_function=grad_function, name=name or "cwise") | [
"def",
"cwise",
"(",
"tf_fn",
",",
"xs",
",",
"output_dtype",
"=",
"None",
",",
"grad_function",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"return",
"slicewise",
"(",
"tf_fn",
",",
"xs",
",",
"output_dtype",
"=",
"output_dtype",
",",
"splittable_dims",
"=",
"xs",
"[",
"0",
"]",
".",
"shape",
".",
"dims",
",",
"grad_function",
"=",
"grad_function",
",",
"name",
"=",
"name",
"or",
"\"cwise\"",
")"
] | Component-wise operation with no broadcasting.
Args:
tf_fn: a component-wise function taking n tf.Tensor inputs and producing
a tf.Tensor output
xs: n Tensors
output_dtype: an optional dtype
grad_function: an optional python function
name: an optional string
Returns:
a Tensor | [
"Component",
"-",
"wise",
"operation",
"with",
"no",
"broadcasting",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1608-L1624 |
227,855 | tensorflow/mesh | mesh_tensorflow/ops.py | binary_arguments_to_tensors | def binary_arguments_to_tensors(x1, x2):
"""Convert argument of a binary operation to Tensors.
Args:
x1: a Tensor or something convertible to a tf Scalar
x2: a Tensor or something convertible to a tf Scalar
Returns:
new_x1: a Tensor
new_x2: a Tensor
Raises:
ValueError: on failure
"""
if not isinstance(x1, Tensor) and not isinstance(x2, Tensor):
raise ValueError("at least one of x1 and x2 must be an mtf Tensor")
elif isinstance(x1, Tensor) and isinstance(x2, Tensor):
return x1, x2
elif isinstance(x1, Tensor):
return x1, import_tf_tensor(
x1.mesh, tf.convert_to_tensor(x2, dtype=x1.dtype), Shape([]))
else:
return import_tf_tensor(x2.mesh, tf.convert_to_tensor(x1, dtype=x2.dtype),
Shape([])), x2 | python | def binary_arguments_to_tensors(x1, x2):
"""Convert argument of a binary operation to Tensors.
Args:
x1: a Tensor or something convertible to a tf Scalar
x2: a Tensor or something convertible to a tf Scalar
Returns:
new_x1: a Tensor
new_x2: a Tensor
Raises:
ValueError: on failure
"""
if not isinstance(x1, Tensor) and not isinstance(x2, Tensor):
raise ValueError("at least one of x1 and x2 must be an mtf Tensor")
elif isinstance(x1, Tensor) and isinstance(x2, Tensor):
return x1, x2
elif isinstance(x1, Tensor):
return x1, import_tf_tensor(
x1.mesh, tf.convert_to_tensor(x2, dtype=x1.dtype), Shape([]))
else:
return import_tf_tensor(x2.mesh, tf.convert_to_tensor(x1, dtype=x2.dtype),
Shape([])), x2 | [
"def",
"binary_arguments_to_tensors",
"(",
"x1",
",",
"x2",
")",
":",
"if",
"not",
"isinstance",
"(",
"x1",
",",
"Tensor",
")",
"and",
"not",
"isinstance",
"(",
"x2",
",",
"Tensor",
")",
":",
"raise",
"ValueError",
"(",
"\"at least one of x1 and x2 must be an mtf Tensor\"",
")",
"elif",
"isinstance",
"(",
"x1",
",",
"Tensor",
")",
"and",
"isinstance",
"(",
"x2",
",",
"Tensor",
")",
":",
"return",
"x1",
",",
"x2",
"elif",
"isinstance",
"(",
"x1",
",",
"Tensor",
")",
":",
"return",
"x1",
",",
"import_tf_tensor",
"(",
"x1",
".",
"mesh",
",",
"tf",
".",
"convert_to_tensor",
"(",
"x2",
",",
"dtype",
"=",
"x1",
".",
"dtype",
")",
",",
"Shape",
"(",
"[",
"]",
")",
")",
"else",
":",
"return",
"import_tf_tensor",
"(",
"x2",
".",
"mesh",
",",
"tf",
".",
"convert_to_tensor",
"(",
"x1",
",",
"dtype",
"=",
"x2",
".",
"dtype",
")",
",",
"Shape",
"(",
"[",
"]",
")",
")",
",",
"x2"
] | Convert argument of a binary operation to Tensors.
Args:
x1: a Tensor or something convertible to a tf Scalar
x2: a Tensor or something convertible to a tf Scalar
Returns:
new_x1: a Tensor
new_x2: a Tensor
Raises:
ValueError: on failure | [
"Convert",
"argument",
"of",
"a",
"binary",
"operation",
"to",
"Tensors",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1845-L1868 |
227,856 | tensorflow/mesh | mesh_tensorflow/ops.py | minimum | def minimum(x1, x2, output_shape=None, name=None):
"""Binary minimum with broadcsting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor
"""
output_shape = convert_to_shape(output_shape)
with tf.name_scope(name, default_name="minimum"):
x1, x2 = binary_arguments_to_tensors(x1, x2)
return MinMaxOperation(
tf.minimum, x1, x2, output_shape=_infer_binary_broadcast_shape(
x1.shape, x2.shape, output_shape)).outputs[0] | python | def minimum(x1, x2, output_shape=None, name=None):
"""Binary minimum with broadcsting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor
"""
output_shape = convert_to_shape(output_shape)
with tf.name_scope(name, default_name="minimum"):
x1, x2 = binary_arguments_to_tensors(x1, x2)
return MinMaxOperation(
tf.minimum, x1, x2, output_shape=_infer_binary_broadcast_shape(
x1.shape, x2.shape, output_shape)).outputs[0] | [
"def",
"minimum",
"(",
"x1",
",",
"x2",
",",
"output_shape",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"output_shape",
"=",
"convert_to_shape",
"(",
"output_shape",
")",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"default_name",
"=",
"\"minimum\"",
")",
":",
"x1",
",",
"x2",
"=",
"binary_arguments_to_tensors",
"(",
"x1",
",",
"x2",
")",
"return",
"MinMaxOperation",
"(",
"tf",
".",
"minimum",
",",
"x1",
",",
"x2",
",",
"output_shape",
"=",
"_infer_binary_broadcast_shape",
"(",
"x1",
".",
"shape",
",",
"x2",
".",
"shape",
",",
"output_shape",
")",
")",
".",
"outputs",
"[",
"0",
"]"
] | Binary minimum with broadcsting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor | [
"Binary",
"minimum",
"with",
"broadcsting",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1960-L1976 |
227,857 | tensorflow/mesh | mesh_tensorflow/ops.py | split | def split(x, split_dim, num_or_size_splits, name=None):
"""Like tf.split.
Args:
x: a Tensor
split_dim: a Dimension in x.shape.dims
num_or_size_splits: either an integer dividing split_dim.size
or a list of integers adding up to split_dim.size
name: an optional string
Returns:
a list of Tensors.
"""
return SplitOperation(x, split_dim, num_or_size_splits, name=name).outputs | python | def split(x, split_dim, num_or_size_splits, name=None):
"""Like tf.split.
Args:
x: a Tensor
split_dim: a Dimension in x.shape.dims
num_or_size_splits: either an integer dividing split_dim.size
or a list of integers adding up to split_dim.size
name: an optional string
Returns:
a list of Tensors.
"""
return SplitOperation(x, split_dim, num_or_size_splits, name=name).outputs | [
"def",
"split",
"(",
"x",
",",
"split_dim",
",",
"num_or_size_splits",
",",
"name",
"=",
"None",
")",
":",
"return",
"SplitOperation",
"(",
"x",
",",
"split_dim",
",",
"num_or_size_splits",
",",
"name",
"=",
"name",
")",
".",
"outputs"
] | Like tf.split.
Args:
x: a Tensor
split_dim: a Dimension in x.shape.dims
num_or_size_splits: either an integer dividing split_dim.size
or a list of integers adding up to split_dim.size
name: an optional string
Returns:
a list of Tensors. | [
"Like",
"tf",
".",
"split",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L2215-L2227 |
227,858 | tensorflow/mesh | mesh_tensorflow/ops.py | stack | def stack(xs, dim_name, axis=0, name=None):
"""Stack multiple Tensors to make a new dimension.
Args:
xs: a list of Tensors with identical shapes.
dim_name: a string (name of the new dimension)
axis: an integer (index of the new dimension in the output shape)
name: an optional string
Returns:
a Tensor
"""
ret = StackOperation(xs, dim_name, axis, name).outputs[0]
return ret | python | def stack(xs, dim_name, axis=0, name=None):
"""Stack multiple Tensors to make a new dimension.
Args:
xs: a list of Tensors with identical shapes.
dim_name: a string (name of the new dimension)
axis: an integer (index of the new dimension in the output shape)
name: an optional string
Returns:
a Tensor
"""
ret = StackOperation(xs, dim_name, axis, name).outputs[0]
return ret | [
"def",
"stack",
"(",
"xs",
",",
"dim_name",
",",
"axis",
"=",
"0",
",",
"name",
"=",
"None",
")",
":",
"ret",
"=",
"StackOperation",
"(",
"xs",
",",
"dim_name",
",",
"axis",
",",
"name",
")",
".",
"outputs",
"[",
"0",
"]",
"return",
"ret"
] | Stack multiple Tensors to make a new dimension.
Args:
xs: a list of Tensors with identical shapes.
dim_name: a string (name of the new dimension)
axis: an integer (index of the new dimension in the output shape)
name: an optional string
Returns:
a Tensor | [
"Stack",
"multiple",
"Tensors",
"to",
"make",
"a",
"new",
"dimension",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L2264-L2277 |
227,859 | tensorflow/mesh | mesh_tensorflow/ops.py | cumsum | def cumsum(x, dim, exclusive=False):
"""Cumulative sum.
Args:
x: a Tensor
dim: a Dimension
exclusive: a boolean
Returns:
a Tensor with the same shape as x.
"""
with tf.variable_scope("cumsum"):
new_name = "tmp_dim_cumsum"
new_dim = Dimension(new_name, dim.size)
new_shape = x.shape.rename_dimension(dim.name, new_name)
comparator = less if exclusive else less_equal
m = cast(
comparator(mtf_range(x.mesh, dim, dtype=tf.float32),
mtf_range(x.mesh, new_dim, dtype=tf.float32)), x.dtype)
ret = einsum([x, m], output_shape=new_shape)
return reshape(ret, x.shape) | python | def cumsum(x, dim, exclusive=False):
"""Cumulative sum.
Args:
x: a Tensor
dim: a Dimension
exclusive: a boolean
Returns:
a Tensor with the same shape as x.
"""
with tf.variable_scope("cumsum"):
new_name = "tmp_dim_cumsum"
new_dim = Dimension(new_name, dim.size)
new_shape = x.shape.rename_dimension(dim.name, new_name)
comparator = less if exclusive else less_equal
m = cast(
comparator(mtf_range(x.mesh, dim, dtype=tf.float32),
mtf_range(x.mesh, new_dim, dtype=tf.float32)), x.dtype)
ret = einsum([x, m], output_shape=new_shape)
return reshape(ret, x.shape) | [
"def",
"cumsum",
"(",
"x",
",",
"dim",
",",
"exclusive",
"=",
"False",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"cumsum\"",
")",
":",
"new_name",
"=",
"\"tmp_dim_cumsum\"",
"new_dim",
"=",
"Dimension",
"(",
"new_name",
",",
"dim",
".",
"size",
")",
"new_shape",
"=",
"x",
".",
"shape",
".",
"rename_dimension",
"(",
"dim",
".",
"name",
",",
"new_name",
")",
"comparator",
"=",
"less",
"if",
"exclusive",
"else",
"less_equal",
"m",
"=",
"cast",
"(",
"comparator",
"(",
"mtf_range",
"(",
"x",
".",
"mesh",
",",
"dim",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
",",
"mtf_range",
"(",
"x",
".",
"mesh",
",",
"new_dim",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
")",
",",
"x",
".",
"dtype",
")",
"ret",
"=",
"einsum",
"(",
"[",
"x",
",",
"m",
"]",
",",
"output_shape",
"=",
"new_shape",
")",
"return",
"reshape",
"(",
"ret",
",",
"x",
".",
"shape",
")"
] | Cumulative sum.
Args:
x: a Tensor
dim: a Dimension
exclusive: a boolean
Returns:
a Tensor with the same shape as x. | [
"Cumulative",
"sum",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L2324-L2344 |
227,860 | tensorflow/mesh | mesh_tensorflow/ops.py | shift | def shift(x, offset, dim, wrap, name=None):
"""Shift operation.
Shift x right by +offset in dimension dim.
Args:
x: a Tensor
offset: an integer. If negative, shift left instead of right.
dim: a Dimension of x
wrap: a boolean - whether to wrap (True) or pad with zeros (False).
name: an optional string
Returns:
a Tensor with the same shape and dtype as x
"""
return ShiftOperation(x, offset, dim, wrap, name=name).outputs[0] | python | def shift(x, offset, dim, wrap, name=None):
"""Shift operation.
Shift x right by +offset in dimension dim.
Args:
x: a Tensor
offset: an integer. If negative, shift left instead of right.
dim: a Dimension of x
wrap: a boolean - whether to wrap (True) or pad with zeros (False).
name: an optional string
Returns:
a Tensor with the same shape and dtype as x
"""
return ShiftOperation(x, offset, dim, wrap, name=name).outputs[0] | [
"def",
"shift",
"(",
"x",
",",
"offset",
",",
"dim",
",",
"wrap",
",",
"name",
"=",
"None",
")",
":",
"return",
"ShiftOperation",
"(",
"x",
",",
"offset",
",",
"dim",
",",
"wrap",
",",
"name",
"=",
"name",
")",
".",
"outputs",
"[",
"0",
"]"
] | Shift operation.
Shift x right by +offset in dimension dim.
Args:
x: a Tensor
offset: an integer. If negative, shift left instead of right.
dim: a Dimension of x
wrap: a boolean - whether to wrap (True) or pad with zeros (False).
name: an optional string
Returns:
a Tensor with the same shape and dtype as x | [
"Shift",
"operation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L2755-L2770 |
227,861 | tensorflow/mesh | mesh_tensorflow/ops.py | import_laid_out_tensor | def import_laid_out_tensor(mesh, laid_out_tensor, shape, name=None):
"""Import a laid_out_tensor.
For expert users.
The input must be laid out appropriately given the eventual MeshImpl,
and layout.
Args:
mesh: a Mesh
laid_out_tensor: a LaidOutTensor
shape: a mtf.Shape
name: an optional string
Returns:
a mtf.Tensor
"""
return ImportLaidOutTensorOperation(
mesh, laid_out_tensor, convert_to_shape(shape), name=name).outputs[0] | python | def import_laid_out_tensor(mesh, laid_out_tensor, shape, name=None):
"""Import a laid_out_tensor.
For expert users.
The input must be laid out appropriately given the eventual MeshImpl,
and layout.
Args:
mesh: a Mesh
laid_out_tensor: a LaidOutTensor
shape: a mtf.Shape
name: an optional string
Returns:
a mtf.Tensor
"""
return ImportLaidOutTensorOperation(
mesh, laid_out_tensor, convert_to_shape(shape), name=name).outputs[0] | [
"def",
"import_laid_out_tensor",
"(",
"mesh",
",",
"laid_out_tensor",
",",
"shape",
",",
"name",
"=",
"None",
")",
":",
"return",
"ImportLaidOutTensorOperation",
"(",
"mesh",
",",
"laid_out_tensor",
",",
"convert_to_shape",
"(",
"shape",
")",
",",
"name",
"=",
"name",
")",
".",
"outputs",
"[",
"0",
"]"
] | Import a laid_out_tensor.
For expert users.
The input must be laid out appropriately given the eventual MeshImpl,
and layout.
Args:
mesh: a Mesh
laid_out_tensor: a LaidOutTensor
shape: a mtf.Shape
name: an optional string
Returns:
a mtf.Tensor | [
"Import",
"a",
"laid_out_tensor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L2972-L2989 |
227,862 | tensorflow/mesh | mesh_tensorflow/ops.py | get_variable | def get_variable(mesh, name, shape, dtype=tf.float32,
master_dtype=None, slice_dtype=None, activation_dtype=None,
initializer=None, trainable=True,
**kwargs):
"""Create a new variable or retrieve an already-created one.
Args:
mesh: a Mesh
name: a string (uses the existing tf.variable_scope())
shape: a Shape
dtype: a VariableDType or a tf.DType
master_dtype: an optional tf.DType (deprecated - use dtype arg)
slice_dtype: an optional tf.DType (deprecated - use dtype arg)
activation_dtype: an optional tf.DType (deprecated - use dtype arg)
initializer: an optional tf initializer function
trainable: a boolean
**kwargs: additional keyword arguments to tf.get_variable
Returns:
a Tensor with the given shape and dtype equal to dtype.activation_dtype
"""
if dtype is None:
dtype = VariableDType(master_dtype, slice_dtype, activation_dtype)
elif isinstance(dtype, tf.DType):
dtype = VariableDType(
master_dtype or dtype, slice_dtype or dtype, activation_dtype or dtype)
elif not isinstance(dtype, VariableDType):
raise ValueError("dtype should be a tf.dtype or a mtf.VariableDType")
scope_name = tf.get_variable_scope().name
if scope_name:
full_name = scope_name + "/" + name
else:
full_name = name
if full_name in mesh.graph.name_to_variable:
var = mesh.graph.name_to_variable[full_name]
else:
var = Variable(
mesh, name, convert_to_shape(shape), dtype, initializer, trainable,
**kwargs)
if var.name != full_name:
raise ValueError(
"Expected var.name == full_name. %s vs %s" % (var.name, full_name))
mesh.graph.name_to_variable[full_name] = var
return var.outputs[0] | python | def get_variable(mesh, name, shape, dtype=tf.float32,
master_dtype=None, slice_dtype=None, activation_dtype=None,
initializer=None, trainable=True,
**kwargs):
"""Create a new variable or retrieve an already-created one.
Args:
mesh: a Mesh
name: a string (uses the existing tf.variable_scope())
shape: a Shape
dtype: a VariableDType or a tf.DType
master_dtype: an optional tf.DType (deprecated - use dtype arg)
slice_dtype: an optional tf.DType (deprecated - use dtype arg)
activation_dtype: an optional tf.DType (deprecated - use dtype arg)
initializer: an optional tf initializer function
trainable: a boolean
**kwargs: additional keyword arguments to tf.get_variable
Returns:
a Tensor with the given shape and dtype equal to dtype.activation_dtype
"""
if dtype is None:
dtype = VariableDType(master_dtype, slice_dtype, activation_dtype)
elif isinstance(dtype, tf.DType):
dtype = VariableDType(
master_dtype or dtype, slice_dtype or dtype, activation_dtype or dtype)
elif not isinstance(dtype, VariableDType):
raise ValueError("dtype should be a tf.dtype or a mtf.VariableDType")
scope_name = tf.get_variable_scope().name
if scope_name:
full_name = scope_name + "/" + name
else:
full_name = name
if full_name in mesh.graph.name_to_variable:
var = mesh.graph.name_to_variable[full_name]
else:
var = Variable(
mesh, name, convert_to_shape(shape), dtype, initializer, trainable,
**kwargs)
if var.name != full_name:
raise ValueError(
"Expected var.name == full_name. %s vs %s" % (var.name, full_name))
mesh.graph.name_to_variable[full_name] = var
return var.outputs[0] | [
"def",
"get_variable",
"(",
"mesh",
",",
"name",
",",
"shape",
",",
"dtype",
"=",
"tf",
".",
"float32",
",",
"master_dtype",
"=",
"None",
",",
"slice_dtype",
"=",
"None",
",",
"activation_dtype",
"=",
"None",
",",
"initializer",
"=",
"None",
",",
"trainable",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"dtype",
"is",
"None",
":",
"dtype",
"=",
"VariableDType",
"(",
"master_dtype",
",",
"slice_dtype",
",",
"activation_dtype",
")",
"elif",
"isinstance",
"(",
"dtype",
",",
"tf",
".",
"DType",
")",
":",
"dtype",
"=",
"VariableDType",
"(",
"master_dtype",
"or",
"dtype",
",",
"slice_dtype",
"or",
"dtype",
",",
"activation_dtype",
"or",
"dtype",
")",
"elif",
"not",
"isinstance",
"(",
"dtype",
",",
"VariableDType",
")",
":",
"raise",
"ValueError",
"(",
"\"dtype should be a tf.dtype or a mtf.VariableDType\"",
")",
"scope_name",
"=",
"tf",
".",
"get_variable_scope",
"(",
")",
".",
"name",
"if",
"scope_name",
":",
"full_name",
"=",
"scope_name",
"+",
"\"/\"",
"+",
"name",
"else",
":",
"full_name",
"=",
"name",
"if",
"full_name",
"in",
"mesh",
".",
"graph",
".",
"name_to_variable",
":",
"var",
"=",
"mesh",
".",
"graph",
".",
"name_to_variable",
"[",
"full_name",
"]",
"else",
":",
"var",
"=",
"Variable",
"(",
"mesh",
",",
"name",
",",
"convert_to_shape",
"(",
"shape",
")",
",",
"dtype",
",",
"initializer",
",",
"trainable",
",",
"*",
"*",
"kwargs",
")",
"if",
"var",
".",
"name",
"!=",
"full_name",
":",
"raise",
"ValueError",
"(",
"\"Expected var.name == full_name. %s vs %s\"",
"%",
"(",
"var",
".",
"name",
",",
"full_name",
")",
")",
"mesh",
".",
"graph",
".",
"name_to_variable",
"[",
"full_name",
"]",
"=",
"var",
"return",
"var",
".",
"outputs",
"[",
"0",
"]"
] | Create a new variable or retrieve an already-created one.
Args:
mesh: a Mesh
name: a string (uses the existing tf.variable_scope())
shape: a Shape
dtype: a VariableDType or a tf.DType
master_dtype: an optional tf.DType (deprecated - use dtype arg)
slice_dtype: an optional tf.DType (deprecated - use dtype arg)
activation_dtype: an optional tf.DType (deprecated - use dtype arg)
initializer: an optional tf initializer function
trainable: a boolean
**kwargs: additional keyword arguments to tf.get_variable
Returns:
a Tensor with the given shape and dtype equal to dtype.activation_dtype | [
"Create",
"a",
"new",
"variable",
"or",
"retrieve",
"an",
"already",
"-",
"created",
"one",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3210-L3253 |
227,863 | tensorflow/mesh | mesh_tensorflow/ops.py | assign | def assign(var, new_val, assign_fn=assign_slice):
"""Assign a new value to a variable.
Args:
var: either a Variable operation or its output Tensor.
new_val: a Tensor
assign_fn: a function from
(mtf.Variable, tf.Variable, tf.Tensor) -> tf.Operation
Returns:
an Operation
Raises:
ValueError: if var is not a Variable and var.operation is not a Variable
"""
if isinstance(var, Tensor):
var = var.operation
if not isinstance(var, Variable):
raise ValueError("var must be a mtf.Variable or its output Tensor.")
return Assign([var], [new_val], assign_fn=assign_fn) | python | def assign(var, new_val, assign_fn=assign_slice):
"""Assign a new value to a variable.
Args:
var: either a Variable operation or its output Tensor.
new_val: a Tensor
assign_fn: a function from
(mtf.Variable, tf.Variable, tf.Tensor) -> tf.Operation
Returns:
an Operation
Raises:
ValueError: if var is not a Variable and var.operation is not a Variable
"""
if isinstance(var, Tensor):
var = var.operation
if not isinstance(var, Variable):
raise ValueError("var must be a mtf.Variable or its output Tensor.")
return Assign([var], [new_val], assign_fn=assign_fn) | [
"def",
"assign",
"(",
"var",
",",
"new_val",
",",
"assign_fn",
"=",
"assign_slice",
")",
":",
"if",
"isinstance",
"(",
"var",
",",
"Tensor",
")",
":",
"var",
"=",
"var",
".",
"operation",
"if",
"not",
"isinstance",
"(",
"var",
",",
"Variable",
")",
":",
"raise",
"ValueError",
"(",
"\"var must be a mtf.Variable or its output Tensor.\"",
")",
"return",
"Assign",
"(",
"[",
"var",
"]",
",",
"[",
"new_val",
"]",
",",
"assign_fn",
"=",
"assign_fn",
")"
] | Assign a new value to a variable.
Args:
var: either a Variable operation or its output Tensor.
new_val: a Tensor
assign_fn: a function from
(mtf.Variable, tf.Variable, tf.Tensor) -> tf.Operation
Returns:
an Operation
Raises:
ValueError: if var is not a Variable and var.operation is not a Variable | [
"Assign",
"a",
"new",
"value",
"to",
"a",
"variable",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3304-L3321 |
227,864 | tensorflow/mesh | mesh_tensorflow/ops.py | Print | def Print(x, data, message, **kwargs): # pylint: disable=invalid-name
"""Call tf.Print.
Args:
x: a Tensor.
data: a list of Tensor
message: a string
**kwargs: keyword arguments to tf.Print
Returns:
a Tensor which is identical in value to x
"""
return PrintOperation(x, data, message, **kwargs).outputs[0] | python | def Print(x, data, message, **kwargs): # pylint: disable=invalid-name
"""Call tf.Print.
Args:
x: a Tensor.
data: a list of Tensor
message: a string
**kwargs: keyword arguments to tf.Print
Returns:
a Tensor which is identical in value to x
"""
return PrintOperation(x, data, message, **kwargs).outputs[0] | [
"def",
"Print",
"(",
"x",
",",
"data",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=invalid-name",
"return",
"PrintOperation",
"(",
"x",
",",
"data",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
".",
"outputs",
"[",
"0",
"]"
] | Call tf.Print.
Args:
x: a Tensor.
data: a list of Tensor
message: a string
**kwargs: keyword arguments to tf.Print
Returns:
a Tensor which is identical in value to x | [
"Call",
"tf",
".",
"Print",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3450-L3461 |
227,865 | tensorflow/mesh | mesh_tensorflow/ops.py | rename_dimension | def rename_dimension(x, old_name, new_name):
"""Reshape a Tensor, renaming one dimension.
Args:
x: a Tensor
old_name: a string
new_name: a string
Returns:
a Tensor
"""
return reshape(x, x.shape.rename_dimension(old_name, new_name)) | python | def rename_dimension(x, old_name, new_name):
"""Reshape a Tensor, renaming one dimension.
Args:
x: a Tensor
old_name: a string
new_name: a string
Returns:
a Tensor
"""
return reshape(x, x.shape.rename_dimension(old_name, new_name)) | [
"def",
"rename_dimension",
"(",
"x",
",",
"old_name",
",",
"new_name",
")",
":",
"return",
"reshape",
"(",
"x",
",",
"x",
".",
"shape",
".",
"rename_dimension",
"(",
"old_name",
",",
"new_name",
")",
")"
] | Reshape a Tensor, renaming one dimension.
Args:
x: a Tensor
old_name: a string
new_name: a string
Returns:
a Tensor | [
"Reshape",
"a",
"Tensor",
"renaming",
"one",
"dimension",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3576-L3587 |
227,866 | tensorflow/mesh | mesh_tensorflow/ops.py | replace_dimensions | def replace_dimensions(tensor_or_shape, old_dim_or_dims, new_dim_or_dims):
"""Replace dimensions in a Tensor or Shape.
old_dim_or_dims consists of a single dimension or a list of dimensions
that must occur consecutively in the input shape. They are replaced
by the dimensions in new_dim_or_dims.
Args:
tensor_or_shape: a Tensor or a Shape
old_dim_or_dims: a Dimension or a list of Dimensions
new_dim_or_dims: a Dimensions or a list of Dimensions
Returns:
a new Tensor or a Shape
"""
if isinstance(tensor_or_shape, Tensor):
return reshape(tensor_or_shape, replace_dimensions(
tensor_or_shape.shape, old_dim_or_dims, new_dim_or_dims))
if not isinstance(tensor_or_shape, Shape):
raise ValueError(
"tensor_or_shape must be a Tensor or Shape got %s" % (tensor_or_shape,))
in_dims = tensor_or_shape.dims
if isinstance(old_dim_or_dims, Dimension):
old_dim_or_dims = [old_dim_or_dims]
if isinstance(new_dim_or_dims, Dimension):
new_dim_or_dims = [new_dim_or_dims]
if not isinstance(old_dim_or_dims, list) or not old_dim_or_dims:
raise ValueError(
"old_dim_or_dims must be a Dimension or a list of Dimension got %s"
% (old_dim_or_dims,))
if not isinstance(new_dim_or_dims, list) or not new_dim_or_dims:
raise ValueError(
"new_dim_or_dims must be a Dimension or a list of Dimension got %s"
% (new_dim_or_dims,))
try:
positions = [in_dims.index(d) for d in old_dim_or_dims]
pos = positions[0]
if positions != list(range(pos, pos + len(positions))):
raise ValueError()
except ValueError:
raise ValueError(
"old_dim_or_dims must be a subsequence of the input's dimensions"
" old_dim_or_dims=%s input's dimensions=%s" %
(old_dim_or_dims, in_dims))
return Shape(in_dims[:pos] + new_dim_or_dims +
in_dims[pos + len(old_dim_or_dims):]) | python | def replace_dimensions(tensor_or_shape, old_dim_or_dims, new_dim_or_dims):
"""Replace dimensions in a Tensor or Shape.
old_dim_or_dims consists of a single dimension or a list of dimensions
that must occur consecutively in the input shape. They are replaced
by the dimensions in new_dim_or_dims.
Args:
tensor_or_shape: a Tensor or a Shape
old_dim_or_dims: a Dimension or a list of Dimensions
new_dim_or_dims: a Dimensions or a list of Dimensions
Returns:
a new Tensor or a Shape
"""
if isinstance(tensor_or_shape, Tensor):
return reshape(tensor_or_shape, replace_dimensions(
tensor_or_shape.shape, old_dim_or_dims, new_dim_or_dims))
if not isinstance(tensor_or_shape, Shape):
raise ValueError(
"tensor_or_shape must be a Tensor or Shape got %s" % (tensor_or_shape,))
in_dims = tensor_or_shape.dims
if isinstance(old_dim_or_dims, Dimension):
old_dim_or_dims = [old_dim_or_dims]
if isinstance(new_dim_or_dims, Dimension):
new_dim_or_dims = [new_dim_or_dims]
if not isinstance(old_dim_or_dims, list) or not old_dim_or_dims:
raise ValueError(
"old_dim_or_dims must be a Dimension or a list of Dimension got %s"
% (old_dim_or_dims,))
if not isinstance(new_dim_or_dims, list) or not new_dim_or_dims:
raise ValueError(
"new_dim_or_dims must be a Dimension or a list of Dimension got %s"
% (new_dim_or_dims,))
try:
positions = [in_dims.index(d) for d in old_dim_or_dims]
pos = positions[0]
if positions != list(range(pos, pos + len(positions))):
raise ValueError()
except ValueError:
raise ValueError(
"old_dim_or_dims must be a subsequence of the input's dimensions"
" old_dim_or_dims=%s input's dimensions=%s" %
(old_dim_or_dims, in_dims))
return Shape(in_dims[:pos] + new_dim_or_dims +
in_dims[pos + len(old_dim_or_dims):]) | [
"def",
"replace_dimensions",
"(",
"tensor_or_shape",
",",
"old_dim_or_dims",
",",
"new_dim_or_dims",
")",
":",
"if",
"isinstance",
"(",
"tensor_or_shape",
",",
"Tensor",
")",
":",
"return",
"reshape",
"(",
"tensor_or_shape",
",",
"replace_dimensions",
"(",
"tensor_or_shape",
".",
"shape",
",",
"old_dim_or_dims",
",",
"new_dim_or_dims",
")",
")",
"if",
"not",
"isinstance",
"(",
"tensor_or_shape",
",",
"Shape",
")",
":",
"raise",
"ValueError",
"(",
"\"tensor_or_shape must be a Tensor or Shape got %s\"",
"%",
"(",
"tensor_or_shape",
",",
")",
")",
"in_dims",
"=",
"tensor_or_shape",
".",
"dims",
"if",
"isinstance",
"(",
"old_dim_or_dims",
",",
"Dimension",
")",
":",
"old_dim_or_dims",
"=",
"[",
"old_dim_or_dims",
"]",
"if",
"isinstance",
"(",
"new_dim_or_dims",
",",
"Dimension",
")",
":",
"new_dim_or_dims",
"=",
"[",
"new_dim_or_dims",
"]",
"if",
"not",
"isinstance",
"(",
"old_dim_or_dims",
",",
"list",
")",
"or",
"not",
"old_dim_or_dims",
":",
"raise",
"ValueError",
"(",
"\"old_dim_or_dims must be a Dimension or a list of Dimension got %s\"",
"%",
"(",
"old_dim_or_dims",
",",
")",
")",
"if",
"not",
"isinstance",
"(",
"new_dim_or_dims",
",",
"list",
")",
"or",
"not",
"new_dim_or_dims",
":",
"raise",
"ValueError",
"(",
"\"new_dim_or_dims must be a Dimension or a list of Dimension got %s\"",
"%",
"(",
"new_dim_or_dims",
",",
")",
")",
"try",
":",
"positions",
"=",
"[",
"in_dims",
".",
"index",
"(",
"d",
")",
"for",
"d",
"in",
"old_dim_or_dims",
"]",
"pos",
"=",
"positions",
"[",
"0",
"]",
"if",
"positions",
"!=",
"list",
"(",
"range",
"(",
"pos",
",",
"pos",
"+",
"len",
"(",
"positions",
")",
")",
")",
":",
"raise",
"ValueError",
"(",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"old_dim_or_dims must be a subsequence of the input's dimensions\"",
"\" old_dim_or_dims=%s input's dimensions=%s\"",
"%",
"(",
"old_dim_or_dims",
",",
"in_dims",
")",
")",
"return",
"Shape",
"(",
"in_dims",
"[",
":",
"pos",
"]",
"+",
"new_dim_or_dims",
"+",
"in_dims",
"[",
"pos",
"+",
"len",
"(",
"old_dim_or_dims",
")",
":",
"]",
")"
] | Replace dimensions in a Tensor or Shape.
old_dim_or_dims consists of a single dimension or a list of dimensions
that must occur consecutively in the input shape. They are replaced
by the dimensions in new_dim_or_dims.
Args:
tensor_or_shape: a Tensor or a Shape
old_dim_or_dims: a Dimension or a list of Dimensions
new_dim_or_dims: a Dimensions or a list of Dimensions
Returns:
a new Tensor or a Shape | [
"Replace",
"dimensions",
"in",
"a",
"Tensor",
"or",
"Shape",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3590-L3634 |
227,867 | tensorflow/mesh | mesh_tensorflow/ops.py | einsum | def einsum(xs, output_shape=None, reduced_dims=None, name=None):
"""Einstein summation.
einsum(xs, output_shape) is equivalent to broadcasting all inputs
to the union of all of their shapes, multiplying them componentwise,
and finally reduce_summing down to output_shape.
One common case of this is matrix multiplication:
x has shape [a, b]
y has shape [b, c]
matmul(x, y) == einsum([x, y], output_shape=[a, c])
We provide a few options for specifying the output shape:
If neither output_shape nor reduced_dims is specified, then the output
shape is set to the contain all dimensions that appear exactly once in the
inputs, in order of appearance.
If output_shape is not specified, then the output shape is set to the contain
all dimensions that appear in xs but not in reduced_dims, in the order
that they appear in xs. If reduced_dims is also not specified, then
reduced_dims is set to the set of all dimensions that appear at least twice in
xs.
If both output_shape and reduced_dims are specified, then we check that
reduced_dims matches the set of dimensions present in xs but not in
output_shape, and throw an exception if it does not. This helps to reduce
bugs.
Args:
xs: a list of Tensors
output_shape: an optional Shape.
reduced_dims: an optional list of Dimensions.
name: an optional string
Returns:
a Tensor
Raises:
ValueError: if reduced_dims contradicts output_shape
"""
output_shape = convert_to_shape(output_shape)
input_dim_count = collections.defaultdict(int)
input_dims = []
for x in xs:
for d in x.shape.dims:
if d not in input_dim_count:
input_dims.append(d)
input_dim_count[d] += 1
if output_shape is None:
if reduced_dims is None:
reduced_dims = [d for d, c in six.iteritems(input_dim_count) if c > 1]
output_shape = Shape([d for d in input_dims if d not in reduced_dims])
elif reduced_dims is not None:
for d in reduced_dims:
if not isinstance(d, Dimension):
raise ValueError("reduced_dims must be a list of Dimensions. Got %s."
% (reduced_dims,))
computed_reduced_dims = [
d for d in input_dims if d not in output_shape.dims]
if set(computed_reduced_dims) != set(reduced_dims):
raise ValueError(
"Specified reduced_dims and output_shape do not match."
" xs=%s output_shape=%s reduced_dims=%s " % (
xs, output_shape, reduced_dims))
return EinsumOperation(xs, output_shape, name=name).outputs[0] | python | def einsum(xs, output_shape=None, reduced_dims=None, name=None):
"""Einstein summation.
einsum(xs, output_shape) is equivalent to broadcasting all inputs
to the union of all of their shapes, multiplying them componentwise,
and finally reduce_summing down to output_shape.
One common case of this is matrix multiplication:
x has shape [a, b]
y has shape [b, c]
matmul(x, y) == einsum([x, y], output_shape=[a, c])
We provide a few options for specifying the output shape:
If neither output_shape nor reduced_dims is specified, then the output
shape is set to the contain all dimensions that appear exactly once in the
inputs, in order of appearance.
If output_shape is not specified, then the output shape is set to the contain
all dimensions that appear in xs but not in reduced_dims, in the order
that they appear in xs. If reduced_dims is also not specified, then
reduced_dims is set to the set of all dimensions that appear at least twice in
xs.
If both output_shape and reduced_dims are specified, then we check that
reduced_dims matches the set of dimensions present in xs but not in
output_shape, and throw an exception if it does not. This helps to reduce
bugs.
Args:
xs: a list of Tensors
output_shape: an optional Shape.
reduced_dims: an optional list of Dimensions.
name: an optional string
Returns:
a Tensor
Raises:
ValueError: if reduced_dims contradicts output_shape
"""
output_shape = convert_to_shape(output_shape)
input_dim_count = collections.defaultdict(int)
input_dims = []
for x in xs:
for d in x.shape.dims:
if d not in input_dim_count:
input_dims.append(d)
input_dim_count[d] += 1
if output_shape is None:
if reduced_dims is None:
reduced_dims = [d for d, c in six.iteritems(input_dim_count) if c > 1]
output_shape = Shape([d for d in input_dims if d not in reduced_dims])
elif reduced_dims is not None:
for d in reduced_dims:
if not isinstance(d, Dimension):
raise ValueError("reduced_dims must be a list of Dimensions. Got %s."
% (reduced_dims,))
computed_reduced_dims = [
d for d in input_dims if d not in output_shape.dims]
if set(computed_reduced_dims) != set(reduced_dims):
raise ValueError(
"Specified reduced_dims and output_shape do not match."
" xs=%s output_shape=%s reduced_dims=%s " % (
xs, output_shape, reduced_dims))
return EinsumOperation(xs, output_shape, name=name).outputs[0] | [
"def",
"einsum",
"(",
"xs",
",",
"output_shape",
"=",
"None",
",",
"reduced_dims",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"output_shape",
"=",
"convert_to_shape",
"(",
"output_shape",
")",
"input_dim_count",
"=",
"collections",
".",
"defaultdict",
"(",
"int",
")",
"input_dims",
"=",
"[",
"]",
"for",
"x",
"in",
"xs",
":",
"for",
"d",
"in",
"x",
".",
"shape",
".",
"dims",
":",
"if",
"d",
"not",
"in",
"input_dim_count",
":",
"input_dims",
".",
"append",
"(",
"d",
")",
"input_dim_count",
"[",
"d",
"]",
"+=",
"1",
"if",
"output_shape",
"is",
"None",
":",
"if",
"reduced_dims",
"is",
"None",
":",
"reduced_dims",
"=",
"[",
"d",
"for",
"d",
",",
"c",
"in",
"six",
".",
"iteritems",
"(",
"input_dim_count",
")",
"if",
"c",
">",
"1",
"]",
"output_shape",
"=",
"Shape",
"(",
"[",
"d",
"for",
"d",
"in",
"input_dims",
"if",
"d",
"not",
"in",
"reduced_dims",
"]",
")",
"elif",
"reduced_dims",
"is",
"not",
"None",
":",
"for",
"d",
"in",
"reduced_dims",
":",
"if",
"not",
"isinstance",
"(",
"d",
",",
"Dimension",
")",
":",
"raise",
"ValueError",
"(",
"\"reduced_dims must be a list of Dimensions. Got %s.\"",
"%",
"(",
"reduced_dims",
",",
")",
")",
"computed_reduced_dims",
"=",
"[",
"d",
"for",
"d",
"in",
"input_dims",
"if",
"d",
"not",
"in",
"output_shape",
".",
"dims",
"]",
"if",
"set",
"(",
"computed_reduced_dims",
")",
"!=",
"set",
"(",
"reduced_dims",
")",
":",
"raise",
"ValueError",
"(",
"\"Specified reduced_dims and output_shape do not match.\"",
"\" xs=%s output_shape=%s reduced_dims=%s \"",
"%",
"(",
"xs",
",",
"output_shape",
",",
"reduced_dims",
")",
")",
"return",
"EinsumOperation",
"(",
"xs",
",",
"output_shape",
",",
"name",
"=",
"name",
")",
".",
"outputs",
"[",
"0",
"]"
] | Einstein summation.
einsum(xs, output_shape) is equivalent to broadcasting all inputs
to the union of all of their shapes, multiplying them componentwise,
and finally reduce_summing down to output_shape.
One common case of this is matrix multiplication:
x has shape [a, b]
y has shape [b, c]
matmul(x, y) == einsum([x, y], output_shape=[a, c])
We provide a few options for specifying the output shape:
If neither output_shape nor reduced_dims is specified, then the output
shape is set to the contain all dimensions that appear exactly once in the
inputs, in order of appearance.
If output_shape is not specified, then the output shape is set to the contain
all dimensions that appear in xs but not in reduced_dims, in the order
that they appear in xs. If reduced_dims is also not specified, then
reduced_dims is set to the set of all dimensions that appear at least twice in
xs.
If both output_shape and reduced_dims are specified, then we check that
reduced_dims matches the set of dimensions present in xs but not in
output_shape, and throw an exception if it does not. This helps to reduce
bugs.
Args:
xs: a list of Tensors
output_shape: an optional Shape.
reduced_dims: an optional list of Dimensions.
name: an optional string
Returns:
a Tensor
Raises:
ValueError: if reduced_dims contradicts output_shape | [
"Einstein",
"summation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3637-L3700 |
227,868 | tensorflow/mesh | mesh_tensorflow/ops.py | _reduction_output_shape | def _reduction_output_shape(x, output_shape, reduced_dim):
"""Helper function to reduce_sum, etc."""
if output_shape is None:
if reduced_dim is None:
return Shape([])
else:
if reduced_dim not in x.shape.dims:
raise ValueError(
"reduced_dim=%s not in x.shape.dims=%s" % (reduced_dim, x.shape))
return x.shape - reduced_dim
if reduced_dim is not None:
if [reduced_dim] != [d for d in x.shape.dims if d not in output_shape.dims]:
raise ValueError(
"reduced_dim contradicts output_shape:"
"x=%s output_shape=%s reduced_dim=%s" %
(x, output_shape, reduced_dim))
return output_shape | python | def _reduction_output_shape(x, output_shape, reduced_dim):
"""Helper function to reduce_sum, etc."""
if output_shape is None:
if reduced_dim is None:
return Shape([])
else:
if reduced_dim not in x.shape.dims:
raise ValueError(
"reduced_dim=%s not in x.shape.dims=%s" % (reduced_dim, x.shape))
return x.shape - reduced_dim
if reduced_dim is not None:
if [reduced_dim] != [d for d in x.shape.dims if d not in output_shape.dims]:
raise ValueError(
"reduced_dim contradicts output_shape:"
"x=%s output_shape=%s reduced_dim=%s" %
(x, output_shape, reduced_dim))
return output_shape | [
"def",
"_reduction_output_shape",
"(",
"x",
",",
"output_shape",
",",
"reduced_dim",
")",
":",
"if",
"output_shape",
"is",
"None",
":",
"if",
"reduced_dim",
"is",
"None",
":",
"return",
"Shape",
"(",
"[",
"]",
")",
"else",
":",
"if",
"reduced_dim",
"not",
"in",
"x",
".",
"shape",
".",
"dims",
":",
"raise",
"ValueError",
"(",
"\"reduced_dim=%s not in x.shape.dims=%s\"",
"%",
"(",
"reduced_dim",
",",
"x",
".",
"shape",
")",
")",
"return",
"x",
".",
"shape",
"-",
"reduced_dim",
"if",
"reduced_dim",
"is",
"not",
"None",
":",
"if",
"[",
"reduced_dim",
"]",
"!=",
"[",
"d",
"for",
"d",
"in",
"x",
".",
"shape",
".",
"dims",
"if",
"d",
"not",
"in",
"output_shape",
".",
"dims",
"]",
":",
"raise",
"ValueError",
"(",
"\"reduced_dim contradicts output_shape:\"",
"\"x=%s output_shape=%s reduced_dim=%s\"",
"%",
"(",
"x",
",",
"output_shape",
",",
"reduced_dim",
")",
")",
"return",
"output_shape"
] | Helper function to reduce_sum, etc. | [
"Helper",
"function",
"to",
"reduce_sum",
"etc",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3709-L3725 |
227,869 | tensorflow/mesh | mesh_tensorflow/ops.py | top_1 | def top_1(x, reduced_dim, dtype=tf.int32, name=None):
"""Argmax and Max.
Args:
x: a Tensor
reduced_dim: a Dimension in x.shape.dims
dtype: a tf.dtype (for the output)
name: an optional string
Returns:
indices: a Tensor with given dtype
values: optional Tensor equal to mtf.reduce_max(x, reduced_dim=reduced_dim)
"""
reduced_dim = convert_to_dimension(reduced_dim)
with tf.name_scope(name, default_name="top_1"):
max_val = reduce_max(x, reduced_dim=reduced_dim)
is_max = to_float(equal(x, max_val))
pos = mtf_range(x.mesh, reduced_dim, tf.float32)
ret = reduce_max(is_max * pos, reduced_dim=reduced_dim)
ret = cast(ret, dtype)
return ret, max_val | python | def top_1(x, reduced_dim, dtype=tf.int32, name=None):
"""Argmax and Max.
Args:
x: a Tensor
reduced_dim: a Dimension in x.shape.dims
dtype: a tf.dtype (for the output)
name: an optional string
Returns:
indices: a Tensor with given dtype
values: optional Tensor equal to mtf.reduce_max(x, reduced_dim=reduced_dim)
"""
reduced_dim = convert_to_dimension(reduced_dim)
with tf.name_scope(name, default_name="top_1"):
max_val = reduce_max(x, reduced_dim=reduced_dim)
is_max = to_float(equal(x, max_val))
pos = mtf_range(x.mesh, reduced_dim, tf.float32)
ret = reduce_max(is_max * pos, reduced_dim=reduced_dim)
ret = cast(ret, dtype)
return ret, max_val | [
"def",
"top_1",
"(",
"x",
",",
"reduced_dim",
",",
"dtype",
"=",
"tf",
".",
"int32",
",",
"name",
"=",
"None",
")",
":",
"reduced_dim",
"=",
"convert_to_dimension",
"(",
"reduced_dim",
")",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"default_name",
"=",
"\"top_1\"",
")",
":",
"max_val",
"=",
"reduce_max",
"(",
"x",
",",
"reduced_dim",
"=",
"reduced_dim",
")",
"is_max",
"=",
"to_float",
"(",
"equal",
"(",
"x",
",",
"max_val",
")",
")",
"pos",
"=",
"mtf_range",
"(",
"x",
".",
"mesh",
",",
"reduced_dim",
",",
"tf",
".",
"float32",
")",
"ret",
"=",
"reduce_max",
"(",
"is_max",
"*",
"pos",
",",
"reduced_dim",
"=",
"reduced_dim",
")",
"ret",
"=",
"cast",
"(",
"ret",
",",
"dtype",
")",
"return",
"ret",
",",
"max_val"
] | Argmax and Max.
Args:
x: a Tensor
reduced_dim: a Dimension in x.shape.dims
dtype: a tf.dtype (for the output)
name: an optional string
Returns:
indices: a Tensor with given dtype
values: optional Tensor equal to mtf.reduce_max(x, reduced_dim=reduced_dim) | [
"Argmax",
"and",
"Max",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3875-L3894 |
227,870 | tensorflow/mesh | mesh_tensorflow/ops.py | top_k | def top_k(x, reduced_dim, new_dim, dtype=tf.int32, name=None):
"""Like tf.top_k.
This operation returns two tensors with the same shape. The output shape
is identical to the shape of x, except that reduced_dim is replaced by
new_dim.
Args:
x: a Tensor
reduced_dim: a Dimension in x.shape.dims.
new_dim: a Dimension. The size determines k.
dtype: optional dtype for indices.
name: optional string.
Returns:
indices: a Tensor with given dtype.
values: a Tensor with same type as x.
"""
reduced_dim = convert_to_dimension(reduced_dim)
new_dim = convert_to_dimension(new_dim)
indices = []
values = []
k = new_dim.size
with tf.name_scope(name, default_name="top_k"):
for i in xrange(k):
max_index, max_val = top_1(x, reduced_dim, dtype)
indices.append(max_index)
values.append(max_val)
if i + 1 < k:
x += one_hot(max_index, reduced_dim, on_value=-1e9, dtype=x.dtype)
axis = x.shape.dims.index(reduced_dim)
return stack(indices, new_dim.name, axis), stack(values, new_dim.name, axis) | python | def top_k(x, reduced_dim, new_dim, dtype=tf.int32, name=None):
"""Like tf.top_k.
This operation returns two tensors with the same shape. The output shape
is identical to the shape of x, except that reduced_dim is replaced by
new_dim.
Args:
x: a Tensor
reduced_dim: a Dimension in x.shape.dims.
new_dim: a Dimension. The size determines k.
dtype: optional dtype for indices.
name: optional string.
Returns:
indices: a Tensor with given dtype.
values: a Tensor with same type as x.
"""
reduced_dim = convert_to_dimension(reduced_dim)
new_dim = convert_to_dimension(new_dim)
indices = []
values = []
k = new_dim.size
with tf.name_scope(name, default_name="top_k"):
for i in xrange(k):
max_index, max_val = top_1(x, reduced_dim, dtype)
indices.append(max_index)
values.append(max_val)
if i + 1 < k:
x += one_hot(max_index, reduced_dim, on_value=-1e9, dtype=x.dtype)
axis = x.shape.dims.index(reduced_dim)
return stack(indices, new_dim.name, axis), stack(values, new_dim.name, axis) | [
"def",
"top_k",
"(",
"x",
",",
"reduced_dim",
",",
"new_dim",
",",
"dtype",
"=",
"tf",
".",
"int32",
",",
"name",
"=",
"None",
")",
":",
"reduced_dim",
"=",
"convert_to_dimension",
"(",
"reduced_dim",
")",
"new_dim",
"=",
"convert_to_dimension",
"(",
"new_dim",
")",
"indices",
"=",
"[",
"]",
"values",
"=",
"[",
"]",
"k",
"=",
"new_dim",
".",
"size",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"default_name",
"=",
"\"top_k\"",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"k",
")",
":",
"max_index",
",",
"max_val",
"=",
"top_1",
"(",
"x",
",",
"reduced_dim",
",",
"dtype",
")",
"indices",
".",
"append",
"(",
"max_index",
")",
"values",
".",
"append",
"(",
"max_val",
")",
"if",
"i",
"+",
"1",
"<",
"k",
":",
"x",
"+=",
"one_hot",
"(",
"max_index",
",",
"reduced_dim",
",",
"on_value",
"=",
"-",
"1e9",
",",
"dtype",
"=",
"x",
".",
"dtype",
")",
"axis",
"=",
"x",
".",
"shape",
".",
"dims",
".",
"index",
"(",
"reduced_dim",
")",
"return",
"stack",
"(",
"indices",
",",
"new_dim",
".",
"name",
",",
"axis",
")",
",",
"stack",
"(",
"values",
",",
"new_dim",
".",
"name",
",",
"axis",
")"
] | Like tf.top_k.
This operation returns two tensors with the same shape. The output shape
is identical to the shape of x, except that reduced_dim is replaced by
new_dim.
Args:
x: a Tensor
reduced_dim: a Dimension in x.shape.dims.
new_dim: a Dimension. The size determines k.
dtype: optional dtype for indices.
name: optional string.
Returns:
indices: a Tensor with given dtype.
values: a Tensor with same type as x. | [
"Like",
"tf",
".",
"top_k",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3902-L3932 |
227,871 | tensorflow/mesh | mesh_tensorflow/ops.py | add | def add(x1, x2, output_shape=None, name=None):
"""Binary addition with broadcsting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor
"""
output_shape = convert_to_shape(output_shape)
if not isinstance(x2, Tensor):
return ScalarAddOperation(x1, x2).outputs[0]
with tf.name_scope(name, default_name="add"):
x1, x2 = binary_arguments_to_tensors(x1, x2)
return AddOperation(
x1, x2, output_shape=_infer_binary_broadcast_shape(
x1.shape, x2.shape, output_shape)).outputs[0] | python | def add(x1, x2, output_shape=None, name=None):
"""Binary addition with broadcsting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor
"""
output_shape = convert_to_shape(output_shape)
if not isinstance(x2, Tensor):
return ScalarAddOperation(x1, x2).outputs[0]
with tf.name_scope(name, default_name="add"):
x1, x2 = binary_arguments_to_tensors(x1, x2)
return AddOperation(
x1, x2, output_shape=_infer_binary_broadcast_shape(
x1.shape, x2.shape, output_shape)).outputs[0] | [
"def",
"add",
"(",
"x1",
",",
"x2",
",",
"output_shape",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"output_shape",
"=",
"convert_to_shape",
"(",
"output_shape",
")",
"if",
"not",
"isinstance",
"(",
"x2",
",",
"Tensor",
")",
":",
"return",
"ScalarAddOperation",
"(",
"x1",
",",
"x2",
")",
".",
"outputs",
"[",
"0",
"]",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"default_name",
"=",
"\"add\"",
")",
":",
"x1",
",",
"x2",
"=",
"binary_arguments_to_tensors",
"(",
"x1",
",",
"x2",
")",
"return",
"AddOperation",
"(",
"x1",
",",
"x2",
",",
"output_shape",
"=",
"_infer_binary_broadcast_shape",
"(",
"x1",
".",
"shape",
",",
"x2",
".",
"shape",
",",
"output_shape",
")",
")",
".",
"outputs",
"[",
"0",
"]"
] | Binary addition with broadcsting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor | [
"Binary",
"addition",
"with",
"broadcsting",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3968-L3986 |
227,872 | tensorflow/mesh | mesh_tensorflow/ops.py | sub | def sub(x1, x2, output_shape=None, name=None):
"""Binary subtraction with broadcsting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor
"""
output_shape = convert_to_shape(output_shape)
if not isinstance(x2, Tensor):
return ScalarAddOperation(x1, -x2).outputs[0]
with tf.name_scope(name, default_name="sub"):
x1, x2 = binary_arguments_to_tensors(x1, x2)
return add(x1, negative(x2), output_shape=output_shape) | python | def sub(x1, x2, output_shape=None, name=None):
"""Binary subtraction with broadcsting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor
"""
output_shape = convert_to_shape(output_shape)
if not isinstance(x2, Tensor):
return ScalarAddOperation(x1, -x2).outputs[0]
with tf.name_scope(name, default_name="sub"):
x1, x2 = binary_arguments_to_tensors(x1, x2)
return add(x1, negative(x2), output_shape=output_shape) | [
"def",
"sub",
"(",
"x1",
",",
"x2",
",",
"output_shape",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"output_shape",
"=",
"convert_to_shape",
"(",
"output_shape",
")",
"if",
"not",
"isinstance",
"(",
"x2",
",",
"Tensor",
")",
":",
"return",
"ScalarAddOperation",
"(",
"x1",
",",
"-",
"x2",
")",
".",
"outputs",
"[",
"0",
"]",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"default_name",
"=",
"\"sub\"",
")",
":",
"x1",
",",
"x2",
"=",
"binary_arguments_to_tensors",
"(",
"x1",
",",
"x2",
")",
"return",
"add",
"(",
"x1",
",",
"negative",
"(",
"x2",
")",
",",
"output_shape",
"=",
"output_shape",
")"
] | Binary subtraction with broadcsting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor | [
"Binary",
"subtraction",
"with",
"broadcsting",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3995-L4011 |
227,873 | tensorflow/mesh | mesh_tensorflow/ops.py | multiply | def multiply(x1, x2, output_shape=None, name=None):
"""Binary multiplication with broadcasting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor
"""
if not isinstance(x2, Tensor):
return ScalarMultiplyOperation(x1, x2).outputs[0]
with tf.name_scope(name, default_name="mul"):
x1, x2 = binary_arguments_to_tensors(x1, x2)
return einsum(
[x1, x2],
output_shape=_infer_binary_broadcast_shape(
x1.shape, x2.shape, output_shape)) | python | def multiply(x1, x2, output_shape=None, name=None):
"""Binary multiplication with broadcasting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor
"""
if not isinstance(x2, Tensor):
return ScalarMultiplyOperation(x1, x2).outputs[0]
with tf.name_scope(name, default_name="mul"):
x1, x2 = binary_arguments_to_tensors(x1, x2)
return einsum(
[x1, x2],
output_shape=_infer_binary_broadcast_shape(
x1.shape, x2.shape, output_shape)) | [
"def",
"multiply",
"(",
"x1",
",",
"x2",
",",
"output_shape",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"x2",
",",
"Tensor",
")",
":",
"return",
"ScalarMultiplyOperation",
"(",
"x1",
",",
"x2",
")",
".",
"outputs",
"[",
"0",
"]",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"default_name",
"=",
"\"mul\"",
")",
":",
"x1",
",",
"x2",
"=",
"binary_arguments_to_tensors",
"(",
"x1",
",",
"x2",
")",
"return",
"einsum",
"(",
"[",
"x1",
",",
"x2",
"]",
",",
"output_shape",
"=",
"_infer_binary_broadcast_shape",
"(",
"x1",
".",
"shape",
",",
"x2",
".",
"shape",
",",
"output_shape",
")",
")"
] | Binary multiplication with broadcasting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor | [
"Binary",
"multiplication",
"with",
"broadcasting",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4014-L4032 |
227,874 | tensorflow/mesh | mesh_tensorflow/ops.py | divide | def divide(x1, x2, output_shape=None, name=None):
"""Binary division with broadcasting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor
"""
output_shape = convert_to_shape(output_shape)
if not isinstance(x2, Tensor):
return ScalarMultiplyOperation(x1, 1.0 / x2).outputs[0]
with tf.name_scope(name, default_name="divide"):
x1, x2 = binary_arguments_to_tensors(x1, x2)
return multiply(x1, reciprocal(x2), output_shape=output_shape) | python | def divide(x1, x2, output_shape=None, name=None):
"""Binary division with broadcasting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor
"""
output_shape = convert_to_shape(output_shape)
if not isinstance(x2, Tensor):
return ScalarMultiplyOperation(x1, 1.0 / x2).outputs[0]
with tf.name_scope(name, default_name="divide"):
x1, x2 = binary_arguments_to_tensors(x1, x2)
return multiply(x1, reciprocal(x2), output_shape=output_shape) | [
"def",
"divide",
"(",
"x1",
",",
"x2",
",",
"output_shape",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"output_shape",
"=",
"convert_to_shape",
"(",
"output_shape",
")",
"if",
"not",
"isinstance",
"(",
"x2",
",",
"Tensor",
")",
":",
"return",
"ScalarMultiplyOperation",
"(",
"x1",
",",
"1.0",
"/",
"x2",
")",
".",
"outputs",
"[",
"0",
"]",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"default_name",
"=",
"\"divide\"",
")",
":",
"x1",
",",
"x2",
"=",
"binary_arguments_to_tensors",
"(",
"x1",
",",
"x2",
")",
"return",
"multiply",
"(",
"x1",
",",
"reciprocal",
"(",
"x2",
")",
",",
"output_shape",
"=",
"output_shape",
")"
] | Binary division with broadcasting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor | [
"Binary",
"division",
"with",
"broadcasting",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4035-L4051 |
227,875 | tensorflow/mesh | mesh_tensorflow/ops.py | one_hot | def one_hot(indices, output_dim, on_value=1.0,
off_value=0.0, dtype=tf.float32, name=None):
"""One hot operation.
TODO(noam): Is there a good reason we need a special mtf.Operation here?
We could just use some code like this:
cast(equal(indices, mtf_range(indices.mesh, output_dim, dtype=indices.dtype)),
dtype)
Args:
indices: a Tensor
output_dim: a Dimension
on_value: Value taken when indices are on at a location, default 1
off_value: Value taken when indices are off at a location, default 0
dtype: a tf.DType
name: an optional string
Returns:
a Tensor with shape extended by output_dim for the last axis.
"""
return OneHotOperation(
indices, output_dim, on_value, off_value, dtype, name=name).outputs[0] | python | def one_hot(indices, output_dim, on_value=1.0,
off_value=0.0, dtype=tf.float32, name=None):
"""One hot operation.
TODO(noam): Is there a good reason we need a special mtf.Operation here?
We could just use some code like this:
cast(equal(indices, mtf_range(indices.mesh, output_dim, dtype=indices.dtype)),
dtype)
Args:
indices: a Tensor
output_dim: a Dimension
on_value: Value taken when indices are on at a location, default 1
off_value: Value taken when indices are off at a location, default 0
dtype: a tf.DType
name: an optional string
Returns:
a Tensor with shape extended by output_dim for the last axis.
"""
return OneHotOperation(
indices, output_dim, on_value, off_value, dtype, name=name).outputs[0] | [
"def",
"one_hot",
"(",
"indices",
",",
"output_dim",
",",
"on_value",
"=",
"1.0",
",",
"off_value",
"=",
"0.0",
",",
"dtype",
"=",
"tf",
".",
"float32",
",",
"name",
"=",
"None",
")",
":",
"return",
"OneHotOperation",
"(",
"indices",
",",
"output_dim",
",",
"on_value",
",",
"off_value",
",",
"dtype",
",",
"name",
"=",
"name",
")",
".",
"outputs",
"[",
"0",
"]"
] | One hot operation.
TODO(noam): Is there a good reason we need a special mtf.Operation here?
We could just use some code like this:
cast(equal(indices, mtf_range(indices.mesh, output_dim, dtype=indices.dtype)),
dtype)
Args:
indices: a Tensor
output_dim: a Dimension
on_value: Value taken when indices are on at a location, default 1
off_value: Value taken when indices are off at a location, default 0
dtype: a tf.DType
name: an optional string
Returns:
a Tensor with shape extended by output_dim for the last axis. | [
"One",
"hot",
"operation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4087-L4107 |
227,876 | tensorflow/mesh | mesh_tensorflow/ops.py | gradients | def gradients(ys, xs, grad_ys=None):
"""Compute gradients in dtf.
Args:
ys: a list of Tensors
xs: a list of Tensors
grad_ys: an optional list of Tensors
Returns:
grad_xs: a list of Tensors
"""
graph = ys[0].graph
if not grad_ys:
grad_ys = [Constant(y.mesh, 1.0, y.shape, y.dtype).outputs[0] for y in ys]
# figure out what Tensors are downstream of xs
downstream = set(xs)
for op in graph.operations:
if op.has_gradient:
if set(op.inputs) & downstream:
downstream |= set(op.outputs)
tensor_to_gradient = dict(zip(ys, grad_ys))
for op in graph.operations[::-1]:
grad_outputs = [tensor_to_gradient.get(out) for out in op.outputs]
if op.has_gradient and any(grad_outputs) and (set(op.inputs) & downstream):
with tf.variable_scope(op.name + "/gradients"):
input_grads = op.gradient(grad_outputs)
for inp, grad in zip(op.inputs, input_grads):
if inp in downstream and grad is not None:
if inp in tensor_to_gradient:
tensor_to_gradient[inp] += grad
else:
tensor_to_gradient[inp] = grad
return [tensor_to_gradient.get(x, None) for x in xs] | python | def gradients(ys, xs, grad_ys=None):
"""Compute gradients in dtf.
Args:
ys: a list of Tensors
xs: a list of Tensors
grad_ys: an optional list of Tensors
Returns:
grad_xs: a list of Tensors
"""
graph = ys[0].graph
if not grad_ys:
grad_ys = [Constant(y.mesh, 1.0, y.shape, y.dtype).outputs[0] for y in ys]
# figure out what Tensors are downstream of xs
downstream = set(xs)
for op in graph.operations:
if op.has_gradient:
if set(op.inputs) & downstream:
downstream |= set(op.outputs)
tensor_to_gradient = dict(zip(ys, grad_ys))
for op in graph.operations[::-1]:
grad_outputs = [tensor_to_gradient.get(out) for out in op.outputs]
if op.has_gradient and any(grad_outputs) and (set(op.inputs) & downstream):
with tf.variable_scope(op.name + "/gradients"):
input_grads = op.gradient(grad_outputs)
for inp, grad in zip(op.inputs, input_grads):
if inp in downstream and grad is not None:
if inp in tensor_to_gradient:
tensor_to_gradient[inp] += grad
else:
tensor_to_gradient[inp] = grad
return [tensor_to_gradient.get(x, None) for x in xs] | [
"def",
"gradients",
"(",
"ys",
",",
"xs",
",",
"grad_ys",
"=",
"None",
")",
":",
"graph",
"=",
"ys",
"[",
"0",
"]",
".",
"graph",
"if",
"not",
"grad_ys",
":",
"grad_ys",
"=",
"[",
"Constant",
"(",
"y",
".",
"mesh",
",",
"1.0",
",",
"y",
".",
"shape",
",",
"y",
".",
"dtype",
")",
".",
"outputs",
"[",
"0",
"]",
"for",
"y",
"in",
"ys",
"]",
"# figure out what Tensors are downstream of xs",
"downstream",
"=",
"set",
"(",
"xs",
")",
"for",
"op",
"in",
"graph",
".",
"operations",
":",
"if",
"op",
".",
"has_gradient",
":",
"if",
"set",
"(",
"op",
".",
"inputs",
")",
"&",
"downstream",
":",
"downstream",
"|=",
"set",
"(",
"op",
".",
"outputs",
")",
"tensor_to_gradient",
"=",
"dict",
"(",
"zip",
"(",
"ys",
",",
"grad_ys",
")",
")",
"for",
"op",
"in",
"graph",
".",
"operations",
"[",
":",
":",
"-",
"1",
"]",
":",
"grad_outputs",
"=",
"[",
"tensor_to_gradient",
".",
"get",
"(",
"out",
")",
"for",
"out",
"in",
"op",
".",
"outputs",
"]",
"if",
"op",
".",
"has_gradient",
"and",
"any",
"(",
"grad_outputs",
")",
"and",
"(",
"set",
"(",
"op",
".",
"inputs",
")",
"&",
"downstream",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"op",
".",
"name",
"+",
"\"/gradients\"",
")",
":",
"input_grads",
"=",
"op",
".",
"gradient",
"(",
"grad_outputs",
")",
"for",
"inp",
",",
"grad",
"in",
"zip",
"(",
"op",
".",
"inputs",
",",
"input_grads",
")",
":",
"if",
"inp",
"in",
"downstream",
"and",
"grad",
"is",
"not",
"None",
":",
"if",
"inp",
"in",
"tensor_to_gradient",
":",
"tensor_to_gradient",
"[",
"inp",
"]",
"+=",
"grad",
"else",
":",
"tensor_to_gradient",
"[",
"inp",
"]",
"=",
"grad",
"return",
"[",
"tensor_to_gradient",
".",
"get",
"(",
"x",
",",
"None",
")",
"for",
"x",
"in",
"xs",
"]"
] | Compute gradients in dtf.
Args:
ys: a list of Tensors
xs: a list of Tensors
grad_ys: an optional list of Tensors
Returns:
grad_xs: a list of Tensors | [
"Compute",
"gradients",
"in",
"dtf",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4129-L4161 |
227,877 | tensorflow/mesh | mesh_tensorflow/ops.py | _infer_binary_broadcast_shape | def _infer_binary_broadcast_shape(shape1, shape2, given_output_shape=None):
"""Infer shape of the output of a binary op with broadcasting.
If the output shape is not given with given_output_shape, then we check
to see if one of the shapes is a subsequence of the other one, and we
return the one that is the supersequence. Otherwise, we list the dimensions
of shape1, followed by all new dimensions in shape2.
Args:
shape1: a Shape
shape2: a Shape
given_output_shape: an optional Shape
Returns:
a Shape
"""
shape1 = convert_to_shape(shape1)
shape2 = convert_to_shape(shape2)
given_output_shape = convert_to_shape(given_output_shape)
if given_output_shape is not None:
return given_output_shape
if is_subsequence(shape1.dims, shape2.dims):
return shape2
if is_subsequence(shape2.dims, shape1.dims):
return shape1
return Shape(
shape1.dims + [d for d in shape2.dims if d not in shape1.dims]) | python | def _infer_binary_broadcast_shape(shape1, shape2, given_output_shape=None):
"""Infer shape of the output of a binary op with broadcasting.
If the output shape is not given with given_output_shape, then we check
to see if one of the shapes is a subsequence of the other one, and we
return the one that is the supersequence. Otherwise, we list the dimensions
of shape1, followed by all new dimensions in shape2.
Args:
shape1: a Shape
shape2: a Shape
given_output_shape: an optional Shape
Returns:
a Shape
"""
shape1 = convert_to_shape(shape1)
shape2 = convert_to_shape(shape2)
given_output_shape = convert_to_shape(given_output_shape)
if given_output_shape is not None:
return given_output_shape
if is_subsequence(shape1.dims, shape2.dims):
return shape2
if is_subsequence(shape2.dims, shape1.dims):
return shape1
return Shape(
shape1.dims + [d for d in shape2.dims if d not in shape1.dims]) | [
"def",
"_infer_binary_broadcast_shape",
"(",
"shape1",
",",
"shape2",
",",
"given_output_shape",
"=",
"None",
")",
":",
"shape1",
"=",
"convert_to_shape",
"(",
"shape1",
")",
"shape2",
"=",
"convert_to_shape",
"(",
"shape2",
")",
"given_output_shape",
"=",
"convert_to_shape",
"(",
"given_output_shape",
")",
"if",
"given_output_shape",
"is",
"not",
"None",
":",
"return",
"given_output_shape",
"if",
"is_subsequence",
"(",
"shape1",
".",
"dims",
",",
"shape2",
".",
"dims",
")",
":",
"return",
"shape2",
"if",
"is_subsequence",
"(",
"shape2",
".",
"dims",
",",
"shape1",
".",
"dims",
")",
":",
"return",
"shape1",
"return",
"Shape",
"(",
"shape1",
".",
"dims",
"+",
"[",
"d",
"for",
"d",
"in",
"shape2",
".",
"dims",
"if",
"d",
"not",
"in",
"shape1",
".",
"dims",
"]",
")"
] | Infer shape of the output of a binary op with broadcasting.
If the output shape is not given with given_output_shape, then we check
to see if one of the shapes is a subsequence of the other one, and we
return the one that is the supersequence. Otherwise, we list the dimensions
of shape1, followed by all new dimensions in shape2.
Args:
shape1: a Shape
shape2: a Shape
given_output_shape: an optional Shape
Returns:
a Shape | [
"Infer",
"shape",
"of",
"the",
"output",
"of",
"a",
"binary",
"op",
"with",
"broadcasting",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4164-L4189 |
227,878 | tensorflow/mesh | mesh_tensorflow/ops.py | _expand_dims | def _expand_dims(x, input_shape, output_shape):
"""Expand dimensions and transpose if necessary.
Args:
x: a tf.Tensor
input_shape: a Shape
output_shape: a Shape whose dimensions are a superset of
those in input_shape
Returns:
a tf.Tensor
"""
verify_no_new_dims([output_shape], input_shape)
if input_shape == output_shape or input_shape.ndims == 0:
return x
perm = [input_shape.dims.index(d) for d in output_shape.dims
if d in input_shape.dims]
x = tf.transpose(x, perm)
for i, d in enumerate(output_shape.dims):
if d not in input_shape.dims:
x = tf.expand_dims(x, i)
return x | python | def _expand_dims(x, input_shape, output_shape):
"""Expand dimensions and transpose if necessary.
Args:
x: a tf.Tensor
input_shape: a Shape
output_shape: a Shape whose dimensions are a superset of
those in input_shape
Returns:
a tf.Tensor
"""
verify_no_new_dims([output_shape], input_shape)
if input_shape == output_shape or input_shape.ndims == 0:
return x
perm = [input_shape.dims.index(d) for d in output_shape.dims
if d in input_shape.dims]
x = tf.transpose(x, perm)
for i, d in enumerate(output_shape.dims):
if d not in input_shape.dims:
x = tf.expand_dims(x, i)
return x | [
"def",
"_expand_dims",
"(",
"x",
",",
"input_shape",
",",
"output_shape",
")",
":",
"verify_no_new_dims",
"(",
"[",
"output_shape",
"]",
",",
"input_shape",
")",
"if",
"input_shape",
"==",
"output_shape",
"or",
"input_shape",
".",
"ndims",
"==",
"0",
":",
"return",
"x",
"perm",
"=",
"[",
"input_shape",
".",
"dims",
".",
"index",
"(",
"d",
")",
"for",
"d",
"in",
"output_shape",
".",
"dims",
"if",
"d",
"in",
"input_shape",
".",
"dims",
"]",
"x",
"=",
"tf",
".",
"transpose",
"(",
"x",
",",
"perm",
")",
"for",
"i",
",",
"d",
"in",
"enumerate",
"(",
"output_shape",
".",
"dims",
")",
":",
"if",
"d",
"not",
"in",
"input_shape",
".",
"dims",
":",
"x",
"=",
"tf",
".",
"expand_dims",
"(",
"x",
",",
"i",
")",
"return",
"x"
] | Expand dimensions and transpose if necessary.
Args:
x: a tf.Tensor
input_shape: a Shape
output_shape: a Shape whose dimensions are a superset of
those in input_shape
Returns:
a tf.Tensor | [
"Expand",
"dimensions",
"and",
"transpose",
"if",
"necessary",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4192-L4213 |
227,879 | tensorflow/mesh | mesh_tensorflow/ops.py | _einsum_equation | def _einsum_equation(input_shapes, output_shape):
"""Turn shapes into an einsum equation.
e.g. "ij,jk->ik"
Args:
input_shapes: a list of Shapes
output_shape: a Shape
Returns:
a string
"""
ret = []
next_letter = ord("a")
dim_to_letter = {}
for shape_num, shape in enumerate(input_shapes + [output_shape]):
if shape_num == len(input_shapes):
ret.append("->")
elif shape_num > 0:
ret.append(",")
for d in shape.dims:
if d not in dim_to_letter:
dim_to_letter[d] = chr(next_letter)
next_letter += 1
ret.append(dim_to_letter[d])
return "".join(ret) | python | def _einsum_equation(input_shapes, output_shape):
"""Turn shapes into an einsum equation.
e.g. "ij,jk->ik"
Args:
input_shapes: a list of Shapes
output_shape: a Shape
Returns:
a string
"""
ret = []
next_letter = ord("a")
dim_to_letter = {}
for shape_num, shape in enumerate(input_shapes + [output_shape]):
if shape_num == len(input_shapes):
ret.append("->")
elif shape_num > 0:
ret.append(",")
for d in shape.dims:
if d not in dim_to_letter:
dim_to_letter[d] = chr(next_letter)
next_letter += 1
ret.append(dim_to_letter[d])
return "".join(ret) | [
"def",
"_einsum_equation",
"(",
"input_shapes",
",",
"output_shape",
")",
":",
"ret",
"=",
"[",
"]",
"next_letter",
"=",
"ord",
"(",
"\"a\"",
")",
"dim_to_letter",
"=",
"{",
"}",
"for",
"shape_num",
",",
"shape",
"in",
"enumerate",
"(",
"input_shapes",
"+",
"[",
"output_shape",
"]",
")",
":",
"if",
"shape_num",
"==",
"len",
"(",
"input_shapes",
")",
":",
"ret",
".",
"append",
"(",
"\"->\"",
")",
"elif",
"shape_num",
">",
"0",
":",
"ret",
".",
"append",
"(",
"\",\"",
")",
"for",
"d",
"in",
"shape",
".",
"dims",
":",
"if",
"d",
"not",
"in",
"dim_to_letter",
":",
"dim_to_letter",
"[",
"d",
"]",
"=",
"chr",
"(",
"next_letter",
")",
"next_letter",
"+=",
"1",
"ret",
".",
"append",
"(",
"dim_to_letter",
"[",
"d",
"]",
")",
"return",
"\"\"",
".",
"join",
"(",
"ret",
")"
] | Turn shapes into an einsum equation.
e.g. "ij,jk->ik"
Args:
input_shapes: a list of Shapes
output_shape: a Shape
Returns:
a string | [
"Turn",
"shapes",
"into",
"an",
"einsum",
"equation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4216-L4241 |
227,880 | tensorflow/mesh | mesh_tensorflow/ops.py | is_subsequence | def is_subsequence(short_seq, long_seq):
"""Is short_seq a subsequence of long_seq."""
if not short_seq:
return True
pos = 0
for x in long_seq:
if pos == len(short_seq):
return True
if short_seq[pos] == x:
pos += 1
if pos == len(short_seq):
return True
return False | python | def is_subsequence(short_seq, long_seq):
"""Is short_seq a subsequence of long_seq."""
if not short_seq:
return True
pos = 0
for x in long_seq:
if pos == len(short_seq):
return True
if short_seq[pos] == x:
pos += 1
if pos == len(short_seq):
return True
return False | [
"def",
"is_subsequence",
"(",
"short_seq",
",",
"long_seq",
")",
":",
"if",
"not",
"short_seq",
":",
"return",
"True",
"pos",
"=",
"0",
"for",
"x",
"in",
"long_seq",
":",
"if",
"pos",
"==",
"len",
"(",
"short_seq",
")",
":",
"return",
"True",
"if",
"short_seq",
"[",
"pos",
"]",
"==",
"x",
":",
"pos",
"+=",
"1",
"if",
"pos",
"==",
"len",
"(",
"short_seq",
")",
":",
"return",
"True",
"return",
"False"
] | Is short_seq a subsequence of long_seq. | [
"Is",
"short_seq",
"a",
"subsequence",
"of",
"long_seq",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4244-L4256 |
227,881 | tensorflow/mesh | mesh_tensorflow/ops.py | verify_no_new_dims | def verify_no_new_dims(input_shapes, output_shape):
"""Verifies that all dimensions in the output are in at least one input.
Args:
input_shapes: a list of Shapes
output_shape: a Shape
Raises:
ValueError: if there are new dimensions in the output.
"""
all_input_dims = set(sum([s.dims for s in input_shapes], []))
all_output_dims = set(output_shape.dims)
if not all_output_dims.issubset(all_input_dims):
raise ValueError(
"No new dimensions allowed in output"
" input_shapes = %s output_shape= %s"
% ([s.dims for s in input_shapes], output_shape.dims)) | python | def verify_no_new_dims(input_shapes, output_shape):
"""Verifies that all dimensions in the output are in at least one input.
Args:
input_shapes: a list of Shapes
output_shape: a Shape
Raises:
ValueError: if there are new dimensions in the output.
"""
all_input_dims = set(sum([s.dims for s in input_shapes], []))
all_output_dims = set(output_shape.dims)
if not all_output_dims.issubset(all_input_dims):
raise ValueError(
"No new dimensions allowed in output"
" input_shapes = %s output_shape= %s"
% ([s.dims for s in input_shapes], output_shape.dims)) | [
"def",
"verify_no_new_dims",
"(",
"input_shapes",
",",
"output_shape",
")",
":",
"all_input_dims",
"=",
"set",
"(",
"sum",
"(",
"[",
"s",
".",
"dims",
"for",
"s",
"in",
"input_shapes",
"]",
",",
"[",
"]",
")",
")",
"all_output_dims",
"=",
"set",
"(",
"output_shape",
".",
"dims",
")",
"if",
"not",
"all_output_dims",
".",
"issubset",
"(",
"all_input_dims",
")",
":",
"raise",
"ValueError",
"(",
"\"No new dimensions allowed in output\"",
"\" input_shapes = %s output_shape= %s\"",
"%",
"(",
"[",
"s",
".",
"dims",
"for",
"s",
"in",
"input_shapes",
"]",
",",
"output_shape",
".",
"dims",
")",
")"
] | Verifies that all dimensions in the output are in at least one input.
Args:
input_shapes: a list of Shapes
output_shape: a Shape
Raises:
ValueError: if there are new dimensions in the output. | [
"Verifies",
"that",
"all",
"dimensions",
"in",
"the",
"output",
"are",
"in",
"at",
"least",
"one",
"input",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4259-L4274 |
227,882 | tensorflow/mesh | mesh_tensorflow/ops.py | pnum_to_processor_coordinates | def pnum_to_processor_coordinates(mesh_shape, pnum):
"""Coordinates of a processor in the mesh.
Args:
mesh_shape: a Shape
pnum: an integer less than len(mesh_shape)
Returns:
a list of integers with length len(mesh_shape)
"""
ret = []
for dimsize in mesh_shape.to_integer_list[::-1]:
ret.append(pnum % dimsize)
pnum //= dimsize
return ret[::-1] | python | def pnum_to_processor_coordinates(mesh_shape, pnum):
"""Coordinates of a processor in the mesh.
Args:
mesh_shape: a Shape
pnum: an integer less than len(mesh_shape)
Returns:
a list of integers with length len(mesh_shape)
"""
ret = []
for dimsize in mesh_shape.to_integer_list[::-1]:
ret.append(pnum % dimsize)
pnum //= dimsize
return ret[::-1] | [
"def",
"pnum_to_processor_coordinates",
"(",
"mesh_shape",
",",
"pnum",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"dimsize",
"in",
"mesh_shape",
".",
"to_integer_list",
"[",
":",
":",
"-",
"1",
"]",
":",
"ret",
".",
"append",
"(",
"pnum",
"%",
"dimsize",
")",
"pnum",
"//=",
"dimsize",
"return",
"ret",
"[",
":",
":",
"-",
"1",
"]"
] | Coordinates of a processor in the mesh.
Args:
mesh_shape: a Shape
pnum: an integer less than len(mesh_shape)
Returns:
a list of integers with length len(mesh_shape) | [
"Coordinates",
"of",
"a",
"processor",
"in",
"the",
"mesh",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4277-L4291 |
227,883 | tensorflow/mesh | mesh_tensorflow/ops.py | processor_coordinates_to_pnum | def processor_coordinates_to_pnum(mesh_shape, coord):
"""Inverse of pnum_to_processor_coordinates.
Args:
mesh_shape: a Shape
coord: a list of integers with length len(mesh_shape)
Returns:
an integer less than len(mesh_shape)
"""
ret = 0
multiplier = 1
for c, d in zip(coord[::-1], mesh_shape.to_integer_list[::-1]):
ret += multiplier * c
multiplier *= d
return ret | python | def processor_coordinates_to_pnum(mesh_shape, coord):
"""Inverse of pnum_to_processor_coordinates.
Args:
mesh_shape: a Shape
coord: a list of integers with length len(mesh_shape)
Returns:
an integer less than len(mesh_shape)
"""
ret = 0
multiplier = 1
for c, d in zip(coord[::-1], mesh_shape.to_integer_list[::-1]):
ret += multiplier * c
multiplier *= d
return ret | [
"def",
"processor_coordinates_to_pnum",
"(",
"mesh_shape",
",",
"coord",
")",
":",
"ret",
"=",
"0",
"multiplier",
"=",
"1",
"for",
"c",
",",
"d",
"in",
"zip",
"(",
"coord",
"[",
":",
":",
"-",
"1",
"]",
",",
"mesh_shape",
".",
"to_integer_list",
"[",
":",
":",
"-",
"1",
"]",
")",
":",
"ret",
"+=",
"multiplier",
"*",
"c",
"multiplier",
"*=",
"d",
"return",
"ret"
] | Inverse of pnum_to_processor_coordinates.
Args:
mesh_shape: a Shape
coord: a list of integers with length len(mesh_shape)
Returns:
an integer less than len(mesh_shape) | [
"Inverse",
"of",
"pnum_to_processor_coordinates",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4294-L4309 |
227,884 | tensorflow/mesh | mesh_tensorflow/ops.py | pnum_to_group | def pnum_to_group(mesh_shape, group_dims, pnum):
"""Group number for grouped allreduce.
Args:
mesh_shape: a Shape
group_dims: a list of integers (the dimensions reduced over)
pnum: an integer
Returns:
an integer
"""
coord = pnum_to_processor_coordinates(mesh_shape, pnum)
remaining_shape = Shape(
[d for i, d in enumerate(mesh_shape) if i not in group_dims])
remaining_coord = [d for i, d in enumerate(coord) if i not in group_dims]
return processor_coordinates_to_pnum(remaining_shape, remaining_coord) | python | def pnum_to_group(mesh_shape, group_dims, pnum):
"""Group number for grouped allreduce.
Args:
mesh_shape: a Shape
group_dims: a list of integers (the dimensions reduced over)
pnum: an integer
Returns:
an integer
"""
coord = pnum_to_processor_coordinates(mesh_shape, pnum)
remaining_shape = Shape(
[d for i, d in enumerate(mesh_shape) if i not in group_dims])
remaining_coord = [d for i, d in enumerate(coord) if i not in group_dims]
return processor_coordinates_to_pnum(remaining_shape, remaining_coord) | [
"def",
"pnum_to_group",
"(",
"mesh_shape",
",",
"group_dims",
",",
"pnum",
")",
":",
"coord",
"=",
"pnum_to_processor_coordinates",
"(",
"mesh_shape",
",",
"pnum",
")",
"remaining_shape",
"=",
"Shape",
"(",
"[",
"d",
"for",
"i",
",",
"d",
"in",
"enumerate",
"(",
"mesh_shape",
")",
"if",
"i",
"not",
"in",
"group_dims",
"]",
")",
"remaining_coord",
"=",
"[",
"d",
"for",
"i",
",",
"d",
"in",
"enumerate",
"(",
"coord",
")",
"if",
"i",
"not",
"in",
"group_dims",
"]",
"return",
"processor_coordinates_to_pnum",
"(",
"remaining_shape",
",",
"remaining_coord",
")"
] | Group number for grouped allreduce.
Args:
mesh_shape: a Shape
group_dims: a list of integers (the dimensions reduced over)
pnum: an integer
Returns:
an integer | [
"Group",
"number",
"for",
"grouped",
"allreduce",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4312-L4327 |
227,885 | tensorflow/mesh | mesh_tensorflow/ops.py | processor_groups | def processor_groups(mesh_shape, group_dims):
"""Groups of processors which differ only in the given dimensions.
Args:
mesh_shape: a Shape
group_dims: a list of integers
Returns:
a list of lists of integers (processor numbers)
"""
group_numbers = [
pnum_to_group(mesh_shape, group_dims, pnum)
for pnum in xrange(mesh_shape.size)]
ret = []
for pnum, g in enumerate(group_numbers):
while len(ret) <= g:
ret.append([])
ret[g].append(pnum)
return ret | python | def processor_groups(mesh_shape, group_dims):
"""Groups of processors which differ only in the given dimensions.
Args:
mesh_shape: a Shape
group_dims: a list of integers
Returns:
a list of lists of integers (processor numbers)
"""
group_numbers = [
pnum_to_group(mesh_shape, group_dims, pnum)
for pnum in xrange(mesh_shape.size)]
ret = []
for pnum, g in enumerate(group_numbers):
while len(ret) <= g:
ret.append([])
ret[g].append(pnum)
return ret | [
"def",
"processor_groups",
"(",
"mesh_shape",
",",
"group_dims",
")",
":",
"group_numbers",
"=",
"[",
"pnum_to_group",
"(",
"mesh_shape",
",",
"group_dims",
",",
"pnum",
")",
"for",
"pnum",
"in",
"xrange",
"(",
"mesh_shape",
".",
"size",
")",
"]",
"ret",
"=",
"[",
"]",
"for",
"pnum",
",",
"g",
"in",
"enumerate",
"(",
"group_numbers",
")",
":",
"while",
"len",
"(",
"ret",
")",
"<=",
"g",
":",
"ret",
".",
"append",
"(",
"[",
"]",
")",
"ret",
"[",
"g",
"]",
".",
"append",
"(",
"pnum",
")",
"return",
"ret"
] | Groups of processors which differ only in the given dimensions.
Args:
mesh_shape: a Shape
group_dims: a list of integers
Returns:
a list of lists of integers (processor numbers) | [
"Groups",
"of",
"processors",
"which",
"differ",
"only",
"in",
"the",
"given",
"dimensions",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4330-L4348 |
227,886 | tensorflow/mesh | mesh_tensorflow/ops.py | mtf_range | def mtf_range(mesh, dim, dtype, name=None):
"""Create a 1d mesh tensor with a range from [0, dim.size).
Call externally as mtf.range()
Args:
mesh: a Mesh
dim: a Dimension
dtype: a tf.DType
name: an optional string
Returns:
a Tensor
"""
dim = convert_to_dimension(dim)
with tf.variable_scope(name, default_name="range"):
if dtype == tf.bfloat16:
# tf.range(dtype=bfloat16) gives the wrong shape.
# TODO(noam): report the bug.
tf_range = tf.cast(tf.range(dim.size), tf.bfloat16)
else:
tf_range = tf.range(dim.size, dtype=dtype)
return import_tf_tensor(mesh, tf_range, shape=Shape([dim])) | python | def mtf_range(mesh, dim, dtype, name=None):
"""Create a 1d mesh tensor with a range from [0, dim.size).
Call externally as mtf.range()
Args:
mesh: a Mesh
dim: a Dimension
dtype: a tf.DType
name: an optional string
Returns:
a Tensor
"""
dim = convert_to_dimension(dim)
with tf.variable_scope(name, default_name="range"):
if dtype == tf.bfloat16:
# tf.range(dtype=bfloat16) gives the wrong shape.
# TODO(noam): report the bug.
tf_range = tf.cast(tf.range(dim.size), tf.bfloat16)
else:
tf_range = tf.range(dim.size, dtype=dtype)
return import_tf_tensor(mesh, tf_range, shape=Shape([dim])) | [
"def",
"mtf_range",
"(",
"mesh",
",",
"dim",
",",
"dtype",
",",
"name",
"=",
"None",
")",
":",
"dim",
"=",
"convert_to_dimension",
"(",
"dim",
")",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"range\"",
")",
":",
"if",
"dtype",
"==",
"tf",
".",
"bfloat16",
":",
"# tf.range(dtype=bfloat16) gives the wrong shape.",
"# TODO(noam): report the bug.",
"tf_range",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"range",
"(",
"dim",
".",
"size",
")",
",",
"tf",
".",
"bfloat16",
")",
"else",
":",
"tf_range",
"=",
"tf",
".",
"range",
"(",
"dim",
".",
"size",
",",
"dtype",
"=",
"dtype",
")",
"return",
"import_tf_tensor",
"(",
"mesh",
",",
"tf_range",
",",
"shape",
"=",
"Shape",
"(",
"[",
"dim",
"]",
")",
")"
] | Create a 1d mesh tensor with a range from [0, dim.size).
Call externally as mtf.range()
Args:
mesh: a Mesh
dim: a Dimension
dtype: a tf.DType
name: an optional string
Returns:
a Tensor | [
"Create",
"a",
"1d",
"mesh",
"tensor",
"with",
"a",
"range",
"from",
"[",
"0",
"dim",
".",
"size",
")",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4406-L4428 |
227,887 | tensorflow/mesh | mesh_tensorflow/ops.py | pretty_print_counters | def pretty_print_counters(counters):
"""print counters hierarchically.
Each counter is a pair of a string and a number.
The string can have slashes, meaning that the number also counts towards
each prefix. e.g. "parameters/trainable" counts towards both "parameters"
and "parameters/trainable".
Args:
counters: a list of (string, number) pairs
Returns:
a string
"""
totals = collections.defaultdict(int)
for (name, val) in counters:
prefixes = [name[:i] for i in xrange(len(name)) if name[i] == "/"] + [name]
for p in prefixes:
totals[p] += val
parts = []
for name, val in sorted(six.iteritems(totals)):
parts.append(" " * name.count("/") + "%s: %.3g" % (name, val))
return "\n".join(parts) | python | def pretty_print_counters(counters):
"""print counters hierarchically.
Each counter is a pair of a string and a number.
The string can have slashes, meaning that the number also counts towards
each prefix. e.g. "parameters/trainable" counts towards both "parameters"
and "parameters/trainable".
Args:
counters: a list of (string, number) pairs
Returns:
a string
"""
totals = collections.defaultdict(int)
for (name, val) in counters:
prefixes = [name[:i] for i in xrange(len(name)) if name[i] == "/"] + [name]
for p in prefixes:
totals[p] += val
parts = []
for name, val in sorted(six.iteritems(totals)):
parts.append(" " * name.count("/") + "%s: %.3g" % (name, val))
return "\n".join(parts) | [
"def",
"pretty_print_counters",
"(",
"counters",
")",
":",
"totals",
"=",
"collections",
".",
"defaultdict",
"(",
"int",
")",
"for",
"(",
"name",
",",
"val",
")",
"in",
"counters",
":",
"prefixes",
"=",
"[",
"name",
"[",
":",
"i",
"]",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"name",
")",
")",
"if",
"name",
"[",
"i",
"]",
"==",
"\"/\"",
"]",
"+",
"[",
"name",
"]",
"for",
"p",
"in",
"prefixes",
":",
"totals",
"[",
"p",
"]",
"+=",
"val",
"parts",
"=",
"[",
"]",
"for",
"name",
",",
"val",
"in",
"sorted",
"(",
"six",
".",
"iteritems",
"(",
"totals",
")",
")",
":",
"parts",
".",
"append",
"(",
"\" \"",
"*",
"name",
".",
"count",
"(",
"\"/\"",
")",
"+",
"\"%s: %.3g\"",
"%",
"(",
"name",
",",
"val",
")",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"parts",
")"
] | print counters hierarchically.
Each counter is a pair of a string and a number.
The string can have slashes, meaning that the number also counts towards
each prefix. e.g. "parameters/trainable" counts towards both "parameters"
and "parameters/trainable".
Args:
counters: a list of (string, number) pairs
Returns:
a string | [
"print",
"counters",
"hierarchically",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4431-L4453 |
227,888 | tensorflow/mesh | mesh_tensorflow/ops.py | _parse_string_to_list_of_pairs | def _parse_string_to_list_of_pairs(s, seconds_to_int=False):
r"""Parses a string into a list of pairs.
In the input string, each pair is separated by a colon, and the delimiters
between pairs are any of " ,.;".
e.g. "rows:32,cols:32"
Args:
s: str to parse.
seconds_to_int: Boolean. If True, then the second elements are returned
as integers; otherwise they are strings.
Returns:
List of tuple pairs.
Raises:
ValueError: Badly formatted string.
"""
ret = []
for p in [s.split(":") for s in re.sub("[,.;]", " ", s).split()]:
if len(p) != 2:
raise ValueError("bad input to _parse_string_to_list_of_pairs %s" % s)
if seconds_to_int:
ret.append((p[0], int(p[1])))
else:
ret.append(tuple(p))
return ret | python | def _parse_string_to_list_of_pairs(s, seconds_to_int=False):
r"""Parses a string into a list of pairs.
In the input string, each pair is separated by a colon, and the delimiters
between pairs are any of " ,.;".
e.g. "rows:32,cols:32"
Args:
s: str to parse.
seconds_to_int: Boolean. If True, then the second elements are returned
as integers; otherwise they are strings.
Returns:
List of tuple pairs.
Raises:
ValueError: Badly formatted string.
"""
ret = []
for p in [s.split(":") for s in re.sub("[,.;]", " ", s).split()]:
if len(p) != 2:
raise ValueError("bad input to _parse_string_to_list_of_pairs %s" % s)
if seconds_to_int:
ret.append((p[0], int(p[1])))
else:
ret.append(tuple(p))
return ret | [
"def",
"_parse_string_to_list_of_pairs",
"(",
"s",
",",
"seconds_to_int",
"=",
"False",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"p",
"in",
"[",
"s",
".",
"split",
"(",
"\":\"",
")",
"for",
"s",
"in",
"re",
".",
"sub",
"(",
"\"[,.;]\"",
",",
"\" \"",
",",
"s",
")",
".",
"split",
"(",
")",
"]",
":",
"if",
"len",
"(",
"p",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"bad input to _parse_string_to_list_of_pairs %s\"",
"%",
"s",
")",
"if",
"seconds_to_int",
":",
"ret",
".",
"append",
"(",
"(",
"p",
"[",
"0",
"]",
",",
"int",
"(",
"p",
"[",
"1",
"]",
")",
")",
")",
"else",
":",
"ret",
".",
"append",
"(",
"tuple",
"(",
"p",
")",
")",
"return",
"ret"
] | r"""Parses a string into a list of pairs.
In the input string, each pair is separated by a colon, and the delimiters
between pairs are any of " ,.;".
e.g. "rows:32,cols:32"
Args:
s: str to parse.
seconds_to_int: Boolean. If True, then the second elements are returned
as integers; otherwise they are strings.
Returns:
List of tuple pairs.
Raises:
ValueError: Badly formatted string. | [
"r",
"Parses",
"a",
"string",
"into",
"a",
"list",
"of",
"pairs",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4456-L4483 |
227,889 | tensorflow/mesh | mesh_tensorflow/ops.py | parallel | def parallel(devices, fn, *args, **kwargs):
"""Call a function once on each device.
Args:
devices: a list of n devices
fn: a function
*args: arguments, each of which is a list of length n
**kwargs: keyword-args, each of which is a list of length n
Returns:
a list of length n
Raises:
ValueError: if the arguments are not all lists of length n
"""
if not isinstance(devices, list):
raise ValueError("devices must be a list")
for x in list(args) + list(six.itervalues(kwargs)):
if not isinstance(x, list) or len(x) != len(devices):
raise ValueError(
"Argument not a list with same length as devices "
"arg=%s devices=%s" % (x, devices))
ret = []
for i, device in enumerate(devices):
with tf.device(device):
with tf.variable_scope("parallel_%d" % i):
my_args = [x[i] for x in args]
my_kwargs = {k: v[i] for k, v in six.iteritems(kwargs)}
ret.append(fn(*my_args, **my_kwargs))
return ret | python | def parallel(devices, fn, *args, **kwargs):
"""Call a function once on each device.
Args:
devices: a list of n devices
fn: a function
*args: arguments, each of which is a list of length n
**kwargs: keyword-args, each of which is a list of length n
Returns:
a list of length n
Raises:
ValueError: if the arguments are not all lists of length n
"""
if not isinstance(devices, list):
raise ValueError("devices must be a list")
for x in list(args) + list(six.itervalues(kwargs)):
if not isinstance(x, list) or len(x) != len(devices):
raise ValueError(
"Argument not a list with same length as devices "
"arg=%s devices=%s" % (x, devices))
ret = []
for i, device in enumerate(devices):
with tf.device(device):
with tf.variable_scope("parallel_%d" % i):
my_args = [x[i] for x in args]
my_kwargs = {k: v[i] for k, v in six.iteritems(kwargs)}
ret.append(fn(*my_args, **my_kwargs))
return ret | [
"def",
"parallel",
"(",
"devices",
",",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"devices",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"\"devices must be a list\"",
")",
"for",
"x",
"in",
"list",
"(",
"args",
")",
"+",
"list",
"(",
"six",
".",
"itervalues",
"(",
"kwargs",
")",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"list",
")",
"or",
"len",
"(",
"x",
")",
"!=",
"len",
"(",
"devices",
")",
":",
"raise",
"ValueError",
"(",
"\"Argument not a list with same length as devices \"",
"\"arg=%s devices=%s\"",
"%",
"(",
"x",
",",
"devices",
")",
")",
"ret",
"=",
"[",
"]",
"for",
"i",
",",
"device",
"in",
"enumerate",
"(",
"devices",
")",
":",
"with",
"tf",
".",
"device",
"(",
"device",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"parallel_%d\"",
"%",
"i",
")",
":",
"my_args",
"=",
"[",
"x",
"[",
"i",
"]",
"for",
"x",
"in",
"args",
"]",
"my_kwargs",
"=",
"{",
"k",
":",
"v",
"[",
"i",
"]",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"kwargs",
")",
"}",
"ret",
".",
"append",
"(",
"fn",
"(",
"*",
"my_args",
",",
"*",
"*",
"my_kwargs",
")",
")",
"return",
"ret"
] | Call a function once on each device.
Args:
devices: a list of n devices
fn: a function
*args: arguments, each of which is a list of length n
**kwargs: keyword-args, each of which is a list of length n
Returns:
a list of length n
Raises:
ValueError: if the arguments are not all lists of length n | [
"Call",
"a",
"function",
"once",
"on",
"each",
"device",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4486-L4513 |
227,890 | tensorflow/mesh | mesh_tensorflow/ops.py | random_uniform | def random_uniform(mesh, shape, **kwargs):
"""Random uniform.
Args:
mesh: a Mesh
shape: a Shape
**kwargs: keyword args for tf.random.uniform, except seed
Returns:
a Tensor
"""
shape = convert_to_shape(shape)
return RandomOperation(mesh, shape, tf.random.uniform, **kwargs).outputs[0] | python | def random_uniform(mesh, shape, **kwargs):
"""Random uniform.
Args:
mesh: a Mesh
shape: a Shape
**kwargs: keyword args for tf.random.uniform, except seed
Returns:
a Tensor
"""
shape = convert_to_shape(shape)
return RandomOperation(mesh, shape, tf.random.uniform, **kwargs).outputs[0] | [
"def",
"random_uniform",
"(",
"mesh",
",",
"shape",
",",
"*",
"*",
"kwargs",
")",
":",
"shape",
"=",
"convert_to_shape",
"(",
"shape",
")",
"return",
"RandomOperation",
"(",
"mesh",
",",
"shape",
",",
"tf",
".",
"random",
".",
"uniform",
",",
"*",
"*",
"kwargs",
")",
".",
"outputs",
"[",
"0",
"]"
] | Random uniform.
Args:
mesh: a Mesh
shape: a Shape
**kwargs: keyword args for tf.random.uniform, except seed
Returns:
a Tensor | [
"Random",
"uniform",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4611-L4623 |
227,891 | tensorflow/mesh | mesh_tensorflow/ops.py | dropout | def dropout(x, keep_prob, noise_shape=None, name=None):
"""Dropout layer.
Args:
x: a Tensor
keep_prob: a float between 0.0 and 1.0
noise_shape: an optional Shape (a subset of x.shape)
name: an optional string
Returns:
a Tensor
"""
noise_shape = convert_to_shape(noise_shape)
if noise_shape is None:
noise_shape = x.shape
with tf.variable_scope(name, default_name="dropout"):
if keep_prob == 1.0:
return x
noise = cast(less(random_uniform(
x.mesh, noise_shape, dtype=x.dtype), keep_prob), x.dtype)
noise /= keep_prob
return x * noise | python | def dropout(x, keep_prob, noise_shape=None, name=None):
"""Dropout layer.
Args:
x: a Tensor
keep_prob: a float between 0.0 and 1.0
noise_shape: an optional Shape (a subset of x.shape)
name: an optional string
Returns:
a Tensor
"""
noise_shape = convert_to_shape(noise_shape)
if noise_shape is None:
noise_shape = x.shape
with tf.variable_scope(name, default_name="dropout"):
if keep_prob == 1.0:
return x
noise = cast(less(random_uniform(
x.mesh, noise_shape, dtype=x.dtype), keep_prob), x.dtype)
noise /= keep_prob
return x * noise | [
"def",
"dropout",
"(",
"x",
",",
"keep_prob",
",",
"noise_shape",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"noise_shape",
"=",
"convert_to_shape",
"(",
"noise_shape",
")",
"if",
"noise_shape",
"is",
"None",
":",
"noise_shape",
"=",
"x",
".",
"shape",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"dropout\"",
")",
":",
"if",
"keep_prob",
"==",
"1.0",
":",
"return",
"x",
"noise",
"=",
"cast",
"(",
"less",
"(",
"random_uniform",
"(",
"x",
".",
"mesh",
",",
"noise_shape",
",",
"dtype",
"=",
"x",
".",
"dtype",
")",
",",
"keep_prob",
")",
",",
"x",
".",
"dtype",
")",
"noise",
"/=",
"keep_prob",
"return",
"x",
"*",
"noise"
] | Dropout layer.
Args:
x: a Tensor
keep_prob: a float between 0.0 and 1.0
noise_shape: an optional Shape (a subset of x.shape)
name: an optional string
Returns:
a Tensor | [
"Dropout",
"layer",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4626-L4647 |
227,892 | tensorflow/mesh | mesh_tensorflow/ops.py | _cumprod | def _cumprod(l):
"""Cumulative product of a list.
Args:
l: a list of integers
Returns:
a list with one more element (starting with 1)
"""
ret = [1]
for item in l:
ret.append(ret[-1] * item)
return ret | python | def _cumprod(l):
"""Cumulative product of a list.
Args:
l: a list of integers
Returns:
a list with one more element (starting with 1)
"""
ret = [1]
for item in l:
ret.append(ret[-1] * item)
return ret | [
"def",
"_cumprod",
"(",
"l",
")",
":",
"ret",
"=",
"[",
"1",
"]",
"for",
"item",
"in",
"l",
":",
"ret",
".",
"append",
"(",
"ret",
"[",
"-",
"1",
"]",
"*",
"item",
")",
"return",
"ret"
] | Cumulative product of a list.
Args:
l: a list of integers
Returns:
a list with one more element (starting with 1) | [
"Cumulative",
"product",
"of",
"a",
"list",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4650-L4661 |
227,893 | tensorflow/mesh | mesh_tensorflow/ops.py | while_loop | def while_loop(cond_fn, body_fn, inputs, num_loop_vars=None,
has_accumulators=False, **kwargs):
"""While Loop.
See comments above for WhileLoopOperation
num_loop_vars is a hack for the multi-gpu setup. In this case, loops
are generally slow, as all loop variables are placed on device. By setting
num_loop_vars=k, then all of the loop variables except for the first k
are handled as mtf Variables instead of loop variables, using explicit
updates and control dependencies. In this case, we only return the
first num_loop_vars outputs. Do not use this option on TPU, since it
is unnecessary and also produces incorrect results, since xla does not
respect control dependencies.
Args:
cond_fn: a function from n Tensors to scalar boolean Tensor
body_fn: a function from n Tensors to list of n Tensors
inputs: a list of n Tensors
num_loop_vars: an optional integer.
has_accumulators: a boolean
**kwargs: additional kwargs passed to tf.while_loop
Returns:
a list of n Tensors.
"""
if num_loop_vars is None:
return WhileLoopOperation(cond_fn, body_fn, inputs, tf_kwargs=kwargs,
has_accumulators=has_accumulators).outputs
# Turn all loop vars except for the first ones into non-loop vars.
# see comments in docstring.
assert num_loop_vars > 0
extra_inputs = inputs[num_loop_vars:]
my_vars = []
for i, x in enumerate(extra_inputs):
my_vars.append(get_variable(
x.mesh, "loop_var_%d" % i,
x.shape, initializer=tf.zeros_initializer(),
dtype=x.dtype,
collections=[tf.GraphKeys.LOCAL_VARIABLES]))
my_vars = tuple(my_vars)
first_input = depend(
inputs[0], [assign(var, x) for var, x in zip(my_vars, extra_inputs)])
inputs = [first_input] + inputs[1:num_loop_vars]
def my_cond_fn(*inputs):
return cond_fn(*(inputs + my_vars))
def my_body_fn(*inputs):
outputs = tuple(body_fn(*(inputs + my_vars)))
extra_outputs = outputs[num_loop_vars:]
first_output = depend(
outputs[0], [assign(var, x) for var, x in zip(my_vars, extra_outputs)])
outputs = (first_output,) + outputs[1:num_loop_vars]
return outputs
return WhileLoopOperation(
my_cond_fn, my_body_fn, inputs, tf_kwargs=kwargs,
has_accumulators=has_accumulators).outputs | python | def while_loop(cond_fn, body_fn, inputs, num_loop_vars=None,
has_accumulators=False, **kwargs):
"""While Loop.
See comments above for WhileLoopOperation
num_loop_vars is a hack for the multi-gpu setup. In this case, loops
are generally slow, as all loop variables are placed on device. By setting
num_loop_vars=k, then all of the loop variables except for the first k
are handled as mtf Variables instead of loop variables, using explicit
updates and control dependencies. In this case, we only return the
first num_loop_vars outputs. Do not use this option on TPU, since it
is unnecessary and also produces incorrect results, since xla does not
respect control dependencies.
Args:
cond_fn: a function from n Tensors to scalar boolean Tensor
body_fn: a function from n Tensors to list of n Tensors
inputs: a list of n Tensors
num_loop_vars: an optional integer.
has_accumulators: a boolean
**kwargs: additional kwargs passed to tf.while_loop
Returns:
a list of n Tensors.
"""
if num_loop_vars is None:
return WhileLoopOperation(cond_fn, body_fn, inputs, tf_kwargs=kwargs,
has_accumulators=has_accumulators).outputs
# Turn all loop vars except for the first ones into non-loop vars.
# see comments in docstring.
assert num_loop_vars > 0
extra_inputs = inputs[num_loop_vars:]
my_vars = []
for i, x in enumerate(extra_inputs):
my_vars.append(get_variable(
x.mesh, "loop_var_%d" % i,
x.shape, initializer=tf.zeros_initializer(),
dtype=x.dtype,
collections=[tf.GraphKeys.LOCAL_VARIABLES]))
my_vars = tuple(my_vars)
first_input = depend(
inputs[0], [assign(var, x) for var, x in zip(my_vars, extra_inputs)])
inputs = [first_input] + inputs[1:num_loop_vars]
def my_cond_fn(*inputs):
return cond_fn(*(inputs + my_vars))
def my_body_fn(*inputs):
outputs = tuple(body_fn(*(inputs + my_vars)))
extra_outputs = outputs[num_loop_vars:]
first_output = depend(
outputs[0], [assign(var, x) for var, x in zip(my_vars, extra_outputs)])
outputs = (first_output,) + outputs[1:num_loop_vars]
return outputs
return WhileLoopOperation(
my_cond_fn, my_body_fn, inputs, tf_kwargs=kwargs,
has_accumulators=has_accumulators).outputs | [
"def",
"while_loop",
"(",
"cond_fn",
",",
"body_fn",
",",
"inputs",
",",
"num_loop_vars",
"=",
"None",
",",
"has_accumulators",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"num_loop_vars",
"is",
"None",
":",
"return",
"WhileLoopOperation",
"(",
"cond_fn",
",",
"body_fn",
",",
"inputs",
",",
"tf_kwargs",
"=",
"kwargs",
",",
"has_accumulators",
"=",
"has_accumulators",
")",
".",
"outputs",
"# Turn all loop vars except for the first ones into non-loop vars.",
"# see comments in docstring.",
"assert",
"num_loop_vars",
">",
"0",
"extra_inputs",
"=",
"inputs",
"[",
"num_loop_vars",
":",
"]",
"my_vars",
"=",
"[",
"]",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"extra_inputs",
")",
":",
"my_vars",
".",
"append",
"(",
"get_variable",
"(",
"x",
".",
"mesh",
",",
"\"loop_var_%d\"",
"%",
"i",
",",
"x",
".",
"shape",
",",
"initializer",
"=",
"tf",
".",
"zeros_initializer",
"(",
")",
",",
"dtype",
"=",
"x",
".",
"dtype",
",",
"collections",
"=",
"[",
"tf",
".",
"GraphKeys",
".",
"LOCAL_VARIABLES",
"]",
")",
")",
"my_vars",
"=",
"tuple",
"(",
"my_vars",
")",
"first_input",
"=",
"depend",
"(",
"inputs",
"[",
"0",
"]",
",",
"[",
"assign",
"(",
"var",
",",
"x",
")",
"for",
"var",
",",
"x",
"in",
"zip",
"(",
"my_vars",
",",
"extra_inputs",
")",
"]",
")",
"inputs",
"=",
"[",
"first_input",
"]",
"+",
"inputs",
"[",
"1",
":",
"num_loop_vars",
"]",
"def",
"my_cond_fn",
"(",
"*",
"inputs",
")",
":",
"return",
"cond_fn",
"(",
"*",
"(",
"inputs",
"+",
"my_vars",
")",
")",
"def",
"my_body_fn",
"(",
"*",
"inputs",
")",
":",
"outputs",
"=",
"tuple",
"(",
"body_fn",
"(",
"*",
"(",
"inputs",
"+",
"my_vars",
")",
")",
")",
"extra_outputs",
"=",
"outputs",
"[",
"num_loop_vars",
":",
"]",
"first_output",
"=",
"depend",
"(",
"outputs",
"[",
"0",
"]",
",",
"[",
"assign",
"(",
"var",
",",
"x",
")",
"for",
"var",
",",
"x",
"in",
"zip",
"(",
"my_vars",
",",
"extra_outputs",
")",
"]",
")",
"outputs",
"=",
"(",
"first_output",
",",
")",
"+",
"outputs",
"[",
"1",
":",
"num_loop_vars",
"]",
"return",
"outputs",
"return",
"WhileLoopOperation",
"(",
"my_cond_fn",
",",
"my_body_fn",
",",
"inputs",
",",
"tf_kwargs",
"=",
"kwargs",
",",
"has_accumulators",
"=",
"has_accumulators",
")",
".",
"outputs"
] | While Loop.
See comments above for WhileLoopOperation
num_loop_vars is a hack for the multi-gpu setup. In this case, loops
are generally slow, as all loop variables are placed on device. By setting
num_loop_vars=k, then all of the loop variables except for the first k
are handled as mtf Variables instead of loop variables, using explicit
updates and control dependencies. In this case, we only return the
first num_loop_vars outputs. Do not use this option on TPU, since it
is unnecessary and also produces incorrect results, since xla does not
respect control dependencies.
Args:
cond_fn: a function from n Tensors to scalar boolean Tensor
body_fn: a function from n Tensors to list of n Tensors
inputs: a list of n Tensors
num_loop_vars: an optional integer.
has_accumulators: a boolean
**kwargs: additional kwargs passed to tf.while_loop
Returns:
a list of n Tensors. | [
"While",
"Loop",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4855-L4910 |
227,894 | tensorflow/mesh | mesh_tensorflow/ops.py | _shape_union | def _shape_union(shapes):
"""A shape containing the union of all dimensions in the input shapes.
Args:
shapes: a list of Shapes
Returns:
a Shape
"""
return Shape(sorted(list(set(sum([s.dims for s in shapes], []))))) | python | def _shape_union(shapes):
"""A shape containing the union of all dimensions in the input shapes.
Args:
shapes: a list of Shapes
Returns:
a Shape
"""
return Shape(sorted(list(set(sum([s.dims for s in shapes], []))))) | [
"def",
"_shape_union",
"(",
"shapes",
")",
":",
"return",
"Shape",
"(",
"sorted",
"(",
"list",
"(",
"set",
"(",
"sum",
"(",
"[",
"s",
".",
"dims",
"for",
"s",
"in",
"shapes",
"]",
",",
"[",
"]",
")",
")",
")",
")",
")"
] | A shape containing the union of all dimensions in the input shapes.
Args:
shapes: a list of Shapes
Returns:
a Shape | [
"A",
"shape",
"containing",
"the",
"union",
"of",
"all",
"dimensions",
"in",
"the",
"input",
"shapes",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4921-L4930 |
227,895 | tensorflow/mesh | mesh_tensorflow/ops.py | _tf_flatten_batch_dims | def _tf_flatten_batch_dims(x, num_nonbatch_dims):
"""Flatten all but last num_nonbatch_dims into one dimension.
Args:
x: a tf.Tensor:
num_nonbatch_dims: an integer
Returns:
a tf.Tensor with 1 + num_nonbatch_dims dimensions.
"""
shape = x.shape.as_list()
assert None not in shape
new_shape = ([list_product(shape[:-num_nonbatch_dims])]
+ shape[-num_nonbatch_dims:])
if new_shape != shape:
x = tf.reshape(x, new_shape)
return x | python | def _tf_flatten_batch_dims(x, num_nonbatch_dims):
"""Flatten all but last num_nonbatch_dims into one dimension.
Args:
x: a tf.Tensor:
num_nonbatch_dims: an integer
Returns:
a tf.Tensor with 1 + num_nonbatch_dims dimensions.
"""
shape = x.shape.as_list()
assert None not in shape
new_shape = ([list_product(shape[:-num_nonbatch_dims])]
+ shape[-num_nonbatch_dims:])
if new_shape != shape:
x = tf.reshape(x, new_shape)
return x | [
"def",
"_tf_flatten_batch_dims",
"(",
"x",
",",
"num_nonbatch_dims",
")",
":",
"shape",
"=",
"x",
".",
"shape",
".",
"as_list",
"(",
")",
"assert",
"None",
"not",
"in",
"shape",
"new_shape",
"=",
"(",
"[",
"list_product",
"(",
"shape",
"[",
":",
"-",
"num_nonbatch_dims",
"]",
")",
"]",
"+",
"shape",
"[",
"-",
"num_nonbatch_dims",
":",
"]",
")",
"if",
"new_shape",
"!=",
"shape",
":",
"x",
"=",
"tf",
".",
"reshape",
"(",
"x",
",",
"new_shape",
")",
"return",
"x"
] | Flatten all but last num_nonbatch_dims into one dimension.
Args:
x: a tf.Tensor:
num_nonbatch_dims: an integer
Returns:
a tf.Tensor with 1 + num_nonbatch_dims dimensions. | [
"Flatten",
"all",
"but",
"last",
"num_nonbatch_dims",
"into",
"one",
"dimension",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4933-L4949 |
227,896 | tensorflow/mesh | mesh_tensorflow/ops.py | _tf_restore_batch_dims | def _tf_restore_batch_dims(x, num_nonbatch_dims, prototype):
"""Reverse op of _tf_flatten_batch_dims.
Un-flatten the first dimension of x to match all but the last
num_nonbatch_dims dimensions of prototype.
Args:
x: a tf.Tensor with 1 + num_nonbatch_dims dimensions
num_nonbatch_dims: an integer
prototype: a tf.Tensor
Returns:
a tf.Tensor
"""
assert x.shape.ndims == 1 + num_nonbatch_dims
new_shape = (
prototype.shape.as_list()[:-num_nonbatch_dims] + x.shape.as_list()[1:])
assert None not in new_shape
if new_shape != x.shape.as_list():
x = tf.reshape(x, new_shape)
return x | python | def _tf_restore_batch_dims(x, num_nonbatch_dims, prototype):
"""Reverse op of _tf_flatten_batch_dims.
Un-flatten the first dimension of x to match all but the last
num_nonbatch_dims dimensions of prototype.
Args:
x: a tf.Tensor with 1 + num_nonbatch_dims dimensions
num_nonbatch_dims: an integer
prototype: a tf.Tensor
Returns:
a tf.Tensor
"""
assert x.shape.ndims == 1 + num_nonbatch_dims
new_shape = (
prototype.shape.as_list()[:-num_nonbatch_dims] + x.shape.as_list()[1:])
assert None not in new_shape
if new_shape != x.shape.as_list():
x = tf.reshape(x, new_shape)
return x | [
"def",
"_tf_restore_batch_dims",
"(",
"x",
",",
"num_nonbatch_dims",
",",
"prototype",
")",
":",
"assert",
"x",
".",
"shape",
".",
"ndims",
"==",
"1",
"+",
"num_nonbatch_dims",
"new_shape",
"=",
"(",
"prototype",
".",
"shape",
".",
"as_list",
"(",
")",
"[",
":",
"-",
"num_nonbatch_dims",
"]",
"+",
"x",
".",
"shape",
".",
"as_list",
"(",
")",
"[",
"1",
":",
"]",
")",
"assert",
"None",
"not",
"in",
"new_shape",
"if",
"new_shape",
"!=",
"x",
".",
"shape",
".",
"as_list",
"(",
")",
":",
"x",
"=",
"tf",
".",
"reshape",
"(",
"x",
",",
"new_shape",
")",
"return",
"x"
] | Reverse op of _tf_flatten_batch_dims.
Un-flatten the first dimension of x to match all but the last
num_nonbatch_dims dimensions of prototype.
Args:
x: a tf.Tensor with 1 + num_nonbatch_dims dimensions
num_nonbatch_dims: an integer
prototype: a tf.Tensor
Returns:
a tf.Tensor | [
"Reverse",
"op",
"of",
"_tf_flatten_batch_dims",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4952-L4972 |
227,897 | tensorflow/mesh | mesh_tensorflow/ops.py | halo_exchange | def halo_exchange(x, blocks_dim, block_size_dim, halo_size, wrap=False):
"""Concat each block with the margins of adjacent blocks.
Get left and right blocks_dim and concatenate along block_size_dim.
Args:
x: a Tensor.
blocks_dim: a Dimension in x.shape
block_size_dim: a Dimension in x.shape
halo_size: an integer
wrap: a boolean
Returns:
a Tensor with the same shape as x, other than in block_size_dim, whose
size is increased by 2*halo_size.
"""
if halo_size == 0:
return x
block_size = block_size_dim.size
partial_size = halo_size % block_size
num_complete_blocks = halo_size // block_size
parts = [x]
for i in xrange(1, num_complete_blocks + 1):
parts = ([shift(x, i, blocks_dim, wrap)] + parts +
[shift(x, -i, blocks_dim, wrap)])
if partial_size > 0:
left_margin = mtf_slice(x, 0, partial_size, block_size_dim.name)
right_margin = mtf_slice(
x, block_size_dim.size - partial_size, partial_size,
block_size_dim.name)
parts = (
[shift(right_margin, num_complete_blocks + 1, blocks_dim, wrap)]
+ parts +
[shift(left_margin, -(num_complete_blocks + 1), blocks_dim, wrap)])
return concat(parts, block_size_dim.name) | python | def halo_exchange(x, blocks_dim, block_size_dim, halo_size, wrap=False):
"""Concat each block with the margins of adjacent blocks.
Get left and right blocks_dim and concatenate along block_size_dim.
Args:
x: a Tensor.
blocks_dim: a Dimension in x.shape
block_size_dim: a Dimension in x.shape
halo_size: an integer
wrap: a boolean
Returns:
a Tensor with the same shape as x, other than in block_size_dim, whose
size is increased by 2*halo_size.
"""
if halo_size == 0:
return x
block_size = block_size_dim.size
partial_size = halo_size % block_size
num_complete_blocks = halo_size // block_size
parts = [x]
for i in xrange(1, num_complete_blocks + 1):
parts = ([shift(x, i, blocks_dim, wrap)] + parts +
[shift(x, -i, blocks_dim, wrap)])
if partial_size > 0:
left_margin = mtf_slice(x, 0, partial_size, block_size_dim.name)
right_margin = mtf_slice(
x, block_size_dim.size - partial_size, partial_size,
block_size_dim.name)
parts = (
[shift(right_margin, num_complete_blocks + 1, blocks_dim, wrap)]
+ parts +
[shift(left_margin, -(num_complete_blocks + 1), blocks_dim, wrap)])
return concat(parts, block_size_dim.name) | [
"def",
"halo_exchange",
"(",
"x",
",",
"blocks_dim",
",",
"block_size_dim",
",",
"halo_size",
",",
"wrap",
"=",
"False",
")",
":",
"if",
"halo_size",
"==",
"0",
":",
"return",
"x",
"block_size",
"=",
"block_size_dim",
".",
"size",
"partial_size",
"=",
"halo_size",
"%",
"block_size",
"num_complete_blocks",
"=",
"halo_size",
"//",
"block_size",
"parts",
"=",
"[",
"x",
"]",
"for",
"i",
"in",
"xrange",
"(",
"1",
",",
"num_complete_blocks",
"+",
"1",
")",
":",
"parts",
"=",
"(",
"[",
"shift",
"(",
"x",
",",
"i",
",",
"blocks_dim",
",",
"wrap",
")",
"]",
"+",
"parts",
"+",
"[",
"shift",
"(",
"x",
",",
"-",
"i",
",",
"blocks_dim",
",",
"wrap",
")",
"]",
")",
"if",
"partial_size",
">",
"0",
":",
"left_margin",
"=",
"mtf_slice",
"(",
"x",
",",
"0",
",",
"partial_size",
",",
"block_size_dim",
".",
"name",
")",
"right_margin",
"=",
"mtf_slice",
"(",
"x",
",",
"block_size_dim",
".",
"size",
"-",
"partial_size",
",",
"partial_size",
",",
"block_size_dim",
".",
"name",
")",
"parts",
"=",
"(",
"[",
"shift",
"(",
"right_margin",
",",
"num_complete_blocks",
"+",
"1",
",",
"blocks_dim",
",",
"wrap",
")",
"]",
"+",
"parts",
"+",
"[",
"shift",
"(",
"left_margin",
",",
"-",
"(",
"num_complete_blocks",
"+",
"1",
")",
",",
"blocks_dim",
",",
"wrap",
")",
"]",
")",
"return",
"concat",
"(",
"parts",
",",
"block_size_dim",
".",
"name",
")"
] | Concat each block with the margins of adjacent blocks.
Get left and right blocks_dim and concatenate along block_size_dim.
Args:
x: a Tensor.
blocks_dim: a Dimension in x.shape
block_size_dim: a Dimension in x.shape
halo_size: an integer
wrap: a boolean
Returns:
a Tensor with the same shape as x, other than in block_size_dim, whose
size is increased by 2*halo_size. | [
"Concat",
"each",
"block",
"with",
"the",
"margins",
"of",
"adjacent",
"blocks",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4975-L5011 |
227,898 | tensorflow/mesh | mesh_tensorflow/ops.py | conv2d_with_blocks | def conv2d_with_blocks(
conv_input,
conv_filter,
strides,
padding,
h_blocks_dim=None,
w_blocks_dim=None,
name=None):
"""conv2d operation with spatial partitioning.
Spatial partitioning is implemented by decomposing the image into blocks.
Block dimensions represented as h_blocks_dim and w_blocks_dim can be split
along the mesh axis. If split, then we do a halo exchange where each block
receives the part of the image from its left and right neighbors necessary to
do the convolution. Exchange can involve complete or partial blocks depending
on the filter height and width.
Currently, only "SAME" padding with dilation rate of 1 is supported.
Args:
conv_input: a Tensor of shape
[batch, h_blocks_dim, w_blocks_dim, h_dim, w_dim, in_channels_dim]
conv_filter: a Tensor of shape
[filter_height, filter_width, in_channels_dim, out_channels_dim]
strides: A list of ints. 1-D tensor of length 4.
padding: string, "SAME". The type of padding algorithm to use.
Valid is not currently supported.
h_blocks_dim: Dimension representing number of height blocks.
w_blocks_dim: Dimension representing number of height blocks.
name: A name for the operation (optional).
Returns:
A Tensor of shape
[batch, h_blocks_dim, w_blocks_dim, h_dim, w_dim, out_channels_dim]
"""
filter_h_dim, filter_w_dim = conv_filter.shape.dims[:2]
assert filter_h_dim.size % 2 == 1
assert filter_w_dim.size % 2 == 1
h_dim, w_dim = conv_input.shape.dims[-3:-1]
# If h_blocks_dim and w_blocks_dim is not split, directly call conv2d.
if h_blocks_dim is None and w_blocks_dim is None:
return conv2d(conv_input, conv_filter, strides, padding, name)
# Padding 'VALID' is not supported yet.
if padding != "SAME":
raise NotImplementedError("conv2d_with_blocks requires padding=SAME")
# Halo exchange for h_blocks and w_blocks.
for blocks_dim, block_size_dim, halo_size in [
(h_blocks_dim, h_dim, filter_h_dim.size // 2),
(w_blocks_dim, w_dim, filter_w_dim.size // 2)]:
if halo_size > 0:
if blocks_dim is not None:
conv_input = halo_exchange(
conv_input, blocks_dim, block_size_dim, halo_size)
else:
conv_input = pad(
conv_input, [halo_size, halo_size], block_size_dim.name)
return conv2d(conv_input, conv_filter, strides, "VALID", name) | python | def conv2d_with_blocks(
conv_input,
conv_filter,
strides,
padding,
h_blocks_dim=None,
w_blocks_dim=None,
name=None):
"""conv2d operation with spatial partitioning.
Spatial partitioning is implemented by decomposing the image into blocks.
Block dimensions represented as h_blocks_dim and w_blocks_dim can be split
along the mesh axis. If split, then we do a halo exchange where each block
receives the part of the image from its left and right neighbors necessary to
do the convolution. Exchange can involve complete or partial blocks depending
on the filter height and width.
Currently, only "SAME" padding with dilation rate of 1 is supported.
Args:
conv_input: a Tensor of shape
[batch, h_blocks_dim, w_blocks_dim, h_dim, w_dim, in_channels_dim]
conv_filter: a Tensor of shape
[filter_height, filter_width, in_channels_dim, out_channels_dim]
strides: A list of ints. 1-D tensor of length 4.
padding: string, "SAME". The type of padding algorithm to use.
Valid is not currently supported.
h_blocks_dim: Dimension representing number of height blocks.
w_blocks_dim: Dimension representing number of height blocks.
name: A name for the operation (optional).
Returns:
A Tensor of shape
[batch, h_blocks_dim, w_blocks_dim, h_dim, w_dim, out_channels_dim]
"""
filter_h_dim, filter_w_dim = conv_filter.shape.dims[:2]
assert filter_h_dim.size % 2 == 1
assert filter_w_dim.size % 2 == 1
h_dim, w_dim = conv_input.shape.dims[-3:-1]
# If h_blocks_dim and w_blocks_dim is not split, directly call conv2d.
if h_blocks_dim is None and w_blocks_dim is None:
return conv2d(conv_input, conv_filter, strides, padding, name)
# Padding 'VALID' is not supported yet.
if padding != "SAME":
raise NotImplementedError("conv2d_with_blocks requires padding=SAME")
# Halo exchange for h_blocks and w_blocks.
for blocks_dim, block_size_dim, halo_size in [
(h_blocks_dim, h_dim, filter_h_dim.size // 2),
(w_blocks_dim, w_dim, filter_w_dim.size // 2)]:
if halo_size > 0:
if blocks_dim is not None:
conv_input = halo_exchange(
conv_input, blocks_dim, block_size_dim, halo_size)
else:
conv_input = pad(
conv_input, [halo_size, halo_size], block_size_dim.name)
return conv2d(conv_input, conv_filter, strides, "VALID", name) | [
"def",
"conv2d_with_blocks",
"(",
"conv_input",
",",
"conv_filter",
",",
"strides",
",",
"padding",
",",
"h_blocks_dim",
"=",
"None",
",",
"w_blocks_dim",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"filter_h_dim",
",",
"filter_w_dim",
"=",
"conv_filter",
".",
"shape",
".",
"dims",
"[",
":",
"2",
"]",
"assert",
"filter_h_dim",
".",
"size",
"%",
"2",
"==",
"1",
"assert",
"filter_w_dim",
".",
"size",
"%",
"2",
"==",
"1",
"h_dim",
",",
"w_dim",
"=",
"conv_input",
".",
"shape",
".",
"dims",
"[",
"-",
"3",
":",
"-",
"1",
"]",
"# If h_blocks_dim and w_blocks_dim is not split, directly call conv2d.",
"if",
"h_blocks_dim",
"is",
"None",
"and",
"w_blocks_dim",
"is",
"None",
":",
"return",
"conv2d",
"(",
"conv_input",
",",
"conv_filter",
",",
"strides",
",",
"padding",
",",
"name",
")",
"# Padding 'VALID' is not supported yet.",
"if",
"padding",
"!=",
"\"SAME\"",
":",
"raise",
"NotImplementedError",
"(",
"\"conv2d_with_blocks requires padding=SAME\"",
")",
"# Halo exchange for h_blocks and w_blocks.",
"for",
"blocks_dim",
",",
"block_size_dim",
",",
"halo_size",
"in",
"[",
"(",
"h_blocks_dim",
",",
"h_dim",
",",
"filter_h_dim",
".",
"size",
"//",
"2",
")",
",",
"(",
"w_blocks_dim",
",",
"w_dim",
",",
"filter_w_dim",
".",
"size",
"//",
"2",
")",
"]",
":",
"if",
"halo_size",
">",
"0",
":",
"if",
"blocks_dim",
"is",
"not",
"None",
":",
"conv_input",
"=",
"halo_exchange",
"(",
"conv_input",
",",
"blocks_dim",
",",
"block_size_dim",
",",
"halo_size",
")",
"else",
":",
"conv_input",
"=",
"pad",
"(",
"conv_input",
",",
"[",
"halo_size",
",",
"halo_size",
"]",
",",
"block_size_dim",
".",
"name",
")",
"return",
"conv2d",
"(",
"conv_input",
",",
"conv_filter",
",",
"strides",
",",
"\"VALID\"",
",",
"name",
")"
] | conv2d operation with spatial partitioning.
Spatial partitioning is implemented by decomposing the image into blocks.
Block dimensions represented as h_blocks_dim and w_blocks_dim can be split
along the mesh axis. If split, then we do a halo exchange where each block
receives the part of the image from its left and right neighbors necessary to
do the convolution. Exchange can involve complete or partial blocks depending
on the filter height and width.
Currently, only "SAME" padding with dilation rate of 1 is supported.
Args:
conv_input: a Tensor of shape
[batch, h_blocks_dim, w_blocks_dim, h_dim, w_dim, in_channels_dim]
conv_filter: a Tensor of shape
[filter_height, filter_width, in_channels_dim, out_channels_dim]
strides: A list of ints. 1-D tensor of length 4.
padding: string, "SAME". The type of padding algorithm to use.
Valid is not currently supported.
h_blocks_dim: Dimension representing number of height blocks.
w_blocks_dim: Dimension representing number of height blocks.
name: A name for the operation (optional).
Returns:
A Tensor of shape
[batch, h_blocks_dim, w_blocks_dim, h_dim, w_dim, out_channels_dim] | [
"conv2d",
"operation",
"with",
"spatial",
"partitioning",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L5049-L5108 |
227,899 | tensorflow/mesh | mesh_tensorflow/ops.py | tensor_dim_to_mesh_dim_size | def tensor_dim_to_mesh_dim_size(layout, mesh_shape, tensor_dim):
"""How many ways does a tensor dimension get split.
This is used to "cheat" when building the mtf graph and peek at how a
tensor dimension will be split. Returns 1 if the tensor dimension is not
split.
Args:
layout: an input to convert_to_layout_rules
mesh_shape: an input to convert_to_shape
tensor_dim: a Dimension
Returns:
an integer
"""
layout_rules = convert_to_layout_rules(layout)
mesh_shape = convert_to_shape(mesh_shape)
mesh_axis = layout_rules.tensor_dimension_to_mesh_axis(tensor_dim, mesh_shape)
if mesh_axis is None:
return 1
else:
return mesh_shape.dims[mesh_axis].size | python | def tensor_dim_to_mesh_dim_size(layout, mesh_shape, tensor_dim):
"""How many ways does a tensor dimension get split.
This is used to "cheat" when building the mtf graph and peek at how a
tensor dimension will be split. Returns 1 if the tensor dimension is not
split.
Args:
layout: an input to convert_to_layout_rules
mesh_shape: an input to convert_to_shape
tensor_dim: a Dimension
Returns:
an integer
"""
layout_rules = convert_to_layout_rules(layout)
mesh_shape = convert_to_shape(mesh_shape)
mesh_axis = layout_rules.tensor_dimension_to_mesh_axis(tensor_dim, mesh_shape)
if mesh_axis is None:
return 1
else:
return mesh_shape.dims[mesh_axis].size | [
"def",
"tensor_dim_to_mesh_dim_size",
"(",
"layout",
",",
"mesh_shape",
",",
"tensor_dim",
")",
":",
"layout_rules",
"=",
"convert_to_layout_rules",
"(",
"layout",
")",
"mesh_shape",
"=",
"convert_to_shape",
"(",
"mesh_shape",
")",
"mesh_axis",
"=",
"layout_rules",
".",
"tensor_dimension_to_mesh_axis",
"(",
"tensor_dim",
",",
"mesh_shape",
")",
"if",
"mesh_axis",
"is",
"None",
":",
"return",
"1",
"else",
":",
"return",
"mesh_shape",
".",
"dims",
"[",
"mesh_axis",
"]",
".",
"size"
] | How many ways does a tensor dimension get split.
This is used to "cheat" when building the mtf graph and peek at how a
tensor dimension will be split. Returns 1 if the tensor dimension is not
split.
Args:
layout: an input to convert_to_layout_rules
mesh_shape: an input to convert_to_shape
tensor_dim: a Dimension
Returns:
an integer | [
"How",
"many",
"ways",
"does",
"a",
"tensor",
"dimension",
"get",
"split",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L5111-L5132 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.