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
Phylliade/ikpy
scripts/hand_follow.py
follow_hand
def follow_hand(poppy, delta): """Tell the right hand to follow the left hand""" right_arm_position = poppy.l_arm_chain.end_effector + delta poppy.r_arm_chain.goto(right_arm_position, 0.5, wait=True)
python
def follow_hand(poppy, delta): """Tell the right hand to follow the left hand""" right_arm_position = poppy.l_arm_chain.end_effector + delta poppy.r_arm_chain.goto(right_arm_position, 0.5, wait=True)
[ "def", "follow_hand", "(", "poppy", ",", "delta", ")", ":", "right_arm_position", "=", "poppy", ".", "l_arm_chain", ".", "end_effector", "+", "delta", "poppy", ".", "r_arm_chain", ".", "goto", "(", "right_arm_position", ",", "0.5", ",", "wait", "=", "True", ...
Tell the right hand to follow the left hand
[ "Tell", "the", "right", "hand", "to", "follow", "the", "left", "hand" ]
60e36d6163136942bf520d952db17123c658d0b6
https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/scripts/hand_follow.py#L27-L30
train
Phylliade/ikpy
src/ikpy/inverse_kinematics.py
inverse_kinematic_optimization
def inverse_kinematic_optimization(chain, target_frame, starting_nodes_angles, regularization_parameter=None, max_iter=None): """ Computes the inverse kinematic on the specified target with an optimization method Parameters ---------- chain: ikpy.chain.Chain The chain used for the Inverse k...
python
def inverse_kinematic_optimization(chain, target_frame, starting_nodes_angles, regularization_parameter=None, max_iter=None): """ Computes the inverse kinematic on the specified target with an optimization method Parameters ---------- chain: ikpy.chain.Chain The chain used for the Inverse k...
[ "def", "inverse_kinematic_optimization", "(", "chain", ",", "target_frame", ",", "starting_nodes_angles", ",", "regularization_parameter", "=", "None", ",", "max_iter", "=", "None", ")", ":", "target", "=", "target_frame", "[", ":", "3", ",", "3", "]", "if", "...
Computes the inverse kinematic on the specified target with an optimization method Parameters ---------- chain: ikpy.chain.Chain The chain used for the Inverse kinematics. target_frame: numpy.array The desired target. starting_nodes_angles: numpy.array The initial pose of yo...
[ "Computes", "the", "inverse", "kinematic", "on", "the", "specified", "target", "with", "an", "optimization", "method" ]
60e36d6163136942bf520d952db17123c658d0b6
https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/inverse_kinematics.py#L7-L61
train
Phylliade/ikpy
src/ikpy/chain.py
Chain.forward_kinematics
def forward_kinematics(self, joints, full_kinematics=False): """Returns the transformation matrix of the forward kinematics Parameters ---------- joints: list The list of the positions of each joint. Note : Inactive joints must be in the list. full_kinematics: bool ...
python
def forward_kinematics(self, joints, full_kinematics=False): """Returns the transformation matrix of the forward kinematics Parameters ---------- joints: list The list of the positions of each joint. Note : Inactive joints must be in the list. full_kinematics: bool ...
[ "def", "forward_kinematics", "(", "self", ",", "joints", ",", "full_kinematics", "=", "False", ")", ":", "frame_matrix", "=", "np", ".", "eye", "(", "4", ")", "if", "full_kinematics", ":", "frame_matrixes", "=", "[", "]", "if", "len", "(", "self", ".", ...
Returns the transformation matrix of the forward kinematics Parameters ---------- joints: list The list of the positions of each joint. Note : Inactive joints must be in the list. full_kinematics: bool Return the transformation matrices of each joint Ret...
[ "Returns", "the", "transformation", "matrix", "of", "the", "forward", "kinematics" ]
60e36d6163136942bf520d952db17123c658d0b6
https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/chain.py#L48-L83
train
Phylliade/ikpy
src/ikpy/chain.py
Chain.inverse_kinematics
def inverse_kinematics(self, target, initial_position=None, **kwargs): """Computes the inverse kinematic on the specified target Parameters ---------- target: numpy.array The frame target of the inverse kinematic, in meters. It must be 4x4 transformation matrix initi...
python
def inverse_kinematics(self, target, initial_position=None, **kwargs): """Computes the inverse kinematic on the specified target Parameters ---------- target: numpy.array The frame target of the inverse kinematic, in meters. It must be 4x4 transformation matrix initi...
[ "def", "inverse_kinematics", "(", "self", ",", "target", ",", "initial_position", "=", "None", ",", "**", "kwargs", ")", ":", "target", "=", "np", ".", "array", "(", "target", ")", "if", "target", ".", "shape", "!=", "(", "4", ",", "4", ")", ":", "...
Computes the inverse kinematic on the specified target Parameters ---------- target: numpy.array The frame target of the inverse kinematic, in meters. It must be 4x4 transformation matrix initial_position: numpy.array Optional : the initial position of each joint...
[ "Computes", "the", "inverse", "kinematic", "on", "the", "specified", "target" ]
60e36d6163136942bf520d952db17123c658d0b6
https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/chain.py#L85-L107
train
Phylliade/ikpy
src/ikpy/chain.py
Chain.plot
def plot(self, joints, ax, target=None, show=False): """Plots the Chain using Matplotlib Parameters ---------- joints: list The list of the positions of each joint ax: matplotlib.axes.Axes A matplotlib axes target: numpy.array An optio...
python
def plot(self, joints, ax, target=None, show=False): """Plots the Chain using Matplotlib Parameters ---------- joints: list The list of the positions of each joint ax: matplotlib.axes.Axes A matplotlib axes target: numpy.array An optio...
[ "def", "plot", "(", "self", ",", "joints", ",", "ax", ",", "target", "=", "None", ",", "show", "=", "False", ")", ":", "from", ".", "import", "plot_utils", "if", "ax", "is", "None", ":", "ax", "=", "plot_utils", ".", "init_3d_figure", "(", ")", "pl...
Plots the Chain using Matplotlib Parameters ---------- joints: list The list of the positions of each joint ax: matplotlib.axes.Axes A matplotlib axes target: numpy.array An optional target show: bool Display the axe. Defau...
[ "Plots", "the", "Chain", "using", "Matplotlib" ]
60e36d6163136942bf520d952db17123c658d0b6
https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/chain.py#L109-L135
train
Phylliade/ikpy
src/ikpy/chain.py
Chain.from_urdf_file
def from_urdf_file(cls, urdf_file, base_elements=None, last_link_vector=None, base_element_type="link", active_links_mask=None, name="chain"): """Creates a chain from an URDF file Parameters ---------- urdf_file: str The path of the URDF file base_elements: list of s...
python
def from_urdf_file(cls, urdf_file, base_elements=None, last_link_vector=None, base_element_type="link", active_links_mask=None, name="chain"): """Creates a chain from an URDF file Parameters ---------- urdf_file: str The path of the URDF file base_elements: list of s...
[ "def", "from_urdf_file", "(", "cls", ",", "urdf_file", ",", "base_elements", "=", "None", ",", "last_link_vector", "=", "None", ",", "base_element_type", "=", "\"link\"", ",", "active_links_mask", "=", "None", ",", "name", "=", "\"chain\"", ")", ":", "if", "...
Creates a chain from an URDF file Parameters ---------- urdf_file: str The path of the URDF file base_elements: list of strings List of the links beginning the chain last_link_vector: numpy.array Optional : The translation vector of the tip. ...
[ "Creates", "a", "chain", "from", "an", "URDF", "file" ]
60e36d6163136942bf520d952db17123c658d0b6
https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/chain.py#L138-L159
train
blockchain-certificates/cert-issuer
cert_issuer/signer.py
check_internet_off
def check_internet_off(secrets_file_path): """If internet off and USB plugged in, returns true. Else, continues to wait...""" while True: if internet_on() is False and os.path.exists(secrets_file_path): break else: print("Turn off your internet and plug in your USB to con...
python
def check_internet_off(secrets_file_path): """If internet off and USB plugged in, returns true. Else, continues to wait...""" while True: if internet_on() is False and os.path.exists(secrets_file_path): break else: print("Turn off your internet and plug in your USB to con...
[ "def", "check_internet_off", "(", "secrets_file_path", ")", ":", "while", "True", ":", "if", "internet_on", "(", ")", "is", "False", "and", "os", ".", "path", ".", "exists", "(", "secrets_file_path", ")", ":", "break", "else", ":", "print", "(", "\"Turn of...
If internet off and USB plugged in, returns true. Else, continues to wait...
[ "If", "internet", "off", "and", "USB", "plugged", "in", "returns", "true", ".", "Else", "continues", "to", "wait", "..." ]
e8a48e25472473b149bd411a9fd5f2ff0f8f100a
https://github.com/blockchain-certificates/cert-issuer/blob/e8a48e25472473b149bd411a9fd5f2ff0f8f100a/cert_issuer/signer.py#L66-L74
train
blockchain-certificates/cert-issuer
cert_issuer/signer.py
check_internet_on
def check_internet_on(secrets_file_path): """If internet on and USB unplugged, returns true. Else, continues to wait...""" while True: if internet_on() is True and not os.path.exists(secrets_file_path): break else: print("Turn on your internet and unplug your USB to conti...
python
def check_internet_on(secrets_file_path): """If internet on and USB unplugged, returns true. Else, continues to wait...""" while True: if internet_on() is True and not os.path.exists(secrets_file_path): break else: print("Turn on your internet and unplug your USB to conti...
[ "def", "check_internet_on", "(", "secrets_file_path", ")", ":", "while", "True", ":", "if", "internet_on", "(", ")", "is", "True", "and", "not", "os", ".", "path", ".", "exists", "(", "secrets_file_path", ")", ":", "break", "else", ":", "print", "(", "\"...
If internet on and USB unplugged, returns true. Else, continues to wait...
[ "If", "internet", "on", "and", "USB", "unplugged", "returns", "true", ".", "Else", "continues", "to", "wait", "..." ]
e8a48e25472473b149bd411a9fd5f2ff0f8f100a
https://github.com/blockchain-certificates/cert-issuer/blob/e8a48e25472473b149bd411a9fd5f2ff0f8f100a/cert_issuer/signer.py#L77-L85
train
blockchain-certificates/cert-issuer
cert_issuer/blockchain_handlers/bitcoin/signer.py
verify_signature
def verify_signature(uid, signed_cert_file_name, issuing_address): """ Verify the certificate signature matches the expected. Double-check the uid field in the certificate and use VerifyMessage to confirm that the signature in the certificate matches the issuing_address. Raises error is verification fa...
python
def verify_signature(uid, signed_cert_file_name, issuing_address): """ Verify the certificate signature matches the expected. Double-check the uid field in the certificate and use VerifyMessage to confirm that the signature in the certificate matches the issuing_address. Raises error is verification fa...
[ "def", "verify_signature", "(", "uid", ",", "signed_cert_file_name", ",", "issuing_address", ")", ":", "logging", ".", "info", "(", "'verifying signature for certificate with uid=%s:'", ",", "uid", ")", "with", "open", "(", "signed_cert_file_name", ")", "as", "in_file...
Verify the certificate signature matches the expected. Double-check the uid field in the certificate and use VerifyMessage to confirm that the signature in the certificate matches the issuing_address. Raises error is verification fails. Raises UnverifiedSignatureError if signature is invalid :param u...
[ "Verify", "the", "certificate", "signature", "matches", "the", "expected", ".", "Double", "-", "check", "the", "uid", "field", "in", "the", "certificate", "and", "use", "VerifyMessage", "to", "confirm", "that", "the", "signature", "in", "the", "certificate", "...
e8a48e25472473b149bd411a9fd5f2ff0f8f100a
https://github.com/blockchain-certificates/cert-issuer/blob/e8a48e25472473b149bd411a9fd5f2ff0f8f100a/cert_issuer/blockchain_handlers/bitcoin/signer.py#L52-L78
train
blockchain-certificates/cert-issuer
cert_issuer/blockchain_handlers/ethereum/connectors.py
EtherscanBroadcaster.get_balance
def get_balance(self, address, api_token): """ returns the balance in wei with some inspiration from PyWallet """ broadcast_url = self.base_url + '?module=account&action=balance' broadcast_url += '&address=%s' % address broadcast_url += '&tag=latest' if ap...
python
def get_balance(self, address, api_token): """ returns the balance in wei with some inspiration from PyWallet """ broadcast_url = self.base_url + '?module=account&action=balance' broadcast_url += '&address=%s' % address broadcast_url += '&tag=latest' if ap...
[ "def", "get_balance", "(", "self", ",", "address", ",", "api_token", ")", ":", "broadcast_url", "=", "self", ".", "base_url", "+", "'?module=account&action=balance'", "broadcast_url", "+=", "'&address=%s'", "%", "address", "broadcast_url", "+=", "'&tag=latest'", "if...
returns the balance in wei with some inspiration from PyWallet
[ "returns", "the", "balance", "in", "wei", "with", "some", "inspiration", "from", "PyWallet" ]
e8a48e25472473b149bd411a9fd5f2ff0f8f100a
https://github.com/blockchain-certificates/cert-issuer/blob/e8a48e25472473b149bd411a9fd5f2ff0f8f100a/cert_issuer/blockchain_handlers/ethereum/connectors.py#L80-L95
train
blockchain-certificates/cert-issuer
cert_issuer/blockchain_handlers/ethereum/connectors.py
EtherscanBroadcaster.get_address_nonce
def get_address_nonce(self, address, api_token): """ Looks up the address nonce of this address Neccesary for the transaction creation """ broadcast_url = self.base_url + '?module=proxy&action=eth_getTransactionCount' broadcast_url += '&address=%s' % address broad...
python
def get_address_nonce(self, address, api_token): """ Looks up the address nonce of this address Neccesary for the transaction creation """ broadcast_url = self.base_url + '?module=proxy&action=eth_getTransactionCount' broadcast_url += '&address=%s' % address broad...
[ "def", "get_address_nonce", "(", "self", ",", "address", ",", "api_token", ")", ":", "broadcast_url", "=", "self", ".", "base_url", "+", "'?module=proxy&action=eth_getTransactionCount'", "broadcast_url", "+=", "'&address=%s'", "%", "address", "broadcast_url", "+=", "'...
Looks up the address nonce of this address Neccesary for the transaction creation
[ "Looks", "up", "the", "address", "nonce", "of", "this", "address", "Neccesary", "for", "the", "transaction", "creation" ]
e8a48e25472473b149bd411a9fd5f2ff0f8f100a
https://github.com/blockchain-certificates/cert-issuer/blob/e8a48e25472473b149bd411a9fd5f2ff0f8f100a/cert_issuer/blockchain_handlers/ethereum/connectors.py#L97-L115
train
tensorflow/mesh
mesh_tensorflow/tpu_variables.py
ReplicatedVariable._dense_var_to_tensor
def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False): """Converts a variable to a tensor.""" # pylint: disable=protected-access if _enclosing_tpu_context() is None: if hasattr(self._primary_var, '_dense_var_to_tensor'): return self._primary_var._dense_var_to_tensor(dtype, name, ...
python
def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False): """Converts a variable to a tensor.""" # pylint: disable=protected-access if _enclosing_tpu_context() is None: if hasattr(self._primary_var, '_dense_var_to_tensor'): return self._primary_var._dense_var_to_tensor(dtype, name, ...
[ "def", "_dense_var_to_tensor", "(", "self", ",", "dtype", "=", "None", ",", "name", "=", "None", ",", "as_ref", "=", "False", ")", ":", "if", "_enclosing_tpu_context", "(", ")", "is", "None", ":", "if", "hasattr", "(", "self", ".", "_primary_var", ",", ...
Converts a variable to a tensor.
[ "Converts", "a", "variable", "to", "a", "tensor", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/tpu_variables.py#L183-L197
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/memory_estimator.py
MemoryEstimator._compute_layout_validator
def _compute_layout_validator(self): """Computes self._layout_validator.""" self._layout_validator = valid_layouts.LayoutValidator(self.mtf_graph, self.mesh_shape)
python
def _compute_layout_validator(self): """Computes self._layout_validator.""" self._layout_validator = valid_layouts.LayoutValidator(self.mtf_graph, self.mesh_shape)
[ "def", "_compute_layout_validator", "(", "self", ")", ":", "self", ".", "_layout_validator", "=", "valid_layouts", ".", "LayoutValidator", "(", "self", ".", "mtf_graph", ",", "self", ".", "mesh_shape", ")" ]
Computes self._layout_validator.
[ "Computes", "self", ".", "_layout_validator", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/memory_estimator.py#L87-L90
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/memory_estimator.py
MemoryEstimator._compute_graph_interface
def _compute_graph_interface(self): """Computes self._graph_interface.""" self._graph_interface = graph_interface.GraphInterface(self.mtf_graph) for mtf_output in self.mtf_outputs: self._graph_interface.set_tensor_final(mtf_output.name)
python
def _compute_graph_interface(self): """Computes self._graph_interface.""" self._graph_interface = graph_interface.GraphInterface(self.mtf_graph) for mtf_output in self.mtf_outputs: self._graph_interface.set_tensor_final(mtf_output.name)
[ "def", "_compute_graph_interface", "(", "self", ")", ":", "self", ".", "_graph_interface", "=", "graph_interface", ".", "GraphInterface", "(", "self", ".", "mtf_graph", ")", "for", "mtf_output", "in", "self", ".", "mtf_outputs", ":", "self", ".", "_graph_interfa...
Computes self._graph_interface.
[ "Computes", "self", ".", "_graph_interface", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/memory_estimator.py#L92-L96
train
tensorflow/mesh
mesh_tensorflow/transformer/transformer.py
make_layer_stack
def make_layer_stack(layers=gin.REQUIRED, num_layers=6): """Configurable layer stack. Args: layers: a list of subclasses of TransformerLayer num_layers: an integer Returns: a LayerStack """ return LayerStack([cls() for cls in layers] * num_layers)
python
def make_layer_stack(layers=gin.REQUIRED, num_layers=6): """Configurable layer stack. Args: layers: a list of subclasses of TransformerLayer num_layers: an integer Returns: a LayerStack """ return LayerStack([cls() for cls in layers] * num_layers)
[ "def", "make_layer_stack", "(", "layers", "=", "gin", ".", "REQUIRED", ",", "num_layers", "=", "6", ")", ":", "return", "LayerStack", "(", "[", "cls", "(", ")", "for", "cls", "in", "layers", "]", "*", "num_layers", ")" ]
Configurable layer stack. Args: layers: a list of subclasses of TransformerLayer num_layers: an integer Returns: a LayerStack
[ "Configurable", "layer", "stack", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/transformer.py#L946-L955
train
tensorflow/mesh
mesh_tensorflow/transformer/transformer.py
make_bitransformer
def make_bitransformer( input_vocab_size=gin.REQUIRED, output_vocab_size=gin.REQUIRED, layout=None, mesh_shape=None): """Gin-configurable bitransformer constructor. In your config file you need to set the encoder and decoder layers like this: encoder/make_layer_stack.layers = [ @transformer_l...
python
def make_bitransformer( input_vocab_size=gin.REQUIRED, output_vocab_size=gin.REQUIRED, layout=None, mesh_shape=None): """Gin-configurable bitransformer constructor. In your config file you need to set the encoder and decoder layers like this: encoder/make_layer_stack.layers = [ @transformer_l...
[ "def", "make_bitransformer", "(", "input_vocab_size", "=", "gin", ".", "REQUIRED", ",", "output_vocab_size", "=", "gin", ".", "REQUIRED", ",", "layout", "=", "None", ",", "mesh_shape", "=", "None", ")", ":", "with", "gin", ".", "config_scope", "(", "\"encode...
Gin-configurable bitransformer constructor. In your config file you need to set the encoder and decoder layers like this: encoder/make_layer_stack.layers = [ @transformer_layers.SelfAttention, @transformer_layers.DenseReluDense, ] decoder/make_layer_stack.layers = [ @transformer_layers.SelfAttentio...
[ "Gin", "-", "configurable", "bitransformer", "constructor", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/transformer.py#L959-L1005
train
tensorflow/mesh
mesh_tensorflow/transformer/transformer.py
Context.get_states
def get_states(self, n): """Get the next n recurrent states. Called by layers in "incremental" mode. Args: n: an integer Returns: a list of n Tensors """ return self.states[len(self.new_states):len(self.new_states) + n]
python
def get_states(self, n): """Get the next n recurrent states. Called by layers in "incremental" mode. Args: n: an integer Returns: a list of n Tensors """ return self.states[len(self.new_states):len(self.new_states) + n]
[ "def", "get_states", "(", "self", ",", "n", ")", ":", "return", "self", ".", "states", "[", "len", "(", "self", ".", "new_states", ")", ":", "len", "(", "self", ".", "new_states", ")", "+", "n", "]" ]
Get the next n recurrent states. Called by layers in "incremental" mode. Args: n: an integer Returns: a list of n Tensors
[ "Get", "the", "next", "n", "recurrent", "states", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/transformer.py#L219-L229
train
tensorflow/mesh
mesh_tensorflow/transformer/transformer.py
Context.get_constant_state
def get_constant_state(self): """Read state that was written in "first_part" mode. Returns: a structure """ ret = self.constant_states[self.next_constant_state] self.next_constant_state += 1 return ret
python
def get_constant_state(self): """Read state that was written in "first_part" mode. Returns: a structure """ ret = self.constant_states[self.next_constant_state] self.next_constant_state += 1 return ret
[ "def", "get_constant_state", "(", "self", ")", ":", "ret", "=", "self", ".", "constant_states", "[", "self", ".", "next_constant_state", "]", "self", ".", "next_constant_state", "+=", "1", "return", "ret" ]
Read state that was written in "first_part" mode. Returns: a structure
[ "Read", "state", "that", "was", "written", "in", "first_part", "mode", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/transformer.py#L252-L260
train
tensorflow/mesh
mesh_tensorflow/transformer/transformer.py
Context.nonpadding
def nonpadding(self): """Tensor with zeros in padding positions and ones elsewhere.""" if self.sequence_id is None: return None if self.sequence_id == 1: return 1 else: return mtf.cast( mtf.not_equal(self.sequence_id, 0), self.activation_dtype)
python
def nonpadding(self): """Tensor with zeros in padding positions and ones elsewhere.""" if self.sequence_id is None: return None if self.sequence_id == 1: return 1 else: return mtf.cast( mtf.not_equal(self.sequence_id, 0), self.activation_dtype)
[ "def", "nonpadding", "(", "self", ")", ":", "if", "self", ".", "sequence_id", "is", "None", ":", "return", "None", "if", "self", ".", "sequence_id", "==", "1", ":", "return", "1", "else", ":", "return", "mtf", ".", "cast", "(", "mtf", ".", "not_equal...
Tensor with zeros in padding positions and ones elsewhere.
[ "Tensor", "with", "zeros", "in", "padding", "positions", "and", "ones", "elsewhere", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/transformer.py#L263-L271
train
tensorflow/mesh
mesh_tensorflow/transformer/metrics.py
sequence_accuracy
def sequence_accuracy(labels, outputs): """Compute the sequence-level accuracy. A sequence is only considered correct if all of its entries were predicted correctly. Args: labels: ground-truth labels, shape=(batch, packed_seq_length) outputs: predicted tokens, shape=(batch, seq_length) Returns: ...
python
def sequence_accuracy(labels, outputs): """Compute the sequence-level accuracy. A sequence is only considered correct if all of its entries were predicted correctly. Args: labels: ground-truth labels, shape=(batch, packed_seq_length) outputs: predicted tokens, shape=(batch, seq_length) Returns: ...
[ "def", "sequence_accuracy", "(", "labels", ",", "outputs", ")", ":", "all_correct", "=", "tf", ".", "reduce_all", "(", "tf", ".", "logical_or", "(", "tf", ".", "equal", "(", "labels", ",", "outputs", ")", ",", "tf", ".", "equal", "(", "labels", ",", ...
Compute the sequence-level accuracy. A sequence is only considered correct if all of its entries were predicted correctly. Args: labels: ground-truth labels, shape=(batch, packed_seq_length) outputs: predicted tokens, shape=(batch, seq_length) Returns: Two ops, one for getting the current average ...
[ "Compute", "the", "sequence", "-", "level", "accuracy", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/metrics.py#L46-L63
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/graph_interface.py
GraphInterface.get_operation_input_names
def get_operation_input_names(self, operation_name): """Generates the names of all input tensors of an operation. Args: operation_name: a string, the name of an operation in the graph. Yields: a string, the name of an input tensor. """ for input_tensor in self._name_to_operation(operat...
python
def get_operation_input_names(self, operation_name): """Generates the names of all input tensors of an operation. Args: operation_name: a string, the name of an operation in the graph. Yields: a string, the name of an input tensor. """ for input_tensor in self._name_to_operation(operat...
[ "def", "get_operation_input_names", "(", "self", ",", "operation_name", ")", ":", "for", "input_tensor", "in", "self", ".", "_name_to_operation", "(", "operation_name", ")", ".", "inputs", ":", "yield", "input_tensor", ".", "name" ]
Generates the names of all input tensors of an operation. Args: operation_name: a string, the name of an operation in the graph. Yields: a string, the name of an input tensor.
[ "Generates", "the", "names", "of", "all", "input", "tensors", "of", "an", "operation", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L93-L103
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/graph_interface.py
GraphInterface.get_operation_output_names
def get_operation_output_names(self, operation_name): """Generates the names of all output tensors of an operation. Args: operation_name: a string, the name of an operation in the graph. Yields: a string, the name of an output tensor. """ for output_tensor in self._name_to_operation(op...
python
def get_operation_output_names(self, operation_name): """Generates the names of all output tensors of an operation. Args: operation_name: a string, the name of an operation in the graph. Yields: a string, the name of an output tensor. """ for output_tensor in self._name_to_operation(op...
[ "def", "get_operation_output_names", "(", "self", ",", "operation_name", ")", ":", "for", "output_tensor", "in", "self", ".", "_name_to_operation", "(", "operation_name", ")", ".", "outputs", ":", "yield", "output_tensor", ".", "name" ]
Generates the names of all output tensors of an operation. Args: operation_name: a string, the name of an operation in the graph. Yields: a string, the name of an output tensor.
[ "Generates", "the", "names", "of", "all", "output", "tensors", "of", "an", "operation", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L105-L115
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/graph_interface.py
GraphInterface.get_tensor_shape
def get_tensor_shape(self, tensor_name): """The tf.TensorShape of a tensor. Args: tensor_name: string, the name of a tensor in the graph. Returns: a tf.TensorShape """ tensor = self._name_to_tensor(tensor_name) if isinstance(tensor, mtf.Tensor): return tf.TensorShape(tensor....
python
def get_tensor_shape(self, tensor_name): """The tf.TensorShape of a tensor. Args: tensor_name: string, the name of a tensor in the graph. Returns: a tf.TensorShape """ tensor = self._name_to_tensor(tensor_name) if isinstance(tensor, mtf.Tensor): return tf.TensorShape(tensor....
[ "def", "get_tensor_shape", "(", "self", ",", "tensor_name", ")", ":", "tensor", "=", "self", ".", "_name_to_tensor", "(", "tensor_name", ")", "if", "isinstance", "(", "tensor", ",", "mtf", ".", "Tensor", ")", ":", "return", "tf", ".", "TensorShape", "(", ...
The tf.TensorShape of a tensor. Args: tensor_name: string, the name of a tensor in the graph. Returns: a tf.TensorShape
[ "The", "tf", ".", "TensorShape", "of", "a", "tensor", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L137-L151
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/graph_interface.py
GraphInterface.get_tensor_num_entries
def get_tensor_num_entries(self, tensor_name, partial_layout=None, mesh_dimension_to_size=None): """The number of entries in a tensor. If partial_layout is specified, then mesh_dimension_to_size must also be. In this case, the number of entries on a single device is returned. ...
python
def get_tensor_num_entries(self, tensor_name, partial_layout=None, mesh_dimension_to_size=None): """The number of entries in a tensor. If partial_layout is specified, then mesh_dimension_to_size must also be. In this case, the number of entries on a single device is returned. ...
[ "def", "get_tensor_num_entries", "(", "self", ",", "tensor_name", ",", "partial_layout", "=", "None", ",", "mesh_dimension_to_size", "=", "None", ")", ":", "shape", "=", "self", ".", "get_tensor_shape", "(", "tensor_name", ")", "num_entries", "=", "1", "for", ...
The number of entries in a tensor. If partial_layout is specified, then mesh_dimension_to_size must also be. In this case, the number of entries on a single device is returned. Args: tensor_name: a string, name of a tensor in the graph. partial_layout: an optional {string: string}, from MTF di...
[ "The", "number", "of", "entries", "in", "a", "tensor", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L153-L187
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/graph_interface.py
GraphInterface.get_tensor_size
def get_tensor_size(self, tensor_name, partial_layout=None, mesh_dimension_to_size=None): """The size of a tensor in bytes. If partial_layout is specified, then mesh_dimension_to_size must also be. In this case, the size on a single device is returned. Args: tensor_name: a ...
python
def get_tensor_size(self, tensor_name, partial_layout=None, mesh_dimension_to_size=None): """The size of a tensor in bytes. If partial_layout is specified, then mesh_dimension_to_size must also be. In this case, the size on a single device is returned. Args: tensor_name: a ...
[ "def", "get_tensor_size", "(", "self", ",", "tensor_name", ",", "partial_layout", "=", "None", ",", "mesh_dimension_to_size", "=", "None", ")", ":", "return", "(", "self", ".", "get_tensor_dtype", "(", "tensor_name", ")", ".", "size", "*", "self", ".", "get_...
The size of a tensor in bytes. If partial_layout is specified, then mesh_dimension_to_size must also be. In this case, the size on a single device is returned. Args: tensor_name: a string, name of a tensor in the graph. partial_layout: an optional {string: string}, from MTF dimension name to ...
[ "The", "size", "of", "a", "tensor", "in", "bytes", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L189-L208
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/graph_interface.py
GraphInterface.get_tensor_device
def get_tensor_device(self, tensor_name): """The device of a tensor. Note that only tf tensors have device assignments. Args: tensor_name: a string, name of a tensor in the graph. Returns: a string or None, representing the device name. """ tensor = self._name_to_tensor(tensor_nam...
python
def get_tensor_device(self, tensor_name): """The device of a tensor. Note that only tf tensors have device assignments. Args: tensor_name: a string, name of a tensor in the graph. Returns: a string or None, representing the device name. """ tensor = self._name_to_tensor(tensor_nam...
[ "def", "get_tensor_device", "(", "self", ",", "tensor_name", ")", ":", "tensor", "=", "self", ".", "_name_to_tensor", "(", "tensor_name", ")", "if", "isinstance", "(", "tensor", ",", "tf", ".", "Tensor", ")", ":", "return", "tensor", ".", "device", "else",...
The device of a tensor. Note that only tf tensors have device assignments. Args: tensor_name: a string, name of a tensor in the graph. Returns: a string or None, representing the device name.
[ "The", "device", "of", "a", "tensor", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L210-L225
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/graph_interface.py
GraphInterface.get_operation_device
def get_operation_device(self, operation_name): """The device of an operation. Note that only tf operations have device assignments. Args: operation_name: a string, name of an operation in the graph. Returns: a string or None, representing the device name. """ operation = self._na...
python
def get_operation_device(self, operation_name): """The device of an operation. Note that only tf operations have device assignments. Args: operation_name: a string, name of an operation in the graph. Returns: a string or None, representing the device name. """ operation = self._na...
[ "def", "get_operation_device", "(", "self", ",", "operation_name", ")", ":", "operation", "=", "self", ".", "_name_to_operation", "(", "operation_name", ")", "if", "isinstance", "(", "operation", ",", "tf", ".", "Operation", ")", ":", "return", "operation", "....
The device of an operation. Note that only tf operations have device assignments. Args: operation_name: a string, name of an operation in the graph. Returns: a string or None, representing the device name.
[ "The", "device", "of", "an", "operation", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L242-L257
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/graph_interface.py
GraphInterface.get_tensor_mtf_dimension_names
def get_tensor_mtf_dimension_names(self, tensor_name): """The Mesh TensorFlow dimensions associated with a tensor. Args: tensor_name: a string, name of a tensor in the graph. Returns: a [string], the names of Mesh TensorFlow dimensions. """ tensor = self._name_to_tensor(tensor_name) ...
python
def get_tensor_mtf_dimension_names(self, tensor_name): """The Mesh TensorFlow dimensions associated with a tensor. Args: tensor_name: a string, name of a tensor in the graph. Returns: a [string], the names of Mesh TensorFlow dimensions. """ tensor = self._name_to_tensor(tensor_name) ...
[ "def", "get_tensor_mtf_dimension_names", "(", "self", ",", "tensor_name", ")", ":", "tensor", "=", "self", ".", "_name_to_tensor", "(", "tensor_name", ")", "if", "isinstance", "(", "tensor", ",", "mtf", ".", "Tensor", ")", ":", "return", "tensor", ".", "shap...
The Mesh TensorFlow dimensions associated with a tensor. Args: tensor_name: a string, name of a tensor in the graph. Returns: a [string], the names of Mesh TensorFlow dimensions.
[ "The", "Mesh", "TensorFlow", "dimensions", "associated", "with", "a", "tensor", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L259-L272
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/graph_interface.py
GraphInterface.get_operation_mtf_dimension_names
def get_operation_mtf_dimension_names(self, operation_name): """The Mesh TensorFlow dimensions associated with an operation. Args: operation_name: a string, name of an operation in the graph. Returns: a set(string), the names of Mesh TensorFlow dimensions. """ mtf_dimension_names = set...
python
def get_operation_mtf_dimension_names(self, operation_name): """The Mesh TensorFlow dimensions associated with an operation. Args: operation_name: a string, name of an operation in the graph. Returns: a set(string), the names of Mesh TensorFlow dimensions. """ mtf_dimension_names = set...
[ "def", "get_operation_mtf_dimension_names", "(", "self", ",", "operation_name", ")", ":", "mtf_dimension_names", "=", "set", "(", ")", "for", "tensor_name", "in", "self", ".", "get_operation_input_names", "(", "operation_name", ")", ":", "mtf_dimension_names", ".", ...
The Mesh TensorFlow dimensions associated with an operation. Args: operation_name: a string, name of an operation in the graph. Returns: a set(string), the names of Mesh TensorFlow dimensions.
[ "The", "Mesh", "TensorFlow", "dimensions", "associated", "with", "an", "operation", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L274-L290
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/graph_interface.py
GraphInterface.set_tensor_final
def set_tensor_final(self, tensor_name): """Denotes a tensor as a final output of the computation. Args: tensor_name: a string, name of a tensor in the graph. """ tensor = self._name_to_tensor(tensor_name) self._final_tensors.add(tensor)
python
def set_tensor_final(self, tensor_name): """Denotes a tensor as a final output of the computation. Args: tensor_name: a string, name of a tensor in the graph. """ tensor = self._name_to_tensor(tensor_name) self._final_tensors.add(tensor)
[ "def", "set_tensor_final", "(", "self", ",", "tensor_name", ")", ":", "tensor", "=", "self", ".", "_name_to_tensor", "(", "tensor_name", ")", "self", ".", "_final_tensors", ".", "add", "(", "tensor", ")" ]
Denotes a tensor as a final output of the computation. Args: tensor_name: a string, name of a tensor in the graph.
[ "Denotes", "a", "tensor", "as", "a", "final", "output", "of", "the", "computation", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L292-L299
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/graph_interface.py
GraphInterface.is_tensor_final
def is_tensor_final(self, tensor_name): """Whether a tensor is a final output of the computation. Args: tensor_name: a string, name of a tensor in the graph. Returns: a boolean indicating whether the tensor was a final output. """ tensor = self._name_to_tensor(tensor_name) return t...
python
def is_tensor_final(self, tensor_name): """Whether a tensor is a final output of the computation. Args: tensor_name: a string, name of a tensor in the graph. Returns: a boolean indicating whether the tensor was a final output. """ tensor = self._name_to_tensor(tensor_name) return t...
[ "def", "is_tensor_final", "(", "self", ",", "tensor_name", ")", ":", "tensor", "=", "self", ".", "_name_to_tensor", "(", "tensor_name", ")", "return", "tensor", "in", "self", ".", "_final_tensors" ]
Whether a tensor is a final output of the computation. Args: tensor_name: a string, name of a tensor in the graph. Returns: a boolean indicating whether the tensor was a final output.
[ "Whether", "a", "tensor", "is", "a", "final", "output", "of", "the", "computation", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L301-L311
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/graph_interface.py
GraphInterface.compute_cost_graph
def compute_cost_graph(self, devices=None): """Computes a CostGraphDef protobuf based on this graph. Defined in tensorflow/core/framework/cost_graph.proto. Args: devices: optional [string], the names of devices to consider. If specified, any tensor on a device not listed is given a size of...
python
def compute_cost_graph(self, devices=None): """Computes a CostGraphDef protobuf based on this graph. Defined in tensorflow/core/framework/cost_graph.proto. Args: devices: optional [string], the names of devices to consider. If specified, any tensor on a device not listed is given a size of...
[ "def", "compute_cost_graph", "(", "self", ",", "devices", "=", "None", ")", ":", "cost_graph_def", "=", "cost_graph_pb2", ".", "CostGraphDef", "(", ")", "for", "i", ",", "operation_name", "in", "enumerate", "(", "self", ".", "get_all_operation_names", "(", ")"...
Computes a CostGraphDef protobuf based on this graph. Defined in tensorflow/core/framework/cost_graph.proto. Args: devices: optional [string], the names of devices to consider. If specified, any tensor on a device not listed is given a size of zero. Any device-less tensor (e.g. Mesh ...
[ "Computes", "a", "CostGraphDef", "protobuf", "based", "on", "this", "graph", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L313-L365
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/graph_interface.py
GraphInterface.compute_memory_contents_under_schedule
def compute_memory_contents_under_schedule(self, schedule): """The in-memory tensors present when executing each operation in schedule. Simulates running operations in the order given by a schedule. Keeps track of the tensors in memory at every point in time, and outputs a list (one entry for each poin...
python
def compute_memory_contents_under_schedule(self, schedule): """The in-memory tensors present when executing each operation in schedule. Simulates running operations in the order given by a schedule. Keeps track of the tensors in memory at every point in time, and outputs a list (one entry for each poin...
[ "def", "compute_memory_contents_under_schedule", "(", "self", ",", "schedule", ")", ":", "out_degree", "=", "self", ".", "_compute_initial_out_degree", "(", ")", "curr_memory_contents", "=", "set", "(", ")", "memory_contents_for_each_operation", "=", "[", "]", "for", ...
The in-memory tensors present when executing each operation in schedule. Simulates running operations in the order given by a schedule. Keeps track of the tensors in memory at every point in time, and outputs a list (one entry for each point in time) of all sets of all memory contents (i.e. a frozenset...
[ "The", "in", "-", "memory", "tensors", "present", "when", "executing", "each", "operation", "in", "schedule", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L367-L407
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/graph_interface.py
GraphInterface._initialize_operations
def _initialize_operations(self): """Initializer for _operations. Raises: TypeError: _graph is not a tf.Graph or mtf.Graph. Returns: a list of (tf.Operation or mtf.Operation) """ if isinstance(self._graph, tf.Graph): return self._graph.get_operations() elif isinstance(self._g...
python
def _initialize_operations(self): """Initializer for _operations. Raises: TypeError: _graph is not a tf.Graph or mtf.Graph. Returns: a list of (tf.Operation or mtf.Operation) """ if isinstance(self._graph, tf.Graph): return self._graph.get_operations() elif isinstance(self._g...
[ "def", "_initialize_operations", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "_graph", ",", "tf", ".", "Graph", ")", ":", "return", "self", ".", "_graph", ".", "get_operations", "(", ")", "elif", "isinstance", "(", "self", ".", "_graph",...
Initializer for _operations. Raises: TypeError: _graph is not a tf.Graph or mtf.Graph. Returns: a list of (tf.Operation or mtf.Operation)
[ "Initializer", "for", "_operations", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L409-L424
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/graph_interface.py
GraphInterface._initialize_operation_name_to_id
def _initialize_operation_name_to_id(self): """Initializer for _operation_name_to_id. Returns: a {string: int}, mapping operation names to their index in _operations. """ operation_name_to_id = {} for i, operation in enumerate(self._operations): operation_name_to_id[operation.name] = i ...
python
def _initialize_operation_name_to_id(self): """Initializer for _operation_name_to_id. Returns: a {string: int}, mapping operation names to their index in _operations. """ operation_name_to_id = {} for i, operation in enumerate(self._operations): operation_name_to_id[operation.name] = i ...
[ "def", "_initialize_operation_name_to_id", "(", "self", ")", ":", "operation_name_to_id", "=", "{", "}", "for", "i", ",", "operation", "in", "enumerate", "(", "self", ".", "_operations", ")", ":", "operation_name_to_id", "[", "operation", ".", "name", "]", "="...
Initializer for _operation_name_to_id. Returns: a {string: int}, mapping operation names to their index in _operations.
[ "Initializer", "for", "_operation_name_to_id", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L426-L435
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/graph_interface.py
GraphInterface._initialize_tensor_name_to_ids
def _initialize_tensor_name_to_ids(self): """Initializer for _tensor_name_to_ids. Returns: a {string: (int, int)}, mapping the name of tensor T to the index of T's operation in _operations and T's index in T's operation's outputs. """ tensor_name_to_ids = {} for i, operation in enum...
python
def _initialize_tensor_name_to_ids(self): """Initializer for _tensor_name_to_ids. Returns: a {string: (int, int)}, mapping the name of tensor T to the index of T's operation in _operations and T's index in T's operation's outputs. """ tensor_name_to_ids = {} for i, operation in enum...
[ "def", "_initialize_tensor_name_to_ids", "(", "self", ")", ":", "tensor_name_to_ids", "=", "{", "}", "for", "i", ",", "operation", "in", "enumerate", "(", "self", ".", "_operations", ")", ":", "for", "j", ",", "tensor", "in", "enumerate", "(", "operation", ...
Initializer for _tensor_name_to_ids. Returns: a {string: (int, int)}, mapping the name of tensor T to the index of T's operation in _operations and T's index in T's operation's outputs.
[ "Initializer", "for", "_tensor_name_to_ids", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L437-L448
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/graph_interface.py
GraphInterface._name_to_tensor
def _name_to_tensor(self, tensor_name): """The tensor with the given name. Args: tensor_name: a string, name of a tensor in the graph. Returns: a tf.Tensor or mtf.Tensor """ id1, id2 = self._tensor_name_to_ids[tensor_name] return self._operations[id1].outputs[id2]
python
def _name_to_tensor(self, tensor_name): """The tensor with the given name. Args: tensor_name: a string, name of a tensor in the graph. Returns: a tf.Tensor or mtf.Tensor """ id1, id2 = self._tensor_name_to_ids[tensor_name] return self._operations[id1].outputs[id2]
[ "def", "_name_to_tensor", "(", "self", ",", "tensor_name", ")", ":", "id1", ",", "id2", "=", "self", ".", "_tensor_name_to_ids", "[", "tensor_name", "]", "return", "self", ".", "_operations", "[", "id1", "]", ".", "outputs", "[", "id2", "]" ]
The tensor with the given name. Args: tensor_name: a string, name of a tensor in the graph. Returns: a tf.Tensor or mtf.Tensor
[ "The", "tensor", "with", "the", "given", "name", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L471-L481
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/graph_interface.py
GraphInterface._compute_initial_out_degree
def _compute_initial_out_degree(self): """The number of operations which use each tensor as input. Returns: a {string, int} mapping tensor name to the number of operations which use it as input, or one plus that quantity if the tensor is final. """ out_degree = collections.defaultdict(int) ...
python
def _compute_initial_out_degree(self): """The number of operations which use each tensor as input. Returns: a {string, int} mapping tensor name to the number of operations which use it as input, or one plus that quantity if the tensor is final. """ out_degree = collections.defaultdict(int) ...
[ "def", "_compute_initial_out_degree", "(", "self", ")", ":", "out_degree", "=", "collections", ".", "defaultdict", "(", "int", ")", "for", "tensor_name", "in", "self", ".", "get_all_tensor_names", "(", ")", ":", "if", "self", ".", "is_tensor_final", "(", "tens...
The number of operations which use each tensor as input. Returns: a {string, int} mapping tensor name to the number of operations which use it as input, or one plus that quantity if the tensor is final.
[ "The", "number", "of", "operations", "which", "use", "each", "tensor", "as", "input", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L483-L502
train
tensorflow/mesh
mesh_tensorflow/layers.py
layer_norm
def layer_norm(x, dim, epsilon=1e-6, name="layer_prepostprocess"): """Layer normalization over dimension dim. Args: x: a mtf.Tensor whose shape contains dim. dim: a mtf.Dimension epsilon: a floating point number name: a string. variable scope. Returns: a mtf.Tensor with same shape as x. ""...
python
def layer_norm(x, dim, epsilon=1e-6, name="layer_prepostprocess"): """Layer normalization over dimension dim. Args: x: a mtf.Tensor whose shape contains dim. dim: a mtf.Dimension epsilon: a floating point number name: a string. variable scope. Returns: a mtf.Tensor with same shape as x. ""...
[ "def", "layer_norm", "(", "x", ",", "dim", ",", "epsilon", "=", "1e-6", ",", "name", "=", "\"layer_prepostprocess\"", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", "+", "\"/layer_norm\"", ")", ":", "scale", "=", "mtf", ".", "get_variable", ...
Layer normalization over dimension dim. Args: x: a mtf.Tensor whose shape contains dim. dim: a mtf.Dimension epsilon: a floating point number name: a string. variable scope. Returns: a mtf.Tensor with same shape as x.
[ "Layer", "normalization", "over", "dimension", "dim", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L85-L114
train
tensorflow/mesh
mesh_tensorflow/layers.py
softmax_cross_entropy_with_logits
def softmax_cross_entropy_with_logits(logits, targets, vocab_dim, z_loss=0.0): """Per-example softmax loss. if z_loss is nonzero, we add a loss equal to z_loss*log(z)^2, where z is the partition function. Example value: z_loss=1e-4. Two uses of z_loss are: - To keep the logits from drifting too far from zero...
python
def softmax_cross_entropy_with_logits(logits, targets, vocab_dim, z_loss=0.0): """Per-example softmax loss. if z_loss is nonzero, we add a loss equal to z_loss*log(z)^2, where z is the partition function. Example value: z_loss=1e-4. Two uses of z_loss are: - To keep the logits from drifting too far from zero...
[ "def", "softmax_cross_entropy_with_logits", "(", "logits", ",", "targets", ",", "vocab_dim", ",", "z_loss", "=", "0.0", ")", ":", "if", "logits", ".", "shape", "!=", "targets", ".", "shape", ":", "raise", "ValueError", "(", "\"logits shape must equal targets shape...
Per-example softmax loss. if z_loss is nonzero, we add a loss equal to z_loss*log(z)^2, where z is the partition function. Example value: z_loss=1e-4. Two uses of z_loss are: - To keep the logits from drifting too far from zero, which can cause unacceptable roundoff errors in bfloat16. - To encourage th...
[ "Per", "-", "example", "softmax", "loss", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L187-L220
train
tensorflow/mesh
mesh_tensorflow/layers.py
sigmoid_cross_entropy_with_logits
def sigmoid_cross_entropy_with_logits(logits, targets): """Sigmoid cross-entropy loss. Args: logits: a mtf.Tensor targets: a mtf.Tensor with the same shape as logits Returns: a mtf.Tensor whose shape is equal to logits.shape Raises: ValueError: if the shapes do not match. """ if logits.sh...
python
def sigmoid_cross_entropy_with_logits(logits, targets): """Sigmoid cross-entropy loss. Args: logits: a mtf.Tensor targets: a mtf.Tensor with the same shape as logits Returns: a mtf.Tensor whose shape is equal to logits.shape Raises: ValueError: if the shapes do not match. """ if logits.sh...
[ "def", "sigmoid_cross_entropy_with_logits", "(", "logits", ",", "targets", ")", ":", "if", "logits", ".", "shape", "!=", "targets", ".", "shape", ":", "raise", "ValueError", "(", "\"logits shape must equal targets shape\"", "\"logits=%s targets=%s\"", "%", "(", "logit...
Sigmoid cross-entropy loss. Args: logits: a mtf.Tensor targets: a mtf.Tensor with the same shape as logits Returns: a mtf.Tensor whose shape is equal to logits.shape Raises: ValueError: if the shapes do not match.
[ "Sigmoid", "cross", "-", "entropy", "loss", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L223-L242
train
tensorflow/mesh
mesh_tensorflow/layers.py
dense_relu_dense
def dense_relu_dense(x, hidden_channels, dropout=0.0, dropout_broadcast_dims=None, master_dtype=tf.float32, slice_dtype=tf.float32, name=None): """Hidden layer with ReLU activation followed by linear projection. ...
python
def dense_relu_dense(x, hidden_channels, dropout=0.0, dropout_broadcast_dims=None, master_dtype=tf.float32, slice_dtype=tf.float32, name=None): """Hidden layer with ReLU activation followed by linear projection. ...
[ "def", "dense_relu_dense", "(", "x", ",", "hidden_channels", ",", "dropout", "=", "0.0", ",", "dropout_broadcast_dims", "=", "None", ",", "master_dtype", "=", "tf", ".", "float32", ",", "slice_dtype", "=", "tf", ".", "float32", ",", "name", "=", "None", ")...
Hidden layer with ReLU activation followed by linear projection. The output has the same number of channels as the input. Args: x: a mtf.Tensor hidden_channels: a mtf.Dimension - channels in the hidden layer dropout: an optional float dropout_broadcast_dims: an optional list of mtf.Dimension m...
[ "Hidden", "layer", "with", "ReLU", "activation", "followed", "by", "linear", "projection", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L251-L283
train
tensorflow/mesh
mesh_tensorflow/layers.py
local_1d_halo_exchange
def local_1d_halo_exchange(k, v, num_w_blocks, w_dim, mask_right): """Halo exchange for keys and values for Local 1D attention.""" if num_w_blocks is not None: if mask_right: k = mtf.left_halo_exchange(k, num_w_blocks, w_dim, w_dim.size) v = mtf.left_halo_exchange(v, num_w_blocks, w_dim, w_dim.size)...
python
def local_1d_halo_exchange(k, v, num_w_blocks, w_dim, mask_right): """Halo exchange for keys and values for Local 1D attention.""" if num_w_blocks is not None: if mask_right: k = mtf.left_halo_exchange(k, num_w_blocks, w_dim, w_dim.size) v = mtf.left_halo_exchange(v, num_w_blocks, w_dim, w_dim.size)...
[ "def", "local_1d_halo_exchange", "(", "k", ",", "v", ",", "num_w_blocks", ",", "w_dim", ",", "mask_right", ")", ":", "if", "num_w_blocks", "is", "not", "None", ":", "if", "mask_right", ":", "k", "=", "mtf", ".", "left_halo_exchange", "(", "k", ",", "num_...
Halo exchange for keys and values for Local 1D attention.
[ "Halo", "exchange", "for", "keys", "and", "values", "for", "Local", "1D", "attention", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L286-L302
train
tensorflow/mesh
mesh_tensorflow/layers.py
local_2d_halo_exchange
def local_2d_halo_exchange(k, v, num_h_blocks, h_dim, num_w_blocks, w_dim, mask_right): """Halo exchange for keys and values for Local 2D attention.""" for blocks_dim, block_size_dim, halo_size in [ (num_h_blocks, h_dim, h_dim.size), (num_w_blocks, w_dim, w_dim.size)]: # s...
python
def local_2d_halo_exchange(k, v, num_h_blocks, h_dim, num_w_blocks, w_dim, mask_right): """Halo exchange for keys and values for Local 2D attention.""" for blocks_dim, block_size_dim, halo_size in [ (num_h_blocks, h_dim, h_dim.size), (num_w_blocks, w_dim, w_dim.size)]: # s...
[ "def", "local_2d_halo_exchange", "(", "k", ",", "v", ",", "num_h_blocks", ",", "h_dim", ",", "num_w_blocks", ",", "w_dim", ",", "mask_right", ")", ":", "for", "blocks_dim", ",", "block_size_dim", ",", "halo_size", "in", "[", "(", "num_h_blocks", ",", "h_dim"...
Halo exchange for keys and values for Local 2D attention.
[ "Halo", "exchange", "for", "keys", "and", "values", "for", "Local", "2D", "attention", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L535-L557
train
tensorflow/mesh
mesh_tensorflow/layers.py
local_2d_self_attention_spatial_blocks
def local_2d_self_attention_spatial_blocks(query_antecedent, kv_channels, heads, memory_h_dim=None, memory_w_dim=None, ...
python
def local_2d_self_attention_spatial_blocks(query_antecedent, kv_channels, heads, memory_h_dim=None, memory_w_dim=None, ...
[ "def", "local_2d_self_attention_spatial_blocks", "(", "query_antecedent", ",", "kv_channels", ",", "heads", ",", "memory_h_dim", "=", "None", ",", "memory_w_dim", "=", "None", ",", "mask_right", "=", "False", ",", "master_dtype", "=", "tf", ".", "float32", ",", ...
Attention to the source position and a neighborhood to the left or right. The sequence is divided into blocks of length block_size. Attention for a given query position can only see memory positions less than or equal to the query position, in the corresponding block and the previous block. Args: query_...
[ "Attention", "to", "the", "source", "position", "and", "a", "neighborhood", "to", "the", "left", "or", "right", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L560-L642
train
tensorflow/mesh
mesh_tensorflow/layers.py
multihead_attention_vars
def multihead_attention_vars( mesh, heads, io_channels, kv_channels, master_dtype, slice_dtype, activation_dtype): """Deprecated version of multihead_attention_params with combine=True.""" return multihead_attention_params( mesh, heads, io_channels, kv_channels, mtf.VariableDType(master_dtype, s...
python
def multihead_attention_vars( mesh, heads, io_channels, kv_channels, master_dtype, slice_dtype, activation_dtype): """Deprecated version of multihead_attention_params with combine=True.""" return multihead_attention_params( mesh, heads, io_channels, kv_channels, mtf.VariableDType(master_dtype, s...
[ "def", "multihead_attention_vars", "(", "mesh", ",", "heads", ",", "io_channels", ",", "kv_channels", ",", "master_dtype", ",", "slice_dtype", ",", "activation_dtype", ")", ":", "return", "multihead_attention_params", "(", "mesh", ",", "heads", ",", "io_channels", ...
Deprecated version of multihead_attention_params with combine=True.
[ "Deprecated", "version", "of", "multihead_attention_params", "with", "combine", "=", "True", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L650-L657
train
tensorflow/mesh
mesh_tensorflow/layers.py
multihead_attention_params
def multihead_attention_params(mesh, heads, io_channels, kv_channels, variable_dtype, combine=False): """Create Parameters for Multihead Attention. If the combine flag is set to True, then we create only one variable which stacks together all of the parameters. Otherwise, we creat...
python
def multihead_attention_params(mesh, heads, io_channels, kv_channels, variable_dtype, combine=False): """Create Parameters for Multihead Attention. If the combine flag is set to True, then we create only one variable which stacks together all of the parameters. Otherwise, we creat...
[ "def", "multihead_attention_params", "(", "mesh", ",", "heads", ",", "io_channels", ",", "kv_channels", ",", "variable_dtype", ",", "combine", "=", "False", ")", ":", "qkvo", "=", "mtf", ".", "Dimension", "(", "\"qkvo\"", ",", "4", ")", "qk_stddev", "=", "...
Create Parameters for Multihead Attention. If the combine flag is set to True, then we create only one variable which stacks together all of the parameters. Otherwise, we create four separate variables. Args: mesh: a Mesh heads: a Dimension io_channels: a Dimension kv_channels: a Dimension ...
[ "Create", "Parameters", "for", "Multihead", "Attention", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L660-L707
train
tensorflow/mesh
mesh_tensorflow/layers.py
attention_mask_ignore_padding
def attention_mask_ignore_padding(inputs, dtype=tf.float32): """Bias for encoder-decoder attention. Args: inputs: a mtf.Tensor with shape [..., length_dim] dtype: a tf.dtype Returns: a mtf.Tensor with shape [..., memory_length_dim] """ inputs = rename_length_to_memory_length(inputs) return mtf...
python
def attention_mask_ignore_padding(inputs, dtype=tf.float32): """Bias for encoder-decoder attention. Args: inputs: a mtf.Tensor with shape [..., length_dim] dtype: a tf.dtype Returns: a mtf.Tensor with shape [..., memory_length_dim] """ inputs = rename_length_to_memory_length(inputs) return mtf...
[ "def", "attention_mask_ignore_padding", "(", "inputs", ",", "dtype", "=", "tf", ".", "float32", ")", ":", "inputs", "=", "rename_length_to_memory_length", "(", "inputs", ")", "return", "mtf", ".", "cast", "(", "mtf", ".", "equal", "(", "inputs", ",", "0", ...
Bias for encoder-decoder attention. Args: inputs: a mtf.Tensor with shape [..., length_dim] dtype: a tf.dtype Returns: a mtf.Tensor with shape [..., memory_length_dim]
[ "Bias", "for", "encoder", "-", "decoder", "attention", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L918-L929
train
tensorflow/mesh
mesh_tensorflow/layers.py
attention_mask_autoregressive
def attention_mask_autoregressive(query_pos, dtype=tf.float32): """Bias for self-attention where attention to the right is disallowed. Args: query_pos: a mtf.Tensor with shape [..., length_dim] dtype: a tf.dtype Returns: a mtf.Tensor with shape [..., length_dim, memory_length_dim] """ memory_pos...
python
def attention_mask_autoregressive(query_pos, dtype=tf.float32): """Bias for self-attention where attention to the right is disallowed. Args: query_pos: a mtf.Tensor with shape [..., length_dim] dtype: a tf.dtype Returns: a mtf.Tensor with shape [..., length_dim, memory_length_dim] """ memory_pos...
[ "def", "attention_mask_autoregressive", "(", "query_pos", ",", "dtype", "=", "tf", ".", "float32", ")", ":", "memory_pos", "=", "rename_length_to_memory_length", "(", "query_pos", ")", "return", "mtf", ".", "cast", "(", "mtf", ".", "less", "(", "query_pos", ",...
Bias for self-attention where attention to the right is disallowed. Args: query_pos: a mtf.Tensor with shape [..., length_dim] dtype: a tf.dtype Returns: a mtf.Tensor with shape [..., length_dim, memory_length_dim]
[ "Bias", "for", "self", "-", "attention", "where", "attention", "to", "the", "right", "is", "disallowed", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L932-L943
train
tensorflow/mesh
mesh_tensorflow/layers.py
attention_mask_same_segment
def attention_mask_same_segment( query_segment, memory_segment=None, dtype=tf.float32): """Bias for attention where attention between segments is disallowed. Args: query_segment: a mtf.Tensor with shape [..., length_dim] memory_segment: a mtf.Tensor with shape [..., memory_length_dim] dtype: a tf.d...
python
def attention_mask_same_segment( query_segment, memory_segment=None, dtype=tf.float32): """Bias for attention where attention between segments is disallowed. Args: query_segment: a mtf.Tensor with shape [..., length_dim] memory_segment: a mtf.Tensor with shape [..., memory_length_dim] dtype: a tf.d...
[ "def", "attention_mask_same_segment", "(", "query_segment", ",", "memory_segment", "=", "None", ",", "dtype", "=", "tf", ".", "float32", ")", ":", "memory_segment", "=", "rename_length_to_memory_length", "(", "memory_segment", "or", "query_segment", ")", "return", "...
Bias for attention where attention between segments is disallowed. Args: query_segment: a mtf.Tensor with shape [..., length_dim] memory_segment: a mtf.Tensor with shape [..., memory_length_dim] dtype: a tf.dtype Returns: a mtf.Tensor with shape [..., length_dim, memory_length_dim]
[ "Bias", "for", "attention", "where", "attention", "between", "segments", "is", "disallowed", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L946-L960
train
tensorflow/mesh
mesh_tensorflow/layers.py
multiplicative_jitter
def multiplicative_jitter(x, epsilon=1e-2): """Multiply values by a random number between 1-epsilon and 1+epsilon. Makes models more resilient to rounding errors introduced by bfloat16. This seems particularly important for logits. Args: x: a mtf.Tensor epsilon: a floating point value Returns: ...
python
def multiplicative_jitter(x, epsilon=1e-2): """Multiply values by a random number between 1-epsilon and 1+epsilon. Makes models more resilient to rounding errors introduced by bfloat16. This seems particularly important for logits. Args: x: a mtf.Tensor epsilon: a floating point value Returns: ...
[ "def", "multiplicative_jitter", "(", "x", ",", "epsilon", "=", "1e-2", ")", ":", "if", "epsilon", "==", "0", ":", "return", "x", "return", "x", "*", "mtf", ".", "random_uniform", "(", "x", ".", "mesh", ",", "x", ".", "shape", ",", "minval", "=", "1...
Multiply values by a random number between 1-epsilon and 1+epsilon. Makes models more resilient to rounding errors introduced by bfloat16. This seems particularly important for logits. Args: x: a mtf.Tensor epsilon: a floating point value Returns: a mtf.Tensor with the same type and shape as x.
[ "Multiply", "values", "by", "a", "random", "number", "between", "1", "-", "epsilon", "and", "1", "+", "epsilon", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L1029-L1045
train
tensorflow/mesh
mesh_tensorflow/layers.py
multihead_self_attention_memory_compressed
def multihead_self_attention_memory_compressed(x, mask_right, compression_factor, kv_channels, heads, ...
python
def multihead_self_attention_memory_compressed(x, mask_right, compression_factor, kv_channels, heads, ...
[ "def", "multihead_self_attention_memory_compressed", "(", "x", ",", "mask_right", ",", "compression_factor", ",", "kv_channels", ",", "heads", ",", "dropout", "=", "0.0", ",", "dropout_broadcast_dims", "=", "None", ",", "master_dtype", "=", "tf", ".", "float32", "...
Memory-compressed self-attention. The memory is first average-pooled (strided) to make it shorter by a factor of compression_factor. Args: x: a mtf.Tensor with shape [<batch_dims>, query_length, io_channels] mask_right: a boolean compression_factor: an integer kv_channels: a mtf.Dimension ...
[ "Memory", "-", "compressed", "self", "-", "attention", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L1048-L1113
train
tensorflow/mesh
mesh_tensorflow/layers.py
compress_mean
def compress_mean(x, dim, compression_factor): """Compress by taking group means. Args: x: a Tensor dim: a dimension in x.shape compression_factor: an integer Returns: a Tensor """ dims = x.shape.dims pos = dims.index(dim) compressed_dim = mtf.Dimension(dim.name, dim.size // compression_...
python
def compress_mean(x, dim, compression_factor): """Compress by taking group means. Args: x: a Tensor dim: a dimension in x.shape compression_factor: an integer Returns: a Tensor """ dims = x.shape.dims pos = dims.index(dim) compressed_dim = mtf.Dimension(dim.name, dim.size // compression_...
[ "def", "compress_mean", "(", "x", ",", "dim", ",", "compression_factor", ")", ":", "dims", "=", "x", ".", "shape", ".", "dims", "pos", "=", "dims", ".", "index", "(", "dim", ")", "compressed_dim", "=", "mtf", ".", "Dimension", "(", "dim", ".", "name"...
Compress by taking group means. Args: x: a Tensor dim: a dimension in x.shape compression_factor: an integer Returns: a Tensor
[ "Compress", "by", "taking", "group", "means", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L1116-L1136
train
tensorflow/mesh
mesh_tensorflow/layers.py
embedding
def embedding(indices, vocab_dim, output_dim, variable_dtype, name="embedding"): """Embedding layer.""" weights = embedding_weights( indices.mesh, vocab_dim, output_dim, variable_dtype, name) return mtf.gather(weights, indices, vocab_dim)
python
def embedding(indices, vocab_dim, output_dim, variable_dtype, name="embedding"): """Embedding layer.""" weights = embedding_weights( indices.mesh, vocab_dim, output_dim, variable_dtype, name) return mtf.gather(weights, indices, vocab_dim)
[ "def", "embedding", "(", "indices", ",", "vocab_dim", ",", "output_dim", ",", "variable_dtype", ",", "name", "=", "\"embedding\"", ")", ":", "weights", "=", "embedding_weights", "(", "indices", ".", "mesh", ",", "vocab_dim", ",", "output_dim", ",", "variable_d...
Embedding layer.
[ "Embedding", "layer", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L1146-L1150
train
tensorflow/mesh
mesh_tensorflow/transformer/transformer_layers.py
attention_params
def attention_params(context, kv_dim, num_heads, num_memory_heads=0, shared_kv=False): """Attention Parameters for Transformer Layers. The num_heads argument indicates the number of read-heads. For the familiar behavior describe...
python
def attention_params(context, kv_dim, num_heads, num_memory_heads=0, shared_kv=False): """Attention Parameters for Transformer Layers. The num_heads argument indicates the number of read-heads. For the familiar behavior describe...
[ "def", "attention_params", "(", "context", ",", "kv_dim", ",", "num_heads", ",", "num_memory_heads", "=", "0", ",", "shared_kv", "=", "False", ")", ":", "if", "num_heads", "==", "1", ":", "query_heads_dims", "=", "None", "memory_heads_dims", "=", "None", "el...
Attention Parameters for Transformer Layers. The num_heads argument indicates the number of read-heads. For the familiar behavior described in "Attention Is All You Need", set num_memory_heads=0. If num_memory_heads==1, then there is only a single write-head, and multiple read-heads. This leads to faster ...
[ "Attention", "Parameters", "for", "Transformer", "Layers", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/transformer_layers.py#L62-L116
train
tensorflow/mesh
mesh_tensorflow/transformer/metric_utils.py
get_metric_fns
def get_metric_fns(metric_names, labels, outputs): """Generate a dictionary of metric name to metric function. Args: metric_names: list of strings in the format "prefix/metric_function_name". metric_function_name should refer to a function name in metrics.py. The prefix will be included in the key ...
python
def get_metric_fns(metric_names, labels, outputs): """Generate a dictionary of metric name to metric function. Args: metric_names: list of strings in the format "prefix/metric_function_name". metric_function_name should refer to a function name in metrics.py. The prefix will be included in the key ...
[ "def", "get_metric_fns", "(", "metric_names", ",", "labels", ",", "outputs", ")", ":", "metric_fns", "=", "{", "}", "for", "metric_name", "in", "metric_names", ":", "metric_fn_name", "=", "metric_name", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", ...
Generate a dictionary of metric name to metric function. Args: metric_names: list of strings in the format "prefix/metric_function_name". metric_function_name should refer to a function name in metrics.py. The prefix will be included in the key in the returned dict. labels: a tensor where batch i...
[ "Generate", "a", "dictionary", "of", "metric", "name", "to", "metric", "function", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/metric_utils.py#L28-L50
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/scheduler.py
minimize_peak_memory
def minimize_peak_memory(graph, scheduler_alg): """Computes a schedule to minimize peak memory. Args: graph: an mtf.auto_mtf.graph_interface.GraphInterface. scheduler_alg: a string, one of 'NAIVE' or 'LIST' Returns: an iterable of integers representing the schedule. """ if scheduler_alg == 'NAIV...
python
def minimize_peak_memory(graph, scheduler_alg): """Computes a schedule to minimize peak memory. Args: graph: an mtf.auto_mtf.graph_interface.GraphInterface. scheduler_alg: a string, one of 'NAIVE' or 'LIST' Returns: an iterable of integers representing the schedule. """ if scheduler_alg == 'NAIV...
[ "def", "minimize_peak_memory", "(", "graph", ",", "scheduler_alg", ")", ":", "if", "scheduler_alg", "==", "'NAIVE'", ":", "return", "_minimize_peak_memory_naive", "(", "graph", ")", "elif", "scheduler_alg", "==", "'LIST'", ":", "return", "_minimize_peak_memory_list", ...
Computes a schedule to minimize peak memory. Args: graph: an mtf.auto_mtf.graph_interface.GraphInterface. scheduler_alg: a string, one of 'NAIVE' or 'LIST' Returns: an iterable of integers representing the schedule.
[ "Computes", "a", "schedule", "to", "minimize", "peak", "memory", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/scheduler.py#L35-L52
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/scheduler.py
_minimize_peak_memory_list
def _minimize_peak_memory_list(graph): """Computes schedule according to the greedy list heuristic. Greedy list heuristic: schedule the operation which results in the most bytes of memory being (immediately) freed. TODO(joshuawang): Experiment with tiebreaking by preferring more successors. Args: graph:...
python
def _minimize_peak_memory_list(graph): """Computes schedule according to the greedy list heuristic. Greedy list heuristic: schedule the operation which results in the most bytes of memory being (immediately) freed. TODO(joshuawang): Experiment with tiebreaking by preferring more successors. Args: graph:...
[ "def", "_minimize_peak_memory_list", "(", "graph", ")", ":", "schedule", "=", "[", "]", "bytes_freed", "=", "{", "}", "users_of", "=", "collections", ".", "defaultdict", "(", "set", ")", "in_degree", "=", "collections", ".", "defaultdict", "(", "int", ")", ...
Computes schedule according to the greedy list heuristic. Greedy list heuristic: schedule the operation which results in the most bytes of memory being (immediately) freed. TODO(joshuawang): Experiment with tiebreaking by preferring more successors. Args: graph: an mtf.auto_mtf.graph_interface.GraphInterf...
[ "Computes", "schedule", "according", "to", "the", "greedy", "list", "heuristic", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/scheduler.py#L67-L154
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/layout.py
layout
def layout(mtf_graph, mesh_shape, mtf_outputs=()): """Compute layout rules based on a computational graph and mesh shape. Args: mtf_graph: a mtf.Graph. mesh_shape: an mtf.Shape, str, or listlike of mtf.Dimension. mtf_outputs: an optional iterable of mtf.Tensor, representing the outputs of the c...
python
def layout(mtf_graph, mesh_shape, mtf_outputs=()): """Compute layout rules based on a computational graph and mesh shape. Args: mtf_graph: a mtf.Graph. mesh_shape: an mtf.Shape, str, or listlike of mtf.Dimension. mtf_outputs: an optional iterable of mtf.Tensor, representing the outputs of the c...
[ "def", "layout", "(", "mtf_graph", ",", "mesh_shape", ",", "mtf_outputs", "=", "(", ")", ")", ":", "mesh_shape", "=", "mtf", ".", "convert_to_shape", "(", "mesh_shape", ")", "estimator", "=", "memory_estimator", ".", "MemoryEstimator", "(", "mtf_graph", ",", ...
Compute layout rules based on a computational graph and mesh shape. Args: mtf_graph: a mtf.Graph. mesh_shape: an mtf.Shape, str, or listlike of mtf.Dimension. mtf_outputs: an optional iterable of mtf.Tensor, representing the outputs of the computation. Returns: a mtf.LayoutRules
[ "Compute", "layout", "rules", "based", "on", "a", "computational", "graph", "and", "mesh", "shape", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout.py#L47-L63
train
tensorflow/mesh
mesh_tensorflow/optimize.py
Optimizer.apply_grads
def apply_grads(self, grads, variables): """Apply gradients to variables. Call this function externally instead of apply_grad(). This causes the operations to be combined, which is necessary for stacking variables see mtf.rewrite_stack_variables(). Args: grads: a list of Tensor variab...
python
def apply_grads(self, grads, variables): """Apply gradients to variables. Call this function externally instead of apply_grad(). This causes the operations to be combined, which is necessary for stacking variables see mtf.rewrite_stack_variables(). Args: grads: a list of Tensor variab...
[ "def", "apply_grads", "(", "self", ",", "grads", ",", "variables", ")", ":", "ops", "=", "[", "]", "for", "grad", ",", "var", "in", "zip", "(", "grads", ",", "variables", ")", ":", "ops", ".", "extend", "(", "self", ".", "apply_grad", "(", "grad", ...
Apply gradients to variables. Call this function externally instead of apply_grad(). This causes the operations to be combined, which is necessary for stacking variables see mtf.rewrite_stack_variables(). Args: grads: a list of Tensor variables: a list of Variables Returns: a li...
[ "Apply", "gradients", "to", "variables", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/optimize.py#L39-L57
train
tensorflow/mesh
mesh_tensorflow/optimize.py
AdafactorOptimizer._factored_dims
def _factored_dims(self, shape): """Should we use a factored second moment estimator. Based on the shape of the variable. If we factor the accumulator, then this function returns a list of two mtf.Dimensions to reduce over. We always pick the two largest dimensions. If there are not two dimensions...
python
def _factored_dims(self, shape): """Should we use a factored second moment estimator. Based on the shape of the variable. If we factor the accumulator, then this function returns a list of two mtf.Dimensions to reduce over. We always pick the two largest dimensions. If there are not two dimensions...
[ "def", "_factored_dims", "(", "self", ",", "shape", ")", ":", "if", "not", "self", ".", "_factored", "or", "shape", ".", "ndims", "<", "2", ":", "return", "None", "sorted_dims", "=", "sorted", "(", "shape", ".", "dims", ",", "key", "=", "lambda", "d"...
Should we use a factored second moment estimator. Based on the shape of the variable. If we factor the accumulator, then this function returns a list of two mtf.Dimensions to reduce over. We always pick the two largest dimensions. If there are not two dimensions of size >= min_dim_size_to_factor, then...
[ "Should", "we", "use", "a", "factored", "second", "moment", "estimator", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/optimize.py#L139-L158
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/valid_layouts.py
LayoutValidator.is_valid_assignment
def is_valid_assignment(self, mtf_dimension_name, mesh_dimension_name): """Whether this MTF dimension may be assigned to this mesh dimension. Args: mtf_dimension_name: string, the name of a Mesh TensorFlow dimension. mesh_dimension_name: string, the name of a mesh dimension. Returns: A b...
python
def is_valid_assignment(self, mtf_dimension_name, mesh_dimension_name): """Whether this MTF dimension may be assigned to this mesh dimension. Args: mtf_dimension_name: string, the name of a Mesh TensorFlow dimension. mesh_dimension_name: string, the name of a mesh dimension. Returns: A b...
[ "def", "is_valid_assignment", "(", "self", ",", "mtf_dimension_name", ",", "mesh_dimension_name", ")", ":", "return", "(", "(", "mtf_dimension_name", "in", "self", ".", "_splittable_mtf_dimension_names", ")", "and", "(", "self", ".", "_mtf_dimension_name_to_size_gcd", ...
Whether this MTF dimension may be assigned to this mesh dimension. Args: mtf_dimension_name: string, the name of a Mesh TensorFlow dimension. mesh_dimension_name: string, the name of a mesh dimension. Returns: A boolean indicating whether the assignment is valid.
[ "Whether", "this", "MTF", "dimension", "may", "be", "assigned", "to", "this", "mesh", "dimension", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/valid_layouts.py#L83-L95
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/valid_layouts.py
LayoutValidator._initialize_splittable_dimensions
def _initialize_splittable_dimensions(self, mtf_graph): """Initializer for self._splittable_mtf_dimension_names. Args: mtf_graph: an mtf.Graph. Returns: A set(string) of the names of Mesh TensorFlow dimensions that may be assigned in a layout. """ all_mtf_dimension_names = set() ...
python
def _initialize_splittable_dimensions(self, mtf_graph): """Initializer for self._splittable_mtf_dimension_names. Args: mtf_graph: an mtf.Graph. Returns: A set(string) of the names of Mesh TensorFlow dimensions that may be assigned in a layout. """ all_mtf_dimension_names = set() ...
[ "def", "_initialize_splittable_dimensions", "(", "self", ",", "mtf_graph", ")", ":", "all_mtf_dimension_names", "=", "set", "(", ")", "for", "mtf_operation", "in", "mtf_graph", ".", "operations", ":", "for", "mtf_tensor", "in", "mtf_operation", ".", "outputs", ":"...
Initializer for self._splittable_mtf_dimension_names. Args: mtf_graph: an mtf.Graph. Returns: A set(string) of the names of Mesh TensorFlow dimensions that may be assigned in a layout.
[ "Initializer", "for", "self", ".", "_splittable_mtf_dimension_names", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/valid_layouts.py#L97-L118
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/valid_layouts.py
LayoutValidator._initialize_mtf_dimension_name_to_size_gcd
def _initialize_mtf_dimension_name_to_size_gcd(self, mtf_graph): """Initializer for self._mtf_dimension_name_to_size_gcd. Args: mtf_graph: an mtf.Graph. Returns: A {string: int}, mapping the name of an MTF dimension to the greatest common divisor of all the sizes it has. All these sizes ...
python
def _initialize_mtf_dimension_name_to_size_gcd(self, mtf_graph): """Initializer for self._mtf_dimension_name_to_size_gcd. Args: mtf_graph: an mtf.Graph. Returns: A {string: int}, mapping the name of an MTF dimension to the greatest common divisor of all the sizes it has. All these sizes ...
[ "def", "_initialize_mtf_dimension_name_to_size_gcd", "(", "self", ",", "mtf_graph", ")", ":", "mtf_dimension_name_to_size_gcd", "=", "{", "}", "for", "mtf_operation", "in", "mtf_graph", ".", "operations", ":", "for", "mtf_tensor", "in", "mtf_operation", ".", "outputs"...
Initializer for self._mtf_dimension_name_to_size_gcd. Args: mtf_graph: an mtf.Graph. Returns: A {string: int}, mapping the name of an MTF dimension to the greatest common divisor of all the sizes it has. All these sizes being evenly divisible by some x is equivalent to the GCD being di...
[ "Initializer", "for", "self", ".", "_mtf_dimension_name_to_size_gcd", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/valid_layouts.py#L120-L140
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/valid_layouts.py
LayoutValidator._initialize_mesh_dimension_name_to_size
def _initialize_mesh_dimension_name_to_size(self, mesh_shape): """Initializer for self._mesh_dimension_name_to_size. Args: mesh_shape: an mtf.Shape. Returns: A {string: int} mapping mesh dimension names to their sizes. """ mesh_dimension_name_to_size = {} # {string: int} for mesh_...
python
def _initialize_mesh_dimension_name_to_size(self, mesh_shape): """Initializer for self._mesh_dimension_name_to_size. Args: mesh_shape: an mtf.Shape. Returns: A {string: int} mapping mesh dimension names to their sizes. """ mesh_dimension_name_to_size = {} # {string: int} for mesh_...
[ "def", "_initialize_mesh_dimension_name_to_size", "(", "self", ",", "mesh_shape", ")", ":", "mesh_dimension_name_to_size", "=", "{", "}", "for", "mesh_dimension", "in", "mesh_shape", ".", "dims", ":", "mesh_dimension_name_to_size", "[", "mesh_dimension", ".", "name", ...
Initializer for self._mesh_dimension_name_to_size. Args: mesh_shape: an mtf.Shape. Returns: A {string: int} mapping mesh dimension names to their sizes.
[ "Initializer", "for", "self", ".", "_mesh_dimension_name_to_size", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/valid_layouts.py#L142-L154
train
tensorflow/mesh
mesh_tensorflow/placement_mesh_impl.py
allconcat_ring
def allconcat_ring(xs, devices, concat_axis): """Concatenate all Tensors everywhere. Performance-optimized for a ring of devices. Args: xs: a list of n tf.Tensors devices: a list of n strings concat_axis: an integer Returns: a list of n Tensors """ n = len(xs) if n == 1: return xs ...
python
def allconcat_ring(xs, devices, concat_axis): """Concatenate all Tensors everywhere. Performance-optimized for a ring of devices. Args: xs: a list of n tf.Tensors devices: a list of n strings concat_axis: an integer Returns: a list of n Tensors """ n = len(xs) if n == 1: return xs ...
[ "def", "allconcat_ring", "(", "xs", ",", "devices", ",", "concat_axis", ")", ":", "n", "=", "len", "(", "xs", ")", "if", "n", "==", "1", ":", "return", "xs", "parts", "=", "[", "[", "xs", "[", "target", "]", "if", "target", "==", "source", "else"...
Concatenate all Tensors everywhere. Performance-optimized for a ring of devices. Args: xs: a list of n tf.Tensors devices: a list of n strings concat_axis: an integer Returns: a list of n Tensors
[ "Concatenate", "all", "Tensors", "everywhere", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/placement_mesh_impl.py#L462-L491
train
tensorflow/mesh
mesh_tensorflow/placement_mesh_impl.py
PlacementMeshImpl.Print
def Print(self, x, data, message, **kwargs): # pylint: disable=invalid-name """call tf.Print. Args: x: a LaidOutTensor data: a list of LaidOutTensor message: a string **kwargs: keyword arguments to tf.print Returns: a LaidOutTensor """ tf.logging.info("PlacementMeshIm...
python
def Print(self, x, data, message, **kwargs): # pylint: disable=invalid-name """call tf.Print. Args: x: a LaidOutTensor data: a list of LaidOutTensor message: a string **kwargs: keyword arguments to tf.print Returns: a LaidOutTensor """ tf.logging.info("PlacementMeshIm...
[ "def", "Print", "(", "self", ",", "x", ",", "data", ",", "message", ",", "**", "kwargs", ")", ":", "tf", ".", "logging", ".", "info", "(", "\"PlacementMeshImpl::Print\"", ")", "new_slices", "=", "x", ".", "tensor_list", "[", ":", "]", "with", "tf", "...
call tf.Print. Args: x: a LaidOutTensor data: a list of LaidOutTensor message: a string **kwargs: keyword arguments to tf.print Returns: a LaidOutTensor
[ "call", "tf", ".", "Print", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/placement_mesh_impl.py#L185-L202
train
tensorflow/mesh
mesh_tensorflow/placement_mesh_impl.py
PlacementMeshImpl.alltoall
def alltoall(self, x, mesh_axis, split_axis, concat_axis): """Grouped alltoall. Args: x: a LaidOutTensor mesh_axis: an integer the mesh axis along which to group split_axis: an integer (the Tensor axis along which to split) concat_axis: an integer (the Tensor axis along which to concate...
python
def alltoall(self, x, mesh_axis, split_axis, concat_axis): """Grouped alltoall. Args: x: a LaidOutTensor mesh_axis: an integer the mesh axis along which to group split_axis: an integer (the Tensor axis along which to split) concat_axis: an integer (the Tensor axis along which to concate...
[ "def", "alltoall", "(", "self", ",", "x", ",", "mesh_axis", ",", "split_axis", ",", "concat_axis", ")", ":", "return", "self", ".", "_collective_with_groups", "(", "x", ",", "[", "mesh_axis", "]", ",", "functools", ".", "partial", "(", "alltoall_ring", ","...
Grouped alltoall. Args: x: a LaidOutTensor mesh_axis: an integer the mesh axis along which to group split_axis: an integer (the Tensor axis along which to split) concat_axis: an integer (the Tensor axis along which to concatenate) Returns: a LaidOutTensor
[ "Grouped", "alltoall", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/placement_mesh_impl.py#L232-L246
train
tensorflow/mesh
mesh_tensorflow/placement_mesh_impl.py
PlacementMeshImpl.import_tf_tensor
def import_tf_tensor(self, x, tf_x): """Import a tf.Tensor, producing a LaidOutTensor. Args: x: a Tensor tf_x: a tf.Tensor Returns: a LaidOutTensor """ return self.LaidOutTensor(self.make_slices(tf_x, x.shape))
python
def import_tf_tensor(self, x, tf_x): """Import a tf.Tensor, producing a LaidOutTensor. Args: x: a Tensor tf_x: a tf.Tensor Returns: a LaidOutTensor """ return self.LaidOutTensor(self.make_slices(tf_x, x.shape))
[ "def", "import_tf_tensor", "(", "self", ",", "x", ",", "tf_x", ")", ":", "return", "self", ".", "LaidOutTensor", "(", "self", ".", "make_slices", "(", "tf_x", ",", "x", ".", "shape", ")", ")" ]
Import a tf.Tensor, producing a LaidOutTensor. Args: x: a Tensor tf_x: a tf.Tensor Returns: a LaidOutTensor
[ "Import", "a", "tf", ".", "Tensor", "producing", "a", "LaidOutTensor", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/placement_mesh_impl.py#L350-L359
train
tensorflow/mesh
mesh_tensorflow/transformer/attention.py
attention
def attention(q, k, v, memory_length_dim, key_dim, value_dim, mask=None, dropout_rate=0.0, dropout_broadcast_dims=None, extra_logit=None): """Dot-product attention - doesn't use positional dim...
python
def attention(q, k, v, memory_length_dim, key_dim, value_dim, mask=None, dropout_rate=0.0, dropout_broadcast_dims=None, extra_logit=None): """Dot-product attention - doesn't use positional dim...
[ "def", "attention", "(", "q", ",", "k", ",", "v", ",", "memory_length_dim", ",", "key_dim", ",", "value_dim", ",", "mask", "=", "None", ",", "dropout_rate", "=", "0.0", ",", "dropout_broadcast_dims", "=", "None", ",", "extra_logit", "=", "None", ")", ":"...
Dot-product attention - doesn't use positional dimensions. key_dim is a Dimension representing the channels in the queries and keys value_dim is a Dimension representing the channels in values memory_length_dim is a Dimension representing the different key/value pairs. Dimensions of q: other_query_dims + {key...
[ "Dot", "-", "product", "attention", "-", "doesn", "t", "use", "positional", "dimensions", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/attention.py#L27-L76
train
tensorflow/mesh
mesh_tensorflow/transformer/attention.py
attention_params_simple
def attention_params_simple( mesh, io_dim, kv_dim, heads_dim, variable_dtype): """Common case attention parameters. Args: mesh: a Mesh io_dim: a Dimension (channels dimension of inputs and outputs) kv_dim: a Dimension (channels in keys and values) heads_dim: a Dimension (number of attention "he...
python
def attention_params_simple( mesh, io_dim, kv_dim, heads_dim, variable_dtype): """Common case attention parameters. Args: mesh: a Mesh io_dim: a Dimension (channels dimension of inputs and outputs) kv_dim: a Dimension (channels in keys and values) heads_dim: a Dimension (number of attention "he...
[ "def", "attention_params_simple", "(", "mesh", ",", "io_dim", ",", "kv_dim", ",", "heads_dim", ",", "variable_dtype", ")", ":", "return", "AttentionParams", "(", "mesh", ",", "query_input_dim", "=", "io_dim", ",", "memory_input_dim", "=", "io_dim", ",", "output_...
Common case attention parameters. Args: mesh: a Mesh io_dim: a Dimension (channels dimension of inputs and outputs) kv_dim: a Dimension (channels in keys and values) heads_dim: a Dimension (number of attention "heads") variable_dtype: a mtf.VariableDType Returns: an AttentionParams
[ "Common", "case", "attention", "parameters", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/attention.py#L264-L286
train
tensorflow/mesh
mesh_tensorflow/transformer/attention.py
local_attention_1d
def local_attention_1d(q, k, v, length_dim, key_dim, value_dim, autoregressive=True, length_dim_num_splits=1, radius=128, ...
python
def local_attention_1d(q, k, v, length_dim, key_dim, value_dim, autoregressive=True, length_dim_num_splits=1, radius=128, ...
[ "def", "local_attention_1d", "(", "q", ",", "k", ",", "v", ",", "length_dim", ",", "key_dim", ",", "value_dim", ",", "autoregressive", "=", "True", ",", "length_dim_num_splits", "=", "1", ",", "radius", "=", "128", ",", "sequence_id", "=", "1", ",", "att...
Attention to the a neighborood around the source. If autoregressive, then query position p can only see memory positions in the range (p - radius, p]. If not autoregressive, then query position p can only see memory positions in the range (p - window_size, p + radius]. Args: q: a Tensor containing leng...
[ "Attention", "to", "the", "a", "neighborood", "around", "the", "source", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/attention.py#L289-L377
train
tensorflow/mesh
mesh_tensorflow/transformer/attention.py
AttentionParams.compute_q
def compute_q(self, query_antecedent): """Compute query Tensor q. Args: query_antecedent: a Tensor with dimensions {query_input_dim} + other_dims Returns: a Tensor with dimensions query_heads_dims + {key_dim} + other_dims """ ret = mtf.einsum( [query_antecedent...
python
def compute_q(self, query_antecedent): """Compute query Tensor q. Args: query_antecedent: a Tensor with dimensions {query_input_dim} + other_dims Returns: a Tensor with dimensions query_heads_dims + {key_dim} + other_dims """ ret = mtf.einsum( [query_antecedent...
[ "def", "compute_q", "(", "self", ",", "query_antecedent", ")", ":", "ret", "=", "mtf", ".", "einsum", "(", "[", "query_antecedent", ",", "self", ".", "wq", "]", ",", "reduced_dims", "=", "[", "self", ".", "query_input_dim", "]", ")", "if", "self", ".",...
Compute query Tensor q. Args: query_antecedent: a Tensor with dimensions {query_input_dim} + other_dims Returns: a Tensor with dimensions query_heads_dims + {key_dim} + other_dims
[ "Compute", "query", "Tensor", "q", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/attention.py#L153-L167
train
tensorflow/mesh
mesh_tensorflow/transformer/attention.py
AttentionParams.compute_k
def compute_k(self, memory_antecedent): """Compute key Tensor k. Args: memory_antecedent: a Tensor with dimensions {memory_input_dim} + other_dims Returns: a Tensor with dimensions memory_heads_dims + {key_dim} + other_dims """ if self.shared_kv: raise ValueError("...
python
def compute_k(self, memory_antecedent): """Compute key Tensor k. Args: memory_antecedent: a Tensor with dimensions {memory_input_dim} + other_dims Returns: a Tensor with dimensions memory_heads_dims + {key_dim} + other_dims """ if self.shared_kv: raise ValueError("...
[ "def", "compute_k", "(", "self", ",", "memory_antecedent", ")", ":", "if", "self", ".", "shared_kv", ":", "raise", "ValueError", "(", "\"compute_k cannot be called with shared_kv\"", ")", "ret", "=", "mtf", ".", "einsum", "(", "[", "memory_antecedent", ",", "sel...
Compute key Tensor k. Args: memory_antecedent: a Tensor with dimensions {memory_input_dim} + other_dims Returns: a Tensor with dimensions memory_heads_dims + {key_dim} + other_dims
[ "Compute", "key", "Tensor", "k", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/attention.py#L187-L203
train
tensorflow/mesh
mesh_tensorflow/transformer/attention.py
AttentionParams.compute_v
def compute_v(self, memory_antecedent): """Compute value Tensor v. Args: memory_antecedent: a Tensor with dimensions {memory_input_dim} + other_dims Returns: a Tensor with dimensions memory_heads_dims + {value_dim} + other_dims """ if self.shared_kv: raise ValueErr...
python
def compute_v(self, memory_antecedent): """Compute value Tensor v. Args: memory_antecedent: a Tensor with dimensions {memory_input_dim} + other_dims Returns: a Tensor with dimensions memory_heads_dims + {value_dim} + other_dims """ if self.shared_kv: raise ValueErr...
[ "def", "compute_v", "(", "self", ",", "memory_antecedent", ")", ":", "if", "self", ".", "shared_kv", ":", "raise", "ValueError", "(", "\"compute_v cannot be called with shared_kv\"", ")", "ret", "=", "mtf", ".", "einsum", "(", "[", "memory_antecedent", ",", "sel...
Compute value Tensor v. Args: memory_antecedent: a Tensor with dimensions {memory_input_dim} + other_dims Returns: a Tensor with dimensions memory_heads_dims + {value_dim} + other_dims
[ "Compute", "value", "Tensor", "v", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/attention.py#L205-L221
train
tensorflow/mesh
mesh_tensorflow/transformer/attention.py
AttentionParams.compute_output
def compute_output(self, o, output_shape=None): """Compute output of multihead attention. Args: o: a Tensor with dimensions query_heads_dims + {value_dim} + other_dims output_shape: an optional Shape Returns: a Tensor with shape: {output_dim} + other_dims """ if ...
python
def compute_output(self, o, output_shape=None): """Compute output of multihead attention. Args: o: a Tensor with dimensions query_heads_dims + {value_dim} + other_dims output_shape: an optional Shape Returns: a Tensor with shape: {output_dim} + other_dims """ if ...
[ "def", "compute_output", "(", "self", ",", "o", ",", "output_shape", "=", "None", ")", ":", "if", "self", ".", "combine_dims", ":", "o", "=", "mtf", ".", "transpose", "(", "o", ",", "o", ".", "shape", "-", "self", ".", "o_dims", "+", "self", ".", ...
Compute output of multihead attention. Args: o: a Tensor with dimensions query_heads_dims + {value_dim} + other_dims output_shape: an optional Shape Returns: a Tensor with shape: {output_dim} + other_dims
[ "Compute", "output", "of", "multihead", "attention", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/attention.py#L223-L241
train
tensorflow/mesh
mesh_tensorflow/transformer/t2t_vocabulary.py
T2tVocabulary.encode_tf
def encode_tf(self, s): """Encode a tf.Scalar string to a tf.Tensor. This will be necessary for on-the-fly tokenization. Args: s: a tf.Scalar with dtype tf.string Returns: a 1d tf.Tensor with dtype tf.int32 """ ids = subword_text_encoder_ops.subword_text_encoder_encode( s, ...
python
def encode_tf(self, s): """Encode a tf.Scalar string to a tf.Tensor. This will be necessary for on-the-fly tokenization. Args: s: a tf.Scalar with dtype tf.string Returns: a 1d tf.Tensor with dtype tf.int32 """ ids = subword_text_encoder_ops.subword_text_encoder_encode( s, ...
[ "def", "encode_tf", "(", "self", ",", "s", ")", ":", "ids", "=", "subword_text_encoder_ops", ".", "subword_text_encoder_encode", "(", "s", ",", "self", ".", "_filepath", ")", "return", "ids", "[", ":", "-", "1", "]" ]
Encode a tf.Scalar string to a tf.Tensor. This will be necessary for on-the-fly tokenization. Args: s: a tf.Scalar with dtype tf.string Returns: a 1d tf.Tensor with dtype tf.int32
[ "Encode", "a", "tf", ".", "Scalar", "string", "to", "a", "tf", ".", "Tensor", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/t2t_vocabulary.py#L79-L92
train
tensorflow/mesh
mesh_tensorflow/transformer/model_builder.py
simple_layer_stack
def simple_layer_stack(include_encdec_attention, num_layers=6, d_ff=2048, num_heads=8, d_kv=128, dropout_rate=0.1): """Create a layer stack. Args: include_encdec_attention: a boolean num_layer...
python
def simple_layer_stack(include_encdec_attention, num_layers=6, d_ff=2048, num_heads=8, d_kv=128, dropout_rate=0.1): """Create a layer stack. Args: include_encdec_attention: a boolean num_layer...
[ "def", "simple_layer_stack", "(", "include_encdec_attention", ",", "num_layers", "=", "6", ",", "d_ff", "=", "2048", ",", "num_heads", "=", "8", ",", "d_kv", "=", "128", ",", "dropout_rate", "=", "0.1", ")", ":", "ret", "=", "[", "]", "for", "_", "in",...
Create a layer stack. Args: include_encdec_attention: a boolean num_layers: an integer d_ff: an integer num_heads: an integer d_kv: an integer dropout_rate: a float Returns: a LayerStack
[ "Create", "a", "layer", "stack", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/model_builder.py#L30-L66
train
tensorflow/mesh
examples/toy_model_tpu.py
toy_model
def toy_model(features, mesh): """A toy model implemented by mesh tensorlfow.""" batch_dim = mtf.Dimension('batch', FLAGS.batch_size) io_dim = mtf.Dimension('io', FLAGS.io_size) master_dtype = tf.as_dtype(FLAGS.master_dtype) slice_dtype = tf.as_dtype(FLAGS.slice_dtype) activation_dtype = tf.as_dtype(FLAGS....
python
def toy_model(features, mesh): """A toy model implemented by mesh tensorlfow.""" batch_dim = mtf.Dimension('batch', FLAGS.batch_size) io_dim = mtf.Dimension('io', FLAGS.io_size) master_dtype = tf.as_dtype(FLAGS.master_dtype) slice_dtype = tf.as_dtype(FLAGS.slice_dtype) activation_dtype = tf.as_dtype(FLAGS....
[ "def", "toy_model", "(", "features", ",", "mesh", ")", ":", "batch_dim", "=", "mtf", ".", "Dimension", "(", "'batch'", ",", "FLAGS", ".", "batch_size", ")", "io_dim", "=", "mtf", ".", "Dimension", "(", "'io'", ",", "FLAGS", ".", "io_size", ")", "master...
A toy model implemented by mesh tensorlfow.
[ "A", "toy", "model", "implemented", "by", "mesh", "tensorlfow", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/toy_model_tpu.py#L103-L142
train
tensorflow/mesh
examples/toy_model_tpu.py
run_toy_model_tpu
def run_toy_model_tpu(): """Run a toy model on TPU.""" tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver( FLAGS.tpu, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project) iterations_per_loop = FLAGS.iterations mesh_shape = mtf.convert_to_shape(FLAGS.mesh_shape) config = tpu_config.RunConf...
python
def run_toy_model_tpu(): """Run a toy model on TPU.""" tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver( FLAGS.tpu, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project) iterations_per_loop = FLAGS.iterations mesh_shape = mtf.convert_to_shape(FLAGS.mesh_shape) config = tpu_config.RunConf...
[ "def", "run_toy_model_tpu", "(", ")", ":", "tpu_cluster_resolver", "=", "tf", ".", "contrib", ".", "cluster_resolver", ".", "TPUClusterResolver", "(", "FLAGS", ".", "tpu", ",", "zone", "=", "FLAGS", ".", "tpu_zone", ",", "project", "=", "FLAGS", ".", "gcp_pr...
Run a toy model on TPU.
[ "Run", "a", "toy", "model", "on", "TPU", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/toy_model_tpu.py#L243-L282
train
tensorflow/mesh
examples/mnist.py
mnist_model
def mnist_model(image, labels, mesh): """The model. Args: image: tf.Tensor with shape [batch, 28*28] labels: a tf.Tensor with shape [batch] and dtype tf.int32 mesh: a mtf.Mesh Returns: logits: a mtf.Tensor with shape [batch, 10] loss: a mtf.Tensor with shape [] """ batch_dim = mtf.Dimens...
python
def mnist_model(image, labels, mesh): """The model. Args: image: tf.Tensor with shape [batch, 28*28] labels: a tf.Tensor with shape [batch] and dtype tf.int32 mesh: a mtf.Mesh Returns: logits: a mtf.Tensor with shape [batch, 10] loss: a mtf.Tensor with shape [] """ batch_dim = mtf.Dimens...
[ "def", "mnist_model", "(", "image", ",", "labels", ",", "mesh", ")", ":", "batch_dim", "=", "mtf", ".", "Dimension", "(", "\"batch\"", ",", "FLAGS", ".", "batch_size", ")", "row_blocks_dim", "=", "mtf", ".", "Dimension", "(", "\"row_blocks\"", ",", "4", ...
The model. Args: image: tf.Tensor with shape [batch, 28*28] labels: a tf.Tensor with shape [batch] and dtype tf.int32 mesh: a mtf.Mesh Returns: logits: a mtf.Tensor with shape [batch, 10] loss: a mtf.Tensor with shape []
[ "The", "model", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/mnist.py#L50-L118
train
tensorflow/mesh
examples/mnist.py
run_mnist
def run_mnist(): """Run MNIST training and eval loop.""" mnist_classifier = tf.estimator.Estimator( model_fn=model_fn, model_dir=FLAGS.model_dir) # Set up training and evaluation input functions. def train_input_fn(): """Prepare data for training.""" # When choosing shuffle buffer sizes, l...
python
def run_mnist(): """Run MNIST training and eval loop.""" mnist_classifier = tf.estimator.Estimator( model_fn=model_fn, model_dir=FLAGS.model_dir) # Set up training and evaluation input functions. def train_input_fn(): """Prepare data for training.""" # When choosing shuffle buffer sizes, l...
[ "def", "run_mnist", "(", ")", ":", "mnist_classifier", "=", "tf", ".", "estimator", ".", "Estimator", "(", "model_fn", "=", "model_fn", ",", "model_dir", "=", "FLAGS", ".", "model_dir", ")", "def", "train_input_fn", "(", ")", ":", "ds", "=", "dataset", "...
Run MNIST training and eval loop.
[ "Run", "MNIST", "training", "and", "eval", "loop", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/mnist.py#L207-L236
train
tensorflow/mesh
mesh_tensorflow/transformer/moe.py
MoE2D.call
def call(self, context, x, losses=None): """Call the layer.""" has_length_dim = context.length_dim in x.shape.dims if not has_length_dim: x_shape = x.shape shape_with_length = mtf.Shape( x_shape.dims[:-1] + [mtf.Dimension("length", 1)] + x_shape.dims[-1:]) x = mtf.resha...
python
def call(self, context, x, losses=None): """Call the layer.""" has_length_dim = context.length_dim in x.shape.dims if not has_length_dim: x_shape = x.shape shape_with_length = mtf.Shape( x_shape.dims[:-1] + [mtf.Dimension("length", 1)] + x_shape.dims[-1:]) x = mtf.resha...
[ "def", "call", "(", "self", ",", "context", ",", "x", ",", "losses", "=", "None", ")", ":", "has_length_dim", "=", "context", ".", "length_dim", "in", "x", ".", "shape", ".", "dims", "if", "not", "has_length_dim", ":", "x_shape", "=", "x", ".", "shap...
Call the layer.
[ "Call", "the", "layer", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/moe.py#L123-L145
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/print_cp_model_solution.py
print_solution
def print_solution(model, solver): """Prints the solution associated with solver. If solver has already had Solve() called on it, prints the solution. This includes each variable and its assignment, along with the objective function and its optimal value. If solver has not had Solve() called on it, or there ...
python
def print_solution(model, solver): """Prints the solution associated with solver. If solver has already had Solve() called on it, prints the solution. This includes each variable and its assignment, along with the objective function and its optimal value. If solver has not had Solve() called on it, or there ...
[ "def", "print_solution", "(", "model", ",", "solver", ")", ":", "model_proto", "=", "model", ".", "Proto", "(", ")", "response_proto", "=", "solver", ".", "ResponseProto", "(", ")", "variables_in_objective_map", "=", "{", "}", "maximization", "=", "False", "...
Prints the solution associated with solver. If solver has already had Solve() called on it, prints the solution. This includes each variable and its assignment, along with the objective function and its optimal value. If solver has not had Solve() called on it, or there is no feasible solution, this will pro...
[ "Prints", "the", "solution", "associated", "with", "solver", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/print_cp_model_solution.py#L32-L84
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/layout_optimizer.py
_local_var_name
def _local_var_name(splittable_dimensions, assignment): """Name for a local variable. Args: splittable_dimensions: frozenset of names of splittable dimensions. assignment: dict from names of splittable dimensions to names of mesh dimensions. Returns: A string, the variable name. """ assign...
python
def _local_var_name(splittable_dimensions, assignment): """Name for a local variable. Args: splittable_dimensions: frozenset of names of splittable dimensions. assignment: dict from names of splittable dimensions to names of mesh dimensions. Returns: A string, the variable name. """ assign...
[ "def", "_local_var_name", "(", "splittable_dimensions", ",", "assignment", ")", ":", "assignment_string", "=", "[", "]", "for", "splittable", "in", "sorted", "(", "splittable_dimensions", ")", ":", "if", "splittable", "in", "assignment", ":", "assignment_string", ...
Name for a local variable. Args: splittable_dimensions: frozenset of names of splittable dimensions. assignment: dict from names of splittable dimensions to names of mesh dimensions. Returns: A string, the variable name.
[ "Name", "for", "a", "local", "variable", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout_optimizer.py#L383-L401
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/layout_optimizer.py
_generate_assignments
def _generate_assignments(splittable_dimensions, mesh_dimension_to_size): """Generates all ways to map splittable dimensions to mesh dimensions. Args: splittable_dimensions: a frozenset of the names of splittable dimensions. mesh_dimension_to_size: a dictionary from mesh dimension name to size. Returns:...
python
def _generate_assignments(splittable_dimensions, mesh_dimension_to_size): """Generates all ways to map splittable dimensions to mesh dimensions. Args: splittable_dimensions: a frozenset of the names of splittable dimensions. mesh_dimension_to_size: a dictionary from mesh dimension name to size. Returns:...
[ "def", "_generate_assignments", "(", "splittable_dimensions", ",", "mesh_dimension_to_size", ")", ":", "assignments", "=", "[", "]", "for", "assignment_size", "in", "six", ".", "moves", ".", "xrange", "(", "1", "+", "min", "(", "len", "(", "splittable_dimensions...
Generates all ways to map splittable dimensions to mesh dimensions. Args: splittable_dimensions: a frozenset of the names of splittable dimensions. mesh_dimension_to_size: a dictionary from mesh dimension name to size. Returns: A list of the valid assignments. Each assignment is a dict keyed by every ...
[ "Generates", "all", "ways", "to", "map", "splittable", "dimensions", "to", "mesh", "dimensions", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout_optimizer.py#L404-L423
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/layout_optimizer.py
LayoutOptimizer._preprocess_input
def _preprocess_input(self): """Computing useful input data structures to ease IP construction.""" # Compute the sets of MTF dimensions used in operations/tensors. # a {string: frozenset(string)}, mapping operation name to MTF dimension # names. self._operation_name_to_mtf_dimension_set = {} # ...
python
def _preprocess_input(self): """Computing useful input data structures to ease IP construction.""" # Compute the sets of MTF dimensions used in operations/tensors. # a {string: frozenset(string)}, mapping operation name to MTF dimension # names. self._operation_name_to_mtf_dimension_set = {} # ...
[ "def", "_preprocess_input", "(", "self", ")", ":", "self", ".", "_operation_name_to_mtf_dimension_set", "=", "{", "}", "self", ".", "_tensor_name_to_mtf_dimension_set", "=", "{", "}", "for", "operation_name", "in", "self", ".", "_graph", ".", "get_all_operation_name...
Computing useful input data structures to ease IP construction.
[ "Computing", "useful", "input", "data", "structures", "to", "ease", "IP", "construction", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout_optimizer.py#L123-L152
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/layout_optimizer.py
LayoutOptimizer._initialize_variables
def _initialize_variables(self): """Initializing the variables of the IP.""" # Initialize global variables. self._global_vars = {} # Indexed by (MTF dimension, mesh dimension) for mtf_dimension_name in ( self._layout_validator.splittable_mtf_dimension_names): for mesh_dimension_name in ( ...
python
def _initialize_variables(self): """Initializing the variables of the IP.""" # Initialize global variables. self._global_vars = {} # Indexed by (MTF dimension, mesh dimension) for mtf_dimension_name in ( self._layout_validator.splittable_mtf_dimension_names): for mesh_dimension_name in ( ...
[ "def", "_initialize_variables", "(", "self", ")", ":", "self", ".", "_global_vars", "=", "{", "}", "for", "mtf_dimension_name", "in", "(", "self", ".", "_layout_validator", ".", "splittable_mtf_dimension_names", ")", ":", "for", "mesh_dimension_name", "in", "(", ...
Initializing the variables of the IP.
[ "Initializing", "the", "variables", "of", "the", "IP", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout_optimizer.py#L154-L187
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/layout_optimizer.py
LayoutOptimizer._add_constraints
def _add_constraints(self): """Adding constraints to the IP.""" # Add operation constraints. for mesh_dimension_name in ( self._layout_validator.mesh_dimension_name_to_size): for mtf_dimension_set in self._operation_mtf_dimension_sets: self._model.Add( sum(self._global_vars...
python
def _add_constraints(self): """Adding constraints to the IP.""" # Add operation constraints. for mesh_dimension_name in ( self._layout_validator.mesh_dimension_name_to_size): for mtf_dimension_set in self._operation_mtf_dimension_sets: self._model.Add( sum(self._global_vars...
[ "def", "_add_constraints", "(", "self", ")", ":", "for", "mesh_dimension_name", "in", "(", "self", ".", "_layout_validator", ".", "mesh_dimension_name_to_size", ")", ":", "for", "mtf_dimension_set", "in", "self", ".", "_operation_mtf_dimension_sets", ":", "self", "....
Adding constraints to the IP.
[ "Adding", "constraints", "to", "the", "IP", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout_optimizer.py#L189-L262
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/layout_optimizer.py
LayoutOptimizer._get_memory_contents
def _get_memory_contents(self): """Runs the scheduler to determine memory contents at every point in time. Returns: a list of frozenset of strings, where the ith entry describes the tensors in memory when executing operation i (where schedule[i] is an index into GetAllOperationNames()). "...
python
def _get_memory_contents(self): """Runs the scheduler to determine memory contents at every point in time. Returns: a list of frozenset of strings, where the ith entry describes the tensors in memory when executing operation i (where schedule[i] is an index into GetAllOperationNames()). "...
[ "def", "_get_memory_contents", "(", "self", ")", ":", "if", "self", ".", "_memory_contents", "is", "not", "None", ":", "return", "self", ".", "_memory_contents", "schedule", "=", "scheduler", ".", "minimize_peak_memory", "(", "self", ".", "_graph", ",", "self"...
Runs the scheduler to determine memory contents at every point in time. Returns: a list of frozenset of strings, where the ith entry describes the tensors in memory when executing operation i (where schedule[i] is an index into GetAllOperationNames()).
[ "Runs", "the", "scheduler", "to", "determine", "memory", "contents", "at", "every", "point", "in", "time", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout_optimizer.py#L268-L283
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/layout_optimizer.py
LayoutOptimizer.solve
def solve(self, print_solution=False): """Solves the current integer program and returns the computed layout. Args: print_solution: An optional boolean indicating whether to print the full solution in human-readable format. Returns: The computed layout (as a string). Raises: ...
python
def solve(self, print_solution=False): """Solves the current integer program and returns the computed layout. Args: print_solution: An optional boolean indicating whether to print the full solution in human-readable format. Returns: The computed layout (as a string). Raises: ...
[ "def", "solve", "(", "self", ",", "print_solution", "=", "False", ")", ":", "self", ".", "_cp_solver", "=", "cp_model", ".", "CpSolver", "(", ")", "status", "=", "self", ".", "_cp_solver", ".", "Solve", "(", "self", ".", "_model", ")", "if", "status", ...
Solves the current integer program and returns the computed layout. Args: print_solution: An optional boolean indicating whether to print the full solution in human-readable format. Returns: The computed layout (as a string). Raises: SolverError: the internal solver could not fi...
[ "Solves", "the", "current", "integer", "program", "and", "returns", "the", "computed", "layout", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout_optimizer.py#L285-L326
train
tensorflow/mesh
mesh_tensorflow/auto_mtf/layout_optimizer.py
LayoutOptimizer.evaluate_layout
def evaluate_layout(self, layout): """The current objective value for the given layout. TODO(joshuawang): The current function does not check that the given layout is valid. Args: layout: a string, representing a layout to evaluate (e.g. "d_ff:m1;heads:m2"). Returns: A float...
python
def evaluate_layout(self, layout): """The current objective value for the given layout. TODO(joshuawang): The current function does not check that the given layout is valid. Args: layout: a string, representing a layout to evaluate (e.g. "d_ff:m1;heads:m2"). Returns: A float...
[ "def", "evaluate_layout", "(", "self", ",", "layout", ")", ":", "layout_dict", "=", "{", "}", "if", "layout", ":", "for", "pair", "in", "layout", ".", "split", "(", "\";\"", ")", ":", "mtf_dimension_name", ",", "mesh_dimension_name", "=", "pair", ".", "s...
The current objective value for the given layout. TODO(joshuawang): The current function does not check that the given layout is valid. Args: layout: a string, representing a layout to evaluate (e.g. "d_ff:m1;heads:m2"). Returns: A float, the objective value.
[ "The", "current", "objective", "value", "for", "the", "given", "layout", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout_optimizer.py#L328-L367
train
tensorflow/mesh
mesh_tensorflow/utils.py
BalancedVariablePlacer.device_function
def device_function(self, var): """Choose a device for the input variable. Args: var: an Variable. Returns: The device for placing the var. """ if var.type not in ('Variable', 'VariableV2', 'VarHandleOp'): tf.logging.debug('Place {} on last device: {}.'.format( var.name...
python
def device_function(self, var): """Choose a device for the input variable. Args: var: an Variable. Returns: The device for placing the var. """ if var.type not in ('Variable', 'VariableV2', 'VarHandleOp'): tf.logging.debug('Place {} on last device: {}.'.format( var.name...
[ "def", "device_function", "(", "self", ",", "var", ")", ":", "if", "var", ".", "type", "not", "in", "(", "'Variable'", ",", "'VariableV2'", ",", "'VarHandleOp'", ")", ":", "tf", ".", "logging", ".", "debug", "(", "'Place {} on last device: {}.'", ".", "for...
Choose a device for the input variable. Args: var: an Variable. Returns: The device for placing the var.
[ "Choose", "a", "device", "for", "the", "input", "variable", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/utils.py#L45-L70
train
tensorflow/mesh
mesh_tensorflow/beam_search.py
greedy_decode
def greedy_decode(logits_fn, initial_ids, temperature=0.0, initial_states=None, eos_id=EOS_ID, forced_ids=None, use_tpu=True): """Greedy decoding. Args: logits_fn: Interface to the model, to provide logi...
python
def greedy_decode(logits_fn, initial_ids, temperature=0.0, initial_states=None, eos_id=EOS_ID, forced_ids=None, use_tpu=True): """Greedy decoding. Args: logits_fn: Interface to the model, to provide logi...
[ "def", "greedy_decode", "(", "logits_fn", ",", "initial_ids", ",", "temperature", "=", "0.0", ",", "initial_states", "=", "None", ",", "eos_id", "=", "EOS_ID", ",", "forced_ids", "=", "None", ",", "use_tpu", "=", "True", ")", ":", "length_dim", "=", "initi...
Greedy decoding. Args: logits_fn: Interface to the model, to provide logits. Shoud take: step_num - mtf Scalar ids - mtf Tensor with shape [..., length] states - list of mtf.Tensor Should return: logits - [batch, vocab_size] new_states - list of m...
[ "Greedy", "decoding", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/beam_search.py#L577-L642
train
tensorflow/mesh
mesh_tensorflow/transformer/dataset.py
pack_and_batch
def pack_and_batch(dataset, batch_size, length, pack=True): """Create a tf.data.Dataset which emits training batches. The input dataset emits feature-dictionaries where each feature is a vector of integers ending in EOS=1 The tensors in the returned tf.data.Dataset have shape [batch_size, length]. Zeros in...
python
def pack_and_batch(dataset, batch_size, length, pack=True): """Create a tf.data.Dataset which emits training batches. The input dataset emits feature-dictionaries where each feature is a vector of integers ending in EOS=1 The tensors in the returned tf.data.Dataset have shape [batch_size, length]. Zeros in...
[ "def", "pack_and_batch", "(", "dataset", ",", "batch_size", ",", "length", ",", "pack", "=", "True", ")", ":", "if", "pack", ":", "dataset", "=", "pack_dataset", "(", "dataset", ",", "length", "=", "length", ")", "dataset", "=", "dataset", ".", "map", ...
Create a tf.data.Dataset which emits training batches. The input dataset emits feature-dictionaries where each feature is a vector of integers ending in EOS=1 The tensors in the returned tf.data.Dataset have shape [batch_size, length]. Zeros indicate padding. length indicates the length of the emitted exa...
[ "Create", "a", "tf", ".", "data", ".", "Dataset", "which", "emits", "training", "batches", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L98-L150
train
tensorflow/mesh
mesh_tensorflow/transformer/dataset.py
encode_dataset
def encode_dataset(dataset, vocabulary): """Encode from strings to token ids. Args: dataset: a tf.data.Dataset with string values. vocabulary: a mesh_tensorflow.transformer.Vocabulary Returns: a tf.data.Dataset with integer-vector values ending in EOS=1 """ def encode(features): return {k: vo...
python
def encode_dataset(dataset, vocabulary): """Encode from strings to token ids. Args: dataset: a tf.data.Dataset with string values. vocabulary: a mesh_tensorflow.transformer.Vocabulary Returns: a tf.data.Dataset with integer-vector values ending in EOS=1 """ def encode(features): return {k: vo...
[ "def", "encode_dataset", "(", "dataset", ",", "vocabulary", ")", ":", "def", "encode", "(", "features", ")", ":", "return", "{", "k", ":", "vocabulary", ".", "encode_tf", "(", "v", ")", "for", "k", ",", "v", "in", "features", ".", "items", "(", ")", ...
Encode from strings to token ids. Args: dataset: a tf.data.Dataset with string values. vocabulary: a mesh_tensorflow.transformer.Vocabulary Returns: a tf.data.Dataset with integer-vector values ending in EOS=1
[ "Encode", "from", "strings", "to", "token", "ids", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L153-L164
train
tensorflow/mesh
mesh_tensorflow/transformer/dataset.py
packed_parallel_tsv_dataset
def packed_parallel_tsv_dataset(filenames=gin.REQUIRED, dataset_split=gin.REQUIRED, batch_size=gin.REQUIRED, sequence_length=gin.REQUIRED, vocabulary=gin.REQUIRED, ...
python
def packed_parallel_tsv_dataset(filenames=gin.REQUIRED, dataset_split=gin.REQUIRED, batch_size=gin.REQUIRED, sequence_length=gin.REQUIRED, vocabulary=gin.REQUIRED, ...
[ "def", "packed_parallel_tsv_dataset", "(", "filenames", "=", "gin", ".", "REQUIRED", ",", "dataset_split", "=", "gin", ".", "REQUIRED", ",", "batch_size", "=", "gin", ".", "REQUIRED", ",", "sequence_length", "=", "gin", ".", "REQUIRED", ",", "vocabulary", "=",...
Reads parallel tab-separated text file. One example per line.
[ "Reads", "parallel", "tab", "-", "separated", "text", "file", ".", "One", "example", "per", "line", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L213-L250
train
tensorflow/mesh
mesh_tensorflow/transformer/dataset.py
supervised_to_dict
def supervised_to_dict(dataset, text2self): """Turns a supervised dataset into a dataset with a feature dictionary. if text2self, then the features dictionary contains a "targets" key. else, the features dictionary contains "inputs" and "targets" keys. Args: dataset: a tf.data.Dataset text2self: a boo...
python
def supervised_to_dict(dataset, text2self): """Turns a supervised dataset into a dataset with a feature dictionary. if text2self, then the features dictionary contains a "targets" key. else, the features dictionary contains "inputs" and "targets" keys. Args: dataset: a tf.data.Dataset text2self: a boo...
[ "def", "supervised_to_dict", "(", "dataset", ",", "text2self", ")", ":", "def", "my_fn", "(", "inputs", ",", "targets", ")", ":", "if", "text2self", ":", "return", "{", "\"targets\"", ":", "targets", "}", "else", ":", "return", "{", "\"inputs\"", ":", "i...
Turns a supervised dataset into a dataset with a feature dictionary. if text2self, then the features dictionary contains a "targets" key. else, the features dictionary contains "inputs" and "targets" keys. Args: dataset: a tf.data.Dataset text2self: a boolean Returns: a tf.data.Dataset
[ "Turns", "a", "supervised", "dataset", "into", "a", "dataset", "with", "a", "feature", "dictionary", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L291-L308
train
tensorflow/mesh
mesh_tensorflow/transformer/dataset.py
encode_all_features
def encode_all_features(dataset, vocabulary): """Encode all features. Args: dataset: a tf.data.Dataset vocabulary: a vocabulary.Vocabulary Returns: a tf.data.Dataset """ def my_fn(features): ret = {} for k, v in features.items(): v = vocabulary.encode_tf(v) v = tf.concat([tf.t...
python
def encode_all_features(dataset, vocabulary): """Encode all features. Args: dataset: a tf.data.Dataset vocabulary: a vocabulary.Vocabulary Returns: a tf.data.Dataset """ def my_fn(features): ret = {} for k, v in features.items(): v = vocabulary.encode_tf(v) v = tf.concat([tf.t...
[ "def", "encode_all_features", "(", "dataset", ",", "vocabulary", ")", ":", "def", "my_fn", "(", "features", ")", ":", "ret", "=", "{", "}", "for", "k", ",", "v", "in", "features", ".", "items", "(", ")", ":", "v", "=", "vocabulary", ".", "encode_tf",...
Encode all features. Args: dataset: a tf.data.Dataset vocabulary: a vocabulary.Vocabulary Returns: a tf.data.Dataset
[ "Encode", "all", "features", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L311-L327
train
tensorflow/mesh
mesh_tensorflow/transformer/dataset.py
pretokenized_tfrecord_dataset
def pretokenized_tfrecord_dataset(filenames, text2self, eos_included, repeat, batch_size, sequence_length): """Reads tensor2tensor-style data files....
python
def pretokenized_tfrecord_dataset(filenames, text2self, eos_included, repeat, batch_size, sequence_length): """Reads tensor2tensor-style data files....
[ "def", "pretokenized_tfrecord_dataset", "(", "filenames", ",", "text2self", ",", "eos_included", ",", "repeat", ",", "batch_size", ",", "sequence_length", ")", ":", "dataset", "=", "tf", ".", "data", ".", "TFRecordDataset", "(", "filenames", ",", "buffer_size", ...
Reads tensor2tensor-style data files. The dataset is defined by sets of TFRecord files of TFExample protos. There should be a "targets" feature (a 1d tensor of integers) If not text2self, there should also be an "inputs" feature. Other features get ignored. eos_included specifies whether the inputs and targ...
[ "Reads", "tensor2tensor", "-", "style", "data", "files", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/dataset.py#L330-L376
train