repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
tensorflow/tensor2tensor
tensor2tensor/utils/beam_search.py
top_k_with_unique
def top_k_with_unique(inputs, k): """Finds the values and indices of the k largests entries. Instead of doing sort like tf.nn.top_k, this function finds the max value k times. The running time is proportional to k, which is be faster when k is small. The current implementation supports only inputs of rank 2. ...
python
def top_k_with_unique(inputs, k): """Finds the values and indices of the k largests entries. Instead of doing sort like tf.nn.top_k, this function finds the max value k times. The running time is proportional to k, which is be faster when k is small. The current implementation supports only inputs of rank 2. ...
[ "def", "top_k_with_unique", "(", "inputs", ",", "k", ")", ":", "unique_inputs", "=", "_create_make_unique", "(", "tf", ".", "cast", "(", "inputs", ",", "tf", ".", "float32", ")", ")", "top_values", ",", "indices", "=", "_create_topk_unique", "(", "unique_inp...
Finds the values and indices of the k largests entries. Instead of doing sort like tf.nn.top_k, this function finds the max value k times. The running time is proportional to k, which is be faster when k is small. The current implementation supports only inputs of rank 2. In addition, iota is used to replace t...
[ "Finds", "the", "values", "and", "indices", "of", "the", "k", "largests", "entries", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L273-L295
train
tensorflow/tensor2tensor
tensor2tensor/utils/beam_search.py
compute_topk_scores_and_seq
def compute_topk_scores_and_seq(sequences, scores, scores_to_gather, flags, beam_size, batch_size, prefix="default", ...
python
def compute_topk_scores_and_seq(sequences, scores, scores_to_gather, flags, beam_size, batch_size, prefix="default", ...
[ "def", "compute_topk_scores_and_seq", "(", "sequences", ",", "scores", ",", "scores_to_gather", ",", "flags", ",", "beam_size", ",", "batch_size", ",", "prefix", "=", "\"default\"", ",", "states_to_gather", "=", "None", ",", "use_tpu", "=", "False", ",", "use_to...
Given sequences and scores, will gather the top k=beam size sequences. This function is used to grow alive, and finished. It takes sequences, scores, and flags, and returns the top k from sequences, scores_to_gather, and flags based on the values in scores. This method permits easy introspection using tfdbg. ...
[ "Given", "sequences", "and", "scores", "will", "gather", "the", "top", "k", "=", "beam", "size", "sequences", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L298-L393
train
tensorflow/tensor2tensor
tensor2tensor/utils/beam_search.py
beam_search
def beam_search(symbols_to_logits_fn, initial_ids, beam_size, decode_length, vocab_size, alpha, states=None, eos_id=EOS_ID, stop_early=True, use_tpu=False, use_...
python
def beam_search(symbols_to_logits_fn, initial_ids, beam_size, decode_length, vocab_size, alpha, states=None, eos_id=EOS_ID, stop_early=True, use_tpu=False, use_...
[ "def", "beam_search", "(", "symbols_to_logits_fn", ",", "initial_ids", ",", "beam_size", ",", "decode_length", ",", "vocab_size", ",", "alpha", ",", "states", "=", "None", ",", "eos_id", "=", "EOS_ID", ",", "stop_early", "=", "True", ",", "use_tpu", "=", "Fa...
Beam search with length penalties. Requires a function that can take the currently decoded symbols and return the logits for the next symbol. The implementation is inspired by https://arxiv.org/abs/1609.08144. When running, the beam search steps can be visualized by using tfdbg to watch the operations gener...
[ "Beam", "search", "with", "length", "penalties", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L396-L813
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/video_utils.py
video_augmentation
def video_augmentation(features, hue=False, saturate=False, contrast=False): """Augments video with optional hue, saturation and constrast. Args: features: dict, with keys "inputs", "targets". features["inputs"], 4-D Tensor, shape=(THWC) features["targets"], 4-D Tensor, shape=(THWC)...
python
def video_augmentation(features, hue=False, saturate=False, contrast=False): """Augments video with optional hue, saturation and constrast. Args: features: dict, with keys "inputs", "targets". features["inputs"], 4-D Tensor, shape=(THWC) features["targets"], 4-D Tensor, shape=(THWC)...
[ "def", "video_augmentation", "(", "features", ",", "hue", "=", "False", ",", "saturate", "=", "False", ",", "contrast", "=", "False", ")", ":", "inputs", ",", "targets", "=", "features", "[", "\"inputs\"", "]", ",", "features", "[", "\"targets\"", "]", "...
Augments video with optional hue, saturation and constrast. Args: features: dict, with keys "inputs", "targets". features["inputs"], 4-D Tensor, shape=(THWC) features["targets"], 4-D Tensor, shape=(THWC) hue: bool, apply hue_transform. saturate: bool, apply saturation transfor...
[ "Augments", "video", "with", "optional", "hue", "saturation", "and", "constrast", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L52-L78
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/video_utils.py
create_border
def create_border(video, color="blue", border_percent=2): """Creates a border around each frame to differentiate input and target. Args: video: 5-D NumPy array. color: string, "blue", "red" or "green". border_percent: Percentarge of the frame covered by the border. Returns: video: 5-D NumPy array...
python
def create_border(video, color="blue", border_percent=2): """Creates a border around each frame to differentiate input and target. Args: video: 5-D NumPy array. color: string, "blue", "red" or "green". border_percent: Percentarge of the frame covered by the border. Returns: video: 5-D NumPy array...
[ "def", "create_border", "(", "video", ",", "color", "=", "\"blue\"", ",", "border_percent", "=", "2", ")", ":", "# Do not create border if the video is not in RGB format", "if", "video", ".", "shape", "[", "-", "1", "]", "!=", "3", ":", "return", "video", "col...
Creates a border around each frame to differentiate input and target. Args: video: 5-D NumPy array. color: string, "blue", "red" or "green". border_percent: Percentarge of the frame covered by the border. Returns: video: 5-D NumPy array.
[ "Creates", "a", "border", "around", "each", "frame", "to", "differentiate", "input", "and", "target", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L81-L103
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/video_utils.py
convert_videos_to_summaries
def convert_videos_to_summaries(input_videos, output_videos, target_videos, tag, decode_hparams, display_ground_truth=False): """Converts input, output and target videos into video summaries. Args: input_videos: 5-D NumPy array, (NTHWC) conditioni...
python
def convert_videos_to_summaries(input_videos, output_videos, target_videos, tag, decode_hparams, display_ground_truth=False): """Converts input, output and target videos into video summaries. Args: input_videos: 5-D NumPy array, (NTHWC) conditioni...
[ "def", "convert_videos_to_summaries", "(", "input_videos", ",", "output_videos", ",", "target_videos", ",", "tag", ",", "decode_hparams", ",", "display_ground_truth", "=", "False", ")", ":", "fps", "=", "decode_hparams", ".", "frames_per_second", "border_percent", "="...
Converts input, output and target videos into video summaries. Args: input_videos: 5-D NumPy array, (NTHWC) conditioning frames. output_videos: 5-D NumPy array, (NTHWC) model predictions. target_videos: 5-D NumPy array, (NTHWC) target frames. tag: tf summary tag. decode_hparams: HParams. disp...
[ "Converts", "input", "output", "and", "target", "videos", "into", "video", "summaries", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L106-L162
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/video_utils.py
display_video_hooks
def display_video_hooks(hook_args): """Hooks to display videos at decode time.""" predictions = hook_args.predictions max_outputs = hook_args.decode_hparams.max_display_outputs max_decodes = hook_args.decode_hparams.max_display_decodes with tf.Graph().as_default(): _, best_decodes = video_metrics.compute...
python
def display_video_hooks(hook_args): """Hooks to display videos at decode time.""" predictions = hook_args.predictions max_outputs = hook_args.decode_hparams.max_display_outputs max_decodes = hook_args.decode_hparams.max_display_decodes with tf.Graph().as_default(): _, best_decodes = video_metrics.compute...
[ "def", "display_video_hooks", "(", "hook_args", ")", ":", "predictions", "=", "hook_args", ".", "predictions", "max_outputs", "=", "hook_args", ".", "decode_hparams", ".", "max_display_outputs", "max_decodes", "=", "hook_args", ".", "decode_hparams", ".", "max_display...
Hooks to display videos at decode time.
[ "Hooks", "to", "display", "videos", "at", "decode", "time", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L165-L206
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/video_utils.py
summarize_video_metrics
def summarize_video_metrics(hook_args): """Computes video metrics summaries using the decoder output.""" problem_name = hook_args.problem.name current_problem = hook_args.problem hparams = hook_args.hparams output_dirs = hook_args.output_dirs predictions = hook_args.predictions frame_shape = [ curre...
python
def summarize_video_metrics(hook_args): """Computes video metrics summaries using the decoder output.""" problem_name = hook_args.problem.name current_problem = hook_args.problem hparams = hook_args.hparams output_dirs = hook_args.output_dirs predictions = hook_args.predictions frame_shape = [ curre...
[ "def", "summarize_video_metrics", "(", "hook_args", ")", ":", "problem_name", "=", "hook_args", ".", "problem", ".", "name", "current_problem", "=", "hook_args", ".", "problem", "hparams", "=", "hook_args", ".", "hparams", "output_dirs", "=", "hook_args", ".", "...
Computes video metrics summaries using the decoder output.
[ "Computes", "video", "metrics", "summaries", "using", "the", "decoder", "output", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L209-L235
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/video_utils.py
debug_video_writer_factory
def debug_video_writer_factory(output_dir): """Creates a VideoWriter for debug videos.""" if FLAGS.disable_ffmpeg: return common_video.IndividualFrameWriter(output_dir) else: output_path = os.path.join(output_dir, "video.avi") return common_video.WholeVideoWriter( fps=10, output_path=output_pa...
python
def debug_video_writer_factory(output_dir): """Creates a VideoWriter for debug videos.""" if FLAGS.disable_ffmpeg: return common_video.IndividualFrameWriter(output_dir) else: output_path = os.path.join(output_dir, "video.avi") return common_video.WholeVideoWriter( fps=10, output_path=output_pa...
[ "def", "debug_video_writer_factory", "(", "output_dir", ")", ":", "if", "FLAGS", ".", "disable_ffmpeg", ":", "return", "common_video", ".", "IndividualFrameWriter", "(", "output_dir", ")", "else", ":", "output_path", "=", "os", ".", "path", ".", "join", "(", "...
Creates a VideoWriter for debug videos.
[ "Creates", "a", "VideoWriter", "for", "debug", "videos", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L238-L246
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/video_utils.py
VideoProblem.preprocess_example
def preprocess_example(self, example, mode, hparams): """Runtime preprocessing, e.g., resize example["frame"].""" if getattr(hparams, "preprocess_resize_frames", None) is not None: example["frame"] = tf.image.resize_images( example["frame"], hparams.preprocess_resize_frames, tf.image.R...
python
def preprocess_example(self, example, mode, hparams): """Runtime preprocessing, e.g., resize example["frame"].""" if getattr(hparams, "preprocess_resize_frames", None) is not None: example["frame"] = tf.image.resize_images( example["frame"], hparams.preprocess_resize_frames, tf.image.R...
[ "def", "preprocess_example", "(", "self", ",", "example", ",", "mode", ",", "hparams", ")", ":", "if", "getattr", "(", "hparams", ",", "\"preprocess_resize_frames\"", ",", "None", ")", "is", "not", "None", ":", "example", "[", "\"frame\"", "]", "=", "tf", ...
Runtime preprocessing, e.g., resize example["frame"].
[ "Runtime", "preprocessing", "e", ".", "g", ".", "resize", "example", "[", "frame", "]", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L346-L352
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/video_utils.py
VideoProblem.serving_input_fn
def serving_input_fn(self, hparams): """For serving/predict, assume that only video frames are provided.""" video_input_frames = tf.placeholder( dtype=tf.float32, shape=[ None, hparams.video_num_input_frames, self.frame_width, self.frame_height, self.num_channels ...
python
def serving_input_fn(self, hparams): """For serving/predict, assume that only video frames are provided.""" video_input_frames = tf.placeholder( dtype=tf.float32, shape=[ None, hparams.video_num_input_frames, self.frame_width, self.frame_height, self.num_channels ...
[ "def", "serving_input_fn", "(", "self", ",", "hparams", ")", ":", "video_input_frames", "=", "tf", ".", "placeholder", "(", "dtype", "=", "tf", ".", "float32", ",", "shape", "=", "[", "None", ",", "hparams", ".", "video_num_input_frames", ",", "self", ".",...
For serving/predict, assume that only video frames are provided.
[ "For", "serving", "/", "predict", "assume", "that", "only", "video", "frames", "are", "provided", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L397-L409
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/video_utils.py
VideoProblem.generate_encoded_samples
def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split): """Generate samples of the encoded frames with possible extra data. By default this function just encodes the numpy array returned as "frame" from `self.generate_samples` into a PNG image. Override this function to get other encoding...
python
def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split): """Generate samples of the encoded frames with possible extra data. By default this function just encodes the numpy array returned as "frame" from `self.generate_samples` into a PNG image. Override this function to get other encoding...
[ "def", "generate_encoded_samples", "(", "self", ",", "data_dir", ",", "tmp_dir", ",", "dataset_split", ")", ":", "writer", "=", "None", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", ":", "image_t", "=", "tf", ".", "placeholder", "(",...
Generate samples of the encoded frames with possible extra data. By default this function just encodes the numpy array returned as "frame" from `self.generate_samples` into a PNG image. Override this function to get other encodings on disk. Args: data_dir: final data directory. Typically only us...
[ "Generate", "samples", "of", "the", "encoded", "frames", "with", "possible", "extra", "data", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L573-L630
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/video_utils.py
VideoProblem.generate_data
def generate_data(self, data_dir, tmp_dir, task_id=-1): """The function generating the data.""" filepath_fns = { problem.DatasetSplit.TRAIN: self.training_filepaths, problem.DatasetSplit.EVAL: self.dev_filepaths, problem.DatasetSplit.TEST: self.test_filepaths, } # We set shuffle...
python
def generate_data(self, data_dir, tmp_dir, task_id=-1): """The function generating the data.""" filepath_fns = { problem.DatasetSplit.TRAIN: self.training_filepaths, problem.DatasetSplit.EVAL: self.dev_filepaths, problem.DatasetSplit.TEST: self.test_filepaths, } # We set shuffle...
[ "def", "generate_data", "(", "self", ",", "data_dir", ",", "tmp_dir", ",", "task_id", "=", "-", "1", ")", ":", "filepath_fns", "=", "{", "problem", ".", "DatasetSplit", ".", "TRAIN", ":", "self", ".", "training_filepaths", ",", "problem", ".", "DatasetSpli...
The function generating the data.
[ "The", "function", "generating", "the", "data", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L632-L659
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
add_scope
def add_scope(scope=None, scope_fn=None): """Return a decorator which add a TF name/variable scope to a function. Note that the function returned by the decorator accept an additional 'name' parameter, which can overwrite the name scope given when the function is created. Args: scope (str): name of the ...
python
def add_scope(scope=None, scope_fn=None): """Return a decorator which add a TF name/variable scope to a function. Note that the function returned by the decorator accept an additional 'name' parameter, which can overwrite the name scope given when the function is created. Args: scope (str): name of the ...
[ "def", "add_scope", "(", "scope", "=", "None", ",", "scope_fn", "=", "None", ")", ":", "def", "decorator", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":",...
Return a decorator which add a TF name/variable scope to a function. Note that the function returned by the decorator accept an additional 'name' parameter, which can overwrite the name scope given when the function is created. Args: scope (str): name of the scope. If None, the function name is used. ...
[ "Return", "a", "decorator", "which", "add", "a", "TF", "name", "/", "variable", "scope", "to", "a", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L40-L64
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
_add_variable_proxy_methods
def _add_variable_proxy_methods(var, proxy_tensor): """Proxy methods of underlying variable. This enables our custom getters to still work with, e.g., batch norm. Args: var: Variable to proxy proxy_tensor: Tensor that is identity of var """ proxy_tensor.read_value = lambda: tf.identity(proxy_tensor)...
python
def _add_variable_proxy_methods(var, proxy_tensor): """Proxy methods of underlying variable. This enables our custom getters to still work with, e.g., batch norm. Args: var: Variable to proxy proxy_tensor: Tensor that is identity of var """ proxy_tensor.read_value = lambda: tf.identity(proxy_tensor)...
[ "def", "_add_variable_proxy_methods", "(", "var", ",", "proxy_tensor", ")", ":", "proxy_tensor", ".", "read_value", "=", "lambda", ":", "tf", ".", "identity", "(", "proxy_tensor", ")", "proxy_tensor", ".", "assign_sub", "=", "var", ".", "assign_sub", "proxy_tens...
Proxy methods of underlying variable. This enables our custom getters to still work with, e.g., batch norm. Args: var: Variable to proxy proxy_tensor: Tensor that is identity of var
[ "Proxy", "methods", "of", "underlying", "variable", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L75-L87
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
_rowwise_unsorted_segment_sum
def _rowwise_unsorted_segment_sum(values, indices, n): """UnsortedSegmentSum on each row. Args: values: a `Tensor` with shape `[batch_size, k]`. indices: an integer `Tensor` with shape `[batch_size, k]`. n: an integer. Returns: A `Tensor` with the same type as `values` and shape `[batch_size, n]`...
python
def _rowwise_unsorted_segment_sum(values, indices, n): """UnsortedSegmentSum on each row. Args: values: a `Tensor` with shape `[batch_size, k]`. indices: an integer `Tensor` with shape `[batch_size, k]`. n: an integer. Returns: A `Tensor` with the same type as `values` and shape `[batch_size, n]`...
[ "def", "_rowwise_unsorted_segment_sum", "(", "values", ",", "indices", ",", "n", ")", ":", "batch", ",", "k", "=", "tf", ".", "unstack", "(", "tf", ".", "shape", "(", "indices", ")", ",", "num", "=", "2", ")", "indices_flat", "=", "tf", ".", "reshape...
UnsortedSegmentSum on each row. Args: values: a `Tensor` with shape `[batch_size, k]`. indices: an integer `Tensor` with shape `[batch_size, k]`. n: an integer. Returns: A `Tensor` with the same type as `values` and shape `[batch_size, n]`.
[ "UnsortedSegmentSum", "on", "each", "row", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L267-L281
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
_prob_in_top_k
def _prob_in_top_k( clean_values, noisy_values, noise_stddev, noisy_top_values, k): """Helper function to NoisyTopKGating. Computes the probability that value is in top k, given different random noise. This gives us a way of backpropagating from a loss that balances the number of times each expert is in t...
python
def _prob_in_top_k( clean_values, noisy_values, noise_stddev, noisy_top_values, k): """Helper function to NoisyTopKGating. Computes the probability that value is in top k, given different random noise. This gives us a way of backpropagating from a loss that balances the number of times each expert is in t...
[ "def", "_prob_in_top_k", "(", "clean_values", ",", "noisy_values", ",", "noise_stddev", ",", "noisy_top_values", ",", "k", ")", ":", "batch", "=", "tf", ".", "shape", "(", "clean_values", ")", "[", "0", "]", "m", "=", "tf", ".", "shape", "(", "noisy_top_...
Helper function to NoisyTopKGating. Computes the probability that value is in top k, given different random noise. This gives us a way of backpropagating from a loss that balances the number of times each expert is in the top k experts per example. In the case of no noise, pass in None for noise_stddev, and ...
[ "Helper", "function", "to", "NoisyTopKGating", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L303-L348
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
cv_squared
def cv_squared(x): """The squared coefficient of variation of a sample. Useful as a loss to encourage a positive distribution to be more uniform. Epsilons added for numerical stability. Returns 0 for an empty Tensor. Args: x: a `Tensor`. Returns: a `Scalar`. """ epsilon = 1e-10 float_size =...
python
def cv_squared(x): """The squared coefficient of variation of a sample. Useful as a loss to encourage a positive distribution to be more uniform. Epsilons added for numerical stability. Returns 0 for an empty Tensor. Args: x: a `Tensor`. Returns: a `Scalar`. """ epsilon = 1e-10 float_size =...
[ "def", "cv_squared", "(", "x", ")", ":", "epsilon", "=", "1e-10", "float_size", "=", "tf", ".", "to_float", "(", "tf", ".", "size", "(", "x", ")", ")", "+", "epsilon", "mean", "=", "tf", ".", "reduce_sum", "(", "x", ")", "/", "float_size", "varianc...
The squared coefficient of variation of a sample. Useful as a loss to encourage a positive distribution to be more uniform. Epsilons added for numerical stability. Returns 0 for an empty Tensor. Args: x: a `Tensor`. Returns: a `Scalar`.
[ "The", "squared", "coefficient", "of", "variation", "of", "a", "sample", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L351-L368
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
update_hparams_for_vq_gating
def update_hparams_for_vq_gating(hparams): """VQ Gating hparams.""" hparams.add_hparam("z_size", 4) hparams.add_hparam("noise_dev", 0.5) # Bottleneck kinds supported: dense, vae, dvq. hparams.add_hparam("bottleneck_kind", "dvq") hparams.add_hparam("num_blocks", 1) hparams.add_hparam("num_residuals", 1) ...
python
def update_hparams_for_vq_gating(hparams): """VQ Gating hparams.""" hparams.add_hparam("z_size", 4) hparams.add_hparam("noise_dev", 0.5) # Bottleneck kinds supported: dense, vae, dvq. hparams.add_hparam("bottleneck_kind", "dvq") hparams.add_hparam("num_blocks", 1) hparams.add_hparam("num_residuals", 1) ...
[ "def", "update_hparams_for_vq_gating", "(", "hparams", ")", ":", "hparams", ".", "add_hparam", "(", "\"z_size\"", ",", "4", ")", "hparams", ".", "add_hparam", "(", "\"noise_dev\"", ",", "0.5", ")", "# Bottleneck kinds supported: dense, vae, dvq.", "hparams", ".", "a...
VQ Gating hparams.
[ "VQ", "Gating", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L384-L402
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
_my_top_k
def _my_top_k(x, k): """GPU-compatible version of top-k that works for very small constant k. Calls argmax repeatedly. tf.nn.top_k is implemented for GPU, but the gradient, sparse_to_dense, seems not to be, so if we use tf.nn.top_k, then both the top_k and its gradient go on cpu. Once this is not an issue,...
python
def _my_top_k(x, k): """GPU-compatible version of top-k that works for very small constant k. Calls argmax repeatedly. tf.nn.top_k is implemented for GPU, but the gradient, sparse_to_dense, seems not to be, so if we use tf.nn.top_k, then both the top_k and its gradient go on cpu. Once this is not an issue,...
[ "def", "_my_top_k", "(", "x", ",", "k", ")", ":", "if", "k", ">", "10", ":", "return", "tf", ".", "nn", ".", "top_k", "(", "x", ",", "k", ")", "values", "=", "[", "]", "indices", "=", "[", "]", "depth", "=", "tf", ".", "shape", "(", "x", ...
GPU-compatible version of top-k that works for very small constant k. Calls argmax repeatedly. tf.nn.top_k is implemented for GPU, but the gradient, sparse_to_dense, seems not to be, so if we use tf.nn.top_k, then both the top_k and its gradient go on cpu. Once this is not an issue, this function becomes o...
[ "GPU", "-", "compatible", "version", "of", "top", "-", "k", "that", "works", "for", "very", "small", "constant", "k", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L405-L434
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
vq_gating
def vq_gating(x, num_experts, k, bneck, hparams=None, name="vq_gating"): """VQ gating. Args: x: input Tensor with shape [batch_size, input_size] num_experts: an integer k: an integer - number of experts per example bneck: a bottl...
python
def vq_gating(x, num_experts, k, bneck, hparams=None, name="vq_gating"): """VQ gating. Args: x: input Tensor with shape [batch_size, input_size] num_experts: an integer k: an integer - number of experts per example bneck: a bottl...
[ "def", "vq_gating", "(", "x", ",", "num_experts", ",", "k", ",", "bneck", ",", "hparams", "=", "None", ",", "name", "=", "\"vq_gating\"", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "reuse", "=", "tf", ".", "AUTO_REUSE", ")", ":"...
VQ gating. Args: x: input Tensor with shape [batch_size, input_size] num_experts: an integer k: an integer - number of experts per example bneck: a bottleneck object hparams: optional hparams name: an optional string Returns: gates: a Tensor with shape [batch_size, num_experts] loa...
[ "VQ", "gating", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L437-L511
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
noisy_top_k_gating
def noisy_top_k_gating(x, num_experts, train, k=2, initializer=tf.zeros_initializer(), noisy_gating=True, noise_epsilon=1e-2, name=None): """Noisy top-k gati...
python
def noisy_top_k_gating(x, num_experts, train, k=2, initializer=tf.zeros_initializer(), noisy_gating=True, noise_epsilon=1e-2, name=None): """Noisy top-k gati...
[ "def", "noisy_top_k_gating", "(", "x", ",", "num_experts", ",", "train", ",", "k", "=", "2", ",", "initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ",", "noisy_gating", "=", "True", ",", "noise_epsilon", "=", "1e-2", ",", "name", "=", "None",...
Noisy top-k gating. See paper: https://arxiv.org/abs/1701.06538. Args: x: input Tensor with shape [batch_size, input_size] num_experts: an integer train: a boolean - we only add noise at training time. k: an integer - number of experts per example initializer: an initializer noisy_gating: ...
[ "Noisy", "top", "-", "k", "gating", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L514-L579
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
map_ids
def map_ids(x, indices, map_fn): """Apply a function to each coordinate ids of a multidimensional tensor. This allows to process each sequence of a batch independently. This is similar to tf.map_fn but with tensor where the batch dim has been flatten. Warning: The indices ids have to be contiguous and ordered...
python
def map_ids(x, indices, map_fn): """Apply a function to each coordinate ids of a multidimensional tensor. This allows to process each sequence of a batch independently. This is similar to tf.map_fn but with tensor where the batch dim has been flatten. Warning: The indices ids have to be contiguous and ordered...
[ "def", "map_ids", "(", "x", ",", "indices", ",", "map_fn", ")", ":", "indices", "=", "tf", ".", "reshape", "(", "indices", ",", "[", "-", "1", "]", ")", "t_i", "=", "tf", ".", "constant", "(", "0", ")", "# batch_coordinates start at 0", "t_batch_size",...
Apply a function to each coordinate ids of a multidimensional tensor. This allows to process each sequence of a batch independently. This is similar to tf.map_fn but with tensor where the batch dim has been flatten. Warning: The indices ids have to be contiguous and ordered in memory as the output vector for ...
[ "Apply", "a", "function", "to", "each", "coordinate", "ids", "of", "a", "multidimensional", "tensor", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L665-L730
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
ffn_expert_fn
def ffn_expert_fn(input_size, hidden_sizes, output_size, hidden_activation=tf.nn.relu): """Returns a function that creates a feed-forward network. Use this function to create the expert_fn argument to distributed_moe. Args: input_size: an integer hid...
python
def ffn_expert_fn(input_size, hidden_sizes, output_size, hidden_activation=tf.nn.relu): """Returns a function that creates a feed-forward network. Use this function to create the expert_fn argument to distributed_moe. Args: input_size: an integer hid...
[ "def", "ffn_expert_fn", "(", "input_size", ",", "hidden_sizes", ",", "output_size", ",", "hidden_activation", "=", "tf", ".", "nn", ".", "relu", ")", ":", "def", "my_fn", "(", "x", ")", ":", "layer_sizes", "=", "[", "input_size", "]", "+", "hidden_sizes", ...
Returns a function that creates a feed-forward network. Use this function to create the expert_fn argument to distributed_moe. Args: input_size: an integer hidden_sizes: a list of integers output_size: an integer hidden_activation: a unary function. Returns: a unary function
[ "Returns", "a", "function", "that", "creates", "a", "feed", "-", "forward", "network", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L956-L983
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
flatten_all_but_last
def flatten_all_but_last(a): """Flatten all dimensions of a except the last.""" ret = tf.reshape(a, [-1, tf.shape(a)[-1]]) if not tf.executing_eagerly(): ret.set_shape([None] + a.get_shape().as_list()[-1:]) return ret
python
def flatten_all_but_last(a): """Flatten all dimensions of a except the last.""" ret = tf.reshape(a, [-1, tf.shape(a)[-1]]) if not tf.executing_eagerly(): ret.set_shape([None] + a.get_shape().as_list()[-1:]) return ret
[ "def", "flatten_all_but_last", "(", "a", ")", ":", "ret", "=", "tf", ".", "reshape", "(", "a", ",", "[", "-", "1", ",", "tf", ".", "shape", "(", "a", ")", "[", "-", "1", "]", "]", ")", "if", "not", "tf", ".", "executing_eagerly", "(", ")", ":...
Flatten all dimensions of a except the last.
[ "Flatten", "all", "dimensions", "of", "a", "except", "the", "last", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L986-L991
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
local_moe
def local_moe(x, train, expert_fn, num_experts, k=1, loss_coef=1e-2, hparams=None, pass_x=True, pass_gates=False, additional_dispatch_params=None, name=None): """Call a local mix...
python
def local_moe(x, train, expert_fn, num_experts, k=1, loss_coef=1e-2, hparams=None, pass_x=True, pass_gates=False, additional_dispatch_params=None, name=None): """Call a local mix...
[ "def", "local_moe", "(", "x", ",", "train", ",", "expert_fn", ",", "num_experts", ",", "k", "=", "1", ",", "loss_coef", "=", "1e-2", ",", "hparams", "=", "None", ",", "pass_x", "=", "True", ",", "pass_gates", "=", "False", ",", "additional_dispatch_param...
Call a local mixture of experts. Args: x: a tensors with shape [... , input_size] train: a boolean scalar. expert_fn: a function. num_experts: an integer - number of experts k: an integer - how many experts to use for each batch element loss_coef: a scalar - multiplier on load-balancing losse...
[ "Call", "a", "local", "mixture", "of", "experts", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L994-L1074
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
local_moe_tpu
def local_moe_tpu(inputs, hidden_size, output_size, num_experts, loss_coef=1e-3, overhead=1.0): """Local mixture of experts that works well on TPU. See https://arxiv.org/abs/1701.06538 There are num_experts expert networks...
python
def local_moe_tpu(inputs, hidden_size, output_size, num_experts, loss_coef=1e-3, overhead=1.0): """Local mixture of experts that works well on TPU. See https://arxiv.org/abs/1701.06538 There are num_experts expert networks...
[ "def", "local_moe_tpu", "(", "inputs", ",", "hidden_size", ",", "output_size", ",", "num_experts", ",", "loss_coef", "=", "1e-3", ",", "overhead", "=", "1.0", ")", ":", "batch", ",", "length", ",", "input_size", "=", "common_layers", ".", "shape_list", "(", ...
Local mixture of experts that works well on TPU. See https://arxiv.org/abs/1701.06538 There are num_experts expert networks, each containing a relu-activated hidden layer of size hidden_size, followed by an output projection. The number of parameters is thus: num_experts * (input_size * hidden_size + hid...
[ "Local", "mixture", "of", "experts", "that", "works", "well", "on", "TPU", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L1217-L1411
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
reduce_by_device
def reduce_by_device(parallelism, data, reduce_fn): """Reduces data per device. This can be useful, for example, if we want to all-reduce n tensors on k<n devices (like during eval when we have only one device). We call reduce_by_device() to first sum the tensors per device, then call our usual all-reduce o...
python
def reduce_by_device(parallelism, data, reduce_fn): """Reduces data per device. This can be useful, for example, if we want to all-reduce n tensors on k<n devices (like during eval when we have only one device). We call reduce_by_device() to first sum the tensors per device, then call our usual all-reduce o...
[ "def", "reduce_by_device", "(", "parallelism", ",", "data", ",", "reduce_fn", ")", ":", "unique_devices", "=", "[", "]", "device_to_data", "=", "{", "}", "for", "dev", ",", "datum", "in", "zip", "(", "parallelism", ".", "devices", ",", "data", ")", ":", ...
Reduces data per device. This can be useful, for example, if we want to all-reduce n tensors on k<n devices (like during eval when we have only one device). We call reduce_by_device() to first sum the tensors per device, then call our usual all-reduce operation to create one sum per device, followed by expa...
[ "Reduces", "data", "per", "device", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L1414-L1443
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
expand_by_device
def expand_by_device(original_parallelism, device_parallelism, data): """Opposite of reduce_by_device(). Args: original_parallelism: a expert_utils.Parallelism object. device_parallelism: a expert_utils.Parallelism object. data: a list of tensors with length device_parallelism.n Returns: a list ...
python
def expand_by_device(original_parallelism, device_parallelism, data): """Opposite of reduce_by_device(). Args: original_parallelism: a expert_utils.Parallelism object. device_parallelism: a expert_utils.Parallelism object. data: a list of tensors with length device_parallelism.n Returns: a list ...
[ "def", "expand_by_device", "(", "original_parallelism", ",", "device_parallelism", ",", "data", ")", ":", "device_to_datum", "=", "{", "device_parallelism", ".", "devices", "[", "i", "]", ":", "data", "[", "i", "]", "for", "i", "in", "range", "(", "device_pa...
Opposite of reduce_by_device(). Args: original_parallelism: a expert_utils.Parallelism object. device_parallelism: a expert_utils.Parallelism object. data: a list of tensors with length device_parallelism.n Returns: a list of Tensors with length original_parallelism.n
[ "Opposite", "of", "reduce_by_device", "()", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L1446-L1460
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
all_reduce_ring
def all_reduce_ring(x, parallelism, maybe_reduce=True, use_bfloat16=True): """Compute the sum of all Tensors and put the result everywhere. Assumes that the devices are connected in a ring. Args: x: a list of Tensors with length parallelism.n parallelism: a expert_utils.Parallelism object. maybe_red...
python
def all_reduce_ring(x, parallelism, maybe_reduce=True, use_bfloat16=True): """Compute the sum of all Tensors and put the result everywhere. Assumes that the devices are connected in a ring. Args: x: a list of Tensors with length parallelism.n parallelism: a expert_utils.Parallelism object. maybe_red...
[ "def", "all_reduce_ring", "(", "x", ",", "parallelism", ",", "maybe_reduce", "=", "True", ",", "use_bfloat16", "=", "True", ")", ":", "if", "parallelism", ".", "n", "==", "1", ":", "return", "x", "if", "maybe_reduce", ":", "original_parallelism", "=", "par...
Compute the sum of all Tensors and put the result everywhere. Assumes that the devices are connected in a ring. Args: x: a list of Tensors with length parallelism.n parallelism: a expert_utils.Parallelism object. maybe_reduce: a boolean - first reduce per device. use_bfloat16: a boolean - saves ba...
[ "Compute", "the", "sum", "of", "all", "Tensors", "and", "put", "the", "result", "everywhere", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L1463-L1537
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
Parallelism._maybe_repeat
def _maybe_repeat(self, x): """Utility function for processing arguments that are singletons or lists. Args: x: either a list of self.n elements, or not a list. Returns: a list of self.n elements. """ if isinstance(x, list): assert len(x) == self.n return x else: ...
python
def _maybe_repeat(self, x): """Utility function for processing arguments that are singletons or lists. Args: x: either a list of self.n elements, or not a list. Returns: a list of self.n elements. """ if isinstance(x, list): assert len(x) == self.n return x else: ...
[ "def", "_maybe_repeat", "(", "self", ",", "x", ")", ":", "if", "isinstance", "(", "x", ",", "list", ")", ":", "assert", "len", "(", "x", ")", "==", "self", ".", "n", "return", "x", "else", ":", "return", "[", "x", "]", "*", "self", ".", "n" ]
Utility function for processing arguments that are singletons or lists. Args: x: either a list of self.n elements, or not a list. Returns: a list of self.n elements.
[ "Utility", "function", "for", "processing", "arguments", "that", "are", "singletons", "or", "lists", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L251-L264
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
PadRemover.remove
def remove(self, x): """Remove padding from the given tensor. Args: x (tf.Tensor): of shape [dim_origin,...] Returns: a tensor of shape [dim_compressed,...] with dim_compressed <= dim_origin """ with tf.name_scope("pad_reduce/remove"): x_shape = x.get_shape().as_list() x = ...
python
def remove(self, x): """Remove padding from the given tensor. Args: x (tf.Tensor): of shape [dim_origin,...] Returns: a tensor of shape [dim_compressed,...] with dim_compressed <= dim_origin """ with tf.name_scope("pad_reduce/remove"): x_shape = x.get_shape().as_list() x = ...
[ "def", "remove", "(", "self", ",", "x", ")", ":", "with", "tf", ".", "name_scope", "(", "\"pad_reduce/remove\"", ")", ":", "x_shape", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "x", "=", "tf", ".", "gather_nd", "(", "x", ",", ...
Remove padding from the given tensor. Args: x (tf.Tensor): of shape [dim_origin,...] Returns: a tensor of shape [dim_compressed,...] with dim_compressed <= dim_origin
[ "Remove", "padding", "from", "the", "given", "tensor", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L624-L643
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
PadRemover.restore
def restore(self, x): """Add padding back to the given tensor. Args: x (tf.Tensor): of shape [dim_compressed,...] Returns: a tensor of shape [dim_origin,...] with dim_compressed >= dim_origin. The dim is restored from the original reference tensor """ with tf.name_scope("pad_redu...
python
def restore(self, x): """Add padding back to the given tensor. Args: x (tf.Tensor): of shape [dim_compressed,...] Returns: a tensor of shape [dim_origin,...] with dim_compressed >= dim_origin. The dim is restored from the original reference tensor """ with tf.name_scope("pad_redu...
[ "def", "restore", "(", "self", ",", "x", ")", ":", "with", "tf", ".", "name_scope", "(", "\"pad_reduce/restore\"", ")", ":", "x", "=", "tf", ".", "scatter_nd", "(", "indices", "=", "self", ".", "nonpad_ids", ",", "updates", "=", "x", ",", "shape", "=...
Add padding back to the given tensor. Args: x (tf.Tensor): of shape [dim_compressed,...] Returns: a tensor of shape [dim_origin,...] with dim_compressed >= dim_origin. The dim is restored from the original reference tensor
[ "Add", "padding", "back", "to", "the", "given", "tensor", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L645-L661
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
SparseDispatcher.dispatch
def dispatch(self, inp): """Create one input Tensor for each expert. The `Tensor` for a expert `i` contains the slices of `inp` corresponding to the batch elements `b` where `gates[b, i] > 0`. Args: inp: a `Tensor` of shape "[batch_size, <extra_input_dims>]` Returns: a list of `num_exp...
python
def dispatch(self, inp): """Create one input Tensor for each expert. The `Tensor` for a expert `i` contains the slices of `inp` corresponding to the batch elements `b` where `gates[b, i] > 0`. Args: inp: a `Tensor` of shape "[batch_size, <extra_input_dims>]` Returns: a list of `num_exp...
[ "def", "dispatch", "(", "self", ",", "inp", ")", ":", "inp", "=", "tf", ".", "gather", "(", "inp", ",", "self", ".", "_batch_index", ")", "return", "tf", ".", "split", "(", "inp", ",", "self", ".", "_part_sizes_tensor", ",", "0", ",", "num", "=", ...
Create one input Tensor for each expert. The `Tensor` for a expert `i` contains the slices of `inp` corresponding to the batch elements `b` where `gates[b, i] > 0`. Args: inp: a `Tensor` of shape "[batch_size, <extra_input_dims>]` Returns: a list of `num_experts` `Tensor`s with shapes ...
[ "Create", "one", "input", "Tensor", "for", "each", "expert", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L794-L807
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
SparseDispatcher.combine
def combine(self, expert_out, multiply_by_gates=True): """Sum together the expert output, weighted by the gates. The slice corresponding to a particular batch element `b` is computed as the sum over all experts `i` of the expert output, weighted by the corresponding gate values. If `multiply_by_gates`...
python
def combine(self, expert_out, multiply_by_gates=True): """Sum together the expert output, weighted by the gates. The slice corresponding to a particular batch element `b` is computed as the sum over all experts `i` of the expert output, weighted by the corresponding gate values. If `multiply_by_gates`...
[ "def", "combine", "(", "self", ",", "expert_out", ",", "multiply_by_gates", "=", "True", ")", ":", "# see comments on convert_gradient_to_tensor", "stitched", "=", "common_layers", ".", "convert_gradient_to_tensor", "(", "tf", ".", "concat", "(", "expert_out", ",", ...
Sum together the expert output, weighted by the gates. The slice corresponding to a particular batch element `b` is computed as the sum over all experts `i` of the expert output, weighted by the corresponding gate values. If `multiply_by_gates` is set to False, the gate values are ignored. Args: ...
[ "Sum", "together", "the", "expert", "output", "weighted", "by", "the", "gates", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L810-L833
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
SparseDispatcher.expert_to_gates
def expert_to_gates(self): """Gate values corresponding to the examples in the per-expert `Tensor`s. Returns: a list of `num_experts` one-dimensional `Tensor`s with type `tf.float32` and shapes `[expert_batch_size_i]` """ return tf.split( self._nonzero_gates, self._part_sizes_te...
python
def expert_to_gates(self): """Gate values corresponding to the examples in the per-expert `Tensor`s. Returns: a list of `num_experts` one-dimensional `Tensor`s with type `tf.float32` and shapes `[expert_batch_size_i]` """ return tf.split( self._nonzero_gates, self._part_sizes_te...
[ "def", "expert_to_gates", "(", "self", ")", ":", "return", "tf", ".", "split", "(", "self", ".", "_nonzero_gates", ",", "self", ".", "_part_sizes_tensor", ",", "0", ",", "num", "=", "self", ".", "_num_experts", ")" ]
Gate values corresponding to the examples in the per-expert `Tensor`s. Returns: a list of `num_experts` one-dimensional `Tensor`s with type `tf.float32` and shapes `[expert_batch_size_i]`
[ "Gate", "values", "corresponding", "to", "the", "examples", "in", "the", "per", "-", "expert", "Tensor", "s", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L835-L843
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
SparseDispatcher.expert_to_batch_indices
def expert_to_batch_indices(self): """Batch indices corresponding to the examples in the per-expert `Tensor`s. Returns: a list of `num_experts` one-dimensional `Tensor`s with type `tf.int64` and shapes `[expert_batch_size_i]` """ return tf.split( self._batch_index, self._part_si...
python
def expert_to_batch_indices(self): """Batch indices corresponding to the examples in the per-expert `Tensor`s. Returns: a list of `num_experts` one-dimensional `Tensor`s with type `tf.int64` and shapes `[expert_batch_size_i]` """ return tf.split( self._batch_index, self._part_si...
[ "def", "expert_to_batch_indices", "(", "self", ")", ":", "return", "tf", ".", "split", "(", "self", ".", "_batch_index", ",", "self", ".", "_part_sizes_tensor", ",", "0", ",", "num", "=", "self", ".", "_num_experts", ")" ]
Batch indices corresponding to the examples in the per-expert `Tensor`s. Returns: a list of `num_experts` one-dimensional `Tensor`s with type `tf.int64` and shapes `[expert_batch_size_i]`
[ "Batch", "indices", "corresponding", "to", "the", "examples", "in", "the", "per", "-", "expert", "Tensor", "s", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L845-L853
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
DistributedSparseDispatcher.dispatch
def dispatch(self, inp): """Create one input Tensor for each expert. Args: inp: a list of length num_datashards `Tensor`s with shapes `[batch_size[d], <extra_input_dims>]`. Returns: a list of `num_experts` `Tensor`s with shapes `[num_examples[i], <extra_input_dims>]`. """ ...
python
def dispatch(self, inp): """Create one input Tensor for each expert. Args: inp: a list of length num_datashards `Tensor`s with shapes `[batch_size[d], <extra_input_dims>]`. Returns: a list of `num_experts` `Tensor`s with shapes `[num_examples[i], <extra_input_dims>]`. """ ...
[ "def", "dispatch", "(", "self", ",", "inp", ")", ":", "dispatched", "=", "self", ".", "_dp", "(", "lambda", "a", ",", "b", ":", "a", ".", "dispatch", "(", "b", ")", ",", "self", ".", "_dispatchers", ",", "inp", ")", "ret", "=", "self", ".", "_e...
Create one input Tensor for each expert. Args: inp: a list of length num_datashards `Tensor`s with shapes `[batch_size[d], <extra_input_dims>]`. Returns: a list of `num_experts` `Tensor`s with shapes `[num_examples[i], <extra_input_dims>]`.
[ "Create", "one", "input", "Tensor", "for", "each", "expert", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L890-L905
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
DistributedSparseDispatcher.combine
def combine(self, expert_out, multiply_by_gates=True): """Sum together the expert output, multiplied by the corresponding gates. Args: expert_out: a list of `num_experts` `Tensor`s, each with shape `[expert_batch_size_i, <extra_output_dims>]`. multiply_by_gates: a boolean. Returns: ...
python
def combine(self, expert_out, multiply_by_gates=True): """Sum together the expert output, multiplied by the corresponding gates. Args: expert_out: a list of `num_experts` `Tensor`s, each with shape `[expert_batch_size_i, <extra_output_dims>]`. multiply_by_gates: a boolean. Returns: ...
[ "def", "combine", "(", "self", ",", "expert_out", ",", "multiply_by_gates", "=", "True", ")", ":", "expert_part_sizes", "=", "tf", ".", "unstack", "(", "tf", ".", "stack", "(", "[", "d", ".", "part_sizes", "for", "d", "in", "self", ".", "_dispatchers", ...
Sum together the expert output, multiplied by the corresponding gates. Args: expert_out: a list of `num_experts` `Tensor`s, each with shape `[expert_batch_size_i, <extra_output_dims>]`. multiply_by_gates: a boolean. Returns: a list of num_datashards `Tensor`s with shapes `[ba...
[ "Sum", "together", "the", "expert", "output", "multiplied", "by", "the", "corresponding", "gates", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L907-L930
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
DistributedSparseDispatcher.expert_to_gates
def expert_to_gates(self): """Gate values corresponding to the examples in the per-expert `Tensor`s. Returns: a list of `num_experts` one-dimensional `Tensor`s of type `tf.float32`. """ return self._ep( tf.concat, transpose_list_of_lists( self._dp(lambda d: d.expert_to...
python
def expert_to_gates(self): """Gate values corresponding to the examples in the per-expert `Tensor`s. Returns: a list of `num_experts` one-dimensional `Tensor`s of type `tf.float32`. """ return self._ep( tf.concat, transpose_list_of_lists( self._dp(lambda d: d.expert_to...
[ "def", "expert_to_gates", "(", "self", ")", ":", "return", "self", ".", "_ep", "(", "tf", ".", "concat", ",", "transpose_list_of_lists", "(", "self", ".", "_dp", "(", "lambda", "d", ":", "d", ".", "expert_to_gates", "(", ")", ",", "self", ".", "_dispat...
Gate values corresponding to the examples in the per-expert `Tensor`s. Returns: a list of `num_experts` one-dimensional `Tensor`s of type `tf.float32`.
[ "Gate", "values", "corresponding", "to", "the", "examples", "in", "the", "per", "-", "expert", "Tensor", "s", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L932-L941
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
TruncatingDispatcher.dispatch
def dispatch(self, inp): """Send the inputs to the experts. Args: inp: a `Tensor` of shape "[batch, length, depth]` Returns: a tensor with shape [batch, num_experts, expert_capacity, depth] """ inp = tf.reshape(inp, [self._batch * self._length, -1]) # [batch, num_experts, expert_cap...
python
def dispatch(self, inp): """Send the inputs to the experts. Args: inp: a `Tensor` of shape "[batch, length, depth]` Returns: a tensor with shape [batch, num_experts, expert_capacity, depth] """ inp = tf.reshape(inp, [self._batch * self._length, -1]) # [batch, num_experts, expert_cap...
[ "def", "dispatch", "(", "self", ",", "inp", ")", ":", "inp", "=", "tf", ".", "reshape", "(", "inp", ",", "[", "self", ".", "_batch", "*", "self", ".", "_length", ",", "-", "1", "]", ")", "# [batch, num_experts, expert_capacity, depth]", "ret", "=", "tf...
Send the inputs to the experts. Args: inp: a `Tensor` of shape "[batch, length, depth]` Returns: a tensor with shape [batch, num_experts, expert_capacity, depth]
[ "Send", "the", "inputs", "to", "the", "experts", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L1158-L1169
train
tensorflow/tensor2tensor
tensor2tensor/utils/expert_utils.py
TruncatingDispatcher.combine
def combine(self, x): """Return the output from the experts. When one example goes to multiple experts, the outputs are summed. Args: x: a Tensor with shape [batch, num_experts, expert_capacity, depth] Returns: a `Tensor` with shape `[batch, length, depth] """ depth = tf.shape(x)[...
python
def combine(self, x): """Return the output from the experts. When one example goes to multiple experts, the outputs are summed. Args: x: a Tensor with shape [batch, num_experts, expert_capacity, depth] Returns: a `Tensor` with shape `[batch, length, depth] """ depth = tf.shape(x)[...
[ "def", "combine", "(", "self", ",", "x", ")", ":", "depth", "=", "tf", ".", "shape", "(", "x", ")", "[", "-", "1", "]", "x", "*=", "tf", ".", "expand_dims", "(", "self", ".", "_nonpadding", ",", "-", "1", ")", "ret", "=", "tf", ".", "unsorted...
Return the output from the experts. When one example goes to multiple experts, the outputs are summed. Args: x: a Tensor with shape [batch, num_experts, expert_capacity, depth] Returns: a `Tensor` with shape `[batch, length, depth]
[ "Return", "the", "output", "from", "the", "experts", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L1172-L1188
train
tensorflow/tensor2tensor
tensor2tensor/rl/evaluator.py
make_env
def make_env(env_type, real_env, sim_env_kwargs): """Factory function for envs.""" return { "real": lambda: real_env.new_like( # pylint: disable=g-long-lambda batch_size=sim_env_kwargs["batch_size"], store_rollouts=False, ), "simulated": lambda: rl_utils.SimulatedBatchGymEnvWi...
python
def make_env(env_type, real_env, sim_env_kwargs): """Factory function for envs.""" return { "real": lambda: real_env.new_like( # pylint: disable=g-long-lambda batch_size=sim_env_kwargs["batch_size"], store_rollouts=False, ), "simulated": lambda: rl_utils.SimulatedBatchGymEnvWi...
[ "def", "make_env", "(", "env_type", ",", "real_env", ",", "sim_env_kwargs", ")", ":", "return", "{", "\"real\"", ":", "lambda", ":", "real_env", ".", "new_like", "(", "# pylint: disable=g-long-lambda", "batch_size", "=", "sim_env_kwargs", "[", "\"batch_size\"", "]...
Factory function for envs.
[ "Factory", "function", "for", "envs", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/evaluator.py#L240-L250
train
tensorflow/tensor2tensor
tensor2tensor/rl/evaluator.py
make_agent
def make_agent( agent_type, env, policy_hparams, policy_dir, sampling_temp, sim_env_kwargs_fn=None, frame_stack_size=None, rollout_agent_type=None, batch_size=None, inner_batch_size=None, env_type=None, **planner_kwargs ): """Factory function for Agents.""" if batch_size is None: batch_size = env.ba...
python
def make_agent( agent_type, env, policy_hparams, policy_dir, sampling_temp, sim_env_kwargs_fn=None, frame_stack_size=None, rollout_agent_type=None, batch_size=None, inner_batch_size=None, env_type=None, **planner_kwargs ): """Factory function for Agents.""" if batch_size is None: batch_size = env.ba...
[ "def", "make_agent", "(", "agent_type", ",", "env", ",", "policy_hparams", ",", "policy_dir", ",", "sampling_temp", ",", "sim_env_kwargs_fn", "=", "None", ",", "frame_stack_size", "=", "None", ",", "rollout_agent_type", "=", "None", ",", "batch_size", "=", "None...
Factory function for Agents.
[ "Factory", "function", "for", "Agents", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/evaluator.py#L253-L277
train
tensorflow/tensor2tensor
tensor2tensor/rl/evaluator.py
collect_frames_for_random_starts
def collect_frames_for_random_starts( storage_env, stacked_env, agent, frame_stack_size, random_starts_step_limit, log_every_steps=None ): """Collects frames from real env for random starts of simulated env.""" del frame_stack_size storage_env.start_new_epoch(0) tf.logging.info( "Collecting %d fra...
python
def collect_frames_for_random_starts( storage_env, stacked_env, agent, frame_stack_size, random_starts_step_limit, log_every_steps=None ): """Collects frames from real env for random starts of simulated env.""" del frame_stack_size storage_env.start_new_epoch(0) tf.logging.info( "Collecting %d fra...
[ "def", "collect_frames_for_random_starts", "(", "storage_env", ",", "stacked_env", ",", "agent", ",", "frame_stack_size", ",", "random_starts_step_limit", ",", "log_every_steps", "=", "None", ")", ":", "del", "frame_stack_size", "storage_env", ".", "start_new_epoch", "(...
Collects frames from real env for random starts of simulated env.
[ "Collects", "frames", "from", "real", "env", "for", "random", "starts", "of", "simulated", "env", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/evaluator.py#L280-L297
train
tensorflow/tensor2tensor
tensor2tensor/rl/evaluator.py
make_agent_from_hparams
def make_agent_from_hparams( agent_type, base_env, stacked_env, loop_hparams, policy_hparams, planner_hparams, model_dir, policy_dir, sampling_temp, video_writers=() ): """Creates an Agent from hparams.""" def sim_env_kwargs_fn(): return rl.make_simulated_env_kwargs( base_env, loop_hparams, batc...
python
def make_agent_from_hparams( agent_type, base_env, stacked_env, loop_hparams, policy_hparams, planner_hparams, model_dir, policy_dir, sampling_temp, video_writers=() ): """Creates an Agent from hparams.""" def sim_env_kwargs_fn(): return rl.make_simulated_env_kwargs( base_env, loop_hparams, batc...
[ "def", "make_agent_from_hparams", "(", "agent_type", ",", "base_env", ",", "stacked_env", ",", "loop_hparams", ",", "policy_hparams", ",", "planner_hparams", ",", "model_dir", ",", "policy_dir", ",", "sampling_temp", ",", "video_writers", "=", "(", ")", ")", ":", ...
Creates an Agent from hparams.
[ "Creates", "an", "Agent", "from", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/evaluator.py#L300-L321
train
tensorflow/tensor2tensor
tensor2tensor/rl/evaluator.py
make_eval_fn_with_agent
def make_eval_fn_with_agent( agent_type, eval_mode, planner_hparams, model_dir, log_every_steps=None, video_writers=(), random_starts_step_limit=None ): """Returns an out-of-graph eval_fn using the Agent API.""" def eval_fn(env, loop_hparams, policy_hparams, policy_dir, sampling_temp): """Eval function....
python
def make_eval_fn_with_agent( agent_type, eval_mode, planner_hparams, model_dir, log_every_steps=None, video_writers=(), random_starts_step_limit=None ): """Returns an out-of-graph eval_fn using the Agent API.""" def eval_fn(env, loop_hparams, policy_hparams, policy_dir, sampling_temp): """Eval function....
[ "def", "make_eval_fn_with_agent", "(", "agent_type", ",", "eval_mode", ",", "planner_hparams", ",", "model_dir", ",", "log_every_steps", "=", "None", ",", "video_writers", "=", "(", ")", ",", "random_starts_step_limit", "=", "None", ")", ":", "def", "eval_fn", "...
Returns an out-of-graph eval_fn using the Agent API.
[ "Returns", "an", "out", "-", "of", "-", "graph", "eval_fn", "using", "the", "Agent", "API", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/evaluator.py#L324-L372
train
tensorflow/tensor2tensor
tensor2tensor/rl/evaluator.py
evaluate_world_model
def evaluate_world_model( agent_type, loop_hparams, planner_hparams, model_dir, policy_dir, random_starts_step_limit, debug_video_path, log_every_steps ): """Evaluates the world model.""" if debug_video_path: debug_video_path = os.path.join(debug_video_path, "0.avi") storage_env = rl_utils.setup_env(...
python
def evaluate_world_model( agent_type, loop_hparams, planner_hparams, model_dir, policy_dir, random_starts_step_limit, debug_video_path, log_every_steps ): """Evaluates the world model.""" if debug_video_path: debug_video_path = os.path.join(debug_video_path, "0.avi") storage_env = rl_utils.setup_env(...
[ "def", "evaluate_world_model", "(", "agent_type", ",", "loop_hparams", ",", "planner_hparams", ",", "model_dir", ",", "policy_dir", ",", "random_starts_step_limit", ",", "debug_video_path", ",", "log_every_steps", ")", ":", "if", "debug_video_path", ":", "debug_video_pa...
Evaluates the world model.
[ "Evaluates", "the", "world", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/evaluator.py#L375-L400
train
tensorflow/tensor2tensor
tensor2tensor/rl/evaluator.py
evaluate
def evaluate( loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir, agent_type, eval_mode, eval_with_learner, log_every_steps, debug_video_path, num_debug_videos=1, random_starts_step_limit=None, report_fn=None, report_metric=None ): """Evaluate.""" if eval_with_learner: assert...
python
def evaluate( loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir, agent_type, eval_mode, eval_with_learner, log_every_steps, debug_video_path, num_debug_videos=1, random_starts_step_limit=None, report_fn=None, report_metric=None ): """Evaluate.""" if eval_with_learner: assert...
[ "def", "evaluate", "(", "loop_hparams", ",", "planner_hparams", ",", "policy_dir", ",", "model_dir", ",", "eval_metrics_dir", ",", "agent_type", ",", "eval_mode", ",", "eval_with_learner", ",", "log_every_steps", ",", "debug_video_path", ",", "num_debug_videos", "=", ...
Evaluate.
[ "Evaluate", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/evaluator.py#L403-L461
train
tensorflow/tensor2tensor
tensor2tensor/rl/evaluator.py
get_game_for_worker
def get_game_for_worker(map_name, directory_id): """Get game for the given worker (directory) id.""" if map_name == "v100unfriendly": games = ["chopper_command", "boxing", "asterix", "seaquest"] worker_per_game = 5 elif map_name == "human_nice": games = gym_env.ATARI_GAMES_WITH_HUMAN_SCORE_NICE wo...
python
def get_game_for_worker(map_name, directory_id): """Get game for the given worker (directory) id.""" if map_name == "v100unfriendly": games = ["chopper_command", "boxing", "asterix", "seaquest"] worker_per_game = 5 elif map_name == "human_nice": games = gym_env.ATARI_GAMES_WITH_HUMAN_SCORE_NICE wo...
[ "def", "get_game_for_worker", "(", "map_name", ",", "directory_id", ")", ":", "if", "map_name", "==", "\"v100unfriendly\"", ":", "games", "=", "[", "\"chopper_command\"", ",", "\"boxing\"", ",", "\"asterix\"", ",", "\"seaquest\"", "]", "worker_per_game", "=", "5",...
Get game for the given worker (directory) id.
[ "Get", "game", "for", "the", "given", "worker", "(", "directory", ")", "id", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/evaluator.py#L464-L477
train
tensorflow/tensor2tensor
tensor2tensor/envs/tic_tac_toe_env.py
get_open_spaces
def get_open_spaces(board): """Given a representation of the board, returns a list of open spaces.""" open_spaces = [] for i in range(3): for j in range(3): if board[i][j] == 0: open_spaces.append(encode_pos(i, j)) return open_spaces
python
def get_open_spaces(board): """Given a representation of the board, returns a list of open spaces.""" open_spaces = [] for i in range(3): for j in range(3): if board[i][j] == 0: open_spaces.append(encode_pos(i, j)) return open_spaces
[ "def", "get_open_spaces", "(", "board", ")", ":", "open_spaces", "=", "[", "]", "for", "i", "in", "range", "(", "3", ")", ":", "for", "j", "in", "range", "(", "3", ")", ":", "if", "board", "[", "i", "]", "[", "j", "]", "==", "0", ":", "open_s...
Given a representation of the board, returns a list of open spaces.
[ "Given", "a", "representation", "of", "the", "board", "returns", "a", "list", "of", "open", "spaces", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/tic_tac_toe_env.py#L46-L53
train
tensorflow/tensor2tensor
tensor2tensor/envs/tic_tac_toe_env.py
get_reward_and_done
def get_reward_and_done(board): """Given a representation of the board, returns reward and done.""" # Returns (reward, done) where: # reward: -1 means lost, +1 means win, 0 means draw or continuing. # done: True if the game is over, i.e. someone won or it is a draw. # Sum all rows ... all_sums = [np.sum(bo...
python
def get_reward_and_done(board): """Given a representation of the board, returns reward and done.""" # Returns (reward, done) where: # reward: -1 means lost, +1 means win, 0 means draw or continuing. # done: True if the game is over, i.e. someone won or it is a draw. # Sum all rows ... all_sums = [np.sum(bo...
[ "def", "get_reward_and_done", "(", "board", ")", ":", "# Returns (reward, done) where:", "# reward: -1 means lost, +1 means win, 0 means draw or continuing.", "# done: True if the game is over, i.e. someone won or it is a draw.", "# Sum all rows ...", "all_sums", "=", "[", "np", ".", "...
Given a representation of the board, returns reward and done.
[ "Given", "a", "representation", "of", "the", "board", "returns", "reward", "and", "done", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/tic_tac_toe_env.py#L56-L80
train
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
decode_hparams
def decode_hparams(overrides=""): """Hyperparameters for decoding.""" hp = hparam.HParams( save_images=False, log_results=True, extra_length=100, min_length_ratio=0.0, batch_size=0, beam_size=4, alpha=0.6, eos_penalty=0.0, block_size=0, guess_and_check_top...
python
def decode_hparams(overrides=""): """Hyperparameters for decoding.""" hp = hparam.HParams( save_images=False, log_results=True, extra_length=100, min_length_ratio=0.0, batch_size=0, beam_size=4, alpha=0.6, eos_penalty=0.0, block_size=0, guess_and_check_top...
[ "def", "decode_hparams", "(", "overrides", "=", "\"\"", ")", ":", "hp", "=", "hparam", ".", "HParams", "(", "save_images", "=", "False", ",", "log_results", "=", "True", ",", "extra_length", "=", "100", ",", "min_length_ratio", "=", "0.0", ",", "batch_size...
Hyperparameters for decoding.
[ "Hyperparameters", "for", "decoding", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L47-L101
train
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
log_decode_results
def log_decode_results(inputs, outputs, problem_name, prediction_idx, inputs_vocab, targets_vocab, targets=None, save_images=False, outp...
python
def log_decode_results(inputs, outputs, problem_name, prediction_idx, inputs_vocab, targets_vocab, targets=None, save_images=False, outp...
[ "def", "log_decode_results", "(", "inputs", ",", "outputs", ",", "problem_name", ",", "prediction_idx", ",", "inputs_vocab", ",", "targets_vocab", ",", "targets", "=", "None", ",", "save_images", "=", "False", ",", "output_dir", "=", "None", ",", "identity_outpu...
Log inference results.
[ "Log", "inference", "results", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L104-L170
train
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
decode_from_dataset
def decode_from_dataset(estimator, problem_name, hparams, decode_hp, decode_to_file=None, dataset_split=None, checkpoint_path=None): """Perform decoding from dataset.""" tf...
python
def decode_from_dataset(estimator, problem_name, hparams, decode_hp, decode_to_file=None, dataset_split=None, checkpoint_path=None): """Perform decoding from dataset.""" tf...
[ "def", "decode_from_dataset", "(", "estimator", ",", "problem_name", ",", "hparams", ",", "decode_hp", ",", "decode_to_file", "=", "None", ",", "dataset_split", "=", "None", ",", "checkpoint_path", "=", "None", ")", ":", "tf", ".", "logging", ".", "info", "(...
Perform decoding from dataset.
[ "Perform", "decoding", "from", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L173-L242
train
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
decode_once
def decode_once(estimator, problem_name, hparams, infer_input_fn, decode_hp, decode_to_file, output_dir, log_results=True, checkpoint_path=None): """Decodes once. Args: estimator: tf....
python
def decode_once(estimator, problem_name, hparams, infer_input_fn, decode_hp, decode_to_file, output_dir, log_results=True, checkpoint_path=None): """Decodes once. Args: estimator: tf....
[ "def", "decode_once", "(", "estimator", ",", "problem_name", ",", "hparams", ",", "infer_input_fn", ",", "decode_hp", ",", "decode_to_file", ",", "output_dir", ",", "log_results", "=", "True", ",", "checkpoint_path", "=", "None", ")", ":", "# Get the predictions a...
Decodes once. Args: estimator: tf.estimator.Estimator instance. Used to generate encoded predictions. problem_name: str. Name of problem. hparams: HParams instance. HParams for model training. infer_input_fn: zero-arg function. Input function for estimator. decode_hp: HParams instance. See ...
[ "Decodes", "once", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L245-L391
train
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
decode_from_file
def decode_from_file(estimator, filename, hparams, decode_hp, decode_to_file=None, checkpoint_path=None): """Compute predictions on entries in filename and write them out.""" if not decode_hp.batch_size: dec...
python
def decode_from_file(estimator, filename, hparams, decode_hp, decode_to_file=None, checkpoint_path=None): """Compute predictions on entries in filename and write them out.""" if not decode_hp.batch_size: dec...
[ "def", "decode_from_file", "(", "estimator", ",", "filename", ",", "hparams", ",", "decode_hp", ",", "decode_to_file", "=", "None", ",", "checkpoint_path", "=", "None", ")", ":", "if", "not", "decode_hp", ".", "batch_size", ":", "decode_hp", ".", "batch_size",...
Compute predictions on entries in filename and write them out.
[ "Compute", "predictions", "on", "entries", "in", "filename", "and", "write", "them", "out", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L394-L559
train
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
_decode_filename
def _decode_filename(base_filename, problem_name, decode_hp): """Generates decode filename. Args: base_filename: A string, base of the decode filename. problem_name: A string, name of the problem. decode_hp: HParams for decoding. Returns: A string, produced decode filename. """ if decode_hp....
python
def _decode_filename(base_filename, problem_name, decode_hp): """Generates decode filename. Args: base_filename: A string, base of the decode filename. problem_name: A string, name of the problem. decode_hp: HParams for decoding. Returns: A string, produced decode filename. """ if decode_hp....
[ "def", "_decode_filename", "(", "base_filename", ",", "problem_name", ",", "decode_hp", ")", ":", "if", "decode_hp", ".", "shards", ">", "1", ":", "base_filename", "=", "_add_shard_to_filename", "(", "base_filename", ",", "decode_hp", ")", "if", "(", "\"beam{bea...
Generates decode filename. Args: base_filename: A string, base of the decode filename. problem_name: A string, name of the problem. decode_hp: HParams for decoding. Returns: A string, produced decode filename.
[ "Generates", "decode", "filename", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L573-L598
train
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
make_input_fn_from_generator
def make_input_fn_from_generator(gen): """Use py_func to yield elements from the given generator.""" first_ex = six.next(gen) flattened = tf.contrib.framework.nest.flatten(first_ex) types = [t.dtype for t in flattened] shapes = [[None] * len(t.shape) for t in flattened] first_ex_list = [first_ex] def py_...
python
def make_input_fn_from_generator(gen): """Use py_func to yield elements from the given generator.""" first_ex = six.next(gen) flattened = tf.contrib.framework.nest.flatten(first_ex) types = [t.dtype for t in flattened] shapes = [[None] * len(t.shape) for t in flattened] first_ex_list = [first_ex] def py_...
[ "def", "make_input_fn_from_generator", "(", "gen", ")", ":", "first_ex", "=", "six", ".", "next", "(", "gen", ")", "flattened", "=", "tf", ".", "contrib", ".", "framework", ".", "nest", ".", "flatten", "(", "first_ex", ")", "types", "=", "[", "t", ".",...
Use py_func to yield elements from the given generator.
[ "Use", "py_func", "to", "yield", "elements", "from", "the", "given", "generator", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L601-L622
train
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
decode_interactively
def decode_interactively(estimator, hparams, decode_hp, checkpoint_path=None): """Interactive decoding.""" is_image = "image" in hparams.problem.name is_text2class = isinstance(hparams.problem, text_problems.Text2ClassProblem) skip_eos_postprocess = ( is_image or is_text2clas...
python
def decode_interactively(estimator, hparams, decode_hp, checkpoint_path=None): """Interactive decoding.""" is_image = "image" in hparams.problem.name is_text2class = isinstance(hparams.problem, text_problems.Text2ClassProblem) skip_eos_postprocess = ( is_image or is_text2clas...
[ "def", "decode_interactively", "(", "estimator", ",", "hparams", ",", "decode_hp", ",", "checkpoint_path", "=", "None", ")", ":", "is_image", "=", "\"image\"", "in", "hparams", ".", "problem", ".", "name", "is_text2class", "=", "isinstance", "(", "hparams", "....
Interactive decoding.
[ "Interactive", "decoding", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L625-L666
train
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
_decode_batch_input_fn
def _decode_batch_input_fn(num_decode_batches, sorted_inputs, vocabulary, batch_size, max_input_size, task_id=-1, has_input=True): """Generator to produce batches of inputs.""" tf.logging.info(" batch %d" % num_decode_batches) for b in range(num_decode_batches...
python
def _decode_batch_input_fn(num_decode_batches, sorted_inputs, vocabulary, batch_size, max_input_size, task_id=-1, has_input=True): """Generator to produce batches of inputs.""" tf.logging.info(" batch %d" % num_decode_batches) for b in range(num_decode_batches...
[ "def", "_decode_batch_input_fn", "(", "num_decode_batches", ",", "sorted_inputs", ",", "vocabulary", ",", "batch_size", ",", "max_input_size", ",", "task_id", "=", "-", "1", ",", "has_input", "=", "True", ")", ":", "tf", ".", "logging", ".", "info", "(", "\"...
Generator to produce batches of inputs.
[ "Generator", "to", "produce", "batches", "of", "inputs", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L669-L697
train
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
_interactive_input_fn
def _interactive_input_fn(hparams, decode_hp): """Generator that reads from the terminal and yields "interactive inputs". Due to temporary limitations in tf.learn, if we don't want to reload the whole graph, then we are stuck encoding all of the input as one fixed-size numpy array. We yield int32 arrays wit...
python
def _interactive_input_fn(hparams, decode_hp): """Generator that reads from the terminal and yields "interactive inputs". Due to temporary limitations in tf.learn, if we don't want to reload the whole graph, then we are stuck encoding all of the input as one fixed-size numpy array. We yield int32 arrays wit...
[ "def", "_interactive_input_fn", "(", "hparams", ",", "decode_hp", ")", ":", "num_samples", "=", "decode_hp", ".", "num_samples", "if", "decode_hp", ".", "num_samples", ">", "0", "else", "1", "decode_length", "=", "decode_hp", ".", "extra_length", "input_type", "...
Generator that reads from the terminal and yields "interactive inputs". Due to temporary limitations in tf.learn, if we don't want to reload the whole graph, then we are stuck encoding all of the input as one fixed-size numpy array. We yield int32 arrays with shape [const_array_size]. The format is: [num_s...
[ "Generator", "that", "reads", "from", "the", "terminal", "and", "yields", "interactive", "inputs", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L700-L779
train
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
save_video
def save_video(video, save_path_template): """Save frames of the videos into files.""" try: from PIL import Image # pylint: disable=g-import-not-at-top except ImportError as e: tf.logging.warning( "Showing and saving an image requires PIL library to be " "installed: %s", e) raise NotI...
python
def save_video(video, save_path_template): """Save frames of the videos into files.""" try: from PIL import Image # pylint: disable=g-import-not-at-top except ImportError as e: tf.logging.warning( "Showing and saving an image requires PIL library to be " "installed: %s", e) raise NotI...
[ "def", "save_video", "(", "video", ",", "save_path_template", ")", ":", "try", ":", "from", "PIL", "import", "Image", "# pylint: disable=g-import-not-at-top", "except", "ImportError", "as", "e", ":", "tf", ".", "logging", ".", "warning", "(", "\"Showing and saving...
Save frames of the videos into files.
[ "Save", "frames", "of", "the", "videos", "into", "files", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L782-L795
train
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
show_and_save_image
def show_and_save_image(img, save_path): """Shows an image using matplotlib and saves it.""" try: import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top except ImportError as e: tf.logging.warning( "Showing and saving an image requires matplotlib to be " "installed: %s", e)...
python
def show_and_save_image(img, save_path): """Shows an image using matplotlib and saves it.""" try: import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top except ImportError as e: tf.logging.warning( "Showing and saving an image requires matplotlib to be " "installed: %s", e)...
[ "def", "show_and_save_image", "(", "img", ",", "save_path", ")", ":", "try", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "# pylint: disable=g-import-not-at-top", "except", "ImportError", "as", "e", ":", "tf", ".", "logging", ".", "warning", "(", "...
Shows an image using matplotlib and saves it.
[ "Shows", "an", "image", "using", "matplotlib", "and", "saves", "it", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L798-L809
train
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
_get_language_modeling_inputs
def _get_language_modeling_inputs(filename, delimiter="\n", repeat=1, append_space_to_final_punctionation=True): """Read a file of partial texts to continue. The purpose of append_space_to_final_punctionation is t...
python
def _get_language_modeling_inputs(filename, delimiter="\n", repeat=1, append_space_to_final_punctionation=True): """Read a file of partial texts to continue. The purpose of append_space_to_final_punctionation is t...
[ "def", "_get_language_modeling_inputs", "(", "filename", ",", "delimiter", "=", "\"\\n\"", ",", "repeat", "=", "1", ",", "append_space_to_final_punctionation", "=", "True", ")", ":", "with", "tf", ".", "gfile", ".", "Open", "(", "filename", ")", "as", "f", "...
Read a file of partial texts to continue. The purpose of append_space_to_final_punctionation is that SubwordTokenizer groups punctuation and the ensuing space in the same token. Adding a space causes the token to be completed. Args: filename: a string delimiter: a string repeat: an integer - we r...
[ "Read", "a", "file", "of", "partial", "texts", "to", "continue", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L812-L840
train
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
_get_sorted_inputs
def _get_sorted_inputs(filename, delimiter="\n"): """Returning inputs sorted according to decreasing length. This causes inputs of similar lengths to be processed in the same batch, facilitating early stopping for short sequences. Longer sequences are sorted first so that if you're going to get OOMs, you'll...
python
def _get_sorted_inputs(filename, delimiter="\n"): """Returning inputs sorted according to decreasing length. This causes inputs of similar lengths to be processed in the same batch, facilitating early stopping for short sequences. Longer sequences are sorted first so that if you're going to get OOMs, you'll...
[ "def", "_get_sorted_inputs", "(", "filename", ",", "delimiter", "=", "\"\\n\"", ")", ":", "tf", ".", "logging", ".", "info", "(", "\"Getting sorted inputs\"", ")", "with", "tf", ".", "gfile", ".", "Open", "(", "filename", ")", "as", "f", ":", "text", "="...
Returning inputs sorted according to decreasing length. This causes inputs of similar lengths to be processed in the same batch, facilitating early stopping for short sequences. Longer sequences are sorted first so that if you're going to get OOMs, you'll see it in the first batch. Args: filename: path...
[ "Returning", "inputs", "sorted", "according", "to", "decreasing", "length", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L843-L876
train
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
_save_until_eos
def _save_until_eos(ids, skip=False): """Strips everything after the first <EOS> token, which is normally 1.""" ids = ids.flatten() if skip: return ids try: index = list(ids).index(text_encoder.EOS_ID) return ids[0:index] except ValueError: # No EOS_ID: return the array as-is. return ids
python
def _save_until_eos(ids, skip=False): """Strips everything after the first <EOS> token, which is normally 1.""" ids = ids.flatten() if skip: return ids try: index = list(ids).index(text_encoder.EOS_ID) return ids[0:index] except ValueError: # No EOS_ID: return the array as-is. return ids
[ "def", "_save_until_eos", "(", "ids", ",", "skip", "=", "False", ")", ":", "ids", "=", "ids", ".", "flatten", "(", ")", "if", "skip", ":", "return", "ids", "try", ":", "index", "=", "list", "(", "ids", ")", ".", "index", "(", "text_encoder", ".", ...
Strips everything after the first <EOS> token, which is normally 1.
[ "Strips", "everything", "after", "the", "first", "<EOS", ">", "token", "which", "is", "normally", "1", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L879-L889
train
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
_interactive_input_tensor_to_features_dict
def _interactive_input_tensor_to_features_dict(feature_map, hparams): """Convert the interactive input format (see above) to a dictionary. Args: feature_map: dict with inputs. hparams: model hyperparameters Returns: a features dictionary, as expected by the decoder. """ inputs = tf.convert_to_te...
python
def _interactive_input_tensor_to_features_dict(feature_map, hparams): """Convert the interactive input format (see above) to a dictionary. Args: feature_map: dict with inputs. hparams: model hyperparameters Returns: a features dictionary, as expected by the decoder. """ inputs = tf.convert_to_te...
[ "def", "_interactive_input_tensor_to_features_dict", "(", "feature_map", ",", "hparams", ")", ":", "inputs", "=", "tf", ".", "convert_to_tensor", "(", "feature_map", "[", "\"inputs\"", "]", ")", "input_is_image", "=", "False", "if", "len", "(", "inputs", ".", "g...
Convert the interactive input format (see above) to a dictionary. Args: feature_map: dict with inputs. hparams: model hyperparameters Returns: a features dictionary, as expected by the decoder.
[ "Convert", "the", "interactive", "input", "format", "(", "see", "above", ")", "to", "a", "dictionary", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L892-L930
train
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
_decode_input_tensor_to_features_dict
def _decode_input_tensor_to_features_dict(feature_map, hparams): """Convert the interactive input format (see above) to a dictionary. Args: feature_map: dict with inputs. hparams: model hyperparameters Returns: a features dictionary, as expected by the decoder. """ inputs = tf.convert_to_tensor(...
python
def _decode_input_tensor_to_features_dict(feature_map, hparams): """Convert the interactive input format (see above) to a dictionary. Args: feature_map: dict with inputs. hparams: model hyperparameters Returns: a features dictionary, as expected by the decoder. """ inputs = tf.convert_to_tensor(...
[ "def", "_decode_input_tensor_to_features_dict", "(", "feature_map", ",", "hparams", ")", ":", "inputs", "=", "tf", ".", "convert_to_tensor", "(", "feature_map", "[", "\"inputs\"", "]", ")", "input_is_image", "=", "False", "x", "=", "inputs", "p_hparams", "=", "h...
Convert the interactive input format (see above) to a dictionary. Args: feature_map: dict with inputs. hparams: model hyperparameters Returns: a features dictionary, as expected by the decoder.
[ "Convert", "the", "interactive", "input", "format", "(", "see", "above", ")", "to", "a", "dictionary", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L933-L960
train
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
run_postdecode_hooks
def run_postdecode_hooks(decode_hook_args, dataset_split): """Run hooks after decodes have run.""" hooks = decode_hook_args.problem.decode_hooks if not hooks: return global_step = latest_checkpoint_step(decode_hook_args.estimator.model_dir) if global_step is None: tf.logging.info( "Skipping de...
python
def run_postdecode_hooks(decode_hook_args, dataset_split): """Run hooks after decodes have run.""" hooks = decode_hook_args.problem.decode_hooks if not hooks: return global_step = latest_checkpoint_step(decode_hook_args.estimator.model_dir) if global_step is None: tf.logging.info( "Skipping de...
[ "def", "run_postdecode_hooks", "(", "decode_hook_args", ",", "dataset_split", ")", ":", "hooks", "=", "decode_hook_args", ".", "problem", ".", "decode_hooks", "if", "not", "hooks", ":", "return", "global_step", "=", "latest_checkpoint_step", "(", "decode_hook_args", ...
Run hooks after decodes have run.
[ "Run", "hooks", "after", "decodes", "have", "run", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L982-L1008
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/style_transfer.py
StyleTransferProblemShakespeare.dataset_splits
def dataset_splits(self): """Splits of data to produce and number of output shards for each.""" return [{ "split": problem.DatasetSplit.TRAIN, "shards": _TRAIN_SHARDS, }, { "split": problem.DatasetSplit.EVAL, "shards": _DEV_SHARDS, }]
python
def dataset_splits(self): """Splits of data to produce and number of output shards for each.""" return [{ "split": problem.DatasetSplit.TRAIN, "shards": _TRAIN_SHARDS, }, { "split": problem.DatasetSplit.EVAL, "shards": _DEV_SHARDS, }]
[ "def", "dataset_splits", "(", "self", ")", ":", "return", "[", "{", "\"split\"", ":", "problem", ".", "DatasetSplit", ".", "TRAIN", ",", "\"shards\"", ":", "_TRAIN_SHARDS", ",", "}", ",", "{", "\"split\"", ":", "problem", ".", "DatasetSplit", ".", "EVAL", ...
Splits of data to produce and number of output shards for each.
[ "Splits", "of", "data", "to", "produce", "and", "number", "of", "output", "shards", "for", "each", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/style_transfer.py#L87-L95
train
tensorflow/tensor2tensor
tensor2tensor/models/mtf_image_transformer.py
local_attention1d_spatial_decoder
def local_attention1d_spatial_decoder(x, kv_dim, heads_dim, feedforward_dim, hparams): """Image Transformer decoder with local1D spatial layers.""" batch_dim, length_dim, model_dim = x.shape.dims blocks_w_dim = mtf.Dimension("blocksw", hparams.block_length) num_w_blocks_dim...
python
def local_attention1d_spatial_decoder(x, kv_dim, heads_dim, feedforward_dim, hparams): """Image Transformer decoder with local1D spatial layers.""" batch_dim, length_dim, model_dim = x.shape.dims blocks_w_dim = mtf.Dimension("blocksw", hparams.block_length) num_w_blocks_dim...
[ "def", "local_attention1d_spatial_decoder", "(", "x", ",", "kv_dim", ",", "heads_dim", ",", "feedforward_dim", ",", "hparams", ")", ":", "batch_dim", ",", "length_dim", ",", "model_dim", "=", "x", ".", "shape", ".", "dims", "blocks_w_dim", "=", "mtf", ".", "...
Image Transformer decoder with local1D spatial layers.
[ "Image", "Transformer", "decoder", "with", "local1D", "spatial", "layers", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L252-L283
train
tensorflow/tensor2tensor
tensor2tensor/models/mtf_image_transformer.py
local_attention2d_spatial_decoder
def local_attention2d_spatial_decoder(x, kv_dim, heads_dim, feedforward_dim, hparams): """Image Transformer decoder with local2D spatial layers.""" batch_dim, length_dim, model_dim = x.shape.dims blocks_h_dim = mtf.Dimension("blocksh", hparams.block_height) blocks_w_dim = m...
python
def local_attention2d_spatial_decoder(x, kv_dim, heads_dim, feedforward_dim, hparams): """Image Transformer decoder with local2D spatial layers.""" batch_dim, length_dim, model_dim = x.shape.dims blocks_h_dim = mtf.Dimension("blocksh", hparams.block_height) blocks_w_dim = m...
[ "def", "local_attention2d_spatial_decoder", "(", "x", ",", "kv_dim", ",", "heads_dim", ",", "feedforward_dim", ",", "hparams", ")", ":", "batch_dim", ",", "length_dim", ",", "model_dim", "=", "x", ".", "shape", ".", "dims", "blocks_h_dim", "=", "mtf", ".", "...
Image Transformer decoder with local2D spatial layers.
[ "Image", "Transformer", "decoder", "with", "local2D", "spatial", "layers", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L286-L331
train
tensorflow/tensor2tensor
tensor2tensor/models/mtf_image_transformer.py
local_attention1d_masked_decoder
def local_attention1d_masked_decoder(x, kv_dim, heads_dim, feedforward_dim, hparams): """Image Transformer decoder with local1D masked layers.""" print(x) _, length_dim, model_dim = x.shape.dims for layer in range(hparams.num_decoder_layers): layer_name = "decoder_layer_...
python
def local_attention1d_masked_decoder(x, kv_dim, heads_dim, feedforward_dim, hparams): """Image Transformer decoder with local1D masked layers.""" print(x) _, length_dim, model_dim = x.shape.dims for layer in range(hparams.num_decoder_layers): layer_name = "decoder_layer_...
[ "def", "local_attention1d_masked_decoder", "(", "x", ",", "kv_dim", ",", "heads_dim", ",", "feedforward_dim", ",", "hparams", ")", ":", "print", "(", "x", ")", "_", ",", "length_dim", ",", "model_dim", "=", "x", ".", "shape", ".", "dims", "for", "layer", ...
Image Transformer decoder with local1D masked layers.
[ "Image", "Transformer", "decoder", "with", "local1D", "masked", "layers", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L334-L362
train
tensorflow/tensor2tensor
tensor2tensor/models/mtf_image_transformer.py
mtf_image_transformer_base
def mtf_image_transformer_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.no_data_parallelism = True hparams.use_fixed_batch_size = True hparams.batch_size = 1 hparams.max_length = 3072 hparams.hidden_size = 256 hparams.label_smoothing = 0.0 # 8-way model-paralle...
python
def mtf_image_transformer_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.no_data_parallelism = True hparams.use_fixed_batch_size = True hparams.batch_size = 1 hparams.max_length = 3072 hparams.hidden_size = 256 hparams.label_smoothing = 0.0 # 8-way model-paralle...
[ "def", "mtf_image_transformer_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "no_data_parallelism", "=", "True", "hparams", ".", "use_fixed_batch_size", "=", "True", "hparams", ".", "batch_size", "=", "1", ...
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L366-L412
train
tensorflow/tensor2tensor
tensor2tensor/models/mtf_image_transformer.py
mtf_image_transformer_tiny
def mtf_image_transformer_tiny(): """Catch bugs locally...""" hparams = mtf_image_transformer_base() hparams.hidden_size = 128 hparams.d_ff = 256 hparams.batch_size = 4 hparams.num_encoder_layers = 1 hparams.num_decoder_layers = 4 hparams.num_heads = 4 hparams.attention_key_size = 128 hparams.attent...
python
def mtf_image_transformer_tiny(): """Catch bugs locally...""" hparams = mtf_image_transformer_base() hparams.hidden_size = 128 hparams.d_ff = 256 hparams.batch_size = 4 hparams.num_encoder_layers = 1 hparams.num_decoder_layers = 4 hparams.num_heads = 4 hparams.attention_key_size = 128 hparams.attent...
[ "def", "mtf_image_transformer_tiny", "(", ")", ":", "hparams", "=", "mtf_image_transformer_base", "(", ")", "hparams", ".", "hidden_size", "=", "128", "hparams", ".", "d_ff", "=", "256", "hparams", ".", "batch_size", "=", "4", "hparams", ".", "num_encoder_layers...
Catch bugs locally...
[ "Catch", "bugs", "locally", "..." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L416-L431
train
tensorflow/tensor2tensor
tensor2tensor/models/mtf_image_transformer.py
mtf_image_transformer_single
def mtf_image_transformer_single(): """Small single parameters.""" hparams = mtf_image_transformer_tiny() hparams.mesh_shape = "" hparams.layout = "" hparams.hidden_size = 32 hparams.filter_size = 32 hparams.batch_size = 1 hparams.num_encoder_layers = 1 hparams.num_decoder_layers = 1 hparams.num_hea...
python
def mtf_image_transformer_single(): """Small single parameters.""" hparams = mtf_image_transformer_tiny() hparams.mesh_shape = "" hparams.layout = "" hparams.hidden_size = 32 hparams.filter_size = 32 hparams.batch_size = 1 hparams.num_encoder_layers = 1 hparams.num_decoder_layers = 1 hparams.num_hea...
[ "def", "mtf_image_transformer_single", "(", ")", ":", "hparams", "=", "mtf_image_transformer_tiny", "(", ")", "hparams", ".", "mesh_shape", "=", "\"\"", "hparams", ".", "layout", "=", "\"\"", "hparams", ".", "hidden_size", "=", "32", "hparams", ".", "filter_size...
Small single parameters.
[ "Small", "single", "parameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L435-L449
train
tensorflow/tensor2tensor
tensor2tensor/models/mtf_image_transformer.py
mtf_image_transformer_base_single
def mtf_image_transformer_base_single(): """Small single parameters.""" hparams = mtf_image_transformer_base() hparams.num_decoder_layers = 6 hparams.filter_size = 256 hparams.block_length = 128 hparams.mesh_shape = "" hparams.layout = "" return hparams
python
def mtf_image_transformer_base_single(): """Small single parameters.""" hparams = mtf_image_transformer_base() hparams.num_decoder_layers = 6 hparams.filter_size = 256 hparams.block_length = 128 hparams.mesh_shape = "" hparams.layout = "" return hparams
[ "def", "mtf_image_transformer_base_single", "(", ")", ":", "hparams", "=", "mtf_image_transformer_base", "(", ")", "hparams", ".", "num_decoder_layers", "=", "6", "hparams", ".", "filter_size", "=", "256", "hparams", ".", "block_length", "=", "128", "hparams", "."...
Small single parameters.
[ "Small", "single", "parameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L453-L461
train
tensorflow/tensor2tensor
tensor2tensor/models/mtf_image_transformer.py
mtf_image_transformer_tiny_spatial1d
def mtf_image_transformer_tiny_spatial1d(): """Small single parameters.""" hparams = mtf_image_transformer_tiny() hparams.num_decoder_layers = 6 hparams.filter_size = 128 hparams.block_height = 8 hparams.block_width = 8 hparams.attention_type = "local1d_spatial" hparams.mesh_shape = "" hparams.layout ...
python
def mtf_image_transformer_tiny_spatial1d(): """Small single parameters.""" hparams = mtf_image_transformer_tiny() hparams.num_decoder_layers = 6 hparams.filter_size = 128 hparams.block_height = 8 hparams.block_width = 8 hparams.attention_type = "local1d_spatial" hparams.mesh_shape = "" hparams.layout ...
[ "def", "mtf_image_transformer_tiny_spatial1d", "(", ")", ":", "hparams", "=", "mtf_image_transformer_tiny", "(", ")", "hparams", ".", "num_decoder_layers", "=", "6", "hparams", ".", "filter_size", "=", "128", "hparams", ".", "block_height", "=", "8", "hparams", "....
Small single parameters.
[ "Small", "single", "parameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L465-L475
train
tensorflow/tensor2tensor
tensor2tensor/models/mtf_image_transformer.py
mtf_image_transformer_base_cifar
def mtf_image_transformer_base_cifar(): """Data parallel CIFAR parameters.""" hparams = mtf_image_transformer_base() hparams.mesh_shape = "batch:8" hparams.layout = "batch:batch" hparams.learning_rate_decay_steps = 13600 # one epoch hparams.batch_size = 32 hparams.num_heads = 4 hparams.num_decoder_laye...
python
def mtf_image_transformer_base_cifar(): """Data parallel CIFAR parameters.""" hparams = mtf_image_transformer_base() hparams.mesh_shape = "batch:8" hparams.layout = "batch:batch" hparams.learning_rate_decay_steps = 13600 # one epoch hparams.batch_size = 32 hparams.num_heads = 4 hparams.num_decoder_laye...
[ "def", "mtf_image_transformer_base_cifar", "(", ")", ":", "hparams", "=", "mtf_image_transformer_base", "(", ")", "hparams", ".", "mesh_shape", "=", "\"batch:8\"", "hparams", ".", "layout", "=", "\"batch:batch\"", "hparams", ".", "learning_rate_decay_steps", "=", "136...
Data parallel CIFAR parameters.
[ "Data", "parallel", "CIFAR", "parameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L493-L510
train
tensorflow/tensor2tensor
tensor2tensor/models/mtf_image_transformer.py
mtf_image_transformer_cifar_4x
def mtf_image_transformer_cifar_4x(): """Data parallel CIFAR parameters.""" hparams = mtf_image_transformer_base_cifar() hparams.mesh_shape = "batch:32" hparams.layout = "batch:batch" hparams.batch_size = 128 return hparams
python
def mtf_image_transformer_cifar_4x(): """Data parallel CIFAR parameters.""" hparams = mtf_image_transformer_base_cifar() hparams.mesh_shape = "batch:32" hparams.layout = "batch:batch" hparams.batch_size = 128 return hparams
[ "def", "mtf_image_transformer_cifar_4x", "(", ")", ":", "hparams", "=", "mtf_image_transformer_base_cifar", "(", ")", "hparams", ".", "mesh_shape", "=", "\"batch:32\"", "hparams", ".", "layout", "=", "\"batch:batch\"", "hparams", ".", "batch_size", "=", "128", "retu...
Data parallel CIFAR parameters.
[ "Data", "parallel", "CIFAR", "parameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L514-L520
train
tensorflow/tensor2tensor
tensor2tensor/models/mtf_image_transformer.py
mtf_image_transformer_cifar_mp_4x
def mtf_image_transformer_cifar_mp_4x(): """Data parallel CIFAR parameters.""" hparams = mtf_image_transformer_base_cifar() hparams.mesh_shape = "model:4;batch:8" hparams.layout = "batch:batch;d_ff:model;heads:model" hparams.batch_size = 32 hparams.num_heads = 8 hparams.d_ff = 8192 return hparams
python
def mtf_image_transformer_cifar_mp_4x(): """Data parallel CIFAR parameters.""" hparams = mtf_image_transformer_base_cifar() hparams.mesh_shape = "model:4;batch:8" hparams.layout = "batch:batch;d_ff:model;heads:model" hparams.batch_size = 32 hparams.num_heads = 8 hparams.d_ff = 8192 return hparams
[ "def", "mtf_image_transformer_cifar_mp_4x", "(", ")", ":", "hparams", "=", "mtf_image_transformer_base_cifar", "(", ")", "hparams", ".", "mesh_shape", "=", "\"model:4;batch:8\"", "hparams", ".", "layout", "=", "\"batch:batch;d_ff:model;heads:model\"", "hparams", ".", "bat...
Data parallel CIFAR parameters.
[ "Data", "parallel", "CIFAR", "parameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L524-L532
train
tensorflow/tensor2tensor
tensor2tensor/models/mtf_image_transformer.py
mtf_image_transformer_base_imagenet
def mtf_image_transformer_base_imagenet(): """Data parallel CIFAR parameters.""" hparams = mtf_image_transformer_base_cifar() hparams.mesh_shape = "batch:32" hparams.layout = "batch:batch" hparams.batch_size = 128 hparams.d_ff = 2048 hparams.hidden_size = 512 hparams.num_decoder_layers = 12 hparams.le...
python
def mtf_image_transformer_base_imagenet(): """Data parallel CIFAR parameters.""" hparams = mtf_image_transformer_base_cifar() hparams.mesh_shape = "batch:32" hparams.layout = "batch:batch" hparams.batch_size = 128 hparams.d_ff = 2048 hparams.hidden_size = 512 hparams.num_decoder_layers = 12 hparams.le...
[ "def", "mtf_image_transformer_base_imagenet", "(", ")", ":", "hparams", "=", "mtf_image_transformer_base_cifar", "(", ")", "hparams", ".", "mesh_shape", "=", "\"batch:32\"", "hparams", ".", "layout", "=", "\"batch:batch\"", "hparams", ".", "batch_size", "=", "128", ...
Data parallel CIFAR parameters.
[ "Data", "parallel", "CIFAR", "parameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L536-L551
train
tensorflow/tensor2tensor
tensor2tensor/models/mtf_image_transformer.py
mtf_image_transformer_base_imagenet_mp
def mtf_image_transformer_base_imagenet_mp(): """Model parallel ImageNet parameters.""" hparams = mtf_image_transformer_base_imagenet() hparams.mesh_shape = "model:4;batch:8" hparams.layout = "batch:batch;d_ff:model;heads:model" hparams.batch_size = 32 hparams.num_heads = 8 hparams.d_ff = 8192 hparams.l...
python
def mtf_image_transformer_base_imagenet_mp(): """Model parallel ImageNet parameters.""" hparams = mtf_image_transformer_base_imagenet() hparams.mesh_shape = "model:4;batch:8" hparams.layout = "batch:batch;d_ff:model;heads:model" hparams.batch_size = 32 hparams.num_heads = 8 hparams.d_ff = 8192 hparams.l...
[ "def", "mtf_image_transformer_base_imagenet_mp", "(", ")", ":", "hparams", "=", "mtf_image_transformer_base_imagenet", "(", ")", "hparams", ".", "mesh_shape", "=", "\"model:4;batch:8\"", "hparams", ".", "layout", "=", "\"batch:batch;d_ff:model;heads:model\"", "hparams", "."...
Model parallel ImageNet parameters.
[ "Model", "parallel", "ImageNet", "parameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L555-L565
train
tensorflow/tensor2tensor
tensor2tensor/models/mtf_image_transformer.py
mtf_image_transformer_base_imagenet_mp128
def mtf_image_transformer_base_imagenet_mp128(): """Model parallel ImageNet parameters.""" hparams = mtf_image_transformer_base_imagenet() hparams.mesh_shape = "model:8;batch:4" hparams.layout = "batch:batch;d_ff:model;heads:model" hparams.batch_size = 8 hparams.img_len = 128 hparams.block_length = 128 ...
python
def mtf_image_transformer_base_imagenet_mp128(): """Model parallel ImageNet parameters.""" hparams = mtf_image_transformer_base_imagenet() hparams.mesh_shape = "model:8;batch:4" hparams.layout = "batch:batch;d_ff:model;heads:model" hparams.batch_size = 8 hparams.img_len = 128 hparams.block_length = 128 ...
[ "def", "mtf_image_transformer_base_imagenet_mp128", "(", ")", ":", "hparams", "=", "mtf_image_transformer_base_imagenet", "(", ")", "hparams", ".", "mesh_shape", "=", "\"model:8;batch:4\"", "hparams", ".", "layout", "=", "\"batch:batch;d_ff:model;heads:model\"", "hparams", ...
Model parallel ImageNet parameters.
[ "Model", "parallel", "ImageNet", "parameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L569-L583
train
tensorflow/tensor2tensor
tensor2tensor/models/mtf_image_transformer.py
mtf_image_transformer_base_imagenet_mp_sp
def mtf_image_transformer_base_imagenet_mp_sp(): """Model parallel ImageNet parameters.""" hparams = mtf_image_transformer_base_imagenet_mp128() hparams.mesh_shape = "model:8;batch:4" hparams.layout = "batch:batch;d_ff:model;num_wblocks:model" hparams.batch_size = 8 hparams.img_len = 128 hparams.block_len...
python
def mtf_image_transformer_base_imagenet_mp_sp(): """Model parallel ImageNet parameters.""" hparams = mtf_image_transformer_base_imagenet_mp128() hparams.mesh_shape = "model:8;batch:4" hparams.layout = "batch:batch;d_ff:model;num_wblocks:model" hparams.batch_size = 8 hparams.img_len = 128 hparams.block_len...
[ "def", "mtf_image_transformer_base_imagenet_mp_sp", "(", ")", ":", "hparams", "=", "mtf_image_transformer_base_imagenet_mp128", "(", ")", "hparams", ".", "mesh_shape", "=", "\"model:8;batch:4\"", "hparams", ".", "layout", "=", "\"batch:batch;d_ff:model;num_wblocks:model\"", "...
Model parallel ImageNet parameters.
[ "Model", "parallel", "ImageNet", "parameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L587-L596
train
tensorflow/tensor2tensor
tensor2tensor/models/mtf_image_transformer.py
mtf_image_transformer_base_imagenet_mp64
def mtf_image_transformer_base_imagenet_mp64(): """Model parallel ImageNet parameters.""" hparams = mtf_image_transformer_base_imagenet() hparams.mesh_shape = "model:8;batch:4" hparams.layout = "batch:batch;d_ff:model;heads:model" hparams.batch_size = 8 hparams.img_len = 64 hparams.num_decoder_layers = 8 ...
python
def mtf_image_transformer_base_imagenet_mp64(): """Model parallel ImageNet parameters.""" hparams = mtf_image_transformer_base_imagenet() hparams.mesh_shape = "model:8;batch:4" hparams.layout = "batch:batch;d_ff:model;heads:model" hparams.batch_size = 8 hparams.img_len = 64 hparams.num_decoder_layers = 8 ...
[ "def", "mtf_image_transformer_base_imagenet_mp64", "(", ")", ":", "hparams", "=", "mtf_image_transformer_base_imagenet", "(", ")", "hparams", ".", "mesh_shape", "=", "\"model:8;batch:4\"", "hparams", ".", "layout", "=", "\"batch:batch;d_ff:model;heads:model\"", "hparams", "...
Model parallel ImageNet parameters.
[ "Model", "parallel", "ImageNet", "parameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L600-L608
train
tensorflow/tensor2tensor
tensor2tensor/layers/reversible_layers.py
create_degrees
def create_degrees(input_dim, hidden_dims, input_order='left-to-right', hidden_order='left-to-right'): """Returns a list of degree vectors, one for each input and hidden layer. A unit with degree d can only receive input from units with degree < d. Output ...
python
def create_degrees(input_dim, hidden_dims, input_order='left-to-right', hidden_order='left-to-right'): """Returns a list of degree vectors, one for each input and hidden layer. A unit with degree d can only receive input from units with degree < d. Output ...
[ "def", "create_degrees", "(", "input_dim", ",", "hidden_dims", ",", "input_order", "=", "'left-to-right'", ",", "hidden_order", "=", "'left-to-right'", ")", ":", "if", "(", "isinstance", "(", "input_order", ",", "str", ")", "and", "input_order", "not", "in", "...
Returns a list of degree vectors, one for each input and hidden layer. A unit with degree d can only receive input from units with degree < d. Output units always have the same degree as their associated input unit. Args: input_dim: Number of inputs. hidden_dims: list with the number of hidden units per...
[ "Returns", "a", "list", "of", "degree", "vectors", "one", "for", "each", "input", "and", "hidden", "layer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/reversible_layers.py#L218-L269
train
tensorflow/tensor2tensor
tensor2tensor/layers/reversible_layers.py
create_masks
def create_masks(input_dim, hidden_dims, input_order='left-to-right', hidden_order='left-to-right'): """Returns a list of binary mask matrices respecting autoregressive ordering. Args: input_dim: Number of inputs. hidden_dims: list with the number of hidde...
python
def create_masks(input_dim, hidden_dims, input_order='left-to-right', hidden_order='left-to-right'): """Returns a list of binary mask matrices respecting autoregressive ordering. Args: input_dim: Number of inputs. hidden_dims: list with the number of hidde...
[ "def", "create_masks", "(", "input_dim", ",", "hidden_dims", ",", "input_order", "=", "'left-to-right'", ",", "hidden_order", "=", "'left-to-right'", ")", ":", "degrees", "=", "create_degrees", "(", "input_dim", ",", "hidden_dims", ",", "input_order", ",", "hidden...
Returns a list of binary mask matrices respecting autoregressive ordering. Args: input_dim: Number of inputs. hidden_dims: list with the number of hidden units per layer. It does not include the output layer; those number of units will always be set to input_dim downstream. Each hidden unit size ...
[ "Returns", "a", "list", "of", "binary", "mask", "matrices", "respecting", "autoregressive", "ordering", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/reversible_layers.py#L272-L302
train
tensorflow/tensor2tensor
tensor2tensor/layers/reversible_layers.py
sinkhorn
def sinkhorn(inputs, n_iters=20): """Performs incomplete Sinkhorn normalization to inputs. By a theorem by Sinkhorn and Knopp [1], a sufficiently well-behaved matrix with positive entries can be turned into a doubly-stochastic matrix (i.e. its rows and columns add up to one) via the succesive row and column ...
python
def sinkhorn(inputs, n_iters=20): """Performs incomplete Sinkhorn normalization to inputs. By a theorem by Sinkhorn and Knopp [1], a sufficiently well-behaved matrix with positive entries can be turned into a doubly-stochastic matrix (i.e. its rows and columns add up to one) via the succesive row and column ...
[ "def", "sinkhorn", "(", "inputs", ",", "n_iters", "=", "20", ")", ":", "vocab_size", "=", "tf", ".", "shape", "(", "inputs", ")", "[", "-", "1", "]", "log_alpha", "=", "tf", ".", "reshape", "(", "inputs", ",", "[", "-", "1", ",", "vocab_size", ",...
Performs incomplete Sinkhorn normalization to inputs. By a theorem by Sinkhorn and Knopp [1], a sufficiently well-behaved matrix with positive entries can be turned into a doubly-stochastic matrix (i.e. its rows and columns add up to one) via the succesive row and column normalization. -To ensure positivity...
[ "Performs", "incomplete", "Sinkhorn", "normalization", "to", "inputs", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/reversible_layers.py#L319-L358
train
tensorflow/tensor2tensor
tensor2tensor/layers/reversible_layers.py
TransformedRandomVariable
def TransformedRandomVariable(random_variable, # pylint: disable=invalid-name reversible_layer, name=None, sample_shape=(), value=None): """Random variable for f(x), where x ~ p(x) and f is reversi...
python
def TransformedRandomVariable(random_variable, # pylint: disable=invalid-name reversible_layer, name=None, sample_shape=(), value=None): """Random variable for f(x), where x ~ p(x) and f is reversi...
[ "def", "TransformedRandomVariable", "(", "random_variable", ",", "# pylint: disable=invalid-name", "reversible_layer", ",", "name", "=", "None", ",", "sample_shape", "=", "(", ")", ",", "value", "=", "None", ")", ":", "return", "ed", ".", "RandomVariable", "(", ...
Random variable for f(x), where x ~ p(x) and f is reversible.
[ "Random", "variable", "for", "f", "(", "x", ")", "where", "x", "~", "p", "(", "x", ")", "and", "f", "is", "reversible", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/reversible_layers.py#L447-L458
train
tensorflow/tensor2tensor
tensor2tensor/layers/reversible_layers.py
ActNorm.log_det_jacobian
def log_det_jacobian(self, inputs): """Returns log det | dx / dy | = num_events * sum log | scale |.""" del inputs # unused # Number of events is number of all elements excluding the batch and # channel dimensions. num_events = tf.reduce_prod(tf.shape(inputs)[1:-1]) log_det_jacobian = num_event...
python
def log_det_jacobian(self, inputs): """Returns log det | dx / dy | = num_events * sum log | scale |.""" del inputs # unused # Number of events is number of all elements excluding the batch and # channel dimensions. num_events = tf.reduce_prod(tf.shape(inputs)[1:-1]) log_det_jacobian = num_event...
[ "def", "log_det_jacobian", "(", "self", ",", "inputs", ")", ":", "del", "inputs", "# unused", "# Number of events is number of all elements excluding the batch and", "# channel dimensions.", "num_events", "=", "tf", ".", "reduce_prod", "(", "tf", ".", "shape", "(", "inp...
Returns log det | dx / dy | = num_events * sum log | scale |.
[ "Returns", "log", "det", "|", "dx", "/", "dy", "|", "=", "num_events", "*", "sum", "log", "|", "scale", "|", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/reversible_layers.py#L94-L101
train
tensorflow/tensor2tensor
tensor2tensor/layers/vq_discrete.py
DiscreteBottleneck.slice_hidden
def slice_hidden(self, x): """Slice encoder hidden state into block_dim. Args: x: Encoder hidden state of shape [-1, hidden_size]. Returns: Sliced states of shape [-1, num_blocks, block_dim]. """ x_sliced = tf.reshape( x, shape=[-1, self.hparams.num_blocks, self.hparams.blo...
python
def slice_hidden(self, x): """Slice encoder hidden state into block_dim. Args: x: Encoder hidden state of shape [-1, hidden_size]. Returns: Sliced states of shape [-1, num_blocks, block_dim]. """ x_sliced = tf.reshape( x, shape=[-1, self.hparams.num_blocks, self.hparams.blo...
[ "def", "slice_hidden", "(", "self", ",", "x", ")", ":", "x_sliced", "=", "tf", ".", "reshape", "(", "x", ",", "shape", "=", "[", "-", "1", ",", "self", ".", "hparams", ".", "num_blocks", ",", "self", ".", "hparams", ".", "block_dim", "]", ")", "r...
Slice encoder hidden state into block_dim. Args: x: Encoder hidden state of shape [-1, hidden_size]. Returns: Sliced states of shape [-1, num_blocks, block_dim].
[ "Slice", "encoder", "hidden", "state", "into", "block_dim", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/vq_discrete.py#L61-L72
train
tensorflow/tensor2tensor
tensor2tensor/layers/vq_discrete.py
DiscreteBottleneck.nearest_neighbor
def nearest_neighbor(self, x, means): """Find the nearest element in means to elements in x. Args: x: Batch of encoder continuous latent states sliced/projected into shape [-1, num_blocks, block_dim]. means: Embedding means of shape. Returns: Tensor with nearest element in...
python
def nearest_neighbor(self, x, means): """Find the nearest element in means to elements in x. Args: x: Batch of encoder continuous latent states sliced/projected into shape [-1, num_blocks, block_dim]. means: Embedding means of shape. Returns: Tensor with nearest element in...
[ "def", "nearest_neighbor", "(", "self", ",", "x", ",", "means", ")", ":", "x_norm_sq", "=", "tf", ".", "reduce_sum", "(", "tf", ".", "square", "(", "x", ")", ",", "axis", "=", "-", "1", ",", "keep_dims", "=", "True", ")", "means_norm_sq", "=", "tf"...
Find the nearest element in means to elements in x. Args: x: Batch of encoder continuous latent states sliced/projected into shape [-1, num_blocks, block_dim]. means: Embedding means of shape. Returns: Tensor with nearest element in mean encoded in one-hot notation.
[ "Find", "the", "nearest", "element", "in", "means", "to", "elements", "in", "x", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/vq_discrete.py#L74-L120
train
tensorflow/tensor2tensor
tensor2tensor/layers/vq_discrete.py
DiscreteBottleneck.embedding_lookup
def embedding_lookup(self, x, means): """Compute nearest neighbors and loss for training the embeddings. Args: x: Batch of encoder continuous latent states sliced/projected into shape [-1, num_blocks, block_dim]. means: Embedding means. Returns: The nearest neighbor...
python
def embedding_lookup(self, x, means): """Compute nearest neighbors and loss for training the embeddings. Args: x: Batch of encoder continuous latent states sliced/projected into shape [-1, num_blocks, block_dim]. means: Embedding means. Returns: The nearest neighbor...
[ "def", "embedding_lookup", "(", "self", ",", "x", ",", "means", ")", ":", "x_means_hot", "=", "self", ".", "nearest_neighbor", "(", "x", ",", "means", ")", "x_means_hot_flat", "=", "tf", ".", "reshape", "(", "x_means_hot", ",", "[", "-", "1", ",", "sel...
Compute nearest neighbors and loss for training the embeddings. Args: x: Batch of encoder continuous latent states sliced/projected into shape [-1, num_blocks, block_dim]. means: Embedding means. Returns: The nearest neighbor in one hot form, the nearest neighbor ...
[ "Compute", "nearest", "neighbors", "and", "loss", "for", "training", "the", "embeddings", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/vq_discrete.py#L122-L145
train
tensorflow/tensor2tensor
tensor2tensor/layers/vq_discrete.py
DiscreteBottleneck.int_to_bit
def int_to_bit(self, x_int, num_bits, base=2): """Turn x_int representing numbers into a bitwise (lower-endian) tensor. Args: x_int: Tensor containing integer to be converted into base notation. num_bits: Number of bits in the representation. base: Base of the representation. ...
python
def int_to_bit(self, x_int, num_bits, base=2): """Turn x_int representing numbers into a bitwise (lower-endian) tensor. Args: x_int: Tensor containing integer to be converted into base notation. num_bits: Number of bits in the representation. base: Base of the representation. ...
[ "def", "int_to_bit", "(", "self", ",", "x_int", ",", "num_bits", ",", "base", "=", "2", ")", ":", "x_l", "=", "tf", ".", "to_int32", "(", "tf", ".", "expand_dims", "(", "x_int", ",", "axis", "=", "-", "1", ")", ")", "# pylint: disable=g-complex-compreh...
Turn x_int representing numbers into a bitwise (lower-endian) tensor. Args: x_int: Tensor containing integer to be converted into base notation. num_bits: Number of bits in the representation. base: Base of the representation. Returns: Corresponding number expressed in ...
[ "Turn", "x_int", "representing", "numbers", "into", "a", "bitwise", "(", "lower", "-", "endian", ")", "tensor", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/vq_discrete.py#L167-L187
train
tensorflow/tensor2tensor
tensor2tensor/layers/vq_discrete.py
DiscreteBottleneck.embed
def embed(self, x): """Embedding function that takes discrete latent and returns embedding. Args: x: Input to the discretization bottleneck. Returns: Continuous embedding to be passed on to the decoder. Raises: ValueError: For unknown or missing arguments. """ shape_x =...
python
def embed(self, x): """Embedding function that takes discrete latent and returns embedding. Args: x: Input to the discretization bottleneck. Returns: Continuous embedding to be passed on to the decoder. Raises: ValueError: For unknown or missing arguments. """ shape_x =...
[ "def", "embed", "(", "self", ",", "x", ")", ":", "shape_x", "=", "common_layers", ".", "shape_list", "(", "x", ")", "x_flat", "=", "tf", ".", "reshape", "(", "x", ",", "[", "-", "1", ",", "1", "]", ")", "c", "=", "self", ".", "int_to_bit", "(",...
Embedding function that takes discrete latent and returns embedding. Args: x: Input to the discretization bottleneck. Returns: Continuous embedding to be passed on to the decoder. Raises: ValueError: For unknown or missing arguments.
[ "Embedding", "function", "that", "takes", "discrete", "latent", "and", "returns", "embedding", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/vq_discrete.py#L189-L223
train
tensorflow/tensor2tensor
tensor2tensor/layers/vq_discrete.py
DiscreteBottleneck.discrete_bottleneck
def discrete_bottleneck(self, x): """Discretization bottleneck for latent variables. Args: x: Input to the discretization bottleneck. Returns: Embedding to pass to the decoder, discrete latent, loss, and the embedding function. Raises: ValueError: If projection...
python
def discrete_bottleneck(self, x): """Discretization bottleneck for latent variables. Args: x: Input to the discretization bottleneck. Returns: Embedding to pass to the decoder, discrete latent, loss, and the embedding function. Raises: ValueError: If projection...
[ "def", "discrete_bottleneck", "(", "self", ",", "x", ")", ":", "x_reshaped", "=", "self", ".", "slice_hidden", "(", "x", ")", "x_means_hot", "=", "[", "]", "x_means", "=", "0", "loss", "=", "0", "x_means_hot", ",", "x_means", ",", "q_loss", ",", "e_los...
Discretization bottleneck for latent variables. Args: x: Input to the discretization bottleneck. Returns: Embedding to pass to the decoder, discrete latent, loss, and the embedding function. Raises: ValueError: If projection_tensors is None for reshape_method ...
[ "Discretization", "bottleneck", "for", "latent", "variables", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/vq_discrete.py#L225-L310
train
tensorflow/tensor2tensor
tensor2tensor/models/research/adafactor_experiments.py
mimic_adam_with_adafactor
def mimic_adam_with_adafactor(hparams): """Switch from Adam to Adafactor, approximating the behavior of Adam. Some minor things may be different, like epsilon and beta1 correction. Args: hparams: model hyperparameters where "adam" in hparams.optimizer """ assert "adam" in hparams.optimizer hparams.opt...
python
def mimic_adam_with_adafactor(hparams): """Switch from Adam to Adafactor, approximating the behavior of Adam. Some minor things may be different, like epsilon and beta1 correction. Args: hparams: model hyperparameters where "adam" in hparams.optimizer """ assert "adam" in hparams.optimizer hparams.opt...
[ "def", "mimic_adam_with_adafactor", "(", "hparams", ")", ":", "assert", "\"adam\"", "in", "hparams", ".", "optimizer", "hparams", ".", "optimizer", "=", "\"adafactor\"", "hparams", ".", "optimizer_adafactor_beta1", "=", "hparams", ".", "optimizer_adam_beta1", "hparams...
Switch from Adam to Adafactor, approximating the behavior of Adam. Some minor things may be different, like epsilon and beta1 correction. Args: hparams: model hyperparameters where "adam" in hparams.optimizer
[ "Switch", "from", "Adam", "to", "Adafactor", "approximating", "the", "behavior", "of", "Adam", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/adafactor_experiments.py#L27-L42
train
tensorflow/tensor2tensor
tensor2tensor/models/research/adafactor_experiments.py
afx_adam
def afx_adam(): """Old version - Adam.""" hparams = transformer.transformer_base_v2() hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.999 hparams.symbol_modality_num_shards = 1 hparams.batch_size = 2048 hparams.optimizer = "adam" hparams.learning_rate_schedule = ( "constant*rsq...
python
def afx_adam(): """Old version - Adam.""" hparams = transformer.transformer_base_v2() hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.999 hparams.symbol_modality_num_shards = 1 hparams.batch_size = 2048 hparams.optimizer = "adam" hparams.learning_rate_schedule = ( "constant*rsq...
[ "def", "afx_adam", "(", ")", ":", "hparams", "=", "transformer", ".", "transformer_base_v2", "(", ")", "hparams", ".", "optimizer_adam_beta1", "=", "0.9", "hparams", ".", "optimizer_adam_beta2", "=", "0.999", "hparams", ".", "symbol_modality_num_shards", "=", "1",...
Old version - Adam.
[ "Old", "version", "-", "Adam", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/adafactor_experiments.py#L46-L57
train