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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
241,600 | tensorflow/mesh | mesh_tensorflow/layers.py | layer_norm | def layer_norm(x, dim, epsilon=1e-6, name="layer_prepostprocess"):
"""Layer normalization over dimension dim.
Args:
x: a mtf.Tensor whose shape contains dim.
dim: a mtf.Dimension
epsilon: a floating point number
name: a string. variable scope.
Returns:
a mtf.Tensor with same shape as x.
""... | python | def layer_norm(x, dim, epsilon=1e-6, name="layer_prepostprocess"):
with tf.variable_scope(name + "/layer_norm"):
scale = mtf.get_variable(
x.mesh,
"layer_norm_scale",
mtf.Shape([dim]),
initializer=tf.ones_initializer(),
activation_dtype=x.dtype)
bias = mtf.get_variable(... | [
"def",
"layer_norm",
"(",
"x",
",",
"dim",
",",
"epsilon",
"=",
"1e-6",
",",
"name",
"=",
"\"layer_prepostprocess\"",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
"+",
"\"/layer_norm\"",
")",
":",
"scale",
"=",
"mtf",
".",
"get_variable",
... | Layer normalization over dimension dim.
Args:
x: a mtf.Tensor whose shape contains dim.
dim: a mtf.Dimension
epsilon: a floating point number
name: a string. variable scope.
Returns:
a mtf.Tensor with same shape as x. | [
"Layer",
"normalization",
"over",
"dimension",
"dim",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L85-L114 |
241,601 | tensorflow/mesh | mesh_tensorflow/layers.py | softmax_cross_entropy_with_logits | def softmax_cross_entropy_with_logits(logits, targets, vocab_dim, z_loss=0.0):
"""Per-example softmax loss.
if z_loss is nonzero, we add a loss equal to z_loss*log(z)^2, where z is the
partition function. Example value: z_loss=1e-4. Two uses of z_loss are:
- To keep the logits from drifting too far from zero... | python | def softmax_cross_entropy_with_logits(logits, targets, vocab_dim, z_loss=0.0):
if logits.shape != targets.shape:
raise ValueError(
"logits shape must equal targets shape"
"logits=%s targets=%s" % (logits.to_string, targets.to_string))
if vocab_dim not in logits.shape.dims:
raise ValueError("... | [
"def",
"softmax_cross_entropy_with_logits",
"(",
"logits",
",",
"targets",
",",
"vocab_dim",
",",
"z_loss",
"=",
"0.0",
")",
":",
"if",
"logits",
".",
"shape",
"!=",
"targets",
".",
"shape",
":",
"raise",
"ValueError",
"(",
"\"logits shape must equal targets shape... | Per-example softmax loss.
if z_loss is nonzero, we add a loss equal to z_loss*log(z)^2, where z is the
partition function. Example value: z_loss=1e-4. Two uses of z_loss are:
- To keep the logits from drifting too far from zero, which can cause
unacceptable roundoff errors in bfloat16.
- To encourage th... | [
"Per",
"-",
"example",
"softmax",
"loss",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L187-L220 |
241,602 | tensorflow/mesh | mesh_tensorflow/layers.py | sigmoid_cross_entropy_with_logits | def sigmoid_cross_entropy_with_logits(logits, targets):
"""Sigmoid cross-entropy loss.
Args:
logits: a mtf.Tensor
targets: a mtf.Tensor with the same shape as logits
Returns:
a mtf.Tensor whose shape is equal to logits.shape
Raises:
ValueError: if the shapes do not match.
"""
if logits.sh... | python | def sigmoid_cross_entropy_with_logits(logits, targets):
if logits.shape != targets.shape:
raise ValueError(
"logits shape must equal targets shape"
"logits=%s targets=%s" % (logits.to_string, targets.to_string))
x = logits
z = targets
return mtf.relu(x) - x * z + mtf.log(1 + mtf.exp(-mtf.abs... | [
"def",
"sigmoid_cross_entropy_with_logits",
"(",
"logits",
",",
"targets",
")",
":",
"if",
"logits",
".",
"shape",
"!=",
"targets",
".",
"shape",
":",
"raise",
"ValueError",
"(",
"\"logits shape must equal targets shape\"",
"\"logits=%s targets=%s\"",
"%",
"(",
"logit... | Sigmoid cross-entropy loss.
Args:
logits: a mtf.Tensor
targets: a mtf.Tensor with the same shape as logits
Returns:
a mtf.Tensor whose shape is equal to logits.shape
Raises:
ValueError: if the shapes do not match. | [
"Sigmoid",
"cross",
"-",
"entropy",
"loss",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L223-L242 |
241,603 | tensorflow/mesh | mesh_tensorflow/layers.py | dense_relu_dense | def dense_relu_dense(x,
hidden_channels,
dropout=0.0,
dropout_broadcast_dims=None,
master_dtype=tf.float32,
slice_dtype=tf.float32, name=None):
"""Hidden layer with ReLU activation followed by linear projection.
... | python | def dense_relu_dense(x,
hidden_channels,
dropout=0.0,
dropout_broadcast_dims=None,
master_dtype=tf.float32,
slice_dtype=tf.float32, name=None):
with tf.variable_scope(name, default_name="dense_relu_dense"):
io... | [
"def",
"dense_relu_dense",
"(",
"x",
",",
"hidden_channels",
",",
"dropout",
"=",
"0.0",
",",
"dropout_broadcast_dims",
"=",
"None",
",",
"master_dtype",
"=",
"tf",
".",
"float32",
",",
"slice_dtype",
"=",
"tf",
".",
"float32",
",",
"name",
"=",
"None",
")... | Hidden layer with ReLU activation followed by linear projection.
The output has the same number of channels as the input.
Args:
x: a mtf.Tensor
hidden_channels: a mtf.Dimension - channels in the hidden layer
dropout: an optional float
dropout_broadcast_dims: an optional list of mtf.Dimension
m... | [
"Hidden",
"layer",
"with",
"ReLU",
"activation",
"followed",
"by",
"linear",
"projection",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L251-L283 |
241,604 | tensorflow/mesh | mesh_tensorflow/layers.py | local_1d_halo_exchange | def local_1d_halo_exchange(k, v, num_w_blocks, w_dim, mask_right):
"""Halo exchange for keys and values for Local 1D attention."""
if num_w_blocks is not None:
if mask_right:
k = mtf.left_halo_exchange(k, num_w_blocks, w_dim, w_dim.size)
v = mtf.left_halo_exchange(v, num_w_blocks, w_dim, w_dim.size)... | python | def local_1d_halo_exchange(k, v, num_w_blocks, w_dim, mask_right):
if num_w_blocks is not None:
if mask_right:
k = mtf.left_halo_exchange(k, num_w_blocks, w_dim, w_dim.size)
v = mtf.left_halo_exchange(v, num_w_blocks, w_dim, w_dim.size)
else:
k = mtf.halo_exchange(k, num_w_blocks, w_dim, w_d... | [
"def",
"local_1d_halo_exchange",
"(",
"k",
",",
"v",
",",
"num_w_blocks",
",",
"w_dim",
",",
"mask_right",
")",
":",
"if",
"num_w_blocks",
"is",
"not",
"None",
":",
"if",
"mask_right",
":",
"k",
"=",
"mtf",
".",
"left_halo_exchange",
"(",
"k",
",",
"num_... | Halo exchange for keys and values for Local 1D attention. | [
"Halo",
"exchange",
"for",
"keys",
"and",
"values",
"for",
"Local",
"1D",
"attention",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L286-L302 |
241,605 | tensorflow/mesh | mesh_tensorflow/layers.py | local_2d_halo_exchange | def local_2d_halo_exchange(k, v, num_h_blocks, h_dim,
num_w_blocks, w_dim, mask_right):
"""Halo exchange for keys and values for Local 2D attention."""
for blocks_dim, block_size_dim, halo_size in [
(num_h_blocks, h_dim, h_dim.size),
(num_w_blocks, w_dim, w_dim.size)]:
# s... | python | def local_2d_halo_exchange(k, v, num_h_blocks, h_dim,
num_w_blocks, w_dim, mask_right):
for blocks_dim, block_size_dim, halo_size in [
(num_h_blocks, h_dim, h_dim.size),
(num_w_blocks, w_dim, w_dim.size)]:
# shape of k is [num_h_blocks, num_w_blocks, h_dim, w_dim, kv_channel... | [
"def",
"local_2d_halo_exchange",
"(",
"k",
",",
"v",
",",
"num_h_blocks",
",",
"h_dim",
",",
"num_w_blocks",
",",
"w_dim",
",",
"mask_right",
")",
":",
"for",
"blocks_dim",
",",
"block_size_dim",
",",
"halo_size",
"in",
"[",
"(",
"num_h_blocks",
",",
"h_dim"... | Halo exchange for keys and values for Local 2D attention. | [
"Halo",
"exchange",
"for",
"keys",
"and",
"values",
"for",
"Local",
"2D",
"attention",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L535-L557 |
241,606 | tensorflow/mesh | mesh_tensorflow/layers.py | local_2d_self_attention_spatial_blocks | def local_2d_self_attention_spatial_blocks(query_antecedent,
kv_channels,
heads,
memory_h_dim=None,
memory_w_dim=None,
... | python | def local_2d_self_attention_spatial_blocks(query_antecedent,
kv_channels,
heads,
memory_h_dim=None,
memory_w_dim=None,
... | [
"def",
"local_2d_self_attention_spatial_blocks",
"(",
"query_antecedent",
",",
"kv_channels",
",",
"heads",
",",
"memory_h_dim",
"=",
"None",
",",
"memory_w_dim",
"=",
"None",
",",
"mask_right",
"=",
"False",
",",
"master_dtype",
"=",
"tf",
".",
"float32",
",",
... | Attention to the source position and a neighborhood to the left or right.
The sequence is divided into blocks of length block_size.
Attention for a given query position can only see memory positions
less than or equal to the query position, in the corresponding block
and the previous block.
Args:
query_... | [
"Attention",
"to",
"the",
"source",
"position",
"and",
"a",
"neighborhood",
"to",
"the",
"left",
"or",
"right",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L560-L642 |
241,607 | tensorflow/mesh | mesh_tensorflow/layers.py | multihead_attention_vars | def multihead_attention_vars(
mesh, heads, io_channels, kv_channels,
master_dtype, slice_dtype, activation_dtype):
"""Deprecated version of multihead_attention_params with combine=True."""
return multihead_attention_params(
mesh, heads, io_channels, kv_channels,
mtf.VariableDType(master_dtype, s... | python | def multihead_attention_vars(
mesh, heads, io_channels, kv_channels,
master_dtype, slice_dtype, activation_dtype):
return multihead_attention_params(
mesh, heads, io_channels, kv_channels,
mtf.VariableDType(master_dtype, slice_dtype, activation_dtype),
combine=True) | [
"def",
"multihead_attention_vars",
"(",
"mesh",
",",
"heads",
",",
"io_channels",
",",
"kv_channels",
",",
"master_dtype",
",",
"slice_dtype",
",",
"activation_dtype",
")",
":",
"return",
"multihead_attention_params",
"(",
"mesh",
",",
"heads",
",",
"io_channels",
... | Deprecated version of multihead_attention_params with combine=True. | [
"Deprecated",
"version",
"of",
"multihead_attention_params",
"with",
"combine",
"=",
"True",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L650-L657 |
241,608 | tensorflow/mesh | mesh_tensorflow/layers.py | multihead_attention_params | def multihead_attention_params(mesh, heads, io_channels, kv_channels,
variable_dtype, combine=False):
"""Create Parameters for Multihead Attention.
If the combine flag is set to True, then we create only one variable
which stacks together all of the parameters. Otherwise, we creat... | python | def multihead_attention_params(mesh, heads, io_channels, kv_channels,
variable_dtype, combine=False):
qkvo = mtf.Dimension("qkvo", 4)
qk_stddev = (io_channels.size ** -0.5) * (kv_channels.size ** -0.25)
v_stddev = io_channels.size ** -0.5
# TODO(noam): should be: o_stddev = (kv_ch... | [
"def",
"multihead_attention_params",
"(",
"mesh",
",",
"heads",
",",
"io_channels",
",",
"kv_channels",
",",
"variable_dtype",
",",
"combine",
"=",
"False",
")",
":",
"qkvo",
"=",
"mtf",
".",
"Dimension",
"(",
"\"qkvo\"",
",",
"4",
")",
"qk_stddev",
"=",
"... | Create Parameters for Multihead Attention.
If the combine flag is set to True, then we create only one variable
which stacks together all of the parameters. Otherwise, we create four
separate variables.
Args:
mesh: a Mesh
heads: a Dimension
io_channels: a Dimension
kv_channels: a Dimension
... | [
"Create",
"Parameters",
"for",
"Multihead",
"Attention",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L660-L707 |
241,609 | tensorflow/mesh | mesh_tensorflow/layers.py | attention_mask_ignore_padding | def attention_mask_ignore_padding(inputs, dtype=tf.float32):
"""Bias for encoder-decoder attention.
Args:
inputs: a mtf.Tensor with shape [..., length_dim]
dtype: a tf.dtype
Returns:
a mtf.Tensor with shape [..., memory_length_dim]
"""
inputs = rename_length_to_memory_length(inputs)
return mtf... | python | def attention_mask_ignore_padding(inputs, dtype=tf.float32):
inputs = rename_length_to_memory_length(inputs)
return mtf.cast(mtf.equal(inputs, 0), dtype) * -1e9 | [
"def",
"attention_mask_ignore_padding",
"(",
"inputs",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
":",
"inputs",
"=",
"rename_length_to_memory_length",
"(",
"inputs",
")",
"return",
"mtf",
".",
"cast",
"(",
"mtf",
".",
"equal",
"(",
"inputs",
",",
"0",
... | Bias for encoder-decoder attention.
Args:
inputs: a mtf.Tensor with shape [..., length_dim]
dtype: a tf.dtype
Returns:
a mtf.Tensor with shape [..., memory_length_dim] | [
"Bias",
"for",
"encoder",
"-",
"decoder",
"attention",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L918-L929 |
241,610 | tensorflow/mesh | mesh_tensorflow/layers.py | attention_mask_autoregressive | def attention_mask_autoregressive(query_pos, dtype=tf.float32):
"""Bias for self-attention where attention to the right is disallowed.
Args:
query_pos: a mtf.Tensor with shape [..., length_dim]
dtype: a tf.dtype
Returns:
a mtf.Tensor with shape [..., length_dim, memory_length_dim]
"""
memory_pos... | python | def attention_mask_autoregressive(query_pos, dtype=tf.float32):
memory_pos = rename_length_to_memory_length(query_pos)
return mtf.cast(mtf.less(query_pos, memory_pos), dtype) * -1e9 | [
"def",
"attention_mask_autoregressive",
"(",
"query_pos",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
":",
"memory_pos",
"=",
"rename_length_to_memory_length",
"(",
"query_pos",
")",
"return",
"mtf",
".",
"cast",
"(",
"mtf",
".",
"less",
"(",
"query_pos",
",... | Bias for self-attention where attention to the right is disallowed.
Args:
query_pos: a mtf.Tensor with shape [..., length_dim]
dtype: a tf.dtype
Returns:
a mtf.Tensor with shape [..., length_dim, memory_length_dim] | [
"Bias",
"for",
"self",
"-",
"attention",
"where",
"attention",
"to",
"the",
"right",
"is",
"disallowed",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L932-L943 |
241,611 | tensorflow/mesh | mesh_tensorflow/layers.py | attention_mask_same_segment | def attention_mask_same_segment(
query_segment, memory_segment=None, dtype=tf.float32):
"""Bias for attention where attention between segments is disallowed.
Args:
query_segment: a mtf.Tensor with shape [..., length_dim]
memory_segment: a mtf.Tensor with shape [..., memory_length_dim]
dtype: a tf.d... | python | def attention_mask_same_segment(
query_segment, memory_segment=None, dtype=tf.float32):
memory_segment = rename_length_to_memory_length(
memory_segment or query_segment)
return mtf.cast(mtf.not_equal(query_segment, memory_segment), dtype) * -1e9 | [
"def",
"attention_mask_same_segment",
"(",
"query_segment",
",",
"memory_segment",
"=",
"None",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
":",
"memory_segment",
"=",
"rename_length_to_memory_length",
"(",
"memory_segment",
"or",
"query_segment",
")",
"return",
"... | Bias for attention where attention between segments is disallowed.
Args:
query_segment: a mtf.Tensor with shape [..., length_dim]
memory_segment: a mtf.Tensor with shape [..., memory_length_dim]
dtype: a tf.dtype
Returns:
a mtf.Tensor with shape [..., length_dim, memory_length_dim] | [
"Bias",
"for",
"attention",
"where",
"attention",
"between",
"segments",
"is",
"disallowed",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L946-L960 |
241,612 | tensorflow/mesh | mesh_tensorflow/layers.py | multiplicative_jitter | def multiplicative_jitter(x, epsilon=1e-2):
"""Multiply values by a random number between 1-epsilon and 1+epsilon.
Makes models more resilient to rounding errors introduced by bfloat16.
This seems particularly important for logits.
Args:
x: a mtf.Tensor
epsilon: a floating point value
Returns:
... | python | def multiplicative_jitter(x, epsilon=1e-2):
if epsilon == 0:
return x
return x * mtf.random_uniform(
x.mesh, x.shape, minval=1.0 - epsilon, maxval=1.0+epsilon, dtype=x.dtype) | [
"def",
"multiplicative_jitter",
"(",
"x",
",",
"epsilon",
"=",
"1e-2",
")",
":",
"if",
"epsilon",
"==",
"0",
":",
"return",
"x",
"return",
"x",
"*",
"mtf",
".",
"random_uniform",
"(",
"x",
".",
"mesh",
",",
"x",
".",
"shape",
",",
"minval",
"=",
"1... | Multiply values by a random number between 1-epsilon and 1+epsilon.
Makes models more resilient to rounding errors introduced by bfloat16.
This seems particularly important for logits.
Args:
x: a mtf.Tensor
epsilon: a floating point value
Returns:
a mtf.Tensor with the same type and shape as x. | [
"Multiply",
"values",
"by",
"a",
"random",
"number",
"between",
"1",
"-",
"epsilon",
"and",
"1",
"+",
"epsilon",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L1029-L1045 |
241,613 | tensorflow/mesh | mesh_tensorflow/layers.py | multihead_self_attention_memory_compressed | def multihead_self_attention_memory_compressed(x,
mask_right,
compression_factor,
kv_channels,
heads,
... | python | def multihead_self_attention_memory_compressed(x,
mask_right,
compression_factor,
kv_channels,
heads,
... | [
"def",
"multihead_self_attention_memory_compressed",
"(",
"x",
",",
"mask_right",
",",
"compression_factor",
",",
"kv_channels",
",",
"heads",
",",
"dropout",
"=",
"0.0",
",",
"dropout_broadcast_dims",
"=",
"None",
",",
"master_dtype",
"=",
"tf",
".",
"float32",
"... | Memory-compressed self-attention.
The memory is first average-pooled (strided) to make it shorter by
a factor of compression_factor.
Args:
x: a mtf.Tensor with shape
[<batch_dims>, query_length, io_channels]
mask_right: a boolean
compression_factor: an integer
kv_channels: a mtf.Dimension ... | [
"Memory",
"-",
"compressed",
"self",
"-",
"attention",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L1048-L1113 |
241,614 | tensorflow/mesh | mesh_tensorflow/layers.py | compress_mean | def compress_mean(x, dim, compression_factor):
"""Compress by taking group means.
Args:
x: a Tensor
dim: a dimension in x.shape
compression_factor: an integer
Returns:
a Tensor
"""
dims = x.shape.dims
pos = dims.index(dim)
compressed_dim = mtf.Dimension(dim.name, dim.size // compression_... | python | def compress_mean(x, dim, compression_factor):
dims = x.shape.dims
pos = dims.index(dim)
compressed_dim = mtf.Dimension(dim.name, dim.size // compression_factor)
compression_factor_dim = mtf.Dimension(
"compression_factor", compression_factor)
new_shape = (
dims[:pos] + [compressed_dim, compressio... | [
"def",
"compress_mean",
"(",
"x",
",",
"dim",
",",
"compression_factor",
")",
":",
"dims",
"=",
"x",
".",
"shape",
".",
"dims",
"pos",
"=",
"dims",
".",
"index",
"(",
"dim",
")",
"compressed_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"dim",
".",
"name"... | Compress by taking group means.
Args:
x: a Tensor
dim: a dimension in x.shape
compression_factor: an integer
Returns:
a Tensor | [
"Compress",
"by",
"taking",
"group",
"means",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L1116-L1136 |
241,615 | tensorflow/mesh | mesh_tensorflow/layers.py | embedding | def embedding(indices, vocab_dim, output_dim, variable_dtype, name="embedding"):
"""Embedding layer."""
weights = embedding_weights(
indices.mesh, vocab_dim, output_dim, variable_dtype, name)
return mtf.gather(weights, indices, vocab_dim) | python | def embedding(indices, vocab_dim, output_dim, variable_dtype, name="embedding"):
weights = embedding_weights(
indices.mesh, vocab_dim, output_dim, variable_dtype, name)
return mtf.gather(weights, indices, vocab_dim) | [
"def",
"embedding",
"(",
"indices",
",",
"vocab_dim",
",",
"output_dim",
",",
"variable_dtype",
",",
"name",
"=",
"\"embedding\"",
")",
":",
"weights",
"=",
"embedding_weights",
"(",
"indices",
".",
"mesh",
",",
"vocab_dim",
",",
"output_dim",
",",
"variable_d... | Embedding layer. | [
"Embedding",
"layer",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L1146-L1150 |
241,616 | 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 describe... | python | 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("he... | [
"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",
"el... | 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 ... | [
"Attention",
"Parameters",
"for",
"Transformer",
"Layers",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/transformer_layers.py#L62-L116 |
241,617 | 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 ... | python | 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:
r... | [
"def",
"get_metric_fns",
"(",
"metric_names",
",",
"labels",
",",
"outputs",
")",
":",
"metric_fns",
"=",
"{",
"}",
"for",
"metric_name",
"in",
"metric_names",
":",
"metric_fn_name",
"=",
"metric_name",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
... | 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 i... | [
"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 |
241,618 | 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 == 'NAIV... | python | 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 '
'... | [
"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",
... | 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 |
241,619 | 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:... | python | 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 ... | [
"def",
"_minimize_peak_memory_list",
"(",
"graph",
")",
":",
"schedule",
"=",
"[",
"]",
"bytes_freed",
"=",
"{",
"}",
"# {operation_name: bytes freed}",
"users_of",
"=",
"collections",
".",
"defaultdict",
"(",
"set",
")",
"# {tensor_name: set(operation_name)}",
"in_de... | 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.GraphInterf... | [
"Computes",
"schedule",
"according",
"to",
"the",
"greedy",
"list",
"heuristic",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/scheduler.py#L67-L154 |
241,620 | 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 c... | python | 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_ru... | [
"def",
"layout",
"(",
"mtf_graph",
",",
"mesh_shape",
",",
"mtf_outputs",
"=",
"(",
")",
")",
":",
"mesh_shape",
"=",
"mtf",
".",
"convert_to_shape",
"(",
"mesh_shape",
")",
"estimator",
"=",
"memory_estimator",
".",
"MemoryEstimator",
"(",
"mtf_graph",
",",
... | 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 |
241,621 | 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
variab... | python | 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) | [
"def",
"apply_grads",
"(",
"self",
",",
"grads",
",",
"variables",
")",
":",
"ops",
"=",
"[",
"]",
"for",
"grad",
",",
"var",
"in",
"zip",
"(",
"grads",
",",
"variables",
")",
":",
"ops",
".",
"extend",
"(",
"self",
".",
"apply_grad",
"(",
"grad",
... | 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 li... | [
"Apply",
"gradients",
"to",
"variables",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/optimize.py#L39-L57 |
241,622 | 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... | python | 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] | [
"def",
"_factored_dims",
"(",
"self",
",",
"shape",
")",
":",
"if",
"not",
"self",
".",
"_factored",
"or",
"shape",
".",
"ndims",
"<",
"2",
":",
"return",
"None",
"sorted_dims",
"=",
"sorted",
"(",
"shape",
".",
"dims",
",",
"key",
"=",
"lambda",
"d"... | 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... | [
"Should",
"we",
"use",
"a",
"factored",
"second",
"moment",
"estimator",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/optimize.py#L139-L158 |
241,623 | 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 b... | python | 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)) | [
"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",
... | 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 |
241,624 | 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() ... | python | 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):
... | [
"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",
".",... | 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 |
241,625 | 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 ... | python | 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] = fracti... | [
"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"... | 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 di... | [
"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 |
241,626 | 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_... | python | 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 | [
"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"... | 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 |
241,627 | 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
... | python | 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 + dis... | [
"def",
"allconcat_ring",
"(",
"xs",
",",
"devices",
",",
"concat_axis",
")",
":",
"n",
"=",
"len",
"(",
"xs",
")",
"if",
"n",
"==",
"1",
":",
"return",
"xs",
"# [target, source]",
"parts",
"=",
"[",
"[",
"xs",
"[",
"target",
"]",
"if",
"target",
"=... | 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 |
241,628 | 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("PlacementMeshIm... | python | 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, **kwa... | [
"def",
"Print",
"(",
"self",
",",
"x",
",",
"data",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=invalid-name",
"tf",
".",
"logging",
".",
"info",
"(",
"\"PlacementMeshImpl::Print\"",
")",
"new_slices",
"=",
"x",
".",
"tensor_list",
... | 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 |
241,629 | 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 concate... | python | 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)) | [
"def",
"alltoall",
"(",
"self",
",",
"x",
",",
"mesh_axis",
",",
"split_axis",
",",
"concat_axis",
")",
":",
"return",
"self",
".",
"_collective_with_groups",
"(",
"x",
",",
"[",
"mesh_axis",
"]",
",",
"functools",
".",
"partial",
"(",
"alltoall_ring",
","... | 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 |
241,630 | 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):
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 |
241,631 | 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 dim... | 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):
logits = mtf.einsum([q, k], reduced_dims=[key_dim])
... | [
"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... | [
"Dot",
"-",
"product",
"attention",
"-",
"doesn",
"t",
"use",
"positional",
"dimensions",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/attention.py#L27-L76 |
241,632 | 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 "he... | python | 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_... | [
"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_... | 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 |
241,633 | 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,
... | python | def local_attention_1d(q,
k,
v,
length_dim,
key_dim,
value_dim,
autoregressive=True,
length_dim_num_splits=1,
radius=128,
... | [
"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",
",",
"att... | 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 leng... | [
"Attention",
"to",
"the",
"a",
"neighborood",
"around",
"the",
"source",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/attention.py#L289-L377 |
241,634 | 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... | python | 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 | [
"def",
"compute_q",
"(",
"self",
",",
"query_antecedent",
")",
":",
"ret",
"=",
"mtf",
".",
"einsum",
"(",
"[",
"query_antecedent",
",",
"self",
".",
"wq",
"]",
",",
"reduced_dims",
"=",
"[",
"self",
".",
"query_input_dim",
"]",
")",
"if",
"self",
".",... | 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 |
241,635 | 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("... | python | 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.... | [
"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",
",",
"sel... | 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 |
241,636 | 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 ValueErr... | python | 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.... | [
"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",
",",
"sel... | 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 |
241,637 | 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 ... | python | 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(... | [
"def",
"compute_output",
"(",
"self",
",",
"o",
",",
"output_shape",
"=",
"None",
")",
":",
"if",
"self",
".",
"combine_dims",
":",
"o",
"=",
"mtf",
".",
"transpose",
"(",
"o",
",",
"o",
".",
"shape",
"-",
"self",
".",
"o_dims",
"+",
"self",
".",
... | 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 |
241,638 | 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, ... | python | 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] | [
"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 |
241,639 | 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_layer... | python | 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.Self... | [
"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",... | 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 |
241,640 | 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.... | python | 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, ... | [
"def",
"toy_model",
"(",
"features",
",",
"mesh",
")",
":",
"batch_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"'batch'",
",",
"FLAGS",
".",
"batch_size",
")",
"io_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"'io'",
",",
"FLAGS",
".",
"io_size",
")",
"master... | 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 |
241,641 | 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.RunConf... | python | 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_re... | [
"def",
"run_toy_model_tpu",
"(",
")",
":",
"tpu_cluster_resolver",
"=",
"tf",
".",
"contrib",
".",
"cluster_resolver",
".",
"TPUClusterResolver",
"(",
"FLAGS",
".",
"tpu",
",",
"zone",
"=",
"FLAGS",
".",
"tpu_zone",
",",
"project",
"=",
"FLAGS",
".",
"gcp_pr... | 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 |
241,642 | 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.Dimens... | python | 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",... | [
"def",
"mnist_model",
"(",
"image",
",",
"labels",
",",
"mesh",
")",
":",
"batch_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"\"batch\"",
",",
"FLAGS",
".",
"batch_size",
")",
"row_blocks_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"\"row_blocks\"",
",",
"4",
... | 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 |
241,643 | 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, l... | python | 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
# randomn... | [
"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... | 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 |
241,644 | 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.resha... | python | 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)
... | [
"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",
".",
"shap... | Call the layer. | [
"Call",
"the",
"layer",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/moe.py#L123-L145 |
241,645 | 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 ... | python | 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[obje... | [
"def",
"print_solution",
"(",
"model",
",",
"solver",
")",
":",
"model_proto",
"=",
"model",
".",
"Proto",
"(",
")",
"response_proto",
"=",
"solver",
".",
"ResponseProto",
"(",
")",
"variables_in_objective_map",
"=",
"{",
"}",
"maximization",
"=",
"False",
"... | 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 pro... | [
"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 |
241,646 | 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.
"""
assign... | python | 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... | [
"def",
"_local_var_name",
"(",
"splittable_dimensions",
",",
"assignment",
")",
":",
"assignment_string",
"=",
"[",
"]",
"for",
"splittable",
"in",
"sorted",
"(",
"splittable_dimensions",
")",
":",
"if",
"splittable",
"in",
"assignment",
":",
"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 |
241,647 | 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:... | python | 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,
... | [
"def",
"_generate_assignments",
"(",
"splittable_dimensions",
",",
"mesh_dimension_to_size",
")",
":",
"assignments",
"=",
"[",
"]",
"for",
"assignment_size",
"in",
"six",
".",
"moves",
".",
"xrange",
"(",
"1",
"+",
"min",
"(",
"len",
"(",
"splittable_dimensions... | 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
... | [
"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 |
241,648 | 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 = {}
# ... | python | 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.... | [
"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 {strin... | 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 |
241,649 | 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 (
... | python | 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_... | [
"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_... | 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 |
241,650 | 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... | python | 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_nam... | [
"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_dime... | 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 |
241,651 | 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()).
"... | python | 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_content... | [
"def",
"_get_memory_contents",
"(",
"self",
")",
":",
"if",
"self",
".",
"_memory_contents",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_memory_contents",
"schedule",
"=",
"scheduler",
".",
"minimize_peak_memory",
"(",
"self",
".",
"_graph",
",",
"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()). | [
"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 |
241,652 | 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:
... | python | 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.")
... | [
"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",
... | 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 fi... | [
"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 |
241,653 | 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... | python | 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]... | [
"def",
"evaluate_layout",
"(",
"self",
",",
"layout",
")",
":",
"layout_dict",
"=",
"{",
"}",
"if",
"layout",
":",
"for",
"pair",
"in",
"layout",
".",
"split",
"(",
"\";\"",
")",
":",
"mtf_dimension_name",
",",
"mesh_dimension_name",
"=",
"pair",
".",
"s... | 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 |
241,654 | 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... | python | 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... | [
"def",
"device_function",
"(",
"self",
",",
"var",
")",
":",
"if",
"var",
".",
"type",
"not",
"in",
"(",
"'Variable'",
",",
"'VariableV2'",
",",
"'VarHandleOp'",
")",
":",
"tf",
".",
"logging",
".",
"debug",
"(",
"'Place {} on last device: {}.'",
".",
"for... | 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 |
241,655 | 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 logi... | python | 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... | [
"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",
"=",
"initi... | 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 m... | [
"Greedy",
"decoding",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/beam_search.py#L577-L642 |
241,656 | 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 in... | python | 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
)
... | [
"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",
... | 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 exa... | [
"Create",
"a",
"tf",
".",
"data",
".",
"Dataset",
"which",
"emits",
"training",
"batches",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L98-L150 |
241,657 | 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: vo... | python | 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) | [
"def",
"encode_dataset",
"(",
"dataset",
",",
"vocabulary",
")",
":",
"def",
"encode",
"(",
"features",
")",
":",
"return",
"{",
"k",
":",
"vocabulary",
".",
"encode_tf",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"features",
".",
"items",
"(",
")",
... | 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 |
241,658 | 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,
... | python | def packed_parallel_tsv_dataset(filenames=gin.REQUIRED,
dataset_split=gin.REQUIRED,
batch_size=gin.REQUIRED,
sequence_length=gin.REQUIRED,
vocabulary=gin.REQUIRED,
... | [
"def",
"packed_parallel_tsv_dataset",
"(",
"filenames",
"=",
"gin",
".",
"REQUIRED",
",",
"dataset_split",
"=",
"gin",
".",
"REQUIRED",
",",
"batch_size",
"=",
"gin",
".",
"REQUIRED",
",",
"sequence_length",
"=",
"gin",
".",
"REQUIRED",
",",
"vocabulary",
"=",... | 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 |
241,659 | 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 boo... | python | 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) | [
"def",
"supervised_to_dict",
"(",
"dataset",
",",
"text2self",
")",
":",
"def",
"my_fn",
"(",
"inputs",
",",
"targets",
")",
":",
"if",
"text2self",
":",
"return",
"{",
"\"targets\"",
":",
"targets",
"}",
"else",
":",
"return",
"{",
"\"inputs\"",
":",
"i... | 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 |
241,660 | 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.t... | python | 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) | [
"def",
"encode_all_features",
"(",
"dataset",
",",
"vocabulary",
")",
":",
"def",
"my_fn",
"(",
"features",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"features",
".",
"items",
"(",
")",
":",
"v",
"=",
"vocabulary",
".",
"encode_tf",... | 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 |
241,661 | 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.... | python | def pretokenized_tfrecord_dataset(filenames,
text2self,
eos_included,
repeat,
batch_size,
sequence_length):
dataset = tf.data.TFRecordDataset(filena... | [
"def",
"pretokenized_tfrecord_dataset",
"(",
"filenames",
",",
"text2self",
",",
"eos_included",
",",
"repeat",
",",
"batch_size",
",",
"sequence_length",
")",
":",
"dataset",
"=",
"tf",
".",
"data",
".",
"TFRecordDataset",
"(",
"filenames",
",",
"buffer_size",
... | 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 targ... | [
"Reads",
"tensor2tensor",
"-",
"style",
"data",
"files",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L330-L376 |
241,662 | 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,
... | 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,
... | [
"def",
"pretokenized_t2t_dataset",
"(",
"dataset_name",
"=",
"gin",
".",
"REQUIRED",
",",
"text2self",
"=",
"False",
",",
"data_dir",
"=",
"gin",
".",
"REQUIRED",
",",
"dataset_split",
"=",
"\"train\"",
",",
"batch_size",
"=",
"gin",
".",
"REQUIRED",
",",
"s... | 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... | [
"Loads",
"the",
"Tensor2tensor",
"dataset",
"specified",
"by",
"dataset_name",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L380-L417 |
241,663 | 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 effic... | python | 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 s... | [
"def",
"pack_dataset",
"(",
"dataset",
",",
"length",
",",
"keys",
"=",
"None",
",",
"use_custom_ops",
"=",
"False",
")",
":",
"shapes",
"=",
"dataset",
".",
"output_shapes",
"if",
"keys",
"is",
"None",
":",
"keys",
"=",
"shapes",
".",
"keys",
"(",
")"... | 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 e... | [
"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 |
241,664 | 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):
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 |
241,665 | 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.na... | python | 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, ... | [
"def",
"convert_to_dimension",
"(",
"d",
")",
":",
"if",
"d",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"d",
",",
"Dimension",
")",
":",
"if",
"not",
"isinstance",
"(",
"d",
".",
"name",
",",
"str",
")",
"or",
"not",
"isinstance",... | 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 |
241,666 | 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_lis... | python | 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) | [
"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_o... | 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 |
241,667 | 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):
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",
"Lay... | 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 |
241,668 | 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):
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",
"(",
")",
... | 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 |
241,669 | 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.
s... | python | 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_sha... | [
"def",
"slicewise",
"(",
"tf_fn",
",",
"xs",
",",
"output_shape",
"=",
"None",
",",
"output_dtype",
"=",
"None",
",",
"splittable_dims",
"=",
"None",
",",
"grad_function",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"multiple_outputs",
"=",
"isinstanc... | 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
... | [
"Slice",
"-",
"wise",
"call",
"to",
"any",
"tensorflow",
"function",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1568-L1605 |
241,670 | 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 | 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") | [
"def",
"cwise",
"(",
"tf_fn",
",",
"xs",
",",
"output_dtype",
"=",
"None",
",",
"grad_function",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"return",
"slicewise",
"(",
"tf_fn",
",",
"xs",
",",
"output_dtype",
"=",
"output_dtype",
",",
"splittable_d... | 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 |
241,671 | 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
"""
... | python | 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(
... | [
"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 ... | 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 |
241,672 | 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="mini... | python | 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... | [
"def",
"minimum",
"(",
"x1",
",",
"x2",
",",
"output_shape",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"output_shape",
"=",
"convert_to_shape",
"(",
"output_shape",
")",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"default_name",
"=",
"\"mi... | 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 |
241,673 | 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... | python | def split(x, split_dim, num_or_size_splits, name=None):
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 |
241,674 | 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:
... | python | def stack(xs, dim_name, axis=0, name=None):
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 |
241,675 | 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.shap... | python | 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, dty... | [
"def",
"cumsum",
"(",
"x",
",",
"dim",
",",
"exclusive",
"=",
"False",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"cumsum\"",
")",
":",
"new_name",
"=",
"\"tmp_dim_cumsum\"",
"new_dim",
"=",
"Dimension",
"(",
"new_name",
",",
"dim",
".",
"size... | 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 |
241,676 | 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 option... | python | def shift(x, offset, dim, wrap, name=None):
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 ... | [
"Shift",
"operation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L2755-L2770 |
241,677 | 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 strin... | python | 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] | [
"def",
"import_laid_out_tensor",
"(",
"mesh",
",",
"laid_out_tensor",
",",
"shape",
",",
"name",
"=",
"None",
")",
":",
"return",
"ImportLaidOutTensorOperation",
"(",
"mesh",
",",
"laid_out_tensor",
",",
"convert_to_shape",
"(",
"shape",
")",
",",
"name",
"=",
... | 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 |
241,678 | 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 (u... | python | 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(d... | [
"def",
"get_variable",
"(",
"mesh",
",",
"name",
",",
"shape",
",",
"dtype",
"=",
"tf",
".",
"float32",
",",
"master_dtype",
"=",
"None",
",",
"slice_dtype",
"=",
"None",
",",
"activation_dtype",
"=",
"None",
",",
"initializer",
"=",
"None",
",",
"traina... | 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... | [
"Create",
"a",
"new",
"variable",
"or",
"retrieve",
"an",
"already",
"-",
"created",
"one",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3210-L3253 |
241,679 | 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:
Value... | python | 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) | [
"def",
"assign",
"(",
"var",
",",
"new_val",
",",
"assign_fn",
"=",
"assign_slice",
")",
":",
"if",
"isinstance",
"(",
"var",
",",
"Tensor",
")",
":",
"var",
"=",
"var",
".",
"operation",
"if",
"not",
"isinstance",
"(",
"var",
",",
"Variable",
")",
"... | 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 no... | [
"Assign",
"a",
"new",
"value",
"to",
"a",
"variable",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3304-L3321 |
241,680 | 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, **kwa... | python | def Print(x, data, message, **kwargs): # pylint: disable=invalid-name
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 |
241,681 | 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):
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 |
241,682 | 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:
t... | python | 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(
"tenso... | [
"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_o... | 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 o... | [
"Replace",
"dimensions",
"in",
"a",
"Tensor",
"or",
"Shape",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3590-L3634 |
241,683 | 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 mu... | python | 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... | [
"def",
"einsum",
"(",
"xs",
",",
"output_shape",
"=",
"None",
",",
"reduced_dims",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"output_shape",
"=",
"convert_to_shape",
"(",
"output_shape",
")",
"input_dim_count",
"=",
"collections",
".",
"defaultdict",
... | 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]
... | [
"Einstein",
"summation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3637-L3700 |
241,684 | 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" % (reduce... | python | 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 - redu... | [
"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",
... | 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 |
241,685 | 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, re... | python | 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_ma... | [
"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... | 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 |
241,686 | 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.
n... | python | 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... | [
"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_... | 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 dty... | [
"Like",
"tf",
".",
"top_k",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3902-L3932 |
241,687 | 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 Scal... | python | 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, outpu... | [
"def",
"add",
"(",
"x1",
",",
"x2",
",",
"output_shape",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"output_shape",
"=",
"convert_to_shape",
"(",
"output_shape",
")",
"if",
"not",
"isinstance",
"(",
"x2",
",",
"Tensor",
")",
":",
"return",
"Scala... | 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 |
241,688 | 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 S... | python | 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... | [
"def",
"sub",
"(",
"x1",
",",
"x2",
",",
"output_shape",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"output_shape",
"=",
"convert_to_shape",
"(",
"output_shape",
")",
"if",
"not",
"isinstance",
"(",
"x2",
",",
"Tensor",
")",
":",
"return",
"Scala... | 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 |
241,689 | 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[... | python | 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_sh... | [
"def",
"multiply",
"(",
"x1",
",",
"x2",
",",
"output_shape",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"x2",
",",
"Tensor",
")",
":",
"return",
"ScalarMultiplyOperation",
"(",
"x1",
",",
"x2",
")",
".",
"output... | 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 |
241,690 | 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 ... | python | 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, recip... | [
"def",
"divide",
"(",
"x1",
",",
"x2",
",",
"output_shape",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"output_shape",
"=",
"convert_to_shape",
"(",
"output_shape",
")",
"if",
"not",
"isinstance",
"(",
"x2",
",",
"Tensor",
")",
":",
"return",
"Sc... | 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 |
241,691 | 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.dty... | python | 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] | [
"def",
"one_hot",
"(",
"indices",
",",
"output_dim",
",",
"on_value",
"=",
"1.0",
",",
"off_value",
"=",
"0.0",
",",
"dtype",
"=",
"tf",
".",
"float32",
",",
"name",
"=",
"None",
")",
":",
"return",
"OneHotOperation",
"(",
"indices",
",",
"output_dim",
... | 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... | [
"One",
"hot",
"operation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4087-L4107 |
241,692 | 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).output... | python | 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:
... | [
"def",
"gradients",
"(",
"ys",
",",
"xs",
",",
"grad_ys",
"=",
"None",
")",
":",
"graph",
"=",
"ys",
"[",
"0",
"]",
".",
"graph",
"if",
"not",
"grad_ys",
":",
"grad_ys",
"=",
"[",
"Constant",
"(",
"y",
".",
"mesh",
",",
"1.0",
",",
"y",
".",
... | 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 |
241,693 | 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 sup... | python | 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)... | [
"def",
"_infer_binary_broadcast_shape",
"(",
"shape1",
",",
"shape2",
",",
"given_output_shape",
"=",
"None",
")",
":",
"shape1",
"=",
"convert_to_shape",
"(",
"shape1",
")",
"shape2",
"=",
"convert_to_shape",
"(",
"shape2",
")",
"given_output_shape",
"=",
"conver... | 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 d... | [
"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 |
241,694 | 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_sha... | python | 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 enumerat... | [
"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",
":",
"r... | 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 |
241,695 | 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 + ... | python | 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 n... | [
"def",
"_einsum_equation",
"(",
"input_shapes",
",",
"output_shape",
")",
":",
"ret",
"=",
"[",
"]",
"next_letter",
"=",
"ord",
"(",
"\"a\"",
")",
"dim_to_letter",
"=",
"{",
"}",
"for",
"shape_num",
",",
"shape",
"in",
"enumerate",
"(",
"input_shapes",
"+"... | 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 |
241,696 | 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):
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",
"... | 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 |
241,697 | 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 inpu... | python | 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= ... | [
"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",
"(",
"... | 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 |
241,698 | 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.app... | python | 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] | [
"def",
"pnum_to_processor_coordinates",
"(",
"mesh_shape",
",",
"pnum",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"dimsize",
"in",
"mesh_shape",
".",
"to_integer_list",
"[",
":",
":",
"-",
"1",
"]",
":",
"ret",
".",
"append",
"(",
"pnum",
"%",
"dimsize",
... | 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 |
241,699 | 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.... | python | 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 | [
"def",
"processor_coordinates_to_pnum",
"(",
"mesh_shape",
",",
"coord",
")",
":",
"ret",
"=",
"0",
"multiplier",
"=",
"1",
"for",
"c",
",",
"d",
"in",
"zip",
"(",
"coord",
"[",
":",
":",
"-",
"1",
"]",
",",
"mesh_shape",
".",
"to_integer_list",
"[",
... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.