repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
tensorflow/mesh
mesh_tensorflow/transformer/dataset.py
pretokenized_t2t_dataset
def pretokenized_t2t_dataset(dataset_name=gin.REQUIRED, text2self=False, data_dir=gin.REQUIRED, dataset_split="train", batch_size=gin.REQUIRED, sequence_length=gin.REQUIRED, ...
python
def pretokenized_t2t_dataset(dataset_name=gin.REQUIRED, text2self=False, data_dir=gin.REQUIRED, dataset_split="train", batch_size=gin.REQUIRED, sequence_length=gin.REQUIRED, ...
[ "def", "pretokenized_t2t_dataset", "(", "dataset_name", "=", "gin", ".", "REQUIRED", ",", "text2self", "=", "False", ",", "data_dir", "=", "gin", ".", "REQUIRED", ",", "dataset_split", "=", "\"train\"", ",", "batch_size", "=", "gin", ".", "REQUIRED", ",", "s...
Loads the Tensor2tensor dataset specified by dataset_name. Args: dataset_name: TensorFlow Datasets dataset name. text2self: a boolean data_dir: string, data_dir for TensorFlow Datasets dataset_split: a string - "train" or "dev" batch_size: an integer sequence_length: an integer vocabulary...
[ "Loads", "the", "Tensor2tensor", "dataset", "specified", "by", "dataset_name", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L380-L417
train
tensorflow/mesh
mesh_tensorflow/transformer/dataset.py
pack_dataset
def pack_dataset(dataset, length, keys=None, use_custom_ops=False): """Creates a 'packed' version of a dataset on-the-fly. Borrowed from the tensor2tensor library. TODO(noam): make this faster This is meant to replace the irritation of having to create a separate "packed" version of a dataset to train effic...
python
def pack_dataset(dataset, length, keys=None, use_custom_ops=False): """Creates a 'packed' version of a dataset on-the-fly. Borrowed from the tensor2tensor library. TODO(noam): make this faster This is meant to replace the irritation of having to create a separate "packed" version of a dataset to train effic...
[ "def", "pack_dataset", "(", "dataset", ",", "length", ",", "keys", "=", "None", ",", "use_custom_ops", "=", "False", ")", ":", "shapes", "=", "dataset", ".", "output_shapes", "if", "keys", "is", "None", ":", "keys", "=", "shapes", ".", "keys", "(", ")"...
Creates a 'packed' version of a dataset on-the-fly. Borrowed from the tensor2tensor library. TODO(noam): make this faster This is meant to replace the irritation of having to create a separate "packed" version of a dataset to train efficiently on TPU. Each example in the output dataset represents several e...
[ "Creates", "a", "packed", "version", "of", "a", "dataset", "on", "-", "the", "-", "fly", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L421-L490
train
tensorflow/mesh
mesh_tensorflow/transformer/dataset.py
trim_and_pad_all_features
def trim_and_pad_all_features(features, length): """Trim and pad first dimension of all features to size length.""" return {k: _trim_and_pad(v, length) for k, v in features.items()}
python
def trim_and_pad_all_features(features, length): """Trim and pad first dimension of all features to size length.""" return {k: _trim_and_pad(v, length) for k, v in features.items()}
[ "def", "trim_and_pad_all_features", "(", "features", ",", "length", ")", ":", "return", "{", "k", ":", "_trim_and_pad", "(", "v", ",", "length", ")", "for", "k", ",", "v", "in", "features", ".", "items", "(", ")", "}" ]
Trim and pad first dimension of all features to size length.
[ "Trim", "and", "pad", "first", "dimension", "of", "all", "features", "to", "size", "length", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L667-L669
train
tensorflow/mesh
mesh_tensorflow/ops.py
convert_to_dimension
def convert_to_dimension(d): """Converts input to a Dimension. Args: d: Dimension, tuple (string, int), or None. Returns: Dimension or None. Raises: ValueError: If d cannot be converted to a Dimension. """ if d is None: return None if isinstance(d, Dimension): if not isinstance(d.na...
python
def convert_to_dimension(d): """Converts input to a Dimension. Args: d: Dimension, tuple (string, int), or None. Returns: Dimension or None. Raises: ValueError: If d cannot be converted to a Dimension. """ if d is None: return None if isinstance(d, Dimension): if not isinstance(d.na...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
convert_to_shape
def convert_to_shape(x): """Converts input to a Shape. Args: x: Shape, str, or None. Returns: Shape or None. Raises: ValueError: If x cannot be converted to a Shape. """ if x is None: return None if isinstance(x, Shape): return x if isinstance(x, str): x = _parse_string_to_lis...
python
def convert_to_shape(x): """Converts input to a Shape. Args: x: Shape, str, or None. Returns: Shape or None. Raises: ValueError: If x cannot be converted to a Shape. """ if x is None: return None if isinstance(x, Shape): return x if isinstance(x, str): x = _parse_string_to_lis...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
convert_to_layout_rules
def convert_to_layout_rules(x): """Converts input to a LayoutRules. Args: x: LayoutRules, str, or set-like of string pairs. Returns: LayoutRules. """ if isinstance(x, LayoutRules): return x if isinstance(x, str): x = _parse_string_to_list_of_pairs(x) return LayoutRules(x)
python
def convert_to_layout_rules(x): """Converts input to a LayoutRules. Args: x: LayoutRules, str, or set-like of string pairs. Returns: LayoutRules. """ if isinstance(x, LayoutRules): return x if isinstance(x, str): x = _parse_string_to_list_of_pairs(x) return LayoutRules(x)
[ "def", "convert_to_layout_rules", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "LayoutRules", ")", ":", "return", "x", "if", "isinstance", "(", "x", ",", "str", ")", ":", "x", "=", "_parse_string_to_list_of_pairs", "(", "x", ")", "return", "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
convert_args_to_laid_out_tensors
def convert_args_to_laid_out_tensors(xs): """Convert list elements to laid-out-tensors when possible. Args: xs: a list Returns: a list """ ret = [] for x in xs: if hasattr(x, "to_laid_out_tensor"): ret.append(x.to_laid_out_tensor()) else: ret.append(x) return ret
python
def convert_args_to_laid_out_tensors(xs): """Convert list elements to laid-out-tensors when possible. Args: xs: a list Returns: a list """ ret = [] for x in xs: if hasattr(x, "to_laid_out_tensor"): ret.append(x.to_laid_out_tensor()) else: ret.append(x) return ret
[ "def", "convert_args_to_laid_out_tensors", "(", "xs", ")", ":", "ret", "=", "[", "]", "for", "x", "in", "xs", ":", "if", "hasattr", "(", "x", ",", "\"to_laid_out_tensor\"", ")", ":", "ret", ".", "append", "(", "x", ".", "to_laid_out_tensor", "(", ")", ...
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
train
tensorflow/mesh
mesh_tensorflow/ops.py
slicewise
def slicewise(tf_fn, xs, output_shape=None, output_dtype=None, splittable_dims=None, grad_function=None, name=None): """Slice-wise call to any tensorflow function. The output shape and dtype default to those of the first input. s...
python
def slicewise(tf_fn, xs, output_shape=None, output_dtype=None, splittable_dims=None, grad_function=None, name=None): """Slice-wise call to any tensorflow function. The output shape and dtype default to those of the first input. s...
[ "def", "slicewise", "(", "tf_fn", ",", "xs", ",", "output_shape", "=", "None", ",", "output_dtype", "=", "None", ",", "splittable_dims", "=", "None", ",", "grad_function", "=", "None", ",", "name", "=", "None", ")", ":", "multiple_outputs", "=", "isinstanc...
Slice-wise call to any tensorflow function. The output shape and dtype default to those of the first input. splittable_dims is a list of Dimensions which can be split while keeping the computation valid. Args: tf_fn: a function taking n tf.Tensors and returning a tf.Tensor xs: a list of n Tensors ...
[ "Slice", "-", "wise", "call", "to", "any", "tensorflow", "function", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1568-L1605
train
tensorflow/mesh
mesh_tensorflow/ops.py
cwise
def cwise(tf_fn, xs, output_dtype=None, grad_function=None, name=None): """Component-wise operation with no broadcasting. Args: tf_fn: a component-wise function taking n tf.Tensor inputs and producing a tf.Tensor output xs: n Tensors output_dtype: an optional dtype grad_function: an optional ...
python
def cwise(tf_fn, xs, output_dtype=None, grad_function=None, name=None): """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 ...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
binary_arguments_to_tensors
def binary_arguments_to_tensors(x1, x2): """Convert argument of a binary operation to Tensors. Args: x1: a Tensor or something convertible to a tf Scalar x2: a Tensor or something convertible to a tf Scalar Returns: new_x1: a Tensor new_x2: a Tensor Raises: ValueError: on failure """ ...
python
def binary_arguments_to_tensors(x1, x2): """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 """ ...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
minimum
def minimum(x1, x2, output_shape=None, name=None): """Binary minimum with broadcsting. Args: x1: a Tensor x2: a Tensor output_shape: an optional Shape name: an optional string Returns: a Tensor """ output_shape = convert_to_shape(output_shape) with tf.name_scope(name, default_name="mini...
python
def minimum(x1, x2, output_shape=None, name=None): """Binary minimum with broadcsting. Args: x1: a Tensor x2: a Tensor output_shape: an optional Shape name: an optional string Returns: a Tensor """ output_shape = convert_to_shape(output_shape) with tf.name_scope(name, default_name="mini...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
split
def split(x, split_dim, num_or_size_splits, name=None): """Like tf.split. Args: x: a Tensor split_dim: a Dimension in x.shape.dims num_or_size_splits: either an integer dividing split_dim.size or a list of integers adding up to split_dim.size name: an optional string Returns: a list of...
python
def split(x, split_dim, num_or_size_splits, name=None): """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...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
stack
def stack(xs, dim_name, axis=0, name=None): """Stack multiple Tensors to make a new dimension. Args: xs: a list of Tensors with identical shapes. dim_name: a string (name of the new dimension) axis: an integer (index of the new dimension in the output shape) name: an optional string Returns: ...
python
def stack(xs, dim_name, axis=0, name=None): """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: ...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
cumsum
def cumsum(x, dim, exclusive=False): """Cumulative sum. Args: x: a Tensor dim: a Dimension exclusive: a boolean Returns: a Tensor with the same shape as x. """ with tf.variable_scope("cumsum"): new_name = "tmp_dim_cumsum" new_dim = Dimension(new_name, dim.size) new_shape = x.shap...
python
def cumsum(x, dim, exclusive=False): """Cumulative sum. Args: x: a Tensor dim: a Dimension exclusive: a boolean Returns: a Tensor with the same shape as x. """ with tf.variable_scope("cumsum"): new_name = "tmp_dim_cumsum" new_dim = Dimension(new_name, dim.size) new_shape = x.shap...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
shift
def shift(x, offset, dim, wrap, name=None): """Shift operation. Shift x right by +offset in dimension dim. Args: x: a Tensor offset: an integer. If negative, shift left instead of right. dim: a Dimension of x wrap: a boolean - whether to wrap (True) or pad with zeros (False). name: an option...
python
def shift(x, offset, dim, wrap, name=None): """Shift operation. Shift x right by +offset in dimension dim. Args: x: a Tensor offset: an integer. If negative, shift left instead of right. dim: a Dimension of x wrap: a boolean - whether to wrap (True) or pad with zeros (False). name: an option...
[ "def", "shift", "(", "x", ",", "offset", ",", "dim", ",", "wrap", ",", "name", "=", "None", ")", ":", "return", "ShiftOperation", "(", "x", ",", "offset", ",", "dim", ",", "wrap", ",", "name", "=", "name", ")", ".", "outputs", "[", "0", "]" ]
Shift operation. Shift x right by +offset in dimension dim. Args: x: a Tensor offset: an integer. If negative, shift left instead of right. dim: a Dimension of x wrap: a boolean - whether to wrap (True) or pad with zeros (False). name: an optional string Returns: a Tensor with the same ...
[ "Shift", "operation", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L2755-L2770
train
tensorflow/mesh
mesh_tensorflow/ops.py
import_laid_out_tensor
def import_laid_out_tensor(mesh, laid_out_tensor, shape, name=None): """Import a laid_out_tensor. For expert users. The input must be laid out appropriately given the eventual MeshImpl, and layout. Args: mesh: a Mesh laid_out_tensor: a LaidOutTensor shape: a mtf.Shape name: an optional strin...
python
def import_laid_out_tensor(mesh, laid_out_tensor, shape, name=None): """Import a laid_out_tensor. For expert users. The input must be laid out appropriately given the eventual MeshImpl, and layout. Args: mesh: a Mesh laid_out_tensor: a LaidOutTensor shape: a mtf.Shape name: an optional strin...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
get_variable
def get_variable(mesh, name, shape, dtype=tf.float32, master_dtype=None, slice_dtype=None, activation_dtype=None, initializer=None, trainable=True, **kwargs): """Create a new variable or retrieve an already-created one. Args: mesh: a Mesh name: a string (u...
python
def get_variable(mesh, name, shape, dtype=tf.float32, master_dtype=None, slice_dtype=None, activation_dtype=None, initializer=None, trainable=True, **kwargs): """Create a new variable or retrieve an already-created one. Args: mesh: a Mesh name: a string (u...
[ "def", "get_variable", "(", "mesh", ",", "name", ",", "shape", ",", "dtype", "=", "tf", ".", "float32", ",", "master_dtype", "=", "None", ",", "slice_dtype", "=", "None", ",", "activation_dtype", "=", "None", ",", "initializer", "=", "None", ",", "traina...
Create a new variable or retrieve an already-created one. Args: mesh: a Mesh name: a string (uses the existing tf.variable_scope()) shape: a Shape dtype: a VariableDType or a tf.DType master_dtype: an optional tf.DType (deprecated - use dtype arg) slice_dtype: an optional tf.DType (deprecated...
[ "Create", "a", "new", "variable", "or", "retrieve", "an", "already", "-", "created", "one", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3210-L3253
train
tensorflow/mesh
mesh_tensorflow/ops.py
assign
def assign(var, new_val, assign_fn=assign_slice): """Assign a new value to a variable. Args: var: either a Variable operation or its output Tensor. new_val: a Tensor assign_fn: a function from (mtf.Variable, tf.Variable, tf.Tensor) -> tf.Operation Returns: an Operation Raises: Value...
python
def assign(var, new_val, assign_fn=assign_slice): """Assign a new value to a variable. Args: var: either a Variable operation or its output Tensor. new_val: a Tensor assign_fn: a function from (mtf.Variable, tf.Variable, tf.Tensor) -> tf.Operation Returns: an Operation Raises: Value...
[ "def", "assign", "(", "var", ",", "new_val", ",", "assign_fn", "=", "assign_slice", ")", ":", "if", "isinstance", "(", "var", ",", "Tensor", ")", ":", "var", "=", "var", ".", "operation", "if", "not", "isinstance", "(", "var", ",", "Variable", ")", "...
Assign a new value to a variable. Args: var: either a Variable operation or its output Tensor. new_val: a Tensor assign_fn: a function from (mtf.Variable, tf.Variable, tf.Tensor) -> tf.Operation Returns: an Operation Raises: ValueError: if var is not a Variable and var.operation is no...
[ "Assign", "a", "new", "value", "to", "a", "variable", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3304-L3321
train
tensorflow/mesh
mesh_tensorflow/ops.py
Print
def Print(x, data, message, **kwargs): # pylint: disable=invalid-name """Call tf.Print. Args: x: a Tensor. data: a list of Tensor message: a string **kwargs: keyword arguments to tf.Print Returns: a Tensor which is identical in value to x """ return PrintOperation(x, data, message, **kwa...
python
def Print(x, data, message, **kwargs): # pylint: disable=invalid-name """Call tf.Print. Args: x: a Tensor. data: a list of Tensor message: a string **kwargs: keyword arguments to tf.Print Returns: a Tensor which is identical in value to x """ return PrintOperation(x, data, message, **kwa...
[ "def", "Print", "(", "x", ",", "data", ",", "message", ",", "**", "kwargs", ")", ":", "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
rename_dimension
def rename_dimension(x, old_name, new_name): """Reshape a Tensor, renaming one dimension. Args: x: a Tensor old_name: a string new_name: a string Returns: a Tensor """ return reshape(x, x.shape.rename_dimension(old_name, new_name))
python
def rename_dimension(x, old_name, new_name): """Reshape a Tensor, renaming one dimension. Args: x: a Tensor old_name: a string new_name: a string Returns: a Tensor """ return reshape(x, x.shape.rename_dimension(old_name, new_name))
[ "def", "rename_dimension", "(", "x", ",", "old_name", ",", "new_name", ")", ":", "return", "reshape", "(", "x", ",", "x", ".", "shape", ".", "rename_dimension", "(", "old_name", ",", "new_name", ")", ")" ]
Reshape a Tensor, renaming one dimension. Args: x: a Tensor old_name: a string new_name: a string Returns: a Tensor
[ "Reshape", "a", "Tensor", "renaming", "one", "dimension", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3576-L3587
train
tensorflow/mesh
mesh_tensorflow/ops.py
replace_dimensions
def replace_dimensions(tensor_or_shape, old_dim_or_dims, new_dim_or_dims): """Replace dimensions in a Tensor or Shape. old_dim_or_dims consists of a single dimension or a list of dimensions that must occur consecutively in the input shape. They are replaced by the dimensions in new_dim_or_dims. Args: t...
python
def replace_dimensions(tensor_or_shape, old_dim_or_dims, new_dim_or_dims): """Replace dimensions in a Tensor or Shape. old_dim_or_dims consists of a single dimension or a list of dimensions that must occur consecutively in the input shape. They are replaced by the dimensions in new_dim_or_dims. Args: t...
[ "def", "replace_dimensions", "(", "tensor_or_shape", ",", "old_dim_or_dims", ",", "new_dim_or_dims", ")", ":", "if", "isinstance", "(", "tensor_or_shape", ",", "Tensor", ")", ":", "return", "reshape", "(", "tensor_or_shape", ",", "replace_dimensions", "(", "tensor_o...
Replace dimensions in a Tensor or Shape. old_dim_or_dims consists of a single dimension or a list of dimensions that must occur consecutively in the input shape. They are replaced by the dimensions in new_dim_or_dims. Args: tensor_or_shape: a Tensor or a Shape old_dim_or_dims: a Dimension or a list o...
[ "Replace", "dimensions", "in", "a", "Tensor", "or", "Shape", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3590-L3634
train
tensorflow/mesh
mesh_tensorflow/ops.py
einsum
def einsum(xs, output_shape=None, reduced_dims=None, name=None): """Einstein summation. einsum(xs, output_shape) is equivalent to broadcasting all inputs to the union of all of their shapes, multiplying them componentwise, and finally reduce_summing down to output_shape. One common case of this is matrix mu...
python
def einsum(xs, output_shape=None, reduced_dims=None, name=None): """Einstein summation. einsum(xs, output_shape) is equivalent to broadcasting all inputs to the union of all of their shapes, multiplying them componentwise, and finally reduce_summing down to output_shape. One common case of this is matrix mu...
[ "def", "einsum", "(", "xs", ",", "output_shape", "=", "None", ",", "reduced_dims", "=", "None", ",", "name", "=", "None", ")", ":", "output_shape", "=", "convert_to_shape", "(", "output_shape", ")", "input_dim_count", "=", "collections", ".", "defaultdict", ...
Einstein summation. einsum(xs, output_shape) is equivalent to broadcasting all inputs to the union of all of their shapes, multiplying them componentwise, and finally reduce_summing down to output_shape. One common case of this is matrix multiplication: x has shape [a, b] y has shape [b, c] ...
[ "Einstein", "summation", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3637-L3700
train
tensorflow/mesh
mesh_tensorflow/ops.py
_reduction_output_shape
def _reduction_output_shape(x, output_shape, reduced_dim): """Helper function to reduce_sum, etc.""" if output_shape is None: if reduced_dim is None: return Shape([]) else: if reduced_dim not in x.shape.dims: raise ValueError( "reduced_dim=%s not in x.shape.dims=%s" % (reduce...
python
def _reduction_output_shape(x, output_shape, reduced_dim): """Helper function to reduce_sum, etc.""" if output_shape is None: if reduced_dim is None: return Shape([]) else: if reduced_dim not in x.shape.dims: raise ValueError( "reduced_dim=%s not in x.shape.dims=%s" % (reduce...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
top_1
def top_1(x, reduced_dim, dtype=tf.int32, name=None): """Argmax and Max. Args: x: a Tensor reduced_dim: a Dimension in x.shape.dims dtype: a tf.dtype (for the output) name: an optional string Returns: indices: a Tensor with given dtype values: optional Tensor equal to mtf.reduce_max(x, re...
python
def top_1(x, reduced_dim, dtype=tf.int32, name=None): """Argmax and Max. Args: x: a Tensor reduced_dim: a Dimension in x.shape.dims dtype: a tf.dtype (for the output) name: an optional string Returns: indices: a Tensor with given dtype values: optional Tensor equal to mtf.reduce_max(x, re...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
top_k
def top_k(x, reduced_dim, new_dim, dtype=tf.int32, name=None): """Like tf.top_k. This operation returns two tensors with the same shape. The output shape is identical to the shape of x, except that reduced_dim is replaced by new_dim. Args: x: a Tensor reduced_dim: a Dimension in x.shape.dims. n...
python
def top_k(x, reduced_dim, new_dim, dtype=tf.int32, name=None): """Like tf.top_k. This operation returns two tensors with the same shape. The output shape is identical to the shape of x, except that reduced_dim is replaced by new_dim. Args: x: a Tensor reduced_dim: a Dimension in x.shape.dims. n...
[ "def", "top_k", "(", "x", ",", "reduced_dim", ",", "new_dim", ",", "dtype", "=", "tf", ".", "int32", ",", "name", "=", "None", ")", ":", "reduced_dim", "=", "convert_to_dimension", "(", "reduced_dim", ")", "new_dim", "=", "convert_to_dimension", "(", "new_...
Like tf.top_k. This operation returns two tensors with the same shape. The output shape is identical to the shape of x, except that reduced_dim is replaced by new_dim. Args: x: a Tensor reduced_dim: a Dimension in x.shape.dims. new_dim: a Dimension. The size determines k. dtype: optional dty...
[ "Like", "tf", ".", "top_k", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3902-L3932
train
tensorflow/mesh
mesh_tensorflow/ops.py
add
def add(x1, x2, output_shape=None, name=None): """Binary addition with broadcsting. Args: x1: a Tensor x2: a Tensor output_shape: an optional Shape name: an optional string Returns: a Tensor """ output_shape = convert_to_shape(output_shape) if not isinstance(x2, Tensor): return Scal...
python
def add(x1, x2, output_shape=None, name=None): """Binary addition with broadcsting. Args: x1: a Tensor x2: a Tensor output_shape: an optional Shape name: an optional string Returns: a Tensor """ output_shape = convert_to_shape(output_shape) if not isinstance(x2, Tensor): return Scal...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
sub
def sub(x1, x2, output_shape=None, name=None): """Binary subtraction with broadcsting. Args: x1: a Tensor x2: a Tensor output_shape: an optional Shape name: an optional string Returns: a Tensor """ output_shape = convert_to_shape(output_shape) if not isinstance(x2, Tensor): return S...
python
def sub(x1, x2, output_shape=None, name=None): """Binary subtraction with broadcsting. Args: x1: a Tensor x2: a Tensor output_shape: an optional Shape name: an optional string Returns: a Tensor """ output_shape = convert_to_shape(output_shape) if not isinstance(x2, Tensor): return S...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
multiply
def multiply(x1, x2, output_shape=None, name=None): """Binary multiplication with broadcasting. Args: x1: a Tensor x2: a Tensor output_shape: an optional Shape name: an optional string Returns: a Tensor """ if not isinstance(x2, Tensor): return ScalarMultiplyOperation(x1, x2).outputs[...
python
def multiply(x1, x2, output_shape=None, name=None): """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[...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
divide
def divide(x1, x2, output_shape=None, name=None): """Binary division with broadcasting. Args: x1: a Tensor x2: a Tensor output_shape: an optional Shape name: an optional string Returns: a Tensor """ output_shape = convert_to_shape(output_shape) if not isinstance(x2, Tensor): return ...
python
def divide(x1, x2, output_shape=None, name=None): """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 ...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
one_hot
def one_hot(indices, output_dim, on_value=1.0, off_value=0.0, dtype=tf.float32, name=None): """One hot operation. TODO(noam): Is there a good reason we need a special mtf.Operation here? We could just use some code like this: cast(equal(indices, mtf_range(indices.mesh, output_dim, dtype=indices.dty...
python
def one_hot(indices, output_dim, on_value=1.0, off_value=0.0, dtype=tf.float32, name=None): """One hot operation. TODO(noam): Is there a good reason we need a special mtf.Operation here? We could just use some code like this: cast(equal(indices, mtf_range(indices.mesh, output_dim, dtype=indices.dty...
[ "def", "one_hot", "(", "indices", ",", "output_dim", ",", "on_value", "=", "1.0", ",", "off_value", "=", "0.0", ",", "dtype", "=", "tf", ".", "float32", ",", "name", "=", "None", ")", ":", "return", "OneHotOperation", "(", "indices", ",", "output_dim", ...
One hot operation. TODO(noam): Is there a good reason we need a special mtf.Operation here? We could just use some code like this: cast(equal(indices, mtf_range(indices.mesh, output_dim, dtype=indices.dtype)), dtype) Args: indices: a Tensor output_dim: a Dimension on_value: Value taken when...
[ "One", "hot", "operation", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4087-L4107
train
tensorflow/mesh
mesh_tensorflow/ops.py
gradients
def gradients(ys, xs, grad_ys=None): """Compute gradients in dtf. Args: ys: a list of Tensors xs: a list of Tensors grad_ys: an optional list of Tensors Returns: grad_xs: a list of Tensors """ graph = ys[0].graph if not grad_ys: grad_ys = [Constant(y.mesh, 1.0, y.shape, y.dtype).output...
python
def gradients(ys, xs, grad_ys=None): """Compute gradients in dtf. Args: ys: a list of Tensors xs: a list of Tensors grad_ys: an optional list of Tensors Returns: grad_xs: a list of Tensors """ graph = ys[0].graph if not grad_ys: grad_ys = [Constant(y.mesh, 1.0, y.shape, y.dtype).output...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
_infer_binary_broadcast_shape
def _infer_binary_broadcast_shape(shape1, shape2, given_output_shape=None): """Infer shape of the output of a binary op with broadcasting. If the output shape is not given with given_output_shape, then we check to see if one of the shapes is a subsequence of the other one, and we return the one that is the sup...
python
def _infer_binary_broadcast_shape(shape1, shape2, given_output_shape=None): """Infer shape of the output of a binary op with broadcasting. If the output shape is not given with given_output_shape, then we check to see if one of the shapes is a subsequence of the other one, and we return the one that is the sup...
[ "def", "_infer_binary_broadcast_shape", "(", "shape1", ",", "shape2", ",", "given_output_shape", "=", "None", ")", ":", "shape1", "=", "convert_to_shape", "(", "shape1", ")", "shape2", "=", "convert_to_shape", "(", "shape2", ")", "given_output_shape", "=", "conver...
Infer shape of the output of a binary op with broadcasting. If the output shape is not given with given_output_shape, then we check to see if one of the shapes is a subsequence of the other one, and we return the one that is the supersequence. Otherwise, we list the dimensions of shape1, followed by all new d...
[ "Infer", "shape", "of", "the", "output", "of", "a", "binary", "op", "with", "broadcasting", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4164-L4189
train
tensorflow/mesh
mesh_tensorflow/ops.py
_expand_dims
def _expand_dims(x, input_shape, output_shape): """Expand dimensions and transpose if necessary. Args: x: a tf.Tensor input_shape: a Shape output_shape: a Shape whose dimensions are a superset of those in input_shape Returns: a tf.Tensor """ verify_no_new_dims([output_shape], input_sha...
python
def _expand_dims(x, input_shape, output_shape): """Expand dimensions and transpose if necessary. Args: x: a tf.Tensor input_shape: a Shape output_shape: a Shape whose dimensions are a superset of those in input_shape Returns: a tf.Tensor """ verify_no_new_dims([output_shape], input_sha...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
_einsum_equation
def _einsum_equation(input_shapes, output_shape): """Turn shapes into an einsum equation. e.g. "ij,jk->ik" Args: input_shapes: a list of Shapes output_shape: a Shape Returns: a string """ ret = [] next_letter = ord("a") dim_to_letter = {} for shape_num, shape in enumerate(input_shapes + ...
python
def _einsum_equation(input_shapes, output_shape): """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 + ...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
is_subsequence
def is_subsequence(short_seq, long_seq): """Is short_seq a subsequence of long_seq.""" if not short_seq: return True pos = 0 for x in long_seq: if pos == len(short_seq): return True if short_seq[pos] == x: pos += 1 if pos == len(short_seq): return True return False
python
def is_subsequence(short_seq, long_seq): """Is short_seq a subsequence of long_seq.""" if not short_seq: return True pos = 0 for x in long_seq: if pos == len(short_seq): return True if short_seq[pos] == x: pos += 1 if pos == len(short_seq): return True return False
[ "def", "is_subsequence", "(", "short_seq", ",", "long_seq", ")", ":", "if", "not", "short_seq", ":", "return", "True", "pos", "=", "0", "for", "x", "in", "long_seq", ":", "if", "pos", "==", "len", "(", "short_seq", ")", ":", "return", "True", "if", "...
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
train
tensorflow/mesh
mesh_tensorflow/ops.py
verify_no_new_dims
def verify_no_new_dims(input_shapes, output_shape): """Verifies that all dimensions in the output are in at least one input. Args: input_shapes: a list of Shapes output_shape: a Shape Raises: ValueError: if there are new dimensions in the output. """ all_input_dims = set(sum([s.dims for s in inpu...
python
def verify_no_new_dims(input_shapes, output_shape): """Verifies that all dimensions in the output are in at least one input. Args: input_shapes: a list of Shapes output_shape: a Shape Raises: ValueError: if there are new dimensions in the output. """ all_input_dims = set(sum([s.dims for s in inpu...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
pnum_to_processor_coordinates
def pnum_to_processor_coordinates(mesh_shape, pnum): """Coordinates of a processor in the mesh. Args: mesh_shape: a Shape pnum: an integer less than len(mesh_shape) Returns: a list of integers with length len(mesh_shape) """ ret = [] for dimsize in mesh_shape.to_integer_list[::-1]: ret.app...
python
def pnum_to_processor_coordinates(mesh_shape, pnum): """Coordinates of a processor in the mesh. Args: mesh_shape: a Shape pnum: an integer less than len(mesh_shape) Returns: a list of integers with length len(mesh_shape) """ ret = [] for dimsize in mesh_shape.to_integer_list[::-1]: ret.app...
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
processor_coordinates_to_pnum
def processor_coordinates_to_pnum(mesh_shape, coord): """Inverse of pnum_to_processor_coordinates. Args: mesh_shape: a Shape coord: a list of integers with length len(mesh_shape) Returns: an integer less than len(mesh_shape) """ ret = 0 multiplier = 1 for c, d in zip(coord[::-1], mesh_shape....
python
def processor_coordinates_to_pnum(mesh_shape, coord): """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....
[ "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
train
tensorflow/mesh
mesh_tensorflow/ops.py
pnum_to_group
def pnum_to_group(mesh_shape, group_dims, pnum): """Group number for grouped allreduce. Args: mesh_shape: a Shape group_dims: a list of integers (the dimensions reduced over) pnum: an integer Returns: an integer """ coord = pnum_to_processor_coordinates(mesh_shape, pnum) remaining_shape = ...
python
def pnum_to_group(mesh_shape, group_dims, pnum): """Group number for grouped allreduce. Args: mesh_shape: a Shape group_dims: a list of integers (the dimensions reduced over) pnum: an integer Returns: an integer """ coord = pnum_to_processor_coordinates(mesh_shape, pnum) remaining_shape = ...
[ "def", "pnum_to_group", "(", "mesh_shape", ",", "group_dims", ",", "pnum", ")", ":", "coord", "=", "pnum_to_processor_coordinates", "(", "mesh_shape", ",", "pnum", ")", "remaining_shape", "=", "Shape", "(", "[", "d", "for", "i", ",", "d", "in", "enumerate", ...
Group number for grouped allreduce. Args: mesh_shape: a Shape group_dims: a list of integers (the dimensions reduced over) pnum: an integer Returns: an integer
[ "Group", "number", "for", "grouped", "allreduce", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4312-L4327
train
tensorflow/mesh
mesh_tensorflow/ops.py
processor_groups
def processor_groups(mesh_shape, group_dims): """Groups of processors which differ only in the given dimensions. Args: mesh_shape: a Shape group_dims: a list of integers Returns: a list of lists of integers (processor numbers) """ group_numbers = [ pnum_to_group(mesh_shape, group_dims, pnu...
python
def processor_groups(mesh_shape, group_dims): """Groups of processors which differ only in the given dimensions. Args: mesh_shape: a Shape group_dims: a list of integers Returns: a list of lists of integers (processor numbers) """ group_numbers = [ pnum_to_group(mesh_shape, group_dims, pnu...
[ "def", "processor_groups", "(", "mesh_shape", ",", "group_dims", ")", ":", "group_numbers", "=", "[", "pnum_to_group", "(", "mesh_shape", ",", "group_dims", ",", "pnum", ")", "for", "pnum", "in", "xrange", "(", "mesh_shape", ".", "size", ")", "]", "ret", "...
Groups of processors which differ only in the given dimensions. Args: mesh_shape: a Shape group_dims: a list of integers Returns: a list of lists of integers (processor numbers)
[ "Groups", "of", "processors", "which", "differ", "only", "in", "the", "given", "dimensions", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4330-L4348
train
tensorflow/mesh
mesh_tensorflow/ops.py
mtf_range
def mtf_range(mesh, dim, dtype, name=None): """Create a 1d mesh tensor with a range from [0, dim.size). Call externally as mtf.range() Args: mesh: a Mesh dim: a Dimension dtype: a tf.DType name: an optional string Returns: a Tensor """ dim = convert_to_dimension(dim) with tf.variabl...
python
def mtf_range(mesh, dim, dtype, name=None): """Create a 1d mesh tensor with a range from [0, dim.size). Call externally as mtf.range() Args: mesh: a Mesh dim: a Dimension dtype: a tf.DType name: an optional string Returns: a Tensor """ dim = convert_to_dimension(dim) with tf.variabl...
[ "def", "mtf_range", "(", "mesh", ",", "dim", ",", "dtype", ",", "name", "=", "None", ")", ":", "dim", "=", "convert_to_dimension", "(", "dim", ")", "with", "tf", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"range\"", ")", ":", "if",...
Create a 1d mesh tensor with a range from [0, dim.size). Call externally as mtf.range() Args: mesh: a Mesh dim: a Dimension dtype: a tf.DType name: an optional string Returns: a Tensor
[ "Create", "a", "1d", "mesh", "tensor", "with", "a", "range", "from", "[", "0", "dim", ".", "size", ")", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4406-L4428
train
tensorflow/mesh
mesh_tensorflow/ops.py
pretty_print_counters
def pretty_print_counters(counters): """print counters hierarchically. Each counter is a pair of a string and a number. The string can have slashes, meaning that the number also counts towards each prefix. e.g. "parameters/trainable" counts towards both "parameters" and "parameters/trainable". Args: ...
python
def pretty_print_counters(counters): """print counters hierarchically. Each counter is a pair of a string and a number. The string can have slashes, meaning that the number also counts towards each prefix. e.g. "parameters/trainable" counts towards both "parameters" and "parameters/trainable". Args: ...
[ "def", "pretty_print_counters", "(", "counters", ")", ":", "totals", "=", "collections", ".", "defaultdict", "(", "int", ")", "for", "(", "name", ",", "val", ")", "in", "counters", ":", "prefixes", "=", "[", "name", "[", ":", "i", "]", "for", "i", "i...
print counters hierarchically. Each counter is a pair of a string and a number. The string can have slashes, meaning that the number also counts towards each prefix. e.g. "parameters/trainable" counts towards both "parameters" and "parameters/trainable". Args: counters: a list of (string, number) pair...
[ "print", "counters", "hierarchically", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4431-L4453
train
tensorflow/mesh
mesh_tensorflow/ops.py
_parse_string_to_list_of_pairs
def _parse_string_to_list_of_pairs(s, seconds_to_int=False): r"""Parses a string into a list of pairs. In the input string, each pair is separated by a colon, and the delimiters between pairs are any of " ,.;". e.g. "rows:32,cols:32" Args: s: str to parse. seconds_to_int: Boolean. If True, then the...
python
def _parse_string_to_list_of_pairs(s, seconds_to_int=False): r"""Parses a string into a list of pairs. In the input string, each pair is separated by a colon, and the delimiters between pairs are any of " ,.;". e.g. "rows:32,cols:32" Args: s: str to parse. seconds_to_int: Boolean. If True, then the...
[ "def", "_parse_string_to_list_of_pairs", "(", "s", ",", "seconds_to_int", "=", "False", ")", ":", "r", "ret", "=", "[", "]", "for", "p", "in", "[", "s", ".", "split", "(", "\":\"", ")", "for", "s", "in", "re", ".", "sub", "(", "\"[,.;]\"", ",", "\"...
r"""Parses a string into a list of pairs. In the input string, each pair is separated by a colon, and the delimiters between pairs are any of " ,.;". e.g. "rows:32,cols:32" Args: s: str to parse. seconds_to_int: Boolean. If True, then the second elements are returned as integers; otherwise the...
[ "r", "Parses", "a", "string", "into", "a", "list", "of", "pairs", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4456-L4483
train
tensorflow/mesh
mesh_tensorflow/ops.py
parallel
def parallel(devices, fn, *args, **kwargs): """Call a function once on each device. Args: devices: a list of n devices fn: a function *args: arguments, each of which is a list of length n **kwargs: keyword-args, each of which is a list of length n Returns: a list of length n Raises: Val...
python
def parallel(devices, fn, *args, **kwargs): """Call a function once on each device. Args: devices: a list of n devices fn: a function *args: arguments, each of which is a list of length n **kwargs: keyword-args, each of which is a list of length n Returns: a list of length n Raises: Val...
[ "def", "parallel", "(", "devices", ",", "fn", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "not", "isinstance", "(", "devices", ",", "list", ")", ":", "raise", "ValueError", "(", "\"devices must be a list\"", ")", "for", "x", "in", "list", "(...
Call a function once on each device. Args: devices: a list of n devices fn: a function *args: arguments, each of which is a list of length n **kwargs: keyword-args, each of which is a list of length n Returns: a list of length n Raises: ValueError: if the arguments are not all lists of le...
[ "Call", "a", "function", "once", "on", "each", "device", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4486-L4513
train
tensorflow/mesh
mesh_tensorflow/ops.py
random_uniform
def random_uniform(mesh, shape, **kwargs): """Random uniform. Args: mesh: a Mesh shape: a Shape **kwargs: keyword args for tf.random.uniform, except seed Returns: a Tensor """ shape = convert_to_shape(shape) return RandomOperation(mesh, shape, tf.random.uniform, **kwargs).outputs[0]
python
def random_uniform(mesh, shape, **kwargs): """Random uniform. Args: mesh: a Mesh shape: a Shape **kwargs: keyword args for tf.random.uniform, except seed Returns: a Tensor """ shape = convert_to_shape(shape) return RandomOperation(mesh, shape, tf.random.uniform, **kwargs).outputs[0]
[ "def", "random_uniform", "(", "mesh", ",", "shape", ",", "**", "kwargs", ")", ":", "shape", "=", "convert_to_shape", "(", "shape", ")", "return", "RandomOperation", "(", "mesh", ",", "shape", ",", "tf", ".", "random", ".", "uniform", ",", "**", "kwargs",...
Random uniform. Args: mesh: a Mesh shape: a Shape **kwargs: keyword args for tf.random.uniform, except seed Returns: a Tensor
[ "Random", "uniform", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4611-L4623
train
tensorflow/mesh
mesh_tensorflow/ops.py
dropout
def dropout(x, keep_prob, noise_shape=None, name=None): """Dropout layer. Args: x: a Tensor keep_prob: a float between 0.0 and 1.0 noise_shape: an optional Shape (a subset of x.shape) name: an optional string Returns: a Tensor """ noise_shape = convert_to_shape(noise_shape) if noise_sh...
python
def dropout(x, keep_prob, noise_shape=None, name=None): """Dropout layer. Args: x: a Tensor keep_prob: a float between 0.0 and 1.0 noise_shape: an optional Shape (a subset of x.shape) name: an optional string Returns: a Tensor """ noise_shape = convert_to_shape(noise_shape) if noise_sh...
[ "def", "dropout", "(", "x", ",", "keep_prob", ",", "noise_shape", "=", "None", ",", "name", "=", "None", ")", ":", "noise_shape", "=", "convert_to_shape", "(", "noise_shape", ")", "if", "noise_shape", "is", "None", ":", "noise_shape", "=", "x", ".", "sha...
Dropout layer. Args: x: a Tensor keep_prob: a float between 0.0 and 1.0 noise_shape: an optional Shape (a subset of x.shape) name: an optional string Returns: a Tensor
[ "Dropout", "layer", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4626-L4647
train
tensorflow/mesh
mesh_tensorflow/ops.py
_cumprod
def _cumprod(l): """Cumulative product of a list. Args: l: a list of integers Returns: a list with one more element (starting with 1) """ ret = [1] for item in l: ret.append(ret[-1] * item) return ret
python
def _cumprod(l): """Cumulative product of a list. Args: l: a list of integers Returns: a list with one more element (starting with 1) """ ret = [1] for item in l: ret.append(ret[-1] * item) return ret
[ "def", "_cumprod", "(", "l", ")", ":", "ret", "=", "[", "1", "]", "for", "item", "in", "l", ":", "ret", ".", "append", "(", "ret", "[", "-", "1", "]", "*", "item", ")", "return", "ret" ]
Cumulative product of a list. Args: l: a list of integers Returns: a list with one more element (starting with 1)
[ "Cumulative", "product", "of", "a", "list", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4650-L4661
train
tensorflow/mesh
mesh_tensorflow/ops.py
while_loop
def while_loop(cond_fn, body_fn, inputs, num_loop_vars=None, has_accumulators=False, **kwargs): """While Loop. See comments above for WhileLoopOperation num_loop_vars is a hack for the multi-gpu setup. In this case, loops are generally slow, as all loop variables are placed on device. By sett...
python
def while_loop(cond_fn, body_fn, inputs, num_loop_vars=None, has_accumulators=False, **kwargs): """While Loop. See comments above for WhileLoopOperation num_loop_vars is a hack for the multi-gpu setup. In this case, loops are generally slow, as all loop variables are placed on device. By sett...
[ "def", "while_loop", "(", "cond_fn", ",", "body_fn", ",", "inputs", ",", "num_loop_vars", "=", "None", ",", "has_accumulators", "=", "False", ",", "**", "kwargs", ")", ":", "if", "num_loop_vars", "is", "None", ":", "return", "WhileLoopOperation", "(", "cond_...
While Loop. See comments above for WhileLoopOperation num_loop_vars is a hack for the multi-gpu setup. In this case, loops are generally slow, as all loop variables are placed on device. By setting num_loop_vars=k, then all of the loop variables except for the first k are handled as mtf Variables instead ...
[ "While", "Loop", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4855-L4910
train
tensorflow/mesh
mesh_tensorflow/ops.py
_shape_union
def _shape_union(shapes): """A shape containing the union of all dimensions in the input shapes. Args: shapes: a list of Shapes Returns: a Shape """ return Shape(sorted(list(set(sum([s.dims for s in shapes], [])))))
python
def _shape_union(shapes): """A shape containing the union of all dimensions in the input shapes. Args: shapes: a list of Shapes Returns: a Shape """ return Shape(sorted(list(set(sum([s.dims for s in shapes], [])))))
[ "def", "_shape_union", "(", "shapes", ")", ":", "return", "Shape", "(", "sorted", "(", "list", "(", "set", "(", "sum", "(", "[", "s", ".", "dims", "for", "s", "in", "shapes", "]", ",", "[", "]", ")", ")", ")", ")", ")" ]
A shape containing the union of all dimensions in the input shapes. Args: shapes: a list of Shapes Returns: a Shape
[ "A", "shape", "containing", "the", "union", "of", "all", "dimensions", "in", "the", "input", "shapes", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4921-L4930
train
tensorflow/mesh
mesh_tensorflow/ops.py
_tf_flatten_batch_dims
def _tf_flatten_batch_dims(x, num_nonbatch_dims): """Flatten all but last num_nonbatch_dims into one dimension. Args: x: a tf.Tensor: num_nonbatch_dims: an integer Returns: a tf.Tensor with 1 + num_nonbatch_dims dimensions. """ shape = x.shape.as_list() assert None not in shape new_shape = (...
python
def _tf_flatten_batch_dims(x, num_nonbatch_dims): """Flatten all but last num_nonbatch_dims into one dimension. Args: x: a tf.Tensor: num_nonbatch_dims: an integer Returns: a tf.Tensor with 1 + num_nonbatch_dims dimensions. """ shape = x.shape.as_list() assert None not in shape new_shape = (...
[ "def", "_tf_flatten_batch_dims", "(", "x", ",", "num_nonbatch_dims", ")", ":", "shape", "=", "x", ".", "shape", ".", "as_list", "(", ")", "assert", "None", "not", "in", "shape", "new_shape", "=", "(", "[", "list_product", "(", "shape", "[", ":", "-", "...
Flatten all but last num_nonbatch_dims into one dimension. Args: x: a tf.Tensor: num_nonbatch_dims: an integer Returns: a tf.Tensor with 1 + num_nonbatch_dims dimensions.
[ "Flatten", "all", "but", "last", "num_nonbatch_dims", "into", "one", "dimension", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4933-L4949
train
tensorflow/mesh
mesh_tensorflow/ops.py
_tf_restore_batch_dims
def _tf_restore_batch_dims(x, num_nonbatch_dims, prototype): """Reverse op of _tf_flatten_batch_dims. Un-flatten the first dimension of x to match all but the last num_nonbatch_dims dimensions of prototype. Args: x: a tf.Tensor with 1 + num_nonbatch_dims dimensions num_nonbatch_dims: an integer pr...
python
def _tf_restore_batch_dims(x, num_nonbatch_dims, prototype): """Reverse op of _tf_flatten_batch_dims. Un-flatten the first dimension of x to match all but the last num_nonbatch_dims dimensions of prototype. Args: x: a tf.Tensor with 1 + num_nonbatch_dims dimensions num_nonbatch_dims: an integer pr...
[ "def", "_tf_restore_batch_dims", "(", "x", ",", "num_nonbatch_dims", ",", "prototype", ")", ":", "assert", "x", ".", "shape", ".", "ndims", "==", "1", "+", "num_nonbatch_dims", "new_shape", "=", "(", "prototype", ".", "shape", ".", "as_list", "(", ")", "["...
Reverse op of _tf_flatten_batch_dims. Un-flatten the first dimension of x to match all but the last num_nonbatch_dims dimensions of prototype. Args: x: a tf.Tensor with 1 + num_nonbatch_dims dimensions num_nonbatch_dims: an integer prototype: a tf.Tensor Returns: a tf.Tensor
[ "Reverse", "op", "of", "_tf_flatten_batch_dims", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4952-L4972
train
tensorflow/mesh
mesh_tensorflow/ops.py
halo_exchange
def halo_exchange(x, blocks_dim, block_size_dim, halo_size, wrap=False): """Concat each block with the margins of adjacent blocks. Get left and right blocks_dim and concatenate along block_size_dim. Args: x: a Tensor. blocks_dim: a Dimension in x.shape block_size_dim: a Dimension in x.shape halo...
python
def halo_exchange(x, blocks_dim, block_size_dim, halo_size, wrap=False): """Concat each block with the margins of adjacent blocks. Get left and right blocks_dim and concatenate along block_size_dim. Args: x: a Tensor. blocks_dim: a Dimension in x.shape block_size_dim: a Dimension in x.shape halo...
[ "def", "halo_exchange", "(", "x", ",", "blocks_dim", ",", "block_size_dim", ",", "halo_size", ",", "wrap", "=", "False", ")", ":", "if", "halo_size", "==", "0", ":", "return", "x", "block_size", "=", "block_size_dim", ".", "size", "partial_size", "=", "hal...
Concat each block with the margins of adjacent blocks. Get left and right blocks_dim and concatenate along block_size_dim. Args: x: a Tensor. blocks_dim: a Dimension in x.shape block_size_dim: a Dimension in x.shape halo_size: an integer wrap: a boolean Returns: a Tensor with the same s...
[ "Concat", "each", "block", "with", "the", "margins", "of", "adjacent", "blocks", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4975-L5011
train
tensorflow/mesh
mesh_tensorflow/ops.py
conv2d_with_blocks
def conv2d_with_blocks( conv_input, conv_filter, strides, padding, h_blocks_dim=None, w_blocks_dim=None, name=None): """conv2d operation with spatial partitioning. Spatial partitioning is implemented by decomposing the image into blocks. Block dimensions represented as h_blocks_dim an...
python
def conv2d_with_blocks( conv_input, conv_filter, strides, padding, h_blocks_dim=None, w_blocks_dim=None, name=None): """conv2d operation with spatial partitioning. Spatial partitioning is implemented by decomposing the image into blocks. Block dimensions represented as h_blocks_dim an...
[ "def", "conv2d_with_blocks", "(", "conv_input", ",", "conv_filter", ",", "strides", ",", "padding", ",", "h_blocks_dim", "=", "None", ",", "w_blocks_dim", "=", "None", ",", "name", "=", "None", ")", ":", "filter_h_dim", ",", "filter_w_dim", "=", "conv_filter",...
conv2d operation with spatial partitioning. Spatial partitioning is implemented by decomposing the image into blocks. Block dimensions represented as h_blocks_dim and w_blocks_dim can be split along the mesh axis. If split, then we do a halo exchange where each block receives the part of the image from its lef...
[ "conv2d", "operation", "with", "spatial", "partitioning", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L5049-L5108
train
tensorflow/mesh
mesh_tensorflow/ops.py
tensor_dim_to_mesh_dim_size
def tensor_dim_to_mesh_dim_size(layout, mesh_shape, tensor_dim): """How many ways does a tensor dimension get split. This is used to "cheat" when building the mtf graph and peek at how a tensor dimension will be split. Returns 1 if the tensor dimension is not split. Args: layout: an input to convert_to...
python
def tensor_dim_to_mesh_dim_size(layout, mesh_shape, tensor_dim): """How many ways does a tensor dimension get split. This is used to "cheat" when building the mtf graph and peek at how a tensor dimension will be split. Returns 1 if the tensor dimension is not split. Args: layout: an input to convert_to...
[ "def", "tensor_dim_to_mesh_dim_size", "(", "layout", ",", "mesh_shape", ",", "tensor_dim", ")", ":", "layout_rules", "=", "convert_to_layout_rules", "(", "layout", ")", "mesh_shape", "=", "convert_to_shape", "(", "mesh_shape", ")", "mesh_axis", "=", "layout_rules", ...
How many ways does a tensor dimension get split. This is used to "cheat" when building the mtf graph and peek at how a tensor dimension will be split. Returns 1 if the tensor dimension is not split. Args: layout: an input to convert_to_layout_rules mesh_shape: an input to convert_to_shape tensor_...
[ "How", "many", "ways", "does", "a", "tensor", "dimension", "get", "split", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L5111-L5132
train
tensorflow/mesh
mesh_tensorflow/ops.py
serialize_training_step
def serialize_training_step(features, model_fn, batch_dim, num_splits): """Break the training batch into multiple microbatches. Returns two structures: grads - a list of Tensors corresponding to the gradients on graph.trainable_variables. These are summed across all microbatches outputs - a dictionary ...
python
def serialize_training_step(features, model_fn, batch_dim, num_splits): """Break the training batch into multiple microbatches. Returns two structures: grads - a list of Tensors corresponding to the gradients on graph.trainable_variables. These are summed across all microbatches outputs - a dictionary ...
[ "def", "serialize_training_step", "(", "features", ",", "model_fn", ",", "batch_dim", ",", "num_splits", ")", ":", "for", "v", "in", "features", ".", "values", "(", ")", ":", "mesh", "=", "v", ".", "mesh", "graph", "=", "v", ".", "graph", "microbatch_dim...
Break the training batch into multiple microbatches. Returns two structures: grads - a list of Tensors corresponding to the gradients on graph.trainable_variables. These are summed across all microbatches outputs - a dictionary of Tensors corresponding to the output dictionary of model_fn. Each va...
[ "Break", "the", "training", "batch", "into", "multiple", "microbatches", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L5146-L5231
train
tensorflow/mesh
mesh_tensorflow/ops.py
Shape.rename_dimension
def rename_dimension(self, old_name, new_name): """Returns a copy where one dimension is renamed.""" if old_name not in self.dimension_names: raise ValueError("Shape %s does not have dimension named %s" % (self, old_name)) return Shape( [Dimension(new_name, d.size) if d....
python
def rename_dimension(self, old_name, new_name): """Returns a copy where one dimension is renamed.""" if old_name not in self.dimension_names: raise ValueError("Shape %s does not have dimension named %s" % (self, old_name)) return Shape( [Dimension(new_name, d.size) if d....
[ "def", "rename_dimension", "(", "self", ",", "old_name", ",", "new_name", ")", ":", "if", "old_name", "not", "in", "self", ".", "dimension_names", ":", "raise", "ValueError", "(", "\"Shape %s does not have dimension named %s\"", "%", "(", "self", ",", "old_name", ...
Returns a copy where one dimension is renamed.
[ "Returns", "a", "copy", "where", "one", "dimension", "is", "renamed", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L163-L170
train
tensorflow/mesh
mesh_tensorflow/ops.py
Shape.resize_dimension
def resize_dimension(self, name, new_size): """Returns a copy where one dimension has a different size.""" if name not in self.dimension_names: raise ValueError("Shape %s does not have dimension named %s" % (self, name)) return Shape( [Dimension(name, new_size) if d.name...
python
def resize_dimension(self, name, new_size): """Returns a copy where one dimension has a different size.""" if name not in self.dimension_names: raise ValueError("Shape %s does not have dimension named %s" % (self, name)) return Shape( [Dimension(name, new_size) if d.name...
[ "def", "resize_dimension", "(", "self", ",", "name", ",", "new_size", ")", ":", "if", "name", "not", "in", "self", ".", "dimension_names", ":", "raise", "ValueError", "(", "\"Shape %s does not have dimension named %s\"", "%", "(", "self", ",", "name", ")", ")"...
Returns a copy where one dimension has a different size.
[ "Returns", "a", "copy", "where", "one", "dimension", "has", "a", "different", "size", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L172-L179
train
tensorflow/mesh
mesh_tensorflow/ops.py
LayoutRules.tensor_layout
def tensor_layout(self, tensor_shape, mesh_shape): """Computes TensorLayout given a Tensor Shape and a Mesh Shape. Args: tensor_shape: Shape. mesh_shape: Shape. Returns: TensorLayout. Raises: ValueError: If two Tensor Dimensions map to the same Mesh Dimensions. """ ret...
python
def tensor_layout(self, tensor_shape, mesh_shape): """Computes TensorLayout given a Tensor Shape and a Mesh Shape. Args: tensor_shape: Shape. mesh_shape: Shape. Returns: TensorLayout. Raises: ValueError: If two Tensor Dimensions map to the same Mesh Dimensions. """ ret...
[ "def", "tensor_layout", "(", "self", ",", "tensor_shape", ",", "mesh_shape", ")", ":", "ret", "=", "[", "self", ".", "tensor_dimension_to_mesh_axis", "(", "d", ",", "mesh_shape", ")", "for", "d", "in", "tensor_shape", "]", "not_nones", "=", "[", "a", "for"...
Computes TensorLayout given a Tensor Shape and a Mesh Shape. Args: tensor_shape: Shape. mesh_shape: Shape. Returns: TensorLayout. Raises: ValueError: If two Tensor Dimensions map to the same Mesh Dimensions.
[ "Computes", "TensorLayout", "given", "a", "Tensor", "Shape", "and", "a", "Mesh", "Shape", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L247-L268
train
tensorflow/mesh
mesh_tensorflow/ops.py
TensorLayout.mesh_axis_to_tensor_axis
def mesh_axis_to_tensor_axis(self, mesh_ndims): """For each mesh axis, which Tensor axis maps to it. Args: mesh_ndims: int. Returns: Tuple of optional integers, with length mesh_ndims. """ ta2ma = self._tensor_axis_to_mesh_axis return tuple( [ta2ma.index(mesh_axis) if mesh_...
python
def mesh_axis_to_tensor_axis(self, mesh_ndims): """For each mesh axis, which Tensor axis maps to it. Args: mesh_ndims: int. Returns: Tuple of optional integers, with length mesh_ndims. """ ta2ma = self._tensor_axis_to_mesh_axis return tuple( [ta2ma.index(mesh_axis) if mesh_...
[ "def", "mesh_axis_to_tensor_axis", "(", "self", ",", "mesh_ndims", ")", ":", "ta2ma", "=", "self", ".", "_tensor_axis_to_mesh_axis", "return", "tuple", "(", "[", "ta2ma", ".", "index", "(", "mesh_axis", ")", "if", "mesh_axis", "in", "ta2ma", "else", "None", ...
For each mesh axis, which Tensor axis maps to it. Args: mesh_ndims: int. Returns: Tuple of optional integers, with length mesh_ndims.
[ "For", "each", "mesh", "axis", "which", "Tensor", "axis", "maps", "to", "it", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L339-L351
train
tensorflow/mesh
mesh_tensorflow/ops.py
Graph.unique_name
def unique_name(self, name, mark_as_used=True): """Like tf.Graph.unique_name, returns a unique operation name for `name`. Args: name: The name for an operation. mark_as_used: whether to mark this name as being used. Returns: A string to use as the name for the operation. """ scop...
python
def unique_name(self, name, mark_as_used=True): """Like tf.Graph.unique_name, returns a unique operation name for `name`. Args: name: The name for an operation. mark_as_used: whether to mark this name as being used. Returns: A string to use as the name for the operation. """ scop...
[ "def", "unique_name", "(", "self", ",", "name", ",", "mark_as_used", "=", "True", ")", ":", "scope_name", "=", "tf", ".", "get_variable_scope", "(", ")", ".", "name", "if", "scope_name", ":", "name", "=", "scope_name", "+", "\"/\"", "+", "name", "name_ke...
Like tf.Graph.unique_name, returns a unique operation name for `name`. Args: name: The name for an operation. mark_as_used: whether to mark this name as being used. Returns: A string to use as the name for the operation.
[ "Like", "tf", ".", "Graph", ".", "unique_name", "returns", "a", "unique", "operation", "name", "for", "name", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L384-L413
train
tensorflow/mesh
mesh_tensorflow/ops.py
Graph.combine_assignments
def combine_assignments(self, assignments): """Rewrite the current graph to combine "Assign" operations. Combine similar Assign operations into grouped Assign operations. This is useful when using the rewrite_stack_variables() optimization, since variables can only be stacked if they are present in the...
python
def combine_assignments(self, assignments): """Rewrite the current graph to combine "Assign" operations. Combine similar Assign operations into grouped Assign operations. This is useful when using the rewrite_stack_variables() optimization, since variables can only be stacked if they are present in the...
[ "def", "combine_assignments", "(", "self", ",", "assignments", ")", ":", "group_by_fn", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "a", "in", "assignments", ":", "if", "not", "isinstance", "(", "a", ",", "Assign", ")", ":", "raise", ...
Rewrite the current graph to combine "Assign" operations. Combine similar Assign operations into grouped Assign operations. This is useful when using the rewrite_stack_variables() optimization, since variables can only be stacked if they are present in the same set of Assign operations. This funct...
[ "Rewrite", "the", "current", "graph", "to", "combine", "Assign", "operations", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L534-L567
train
tensorflow/mesh
mesh_tensorflow/ops.py
MeshImpl.tensor_layout
def tensor_layout(self, arg): """Compute TensorLayout for a Tensor or a Shape. Args: arg: Tensor or Shape. Returns: TensorLayout. """ if isinstance(arg, Tensor): arg = arg.shape return self.layout_rules.tensor_layout(arg, self.shape)
python
def tensor_layout(self, arg): """Compute TensorLayout for a Tensor or a Shape. Args: arg: Tensor or Shape. Returns: TensorLayout. """ if isinstance(arg, Tensor): arg = arg.shape return self.layout_rules.tensor_layout(arg, self.shape)
[ "def", "tensor_layout", "(", "self", ",", "arg", ")", ":", "if", "isinstance", "(", "arg", ",", "Tensor", ")", ":", "arg", "=", "arg", ".", "shape", "return", "self", ".", "layout_rules", ".", "tensor_layout", "(", "arg", ",", "self", ".", "shape", "...
Compute TensorLayout for a Tensor or a Shape. Args: arg: Tensor or Shape. Returns: TensorLayout.
[ "Compute", "TensorLayout", "for", "a", "Tensor", "or", "a", "Shape", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L803-L814
train
tensorflow/mesh
mesh_tensorflow/ops.py
MeshImpl.mesh_axis_to_cumprod
def mesh_axis_to_cumprod(self, tensor_shape): """For each mesh axis, give the product of previous tensor axes. Args: tensor_shape: Shape. Returns: list with length self.ndims where each element is an integer or None. """ tensor_layout = self.tensor_layout(tensor_shape) ma2ta = tens...
python
def mesh_axis_to_cumprod(self, tensor_shape): """For each mesh axis, give the product of previous tensor axes. Args: tensor_shape: Shape. Returns: list with length self.ndims where each element is an integer or None. """ tensor_layout = self.tensor_layout(tensor_shape) ma2ta = tens...
[ "def", "mesh_axis_to_cumprod", "(", "self", ",", "tensor_shape", ")", ":", "tensor_layout", "=", "self", ".", "tensor_layout", "(", "tensor_shape", ")", "ma2ta", "=", "tensor_layout", ".", "mesh_axis_to_tensor_axis", "(", "self", ".", "ndims", ")", "ta2cumprod", ...
For each mesh axis, give the product of previous tensor axes. Args: tensor_shape: Shape. Returns: list with length self.ndims where each element is an integer or None.
[ "For", "each", "mesh", "axis", "give", "the", "product", "of", "previous", "tensor", "axes", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L816-L828
train
tensorflow/mesh
mesh_tensorflow/ops.py
MeshImpl.slice_shape
def slice_shape(self, tensor_shape): """Shape of each slice of the Tensor. Args: tensor_shape: Shape. Returns: list of integers with length tensor_shape.ndims. Raises: ValueError: If a Tensor dimension is not divisible by the corresponding Mesh dimension. """ tensor_...
python
def slice_shape(self, tensor_shape): """Shape of each slice of the Tensor. Args: tensor_shape: Shape. Returns: list of integers with length tensor_shape.ndims. Raises: ValueError: If a Tensor dimension is not divisible by the corresponding Mesh dimension. """ tensor_...
[ "def", "slice_shape", "(", "self", ",", "tensor_shape", ")", ":", "tensor_layout", "=", "self", ".", "tensor_layout", "(", "tensor_shape", ")", "ret", "=", "[", "]", "for", "tensor_dim", ",", "mesh_axis", "in", "zip", "(", "tensor_shape", ",", "tensor_layout...
Shape of each slice of the Tensor. Args: tensor_shape: Shape. Returns: list of integers with length tensor_shape.ndims. Raises: ValueError: If a Tensor dimension is not divisible by the corresponding Mesh dimension.
[ "Shape", "of", "each", "slice", "of", "the", "Tensor", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L830-L857
train
tensorflow/mesh
mesh_tensorflow/ops.py
MeshImpl.slice_begin
def slice_begin(self, tensor_shape, pnum): """Begin position for the tensor slice for the given processor. Args: tensor_shape: Shape. pnum: int <= self.size. Returns: list of integers with length tensor_shape.ndims. """ tensor_layout = self.tensor_layout(tensor_shape) coordin...
python
def slice_begin(self, tensor_shape, pnum): """Begin position for the tensor slice for the given processor. Args: tensor_shape: Shape. pnum: int <= self.size. Returns: list of integers with length tensor_shape.ndims. """ tensor_layout = self.tensor_layout(tensor_shape) coordin...
[ "def", "slice_begin", "(", "self", ",", "tensor_shape", ",", "pnum", ")", ":", "tensor_layout", "=", "self", ".", "tensor_layout", "(", "tensor_shape", ")", "coordinates", "=", "pnum_to_processor_coordinates", "(", "self", ".", "shape", ",", "pnum", ")", "ret"...
Begin position for the tensor slice for the given processor. Args: tensor_shape: Shape. pnum: int <= self.size. Returns: list of integers with length tensor_shape.ndims.
[ "Begin", "position", "for", "the", "tensor", "slice", "for", "the", "given", "processor", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L859-L879
train
tensorflow/mesh
mesh_tensorflow/ops.py
MeshImpl.Print
def Print(self, x, data, message, **kwargs): # pylint: disable=invalid-name """Calls tf.Print. Args: x: LaidOutTensor. data: list of LaidOutTensor. message: str. **kwargs: keyword arguments to tf.print. Returns: LaidOutTensor. """ del data, message, kwargs tf.log...
python
def Print(self, x, data, message, **kwargs): # pylint: disable=invalid-name """Calls tf.Print. Args: x: LaidOutTensor. data: list of LaidOutTensor. message: str. **kwargs: keyword arguments to tf.print. Returns: LaidOutTensor. """ del data, message, kwargs tf.log...
[ "def", "Print", "(", "self", ",", "x", ",", "data", ",", "message", ",", "**", "kwargs", ")", ":", "del", "data", ",", "message", ",", "kwargs", "tf", ".", "logging", ".", "warning", "(", "\"Warning - mtf.Print not implemented for this mesh type\"", ")", "re...
Calls tf.Print. Args: x: LaidOutTensor. data: list of LaidOutTensor. message: str. **kwargs: keyword arguments to tf.print. Returns: LaidOutTensor.
[ "Calls", "tf", ".", "Print", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L908-L922
train
tensorflow/mesh
mesh_tensorflow/ops.py
MeshImpl.allsplit
def allsplit(self, x, mesh_axis, split_axis, which=None): """Inverse of allconcat - split each slice and keep only one piece of it. The number of ways to split is the number of processors in the group. The part that is kept corresponds to the processor's index in the group. Args: x: LaidOutTenso...
python
def allsplit(self, x, mesh_axis, split_axis, which=None): """Inverse of allconcat - split each slice and keep only one piece of it. The number of ways to split is the number of processors in the group. The part that is kept corresponds to the processor's index in the group. Args: x: LaidOutTenso...
[ "def", "allsplit", "(", "self", ",", "x", ",", "mesh_axis", ",", "split_axis", ",", "which", "=", "None", ")", ":", "if", "which", "is", "None", ":", "which", "=", "self", ".", "laid_out_pcoord", "(", "mesh_axis", ")", "num_splits", "=", "self", ".", ...
Inverse of allconcat - split each slice and keep only one piece of it. The number of ways to split is the number of processors in the group. The part that is kept corresponds to the processor's index in the group. Args: x: LaidOutTensor. mesh_axis: int, the mesh axis along which to split. ...
[ "Inverse", "of", "allconcat", "-", "split", "each", "slice", "and", "keep", "only", "one", "piece", "of", "it", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L937-L964
train
tensorflow/mesh
mesh_tensorflow/ops.py
MeshImpl.shift_by_n_processors
def shift_by_n_processors(self, x, mesh_axis, offset, wrap): """Receive the slice from processor pcoord - offset. Args: x: a LaidOutTensor mesh_axis: an integer offset: an integer wrap: a boolean. If True, then wrap around. Otherwise, pad with zeros. """ n = self.shape[mesh_axis...
python
def shift_by_n_processors(self, x, mesh_axis, offset, wrap): """Receive the slice from processor pcoord - offset. Args: x: a LaidOutTensor mesh_axis: an integer offset: an integer wrap: a boolean. If True, then wrap around. Otherwise, pad with zeros. """ n = self.shape[mesh_axis...
[ "def", "shift_by_n_processors", "(", "self", ",", "x", ",", "mesh_axis", ",", "offset", ",", "wrap", ")", ":", "n", "=", "self", ".", "shape", "[", "mesh_axis", "]", ".", "size", "source_pcoord", "=", "[", "]", "for", "i", "in", "xrange", "(", "n", ...
Receive the slice from processor pcoord - offset. Args: x: a LaidOutTensor mesh_axis: an integer offset: an integer wrap: a boolean. If True, then wrap around. Otherwise, pad with zeros.
[ "Receive", "the", "slice", "from", "processor", "pcoord", "-", "offset", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1017-L1036
train
tensorflow/mesh
mesh_tensorflow/ops.py
MeshImpl.laid_out_pcoord
def laid_out_pcoord(self, mesh_axis): """Returns a LaidOutTensor containing the processor coordinate. Args: mesh_axis: int. Returns: LaidOutTensor where each slice is an integer scalar. """ divisor = list_product(self.shape.to_integer_list[mesh_axis + 1:]) modulus = self.shape[mesh...
python
def laid_out_pcoord(self, mesh_axis): """Returns a LaidOutTensor containing the processor coordinate. Args: mesh_axis: int. Returns: LaidOutTensor where each slice is an integer scalar. """ divisor = list_product(self.shape.to_integer_list[mesh_axis + 1:]) modulus = self.shape[mesh...
[ "def", "laid_out_pcoord", "(", "self", ",", "mesh_axis", ")", ":", "divisor", "=", "list_product", "(", "self", ".", "shape", ".", "to_integer_list", "[", "mesh_axis", "+", "1", ":", "]", ")", "modulus", "=", "self", ".", "shape", "[", "mesh_axis", "]", ...
Returns a LaidOutTensor containing the processor coordinate. Args: mesh_axis: int. Returns: LaidOutTensor where each slice is an integer scalar.
[ "Returns", "a", "LaidOutTensor", "containing", "the", "processor", "coordinate", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1046-L1059
train
tensorflow/mesh
mesh_tensorflow/ops.py
MeshImpl.laid_out_slice_num
def laid_out_slice_num(self, tensor_shape): """A LaidOutTensor with an int32 scalar, identical for identical slices. This is useful for synchronizing random operations. Args: tensor_shape: a TensorShape Returns: a LaidOutTensor where each slice is an integer scalar. """ ret = self....
python
def laid_out_slice_num(self, tensor_shape): """A LaidOutTensor with an int32 scalar, identical for identical slices. This is useful for synchronizing random operations. Args: tensor_shape: a TensorShape Returns: a LaidOutTensor where each slice is an integer scalar. """ ret = self....
[ "def", "laid_out_slice_num", "(", "self", ",", "tensor_shape", ")", ":", "ret", "=", "self", ".", "slicewise", "(", "lambda", ":", "tf", ".", "to_int32", "(", "0", ")", ")", "tensor_layout", "=", "self", ".", "tensor_layout", "(", "tensor_shape", ")", "f...
A LaidOutTensor with an int32 scalar, identical for identical slices. This is useful for synchronizing random operations. Args: tensor_shape: a TensorShape Returns: a LaidOutTensor where each slice is an integer scalar.
[ "A", "LaidOutTensor", "with", "an", "int32", "scalar", "identical", "for", "identical", "slices", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1061-L1080
train
tensorflow/mesh
mesh_tensorflow/ops.py
MeshImpl.broadcast_impl
def broadcast_impl(self, old_slices, old_shape, new_shape): """Implementation of a broadcast operation. Args: old_slices: LaidOutTensor. old_shape: Shape. new_shape: Shape. Returns: LaidOutTensor. """ new_slice_shape = self.slice_shape(new_shape) def tf_fn(x): ret...
python
def broadcast_impl(self, old_slices, old_shape, new_shape): """Implementation of a broadcast operation. Args: old_slices: LaidOutTensor. old_shape: Shape. new_shape: Shape. Returns: LaidOutTensor. """ new_slice_shape = self.slice_shape(new_shape) def tf_fn(x): ret...
[ "def", "broadcast_impl", "(", "self", ",", "old_slices", ",", "old_shape", ",", "new_shape", ")", ":", "new_slice_shape", "=", "self", ".", "slice_shape", "(", "new_shape", ")", "def", "tf_fn", "(", "x", ")", ":", "return", "(", "tf", ".", "zeros", "(", ...
Implementation of a broadcast operation. Args: old_slices: LaidOutTensor. old_shape: Shape. new_shape: Shape. Returns: LaidOutTensor.
[ "Implementation", "of", "a", "broadcast", "operation", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1082-L1097
train
tensorflow/mesh
mesh_tensorflow/ops.py
MeshImpl.make_slices
def make_slices(self, tf_tensor, tensor_shape): """Turns a single tf.Tensor into a list of slices, one for each processor. Args: tf_tensor: tf.Tensor. tensor_shape: Shape. Returns: list of tf.tensor with length self.size. """ tensor_layout = self.tensor_layout(tensor_shape) s...
python
def make_slices(self, tf_tensor, tensor_shape): """Turns a single tf.Tensor into a list of slices, one for each processor. Args: tf_tensor: tf.Tensor. tensor_shape: Shape. Returns: list of tf.tensor with length self.size. """ tensor_layout = self.tensor_layout(tensor_shape) s...
[ "def", "make_slices", "(", "self", ",", "tf_tensor", ",", "tensor_shape", ")", ":", "tensor_layout", "=", "self", ".", "tensor_layout", "(", "tensor_shape", ")", "slice_shape", "=", "self", ".", "slice_shape", "(", "tensor_shape", ")", "def", "my_fn", "(", "...
Turns a single tf.Tensor into a list of slices, one for each processor. Args: tf_tensor: tf.Tensor. tensor_shape: Shape. Returns: list of tf.tensor with length self.size.
[ "Turns", "a", "single", "tf", ".", "Tensor", "into", "a", "list", "of", "slices", "one", "for", "each", "processor", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1099-L1119
train
tensorflow/mesh
mesh_tensorflow/ops.py
MeshImpl.combine_slices
def combine_slices(self, slices, tensor_shape, device=None): """Turns a set of slices into a single tensor. Args: slices: list of tf.Tensor with length self.size. tensor_shape: Shape. device: optional str. If absent, we use the devices of the slices. Returns: tf.Tensor. """ ...
python
def combine_slices(self, slices, tensor_shape, device=None): """Turns a set of slices into a single tensor. Args: slices: list of tf.Tensor with length self.size. tensor_shape: Shape. device: optional str. If absent, we use the devices of the slices. Returns: tf.Tensor. """ ...
[ "def", "combine_slices", "(", "self", ",", "slices", ",", "tensor_shape", ",", "device", "=", "None", ")", ":", "if", "tensor_shape", ".", "ndims", "==", "0", ":", "return", "slices", "[", "0", "]", "ret", "=", "slices", "[", ":", "]", "tensor_layout",...
Turns a set of slices into a single tensor. Args: slices: list of tf.Tensor with length self.size. tensor_shape: Shape. device: optional str. If absent, we use the devices of the slices. Returns: tf.Tensor.
[ "Turns", "a", "set", "of", "slices", "into", "a", "single", "tensor", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1121-L1155
train
tensorflow/mesh
mesh_tensorflow/ops.py
Operation._initialize_splittable_and_unsplittable_dims
def _initialize_splittable_and_unsplittable_dims( self, default_splittability, exception_dims_iterable=None): """Initializer for splittable_dims and unsplittable_dims. Helper method to categorize all dimensions in the input/output tensors as either splittable or unsplittable. Args: default...
python
def _initialize_splittable_and_unsplittable_dims( self, default_splittability, exception_dims_iterable=None): """Initializer for splittable_dims and unsplittable_dims. Helper method to categorize all dimensions in the input/output tensors as either splittable or unsplittable. Args: default...
[ "def", "_initialize_splittable_and_unsplittable_dims", "(", "self", ",", "default_splittability", ",", "exception_dims_iterable", "=", "None", ")", ":", "default_dims", "=", "set", "(", ")", "exception_dims", "=", "set", "(", ")", "if", "exception_dims_iterable", ":",...
Initializer for splittable_dims and unsplittable_dims. Helper method to categorize all dimensions in the input/output tensors as either splittable or unsplittable. Args: default_splittability: a string which is either "splittable" or "unsplittable". exception_dims_iterable: an optional...
[ "Initializer", "for", "splittable_dims", "and", "unsplittable_dims", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1448-L1486
train
tensorflow/mesh
mesh_tensorflow/ops.py
ReshapeOperation.lower
def lower(self, lowering): """Lower the ReshapeOperation. Reshaping can require collective communication between processors. We haven't yet implemented all possible reshapes. We try to handle the common cases here - otherwise we raise a NotImplementedError. Args: lowering: a Lowering Ra...
python
def lower(self, lowering): """Lower the ReshapeOperation. Reshaping can require collective communication between processors. We haven't yet implemented all possible reshapes. We try to handle the common cases here - otherwise we raise a NotImplementedError. Args: lowering: a Lowering Ra...
[ "def", "lower", "(", "self", ",", "lowering", ")", ":", "old_shape", "=", "self", ".", "inputs", "[", "0", "]", ".", "shape", "new_shape", "=", "self", ".", "outputs", "[", "0", "]", ".", "shape", "mesh_impl", "=", "lowering", ".", "mesh_impl", "(", ...
Lower the ReshapeOperation. Reshaping can require collective communication between processors. We haven't yet implemented all possible reshapes. We try to handle the common cases here - otherwise we raise a NotImplementedError. Args: lowering: a Lowering Raises: NotImplementedError: i...
[ "Lower", "the", "ReshapeOperation", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3478-L3558
train
tensorflow/mesh
mesh_tensorflow/transformer/utils.py
get_variable_dtype
def get_variable_dtype( master_dtype=tf.bfloat16, slice_dtype=tf.float32, activation_dtype=tf.float32): """Datatypes to use for the run. Args: master_dtype: string, datatype for checkpoints keep this the same between training and eval/inference slice_dtype: string, datatype for variables ...
python
def get_variable_dtype( master_dtype=tf.bfloat16, slice_dtype=tf.float32, activation_dtype=tf.float32): """Datatypes to use for the run. Args: master_dtype: string, datatype for checkpoints keep this the same between training and eval/inference slice_dtype: string, datatype for variables ...
[ "def", "get_variable_dtype", "(", "master_dtype", "=", "tf", ".", "bfloat16", ",", "slice_dtype", "=", "tf", ".", "float32", ",", "activation_dtype", "=", "tf", ".", "float32", ")", ":", "return", "mtf", ".", "VariableDType", "(", "master_dtype", "=", "tf", ...
Datatypes to use for the run. Args: master_dtype: string, datatype for checkpoints keep this the same between training and eval/inference slice_dtype: string, datatype for variables in memory must be tf.float32 for training activation_dtype: string, datatype for activations less memory ...
[ "Datatypes", "to", "use", "for", "the", "run", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/utils.py#L38-L57
train
tensorflow/mesh
mesh_tensorflow/transformer/utils.py
build_model
def build_model(model_type="bitransformer", input_vocab_size=gin.REQUIRED, output_vocab_size=gin.REQUIRED, layout_rules=None, mesh_shape=None): """Build a transformer model. Currently, three types of models are supported: "bitransformer": The tradi...
python
def build_model(model_type="bitransformer", input_vocab_size=gin.REQUIRED, output_vocab_size=gin.REQUIRED, layout_rules=None, mesh_shape=None): """Build a transformer model. Currently, three types of models are supported: "bitransformer": The tradi...
[ "def", "build_model", "(", "model_type", "=", "\"bitransformer\"", ",", "input_vocab_size", "=", "gin", ".", "REQUIRED", ",", "output_vocab_size", "=", "gin", ".", "REQUIRED", ",", "layout_rules", "=", "None", ",", "mesh_shape", "=", "None", ")", ":", "if", ...
Build a transformer model. Currently, three types of models are supported: "bitransformer": The traditional encoder-decoder architecture from "attention is all you need". Requires a non-text2self dataset. "lm": an autoregressive language model (one layer stack). This is similar to the decoder part ...
[ "Build", "a", "transformer", "model", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/utils.py#L94-L139
train
tensorflow/mesh
mesh_tensorflow/transformer/utils.py
decode_from_file
def decode_from_file(estimator, vocabulary, model_type, batch_size, sequence_length, checkpoint_path="", input_filename=gin.REQUIRED, output_filename=gin.REQUIRED, ...
python
def decode_from_file(estimator, vocabulary, model_type, batch_size, sequence_length, checkpoint_path="", input_filename=gin.REQUIRED, output_filename=gin.REQUIRED, ...
[ "def", "decode_from_file", "(", "estimator", ",", "vocabulary", ",", "model_type", ",", "batch_size", ",", "sequence_length", ",", "checkpoint_path", "=", "\"\"", ",", "input_filename", "=", "gin", ".", "REQUIRED", ",", "output_filename", "=", "gin", ".", "REQUI...
Decode from a text file. Args: estimator: a TPUEstimator vocabulary: a mtf.transformer.vocabulary.Vocabulary model_type: a string batch_size: an integer sequence_length: an integer (maximum decode length) checkpoint_path: an optional string input_filename: a string output_filename: a ...
[ "Decode", "from", "a", "text", "file", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/utils.py#L385-L473
train
tensorflow/mesh
mesh_tensorflow/transformer/utils.py
clean_decodes
def clean_decodes(ids, vocab_size, eos_id=1): """Stop at EOS or padding or OOV. Args: ids: a list of integers vocab_size: an integer eos_id: EOS id Returns: a list of integers """ ret = [] for i in ids: if i == eos_id: break if i >= vocab_size: break ret.append(int(...
python
def clean_decodes(ids, vocab_size, eos_id=1): """Stop at EOS or padding or OOV. Args: ids: a list of integers vocab_size: an integer eos_id: EOS id Returns: a list of integers """ ret = [] for i in ids: if i == eos_id: break if i >= vocab_size: break ret.append(int(...
[ "def", "clean_decodes", "(", "ids", ",", "vocab_size", ",", "eos_id", "=", "1", ")", ":", "ret", "=", "[", "]", "for", "i", "in", "ids", ":", "if", "i", "==", "eos_id", ":", "break", "if", "i", ">=", "vocab_size", ":", "break", "ret", ".", "appen...
Stop at EOS or padding or OOV. Args: ids: a list of integers vocab_size: an integer eos_id: EOS id Returns: a list of integers
[ "Stop", "at", "EOS", "or", "padding", "or", "OOV", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/utils.py#L477-L495
train
tensorflow/mesh
mesh_tensorflow/transformer/utils.py
auto_batch_size
def auto_batch_size(sequence_length, mesh_shape, layout_rules, tokens_per_split=2048): """Automatically compute batch size. Args: sequence_length: an integer mesh_shape: an input to mtf.convert_to_shape() layout_rules: an input to mtf.convert_...
python
def auto_batch_size(sequence_length, mesh_shape, layout_rules, tokens_per_split=2048): """Automatically compute batch size. Args: sequence_length: an integer mesh_shape: an input to mtf.convert_to_shape() layout_rules: an input to mtf.convert_...
[ "def", "auto_batch_size", "(", "sequence_length", ",", "mesh_shape", ",", "layout_rules", ",", "tokens_per_split", "=", "2048", ")", ":", "num_splits", "=", "mtf", ".", "tensor_dim_to_mesh_dim_size", "(", "layout_rules", ",", "mesh_shape", ",", "mtf", ".", "Dimens...
Automatically compute batch size. Args: sequence_length: an integer mesh_shape: an input to mtf.convert_to_shape() layout_rules: an input to mtf.convert_to_layout_rules() tokens_per_split: an integer Returns: an integer
[ "Automatically", "compute", "batch", "size", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/utils.py#L499-L520
train
tensorflow/mesh
mesh_tensorflow/transformer/utils.py
evaluate
def evaluate(estimator, eval_args): """Runs evaluation on the latest model checkpoint & logs to tensorboard. Args: estimator: A tf.Estimator object. eval_args: Dictionary of {eval_name: (input_fn, eval_steps)} where eval_name is the name of the evaluation set, e.g. "train" or "val", input_fn is an ...
python
def evaluate(estimator, eval_args): """Runs evaluation on the latest model checkpoint & logs to tensorboard. Args: estimator: A tf.Estimator object. eval_args: Dictionary of {eval_name: (input_fn, eval_steps)} where eval_name is the name of the evaluation set, e.g. "train" or "val", input_fn is an ...
[ "def", "evaluate", "(", "estimator", ",", "eval_args", ")", ":", "values", "=", "{", "}", "checkpoint_path", "=", "estimator", ".", "latest_checkpoint", "(", ")", "if", "not", "checkpoint_path", ":", "return", "values", "tf", ".", "logging", ".", "info", "...
Runs evaluation on the latest model checkpoint & logs to tensorboard. Args: estimator: A tf.Estimator object. eval_args: Dictionary of {eval_name: (input_fn, eval_steps)} where eval_name is the name of the evaluation set, e.g. "train" or "val", input_fn is an input function returning a tuple (fea...
[ "Runs", "evaluation", "on", "the", "latest", "model", "checkpoint", "&", "logs", "to", "tensorboard", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/utils.py#L715-L750
train
tensorflow/mesh
mesh_tensorflow/simd_mesh_impl.py
_ring_2d
def _ring_2d(m, n): """Ring-order of a mxn mesh. Args: m: an integer n: an integer Returns: a list of mxn pairs """ if m == 1: return [(0, i) for i in range(n)] if n == 1: return [(i, 0) for i in range(m)] if m % 2 != 0: tf.logging.warning("Odd dimension") return [(i % m, i //...
python
def _ring_2d(m, n): """Ring-order of a mxn mesh. Args: m: an integer n: an integer Returns: a list of mxn pairs """ if m == 1: return [(0, i) for i in range(n)] if n == 1: return [(i, 0) for i in range(m)] if m % 2 != 0: tf.logging.warning("Odd dimension") return [(i % m, i //...
[ "def", "_ring_2d", "(", "m", ",", "n", ")", ":", "if", "m", "==", "1", ":", "return", "[", "(", "0", ",", "i", ")", "for", "i", "in", "range", "(", "n", ")", "]", "if", "n", "==", "1", ":", "return", "[", "(", "i", ",", "0", ")", "for",...
Ring-order of a mxn mesh. Args: m: an integer n: an integer Returns: a list of mxn pairs
[ "Ring", "-", "order", "of", "a", "mxn", "mesh", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/simd_mesh_impl.py#L568-L592
train
tensorflow/mesh
mesh_tensorflow/simd_mesh_impl.py
tile_2d
def tile_2d(physical_shape, tile_shape, outer_name="outer", inner_name="inner", cores_name=None): """2D tiling of a 3d physical mesh. The "outer" mesh dimension corresponds to which tile. The "inner" mesh dimension corresponds to the position within a tile of processors. ...
python
def tile_2d(physical_shape, tile_shape, outer_name="outer", inner_name="inner", cores_name=None): """2D tiling of a 3d physical mesh. The "outer" mesh dimension corresponds to which tile. The "inner" mesh dimension corresponds to the position within a tile of processors. ...
[ "def", "tile_2d", "(", "physical_shape", ",", "tile_shape", ",", "outer_name", "=", "\"outer\"", ",", "inner_name", "=", "\"inner\"", ",", "cores_name", "=", "None", ")", ":", "logical_to_physical", "=", "[", "]", "p0", ",", "p1", ",", "p2", "=", "physical...
2D tiling of a 3d physical mesh. The "outer" mesh dimension corresponds to which tile. The "inner" mesh dimension corresponds to the position within a tile of processors. Optionally, if cores_name is specified, then a 3 dimensional logical mesh is returned, with the third dimension representing the two diff...
[ "2D", "tiling", "of", "a", "3d", "physical", "mesh", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/simd_mesh_impl.py#L595-L661
train
tensorflow/mesh
mesh_tensorflow/simd_mesh_impl.py
SimdMeshImpl.slice
def slice(self, tf_tensor, tensor_shape): """"Slice out the corresponding part of tensor given the pnum variable.""" tensor_layout = self.tensor_layout(tensor_shape) if tensor_layout.is_fully_replicated: return self.LaidOutTensor([tf_tensor]) else: slice_shape = self.slice_shape(tensor_shap...
python
def slice(self, tf_tensor, tensor_shape): """"Slice out the corresponding part of tensor given the pnum variable.""" tensor_layout = self.tensor_layout(tensor_shape) if tensor_layout.is_fully_replicated: return self.LaidOutTensor([tf_tensor]) else: slice_shape = self.slice_shape(tensor_shap...
[ "def", "slice", "(", "self", ",", "tf_tensor", ",", "tensor_shape", ")", ":", "tensor_layout", "=", "self", ".", "tensor_layout", "(", "tensor_shape", ")", "if", "tensor_layout", ".", "is_fully_replicated", ":", "return", "self", ".", "LaidOutTensor", "(", "["...
Slice out the corresponding part of tensor given the pnum variable.
[ "Slice", "out", "the", "corresponding", "part", "of", "tensor", "given", "the", "pnum", "variable", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/simd_mesh_impl.py#L443-L458
train
tensorflow/mesh
examples/mnist_dataset.py
read32
def read32(bytestream): """Read 4 bytes from bytestream as an unsigned 32-bit integer.""" dt = np.dtype(np.uint32).newbyteorder('>') return np.frombuffer(bytestream.read(4), dtype=dt)[0]
python
def read32(bytestream): """Read 4 bytes from bytestream as an unsigned 32-bit integer.""" dt = np.dtype(np.uint32).newbyteorder('>') return np.frombuffer(bytestream.read(4), dtype=dt)[0]
[ "def", "read32", "(", "bytestream", ")", ":", "dt", "=", "np", ".", "dtype", "(", "np", ".", "uint32", ")", ".", "newbyteorder", "(", "'>'", ")", "return", "np", ".", "frombuffer", "(", "bytestream", ".", "read", "(", "4", ")", ",", "dtype", "=", ...
Read 4 bytes from bytestream as an unsigned 32-bit integer.
[ "Read", "4", "bytes", "from", "bytestream", "as", "an", "unsigned", "32", "-", "bit", "integer", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/mnist_dataset.py#L45-L48
train
tensorflow/mesh
examples/mnist_dataset.py
check_image_file_header
def check_image_file_header(filename): """Validate that filename corresponds to images for the MNIST dataset.""" with tf.gfile.Open(filename, 'rb') as f: magic = read32(f) read32(f) # num_images, unused rows = read32(f) cols = read32(f) if magic != 2051: raise ValueError('Invalid magic nu...
python
def check_image_file_header(filename): """Validate that filename corresponds to images for the MNIST dataset.""" with tf.gfile.Open(filename, 'rb') as f: magic = read32(f) read32(f) # num_images, unused rows = read32(f) cols = read32(f) if magic != 2051: raise ValueError('Invalid magic nu...
[ "def", "check_image_file_header", "(", "filename", ")", ":", "with", "tf", ".", "gfile", ".", "Open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "magic", "=", "read32", "(", "f", ")", "read32", "(", "f", ")", "rows", "=", "read32", "(", "f"...
Validate that filename corresponds to images for the MNIST dataset.
[ "Validate", "that", "filename", "corresponds", "to", "images", "for", "the", "MNIST", "dataset", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/mnist_dataset.py#L51-L64
train
tensorflow/mesh
examples/mnist_dataset.py
check_labels_file_header
def check_labels_file_header(filename): """Validate that filename corresponds to labels for the MNIST dataset.""" with tf.gfile.Open(filename, 'rb') as f: magic = read32(f) read32(f) # num_items, unused if magic != 2049: raise ValueError('Invalid magic number %d in MNIST file %s' % (magic, ...
python
def check_labels_file_header(filename): """Validate that filename corresponds to labels for the MNIST dataset.""" with tf.gfile.Open(filename, 'rb') as f: magic = read32(f) read32(f) # num_items, unused if magic != 2049: raise ValueError('Invalid magic number %d in MNIST file %s' % (magic, ...
[ "def", "check_labels_file_header", "(", "filename", ")", ":", "with", "tf", ".", "gfile", ".", "Open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "magic", "=", "read32", "(", "f", ")", "read32", "(", "f", ")", "if", "magic", "!=", "2049", "...
Validate that filename corresponds to labels for the MNIST dataset.
[ "Validate", "that", "filename", "corresponds", "to", "labels", "for", "the", "MNIST", "dataset", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/mnist_dataset.py#L67-L74
train
tensorflow/mesh
examples/mnist_dataset.py
dataset
def dataset(directory, images_file, labels_file): """Download and parse MNIST dataset.""" images_file = download(directory, images_file) labels_file = download(directory, labels_file) check_image_file_header(images_file) check_labels_file_header(labels_file) def decode_image(image): # Normalize from ...
python
def dataset(directory, images_file, labels_file): """Download and parse MNIST dataset.""" images_file = download(directory, images_file) labels_file = download(directory, labels_file) check_image_file_header(images_file) check_labels_file_header(labels_file) def decode_image(image): # Normalize from ...
[ "def", "dataset", "(", "directory", ",", "images_file", ",", "labels_file", ")", ":", "images_file", "=", "download", "(", "directory", ",", "images_file", ")", "labels_file", "=", "download", "(", "directory", ",", "labels_file", ")", "check_image_file_header", ...
Download and parse MNIST dataset.
[ "Download", "and", "parse", "MNIST", "dataset", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/mnist_dataset.py#L95-L120
train
mattjj/pyhsmm
pyhsmm/util/stats.py
sample_discrete
def sample_discrete(distn,size=[],dtype=np.int32): 'samples from a one-dimensional finite pmf' distn = np.atleast_1d(distn) assert (distn >=0).all() and distn.ndim == 1 if (0 == distn).all(): return np.random.randint(distn.shape[0],size=size) cumvals = np.cumsum(distn) return np.sum(np.a...
python
def sample_discrete(distn,size=[],dtype=np.int32): 'samples from a one-dimensional finite pmf' distn = np.atleast_1d(distn) assert (distn >=0).all() and distn.ndim == 1 if (0 == distn).all(): return np.random.randint(distn.shape[0],size=size) cumvals = np.cumsum(distn) return np.sum(np.a...
[ "def", "sample_discrete", "(", "distn", ",", "size", "=", "[", "]", ",", "dtype", "=", "np", ".", "int32", ")", ":", "'samples from a one-dimensional finite pmf'", "distn", "=", "np", ".", "atleast_1d", "(", "distn", ")", "assert", "(", "distn", ">=", "0",...
samples from a one-dimensional finite pmf
[ "samples", "from", "a", "one", "-", "dimensional", "finite", "pmf" ]
a9a39c2bfd539048e35877cb13283552eadc24e2
https://github.com/mattjj/pyhsmm/blob/a9a39c2bfd539048e35877cb13283552eadc24e2/pyhsmm/util/stats.py#L116-L123
train
mattjj/pyhsmm
pyhsmm/models.py
_HMMBase.used_states
def used_states(self): 'a list of the used states in the order they appear' c = itertools.count() canonical_ids = collections.defaultdict(lambda: next(c)) for s in self.states_list: for state in s.stateseq: canonical_ids[state] return list(map(operator...
python
def used_states(self): 'a list of the used states in the order they appear' c = itertools.count() canonical_ids = collections.defaultdict(lambda: next(c)) for s in self.states_list: for state in s.stateseq: canonical_ids[state] return list(map(operator...
[ "def", "used_states", "(", "self", ")", ":", "'a list of the used states in the order they appear'", "c", "=", "itertools", ".", "count", "(", ")", "canonical_ids", "=", "collections", ".", "defaultdict", "(", "lambda", ":", "next", "(", "c", ")", ")", "for", ...
a list of the used states in the order they appear
[ "a", "list", "of", "the", "used", "states", "in", "the", "order", "they", "appear" ]
a9a39c2bfd539048e35877cb13283552eadc24e2
https://github.com/mattjj/pyhsmm/blob/a9a39c2bfd539048e35877cb13283552eadc24e2/pyhsmm/models.py#L188-L196
train
mattjj/pyhsmm
pyhsmm/util/plot.py
plot_gaussian_2D
def plot_gaussian_2D(mu, lmbda, color='b', centermarker=True,label='',alpha=1.,ax=None,artists=None): ''' Plots mean and cov ellipsoid into current axes. Must be 2D. lmbda is a covariance matrix. ''' assert len(mu) == 2 ax = ax if ax else plt.gca() # TODO use artists! t = np.hstack([np.ara...
python
def plot_gaussian_2D(mu, lmbda, color='b', centermarker=True,label='',alpha=1.,ax=None,artists=None): ''' Plots mean and cov ellipsoid into current axes. Must be 2D. lmbda is a covariance matrix. ''' assert len(mu) == 2 ax = ax if ax else plt.gca() # TODO use artists! t = np.hstack([np.ara...
[ "def", "plot_gaussian_2D", "(", "mu", ",", "lmbda", ",", "color", "=", "'b'", ",", "centermarker", "=", "True", ",", "label", "=", "''", ",", "alpha", "=", "1.", ",", "ax", "=", "None", ",", "artists", "=", "None", ")", ":", "assert", "len", "(", ...
Plots mean and cov ellipsoid into current axes. Must be 2D. lmbda is a covariance matrix.
[ "Plots", "mean", "and", "cov", "ellipsoid", "into", "current", "axes", ".", "Must", "be", "2D", ".", "lmbda", "is", "a", "covariance", "matrix", "." ]
a9a39c2bfd539048e35877cb13283552eadc24e2
https://github.com/mattjj/pyhsmm/blob/a9a39c2bfd539048e35877cb13283552eadc24e2/pyhsmm/util/plot.py#L7-L34
train
mattjj/pyhsmm
pyhsmm/basic/abstractions.py
DurationDistribution.resample_with_censoring
def resample_with_censoring(self,data=[],censored_data=[]): ''' censored_data is full of observations that were censored, meaning a value of x really could have been anything >= x, so this method samples them out to be at least that large ''' filled_in = self._uncensor_da...
python
def resample_with_censoring(self,data=[],censored_data=[]): ''' censored_data is full of observations that were censored, meaning a value of x really could have been anything >= x, so this method samples them out to be at least that large ''' filled_in = self._uncensor_da...
[ "def", "resample_with_censoring", "(", "self", ",", "data", "=", "[", "]", ",", "censored_data", "=", "[", "]", ")", ":", "filled_in", "=", "self", ".", "_uncensor_data", "(", "censored_data", ")", "return", "self", ".", "resample", "(", "data", "=", "co...
censored_data is full of observations that were censored, meaning a value of x really could have been anything >= x, so this method samples them out to be at least that large
[ "censored_data", "is", "full", "of", "observations", "that", "were", "censored", "meaning", "a", "value", "of", "x", "really", "could", "have", "been", "anything", ">", "=", "x", "so", "this", "method", "samples", "them", "out", "to", "be", "at", "least", ...
a9a39c2bfd539048e35877cb13283552eadc24e2
https://github.com/mattjj/pyhsmm/blob/a9a39c2bfd539048e35877cb13283552eadc24e2/pyhsmm/basic/abstractions.py#L70-L77
train
mattjj/pyhsmm
pyhsmm/util/general.py
scoreatpercentile
def scoreatpercentile(data,per,axis=0): 'like the function in scipy.stats but with an axis argument and works on arrays' a = np.sort(data,axis=axis) idx = per/100. * (data.shape[axis]-1) if (idx % 1 == 0): return a[[slice(None) if ii != axis else idx for ii in range(a.ndim)]] else: ...
python
def scoreatpercentile(data,per,axis=0): 'like the function in scipy.stats but with an axis argument and works on arrays' a = np.sort(data,axis=axis) idx = per/100. * (data.shape[axis]-1) if (idx % 1 == 0): return a[[slice(None) if ii != axis else idx for ii in range(a.ndim)]] else: ...
[ "def", "scoreatpercentile", "(", "data", ",", "per", ",", "axis", "=", "0", ")", ":", "'like the function in scipy.stats but with an axis argument and works on arrays'", "a", "=", "np", ".", "sort", "(", "data", ",", "axis", "=", "axis", ")", "idx", "=", "per", ...
like the function in scipy.stats but with an axis argument and works on arrays
[ "like", "the", "function", "in", "scipy", ".", "stats", "but", "with", "an", "axis", "argument", "and", "works", "on", "arrays" ]
a9a39c2bfd539048e35877cb13283552eadc24e2
https://github.com/mattjj/pyhsmm/blob/a9a39c2bfd539048e35877cb13283552eadc24e2/pyhsmm/util/general.py#L119-L131
train
lk-geimfari/mimesis
mimesis/providers/internet.py
Internet.content_type
def content_type(self, mime_type: Optional[MimeType] = None) -> str: """Get a random HTTP content type. :return: Content type. :Example: Content-Type: application/json """ fmt = self.__file.mime_type(type_=mime_type) return 'Content-Type: {}'.format(fmt)
python
def content_type(self, mime_type: Optional[MimeType] = None) -> str: """Get a random HTTP content type. :return: Content type. :Example: Content-Type: application/json """ fmt = self.__file.mime_type(type_=mime_type) return 'Content-Type: {}'.format(fmt)
[ "def", "content_type", "(", "self", ",", "mime_type", ":", "Optional", "[", "MimeType", "]", "=", "None", ")", "->", "str", ":", "fmt", "=", "self", ".", "__file", ".", "mime_type", "(", "type_", "=", "mime_type", ")", "return", "'Content-Type: {}'", "."...
Get a random HTTP content type. :return: Content type. :Example: Content-Type: application/json
[ "Get", "a", "random", "HTTP", "content", "type", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L46-L55
train
lk-geimfari/mimesis
mimesis/providers/internet.py
Internet.ip_v4
def ip_v4(self, with_port: bool = False) -> str: """Generate a random IPv4 address. :param with_port: Add port to IP. :return: Random IPv4 address. :Example: 19.121.223.58 """ ip = '.'.join(str(self.random.randint(0, 255)) for _ in range(4)) if with...
python
def ip_v4(self, with_port: bool = False) -> str: """Generate a random IPv4 address. :param with_port: Add port to IP. :return: Random IPv4 address. :Example: 19.121.223.58 """ ip = '.'.join(str(self.random.randint(0, 255)) for _ in range(4)) if with...
[ "def", "ip_v4", "(", "self", ",", "with_port", ":", "bool", "=", "False", ")", "->", "str", ":", "ip", "=", "'.'", ".", "join", "(", "str", "(", "self", ".", "random", ".", "randint", "(", "0", ",", "255", ")", ")", "for", "_", "in", "range", ...
Generate a random IPv4 address. :param with_port: Add port to IP. :return: Random IPv4 address. :Example: 19.121.223.58
[ "Generate", "a", "random", "IPv4", "address", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L87-L101
train
lk-geimfari/mimesis
mimesis/providers/internet.py
Internet.ip_v6
def ip_v6(self) -> str: """Generate a random IPv6 address. :return: Random IPv6 address. :Example: 2001:c244:cf9d:1fb1:c56d:f52c:8a04:94f3 """ ipv6 = IPv6Address( self.random.randint( 0, 2 ** 128 - 1, ), ) retu...
python
def ip_v6(self) -> str: """Generate a random IPv6 address. :return: Random IPv6 address. :Example: 2001:c244:cf9d:1fb1:c56d:f52c:8a04:94f3 """ ipv6 = IPv6Address( self.random.randint( 0, 2 ** 128 - 1, ), ) retu...
[ "def", "ip_v6", "(", "self", ")", "->", "str", ":", "ipv6", "=", "IPv6Address", "(", "self", ".", "random", ".", "randint", "(", "0", ",", "2", "**", "128", "-", "1", ",", ")", ",", ")", "return", "str", "(", "ipv6", ")" ]
Generate a random IPv6 address. :return: Random IPv6 address. :Example: 2001:c244:cf9d:1fb1:c56d:f52c:8a04:94f3
[ "Generate", "a", "random", "IPv6", "address", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L103-L116
train
lk-geimfari/mimesis
mimesis/providers/internet.py
Internet.mac_address
def mac_address(self) -> str: """Generate a random MAC address. :return: Random MAC address. :Example: 00:16:3e:25:e7:b1 """ mac_hex = [ 0x00, 0x16, 0x3e, self.random.randint(0x00, 0x7f), self.random.randint(0x00, 0xff), ...
python
def mac_address(self) -> str: """Generate a random MAC address. :return: Random MAC address. :Example: 00:16:3e:25:e7:b1 """ mac_hex = [ 0x00, 0x16, 0x3e, self.random.randint(0x00, 0x7f), self.random.randint(0x00, 0xff), ...
[ "def", "mac_address", "(", "self", ")", "->", "str", ":", "mac_hex", "=", "[", "0x00", ",", "0x16", ",", "0x3e", ",", "self", ".", "random", ".", "randint", "(", "0x00", ",", "0x7f", ")", ",", "self", ".", "random", ".", "randint", "(", "0x00", "...
Generate a random MAC address. :return: Random MAC address. :Example: 00:16:3e:25:e7:b1
[ "Generate", "a", "random", "MAC", "address", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L118-L133
train
lk-geimfari/mimesis
mimesis/providers/internet.py
Internet.image_placeholder
def image_placeholder(width: Union[int, str] = 1920, height: Union[int, str] = 1080) -> str: """Generate a link to the image placeholder. :param width: Width of image. :param height: Height of image. :return: URL to image placeholder. """ url = ...
python
def image_placeholder(width: Union[int, str] = 1920, height: Union[int, str] = 1080) -> str: """Generate a link to the image placeholder. :param width: Width of image. :param height: Height of image. :return: URL to image placeholder. """ url = ...
[ "def", "image_placeholder", "(", "width", ":", "Union", "[", "int", ",", "str", "]", "=", "1920", ",", "height", ":", "Union", "[", "int", ",", "str", "]", "=", "1080", ")", "->", "str", ":", "url", "=", "'http://placehold.it/{width}x{height}'", "return"...
Generate a link to the image placeholder. :param width: Width of image. :param height: Height of image. :return: URL to image placeholder.
[ "Generate", "a", "link", "to", "the", "image", "placeholder", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L146-L155
train
lk-geimfari/mimesis
mimesis/providers/internet.py
Internet.hashtags
def hashtags(self, quantity: int = 4) -> Union[str, list]: """Generate a list of hashtags. :param quantity: The quantity of hashtags. :return: The list of hashtags. :raises NonEnumerableError: if category is not in Hashtag. :Example: ['#love', '#sky', '#nice'] ...
python
def hashtags(self, quantity: int = 4) -> Union[str, list]: """Generate a list of hashtags. :param quantity: The quantity of hashtags. :return: The list of hashtags. :raises NonEnumerableError: if category is not in Hashtag. :Example: ['#love', '#sky', '#nice'] ...
[ "def", "hashtags", "(", "self", ",", "quantity", ":", "int", "=", "4", ")", "->", "Union", "[", "str", ",", "list", "]", ":", "tags", "=", "[", "'#'", "+", "self", ".", "random", ".", "choice", "(", "HASHTAGS", ")", "for", "_", "in", "range", "...
Generate a list of hashtags. :param quantity: The quantity of hashtags. :return: The list of hashtags. :raises NonEnumerableError: if category is not in Hashtag. :Example: ['#love', '#sky', '#nice']
[ "Generate", "a", "list", "of", "hashtags", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L191-L207
train
lk-geimfari/mimesis
mimesis/providers/internet.py
Internet.home_page
def home_page(self, tld_type: Optional[TLDType] = None) -> str: """Generate a random home page. :param tld_type: TLD type. :return: Random home page. :Example: http://www.fontir.info """ resource = self.random.choice(USERNAMES) domain = self.top_leve...
python
def home_page(self, tld_type: Optional[TLDType] = None) -> str: """Generate a random home page. :param tld_type: TLD type. :return: Random home page. :Example: http://www.fontir.info """ resource = self.random.choice(USERNAMES) domain = self.top_leve...
[ "def", "home_page", "(", "self", ",", "tld_type", ":", "Optional", "[", "TLDType", "]", "=", "None", ")", "->", "str", ":", "resource", "=", "self", ".", "random", ".", "choice", "(", "USERNAMES", ")", "domain", "=", "self", ".", "top_level_domain", "(...
Generate a random home page. :param tld_type: TLD type. :return: Random home page. :Example: http://www.fontir.info
[ "Generate", "a", "random", "home", "page", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L209-L224
train