partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
weight_targeting
Weight-level magnitude pruning.
tensor2tensor/layers/common_layers.py
def weight_targeting(w, k): """Weight-level magnitude pruning.""" k = tf.to_int32(k) w_shape = shape_list(w) size = tf.to_int32(tf.reduce_prod(w_shape[:-1])) w = tf.reshape(w, [size, w_shape[-1]]) transpose_w = tf.transpose(w) thres = tf.contrib.framework.sort(tf.abs(transpose_w), axis=1)[:, k] mask = ...
def weight_targeting(w, k): """Weight-level magnitude pruning.""" k = tf.to_int32(k) w_shape = shape_list(w) size = tf.to_int32(tf.reduce_prod(w_shape[:-1])) w = tf.reshape(w, [size, w_shape[-1]]) transpose_w = tf.transpose(w) thres = tf.contrib.framework.sort(tf.abs(transpose_w), axis=1)[:, k] mask = ...
[ "Weight", "-", "level", "magnitude", "pruning", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3844-L3855
[ "def", "weight_targeting", "(", "w", ",", "k", ")", ":", "k", "=", "tf", ".", "to_int32", "(", "k", ")", "w_shape", "=", "shape_list", "(", "w", ")", "size", "=", "tf", ".", "to_int32", "(", "tf", ".", "reduce_prod", "(", "w_shape", "[", ":", "-"...
272500b6efe353aeb638d2745ed56e519462ca31
train
unit_targeting
Unit-level magnitude pruning.
tensor2tensor/layers/common_layers.py
def unit_targeting(w, k): """Unit-level magnitude pruning.""" k = tf.to_int32(k) w_shape = shape_list(w) size = tf.to_int32(tf.reduce_prod(w_shape[:-1])) w = tf.reshape(w, [size, w_shape[-1]]) norm = tf.norm(w, axis=0) thres = tf.contrib.framework.sort(norm, axis=0)[k] mask = to_float(thres >= norm)[No...
def unit_targeting(w, k): """Unit-level magnitude pruning.""" k = tf.to_int32(k) w_shape = shape_list(w) size = tf.to_int32(tf.reduce_prod(w_shape[:-1])) w = tf.reshape(w, [size, w_shape[-1]]) norm = tf.norm(w, axis=0) thres = tf.contrib.framework.sort(norm, axis=0)[k] mask = to_float(thres >= norm)[No...
[ "Unit", "-", "level", "magnitude", "pruning", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3858-L3870
[ "def", "unit_targeting", "(", "w", ",", "k", ")", ":", "k", "=", "tf", ".", "to_int32", "(", "k", ")", "w_shape", "=", "shape_list", "(", "w", ")", "size", "=", "tf", ".", "to_int32", "(", "tf", ".", "reduce_prod", "(", "w_shape", "[", ":", "-", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
td_conv
Apply targeted dropout to the weights of a convolution.
tensor2tensor/layers/common_layers.py
def td_conv(inputs, filters, kernel_size, targeting_count, targeting_fn, keep_prob, is_training, do_prune=True, strides=(1, 1), padding="valid", data_format="channels_last", dilation_rate=...
def td_conv(inputs, filters, kernel_size, targeting_count, targeting_fn, keep_prob, is_training, do_prune=True, strides=(1, 1), padding="valid", data_format="channels_last", dilation_rate=...
[ "Apply", "targeted", "dropout", "to", "the", "weights", "of", "a", "convolution", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3873-L3938
[ "def", "td_conv", "(", "inputs", ",", "filters", ",", "kernel_size", ",", "targeting_count", ",", "targeting_fn", ",", "keep_prob", ",", "is_training", ",", "do_prune", "=", "True", ",", "strides", "=", "(", "1", ",", "1", ")", ",", "padding", "=", "\"va...
272500b6efe353aeb638d2745ed56e519462ca31
train
targeted_dropout
Applies targeted dropout. Applies dropout at a rate of `1 - keep_prob` to only those elements of `inputs` marked by `targeting_fn`. See below and paper for more detail: "Targeted Dropout for Posthoc Pruning" Aidan N. Gomez, Ivan Zhang, Kevin Swersky, Yarin Gal, and Geoffrey E. Hinton. Args: inputs: T...
tensor2tensor/layers/common_layers.py
def targeted_dropout(inputs, k, keep_prob, targeting_fn, is_training, do_prune=False): """Applies targeted dropout. Applies dropout at a rate of `1 - keep_prob` to only those elements of `inputs` marked by `t...
def targeted_dropout(inputs, k, keep_prob, targeting_fn, is_training, do_prune=False): """Applies targeted dropout. Applies dropout at a rate of `1 - keep_prob` to only those elements of `inputs` marked by `t...
[ "Applies", "targeted", "dropout", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3941-L3982
[ "def", "targeted_dropout", "(", "inputs", ",", "k", ",", "keep_prob", ",", "targeting_fn", ",", "is_training", ",", "do_prune", "=", "False", ")", ":", "if", "not", "is_training", "and", "do_prune", ":", "k", "=", "tf", ".", "round", "(", "to_float", "("...
272500b6efe353aeb638d2745ed56e519462ca31
train
kl_divergence
KL divergence of diagonal gaussian N(mu,exp(log_var)) and N(0,1). Args: mu: mu parameter of the distribution. log_var: log(var) parameter of the distribution. mu_p: optional mu from a learned prior distribution log_var_p: optional log(var) from a learned prior distribution Returns: the KL loss.
tensor2tensor/layers/common_layers.py
def kl_divergence(mu, log_var, mu_p=0.0, log_var_p=0.0): """KL divergence of diagonal gaussian N(mu,exp(log_var)) and N(0,1). Args: mu: mu parameter of the distribution. log_var: log(var) parameter of the distribution. mu_p: optional mu from a learned prior distribution log_var_p: optional log(var)...
def kl_divergence(mu, log_var, mu_p=0.0, log_var_p=0.0): """KL divergence of diagonal gaussian N(mu,exp(log_var)) and N(0,1). Args: mu: mu parameter of the distribution. log_var: log(var) parameter of the distribution. mu_p: optional mu from a learned prior distribution log_var_p: optional log(var)...
[ "KL", "divergence", "of", "diagonal", "gaussian", "N", "(", "mu", "exp", "(", "log_var", "))", "and", "N", "(", "0", "1", ")", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3985-L4004
[ "def", "kl_divergence", "(", "mu", ",", "log_var", ",", "mu_p", "=", "0.0", ",", "log_var_p", "=", "0.0", ")", ":", "batch_size", "=", "shape_list", "(", "mu", ")", "[", "0", "]", "prior_distribution", "=", "tfp", ".", "distributions", ".", "Normal", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
FactoredTensor.to_tensor
Convert to Tensor.
tensor2tensor/layers/common_layers.py
def to_tensor(self): """Convert to Tensor.""" a_shape = shape_list(self.a) b_shape = shape_list(self.b) inner_dim = b_shape[1] result_dim = b_shape[0] flat_a = tf.reshape(self.a, [-1, inner_dim]) product = tf.matmul(flat_a, self.b, transpose_b=True) product_shape = a_shape[:-1] + [result...
def to_tensor(self): """Convert to Tensor.""" a_shape = shape_list(self.a) b_shape = shape_list(self.b) inner_dim = b_shape[1] result_dim = b_shape[0] flat_a = tf.reshape(self.a, [-1, inner_dim]) product = tf.matmul(flat_a, self.b, transpose_b=True) product_shape = a_shape[:-1] + [result...
[ "Convert", "to", "Tensor", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2601-L2613
[ "def", "to_tensor", "(", "self", ")", ":", "a_shape", "=", "shape_list", "(", "self", ".", "a", ")", "b_shape", "=", "shape_list", "(", "self", ".", "b", ")", "inner_dim", "=", "b_shape", "[", "1", "]", "result_dim", "=", "b_shape", "[", "0", "]", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
WeightNorm._compute_weights
Generate weights with normalization.
tensor2tensor/layers/common_layers.py
def _compute_weights(self): """Generate weights with normalization.""" with tf.variable_scope("compute_weights"): self.layer.kernel = tf.nn.l2_normalize( self.layer.v, axis=self.norm_axes) * self.layer.g
def _compute_weights(self): """Generate weights with normalization.""" with tf.variable_scope("compute_weights"): self.layer.kernel = tf.nn.l2_normalize( self.layer.v, axis=self.norm_axes) * self.layer.g
[ "Generate", "weights", "with", "normalization", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L4089-L4093
[ "def", "_compute_weights", "(", "self", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"compute_weights\"", ")", ":", "self", ".", "layer", ".", "kernel", "=", "tf", ".", "nn", ".", "l2_normalize", "(", "self", ".", "layer", ".", "v", ",", "axis...
272500b6efe353aeb638d2745ed56e519462ca31
train
WeightNorm._init_norm
Set the norm of the weight vector.
tensor2tensor/layers/common_layers.py
def _init_norm(self, weights): """Set the norm of the weight vector.""" with tf.variable_scope("init_norm"): flat = tf.reshape(weights, [-1, self.layer_depth]) return tf.reshape(tf.norm(flat, axis=0), (self.layer_depth,))
def _init_norm(self, weights): """Set the norm of the weight vector.""" with tf.variable_scope("init_norm"): flat = tf.reshape(weights, [-1, self.layer_depth]) return tf.reshape(tf.norm(flat, axis=0), (self.layer_depth,))
[ "Set", "the", "norm", "of", "the", "weight", "vector", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L4095-L4099
[ "def", "_init_norm", "(", "self", ",", "weights", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"init_norm\"", ")", ":", "flat", "=", "tf", ".", "reshape", "(", "weights", ",", "[", "-", "1", ",", "self", ".", "layer_depth", "]", ")", "return...
272500b6efe353aeb638d2745ed56e519462ca31
train
WeightNorm._data_dep_init
Data dependent initialization for eager execution.
tensor2tensor/layers/common_layers.py
def _data_dep_init(self, inputs): """Data dependent initialization for eager execution.""" with tf.variable_scope("data_dep_init"): # Generate data dependent init values activation = self.layer.activation self.layer.activation = None x_init = self.layer.call(inputs) m_init, v_init...
def _data_dep_init(self, inputs): """Data dependent initialization for eager execution.""" with tf.variable_scope("data_dep_init"): # Generate data dependent init values activation = self.layer.activation self.layer.activation = None x_init = self.layer.call(inputs) m_init, v_init...
[ "Data", "dependent", "initialization", "for", "eager", "execution", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L4101-L4116
[ "def", "_data_dep_init", "(", "self", ",", "inputs", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"data_dep_init\"", ")", ":", "# Generate data dependent init values", "activation", "=", "self", ".", "layer", ".", "activation", "self", ".", "layer", "."...
272500b6efe353aeb638d2745ed56e519462ca31
train
WeightNorm.build
Build `Layer`.
tensor2tensor/layers/common_layers.py
def build(self, input_shape=None): """Build `Layer`.""" input_shape = tf.TensorShape(input_shape).as_list() self.input_spec = layers().InputSpec(shape=input_shape) if not self.layer.built: self.layer.build(input_shape) self.layer.built = False if not hasattr(self.layer, "kernel"): ...
def build(self, input_shape=None): """Build `Layer`.""" input_shape = tf.TensorShape(input_shape).as_list() self.input_spec = layers().InputSpec(shape=input_shape) if not self.layer.built: self.layer.build(input_shape) self.layer.built = False if not hasattr(self.layer, "kernel"): ...
[ "Build", "Layer", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L4118-L4151
[ "def", "build", "(", "self", ",", "input_shape", "=", "None", ")", ":", "input_shape", "=", "tf", ".", "TensorShape", "(", "input_shape", ")", ".", "as_list", "(", ")", "self", ".", "input_spec", "=", "layers", "(", ")", ".", "InputSpec", "(", "shape",...
272500b6efe353aeb638d2745ed56e519462ca31
train
WeightNorm.call
Call `Layer`.
tensor2tensor/layers/common_layers.py
def call(self, inputs): """Call `Layer`.""" # if context.executing_eagerly(): # if not self.initialized: # self._data_dep_init(inputs) self._compute_weights() # Recompute weights for each forward pass output = self.layer.call(inputs) return output
def call(self, inputs): """Call `Layer`.""" # if context.executing_eagerly(): # if not self.initialized: # self._data_dep_init(inputs) self._compute_weights() # Recompute weights for each forward pass output = self.layer.call(inputs) return output
[ "Call", "Layer", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L4153-L4161
[ "def", "call", "(", "self", ",", "inputs", ")", ":", "# if context.executing_eagerly():", "# if not self.initialized:", "# self._data_dep_init(inputs)", "self", ".", "_compute_weights", "(", ")", "# Recompute weights for each forward pass", "output", "=", "self", ".", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
compute_mean_reward
Calculate mean rewards from given epoch.
tensor2tensor/rl/rl_utils.py
def compute_mean_reward(rollouts, clipped): """Calculate mean rewards from given epoch.""" reward_name = "reward" if clipped else "unclipped_reward" rewards = [] for rollout in rollouts: if rollout[-1].done: rollout_reward = sum(getattr(frame, reward_name) for frame in rollout) rewards.append(ro...
def compute_mean_reward(rollouts, clipped): """Calculate mean rewards from given epoch.""" reward_name = "reward" if clipped else "unclipped_reward" rewards = [] for rollout in rollouts: if rollout[-1].done: rollout_reward = sum(getattr(frame, reward_name) for frame in rollout) rewards.append(ro...
[ "Calculate", "mean", "rewards", "from", "given", "epoch", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L45-L57
[ "def", "compute_mean_reward", "(", "rollouts", ",", "clipped", ")", ":", "reward_name", "=", "\"reward\"", "if", "clipped", "else", "\"unclipped_reward\"", "rewards", "=", "[", "]", "for", "rollout", "in", "rollouts", ":", "if", "rollout", "[", "-", "1", "]"...
272500b6efe353aeb638d2745ed56e519462ca31
train
evaluate_single_config
Evaluate the PPO agent in the real environment.
tensor2tensor/rl/rl_utils.py
def evaluate_single_config( hparams, sampling_temp, max_num_noops, agent_model_dir, eval_fn=_eval_fn_with_learner ): """Evaluate the PPO agent in the real environment.""" tf.logging.info("Evaluating metric %s", get_metric_name( sampling_temp, max_num_noops, clipped=False )) eval_hparams = trainer_...
def evaluate_single_config( hparams, sampling_temp, max_num_noops, agent_model_dir, eval_fn=_eval_fn_with_learner ): """Evaluate the PPO agent in the real environment.""" tf.logging.info("Evaluating metric %s", get_metric_name( sampling_temp, max_num_noops, clipped=False )) eval_hparams = trainer_...
[ "Evaluate", "the", "PPO", "agent", "in", "the", "real", "environment", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L77-L97
[ "def", "evaluate_single_config", "(", "hparams", ",", "sampling_temp", ",", "max_num_noops", ",", "agent_model_dir", ",", "eval_fn", "=", "_eval_fn_with_learner", ")", ":", "tf", ".", "logging", ".", "info", "(", "\"Evaluating metric %s\"", ",", "get_metric_name", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
evaluate_all_configs
Evaluate the agent with multiple eval configurations.
tensor2tensor/rl/rl_utils.py
def evaluate_all_configs( hparams, agent_model_dir, eval_fn=_eval_fn_with_learner ): """Evaluate the agent with multiple eval configurations.""" metrics = {} # Iterate over all combinations of sampling temperatures and whether to do # initial no-ops. for sampling_temp in hparams.eval_sampling_temps: #...
def evaluate_all_configs( hparams, agent_model_dir, eval_fn=_eval_fn_with_learner ): """Evaluate the agent with multiple eval configurations.""" metrics = {} # Iterate over all combinations of sampling temperatures and whether to do # initial no-ops. for sampling_temp in hparams.eval_sampling_temps: #...
[ "Evaluate", "the", "agent", "with", "multiple", "eval", "configurations", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L100-L117
[ "def", "evaluate_all_configs", "(", "hparams", ",", "agent_model_dir", ",", "eval_fn", "=", "_eval_fn_with_learner", ")", ":", "metrics", "=", "{", "}", "# Iterate over all combinations of sampling temperatures and whether to do", "# initial no-ops.", "for", "sampling_temp", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
evaluate_world_model
Evaluate the world model (reward accuracy).
tensor2tensor/rl/rl_utils.py
def evaluate_world_model( real_env, hparams, world_model_dir, debug_video_path, split=tf.estimator.ModeKeys.EVAL, ): """Evaluate the world model (reward accuracy).""" frame_stack_size = hparams.frame_stack_size rollout_subsequences = [] def initial_frame_chooser(batch_size): assert batch_size == len...
def evaluate_world_model( real_env, hparams, world_model_dir, debug_video_path, split=tf.estimator.ModeKeys.EVAL, ): """Evaluate the world model (reward accuracy).""" frame_stack_size = hparams.frame_stack_size rollout_subsequences = [] def initial_frame_chooser(batch_size): assert batch_size == len...
[ "Evaluate", "the", "world", "model", "(", "reward", "accuracy", ")", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L120-L249
[ "def", "evaluate_world_model", "(", "real_env", ",", "hparams", ",", "world_model_dir", ",", "debug_video_path", ",", "split", "=", "tf", ".", "estimator", ".", "ModeKeys", ".", "EVAL", ",", ")", ":", "frame_stack_size", "=", "hparams", ".", "frame_stack_size", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
summarize_metrics
Write metrics to summary.
tensor2tensor/rl/rl_utils.py
def summarize_metrics(eval_metrics_writer, metrics, epoch): """Write metrics to summary.""" for (name, value) in six.iteritems(metrics): summary = tf.Summary() summary.value.add(tag=name, simple_value=value) eval_metrics_writer.add_summary(summary, epoch) eval_metrics_writer.flush()
def summarize_metrics(eval_metrics_writer, metrics, epoch): """Write metrics to summary.""" for (name, value) in six.iteritems(metrics): summary = tf.Summary() summary.value.add(tag=name, simple_value=value) eval_metrics_writer.add_summary(summary, epoch) eval_metrics_writer.flush()
[ "Write", "metrics", "to", "summary", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L252-L258
[ "def", "summarize_metrics", "(", "eval_metrics_writer", ",", "metrics", ",", "epoch", ")", ":", "for", "(", "name", ",", "value", ")", "in", "six", ".", "iteritems", "(", "metrics", ")", ":", "summary", "=", "tf", ".", "Summary", "(", ")", "summary", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
full_game_name
CamelCase game name with mode suffix. Args: short_name: snake_case name without mode e.g "crazy_climber" Returns: full game name e.g. "CrazyClimberNoFrameskip-v4"
tensor2tensor/rl/rl_utils.py
def full_game_name(short_name): """CamelCase game name with mode suffix. Args: short_name: snake_case name without mode e.g "crazy_climber" Returns: full game name e.g. "CrazyClimberNoFrameskip-v4" """ camel_game_name = misc_utils.snakecase_to_camelcase(short_name) full_name = camel_game_name + AT...
def full_game_name(short_name): """CamelCase game name with mode suffix. Args: short_name: snake_case name without mode e.g "crazy_climber" Returns: full game name e.g. "CrazyClimberNoFrameskip-v4" """ camel_game_name = misc_utils.snakecase_to_camelcase(short_name) full_name = camel_game_name + AT...
[ "CamelCase", "game", "name", "with", "mode", "suffix", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L270-L281
[ "def", "full_game_name", "(", "short_name", ")", ":", "camel_game_name", "=", "misc_utils", ".", "snakecase_to_camelcase", "(", "short_name", ")", "full_name", "=", "camel_game_name", "+", "ATARI_GAME_MODE", "return", "full_name" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
setup_env
Setup.
tensor2tensor/rl/rl_utils.py
def setup_env(hparams, batch_size, max_num_noops, rl_env_max_episode_steps=-1, env_name=None): """Setup.""" if not env_name: env_name = full_game_name(hparams.game) maxskip_envs = should_apply_max_and_skip_env(hparams) env = T2TGymEnv( base_env...
def setup_env(hparams, batch_size, max_num_noops, rl_env_max_episode_steps=-1, env_name=None): """Setup.""" if not env_name: env_name = full_game_name(hparams.game) maxskip_envs = should_apply_max_and_skip_env(hparams) env = T2TGymEnv( base_env...
[ "Setup", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L289-L313
[ "def", "setup_env", "(", "hparams", ",", "batch_size", ",", "max_num_noops", ",", "rl_env_max_episode_steps", "=", "-", "1", ",", "env_name", "=", "None", ")", ":", "if", "not", "env_name", ":", "env_name", "=", "full_game_name", "(", "hparams", ".", "game",...
272500b6efe353aeb638d2745ed56e519462ca31
train
update_hparams_from_hparams
Copy a subset of hparams to target_hparams.
tensor2tensor/rl/rl_utils.py
def update_hparams_from_hparams(target_hparams, source_hparams, prefix): """Copy a subset of hparams to target_hparams.""" for (param_name, param_value) in six.iteritems(source_hparams.values()): if param_name.startswith(prefix): target_hparams.set_hparam(param_name[len(prefix):], param_value)
def update_hparams_from_hparams(target_hparams, source_hparams, prefix): """Copy a subset of hparams to target_hparams.""" for (param_name, param_value) in six.iteritems(source_hparams.values()): if param_name.startswith(prefix): target_hparams.set_hparam(param_name[len(prefix):], param_value)
[ "Copy", "a", "subset", "of", "hparams", "to", "target_hparams", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L316-L320
[ "def", "update_hparams_from_hparams", "(", "target_hparams", ",", "source_hparams", ",", "prefix", ")", ":", "for", "(", "param_name", ",", "param_value", ")", "in", "six", ".", "iteritems", "(", "source_hparams", ".", "values", "(", ")", ")", ":", "if", "pa...
272500b6efe353aeb638d2745ed56e519462ca31
train
random_rollout_subsequences
Chooses a random frame sequence of given length from a set of rollouts.
tensor2tensor/rl/rl_utils.py
def random_rollout_subsequences(rollouts, num_subsequences, subsequence_length): """Chooses a random frame sequence of given length from a set of rollouts.""" def choose_subsequence(): # TODO(koz4k): Weigh rollouts by their lengths so sampling is uniform over # frames and not rollouts. rollout = random....
def random_rollout_subsequences(rollouts, num_subsequences, subsequence_length): """Chooses a random frame sequence of given length from a set of rollouts.""" def choose_subsequence(): # TODO(koz4k): Weigh rollouts by their lengths so sampling is uniform over # frames and not rollouts. rollout = random....
[ "Chooses", "a", "random", "frame", "sequence", "of", "given", "length", "from", "a", "set", "of", "rollouts", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L323-L336
[ "def", "random_rollout_subsequences", "(", "rollouts", ",", "num_subsequences", ",", "subsequence_length", ")", ":", "def", "choose_subsequence", "(", ")", ":", "# TODO(koz4k): Weigh rollouts by their lengths so sampling is uniform over", "# frames and not rollouts.", "rollout", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
make_initial_frame_chooser
Make frame chooser. Args: real_env: T2TEnv to take initial frames from. frame_stack_size (int): Number of consecutive frames to extract. simulation_random_starts (bool): Whether to choose frames at random. simulation_flip_first_random_for_beginning (bool): Whether to flip the first frame stack ...
tensor2tensor/rl/rl_utils.py
def make_initial_frame_chooser( real_env, frame_stack_size, simulation_random_starts, simulation_flip_first_random_for_beginning, split=tf.estimator.ModeKeys.TRAIN, ): """Make frame chooser. Args: real_env: T2TEnv to take initial frames from. frame_stack_size (int): Number of consecutive frames...
def make_initial_frame_chooser( real_env, frame_stack_size, simulation_random_starts, simulation_flip_first_random_for_beginning, split=tf.estimator.ModeKeys.TRAIN, ): """Make frame chooser. Args: real_env: T2TEnv to take initial frames from. frame_stack_size (int): Number of consecutive frames...
[ "Make", "frame", "chooser", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L339-L382
[ "def", "make_initial_frame_chooser", "(", "real_env", ",", "frame_stack_size", ",", "simulation_random_starts", ",", "simulation_flip_first_random_for_beginning", ",", "split", "=", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", ",", ")", ":", "initial_frame_rol...
272500b6efe353aeb638d2745ed56e519462ca31
train
absolute_hinge_difference
Point-wise, hinge loss-like, difference between arrays. Args: arr1: integer array to compare. arr2: integer array to compare. min_diff: minimal difference taken into consideration. dtype: dtype of returned array. Returns: array
tensor2tensor/rl/rl_utils.py
def absolute_hinge_difference(arr1, arr2, min_diff=10, dtype=np.uint8): """Point-wise, hinge loss-like, difference between arrays. Args: arr1: integer array to compare. arr2: integer array to compare. min_diff: minimal difference taken into consideration. dtype: dtype of returned array. Returns:...
def absolute_hinge_difference(arr1, arr2, min_diff=10, dtype=np.uint8): """Point-wise, hinge loss-like, difference between arrays. Args: arr1: integer array to compare. arr2: integer array to compare. min_diff: minimal difference taken into consideration. dtype: dtype of returned array. Returns:...
[ "Point", "-", "wise", "hinge", "loss", "-", "like", "difference", "between", "arrays", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L385-L398
[ "def", "absolute_hinge_difference", "(", "arr1", ",", "arr2", ",", "min_diff", "=", "10", ",", "dtype", "=", "np", ".", "uint8", ")", ":", "diff", "=", "np", ".", "abs", "(", "arr1", ".", "astype", "(", "np", ".", "int", ")", "-", "arr2", ",", "d...
272500b6efe353aeb638d2745ed56e519462ca31
train
augment_observation
Augments an observation with debug info.
tensor2tensor/rl/rl_utils.py
def augment_observation( observation, reward, cum_reward, frame_index, bar_color=None, header_height=27 ): """Augments an observation with debug info.""" img = PIL_Image().new( "RGB", (observation.shape[1], header_height,) ) draw = PIL_ImageDraw().Draw(img) draw.text( (1, 0), "c:{:3}, r:{:...
def augment_observation( observation, reward, cum_reward, frame_index, bar_color=None, header_height=27 ): """Augments an observation with debug info.""" img = PIL_Image().new( "RGB", (observation.shape[1], header_height,) ) draw = PIL_ImageDraw().Draw(img) draw.text( (1, 0), "c:{:3}, r:{:...
[ "Augments", "an", "observation", "with", "debug", "info", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L402-L423
[ "def", "augment_observation", "(", "observation", ",", "reward", ",", "cum_reward", ",", "frame_index", ",", "bar_color", "=", "None", ",", "header_height", "=", "27", ")", ":", "img", "=", "PIL_Image", "(", ")", ".", "new", "(", "\"RGB\"", ",", "(", "ob...
272500b6efe353aeb638d2745ed56e519462ca31
train
run_rollouts
Runs a batch of rollouts from given initial observations.
tensor2tensor/rl/rl_utils.py
def run_rollouts( env, agent, initial_observations, step_limit=None, discount_factor=1.0, log_every_steps=None, video_writers=(), color_bar=False, many_rollouts_from_each_env=False ): """Runs a batch of rollouts from given initial observations.""" assert step_limit is not None or not many_rollouts_from_...
def run_rollouts( env, agent, initial_observations, step_limit=None, discount_factor=1.0, log_every_steps=None, video_writers=(), color_bar=False, many_rollouts_from_each_env=False ): """Runs a batch of rollouts from given initial observations.""" assert step_limit is not None or not many_rollouts_from_...
[ "Runs", "a", "batch", "of", "rollouts", "from", "given", "initial", "observations", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L426-L499
[ "def", "run_rollouts", "(", "env", ",", "agent", ",", "initial_observations", ",", "step_limit", "=", "None", ",", "discount_factor", "=", "1.0", ",", "log_every_steps", "=", "None", ",", "video_writers", "=", "(", ")", ",", "color_bar", "=", "False", ",", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
BatchStackWrapper.set_initial_state
Sets the state that will be used on next reset.
tensor2tensor/rl/rl_utils.py
def set_initial_state(self, initial_state, initial_frames): """Sets the state that will be used on next reset.""" self.env.set_initial_state(initial_state, initial_frames) self._initial_frames = initial_frames
def set_initial_state(self, initial_state, initial_frames): """Sets the state that will be used on next reset.""" self.env.set_initial_state(initial_state, initial_frames) self._initial_frames = initial_frames
[ "Sets", "the", "state", "that", "will", "be", "used", "on", "next", "reset", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L806-L809
[ "def", "set_initial_state", "(", "self", ",", "initial_state", ",", "initial_frames", ")", ":", "self", ".", "env", ".", "set_initial_state", "(", "initial_state", ",", "initial_frames", ")", "self", ".", "_initial_frames", "=", "initial_frames" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
_maybe_download_corpora
Download corpora if necessary and unzip them. Args: tmp_dir: directory containing dataset. dataset_split: whether we're in train/dev/test mode. Returns: List of all files generated and path to file containing train/dev/test split info.
tensor2tensor/data_generators/cnn_dailymail.py
def _maybe_download_corpora(tmp_dir, dataset_split): """Download corpora if necessary and unzip them. Args: tmp_dir: directory containing dataset. dataset_split: whether we're in train/dev/test mode. Returns: List of all files generated and path to file containing train/dev/test split info. ...
def _maybe_download_corpora(tmp_dir, dataset_split): """Download corpora if necessary and unzip them. Args: tmp_dir: directory containing dataset. dataset_split: whether we're in train/dev/test mode. Returns: List of all files generated and path to file containing train/dev/test split info. ...
[ "Download", "corpora", "if", "necessary", "and", "unzip", "them", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/cnn_dailymail.py#L67-L107
[ "def", "_maybe_download_corpora", "(", "tmp_dir", ",", "dataset_split", ")", ":", "cnn_filename", "=", "\"cnn_stories.tgz\"", "cnn_finalpath", "=", "os", ".", "path", ".", "join", "(", "tmp_dir", ",", "\"cnn/stories/\"", ")", "dailymail_filename", "=", "\"dailymail_...
272500b6efe353aeb638d2745ed56e519462ca31
train
example_splits
Generate splits of the data.
tensor2tensor/data_generators/cnn_dailymail.py
def example_splits(url_file, all_files): """Generate splits of the data.""" def generate_hash(inp): """Generate a sha1 hash to match the raw url to the filename extracted.""" h = hashlib.sha1() h.update(inp) return h.hexdigest() all_files_map = {f.split("/")[-1]: f for f in all_files} urls = ...
def example_splits(url_file, all_files): """Generate splits of the data.""" def generate_hash(inp): """Generate a sha1 hash to match the raw url to the filename extracted.""" h = hashlib.sha1() h.update(inp) return h.hexdigest() all_files_map = {f.split("/")[-1]: f for f in all_files} urls = ...
[ "Generate", "splits", "of", "the", "data", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/cnn_dailymail.py#L110-L134
[ "def", "example_splits", "(", "url_file", ",", "all_files", ")", ":", "def", "generate_hash", "(", "inp", ")", ":", "\"\"\"Generate a sha1 hash to match the raw url to the filename extracted.\"\"\"", "h", "=", "hashlib", ".", "sha1", "(", ")", "h", ".", "update", "(...
272500b6efe353aeb638d2745ed56e519462ca31
train
example_generator
Generate examples.
tensor2tensor/data_generators/cnn_dailymail.py
def example_generator(all_files, urls_path, sum_token): """Generate examples.""" def fix_run_on_sents(line): if u"@highlight" in line: return line if not line: return line if line[-1] in END_TOKENS: return line return line + u"." filelist = example_splits(urls_path, all_files) ...
def example_generator(all_files, urls_path, sum_token): """Generate examples.""" def fix_run_on_sents(line): if u"@highlight" in line: return line if not line: return line if line[-1] in END_TOKENS: return line return line + u"." filelist = example_splits(urls_path, all_files) ...
[ "Generate", "examples", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/cnn_dailymail.py#L137-L173
[ "def", "example_generator", "(", "all_files", ",", "urls_path", ",", "sum_token", ")", ":", "def", "fix_run_on_sents", "(", "line", ")", ":", "if", "u\"@highlight\"", "in", "line", ":", "return", "line", "if", "not", "line", ":", "return", "line", "if", "l...
272500b6efe353aeb638d2745ed56e519462ca31
train
write_raw_text_to_files
Write text to files.
tensor2tensor/data_generators/cnn_dailymail.py
def write_raw_text_to_files(all_files, urls_path, dataset_split, tmp_dir): """Write text to files.""" def write_to_file(all_files, urls_path, tmp_dir, filename): """Write text to files.""" with io.open( os.path.join(tmp_dir, filename + ".source"), "w", encoding="utf-8") as fstory: wit...
def write_raw_text_to_files(all_files, urls_path, dataset_split, tmp_dir): """Write text to files.""" def write_to_file(all_files, urls_path, tmp_dir, filename): """Write text to files.""" with io.open( os.path.join(tmp_dir, filename + ".source"), "w", encoding="utf-8") as fstory: wit...
[ "Write", "text", "to", "files", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/cnn_dailymail.py#L183-L207
[ "def", "write_raw_text_to_files", "(", "all_files", ",", "urls_path", ",", "dataset_split", ",", "tmp_dir", ")", ":", "def", "write_to_file", "(", "all_files", ",", "urls_path", ",", "tmp_dir", ",", "filename", ")", ":", "\"\"\"Write text to files.\"\"\"", "with", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
infer_last_epoch_num
Infer highest epoch number from file names in data_dir.
tensor2tensor/rl/player_utils.py
def infer_last_epoch_num(data_dir): """Infer highest epoch number from file names in data_dir.""" names = os.listdir(data_dir) epochs_str = [re.findall(pattern=r".*\.(-?\d+)$", string=name) for name in names] epochs_str = sum(epochs_str, []) return max([int(epoch_str) for epoch_str in epochs_s...
def infer_last_epoch_num(data_dir): """Infer highest epoch number from file names in data_dir.""" names = os.listdir(data_dir) epochs_str = [re.findall(pattern=r".*\.(-?\d+)$", string=name) for name in names] epochs_str = sum(epochs_str, []) return max([int(epoch_str) for epoch_str in epochs_s...
[ "Infer", "highest", "epoch", "number", "from", "file", "names", "in", "data_dir", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L123-L129
[ "def", "infer_last_epoch_num", "(", "data_dir", ")", ":", "names", "=", "os", ".", "listdir", "(", "data_dir", ")", "epochs_str", "=", "[", "re", ".", "findall", "(", "pattern", "=", "r\".*\\.(-?\\d+)$\"", ",", "string", "=", "name", ")", "for", "name", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
setup_and_load_epoch
Load T2TGymEnv with data from one epoch. Args: hparams: hparams. data_dir: data directory. which_epoch_data: data from which epoch to load. Returns: env.
tensor2tensor/rl/player_utils.py
def setup_and_load_epoch(hparams, data_dir, which_epoch_data=None): """Load T2TGymEnv with data from one epoch. Args: hparams: hparams. data_dir: data directory. which_epoch_data: data from which epoch to load. Returns: env. """ t2t_env = rl_utils.setup_env( hparams, batch_size=hparams...
def setup_and_load_epoch(hparams, data_dir, which_epoch_data=None): """Load T2TGymEnv with data from one epoch. Args: hparams: hparams. data_dir: data directory. which_epoch_data: data from which epoch to load. Returns: env. """ t2t_env = rl_utils.setup_env( hparams, batch_size=hparams...
[ "Load", "T2TGymEnv", "with", "data", "from", "one", "epoch", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L132-L156
[ "def", "setup_and_load_epoch", "(", "hparams", ",", "data_dir", ",", "which_epoch_data", "=", "None", ")", ":", "t2t_env", "=", "rl_utils", ".", "setup_env", "(", "hparams", ",", "batch_size", "=", "hparams", ".", "real_batch_size", ",", "max_num_noops", "=", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
infer_game_name_from_filenames
Infer name from filenames.
tensor2tensor/rl/player_utils.py
def infer_game_name_from_filenames(data_dir, snake_case=True): """Infer name from filenames.""" names = os.listdir(data_dir) game_names = [re.findall(pattern=r"^Gym(.*)NoFrameskip", string=name) for name in names] assert game_names, "No data files found in {}".format(data_dir) game_names = sum...
def infer_game_name_from_filenames(data_dir, snake_case=True): """Infer name from filenames.""" names = os.listdir(data_dir) game_names = [re.findall(pattern=r"^Gym(.*)NoFrameskip", string=name) for name in names] assert game_names, "No data files found in {}".format(data_dir) game_names = sum...
[ "Infer", "name", "from", "filenames", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L159-L171
[ "def", "infer_game_name_from_filenames", "(", "data_dir", ",", "snake_case", "=", "True", ")", ":", "names", "=", "os", ".", "listdir", "(", "data_dir", ")", "game_names", "=", "[", "re", ".", "findall", "(", "pattern", "=", "r\"^Gym(.*)NoFrameskip\"", ",", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
wrap_with_monitor
Wrap environment with gym.Monitor. Video recording provided by Monitor requires 1) both height and width of observation to be even numbers. 2) rendering of environment Args: env: environment. video_dir: video directory. Returns: wrapped environment.
tensor2tensor/rl/player_utils.py
def wrap_with_monitor(env, video_dir): """Wrap environment with gym.Monitor. Video recording provided by Monitor requires 1) both height and width of observation to be even numbers. 2) rendering of environment Args: env: environment. video_dir: video directory. Returns: wrapped environmen...
def wrap_with_monitor(env, video_dir): """Wrap environment with gym.Monitor. Video recording provided by Monitor requires 1) both height and width of observation to be even numbers. 2) rendering of environment Args: env: environment. video_dir: video directory. Returns: wrapped environmen...
[ "Wrap", "environment", "with", "gym", ".", "Monitor", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L245-L264
[ "def", "wrap_with_monitor", "(", "env", ",", "video_dir", ")", ":", "env", "=", "ExtendToEvenDimentions", "(", "env", ")", "env", "=", "RenderObservations", "(", "env", ")", "# pylint: disable=redefined-variable-type", "env", "=", "gym", ".", "wrappers", ".", "M...
272500b6efe353aeb638d2745ed56e519462ca31
train
create_simulated_env
Create SimulatedEnv with minimal subset of hparams.
tensor2tensor/rl/player_utils.py
def create_simulated_env( output_dir, grayscale, resize_width_factor, resize_height_factor, frame_stack_size, generative_model, generative_model_params, random_starts=True, which_epoch_data="last", **other_hparams ): """"Create SimulatedEnv with minimal subset of hparams.""" # We need these, to initiali...
def create_simulated_env( output_dir, grayscale, resize_width_factor, resize_height_factor, frame_stack_size, generative_model, generative_model_params, random_starts=True, which_epoch_data="last", **other_hparams ): """"Create SimulatedEnv with minimal subset of hparams.""" # We need these, to initiali...
[ "Create", "SimulatedEnv", "with", "minimal", "subset", "of", "hparams", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L267-L298
[ "def", "create_simulated_env", "(", "output_dir", ",", "grayscale", ",", "resize_width_factor", ",", "resize_height_factor", ",", "frame_stack_size", ",", "generative_model", ",", "generative_model_params", ",", "random_starts", "=", "True", ",", "which_epoch_data", "=", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
infer_paths
Infers standard paths to policy and model directories. Example: >>> infer_paths("/some/output/dir/", policy="", model="custom/path") {"policy": "/some/output/dir/policy", "model": "custom/path", "output_dir":"/some/output/dir/"} Args: output_dir: output directory. **subdirs: sub-directories. ...
tensor2tensor/rl/player_utils.py
def infer_paths(output_dir, **subdirs): """Infers standard paths to policy and model directories. Example: >>> infer_paths("/some/output/dir/", policy="", model="custom/path") {"policy": "/some/output/dir/policy", "model": "custom/path", "output_dir":"/some/output/dir/"} Args: output_dir: output...
def infer_paths(output_dir, **subdirs): """Infers standard paths to policy and model directories. Example: >>> infer_paths("/some/output/dir/", policy="", model="custom/path") {"policy": "/some/output/dir/policy", "model": "custom/path", "output_dir":"/some/output/dir/"} Args: output_dir: output...
[ "Infers", "standard", "paths", "to", "policy", "and", "model", "directories", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L377-L396
[ "def", "infer_paths", "(", "output_dir", ",", "*", "*", "subdirs", ")", ":", "directories", "=", "{", "}", "for", "name", ",", "path", "in", "six", ".", "iteritems", "(", "subdirs", ")", ":", "directories", "[", "name", "]", "=", "path", "if", "path"...
272500b6efe353aeb638d2745ed56e519462ca31
train
SimulatedGymEnv.add_to_initial_stack
Adds new frame to (initial) frame stack, removes last one.
tensor2tensor/rl/player_utils.py
def add_to_initial_stack(self, frame): """Adds new frame to (initial) frame stack, removes last one.""" if not self._setable_initial_frames: raise ValueError( "This instance does not allow to manually set initial frame stack.") assert_msg = "{}, {}".format(frame.shape, self._initial_frames.s...
def add_to_initial_stack(self, frame): """Adds new frame to (initial) frame stack, removes last one.""" if not self._setable_initial_frames: raise ValueError( "This instance does not allow to manually set initial frame stack.") assert_msg = "{}, {}".format(frame.shape, self._initial_frames.s...
[ "Adds", "new", "frame", "to", "(", "initial", ")", "frame", "stack", "removes", "last", "one", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L111-L120
[ "def", "add_to_initial_stack", "(", "self", ",", "frame", ")", ":", "if", "not", "self", ".", "_setable_initial_frames", ":", "raise", "ValueError", "(", "\"This instance does not allow to manually set initial frame stack.\"", ")", "assert_msg", "=", "\"{}, {}\"", ".", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
ExtendToEvenDimentions.observation
Add single zero row/column to observation if needed.
tensor2tensor/rl/player_utils.py
def observation(self, frame): """Add single zero row/column to observation if needed.""" if frame.shape == self.observation_space.shape: return frame else: extended_frame = np.zeros(self.observation_space.shape, self.observation_space.dtype) assert self.HW_A...
def observation(self, frame): """Add single zero row/column to observation if needed.""" if frame.shape == self.observation_space.shape: return frame else: extended_frame = np.zeros(self.observation_space.shape, self.observation_space.dtype) assert self.HW_A...
[ "Add", "single", "zero", "row", "/", "column", "to", "observation", "if", "needed", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L208-L217
[ "def", "observation", "(", "self", ",", "frame", ")", ":", "if", "frame", ".", "shape", "==", "self", ".", "observation_space", ".", "shape", ":", "return", "frame", "else", ":", "extended_frame", "=", "np", ".", "zeros", "(", "self", ".", "observation_s...
272500b6efe353aeb638d2745ed56e519462ca31
train
PPOPolicyInferencer.infer
Add new observation to frame stack and infer policy. Args: ob: array of shape (height, width, channels) Returns: logits and vf.
tensor2tensor/rl/player_utils.py
def infer(self, ob): """Add new observation to frame stack and infer policy. Args: ob: array of shape (height, width, channels) Returns: logits and vf. """ self._add_to_stack(ob) logits, vf = self.infer_from_frame_stack(self._frame_stack) return logits, vf
def infer(self, ob): """Add new observation to frame stack and infer policy. Args: ob: array of shape (height, width, channels) Returns: logits and vf. """ self._add_to_stack(ob) logits, vf = self.infer_from_frame_stack(self._frame_stack) return logits, vf
[ "Add", "new", "observation", "to", "frame", "stack", "and", "infer", "policy", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L350-L361
[ "def", "infer", "(", "self", ",", "ob", ")", ":", "self", ".", "_add_to_stack", "(", "ob", ")", "logits", ",", "vf", "=", "self", ".", "infer_from_frame_stack", "(", "self", ".", "_frame_stack", ")", "return", "logits", ",", "vf" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
PPOPolicyInferencer.infer_from_frame_stack
Infer policy from stack of observations. Args: ob_stack: array of shape (1, frame_stack_size, height, width, channels) Returns: logits and vf.
tensor2tensor/rl/player_utils.py
def infer_from_frame_stack(self, ob_stack): """Infer policy from stack of observations. Args: ob_stack: array of shape (1, frame_stack_size, height, width, channels) Returns: logits and vf. """ logits, vf = self.sess.run([self.logits_t, self.value_function_t], ...
def infer_from_frame_stack(self, ob_stack): """Infer policy from stack of observations. Args: ob_stack: array of shape (1, frame_stack_size, height, width, channels) Returns: logits and vf. """ logits, vf = self.sess.run([self.logits_t, self.value_function_t], ...
[ "Infer", "policy", "from", "stack", "of", "observations", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L363-L374
[ "def", "infer_from_frame_stack", "(", "self", ",", "ob_stack", ")", ":", "logits", ",", "vf", "=", "self", ".", "sess", ".", "run", "(", "[", "self", ".", "logits_t", ",", "self", ".", "value_function_t", "]", ",", "feed_dict", "=", "{", "self", ".", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_normalize_string
Normalizes the string using tokenizer.encode. Args: raw_str: the input string Returns: A string which is ready to be tokenized using split()
tensor2tensor/data_generators/babi_qa.py
def _normalize_string(raw_str): """Normalizes the string using tokenizer.encode. Args: raw_str: the input string Returns: A string which is ready to be tokenized using split() """ return " ".join( token.strip() for token in tokenizer.encode(text_encoder.native_to_unicode(raw_str)))
def _normalize_string(raw_str): """Normalizes the string using tokenizer.encode. Args: raw_str: the input string Returns: A string which is ready to be tokenized using split() """ return " ".join( token.strip() for token in tokenizer.encode(text_encoder.native_to_unicode(raw_str)))
[ "Normalizes", "the", "string", "using", "tokenizer", ".", "encode", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/babi_qa.py#L84-L95
[ "def", "_normalize_string", "(", "raw_str", ")", ":", "return", "\" \"", ".", "join", "(", "token", ".", "strip", "(", ")", "for", "token", "in", "tokenizer", ".", "encode", "(", "text_encoder", ".", "native_to_unicode", "(", "raw_str", ")", ")", ")" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
_prepare_babi_data
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.
tensor2tensor/data_generators/babi_qa.py
def _prepare_babi_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 _prepare_babi_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...
[ "Downloads", "and", "extracts", "the", "dataset", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/babi_qa.py#L98-L123
[ "def", "_prepare_babi_data", "(", "tmp_dir", ",", "data_dir", ")", ":", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "data_dir", ")", ":", "tf", ".", "gfile", ".", "MakeDirs", "(", "data_dir", ")", "file_path", "=", "os", ".", "path", ".", "j...
272500b6efe353aeb638d2745ed56e519462ca31
train
_babi_parser
Parsing the bAbi dataset (train and test). Args: tmp_dir: temp directory to download and extract the dataset babi_task_id: babi task id subset: babi subset dataset_split: dataset split (train or eval) joint_training: if training the model on all tasks. Returns: babi_instances: set of trai...
tensor2tensor/data_generators/babi_qa.py
def _babi_parser(tmp_dir, babi_task_id, subset, dataset_split, joint_training=True): """Parsing the bAbi dataset (train and test). Args: tmp_dir: temp directory to download and extract the dataset babi_task_id: babi task id subset: bab...
def _babi_parser(tmp_dir, babi_task_id, subset, dataset_split, joint_training=True): """Parsing the bAbi dataset (train and test). Args: tmp_dir: temp directory to download and extract the dataset babi_task_id: babi task id subset: bab...
[ "Parsing", "the", "bAbi", "dataset", "(", "train", "and", "test", ")", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/babi_qa.py#L152-L253
[ "def", "_babi_parser", "(", "tmp_dir", ",", "babi_task_id", ",", "subset", ",", "dataset_split", ",", "joint_training", "=", "True", ")", ":", "def", "_data_file", "(", "mode", ",", "task_id", ")", ":", "\"\"\"Generates the path to the data file for the given mode(tra...
272500b6efe353aeb638d2745ed56e519462ca31
train
_register_babi_problems
It dynamically instantiates a class for each babi subsets-tasks. @registry.register_problem class BabiQaConcatAllTasks_10k(EditSequenceRegexProblem): @property def babi_task_id(self): return "qa0" @property def babi_subset(self): return "en-10k" It does not put the classes int...
tensor2tensor/data_generators/babi_qa.py
def _register_babi_problems(): """It dynamically instantiates a class for each babi subsets-tasks. @registry.register_problem class BabiQaConcatAllTasks_10k(EditSequenceRegexProblem): @property def babi_task_id(self): return "qa0" @property def babi_subset(self): return "en-10k...
def _register_babi_problems(): """It dynamically instantiates a class for each babi subsets-tasks. @registry.register_problem class BabiQaConcatAllTasks_10k(EditSequenceRegexProblem): @property def babi_task_id(self): return "qa0" @property def babi_subset(self): return "en-10k...
[ "It", "dynamically", "instantiates", "a", "class", "for", "each", "babi", "subsets", "-", "tasks", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/babi_qa.py#L510-L539
[ "def", "_register_babi_problems", "(", ")", ":", "for", "(", "subset", ",", "subset_suffix", ")", "in", "[", "(", "\"en\"", ",", "\"_1k\"", ")", ",", "(", "\"en-10k\"", ",", "\"_10k\"", ")", "]", ":", "for", "problem_name", ",", "babi_task_id", "in", "si...
272500b6efe353aeb638d2745ed56e519462ca31
train
BabiQa.get_labels_encoder
Builds encoder for the given class labels. Args: data_dir: data directory Returns: An encoder for class labels.
tensor2tensor/data_generators/babi_qa.py
def get_labels_encoder(self, data_dir): """Builds encoder for the given class labels. Args: data_dir: data directory Returns: An encoder for class labels. """ label_filepath = os.path.join(data_dir, self.vocab_filename) return text_encoder.TokenTextEncoder(label_filepath)
def get_labels_encoder(self, data_dir): """Builds encoder for the given class labels. Args: data_dir: data directory Returns: An encoder for class labels. """ label_filepath = os.path.join(data_dir, self.vocab_filename) return text_encoder.TokenTextEncoder(label_filepath)
[ "Builds", "encoder", "for", "the", "given", "class", "labels", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/babi_qa.py#L326-L336
[ "def", "get_labels_encoder", "(", "self", ",", "data_dir", ")", ":", "label_filepath", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "self", ".", "vocab_filename", ")", "return", "text_encoder", ".", "TokenTextEncoder", "(", "label_filepath", ")" ...
272500b6efe353aeb638d2745ed56e519462ca31
train
BabiQa.generate_encoded_samples
A generator that generates samples that are encoded. Args: data_dir: data directory tmp_dir: temp directory dataset_split: dataset split Yields: A dict.
tensor2tensor/data_generators/babi_qa.py
def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split): """A generator that generates samples that are encoded. Args: data_dir: data directory tmp_dir: temp directory dataset_split: dataset split Yields: A dict. """ generator = self.generate_samples(data_dir,...
def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split): """A generator that generates samples that are encoded. Args: data_dir: data directory tmp_dir: temp directory dataset_split: dataset split Yields: A dict. """ generator = self.generate_samples(data_dir,...
[ "A", "generator", "that", "generates", "samples", "that", "are", "encoded", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/babi_qa.py#L364-L386
[ "def", "generate_encoded_samples", "(", "self", ",", "data_dir", ",", "tmp_dir", ",", "dataset_split", ")", ":", "generator", "=", "self", ".", "generate_samples", "(", "data_dir", ",", "tmp_dir", ",", "dataset_split", ")", "encoder", "=", "self", ".", "get_or...
272500b6efe353aeb638d2745ed56e519462ca31
train
BabiQa.feature_encoders
Return a dict for encoding and decoding inference input/output. Args: data_dir: data directory Returns: A dict of <feature name, TextEncoder>.
tensor2tensor/data_generators/babi_qa.py
def feature_encoders(self, data_dir): """Return a dict for encoding and decoding inference input/output. Args: data_dir: data directory Returns: A dict of <feature name, TextEncoder>. """ encoders = (super(BabiQa, self).feature_encoders(data_dir)) label_encoder = self.get_labels_e...
def feature_encoders(self, data_dir): """Return a dict for encoding and decoding inference input/output. Args: data_dir: data directory Returns: A dict of <feature name, TextEncoder>. """ encoders = (super(BabiQa, self).feature_encoders(data_dir)) label_encoder = self.get_labels_e...
[ "Return", "a", "dict", "for", "encoding", "and", "decoding", "inference", "input", "/", "output", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/babi_qa.py#L388-L401
[ "def", "feature_encoders", "(", "self", ",", "data_dir", ")", ":", "encoders", "=", "(", "super", "(", "BabiQa", ",", "self", ")", ".", "feature_encoders", "(", "data_dir", ")", ")", "label_encoder", "=", "self", ".", "get_labels_encoder", "(", "data_dir", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
BabiQa.hparams
Returns problem_hparams. Args: defaults: default hyperparameters unused_model_hparams: model hyperparameters
tensor2tensor/data_generators/babi_qa.py
def hparams(self, defaults, unused_model_hparams): """Returns problem_hparams. Args: defaults: default hyperparameters unused_model_hparams: model hyperparameters """ (super(BabiQa, self).hparams(defaults, unused_model_hparams)) p = defaults num_classes = self._encoders["targets"]....
def hparams(self, defaults, unused_model_hparams): """Returns problem_hparams. Args: defaults: default hyperparameters unused_model_hparams: model hyperparameters """ (super(BabiQa, self).hparams(defaults, unused_model_hparams)) p = defaults num_classes = self._encoders["targets"]....
[ "Returns", "problem_hparams", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/babi_qa.py#L417-L429
[ "def", "hparams", "(", "self", ",", "defaults", ",", "unused_model_hparams", ")", ":", "(", "super", "(", "BabiQa", ",", "self", ")", ".", "hparams", "(", "defaults", ",", "unused_model_hparams", ")", ")", "p", "=", "defaults", "num_classes", "=", "self", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
TimeseriesProblem.dataset_splits
Splits of data to produce and number the output shards for each.
tensor2tensor/data_generators/timeseries.py
def dataset_splits(self): """Splits of data to produce and number the output shards for each.""" return [{ "split": problem.DatasetSplit.TRAIN, "shards": self.num_train_shards, }, { "split": problem.DatasetSplit.EVAL, "shards": self.num_eval_shards, }, { "split": ...
def dataset_splits(self): """Splits of data to produce and number the output shards for each.""" return [{ "split": problem.DatasetSplit.TRAIN, "shards": self.num_train_shards, }, { "split": problem.DatasetSplit.EVAL, "shards": self.num_eval_shards, }, { "split": ...
[ "Splits", "of", "data", "to", "produce", "and", "number", "the", "output", "shards", "for", "each", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/timeseries.py#L49-L60
[ "def", "dataset_splits", "(", "self", ")", ":", "return", "[", "{", "\"split\"", ":", "problem", ".", "DatasetSplit", ".", "TRAIN", ",", "\"shards\"", ":", "self", ".", "num_train_shards", ",", "}", ",", "{", "\"split\"", ":", "problem", ".", "DatasetSplit...
272500b6efe353aeb638d2745ed56e519462ca31
train
_collect_data
Traverses directory collecting input and target files.
tensor2tensor/data_generators/librispeech.py
def _collect_data(directory, input_ext, transcription_ext): """Traverses directory collecting input and target files.""" # Directory from string to tuple pair of strings # key: the filepath to a datafile including the datafile's basename. Example, # if the datafile was "/path/to/datafile.wav" then the key wou...
def _collect_data(directory, input_ext, transcription_ext): """Traverses directory collecting input and target files.""" # Directory from string to tuple pair of strings # key: the filepath to a datafile including the datafile's basename. Example, # if the datafile was "/path/to/datafile.wav" then the key wou...
[ "Traverses", "directory", "collecting", "input", "and", "target", "files", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/librispeech.py#L63-L85
[ "def", "_collect_data", "(", "directory", ",", "input_ext", ",", "transcription_ext", ")", ":", "# Directory from string to tuple pair of strings", "# key: the filepath to a datafile including the datafile's basename. Example,", "# if the datafile was \"/path/to/datafile.wav\" then the key...
272500b6efe353aeb638d2745ed56e519462ca31
train
add_librispeech_hparams
Adding to base hparams the attributes for for librispeech.
tensor2tensor/data_generators/librispeech.py
def add_librispeech_hparams(hparams): """Adding to base hparams the attributes for for librispeech.""" hparams.batch_size = 36 hparams.audio_compression = 8 hparams.hidden_size = 2048 hparams.max_input_seq_length = 600000 hparams.max_target_seq_length = 350 hparams.max_length = hparams.max_input_seq_lengt...
def add_librispeech_hparams(hparams): """Adding to base hparams the attributes for for librispeech.""" hparams.batch_size = 36 hparams.audio_compression = 8 hparams.hidden_size = 2048 hparams.max_input_seq_length = 600000 hparams.max_target_seq_length = 350 hparams.max_length = hparams.max_input_seq_lengt...
[ "Adding", "to", "base", "hparams", "the", "attributes", "for", "for", "librispeech", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/librispeech.py#L261-L273
[ "def", "add_librispeech_hparams", "(", "hparams", ")", ":", "hparams", ".", "batch_size", "=", "36", "hparams", ".", "audio_compression", "=", "8", "hparams", ".", "hidden_size", "=", "2048", "hparams", ".", "max_input_seq_length", "=", "600000", "hparams", ".",...
272500b6efe353aeb638d2745ed56e519462ca31
train
words_and_tags_from_wsj_tree
Generates linearized trees and tokens from the wsj tree format. It uses the linearized algorithm described in https://arxiv.org/abs/1412.7449. Args: tree_string: tree in wsj format Returns: tuple: (words, linearized tree)
tensor2tensor/data_generators/wsj_parsing.py
def words_and_tags_from_wsj_tree(tree_string): """Generates linearized trees and tokens from the wsj tree format. It uses the linearized algorithm described in https://arxiv.org/abs/1412.7449. Args: tree_string: tree in wsj format Returns: tuple: (words, linearized tree) """ stack, tags, words = ...
def words_and_tags_from_wsj_tree(tree_string): """Generates linearized trees and tokens from the wsj tree format. It uses the linearized algorithm described in https://arxiv.org/abs/1412.7449. Args: tree_string: tree in wsj format Returns: tuple: (words, linearized tree) """ stack, tags, words = ...
[ "Generates", "linearized", "trees", "and", "tokens", "from", "the", "wsj", "tree", "format", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wsj_parsing.py#L79-L103
[ "def", "words_and_tags_from_wsj_tree", "(", "tree_string", ")", ":", "stack", ",", "tags", ",", "words", "=", "[", "]", ",", "[", "]", ",", "[", "]", "for", "tok", "in", "tree_string", ".", "strip", "(", ")", ".", "split", "(", ")", ":", "if", "tok...
272500b6efe353aeb638d2745ed56e519462ca31
train
token_generator
Generator for parsing as a sequence-to-sequence task that uses tokens. This generator assumes the files at source_path and target_path have the same number of lines and yields dictionaries of "inputs" and "targets" where inputs and targets are token ids from source and target lines converted to integers using ...
tensor2tensor/data_generators/wsj_parsing.py
def token_generator(tree_path, source_token_vocab, target_token_vocab, eos=None): """Generator for parsing as a sequence-to-sequence task that uses tokens. This generator assumes the files at source_path and target_path have the same number of lines and yields dictionaries of "inputs" and "ta...
def token_generator(tree_path, source_token_vocab, target_token_vocab, eos=None): """Generator for parsing as a sequence-to-sequence task that uses tokens. This generator assumes the files at source_path and target_path have the same number of lines and yields dictionaries of "inputs" and "ta...
[ "Generator", "for", "parsing", "as", "a", "sequence", "-", "to", "-", "sequence", "task", "that", "uses", "tokens", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wsj_parsing.py#L106-L133
[ "def", "token_generator", "(", "tree_path", ",", "source_token_vocab", ",", "target_token_vocab", ",", "eos", "=", "None", ")", ":", "eos_list", "=", "[", "]", "if", "eos", "is", "None", "else", "[", "eos", "]", "with", "tf", ".", "gfile", ".", "GFile", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
parsing_token_generator
Generator for parsing as a sequence-to-sequence task that uses tokens. This generator assumes the files parsing_{train,dev}.trees, which contain trees in WSJ format. Args: data_dir: path to the data directory. tmp_dir: path to temporary storage directory. train: whether we're training or not. so...
tensor2tensor/data_generators/wsj_parsing.py
def parsing_token_generator(data_dir, tmp_dir, train, source_vocab_size, target_vocab_size): """Generator for parsing as a sequence-to-sequence task that uses tokens. This generator assumes the files parsing_{train,dev}.trees, which contain trees in WSJ format. Args: data_dir: ...
def parsing_token_generator(data_dir, tmp_dir, train, source_vocab_size, target_vocab_size): """Generator for parsing as a sequence-to-sequence task that uses tokens. This generator assumes the files parsing_{train,dev}.trees, which contain trees in WSJ format. Args: data_dir: ...
[ "Generator", "for", "parsing", "as", "a", "sequence", "-", "to", "-", "sequence", "task", "that", "uses", "tokens", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wsj_parsing.py#L136-L156
[ "def", "parsing_token_generator", "(", "data_dir", ",", "tmp_dir", ",", "train", ",", "source_vocab_size", ",", "target_vocab_size", ")", ":", "# TODO(lukaszkaiser): Correct these calls to generate vocabularies. No data", "# sources are being passed.", "del", "(", "data_dir", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
aggregate_stats
Aggregate stats in per-shard stats files.
tensor2tensor/data_generators/wikisum/validate_data.py
def aggregate_stats(stats_files): """Aggregate stats in per-shard stats files.""" all_stats = {} for fname in stats_files: with tf.gfile.Open(fname) as f: stats = json.loads(f.read()) for k, v in stats.iteritems(): if k not in all_stats: if isinstance(v, list): all_st...
def aggregate_stats(stats_files): """Aggregate stats in per-shard stats files.""" all_stats = {} for fname in stats_files: with tf.gfile.Open(fname) as f: stats = json.loads(f.read()) for k, v in stats.iteritems(): if k not in all_stats: if isinstance(v, list): all_st...
[ "Aggregate", "stats", "in", "per", "-", "shard", "stats", "files", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/validate_data.py#L41-L91
[ "def", "aggregate_stats", "(", "stats_files", ")", ":", "all_stats", "=", "{", "}", "for", "fname", "in", "stats_files", ":", "with", "tf", ".", "gfile", ".", "Open", "(", "fname", ")", "as", "f", ":", "stats", "=", "json", ".", "loads", "(", "f", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
filename_to_task_id
Map filename to the task id that created it assuming 1k tasks.
tensor2tensor/data_generators/wikisum/validate_data.py
def filename_to_task_id(fname): """Map filename to the task id that created it assuming 1k tasks.""" # This matches the order and size in WikisumBase.out_filepaths fname = os.path.basename(fname) shard_id_increment = { "train": 0, "dev": 800, "test": 900, } parts = fname.split("-") split...
def filename_to_task_id(fname): """Map filename to the task id that created it assuming 1k tasks.""" # This matches the order and size in WikisumBase.out_filepaths fname = os.path.basename(fname) shard_id_increment = { "train": 0, "dev": 800, "test": 900, } parts = fname.split("-") split...
[ "Map", "filename", "to", "the", "task", "id", "that", "created", "it", "assuming", "1k", "tasks", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/validate_data.py#L94-L107
[ "def", "filename_to_task_id", "(", "fname", ")", ":", "# This matches the order and size in WikisumBase.out_filepaths", "fname", "=", "os", ".", "path", ".", "basename", "(", "fname", ")", "shard_id_increment", "=", "{", "\"train\"", ":", "0", ",", "\"dev\"", ":", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
validate_data_files
Validate presence and minimum size of files.
tensor2tensor/data_generators/wikisum/validate_data.py
def validate_data_files(problem, data_files, min_size): """Validate presence and minimum size of files.""" # Check that all files are present data_dir = os.path.split(data_files[0])[0] out_filepaths = problem.out_filepaths(data_dir) missing_filepaths = set(out_filepaths) - set(data_files) if missing_filepat...
def validate_data_files(problem, data_files, min_size): """Validate presence and minimum size of files.""" # Check that all files are present data_dir = os.path.split(data_files[0])[0] out_filepaths = problem.out_filepaths(data_dir) missing_filepaths = set(out_filepaths) - set(data_files) if missing_filepat...
[ "Validate", "presence", "and", "minimum", "size", "of", "files", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/validate_data.py#L114-L133
[ "def", "validate_data_files", "(", "problem", ",", "data_files", ",", "min_size", ")", ":", "# Check that all files are present", "data_dir", "=", "os", ".", "path", ".", "split", "(", "data_files", "[", "0", "]", ")", "[", "0", "]", "out_filepaths", "=", "p...
272500b6efe353aeb638d2745ed56e519462ca31
train
distill_resnet_32_to_15_cifar20x5
Set of hyperparameters.
tensor2tensor/models/distillation.py
def distill_resnet_32_to_15_cifar20x5(): """Set of hyperparameters.""" hparams = distill_base() hparams.teacher_model = "resnet" hparams.teacher_hparams = "resnet_cifar_32" hparams.student_model = "resnet" hparams.student_hparams = "resnet_cifar_15" hparams.optimizer_momentum_nesterov = True # (base_lr...
def distill_resnet_32_to_15_cifar20x5(): """Set of hyperparameters.""" hparams = distill_base() hparams.teacher_model = "resnet" hparams.teacher_hparams = "resnet_cifar_32" hparams.student_model = "resnet" hparams.student_hparams = "resnet_cifar_15" hparams.optimizer_momentum_nesterov = True # (base_lr...
[ "Set", "of", "hyperparameters", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/distillation.py#L175-L196
[ "def", "distill_resnet_32_to_15_cifar20x5", "(", ")", ":", "hparams", "=", "distill_base", "(", ")", "hparams", ".", "teacher_model", "=", "\"resnet\"", "hparams", ".", "teacher_hparams", "=", "\"resnet_cifar_32\"", "hparams", ".", "student_model", "=", "\"resnet\"", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_prepare_lambada_data
Downloading and preparing the dataset. Args: tmp_dir: tem directory data_dir: data directory vocab_size: size of vocabulary vocab_filename: name of vocab file
tensor2tensor/data_generators/lambada.py
def _prepare_lambada_data(tmp_dir, data_dir, vocab_size, vocab_filename): """Downloading and preparing the dataset. Args: tmp_dir: tem directory data_dir: data directory vocab_size: size of vocabulary vocab_filename: name of vocab file """ if not tf.gfile.Exists(data_dir): tf.gfile.MakeDi...
def _prepare_lambada_data(tmp_dir, data_dir, vocab_size, vocab_filename): """Downloading and preparing the dataset. Args: tmp_dir: tem directory data_dir: data directory vocab_size: size of vocabulary vocab_filename: name of vocab file """ if not tf.gfile.Exists(data_dir): tf.gfile.MakeDi...
[ "Downloading", "and", "preparing", "the", "dataset", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/lambada.py#L57-L86
[ "def", "_prepare_lambada_data", "(", "tmp_dir", ",", "data_dir", ",", "vocab_size", ",", "vocab_filename", ")", ":", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "data_dir", ")", ":", "tf", ".", "gfile", ".", "MakeDirs", "(", "data_dir", ")", "fi...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_dataset_split
Gives the file paths with regards to the given split. Args: tmp_dir: temp directory split: dataset split use_control_set: uses control dataset if true. Returns: list of file paths.
tensor2tensor/data_generators/lambada.py
def get_dataset_split(tmp_dir, split, use_control_set): """Gives the file paths with regards to the given split. Args: tmp_dir: temp directory split: dataset split use_control_set: uses control dataset if true. Returns: list of file paths. """ if not use_control_set: dataset_split = { ...
def get_dataset_split(tmp_dir, split, use_control_set): """Gives the file paths with regards to the given split. Args: tmp_dir: temp directory split: dataset split use_control_set: uses control dataset if true. Returns: list of file paths. """ if not use_control_set: dataset_split = { ...
[ "Gives", "the", "file", "paths", "with", "regards", "to", "the", "given", "split", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/lambada.py#L89-L126
[ "def", "get_dataset_split", "(", "tmp_dir", ",", "split", ",", "use_control_set", ")", ":", "if", "not", "use_control_set", ":", "dataset_split", "=", "{", "problem", ".", "DatasetSplit", ".", "TRAIN", ":", "[", "f", "for", "f", "in", "tf", ".", "gfile", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
TransductionProblem.min_sequence_length
Determine the minimum sequence length given a dataset_split. Args: dataset_split: A problem.DatasetSplit. Returns: The minimum length that a sequence can be for this dataset_split.
tensor2tensor/data_generators/transduction_problems.py
def min_sequence_length(self, dataset_split): """Determine the minimum sequence length given a dataset_split. Args: dataset_split: A problem.DatasetSplit. Returns: The minimum length that a sequence can be for this dataset_split. """ return { problem.DatasetSplit.TRAIN: 8, ...
def min_sequence_length(self, dataset_split): """Determine the minimum sequence length given a dataset_split. Args: dataset_split: A problem.DatasetSplit. Returns: The minimum length that a sequence can be for this dataset_split. """ return { problem.DatasetSplit.TRAIN: 8, ...
[ "Determine", "the", "minimum", "sequence", "length", "given", "a", "dataset_split", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/transduction_problems.py#L63-L76
[ "def", "min_sequence_length", "(", "self", ",", "dataset_split", ")", ":", "return", "{", "problem", ".", "DatasetSplit", ".", "TRAIN", ":", "8", ",", "problem", ".", "DatasetSplit", ".", "EVAL", ":", "65", ",", "problem", ".", "DatasetSplit", ".", "TEST",...
272500b6efe353aeb638d2745ed56e519462ca31
train
TransductionProblem.max_sequence_length
Determine the maximum sequence length given a dataset_split. Args: dataset_split: A problem.DatasetSplit. Returns: The maximum length that a sequence can be for this dataset_split.
tensor2tensor/data_generators/transduction_problems.py
def max_sequence_length(self, dataset_split): """Determine the maximum sequence length given a dataset_split. Args: dataset_split: A problem.DatasetSplit. Returns: The maximum length that a sequence can be for this dataset_split. """ return { problem.DatasetSplit.TRAIN: 64, ...
def max_sequence_length(self, dataset_split): """Determine the maximum sequence length given a dataset_split. Args: dataset_split: A problem.DatasetSplit. Returns: The maximum length that a sequence can be for this dataset_split. """ return { problem.DatasetSplit.TRAIN: 64, ...
[ "Determine", "the", "maximum", "sequence", "length", "given", "a", "dataset_split", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/transduction_problems.py#L78-L91
[ "def", "max_sequence_length", "(", "self", ",", "dataset_split", ")", ":", "return", "{", "problem", ".", "DatasetSplit", ".", "TRAIN", ":", "64", ",", "problem", ".", "DatasetSplit", ".", "EVAL", ":", "128", ",", "problem", ".", "DatasetSplit", ".", "TEST...
272500b6efe353aeb638d2745ed56e519462ca31
train
TransductionProblem.num_samples
Determine the dataset sized given a dataset_split. Args: dataset_split: A problem.DatasetSplit. Returns: The desired number of samples for this dataset_split.
tensor2tensor/data_generators/transduction_problems.py
def num_samples(self, dataset_split): """Determine the dataset sized given a dataset_split. Args: dataset_split: A problem.DatasetSplit. Returns: The desired number of samples for this dataset_split. """ return { problem.DatasetSplit.TRAIN: 1000000, problem.DatasetSplit...
def num_samples(self, dataset_split): """Determine the dataset sized given a dataset_split. Args: dataset_split: A problem.DatasetSplit. Returns: The desired number of samples for this dataset_split. """ return { problem.DatasetSplit.TRAIN: 1000000, problem.DatasetSplit...
[ "Determine", "the", "dataset", "sized", "given", "a", "dataset_split", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/transduction_problems.py#L93-L106
[ "def", "num_samples", "(", "self", ",", "dataset_split", ")", ":", "return", "{", "problem", ".", "DatasetSplit", ".", "TRAIN", ":", "1000000", ",", "problem", ".", "DatasetSplit", ".", "EVAL", ":", "10000", ",", "problem", ".", "DatasetSplit", ".", "TEST"...
272500b6efe353aeb638d2745ed56e519462ca31
train
next_checkpoint
Yields successive checkpoints from model_dir. Args: model_dir: The directory in which checkpoints are saved. timeout_mins: The maximum amount of time in minutes to wait between checkpoints. Set this to -1 to wait indefinitely. Yields: last_ckpt: a new checkpoint path, or None if the t...
tensor2tensor/utils/trainer_lib.py
def next_checkpoint(model_dir, timeout_mins=240): """Yields successive checkpoints from model_dir. Args: model_dir: The directory in which checkpoints are saved. timeout_mins: The maximum amount of time in minutes to wait between checkpoints. Set this to -1 to wait indefinitely. Yields:...
def next_checkpoint(model_dir, timeout_mins=240): """Yields successive checkpoints from model_dir. Args: model_dir: The directory in which checkpoints are saved. timeout_mins: The maximum amount of time in minutes to wait between checkpoints. Set this to -1 to wait indefinitely. Yields:...
[ "Yields", "successive", "checkpoints", "from", "model_dir", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L46-L69
[ "def", "next_checkpoint", "(", "model_dir", ",", "timeout_mins", "=", "240", ")", ":", "last_ckpt", "=", "None", "timeout_secs", "=", "None", "if", "timeout_mins", "!=", "-", "1", ":", "timeout_secs", "=", "timeout_mins", "*", "60", "while", "True", ":", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
next_undecoded_checkpoint
Yields successive checkpoints from model_dir.
tensor2tensor/utils/trainer_lib.py
def next_undecoded_checkpoint(model_dir, timeout_mins=240): """Yields successive checkpoints from model_dir.""" last_ckpt = None last_step = 0 while True: # Get the latest checkpoint. last_ckpt = tf.contrib.training.wait_for_new_checkpoint( model_dir, last_ckpt, seconds_to_sleep=60, timeout=60 *...
def next_undecoded_checkpoint(model_dir, timeout_mins=240): """Yields successive checkpoints from model_dir.""" last_ckpt = None last_step = 0 while True: # Get the latest checkpoint. last_ckpt = tf.contrib.training.wait_for_new_checkpoint( model_dir, last_ckpt, seconds_to_sleep=60, timeout=60 *...
[ "Yields", "successive", "checkpoints", "from", "model_dir", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L72-L102
[ "def", "next_undecoded_checkpoint", "(", "model_dir", ",", "timeout_mins", "=", "240", ")", ":", "last_ckpt", "=", "None", "last_step", "=", "0", "while", "True", ":", "# Get the latest checkpoint.", "last_ckpt", "=", "tf", ".", "contrib", ".", "training", ".", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
create_session_config
The TensorFlow Session config to use.
tensor2tensor/utils/trainer_lib.py
def create_session_config(log_device_placement=False, enable_graph_rewriter=False, gpu_mem_fraction=0.95, use_tpu=False, xla_jit_level=tf.OptimizerOptions.OFF, inter_op_parallelism_threads=0...
def create_session_config(log_device_placement=False, enable_graph_rewriter=False, gpu_mem_fraction=0.95, use_tpu=False, xla_jit_level=tf.OptimizerOptions.OFF, inter_op_parallelism_threads=0...
[ "The", "TensorFlow", "Session", "config", "to", "use", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L105-L137
[ "def", "create_session_config", "(", "log_device_placement", "=", "False", ",", "enable_graph_rewriter", "=", "False", ",", "gpu_mem_fraction", "=", "0.95", ",", "use_tpu", "=", "False", ",", "xla_jit_level", "=", "tf", ".", "OptimizerOptions", ".", "OFF", ",", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
create_run_config
Create RunConfig, TPUConfig, and Parallelism object.
tensor2tensor/utils/trainer_lib.py
def create_run_config(model_name, master="", model_dir=None, iterations_per_loop=1000, num_shards=8, log_device_placement=False, save_checkpoints_steps=1000, save_che...
def create_run_config(model_name, master="", model_dir=None, iterations_per_loop=1000, num_shards=8, log_device_placement=False, save_checkpoints_steps=1000, save_che...
[ "Create", "RunConfig", "TPUConfig", "and", "Parallelism", "object", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L145-L278
[ "def", "create_run_config", "(", "model_name", ",", "master", "=", "\"\"", ",", "model_dir", "=", "None", ",", "iterations_per_loop", "=", "1000", ",", "num_shards", "=", "8", ",", "log_device_placement", "=", "False", ",", "save_checkpoints_steps", "=", "1000",...
272500b6efe353aeb638d2745ed56e519462ca31
train
create_estimator
Create a T2T Estimator.
tensor2tensor/utils/trainer_lib.py
def create_estimator(model_name, hparams, run_config, schedule="train_and_evaluate", decode_hparams=None, use_tpu=False, use_tpu_estimator=False, use_xla=False): """Create...
def create_estimator(model_name, hparams, run_config, schedule="train_and_evaluate", decode_hparams=None, use_tpu=False, use_tpu_estimator=False, use_xla=False): """Create...
[ "Create", "a", "T2T", "Estimator", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L281-L325
[ "def", "create_estimator", "(", "model_name", ",", "hparams", ",", "run_config", ",", "schedule", "=", "\"train_and_evaluate\"", ",", "decode_hparams", "=", "None", ",", "use_tpu", "=", "False", ",", "use_tpu_estimator", "=", "False", ",", "use_xla", "=", "False...
272500b6efe353aeb638d2745ed56e519462ca31
train
create_hooks
Create train and eval hooks for Experiment.
tensor2tensor/utils/trainer_lib.py
def create_hooks(use_tfdbg=False, use_dbgprofile=False, dbgprofile_kwargs=None, use_validation_monitor=False, validation_monitor_kwargs=None, use_early_stopping=False, early_stopping_kwargs=None): """Create train and...
def create_hooks(use_tfdbg=False, use_dbgprofile=False, dbgprofile_kwargs=None, use_validation_monitor=False, validation_monitor_kwargs=None, use_early_stopping=False, early_stopping_kwargs=None): """Create train and...
[ "Create", "train", "and", "eval", "hooks", "for", "Experiment", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L328-L365
[ "def", "create_hooks", "(", "use_tfdbg", "=", "False", ",", "use_dbgprofile", "=", "False", ",", "dbgprofile_kwargs", "=", "None", ",", "use_validation_monitor", "=", "False", ",", "validation_monitor_kwargs", "=", "None", ",", "use_early_stopping", "=", "False", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
create_experiment
Create Experiment.
tensor2tensor/utils/trainer_lib.py
def create_experiment( run_config, hparams, model_name, problem_name, data_dir, train_steps, eval_steps, min_eval_frequency=2000, eval_throttle_seconds=600, schedule="train_and_evaluate", export=False, decode_hparams=None, use_tfdbg=False, use_dbgprofile=False, ...
def create_experiment( run_config, hparams, model_name, problem_name, data_dir, train_steps, eval_steps, min_eval_frequency=2000, eval_throttle_seconds=600, schedule="train_and_evaluate", export=False, decode_hparams=None, use_tfdbg=False, use_dbgprofile=False, ...
[ "Create", "Experiment", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L613-L767
[ "def", "create_experiment", "(", "run_config", ",", "hparams", ",", "model_name", ",", "problem_name", ",", "data_dir", ",", "train_steps", ",", "eval_steps", ",", "min_eval_frequency", "=", "2000", ",", "eval_throttle_seconds", "=", "600", ",", "schedule", "=", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
create_experiment_fn
Wrapper for canonical experiment_fn. See create_experiment.
tensor2tensor/utils/trainer_lib.py
def create_experiment_fn(*args, **kwargs): """Wrapper for canonical experiment_fn. See create_experiment.""" def experiment_fn(run_config, hparams): return create_experiment(run_config, hparams, *args, **kwargs) return experiment_fn
def create_experiment_fn(*args, **kwargs): """Wrapper for canonical experiment_fn. See create_experiment.""" def experiment_fn(run_config, hparams): return create_experiment(run_config, hparams, *args, **kwargs) return experiment_fn
[ "Wrapper", "for", "canonical", "experiment_fn", ".", "See", "create_experiment", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L770-L776
[ "def", "create_experiment_fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "experiment_fn", "(", "run_config", ",", "hparams", ")", ":", "return", "create_experiment", "(", "run_config", ",", "hparams", ",", "*", "args", ",", "*", "*", "k...
272500b6efe353aeb638d2745ed56e519462ca31
train
restore_checkpoint
Restore from a checkpoint.
tensor2tensor/utils/trainer_lib.py
def restore_checkpoint(ckpt_dir, saver, sess, must_restore=False): """Restore from a checkpoint.""" ckpt = tf.train.get_checkpoint_state(ckpt_dir) if must_restore and not ckpt: raise ValueError("No checkpoint found in %s" % ckpt_dir) if not ckpt: return 0 path = ckpt.model_checkpoint_path tf.loggin...
def restore_checkpoint(ckpt_dir, saver, sess, must_restore=False): """Restore from a checkpoint.""" ckpt = tf.train.get_checkpoint_state(ckpt_dir) if must_restore and not ckpt: raise ValueError("No checkpoint found in %s" % ckpt_dir) if not ckpt: return 0 path = ckpt.model_checkpoint_path tf.loggin...
[ "Restore", "from", "a", "checkpoint", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L785-L797
[ "def", "restore_checkpoint", "(", "ckpt_dir", ",", "saver", ",", "sess", ",", "must_restore", "=", "False", ")", ":", "ckpt", "=", "tf", ".", "train", ".", "get_checkpoint_state", "(", "ckpt_dir", ")", "if", "must_restore", "and", "not", "ckpt", ":", "rais...
272500b6efe353aeb638d2745ed56e519462ca31
train
T2TExperiment.train_eval_and_decode
Does eval and decode after training every eval_freq_in_steps.
tensor2tensor/utils/trainer_lib.py
def train_eval_and_decode(self): """Does eval and decode after training every eval_freq_in_steps.""" eval_steps = self._hparams.eval_freq_in_steps packed_dataset = "_packed" in self._hparams.problem.name mlperf_log.transformer_print(key=mlperf_log.TRAIN_LOOP) for i in range(0, self._train_spec.max_s...
def train_eval_and_decode(self): """Does eval and decode after training every eval_freq_in_steps.""" eval_steps = self._hparams.eval_freq_in_steps packed_dataset = "_packed" in self._hparams.problem.name mlperf_log.transformer_print(key=mlperf_log.TRAIN_LOOP) for i in range(0, self._train_spec.max_s...
[ "Does", "eval", "and", "decode", "after", "training", "every", "eval_freq_in_steps", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L419-L461
[ "def", "train_eval_and_decode", "(", "self", ")", ":", "eval_steps", "=", "self", ".", "_hparams", ".", "eval_freq_in_steps", "packed_dataset", "=", "\"_packed\"", "in", "self", ".", "_hparams", ".", "problem", ".", "name", "mlperf_log", ".", "transformer_print", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
T2TExperiment.continuous_eval
Evaluate until checkpoints stop being produced.
tensor2tensor/utils/trainer_lib.py
def continuous_eval(self): """Evaluate until checkpoints stop being produced.""" for ckpt_path in next_checkpoint(self._hparams.model_dir, self._hparams.eval_timeout_mins): # Skip zero'th step. train_step = decoding.get_step_from_ckpt_path(ckpt_path) if tra...
def continuous_eval(self): """Evaluate until checkpoints stop being produced.""" for ckpt_path in next_checkpoint(self._hparams.model_dir, self._hparams.eval_timeout_mins): # Skip zero'th step. train_step = decoding.get_step_from_ckpt_path(ckpt_path) if tra...
[ "Evaluate", "until", "checkpoints", "stop", "being", "produced", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L488-L497
[ "def", "continuous_eval", "(", "self", ")", ":", "for", "ckpt_path", "in", "next_checkpoint", "(", "self", ".", "_hparams", ".", "model_dir", ",", "self", ".", "_hparams", ".", "eval_timeout_mins", ")", ":", "# Skip zero'th step.", "train_step", "=", "decoding",...
272500b6efe353aeb638d2745ed56e519462ca31
train
T2TExperiment.continuous_eval_on_train_data
Evaluate on train data until checkpoints stop being produced.
tensor2tensor/utils/trainer_lib.py
def continuous_eval_on_train_data(self): """Evaluate on train data until checkpoints stop being produced.""" for ckpt_path in next_checkpoint(self._hparams.model_dir, self._hparams.eval_timeout_mins): # Skip zero'th step. train_step = decoding.get_step_from_ckpt_...
def continuous_eval_on_train_data(self): """Evaluate on train data until checkpoints stop being produced.""" for ckpt_path in next_checkpoint(self._hparams.model_dir, self._hparams.eval_timeout_mins): # Skip zero'th step. train_step = decoding.get_step_from_ckpt_...
[ "Evaluate", "on", "train", "data", "until", "checkpoints", "stop", "being", "produced", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L499-L508
[ "def", "continuous_eval_on_train_data", "(", "self", ")", ":", "for", "ckpt_path", "in", "next_checkpoint", "(", "self", ".", "_hparams", ".", "model_dir", ",", "self", ".", "_hparams", ".", "eval_timeout_mins", ")", ":", "# Skip zero'th step.", "train_step", "=",...
272500b6efe353aeb638d2745ed56e519462ca31
train
T2TExperiment.run_std_server
Starts a TensorFlow server and joins the serving thread. Typically used for parameter servers. Raises: ValueError: if not enough information is available in the estimator's config to create a server.
tensor2tensor/utils/trainer_lib.py
def run_std_server(self): """Starts a TensorFlow server and joins the serving thread. Typically used for parameter servers. Raises: ValueError: if not enough information is available in the estimator's config to create a server. """ config = tf.estimator.RunConfig() server = tf.t...
def run_std_server(self): """Starts a TensorFlow server and joins the serving thread. Typically used for parameter servers. Raises: ValueError: if not enough information is available in the estimator's config to create a server. """ config = tf.estimator.RunConfig() server = tf.t...
[ "Starts", "a", "TensorFlow", "server", "and", "joins", "the", "serving", "thread", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L521-L536
[ "def", "run_std_server", "(", "self", ")", ":", "config", "=", "tf", ".", "estimator", ".", "RunConfig", "(", ")", "server", "=", "tf", ".", "train", ".", "Server", "(", "config", ".", "cluster_spec", ",", "job_name", "=", "config", ".", "task_type", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
T2TExperiment.decode
Decodes from dataset or file.
tensor2tensor/utils/trainer_lib.py
def decode(self, dataset_split=None, decode_from_file=False, checkpoint_path=None): """Decodes from dataset or file.""" if decode_from_file: decoding.decode_from_file(self._estimator, self._decode_hparams.decode_from_file, ...
def decode(self, dataset_split=None, decode_from_file=False, checkpoint_path=None): """Decodes from dataset or file.""" if decode_from_file: decoding.decode_from_file(self._estimator, self._decode_hparams.decode_from_file, ...
[ "Decodes", "from", "dataset", "or", "file", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L538-L556
[ "def", "decode", "(", "self", ",", "dataset_split", "=", "None", ",", "decode_from_file", "=", "False", ",", "checkpoint_path", "=", "None", ")", ":", "if", "decode_from_file", ":", "decoding", ".", "decode_from_file", "(", "self", ".", "_estimator", ",", "s...
272500b6efe353aeb638d2745ed56e519462ca31
train
T2TExperiment.continuous_decode
Decode from dataset on new checkpoint.
tensor2tensor/utils/trainer_lib.py
def continuous_decode(self): """Decode from dataset on new checkpoint.""" for _ in next_checkpoint(self._hparams.model_dir, self._decode_hparams.decode_timeout_mins): self.decode()
def continuous_decode(self): """Decode from dataset on new checkpoint.""" for _ in next_checkpoint(self._hparams.model_dir, self._decode_hparams.decode_timeout_mins): self.decode()
[ "Decode", "from", "dataset", "on", "new", "checkpoint", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L558-L562
[ "def", "continuous_decode", "(", "self", ")", ":", "for", "_", "in", "next_checkpoint", "(", "self", ".", "_hparams", ".", "model_dir", ",", "self", ".", "_decode_hparams", ".", "decode_timeout_mins", ")", ":", "self", ".", "decode", "(", ")" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
T2TExperiment.continuous_decode_on_train_data
Decode from dataset on new checkpoint.
tensor2tensor/utils/trainer_lib.py
def continuous_decode_on_train_data(self): """Decode from dataset on new checkpoint.""" for _ in next_checkpoint(self._hparams.model_dir, self._decode_hparams.decode_timeout_mins): self.decode(dataset_split=tf.estimator.ModeKeys.TRAIN)
def continuous_decode_on_train_data(self): """Decode from dataset on new checkpoint.""" for _ in next_checkpoint(self._hparams.model_dir, self._decode_hparams.decode_timeout_mins): self.decode(dataset_split=tf.estimator.ModeKeys.TRAIN)
[ "Decode", "from", "dataset", "on", "new", "checkpoint", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L564-L568
[ "def", "continuous_decode_on_train_data", "(", "self", ")", ":", "for", "_", "in", "next_checkpoint", "(", "self", ".", "_hparams", ".", "model_dir", ",", "self", ".", "_decode_hparams", ".", "decode_timeout_mins", ")", ":", "self", ".", "decode", "(", "datase...
272500b6efe353aeb638d2745ed56e519462ca31
train
T2TExperiment.continuous_decode_on_eval_data
Decode from dataset on new checkpoint.
tensor2tensor/utils/trainer_lib.py
def continuous_decode_on_eval_data(self): """Decode from dataset on new checkpoint.""" if self._hparams.mlperf_mode: ckpt_generator = next_undecoded_checkpoint( self._hparams.model_dir, self._decode_hparams.decode_timeout_mins) else: ckpt_generator = next_checkpoint(self._hparams.model...
def continuous_decode_on_eval_data(self): """Decode from dataset on new checkpoint.""" if self._hparams.mlperf_mode: ckpt_generator = next_undecoded_checkpoint( self._hparams.model_dir, self._decode_hparams.decode_timeout_mins) else: ckpt_generator = next_checkpoint(self._hparams.model...
[ "Decode", "from", "dataset", "on", "new", "checkpoint", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L570-L604
[ "def", "continuous_decode_on_eval_data", "(", "self", ")", ":", "if", "self", ".", "_hparams", ".", "mlperf_mode", ":", "ckpt_generator", "=", "next_undecoded_checkpoint", "(", "self", ".", "_hparams", ".", "model_dir", ",", "self", ".", "_decode_hparams", ".", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
T2TExperiment.continuous_decode_from_file
Decode from file on new checkpoint.
tensor2tensor/utils/trainer_lib.py
def continuous_decode_from_file(self): """Decode from file on new checkpoint.""" for _ in next_checkpoint(self._hparams.model_dir, self._decode_hparams.decode_timeout_mins): self.decode(decode_from_file=True)
def continuous_decode_from_file(self): """Decode from file on new checkpoint.""" for _ in next_checkpoint(self._hparams.model_dir, self._decode_hparams.decode_timeout_mins): self.decode(decode_from_file=True)
[ "Decode", "from", "file", "on", "new", "checkpoint", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L606-L610
[ "def", "continuous_decode_from_file", "(", "self", ")", ":", "for", "_", "in", "next_checkpoint", "(", "self", ".", "_hparams", ".", "model_dir", ",", "self", ".", "_decode_hparams", ".", "decode_timeout_mins", ")", ":", "self", ".", "decode", "(", "decode_fro...
272500b6efe353aeb638d2745ed56e519462ca31
train
_flatten_dict
Flatten dict of dicts into a single dict with appropriate prefixes. Handles only 2 levels of nesting in the original dict. Args: original_dict: Dict which may contain one or more dicts. Returns: flat_dict: Dict without any nesting. Any dicts in the original dict have their keys as prefixes in the ...
tensor2tensor/utils/t2t_model.py
def _flatten_dict(original_dict): """Flatten dict of dicts into a single dict with appropriate prefixes. Handles only 2 levels of nesting in the original dict. Args: original_dict: Dict which may contain one or more dicts. Returns: flat_dict: Dict without any nesting. Any dicts in the original dict ha...
def _flatten_dict(original_dict): """Flatten dict of dicts into a single dict with appropriate prefixes. Handles only 2 levels of nesting in the original dict. Args: original_dict: Dict which may contain one or more dicts. Returns: flat_dict: Dict without any nesting. Any dicts in the original dict ha...
[ "Flatten", "dict", "of", "dicts", "into", "a", "single", "dict", "with", "appropriate", "prefixes", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L63-L87
[ "def", "_flatten_dict", "(", "original_dict", ")", ":", "flat_dict", "=", "{", "}", "for", "key", ",", "value", "in", "original_dict", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "for", "name", ",", "tensor", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_unflatten_dict
Returns a dict of dicts if any prefixes match keys in the flat dict. The function handles the case where the prefix may not be a dict. Args: flat_dict: A dict without any nesting. prefixes: A list of strings which may have been dicts in the original structure.
tensor2tensor/utils/t2t_model.py
def _unflatten_dict(flat_dict, prefixes): """Returns a dict of dicts if any prefixes match keys in the flat dict. The function handles the case where the prefix may not be a dict. Args: flat_dict: A dict without any nesting. prefixes: A list of strings which may have been dicts in the original s...
def _unflatten_dict(flat_dict, prefixes): """Returns a dict of dicts if any prefixes match keys in the flat dict. The function handles the case where the prefix may not be a dict. Args: flat_dict: A dict without any nesting. prefixes: A list of strings which may have been dicts in the original s...
[ "Returns", "a", "dict", "of", "dicts", "if", "any", "prefixes", "match", "keys", "in", "the", "flat", "dict", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L90-L117
[ "def", "_unflatten_dict", "(", "flat_dict", ",", "prefixes", ")", ":", "original_dict", "=", "{", "}", "for", "key", ",", "value", "in", "flat_dict", ".", "items", "(", ")", ":", "prefix_found", "=", "False", "for", "prefix", "in", "prefixes", ":", "full...
272500b6efe353aeb638d2745ed56e519462ca31
train
create_dummy_vars
Dummy vars for restore to work when not using TPU codepath.
tensor2tensor/utils/t2t_model.py
def create_dummy_vars(): """Dummy vars for restore to work when not using TPU codepath.""" var_names = set([v.name for v in tf.global_variables()]) if "losses_avg/problem_0/total_loss:0" in var_names: return with tf.variable_scope("losses_avg"): with tf.variable_scope("problem_0"): for var_name in...
def create_dummy_vars(): """Dummy vars for restore to work when not using TPU codepath.""" var_names = set([v.name for v in tf.global_variables()]) if "losses_avg/problem_0/total_loss:0" in var_names: return with tf.variable_scope("losses_avg"): with tf.variable_scope("problem_0"): for var_name in...
[ "Dummy", "vars", "for", "restore", "to", "work", "when", "not", "using", "TPU", "codepath", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L1916-L1927
[ "def", "create_dummy_vars", "(", ")", ":", "var_names", "=", "set", "(", "[", "v", ".", "name", "for", "v", "in", "tf", ".", "global_variables", "(", ")", "]", ")", "if", "\"losses_avg/problem_0/total_loss:0\"", "in", "var_names", ":", "return", "with", "t...
272500b6efe353aeb638d2745ed56e519462ca31
train
create_tpu_eval_metrics_fn
Create the metrics_fn that TPUEstimatorSpec expects.
tensor2tensor/utils/t2t_model.py
def create_tpu_eval_metrics_fn(problem, model_hparams): """Create the metrics_fn that TPUEstimatorSpec expects.""" metric_fns = [] eval_metrics = problem.eval_metric_fns(model_hparams) tm = _create_target_modality(problem.get_hparams(model_hparams).modality) if isinstance(tm, dict): for k, v in six.iter...
def create_tpu_eval_metrics_fn(problem, model_hparams): """Create the metrics_fn that TPUEstimatorSpec expects.""" metric_fns = [] eval_metrics = problem.eval_metric_fns(model_hparams) tm = _create_target_modality(problem.get_hparams(model_hparams).modality) if isinstance(tm, dict): for k, v in six.iter...
[ "Create", "the", "metrics_fn", "that", "TPUEstimatorSpec", "expects", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L1939-L2015
[ "def", "create_tpu_eval_metrics_fn", "(", "problem", ",", "model_hparams", ")", ":", "metric_fns", "=", "[", "]", "eval_metrics", "=", "problem", ".", "eval_metric_fns", "(", "model_hparams", ")", "tm", "=", "_create_target_modality", "(", "problem", ".", "get_hpa...
272500b6efe353aeb638d2745ed56e519462ca31
train
remove_summaries
Remove summaries from the default graph.
tensor2tensor/utils/t2t_model.py
def remove_summaries(): """Remove summaries from the default graph.""" g = tf.get_default_graph() key = tf.GraphKeys.SUMMARIES log_debug("Remove summaries %s" % str(g.get_collection(key))) del g.get_collection_ref(key)[:] assert not g.get_collection(key)
def remove_summaries(): """Remove summaries from the default graph.""" g = tf.get_default_graph() key = tf.GraphKeys.SUMMARIES log_debug("Remove summaries %s" % str(g.get_collection(key))) del g.get_collection_ref(key)[:] assert not g.get_collection(key)
[ "Remove", "summaries", "from", "the", "default", "graph", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L2018-L2024
[ "def", "remove_summaries", "(", ")", ":", "g", "=", "tf", ".", "get_default_graph", "(", ")", "key", "=", "tf", ".", "GraphKeys", ".", "SUMMARIES", "log_debug", "(", "\"Remove summaries %s\"", "%", "str", "(", "g", ".", "get_collection", "(", "key", ")", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
create_host_call
Construct a host_call writing scalar summaries. Args: model_dir: String containing path to train Returns: (fn, args) Pair to be called by TPUEstimator as the host_call.
tensor2tensor/utils/t2t_model.py
def create_host_call(model_dir): """Construct a host_call writing scalar summaries. Args: model_dir: String containing path to train Returns: (fn, args) Pair to be called by TPUEstimator as the host_call. """ graph = tf.get_default_graph() summaries = graph.get_collection(tf.GraphKeys.SUMMARIES) ...
def create_host_call(model_dir): """Construct a host_call writing scalar summaries. Args: model_dir: String containing path to train Returns: (fn, args) Pair to be called by TPUEstimator as the host_call. """ graph = tf.get_default_graph() summaries = graph.get_collection(tf.GraphKeys.SUMMARIES) ...
[ "Construct", "a", "host_call", "writing", "scalar", "summaries", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L2027-L2098
[ "def", "create_host_call", "(", "model_dir", ")", ":", "graph", "=", "tf", ".", "get_default_graph", "(", ")", "summaries", "=", "graph", ".", "get_collection", "(", "tf", ".", "GraphKeys", ".", "SUMMARIES", ")", "gs_t", "=", "tf", ".", "reshape", "(", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
average_sharded_losses
Average losses across datashards. Args: sharded_losses: list<dict<str loss_name, Tensor loss>>. The loss can be a single Tensor or a 2-tuple (numerator and denominator). Returns: losses: dict<str loss_name, Tensor avg_loss>
tensor2tensor/utils/t2t_model.py
def average_sharded_losses(sharded_losses): """Average losses across datashards. Args: sharded_losses: list<dict<str loss_name, Tensor loss>>. The loss can be a single Tensor or a 2-tuple (numerator and denominator). Returns: losses: dict<str loss_name, Tensor avg_loss> """ losses = {} for l...
def average_sharded_losses(sharded_losses): """Average losses across datashards. Args: sharded_losses: list<dict<str loss_name, Tensor loss>>. The loss can be a single Tensor or a 2-tuple (numerator and denominator). Returns: losses: dict<str loss_name, Tensor avg_loss> """ losses = {} for l...
[ "Average", "losses", "across", "datashards", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L2121-L2143
[ "def", "average_sharded_losses", "(", "sharded_losses", ")", ":", "losses", "=", "{", "}", "for", "loss_name", "in", "sorted", "(", "sharded_losses", "[", "0", "]", ")", ":", "all_shards", "=", "[", "shard_losses", "[", "loss_name", "]", "for", "shard_losses...
272500b6efe353aeb638d2745ed56e519462ca31
train
summarize_features
Generate summaries for features.
tensor2tensor/utils/t2t_model.py
def summarize_features(features, num_shards=1): """Generate summaries for features.""" if not common_layers.should_generate_summaries(): return with tf.name_scope("input_stats"): for (k, v) in sorted(six.iteritems(features)): if (isinstance(v, tf.Tensor) and (v.get_shape().ndims > 1) and ...
def summarize_features(features, num_shards=1): """Generate summaries for features.""" if not common_layers.should_generate_summaries(): return with tf.name_scope("input_stats"): for (k, v) in sorted(six.iteritems(features)): if (isinstance(v, tf.Tensor) and (v.get_shape().ndims > 1) and ...
[ "Generate", "summaries", "for", "features", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L2146-L2161
[ "def", "summarize_features", "(", "features", ",", "num_shards", "=", "1", ")", ":", "if", "not", "common_layers", ".", "should_generate_summaries", "(", ")", ":", "return", "with", "tf", ".", "name_scope", "(", "\"input_stats\"", ")", ":", "for", "(", "k", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_compose_custom_getters
Compose two custom getters. Example use: tf.get_variable_scope().set_custom_getter( compose_custom_getters(tf.get_variable_scope().custom_getter, new_getter)) This composes getters in the same way as creating a new variable scope with the new_getter, but it does not actually create a new variable scope. ...
tensor2tensor/utils/t2t_model.py
def _compose_custom_getters(getter_a, getter_b): """Compose two custom getters. Example use: tf.get_variable_scope().set_custom_getter( compose_custom_getters(tf.get_variable_scope().custom_getter, new_getter)) This composes getters in the same way as creating a new variable scope with the new_getter, b...
def _compose_custom_getters(getter_a, getter_b): """Compose two custom getters. Example use: tf.get_variable_scope().set_custom_getter( compose_custom_getters(tf.get_variable_scope().custom_getter, new_getter)) This composes getters in the same way as creating a new variable scope with the new_getter, b...
[ "Compose", "two", "custom", "getters", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L2186-L2211
[ "def", "_compose_custom_getters", "(", "getter_a", ",", "getter_b", ")", ":", "if", "not", "getter_a", ":", "return", "getter_b", "if", "not", "getter_b", ":", "return", "getter_a", "def", "getter_fn", "(", "getter", ",", "*", "args", ",", "*", "*", "kwarg...
272500b6efe353aeb638d2745ed56e519462ca31
train
set_custom_getter_compose
Set a custom getter in the current variable scope. Do not overwrite the existing custom getter - rather compose with it. Args: custom_getter: a custom getter.
tensor2tensor/utils/t2t_model.py
def set_custom_getter_compose(custom_getter): """Set a custom getter in the current variable scope. Do not overwrite the existing custom getter - rather compose with it. Args: custom_getter: a custom getter. """ tf.get_variable_scope().set_custom_getter( _compose_custom_getters(tf.get_variable_sco...
def set_custom_getter_compose(custom_getter): """Set a custom getter in the current variable scope. Do not overwrite the existing custom getter - rather compose with it. Args: custom_getter: a custom getter. """ tf.get_variable_scope().set_custom_getter( _compose_custom_getters(tf.get_variable_sco...
[ "Set", "a", "custom", "getter", "in", "the", "current", "variable", "scope", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L2214-L2224
[ "def", "set_custom_getter_compose", "(", "custom_getter", ")", ":", "tf", ".", "get_variable_scope", "(", ")", ".", "set_custom_getter", "(", "_compose_custom_getters", "(", "tf", ".", "get_variable_scope", "(", ")", ".", "custom_getter", ",", "custom_getter", ")", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
initialize_from_ckpt
Initialize variables from given directory.
tensor2tensor/utils/t2t_model.py
def initialize_from_ckpt(ckpt_dir, hparams): """Initialize variables from given directory.""" model_dir = hparams.get("model_dir", None) already_has_ckpt = ( model_dir and tf.train.latest_checkpoint(model_dir) is not None) if already_has_ckpt: return tf.logging.info("Checkpoint dir: %s", ckpt_dir) ...
def initialize_from_ckpt(ckpt_dir, hparams): """Initialize variables from given directory.""" model_dir = hparams.get("model_dir", None) already_has_ckpt = ( model_dir and tf.train.latest_checkpoint(model_dir) is not None) if already_has_ckpt: return tf.logging.info("Checkpoint dir: %s", ckpt_dir) ...
[ "Initialize", "variables", "from", "given", "directory", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L2236-L2255
[ "def", "initialize_from_ckpt", "(", "ckpt_dir", ",", "hparams", ")", ":", "model_dir", "=", "hparams", ".", "get", "(", "\"model_dir\"", ",", "None", ")", "already_has_ckpt", "=", "(", "model_dir", "and", "tf", ".", "train", ".", "latest_checkpoint", "(", "m...
272500b6efe353aeb638d2745ed56e519462ca31
train
T2TModel._target_modality_is_real
Whether the target modality is real-valued.
tensor2tensor/utils/t2t_model.py
def _target_modality_is_real(self): """Whether the target modality is real-valued.""" vocab_size = self._problem_hparams.vocab_size["targets"] if vocab_size is not None and hasattr(self._hparams, "vocab_divisor"): vocab_size += (-vocab_size) % self._hparams.vocab_divisor modality = self._problem_h...
def _target_modality_is_real(self): """Whether the target modality is real-valued.""" vocab_size = self._problem_hparams.vocab_size["targets"] if vocab_size is not None and hasattr(self._hparams, "vocab_divisor"): vocab_size += (-vocab_size) % self._hparams.vocab_divisor modality = self._problem_h...
[ "Whether", "the", "target", "modality", "is", "real", "-", "valued", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L302-L311
[ "def", "_target_modality_is_real", "(", "self", ")", ":", "vocab_size", "=", "self", ".", "_problem_hparams", ".", "vocab_size", "[", "\"targets\"", "]", "if", "vocab_size", "is", "not", "None", "and", "hasattr", "(", "self", ".", "_hparams", ",", "\"vocab_div...
272500b6efe353aeb638d2745ed56e519462ca31
train
T2TModel.model_fn_sharded
Estimator model_fn sharded along batch dimension. Args: sharded_features: {str: [Tensor]}. Features sharded along batch dimension. Each list is the same length (== number of shards). Returns: sharded_logits: [Tensor]. Logits for each shard of examples. losses: {str: 0-D Tensor}. Loss...
tensor2tensor/utils/t2t_model.py
def model_fn_sharded(self, sharded_features): """Estimator model_fn sharded along batch dimension. Args: sharded_features: {str: [Tensor]}. Features sharded along batch dimension. Each list is the same length (== number of shards). Returns: sharded_logits: [Tensor]. Logits for each sha...
def model_fn_sharded(self, sharded_features): """Estimator model_fn sharded along batch dimension. Args: sharded_features: {str: [Tensor]}. Features sharded along batch dimension. Each list is the same length (== number of shards). Returns: sharded_logits: [Tensor]. Logits for each sha...
[ "Estimator", "model_fn", "sharded", "along", "batch", "dimension", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L348-L412
[ "def", "model_fn_sharded", "(", "self", ",", "sharded_features", ")", ":", "dp", "=", "self", ".", "_data_parallelism", "# [{str: Tensor}]. Transpose of 'sharded_features'.", "datashard_to_features", "=", "self", ".", "_to_features_per_datashard", "(", "sharded_features", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
T2TModel.bottom
Transforms features to feed into body. Args: features: dict of str to Tensor. Typically it is the preprocessed data batch after Problem's preprocess_example(). Returns: transformed_features: dict of same key-value pairs as features. The value Tensors are newly transformed.
tensor2tensor/utils/t2t_model.py
def bottom(self, features): """Transforms features to feed into body. Args: features: dict of str to Tensor. Typically it is the preprocessed data batch after Problem's preprocess_example(). Returns: transformed_features: dict of same key-value pairs as features. The value Tens...
def bottom(self, features): """Transforms features to feed into body. Args: features: dict of str to Tensor. Typically it is the preprocessed data batch after Problem's preprocess_example(). Returns: transformed_features: dict of same key-value pairs as features. The value Tens...
[ "Transforms", "features", "to", "feed", "into", "body", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L443-L516
[ "def", "bottom", "(", "self", ",", "features", ")", ":", "if", "not", "self", ".", "_problem_hparams", ":", "log_warn", "(", "\"Without a Problem, T2TModel.bottom is a passthrough.\"", ")", "return", "features", "transformed_features", "=", "collections", ".", "Ordere...
272500b6efe353aeb638d2745ed56e519462ca31
train
T2TModel.top
Computes logits given body output and features. Args: body_output: dict of str to Tensor, comprising one key-value pair for each target. Each value denotes the target's pre-logit activations. Alternatively, it may be a single Tensor denoting the pre-logits for that target. featu...
tensor2tensor/utils/t2t_model.py
def top(self, body_output, features): """Computes logits given body output and features. Args: body_output: dict of str to Tensor, comprising one key-value pair for each target. Each value denotes the target's pre-logit activations. Alternatively, it may be a single Tensor denoting the pr...
def top(self, body_output, features): """Computes logits given body output and features. Args: body_output: dict of str to Tensor, comprising one key-value pair for each target. Each value denotes the target's pre-logit activations. Alternatively, it may be a single Tensor denoting the pr...
[ "Computes", "logits", "given", "body", "output", "and", "features", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L583-L612
[ "def", "top", "(", "self", ",", "body_output", ",", "features", ")", ":", "if", "isinstance", "(", "body_output", ",", "dict", ")", ":", "logits", "=", "{", "}", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "body_output", ")", ":", "# ...
272500b6efe353aeb638d2745ed56e519462ca31
train
T2TModel.optimize
Return a training op minimizing loss.
tensor2tensor/utils/t2t_model.py
def optimize(self, loss, num_async_replicas=1, use_tpu=False): """Return a training op minimizing loss.""" lr = learning_rate.learning_rate_schedule(self.hparams) if num_async_replicas > 1: log_info("Dividing learning rate by num_async_replicas: %d", num_async_replicas) lr /= math.s...
def optimize(self, loss, num_async_replicas=1, use_tpu=False): """Return a training op minimizing loss.""" lr = learning_rate.learning_rate_schedule(self.hparams) if num_async_replicas > 1: log_info("Dividing learning rate by num_async_replicas: %d", num_async_replicas) lr /= math.s...
[ "Return", "a", "training", "op", "minimizing", "loss", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L710-L718
[ "def", "optimize", "(", "self", ",", "loss", ",", "num_async_replicas", "=", "1", ",", "use_tpu", "=", "False", ")", ":", "lr", "=", "learning_rate", ".", "learning_rate_schedule", "(", "self", ".", "hparams", ")", "if", "num_async_replicas", ">", "1", ":"...
272500b6efe353aeb638d2745ed56e519462ca31
train
T2TModel.set_mode
Set hparams with the given mode.
tensor2tensor/utils/t2t_model.py
def set_mode(self, mode): """Set hparams with the given mode.""" log_info("Setting T2TModel mode to '%s'", mode) hparams = hparams_lib.copy_hparams(self._original_hparams) hparams.add_hparam("mode", mode) # When not in training mode, set all forms of dropout to zero. if mode != tf.estimator.Mode...
def set_mode(self, mode): """Set hparams with the given mode.""" log_info("Setting T2TModel mode to '%s'", mode) hparams = hparams_lib.copy_hparams(self._original_hparams) hparams.add_hparam("mode", mode) # When not in training mode, set all forms of dropout to zero. if mode != tf.estimator.Mode...
[ "Set", "hparams", "with", "the", "given", "mode", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L720-L731
[ "def", "set_mode", "(", "self", ",", "mode", ")", ":", "log_info", "(", "\"Setting T2TModel mode to '%s'\"", ",", "mode", ")", "hparams", "=", "hparams_lib", ".", "copy_hparams", "(", "self", ".", "_original_hparams", ")", "hparams", ".", "add_hparam", "(", "\...
272500b6efe353aeb638d2745ed56e519462ca31
train
T2TModel.eval_autoregressive
Autoregressive eval. Quadratic time in decode_length. Args: features: an map of string to `Tensor` decode_length: an integer. How many additional timesteps to decode. Returns: logits: `Tensor` losses: a dictionary: {loss-name (string): floating point `Scalar`}. Contains...
tensor2tensor/utils/t2t_model.py
def eval_autoregressive(self, features=None, decode_length=50): """Autoregressive eval. Quadratic time in decode_length. Args: features: an map of string to `Tensor` decode_length: an integer. How many additional timesteps to decode. Returns: logits: `Tensor` losses: a dictio...
def eval_autoregressive(self, features=None, decode_length=50): """Autoregressive eval. Quadratic time in decode_length. Args: features: an map of string to `Tensor` decode_length: an integer. How many additional timesteps to decode. Returns: logits: `Tensor` losses: a dictio...
[ "Autoregressive", "eval", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L737-L752
[ "def", "eval_autoregressive", "(", "self", ",", "features", "=", "None", ",", "decode_length", "=", "50", ")", ":", "results", "=", "self", ".", "_slow_greedy_infer", "(", "features", ",", "decode_length", "=", "decode_length", ")", "return", "results", "[", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
T2TModel.infer
A inference method. Quadratic time in decode_length. Args: features: an map of string to `Tensor` decode_length: an integer. How many additional timesteps to decode. beam_size: number of beams. top_beams: an integer. How many of the beams to return. alpha: Float that controls th...
tensor2tensor/utils/t2t_model.py
def infer(self, features=None, decode_length=50, beam_size=1, top_beams=1, alpha=0.0, use_tpu=False): """A inference method. Quadratic time in decode_length. Args: features: an map of string to `Tensor` decode_length: an i...
def infer(self, features=None, decode_length=50, beam_size=1, top_beams=1, alpha=0.0, use_tpu=False): """A inference method. Quadratic time in decode_length. Args: features: an map of string to `Tensor` decode_length: an i...
[ "A", "inference", "method", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L761-L817
[ "def", "infer", "(", "self", ",", "features", "=", "None", ",", "decode_length", "=", "50", ",", "beam_size", "=", "1", ",", "top_beams", "=", "1", ",", "alpha", "=", "0.0", ",", "use_tpu", "=", "False", ")", ":", "set_custom_getter_compose", "(", "sel...
272500b6efe353aeb638d2745ed56e519462ca31
train
T2TModel._beam_decode
Beam search decoding. Models should ideally implement a more efficient version of this function. Args: features: an map of string to `Tensor` decode_length: an integer. How many additional timesteps to decode. beam_size: number of beams. top_beams: an integer. How many of the beams to...
tensor2tensor/utils/t2t_model.py
def _beam_decode(self, features, decode_length, beam_size, top_beams, alpha, use_tpu=False): """Beam search decoding. Models should ideally implement a more efficient version of this function. ...
def _beam_decode(self, features, decode_length, beam_size, top_beams, alpha, use_tpu=False): """Beam search decoding. Models should ideally implement a more efficient version of this function. ...
[ "Beam", "search", "decoding", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L819-L843
[ "def", "_beam_decode", "(", "self", ",", "features", ",", "decode_length", ",", "beam_size", ",", "top_beams", ",", "alpha", ",", "use_tpu", "=", "False", ")", ":", "return", "self", ".", "_beam_decode_slow", "(", "features", ",", "decode_length", ",", "beam...
272500b6efe353aeb638d2745ed56e519462ca31