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. """ 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( x.mesh, "layer_norm_bias", mtf.Shape([dim]), initializer=tf.zeros_initializer(), activation_dtype=x.dtype) reduced_shape = x.shape - dim mean = mtf.reduce_mean(x, output_shape=reduced_shape) variance = mtf.reduce_mean(mtf.square(x - mean), output_shape=reduced_shape) norm_x = (x - mean) * mtf.rsqrt(variance + epsilon) return norm_x * scale + bias
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( x.mesh, "layer_norm_bias", mtf.Shape([dim]), initializer=tf.zeros_initializer(), activation_dtype=x.dtype) reduced_shape = x.shape - dim mean = mtf.reduce_mean(x, output_shape=reduced_shape) variance = mtf.reduce_mean(mtf.square(x - mean), output_shape=reduced_shape) norm_x = (x - mean) * mtf.rsqrt(variance + epsilon) return norm_x * scale + bias
[ "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, which can cause unacceptable roundoff errors in bfloat16. - To encourage the logits to be normalized log-probabilities. Args: logits: a mtf.Tensor whose shape contains vocab_dim targets: a mtf.Tensor with the same shape as logits vocab_dim: a mtf.Dimension z_loss: a float Returns: a mtf.Tensor whose shape is equal to logits.shape - vocab_dim Raises: ValueError: if the shapes do not match. """ 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("vocab_dim must be in logits.shape.dims") log_z = mtf.reduce_logsumexp(logits, vocab_dim) log_softmax = logits - log_z loss = mtf.negative( mtf.reduce_sum(log_softmax * targets, reduced_dim=vocab_dim)) if z_loss != 0: loss += z_loss * mtf.square(log_z) return loss
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("vocab_dim must be in logits.shape.dims") log_z = mtf.reduce_logsumexp(logits, vocab_dim) log_softmax = logits - log_z loss = mtf.negative( mtf.reduce_sum(log_softmax * targets, reduced_dim=vocab_dim)) if z_loss != 0: loss += z_loss * mtf.square(log_z) return loss
[ "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 the logits to be normalized log-probabilities. Args: logits: a mtf.Tensor whose shape contains vocab_dim targets: a mtf.Tensor with the same shape as logits vocab_dim: a mtf.Dimension z_loss: a float Returns: a mtf.Tensor whose shape is equal to logits.shape - vocab_dim Raises: ValueError: if the shapes do not match.
[ "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.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(x)))
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(x)))
[ "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. 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 master_dtype: a tf.dtype slice_dtype: a tf.dtype name: an optional string Returns: a mtf.Tensor with the same shape as x. """ with tf.variable_scope(name, default_name="dense_relu_dense"): io_channels = x.shape.dims[-1] h = dense(x, hidden_channels, use_bias=False, activation=mtf.relu, master_dtype=master_dtype, slice_dtype=slice_dtype, name="wi") if dropout != 0.0: h = mtf.dropout(h, 1.0 - dropout, noise_shape=h.shape - dropout_broadcast_dims) return dense(h, io_channels, use_bias=False, activation=None, master_dtype=master_dtype, slice_dtype=slice_dtype, name="wo")
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_channels = x.shape.dims[-1] h = dense(x, hidden_channels, use_bias=False, activation=mtf.relu, master_dtype=master_dtype, slice_dtype=slice_dtype, name="wi") if dropout != 0.0: h = mtf.dropout(h, 1.0 - dropout, noise_shape=h.shape - dropout_broadcast_dims) return dense(h, io_channels, use_bias=False, activation=None, master_dtype=master_dtype, slice_dtype=slice_dtype, name="wo")
[ "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 master_dtype: a tf.dtype slice_dtype: a tf.dtype name: an optional string Returns: a mtf.Tensor with the same shape as x.
[ "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) else: k = mtf.halo_exchange(k, num_w_blocks, w_dim, w_dim.size) v = mtf.halo_exchange(v, num_w_blocks, w_dim, w_dim.size) else: if mask_right: k = mtf.pad(k, [w_dim, None], w_dim.name) v = mtf.pad(v, [w_dim, None], w_dim.name) else: k = mtf.pad(k, [w_dim, w_dim], w_dim.name) v = mtf.pad(v, [w_dim, w_dim], w_dim.name) return k, v
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_dim.size) v = mtf.halo_exchange(v, num_w_blocks, w_dim, w_dim.size) else: if mask_right: k = mtf.pad(k, [w_dim, None], w_dim.name) v = mtf.pad(v, [w_dim, None], w_dim.name) else: k = mtf.pad(k, [w_dim, w_dim], w_dim.name) v = mtf.pad(v, [w_dim, w_dim], w_dim.name) return k, v
[ "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)]: # shape of k is [num_h_blocks, num_w_blocks, h_dim, w_dim, kv_channels] if halo_size > 0: if blocks_dim is not None: if mask_right: k = mtf.left_halo_exchange(k, blocks_dim, block_size_dim, halo_size) v = mtf.left_halo_exchange(v, blocks_dim, block_size_dim, halo_size) else: k = mtf.halo_exchange(k, blocks_dim, block_size_dim, halo_size) v = mtf.halo_exchange(v, blocks_dim, block_size_dim, halo_size) else: if mask_right: k = mtf.pad(k, [halo_size, None], block_size_dim.name) v = mtf.pad(v, [halo_size, None], block_size_dim.name) else: k = mtf.pad(k, [halo_size, halo_size], block_size_dim.name) v = mtf.pad(v, [halo_size, halo_size], block_size_dim.name) return k, v
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_channels] if halo_size > 0: if blocks_dim is not None: if mask_right: k = mtf.left_halo_exchange(k, blocks_dim, block_size_dim, halo_size) v = mtf.left_halo_exchange(v, blocks_dim, block_size_dim, halo_size) else: k = mtf.halo_exchange(k, blocks_dim, block_size_dim, halo_size) v = mtf.halo_exchange(v, blocks_dim, block_size_dim, halo_size) else: if mask_right: k = mtf.pad(k, [halo_size, None], block_size_dim.name) v = mtf.pad(v, [halo_size, None], block_size_dim.name) else: k = mtf.pad(k, [halo_size, halo_size], block_size_dim.name) v = mtf.pad(v, [halo_size, halo_size], block_size_dim.name) return k, v
[ "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, mask_right=False, master_dtype=tf.float32, slice_dtype=tf.float32, name=None): """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_antecedent: a mtf.Tensor with shape [batch, num_h_blocks, num_w_blocks, h_dim, w_dim, io_channels] must have the same size as query_length, but a different name. kv_channels: a mtf.Dimension (the size of the key and value vectors) heads: a mtf.Dimension (the number of heads) memory_h_dim: mtf Dimension, for the memory height block. memory_w_dim: mtf Dimension, for the memory width block. mask_right: bool, flag specifying whether we mask out attention to the right for the decoder. master_dtype: a tf.dtype slice_dtype: a tf.dtype name: an optional string. Returns: a Tensor of shape [batch, num_h_blocks, num_w_blocks, h_dim, w_dim, io_channels] Raises: ValueError: if channels or depth don't match. """ with tf.variable_scope( name, default_name="multihead_attention", values=[query_antecedent]): h_dim, w_dim, io_channels = query_antecedent.shape.dims[-3:] batch, num_h_blocks, num_w_blocks = query_antecedent.shape.dims[:3] wq, wk, wv, wo = multihead_attention_vars( query_antecedent.mesh, heads, io_channels, kv_channels, master_dtype, slice_dtype, query_antecedent.dtype) # Rename dimensions for the memory height and width. memory_antecedent = mtf.rename_dimension(query_antecedent, h_dim.name, "memory_" + h_dim.name) memory_antecedent = mtf.rename_dimension(memory_antecedent, w_dim.name, "memory_" + w_dim.name) memory_h_dim, memory_w_dim = memory_antecedent.shape.dims[-3:-1] # Call einsum over the query and memory to get query q, keys k and values v. q = mtf.einsum([query_antecedent, wq], mtf.Shape([ batch, heads, num_h_blocks, num_w_blocks, h_dim, w_dim, kv_channels ])) k = mtf.einsum([memory_antecedent, wk], mtf.Shape([batch, heads, num_h_blocks, num_w_blocks, memory_h_dim, memory_w_dim, kv_channels])) v = mtf.einsum([memory_antecedent, wv], mtf.Shape([batch, heads, num_h_blocks, num_w_blocks, memory_h_dim, memory_w_dim, kv_channels])) # Halo exchange for memory blocks. k, v = local_2d_halo_exchange(k, v, num_h_blocks, memory_h_dim, num_w_blocks, memory_w_dim, mask_right) # Calculate the causal mask to avoid peeking into the future. We compute # this once and reuse it for all blocks since the block_size is known. mask = None if mask_right: mask = attention_bias_local_2d_block(query_antecedent.mesh, h_dim, w_dim, memory_h_dim, memory_w_dim) output = dot_product_attention(q, k, v, mask=mask) return mtf.einsum( [output, wo], mtf.Shape( [batch, num_h_blocks, num_w_blocks, h_dim, w_dim, io_channels]))
python
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, slice_dtype=tf.float32, name=None): with tf.variable_scope( name, default_name="multihead_attention", values=[query_antecedent]): h_dim, w_dim, io_channels = query_antecedent.shape.dims[-3:] batch, num_h_blocks, num_w_blocks = query_antecedent.shape.dims[:3] wq, wk, wv, wo = multihead_attention_vars( query_antecedent.mesh, heads, io_channels, kv_channels, master_dtype, slice_dtype, query_antecedent.dtype) # Rename dimensions for the memory height and width. memory_antecedent = mtf.rename_dimension(query_antecedent, h_dim.name, "memory_" + h_dim.name) memory_antecedent = mtf.rename_dimension(memory_antecedent, w_dim.name, "memory_" + w_dim.name) memory_h_dim, memory_w_dim = memory_antecedent.shape.dims[-3:-1] # Call einsum over the query and memory to get query q, keys k and values v. q = mtf.einsum([query_antecedent, wq], mtf.Shape([ batch, heads, num_h_blocks, num_w_blocks, h_dim, w_dim, kv_channels ])) k = mtf.einsum([memory_antecedent, wk], mtf.Shape([batch, heads, num_h_blocks, num_w_blocks, memory_h_dim, memory_w_dim, kv_channels])) v = mtf.einsum([memory_antecedent, wv], mtf.Shape([batch, heads, num_h_blocks, num_w_blocks, memory_h_dim, memory_w_dim, kv_channels])) # Halo exchange for memory blocks. k, v = local_2d_halo_exchange(k, v, num_h_blocks, memory_h_dim, num_w_blocks, memory_w_dim, mask_right) # Calculate the causal mask to avoid peeking into the future. We compute # this once and reuse it for all blocks since the block_size is known. mask = None if mask_right: mask = attention_bias_local_2d_block(query_antecedent.mesh, h_dim, w_dim, memory_h_dim, memory_w_dim) output = dot_product_attention(q, k, v, mask=mask) return mtf.einsum( [output, wo], mtf.Shape( [batch, num_h_blocks, num_w_blocks, h_dim, w_dim, io_channels]))
[ "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_antecedent: a mtf.Tensor with shape [batch, num_h_blocks, num_w_blocks, h_dim, w_dim, io_channels] must have the same size as query_length, but a different name. kv_channels: a mtf.Dimension (the size of the key and value vectors) heads: a mtf.Dimension (the number of heads) memory_h_dim: mtf Dimension, for the memory height block. memory_w_dim: mtf Dimension, for the memory width block. mask_right: bool, flag specifying whether we mask out attention to the right for the decoder. master_dtype: a tf.dtype slice_dtype: a tf.dtype name: an optional string. Returns: a Tensor of shape [batch, num_h_blocks, num_w_blocks, h_dim, w_dim, io_channels] Raises: ValueError: if channels or depth don't match.
[ "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, slice_dtype, activation_dtype), combine=True)
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 create four separate variables. Args: mesh: a Mesh heads: a Dimension io_channels: a Dimension kv_channels: a Dimension variable_dtype: a mtf.VariableDType combine: a boolean Returns: wq: a Tensor with shape [heads, io_channels, kv_channels] wk: a Tensor with shape [heads, io_channels, kv_channels] wv: a Tensor with shape [heads, io_channels, kv_channels] wo: a Tensor with shape [heads, io_channels, kv_channels] """ 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_channels.size * heads.size) ** -0.5 # verify that this still works and change it. o_stddev = (io_channels.size * heads.size) ** -0.5 if combine: def qkvo_initializer(shape, dtype=None, partition_info=None, verify_shape=None): del partition_info, verify_shape return tf.random_normal(shape, dtype=dtype) * tf.reshape( tf.cast([qk_stddev, qk_stddev, v_stddev, o_stddev], dtype or tf.float32), [4, 1, 1, 1]) var = mtf.get_variable( mesh, "qkvo", mtf.Shape([qkvo, heads, io_channels, kv_channels]), initializer=qkvo_initializer, dtype=variable_dtype) return mtf.unstack(var, qkvo) else: return [mtf.get_variable( mesh, name, mtf.Shape([heads, io_channels, kv_channels]), initializer=tf.random_normal_initializer(stddev=stddev), dtype=variable_dtype) for name, stddev in zip( ["q", "k", "v", "o"], [qk_stddev, qk_stddev, v_stddev, o_stddev])]
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_channels.size * heads.size) ** -0.5 # verify that this still works and change it. o_stddev = (io_channels.size * heads.size) ** -0.5 if combine: def qkvo_initializer(shape, dtype=None, partition_info=None, verify_shape=None): del partition_info, verify_shape return tf.random_normal(shape, dtype=dtype) * tf.reshape( tf.cast([qk_stddev, qk_stddev, v_stddev, o_stddev], dtype or tf.float32), [4, 1, 1, 1]) var = mtf.get_variable( mesh, "qkvo", mtf.Shape([qkvo, heads, io_channels, kv_channels]), initializer=qkvo_initializer, dtype=variable_dtype) return mtf.unstack(var, qkvo) else: return [mtf.get_variable( mesh, name, mtf.Shape([heads, io_channels, kv_channels]), initializer=tf.random_normal_initializer(stddev=stddev), dtype=variable_dtype) for name, stddev in zip( ["q", "k", "v", "o"], [qk_stddev, qk_stddev, v_stddev, o_stddev])]
[ "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 variable_dtype: a mtf.VariableDType combine: a boolean Returns: wq: a Tensor with shape [heads, io_channels, kv_channels] wk: a Tensor with shape [heads, io_channels, kv_channels] wv: a Tensor with shape [heads, io_channels, kv_channels] wo: a Tensor with shape [heads, io_channels, kv_channels]
[ "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.cast(mtf.equal(inputs, 0), dtype) * -1e9
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 = rename_length_to_memory_length(query_pos) return mtf.cast(mtf.less(query_pos, memory_pos), dtype) * -1e9
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.dtype Returns: a mtf.Tensor with shape [..., length_dim, memory_length_dim] """ memory_segment = rename_length_to_memory_length( memory_segment or query_segment) return mtf.cast(mtf.not_equal(query_segment, memory_segment), dtype) * -1e9
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: a mtf.Tensor with the same type and shape as x. """ 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)
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, dropout=0.0, dropout_broadcast_dims=None, master_dtype=tf.float32, slice_dtype=tf.float32, name="multihead_attention"): """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 (the size of the key and value vectors) heads: a mtf.Dimension (the number of heads) dropout: a floating point value dropout_broadcast_dims: an optional list of mtf.Dimension master_dtype: a tf.dtype slice_dtype: a tf.dtype name: an optional string. Returns: A mtf.Tensor with shape [batch, query_length, io_channels] Raises: ValueError: if the dimensions do not match. """ batch_dims = x.shape.dims[:-2] length, io_channels = x.shape.dims[-2:] with tf.variable_scope(name, default_name="compressed_attention", values=[x]): wq, wk, wv, wo = multihead_attention_vars( x.mesh, heads, io_channels, kv_channels, master_dtype, slice_dtype, x.dtype) memory_antecedent = compress_mean(x, length, compression_factor) memory_antecedent = rename_length_to_memory_length(memory_antecedent) memory_length = memory_antecedent.shape.dims[-2] q = mtf.einsum( [x, wq], mtf.Shape(batch_dims + [heads, length, kv_channels])) k = mtf.einsum( [memory_antecedent, wk], mtf.Shape(batch_dims + [heads, memory_length, kv_channels])) v = mtf.einsum( [memory_antecedent, wv], mtf.Shape(batch_dims + [heads, memory_length, kv_channels])) if mask_right: query_pos = mtf.range(x.mesh, length, dtype=tf.int32) memory_pos = ( mtf.range(x.mesh, memory_length, dtype=tf.int32) * compression_factor + (compression_factor - 1)) mask = mtf.cast(mtf.greater(memory_pos, query_pos), x.dtype) * -1e9 else: mask = None o = dot_product_attention( q, k, v, mask, dropout, dropout_broadcast_dims, extra_logit=0.0) return mtf.einsum( [o, wo], mtf.Shape(batch_dims + [length, io_channels]))
python
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, slice_dtype=tf.float32, name="multihead_attention"): batch_dims = x.shape.dims[:-2] length, io_channels = x.shape.dims[-2:] with tf.variable_scope(name, default_name="compressed_attention", values=[x]): wq, wk, wv, wo = multihead_attention_vars( x.mesh, heads, io_channels, kv_channels, master_dtype, slice_dtype, x.dtype) memory_antecedent = compress_mean(x, length, compression_factor) memory_antecedent = rename_length_to_memory_length(memory_antecedent) memory_length = memory_antecedent.shape.dims[-2] q = mtf.einsum( [x, wq], mtf.Shape(batch_dims + [heads, length, kv_channels])) k = mtf.einsum( [memory_antecedent, wk], mtf.Shape(batch_dims + [heads, memory_length, kv_channels])) v = mtf.einsum( [memory_antecedent, wv], mtf.Shape(batch_dims + [heads, memory_length, kv_channels])) if mask_right: query_pos = mtf.range(x.mesh, length, dtype=tf.int32) memory_pos = ( mtf.range(x.mesh, memory_length, dtype=tf.int32) * compression_factor + (compression_factor - 1)) mask = mtf.cast(mtf.greater(memory_pos, query_pos), x.dtype) * -1e9 else: mask = None o = dot_product_attention( q, k, v, mask, dropout, dropout_broadcast_dims, extra_logit=0.0) return mtf.einsum( [o, wo], mtf.Shape(batch_dims + [length, io_channels]))
[ "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 (the size of the key and value vectors) heads: a mtf.Dimension (the number of heads) dropout: a floating point value dropout_broadcast_dims: an optional list of mtf.Dimension master_dtype: a tf.dtype slice_dtype: a tf.dtype name: an optional string. Returns: A mtf.Tensor with shape [batch, query_length, io_channels] Raises: ValueError: if the dimensions do not match.
[ "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_factor) compression_factor_dim = mtf.Dimension( "compression_factor", compression_factor) new_shape = ( dims[:pos] + [compressed_dim, compression_factor_dim] + dims[pos + 1:]) x = mtf.reshape(x, new_shape) x = mtf.reduce_mean(x, reduced_dim=compression_factor_dim) return x
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, compression_factor_dim] + dims[pos + 1:]) x = mtf.reshape(x, new_shape) x = mtf.reduce_mean(x, reduced_dim=compression_factor_dim) return x
[ "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 described in "Attention Is All You Need", set num_memory_heads=0. If num_memory_heads==1, then there is only a single write-head, and multiple read-heads. This leads to faster incremental decoding, since the recurrent state is smaller If num_memory_heads > 1, then num_memory_heads indicates the number of write-heads. A fraction of the read-heads read each write-head. num_memory_heads must divide num_heads. This behavior has not yet been tested. Args: context: a transformer.Context kv_dim: a dimension (for key and value channels) num_heads: an integer num_memory_heads: an optional integer shared_kv: a boolean Returns: an attention.AttentionParams object """ if num_heads == 1: query_heads_dims = None memory_heads_dims = None elif num_memory_heads == 0: query_heads_dims = [mtf.Dimension("heads", num_heads)] memory_heads_dims = query_heads_dims elif num_memory_heads == 1: query_heads_dims = [mtf.Dimension("heads", num_heads)] memory_heads_dims = None else: if num_heads % num_memory_heads != 0: raise ValueError("num_memory_heads must divide num_heads") memory_heads_dims = [mtf.Dimension("heads", num_memory_heads)] query_heads_dims = memory_heads_dims + [ mtf.Dimension("query_heads", num_heads // num_memory_heads)] return attention.AttentionParams( context.mesh, query_input_dim=context.model_dim, memory_input_dim=context.model_dim, output_dim=context.model_dim, key_dim=kv_dim, value_dim=kv_dim, query_heads_dims=query_heads_dims, memory_heads_dims=memory_heads_dims, variable_dtype=context.variable_dtype, shared_kv=shared_kv)
python
def attention_params(context, kv_dim, num_heads, num_memory_heads=0, shared_kv=False): if num_heads == 1: query_heads_dims = None memory_heads_dims = None elif num_memory_heads == 0: query_heads_dims = [mtf.Dimension("heads", num_heads)] memory_heads_dims = query_heads_dims elif num_memory_heads == 1: query_heads_dims = [mtf.Dimension("heads", num_heads)] memory_heads_dims = None else: if num_heads % num_memory_heads != 0: raise ValueError("num_memory_heads must divide num_heads") memory_heads_dims = [mtf.Dimension("heads", num_memory_heads)] query_heads_dims = memory_heads_dims + [ mtf.Dimension("query_heads", num_heads // num_memory_heads)] return attention.AttentionParams( context.mesh, query_input_dim=context.model_dim, memory_input_dim=context.model_dim, output_dim=context.model_dim, key_dim=kv_dim, value_dim=kv_dim, query_heads_dims=query_heads_dims, memory_heads_dims=memory_heads_dims, variable_dtype=context.variable_dtype, shared_kv=shared_kv)
[ "def", "attention_params", "(", "context", ",", "kv_dim", ",", "num_heads", ",", "num_memory_heads", "=", "0", ",", "shared_kv", "=", "False", ")", ":", "if", "num_heads", "==", "1", ":", "query_heads_dims", "=", "None", "memory_heads_dims", "=", "None", "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 incremental decoding, since the recurrent state is smaller If num_memory_heads > 1, then num_memory_heads indicates the number of write-heads. A fraction of the read-heads read each write-head. num_memory_heads must divide num_heads. This behavior has not yet been tested. Args: context: a transformer.Context kv_dim: a dimension (for key and value channels) num_heads: an integer num_memory_heads: an optional integer shared_kv: a boolean Returns: an attention.AttentionParams object
[ "Attention", "Parameters", "for", "Transformer", "Layers", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/transformer_layers.py#L62-L116
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 in the returned dict. labels: a tensor where batch is the first dimension. outputs: a tensor of model predictions, same dimensionality as labels. Returns: metric_fns: dict of metric functions keyed by their name. """ metric_fns = {} for metric_name in metric_names: metric_fn_name = metric_name.split("/")[-1] if hasattr(metrics, metric_fn_name): metric_fn = getattr(metrics, metric_fn_name) metric_fns[metric_name] = metric_fn(labels, outputs) else: raise ValueError("Metric {} is not implemented".format(metric_fn_name)) return metric_fns
python
def get_metric_fns(metric_names, labels, outputs): metric_fns = {} for metric_name in metric_names: metric_fn_name = metric_name.split("/")[-1] if hasattr(metrics, metric_fn_name): metric_fn = getattr(metrics, metric_fn_name) metric_fns[metric_name] = metric_fn(labels, outputs) else: raise ValueError("Metric {} is not implemented".format(metric_fn_name)) return metric_fns
[ "def", "get_metric_fns", "(", "metric_names", ",", "labels", ",", "outputs", ")", ":", "metric_fns", "=", "{", "}", "for", "metric_name", "in", "metric_names", ":", "metric_fn_name", "=", "metric_name", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", ...
Generate a dictionary of metric name to metric function. Args: metric_names: list of strings in the format "prefix/metric_function_name". metric_function_name should refer to a function name in metrics.py. The prefix will be included in the key in the returned dict. labels: a tensor where batch is the first dimension. outputs: a tensor of model predictions, same dimensionality as labels. Returns: metric_fns: dict of metric functions keyed by their name.
[ "Generate", "a", "dictionary", "of", "metric", "name", "to", "metric", "function", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/metric_utils.py#L28-L50
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 == 'NAIVE': return _minimize_peak_memory_naive(graph) elif scheduler_alg == 'LIST': return _minimize_peak_memory_list(graph) else: raise NotImplementedError('{} is not a scheduler algorithm. It should be ' 'one of NAIVE or LIST.' .format(scheduler_alg))
python
def minimize_peak_memory(graph, scheduler_alg): if scheduler_alg == 'NAIVE': return _minimize_peak_memory_naive(graph) elif scheduler_alg == 'LIST': return _minimize_peak_memory_list(graph) else: raise NotImplementedError('{} is not a scheduler algorithm. It should be ' 'one of NAIVE or LIST.' .format(scheduler_alg))
[ "def", "minimize_peak_memory", "(", "graph", ",", "scheduler_alg", ")", ":", "if", "scheduler_alg", "==", "'NAIVE'", ":", "return", "_minimize_peak_memory_naive", "(", "graph", ")", "elif", "scheduler_alg", "==", "'LIST'", ":", "return", "_minimize_peak_memory_list", ...
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: an mtf.auto_mtf.graph_interface.GraphInterface. Returns: an iterable of integers representing the schedule. """ schedule = [] bytes_freed = {} # {operation_name: bytes freed} users_of = collections.defaultdict(set) # {tensor_name: set(operation_name)} in_degree = collections.defaultdict(int) # {operation_name: in degree} operation_id = {} # {operation_name: id} # We want an updatable priority queue, so we use the following workaround: # docs.python.org/2/library/heapq.html#priority-queue-implementation-notes priority_queue = [] # (negative bytes freed, operation name) # Set up the (greedy) topological sort. for i, operation_name in enumerate(graph.get_all_operation_names()): operation_id[operation_name] = i for input_name in graph.get_operation_input_names(operation_name): # Note that in _HybridGraphInterface, an operation may use a tensor twice, # but we deduplicate (with respect to in_degree) so that we can later use # users_of to decrement in_degree. if operation_name in users_of[input_name]: continue users_of[input_name].add(operation_name) in_degree[operation_name] += 1 for operation_name in graph.get_all_operation_names(): bytes_freed[operation_name] = 0 # For each input, this operation frees memory if it is the final consumer. for input_name in graph.get_operation_input_names(operation_name): if len(users_of[input_name]) == 1 and not graph.is_tensor_final( input_name): bytes_freed[operation_name] += graph.get_tensor_size(input_name) # For each output, this operation will require additional bytes of memory # (hence negative bytes freed). for output_name in graph.get_operation_output_names(operation_name): # If the output is used (or is final), then it eats memory. if users_of[output_name] or graph.is_tensor_final(output_name): bytes_freed[operation_name] -= graph.get_tensor_size(output_name) for operation_name in graph.get_all_operation_names(): if in_degree[operation_name] == 0: heapq.heappush(priority_queue, (-bytes_freed[operation_name], operation_name)) # Do the (greedy) topological sort. while priority_queue: neg_bytes_freed, operation_name = heapq.heappop(priority_queue) if bytes_freed[operation_name] != -neg_bytes_freed: continue schedule.append(operation_id[operation_name]) bytes_freed[operation_name] = None for output_name in graph.get_operation_output_names(operation_name): for other_operation_name in users_of[output_name]: in_degree[other_operation_name] -= 1 if in_degree[other_operation_name] == 0: heapq.heappush(priority_queue, (-bytes_freed[other_operation_name], other_operation_name)) for input_name in graph.get_operation_input_names(operation_name): if operation_name not in users_of[input_name]: # Used twice by this operation and hence already removed. continue users_of[input_name].remove(operation_name) if len(users_of[input_name]) != 1 or graph.is_tensor_final(output_name): continue (other_operation_name,) = users_of[input_name] bytes_freed[other_operation_name] += graph.get_tensor_size( input_name) if in_degree[other_operation_name] > 0: continue # Push another copy into the priority queue with our updated value. # The original copy will be ignored since it does not match bytes_freed. heapq.heappush(priority_queue, (-bytes_freed[other_operation_name], other_operation_name)) return schedule
python
def _minimize_peak_memory_list(graph): schedule = [] bytes_freed = {} # {operation_name: bytes freed} users_of = collections.defaultdict(set) # {tensor_name: set(operation_name)} in_degree = collections.defaultdict(int) # {operation_name: in degree} operation_id = {} # {operation_name: id} # We want an updatable priority queue, so we use the following workaround: # docs.python.org/2/library/heapq.html#priority-queue-implementation-notes priority_queue = [] # (negative bytes freed, operation name) # Set up the (greedy) topological sort. for i, operation_name in enumerate(graph.get_all_operation_names()): operation_id[operation_name] = i for input_name in graph.get_operation_input_names(operation_name): # Note that in _HybridGraphInterface, an operation may use a tensor twice, # but we deduplicate (with respect to in_degree) so that we can later use # users_of to decrement in_degree. if operation_name in users_of[input_name]: continue users_of[input_name].add(operation_name) in_degree[operation_name] += 1 for operation_name in graph.get_all_operation_names(): bytes_freed[operation_name] = 0 # For each input, this operation frees memory if it is the final consumer. for input_name in graph.get_operation_input_names(operation_name): if len(users_of[input_name]) == 1 and not graph.is_tensor_final( input_name): bytes_freed[operation_name] += graph.get_tensor_size(input_name) # For each output, this operation will require additional bytes of memory # (hence negative bytes freed). for output_name in graph.get_operation_output_names(operation_name): # If the output is used (or is final), then it eats memory. if users_of[output_name] or graph.is_tensor_final(output_name): bytes_freed[operation_name] -= graph.get_tensor_size(output_name) for operation_name in graph.get_all_operation_names(): if in_degree[operation_name] == 0: heapq.heappush(priority_queue, (-bytes_freed[operation_name], operation_name)) # Do the (greedy) topological sort. while priority_queue: neg_bytes_freed, operation_name = heapq.heappop(priority_queue) if bytes_freed[operation_name] != -neg_bytes_freed: continue schedule.append(operation_id[operation_name]) bytes_freed[operation_name] = None for output_name in graph.get_operation_output_names(operation_name): for other_operation_name in users_of[output_name]: in_degree[other_operation_name] -= 1 if in_degree[other_operation_name] == 0: heapq.heappush(priority_queue, (-bytes_freed[other_operation_name], other_operation_name)) for input_name in graph.get_operation_input_names(operation_name): if operation_name not in users_of[input_name]: # Used twice by this operation and hence already removed. continue users_of[input_name].remove(operation_name) if len(users_of[input_name]) != 1 or graph.is_tensor_final(output_name): continue (other_operation_name,) = users_of[input_name] bytes_freed[other_operation_name] += graph.get_tensor_size( input_name) if in_degree[other_operation_name] > 0: continue # Push another copy into the priority queue with our updated value. # The original copy will be ignored since it does not match bytes_freed. heapq.heappush(priority_queue, (-bytes_freed[other_operation_name], other_operation_name)) return schedule
[ "def", "_minimize_peak_memory_list", "(", "graph", ")", ":", "schedule", "=", "[", "]", "bytes_freed", "=", "{", "}", "# {operation_name: bytes freed}", "users_of", "=", "collections", ".", "defaultdict", "(", "set", ")", "# {tensor_name: set(operation_name)}", "in_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.GraphInterface. Returns: an iterable of integers representing the schedule.
[ "Computes", "schedule", "according", "to", "the", "greedy", "list", "heuristic", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/scheduler.py#L67-L154
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 computation. Returns: a mtf.LayoutRules """ mesh_shape = mtf.convert_to_shape(mesh_shape) estimator = memory_estimator.MemoryEstimator(mtf_graph, mesh_shape, mtf_outputs) optimizer = layout_optimizer.LayoutOptimizer(estimator) return mtf.convert_to_layout_rules(optimizer.solve())
python
def layout(mtf_graph, mesh_shape, mtf_outputs=()): mesh_shape = mtf.convert_to_shape(mesh_shape) estimator = memory_estimator.MemoryEstimator(mtf_graph, mesh_shape, mtf_outputs) optimizer = layout_optimizer.LayoutOptimizer(estimator) return mtf.convert_to_layout_rules(optimizer.solve())
[ "def", "layout", "(", "mtf_graph", ",", "mesh_shape", ",", "mtf_outputs", "=", "(", ")", ")", ":", "mesh_shape", "=", "mtf", ".", "convert_to_shape", "(", "mesh_shape", ")", "estimator", "=", "memory_estimator", ".", "MemoryEstimator", "(", "mtf_graph", ",", ...
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 variables: a list of Variables Returns: a list of Operations """ ops = [] for grad, var in zip(grads, variables): ops.extend(self.apply_grad(grad, var)) if not ops: return ops return variables[0].graph.combine_assignments(ops)
python
def apply_grads(self, grads, variables): 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 list of Operations
[ "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 of size >= min_dim_size_to_factor, then we do not factor. Args: shape: a Shape Returns: either a list of 2 Dimensions or None """ if not self._factored or shape.ndims < 2: return None sorted_dims = sorted(shape.dims, key=lambda d: -d.size) if sorted_dims[1].size < self._min_dim_size_to_factor: return None return sorted_dims[:2]
python
def _factored_dims(self, shape): 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 we do not factor. Args: shape: a Shape Returns: either a list of 2 Dimensions or None
[ "Should", "we", "use", "a", "factored", "second", "moment", "estimator", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/optimize.py#L139-L158
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 boolean indicating whether the assignment is valid. """ return ((mtf_dimension_name in self._splittable_mtf_dimension_names) and (self._mtf_dimension_name_to_size_gcd[mtf_dimension_name] % self._mesh_dimension_name_to_size[mesh_dimension_name] == 0))
python
def is_valid_assignment(self, mtf_dimension_name, mesh_dimension_name): 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() # set(string) for mtf_operation in mtf_graph.operations: for mtf_tensor in mtf_operation.outputs: for mtf_dimension in mtf_tensor.shape.dims: if not re.match(r"_anonymous_\d*", mtf_dimension.name): all_mtf_dimension_names.add(mtf_dimension.name) unsplittable_mtf_dimension_names = set() # set(string) for mtf_operation in mtf_graph.operations: unsplittable_mtf_dimension_names.update(mtf_operation.unsplittable_dims) return all_mtf_dimension_names - unsplittable_mtf_dimension_names
python
def _initialize_splittable_dimensions(self, mtf_graph): all_mtf_dimension_names = set() # set(string) for mtf_operation in mtf_graph.operations: for mtf_tensor in mtf_operation.outputs: for mtf_dimension in mtf_tensor.shape.dims: if not re.match(r"_anonymous_\d*", mtf_dimension.name): all_mtf_dimension_names.add(mtf_dimension.name) unsplittable_mtf_dimension_names = set() # set(string) for mtf_operation in mtf_graph.operations: unsplittable_mtf_dimension_names.update(mtf_operation.unsplittable_dims) return all_mtf_dimension_names - unsplittable_mtf_dimension_names
[ "def", "_initialize_splittable_dimensions", "(", "self", ",", "mtf_graph", ")", ":", "all_mtf_dimension_names", "=", "set", "(", ")", "# set(string)", "for", "mtf_operation", "in", "mtf_graph", ".", "operations", ":", "for", "mtf_tensor", "in", "mtf_operation", ".",...
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 being evenly divisible by some x is equivalent to the GCD being divisible by x. """ mtf_dimension_name_to_size_gcd = {} for mtf_operation in mtf_graph.operations: for mtf_tensor in mtf_operation.outputs: for mtf_dimension in mtf_tensor.shape.dims: mtf_dimension_name_to_size_gcd[mtf_dimension.name] = fractions.gcd( mtf_dimension_name_to_size_gcd.get(mtf_dimension.name, mtf_dimension.size), mtf_dimension.size) return mtf_dimension_name_to_size_gcd
python
def _initialize_mtf_dimension_name_to_size_gcd(self, mtf_graph): mtf_dimension_name_to_size_gcd = {} for mtf_operation in mtf_graph.operations: for mtf_tensor in mtf_operation.outputs: for mtf_dimension in mtf_tensor.shape.dims: mtf_dimension_name_to_size_gcd[mtf_dimension.name] = fractions.gcd( mtf_dimension_name_to_size_gcd.get(mtf_dimension.name, mtf_dimension.size), mtf_dimension.size) return mtf_dimension_name_to_size_gcd
[ "def", "_initialize_mtf_dimension_name_to_size_gcd", "(", "self", ",", "mtf_graph", ")", ":", "mtf_dimension_name_to_size_gcd", "=", "{", "}", "for", "mtf_operation", "in", "mtf_graph", ".", "operations", ":", "for", "mtf_tensor", "in", "mtf_operation", ".", "outputs"...
Initializer for self._mtf_dimension_name_to_size_gcd. Args: mtf_graph: an mtf.Graph. Returns: A {string: int}, mapping the name of an MTF dimension to the greatest common divisor of all the sizes it has. All these sizes being evenly divisible by some x is equivalent to the GCD being divisible by x.
[ "Initializer", "for", "self", ".", "_mtf_dimension_name_to_size_gcd", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/valid_layouts.py#L120-L140
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_dimension in mesh_shape.dims: mesh_dimension_name_to_size[mesh_dimension.name] = mesh_dimension.size return mesh_dimension_name_to_size
python
def _initialize_mesh_dimension_name_to_size(self, mesh_shape): 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 # [target, source] parts = [[xs[target] if target == source else None for source in xrange(n)] for target in xrange(n)] for distance in xrange(1, n // 2 + 1): for target in xrange(n): source = (target + distance) % n if parts[target][source] is None: with tf.device(devices[target]): parts[target][source] = tf.identity(parts[(target + 1) % n][source]) source = (target - distance) % n if parts[target][source] is None: with tf.device(devices[target]): parts[target][source] = tf.identity(parts[(target - 1) % n][source]) return mtf.parallel(devices, tf.concat, parts, axis=[concat_axis] * n)
python
def allconcat_ring(xs, devices, concat_axis): n = len(xs) if n == 1: return xs # [target, source] parts = [[xs[target] if target == source else None for source in xrange(n)] for target in xrange(n)] for distance in xrange(1, n // 2 + 1): for target in xrange(n): source = (target + distance) % n if parts[target][source] is None: with tf.device(devices[target]): parts[target][source] = tf.identity(parts[(target + 1) % n][source]) source = (target - distance) % n if parts[target][source] is None: with tf.device(devices[target]): parts[target][source] = tf.identity(parts[(target - 1) % n][source]) return mtf.parallel(devices, tf.concat, parts, axis=[concat_axis] * n)
[ "def", "allconcat_ring", "(", "xs", ",", "devices", ",", "concat_axis", ")", ":", "n", "=", "len", "(", "xs", ")", "if", "n", "==", "1", ":", "return", "xs", "# [target, source]", "parts", "=", "[", "[", "xs", "[", "target", "]", "if", "target", "=...
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("PlacementMeshImpl::Print") new_slices = x.tensor_list[:] with tf.device(self._devices[0]): new_slices[0] = tf.Print( new_slices[0], [t for d in data for t in d.tensor_list], message, **kwargs) return self.LaidOutTensor(new_slices)
python
def Print(self, x, data, message, **kwargs): # pylint: disable=invalid-name tf.logging.info("PlacementMeshImpl::Print") new_slices = x.tensor_list[:] with tf.device(self._devices[0]): new_slices[0] = tf.Print( new_slices[0], [t for d in data for t in d.tensor_list], message, **kwargs) return self.LaidOutTensor(new_slices)
[ "def", "Print", "(", "self", ",", "x", ",", "data", ",", "message", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=invalid-name", "tf", ".", "logging", ".", "info", "(", "\"PlacementMeshImpl::Print\"", ")", "new_slices", "=", "x", ".", "tensor_list", ...
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 concatenate) Returns: a LaidOutTensor """ return self._collective_with_groups( x, [mesh_axis], functools.partial( alltoall_ring, split_axis=split_axis, concat_axis=concat_axis))
python
def alltoall(self, x, mesh_axis, split_axis, concat_axis): 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 dimensions. key_dim is a Dimension representing the channels in the queries and keys value_dim is a Dimension representing the channels in values memory_length_dim is a Dimension representing the different key/value pairs. Dimensions of q: other_query_dims + {key_dim} Dimensions of k: other_memory_dims + {memory_length_dim, key_dim} Dimensions of v: other_memory_dims + {memory_length_dim, value_dim} other_memory_dims is a subset of other_query_dims Typically, other_query_dims={batch, heads, length} Typically, other_memory_dims={batch, heads} Args: q: a Tensor k: a Tensor v: a Tensor memory_length_dim: a Dimension key_dim: a Dimension value_dim: a Dimension mask: mask Tensor (see attention_mask()) dropout_rate: a float. dropout_broadcast_dims: an optional list of mtf.Dimension extra_logit: an optional scalar or tensor Returns: Tensor with shape q.shape - key_dim + value_dim """ logits = mtf.einsum([q, k], reduced_dims=[key_dim]) if mask is not None: logits += mask weights = mtf.softmax(logits, memory_length_dim, extra_logit=extra_logit) if dropout_rate != 0.0: weights = mtf.dropout( weights, 1.0 - dropout_rate, noise_shape=weights.shape - dropout_broadcast_dims) outputs_shape = q.shape - key_dim + value_dim outputs = mtf.einsum([weights, v], outputs_shape) return outputs
python
def attention(q, k, v, memory_length_dim, key_dim, value_dim, mask=None, dropout_rate=0.0, dropout_broadcast_dims=None, extra_logit=None): logits = mtf.einsum([q, k], reduced_dims=[key_dim]) if mask is not None: logits += mask weights = mtf.softmax(logits, memory_length_dim, extra_logit=extra_logit) if dropout_rate != 0.0: weights = mtf.dropout( weights, 1.0 - dropout_rate, noise_shape=weights.shape - dropout_broadcast_dims) outputs_shape = q.shape - key_dim + value_dim outputs = mtf.einsum([weights, v], outputs_shape) return outputs
[ "def", "attention", "(", "q", ",", "k", ",", "v", ",", "memory_length_dim", ",", "key_dim", ",", "value_dim", ",", "mask", "=", "None", ",", "dropout_rate", "=", "0.0", ",", "dropout_broadcast_dims", "=", "None", ",", "extra_logit", "=", "None", ")", ":"...
Dot-product attention - doesn't use positional dimensions. key_dim is a Dimension representing the channels in the queries and keys value_dim is a Dimension representing the channels in values memory_length_dim is a Dimension representing the different key/value pairs. Dimensions of q: other_query_dims + {key_dim} Dimensions of k: other_memory_dims + {memory_length_dim, key_dim} Dimensions of v: other_memory_dims + {memory_length_dim, value_dim} other_memory_dims is a subset of other_query_dims Typically, other_query_dims={batch, heads, length} Typically, other_memory_dims={batch, heads} Args: q: a Tensor k: a Tensor v: a Tensor memory_length_dim: a Dimension key_dim: a Dimension value_dim: a Dimension mask: mask Tensor (see attention_mask()) dropout_rate: a float. dropout_broadcast_dims: an optional list of mtf.Dimension extra_logit: an optional scalar or tensor Returns: Tensor with shape q.shape - key_dim + value_dim
[ "Dot", "-", "product", "attention", "-", "doesn", "t", "use", "positional", "dimensions", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/attention.py#L27-L76
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 "heads") variable_dtype: a mtf.VariableDType Returns: an AttentionParams """ return AttentionParams( mesh, query_input_dim=io_dim, memory_input_dim=io_dim, output_dim=io_dim, key_dim=kv_dim, value_dim=kv_dim, query_heads_dims=[heads_dim], memory_heads_dims=[heads_dim], variable_dtype=variable_dtype)
python
def attention_params_simple( mesh, io_dim, kv_dim, heads_dim, variable_dtype): return AttentionParams( mesh, query_input_dim=io_dim, memory_input_dim=io_dim, output_dim=io_dim, key_dim=kv_dim, value_dim=kv_dim, query_heads_dims=[heads_dim], memory_heads_dims=[heads_dim], variable_dtype=variable_dtype)
[ "def", "attention_params_simple", "(", "mesh", ",", "io_dim", ",", "kv_dim", ",", "heads_dim", ",", "variable_dtype", ")", ":", "return", "AttentionParams", "(", "mesh", ",", "query_input_dim", "=", "io_dim", ",", "memory_input_dim", "=", "io_dim", ",", "output_...
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, sequence_id=1, attention_kwargs=None): """Attention to the a neighborood around the source. If autoregressive, then query position p can only see memory positions in the range (p - radius, p]. If not autoregressive, then query position p can only see memory positions in the range (p - window_size, p + radius]. Args: q: a Tensor containing length_dim k: a Tensor containing length_dim v: an optional Tensor containing length_dim. If none then uses v=k. length_dim: a Dimension key_dim: a Dimension (the channels dimension of q and k) value_dim: a Dimension (the channels dimension of v) autoregressive: a boolean length_dim_num_splits: an optional integer indicating how many ways the length dimension is split radius: an integer sequence_id: a Tensor or an integer attention_kwargs: optional keyword arguments for attention() Returns: a Tensor with the shape x.shape - key_dim + value_dim Raises: ValueError: if channels or depth don't match. """ # Choose a suitable block size. # We choose the greatest divisor of length_per_split less than or equal # to max(window_size, 128) length_per_split = length_dim.size // length_dim_num_splits block_length = max(radius, 128) while length_per_split % block_length != 0: block_length -= 1 query_block_length = mtf.Dimension("query_block_length", block_length) memory_block_length = mtf.Dimension("memory_block_length", block_length) # The num_blocks dimension gets the same name as the length dimension, # so it will be split in the same way. num_blocks = mtf.Dimension(length_dim.name, length_dim.size // block_length) def _reshape_query(x): return mtf.replace_dimensions( x, length_dim, [num_blocks, query_block_length]) def _reshape_memory(x): x = mtf.replace_dimensions( x, length_dim, [num_blocks, memory_block_length]) return (mtf.left_halo_exchange if autoregressive else mtf.halo_exchange)( x, num_blocks, memory_block_length, radius) q = _reshape_query(q) k = _reshape_memory(k) if v: v = _reshape_memory(v) else: v = k if sequence_id is None: sequence_id = 1 if (not isinstance(sequence_id, mtf.Tensor) or length_dim not in sequence_id.shape.dims): sequence_id += mtf.zeros(q.mesh, [length_dim], tf.int32) q_sequence_id = _reshape_query(sequence_id) m_sequence_id = _reshape_memory(sequence_id) pos = mtf.range(q.mesh, length_dim, dtype=tf.int32) q_pos = _reshape_query(pos) m_pos = _reshape_memory(pos) padded_memory_block_length = mtf.Dimension( "memory_block_length", (1 if autoregressive else 2) * radius + block_length) relative_position = m_pos - q_pos illegal = mtf.not_equal(q_sequence_id, m_sequence_id) illegal = mtf.logical_or(illegal, mtf.less_equal(relative_position, -radius)) illegal = mtf.logical_or(illegal, mtf.greater( relative_position, 0 if autoregressive else radius)) mask = mtf.cast(illegal, q.dtype) * -1e9 o = attention(q, k, v, padded_memory_block_length, key_dim, value_dim, mask, **attention_kwargs) return mtf.replace_dimensions(o, [num_blocks, query_block_length], length_dim)
python
def local_attention_1d(q, k, v, length_dim, key_dim, value_dim, autoregressive=True, length_dim_num_splits=1, radius=128, sequence_id=1, attention_kwargs=None): # Choose a suitable block size. # We choose the greatest divisor of length_per_split less than or equal # to max(window_size, 128) length_per_split = length_dim.size // length_dim_num_splits block_length = max(radius, 128) while length_per_split % block_length != 0: block_length -= 1 query_block_length = mtf.Dimension("query_block_length", block_length) memory_block_length = mtf.Dimension("memory_block_length", block_length) # The num_blocks dimension gets the same name as the length dimension, # so it will be split in the same way. num_blocks = mtf.Dimension(length_dim.name, length_dim.size // block_length) def _reshape_query(x): return mtf.replace_dimensions( x, length_dim, [num_blocks, query_block_length]) def _reshape_memory(x): x = mtf.replace_dimensions( x, length_dim, [num_blocks, memory_block_length]) return (mtf.left_halo_exchange if autoregressive else mtf.halo_exchange)( x, num_blocks, memory_block_length, radius) q = _reshape_query(q) k = _reshape_memory(k) if v: v = _reshape_memory(v) else: v = k if sequence_id is None: sequence_id = 1 if (not isinstance(sequence_id, mtf.Tensor) or length_dim not in sequence_id.shape.dims): sequence_id += mtf.zeros(q.mesh, [length_dim], tf.int32) q_sequence_id = _reshape_query(sequence_id) m_sequence_id = _reshape_memory(sequence_id) pos = mtf.range(q.mesh, length_dim, dtype=tf.int32) q_pos = _reshape_query(pos) m_pos = _reshape_memory(pos) padded_memory_block_length = mtf.Dimension( "memory_block_length", (1 if autoregressive else 2) * radius + block_length) relative_position = m_pos - q_pos illegal = mtf.not_equal(q_sequence_id, m_sequence_id) illegal = mtf.logical_or(illegal, mtf.less_equal(relative_position, -radius)) illegal = mtf.logical_or(illegal, mtf.greater( relative_position, 0 if autoregressive else radius)) mask = mtf.cast(illegal, q.dtype) * -1e9 o = attention(q, k, v, padded_memory_block_length, key_dim, value_dim, mask, **attention_kwargs) return mtf.replace_dimensions(o, [num_blocks, query_block_length], length_dim)
[ "def", "local_attention_1d", "(", "q", ",", "k", ",", "v", ",", "length_dim", ",", "key_dim", ",", "value_dim", ",", "autoregressive", "=", "True", ",", "length_dim_num_splits", "=", "1", ",", "radius", "=", "128", ",", "sequence_id", "=", "1", ",", "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 length_dim k: a Tensor containing length_dim v: an optional Tensor containing length_dim. If none then uses v=k. length_dim: a Dimension key_dim: a Dimension (the channels dimension of q and k) value_dim: a Dimension (the channels dimension of v) autoregressive: a boolean length_dim_num_splits: an optional integer indicating how many ways the length dimension is split radius: an integer sequence_id: a Tensor or an integer attention_kwargs: optional keyword arguments for attention() Returns: a Tensor with the shape x.shape - key_dim + value_dim Raises: ValueError: if channels or depth don't match.
[ "Attention", "to", "the", "a", "neighborood", "around", "the", "source", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/attention.py#L289-L377
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, self.wq], reduced_dims=[self.query_input_dim]) if self.combine_dims: ret = mtf.replace_dimensions(ret, ret.shape.dims[-1], self.q_dims) return ret
python
def compute_q(self, query_antecedent): 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("compute_k cannot be called with shared_kv") ret = mtf.einsum( [memory_antecedent, self.wk], reduced_dims=[self.memory_input_dim]) if self.combine_dims: ret = mtf.replace_dimensions(ret, ret.shape.dims[-1], self.k_dims) return ret
python
def compute_k(self, memory_antecedent): if self.shared_kv: raise ValueError("compute_k cannot be called with shared_kv") ret = mtf.einsum( [memory_antecedent, self.wk], reduced_dims=[self.memory_input_dim]) if self.combine_dims: ret = mtf.replace_dimensions(ret, ret.shape.dims[-1], self.k_dims) return ret
[ "def", "compute_k", "(", "self", ",", "memory_antecedent", ")", ":", "if", "self", ".", "shared_kv", ":", "raise", "ValueError", "(", "\"compute_k cannot be called with shared_kv\"", ")", "ret", "=", "mtf", ".", "einsum", "(", "[", "memory_antecedent", ",", "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 ValueError("compute_v cannot be called with shared_kv") ret = mtf.einsum( [memory_antecedent, self.wv], reduced_dims=[self.memory_input_dim]) if self.combine_dims: ret = mtf.replace_dimensions(ret, ret.shape.dims[-1], self.v_dims) return ret
python
def compute_v(self, memory_antecedent): if self.shared_kv: raise ValueError("compute_v cannot be called with shared_kv") ret = mtf.einsum( [memory_antecedent, self.wv], reduced_dims=[self.memory_input_dim]) if self.combine_dims: ret = mtf.replace_dimensions(ret, ret.shape.dims[-1], self.v_dims) return ret
[ "def", "compute_v", "(", "self", ",", "memory_antecedent", ")", ":", "if", "self", ".", "shared_kv", ":", "raise", "ValueError", "(", "\"compute_v cannot be called with shared_kv\"", ")", "ret", "=", "mtf", ".", "einsum", "(", "[", "memory_antecedent", ",", "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 self.combine_dims: o = mtf.transpose(o, o.shape - self.o_dims + self.o_dims) o = mtf.replace_dimensions(o, self.o_dims, self.wo.shape.dims[0]) reduced_dims = [self.wo.shape.dims[0]] else: reduced_dims = self.o_dims return mtf.einsum( [o, self.wo], output_shape=output_shape, reduced_dims=reduced_dims)
python
def compute_output(self, o, output_shape=None): if self.combine_dims: o = mtf.transpose(o, o.shape - self.o_dims + self.o_dims) o = mtf.replace_dimensions(o, self.o_dims, self.wo.shape.dims[0]) reduced_dims = [self.wo.shape.dims[0]] else: reduced_dims = self.o_dims return mtf.einsum( [o, self.wo], output_shape=output_shape, reduced_dims=reduced_dims)
[ "def", "compute_output", "(", "self", ",", "o", ",", "output_shape", "=", "None", ")", ":", "if", "self", ".", "combine_dims", ":", "o", "=", "mtf", ".", "transpose", "(", "o", ",", "o", ".", "shape", "-", "self", ".", "o_dims", "+", "self", ".", ...
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, self._filepath) # the c++ op apppends 1=EOS - drop it. return ids[:-1]
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_layers: an integer d_ff: an integer num_heads: an integer d_kv: an integer dropout_rate: a float Returns: a LayerStack """ ret = [] for _ in xrange(num_layers): ret.append( transformer_layers.SelfAttention( num_heads=num_heads, key_value_size=d_kv, attention_kwargs={"dropout_rate": dropout_rate})) if include_encdec_attention: ret.append( transformer_layers.EncDecAttention( num_heads=num_heads, key_value_size=d_kv, attention_kwargs={"dropout_rate": dropout_rate})) ret.append( transformer_layers.DenseReluDense( hidden_size=d_ff, dropout_rate=dropout_rate)) return transformer.LayerStack(ret)
python
def simple_layer_stack(include_encdec_attention, num_layers=6, d_ff=2048, num_heads=8, d_kv=128, dropout_rate=0.1): ret = [] for _ in xrange(num_layers): ret.append( transformer_layers.SelfAttention( num_heads=num_heads, key_value_size=d_kv, attention_kwargs={"dropout_rate": dropout_rate})) if include_encdec_attention: ret.append( transformer_layers.EncDecAttention( num_heads=num_heads, key_value_size=d_kv, attention_kwargs={"dropout_rate": dropout_rate})) ret.append( transformer_layers.DenseReluDense( hidden_size=d_ff, dropout_rate=dropout_rate)) return transformer.LayerStack(ret)
[ "def", "simple_layer_stack", "(", "include_encdec_attention", ",", "num_layers", "=", "6", ",", "d_ff", "=", "2048", ",", "num_heads", "=", "8", ",", "d_kv", "=", "128", ",", "dropout_rate", "=", "0.1", ")", ":", "ret", "=", "[", "]", "for", "_", "in",...
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.activation_dtype) x = mtf.import_tf_tensor(mesh, features, mtf.Shape([batch_dim, io_dim])) x = mtf.cast(x, activation_dtype) h = x for lnum in xrange(1, FLAGS.num_hidden_layers + 2): if lnum + 1 == FLAGS.num_hidden_layers + 2: # output layer dim = io_dim elif lnum % 2 == 0: dim = mtf.Dimension('hidden_even', FLAGS.hidden_size) else: dim = mtf.Dimension('hidden_odd', FLAGS.hidden_size) h = mtf.layers.dense( h, dim, use_bias=False, master_dtype=master_dtype, slice_dtype=slice_dtype, name='layer_%d' % lnum) y = h g = tf.train.get_global_step() if FLAGS.step_with_nan >= 0: # Trigger NaN in the forward pass, this is used for testing whether # MeshTensorFlow can handle occasional NaN value. y += mtf.import_tf_tensor( mesh, tf.divide( 0.0, tf.cond(tf.equal(g, FLAGS.step_with_nan), lambda: 0., lambda: 1.)), mtf.Shape([])) loss = mtf.reduce_mean(mtf.square(y - x)) return y, loss
python
def toy_model(features, mesh): batch_dim = mtf.Dimension('batch', FLAGS.batch_size) io_dim = mtf.Dimension('io', FLAGS.io_size) master_dtype = tf.as_dtype(FLAGS.master_dtype) slice_dtype = tf.as_dtype(FLAGS.slice_dtype) activation_dtype = tf.as_dtype(FLAGS.activation_dtype) x = mtf.import_tf_tensor(mesh, features, mtf.Shape([batch_dim, io_dim])) x = mtf.cast(x, activation_dtype) h = x for lnum in xrange(1, FLAGS.num_hidden_layers + 2): if lnum + 1 == FLAGS.num_hidden_layers + 2: # output layer dim = io_dim elif lnum % 2 == 0: dim = mtf.Dimension('hidden_even', FLAGS.hidden_size) else: dim = mtf.Dimension('hidden_odd', FLAGS.hidden_size) h = mtf.layers.dense( h, dim, use_bias=False, master_dtype=master_dtype, slice_dtype=slice_dtype, name='layer_%d' % lnum) y = h g = tf.train.get_global_step() if FLAGS.step_with_nan >= 0: # Trigger NaN in the forward pass, this is used for testing whether # MeshTensorFlow can handle occasional NaN value. y += mtf.import_tf_tensor( mesh, tf.divide( 0.0, tf.cond(tf.equal(g, FLAGS.step_with_nan), lambda: 0., lambda: 1.)), mtf.Shape([])) loss = mtf.reduce_mean(mtf.square(y - x)) return y, loss
[ "def", "toy_model", "(", "features", ",", "mesh", ")", ":", "batch_dim", "=", "mtf", ".", "Dimension", "(", "'batch'", ",", "FLAGS", ".", "batch_size", ")", "io_dim", "=", "mtf", ".", "Dimension", "(", "'io'", ",", "FLAGS", ".", "io_size", ")", "master...
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.RunConfig( cluster=tpu_cluster_resolver, model_dir=FLAGS.model_dir, save_checkpoints_steps=None, # Disable the default saver save_checkpoints_secs=None, # Disable the default saver log_step_count_steps=iterations_per_loop, save_summary_steps=iterations_per_loop, tpu_config=tpu_config.TPUConfig( num_shards=mesh_shape.size, iterations_per_loop=iterations_per_loop, num_cores_per_replica=1, per_host_input_for_training=tpu_config.InputPipelineConfig.BROADCAST)) classifier = tpu_estimator.TPUEstimator( use_tpu=True, model_fn=model_fn, config=config, train_batch_size=FLAGS.batch_size, eval_batch_size=FLAGS.batch_size) current_step = estimator_lib._load_global_step_from_checkpoint_dir(FLAGS.model_dir) # pylint: disable=protected-access,line-too-long logging.info('Current step %d', current_step) if FLAGS.steps_per_checkpoint == 0: classifier.train(input_fn=ToyModelInput(), max_steps=FLAGS.train_steps) return while current_step < FLAGS.train_steps: next_checkpoint = min(current_step + FLAGS.steps_per_checkpoint, FLAGS.train_steps) classifier.train(input_fn=ToyModelInput(), max_steps=next_checkpoint) current_step = next_checkpoint logging.info('Starting to evaluate.') eval_results = classifier.evaluate( input_fn=ToyModelInput(), steps=156) # since we have 10000 examples and batch_size = 64 per host logging.info('Eval results: %s', eval_results)
python
def run_toy_model_tpu(): tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver( FLAGS.tpu, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project) iterations_per_loop = FLAGS.iterations mesh_shape = mtf.convert_to_shape(FLAGS.mesh_shape) config = tpu_config.RunConfig( cluster=tpu_cluster_resolver, model_dir=FLAGS.model_dir, save_checkpoints_steps=None, # Disable the default saver save_checkpoints_secs=None, # Disable the default saver log_step_count_steps=iterations_per_loop, save_summary_steps=iterations_per_loop, tpu_config=tpu_config.TPUConfig( num_shards=mesh_shape.size, iterations_per_loop=iterations_per_loop, num_cores_per_replica=1, per_host_input_for_training=tpu_config.InputPipelineConfig.BROADCAST)) classifier = tpu_estimator.TPUEstimator( use_tpu=True, model_fn=model_fn, config=config, train_batch_size=FLAGS.batch_size, eval_batch_size=FLAGS.batch_size) current_step = estimator_lib._load_global_step_from_checkpoint_dir(FLAGS.model_dir) # pylint: disable=protected-access,line-too-long logging.info('Current step %d', current_step) if FLAGS.steps_per_checkpoint == 0: classifier.train(input_fn=ToyModelInput(), max_steps=FLAGS.train_steps) return while current_step < FLAGS.train_steps: next_checkpoint = min(current_step + FLAGS.steps_per_checkpoint, FLAGS.train_steps) classifier.train(input_fn=ToyModelInput(), max_steps=next_checkpoint) current_step = next_checkpoint logging.info('Starting to evaluate.') eval_results = classifier.evaluate( input_fn=ToyModelInput(), steps=156) # since we have 10000 examples and batch_size = 64 per host logging.info('Eval results: %s', eval_results)
[ "def", "run_toy_model_tpu", "(", ")", ":", "tpu_cluster_resolver", "=", "tf", ".", "contrib", ".", "cluster_resolver", ".", "TPUClusterResolver", "(", "FLAGS", ".", "tpu", ",", "zone", "=", "FLAGS", ".", "tpu_zone", ",", "project", "=", "FLAGS", ".", "gcp_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.Dimension("batch", FLAGS.batch_size) row_blocks_dim = mtf.Dimension("row_blocks", 4) col_blocks_dim = mtf.Dimension("col_blocks", 4) rows_dim = mtf.Dimension("rows_size", 7) cols_dim = mtf.Dimension("cols_size", 7) classes_dim = mtf.Dimension("classes", 10) one_channel_dim = mtf.Dimension("one_channel", 1) x = mtf.import_tf_tensor( mesh, tf.reshape(image, [FLAGS.batch_size, 4, 7, 4, 7, 1]), mtf.Shape( [batch_dim, row_blocks_dim, rows_dim, col_blocks_dim, cols_dim, one_channel_dim])) x = mtf.transpose(x, [ batch_dim, row_blocks_dim, col_blocks_dim, rows_dim, cols_dim, one_channel_dim]) # add some convolutional layers to demonstrate that convolution works. fh_dim = mtf.Dimension("fh", 9) fw_dim = mtf.Dimension("fw", 9) filters1_dim = mtf.Dimension("filters1", 16) filters2_dim = mtf.Dimension("filters2", 16) kernel1 = mtf.get_variable( mesh, "kernel1", [fh_dim, fw_dim, one_channel_dim, filters1_dim]) kernel2 = mtf.get_variable( mesh, "kernel2", [fh_dim, fw_dim, filters1_dim, filters2_dim]) f1 = mtf.relu(mtf.conv2d_with_blocks( x, kernel1, strides=[1, 1, 1, 1], padding="SAME", h_blocks_dim=row_blocks_dim, w_blocks_dim=col_blocks_dim)) f2 = mtf.relu(mtf.conv2d_with_blocks( f1, kernel2, strides=[1, 1, 1, 1], padding="SAME", h_blocks_dim=row_blocks_dim, w_blocks_dim=col_blocks_dim)) x = mtf.reduce_mean(f2, reduced_dim=filters2_dim) # add some fully-connected dense layers. hidden_dim1 = mtf.Dimension("hidden1", FLAGS.hidden_size) hidden_dim2 = mtf.Dimension("hidden2", FLAGS.hidden_size) h1 = mtf.layers.dense( x, hidden_dim1, reduced_dims=x.shape.dims[-4:], activation=mtf.relu, name="hidden1") h2 = mtf.layers.dense( h1, hidden_dim2, activation=mtf.relu, name="hidden2") logits = mtf.layers.dense(h2, classes_dim, name="logits") if labels is None: loss = None else: labels = mtf.import_tf_tensor( mesh, tf.reshape(labels, [FLAGS.batch_size]), mtf.Shape([batch_dim])) loss = mtf.layers.softmax_cross_entropy_with_logits( logits, mtf.one_hot(labels, classes_dim), classes_dim) loss = mtf.reduce_mean(loss) return logits, loss
python
def mnist_model(image, labels, mesh): batch_dim = mtf.Dimension("batch", FLAGS.batch_size) row_blocks_dim = mtf.Dimension("row_blocks", 4) col_blocks_dim = mtf.Dimension("col_blocks", 4) rows_dim = mtf.Dimension("rows_size", 7) cols_dim = mtf.Dimension("cols_size", 7) classes_dim = mtf.Dimension("classes", 10) one_channel_dim = mtf.Dimension("one_channel", 1) x = mtf.import_tf_tensor( mesh, tf.reshape(image, [FLAGS.batch_size, 4, 7, 4, 7, 1]), mtf.Shape( [batch_dim, row_blocks_dim, rows_dim, col_blocks_dim, cols_dim, one_channel_dim])) x = mtf.transpose(x, [ batch_dim, row_blocks_dim, col_blocks_dim, rows_dim, cols_dim, one_channel_dim]) # add some convolutional layers to demonstrate that convolution works. fh_dim = mtf.Dimension("fh", 9) fw_dim = mtf.Dimension("fw", 9) filters1_dim = mtf.Dimension("filters1", 16) filters2_dim = mtf.Dimension("filters2", 16) kernel1 = mtf.get_variable( mesh, "kernel1", [fh_dim, fw_dim, one_channel_dim, filters1_dim]) kernel2 = mtf.get_variable( mesh, "kernel2", [fh_dim, fw_dim, filters1_dim, filters2_dim]) f1 = mtf.relu(mtf.conv2d_with_blocks( x, kernel1, strides=[1, 1, 1, 1], padding="SAME", h_blocks_dim=row_blocks_dim, w_blocks_dim=col_blocks_dim)) f2 = mtf.relu(mtf.conv2d_with_blocks( f1, kernel2, strides=[1, 1, 1, 1], padding="SAME", h_blocks_dim=row_blocks_dim, w_blocks_dim=col_blocks_dim)) x = mtf.reduce_mean(f2, reduced_dim=filters2_dim) # add some fully-connected dense layers. hidden_dim1 = mtf.Dimension("hidden1", FLAGS.hidden_size) hidden_dim2 = mtf.Dimension("hidden2", FLAGS.hidden_size) h1 = mtf.layers.dense( x, hidden_dim1, reduced_dims=x.shape.dims[-4:], activation=mtf.relu, name="hidden1") h2 = mtf.layers.dense( h1, hidden_dim2, activation=mtf.relu, name="hidden2") logits = mtf.layers.dense(h2, classes_dim, name="logits") if labels is None: loss = None else: labels = mtf.import_tf_tensor( mesh, tf.reshape(labels, [FLAGS.batch_size]), mtf.Shape([batch_dim])) loss = mtf.layers.softmax_cross_entropy_with_logits( logits, mtf.one_hot(labels, classes_dim), classes_dim) loss = mtf.reduce_mean(loss) return logits, loss
[ "def", "mnist_model", "(", "image", ",", "labels", ",", "mesh", ")", ":", "batch_dim", "=", "mtf", ".", "Dimension", "(", "\"batch\"", ",", "FLAGS", ".", "batch_size", ")", "row_blocks_dim", "=", "mtf", ".", "Dimension", "(", "\"row_blocks\"", ",", "4", ...
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, larger sizes result in better # randomness, while smaller sizes use less memory. MNIST is a small # enough dataset that we can easily shuffle the full epoch. ds = dataset.train(FLAGS.data_dir) ds_batched = ds.cache().shuffle(buffer_size=50000).batch(FLAGS.batch_size) # Iterate through the dataset a set number (`epochs_between_evals`) of times # during each training session. ds = ds_batched.repeat(FLAGS.epochs_between_evals) return ds def eval_input_fn(): return dataset.test(FLAGS.data_dir).batch( FLAGS.batch_size).make_one_shot_iterator().get_next() # Train and evaluate model. for _ in range(FLAGS.train_epochs // FLAGS.epochs_between_evals): mnist_classifier.train(input_fn=train_input_fn, hooks=None) eval_results = mnist_classifier.evaluate(input_fn=eval_input_fn) print("\nEvaluation results:\n\t%s\n" % eval_results)
python
def run_mnist(): mnist_classifier = tf.estimator.Estimator( model_fn=model_fn, model_dir=FLAGS.model_dir) # Set up training and evaluation input functions. def train_input_fn(): """Prepare data for training.""" # When choosing shuffle buffer sizes, larger sizes result in better # randomness, while smaller sizes use less memory. MNIST is a small # enough dataset that we can easily shuffle the full epoch. ds = dataset.train(FLAGS.data_dir) ds_batched = ds.cache().shuffle(buffer_size=50000).batch(FLAGS.batch_size) # Iterate through the dataset a set number (`epochs_between_evals`) of times # during each training session. ds = ds_batched.repeat(FLAGS.epochs_between_evals) return ds def eval_input_fn(): return dataset.test(FLAGS.data_dir).batch( FLAGS.batch_size).make_one_shot_iterator().get_next() # Train and evaluate model. for _ in range(FLAGS.train_epochs // FLAGS.epochs_between_evals): mnist_classifier.train(input_fn=train_input_fn, hooks=None) eval_results = mnist_classifier.evaluate(input_fn=eval_input_fn) print("\nEvaluation results:\n\t%s\n" % eval_results)
[ "def", "run_mnist", "(", ")", ":", "mnist_classifier", "=", "tf", ".", "estimator", ".", "Estimator", "(", "model_fn", "=", "model_fn", ",", "model_dir", "=", "FLAGS", ".", "model_dir", ")", "# Set up training and evaluation input functions.", "def", "train_input_fn...
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.reshape(x, shape_with_length) y, loss = transformer_moe_layer_v2( x, context.model_dim, self._hparams, context.train, context.variable_dtype, layout=context.layout, mesh_shape=context.mesh_shape, nonpadding=context.nonpadding) if context.losses is not None: context.losses.append(loss) if not has_length_dim: y = mtf.reshape(y, x_shape) return y
python
def call(self, context, x, losses=None): has_length_dim = context.length_dim in x.shape.dims if not has_length_dim: x_shape = x.shape shape_with_length = mtf.Shape( x_shape.dims[:-1] + [mtf.Dimension("length", 1)] + x_shape.dims[-1:]) x = mtf.reshape(x, shape_with_length) y, loss = transformer_moe_layer_v2( x, context.model_dim, self._hparams, context.train, context.variable_dtype, layout=context.layout, mesh_shape=context.mesh_shape, nonpadding=context.nonpadding) if context.losses is not None: context.losses.append(loss) if not has_length_dim: y = mtf.reshape(y, x_shape) return y
[ "def", "call", "(", "self", ",", "context", ",", "x", ",", "losses", "=", "None", ")", ":", "has_length_dim", "=", "context", ".", "length_dim", "in", "x", ".", "shape", ".", "dims", "if", "not", "has_length_dim", ":", "x_shape", "=", "x", ".", "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 is no feasible solution, this will probably crash. Args: model: A pywrapcp.CpModel object. solver: A pywrapcp.CpSolver object. Returns: Nothing, but prints the solution associated with solver. """ model_proto = model.Proto() response_proto = solver.ResponseProto() variables_in_objective_map = {} maximization = False if model_proto.HasField('objective'): objective = model_proto.objective for i in range(len(objective.vars)): variables_in_objective_map[objective.vars[i]] = objective.coeffs[i] if objective.scaling_factor < 0.0: maximization = True variable_assignments = [] variables_in_objective = [] num_vars = len(model_proto.variables) for var_index in range(num_vars): if not model_proto.variables[var_index].name: continue variable_name = model_proto.variables[var_index].name if var_index in variables_in_objective_map: coefficient = variables_in_objective_map[var_index] if coefficient: if maximization: coefficient *= -1 if coefficient < 0: variables_in_objective.append(' - {} * {}'.format( -coefficient, variable_name)) elif coefficient > 0: variables_in_objective.append(' + {} * {}'.format( coefficient, variable_name)) variable_assignments.append(' {} = {}\n'.format( variable_name, response_proto.solution[var_index])) print(''.join(variable_assignments), end='') # Strip the leading '+' if it exists. if variables_in_objective and variables_in_objective[0][1] == '+': variables_in_objective[0] = variables_in_objective[0][2:] print('{}:{}'.format('Maximize' if maximization else 'Minimize', ''.join(variables_in_objective))) print('Objective value: {}\n'.format(solver.ObjectiveValue()))
python
def print_solution(model, solver): model_proto = model.Proto() response_proto = solver.ResponseProto() variables_in_objective_map = {} maximization = False if model_proto.HasField('objective'): objective = model_proto.objective for i in range(len(objective.vars)): variables_in_objective_map[objective.vars[i]] = objective.coeffs[i] if objective.scaling_factor < 0.0: maximization = True variable_assignments = [] variables_in_objective = [] num_vars = len(model_proto.variables) for var_index in range(num_vars): if not model_proto.variables[var_index].name: continue variable_name = model_proto.variables[var_index].name if var_index in variables_in_objective_map: coefficient = variables_in_objective_map[var_index] if coefficient: if maximization: coefficient *= -1 if coefficient < 0: variables_in_objective.append(' - {} * {}'.format( -coefficient, variable_name)) elif coefficient > 0: variables_in_objective.append(' + {} * {}'.format( coefficient, variable_name)) variable_assignments.append(' {} = {}\n'.format( variable_name, response_proto.solution[var_index])) print(''.join(variable_assignments), end='') # Strip the leading '+' if it exists. if variables_in_objective and variables_in_objective[0][1] == '+': variables_in_objective[0] = variables_in_objective[0][2:] print('{}:{}'.format('Maximize' if maximization else 'Minimize', ''.join(variables_in_objective))) print('Objective value: {}\n'.format(solver.ObjectiveValue()))
[ "def", "print_solution", "(", "model", ",", "solver", ")", ":", "model_proto", "=", "model", ".", "Proto", "(", ")", "response_proto", "=", "solver", ".", "ResponseProto", "(", ")", "variables_in_objective_map", "=", "{", "}", "maximization", "=", "False", "...
Prints the solution associated with solver. If solver has already had Solve() called on it, prints the solution. This includes each variable and its assignment, along with the objective function and its optimal value. If solver has not had Solve() called on it, or there is no feasible solution, this will probably crash. Args: model: A pywrapcp.CpModel object. solver: A pywrapcp.CpSolver object. Returns: Nothing, but prints the solution associated with solver.
[ "Prints", "the", "solution", "associated", "with", "solver", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/print_cp_model_solution.py#L32-L84
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. """ assignment_string = [] for splittable in sorted(splittable_dimensions): if splittable in assignment: assignment_string.append("{}:{}".format(splittable, assignment[splittable])) else: assignment_string.append("{}".format(splittable)) return "y_(" + ",".join(assignment_string) + ")"
python
def _local_var_name(splittable_dimensions, assignment): assignment_string = [] for splittable in sorted(splittable_dimensions): if splittable in assignment: assignment_string.append("{}:{}".format(splittable, assignment[splittable])) else: assignment_string.append("{}".format(splittable)) return "y_(" + ",".join(assignment_string) + ")"
[ "def", "_local_var_name", "(", "splittable_dimensions", ",", "assignment", ")", ":", "assignment_string", "=", "[", "]", "for", "splittable", "in", "sorted", "(", "splittable_dimensions", ")", ":", "if", "splittable", "in", "assignment", ":", "assignment_string", ...
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: A list of the valid assignments. Each assignment is a dict keyed by every splittable dimension, whose value is either a mesh dimension or None. """ assignments = [] for assignment_size in six.moves.xrange( 1 + min(len(splittable_dimensions), len(mesh_dimension_to_size))): for s_dims_chosen in itertools.combinations(splittable_dimensions, assignment_size): for m_dims_chosen in itertools.permutations(mesh_dimension_to_size, assignment_size): assignments.append(dict(zip(s_dims_chosen, m_dims_chosen))) return assignments
python
def _generate_assignments(splittable_dimensions, mesh_dimension_to_size): assignments = [] for assignment_size in six.moves.xrange( 1 + min(len(splittable_dimensions), len(mesh_dimension_to_size))): for s_dims_chosen in itertools.combinations(splittable_dimensions, assignment_size): for m_dims_chosen in itertools.permutations(mesh_dimension_to_size, assignment_size): assignments.append(dict(zip(s_dims_chosen, m_dims_chosen))) return assignments
[ "def", "_generate_assignments", "(", "splittable_dimensions", ",", "mesh_dimension_to_size", ")", ":", "assignments", "=", "[", "]", "for", "assignment_size", "in", "six", ".", "moves", ".", "xrange", "(", "1", "+", "min", "(", "len", "(", "splittable_dimensions...
Generates all ways to map splittable dimensions to mesh dimensions. Args: splittable_dimensions: a frozenset of the names of splittable dimensions. mesh_dimension_to_size: a dictionary from mesh dimension name to size. Returns: A list of the valid assignments. Each assignment is a dict keyed by every splittable dimension, whose value is either a mesh dimension or None.
[ "Generates", "all", "ways", "to", "map", "splittable", "dimensions", "to", "mesh", "dimensions", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout_optimizer.py#L404-L423
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 = {} # a {string: frozenset(string)}, mapping tensor name to MTF dimension names. self._tensor_name_to_mtf_dimension_set = {} for operation_name in self._graph.get_all_operation_names(): self._operation_name_to_mtf_dimension_set[operation_name] = frozenset( set(self._graph.get_operation_mtf_dimension_names( operation_name)).intersection( self._layout_validator.splittable_mtf_dimension_names)) for tensor_name in self._graph.get_all_tensor_names(): self._tensor_name_to_mtf_dimension_set[tensor_name] = frozenset( set(self._graph.get_tensor_mtf_dimension_names(tensor_name)) .intersection(self._layout_validator.splittable_mtf_dimension_names)) self._operation_mtf_dimension_sets = set( self._operation_name_to_mtf_dimension_set.values()) self._mtf_dimension_sets = self._operation_mtf_dimension_sets | set( self._tensor_name_to_mtf_dimension_set.values()) # Compute possible assignments for each set of MTF dimensions. self._assignments = {} # indexed by MTF dimension set for mtf_dimension_set in self._mtf_dimension_sets: self._assignments[mtf_dimension_set] = _generate_assignments( mtf_dimension_set, self._layout_validator.mesh_dimension_name_to_size)
python
def _preprocess_input(self): # Compute the sets of MTF dimensions used in operations/tensors. # a {string: frozenset(string)}, mapping operation name to MTF dimension # names. self._operation_name_to_mtf_dimension_set = {} # a {string: frozenset(string)}, mapping tensor name to MTF dimension names. self._tensor_name_to_mtf_dimension_set = {} for operation_name in self._graph.get_all_operation_names(): self._operation_name_to_mtf_dimension_set[operation_name] = frozenset( set(self._graph.get_operation_mtf_dimension_names( operation_name)).intersection( self._layout_validator.splittable_mtf_dimension_names)) for tensor_name in self._graph.get_all_tensor_names(): self._tensor_name_to_mtf_dimension_set[tensor_name] = frozenset( set(self._graph.get_tensor_mtf_dimension_names(tensor_name)) .intersection(self._layout_validator.splittable_mtf_dimension_names)) self._operation_mtf_dimension_sets = set( self._operation_name_to_mtf_dimension_set.values()) self._mtf_dimension_sets = self._operation_mtf_dimension_sets | set( self._tensor_name_to_mtf_dimension_set.values()) # Compute possible assignments for each set of MTF dimensions. self._assignments = {} # indexed by MTF dimension set for mtf_dimension_set in self._mtf_dimension_sets: self._assignments[mtf_dimension_set] = _generate_assignments( mtf_dimension_set, self._layout_validator.mesh_dimension_name_to_size)
[ "def", "_preprocess_input", "(", "self", ")", ":", "# Compute the sets of MTF dimensions used in operations/tensors.", "# a {string: frozenset(string)}, mapping operation name to MTF dimension", "# names.", "self", ".", "_operation_name_to_mtf_dimension_set", "=", "{", "}", "# a {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 ( self._layout_validator.mesh_dimension_name_to_size): name = _global_var_name(mtf_dimension_name, mesh_dimension_name) self._global_vars[(mtf_dimension_name, mesh_dimension_name)] = ( self._model.NewBoolVar(name)) # Initialize local variables. self._local_vars = {} # Indexed by (tensorflow dimension set), then name of # assignment. for mtf_dimension_set in self._mtf_dimension_sets: self._local_vars[mtf_dimension_set] = {} for assignment in self._assignments[mtf_dimension_set]: # TODO(joshuawang): Avoid hash collision no matter what dimension names # are; don't hash by this local var name, swap to using a tuple encoding # of the full assignment instead. name = _local_var_name(mtf_dimension_set, assignment) self._local_vars[mtf_dimension_set][name] = ( self._model.NewBoolVar(name)) # Initialize memory variable. We need a crude upper bound on memory, so we # use the total size of all tensors under the empty assignment. # NOTE(joshuawang): This bound could be improved by factoring in the # schedule. memory_upper_bound = 0 for tensor_name in self._graph.get_all_tensor_names(): if self._graph.is_tensor_on_canonical_device(tensor_name): memory_upper_bound += int(self._graph.get_tensor_size(tensor_name)) self._memory_var = self._model.NewIntVar(0, memory_upper_bound, "z")
python
def _initialize_variables(self): # Initialize global variables. self._global_vars = {} # Indexed by (MTF dimension, mesh dimension) for mtf_dimension_name in ( self._layout_validator.splittable_mtf_dimension_names): for mesh_dimension_name in ( self._layout_validator.mesh_dimension_name_to_size): name = _global_var_name(mtf_dimension_name, mesh_dimension_name) self._global_vars[(mtf_dimension_name, mesh_dimension_name)] = ( self._model.NewBoolVar(name)) # Initialize local variables. self._local_vars = {} # Indexed by (tensorflow dimension set), then name of # assignment. for mtf_dimension_set in self._mtf_dimension_sets: self._local_vars[mtf_dimension_set] = {} for assignment in self._assignments[mtf_dimension_set]: # TODO(joshuawang): Avoid hash collision no matter what dimension names # are; don't hash by this local var name, swap to using a tuple encoding # of the full assignment instead. name = _local_var_name(mtf_dimension_set, assignment) self._local_vars[mtf_dimension_set][name] = ( self._model.NewBoolVar(name)) # Initialize memory variable. We need a crude upper bound on memory, so we # use the total size of all tensors under the empty assignment. # NOTE(joshuawang): This bound could be improved by factoring in the # schedule. memory_upper_bound = 0 for tensor_name in self._graph.get_all_tensor_names(): if self._graph.is_tensor_on_canonical_device(tensor_name): memory_upper_bound += int(self._graph.get_tensor_size(tensor_name)) self._memory_var = self._model.NewIntVar(0, memory_upper_bound, "z")
[ "def", "_initialize_variables", "(", "self", ")", ":", "# Initialize global variables.", "self", ".", "_global_vars", "=", "{", "}", "# Indexed by (MTF dimension, mesh dimension)", "for", "mtf_dimension_name", "in", "(", "self", ".", "_layout_validator", ".", "splittable_...
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[(mtf_dimension_name, mesh_dimension_name)] for mtf_dimension_name in mtf_dimension_set) <= 1) # Add global constraints. for mtf_dimension_name in ( self._layout_validator.splittable_mtf_dimension_names): self._model.Add( sum(self._global_vars[(mtf_dimension_name, mesh_dimension_name)] for mesh_dimension_name in ( self._layout_validator.mesh_dimension_name_to_size)) <= 1) # Add divisibility constraints. for mtf_dimension_name in ( self._layout_validator.splittable_mtf_dimension_names): for mesh_dimension_name in ( self._layout_validator.mesh_dimension_name_to_size): if not self._layout_validator.is_valid_assignment(mtf_dimension_name, mesh_dimension_name): self._model.Add(self._global_vars[(mtf_dimension_name, mesh_dimension_name)] == 0) # Add local constraints. for mtf_dimension_set in self._mtf_dimension_sets: self._model.Add( sum(self._local_vars[mtf_dimension_set][_local_var_name( mtf_dimension_set, assignment)] for assignment in self._assignments[mtf_dimension_set]) == 1) # Add local-to-global constraints. for mtf_dimension_set in self._mtf_dimension_sets: for assignment in self._assignments[mtf_dimension_set]: name = _local_var_name(mtf_dimension_set, assignment) for mtf_dimension_name in mtf_dimension_set: if mtf_dimension_name in assignment: mesh_dimension_name = assignment[mtf_dimension_name] self._model.AddImplication( self._local_vars[mtf_dimension_set][name], self._global_vars[(mtf_dimension_name, mesh_dimension_name)]) else: for mesh_dimension_name in ( self._layout_validator.mesh_dimension_name_to_size): self._model.AddImplication( self._global_vars[(mtf_dimension_name, mesh_dimension_name)], self._local_vars[mtf_dimension_set][name].Not()) # Add memory constraints. tensor_memory_sum = {} for tensor_name in self._graph.get_all_tensor_names(): tensor_memory_sum[tensor_name] = 0 mtf_dimension_set = self._tensor_name_to_mtf_dimension_set[tensor_name] if not self._graph.is_tensor_on_canonical_device(tensor_name): continue for assignment in self._assignments[mtf_dimension_set]: size_under_assignment = self._graph.get_tensor_size( tensor_name, assignment, self._layout_validator.mesh_dimension_name_to_size) name = _local_var_name(mtf_dimension_set, assignment) tensor_memory_sum[tensor_name] += ( size_under_assignment * self._local_vars[mtf_dimension_set][name]) for tensor_names in self._get_memory_contents(): self._model.Add( sum(tensor_memory_sum[tensor_name] for tensor_name in tensor_names) <= self._memory_var)
python
def _add_constraints(self): # Add operation constraints. for mesh_dimension_name in ( self._layout_validator.mesh_dimension_name_to_size): for mtf_dimension_set in self._operation_mtf_dimension_sets: self._model.Add( sum(self._global_vars[(mtf_dimension_name, mesh_dimension_name)] for mtf_dimension_name in mtf_dimension_set) <= 1) # Add global constraints. for mtf_dimension_name in ( self._layout_validator.splittable_mtf_dimension_names): self._model.Add( sum(self._global_vars[(mtf_dimension_name, mesh_dimension_name)] for mesh_dimension_name in ( self._layout_validator.mesh_dimension_name_to_size)) <= 1) # Add divisibility constraints. for mtf_dimension_name in ( self._layout_validator.splittable_mtf_dimension_names): for mesh_dimension_name in ( self._layout_validator.mesh_dimension_name_to_size): if not self._layout_validator.is_valid_assignment(mtf_dimension_name, mesh_dimension_name): self._model.Add(self._global_vars[(mtf_dimension_name, mesh_dimension_name)] == 0) # Add local constraints. for mtf_dimension_set in self._mtf_dimension_sets: self._model.Add( sum(self._local_vars[mtf_dimension_set][_local_var_name( mtf_dimension_set, assignment)] for assignment in self._assignments[mtf_dimension_set]) == 1) # Add local-to-global constraints. for mtf_dimension_set in self._mtf_dimension_sets: for assignment in self._assignments[mtf_dimension_set]: name = _local_var_name(mtf_dimension_set, assignment) for mtf_dimension_name in mtf_dimension_set: if mtf_dimension_name in assignment: mesh_dimension_name = assignment[mtf_dimension_name] self._model.AddImplication( self._local_vars[mtf_dimension_set][name], self._global_vars[(mtf_dimension_name, mesh_dimension_name)]) else: for mesh_dimension_name in ( self._layout_validator.mesh_dimension_name_to_size): self._model.AddImplication( self._global_vars[(mtf_dimension_name, mesh_dimension_name)], self._local_vars[mtf_dimension_set][name].Not()) # Add memory constraints. tensor_memory_sum = {} for tensor_name in self._graph.get_all_tensor_names(): tensor_memory_sum[tensor_name] = 0 mtf_dimension_set = self._tensor_name_to_mtf_dimension_set[tensor_name] if not self._graph.is_tensor_on_canonical_device(tensor_name): continue for assignment in self._assignments[mtf_dimension_set]: size_under_assignment = self._graph.get_tensor_size( tensor_name, assignment, self._layout_validator.mesh_dimension_name_to_size) name = _local_var_name(mtf_dimension_set, assignment) tensor_memory_sum[tensor_name] += ( size_under_assignment * self._local_vars[mtf_dimension_set][name]) for tensor_names in self._get_memory_contents(): self._model.Add( sum(tensor_memory_sum[tensor_name] for tensor_name in tensor_names) <= self._memory_var)
[ "def", "_add_constraints", "(", "self", ")", ":", "# Add operation constraints.", "for", "mesh_dimension_name", "in", "(", "self", ".", "_layout_validator", ".", "mesh_dimension_name_to_size", ")", ":", "for", "mtf_dimension_set", "in", "self", ".", "_operation_mtf_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()). """ if self._memory_contents is not None: return self._memory_contents schedule = scheduler.minimize_peak_memory(self._graph, self._scheduler_alg) self._memory_contents = self._graph.compute_memory_contents_under_schedule( schedule) return self._memory_contents
python
def _get_memory_contents(self): if self._memory_contents is not None: return self._memory_contents schedule = scheduler.minimize_peak_memory(self._graph, self._scheduler_alg) self._memory_contents = self._graph.compute_memory_contents_under_schedule( schedule) return self._memory_contents
[ "def", "_get_memory_contents", "(", "self", ")", ":", "if", "self", ".", "_memory_contents", "is", "not", "None", ":", "return", "self", ".", "_memory_contents", "schedule", "=", "scheduler", ".", "minimize_peak_memory", "(", "self", ".", "_graph", ",", "self"...
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: SolverError: the internal solver could not find a solution, or the solution found is infeasible. """ # Solve and see how well the solver did. self._cp_solver = cp_model.CpSolver() status = self._cp_solver.Solve(self._model) if status != cp_model.OPTIMAL: if status == cp_model.FEASIBLE: logging.warning("A potentially suboptimal solution was found.") else: logging.error("Solver returned status %d.", status) raise SolverError("The solver could not solve the problem and returned " "status {}.".format(status)) # TODO(joshuawang): Verify the solver's solution. if print_solution: print_cp_model_solution.print_solution(self._model, self._cp_solver) # Reconstruct layout from solution. layout = [] for mtf_dimension_name in ( self._layout_validator.splittable_mtf_dimension_names): for mesh_dimension_name in ( self._layout_validator.mesh_dimension_name_to_size): value = self._cp_solver.Value(self._global_vars[(mtf_dimension_name, mesh_dimension_name)]) if value: # Value is integer. layout.append(mtf_dimension_name + ":" + mesh_dimension_name) layout.sort() return ";".join(layout)
python
def solve(self, print_solution=False): # Solve and see how well the solver did. self._cp_solver = cp_model.CpSolver() status = self._cp_solver.Solve(self._model) if status != cp_model.OPTIMAL: if status == cp_model.FEASIBLE: logging.warning("A potentially suboptimal solution was found.") else: logging.error("Solver returned status %d.", status) raise SolverError("The solver could not solve the problem and returned " "status {}.".format(status)) # TODO(joshuawang): Verify the solver's solution. if print_solution: print_cp_model_solution.print_solution(self._model, self._cp_solver) # Reconstruct layout from solution. layout = [] for mtf_dimension_name in ( self._layout_validator.splittable_mtf_dimension_names): for mesh_dimension_name in ( self._layout_validator.mesh_dimension_name_to_size): value = self._cp_solver.Value(self._global_vars[(mtf_dimension_name, mesh_dimension_name)]) if value: # Value is integer. layout.append(mtf_dimension_name + ":" + mesh_dimension_name) layout.sort() return ";".join(layout)
[ "def", "solve", "(", "self", ",", "print_solution", "=", "False", ")", ":", "# Solve and see how well the solver did.", "self", ".", "_cp_solver", "=", "cp_model", ".", "CpSolver", "(", ")", "status", "=", "self", ".", "_cp_solver", ".", "Solve", "(", "self", ...
Solves the current integer program and returns the computed layout. Args: print_solution: An optional boolean indicating whether to print the full solution in human-readable format. Returns: The computed layout (as a string). Raises: SolverError: the internal solver could not find a solution, or the solution found is infeasible.
[ "Solves", "the", "current", "integer", "program", "and", "returns", "the", "computed", "layout", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout_optimizer.py#L285-L326
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, the objective value. """ layout_dict = {} if layout: for pair in layout.split(";"): mtf_dimension_name, mesh_dimension_name = pair.split(":", 1) if (mtf_dimension_name in self._layout_validator.splittable_mtf_dimension_names): layout_dict[mtf_dimension_name] = mesh_dimension_name else: logging.warning("Skipping unsplittable dimension %s.", mtf_dimension_name) tensor_memory = {} # {string: float}, size of each tensor under our layout for tensor_name in self._graph.get_all_tensor_names(): if self._graph.is_tensor_on_canonical_device(tensor_name): tensor_memory[tensor_name] = self._graph.get_tensor_size( tensor_name, layout_dict, self._layout_validator.mesh_dimension_name_to_size) else: tensor_memory[tensor_name] = 0.0 peak_memory_usage = 0.0 for tensor_names in self._get_memory_contents(): memory_usage = 0.0 for tensor_name in tensor_names: memory_usage += tensor_memory[tensor_name] peak_memory_usage = max(peak_memory_usage, memory_usage) return peak_memory_usage
python
def evaluate_layout(self, layout): layout_dict = {} if layout: for pair in layout.split(";"): mtf_dimension_name, mesh_dimension_name = pair.split(":", 1) if (mtf_dimension_name in self._layout_validator.splittable_mtf_dimension_names): layout_dict[mtf_dimension_name] = mesh_dimension_name else: logging.warning("Skipping unsplittable dimension %s.", mtf_dimension_name) tensor_memory = {} # {string: float}, size of each tensor under our layout for tensor_name in self._graph.get_all_tensor_names(): if self._graph.is_tensor_on_canonical_device(tensor_name): tensor_memory[tensor_name] = self._graph.get_tensor_size( tensor_name, layout_dict, self._layout_validator.mesh_dimension_name_to_size) else: tensor_memory[tensor_name] = 0.0 peak_memory_usage = 0.0 for tensor_names in self._get_memory_contents(): memory_usage = 0.0 for tensor_name in tensor_names: memory_usage += tensor_memory[tensor_name] peak_memory_usage = max(peak_memory_usage, memory_usage) return peak_memory_usage
[ "def", "evaluate_layout", "(", "self", ",", "layout", ")", ":", "layout_dict", "=", "{", "}", "if", "layout", ":", "for", "pair", "in", "layout", ".", "split", "(", "\";\"", ")", ":", "mtf_dimension_name", ",", "mesh_dimension_name", "=", "pair", ".", "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, self._last_device)) return self._last_device shape = tf.TensorShape(var.get_attr('shape')) assert shape.num_elements() is not None size = var.get_attr('dtype').size mem, device = heapq.heappop(self._mem_device_heap) mem += shape.num_elements() * size heapq.heappush(self._mem_device_heap, (mem, device)) tf.logging.debug('Place variable {} on {} and consumes {} Bytes.'.format( var.name, device, mem)) self._last_device = device return device
python
def device_function(self, var): if var.type not in ('Variable', 'VariableV2', 'VarHandleOp'): tf.logging.debug('Place {} on last device: {}.'.format( var.name, self._last_device)) return self._last_device shape = tf.TensorShape(var.get_attr('shape')) assert shape.num_elements() is not None size = var.get_attr('dtype').size mem, device = heapq.heappop(self._mem_device_heap) mem += shape.num_elements() * size heapq.heappush(self._mem_device_heap, (mem, device)) tf.logging.debug('Place variable {} on {} and consumes {} Bytes.'.format( var.name, device, mem)) self._last_device = device return device
[ "def", "device_function", "(", "self", ",", "var", ")", ":", "if", "var", ".", "type", "not", "in", "(", "'Variable'", ",", "'VariableV2'", ",", "'VarHandleOp'", ")", ":", "tf", ".", "logging", ".", "debug", "(", "'Place {} on last device: {}.'", ".", "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 logits. Shoud take: step_num - mtf Scalar ids - mtf Tensor with shape [..., length] states - list of mtf.Tensor Should return: logits - [batch, vocab_size] new_states - list of mtf.Tensor initial_ids: mtf.Tensor with shape [..., length], containing zeros. temperature: a float between 0.0 (argmax) and 1.0 (random) initial_states: list of mtf.Tensor eos_id: ID for end of sentence. forced_ids: optional mtf.Tensor with shape [..., length] use_tpu: a boolean Returns: Tensor with shape [..., length] """ length_dim = initial_ids.shape.dims[-1] mesh = initial_ids.mesh num_steps = mtf.constant(mesh, length_dim.size, dtype=tf.int32) def cond_fn(step_num, prev_ids, *unused_states): """Should we run another loop iteration.""" overflow = mtf.equal(step_num, num_steps) has_eos = mtf.reduce_any( mtf.equal(prev_ids, eos_id), reduced_dim=length_dim) all_has_eos = mtf.reduce_all(has_eos) return mtf.logical_not(mtf.logical_or(overflow, all_has_eos)) def body_fn(step_num, ids, *states): """Body function for greedy decoding. Args: step_num: a mtf.Tensor ids: a mtf.Tensor *states: additional mtf.Tensors Returns: new_step_num, new_ids, *new_states """ logits, new_states = logits_fn(step_num, ids, states) vocab_dim = logits.shape.dims[-1] new_ids = mtf.sample_with_temperature( logits, vocab_dim, temperature) if forced_ids is not None: # force the new ids to equal the partial targets where specified # (positions where partial_targets contain nonzero values) forced = mtf.gather(forced_ids, step_num, length_dim) new_ids = forced + new_ids * mtf.to_int32(mtf.equal(forced, 0)) ids += new_ids * mtf.one_hot(step_num, length_dim, dtype=tf.int32) new_step_num = step_num + 1 return [new_step_num, ids] + new_states initial_step_num = mtf.constant(mesh, 0, dtype=tf.int32) while_loop_inputs = [initial_step_num, initial_ids] + initial_states final_step_num, mtf_samples = mtf.while_loop( cond_fn, body_fn, while_loop_inputs, num_loop_vars=None if use_tpu else 2)[:2] mtf_samples = mtf.Print(mtf_samples, [final_step_num], "output_length") return mtf_samples
python
def greedy_decode(logits_fn, initial_ids, temperature=0.0, initial_states=None, eos_id=EOS_ID, forced_ids=None, use_tpu=True): length_dim = initial_ids.shape.dims[-1] mesh = initial_ids.mesh num_steps = mtf.constant(mesh, length_dim.size, dtype=tf.int32) def cond_fn(step_num, prev_ids, *unused_states): """Should we run another loop iteration.""" overflow = mtf.equal(step_num, num_steps) has_eos = mtf.reduce_any( mtf.equal(prev_ids, eos_id), reduced_dim=length_dim) all_has_eos = mtf.reduce_all(has_eos) return mtf.logical_not(mtf.logical_or(overflow, all_has_eos)) def body_fn(step_num, ids, *states): """Body function for greedy decoding. Args: step_num: a mtf.Tensor ids: a mtf.Tensor *states: additional mtf.Tensors Returns: new_step_num, new_ids, *new_states """ logits, new_states = logits_fn(step_num, ids, states) vocab_dim = logits.shape.dims[-1] new_ids = mtf.sample_with_temperature( logits, vocab_dim, temperature) if forced_ids is not None: # force the new ids to equal the partial targets where specified # (positions where partial_targets contain nonzero values) forced = mtf.gather(forced_ids, step_num, length_dim) new_ids = forced + new_ids * mtf.to_int32(mtf.equal(forced, 0)) ids += new_ids * mtf.one_hot(step_num, length_dim, dtype=tf.int32) new_step_num = step_num + 1 return [new_step_num, ids] + new_states initial_step_num = mtf.constant(mesh, 0, dtype=tf.int32) while_loop_inputs = [initial_step_num, initial_ids] + initial_states final_step_num, mtf_samples = mtf.while_loop( cond_fn, body_fn, while_loop_inputs, num_loop_vars=None if use_tpu else 2)[:2] mtf_samples = mtf.Print(mtf_samples, [final_step_num], "output_length") return mtf_samples
[ "def", "greedy_decode", "(", "logits_fn", ",", "initial_ids", ",", "temperature", "=", "0.0", ",", "initial_states", "=", "None", ",", "eos_id", "=", "EOS_ID", ",", "forced_ids", "=", "None", ",", "use_tpu", "=", "True", ")", ":", "length_dim", "=", "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 mtf.Tensor initial_ids: mtf.Tensor with shape [..., length], containing zeros. temperature: a float between 0.0 (argmax) and 1.0 (random) initial_states: list of mtf.Tensor eos_id: ID for end of sentence. forced_ids: optional mtf.Tensor with shape [..., length] use_tpu: a boolean Returns: Tensor with shape [..., length]
[ "Greedy", "decoding", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/beam_search.py#L577-L642
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 indicate padding. length indicates the length of the emitted examples. Examples with inputs/targets longer than length get truncated. TODO(noam): for text2self problems, we should just chop too-long sequences into multiple parts and train on all of them. If pack=False, then each emitted example will contain one example emitted by load_internal(). If pack=True, then multiple examples emitted by load_internal() are concatenated to form one combined example with the given length. See comments in the function pack_dataset(). batch_size indicates the number of (combined) examples per batch, across all cores. Args: dataset: a tf.data.Dataset batch_size: an integer length: an integer pack: a boolean Returns: a tf.data.Dataset where all features have fixed shape [batch, length]. """ if pack: dataset = pack_dataset(dataset, length=length) # Pad/trim length of each example to length dataset = dataset.map( functools.partial(trim_and_pad_all_features, length=length), num_parallel_calls=tf.data.experimental.AUTOTUNE ) dataset = dataset.batch(batch_size, drop_remainder=False) # Pad batch size of each batch to batch_size dataset = dataset.map( functools.partial(trim_and_pad_all_features, length=batch_size), num_parallel_calls=tf.data.experimental.AUTOTUNE ) # Remind TensorFlow of the shape dataset = dataset.map( lambda x: {k: tf.reshape(v, (batch_size, length)) for k, v in x.items()}, num_parallel_calls=tf.data.experimental.AUTOTUNE ) dataset = dataset.prefetch(100) return dataset
python
def pack_and_batch(dataset, batch_size, length, pack=True): if pack: dataset = pack_dataset(dataset, length=length) # Pad/trim length of each example to length dataset = dataset.map( functools.partial(trim_and_pad_all_features, length=length), num_parallel_calls=tf.data.experimental.AUTOTUNE ) dataset = dataset.batch(batch_size, drop_remainder=False) # Pad batch size of each batch to batch_size dataset = dataset.map( functools.partial(trim_and_pad_all_features, length=batch_size), num_parallel_calls=tf.data.experimental.AUTOTUNE ) # Remind TensorFlow of the shape dataset = dataset.map( lambda x: {k: tf.reshape(v, (batch_size, length)) for k, v in x.items()}, num_parallel_calls=tf.data.experimental.AUTOTUNE ) dataset = dataset.prefetch(100) return dataset
[ "def", "pack_and_batch", "(", "dataset", ",", "batch_size", ",", "length", ",", "pack", "=", "True", ")", ":", "if", "pack", ":", "dataset", "=", "pack_dataset", "(", "dataset", ",", "length", "=", "length", ")", "# Pad/trim length of each example to length", ...
Create a tf.data.Dataset which emits training batches. The input dataset emits feature-dictionaries where each feature is a vector of integers ending in EOS=1 The tensors in the returned tf.data.Dataset have shape [batch_size, length]. Zeros indicate padding. length indicates the length of the emitted examples. Examples with inputs/targets longer than length get truncated. TODO(noam): for text2self problems, we should just chop too-long sequences into multiple parts and train on all of them. If pack=False, then each emitted example will contain one example emitted by load_internal(). If pack=True, then multiple examples emitted by load_internal() are concatenated to form one combined example with the given length. See comments in the function pack_dataset(). batch_size indicates the number of (combined) examples per batch, across all cores. Args: dataset: a tf.data.Dataset batch_size: an integer length: an integer pack: a boolean Returns: a tf.data.Dataset where all features have fixed shape [batch, length].
[ "Create", "a", "tf", ".", "data", ".", "Dataset", "which", "emits", "training", "batches", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L98-L150
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: vocabulary.encode_tf(v) for k, v in features.items()} return dataset.map(encode, num_parallel_calls=tf.data.experimental.AUTOTUNE)
python
def encode_dataset(dataset, vocabulary): 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, append_eos=True, shuffle_buffer_size=10000, eos_id=1): """Reads parallel tab-separated text file. One example per line.""" dataset = tf.data.TextLineDataset(filenames) if dataset_split == "train": dataset = dataset.repeat() dataset = dataset.shuffle(shuffle_buffer_size) def _parse_fn(record): # pylint: disable=missing-docstring tokens = tf.decode_csv( record, record_defaults=[""] * 2, field_delim="\t", use_quote_delim=False) return {"inputs": tokens[0], "targets": tokens[1]} def _encode_fn(features): # pylint: disable=missing-docstring inputs_vocabulary = vocabulary[0] if isinstance(vocabulary, tuple) else vocabulary targets_vocabulary = vocabulary[1] if isinstance(vocabulary, tuple) else vocabulary inputs_enc = inputs_vocabulary.encode_tf(features["inputs"]) targets_enc = targets_vocabulary.encode_tf(features["targets"]) if append_eos: inputs_enc = tf.concat([tf.to_int64(inputs_enc), [eos_id]], 0) targets_enc = tf.concat([tf.to_int64(targets_enc), [eos_id]], 0) return {"inputs": inputs_enc, "targets": targets_enc} dataset = dataset.map(_parse_fn) dataset = dataset.map(_encode_fn) return pack_and_batch(dataset, batch_size, sequence_length)
python
def packed_parallel_tsv_dataset(filenames=gin.REQUIRED, dataset_split=gin.REQUIRED, batch_size=gin.REQUIRED, sequence_length=gin.REQUIRED, vocabulary=gin.REQUIRED, append_eos=True, shuffle_buffer_size=10000, eos_id=1): dataset = tf.data.TextLineDataset(filenames) if dataset_split == "train": dataset = dataset.repeat() dataset = dataset.shuffle(shuffle_buffer_size) def _parse_fn(record): # pylint: disable=missing-docstring tokens = tf.decode_csv( record, record_defaults=[""] * 2, field_delim="\t", use_quote_delim=False) return {"inputs": tokens[0], "targets": tokens[1]} def _encode_fn(features): # pylint: disable=missing-docstring inputs_vocabulary = vocabulary[0] if isinstance(vocabulary, tuple) else vocabulary targets_vocabulary = vocabulary[1] if isinstance(vocabulary, tuple) else vocabulary inputs_enc = inputs_vocabulary.encode_tf(features["inputs"]) targets_enc = targets_vocabulary.encode_tf(features["targets"]) if append_eos: inputs_enc = tf.concat([tf.to_int64(inputs_enc), [eos_id]], 0) targets_enc = tf.concat([tf.to_int64(targets_enc), [eos_id]], 0) return {"inputs": inputs_enc, "targets": targets_enc} dataset = dataset.map(_parse_fn) dataset = dataset.map(_encode_fn) return pack_and_batch(dataset, batch_size, sequence_length)
[ "def", "packed_parallel_tsv_dataset", "(", "filenames", "=", "gin", ".", "REQUIRED", ",", "dataset_split", "=", "gin", ".", "REQUIRED", ",", "batch_size", "=", "gin", ".", "REQUIRED", ",", "sequence_length", "=", "gin", ".", "REQUIRED", ",", "vocabulary", "=",...
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 boolean Returns: a tf.data.Dataset """ def my_fn(inputs, targets): if text2self: return {"targets": targets} else: return {"inputs": inputs, "targets": targets} return dataset.map(my_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)
python
def supervised_to_dict(dataset, text2self): 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.to_int64(v), [1]], 0) ret[k] = v return ret return dataset.map(my_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)
python
def encode_all_features(dataset, vocabulary): 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. The dataset is defined by sets of TFRecord files of TFExample protos. There should be a "targets" feature (a 1d tensor of integers) If not text2self, there should also be an "inputs" feature. Other features get ignored. eos_included specifies whether the inputs and targets were written with an EOS token, as in tensor2tensor Args: filenames: a list of strings text2self: a boolean eos_included: a boolean repeat: a boolean batch_size: an integer sequence_length: an integer Returns: A tf.data.Dataset of batches """ dataset = tf.data.TFRecordDataset(filenames, buffer_size=64 * 1024 * 1024) if repeat: dataset = dataset.repeat() keys = ["targets"] if text2self else ["inputs", "targets"] def decode_example(serialized_example): """Return a dict of Tensors from a serialized tensorflow.Example.""" data_fields = {} data_items_to_decoders = {} for k in keys: data_fields[k] = tf.VarLenFeature(tf.int64) data_items_to_decoders[k] = tf.contrib.slim.tfexample_decoder.Tensor(k) decoder = tf.contrib.slim.tfexample_decoder.TFExampleDecoder( data_fields, data_items_to_decoders) decode_items = list(sorted(data_items_to_decoders)) decoded = decoder.decode(serialized_example, items=decode_items) if not eos_included: decoded = [tf.concat([v, [1]], 0) for v in decoded] return dict(zip(decode_items, decoded)) dataset = dataset.map(decode_example, num_parallel_calls=tf.data.experimental.AUTOTUNE) return pack_and_batch(dataset, batch_size, sequence_length)
python
def pretokenized_tfrecord_dataset(filenames, text2self, eos_included, repeat, batch_size, sequence_length): dataset = tf.data.TFRecordDataset(filenames, buffer_size=64 * 1024 * 1024) if repeat: dataset = dataset.repeat() keys = ["targets"] if text2self else ["inputs", "targets"] def decode_example(serialized_example): """Return a dict of Tensors from a serialized tensorflow.Example.""" data_fields = {} data_items_to_decoders = {} for k in keys: data_fields[k] = tf.VarLenFeature(tf.int64) data_items_to_decoders[k] = tf.contrib.slim.tfexample_decoder.Tensor(k) decoder = tf.contrib.slim.tfexample_decoder.TFExampleDecoder( data_fields, data_items_to_decoders) decode_items = list(sorted(data_items_to_decoders)) decoded = decoder.decode(serialized_example, items=decode_items) if not eos_included: decoded = [tf.concat([v, [1]], 0) for v in decoded] return dict(zip(decode_items, decoded)) dataset = dataset.map(decode_example, num_parallel_calls=tf.data.experimental.AUTOTUNE) return pack_and_batch(dataset, batch_size, sequence_length)
[ "def", "pretokenized_tfrecord_dataset", "(", "filenames", ",", "text2self", ",", "eos_included", ",", "repeat", ",", "batch_size", ",", "sequence_length", ")", ":", "dataset", "=", "tf", ".", "data", ".", "TFRecordDataset", "(", "filenames", ",", "buffer_size", ...
Reads tensor2tensor-style data files. The dataset is defined by sets of TFRecord files of TFExample protos. There should be a "targets" feature (a 1d tensor of integers) If not text2self, there should also be an "inputs" feature. Other features get ignored. eos_included specifies whether the inputs and targets were written with an EOS token, as in tensor2tensor Args: filenames: a list of strings text2self: a boolean eos_included: a boolean repeat: a boolean batch_size: an integer sequence_length: an integer Returns: A tf.data.Dataset of batches
[ "Reads", "tensor2tensor", "-", "style", "data", "files", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L330-L376
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, vocabulary=None): """Loads the Tensor2tensor dataset specified by dataset_name. Args: dataset_name: TensorFlow Datasets dataset name. text2self: a boolean data_dir: string, data_dir for TensorFlow Datasets dataset_split: a string - "train" or "dev" batch_size: an integer sequence_length: an integer vocabulary: ignored Returns: A tf.data.Dataset of batches """ del vocabulary filepattern = os.path.join( data_dir, dataset_name + "-" + dataset_split + "-*") filenames = tf.gfile.Glob(filepattern) tf.logging.info("Found %s files matching %s" % (len(filenames), filepattern)) if not filenames: raise ValueError("No matching files found") dataset = pretokenized_tfrecord_dataset( filenames=filenames, text2self=text2self, eos_included=True, repeat=dataset_split == "train", batch_size=batch_size, sequence_length=sequence_length) if dataset_split == "train": dataset = dataset.shuffle(1000) return dataset
python
def pretokenized_t2t_dataset(dataset_name=gin.REQUIRED, text2self=False, data_dir=gin.REQUIRED, dataset_split="train", batch_size=gin.REQUIRED, sequence_length=gin.REQUIRED, vocabulary=None): del vocabulary filepattern = os.path.join( data_dir, dataset_name + "-" + dataset_split + "-*") filenames = tf.gfile.Glob(filepattern) tf.logging.info("Found %s files matching %s" % (len(filenames), filepattern)) if not filenames: raise ValueError("No matching files found") dataset = pretokenized_tfrecord_dataset( filenames=filenames, text2self=text2self, eos_included=True, repeat=dataset_split == "train", batch_size=batch_size, sequence_length=sequence_length) if dataset_split == "train": dataset = dataset.shuffle(1000) return dataset
[ "def", "pretokenized_t2t_dataset", "(", "dataset_name", "=", "gin", ".", "REQUIRED", ",", "text2self", "=", "False", ",", "data_dir", "=", "gin", ".", "REQUIRED", ",", "dataset_split", "=", "\"train\"", ",", "batch_size", "=", "gin", ".", "REQUIRED", ",", "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: ignored Returns: A tf.data.Dataset of batches
[ "Loads", "the", "Tensor2tensor", "dataset", "specified", "by", "dataset_name", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L380-L417
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 efficiently on TPU. Each example in the output dataset represents several examples in the input dataset. For each key in the input dataset, two additional keys are created: <key>_segmentation: an int32 tensor identifying the parts representing the original example. <key>_position: an int32 tensor identifying the position within the original example. Example: Two input examples get combined to form an output example. The input examples are: {"inputs": [8, 7, 1, 0], "targets":[4, 1, 0]} {"inputs": [2, 3, 4, 1], "targets":[5, 6, 1]} The output example is: { "inputs": [8, 7, 1, 2, 3, 4, 1, 0, 0, 0] "inputs_segmentation": [1, 1, 1, 2, 2, 2, 2, 0, 0, 0] "inputs_position": [0, 1, 2, 0, 1, 2, 3, 0, 0, 0] "targets": [4, 1, 5, 6, 1, 0, 0, 0, 0, 0] "targets_segmentation": [1, 1, 2, 2, 2, 0, 0, 0, 0, 0] "targets_position": [0, 1, 0, 1, 2, 0, 0, 0, 0, 0] } 0 represents padding in both the inputs and the outputs. Sequences in the incoming examples are truncated to length "length", and the sequences in the output examples all have fixed (padded) length "length". Args: dataset: a tf.data.Dataset length: an integer keys: a list of strings (e.g. ["inputs", "targets"]) use_custom_ops: a boolean - custom ops are faster but require a custom-built binary, which is not currently possible on cloud-tpu. Returns: a tf.data.Dataset """ shapes = dataset.output_shapes if keys is None: keys = shapes.keys() for k in keys: if k not in shapes: raise ValueError("Key %s not found in dataset. Available keys are %s" % (k, shapes.keys())) if not shapes[k].is_compatible_with(tf.TensorShape([None])): raise ValueError("Tensors to be packed must be one-dimensional.") # trim to length dataset = dataset.map(lambda x: {k: x[k][:length] for k in keys}, num_parallel_calls=tf.data.experimental.AUTOTUNE) # Setting batch_size=length ensures that the concatenated sequences (if they # have length >=1) are sufficient to fill at least one packed example. batch_size = length dataset = dataset.padded_batch( batch_size, padded_shapes={k: [-1] for k in keys}) if use_custom_ops and len(keys) <= 2: return _pack_with_custom_ops(dataset, keys, length) else: return _pack_with_tf_ops(dataset, keys, length)
python
def pack_dataset(dataset, length, keys=None, use_custom_ops=False): shapes = dataset.output_shapes if keys is None: keys = shapes.keys() for k in keys: if k not in shapes: raise ValueError("Key %s not found in dataset. Available keys are %s" % (k, shapes.keys())) if not shapes[k].is_compatible_with(tf.TensorShape([None])): raise ValueError("Tensors to be packed must be one-dimensional.") # trim to length dataset = dataset.map(lambda x: {k: x[k][:length] for k in keys}, num_parallel_calls=tf.data.experimental.AUTOTUNE) # Setting batch_size=length ensures that the concatenated sequences (if they # have length >=1) are sufficient to fill at least one packed example. batch_size = length dataset = dataset.padded_batch( batch_size, padded_shapes={k: [-1] for k in keys}) if use_custom_ops and len(keys) <= 2: return _pack_with_custom_ops(dataset, keys, length) else: return _pack_with_tf_ops(dataset, keys, length)
[ "def", "pack_dataset", "(", "dataset", ",", "length", ",", "keys", "=", "None", ",", "use_custom_ops", "=", "False", ")", ":", "shapes", "=", "dataset", ".", "output_shapes", "if", "keys", "is", "None", ":", "keys", "=", "shapes", ".", "keys", "(", ")"...
Creates a 'packed' version of a dataset on-the-fly. Borrowed from the tensor2tensor library. TODO(noam): make this faster This is meant to replace the irritation of having to create a separate "packed" version of a dataset to train efficiently on TPU. Each example in the output dataset represents several examples in the input dataset. For each key in the input dataset, two additional keys are created: <key>_segmentation: an int32 tensor identifying the parts representing the original example. <key>_position: an int32 tensor identifying the position within the original example. Example: Two input examples get combined to form an output example. The input examples are: {"inputs": [8, 7, 1, 0], "targets":[4, 1, 0]} {"inputs": [2, 3, 4, 1], "targets":[5, 6, 1]} The output example is: { "inputs": [8, 7, 1, 2, 3, 4, 1, 0, 0, 0] "inputs_segmentation": [1, 1, 1, 2, 2, 2, 2, 0, 0, 0] "inputs_position": [0, 1, 2, 0, 1, 2, 3, 0, 0, 0] "targets": [4, 1, 5, 6, 1, 0, 0, 0, 0, 0] "targets_segmentation": [1, 1, 2, 2, 2, 0, 0, 0, 0, 0] "targets_position": [0, 1, 0, 1, 2, 0, 0, 0, 0, 0] } 0 represents padding in both the inputs and the outputs. Sequences in the incoming examples are truncated to length "length", and the sequences in the output examples all have fixed (padded) length "length". Args: dataset: a tf.data.Dataset length: an integer keys: a list of strings (e.g. ["inputs", "targets"]) use_custom_ops: a boolean - custom ops are faster but require a custom-built binary, which is not currently possible on cloud-tpu. Returns: a tf.data.Dataset
[ "Creates", "a", "packed", "version", "of", "a", "dataset", "on", "-", "the", "-", "fly", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L421-L490
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.name, str) or not isinstance(d.size, int): raise ValueError("Bad dimension %s" % (d,)) return d name, size = d if isinstance(name, str) and isinstance(size, int): return Dimension(name, size) else: raise ValueError("could not convert %s to Dimension" % (d,))
python
def convert_to_dimension(d): if d is None: return None if isinstance(d, Dimension): if not isinstance(d.name, str) or not isinstance(d.size, int): raise ValueError("Bad dimension %s" % (d,)) return d name, size = d if isinstance(name, str) and isinstance(size, int): return Dimension(name, size) else: raise ValueError("could not convert %s to Dimension" % (d,))
[ "def", "convert_to_dimension", "(", "d", ")", ":", "if", "d", "is", "None", ":", "return", "None", "if", "isinstance", "(", "d", ",", "Dimension", ")", ":", "if", "not", "isinstance", "(", "d", ".", "name", ",", "str", ")", "or", "not", "isinstance",...
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_list_of_pairs(x, seconds_to_int=True) return Shape(x)
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. splittable_dims is a list of Dimensions which can be split while keeping the computation valid. Args: tf_fn: a function taking n tf.Tensors and returning a tf.Tensor xs: a list of n Tensors output_shape: a Shape (or list of shapes) output_dtype: a dtype (or list of dtypes) splittable_dims: a list of Dimensions which are ok to split grad_function: an optional gradients function. If None, use tf gradient. name: an optional string Returns: a Tensor (or a tuple of Tensors) """ multiple_outputs = isinstance(output_dtype, list) output_shapes = output_shape if multiple_outputs else [output_shape] output_dtypes = output_dtype if multiple_outputs else [output_dtype] op = SlicewiseOperation( tf_fn, xs, [convert_to_shape(shape) or xs[0].shape for shape in output_shapes], [dtype or xs[0].dtype for dtype in output_dtypes], splittable_dims, grad_function, name=name) return tuple(op.outputs) if multiple_outputs else op.outputs[0]
python
def slicewise(tf_fn, xs, output_shape=None, output_dtype=None, splittable_dims=None, grad_function=None, name=None): multiple_outputs = isinstance(output_dtype, list) output_shapes = output_shape if multiple_outputs else [output_shape] output_dtypes = output_dtype if multiple_outputs else [output_dtype] op = SlicewiseOperation( tf_fn, xs, [convert_to_shape(shape) or xs[0].shape for shape in output_shapes], [dtype or xs[0].dtype for dtype in output_dtypes], splittable_dims, grad_function, name=name) return tuple(op.outputs) if multiple_outputs else op.outputs[0]
[ "def", "slicewise", "(", "tf_fn", ",", "xs", ",", "output_shape", "=", "None", ",", "output_dtype", "=", "None", ",", "splittable_dims", "=", "None", ",", "grad_function", "=", "None", ",", "name", "=", "None", ")", ":", "multiple_outputs", "=", "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 output_shape: a Shape (or list of shapes) output_dtype: a dtype (or list of dtypes) splittable_dims: a list of Dimensions which are ok to split grad_function: an optional gradients function. If None, use tf gradient. name: an optional string Returns: a Tensor (or a tuple of Tensors)
[ "Slice", "-", "wise", "call", "to", "any", "tensorflow", "function", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1568-L1605
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 function name: an optional string Returns: a Tensor """ return slicewise( tf_fn, xs, output_dtype=output_dtype, splittable_dims=xs[0].shape.dims, grad_function=grad_function, name=name or "cwise")
python
def cwise(tf_fn, xs, output_dtype=None, grad_function=None, name=None): 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 """ if not isinstance(x1, Tensor) and not isinstance(x2, Tensor): raise ValueError("at least one of x1 and x2 must be an mtf Tensor") elif isinstance(x1, Tensor) and isinstance(x2, Tensor): return x1, x2 elif isinstance(x1, Tensor): return x1, import_tf_tensor( x1.mesh, tf.convert_to_tensor(x2, dtype=x1.dtype), Shape([])) else: return import_tf_tensor(x2.mesh, tf.convert_to_tensor(x1, dtype=x2.dtype), Shape([])), x2
python
def binary_arguments_to_tensors(x1, x2): if not isinstance(x1, Tensor) and not isinstance(x2, Tensor): raise ValueError("at least one of x1 and x2 must be an mtf Tensor") elif isinstance(x1, Tensor) and isinstance(x2, Tensor): return x1, x2 elif isinstance(x1, Tensor): return x1, import_tf_tensor( x1.mesh, tf.convert_to_tensor(x2, dtype=x1.dtype), Shape([])) else: return import_tf_tensor(x2.mesh, tf.convert_to_tensor(x1, dtype=x2.dtype), Shape([])), x2
[ "def", "binary_arguments_to_tensors", "(", "x1", ",", "x2", ")", ":", "if", "not", "isinstance", "(", "x1", ",", "Tensor", ")", "and", "not", "isinstance", "(", "x2", ",", "Tensor", ")", ":", "raise", "ValueError", "(", "\"at least one of x1 and x2 must be an ...
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="minimum"): x1, x2 = binary_arguments_to_tensors(x1, x2) return MinMaxOperation( tf.minimum, x1, x2, output_shape=_infer_binary_broadcast_shape( x1.shape, x2.shape, output_shape)).outputs[0]
python
def minimum(x1, x2, output_shape=None, name=None): output_shape = convert_to_shape(output_shape) with tf.name_scope(name, default_name="minimum"): x1, x2 = binary_arguments_to_tensors(x1, x2) return MinMaxOperation( tf.minimum, x1, x2, output_shape=_infer_binary_broadcast_shape( x1.shape, x2.shape, output_shape)).outputs[0]
[ "def", "minimum", "(", "x1", ",", "x2", ",", "output_shape", "=", "None", ",", "name", "=", "None", ")", ":", "output_shape", "=", "convert_to_shape", "(", "output_shape", ")", "with", "tf", ".", "name_scope", "(", "name", ",", "default_name", "=", "\"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 Tensors. """ return SplitOperation(x, split_dim, num_or_size_splits, name=name).outputs
python
def split(x, split_dim, num_or_size_splits, name=None): 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: a Tensor """ ret = StackOperation(xs, dim_name, axis, name).outputs[0] return ret
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.shape.rename_dimension(dim.name, new_name) comparator = less if exclusive else less_equal m = cast( comparator(mtf_range(x.mesh, dim, dtype=tf.float32), mtf_range(x.mesh, new_dim, dtype=tf.float32)), x.dtype) ret = einsum([x, m], output_shape=new_shape) return reshape(ret, x.shape)
python
def cumsum(x, dim, exclusive=False): with tf.variable_scope("cumsum"): new_name = "tmp_dim_cumsum" new_dim = Dimension(new_name, dim.size) new_shape = x.shape.rename_dimension(dim.name, new_name) comparator = less if exclusive else less_equal m = cast( comparator(mtf_range(x.mesh, dim, dtype=tf.float32), mtf_range(x.mesh, new_dim, dtype=tf.float32)), x.dtype) ret = einsum([x, m], output_shape=new_shape) return reshape(ret, x.shape)
[ "def", "cumsum", "(", "x", ",", "dim", ",", "exclusive", "=", "False", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"cumsum\"", ")", ":", "new_name", "=", "\"tmp_dim_cumsum\"", "new_dim", "=", "Dimension", "(", "new_name", ",", "dim", ".", "size...
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 optional string Returns: a Tensor with the same shape and dtype as x """ return ShiftOperation(x, offset, dim, wrap, name=name).outputs[0]
python
def shift(x, offset, dim, wrap, name=None): return ShiftOperation(x, offset, dim, wrap, name=name).outputs[0]
[ "def", "shift", "(", "x", ",", "offset", ",", "dim", ",", "wrap", ",", "name", "=", "None", ")", ":", "return", "ShiftOperation", "(", "x", ",", "offset", ",", "dim", ",", "wrap", ",", "name", "=", "name", ")", ".", "outputs", "[", "0", "]" ]
Shift operation. Shift x right by +offset in dimension dim. Args: x: a Tensor offset: an integer. If negative, shift left instead of right. dim: a Dimension of x wrap: a boolean - whether to wrap (True) or pad with zeros (False). name: an optional string Returns: a Tensor with the same shape and dtype as x
[ "Shift", "operation", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L2755-L2770
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 string Returns: a mtf.Tensor """ return ImportLaidOutTensorOperation( mesh, laid_out_tensor, convert_to_shape(shape), name=name).outputs[0]
python
def import_laid_out_tensor(mesh, laid_out_tensor, shape, name=None): 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 (uses the existing tf.variable_scope()) shape: a Shape dtype: a VariableDType or a tf.DType master_dtype: an optional tf.DType (deprecated - use dtype arg) slice_dtype: an optional tf.DType (deprecated - use dtype arg) activation_dtype: an optional tf.DType (deprecated - use dtype arg) initializer: an optional tf initializer function trainable: a boolean **kwargs: additional keyword arguments to tf.get_variable Returns: a Tensor with the given shape and dtype equal to dtype.activation_dtype """ if dtype is None: dtype = VariableDType(master_dtype, slice_dtype, activation_dtype) elif isinstance(dtype, tf.DType): dtype = VariableDType( master_dtype or dtype, slice_dtype or dtype, activation_dtype or dtype) elif not isinstance(dtype, VariableDType): raise ValueError("dtype should be a tf.dtype or a mtf.VariableDType") scope_name = tf.get_variable_scope().name if scope_name: full_name = scope_name + "/" + name else: full_name = name if full_name in mesh.graph.name_to_variable: var = mesh.graph.name_to_variable[full_name] else: var = Variable( mesh, name, convert_to_shape(shape), dtype, initializer, trainable, **kwargs) if var.name != full_name: raise ValueError( "Expected var.name == full_name. %s vs %s" % (var.name, full_name)) mesh.graph.name_to_variable[full_name] = var return var.outputs[0]
python
def get_variable(mesh, name, shape, dtype=tf.float32, master_dtype=None, slice_dtype=None, activation_dtype=None, initializer=None, trainable=True, **kwargs): if dtype is None: dtype = VariableDType(master_dtype, slice_dtype, activation_dtype) elif isinstance(dtype, tf.DType): dtype = VariableDType( master_dtype or dtype, slice_dtype or dtype, activation_dtype or dtype) elif not isinstance(dtype, VariableDType): raise ValueError("dtype should be a tf.dtype or a mtf.VariableDType") scope_name = tf.get_variable_scope().name if scope_name: full_name = scope_name + "/" + name else: full_name = name if full_name in mesh.graph.name_to_variable: var = mesh.graph.name_to_variable[full_name] else: var = Variable( mesh, name, convert_to_shape(shape), dtype, initializer, trainable, **kwargs) if var.name != full_name: raise ValueError( "Expected var.name == full_name. %s vs %s" % (var.name, full_name)) mesh.graph.name_to_variable[full_name] = var return var.outputs[0]
[ "def", "get_variable", "(", "mesh", ",", "name", ",", "shape", ",", "dtype", "=", "tf", ".", "float32", ",", "master_dtype", "=", "None", ",", "slice_dtype", "=", "None", ",", "activation_dtype", "=", "None", ",", "initializer", "=", "None", ",", "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 - use dtype arg) activation_dtype: an optional tf.DType (deprecated - use dtype arg) initializer: an optional tf initializer function trainable: a boolean **kwargs: additional keyword arguments to tf.get_variable Returns: a Tensor with the given shape and dtype equal to dtype.activation_dtype
[ "Create", "a", "new", "variable", "or", "retrieve", "an", "already", "-", "created", "one", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3210-L3253
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: ValueError: if var is not a Variable and var.operation is not a Variable """ if isinstance(var, Tensor): var = var.operation if not isinstance(var, Variable): raise ValueError("var must be a mtf.Variable or its output Tensor.") return Assign([var], [new_val], assign_fn=assign_fn)
python
def assign(var, new_val, assign_fn=assign_slice): 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 not a Variable
[ "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, **kwargs).outputs[0]
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: tensor_or_shape: a Tensor or a Shape old_dim_or_dims: a Dimension or a list of Dimensions new_dim_or_dims: a Dimensions or a list of Dimensions Returns: a new Tensor or a Shape """ if isinstance(tensor_or_shape, Tensor): return reshape(tensor_or_shape, replace_dimensions( tensor_or_shape.shape, old_dim_or_dims, new_dim_or_dims)) if not isinstance(tensor_or_shape, Shape): raise ValueError( "tensor_or_shape must be a Tensor or Shape got %s" % (tensor_or_shape,)) in_dims = tensor_or_shape.dims if isinstance(old_dim_or_dims, Dimension): old_dim_or_dims = [old_dim_or_dims] if isinstance(new_dim_or_dims, Dimension): new_dim_or_dims = [new_dim_or_dims] if not isinstance(old_dim_or_dims, list) or not old_dim_or_dims: raise ValueError( "old_dim_or_dims must be a Dimension or a list of Dimension got %s" % (old_dim_or_dims,)) if not isinstance(new_dim_or_dims, list) or not new_dim_or_dims: raise ValueError( "new_dim_or_dims must be a Dimension or a list of Dimension got %s" % (new_dim_or_dims,)) try: positions = [in_dims.index(d) for d in old_dim_or_dims] pos = positions[0] if positions != list(range(pos, pos + len(positions))): raise ValueError() except ValueError: raise ValueError( "old_dim_or_dims must be a subsequence of the input's dimensions" " old_dim_or_dims=%s input's dimensions=%s" % (old_dim_or_dims, in_dims)) return Shape(in_dims[:pos] + new_dim_or_dims + in_dims[pos + len(old_dim_or_dims):])
python
def replace_dimensions(tensor_or_shape, old_dim_or_dims, new_dim_or_dims): if isinstance(tensor_or_shape, Tensor): return reshape(tensor_or_shape, replace_dimensions( tensor_or_shape.shape, old_dim_or_dims, new_dim_or_dims)) if not isinstance(tensor_or_shape, Shape): raise ValueError( "tensor_or_shape must be a Tensor or Shape got %s" % (tensor_or_shape,)) in_dims = tensor_or_shape.dims if isinstance(old_dim_or_dims, Dimension): old_dim_or_dims = [old_dim_or_dims] if isinstance(new_dim_or_dims, Dimension): new_dim_or_dims = [new_dim_or_dims] if not isinstance(old_dim_or_dims, list) or not old_dim_or_dims: raise ValueError( "old_dim_or_dims must be a Dimension or a list of Dimension got %s" % (old_dim_or_dims,)) if not isinstance(new_dim_or_dims, list) or not new_dim_or_dims: raise ValueError( "new_dim_or_dims must be a Dimension or a list of Dimension got %s" % (new_dim_or_dims,)) try: positions = [in_dims.index(d) for d in old_dim_or_dims] pos = positions[0] if positions != list(range(pos, pos + len(positions))): raise ValueError() except ValueError: raise ValueError( "old_dim_or_dims must be a subsequence of the input's dimensions" " old_dim_or_dims=%s input's dimensions=%s" % (old_dim_or_dims, in_dims)) return Shape(in_dims[:pos] + new_dim_or_dims + in_dims[pos + len(old_dim_or_dims):])
[ "def", "replace_dimensions", "(", "tensor_or_shape", ",", "old_dim_or_dims", ",", "new_dim_or_dims", ")", ":", "if", "isinstance", "(", "tensor_or_shape", ",", "Tensor", ")", ":", "return", "reshape", "(", "tensor_or_shape", ",", "replace_dimensions", "(", "tensor_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 of Dimensions new_dim_or_dims: a Dimensions or a list of Dimensions Returns: a new Tensor or a Shape
[ "Replace", "dimensions", "in", "a", "Tensor", "or", "Shape", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3590-L3634
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 multiplication: x has shape [a, b] y has shape [b, c] matmul(x, y) == einsum([x, y], output_shape=[a, c]) We provide a few options for specifying the output shape: If neither output_shape nor reduced_dims is specified, then the output shape is set to the contain all dimensions that appear exactly once in the inputs, in order of appearance. If output_shape is not specified, then the output shape is set to the contain all dimensions that appear in xs but not in reduced_dims, in the order that they appear in xs. If reduced_dims is also not specified, then reduced_dims is set to the set of all dimensions that appear at least twice in xs. If both output_shape and reduced_dims are specified, then we check that reduced_dims matches the set of dimensions present in xs but not in output_shape, and throw an exception if it does not. This helps to reduce bugs. Args: xs: a list of Tensors output_shape: an optional Shape. reduced_dims: an optional list of Dimensions. name: an optional string Returns: a Tensor Raises: ValueError: if reduced_dims contradicts output_shape """ output_shape = convert_to_shape(output_shape) input_dim_count = collections.defaultdict(int) input_dims = [] for x in xs: for d in x.shape.dims: if d not in input_dim_count: input_dims.append(d) input_dim_count[d] += 1 if output_shape is None: if reduced_dims is None: reduced_dims = [d for d, c in six.iteritems(input_dim_count) if c > 1] output_shape = Shape([d for d in input_dims if d not in reduced_dims]) elif reduced_dims is not None: for d in reduced_dims: if not isinstance(d, Dimension): raise ValueError("reduced_dims must be a list of Dimensions. Got %s." % (reduced_dims,)) computed_reduced_dims = [ d for d in input_dims if d not in output_shape.dims] if set(computed_reduced_dims) != set(reduced_dims): raise ValueError( "Specified reduced_dims and output_shape do not match." " xs=%s output_shape=%s reduced_dims=%s " % ( xs, output_shape, reduced_dims)) return EinsumOperation(xs, output_shape, name=name).outputs[0]
python
def einsum(xs, output_shape=None, reduced_dims=None, name=None): output_shape = convert_to_shape(output_shape) input_dim_count = collections.defaultdict(int) input_dims = [] for x in xs: for d in x.shape.dims: if d not in input_dim_count: input_dims.append(d) input_dim_count[d] += 1 if output_shape is None: if reduced_dims is None: reduced_dims = [d for d, c in six.iteritems(input_dim_count) if c > 1] output_shape = Shape([d for d in input_dims if d not in reduced_dims]) elif reduced_dims is not None: for d in reduced_dims: if not isinstance(d, Dimension): raise ValueError("reduced_dims must be a list of Dimensions. Got %s." % (reduced_dims,)) computed_reduced_dims = [ d for d in input_dims if d not in output_shape.dims] if set(computed_reduced_dims) != set(reduced_dims): raise ValueError( "Specified reduced_dims and output_shape do not match." " xs=%s output_shape=%s reduced_dims=%s " % ( xs, output_shape, reduced_dims)) return EinsumOperation(xs, output_shape, name=name).outputs[0]
[ "def", "einsum", "(", "xs", ",", "output_shape", "=", "None", ",", "reduced_dims", "=", "None", ",", "name", "=", "None", ")", ":", "output_shape", "=", "convert_to_shape", "(", "output_shape", ")", "input_dim_count", "=", "collections", ".", "defaultdict", ...
Einstein summation. einsum(xs, output_shape) is equivalent to broadcasting all inputs to the union of all of their shapes, multiplying them componentwise, and finally reduce_summing down to output_shape. One common case of this is matrix multiplication: x has shape [a, b] y has shape [b, c] matmul(x, y) == einsum([x, y], output_shape=[a, c]) We provide a few options for specifying the output shape: If neither output_shape nor reduced_dims is specified, then the output shape is set to the contain all dimensions that appear exactly once in the inputs, in order of appearance. If output_shape is not specified, then the output shape is set to the contain all dimensions that appear in xs but not in reduced_dims, in the order that they appear in xs. If reduced_dims is also not specified, then reduced_dims is set to the set of all dimensions that appear at least twice in xs. If both output_shape and reduced_dims are specified, then we check that reduced_dims matches the set of dimensions present in xs but not in output_shape, and throw an exception if it does not. This helps to reduce bugs. Args: xs: a list of Tensors output_shape: an optional Shape. reduced_dims: an optional list of Dimensions. name: an optional string Returns: a Tensor Raises: ValueError: if reduced_dims contradicts output_shape
[ "Einstein", "summation", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3637-L3700
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" % (reduced_dim, x.shape)) return x.shape - reduced_dim if reduced_dim is not None: if [reduced_dim] != [d for d in x.shape.dims if d not in output_shape.dims]: raise ValueError( "reduced_dim contradicts output_shape:" "x=%s output_shape=%s reduced_dim=%s" % (x, output_shape, reduced_dim)) return output_shape
python
def _reduction_output_shape(x, output_shape, reduced_dim): if output_shape is None: if reduced_dim is None: return Shape([]) else: if reduced_dim not in x.shape.dims: raise ValueError( "reduced_dim=%s not in x.shape.dims=%s" % (reduced_dim, x.shape)) return x.shape - reduced_dim if reduced_dim is not None: if [reduced_dim] != [d for d in x.shape.dims if d not in output_shape.dims]: raise ValueError( "reduced_dim contradicts output_shape:" "x=%s output_shape=%s reduced_dim=%s" % (x, output_shape, reduced_dim)) return output_shape
[ "def", "_reduction_output_shape", "(", "x", ",", "output_shape", ",", "reduced_dim", ")", ":", "if", "output_shape", "is", "None", ":", "if", "reduced_dim", "is", "None", ":", "return", "Shape", "(", "[", "]", ")", "else", ":", "if", "reduced_dim", "not", ...
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, reduced_dim=reduced_dim) """ reduced_dim = convert_to_dimension(reduced_dim) with tf.name_scope(name, default_name="top_1"): max_val = reduce_max(x, reduced_dim=reduced_dim) is_max = to_float(equal(x, max_val)) pos = mtf_range(x.mesh, reduced_dim, tf.float32) ret = reduce_max(is_max * pos, reduced_dim=reduced_dim) ret = cast(ret, dtype) return ret, max_val
python
def top_1(x, reduced_dim, dtype=tf.int32, name=None): reduced_dim = convert_to_dimension(reduced_dim) with tf.name_scope(name, default_name="top_1"): max_val = reduce_max(x, reduced_dim=reduced_dim) is_max = to_float(equal(x, max_val)) pos = mtf_range(x.mesh, reduced_dim, tf.float32) ret = reduce_max(is_max * pos, reduced_dim=reduced_dim) ret = cast(ret, dtype) return ret, max_val
[ "def", "top_1", "(", "x", ",", "reduced_dim", ",", "dtype", "=", "tf", ".", "int32", ",", "name", "=", "None", ")", ":", "reduced_dim", "=", "convert_to_dimension", "(", "reduced_dim", ")", "with", "tf", ".", "name_scope", "(", "name", ",", "default_name...
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. new_dim: a Dimension. The size determines k. dtype: optional dtype for indices. name: optional string. Returns: indices: a Tensor with given dtype. values: a Tensor with same type as x. """ reduced_dim = convert_to_dimension(reduced_dim) new_dim = convert_to_dimension(new_dim) indices = [] values = [] k = new_dim.size with tf.name_scope(name, default_name="top_k"): for i in xrange(k): max_index, max_val = top_1(x, reduced_dim, dtype) indices.append(max_index) values.append(max_val) if i + 1 < k: x += one_hot(max_index, reduced_dim, on_value=-1e9, dtype=x.dtype) axis = x.shape.dims.index(reduced_dim) return stack(indices, new_dim.name, axis), stack(values, new_dim.name, axis)
python
def top_k(x, reduced_dim, new_dim, dtype=tf.int32, name=None): reduced_dim = convert_to_dimension(reduced_dim) new_dim = convert_to_dimension(new_dim) indices = [] values = [] k = new_dim.size with tf.name_scope(name, default_name="top_k"): for i in xrange(k): max_index, max_val = top_1(x, reduced_dim, dtype) indices.append(max_index) values.append(max_val) if i + 1 < k: x += one_hot(max_index, reduced_dim, on_value=-1e9, dtype=x.dtype) axis = x.shape.dims.index(reduced_dim) return stack(indices, new_dim.name, axis), stack(values, new_dim.name, axis)
[ "def", "top_k", "(", "x", ",", "reduced_dim", ",", "new_dim", ",", "dtype", "=", "tf", ".", "int32", ",", "name", "=", "None", ")", ":", "reduced_dim", "=", "convert_to_dimension", "(", "reduced_dim", ")", "new_dim", "=", "convert_to_dimension", "(", "new_...
Like tf.top_k. This operation returns two tensors with the same shape. The output shape is identical to the shape of x, except that reduced_dim is replaced by new_dim. Args: x: a Tensor reduced_dim: a Dimension in x.shape.dims. new_dim: a Dimension. The size determines k. dtype: optional dtype for indices. name: optional string. Returns: indices: a Tensor with given dtype. values: a Tensor with same type as x.
[ "Like", "tf", ".", "top_k", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3902-L3932
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 ScalarAddOperation(x1, x2).outputs[0] with tf.name_scope(name, default_name="add"): x1, x2 = binary_arguments_to_tensors(x1, x2) return AddOperation( x1, x2, output_shape=_infer_binary_broadcast_shape( x1.shape, x2.shape, output_shape)).outputs[0]
python
def add(x1, x2, output_shape=None, name=None): output_shape = convert_to_shape(output_shape) if not isinstance(x2, Tensor): return ScalarAddOperation(x1, x2).outputs[0] with tf.name_scope(name, default_name="add"): x1, x2 = binary_arguments_to_tensors(x1, x2) return AddOperation( x1, x2, output_shape=_infer_binary_broadcast_shape( x1.shape, x2.shape, output_shape)).outputs[0]
[ "def", "add", "(", "x1", ",", "x2", ",", "output_shape", "=", "None", ",", "name", "=", "None", ")", ":", "output_shape", "=", "convert_to_shape", "(", "output_shape", ")", "if", "not", "isinstance", "(", "x2", ",", "Tensor", ")", ":", "return", "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 ScalarAddOperation(x1, -x2).outputs[0] with tf.name_scope(name, default_name="sub"): x1, x2 = binary_arguments_to_tensors(x1, x2) return add(x1, negative(x2), output_shape=output_shape)
python
def sub(x1, x2, output_shape=None, name=None): output_shape = convert_to_shape(output_shape) if not isinstance(x2, Tensor): return ScalarAddOperation(x1, -x2).outputs[0] with tf.name_scope(name, default_name="sub"): x1, x2 = binary_arguments_to_tensors(x1, x2) return add(x1, negative(x2), output_shape=output_shape)
[ "def", "sub", "(", "x1", ",", "x2", ",", "output_shape", "=", "None", ",", "name", "=", "None", ")", ":", "output_shape", "=", "convert_to_shape", "(", "output_shape", ")", "if", "not", "isinstance", "(", "x2", ",", "Tensor", ")", ":", "return", "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[0] with tf.name_scope(name, default_name="mul"): x1, x2 = binary_arguments_to_tensors(x1, x2) return einsum( [x1, x2], output_shape=_infer_binary_broadcast_shape( x1.shape, x2.shape, output_shape))
python
def multiply(x1, x2, output_shape=None, name=None): if not isinstance(x2, Tensor): return ScalarMultiplyOperation(x1, x2).outputs[0] with tf.name_scope(name, default_name="mul"): x1, x2 = binary_arguments_to_tensors(x1, x2) return einsum( [x1, x2], output_shape=_infer_binary_broadcast_shape( x1.shape, x2.shape, output_shape))
[ "def", "multiply", "(", "x1", ",", "x2", ",", "output_shape", "=", "None", ",", "name", "=", "None", ")", ":", "if", "not", "isinstance", "(", "x2", ",", "Tensor", ")", ":", "return", "ScalarMultiplyOperation", "(", "x1", ",", "x2", ")", ".", "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 ScalarMultiplyOperation(x1, 1.0 / x2).outputs[0] with tf.name_scope(name, default_name="divide"): x1, x2 = binary_arguments_to_tensors(x1, x2) return multiply(x1, reciprocal(x2), output_shape=output_shape)
python
def divide(x1, x2, output_shape=None, name=None): output_shape = convert_to_shape(output_shape) if not isinstance(x2, Tensor): return ScalarMultiplyOperation(x1, 1.0 / x2).outputs[0] with tf.name_scope(name, default_name="divide"): x1, x2 = binary_arguments_to_tensors(x1, x2) return multiply(x1, reciprocal(x2), output_shape=output_shape)
[ "def", "divide", "(", "x1", ",", "x2", ",", "output_shape", "=", "None", ",", "name", "=", "None", ")", ":", "output_shape", "=", "convert_to_shape", "(", "output_shape", ")", "if", "not", "isinstance", "(", "x2", ",", "Tensor", ")", ":", "return", "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.dtype)), dtype) Args: indices: a Tensor output_dim: a Dimension on_value: Value taken when indices are on at a location, default 1 off_value: Value taken when indices are off at a location, default 0 dtype: a tf.DType name: an optional string Returns: a Tensor with shape extended by output_dim for the last axis. """ return OneHotOperation( indices, output_dim, on_value, off_value, dtype, name=name).outputs[0]
python
def one_hot(indices, output_dim, on_value=1.0, off_value=0.0, dtype=tf.float32, name=None): 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 indices are on at a location, default 1 off_value: Value taken when indices are off at a location, default 0 dtype: a tf.DType name: an optional string Returns: a Tensor with shape extended by output_dim for the last axis.
[ "One", "hot", "operation", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4087-L4107
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).outputs[0] for y in ys] # figure out what Tensors are downstream of xs downstream = set(xs) for op in graph.operations: if op.has_gradient: if set(op.inputs) & downstream: downstream |= set(op.outputs) tensor_to_gradient = dict(zip(ys, grad_ys)) for op in graph.operations[::-1]: grad_outputs = [tensor_to_gradient.get(out) for out in op.outputs] if op.has_gradient and any(grad_outputs) and (set(op.inputs) & downstream): with tf.variable_scope(op.name + "/gradients"): input_grads = op.gradient(grad_outputs) for inp, grad in zip(op.inputs, input_grads): if inp in downstream and grad is not None: if inp in tensor_to_gradient: tensor_to_gradient[inp] += grad else: tensor_to_gradient[inp] = grad return [tensor_to_gradient.get(x, None) for x in xs]
python
def gradients(ys, xs, grad_ys=None): graph = ys[0].graph if not grad_ys: grad_ys = [Constant(y.mesh, 1.0, y.shape, y.dtype).outputs[0] for y in ys] # figure out what Tensors are downstream of xs downstream = set(xs) for op in graph.operations: if op.has_gradient: if set(op.inputs) & downstream: downstream |= set(op.outputs) tensor_to_gradient = dict(zip(ys, grad_ys)) for op in graph.operations[::-1]: grad_outputs = [tensor_to_gradient.get(out) for out in op.outputs] if op.has_gradient and any(grad_outputs) and (set(op.inputs) & downstream): with tf.variable_scope(op.name + "/gradients"): input_grads = op.gradient(grad_outputs) for inp, grad in zip(op.inputs, input_grads): if inp in downstream and grad is not None: if inp in tensor_to_gradient: tensor_to_gradient[inp] += grad else: tensor_to_gradient[inp] = grad return [tensor_to_gradient.get(x, None) for x in xs]
[ "def", "gradients", "(", "ys", ",", "xs", ",", "grad_ys", "=", "None", ")", ":", "graph", "=", "ys", "[", "0", "]", ".", "graph", "if", "not", "grad_ys", ":", "grad_ys", "=", "[", "Constant", "(", "y", ".", "mesh", ",", "1.0", ",", "y", ".", ...
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 supersequence. Otherwise, we list the dimensions of shape1, followed by all new dimensions in shape2. Args: shape1: a Shape shape2: a Shape given_output_shape: an optional Shape Returns: a Shape """ shape1 = convert_to_shape(shape1) shape2 = convert_to_shape(shape2) given_output_shape = convert_to_shape(given_output_shape) if given_output_shape is not None: return given_output_shape if is_subsequence(shape1.dims, shape2.dims): return shape2 if is_subsequence(shape2.dims, shape1.dims): return shape1 return Shape( shape1.dims + [d for d in shape2.dims if d not in shape1.dims])
python
def _infer_binary_broadcast_shape(shape1, shape2, given_output_shape=None): shape1 = convert_to_shape(shape1) shape2 = convert_to_shape(shape2) given_output_shape = convert_to_shape(given_output_shape) if given_output_shape is not None: return given_output_shape if is_subsequence(shape1.dims, shape2.dims): return shape2 if is_subsequence(shape2.dims, shape1.dims): return shape1 return Shape( shape1.dims + [d for d in shape2.dims if d not in shape1.dims])
[ "def", "_infer_binary_broadcast_shape", "(", "shape1", ",", "shape2", ",", "given_output_shape", "=", "None", ")", ":", "shape1", "=", "convert_to_shape", "(", "shape1", ")", "shape2", "=", "convert_to_shape", "(", "shape2", ")", "given_output_shape", "=", "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 dimensions in shape2. Args: shape1: a Shape shape2: a Shape given_output_shape: an optional Shape Returns: a Shape
[ "Infer", "shape", "of", "the", "output", "of", "a", "binary", "op", "with", "broadcasting", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4164-L4189
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_shape) if input_shape == output_shape or input_shape.ndims == 0: return x perm = [input_shape.dims.index(d) for d in output_shape.dims if d in input_shape.dims] x = tf.transpose(x, perm) for i, d in enumerate(output_shape.dims): if d not in input_shape.dims: x = tf.expand_dims(x, i) return x
python
def _expand_dims(x, input_shape, output_shape): verify_no_new_dims([output_shape], input_shape) if input_shape == output_shape or input_shape.ndims == 0: return x perm = [input_shape.dims.index(d) for d in output_shape.dims if d in input_shape.dims] x = tf.transpose(x, perm) for i, d in enumerate(output_shape.dims): if d not in input_shape.dims: x = tf.expand_dims(x, i) return x
[ "def", "_expand_dims", "(", "x", ",", "input_shape", ",", "output_shape", ")", ":", "verify_no_new_dims", "(", "[", "output_shape", "]", ",", "input_shape", ")", "if", "input_shape", "==", "output_shape", "or", "input_shape", ".", "ndims", "==", "0", ":", "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 + [output_shape]): if shape_num == len(input_shapes): ret.append("->") elif shape_num > 0: ret.append(",") for d in shape.dims: if d not in dim_to_letter: dim_to_letter[d] = chr(next_letter) next_letter += 1 ret.append(dim_to_letter[d]) return "".join(ret)
python
def _einsum_equation(input_shapes, output_shape): ret = [] next_letter = ord("a") dim_to_letter = {} for shape_num, shape in enumerate(input_shapes + [output_shape]): if shape_num == len(input_shapes): ret.append("->") elif shape_num > 0: ret.append(",") for d in shape.dims: if d not in dim_to_letter: dim_to_letter[d] = chr(next_letter) next_letter += 1 ret.append(dim_to_letter[d]) return "".join(ret)
[ "def", "_einsum_equation", "(", "input_shapes", ",", "output_shape", ")", ":", "ret", "=", "[", "]", "next_letter", "=", "ord", "(", "\"a\"", ")", "dim_to_letter", "=", "{", "}", "for", "shape_num", ",", "shape", "in", "enumerate", "(", "input_shapes", "+"...
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 input_shapes], [])) all_output_dims = set(output_shape.dims) if not all_output_dims.issubset(all_input_dims): raise ValueError( "No new dimensions allowed in output" " input_shapes = %s output_shape= %s" % ([s.dims for s in input_shapes], output_shape.dims))
python
def verify_no_new_dims(input_shapes, output_shape): all_input_dims = set(sum([s.dims for s in input_shapes], [])) all_output_dims = set(output_shape.dims) if not all_output_dims.issubset(all_input_dims): raise ValueError( "No new dimensions allowed in output" " input_shapes = %s output_shape= %s" % ([s.dims for s in input_shapes], output_shape.dims))
[ "def", "verify_no_new_dims", "(", "input_shapes", ",", "output_shape", ")", ":", "all_input_dims", "=", "set", "(", "sum", "(", "[", "s", ".", "dims", "for", "s", "in", "input_shapes", "]", ",", "[", "]", ")", ")", "all_output_dims", "=", "set", "(", "...
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.append(pnum % dimsize) pnum //= dimsize return ret[::-1]
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.to_integer_list[::-1]): ret += multiplier * c multiplier *= d return ret
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