repo
stringclasses
85 values
path
stringlengths
8
121
func_name
stringlengths
1
82
original_string
stringlengths
112
65.5k
language
stringclasses
1 value
code
stringlengths
112
65.5k
code_tokens
listlengths
20
4.09k
docstring
stringlengths
3
46.3k
docstring_tokens
listlengths
1
564
sha
stringclasses
85 values
url
stringlengths
93
218
partition
stringclasses
1 value
tensorflow/tensor2tensor
tensor2tensor/rl/gym_utils.py
make_gym_env
def make_gym_env(name, rl_env_max_episode_steps=-1, maxskip_env=False, rendered_env=False, rendered_env_resize_to=None, sticky_actions=False): """Create a gym env optionally with a time limit and maxskip wrapper. NOTE: The returne...
python
def make_gym_env(name, rl_env_max_episode_steps=-1, maxskip_env=False, rendered_env=False, rendered_env_resize_to=None, sticky_actions=False): """Create a gym env optionally with a time limit and maxskip wrapper. NOTE: The returne...
[ "def", "make_gym_env", "(", "name", ",", "rl_env_max_episode_steps", "=", "-", "1", ",", "maxskip_env", "=", "False", ",", "rendered_env", "=", "False", ",", "rendered_env_resize_to", "=", "None", ",", "sticky_actions", "=", "False", ")", ":", "env", "=", "g...
Create a gym env optionally with a time limit and maxskip wrapper. NOTE: The returned env may already be wrapped with TimeLimit! Args: name: `str` - base name of the gym env to make. rl_env_max_episode_steps: `int` or None - Using any value < 0 returns the env as-in, otherwise we impose the requeste...
[ "Create", "a", "gym", "env", "optionally", "with", "a", "time", "limit", "and", "maxskip", "wrapper", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/gym_utils.py#L179-L206
train
tensorflow/tensor2tensor
tensor2tensor/rl/gym_utils.py
register_gym_env
def register_gym_env(class_entry_point, version="v0", kwargs=None): """Registers the class in Gym and returns the registered name and the env.""" split_on_colon = class_entry_point.split(":") assert len(split_on_colon) == 2 class_name = split_on_colon[1] # We have to add the version to conform to gym's API....
python
def register_gym_env(class_entry_point, version="v0", kwargs=None): """Registers the class in Gym and returns the registered name and the env.""" split_on_colon = class_entry_point.split(":") assert len(split_on_colon) == 2 class_name = split_on_colon[1] # We have to add the version to conform to gym's API....
[ "def", "register_gym_env", "(", "class_entry_point", ",", "version", "=", "\"v0\"", ",", "kwargs", "=", "None", ")", ":", "split_on_colon", "=", "class_entry_point", ".", "split", "(", "\":\"", ")", "assert", "len", "(", "split_on_colon", ")", "==", "2", "cl...
Registers the class in Gym and returns the registered name and the env.
[ "Registers", "the", "class", "in", "Gym", "and", "returns", "the", "registered", "name", "and", "the", "env", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/gym_utils.py#L209-L223
train
tensorflow/tensor2tensor
tensor2tensor/rl/gym_utils.py
MaxAndSkipEnv.step
def step(self, action): """Repeat action, sum reward, and max over last observations.""" total_reward = 0.0 done = None for i in range(self._skip): obs, reward, done, info = self.env.step(action) if i == self._skip - 2: self._obs_buffer[0] = obs if i == self._skip - 1: ...
python
def step(self, action): """Repeat action, sum reward, and max over last observations.""" total_reward = 0.0 done = None for i in range(self._skip): obs, reward, done, info = self.env.step(action) if i == self._skip - 2: self._obs_buffer[0] = obs if i == self._skip - 1: ...
[ "def", "step", "(", "self", ",", "action", ")", ":", "total_reward", "=", "0.0", "done", "=", "None", "for", "i", "in", "range", "(", "self", ".", "_skip", ")", ":", "obs", ",", "reward", ",", "done", ",", "info", "=", "self", ".", "env", ".", ...
Repeat action, sum reward, and max over last observations.
[ "Repeat", "action", "sum", "reward", "and", "max", "over", "last", "observations", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/gym_utils.py#L62-L77
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/all_problems.py
_handle_errors
def _handle_errors(errors): """Log out and possibly reraise errors during import.""" if not errors: return log_all = True # pylint: disable=unused-variable err_msg = "T2T: skipped importing {num_missing} data_generators modules." print(err_msg.format(num_missing=len(errors))) for module, err in errors:...
python
def _handle_errors(errors): """Log out and possibly reraise errors during import.""" if not errors: return log_all = True # pylint: disable=unused-variable err_msg = "T2T: skipped importing {num_missing} data_generators modules." print(err_msg.format(num_missing=len(errors))) for module, err in errors:...
[ "def", "_handle_errors", "(", "errors", ")", ":", "if", "not", "errors", ":", "return", "log_all", "=", "True", "# pylint: disable=unused-variable", "err_msg", "=", "\"T2T: skipped importing {num_missing} data_generators modules.\"", "print", "(", "err_msg", ".", "format"...
Log out and possibly reraise errors during import.
[ "Log", "out", "and", "possibly", "reraise", "errors", "during", "import", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/all_problems.py#L113-L126
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparams_lib.py
create_hparams
def create_hparams(hparams_set, hparams_overrides_str="", data_dir=None, problem_name=None, hparams_path=None): """Create HParams with data_dir and problem hparams, if kwargs provided.""" hparams = registry.hparams(hparams_set) if hparams...
python
def create_hparams(hparams_set, hparams_overrides_str="", data_dir=None, problem_name=None, hparams_path=None): """Create HParams with data_dir and problem hparams, if kwargs provided.""" hparams = registry.hparams(hparams_set) if hparams...
[ "def", "create_hparams", "(", "hparams_set", ",", "hparams_overrides_str", "=", "\"\"", ",", "data_dir", "=", "None", ",", "problem_name", "=", "None", ",", "hparams_path", "=", "None", ")", ":", "hparams", "=", "registry", ".", "hparams", "(", "hparams_set", ...
Create HParams with data_dir and problem hparams, if kwargs provided.
[ "Create", "HParams", "with", "data_dir", "and", "problem", "hparams", "if", "kwargs", "provided", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparams_lib.py#L42-L59
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparams_lib.py
create_hparams_from_json
def create_hparams_from_json(json_path, hparams=None): """Loading hparams from json; can also start from hparams if specified.""" tf.logging.info("Loading hparams from existing json %s" % json_path) with tf.gfile.Open(json_path, "r") as f: hparams_values = json.load(f) # Prevent certain keys from overwrit...
python
def create_hparams_from_json(json_path, hparams=None): """Loading hparams from json; can also start from hparams if specified.""" tf.logging.info("Loading hparams from existing json %s" % json_path) with tf.gfile.Open(json_path, "r") as f: hparams_values = json.load(f) # Prevent certain keys from overwrit...
[ "def", "create_hparams_from_json", "(", "json_path", ",", "hparams", "=", "None", ")", ":", "tf", ".", "logging", ".", "info", "(", "\"Loading hparams from existing json %s\"", "%", "json_path", ")", "with", "tf", ".", "gfile", ".", "Open", "(", "json_path", "...
Loading hparams from json; can also start from hparams if specified.
[ "Loading", "hparams", "from", "json", ";", "can", "also", "start", "from", "hparams", "if", "specified", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparams_lib.py#L62-L90
train
tensorflow/tensor2tensor
tensor2tensor/utils/hparams_lib.py
add_problem_hparams
def add_problem_hparams(hparams, problem_name_or_instance): """Add problem hparams for the problems.""" if isinstance(problem_name_or_instance, problem_lib.Problem): problem = problem_name_or_instance else: problem = registry.problem(problem_name_or_instance) p_hparams = problem.get_hparams(hparams) h...
python
def add_problem_hparams(hparams, problem_name_or_instance): """Add problem hparams for the problems.""" if isinstance(problem_name_or_instance, problem_lib.Problem): problem = problem_name_or_instance else: problem = registry.problem(problem_name_or_instance) p_hparams = problem.get_hparams(hparams) h...
[ "def", "add_problem_hparams", "(", "hparams", ",", "problem_name_or_instance", ")", ":", "if", "isinstance", "(", "problem_name_or_instance", ",", "problem_lib", ".", "Problem", ")", ":", "problem", "=", "problem_name_or_instance", "else", ":", "problem", "=", "regi...
Add problem hparams for the problems.
[ "Add", "problem", "hparams", "for", "the", "problems", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/hparams_lib.py#L93-L101
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/subject_verb_agreement.py
load_examples
def load_examples(tmp_dir, prop_train=0.09, prop_val=0.01): """Loads exampls from the tsv file. Args: tmp_dir: temp directory. prop_train: proportion of the train data prop_val: proportion of the validation data Returns: All examples in the dataset pluse train, test, and development splits. "...
python
def load_examples(tmp_dir, prop_train=0.09, prop_val=0.01): """Loads exampls from the tsv file. Args: tmp_dir: temp directory. prop_train: proportion of the train data prop_val: proportion of the validation data Returns: All examples in the dataset pluse train, test, and development splits. "...
[ "def", "load_examples", "(", "tmp_dir", ",", "prop_train", "=", "0.09", ",", "prop_val", "=", "0.01", ")", ":", "infile", "=", "generator_utils", ".", "maybe_download", "(", "tmp_dir", ",", "_TAR", ",", "_URL", ")", "tf", ".", "logging", ".", "info", "("...
Loads exampls from the tsv file. Args: tmp_dir: temp directory. prop_train: proportion of the train data prop_val: proportion of the validation data Returns: All examples in the dataset pluse train, test, and development splits.
[ "Loads", "exampls", "from", "the", "tsv", "file", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/subject_verb_agreement.py#L77-L111
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/cifar.py
_get_cifar
def _get_cifar(directory, url): """Download and extract CIFAR to directory unless it is there.""" filename = os.path.basename(url) path = generator_utils.maybe_download(directory, filename, url) tarfile.open(path, "r:gz").extractall(directory)
python
def _get_cifar(directory, url): """Download and extract CIFAR to directory unless it is there.""" filename = os.path.basename(url) path = generator_utils.maybe_download(directory, filename, url) tarfile.open(path, "r:gz").extractall(directory)
[ "def", "_get_cifar", "(", "directory", ",", "url", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "url", ")", "path", "=", "generator_utils", ".", "maybe_download", "(", "directory", ",", "filename", ",", "url", ")", "tarfile", ".", ...
Download and extract CIFAR to directory unless it is there.
[ "Download", "and", "extract", "CIFAR", "to", "directory", "unless", "it", "is", "there", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/cifar.py#L55-L59
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/cifar.py
cifar_generator
def cifar_generator(cifar_version, tmp_dir, training, how_many, start_from=0): """Image generator for CIFAR-10 and 100. Args: cifar_version: string; one of "cifar10" or "cifar100" tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. ...
python
def cifar_generator(cifar_version, tmp_dir, training, how_many, start_from=0): """Image generator for CIFAR-10 and 100. Args: cifar_version: string; one of "cifar10" or "cifar100" tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. ...
[ "def", "cifar_generator", "(", "cifar_version", ",", "tmp_dir", ",", "training", ",", "how_many", ",", "start_from", "=", "0", ")", ":", "if", "cifar_version", "==", "\"cifar10\"", ":", "url", "=", "_CIFAR10_URL", "train_files", "=", "_CIFAR10_TRAIN_FILES", "tes...
Image generator for CIFAR-10 and 100. Args: cifar_version: string; one of "cifar10" or "cifar100" tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. how_many: how many images and labels to generate. start_from: from which imag...
[ "Image", "generator", "for", "CIFAR", "-", "10", "and", "100", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/cifar.py#L62-L113
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
rlmb_ppo_base
def rlmb_ppo_base(): """HParams for PPO base.""" hparams = _rlmb_base() ppo_params = dict( base_algo="ppo", base_algo_params="ppo_original_params", # Number of real environments to train on simultaneously. real_batch_size=1, # Number of simulated environments to train on simultaneous...
python
def rlmb_ppo_base(): """HParams for PPO base.""" hparams = _rlmb_base() ppo_params = dict( base_algo="ppo", base_algo_params="ppo_original_params", # Number of real environments to train on simultaneously. real_batch_size=1, # Number of simulated environments to train on simultaneous...
[ "def", "rlmb_ppo_base", "(", ")", ":", "hparams", "=", "_rlmb_base", "(", ")", "ppo_params", "=", "dict", "(", "base_algo", "=", "\"ppo\"", ",", "base_algo_params", "=", "\"ppo_original_params\"", ",", "# Number of real environments to train on simultaneously.", "real_b...
HParams for PPO base.
[ "HParams", "for", "PPO", "base", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L138-L171
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
rlmb_dqn_base
def rlmb_dqn_base(): """rlmb_dqn_base params.""" hparams = _rlmb_base() simulated_rollout_length = 10 dqn_params = dict( base_algo="dqn", base_algo_params="dqn_original_params", real_batch_size=1, simulated_batch_size=16, dqn_agent_generates_trainable_dones=False, eval_batch_...
python
def rlmb_dqn_base(): """rlmb_dqn_base params.""" hparams = _rlmb_base() simulated_rollout_length = 10 dqn_params = dict( base_algo="dqn", base_algo_params="dqn_original_params", real_batch_size=1, simulated_batch_size=16, dqn_agent_generates_trainable_dones=False, eval_batch_...
[ "def", "rlmb_dqn_base", "(", ")", ":", "hparams", "=", "_rlmb_base", "(", ")", "simulated_rollout_length", "=", "10", "dqn_params", "=", "dict", "(", "base_algo", "=", "\"dqn\"", ",", "base_algo_params", "=", "\"dqn_original_params\"", ",", "real_batch_size", "=",...
rlmb_dqn_base params.
[ "rlmb_dqn_base", "params", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L189-L210
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
rlmb_ppo_quick
def rlmb_ppo_quick(): """Base setting but quicker with only 2 epochs.""" hparams = rlmb_ppo_base() hparams.epochs = 2 hparams.model_train_steps = 25000 hparams.ppo_epochs_num = 700 hparams.ppo_epoch_length = 50 return hparams
python
def rlmb_ppo_quick(): """Base setting but quicker with only 2 epochs.""" hparams = rlmb_ppo_base() hparams.epochs = 2 hparams.model_train_steps = 25000 hparams.ppo_epochs_num = 700 hparams.ppo_epoch_length = 50 return hparams
[ "def", "rlmb_ppo_quick", "(", ")", ":", "hparams", "=", "rlmb_ppo_base", "(", ")", "hparams", ".", "epochs", "=", "2", "hparams", ".", "model_train_steps", "=", "25000", "hparams", ".", "ppo_epochs_num", "=", "700", "hparams", ".", "ppo_epoch_length", "=", "...
Base setting but quicker with only 2 epochs.
[ "Base", "setting", "but", "quicker", "with", "only", "2", "epochs", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L234-L241
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
rlmb_base_stochastic
def rlmb_base_stochastic(): """Base setting with a stochastic next-frame model.""" hparams = rlmb_base() hparams.initial_epoch_train_steps_multiplier = 5 hparams.generative_model = "next_frame_basic_stochastic" hparams.generative_model_params = "next_frame_basic_stochastic" return hparams
python
def rlmb_base_stochastic(): """Base setting with a stochastic next-frame model.""" hparams = rlmb_base() hparams.initial_epoch_train_steps_multiplier = 5 hparams.generative_model = "next_frame_basic_stochastic" hparams.generative_model_params = "next_frame_basic_stochastic" return hparams
[ "def", "rlmb_base_stochastic", "(", ")", ":", "hparams", "=", "rlmb_base", "(", ")", "hparams", ".", "initial_epoch_train_steps_multiplier", "=", "5", "hparams", ".", "generative_model", "=", "\"next_frame_basic_stochastic\"", "hparams", ".", "generative_model_params", ...
Base setting with a stochastic next-frame model.
[ "Base", "setting", "with", "a", "stochastic", "next", "-", "frame", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L294-L300
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
rlmb_base_stochastic_discrete
def rlmb_base_stochastic_discrete(): """Base setting with stochastic discrete model.""" hparams = rlmb_base() hparams.learning_rate_bump = 1.0 hparams.grayscale = False hparams.generative_model = "next_frame_basic_stochastic_discrete" hparams.generative_model_params = "next_frame_basic_stochastic_discrete" ...
python
def rlmb_base_stochastic_discrete(): """Base setting with stochastic discrete model.""" hparams = rlmb_base() hparams.learning_rate_bump = 1.0 hparams.grayscale = False hparams.generative_model = "next_frame_basic_stochastic_discrete" hparams.generative_model_params = "next_frame_basic_stochastic_discrete" ...
[ "def", "rlmb_base_stochastic_discrete", "(", ")", ":", "hparams", "=", "rlmb_base", "(", ")", "hparams", ".", "learning_rate_bump", "=", "1.0", "hparams", ".", "grayscale", "=", "False", "hparams", ".", "generative_model", "=", "\"next_frame_basic_stochastic_discrete\...
Base setting with stochastic discrete model.
[ "Base", "setting", "with", "stochastic", "discrete", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L313-L324
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
rlmb_long_stochastic_discrete_simulation_deterministic_starts
def rlmb_long_stochastic_discrete_simulation_deterministic_starts(): """Long setting with stochastic discrete model & deterministic sim starts.""" hparams = rlmb_base_stochastic_discrete() hparams.generative_model_params = "next_frame_basic_stochastic_discrete_long" hparams.ppo_epochs_num = 1000 hparams.simul...
python
def rlmb_long_stochastic_discrete_simulation_deterministic_starts(): """Long setting with stochastic discrete model & deterministic sim starts.""" hparams = rlmb_base_stochastic_discrete() hparams.generative_model_params = "next_frame_basic_stochastic_discrete_long" hparams.ppo_epochs_num = 1000 hparams.simul...
[ "def", "rlmb_long_stochastic_discrete_simulation_deterministic_starts", "(", ")", ":", "hparams", "=", "rlmb_base_stochastic_discrete", "(", ")", "hparams", ".", "generative_model_params", "=", "\"next_frame_basic_stochastic_discrete_long\"", "hparams", ".", "ppo_epochs_num", "="...
Long setting with stochastic discrete model & deterministic sim starts.
[ "Long", "setting", "with", "stochastic", "discrete", "model", "&", "deterministic", "sim", "starts", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L403-L409
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
rlmb_long_stochastic_discrete_100steps
def rlmb_long_stochastic_discrete_100steps(): """Long setting with stochastic discrete model, changed ppo steps.""" hparams = rlmb_long_stochastic_discrete() hparams.ppo_epoch_length = 100 hparams.simulated_rollout_length = 100 hparams.simulated_batch_size = 8 return hparams
python
def rlmb_long_stochastic_discrete_100steps(): """Long setting with stochastic discrete model, changed ppo steps.""" hparams = rlmb_long_stochastic_discrete() hparams.ppo_epoch_length = 100 hparams.simulated_rollout_length = 100 hparams.simulated_batch_size = 8 return hparams
[ "def", "rlmb_long_stochastic_discrete_100steps", "(", ")", ":", "hparams", "=", "rlmb_long_stochastic_discrete", "(", ")", "hparams", ".", "ppo_epoch_length", "=", "100", "hparams", ".", "simulated_rollout_length", "=", "100", "hparams", ".", "simulated_batch_size", "="...
Long setting with stochastic discrete model, changed ppo steps.
[ "Long", "setting", "with", "stochastic", "discrete", "model", "changed", "ppo", "steps", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L413-L419
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
rlmb_long_stochastic_discrete_25steps
def rlmb_long_stochastic_discrete_25steps(): """Long setting with stochastic discrete model, changed ppo steps.""" hparams = rlmb_long_stochastic_discrete() hparams.ppo_epoch_length = 25 hparams.simulated_rollout_length = 25 hparams.simulated_batch_size = 32 return hparams
python
def rlmb_long_stochastic_discrete_25steps(): """Long setting with stochastic discrete model, changed ppo steps.""" hparams = rlmb_long_stochastic_discrete() hparams.ppo_epoch_length = 25 hparams.simulated_rollout_length = 25 hparams.simulated_batch_size = 32 return hparams
[ "def", "rlmb_long_stochastic_discrete_25steps", "(", ")", ":", "hparams", "=", "rlmb_long_stochastic_discrete", "(", ")", "hparams", ".", "ppo_epoch_length", "=", "25", "hparams", ".", "simulated_rollout_length", "=", "25", "hparams", ".", "simulated_batch_size", "=", ...
Long setting with stochastic discrete model, changed ppo steps.
[ "Long", "setting", "with", "stochastic", "discrete", "model", "changed", "ppo", "steps", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L423-L429
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
rlmb_base_stochastic_discrete_noresize
def rlmb_base_stochastic_discrete_noresize(): """Base setting with stochastic discrete model.""" hparams = rlmb_base() hparams.generative_model = "next_frame_basic_stochastic_discrete" hparams.generative_model_params = "next_frame_basic_stochastic_discrete" hparams.resize_height_factor = 1 hparams.resize_wi...
python
def rlmb_base_stochastic_discrete_noresize(): """Base setting with stochastic discrete model.""" hparams = rlmb_base() hparams.generative_model = "next_frame_basic_stochastic_discrete" hparams.generative_model_params = "next_frame_basic_stochastic_discrete" hparams.resize_height_factor = 1 hparams.resize_wi...
[ "def", "rlmb_base_stochastic_discrete_noresize", "(", ")", ":", "hparams", "=", "rlmb_base", "(", ")", "hparams", ".", "generative_model", "=", "\"next_frame_basic_stochastic_discrete\"", "hparams", ".", "generative_model_params", "=", "\"next_frame_basic_stochastic_discrete\""...
Base setting with stochastic discrete model.
[ "Base", "setting", "with", "stochastic", "discrete", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L476-L483
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
rlmb_base_sv2p
def rlmb_base_sv2p(): """Base setting with sv2p as world model.""" hparams = rlmb_base() hparams.learning_rate_bump = 1.0 hparams.generative_model = "next_frame_sv2p" hparams.generative_model_params = "next_frame_sv2p_atari" return hparams
python
def rlmb_base_sv2p(): """Base setting with sv2p as world model.""" hparams = rlmb_base() hparams.learning_rate_bump = 1.0 hparams.generative_model = "next_frame_sv2p" hparams.generative_model_params = "next_frame_sv2p_atari" return hparams
[ "def", "rlmb_base_sv2p", "(", ")", ":", "hparams", "=", "rlmb_base", "(", ")", "hparams", ".", "learning_rate_bump", "=", "1.0", "hparams", ".", "generative_model", "=", "\"next_frame_sv2p\"", "hparams", ".", "generative_model_params", "=", "\"next_frame_sv2p_atari\""...
Base setting with sv2p as world model.
[ "Base", "setting", "with", "sv2p", "as", "world", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L487-L493
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
_rlmb_tiny_overrides
def _rlmb_tiny_overrides(): """Parameters to override for tiny setting excluding agent-related hparams.""" return dict( epochs=1, num_real_env_frames=128, model_train_steps=2, max_num_noops=1, eval_max_num_noops=1, generative_model_params="next_frame_tiny", stop_loop_early=...
python
def _rlmb_tiny_overrides(): """Parameters to override for tiny setting excluding agent-related hparams.""" return dict( epochs=1, num_real_env_frames=128, model_train_steps=2, max_num_noops=1, eval_max_num_noops=1, generative_model_params="next_frame_tiny", stop_loop_early=...
[ "def", "_rlmb_tiny_overrides", "(", ")", ":", "return", "dict", "(", "epochs", "=", "1", ",", "num_real_env_frames", "=", "128", ",", "model_train_steps", "=", "2", ",", "max_num_noops", "=", "1", ",", "eval_max_num_noops", "=", "1", ",", "generative_model_par...
Parameters to override for tiny setting excluding agent-related hparams.
[ "Parameters", "to", "override", "for", "tiny", "setting", "excluding", "agent", "-", "related", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L537-L554
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
rlmb_ppo_tiny
def rlmb_ppo_tiny(): """Tiny set for testing.""" hparams = rlmb_ppo_base() hparams = hparams.override_from_dict(_rlmb_tiny_overrides()) update_hparams(hparams, dict( ppo_epochs_num=2, ppo_epoch_length=10, real_ppo_epoch_length=36, real_ppo_effective_num_agents=2, real_batch_size=1,...
python
def rlmb_ppo_tiny(): """Tiny set for testing.""" hparams = rlmb_ppo_base() hparams = hparams.override_from_dict(_rlmb_tiny_overrides()) update_hparams(hparams, dict( ppo_epochs_num=2, ppo_epoch_length=10, real_ppo_epoch_length=36, real_ppo_effective_num_agents=2, real_batch_size=1,...
[ "def", "rlmb_ppo_tiny", "(", ")", ":", "hparams", "=", "rlmb_ppo_base", "(", ")", "hparams", "=", "hparams", ".", "override_from_dict", "(", "_rlmb_tiny_overrides", "(", ")", ")", "update_hparams", "(", "hparams", ",", "dict", "(", "ppo_epochs_num", "=", "2", ...
Tiny set for testing.
[ "Tiny", "set", "for", "testing", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L558-L570
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
rlmb_dqn_tiny
def rlmb_dqn_tiny(): """Tiny set for testing.""" hparams = rlmb_dqn_base() hparams = hparams.override_from_dict(_rlmb_tiny_overrides()) update_hparams(hparams, dict( simulated_rollout_length=2, dqn_time_limit=2, dqn_num_frames=128, real_dqn_replay_buffer_replay_capacity=100, dqn_re...
python
def rlmb_dqn_tiny(): """Tiny set for testing.""" hparams = rlmb_dqn_base() hparams = hparams.override_from_dict(_rlmb_tiny_overrides()) update_hparams(hparams, dict( simulated_rollout_length=2, dqn_time_limit=2, dqn_num_frames=128, real_dqn_replay_buffer_replay_capacity=100, dqn_re...
[ "def", "rlmb_dqn_tiny", "(", ")", ":", "hparams", "=", "rlmb_dqn_base", "(", ")", "hparams", "=", "hparams", ".", "override_from_dict", "(", "_rlmb_tiny_overrides", "(", ")", ")", "update_hparams", "(", "hparams", ",", "dict", "(", "simulated_rollout_length", "=...
Tiny set for testing.
[ "Tiny", "set", "for", "testing", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L579-L592
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
rlmb_tiny_stochastic
def rlmb_tiny_stochastic(): """Tiny setting with a stochastic next-frame model.""" hparams = rlmb_ppo_tiny() hparams.epochs = 1 # Too slow with 2 for regular runs. hparams.generative_model = "next_frame_basic_stochastic" hparams.generative_model_params = "next_frame_basic_stochastic" return hparams
python
def rlmb_tiny_stochastic(): """Tiny setting with a stochastic next-frame model.""" hparams = rlmb_ppo_tiny() hparams.epochs = 1 # Too slow with 2 for regular runs. hparams.generative_model = "next_frame_basic_stochastic" hparams.generative_model_params = "next_frame_basic_stochastic" return hparams
[ "def", "rlmb_tiny_stochastic", "(", ")", ":", "hparams", "=", "rlmb_ppo_tiny", "(", ")", "hparams", ".", "epochs", "=", "1", "# Too slow with 2 for regular runs.", "hparams", ".", "generative_model", "=", "\"next_frame_basic_stochastic\"", "hparams", ".", "generative_mo...
Tiny setting with a stochastic next-frame model.
[ "Tiny", "setting", "with", "a", "stochastic", "next", "-", "frame", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L596-L602
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
rlmb_tiny_recurrent
def rlmb_tiny_recurrent(): """Tiny setting with a recurrent next-frame model.""" hparams = rlmb_ppo_tiny() hparams.epochs = 1 # Too slow with 2 for regular runs. hparams.generative_model = "next_frame_basic_recurrent" hparams.generative_model_params = "next_frame_basic_recurrent" return hparams
python
def rlmb_tiny_recurrent(): """Tiny setting with a recurrent next-frame model.""" hparams = rlmb_ppo_tiny() hparams.epochs = 1 # Too slow with 2 for regular runs. hparams.generative_model = "next_frame_basic_recurrent" hparams.generative_model_params = "next_frame_basic_recurrent" return hparams
[ "def", "rlmb_tiny_recurrent", "(", ")", ":", "hparams", "=", "rlmb_ppo_tiny", "(", ")", "hparams", ".", "epochs", "=", "1", "# Too slow with 2 for regular runs.", "hparams", ".", "generative_model", "=", "\"next_frame_basic_recurrent\"", "hparams", ".", "generative_mode...
Tiny setting with a recurrent next-frame model.
[ "Tiny", "setting", "with", "a", "recurrent", "next", "-", "frame", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L606-L612
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
rlmb_tiny_sv2p
def rlmb_tiny_sv2p(): """Tiny setting with a tiny sv2p model.""" hparams = rlmb_ppo_tiny() hparams.generative_model = "next_frame_sv2p" hparams.generative_model_params = "next_frame_sv2p_tiny" hparams.grayscale = False return hparams
python
def rlmb_tiny_sv2p(): """Tiny setting with a tiny sv2p model.""" hparams = rlmb_ppo_tiny() hparams.generative_model = "next_frame_sv2p" hparams.generative_model_params = "next_frame_sv2p_tiny" hparams.grayscale = False return hparams
[ "def", "rlmb_tiny_sv2p", "(", ")", ":", "hparams", "=", "rlmb_ppo_tiny", "(", ")", "hparams", ".", "generative_model", "=", "\"next_frame_sv2p\"", "hparams", ".", "generative_model_params", "=", "\"next_frame_sv2p_tiny\"", "hparams", ".", "grayscale", "=", "False", ...
Tiny setting with a tiny sv2p model.
[ "Tiny", "setting", "with", "a", "tiny", "sv2p", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L616-L622
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
rlmb_grid
def rlmb_grid(rhp): """Grid over games and frames, and 5 runs each for variance.""" rhp.set_categorical("loop.game", ["breakout", "pong", "freeway"]) base = 100000 medium = base // 2 small = medium // 2 rhp.set_discrete("loop.num_real_env_frames", [base, medium, small]) # Dummy parameter to get 5 runs fo...
python
def rlmb_grid(rhp): """Grid over games and frames, and 5 runs each for variance.""" rhp.set_categorical("loop.game", ["breakout", "pong", "freeway"]) base = 100000 medium = base // 2 small = medium // 2 rhp.set_discrete("loop.num_real_env_frames", [base, medium, small]) # Dummy parameter to get 5 runs fo...
[ "def", "rlmb_grid", "(", "rhp", ")", ":", "rhp", ".", "set_categorical", "(", "\"loop.game\"", ",", "[", "\"breakout\"", ",", "\"pong\"", ",", "\"freeway\"", "]", ")", "base", "=", "100000", "medium", "=", "base", "//", "2", "small", "=", "medium", "//",...
Grid over games and frames, and 5 runs each for variance.
[ "Grid", "over", "games", "and", "frames", "and", "5", "runs", "each", "for", "variance", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L638-L647
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
merge_unscoped_hparams
def merge_unscoped_hparams(scopes_and_hparams): """Merge multiple HParams into one with scopes.""" merged_values = {} for (scope, hparams) in scopes_and_hparams: for key, value in six.iteritems(hparams.values()): scoped_key = "%s.%s" % (scope, key) merged_values[scoped_key] = value return hpara...
python
def merge_unscoped_hparams(scopes_and_hparams): """Merge multiple HParams into one with scopes.""" merged_values = {} for (scope, hparams) in scopes_and_hparams: for key, value in six.iteritems(hparams.values()): scoped_key = "%s.%s" % (scope, key) merged_values[scoped_key] = value return hpara...
[ "def", "merge_unscoped_hparams", "(", "scopes_and_hparams", ")", ":", "merged_values", "=", "{", "}", "for", "(", "scope", ",", "hparams", ")", "in", "scopes_and_hparams", ":", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "hparams", ".", ...
Merge multiple HParams into one with scopes.
[ "Merge", "multiple", "HParams", "into", "one", "with", "scopes", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L855-L863
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
split_scoped_hparams
def split_scoped_hparams(scopes, merged_hparams): """Split single HParams with scoped keys into multiple.""" split_values = {scope: {} for scope in scopes} merged_values = merged_hparams.values() for scoped_key, value in six.iteritems(merged_values): scope = scoped_key.split(".")[0] key = scoped_key[len...
python
def split_scoped_hparams(scopes, merged_hparams): """Split single HParams with scoped keys into multiple.""" split_values = {scope: {} for scope in scopes} merged_values = merged_hparams.values() for scoped_key, value in six.iteritems(merged_values): scope = scoped_key.split(".")[0] key = scoped_key[len...
[ "def", "split_scoped_hparams", "(", "scopes", ",", "merged_hparams", ")", ":", "split_values", "=", "{", "scope", ":", "{", "}", "for", "scope", "in", "scopes", "}", "merged_values", "=", "merged_hparams", ".", "values", "(", ")", "for", "scoped_key", ",", ...
Split single HParams with scoped keys into multiple.
[ "Split", "single", "HParams", "with", "scoped", "keys", "into", "multiple", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L866-L877
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_based_params.py
training_loop_hparams_from_scoped_overrides
def training_loop_hparams_from_scoped_overrides(scoped_overrides, trial_id): """Create HParams suitable for training loop from scoped HParams. Args: scoped_overrides: HParams, with keys all scoped by one of HP_SCOPES. These parameters are overrides for the base HParams created by create_loop_hparam...
python
def training_loop_hparams_from_scoped_overrides(scoped_overrides, trial_id): """Create HParams suitable for training loop from scoped HParams. Args: scoped_overrides: HParams, with keys all scoped by one of HP_SCOPES. These parameters are overrides for the base HParams created by create_loop_hparam...
[ "def", "training_loop_hparams_from_scoped_overrides", "(", "scoped_overrides", ",", "trial_id", ")", ":", "trial_hp_overrides", "=", "scoped_overrides", ".", "values", "(", ")", "# Create loop, model, and ppo base HParams", "loop_hp", "=", "create_loop_hparams", "(", ")", "...
Create HParams suitable for training loop from scoped HParams. Args: scoped_overrides: HParams, with keys all scoped by one of HP_SCOPES. These parameters are overrides for the base HParams created by create_loop_hparams. trial_id: str, trial identifier. This is used to register unique HParams ...
[ "Create", "HParams", "suitable", "for", "training", "loop", "from", "scoped", "HParams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based_params.py#L880-L923
train
tensorflow/tensor2tensor
tensor2tensor/rl/player.py
PlayerEnv.get_keys_to_action
def get_keys_to_action(self): """Get mapping from keyboard keys to actions. Required by gym.utils.play in environment or top level wrapper. Returns: { Unicode code point for keyboard key: action (formatted for step()), ... } """ # Based on gym AtariEnv.get_keys_to_actio...
python
def get_keys_to_action(self): """Get mapping from keyboard keys to actions. Required by gym.utils.play in environment or top level wrapper. Returns: { Unicode code point for keyboard key: action (formatted for step()), ... } """ # Based on gym AtariEnv.get_keys_to_actio...
[ "def", "get_keys_to_action", "(", "self", ")", ":", "# Based on gym AtariEnv.get_keys_to_action()", "keyword_to_key", "=", "{", "\"UP\"", ":", "ord", "(", "\"w\"", ")", ",", "\"DOWN\"", ":", "ord", "(", "\"s\"", ")", ",", "\"LEFT\"", ":", "ord", "(", "\"a\"", ...
Get mapping from keyboard keys to actions. Required by gym.utils.play in environment or top level wrapper. Returns: { Unicode code point for keyboard key: action (formatted for step()), ... }
[ "Get", "mapping", "from", "keyboard", "keys", "to", "actions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player.py#L157-L191
train
tensorflow/tensor2tensor
tensor2tensor/rl/player.py
PlayerEnv.step
def step(self, action): """Pass action to underlying environment(s) or perform special action.""" # Special codes if action in self._player_actions(): envs_step_tuples = self._player_actions()[action]() elif self._wait and action == self.name_to_action_num["NOOP"]: # Ignore no-op, do not pas...
python
def step(self, action): """Pass action to underlying environment(s) or perform special action.""" # Special codes if action in self._player_actions(): envs_step_tuples = self._player_actions()[action]() elif self._wait and action == self.name_to_action_num["NOOP"]: # Ignore no-op, do not pas...
[ "def", "step", "(", "self", ",", "action", ")", ":", "# Special codes", "if", "action", "in", "self", ".", "_player_actions", "(", ")", ":", "envs_step_tuples", "=", "self", ".", "_player_actions", "(", ")", "[", "action", "]", "(", ")", "elif", "self", ...
Pass action to underlying environment(s) or perform special action.
[ "Pass", "action", "to", "underlying", "environment", "(", "s", ")", "or", "perform", "special", "action", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player.py#L203-L221
train
tensorflow/tensor2tensor
tensor2tensor/rl/player.py
PlayerEnv._augment_observation
def _augment_observation(self, ob, reward, cumulative_reward): """"Expand observation array with additional information header (top rows). Args: ob: observation reward: reward to be included in header. cumulative_reward: total cumulated reward to be included in header. Returns: Exp...
python
def _augment_observation(self, ob, reward, cumulative_reward): """"Expand observation array with additional information header (top rows). Args: ob: observation reward: reward to be included in header. cumulative_reward: total cumulated reward to be included in header. Returns: Exp...
[ "def", "_augment_observation", "(", "self", ",", "ob", ",", "reward", ",", "cumulative_reward", ")", ":", "img", "=", "PIL_Image", "(", ")", ".", "new", "(", "\"RGB\"", ",", "(", "ob", ".", "shape", "[", "1", "]", ",", "self", ".", "HEADER_HEIGHT", "...
Expand observation array with additional information header (top rows). Args: ob: observation reward: reward to be included in header. cumulative_reward: total cumulated reward to be included in header. Returns: Expanded observation array.
[ "Expand", "observation", "array", "with", "additional", "information", "header", "(", "top", "rows", ")", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player.py#L223-L254
train
tensorflow/tensor2tensor
tensor2tensor/rl/player.py
SimAndRealEnvPlayer._player_step_tuple
def _player_step_tuple(self, envs_step_tuples): """Construct observation, return usual step tuple. Args: envs_step_tuples: tuples. Returns: Step tuple: ob, reward, done, info ob: concatenated images [simulated observation, real observation, difference], with additional inform...
python
def _player_step_tuple(self, envs_step_tuples): """Construct observation, return usual step tuple. Args: envs_step_tuples: tuples. Returns: Step tuple: ob, reward, done, info ob: concatenated images [simulated observation, real observation, difference], with additional inform...
[ "def", "_player_step_tuple", "(", "self", ",", "envs_step_tuples", ")", ":", "ob_real", ",", "reward_real", ",", "_", ",", "_", "=", "envs_step_tuples", "[", "\"real_env\"", "]", "ob_sim", ",", "reward_sim", ",", "_", ",", "_", "=", "envs_step_tuples", "[", ...
Construct observation, return usual step tuple. Args: envs_step_tuples: tuples. Returns: Step tuple: ob, reward, done, info ob: concatenated images [simulated observation, real observation, difference], with additional informations in header. reward: real environment rewa...
[ "Construct", "observation", "return", "usual", "step", "tuple", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player.py#L345-L373
train
tensorflow/tensor2tensor
tensor2tensor/rl/player.py
SimAndRealEnvPlayer.reset
def reset(self): """Reset simulated and real environments.""" self._frame_counter = 0 ob_real = self.real_env.reset() # Initialize simulated environment with frames from real one. self.sim_env.add_to_initial_stack(ob_real) for _ in range(3): ob_real, _, _, _ = self.real_env.step(self.name_...
python
def reset(self): """Reset simulated and real environments.""" self._frame_counter = 0 ob_real = self.real_env.reset() # Initialize simulated environment with frames from real one. self.sim_env.add_to_initial_stack(ob_real) for _ in range(3): ob_real, _, _, _ = self.real_env.step(self.name_...
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_frame_counter", "=", "0", "ob_real", "=", "self", ".", "real_env", ".", "reset", "(", ")", "# Initialize simulated environment with frames from real one.", "self", ".", "sim_env", ".", "add_to_initial_stack", "...
Reset simulated and real environments.
[ "Reset", "simulated", "and", "real", "environments", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player.py#L375-L390
train
tensorflow/tensor2tensor
tensor2tensor/rl/player.py
SimAndRealEnvPlayer._step_envs
def _step_envs(self, action): """Perform step(action) on environments and update initial_frame_stack.""" self._frame_counter += 1 real_env_step_tuple = self.real_env.step(action) sim_env_step_tuple = self.sim_env.step(action) self.sim_env.add_to_initial_stack(real_env_step_tuple[0]) return self....
python
def _step_envs(self, action): """Perform step(action) on environments and update initial_frame_stack.""" self._frame_counter += 1 real_env_step_tuple = self.real_env.step(action) sim_env_step_tuple = self.sim_env.step(action) self.sim_env.add_to_initial_stack(real_env_step_tuple[0]) return self....
[ "def", "_step_envs", "(", "self", ",", "action", ")", ":", "self", ".", "_frame_counter", "+=", "1", "real_env_step_tuple", "=", "self", ".", "real_env", ".", "step", "(", "action", ")", "sim_env_step_tuple", "=", "self", ".", "sim_env", ".", "step", "(", ...
Perform step(action) on environments and update initial_frame_stack.
[ "Perform", "step", "(", "action", ")", "on", "environments", "and", "update", "initial_frame_stack", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player.py#L400-L406
train
tensorflow/tensor2tensor
tensor2tensor/rl/player.py
SingleEnvPlayer._player_step_tuple
def _player_step_tuple(self, envs_step_tuples): """Augment observation, return usual step tuple.""" ob, reward, done, info = envs_step_tuples["env"] ob = self._augment_observation(ob, reward, self.cumulative_reward) return ob, reward, done, info
python
def _player_step_tuple(self, envs_step_tuples): """Augment observation, return usual step tuple.""" ob, reward, done, info = envs_step_tuples["env"] ob = self._augment_observation(ob, reward, self.cumulative_reward) return ob, reward, done, info
[ "def", "_player_step_tuple", "(", "self", ",", "envs_step_tuples", ")", ":", "ob", ",", "reward", ",", "done", ",", "info", "=", "envs_step_tuples", "[", "\"env\"", "]", "ob", "=", "self", ".", "_augment_observation", "(", "ob", ",", "reward", ",", "self",...
Augment observation, return usual step tuple.
[ "Augment", "observation", "return", "usual", "step", "tuple", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player.py#L449-L453
train
tensorflow/tensor2tensor
tensor2tensor/layers/common_audio.py
add_delta_deltas
def add_delta_deltas(filterbanks, name=None): """Compute time first and second-order derivative channels. Args: filterbanks: float32 tensor with shape [batch_size, len, num_bins, 1] name: scope name Returns: float32 tensor with shape [batch_size, len, num_bins, 3] """ delta_filter = np.array([2,...
python
def add_delta_deltas(filterbanks, name=None): """Compute time first and second-order derivative channels. Args: filterbanks: float32 tensor with shape [batch_size, len, num_bins, 1] name: scope name Returns: float32 tensor with shape [batch_size, len, num_bins, 3] """ delta_filter = np.array([2,...
[ "def", "add_delta_deltas", "(", "filterbanks", ",", "name", "=", "None", ")", ":", "delta_filter", "=", "np", ".", "array", "(", "[", "2", ",", "1", ",", "0", ",", "-", "1", ",", "-", "2", "]", ")", "delta_delta_filter", "=", "scipy", ".", "signal"...
Compute time first and second-order derivative channels. Args: filterbanks: float32 tensor with shape [batch_size, len, num_bins, 1] name: scope name Returns: float32 tensor with shape [batch_size, len, num_bins, 3]
[ "Compute", "time", "first", "and", "second", "-", "order", "derivative", "channels", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_audio.py#L28-L52
train
tensorflow/tensor2tensor
tensor2tensor/layers/common_audio.py
compute_mel_filterbank_features
def compute_mel_filterbank_features( waveforms, sample_rate=16000, dither=1.0 / np.iinfo(np.int16).max, preemphasis=0.97, frame_length=25, frame_step=10, fft_length=None, window_fn=functools.partial(tf.contrib.signal.hann_window, periodic=True), lower_edge_hertz=80.0, upper_edge_hertz=7600.0, num_me...
python
def compute_mel_filterbank_features( waveforms, sample_rate=16000, dither=1.0 / np.iinfo(np.int16).max, preemphasis=0.97, frame_length=25, frame_step=10, fft_length=None, window_fn=functools.partial(tf.contrib.signal.hann_window, periodic=True), lower_edge_hertz=80.0, upper_edge_hertz=7600.0, num_me...
[ "def", "compute_mel_filterbank_features", "(", "waveforms", ",", "sample_rate", "=", "16000", ",", "dither", "=", "1.0", "/", "np", ".", "iinfo", "(", "np", ".", "int16", ")", ".", "max", ",", "preemphasis", "=", "0.97", ",", "frame_length", "=", "25", "...
Implement mel-filterbank extraction using tf ops. Args: waveforms: float32 tensor with shape [batch_size, max_len] sample_rate: sampling rate of the waveform dither: stddev of Gaussian noise added to waveform to prevent quantization artefacts preemphasis: waveform high-pass filtering constant ...
[ "Implement", "mel", "-", "filterbank", "extraction", "using", "tf", "ops", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_audio.py#L55-L138
train
tensorflow/tensor2tensor
tensor2tensor/envs/env_problem_utils.py
play_env_problem_randomly
def play_env_problem_randomly(env_problem, num_steps): """Plays the env problem by randomly sampling actions for `num_steps`.""" # Reset all environments. env_problem.reset() # Play all environments, sampling random actions each time. for _ in range(num_steps): # Sample batc...
python
def play_env_problem_randomly(env_problem, num_steps): """Plays the env problem by randomly sampling actions for `num_steps`.""" # Reset all environments. env_problem.reset() # Play all environments, sampling random actions each time. for _ in range(num_steps): # Sample batc...
[ "def", "play_env_problem_randomly", "(", "env_problem", ",", "num_steps", ")", ":", "# Reset all environments.", "env_problem", ".", "reset", "(", ")", "# Play all environments, sampling random actions each time.", "for", "_", "in", "range", "(", "num_steps", ")", ":", ...
Plays the env problem by randomly sampling actions for `num_steps`.
[ "Plays", "the", "env", "problem", "by", "randomly", "sampling", "actions", "for", "num_steps", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem_utils.py#L30-L46
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/cipher.py
generate_plaintext_random
def generate_plaintext_random(plain_vocab, distribution, train_samples, length): """Generates samples of text from the provided vocabulary. Args: plain_vocab: vocabulary. distribution: distribution. train_samples: samples for training. length: length. Returns: t...
python
def generate_plaintext_random(plain_vocab, distribution, train_samples, length): """Generates samples of text from the provided vocabulary. Args: plain_vocab: vocabulary. distribution: distribution. train_samples: samples for training. length: length. Returns: t...
[ "def", "generate_plaintext_random", "(", "plain_vocab", ",", "distribution", ",", "train_samples", ",", "length", ")", ":", "if", "distribution", "is", "not", "None", ":", "assert", "len", "(", "distribution", ")", "==", "len", "(", "plain_vocab", ")", "train_...
Generates samples of text from the provided vocabulary. Args: plain_vocab: vocabulary. distribution: distribution. train_samples: samples for training. length: length. Returns: train_indices (np.array of Integers): random integers for training. shape = [num_samples, length] test_indi...
[ "Generates", "samples", "of", "text", "from", "the", "provided", "vocabulary", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/cipher.py#L154-L177
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/cipher.py
encipher_shift
def encipher_shift(plaintext, plain_vocab, shift): """Encrypt plain text with a single shift layer. Args: plaintext (list of list of Strings): a list of plain text to encrypt. plain_vocab (list of Integer): unique vocabularies being used. shift (Integer): number of shift, shift to the right if shift is...
python
def encipher_shift(plaintext, plain_vocab, shift): """Encrypt plain text with a single shift layer. Args: plaintext (list of list of Strings): a list of plain text to encrypt. plain_vocab (list of Integer): unique vocabularies being used. shift (Integer): number of shift, shift to the right if shift is...
[ "def", "encipher_shift", "(", "plaintext", ",", "plain_vocab", ",", "shift", ")", ":", "ciphertext", "=", "[", "]", "cipher", "=", "ShiftEncryptionLayer", "(", "plain_vocab", ",", "shift", ")", "for", "_", ",", "sentence", "in", "enumerate", "(", "plaintext"...
Encrypt plain text with a single shift layer. Args: plaintext (list of list of Strings): a list of plain text to encrypt. plain_vocab (list of Integer): unique vocabularies being used. shift (Integer): number of shift, shift to the right if shift is positive. Returns: ciphertext (list of Strings): ...
[ "Encrypt", "plain", "text", "with", "a", "single", "shift", "layer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/cipher.py#L180-L200
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/cipher.py
encipher_vigenere
def encipher_vigenere(plaintext, plain_vocab, key): """Encrypt plain text with given key. Args: plaintext (list of list of Strings): a list of plain text to encrypt. plain_vocab (list of Integer): unique vocabularies being used. key (list of Integer): key to encrypt cipher using Vigenere table. Retu...
python
def encipher_vigenere(plaintext, plain_vocab, key): """Encrypt plain text with given key. Args: plaintext (list of list of Strings): a list of plain text to encrypt. plain_vocab (list of Integer): unique vocabularies being used. key (list of Integer): key to encrypt cipher using Vigenere table. Retu...
[ "def", "encipher_vigenere", "(", "plaintext", ",", "plain_vocab", ",", "key", ")", ":", "ciphertext", "=", "[", "]", "# generate Vigenere table", "layers", "=", "[", "ShiftEncryptionLayer", "(", "plain_vocab", ",", "i", ")", "for", "i", "in", "range", "(", "...
Encrypt plain text with given key. Args: plaintext (list of list of Strings): a list of plain text to encrypt. plain_vocab (list of Integer): unique vocabularies being used. key (list of Integer): key to encrypt cipher using Vigenere table. Returns: ciphertext (list of Strings): encrypted plain te...
[ "Encrypt", "plain", "text", "with", "given", "key", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/cipher.py#L203-L228
train
tensorflow/tensor2tensor
tensor2tensor/models/research/super_lm.py
_super_stack
def _super_stack(inputs, attention_bias, hparams, mp, padding="LEFT"): """A stack of super_lm layers. Args: inputs: a list of Tensors attention_bias: list of bias Tensor for self-attention (see common_attention.attention_bias()) ...
python
def _super_stack(inputs, attention_bias, hparams, mp, padding="LEFT"): """A stack of super_lm layers. Args: inputs: a list of Tensors attention_bias: list of bias Tensor for self-attention (see common_attention.attention_bias()) ...
[ "def", "_super_stack", "(", "inputs", ",", "attention_bias", ",", "hparams", ",", "mp", ",", "padding", "=", "\"LEFT\"", ")", ":", "layers", "=", "hparams", ".", "layers", ".", "strip", "(", "\",\"", ")", ".", "split", "(", "\",\"", ")", "moe_hidden_size...
A stack of super_lm layers. Args: inputs: a list of Tensors attention_bias: list of bias Tensor for self-attention (see common_attention.attention_bias()) hparams: hyperparameters for model mp: a Parallelism object padding: a string Returns: y: a list of Tensors extra_loss: an op...
[ "A", "stack", "of", "super_lm", "layers", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/super_lm.py#L126-L237
train
tensorflow/tensor2tensor
tensor2tensor/models/research/super_lm.py
super_lm_base
def super_lm_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.hidden_size = 512 hparams.moe_hidden_sizes = "512" hparams.batch_size = 16384 hparams.max_length = 0 # All hyperparameters ending in "dropout" are automatically set to 0.0 # when not in training mode. h...
python
def super_lm_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.hidden_size = 512 hparams.moe_hidden_sizes = "512" hparams.batch_size = 16384 hparams.max_length = 0 # All hyperparameters ending in "dropout" are automatically set to 0.0 # when not in training mode. h...
[ "def", "super_lm_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", "moe_hidden_sizes", "=", "\"512\"", "hparams", ".", "batch_size", "=", "16384", "hparams", ".", ...
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/super_lm.py#L241-L288
train
tensorflow/tensor2tensor
tensor2tensor/models/research/super_lm.py
super_lm_moe
def super_lm_moe(): """Add mixture of experts with ~1B params.""" hparams = super_lm_base() hparams.layers = ( ("n,att,m,d,a," "n,moe,m,d,a,") * 4 + "n,ffn,d") hparams.moe_num_experts = 32 hparams.moe_hidden_sizes = "1024" return hparams
python
def super_lm_moe(): """Add mixture of experts with ~1B params.""" hparams = super_lm_base() hparams.layers = ( ("n,att,m,d,a," "n,moe,m,d,a,") * 4 + "n,ffn,d") hparams.moe_num_experts = 32 hparams.moe_hidden_sizes = "1024" return hparams
[ "def", "super_lm_moe", "(", ")", ":", "hparams", "=", "super_lm_base", "(", ")", "hparams", ".", "layers", "=", "(", "(", "\"n,att,m,d,a,\"", "\"n,moe,m,d,a,\"", ")", "*", "4", "+", "\"n,ffn,d\"", ")", "hparams", ".", "moe_num_experts", "=", "32", "hparams",...
Add mixture of experts with ~1B params.
[ "Add", "mixture", "of", "experts", "with", "~1B", "params", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/super_lm.py#L334-L341
train
tensorflow/tensor2tensor
tensor2tensor/models/research/moe_experiments.py
xmoe_tr_dense_2k
def xmoe_tr_dense_2k(): """Series of architectural experiments on Translation. # run on 8-core setup 119M params, einsum=0.95e13 Returns: a hparams """ hparams = mtf_transformer2.mtf_bitransformer_base() hparams.encoder_layers = ["self_att", "drd"] * 4 hparams.decoder_layers = ["self_att", "enc_a...
python
def xmoe_tr_dense_2k(): """Series of architectural experiments on Translation. # run on 8-core setup 119M params, einsum=0.95e13 Returns: a hparams """ hparams = mtf_transformer2.mtf_bitransformer_base() hparams.encoder_layers = ["self_att", "drd"] * 4 hparams.decoder_layers = ["self_att", "enc_a...
[ "def", "xmoe_tr_dense_2k", "(", ")", ":", "hparams", "=", "mtf_transformer2", ".", "mtf_bitransformer_base", "(", ")", "hparams", ".", "encoder_layers", "=", "[", "\"self_att\"", ",", "\"drd\"", "]", "*", "4", "hparams", ".", "decoder_layers", "=", "[", "\"sel...
Series of architectural experiments on Translation. # run on 8-core setup 119M params, einsum=0.95e13 Returns: a hparams
[ "Series", "of", "architectural", "experiments", "on", "Translation", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe_experiments.py#L30-L46
train
tensorflow/tensor2tensor
tensor2tensor/models/research/moe_experiments.py
xmoe_tr_1d
def xmoe_tr_1d(): """Mixture of experts (16 experts). 623M Params, einsum=1.09e13 Returns: a hparams """ hparams = xmoe_tr_dense_2k() hparams.encoder_layers = ["self_att", "moe_1d"] * 4 hparams.decoder_layers = ["self_att", "enc_att", "moe_1d"] * 4 hparams.layout = "batch:batch;experts:batch" h...
python
def xmoe_tr_1d(): """Mixture of experts (16 experts). 623M Params, einsum=1.09e13 Returns: a hparams """ hparams = xmoe_tr_dense_2k() hparams.encoder_layers = ["self_att", "moe_1d"] * 4 hparams.decoder_layers = ["self_att", "enc_att", "moe_1d"] * 4 hparams.layout = "batch:batch;experts:batch" h...
[ "def", "xmoe_tr_1d", "(", ")", ":", "hparams", "=", "xmoe_tr_dense_2k", "(", ")", "hparams", ".", "encoder_layers", "=", "[", "\"self_att\"", ",", "\"moe_1d\"", "]", "*", "4", "hparams", ".", "decoder_layers", "=", "[", "\"self_att\"", ",", "\"enc_att\"", ",...
Mixture of experts (16 experts). 623M Params, einsum=1.09e13 Returns: a hparams
[ "Mixture", "of", "experts", "(", "16", "experts", ")", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe_experiments.py#L64-L79
train
tensorflow/tensor2tensor
tensor2tensor/models/research/moe_experiments.py
xmoe_tr_2d
def xmoe_tr_2d(): """Mixture of experts (16 experts). 623M Params, einsum=1.09e13 Returns: a hparams """ hparams = xmoe_tr_dense_2k() hparams.mesh_shape = "b0:2;b1:4" hparams.outer_batch_size = 4 hparams.layout = "outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0" hparams.encoder_layers = ["...
python
def xmoe_tr_2d(): """Mixture of experts (16 experts). 623M Params, einsum=1.09e13 Returns: a hparams """ hparams = xmoe_tr_dense_2k() hparams.mesh_shape = "b0:2;b1:4" hparams.outer_batch_size = 4 hparams.layout = "outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0" hparams.encoder_layers = ["...
[ "def", "xmoe_tr_2d", "(", ")", ":", "hparams", "=", "xmoe_tr_dense_2k", "(", ")", "hparams", ".", "mesh_shape", "=", "\"b0:2;b1:4\"", "hparams", ".", "outer_batch_size", "=", "4", "hparams", ".", "layout", "=", "\"outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0\...
Mixture of experts (16 experts). 623M Params, einsum=1.09e13 Returns: a hparams
[ "Mixture", "of", "experts", "(", "16", "experts", ")", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe_experiments.py#L83-L100
train
tensorflow/tensor2tensor
tensor2tensor/models/research/moe_experiments.py
xmoe_dense_4k
def xmoe_dense_4k(): """Series of architectural experiments on cheap language models. For all of these architectures, we run on languagemodel_lm1b8k_packed for 32000 steps. All log-perplexities are per-token - multiply by 1.298 for per-word Results: model params(M) einsum alltoall mxu-util...
python
def xmoe_dense_4k(): """Series of architectural experiments on cheap language models. For all of these architectures, we run on languagemodel_lm1b8k_packed for 32000 steps. All log-perplexities are per-token - multiply by 1.298 for per-word Results: model params(M) einsum alltoall mxu-util...
[ "def", "xmoe_dense_4k", "(", ")", ":", "hparams", "=", "mtf_transformer", ".", "mtf_transformer_base_lm", "(", ")", "hparams", ".", "attention_dropout", "=", "0.0", "hparams", ".", "relu_dropout", "=", "0.0", "hparams", ".", "layer_prepostprocess_dropout", "=", "0...
Series of architectural experiments on cheap language models. For all of these architectures, we run on languagemodel_lm1b8k_packed for 32000 steps. All log-perplexities are per-token - multiply by 1.298 for per-word Results: model params(M) einsum alltoall mxu-util log-ppl xmoe_dense_4k ...
[ "Series", "of", "architectural", "experiments", "on", "cheap", "language", "models", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe_experiments.py#L104-L147
train
tensorflow/tensor2tensor
tensor2tensor/models/research/moe_experiments.py
xmoe_top_2
def xmoe_top_2(): """Mixture of experts (16 experts).""" hparams = xmoe_dense_4k() moe.set_default_moe_hparams(hparams) hparams.mesh_shape = "all:8" hparams.layout = "batch:all;experts:all" return hparams
python
def xmoe_top_2(): """Mixture of experts (16 experts).""" hparams = xmoe_dense_4k() moe.set_default_moe_hparams(hparams) hparams.mesh_shape = "all:8" hparams.layout = "batch:all;experts:all" return hparams
[ "def", "xmoe_top_2", "(", ")", ":", "hparams", "=", "xmoe_dense_4k", "(", ")", "moe", ".", "set_default_moe_hparams", "(", "hparams", ")", "hparams", ".", "mesh_shape", "=", "\"all:8\"", "hparams", ".", "layout", "=", "\"batch:all;experts:all\"", "return", "hpar...
Mixture of experts (16 experts).
[ "Mixture", "of", "experts", "(", "16", "experts", ")", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe_experiments.py#L167-L173
train
tensorflow/tensor2tensor
tensor2tensor/models/research/moe_experiments.py
xmoe_2d
def xmoe_2d(): """Two-dimensional hierarchical mixture of 16 experts.""" hparams = xmoe_top_2() hparams.decoder_layers = ["att", "hmoe"] * 4 hparams.mesh_shape = "b0:2;b1:4" hparams.outer_batch_size = 4 hparams.layout = "outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0" hparams.moe_num_experts = [4, ...
python
def xmoe_2d(): """Two-dimensional hierarchical mixture of 16 experts.""" hparams = xmoe_top_2() hparams.decoder_layers = ["att", "hmoe"] * 4 hparams.mesh_shape = "b0:2;b1:4" hparams.outer_batch_size = 4 hparams.layout = "outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0" hparams.moe_num_experts = [4, ...
[ "def", "xmoe_2d", "(", ")", ":", "hparams", "=", "xmoe_top_2", "(", ")", "hparams", ".", "decoder_layers", "=", "[", "\"att\"", ",", "\"hmoe\"", "]", "*", "4", "hparams", ".", "mesh_shape", "=", "\"b0:2;b1:4\"", "hparams", ".", "outer_batch_size", "=", "4"...
Two-dimensional hierarchical mixture of 16 experts.
[ "Two", "-", "dimensional", "hierarchical", "mixture", "of", "16", "experts", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe_experiments.py#L185-L193
train
tensorflow/tensor2tensor
tensor2tensor/models/research/moe_experiments.py
xmoe2_dense
def xmoe2_dense(sz): """Series of architectural experiments on language modeling. Larger models than the ones above. All models are trained on sequences of 1024 tokens. We assume infinite training data, so no dropout necessary. We process 2^36 tokens in training = 524288 steps at batch size 128 TODO(noa...
python
def xmoe2_dense(sz): """Series of architectural experiments on language modeling. Larger models than the ones above. All models are trained on sequences of 1024 tokens. We assume infinite training data, so no dropout necessary. We process 2^36 tokens in training = 524288 steps at batch size 128 TODO(noa...
[ "def", "xmoe2_dense", "(", "sz", ")", ":", "hparams", "=", "mtf_transformer", ".", "mtf_transformer_paper_lm", "(", "sz", ")", "hparams", ".", "attention_dropout", "=", "0.0", "hparams", ".", "relu_dropout", "=", "0.0", "hparams", ".", "layer_prepostprocess_dropou...
Series of architectural experiments on language modeling. Larger models than the ones above. All models are trained on sequences of 1024 tokens. We assume infinite training data, so no dropout necessary. We process 2^36 tokens in training = 524288 steps at batch size 128 TODO(noam): find a large enough da...
[ "Series", "of", "architectural", "experiments", "on", "language", "modeling", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe_experiments.py#L232-L267
train
tensorflow/tensor2tensor
tensor2tensor/models/research/moe_experiments.py
xmoe2_v1
def xmoe2_v1(): """Model incorporating mixture-of-experts and local-attention. ~6B parameters 32 experts in 3 hierarchichal moe layers. Returns: a hparams """ hparams = xmoe2_dense(0) moe.set_default_moe_hparams(hparams) hparams.decoder_layers = ( ["local_att", "local_att", "drd", "a...
python
def xmoe2_v1(): """Model incorporating mixture-of-experts and local-attention. ~6B parameters 32 experts in 3 hierarchichal moe layers. Returns: a hparams """ hparams = xmoe2_dense(0) moe.set_default_moe_hparams(hparams) hparams.decoder_layers = ( ["local_att", "local_att", "drd", "a...
[ "def", "xmoe2_v1", "(", ")", ":", "hparams", "=", "xmoe2_dense", "(", "0", ")", "moe", ".", "set_default_moe_hparams", "(", "hparams", ")", "hparams", ".", "decoder_layers", "=", "(", "[", "\"local_att\"", ",", "\"local_att\"", ",", "\"drd\"", ",", "\"att\""...
Model incorporating mixture-of-experts and local-attention. ~6B parameters 32 experts in 3 hierarchichal moe layers. Returns: a hparams
[ "Model", "incorporating", "mixture", "-", "of", "-", "experts", "and", "local", "-", "attention", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe_experiments.py#L291-L314
train
tensorflow/tensor2tensor
tensor2tensor/models/research/moe_experiments.py
xmoe2_v1_x128
def xmoe2_v1_x128(): """128 experts, ~25B params - Train for 131072 steps on 8x8.""" hparams = xmoe2_v1() hparams.moe_num_experts = [16, 8] hparams.outer_batch_size = 8 hparams.mesh_shape = "b0:8;b1:16" hparams.batch_size = 512 hparams.learning_rate_decay_steps = 16384 return hparams
python
def xmoe2_v1_x128(): """128 experts, ~25B params - Train for 131072 steps on 8x8.""" hparams = xmoe2_v1() hparams.moe_num_experts = [16, 8] hparams.outer_batch_size = 8 hparams.mesh_shape = "b0:8;b1:16" hparams.batch_size = 512 hparams.learning_rate_decay_steps = 16384 return hparams
[ "def", "xmoe2_v1_x128", "(", ")", ":", "hparams", "=", "xmoe2_v1", "(", ")", "hparams", ".", "moe_num_experts", "=", "[", "16", ",", "8", "]", "hparams", ".", "outer_batch_size", "=", "8", "hparams", ".", "mesh_shape", "=", "\"b0:8;b1:16\"", "hparams", "."...
128 experts, ~25B params - Train for 131072 steps on 8x8.
[ "128", "experts", "~25B", "params", "-", "Train", "for", "131072", "steps", "on", "8x8", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe_experiments.py#L318-L326
train
tensorflow/tensor2tensor
tensor2tensor/models/research/moe_experiments.py
xmoe2_tiny
def xmoe2_tiny(): """Test on local cpu.""" hparams = xmoe2_v1() hparams.decoder_layers = [ "local_att", "att", "compressed_att", "drd", "hmoe"] hparams.d_model = 128 hparams.moe_hidden_size = 512 hparams.outer_batch_size = 0 hparams.batch_size = 2 hparams.mesh_shape = "" hparams.activation_dtype...
python
def xmoe2_tiny(): """Test on local cpu.""" hparams = xmoe2_v1() hparams.decoder_layers = [ "local_att", "att", "compressed_att", "drd", "hmoe"] hparams.d_model = 128 hparams.moe_hidden_size = 512 hparams.outer_batch_size = 0 hparams.batch_size = 2 hparams.mesh_shape = "" hparams.activation_dtype...
[ "def", "xmoe2_tiny", "(", ")", ":", "hparams", "=", "xmoe2_v1", "(", ")", "hparams", ".", "decoder_layers", "=", "[", "\"local_att\"", ",", "\"att\"", ",", "\"compressed_att\"", ",", "\"drd\"", ",", "\"hmoe\"", "]", "hparams", ".", "d_model", "=", "128", "...
Test on local cpu.
[ "Test", "on", "local", "cpu", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe_experiments.py#L330-L341
train
tensorflow/tensor2tensor
tensor2tensor/models/research/moe_experiments.py
xmoe2_v1_l4k
def xmoe2_v1_l4k(): """With sequence length 4096.""" hparams = xmoe2_v1() hparams.batch_size = 32 hparams.max_length = 4096 hparams.split_to_length = 4096 hparams.reshape_logits_hack = True return hparams
python
def xmoe2_v1_l4k(): """With sequence length 4096.""" hparams = xmoe2_v1() hparams.batch_size = 32 hparams.max_length = 4096 hparams.split_to_length = 4096 hparams.reshape_logits_hack = True return hparams
[ "def", "xmoe2_v1_l4k", "(", ")", ":", "hparams", "=", "xmoe2_v1", "(", ")", "hparams", ".", "batch_size", "=", "32", "hparams", ".", "max_length", "=", "4096", "hparams", ".", "split_to_length", "=", "4096", "hparams", ".", "reshape_logits_hack", "=", "True"...
With sequence length 4096.
[ "With", "sequence", "length", "4096", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe_experiments.py#L345-L352
train
tensorflow/tensor2tensor
tensor2tensor/models/research/moe_experiments.py
xmoe2_v1_l4k_local_only
def xmoe2_v1_l4k_local_only(): """With sequence length 4096.""" hparams = xmoe2_v1_l4k() hparams.decoder_layers = [ "local_att" if l == "att" else l for l in hparams.decoder_layers] return hparams
python
def xmoe2_v1_l4k_local_only(): """With sequence length 4096.""" hparams = xmoe2_v1_l4k() hparams.decoder_layers = [ "local_att" if l == "att" else l for l in hparams.decoder_layers] return hparams
[ "def", "xmoe2_v1_l4k_local_only", "(", ")", ":", "hparams", "=", "xmoe2_v1_l4k", "(", ")", "hparams", ".", "decoder_layers", "=", "[", "\"local_att\"", "if", "l", "==", "\"att\"", "else", "l", "for", "l", "in", "hparams", ".", "decoder_layers", "]", "return"...
With sequence length 4096.
[ "With", "sequence", "length", "4096", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe_experiments.py#L356-L361
train
tensorflow/tensor2tensor
tensor2tensor/models/research/moe_experiments.py
xmoe2_v1_l4k_global_only
def xmoe2_v1_l4k_global_only(): """With sequence length 4096.""" hparams = xmoe2_v1_l4k() hparams.decoder_layers = [ "att" if l == "local_att" else l for l in hparams.decoder_layers] return hparams
python
def xmoe2_v1_l4k_global_only(): """With sequence length 4096.""" hparams = xmoe2_v1_l4k() hparams.decoder_layers = [ "att" if l == "local_att" else l for l in hparams.decoder_layers] return hparams
[ "def", "xmoe2_v1_l4k_global_only", "(", ")", ":", "hparams", "=", "xmoe2_v1_l4k", "(", ")", "hparams", ".", "decoder_layers", "=", "[", "\"att\"", "if", "l", "==", "\"local_att\"", "else", "l", "for", "l", "in", "hparams", ".", "decoder_layers", "]", "return...
With sequence length 4096.
[ "With", "sequence", "length", "4096", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe_experiments.py#L365-L370
train
tensorflow/tensor2tensor
tensor2tensor/models/research/moe_experiments.py
xmoe2_v1_l4k_compressed_c4
def xmoe2_v1_l4k_compressed_c4(): """With compressed attention.""" hparams = xmoe2_v1_l4k() hparams.decoder_layers = [ "compressed_att" if l == "att" else l for l in hparams.decoder_layers] hparams.compression_factor = 4 return hparams
python
def xmoe2_v1_l4k_compressed_c4(): """With compressed attention.""" hparams = xmoe2_v1_l4k() hparams.decoder_layers = [ "compressed_att" if l == "att" else l for l in hparams.decoder_layers] hparams.compression_factor = 4 return hparams
[ "def", "xmoe2_v1_l4k_compressed_c4", "(", ")", ":", "hparams", "=", "xmoe2_v1_l4k", "(", ")", "hparams", ".", "decoder_layers", "=", "[", "\"compressed_att\"", "if", "l", "==", "\"att\"", "else", "l", "for", "l", "in", "hparams", ".", "decoder_layers", "]", ...
With compressed attention.
[ "With", "compressed", "attention", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe_experiments.py#L374-L380
train
tensorflow/tensor2tensor
tensor2tensor/models/research/moe_experiments.py
wiki_2x2_base
def wiki_2x2_base(): """Set of architectural experiments - language model on wikipedia on a 2x2. 1 epoch = ~180k steps at batch size 32 - we may never finish an epoch! Returns: a hparams """ hparams = mtf_transformer.mtf_transformer_base_lm() hparams.shared_embedding_and_softmax_weights = False # no...
python
def wiki_2x2_base(): """Set of architectural experiments - language model on wikipedia on a 2x2. 1 epoch = ~180k steps at batch size 32 - we may never finish an epoch! Returns: a hparams """ hparams = mtf_transformer.mtf_transformer_base_lm() hparams.shared_embedding_and_softmax_weights = False # no...
[ "def", "wiki_2x2_base", "(", ")", ":", "hparams", "=", "mtf_transformer", ".", "mtf_transformer_base_lm", "(", ")", "hparams", ".", "shared_embedding_and_softmax_weights", "=", "False", "# no dropout - dataset is big enough to avoid overfitting.", "hparams", ".", "attention_d...
Set of architectural experiments - language model on wikipedia on a 2x2. 1 epoch = ~180k steps at batch size 32 - we may never finish an epoch! Returns: a hparams
[ "Set", "of", "architectural", "experiments", "-", "language", "model", "on", "wikipedia", "on", "a", "2x2", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe_experiments.py#L392-L427
train
tensorflow/tensor2tensor
tensor2tensor/models/research/moe_experiments.py
denoise_z15
def denoise_z15(): """Replace tokens instead of masking.""" hparams = xmoe2_dense_0() hparams.decoder_type = "denoising" hparams.noising_spec_train = {"type": "random_zipfian", "prob": 0.15} hparams.noising_use_eval_during_train = 0.25 return hparams
python
def denoise_z15(): """Replace tokens instead of masking.""" hparams = xmoe2_dense_0() hparams.decoder_type = "denoising" hparams.noising_spec_train = {"type": "random_zipfian", "prob": 0.15} hparams.noising_use_eval_during_train = 0.25 return hparams
[ "def", "denoise_z15", "(", ")", ":", "hparams", "=", "xmoe2_dense_0", "(", ")", "hparams", ".", "decoder_type", "=", "\"denoising\"", "hparams", ".", "noising_spec_train", "=", "{", "\"type\"", ":", "\"random_zipfian\"", ",", "\"prob\"", ":", "0.15", "}", "hpa...
Replace tokens instead of masking.
[ "Replace", "tokens", "instead", "of", "masking", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe_experiments.py#L474-L480
train
tensorflow/tensor2tensor
tensor2tensor/models/research/moe_experiments.py
denoise_v1_m15
def denoise_v1_m15(): """Denoising experiment.""" hparams = xmoe2_v1() # no local attention # TODO(noam): non-masked version of local-attention hparams.decoder_layers = [ "att" if l == "local_att" else l for l in hparams.decoder_layers] hparams.decoder_type = "denoising" hparams.noising_spec_train =...
python
def denoise_v1_m15(): """Denoising experiment.""" hparams = xmoe2_v1() # no local attention # TODO(noam): non-masked version of local-attention hparams.decoder_layers = [ "att" if l == "local_att" else l for l in hparams.decoder_layers] hparams.decoder_type = "denoising" hparams.noising_spec_train =...
[ "def", "denoise_v1_m15", "(", ")", ":", "hparams", "=", "xmoe2_v1", "(", ")", "# no local attention", "# TODO(noam): non-masked version of local-attention", "hparams", ".", "decoder_layers", "=", "[", "\"att\"", "if", "l", "==", "\"local_att\"", "else", "l", "for", ...
Denoising experiment.
[ "Denoising", "experiment", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe_experiments.py#L503-L512
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math_two_variables.py
_download_mlu_data
def _download_mlu_data(tmp_dir, data_dir): """Downloads and extracts the dataset. Args: tmp_dir: temp directory to download and extract the dataset data_dir: The base directory where data and vocab files are stored. Returns: tmp_dir: temp directory containing the raw data. """ if not tf.gfile.Ex...
python
def _download_mlu_data(tmp_dir, data_dir): """Downloads and extracts the dataset. Args: tmp_dir: temp directory to download and extract the dataset data_dir: The base directory where data and vocab files are stored. Returns: tmp_dir: temp directory containing the raw data. """ if not tf.gfile.Ex...
[ "def", "_download_mlu_data", "(", "tmp_dir", ",", "data_dir", ")", ":", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "data_dir", ")", ":", "tf", ".", "gfile", ".", "MakeDirs", "(", "data_dir", ")", "filename", "=", "os", ".", "path", ".", "ba...
Downloads and extracts the dataset. Args: tmp_dir: temp directory to download and extract the dataset data_dir: The base directory where data and vocab files are stored. Returns: tmp_dir: temp directory containing the raw data.
[ "Downloads", "and", "extracts", "the", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math_two_variables.py#L60-L85
train
tensorflow/tensor2tensor
tensor2tensor/utils/sari_hook.py
_get_ngram_counter
def _get_ngram_counter(ids, n): """Get a Counter with the ngrams of the given ID list. Args: ids: np.array or a list corresponding to a single sentence n: n-gram size Returns: collections.Counter with ID tuples as keys and 1s as values. """ # Remove zero IDs used to pad the sequence. ids = [to...
python
def _get_ngram_counter(ids, n): """Get a Counter with the ngrams of the given ID list. Args: ids: np.array or a list corresponding to a single sentence n: n-gram size Returns: collections.Counter with ID tuples as keys and 1s as values. """ # Remove zero IDs used to pad the sequence. ids = [to...
[ "def", "_get_ngram_counter", "(", "ids", ",", "n", ")", ":", "# Remove zero IDs used to pad the sequence.", "ids", "=", "[", "token_id", "for", "token_id", "in", "ids", "if", "token_id", "!=", "0", "]", "ngram_list", "=", "[", "tuple", "(", "ids", "[", "i", ...
Get a Counter with the ngrams of the given ID list. Args: ids: np.array or a list corresponding to a single sentence n: n-gram size Returns: collections.Counter with ID tuples as keys and 1s as values.
[ "Get", "a", "Counter", "with", "the", "ngrams", "of", "the", "given", "ID", "list", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/sari_hook.py#L50-L67
train
tensorflow/tensor2tensor
tensor2tensor/utils/sari_hook.py
_get_fbeta_score
def _get_fbeta_score(true_positives, selected, relevant, beta=1): """Compute Fbeta score. Args: true_positives: Number of true positive ngrams. selected: Number of selected ngrams. relevant: Number of relevant ngrams. beta: 0 gives precision only, 1 gives F1 score, and Inf gives recall only. Ret...
python
def _get_fbeta_score(true_positives, selected, relevant, beta=1): """Compute Fbeta score. Args: true_positives: Number of true positive ngrams. selected: Number of selected ngrams. relevant: Number of relevant ngrams. beta: 0 gives precision only, 1 gives F1 score, and Inf gives recall only. Ret...
[ "def", "_get_fbeta_score", "(", "true_positives", ",", "selected", ",", "relevant", ",", "beta", "=", "1", ")", ":", "precision", "=", "1", "if", "selected", ">", "0", ":", "precision", "=", "true_positives", "/", "selected", "if", "beta", "==", "0", ":"...
Compute Fbeta score. Args: true_positives: Number of true positive ngrams. selected: Number of selected ngrams. relevant: Number of relevant ngrams. beta: 0 gives precision only, 1 gives F1 score, and Inf gives recall only. Returns: Fbeta score.
[ "Compute", "Fbeta", "score", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/sari_hook.py#L70-L94
train
tensorflow/tensor2tensor
tensor2tensor/utils/sari_hook.py
get_addition_score
def get_addition_score(source_counts, prediction_counts, target_counts): """Compute the addition score (Equation 4 in the paper).""" added_to_prediction_counts = prediction_counts - source_counts true_positives = sum((added_to_prediction_counts & target_counts).values()) selected = sum(added_to_prediction_count...
python
def get_addition_score(source_counts, prediction_counts, target_counts): """Compute the addition score (Equation 4 in the paper).""" added_to_prediction_counts = prediction_counts - source_counts true_positives = sum((added_to_prediction_counts & target_counts).values()) selected = sum(added_to_prediction_count...
[ "def", "get_addition_score", "(", "source_counts", ",", "prediction_counts", ",", "target_counts", ")", ":", "added_to_prediction_counts", "=", "prediction_counts", "-", "source_counts", "true_positives", "=", "sum", "(", "(", "added_to_prediction_counts", "&", "target_co...
Compute the addition score (Equation 4 in the paper).
[ "Compute", "the", "addition", "score", "(", "Equation", "4", "in", "the", "paper", ")", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/sari_hook.py#L97-L107
train
tensorflow/tensor2tensor
tensor2tensor/utils/sari_hook.py
get_keep_score
def get_keep_score(source_counts, prediction_counts, target_counts): """Compute the keep score (Equation 5 in the paper).""" source_and_prediction_counts = source_counts & prediction_counts source_and_target_counts = source_counts & target_counts true_positives = sum((source_and_prediction_counts & ...
python
def get_keep_score(source_counts, prediction_counts, target_counts): """Compute the keep score (Equation 5 in the paper).""" source_and_prediction_counts = source_counts & prediction_counts source_and_target_counts = source_counts & target_counts true_positives = sum((source_and_prediction_counts & ...
[ "def", "get_keep_score", "(", "source_counts", ",", "prediction_counts", ",", "target_counts", ")", ":", "source_and_prediction_counts", "=", "source_counts", "&", "prediction_counts", "source_and_target_counts", "=", "source_counts", "&", "target_counts", "true_positives", ...
Compute the keep score (Equation 5 in the paper).
[ "Compute", "the", "keep", "score", "(", "Equation", "5", "in", "the", "paper", ")", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/sari_hook.py#L110-L118
train
tensorflow/tensor2tensor
tensor2tensor/utils/sari_hook.py
get_deletion_score
def get_deletion_score(source_counts, prediction_counts, target_counts, beta=0): """Compute the deletion score (Equation 6 in the paper).""" source_not_prediction_counts = source_counts - prediction_counts source_not_target_counts = source_counts - target_counts true_positives = sum((source_not_prediction_count...
python
def get_deletion_score(source_counts, prediction_counts, target_counts, beta=0): """Compute the deletion score (Equation 6 in the paper).""" source_not_prediction_counts = source_counts - prediction_counts source_not_target_counts = source_counts - target_counts true_positives = sum((source_not_prediction_count...
[ "def", "get_deletion_score", "(", "source_counts", ",", "prediction_counts", ",", "target_counts", ",", "beta", "=", "0", ")", ":", "source_not_prediction_counts", "=", "source_counts", "-", "prediction_counts", "source_not_target_counts", "=", "source_counts", "-", "ta...
Compute the deletion score (Equation 6 in the paper).
[ "Compute", "the", "deletion", "score", "(", "Equation", "6", "in", "the", "paper", ")", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/sari_hook.py#L121-L129
train
tensorflow/tensor2tensor
tensor2tensor/utils/sari_hook.py
get_sari_score
def get_sari_score(source_ids, prediction_ids, list_of_targets, max_gram_size=4, beta_for_deletion=0): """Compute the SARI score for a single prediction and one or more targets. Args: source_ids: a list / np.array of SentencePiece IDs prediction_ids: a list / np.array of SentencePiece ID...
python
def get_sari_score(source_ids, prediction_ids, list_of_targets, max_gram_size=4, beta_for_deletion=0): """Compute the SARI score for a single prediction and one or more targets. Args: source_ids: a list / np.array of SentencePiece IDs prediction_ids: a list / np.array of SentencePiece ID...
[ "def", "get_sari_score", "(", "source_ids", ",", "prediction_ids", ",", "list_of_targets", ",", "max_gram_size", "=", "4", ",", "beta_for_deletion", "=", "0", ")", ":", "addition_scores", "=", "[", "]", "keep_scores", "=", "[", "]", "deletion_scores", "=", "["...
Compute the SARI score for a single prediction and one or more targets. Args: source_ids: a list / np.array of SentencePiece IDs prediction_ids: a list / np.array of SentencePiece IDs list_of_targets: a list of target ID lists / np.arrays max_gram_size: int. largest n-gram size we care about (e.g. 3 ...
[ "Compute", "the", "SARI", "score", "for", "a", "single", "prediction", "and", "one", "or", "more", "targets", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/sari_hook.py#L132-L179
train
tensorflow/tensor2tensor
tensor2tensor/utils/sari_hook.py
get_sari
def get_sari(source_ids, prediction_ids, target_ids, max_gram_size=4): """Computes the SARI scores from the given source, prediction and targets. Args: source_ids: A 2D tf.Tensor of size (batch_size , sequence_length) prediction_ids: A 2D tf.Tensor of size (batch_size, sequence_length) target_ids: A 3D...
python
def get_sari(source_ids, prediction_ids, target_ids, max_gram_size=4): """Computes the SARI scores from the given source, prediction and targets. Args: source_ids: A 2D tf.Tensor of size (batch_size , sequence_length) prediction_ids: A 2D tf.Tensor of size (batch_size, sequence_length) target_ids: A 3D...
[ "def", "get_sari", "(", "source_ids", ",", "prediction_ids", ",", "target_ids", ",", "max_gram_size", "=", "4", ")", ":", "def", "get_sari_numpy", "(", "source_ids", ",", "prediction_ids", ",", "target_ids", ")", ":", "\"\"\"Iterate over elements in the batch and call...
Computes the SARI scores from the given source, prediction and targets. Args: source_ids: A 2D tf.Tensor of size (batch_size , sequence_length) prediction_ids: A 2D tf.Tensor of size (batch_size, sequence_length) target_ids: A 3D tf.Tensor of size (batch_size, number_of_targets, sequence_length) ...
[ "Computes", "the", "SARI", "scores", "from", "the", "given", "source", "prediction", "and", "targets", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/sari_hook.py#L182-L221
train
tensorflow/tensor2tensor
tensor2tensor/utils/sari_hook.py
sari_score
def sari_score(predictions, labels, features, **unused_kwargs): """Computes the SARI scores from the given source, prediction and targets. An approximate SARI scoring method since we do not glue word pieces or decode the ids and tokenize the output. By default, we use ngram order of 4. Also, this does not have...
python
def sari_score(predictions, labels, features, **unused_kwargs): """Computes the SARI scores from the given source, prediction and targets. An approximate SARI scoring method since we do not glue word pieces or decode the ids and tokenize the output. By default, we use ngram order of 4. Also, this does not have...
[ "def", "sari_score", "(", "predictions", ",", "labels", ",", "features", ",", "*", "*", "unused_kwargs", ")", ":", "if", "\"inputs\"", "not", "in", "features", ":", "raise", "ValueError", "(", "\"sari_score requires inputs feature\"", ")", "# Convert the inputs and ...
Computes the SARI scores from the given source, prediction and targets. An approximate SARI scoring method since we do not glue word pieces or decode the ids and tokenize the output. By default, we use ngram order of 4. Also, this does not have beam search. Args: predictions: tensor, model predictions. ...
[ "Computes", "the", "SARI", "scores", "from", "the", "given", "source", "prediction", "and", "targets", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/sari_hook.py#L224-L252
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/mnist.py
_get_mnist
def _get_mnist(directory): """Download all MNIST files to directory unless they are there.""" for filename in [ _MNIST_TRAIN_DATA_FILENAME, _MNIST_TRAIN_LABELS_FILENAME, _MNIST_TEST_DATA_FILENAME, _MNIST_TEST_LABELS_FILENAME ]: generator_utils.maybe_download(directory, filename, _MNIST_URL + filen...
python
def _get_mnist(directory): """Download all MNIST files to directory unless they are there.""" for filename in [ _MNIST_TRAIN_DATA_FILENAME, _MNIST_TRAIN_LABELS_FILENAME, _MNIST_TEST_DATA_FILENAME, _MNIST_TEST_LABELS_FILENAME ]: generator_utils.maybe_download(directory, filename, _MNIST_URL + filen...
[ "def", "_get_mnist", "(", "directory", ")", ":", "for", "filename", "in", "[", "_MNIST_TRAIN_DATA_FILENAME", ",", "_MNIST_TRAIN_LABELS_FILENAME", ",", "_MNIST_TEST_DATA_FILENAME", ",", "_MNIST_TEST_LABELS_FILENAME", "]", ":", "generator_utils", ".", "maybe_download", "(",...
Download all MNIST files to directory unless they are there.
[ "Download", "all", "MNIST", "files", "to", "directory", "unless", "they", "are", "there", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/mnist.py#L42-L48
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/mnist.py
_extract_mnist_images
def _extract_mnist_images(filename, num_images): """Extract images from an MNIST file into a numpy array. Args: filename: The path to an MNIST images file. num_images: The number of images in the file. Returns: A numpy array of shape [number_of_images, height, width, channels]. """ with gzip.ope...
python
def _extract_mnist_images(filename, num_images): """Extract images from an MNIST file into a numpy array. Args: filename: The path to an MNIST images file. num_images: The number of images in the file. Returns: A numpy array of shape [number_of_images, height, width, channels]. """ with gzip.ope...
[ "def", "_extract_mnist_images", "(", "filename", ",", "num_images", ")", ":", "with", "gzip", ".", "open", "(", "filename", ")", "as", "bytestream", ":", "bytestream", ".", "read", "(", "16", ")", "buf", "=", "bytestream", ".", "read", "(", "_MNIST_IMAGE_S...
Extract images from an MNIST file into a numpy array. Args: filename: The path to an MNIST images file. num_images: The number of images in the file. Returns: A numpy array of shape [number_of_images, height, width, channels].
[ "Extract", "images", "from", "an", "MNIST", "file", "into", "a", "numpy", "array", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/mnist.py#L51-L66
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/mnist.py
_extract_mnist_labels
def _extract_mnist_labels(filename, num_labels): """Extract labels from an MNIST file into integers. Args: filename: The path to an MNIST labels file. num_labels: The number of labels in the file. Returns: A int64 numpy array of shape [num_labels] """ with gzip.open(filename) as bytestream: ...
python
def _extract_mnist_labels(filename, num_labels): """Extract labels from an MNIST file into integers. Args: filename: The path to an MNIST labels file. num_labels: The number of labels in the file. Returns: A int64 numpy array of shape [num_labels] """ with gzip.open(filename) as bytestream: ...
[ "def", "_extract_mnist_labels", "(", "filename", ",", "num_labels", ")", ":", "with", "gzip", ".", "open", "(", "filename", ")", "as", "bytestream", ":", "bytestream", ".", "read", "(", "8", ")", "buf", "=", "bytestream", ".", "read", "(", "num_labels", ...
Extract labels from an MNIST file into integers. Args: filename: The path to an MNIST labels file. num_labels: The number of labels in the file. Returns: A int64 numpy array of shape [num_labels]
[ "Extract", "labels", "from", "an", "MNIST", "file", "into", "integers", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/mnist.py#L69-L83
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/mnist.py
mnist_common_generator
def mnist_common_generator(tmp_dir, training, how_many, data_filename, label_filename, start_from=0): """Image generator for MNIST. Args: tmp_dir: path to temporary storage dir...
python
def mnist_common_generator(tmp_dir, training, how_many, data_filename, label_filename, start_from=0): """Image generator for MNIST. Args: tmp_dir: path to temporary storage dir...
[ "def", "mnist_common_generator", "(", "tmp_dir", ",", "training", ",", "how_many", ",", "data_filename", ",", "label_filename", ",", "start_from", "=", "0", ")", ":", "data_path", "=", "os", ".", "path", ".", "join", "(", "tmp_dir", ",", "data_filename", ")"...
Image generator for MNIST. Args: tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. how_many: how many images and labels to generate. data_filename: file that contains features data. label_filename: file that contains labels. ...
[ "Image", "generator", "for", "MNIST", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/mnist.py#L86-L114
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/mnist.py
mnist_generator
def mnist_generator(tmp_dir, training, how_many, start_from=0): """Image generator for MNIST. Args: tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. how_many: how many images and labels to generate. start_from: from which imag...
python
def mnist_generator(tmp_dir, training, how_many, start_from=0): """Image generator for MNIST. Args: tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. how_many: how many images and labels to generate. start_from: from which imag...
[ "def", "mnist_generator", "(", "tmp_dir", ",", "training", ",", "how_many", ",", "start_from", "=", "0", ")", ":", "_get_mnist", "(", "tmp_dir", ")", "d", "=", "_MNIST_TRAIN_DATA_FILENAME", "if", "training", "else", "_MNIST_TEST_DATA_FILENAME", "l", "=", "_MNIST...
Image generator for MNIST. Args: tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. how_many: how many images and labels to generate. start_from: from which image to start. Returns: An instance of image_generator that produ...
[ "Image", "generator", "for", "MNIST", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/mnist.py#L117-L132
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/mnist.py
_get_fashion_mnist
def _get_fashion_mnist(directory): """Download all FashionMNIST files to directory unless they are there.""" # Fashion mnist files have the same names as MNIST. # We must choose a separate name (by adding 'fashion-' prefix) in the tmp_dir. for filename in [ _MNIST_TRAIN_DATA_FILENAME, _MNIST_TRAIN_LABELS_...
python
def _get_fashion_mnist(directory): """Download all FashionMNIST files to directory unless they are there.""" # Fashion mnist files have the same names as MNIST. # We must choose a separate name (by adding 'fashion-' prefix) in the tmp_dir. for filename in [ _MNIST_TRAIN_DATA_FILENAME, _MNIST_TRAIN_LABELS_...
[ "def", "_get_fashion_mnist", "(", "directory", ")", ":", "# Fashion mnist files have the same names as MNIST.", "# We must choose a separate name (by adding 'fashion-' prefix) in the tmp_dir.", "for", "filename", "in", "[", "_MNIST_TRAIN_DATA_FILENAME", ",", "_MNIST_TRAIN_LABELS_FILENAME...
Download all FashionMNIST files to directory unless they are there.
[ "Download", "all", "FashionMNIST", "files", "to", "directory", "unless", "they", "are", "there", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/mnist.py#L191-L201
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/mnist.py
fashion_mnist_generator
def fashion_mnist_generator(tmp_dir, training, how_many, start_from=0): """Image generator for FashionMNIST. Args: tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. how_many: how many images and labels to generate. start_from: ...
python
def fashion_mnist_generator(tmp_dir, training, how_many, start_from=0): """Image generator for FashionMNIST. Args: tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. how_many: how many images and labels to generate. start_from: ...
[ "def", "fashion_mnist_generator", "(", "tmp_dir", ",", "training", ",", "how_many", ",", "start_from", "=", "0", ")", ":", "_get_fashion_mnist", "(", "tmp_dir", ")", "d", "=", "_FASHION_MNIST_LOCAL_FILE_PREFIX", "+", "(", "_MNIST_TRAIN_DATA_FILENAME", "if", "trainin...
Image generator for FashionMNIST. Args: tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. how_many: how many images and labels to generate. start_from: from which image to start. Returns: An instance of image_generator tha...
[ "Image", "generator", "for", "FashionMNIST", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/mnist.py#L204-L221
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/timeseries_data_generator.py
generate_data
def generate_data(timeseries_length, timeseries_params): """Generates synthetic timeseries using input parameters. Each generated timeseries has timeseries_length data points. Parameters for each timeseries are specified by timeseries_params. Args: timeseries_length: Number of data points to generate for ...
python
def generate_data(timeseries_length, timeseries_params): """Generates synthetic timeseries using input parameters. Each generated timeseries has timeseries_length data points. Parameters for each timeseries are specified by timeseries_params. Args: timeseries_length: Number of data points to generate for ...
[ "def", "generate_data", "(", "timeseries_length", ",", "timeseries_params", ")", ":", "x", "=", "range", "(", "timeseries_length", ")", "multi_timeseries", "=", "[", "]", "for", "p", "in", "timeseries_params", ":", "# Trend", "y1", "=", "[", "p", "[", "\"m\"...
Generates synthetic timeseries using input parameters. Each generated timeseries has timeseries_length data points. Parameters for each timeseries are specified by timeseries_params. Args: timeseries_length: Number of data points to generate for each timeseries. timeseries_params: Parameters used to gen...
[ "Generates", "synthetic", "timeseries", "using", "input", "parameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/timeseries_data_generator.py#L24-L63
train
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_stochastic.py
next_frame_basic_stochastic
def next_frame_basic_stochastic(): """Basic 2-frame conv model with stochastic tower.""" hparams = basic_deterministic_params.next_frame_basic_deterministic() hparams.stochastic_model = True hparams.add_hparam("latent_channels", 1) hparams.add_hparam("latent_std_min", -5.0) hparams.add_hparam("num_iteration...
python
def next_frame_basic_stochastic(): """Basic 2-frame conv model with stochastic tower.""" hparams = basic_deterministic_params.next_frame_basic_deterministic() hparams.stochastic_model = True hparams.add_hparam("latent_channels", 1) hparams.add_hparam("latent_std_min", -5.0) hparams.add_hparam("num_iteration...
[ "def", "next_frame_basic_stochastic", "(", ")", ":", "hparams", "=", "basic_deterministic_params", ".", "next_frame_basic_deterministic", "(", ")", "hparams", ".", "stochastic_model", "=", "True", "hparams", ".", "add_hparam", "(", "\"latent_channels\"", ",", "1", ")"...
Basic 2-frame conv model with stochastic tower.
[ "Basic", "2", "-", "frame", "conv", "model", "with", "stochastic", "tower", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_stochastic.py#L215-L231
train
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_stochastic.py
next_frame_sampling_stochastic
def next_frame_sampling_stochastic(): """Basic 2-frame conv model with stochastic tower.""" hparams = basic_deterministic_params.next_frame_sampling() hparams.stochastic_model = True hparams.add_hparam("latent_channels", 1) hparams.add_hparam("latent_std_min", -5.0) hparams.add_hparam("num_iterations_1st_st...
python
def next_frame_sampling_stochastic(): """Basic 2-frame conv model with stochastic tower.""" hparams = basic_deterministic_params.next_frame_sampling() hparams.stochastic_model = True hparams.add_hparam("latent_channels", 1) hparams.add_hparam("latent_std_min", -5.0) hparams.add_hparam("num_iterations_1st_st...
[ "def", "next_frame_sampling_stochastic", "(", ")", ":", "hparams", "=", "basic_deterministic_params", ".", "next_frame_sampling", "(", ")", "hparams", ".", "stochastic_model", "=", "True", "hparams", ".", "add_hparam", "(", "\"latent_channels\"", ",", "1", ")", "hpa...
Basic 2-frame conv model with stochastic tower.
[ "Basic", "2", "-", "frame", "conv", "model", "with", "stochastic", "tower", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_stochastic.py#L235-L251
train
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_stochastic.py
next_frame_basic_stochastic_discrete
def next_frame_basic_stochastic_discrete(): """Basic 2-frame conv model with stochastic discrete latent.""" hparams = basic_deterministic_params.next_frame_sampling() hparams.batch_size = 4 hparams.video_num_target_frames = 6 hparams.scheduled_sampling_mode = "prob_inverse_lin" hparams.scheduled_sampling_de...
python
def next_frame_basic_stochastic_discrete(): """Basic 2-frame conv model with stochastic discrete latent.""" hparams = basic_deterministic_params.next_frame_sampling() hparams.batch_size = 4 hparams.video_num_target_frames = 6 hparams.scheduled_sampling_mode = "prob_inverse_lin" hparams.scheduled_sampling_de...
[ "def", "next_frame_basic_stochastic_discrete", "(", ")", ":", "hparams", "=", "basic_deterministic_params", ".", "next_frame_sampling", "(", ")", "hparams", ".", "batch_size", "=", "4", "hparams", ".", "video_num_target_frames", "=", "6", "hparams", ".", "scheduled_sa...
Basic 2-frame conv model with stochastic discrete latent.
[ "Basic", "2", "-", "frame", "conv", "model", "with", "stochastic", "discrete", "latent", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_stochastic.py#L255-L282
train
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_stochastic.py
next_frame_stochastic_discrete_range
def next_frame_stochastic_discrete_range(rhp): """Next frame stochastic discrete tuning grid.""" rhp.set_float("learning_rate_constant", 0.001, 0.01) rhp.set_float("dropout", 0.2, 0.6) rhp.set_int("filter_double_steps", 3, 5) rhp.set_discrete("hidden_size", [64, 96, 128]) rhp.set_discrete("bottleneck_bits",...
python
def next_frame_stochastic_discrete_range(rhp): """Next frame stochastic discrete tuning grid.""" rhp.set_float("learning_rate_constant", 0.001, 0.01) rhp.set_float("dropout", 0.2, 0.6) rhp.set_int("filter_double_steps", 3, 5) rhp.set_discrete("hidden_size", [64, 96, 128]) rhp.set_discrete("bottleneck_bits",...
[ "def", "next_frame_stochastic_discrete_range", "(", "rhp", ")", ":", "rhp", ".", "set_float", "(", "\"learning_rate_constant\"", ",", "0.001", ",", "0.01", ")", "rhp", ".", "set_float", "(", "\"dropout\"", ",", "0.2", ",", "0.6", ")", "rhp", ".", "set_int", ...
Next frame stochastic discrete tuning grid.
[ "Next", "frame", "stochastic", "discrete", "tuning", "grid", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_stochastic.py#L295-L303
train
tensorflow/tensor2tensor
tensor2tensor/trax/layers/base.py
nested_map
def nested_map(x, f): """Map the function f to the nested structure x (dicts, tuples, lists).""" if isinstance(x, list): return [nested_map(y, f) for y in x] if isinstance(x, tuple): return tuple([nested_map(y, f) for y in x]) if isinstance(x, dict): return {k: nested_map(x[k], f) for k in x} retu...
python
def nested_map(x, f): """Map the function f to the nested structure x (dicts, tuples, lists).""" if isinstance(x, list): return [nested_map(y, f) for y in x] if isinstance(x, tuple): return tuple([nested_map(y, f) for y in x]) if isinstance(x, dict): return {k: nested_map(x[k], f) for k in x} retu...
[ "def", "nested_map", "(", "x", ",", "f", ")", ":", "if", "isinstance", "(", "x", ",", "list", ")", ":", "return", "[", "nested_map", "(", "y", ",", "f", ")", "for", "y", "in", "x", "]", "if", "isinstance", "(", "x", ",", "tuple", ")", ":", "r...
Map the function f to the nested structure x (dicts, tuples, lists).
[ "Map", "the", "function", "f", "to", "the", "nested", "structure", "x", "(", "dicts", "tuples", "lists", ")", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/base.py#L147-L155
train
tensorflow/tensor2tensor
tensor2tensor/trax/layers/base.py
shapes
def shapes(x): """Get a structure of shapes for a structure of nested arrays.""" def shape(x): try: return x.shape except Exception: # pylint: disable=broad-except return [] return nested_map(x, shape)
python
def shapes(x): """Get a structure of shapes for a structure of nested arrays.""" def shape(x): try: return x.shape except Exception: # pylint: disable=broad-except return [] return nested_map(x, shape)
[ "def", "shapes", "(", "x", ")", ":", "def", "shape", "(", "x", ")", ":", "try", ":", "return", "x", ".", "shape", "except", "Exception", ":", "# pylint: disable=broad-except", "return", "[", "]", "return", "nested_map", "(", "x", ",", "shape", ")" ]
Get a structure of shapes for a structure of nested arrays.
[ "Get", "a", "structure", "of", "shapes", "for", "a", "structure", "of", "nested", "arrays", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/base.py#L169-L176
train
tensorflow/tensor2tensor
tensor2tensor/trax/layers/base.py
sizes
def sizes(x): """Get a structure of sizes for a structure of nested arrays.""" def size(x): try: return x.size except Exception: # pylint: disable=broad-except return 0 return nested_map(x, size)
python
def sizes(x): """Get a structure of sizes for a structure of nested arrays.""" def size(x): try: return x.size except Exception: # pylint: disable=broad-except return 0 return nested_map(x, size)
[ "def", "sizes", "(", "x", ")", ":", "def", "size", "(", "x", ")", ":", "try", ":", "return", "x", ".", "size", "except", "Exception", ":", "# pylint: disable=broad-except", "return", "0", "return", "nested_map", "(", "x", ",", "size", ")" ]
Get a structure of sizes for a structure of nested arrays.
[ "Get", "a", "structure", "of", "sizes", "for", "a", "structure", "of", "nested", "arrays", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/base.py#L179-L186
train
tensorflow/tensor2tensor
tensor2tensor/trax/layers/base.py
_find_frame
def _find_frame(stack, start=0): """Find the frame with the caller on the stack.""" # We want to find the first place where the layer was called # that is *not* an __init__ function of an inheriting layer. frame = inspect.getframeinfo(stack[start][0]) # If we are in an init, move on. if frame.function == '_...
python
def _find_frame(stack, start=0): """Find the frame with the caller on the stack.""" # We want to find the first place where the layer was called # that is *not* an __init__ function of an inheriting layer. frame = inspect.getframeinfo(stack[start][0]) # If we are in an init, move on. if frame.function == '_...
[ "def", "_find_frame", "(", "stack", ",", "start", "=", "0", ")", ":", "# We want to find the first place where the layer was called", "# that is *not* an __init__ function of an inheriting layer.", "frame", "=", "inspect", ".", "getframeinfo", "(", "stack", "[", "start", "]...
Find the frame with the caller on the stack.
[ "Find", "the", "frame", "with", "the", "caller", "on", "the", "stack", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/base.py#L189-L197
train
tensorflow/tensor2tensor
tensor2tensor/trax/layers/base.py
_shorten_file_path
def _shorten_file_path(line): """Shorten file path in error lines for more readable tracebacks.""" start = line.lower().find('file') if start < 0: return line first_quote = line.find('"', start) if first_quote < 0: return line second_quote = line.find('"', first_quote + 1) if second_quote < 0: ...
python
def _shorten_file_path(line): """Shorten file path in error lines for more readable tracebacks.""" start = line.lower().find('file') if start < 0: return line first_quote = line.find('"', start) if first_quote < 0: return line second_quote = line.find('"', first_quote + 1) if second_quote < 0: ...
[ "def", "_shorten_file_path", "(", "line", ")", ":", "start", "=", "line", ".", "lower", "(", ")", ".", "find", "(", "'file'", ")", "if", "start", "<", "0", ":", "return", "line", "first_quote", "=", "line", ".", "find", "(", "'\"'", ",", "start", "...
Shorten file path in error lines for more readable tracebacks.
[ "Shorten", "file", "path", "in", "error", "lines", "for", "more", "readable", "tracebacks", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/base.py#L200-L213
train
tensorflow/tensor2tensor
tensor2tensor/trax/layers/base.py
_short_traceback
def _short_traceback(skip=3): """Cleaned-up form of traceback.""" counter, res = 0, [] # Skipping 3 lines by default: the top (useless) and self-call. lines = traceback.format_exc().splitlines()[skip:] for l in lines: res.append(_shorten_file_path(l)) if counter % 2 == 1: res.append('') coun...
python
def _short_traceback(skip=3): """Cleaned-up form of traceback.""" counter, res = 0, [] # Skipping 3 lines by default: the top (useless) and self-call. lines = traceback.format_exc().splitlines()[skip:] for l in lines: res.append(_shorten_file_path(l)) if counter % 2 == 1: res.append('') coun...
[ "def", "_short_traceback", "(", "skip", "=", "3", ")", ":", "counter", ",", "res", "=", "0", ",", "[", "]", "# Skipping 3 lines by default: the top (useless) and self-call.", "lines", "=", "traceback", ".", "format_exc", "(", ")", ".", "splitlines", "(", ")", ...
Cleaned-up form of traceback.
[ "Cleaned", "-", "up", "form", "of", "traceback", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/base.py#L216-L232
train
tensorflow/tensor2tensor
tensor2tensor/trax/layers/base.py
layer
def layer(output_shape=None, new_parameters=None): """Create a layer class from a function.""" def layer_decorator(call): """Decorating the call function.""" def output_shape_fun(self, input_shape): if output_shape is None: return input_shape kwargs = self._init_kwargs # pylint: disable...
python
def layer(output_shape=None, new_parameters=None): """Create a layer class from a function.""" def layer_decorator(call): """Decorating the call function.""" def output_shape_fun(self, input_shape): if output_shape is None: return input_shape kwargs = self._init_kwargs # pylint: disable...
[ "def", "layer", "(", "output_shape", "=", "None", ",", "new_parameters", "=", "None", ")", ":", "def", "layer_decorator", "(", "call", ")", ":", "\"\"\"Decorating the call function.\"\"\"", "def", "output_shape_fun", "(", "self", ",", "input_shape", ")", ":", "i...
Create a layer class from a function.
[ "Create", "a", "layer", "class", "from", "a", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/base.py#L238-L276
train
tensorflow/tensor2tensor
tensor2tensor/trax/layers/base.py
Layer.initialize
def initialize(self, input_shape, rng): """Initialize the layer given an input shape and rng. Returns new_parameters(input_shape, rng) on the first call and () on any subsequent call, as the layer is already initialized. This is used for networks that share parameters, so the layer only produces them o...
python
def initialize(self, input_shape, rng): """Initialize the layer given an input shape and rng. Returns new_parameters(input_shape, rng) on the first call and () on any subsequent call, as the layer is already initialized. This is used for networks that share parameters, so the layer only produces them o...
[ "def", "initialize", "(", "self", ",", "input_shape", ",", "rng", ")", ":", "try", ":", "# Re-using this layer, no new parameters.", "if", "not", "self", ".", "_first_init", ":", "return", "(", ")", "# First call of this layer, create parameters.", "self", ".", "_fi...
Initialize the layer given an input shape and rng. Returns new_parameters(input_shape, rng) on the first call and () on any subsequent call, as the layer is already initialized. This is used for networks that share parameters, so the layer only produces them once. Note that all arguments and return va...
[ "Initialize", "the", "layer", "given", "an", "input", "shape", "and", "rng", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/base.py#L74-L102
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikisum/wikisum.py
_references_content
def _references_content(ref_files): """Returns dict<str ref_url, str ref_content>.""" example_spec = { "url": tf.FixedLenFeature([], tf.string), "content": tf.FixedLenFeature([], tf.string), } data = {} for ex in generator_utils.tfrecord_iterator( ref_files, gzipped=True, example_spec=exampl...
python
def _references_content(ref_files): """Returns dict<str ref_url, str ref_content>.""" example_spec = { "url": tf.FixedLenFeature([], tf.string), "content": tf.FixedLenFeature([], tf.string), } data = {} for ex in generator_utils.tfrecord_iterator( ref_files, gzipped=True, example_spec=exampl...
[ "def", "_references_content", "(", "ref_files", ")", ":", "example_spec", "=", "{", "\"url\"", ":", "tf", ".", "FixedLenFeature", "(", "[", "]", ",", "tf", ".", "string", ")", ",", "\"content\"", ":", "tf", ".", "FixedLenFeature", "(", "[", "]", ",", "...
Returns dict<str ref_url, str ref_content>.
[ "Returns", "dict<str", "ref_url", "str", "ref_content", ">", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/wikisum.py#L248-L258
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikisum/wikisum.py
_wiki_urls_for_shard
def _wiki_urls_for_shard(shard_id, urls_dir=None): """Urls for chunk: dict<str wiki_url, list<str> ref_urls>.""" urls_dir = urls_dir or WIKI_URLS_DIR urls_filepath = os.path.join(urls_dir, WIKI_URLS_FILE % shard_id) with tf.gfile.GFile(urls_filepath) as f: return json.loads(f.read())
python
def _wiki_urls_for_shard(shard_id, urls_dir=None): """Urls for chunk: dict<str wiki_url, list<str> ref_urls>.""" urls_dir = urls_dir or WIKI_URLS_DIR urls_filepath = os.path.join(urls_dir, WIKI_URLS_FILE % shard_id) with tf.gfile.GFile(urls_filepath) as f: return json.loads(f.read())
[ "def", "_wiki_urls_for_shard", "(", "shard_id", ",", "urls_dir", "=", "None", ")", ":", "urls_dir", "=", "urls_dir", "or", "WIKI_URLS_DIR", "urls_filepath", "=", "os", ".", "path", ".", "join", "(", "urls_dir", ",", "WIKI_URLS_FILE", "%", "shard_id", ")", "w...
Urls for chunk: dict<str wiki_url, list<str> ref_urls>.
[ "Urls", "for", "chunk", ":", "dict<str", "wiki_url", "list<str", ">", "ref_urls", ">", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/wikisum.py#L261-L266
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikisum/wikisum.py
_wiki_articles
def _wiki_articles(shard_id, wikis_dir=None): """Generates WikipediaArticles from GCS that are part of shard shard_id.""" if not wikis_dir: wikis_dir = WIKI_CONTENT_DIR with tf.Graph().as_default(): dataset = tf.data.TFRecordDataset( cc_utils.readahead( os.path.join(wikis_dir, WIKI_CON...
python
def _wiki_articles(shard_id, wikis_dir=None): """Generates WikipediaArticles from GCS that are part of shard shard_id.""" if not wikis_dir: wikis_dir = WIKI_CONTENT_DIR with tf.Graph().as_default(): dataset = tf.data.TFRecordDataset( cc_utils.readahead( os.path.join(wikis_dir, WIKI_CON...
[ "def", "_wiki_articles", "(", "shard_id", ",", "wikis_dir", "=", "None", ")", ":", "if", "not", "wikis_dir", ":", "wikis_dir", "=", "WIKI_CONTENT_DIR", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", ":", "dataset", "=", "tf", ".", "...
Generates WikipediaArticles from GCS that are part of shard shard_id.
[ "Generates", "WikipediaArticles", "from", "GCS", "that", "are", "part", "of", "shard", "shard_id", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/wikisum.py#L279-L323
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikisum/wikisum.py
rank_reference_paragraphs
def rank_reference_paragraphs(wiki_title, references_content, normalize=True): """Rank and return reference paragraphs by tf-idf score on title tokens.""" normalized_title = _normalize_text(wiki_title) title_tokens = _tokens_to_score( set(tokenizer.encode(text_encoder.native_to_unicode(normalized_title)))) ...
python
def rank_reference_paragraphs(wiki_title, references_content, normalize=True): """Rank and return reference paragraphs by tf-idf score on title tokens.""" normalized_title = _normalize_text(wiki_title) title_tokens = _tokens_to_score( set(tokenizer.encode(text_encoder.native_to_unicode(normalized_title)))) ...
[ "def", "rank_reference_paragraphs", "(", "wiki_title", ",", "references_content", ",", "normalize", "=", "True", ")", ":", "normalized_title", "=", "_normalize_text", "(", "wiki_title", ")", "title_tokens", "=", "_tokens_to_score", "(", "set", "(", "tokenizer", ".",...
Rank and return reference paragraphs by tf-idf score on title tokens.
[ "Rank", "and", "return", "reference", "paragraphs", "by", "tf", "-", "idf", "score", "on", "title", "tokens", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/wikisum.py#L348-L379
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikisum/wikisum.py
produce_examples
def produce_examples(shard_ids, wikis_dir, refs_dir, urls_dir, vocab_path, out_filepaths): """Produce examples from shard_ids to out_filepaths.""" # * Join the Wikipedia articles with their references # * Run Tf-idf to sort reference paragraphs # * Encode the Wikipedia and reference text wi...
python
def produce_examples(shard_ids, wikis_dir, refs_dir, urls_dir, vocab_path, out_filepaths): """Produce examples from shard_ids to out_filepaths.""" # * Join the Wikipedia articles with their references # * Run Tf-idf to sort reference paragraphs # * Encode the Wikipedia and reference text wi...
[ "def", "produce_examples", "(", "shard_ids", ",", "wikis_dir", ",", "refs_dir", ",", "urls_dir", ",", "vocab_path", ",", "out_filepaths", ")", ":", "# * Join the Wikipedia articles with their references", "# * Run Tf-idf to sort reference paragraphs", "# * Encode the Wikipedia an...
Produce examples from shard_ids to out_filepaths.
[ "Produce", "examples", "from", "shard_ids", "to", "out_filepaths", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/wikisum.py#L382-L481
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikisum/wikisum.py
_encode_wiki_sections
def _encode_wiki_sections(sections, vocab): """Encodes sections with vocab. Returns ids and section boundaries.""" ids = [] section_boundaries = [] for i, section in enumerate(sections): if i > 0: # Skip including article title ids.extend(vocab.encode(_format_title(_normalize_text(section.title)...
python
def _encode_wiki_sections(sections, vocab): """Encodes sections with vocab. Returns ids and section boundaries.""" ids = [] section_boundaries = [] for i, section in enumerate(sections): if i > 0: # Skip including article title ids.extend(vocab.encode(_format_title(_normalize_text(section.title)...
[ "def", "_encode_wiki_sections", "(", "sections", ",", "vocab", ")", ":", "ids", "=", "[", "]", "section_boundaries", "=", "[", "]", "for", "i", ",", "section", "in", "enumerate", "(", "sections", ")", ":", "if", "i", ">", "0", ":", "# Skip including arti...
Encodes sections with vocab. Returns ids and section boundaries.
[ "Encodes", "sections", "with", "vocab", ".", "Returns", "ids", "and", "section", "boundaries", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/wikisum.py#L488-L499
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikisum/wikisum.py
extract_references_from_wets
def extract_references_from_wets(wet_files, metadata_dir, out_dir, tmp_dir=None): """Extract references from WET files into sharded output files.""" # Setup output files shard_files = make_ref_shard_files(out_dir) num_refs = 0 for i, wet_file in enumerate(wet_files): num_...
python
def extract_references_from_wets(wet_files, metadata_dir, out_dir, tmp_dir=None): """Extract references from WET files into sharded output files.""" # Setup output files shard_files = make_ref_shard_files(out_dir) num_refs = 0 for i, wet_file in enumerate(wet_files): num_...
[ "def", "extract_references_from_wets", "(", "wet_files", ",", "metadata_dir", ",", "out_dir", ",", "tmp_dir", "=", "None", ")", ":", "# Setup output files", "shard_files", "=", "make_ref_shard_files", "(", "out_dir", ")", "num_refs", "=", "0", "for", "i", ",", "...
Extract references from WET files into sharded output files.
[ "Extract", "references", "from", "WET", "files", "into", "sharded", "output", "files", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/wikisum.py#L506-L557
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/wiki.py
_dump_to_pages
def _dump_to_pages(dump): """Extract pages from an xml dump. Args: dump: a unicode string Returns: a list of unicode strings """ pos = 0 ret = [] start_tag = u"<page>\n" end_tag = u"</page>\n" while True: start_pos = dump.find(start_tag, pos) if start_pos == -1: break start_...
python
def _dump_to_pages(dump): """Extract pages from an xml dump. Args: dump: a unicode string Returns: a list of unicode strings """ pos = 0 ret = [] start_tag = u"<page>\n" end_tag = u"</page>\n" while True: start_pos = dump.find(start_tag, pos) if start_pos == -1: break start_...
[ "def", "_dump_to_pages", "(", "dump", ")", ":", "pos", "=", "0", "ret", "=", "[", "]", "start_tag", "=", "u\"<page>\\n\"", "end_tag", "=", "u\"</page>\\n\"", "while", "True", ":", "start_pos", "=", "dump", ".", "find", "(", "start_tag", ",", "pos", ")", ...
Extract pages from an xml dump. Args: dump: a unicode string Returns: a list of unicode strings
[ "Extract", "pages", "from", "an", "xml", "dump", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki.py#L245-L267
train