id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
22,700 | tensorflow/tensor2tensor | tensor2tensor/data_generators/multi_problem_v2.py | decode_schedule | def decode_schedule(string):
"""Decodes a string into a schedule tuple.
Args:
string: The string encoding of a schedule tuple.
Returns:
A schedule tuple, see encode_schedule for details.
"""
splits = string.split()
steps = [int(x[1:]) for x in splits[1:] if x[0] == '@']
pmfs = np.reshape(
... | python | def decode_schedule(string):
"""Decodes a string into a schedule tuple.
Args:
string: The string encoding of a schedule tuple.
Returns:
A schedule tuple, see encode_schedule for details.
"""
splits = string.split()
steps = [int(x[1:]) for x in splits[1:] if x[0] == '@']
pmfs = np.reshape(
... | [
"def",
"decode_schedule",
"(",
"string",
")",
":",
"splits",
"=",
"string",
".",
"split",
"(",
")",
"steps",
"=",
"[",
"int",
"(",
"x",
"[",
"1",
":",
"]",
")",
"for",
"x",
"in",
"splits",
"[",
"1",
":",
"]",
"if",
"x",
"[",
"0",
"]",
"==",
... | Decodes a string into a schedule tuple.
Args:
string: The string encoding of a schedule tuple.
Returns:
A schedule tuple, see encode_schedule for details. | [
"Decodes",
"a",
"string",
"into",
"a",
"schedule",
"tuple",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L397-L410 |
22,701 | tensorflow/tensor2tensor | tensor2tensor/data_generators/multi_problem_v2.py | tuplize | def tuplize(nested):
"""Recursively converts iterables into tuples.
Args:
nested: A nested structure of items and iterables.
Returns:
A nested structure of items and tuples.
"""
if isinstance(nested, str):
return nested
try:
return tuple(map(tuplize, nested))
except TypeError:
return... | python | def tuplize(nested):
"""Recursively converts iterables into tuples.
Args:
nested: A nested structure of items and iterables.
Returns:
A nested structure of items and tuples.
"""
if isinstance(nested, str):
return nested
try:
return tuple(map(tuplize, nested))
except TypeError:
return... | [
"def",
"tuplize",
"(",
"nested",
")",
":",
"if",
"isinstance",
"(",
"nested",
",",
"str",
")",
":",
"return",
"nested",
"try",
":",
"return",
"tuple",
"(",
"map",
"(",
"tuplize",
",",
"nested",
")",
")",
"except",
"TypeError",
":",
"return",
"nested"
] | Recursively converts iterables into tuples.
Args:
nested: A nested structure of items and iterables.
Returns:
A nested structure of items and tuples. | [
"Recursively",
"converts",
"iterables",
"into",
"tuples",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L413-L427 |
22,702 | tensorflow/tensor2tensor | tensor2tensor/data_generators/multi_problem_v2.py | MultiProblemV2.filepattern | def filepattern(self, *args, **kwargs):
"""Returns a list of filepatterns, one for each problem."""
return [p.filepattern(*args, **kwargs) for p in self.problems] | python | def filepattern(self, *args, **kwargs):
"""Returns a list of filepatterns, one for each problem."""
return [p.filepattern(*args, **kwargs) for p in self.problems] | [
"def",
"filepattern",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"p",
".",
"filepattern",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"for",
"p",
"in",
"self",
".",
"problems",
"]"
] | Returns a list of filepatterns, one for each problem. | [
"Returns",
"a",
"list",
"of",
"filepatterns",
"one",
"for",
"each",
"problem",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L82-L84 |
22,703 | tensorflow/tensor2tensor | tensor2tensor/data_generators/multi_problem_v2.py | MultiProblemV2.generate_data | def generate_data(self, *args, **kwargs):
"""Generates data for each problem."""
for p in self.problems:
p.generate_data(*args, **kwargs) | python | def generate_data(self, *args, **kwargs):
"""Generates data for each problem."""
for p in self.problems:
p.generate_data(*args, **kwargs) | [
"def",
"generate_data",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"p",
"in",
"self",
".",
"problems",
":",
"p",
".",
"generate_data",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Generates data for each problem. | [
"Generates",
"data",
"for",
"each",
"problem",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L86-L89 |
22,704 | tensorflow/tensor2tensor | tensor2tensor/data_generators/multi_problem_v2.py | MultiProblemV2.dataset | def dataset(self, mode, hparams=None, global_step=None, **kwargs):
"""Returns a dataset containing examples from multiple problems.
Args:
mode: A member of problem.DatasetSplit.
hparams: A tf.HParams object, the model hparams.
global_step: A scalar tensor used to compute the sampling distribu... | python | def dataset(self, mode, hparams=None, global_step=None, **kwargs):
"""Returns a dataset containing examples from multiple problems.
Args:
mode: A member of problem.DatasetSplit.
hparams: A tf.HParams object, the model hparams.
global_step: A scalar tensor used to compute the sampling distribu... | [
"def",
"dataset",
"(",
"self",
",",
"mode",
",",
"hparams",
"=",
"None",
",",
"global_step",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"datasets",
"=",
"[",
"p",
".",
"dataset",
"(",
"mode",
",",
"*",
"*",
"kwargs",
")",
"for",
"p",
"in",
... | Returns a dataset containing examples from multiple problems.
Args:
mode: A member of problem.DatasetSplit.
hparams: A tf.HParams object, the model hparams.
global_step: A scalar tensor used to compute the sampling distribution.
If global_step is None, we call tf.train.get_or_create_globa... | [
"Returns",
"a",
"dataset",
"containing",
"examples",
"from",
"multiple",
"problems",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L101-L133 |
22,705 | tensorflow/tensor2tensor | tensor2tensor/data_generators/multi_problem_v2.py | MultiText2TextProblem.normalize_example | def normalize_example(self, example, hparams):
"""Assumes that example contains both inputs and targets."""
length = self.max_length(hparams)
def _to_constant_shape(tensor):
tensor = tensor[:length]
tensor = tf.pad(tensor, [(0, length - tf.shape(tensor)[0])])
return tf.reshape(tensor, [le... | python | def normalize_example(self, example, hparams):
"""Assumes that example contains both inputs and targets."""
length = self.max_length(hparams)
def _to_constant_shape(tensor):
tensor = tensor[:length]
tensor = tf.pad(tensor, [(0, length - tf.shape(tensor)[0])])
return tf.reshape(tensor, [le... | [
"def",
"normalize_example",
"(",
"self",
",",
"example",
",",
"hparams",
")",
":",
"length",
"=",
"self",
".",
"max_length",
"(",
"hparams",
")",
"def",
"_to_constant_shape",
"(",
"tensor",
")",
":",
"tensor",
"=",
"tensor",
"[",
":",
"length",
"]",
"ten... | Assumes that example contains both inputs and targets. | [
"Assumes",
"that",
"example",
"contains",
"both",
"inputs",
"and",
"targets",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L139-L181 |
22,706 | tensorflow/tensor2tensor | tensor2tensor/data_generators/multi_problem_v2.py | MultiText2TextProblem.generate_data_with_shared_vocab | def generate_data_with_shared_vocab(self, data_dir, tmp_dir, task_id=-1):
"""Generates TF-Records for problems using a global vocabulary file."""
global_vocab_filename = os.path.join(data_dir, self.vocab_filename)
if not tf.gfile.Exists(global_vocab_filename):
raise ValueError(
'Global vocab... | python | def generate_data_with_shared_vocab(self, data_dir, tmp_dir, task_id=-1):
"""Generates TF-Records for problems using a global vocabulary file."""
global_vocab_filename = os.path.join(data_dir, self.vocab_filename)
if not tf.gfile.Exists(global_vocab_filename):
raise ValueError(
'Global vocab... | [
"def",
"generate_data_with_shared_vocab",
"(",
"self",
",",
"data_dir",
",",
"tmp_dir",
",",
"task_id",
"=",
"-",
"1",
")",
":",
"global_vocab_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
"self",
".",
"vocab_filename",
")",
"if",
"... | Generates TF-Records for problems using a global vocabulary file. | [
"Generates",
"TF",
"-",
"Records",
"for",
"problems",
"using",
"a",
"global",
"vocabulary",
"file",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L183-L197 |
22,707 | tensorflow/tensor2tensor | tensor2tensor/layers/area_attention.py | lengths_to_area_mask | def lengths_to_area_mask(feature_length, length, max_area_size):
"""Generates a non-padding mask for areas based on lengths.
Args:
feature_length: a tensor of [batch_size]
length: the length of the batch
max_area_size: the maximum area size considered
Returns:
mask: a tensor in shape of [batch_si... | python | def lengths_to_area_mask(feature_length, length, max_area_size):
"""Generates a non-padding mask for areas based on lengths.
Args:
feature_length: a tensor of [batch_size]
length: the length of the batch
max_area_size: the maximum area size considered
Returns:
mask: a tensor in shape of [batch_si... | [
"def",
"lengths_to_area_mask",
"(",
"feature_length",
",",
"length",
",",
"max_area_size",
")",
":",
"paddings",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"expand_dims",
"(",
"tf",
".",
"logical_not",
"(",
"tf",
".",
"sequence_mask",
"(",
"feature_length",
","... | Generates a non-padding mask for areas based on lengths.
Args:
feature_length: a tensor of [batch_size]
length: the length of the batch
max_area_size: the maximum area size considered
Returns:
mask: a tensor in shape of [batch_size, num_areas] | [
"Generates",
"a",
"non",
"-",
"padding",
"mask",
"for",
"areas",
"based",
"on",
"lengths",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/area_attention.py#L27-L44 |
22,708 | tensorflow/tensor2tensor | tensor2tensor/layers/area_attention.py | _pool_one_shape | def _pool_one_shape(features_2d, area_width, area_height, batch_size,
width, height, depth, fn=tf.reduce_max, name=None):
"""Pools for an area in features_2d.
Args:
features_2d: a Tensor in a shape of [batch_size, height, width, depth].
area_width: the max width allowed for an area.
... | python | def _pool_one_shape(features_2d, area_width, area_height, batch_size,
width, height, depth, fn=tf.reduce_max, name=None):
"""Pools for an area in features_2d.
Args:
features_2d: a Tensor in a shape of [batch_size, height, width, depth].
area_width: the max width allowed for an area.
... | [
"def",
"_pool_one_shape",
"(",
"features_2d",
",",
"area_width",
",",
"area_height",
",",
"batch_size",
",",
"width",
",",
"height",
",",
"depth",
",",
"fn",
"=",
"tf",
".",
"reduce_max",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope... | Pools for an area in features_2d.
Args:
features_2d: a Tensor in a shape of [batch_size, height, width, depth].
area_width: the max width allowed for an area.
area_height: the max height allowed for an area.
batch_size: the batch size.
width: the width of the memory.
height: the height of the... | [
"Pools",
"for",
"an",
"area",
"in",
"features_2d",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/area_attention.py#L47-L75 |
22,709 | tensorflow/tensor2tensor | tensor2tensor/layers/area_attention.py | compute_area_features | def compute_area_features(features, max_area_width, max_area_height=1, height=1,
epsilon=1e-6):
"""Computes features for each area.
Args:
features: a Tensor in a shape of [batch_size, height * width, depth].
max_area_width: the max width allowed for an area.
max_area_height: t... | python | def compute_area_features(features, max_area_width, max_area_height=1, height=1,
epsilon=1e-6):
"""Computes features for each area.
Args:
features: a Tensor in a shape of [batch_size, height * width, depth].
max_area_width: the max width allowed for an area.
max_area_height: t... | [
"def",
"compute_area_features",
"(",
"features",
",",
"max_area_width",
",",
"max_area_height",
"=",
"1",
",",
"height",
"=",
"1",
",",
"epsilon",
"=",
"1e-6",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"compute_area_features\"",
")",
":",
"tf",
".",
... | Computes features for each area.
Args:
features: a Tensor in a shape of [batch_size, height * width, depth].
max_area_width: the max width allowed for an area.
max_area_height: the max height allowed for an area.
height: the height of the image.
epsilon: the epsilon added to the variance for comp... | [
"Computes",
"features",
"for",
"each",
"area",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/area_attention.py#L199-L231 |
22,710 | tensorflow/tensor2tensor | tensor2tensor/layers/area_attention.py | compute_area_key | def compute_area_key(features, max_area_width, max_area_height=1, height=1,
mode="mean", training=True, name=None):
"""Computes the key for each area.
Args:
features: a Tensor in a shape of [batch_size, height * width, depth].
max_area_width: the max width allowed for an area.
max_... | python | def compute_area_key(features, max_area_width, max_area_height=1, height=1,
mode="mean", training=True, name=None):
"""Computes the key for each area.
Args:
features: a Tensor in a shape of [batch_size, height * width, depth].
max_area_width: the max width allowed for an area.
max_... | [
"def",
"compute_area_key",
"(",
"features",
",",
"max_area_width",
",",
"max_area_height",
"=",
"1",
",",
"height",
"=",
"1",
",",
"mode",
"=",
"\"mean\"",
",",
"training",
"=",
"True",
",",
"name",
"=",
"None",
")",
":",
"tf",
".",
"logging",
".",
"in... | Computes the key for each area.
Args:
features: a Tensor in a shape of [batch_size, height * width, depth].
max_area_width: the max width allowed for an area.
max_area_height: the max height allowed for an area.
height: the height of the image.
mode: whether to combine different area features or ... | [
"Computes",
"the",
"key",
"for",
"each",
"area",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/area_attention.py#L234-L302 |
22,711 | tensorflow/tensor2tensor | tensor2tensor/rl/trainer_model_based.py | setup_directories | def setup_directories(base_dir, subdirs):
"""Setup directories."""
base_dir = os.path.expanduser(base_dir)
tf.gfile.MakeDirs(base_dir)
all_dirs = {}
for subdir in subdirs:
if isinstance(subdir, six.string_types):
subdir_tuple = (subdir,)
else:
subdir_tuple = subdir
dir_name = os.path.... | python | def setup_directories(base_dir, subdirs):
"""Setup directories."""
base_dir = os.path.expanduser(base_dir)
tf.gfile.MakeDirs(base_dir)
all_dirs = {}
for subdir in subdirs:
if isinstance(subdir, six.string_types):
subdir_tuple = (subdir,)
else:
subdir_tuple = subdir
dir_name = os.path.... | [
"def",
"setup_directories",
"(",
"base_dir",
",",
"subdirs",
")",
":",
"base_dir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"base_dir",
")",
"tf",
".",
"gfile",
".",
"MakeDirs",
"(",
"base_dir",
")",
"all_dirs",
"=",
"{",
"}",
"for",
"subdir",
"... | Setup directories. | [
"Setup",
"directories",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L68-L82 |
22,712 | tensorflow/tensor2tensor | tensor2tensor/rl/trainer_model_based.py | make_relative_timing_fn | def make_relative_timing_fn():
"""Make a function that logs the duration since it was made."""
start_time = time.time()
def format_relative_time():
time_delta = time.time() - start_time
return str(datetime.timedelta(seconds=time_delta))
def log_relative_time():
tf.logging.info("Timing: %s", format... | python | def make_relative_timing_fn():
"""Make a function that logs the duration since it was made."""
start_time = time.time()
def format_relative_time():
time_delta = time.time() - start_time
return str(datetime.timedelta(seconds=time_delta))
def log_relative_time():
tf.logging.info("Timing: %s", format... | [
"def",
"make_relative_timing_fn",
"(",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"def",
"format_relative_time",
"(",
")",
":",
"time_delta",
"=",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
"return",
"str",
"(",
"datetime",
".",
"... | Make a function that logs the duration since it was made. | [
"Make",
"a",
"function",
"that",
"logs",
"the",
"duration",
"since",
"it",
"was",
"made",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L85-L96 |
22,713 | tensorflow/tensor2tensor | tensor2tensor/rl/trainer_model_based.py | train_supervised | def train_supervised(problem, model_name, hparams, data_dir, output_dir,
train_steps, eval_steps, local_eval_frequency=None,
schedule="continuous_train_and_eval"):
"""Train supervised."""
if local_eval_frequency is None:
local_eval_frequency = FLAGS.local_eval_frequency... | python | def train_supervised(problem, model_name, hparams, data_dir, output_dir,
train_steps, eval_steps, local_eval_frequency=None,
schedule="continuous_train_and_eval"):
"""Train supervised."""
if local_eval_frequency is None:
local_eval_frequency = FLAGS.local_eval_frequency... | [
"def",
"train_supervised",
"(",
"problem",
",",
"model_name",
",",
"hparams",
",",
"data_dir",
",",
"output_dir",
",",
"train_steps",
",",
"eval_steps",
",",
"local_eval_frequency",
"=",
"None",
",",
"schedule",
"=",
"\"continuous_train_and_eval\"",
")",
":",
"if"... | Train supervised. | [
"Train",
"supervised",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L125-L138 |
22,714 | tensorflow/tensor2tensor | tensor2tensor/rl/trainer_model_based.py | train_agent | def train_agent(real_env, learner, world_model_dir, hparams, epoch):
"""Train the PPO agent in the simulated environment."""
initial_frame_chooser = rl_utils.make_initial_frame_chooser(
real_env, hparams.frame_stack_size, hparams.simulation_random_starts,
hparams.simulation_flip_first_random_for_beginni... | python | def train_agent(real_env, learner, world_model_dir, hparams, epoch):
"""Train the PPO agent in the simulated environment."""
initial_frame_chooser = rl_utils.make_initial_frame_chooser(
real_env, hparams.frame_stack_size, hparams.simulation_random_starts,
hparams.simulation_flip_first_random_for_beginni... | [
"def",
"train_agent",
"(",
"real_env",
",",
"learner",
",",
"world_model_dir",
",",
"hparams",
",",
"epoch",
")",
":",
"initial_frame_chooser",
"=",
"rl_utils",
".",
"make_initial_frame_chooser",
"(",
"real_env",
",",
"hparams",
".",
"frame_stack_size",
",",
"hpar... | Train the PPO agent in the simulated environment. | [
"Train",
"the",
"PPO",
"agent",
"in",
"the",
"simulated",
"environment",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L141-L170 |
22,715 | tensorflow/tensor2tensor | tensor2tensor/rl/trainer_model_based.py | train_agent_real_env | def train_agent_real_env(env, learner, hparams, epoch):
"""Train the PPO agent in the real environment."""
base_algo_str = hparams.base_algo
train_hparams = trainer_lib.create_hparams(hparams.base_algo_params)
rl_utils.update_hparams_from_hparams(
train_hparams, hparams, "real_" + base_algo_str + "_"
)... | python | def train_agent_real_env(env, learner, hparams, epoch):
"""Train the PPO agent in the real environment."""
base_algo_str = hparams.base_algo
train_hparams = trainer_lib.create_hparams(hparams.base_algo_params)
rl_utils.update_hparams_from_hparams(
train_hparams, hparams, "real_" + base_algo_str + "_"
)... | [
"def",
"train_agent_real_env",
"(",
"env",
",",
"learner",
",",
"hparams",
",",
"epoch",
")",
":",
"base_algo_str",
"=",
"hparams",
".",
"base_algo",
"train_hparams",
"=",
"trainer_lib",
".",
"create_hparams",
"(",
"hparams",
".",
"base_algo_params",
")",
"rl_ut... | Train the PPO agent in the real environment. | [
"Train",
"the",
"PPO",
"agent",
"in",
"the",
"real",
"environment",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L173-L196 |
22,716 | tensorflow/tensor2tensor | tensor2tensor/rl/trainer_model_based.py | train_world_model | def train_world_model(
env, data_dir, output_dir, hparams, world_model_steps_num, epoch
):
"""Train the world model on problem_name."""
world_model_steps_num += world_model_step_increment(
hparams, is_initial_epoch=(epoch == 0)
)
model_hparams = trainer_lib.create_hparams(hparams.generative_model_para... | python | def train_world_model(
env, data_dir, output_dir, hparams, world_model_steps_num, epoch
):
"""Train the world model on problem_name."""
world_model_steps_num += world_model_step_increment(
hparams, is_initial_epoch=(epoch == 0)
)
model_hparams = trainer_lib.create_hparams(hparams.generative_model_para... | [
"def",
"train_world_model",
"(",
"env",
",",
"data_dir",
",",
"output_dir",
",",
"hparams",
",",
"world_model_steps_num",
",",
"epoch",
")",
":",
"world_model_steps_num",
"+=",
"world_model_step_increment",
"(",
"hparams",
",",
"is_initial_epoch",
"=",
"(",
"epoch",... | Train the world model on problem_name. | [
"Train",
"the",
"world",
"model",
"on",
"problem_name",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L199-L228 |
22,717 | tensorflow/tensor2tensor | tensor2tensor/rl/trainer_model_based.py | load_metrics | def load_metrics(event_dir, epoch):
"""Loads metrics for this epoch if they have already been written.
This reads the entire event file but it's small with just per-epoch metrics.
Args:
event_dir: TODO(koz4k): Document this.
epoch: TODO(koz4k): Document this.
Returns:
metrics.
"""
metrics = {... | python | def load_metrics(event_dir, epoch):
"""Loads metrics for this epoch if they have already been written.
This reads the entire event file but it's small with just per-epoch metrics.
Args:
event_dir: TODO(koz4k): Document this.
epoch: TODO(koz4k): Document this.
Returns:
metrics.
"""
metrics = {... | [
"def",
"load_metrics",
"(",
"event_dir",
",",
"epoch",
")",
":",
"metrics",
"=",
"{",
"}",
"for",
"filename",
"in",
"tf",
".",
"gfile",
".",
"ListDirectory",
"(",
"event_dir",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"event_dir",
"... | Loads metrics for this epoch if they have already been written.
This reads the entire event file but it's small with just per-epoch metrics.
Args:
event_dir: TODO(koz4k): Document this.
epoch: TODO(koz4k): Document this.
Returns:
metrics. | [
"Loads",
"metrics",
"for",
"this",
"epoch",
"if",
"they",
"have",
"already",
"been",
"written",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_based.py#L231-L250 |
22,718 | tensorflow/tensor2tensor | tensor2tensor/models/research/gene_expression.py | conv_layer | def conv_layer(x,
hidden_size,
kernel_size,
stride,
pooling_window,
dropout_rate,
dilation_rate,
name="conv"):
"""Single conv layer with relu, optional pooling, and dropout."""
with tf.variable_scope(name):
... | python | def conv_layer(x,
hidden_size,
kernel_size,
stride,
pooling_window,
dropout_rate,
dilation_rate,
name="conv"):
"""Single conv layer with relu, optional pooling, and dropout."""
with tf.variable_scope(name):
... | [
"def",
"conv_layer",
"(",
"x",
",",
"hidden_size",
",",
"kernel_size",
",",
"stride",
",",
"pooling_window",
",",
"dropout_rate",
",",
"dilation_rate",
",",
"name",
"=",
"\"conv\"",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
")",
":",
"out... | Single conv layer with relu, optional pooling, and dropout. | [
"Single",
"conv",
"layer",
"with",
"relu",
"optional",
"pooling",
"and",
"dropout",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/gene_expression.py#L92-L114 |
22,719 | tensorflow/tensor2tensor | tensor2tensor/models/research/gene_expression.py | gene_expression_conv_base | def gene_expression_conv_base():
"""Hparams for GeneExpressionConv model."""
hparams = common_hparams.basic_params1()
batch_size = 10
output_length = 2048
inputs_per_output = 128
chunk_size = 4
input_length = output_length * inputs_per_output // chunk_size
hparams.batch_size = input_length * batch_size... | python | def gene_expression_conv_base():
"""Hparams for GeneExpressionConv model."""
hparams = common_hparams.basic_params1()
batch_size = 10
output_length = 2048
inputs_per_output = 128
chunk_size = 4
input_length = output_length * inputs_per_output // chunk_size
hparams.batch_size = input_length * batch_size... | [
"def",
"gene_expression_conv_base",
"(",
")",
":",
"hparams",
"=",
"common_hparams",
".",
"basic_params1",
"(",
")",
"batch_size",
"=",
"10",
"output_length",
"=",
"2048",
"inputs_per_output",
"=",
"128",
"chunk_size",
"=",
"4",
"input_length",
"=",
"output_length... | Hparams for GeneExpressionConv model. | [
"Hparams",
"for",
"GeneExpressionConv",
"model",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/gene_expression.py#L128-L149 |
22,720 | tensorflow/tensor2tensor | tensor2tensor/layers/latent_layers.py | compress_self_attention_layer | def compress_self_attention_layer(x, hparams, name=None):
"""Attend function."""
with tf.variable_scope(name, default_name="compress_self_attention"):
x, xshape, _ = cia.maybe_reshape_4d_to_3d(x)
y = common_attention.multihead_attention(
common_layers.layer_preprocess(x, hparams),
None,
... | python | def compress_self_attention_layer(x, hparams, name=None):
"""Attend function."""
with tf.variable_scope(name, default_name="compress_self_attention"):
x, xshape, _ = cia.maybe_reshape_4d_to_3d(x)
y = common_attention.multihead_attention(
common_layers.layer_preprocess(x, hparams),
None,
... | [
"def",
"compress_self_attention_layer",
"(",
"x",
",",
"hparams",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"compress_self_attention\"",
")",
":",
"x",
",",
"xshape",
",",
"_",
"=",
"c... | Attend function. | [
"Attend",
"function",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L35-L48 |
22,721 | tensorflow/tensor2tensor | tensor2tensor/layers/latent_layers.py | compute_nats_and_bits_per_dim | def compute_nats_and_bits_per_dim(data_dim,
latent_dim,
average_reconstruction,
average_prior):
"""Computes negative ELBO, which is an upper bound on the negative likelihood.
Args:
data_dim: int-like indicatin... | python | def compute_nats_and_bits_per_dim(data_dim,
latent_dim,
average_reconstruction,
average_prior):
"""Computes negative ELBO, which is an upper bound on the negative likelihood.
Args:
data_dim: int-like indicatin... | [
"def",
"compute_nats_and_bits_per_dim",
"(",
"data_dim",
",",
"latent_dim",
",",
"average_reconstruction",
",",
"average_prior",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"None",
",",
"default_name",
"=",
"\"compute_nats_per_dim\"",
")",
":",
"data_dim",
"=",
... | Computes negative ELBO, which is an upper bound on the negative likelihood.
Args:
data_dim: int-like indicating data dimensionality.
latent_dim: int-like indicating latent dimensionality.
average_reconstruction: Scalar Tensor indicating the reconstruction cost
averaged over all data dimensions and ... | [
"Computes",
"negative",
"ELBO",
"which",
"is",
"an",
"upper",
"bound",
"on",
"the",
"negative",
"likelihood",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L51-L77 |
22,722 | tensorflow/tensor2tensor | tensor2tensor/layers/latent_layers.py | multinomial_sample | def multinomial_sample(x, vocab_size=None, sampling_method="random",
temperature=1.0):
"""Multinomial sampling from a n-dimensional tensor.
Args:
x: Tensor of shape [..., vocab_size]. Parameterizes logits of multinomial.
vocab_size: Number of classes in multinomial distribution.
... | python | def multinomial_sample(x, vocab_size=None, sampling_method="random",
temperature=1.0):
"""Multinomial sampling from a n-dimensional tensor.
Args:
x: Tensor of shape [..., vocab_size]. Parameterizes logits of multinomial.
vocab_size: Number of classes in multinomial distribution.
... | [
"def",
"multinomial_sample",
"(",
"x",
",",
"vocab_size",
"=",
"None",
",",
"sampling_method",
"=",
"\"random\"",
",",
"temperature",
"=",
"1.0",
")",
":",
"vocab_size",
"=",
"vocab_size",
"or",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"[",
"-",
... | Multinomial sampling from a n-dimensional tensor.
Args:
x: Tensor of shape [..., vocab_size]. Parameterizes logits of multinomial.
vocab_size: Number of classes in multinomial distribution.
sampling_method: String, "random" or otherwise deterministic.
temperature: Positive float.
Returns:
Tens... | [
"Multinomial",
"sampling",
"from",
"a",
"n",
"-",
"dimensional",
"tensor",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L80-L99 |
22,723 | tensorflow/tensor2tensor | tensor2tensor/layers/latent_layers.py | ae_latent_sample_beam | def ae_latent_sample_beam(latents_dense_in, inputs, ed, embed, hparams):
"""Samples from the latent space in the autoencoder.
Args:
latents_dense_in: Tensor of shape [batch, length_q, ...]. Only the shape of
its first two dimensions are used. length_q is the latent length, which is
height * width *... | python | def ae_latent_sample_beam(latents_dense_in, inputs, ed, embed, hparams):
"""Samples from the latent space in the autoencoder.
Args:
latents_dense_in: Tensor of shape [batch, length_q, ...]. Only the shape of
its first two dimensions are used. length_q is the latent length, which is
height * width *... | [
"def",
"ae_latent_sample_beam",
"(",
"latents_dense_in",
",",
"inputs",
",",
"ed",
",",
"embed",
",",
"hparams",
")",
":",
"def",
"symbols_to_logits_fn",
"(",
"ids",
")",
":",
"\"\"\"Go from ids to logits.\"\"\"",
"ids",
"=",
"tf",
".",
"expand_dims",
"(",
"ids"... | Samples from the latent space in the autoencoder.
Args:
latents_dense_in: Tensor of shape [batch, length_q, ...]. Only the shape of
its first two dimensions are used. length_q is the latent length, which is
height * width * hparams.num_latents / (2**hparams.num_compress_steps).
inputs: Tensor of ... | [
"Samples",
"from",
"the",
"latent",
"space",
"in",
"the",
"autoencoder",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L133-L182 |
22,724 | tensorflow/tensor2tensor | tensor2tensor/layers/latent_layers.py | residual_block_layer | def residual_block_layer(inputs, hparams):
"""Residual block over inputs.
Runs a residual block consisting of
conv: kernel_size x kernel_size
conv: 1x1
dropout, add and normalize according to hparams.layer_postprocess_sequence.
Args:
inputs: Tensor of shape [batch, height, width, hparams.hidden_... | python | def residual_block_layer(inputs, hparams):
"""Residual block over inputs.
Runs a residual block consisting of
conv: kernel_size x kernel_size
conv: 1x1
dropout, add and normalize according to hparams.layer_postprocess_sequence.
Args:
inputs: Tensor of shape [batch, height, width, hparams.hidden_... | [
"def",
"residual_block_layer",
"(",
"inputs",
",",
"hparams",
")",
":",
"kernel",
"=",
"(",
"hparams",
".",
"res_kernel_size",
",",
"hparams",
".",
"res_kernel_size",
")",
"x",
"=",
"inputs",
"for",
"i",
"in",
"range",
"(",
"hparams",
".",
"num_res_layers",
... | Residual block over inputs.
Runs a residual block consisting of
conv: kernel_size x kernel_size
conv: 1x1
dropout, add and normalize according to hparams.layer_postprocess_sequence.
Args:
inputs: Tensor of shape [batch, height, width, hparams.hidden_size].
hparams: HParams.
Returns:
Ten... | [
"Residual",
"block",
"over",
"inputs",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L185-L219 |
22,725 | tensorflow/tensor2tensor | tensor2tensor/layers/latent_layers.py | transformer_text_encoder | def transformer_text_encoder(inputs,
target_space,
hparams,
name=None):
"""Transformer text encoder over inputs with unmasked full attention.
Args:
inputs: Tensor of shape [batch, length, 1, hparams.hidden_size].
target_... | python | def transformer_text_encoder(inputs,
target_space,
hparams,
name=None):
"""Transformer text encoder over inputs with unmasked full attention.
Args:
inputs: Tensor of shape [batch, length, 1, hparams.hidden_size].
target_... | [
"def",
"transformer_text_encoder",
"(",
"inputs",
",",
"target_space",
",",
"hparams",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"transformer_text_encoder\"",
")",
":",
"inputs",
"=",
"com... | Transformer text encoder over inputs with unmasked full attention.
Args:
inputs: Tensor of shape [batch, length, 1, hparams.hidden_size].
target_space: int. Used for encoding inputs under a target space id.
hparams: HParams.
name: string, variable scope.
Returns:
encoder_output: Tensor of shap... | [
"Transformer",
"text",
"encoder",
"over",
"inputs",
"with",
"unmasked",
"full",
"attention",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L391-L419 |
22,726 | tensorflow/tensor2tensor | tensor2tensor/layers/latent_layers.py | transformer_image_decoder | def transformer_image_decoder(targets,
encoder_output,
ed_attention_bias,
hparams,
name=None):
"""Transformer image decoder over targets with local attention.
Args:
targets: Tensor of shape [... | python | def transformer_image_decoder(targets,
encoder_output,
ed_attention_bias,
hparams,
name=None):
"""Transformer image decoder over targets with local attention.
Args:
targets: Tensor of shape [... | [
"def",
"transformer_image_decoder",
"(",
"targets",
",",
"encoder_output",
",",
"ed_attention_bias",
",",
"hparams",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"transformer_dec\"",
")",
":",
... | Transformer image decoder over targets with local attention.
Args:
targets: Tensor of shape [batch, ...], and whose size is batch * height *
width * hparams.num_channels * hparams.hidden_size.
encoder_output: Tensor of shape [batch, length_kv, hparams.hidden_size].
ed_attention_bias: Tensor which b... | [
"Transformer",
"image",
"decoder",
"over",
"targets",
"with",
"local",
"attention",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L422-L462 |
22,727 | tensorflow/tensor2tensor | tensor2tensor/layers/latent_layers.py | transformer_latent_decoder | def transformer_latent_decoder(x,
encoder_output,
ed_attention_bias,
hparams,
name=None):
"""Transformer decoder over latents using latent_attention_type.
Args:
x: Tensor of shape [batch,... | python | def transformer_latent_decoder(x,
encoder_output,
ed_attention_bias,
hparams,
name=None):
"""Transformer decoder over latents using latent_attention_type.
Args:
x: Tensor of shape [batch,... | [
"def",
"transformer_latent_decoder",
"(",
"x",
",",
"encoder_output",
",",
"ed_attention_bias",
",",
"hparams",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"transformer_latent_dec\"",
")",
":"... | Transformer decoder over latents using latent_attention_type.
Args:
x: Tensor of shape [batch, length_q, hparams.hidden_size]. length_q is the
latent length, which is
height * width * hparams.num_latents / (2**hparams.num_compress_steps).
encoder_output: Tensor of shape [batch, length_kv, hparams... | [
"Transformer",
"decoder",
"over",
"latents",
"using",
"latent_attention_type",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L465-L506 |
22,728 | tensorflow/tensor2tensor | tensor2tensor/layers/latent_layers.py | latent_prediction_model | def latent_prediction_model(inputs,
ed_attention_bias,
latents_discrete,
latents_dense,
hparams,
vocab_size=None,
name=None):
"""Transformer-based lat... | python | def latent_prediction_model(inputs,
ed_attention_bias,
latents_discrete,
latents_dense,
hparams,
vocab_size=None,
name=None):
"""Transformer-based lat... | [
"def",
"latent_prediction_model",
"(",
"inputs",
",",
"ed_attention_bias",
",",
"latents_discrete",
",",
"latents_dense",
",",
"hparams",
",",
"vocab_size",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",... | Transformer-based latent prediction model.
It is an autoregressive decoder over latents_discrete given inputs.
Args:
inputs: Tensor of shape [batch, length_kv, hparams.hidden_size]. Inputs to
attend to for the decoder on latents.
ed_attention_bias: Tensor which broadcasts with shape [batch,
hp... | [
"Transformer",
"-",
"based",
"latent",
"prediction",
"model",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L529-L573 |
22,729 | tensorflow/tensor2tensor | tensor2tensor/layers/latent_layers.py | iaf_flow | def iaf_flow(one_hot_assignments,
scale_weights,
scale_bias,
num_codes,
summary=True,
name=None):
"""Performs a single IAF flow using scale and normalization transformations.
Args:
one_hot_assignments: Assignments Tensor with shape [num_samples, ... | python | def iaf_flow(one_hot_assignments,
scale_weights,
scale_bias,
num_codes,
summary=True,
name=None):
"""Performs a single IAF flow using scale and normalization transformations.
Args:
one_hot_assignments: Assignments Tensor with shape [num_samples, ... | [
"def",
"iaf_flow",
"(",
"one_hot_assignments",
",",
"scale_weights",
",",
"scale_bias",
",",
"num_codes",
",",
"summary",
"=",
"True",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"default_name",
"=",
"\"iaf\"",
")... | Performs a single IAF flow using scale and normalization transformations.
Args:
one_hot_assignments: Assignments Tensor with shape [num_samples, batch_size,
latent_size, num_codes].
scale_weights: Tensor corresponding to lower triangular matrix used to
autoregressively generate scale matrix from ... | [
"Performs",
"a",
"single",
"IAF",
"flow",
"using",
"scale",
"and",
"normalization",
"transformations",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L703-L758 |
22,730 | tensorflow/tensor2tensor | tensor2tensor/data_generators/image_lsun.py | _get_lsun | def _get_lsun(directory, category, split_name):
"""Downloads all lsun files to directory unless they are there."""
generator_utils.maybe_download(directory,
_LSUN_DATA_FILENAME % (category, split_name),
_LSUN_URL % (category, split_name)) | python | def _get_lsun(directory, category, split_name):
"""Downloads all lsun files to directory unless they are there."""
generator_utils.maybe_download(directory,
_LSUN_DATA_FILENAME % (category, split_name),
_LSUN_URL % (category, split_name)) | [
"def",
"_get_lsun",
"(",
"directory",
",",
"category",
",",
"split_name",
")",
":",
"generator_utils",
".",
"maybe_download",
"(",
"directory",
",",
"_LSUN_DATA_FILENAME",
"%",
"(",
"category",
",",
"split_name",
")",
",",
"_LSUN_URL",
"%",
"(",
"category",
",... | Downloads all lsun files to directory unless they are there. | [
"Downloads",
"all",
"lsun",
"files",
"to",
"directory",
"unless",
"they",
"are",
"there",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_lsun.py#L40-L44 |
22,731 | tensorflow/tensor2tensor | tensor2tensor/utils/optimize.py | _mixed_precision_is_enabled | def _mixed_precision_is_enabled(hparams):
"""Should be the same as in common_attention, avoiding import."""
activation_dtype = hparams.activation_dtype
weight_dtype = hparams.weight_dtype
return activation_dtype == tf.float16 and weight_dtype == tf.float32 | python | def _mixed_precision_is_enabled(hparams):
"""Should be the same as in common_attention, avoiding import."""
activation_dtype = hparams.activation_dtype
weight_dtype = hparams.weight_dtype
return activation_dtype == tf.float16 and weight_dtype == tf.float32 | [
"def",
"_mixed_precision_is_enabled",
"(",
"hparams",
")",
":",
"activation_dtype",
"=",
"hparams",
".",
"activation_dtype",
"weight_dtype",
"=",
"hparams",
".",
"weight_dtype",
"return",
"activation_dtype",
"==",
"tf",
".",
"float16",
"and",
"weight_dtype",
"==",
"... | Should be the same as in common_attention, avoiding import. | [
"Should",
"be",
"the",
"same",
"as",
"in",
"common_attention",
"avoiding",
"import",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L36-L40 |
22,732 | tensorflow/tensor2tensor | tensor2tensor/utils/optimize.py | optimize | def optimize(loss, learning_rate, hparams, use_tpu=False, variables=None):
"""Minimize loss."""
loss = weight_decay_and_noise(loss, hparams, learning_rate)
loss = tf.identity(loss, name="total_loss")
if variables is None:
variables = tf.trainable_variables()
# Print trainable variables.
log_variable_siz... | python | def optimize(loss, learning_rate, hparams, use_tpu=False, variables=None):
"""Minimize loss."""
loss = weight_decay_and_noise(loss, hparams, learning_rate)
loss = tf.identity(loss, name="total_loss")
if variables is None:
variables = tf.trainable_variables()
# Print trainable variables.
log_variable_siz... | [
"def",
"optimize",
"(",
"loss",
",",
"learning_rate",
",",
"hparams",
",",
"use_tpu",
"=",
"False",
",",
"variables",
"=",
"None",
")",
":",
"loss",
"=",
"weight_decay_and_noise",
"(",
"loss",
",",
"hparams",
",",
"learning_rate",
")",
"loss",
"=",
"tf",
... | Minimize loss. | [
"Minimize",
"loss",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L43-L94 |
22,733 | tensorflow/tensor2tensor | tensor2tensor/utils/optimize.py | weight_decay_and_noise | def weight_decay_and_noise(loss, hparams, learning_rate, var_list=None):
"""Apply weight decay and weight noise."""
if var_list is None:
var_list = tf.trainable_variables()
decay_vars = [v for v in var_list]
noise_vars = [v for v in var_list if "/body/" in v.name]
weight_decay_loss = weight_decay(hparam... | python | def weight_decay_and_noise(loss, hparams, learning_rate, var_list=None):
"""Apply weight decay and weight noise."""
if var_list is None:
var_list = tf.trainable_variables()
decay_vars = [v for v in var_list]
noise_vars = [v for v in var_list if "/body/" in v.name]
weight_decay_loss = weight_decay(hparam... | [
"def",
"weight_decay_and_noise",
"(",
"loss",
",",
"hparams",
",",
"learning_rate",
",",
"var_list",
"=",
"None",
")",
":",
"if",
"var_list",
"is",
"None",
":",
"var_list",
"=",
"tf",
".",
"trainable_variables",
"(",
")",
"decay_vars",
"=",
"[",
"v",
"for"... | Apply weight decay and weight noise. | [
"Apply",
"weight",
"decay",
"and",
"weight",
"noise",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L238-L256 |
22,734 | tensorflow/tensor2tensor | tensor2tensor/utils/optimize.py | weight_noise | def weight_noise(noise_rate, learning_rate, var_list):
"""Apply weight noise to vars in var_list."""
if not noise_rate:
return [tf.no_op()]
tf.logging.info("Applying weight noise scaled by learning rate, "
"noise_rate: %0.5f", noise_rate)
noise_ops = []
for v in var_list:
with tf.... | python | def weight_noise(noise_rate, learning_rate, var_list):
"""Apply weight noise to vars in var_list."""
if not noise_rate:
return [tf.no_op()]
tf.logging.info("Applying weight noise scaled by learning rate, "
"noise_rate: %0.5f", noise_rate)
noise_ops = []
for v in var_list:
with tf.... | [
"def",
"weight_noise",
"(",
"noise_rate",
",",
"learning_rate",
",",
"var_list",
")",
":",
"if",
"not",
"noise_rate",
":",
"return",
"[",
"tf",
".",
"no_op",
"(",
")",
"]",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Applying weight noise scaled by learning rat... | Apply weight noise to vars in var_list. | [
"Apply",
"weight",
"noise",
"to",
"vars",
"in",
"var_list",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L259-L278 |
22,735 | tensorflow/tensor2tensor | tensor2tensor/utils/optimize.py | weight_decay | def weight_decay(decay_rate, var_list, skip_biases=True):
"""Apply weight decay to vars in var_list."""
if not decay_rate:
return 0.
tf.logging.info("Applying weight decay, decay_rate: %0.5f", decay_rate)
weight_decays = []
for v in var_list:
# Weight decay.
# This is a heuristic way to detect b... | python | def weight_decay(decay_rate, var_list, skip_biases=True):
"""Apply weight decay to vars in var_list."""
if not decay_rate:
return 0.
tf.logging.info("Applying weight decay, decay_rate: %0.5f", decay_rate)
weight_decays = []
for v in var_list:
# Weight decay.
# This is a heuristic way to detect b... | [
"def",
"weight_decay",
"(",
"decay_rate",
",",
"var_list",
",",
"skip_biases",
"=",
"True",
")",
":",
"if",
"not",
"decay_rate",
":",
"return",
"0.",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Applying weight decay, decay_rate: %0.5f\"",
",",
"decay_rate",
")",
... | Apply weight decay to vars in var_list. | [
"Apply",
"weight",
"decay",
"to",
"vars",
"in",
"var_list",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L281-L298 |
22,736 | tensorflow/tensor2tensor | tensor2tensor/utils/optimize.py | summarize_variables | def summarize_variables(var_list=None, tag=None):
"""Summarize the variables.
Args:
var_list: a list of variables; defaults to trainable_variables.
tag: name scope of the summary; defaults to training_variables/.
"""
if var_list is None:
var_list = tf.trainable_variables()
if tag is None:
tag... | python | def summarize_variables(var_list=None, tag=None):
"""Summarize the variables.
Args:
var_list: a list of variables; defaults to trainable_variables.
tag: name scope of the summary; defaults to training_variables/.
"""
if var_list is None:
var_list = tf.trainable_variables()
if tag is None:
tag... | [
"def",
"summarize_variables",
"(",
"var_list",
"=",
"None",
",",
"tag",
"=",
"None",
")",
":",
"if",
"var_list",
"is",
"None",
":",
"var_list",
"=",
"tf",
".",
"trainable_variables",
"(",
")",
"if",
"tag",
"is",
"None",
":",
"tag",
"=",
"\"training_varia... | Summarize the variables.
Args:
var_list: a list of variables; defaults to trainable_variables.
tag: name scope of the summary; defaults to training_variables/. | [
"Summarize",
"the",
"variables",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L330-L345 |
22,737 | tensorflow/tensor2tensor | tensor2tensor/utils/optimize.py | get_variable_initializer | def get_variable_initializer(hparams):
"""Get variable initializer from hparams."""
if not hparams.initializer:
return None
mlperf_log.transformer_print(key=mlperf_log.MODEL_HP_INITIALIZER_GAIN,
value=hparams.initializer_gain,
hparams=hparams)
... | python | def get_variable_initializer(hparams):
"""Get variable initializer from hparams."""
if not hparams.initializer:
return None
mlperf_log.transformer_print(key=mlperf_log.MODEL_HP_INITIALIZER_GAIN,
value=hparams.initializer_gain,
hparams=hparams)
... | [
"def",
"get_variable_initializer",
"(",
"hparams",
")",
":",
"if",
"not",
"hparams",
".",
"initializer",
":",
"return",
"None",
"mlperf_log",
".",
"transformer_print",
"(",
"key",
"=",
"mlperf_log",
".",
"MODEL_HP_INITIALIZER_GAIN",
",",
"value",
"=",
"hparams",
... | Get variable initializer from hparams. | [
"Get",
"variable",
"initializer",
"from",
"hparams",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L348-L373 |
22,738 | tensorflow/tensor2tensor | tensor2tensor/layers/vqa_layers.py | summarize_tensors | def summarize_tensors(tensor_dict, tag=None):
"""Summarize the tensors.
Args:
tensor_dict: a dictionary of tensors.
tag: name scope of the summary; defaults to tensors/.
"""
if tag is None:
tag = "tensors/"
for t_name in list(tensor_dict):
t = tensor_dict[t_name]
tf.summary.histogram(tag... | python | def summarize_tensors(tensor_dict, tag=None):
"""Summarize the tensors.
Args:
tensor_dict: a dictionary of tensors.
tag: name scope of the summary; defaults to tensors/.
"""
if tag is None:
tag = "tensors/"
for t_name in list(tensor_dict):
t = tensor_dict[t_name]
tf.summary.histogram(tag... | [
"def",
"summarize_tensors",
"(",
"tensor_dict",
",",
"tag",
"=",
"None",
")",
":",
"if",
"tag",
"is",
"None",
":",
"tag",
"=",
"\"tensors/\"",
"for",
"t_name",
"in",
"list",
"(",
"tensor_dict",
")",
":",
"t",
"=",
"tensor_dict",
"[",
"t_name",
"]",
"tf... | Summarize the tensors.
Args:
tensor_dict: a dictionary of tensors.
tag: name scope of the summary; defaults to tensors/. | [
"Summarize",
"the",
"tensors",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/vqa_layers.py#L33-L45 |
22,739 | tensorflow/tensor2tensor | tensor2tensor/layers/vqa_layers.py | image_embedding | def image_embedding(images,
model_fn=resnet_v1_152,
trainable=True,
is_training=True,
weight_decay=0.0001,
batch_norm_decay=0.997,
batch_norm_epsilon=1e-5,
batch_norm_scale=True,
... | python | def image_embedding(images,
model_fn=resnet_v1_152,
trainable=True,
is_training=True,
weight_decay=0.0001,
batch_norm_decay=0.997,
batch_norm_epsilon=1e-5,
batch_norm_scale=True,
... | [
"def",
"image_embedding",
"(",
"images",
",",
"model_fn",
"=",
"resnet_v1_152",
",",
"trainable",
"=",
"True",
",",
"is_training",
"=",
"True",
",",
"weight_decay",
"=",
"0.0001",
",",
"batch_norm_decay",
"=",
"0.997",
",",
"batch_norm_epsilon",
"=",
"1e-5",
"... | Extract image features from pretrained resnet model. | [
"Extract",
"image",
"features",
"from",
"pretrained",
"resnet",
"model",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/vqa_layers.py#L48-L99 |
22,740 | tensorflow/tensor2tensor | tensor2tensor/data_generators/audio.py | timit_generator | def timit_generator(data_dir,
tmp_dir,
training,
how_many,
start_from=0,
eos_list=None,
vocab_filename=None,
vocab_size=0):
"""Data generator for TIMIT transcription problem.
... | python | def timit_generator(data_dir,
tmp_dir,
training,
how_many,
start_from=0,
eos_list=None,
vocab_filename=None,
vocab_size=0):
"""Data generator for TIMIT transcription problem.
... | [
"def",
"timit_generator",
"(",
"data_dir",
",",
"tmp_dir",
",",
"training",
",",
"how_many",
",",
"start_from",
"=",
"0",
",",
"eos_list",
"=",
"None",
",",
"vocab_filename",
"=",
"None",
",",
"vocab_size",
"=",
"0",
")",
":",
"del",
"data_dir",
"eos_list"... | Data generator for TIMIT transcription problem.
Args:
data_dir: path to the data directory.
tmp_dir: path to temporary storage directory.
training: a Boolean; if true, we use the train set, otherwise the test set.
how_many: how many inputs and labels to generate.
start_from: from which input to s... | [
"Data",
"generator",
"for",
"TIMIT",
"transcription",
"problem",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/audio.py#L98-L162 |
22,741 | tensorflow/tensor2tensor | tensor2tensor/data_generators/wikitext103.py | _build_vocab | def _build_vocab(filename, vocab_dir, vocab_name):
"""Reads a file to build a vocabulary.
Args:
filename: file to read list of words from.
vocab_dir: directory where to save the vocabulary.
vocab_name: vocab file name.
Returns:
text encoder.
"""
vocab_path = os.path.join(vocab_dir, vocab_nam... | python | def _build_vocab(filename, vocab_dir, vocab_name):
"""Reads a file to build a vocabulary.
Args:
filename: file to read list of words from.
vocab_dir: directory where to save the vocabulary.
vocab_name: vocab file name.
Returns:
text encoder.
"""
vocab_path = os.path.join(vocab_dir, vocab_nam... | [
"def",
"_build_vocab",
"(",
"filename",
",",
"vocab_dir",
",",
"vocab_name",
")",
":",
"vocab_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"vocab_dir",
",",
"vocab_name",
")",
"if",
"not",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"vocab_path",
")",
... | Reads a file to build a vocabulary.
Args:
filename: file to read list of words from.
vocab_dir: directory where to save the vocabulary.
vocab_name: vocab file name.
Returns:
text encoder. | [
"Reads",
"a",
"file",
"to",
"build",
"a",
"vocabulary",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikitext103.py#L37-L59 |
22,742 | tensorflow/tensor2tensor | tensor2tensor/models/research/aligned.py | aligned_8k_grouped | def aligned_8k_grouped():
"""version for languagemodel_wiki_scramble8k50.
languagemodel_wiki_scramble1k50, 1gpu, 7k steps: log(ppl)_eval = 2.92
3.3 steps/sec on P100
8gpu (8x batch), 7k steps: log(ppl)_eval = 2.15
Returns:
a hparams object
"""
hparams = aligned_grouped()
hparams.batch_size = 8192
... | python | def aligned_8k_grouped():
"""version for languagemodel_wiki_scramble8k50.
languagemodel_wiki_scramble1k50, 1gpu, 7k steps: log(ppl)_eval = 2.92
3.3 steps/sec on P100
8gpu (8x batch), 7k steps: log(ppl)_eval = 2.15
Returns:
a hparams object
"""
hparams = aligned_grouped()
hparams.batch_size = 8192
... | [
"def",
"aligned_8k_grouped",
"(",
")",
":",
"hparams",
"=",
"aligned_grouped",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"8192",
"# hparams.attention_image_summary = False",
"hparams",
".",
"num_groups",
"=",
"16",
"hparams",
".",
"multiplicative_overhead",
"=",
... | version for languagemodel_wiki_scramble8k50.
languagemodel_wiki_scramble1k50, 1gpu, 7k steps: log(ppl)_eval = 2.92
3.3 steps/sec on P100
8gpu (8x batch), 7k steps: log(ppl)_eval = 2.15
Returns:
a hparams object | [
"version",
"for",
"languagemodel_wiki_scramble8k50",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/aligned.py#L512-L527 |
22,743 | tensorflow/tensor2tensor | tensor2tensor/utils/beam_search.py | _expand_to_beam_size | def _expand_to_beam_size(tensor, beam_size):
"""Tiles a given tensor by beam_size.
Args:
tensor: tensor to tile [batch_size, ...]
beam_size: How much to tile the tensor by.
Returns:
Tiled tensor [batch_size, beam_size, ...]
"""
tensor = tf.expand_dims(tensor, axis=1)
tile_dims = [1] * tensor.s... | python | def _expand_to_beam_size(tensor, beam_size):
"""Tiles a given tensor by beam_size.
Args:
tensor: tensor to tile [batch_size, ...]
beam_size: How much to tile the tensor by.
Returns:
Tiled tensor [batch_size, beam_size, ...]
"""
tensor = tf.expand_dims(tensor, axis=1)
tile_dims = [1] * tensor.s... | [
"def",
"_expand_to_beam_size",
"(",
"tensor",
",",
"beam_size",
")",
":",
"tensor",
"=",
"tf",
".",
"expand_dims",
"(",
"tensor",
",",
"axis",
"=",
"1",
")",
"tile_dims",
"=",
"[",
"1",
"]",
"*",
"tensor",
".",
"shape",
".",
"ndims",
"tile_dims",
"[",
... | Tiles a given tensor by beam_size.
Args:
tensor: tensor to tile [batch_size, ...]
beam_size: How much to tile the tensor by.
Returns:
Tiled tensor [batch_size, beam_size, ...] | [
"Tiles",
"a",
"given",
"tensor",
"by",
"beam_size",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L68-L82 |
22,744 | tensorflow/tensor2tensor | tensor2tensor/utils/beam_search.py | get_state_shape_invariants | def get_state_shape_invariants(tensor):
"""Returns the shape of the tensor but sets middle dims to None."""
shape = tensor.shape.as_list()
for i in range(1, len(shape) - 1):
shape[i] = None
return tf.TensorShape(shape) | python | def get_state_shape_invariants(tensor):
"""Returns the shape of the tensor but sets middle dims to None."""
shape = tensor.shape.as_list()
for i in range(1, len(shape) - 1):
shape[i] = None
return tf.TensorShape(shape) | [
"def",
"get_state_shape_invariants",
"(",
"tensor",
")",
":",
"shape",
"=",
"tensor",
".",
"shape",
".",
"as_list",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"shape",
")",
"-",
"1",
")",
":",
"shape",
"[",
"i",
"]",
"=",
"No... | Returns the shape of the tensor but sets middle dims to None. | [
"Returns",
"the",
"shape",
"of",
"the",
"tensor",
"but",
"sets",
"middle",
"dims",
"to",
"None",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L85-L90 |
22,745 | tensorflow/tensor2tensor | tensor2tensor/utils/beam_search.py | compute_batch_indices | def compute_batch_indices(batch_size, beam_size):
"""Computes the i'th coordinate that contains the batch index for gathers.
Batch pos is a tensor like [[0,0,0,0,],[1,1,1,1],..]. It says which
batch the beam item is in. This will create the i of the i,j coordinate
needed for the gather.
Args:
batch_size... | python | def compute_batch_indices(batch_size, beam_size):
"""Computes the i'th coordinate that contains the batch index for gathers.
Batch pos is a tensor like [[0,0,0,0,],[1,1,1,1],..]. It says which
batch the beam item is in. This will create the i of the i,j coordinate
needed for the gather.
Args:
batch_size... | [
"def",
"compute_batch_indices",
"(",
"batch_size",
",",
"beam_size",
")",
":",
"batch_pos",
"=",
"tf",
".",
"range",
"(",
"batch_size",
"*",
"beam_size",
")",
"//",
"beam_size",
"batch_pos",
"=",
"tf",
".",
"reshape",
"(",
"batch_pos",
",",
"[",
"batch_size"... | Computes the i'th coordinate that contains the batch index for gathers.
Batch pos is a tensor like [[0,0,0,0,],[1,1,1,1],..]. It says which
batch the beam item is in. This will create the i of the i,j coordinate
needed for the gather.
Args:
batch_size: Batch size
beam_size: Size of the beam.
Returns... | [
"Computes",
"the",
"i",
"th",
"coordinate",
"that",
"contains",
"the",
"batch",
"index",
"for",
"gathers",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L93-L108 |
22,746 | tensorflow/tensor2tensor | tensor2tensor/utils/beam_search.py | fast_tpu_gather | def fast_tpu_gather(params, indices, name=None):
"""Fast gather implementation for models running on TPU.
This function use one_hot and batch matmul to do gather, which is faster
than gather_nd on TPU. For params that have dtype of int32 (sequences to
gather from), batch_gather is used to keep accuracy.
Arg... | python | def fast_tpu_gather(params, indices, name=None):
"""Fast gather implementation for models running on TPU.
This function use one_hot and batch matmul to do gather, which is faster
than gather_nd on TPU. For params that have dtype of int32 (sequences to
gather from), batch_gather is used to keep accuracy.
Arg... | [
"def",
"fast_tpu_gather",
"(",
"params",
",",
"indices",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
")",
":",
"dtype",
"=",
"params",
".",
"dtype",
"def",
"_gather",
"(",
"params",
",",
"indices",
")",
":",
"\"\... | Fast gather implementation for models running on TPU.
This function use one_hot and batch matmul to do gather, which is faster
than gather_nd on TPU. For params that have dtype of int32 (sequences to
gather from), batch_gather is used to keep accuracy.
Args:
params: A tensor from which to gather values.
... | [
"Fast",
"gather",
"implementation",
"for",
"models",
"running",
"on",
"TPU",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L111-L165 |
22,747 | tensorflow/tensor2tensor | tensor2tensor/utils/beam_search.py | _create_make_unique | def _create_make_unique(inputs):
"""Replaces the lower bits of each element with iota.
The iota is used to derive the index, and also serves the purpose to
make each element unique to break ties.
Args:
inputs: A tensor with rank of 2 and dtype of tf.float32.
[batch_size, original_size].
Returns:
... | python | def _create_make_unique(inputs):
"""Replaces the lower bits of each element with iota.
The iota is used to derive the index, and also serves the purpose to
make each element unique to break ties.
Args:
inputs: A tensor with rank of 2 and dtype of tf.float32.
[batch_size, original_size].
Returns:
... | [
"def",
"_create_make_unique",
"(",
"inputs",
")",
":",
"if",
"inputs",
".",
"shape",
".",
"ndims",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"Input of top_k_with_unique must be rank-2 \"",
"\"but got: %s\"",
"%",
"inputs",
".",
"shape",
")",
"height",
"=",
"... | Replaces the lower bits of each element with iota.
The iota is used to derive the index, and also serves the purpose to
make each element unique to break ties.
Args:
inputs: A tensor with rank of 2 and dtype of tf.float32.
[batch_size, original_size].
Returns:
A tensor after element wise transf... | [
"Replaces",
"the",
"lower",
"bits",
"of",
"each",
"element",
"with",
"iota",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L168-L229 |
22,748 | tensorflow/tensor2tensor | tensor2tensor/utils/beam_search.py | _create_topk_unique | def _create_topk_unique(inputs, k):
"""Creates the top k values in sorted order with indices.
Args:
inputs: A tensor with rank of 2. [batch_size, original_size].
k: An integer, number of top elements to select.
Returns:
topk_r2: A tensor, the k largest elements. [batch_size, k].
topk_indices_r2:... | python | def _create_topk_unique(inputs, k):
"""Creates the top k values in sorted order with indices.
Args:
inputs: A tensor with rank of 2. [batch_size, original_size].
k: An integer, number of top elements to select.
Returns:
topk_r2: A tensor, the k largest elements. [batch_size, k].
topk_indices_r2:... | [
"def",
"_create_topk_unique",
"(",
"inputs",
",",
"k",
")",
":",
"height",
"=",
"inputs",
".",
"shape",
"[",
"0",
"]",
"width",
"=",
"inputs",
".",
"shape",
"[",
"1",
"]",
"neg_inf_r0",
"=",
"tf",
".",
"constant",
"(",
"-",
"np",
".",
"inf",
",",
... | Creates the top k values in sorted order with indices.
Args:
inputs: A tensor with rank of 2. [batch_size, original_size].
k: An integer, number of top elements to select.
Returns:
topk_r2: A tensor, the k largest elements. [batch_size, k].
topk_indices_r2: A tensor, indices of the top k values. [... | [
"Creates",
"the",
"top",
"k",
"values",
"in",
"sorted",
"order",
"with",
"indices",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L232-L270 |
22,749 | tensorflow/tensor2tensor | tensor2tensor/utils/beam_search.py | top_k_with_unique | def top_k_with_unique(inputs, k):
"""Finds the values and indices of the k largests entries.
Instead of doing sort like tf.nn.top_k, this function finds the max value
k times. The running time is proportional to k, which is be faster when k
is small. The current implementation supports only inputs of rank 2.
... | python | def top_k_with_unique(inputs, k):
"""Finds the values and indices of the k largests entries.
Instead of doing sort like tf.nn.top_k, this function finds the max value
k times. The running time is proportional to k, which is be faster when k
is small. The current implementation supports only inputs of rank 2.
... | [
"def",
"top_k_with_unique",
"(",
"inputs",
",",
"k",
")",
":",
"unique_inputs",
"=",
"_create_make_unique",
"(",
"tf",
".",
"cast",
"(",
"inputs",
",",
"tf",
".",
"float32",
")",
")",
"top_values",
",",
"indices",
"=",
"_create_topk_unique",
"(",
"unique_inp... | Finds the values and indices of the k largests entries.
Instead of doing sort like tf.nn.top_k, this function finds the max value
k times. The running time is proportional to k, which is be faster when k
is small. The current implementation supports only inputs of rank 2.
In addition, iota is used to replace t... | [
"Finds",
"the",
"values",
"and",
"indices",
"of",
"the",
"k",
"largests",
"entries",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/beam_search.py#L273-L295 |
22,750 | tensorflow/tensor2tensor | tensor2tensor/data_generators/video_utils.py | video_augmentation | def video_augmentation(features, hue=False, saturate=False, contrast=False):
"""Augments video with optional hue, saturation and constrast.
Args:
features: dict, with keys "inputs", "targets".
features["inputs"], 4-D Tensor, shape=(THWC)
features["targets"], 4-D Tensor, shape=(THWC)... | python | def video_augmentation(features, hue=False, saturate=False, contrast=False):
"""Augments video with optional hue, saturation and constrast.
Args:
features: dict, with keys "inputs", "targets".
features["inputs"], 4-D Tensor, shape=(THWC)
features["targets"], 4-D Tensor, shape=(THWC)... | [
"def",
"video_augmentation",
"(",
"features",
",",
"hue",
"=",
"False",
",",
"saturate",
"=",
"False",
",",
"contrast",
"=",
"False",
")",
":",
"inputs",
",",
"targets",
"=",
"features",
"[",
"\"inputs\"",
"]",
",",
"features",
"[",
"\"targets\"",
"]",
"... | Augments video with optional hue, saturation and constrast.
Args:
features: dict, with keys "inputs", "targets".
features["inputs"], 4-D Tensor, shape=(THWC)
features["targets"], 4-D Tensor, shape=(THWC)
hue: bool, apply hue_transform.
saturate: bool, apply saturation transfor... | [
"Augments",
"video",
"with",
"optional",
"hue",
"saturation",
"and",
"constrast",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L52-L78 |
22,751 | tensorflow/tensor2tensor | tensor2tensor/data_generators/video_utils.py | create_border | def create_border(video, color="blue", border_percent=2):
"""Creates a border around each frame to differentiate input and target.
Args:
video: 5-D NumPy array.
color: string, "blue", "red" or "green".
border_percent: Percentarge of the frame covered by the border.
Returns:
video: 5-D NumPy array... | python | def create_border(video, color="blue", border_percent=2):
"""Creates a border around each frame to differentiate input and target.
Args:
video: 5-D NumPy array.
color: string, "blue", "red" or "green".
border_percent: Percentarge of the frame covered by the border.
Returns:
video: 5-D NumPy array... | [
"def",
"create_border",
"(",
"video",
",",
"color",
"=",
"\"blue\"",
",",
"border_percent",
"=",
"2",
")",
":",
"# Do not create border if the video is not in RGB format",
"if",
"video",
".",
"shape",
"[",
"-",
"1",
"]",
"!=",
"3",
":",
"return",
"video",
"col... | Creates a border around each frame to differentiate input and target.
Args:
video: 5-D NumPy array.
color: string, "blue", "red" or "green".
border_percent: Percentarge of the frame covered by the border.
Returns:
video: 5-D NumPy array. | [
"Creates",
"a",
"border",
"around",
"each",
"frame",
"to",
"differentiate",
"input",
"and",
"target",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L81-L103 |
22,752 | tensorflow/tensor2tensor | tensor2tensor/data_generators/video_utils.py | convert_videos_to_summaries | def convert_videos_to_summaries(input_videos, output_videos, target_videos,
tag, decode_hparams,
display_ground_truth=False):
"""Converts input, output and target videos into video summaries.
Args:
input_videos: 5-D NumPy array, (NTHWC) conditioni... | python | def convert_videos_to_summaries(input_videos, output_videos, target_videos,
tag, decode_hparams,
display_ground_truth=False):
"""Converts input, output and target videos into video summaries.
Args:
input_videos: 5-D NumPy array, (NTHWC) conditioni... | [
"def",
"convert_videos_to_summaries",
"(",
"input_videos",
",",
"output_videos",
",",
"target_videos",
",",
"tag",
",",
"decode_hparams",
",",
"display_ground_truth",
"=",
"False",
")",
":",
"fps",
"=",
"decode_hparams",
".",
"frames_per_second",
"border_percent",
"="... | Converts input, output and target videos into video summaries.
Args:
input_videos: 5-D NumPy array, (NTHWC) conditioning frames.
output_videos: 5-D NumPy array, (NTHWC) model predictions.
target_videos: 5-D NumPy array, (NTHWC) target frames.
tag: tf summary tag.
decode_hparams: HParams.
disp... | [
"Converts",
"input",
"output",
"and",
"target",
"videos",
"into",
"video",
"summaries",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L106-L162 |
22,753 | tensorflow/tensor2tensor | tensor2tensor/data_generators/video_utils.py | display_video_hooks | def display_video_hooks(hook_args):
"""Hooks to display videos at decode time."""
predictions = hook_args.predictions
max_outputs = hook_args.decode_hparams.max_display_outputs
max_decodes = hook_args.decode_hparams.max_display_decodes
with tf.Graph().as_default():
_, best_decodes = video_metrics.compute... | python | def display_video_hooks(hook_args):
"""Hooks to display videos at decode time."""
predictions = hook_args.predictions
max_outputs = hook_args.decode_hparams.max_display_outputs
max_decodes = hook_args.decode_hparams.max_display_decodes
with tf.Graph().as_default():
_, best_decodes = video_metrics.compute... | [
"def",
"display_video_hooks",
"(",
"hook_args",
")",
":",
"predictions",
"=",
"hook_args",
".",
"predictions",
"max_outputs",
"=",
"hook_args",
".",
"decode_hparams",
".",
"max_display_outputs",
"max_decodes",
"=",
"hook_args",
".",
"decode_hparams",
".",
"max_display... | Hooks to display videos at decode time. | [
"Hooks",
"to",
"display",
"videos",
"at",
"decode",
"time",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L165-L206 |
22,754 | tensorflow/tensor2tensor | tensor2tensor/data_generators/video_utils.py | summarize_video_metrics | def summarize_video_metrics(hook_args):
"""Computes video metrics summaries using the decoder output."""
problem_name = hook_args.problem.name
current_problem = hook_args.problem
hparams = hook_args.hparams
output_dirs = hook_args.output_dirs
predictions = hook_args.predictions
frame_shape = [
curre... | python | def summarize_video_metrics(hook_args):
"""Computes video metrics summaries using the decoder output."""
problem_name = hook_args.problem.name
current_problem = hook_args.problem
hparams = hook_args.hparams
output_dirs = hook_args.output_dirs
predictions = hook_args.predictions
frame_shape = [
curre... | [
"def",
"summarize_video_metrics",
"(",
"hook_args",
")",
":",
"problem_name",
"=",
"hook_args",
".",
"problem",
".",
"name",
"current_problem",
"=",
"hook_args",
".",
"problem",
"hparams",
"=",
"hook_args",
".",
"hparams",
"output_dirs",
"=",
"hook_args",
".",
"... | Computes video metrics summaries using the decoder output. | [
"Computes",
"video",
"metrics",
"summaries",
"using",
"the",
"decoder",
"output",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L209-L235 |
22,755 | tensorflow/tensor2tensor | tensor2tensor/data_generators/video_utils.py | debug_video_writer_factory | def debug_video_writer_factory(output_dir):
"""Creates a VideoWriter for debug videos."""
if FLAGS.disable_ffmpeg:
return common_video.IndividualFrameWriter(output_dir)
else:
output_path = os.path.join(output_dir, "video.avi")
return common_video.WholeVideoWriter(
fps=10, output_path=output_pa... | python | def debug_video_writer_factory(output_dir):
"""Creates a VideoWriter for debug videos."""
if FLAGS.disable_ffmpeg:
return common_video.IndividualFrameWriter(output_dir)
else:
output_path = os.path.join(output_dir, "video.avi")
return common_video.WholeVideoWriter(
fps=10, output_path=output_pa... | [
"def",
"debug_video_writer_factory",
"(",
"output_dir",
")",
":",
"if",
"FLAGS",
".",
"disable_ffmpeg",
":",
"return",
"common_video",
".",
"IndividualFrameWriter",
"(",
"output_dir",
")",
"else",
":",
"output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"... | Creates a VideoWriter for debug videos. | [
"Creates",
"a",
"VideoWriter",
"for",
"debug",
"videos",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L238-L246 |
22,756 | tensorflow/tensor2tensor | tensor2tensor/data_generators/video_utils.py | VideoProblem.generate_encoded_samples | def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split):
"""Generate samples of the encoded frames with possible extra data.
By default this function just encodes the numpy array returned as "frame"
from `self.generate_samples` into a PNG image. Override this function to
get other encoding... | python | def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split):
"""Generate samples of the encoded frames with possible extra data.
By default this function just encodes the numpy array returned as "frame"
from `self.generate_samples` into a PNG image. Override this function to
get other encoding... | [
"def",
"generate_encoded_samples",
"(",
"self",
",",
"data_dir",
",",
"tmp_dir",
",",
"dataset_split",
")",
":",
"writer",
"=",
"None",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
":",
"image_t",
"=",
"tf",
".",
"placeholder",
"(",... | Generate samples of the encoded frames with possible extra data.
By default this function just encodes the numpy array returned as "frame"
from `self.generate_samples` into a PNG image. Override this function to
get other encodings on disk.
Args:
data_dir: final data directory. Typically only us... | [
"Generate",
"samples",
"of",
"the",
"encoded",
"frames",
"with",
"possible",
"extra",
"data",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L573-L630 |
22,757 | tensorflow/tensor2tensor | tensor2tensor/data_generators/video_utils.py | VideoProblem.generate_data | def generate_data(self, data_dir, tmp_dir, task_id=-1):
"""The function generating the data."""
filepath_fns = {
problem.DatasetSplit.TRAIN: self.training_filepaths,
problem.DatasetSplit.EVAL: self.dev_filepaths,
problem.DatasetSplit.TEST: self.test_filepaths,
}
# We set shuffle... | python | def generate_data(self, data_dir, tmp_dir, task_id=-1):
"""The function generating the data."""
filepath_fns = {
problem.DatasetSplit.TRAIN: self.training_filepaths,
problem.DatasetSplit.EVAL: self.dev_filepaths,
problem.DatasetSplit.TEST: self.test_filepaths,
}
# We set shuffle... | [
"def",
"generate_data",
"(",
"self",
",",
"data_dir",
",",
"tmp_dir",
",",
"task_id",
"=",
"-",
"1",
")",
":",
"filepath_fns",
"=",
"{",
"problem",
".",
"DatasetSplit",
".",
"TRAIN",
":",
"self",
".",
"training_filepaths",
",",
"problem",
".",
"DatasetSpli... | The function generating the data. | [
"The",
"function",
"generating",
"the",
"data",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L632-L659 |
22,758 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | _add_variable_proxy_methods | def _add_variable_proxy_methods(var, proxy_tensor):
"""Proxy methods of underlying variable.
This enables our custom getters to still work with, e.g., batch norm.
Args:
var: Variable to proxy
proxy_tensor: Tensor that is identity of var
"""
proxy_tensor.read_value = lambda: tf.identity(proxy_tensor)... | python | def _add_variable_proxy_methods(var, proxy_tensor):
"""Proxy methods of underlying variable.
This enables our custom getters to still work with, e.g., batch norm.
Args:
var: Variable to proxy
proxy_tensor: Tensor that is identity of var
"""
proxy_tensor.read_value = lambda: tf.identity(proxy_tensor)... | [
"def",
"_add_variable_proxy_methods",
"(",
"var",
",",
"proxy_tensor",
")",
":",
"proxy_tensor",
".",
"read_value",
"=",
"lambda",
":",
"tf",
".",
"identity",
"(",
"proxy_tensor",
")",
"proxy_tensor",
".",
"assign_sub",
"=",
"var",
".",
"assign_sub",
"proxy_tens... | Proxy methods of underlying variable.
This enables our custom getters to still work with, e.g., batch norm.
Args:
var: Variable to proxy
proxy_tensor: Tensor that is identity of var | [
"Proxy",
"methods",
"of",
"underlying",
"variable",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L75-L87 |
22,759 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | _rowwise_unsorted_segment_sum | def _rowwise_unsorted_segment_sum(values, indices, n):
"""UnsortedSegmentSum on each row.
Args:
values: a `Tensor` with shape `[batch_size, k]`.
indices: an integer `Tensor` with shape `[batch_size, k]`.
n: an integer.
Returns:
A `Tensor` with the same type as `values` and shape `[batch_size, n]`... | python | def _rowwise_unsorted_segment_sum(values, indices, n):
"""UnsortedSegmentSum on each row.
Args:
values: a `Tensor` with shape `[batch_size, k]`.
indices: an integer `Tensor` with shape `[batch_size, k]`.
n: an integer.
Returns:
A `Tensor` with the same type as `values` and shape `[batch_size, n]`... | [
"def",
"_rowwise_unsorted_segment_sum",
"(",
"values",
",",
"indices",
",",
"n",
")",
":",
"batch",
",",
"k",
"=",
"tf",
".",
"unstack",
"(",
"tf",
".",
"shape",
"(",
"indices",
")",
",",
"num",
"=",
"2",
")",
"indices_flat",
"=",
"tf",
".",
"reshape... | UnsortedSegmentSum on each row.
Args:
values: a `Tensor` with shape `[batch_size, k]`.
indices: an integer `Tensor` with shape `[batch_size, k]`.
n: an integer.
Returns:
A `Tensor` with the same type as `values` and shape `[batch_size, n]`. | [
"UnsortedSegmentSum",
"on",
"each",
"row",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L267-L281 |
22,760 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | _prob_in_top_k | def _prob_in_top_k(
clean_values, noisy_values, noise_stddev, noisy_top_values, k):
"""Helper function to NoisyTopKGating.
Computes the probability that value is in top k, given different random noise.
This gives us a way of backpropagating from a loss that balances the number
of times each expert is in t... | python | def _prob_in_top_k(
clean_values, noisy_values, noise_stddev, noisy_top_values, k):
"""Helper function to NoisyTopKGating.
Computes the probability that value is in top k, given different random noise.
This gives us a way of backpropagating from a loss that balances the number
of times each expert is in t... | [
"def",
"_prob_in_top_k",
"(",
"clean_values",
",",
"noisy_values",
",",
"noise_stddev",
",",
"noisy_top_values",
",",
"k",
")",
":",
"batch",
"=",
"tf",
".",
"shape",
"(",
"clean_values",
")",
"[",
"0",
"]",
"m",
"=",
"tf",
".",
"shape",
"(",
"noisy_top_... | Helper function to NoisyTopKGating.
Computes the probability that value is in top k, given different random noise.
This gives us a way of backpropagating from a loss that balances the number
of times each expert is in the top k experts per example.
In the case of no noise, pass in None for noise_stddev, and ... | [
"Helper",
"function",
"to",
"NoisyTopKGating",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L303-L348 |
22,761 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | cv_squared | def cv_squared(x):
"""The squared coefficient of variation of a sample.
Useful as a loss to encourage a positive distribution to be more uniform.
Epsilons added for numerical stability.
Returns 0 for an empty Tensor.
Args:
x: a `Tensor`.
Returns:
a `Scalar`.
"""
epsilon = 1e-10
float_size =... | python | def cv_squared(x):
"""The squared coefficient of variation of a sample.
Useful as a loss to encourage a positive distribution to be more uniform.
Epsilons added for numerical stability.
Returns 0 for an empty Tensor.
Args:
x: a `Tensor`.
Returns:
a `Scalar`.
"""
epsilon = 1e-10
float_size =... | [
"def",
"cv_squared",
"(",
"x",
")",
":",
"epsilon",
"=",
"1e-10",
"float_size",
"=",
"tf",
".",
"to_float",
"(",
"tf",
".",
"size",
"(",
"x",
")",
")",
"+",
"epsilon",
"mean",
"=",
"tf",
".",
"reduce_sum",
"(",
"x",
")",
"/",
"float_size",
"varianc... | The squared coefficient of variation of a sample.
Useful as a loss to encourage a positive distribution to be more uniform.
Epsilons added for numerical stability.
Returns 0 for an empty Tensor.
Args:
x: a `Tensor`.
Returns:
a `Scalar`. | [
"The",
"squared",
"coefficient",
"of",
"variation",
"of",
"a",
"sample",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L351-L368 |
22,762 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | update_hparams_for_vq_gating | def update_hparams_for_vq_gating(hparams):
"""VQ Gating hparams."""
hparams.add_hparam("z_size", 4)
hparams.add_hparam("noise_dev", 0.5)
# Bottleneck kinds supported: dense, vae, dvq.
hparams.add_hparam("bottleneck_kind", "dvq")
hparams.add_hparam("num_blocks", 1)
hparams.add_hparam("num_residuals", 1)
... | python | def update_hparams_for_vq_gating(hparams):
"""VQ Gating hparams."""
hparams.add_hparam("z_size", 4)
hparams.add_hparam("noise_dev", 0.5)
# Bottleneck kinds supported: dense, vae, dvq.
hparams.add_hparam("bottleneck_kind", "dvq")
hparams.add_hparam("num_blocks", 1)
hparams.add_hparam("num_residuals", 1)
... | [
"def",
"update_hparams_for_vq_gating",
"(",
"hparams",
")",
":",
"hparams",
".",
"add_hparam",
"(",
"\"z_size\"",
",",
"4",
")",
"hparams",
".",
"add_hparam",
"(",
"\"noise_dev\"",
",",
"0.5",
")",
"# Bottleneck kinds supported: dense, vae, dvq.",
"hparams",
".",
"a... | VQ Gating hparams. | [
"VQ",
"Gating",
"hparams",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L384-L402 |
22,763 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | _my_top_k | def _my_top_k(x, k):
"""GPU-compatible version of top-k that works for very small constant k.
Calls argmax repeatedly.
tf.nn.top_k is implemented for GPU, but the gradient, sparse_to_dense,
seems not to be, so if we use tf.nn.top_k, then both the top_k and its
gradient go on cpu. Once this is not an issue,... | python | def _my_top_k(x, k):
"""GPU-compatible version of top-k that works for very small constant k.
Calls argmax repeatedly.
tf.nn.top_k is implemented for GPU, but the gradient, sparse_to_dense,
seems not to be, so if we use tf.nn.top_k, then both the top_k and its
gradient go on cpu. Once this is not an issue,... | [
"def",
"_my_top_k",
"(",
"x",
",",
"k",
")",
":",
"if",
"k",
">",
"10",
":",
"return",
"tf",
".",
"nn",
".",
"top_k",
"(",
"x",
",",
"k",
")",
"values",
"=",
"[",
"]",
"indices",
"=",
"[",
"]",
"depth",
"=",
"tf",
".",
"shape",
"(",
"x",
... | GPU-compatible version of top-k that works for very small constant k.
Calls argmax repeatedly.
tf.nn.top_k is implemented for GPU, but the gradient, sparse_to_dense,
seems not to be, so if we use tf.nn.top_k, then both the top_k and its
gradient go on cpu. Once this is not an issue, this function becomes
o... | [
"GPU",
"-",
"compatible",
"version",
"of",
"top",
"-",
"k",
"that",
"works",
"for",
"very",
"small",
"constant",
"k",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L405-L434 |
22,764 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | vq_gating | def vq_gating(x,
num_experts,
k,
bneck,
hparams=None,
name="vq_gating"):
"""VQ gating.
Args:
x: input Tensor with shape [batch_size, input_size]
num_experts: an integer
k: an integer - number of experts per example
bneck: a bottl... | python | def vq_gating(x,
num_experts,
k,
bneck,
hparams=None,
name="vq_gating"):
"""VQ gating.
Args:
x: input Tensor with shape [batch_size, input_size]
num_experts: an integer
k: an integer - number of experts per example
bneck: a bottl... | [
"def",
"vq_gating",
"(",
"x",
",",
"num_experts",
",",
"k",
",",
"bneck",
",",
"hparams",
"=",
"None",
",",
"name",
"=",
"\"vq_gating\"",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"reuse",
"=",
"tf",
".",
"AUTO_REUSE",
")",
":"... | VQ gating.
Args:
x: input Tensor with shape [batch_size, input_size]
num_experts: an integer
k: an integer - number of experts per example
bneck: a bottleneck object
hparams: optional hparams
name: an optional string
Returns:
gates: a Tensor with shape [batch_size, num_experts]
loa... | [
"VQ",
"gating",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L437-L511 |
22,765 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | noisy_top_k_gating | def noisy_top_k_gating(x,
num_experts,
train,
k=2,
initializer=tf.zeros_initializer(),
noisy_gating=True,
noise_epsilon=1e-2,
name=None):
"""Noisy top-k gati... | python | def noisy_top_k_gating(x,
num_experts,
train,
k=2,
initializer=tf.zeros_initializer(),
noisy_gating=True,
noise_epsilon=1e-2,
name=None):
"""Noisy top-k gati... | [
"def",
"noisy_top_k_gating",
"(",
"x",
",",
"num_experts",
",",
"train",
",",
"k",
"=",
"2",
",",
"initializer",
"=",
"tf",
".",
"zeros_initializer",
"(",
")",
",",
"noisy_gating",
"=",
"True",
",",
"noise_epsilon",
"=",
"1e-2",
",",
"name",
"=",
"None",... | Noisy top-k gating.
See paper: https://arxiv.org/abs/1701.06538.
Args:
x: input Tensor with shape [batch_size, input_size]
num_experts: an integer
train: a boolean - we only add noise at training time.
k: an integer - number of experts per example
initializer: an initializer
noisy_gating: ... | [
"Noisy",
"top",
"-",
"k",
"gating",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L514-L579 |
22,766 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | map_ids | def map_ids(x, indices, map_fn):
"""Apply a function to each coordinate ids of a multidimensional tensor.
This allows to process each sequence of a batch independently. This is
similar to tf.map_fn but with tensor where the batch dim has been flatten.
Warning: The indices ids have to be contiguous and ordered... | python | def map_ids(x, indices, map_fn):
"""Apply a function to each coordinate ids of a multidimensional tensor.
This allows to process each sequence of a batch independently. This is
similar to tf.map_fn but with tensor where the batch dim has been flatten.
Warning: The indices ids have to be contiguous and ordered... | [
"def",
"map_ids",
"(",
"x",
",",
"indices",
",",
"map_fn",
")",
":",
"indices",
"=",
"tf",
".",
"reshape",
"(",
"indices",
",",
"[",
"-",
"1",
"]",
")",
"t_i",
"=",
"tf",
".",
"constant",
"(",
"0",
")",
"# batch_coordinates start at 0",
"t_batch_size",... | Apply a function to each coordinate ids of a multidimensional tensor.
This allows to process each sequence of a batch independently. This is
similar to tf.map_fn but with tensor where the batch dim has been flatten.
Warning: The indices ids have to be contiguous and ordered in memory as the
output vector for ... | [
"Apply",
"a",
"function",
"to",
"each",
"coordinate",
"ids",
"of",
"a",
"multidimensional",
"tensor",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L665-L730 |
22,767 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | ffn_expert_fn | def ffn_expert_fn(input_size,
hidden_sizes,
output_size,
hidden_activation=tf.nn.relu):
"""Returns a function that creates a feed-forward network.
Use this function to create the expert_fn argument to distributed_moe.
Args:
input_size: an integer
hid... | python | def ffn_expert_fn(input_size,
hidden_sizes,
output_size,
hidden_activation=tf.nn.relu):
"""Returns a function that creates a feed-forward network.
Use this function to create the expert_fn argument to distributed_moe.
Args:
input_size: an integer
hid... | [
"def",
"ffn_expert_fn",
"(",
"input_size",
",",
"hidden_sizes",
",",
"output_size",
",",
"hidden_activation",
"=",
"tf",
".",
"nn",
".",
"relu",
")",
":",
"def",
"my_fn",
"(",
"x",
")",
":",
"layer_sizes",
"=",
"[",
"input_size",
"]",
"+",
"hidden_sizes",
... | Returns a function that creates a feed-forward network.
Use this function to create the expert_fn argument to distributed_moe.
Args:
input_size: an integer
hidden_sizes: a list of integers
output_size: an integer
hidden_activation: a unary function.
Returns:
a unary function | [
"Returns",
"a",
"function",
"that",
"creates",
"a",
"feed",
"-",
"forward",
"network",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L956-L983 |
22,768 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | flatten_all_but_last | def flatten_all_but_last(a):
"""Flatten all dimensions of a except the last."""
ret = tf.reshape(a, [-1, tf.shape(a)[-1]])
if not tf.executing_eagerly():
ret.set_shape([None] + a.get_shape().as_list()[-1:])
return ret | python | def flatten_all_but_last(a):
"""Flatten all dimensions of a except the last."""
ret = tf.reshape(a, [-1, tf.shape(a)[-1]])
if not tf.executing_eagerly():
ret.set_shape([None] + a.get_shape().as_list()[-1:])
return ret | [
"def",
"flatten_all_but_last",
"(",
"a",
")",
":",
"ret",
"=",
"tf",
".",
"reshape",
"(",
"a",
",",
"[",
"-",
"1",
",",
"tf",
".",
"shape",
"(",
"a",
")",
"[",
"-",
"1",
"]",
"]",
")",
"if",
"not",
"tf",
".",
"executing_eagerly",
"(",
")",
":... | Flatten all dimensions of a except the last. | [
"Flatten",
"all",
"dimensions",
"of",
"a",
"except",
"the",
"last",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L986-L991 |
22,769 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | local_moe | def local_moe(x,
train,
expert_fn,
num_experts,
k=1,
loss_coef=1e-2,
hparams=None,
pass_x=True,
pass_gates=False,
additional_dispatch_params=None,
name=None):
"""Call a local mix... | python | def local_moe(x,
train,
expert_fn,
num_experts,
k=1,
loss_coef=1e-2,
hparams=None,
pass_x=True,
pass_gates=False,
additional_dispatch_params=None,
name=None):
"""Call a local mix... | [
"def",
"local_moe",
"(",
"x",
",",
"train",
",",
"expert_fn",
",",
"num_experts",
",",
"k",
"=",
"1",
",",
"loss_coef",
"=",
"1e-2",
",",
"hparams",
"=",
"None",
",",
"pass_x",
"=",
"True",
",",
"pass_gates",
"=",
"False",
",",
"additional_dispatch_param... | Call a local mixture of experts.
Args:
x: a tensors with shape [... , input_size]
train: a boolean scalar.
expert_fn: a function.
num_experts: an integer - number of experts
k: an integer - how many experts to use for each batch element
loss_coef: a scalar - multiplier on load-balancing losse... | [
"Call",
"a",
"local",
"mixture",
"of",
"experts",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L994-L1074 |
22,770 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | reduce_by_device | def reduce_by_device(parallelism, data, reduce_fn):
"""Reduces data per device.
This can be useful, for example, if we want to all-reduce n tensors on k<n
devices (like during eval when we have only one device). We call
reduce_by_device() to first sum the tensors per device, then call our usual
all-reduce o... | python | def reduce_by_device(parallelism, data, reduce_fn):
"""Reduces data per device.
This can be useful, for example, if we want to all-reduce n tensors on k<n
devices (like during eval when we have only one device). We call
reduce_by_device() to first sum the tensors per device, then call our usual
all-reduce o... | [
"def",
"reduce_by_device",
"(",
"parallelism",
",",
"data",
",",
"reduce_fn",
")",
":",
"unique_devices",
"=",
"[",
"]",
"device_to_data",
"=",
"{",
"}",
"for",
"dev",
",",
"datum",
"in",
"zip",
"(",
"parallelism",
".",
"devices",
",",
"data",
")",
":",
... | Reduces data per device.
This can be useful, for example, if we want to all-reduce n tensors on k<n
devices (like during eval when we have only one device). We call
reduce_by_device() to first sum the tensors per device, then call our usual
all-reduce operation to create one sum per device, followed by
expa... | [
"Reduces",
"data",
"per",
"device",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L1414-L1443 |
22,771 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | all_reduce_ring | def all_reduce_ring(x, parallelism, maybe_reduce=True, use_bfloat16=True):
"""Compute the sum of all Tensors and put the result everywhere.
Assumes that the devices are connected in a ring.
Args:
x: a list of Tensors with length parallelism.n
parallelism: a expert_utils.Parallelism object.
maybe_red... | python | def all_reduce_ring(x, parallelism, maybe_reduce=True, use_bfloat16=True):
"""Compute the sum of all Tensors and put the result everywhere.
Assumes that the devices are connected in a ring.
Args:
x: a list of Tensors with length parallelism.n
parallelism: a expert_utils.Parallelism object.
maybe_red... | [
"def",
"all_reduce_ring",
"(",
"x",
",",
"parallelism",
",",
"maybe_reduce",
"=",
"True",
",",
"use_bfloat16",
"=",
"True",
")",
":",
"if",
"parallelism",
".",
"n",
"==",
"1",
":",
"return",
"x",
"if",
"maybe_reduce",
":",
"original_parallelism",
"=",
"par... | Compute the sum of all Tensors and put the result everywhere.
Assumes that the devices are connected in a ring.
Args:
x: a list of Tensors with length parallelism.n
parallelism: a expert_utils.Parallelism object.
maybe_reduce: a boolean - first reduce per device.
use_bfloat16: a boolean - saves ba... | [
"Compute",
"the",
"sum",
"of",
"all",
"Tensors",
"and",
"put",
"the",
"result",
"everywhere",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L1463-L1537 |
22,772 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | Parallelism._maybe_repeat | def _maybe_repeat(self, x):
"""Utility function for processing arguments that are singletons or lists.
Args:
x: either a list of self.n elements, or not a list.
Returns:
a list of self.n elements.
"""
if isinstance(x, list):
assert len(x) == self.n
return x
else:
... | python | def _maybe_repeat(self, x):
"""Utility function for processing arguments that are singletons or lists.
Args:
x: either a list of self.n elements, or not a list.
Returns:
a list of self.n elements.
"""
if isinstance(x, list):
assert len(x) == self.n
return x
else:
... | [
"def",
"_maybe_repeat",
"(",
"self",
",",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"list",
")",
":",
"assert",
"len",
"(",
"x",
")",
"==",
"self",
".",
"n",
"return",
"x",
"else",
":",
"return",
"[",
"x",
"]",
"*",
"self",
".",
"n"
] | Utility function for processing arguments that are singletons or lists.
Args:
x: either a list of self.n elements, or not a list.
Returns:
a list of self.n elements. | [
"Utility",
"function",
"for",
"processing",
"arguments",
"that",
"are",
"singletons",
"or",
"lists",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L251-L264 |
22,773 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | PadRemover.remove | def remove(self, x):
"""Remove padding from the given tensor.
Args:
x (tf.Tensor): of shape [dim_origin,...]
Returns:
a tensor of shape [dim_compressed,...] with dim_compressed <= dim_origin
"""
with tf.name_scope("pad_reduce/remove"):
x_shape = x.get_shape().as_list()
x = ... | python | def remove(self, x):
"""Remove padding from the given tensor.
Args:
x (tf.Tensor): of shape [dim_origin,...]
Returns:
a tensor of shape [dim_compressed,...] with dim_compressed <= dim_origin
"""
with tf.name_scope("pad_reduce/remove"):
x_shape = x.get_shape().as_list()
x = ... | [
"def",
"remove",
"(",
"self",
",",
"x",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"pad_reduce/remove\"",
")",
":",
"x_shape",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"x",
"=",
"tf",
".",
"gather_nd",
"(",
"x",
",",
... | Remove padding from the given tensor.
Args:
x (tf.Tensor): of shape [dim_origin,...]
Returns:
a tensor of shape [dim_compressed,...] with dim_compressed <= dim_origin | [
"Remove",
"padding",
"from",
"the",
"given",
"tensor",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L624-L643 |
22,774 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | PadRemover.restore | def restore(self, x):
"""Add padding back to the given tensor.
Args:
x (tf.Tensor): of shape [dim_compressed,...]
Returns:
a tensor of shape [dim_origin,...] with dim_compressed >= dim_origin. The
dim is restored from the original reference tensor
"""
with tf.name_scope("pad_redu... | python | def restore(self, x):
"""Add padding back to the given tensor.
Args:
x (tf.Tensor): of shape [dim_compressed,...]
Returns:
a tensor of shape [dim_origin,...] with dim_compressed >= dim_origin. The
dim is restored from the original reference tensor
"""
with tf.name_scope("pad_redu... | [
"def",
"restore",
"(",
"self",
",",
"x",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"pad_reduce/restore\"",
")",
":",
"x",
"=",
"tf",
".",
"scatter_nd",
"(",
"indices",
"=",
"self",
".",
"nonpad_ids",
",",
"updates",
"=",
"x",
",",
"shape",
"=... | Add padding back to the given tensor.
Args:
x (tf.Tensor): of shape [dim_compressed,...]
Returns:
a tensor of shape [dim_origin,...] with dim_compressed >= dim_origin. The
dim is restored from the original reference tensor | [
"Add",
"padding",
"back",
"to",
"the",
"given",
"tensor",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L645-L661 |
22,775 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | SparseDispatcher.combine | def combine(self, expert_out, multiply_by_gates=True):
"""Sum together the expert output, weighted by the gates.
The slice corresponding to a particular batch element `b` is computed
as the sum over all experts `i` of the expert output, weighted by the
corresponding gate values. If `multiply_by_gates`... | python | def combine(self, expert_out, multiply_by_gates=True):
"""Sum together the expert output, weighted by the gates.
The slice corresponding to a particular batch element `b` is computed
as the sum over all experts `i` of the expert output, weighted by the
corresponding gate values. If `multiply_by_gates`... | [
"def",
"combine",
"(",
"self",
",",
"expert_out",
",",
"multiply_by_gates",
"=",
"True",
")",
":",
"# see comments on convert_gradient_to_tensor",
"stitched",
"=",
"common_layers",
".",
"convert_gradient_to_tensor",
"(",
"tf",
".",
"concat",
"(",
"expert_out",
",",
... | Sum together the expert output, weighted by the gates.
The slice corresponding to a particular batch element `b` is computed
as the sum over all experts `i` of the expert output, weighted by the
corresponding gate values. If `multiply_by_gates` is set to False, the
gate values are ignored.
Args:
... | [
"Sum",
"together",
"the",
"expert",
"output",
"weighted",
"by",
"the",
"gates",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L810-L833 |
22,776 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | SparseDispatcher.expert_to_batch_indices | def expert_to_batch_indices(self):
"""Batch indices corresponding to the examples in the per-expert `Tensor`s.
Returns:
a list of `num_experts` one-dimensional `Tensor`s with type `tf.int64`
and shapes `[expert_batch_size_i]`
"""
return tf.split(
self._batch_index, self._part_si... | python | def expert_to_batch_indices(self):
"""Batch indices corresponding to the examples in the per-expert `Tensor`s.
Returns:
a list of `num_experts` one-dimensional `Tensor`s with type `tf.int64`
and shapes `[expert_batch_size_i]`
"""
return tf.split(
self._batch_index, self._part_si... | [
"def",
"expert_to_batch_indices",
"(",
"self",
")",
":",
"return",
"tf",
".",
"split",
"(",
"self",
".",
"_batch_index",
",",
"self",
".",
"_part_sizes_tensor",
",",
"0",
",",
"num",
"=",
"self",
".",
"_num_experts",
")"
] | Batch indices corresponding to the examples in the per-expert `Tensor`s.
Returns:
a list of `num_experts` one-dimensional `Tensor`s with type `tf.int64`
and shapes `[expert_batch_size_i]` | [
"Batch",
"indices",
"corresponding",
"to",
"the",
"examples",
"in",
"the",
"per",
"-",
"expert",
"Tensor",
"s",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L845-L853 |
22,777 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | DistributedSparseDispatcher.combine | def combine(self, expert_out, multiply_by_gates=True):
"""Sum together the expert output, multiplied by the corresponding gates.
Args:
expert_out: a list of `num_experts` `Tensor`s, each with shape
`[expert_batch_size_i, <extra_output_dims>]`.
multiply_by_gates: a boolean.
Returns:
... | python | def combine(self, expert_out, multiply_by_gates=True):
"""Sum together the expert output, multiplied by the corresponding gates.
Args:
expert_out: a list of `num_experts` `Tensor`s, each with shape
`[expert_batch_size_i, <extra_output_dims>]`.
multiply_by_gates: a boolean.
Returns:
... | [
"def",
"combine",
"(",
"self",
",",
"expert_out",
",",
"multiply_by_gates",
"=",
"True",
")",
":",
"expert_part_sizes",
"=",
"tf",
".",
"unstack",
"(",
"tf",
".",
"stack",
"(",
"[",
"d",
".",
"part_sizes",
"for",
"d",
"in",
"self",
".",
"_dispatchers",
... | Sum together the expert output, multiplied by the corresponding gates.
Args:
expert_out: a list of `num_experts` `Tensor`s, each with shape
`[expert_batch_size_i, <extra_output_dims>]`.
multiply_by_gates: a boolean.
Returns:
a list of num_datashards `Tensor`s with shapes
`[ba... | [
"Sum",
"together",
"the",
"expert",
"output",
"multiplied",
"by",
"the",
"corresponding",
"gates",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L907-L930 |
22,778 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | TruncatingDispatcher.dispatch | def dispatch(self, inp):
"""Send the inputs to the experts.
Args:
inp: a `Tensor` of shape "[batch, length, depth]`
Returns:
a tensor with shape [batch, num_experts, expert_capacity, depth]
"""
inp = tf.reshape(inp, [self._batch * self._length, -1])
# [batch, num_experts, expert_cap... | python | def dispatch(self, inp):
"""Send the inputs to the experts.
Args:
inp: a `Tensor` of shape "[batch, length, depth]`
Returns:
a tensor with shape [batch, num_experts, expert_capacity, depth]
"""
inp = tf.reshape(inp, [self._batch * self._length, -1])
# [batch, num_experts, expert_cap... | [
"def",
"dispatch",
"(",
"self",
",",
"inp",
")",
":",
"inp",
"=",
"tf",
".",
"reshape",
"(",
"inp",
",",
"[",
"self",
".",
"_batch",
"*",
"self",
".",
"_length",
",",
"-",
"1",
"]",
")",
"# [batch, num_experts, expert_capacity, depth]",
"ret",
"=",
"tf... | Send the inputs to the experts.
Args:
inp: a `Tensor` of shape "[batch, length, depth]`
Returns:
a tensor with shape [batch, num_experts, expert_capacity, depth] | [
"Send",
"the",
"inputs",
"to",
"the",
"experts",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L1158-L1169 |
22,779 | tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | TruncatingDispatcher.combine | def combine(self, x):
"""Return the output from the experts.
When one example goes to multiple experts, the outputs are summed.
Args:
x: a Tensor with shape [batch, num_experts, expert_capacity, depth]
Returns:
a `Tensor` with shape `[batch, length, depth]
"""
depth = tf.shape(x)[... | python | def combine(self, x):
"""Return the output from the experts.
When one example goes to multiple experts, the outputs are summed.
Args:
x: a Tensor with shape [batch, num_experts, expert_capacity, depth]
Returns:
a `Tensor` with shape `[batch, length, depth]
"""
depth = tf.shape(x)[... | [
"def",
"combine",
"(",
"self",
",",
"x",
")",
":",
"depth",
"=",
"tf",
".",
"shape",
"(",
"x",
")",
"[",
"-",
"1",
"]",
"x",
"*=",
"tf",
".",
"expand_dims",
"(",
"self",
".",
"_nonpadding",
",",
"-",
"1",
")",
"ret",
"=",
"tf",
".",
"unsorted... | Return the output from the experts.
When one example goes to multiple experts, the outputs are summed.
Args:
x: a Tensor with shape [batch, num_experts, expert_capacity, depth]
Returns:
a `Tensor` with shape `[batch, length, depth] | [
"Return",
"the",
"output",
"from",
"the",
"experts",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L1172-L1188 |
22,780 | tensorflow/tensor2tensor | tensor2tensor/rl/evaluator.py | make_env | def make_env(env_type, real_env, sim_env_kwargs):
"""Factory function for envs."""
return {
"real": lambda: real_env.new_like( # pylint: disable=g-long-lambda
batch_size=sim_env_kwargs["batch_size"],
store_rollouts=False,
),
"simulated": lambda: rl_utils.SimulatedBatchGymEnvWi... | python | def make_env(env_type, real_env, sim_env_kwargs):
"""Factory function for envs."""
return {
"real": lambda: real_env.new_like( # pylint: disable=g-long-lambda
batch_size=sim_env_kwargs["batch_size"],
store_rollouts=False,
),
"simulated": lambda: rl_utils.SimulatedBatchGymEnvWi... | [
"def",
"make_env",
"(",
"env_type",
",",
"real_env",
",",
"sim_env_kwargs",
")",
":",
"return",
"{",
"\"real\"",
":",
"lambda",
":",
"real_env",
".",
"new_like",
"(",
"# pylint: disable=g-long-lambda",
"batch_size",
"=",
"sim_env_kwargs",
"[",
"\"batch_size\"",
"]... | Factory function for envs. | [
"Factory",
"function",
"for",
"envs",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/evaluator.py#L240-L250 |
22,781 | tensorflow/tensor2tensor | tensor2tensor/rl/evaluator.py | make_agent | def make_agent(
agent_type, env, policy_hparams, policy_dir, sampling_temp,
sim_env_kwargs_fn=None, frame_stack_size=None, rollout_agent_type=None,
batch_size=None, inner_batch_size=None, env_type=None, **planner_kwargs
):
"""Factory function for Agents."""
if batch_size is None:
batch_size = env.ba... | python | def make_agent(
agent_type, env, policy_hparams, policy_dir, sampling_temp,
sim_env_kwargs_fn=None, frame_stack_size=None, rollout_agent_type=None,
batch_size=None, inner_batch_size=None, env_type=None, **planner_kwargs
):
"""Factory function for Agents."""
if batch_size is None:
batch_size = env.ba... | [
"def",
"make_agent",
"(",
"agent_type",
",",
"env",
",",
"policy_hparams",
",",
"policy_dir",
",",
"sampling_temp",
",",
"sim_env_kwargs_fn",
"=",
"None",
",",
"frame_stack_size",
"=",
"None",
",",
"rollout_agent_type",
"=",
"None",
",",
"batch_size",
"=",
"None... | Factory function for Agents. | [
"Factory",
"function",
"for",
"Agents",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/evaluator.py#L253-L277 |
22,782 | tensorflow/tensor2tensor | tensor2tensor/rl/evaluator.py | collect_frames_for_random_starts | def collect_frames_for_random_starts(
storage_env, stacked_env, agent, frame_stack_size, random_starts_step_limit,
log_every_steps=None
):
"""Collects frames from real env for random starts of simulated env."""
del frame_stack_size
storage_env.start_new_epoch(0)
tf.logging.info(
"Collecting %d fra... | python | def collect_frames_for_random_starts(
storage_env, stacked_env, agent, frame_stack_size, random_starts_step_limit,
log_every_steps=None
):
"""Collects frames from real env for random starts of simulated env."""
del frame_stack_size
storage_env.start_new_epoch(0)
tf.logging.info(
"Collecting %d fra... | [
"def",
"collect_frames_for_random_starts",
"(",
"storage_env",
",",
"stacked_env",
",",
"agent",
",",
"frame_stack_size",
",",
"random_starts_step_limit",
",",
"log_every_steps",
"=",
"None",
")",
":",
"del",
"frame_stack_size",
"storage_env",
".",
"start_new_epoch",
"(... | Collects frames from real env for random starts of simulated env. | [
"Collects",
"frames",
"from",
"real",
"env",
"for",
"random",
"starts",
"of",
"simulated",
"env",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/evaluator.py#L280-L297 |
22,783 | tensorflow/tensor2tensor | tensor2tensor/rl/evaluator.py | make_agent_from_hparams | def make_agent_from_hparams(
agent_type, base_env, stacked_env, loop_hparams, policy_hparams,
planner_hparams, model_dir, policy_dir, sampling_temp, video_writers=()
):
"""Creates an Agent from hparams."""
def sim_env_kwargs_fn():
return rl.make_simulated_env_kwargs(
base_env, loop_hparams, batc... | python | def make_agent_from_hparams(
agent_type, base_env, stacked_env, loop_hparams, policy_hparams,
planner_hparams, model_dir, policy_dir, sampling_temp, video_writers=()
):
"""Creates an Agent from hparams."""
def sim_env_kwargs_fn():
return rl.make_simulated_env_kwargs(
base_env, loop_hparams, batc... | [
"def",
"make_agent_from_hparams",
"(",
"agent_type",
",",
"base_env",
",",
"stacked_env",
",",
"loop_hparams",
",",
"policy_hparams",
",",
"planner_hparams",
",",
"model_dir",
",",
"policy_dir",
",",
"sampling_temp",
",",
"video_writers",
"=",
"(",
")",
")",
":",
... | Creates an Agent from hparams. | [
"Creates",
"an",
"Agent",
"from",
"hparams",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/evaluator.py#L300-L321 |
22,784 | tensorflow/tensor2tensor | tensor2tensor/rl/evaluator.py | make_eval_fn_with_agent | def make_eval_fn_with_agent(
agent_type, eval_mode, planner_hparams, model_dir, log_every_steps=None,
video_writers=(), random_starts_step_limit=None
):
"""Returns an out-of-graph eval_fn using the Agent API."""
def eval_fn(env, loop_hparams, policy_hparams, policy_dir, sampling_temp):
"""Eval function.... | python | def make_eval_fn_with_agent(
agent_type, eval_mode, planner_hparams, model_dir, log_every_steps=None,
video_writers=(), random_starts_step_limit=None
):
"""Returns an out-of-graph eval_fn using the Agent API."""
def eval_fn(env, loop_hparams, policy_hparams, policy_dir, sampling_temp):
"""Eval function.... | [
"def",
"make_eval_fn_with_agent",
"(",
"agent_type",
",",
"eval_mode",
",",
"planner_hparams",
",",
"model_dir",
",",
"log_every_steps",
"=",
"None",
",",
"video_writers",
"=",
"(",
")",
",",
"random_starts_step_limit",
"=",
"None",
")",
":",
"def",
"eval_fn",
"... | Returns an out-of-graph eval_fn using the Agent API. | [
"Returns",
"an",
"out",
"-",
"of",
"-",
"graph",
"eval_fn",
"using",
"the",
"Agent",
"API",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/evaluator.py#L324-L372 |
22,785 | tensorflow/tensor2tensor | tensor2tensor/rl/evaluator.py | evaluate_world_model | def evaluate_world_model(
agent_type, loop_hparams, planner_hparams, model_dir, policy_dir,
random_starts_step_limit, debug_video_path, log_every_steps
):
"""Evaluates the world model."""
if debug_video_path:
debug_video_path = os.path.join(debug_video_path, "0.avi")
storage_env = rl_utils.setup_env(... | python | def evaluate_world_model(
agent_type, loop_hparams, planner_hparams, model_dir, policy_dir,
random_starts_step_limit, debug_video_path, log_every_steps
):
"""Evaluates the world model."""
if debug_video_path:
debug_video_path = os.path.join(debug_video_path, "0.avi")
storage_env = rl_utils.setup_env(... | [
"def",
"evaluate_world_model",
"(",
"agent_type",
",",
"loop_hparams",
",",
"planner_hparams",
",",
"model_dir",
",",
"policy_dir",
",",
"random_starts_step_limit",
",",
"debug_video_path",
",",
"log_every_steps",
")",
":",
"if",
"debug_video_path",
":",
"debug_video_pa... | Evaluates the world model. | [
"Evaluates",
"the",
"world",
"model",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/evaluator.py#L375-L400 |
22,786 | tensorflow/tensor2tensor | tensor2tensor/envs/tic_tac_toe_env.py | get_open_spaces | def get_open_spaces(board):
"""Given a representation of the board, returns a list of open spaces."""
open_spaces = []
for i in range(3):
for j in range(3):
if board[i][j] == 0:
open_spaces.append(encode_pos(i, j))
return open_spaces | python | def get_open_spaces(board):
"""Given a representation of the board, returns a list of open spaces."""
open_spaces = []
for i in range(3):
for j in range(3):
if board[i][j] == 0:
open_spaces.append(encode_pos(i, j))
return open_spaces | [
"def",
"get_open_spaces",
"(",
"board",
")",
":",
"open_spaces",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"for",
"j",
"in",
"range",
"(",
"3",
")",
":",
"if",
"board",
"[",
"i",
"]",
"[",
"j",
"]",
"==",
"0",
":",
"open_s... | Given a representation of the board, returns a list of open spaces. | [
"Given",
"a",
"representation",
"of",
"the",
"board",
"returns",
"a",
"list",
"of",
"open",
"spaces",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/tic_tac_toe_env.py#L46-L53 |
22,787 | tensorflow/tensor2tensor | tensor2tensor/envs/tic_tac_toe_env.py | get_reward_and_done | def get_reward_and_done(board):
"""Given a representation of the board, returns reward and done."""
# Returns (reward, done) where:
# reward: -1 means lost, +1 means win, 0 means draw or continuing.
# done: True if the game is over, i.e. someone won or it is a draw.
# Sum all rows ...
all_sums = [np.sum(bo... | python | def get_reward_and_done(board):
"""Given a representation of the board, returns reward and done."""
# Returns (reward, done) where:
# reward: -1 means lost, +1 means win, 0 means draw or continuing.
# done: True if the game is over, i.e. someone won or it is a draw.
# Sum all rows ...
all_sums = [np.sum(bo... | [
"def",
"get_reward_and_done",
"(",
"board",
")",
":",
"# Returns (reward, done) where:",
"# reward: -1 means lost, +1 means win, 0 means draw or continuing.",
"# done: True if the game is over, i.e. someone won or it is a draw.",
"# Sum all rows ...",
"all_sums",
"=",
"[",
"np",
".",
"... | Given a representation of the board, returns reward and done. | [
"Given",
"a",
"representation",
"of",
"the",
"board",
"returns",
"reward",
"and",
"done",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/tic_tac_toe_env.py#L56-L80 |
22,788 | tensorflow/tensor2tensor | tensor2tensor/utils/decoding.py | decode_hparams | def decode_hparams(overrides=""):
"""Hyperparameters for decoding."""
hp = hparam.HParams(
save_images=False,
log_results=True,
extra_length=100,
min_length_ratio=0.0,
batch_size=0,
beam_size=4,
alpha=0.6,
eos_penalty=0.0,
block_size=0,
guess_and_check_top... | python | def decode_hparams(overrides=""):
"""Hyperparameters for decoding."""
hp = hparam.HParams(
save_images=False,
log_results=True,
extra_length=100,
min_length_ratio=0.0,
batch_size=0,
beam_size=4,
alpha=0.6,
eos_penalty=0.0,
block_size=0,
guess_and_check_top... | [
"def",
"decode_hparams",
"(",
"overrides",
"=",
"\"\"",
")",
":",
"hp",
"=",
"hparam",
".",
"HParams",
"(",
"save_images",
"=",
"False",
",",
"log_results",
"=",
"True",
",",
"extra_length",
"=",
"100",
",",
"min_length_ratio",
"=",
"0.0",
",",
"batch_size... | Hyperparameters for decoding. | [
"Hyperparameters",
"for",
"decoding",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L47-L101 |
22,789 | tensorflow/tensor2tensor | tensor2tensor/utils/decoding.py | log_decode_results | def log_decode_results(inputs,
outputs,
problem_name,
prediction_idx,
inputs_vocab,
targets_vocab,
targets=None,
save_images=False,
outp... | python | def log_decode_results(inputs,
outputs,
problem_name,
prediction_idx,
inputs_vocab,
targets_vocab,
targets=None,
save_images=False,
outp... | [
"def",
"log_decode_results",
"(",
"inputs",
",",
"outputs",
",",
"problem_name",
",",
"prediction_idx",
",",
"inputs_vocab",
",",
"targets_vocab",
",",
"targets",
"=",
"None",
",",
"save_images",
"=",
"False",
",",
"output_dir",
"=",
"None",
",",
"identity_outpu... | Log inference results. | [
"Log",
"inference",
"results",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L104-L170 |
22,790 | tensorflow/tensor2tensor | tensor2tensor/utils/decoding.py | decode_from_dataset | def decode_from_dataset(estimator,
problem_name,
hparams,
decode_hp,
decode_to_file=None,
dataset_split=None,
checkpoint_path=None):
"""Perform decoding from dataset."""
tf... | python | def decode_from_dataset(estimator,
problem_name,
hparams,
decode_hp,
decode_to_file=None,
dataset_split=None,
checkpoint_path=None):
"""Perform decoding from dataset."""
tf... | [
"def",
"decode_from_dataset",
"(",
"estimator",
",",
"problem_name",
",",
"hparams",
",",
"decode_hp",
",",
"decode_to_file",
"=",
"None",
",",
"dataset_split",
"=",
"None",
",",
"checkpoint_path",
"=",
"None",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(... | Perform decoding from dataset. | [
"Perform",
"decoding",
"from",
"dataset",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L173-L242 |
22,791 | tensorflow/tensor2tensor | tensor2tensor/utils/decoding.py | _decode_filename | def _decode_filename(base_filename, problem_name, decode_hp):
"""Generates decode filename.
Args:
base_filename: A string, base of the decode filename.
problem_name: A string, name of the problem.
decode_hp: HParams for decoding.
Returns:
A string, produced decode filename.
"""
if decode_hp.... | python | def _decode_filename(base_filename, problem_name, decode_hp):
"""Generates decode filename.
Args:
base_filename: A string, base of the decode filename.
problem_name: A string, name of the problem.
decode_hp: HParams for decoding.
Returns:
A string, produced decode filename.
"""
if decode_hp.... | [
"def",
"_decode_filename",
"(",
"base_filename",
",",
"problem_name",
",",
"decode_hp",
")",
":",
"if",
"decode_hp",
".",
"shards",
">",
"1",
":",
"base_filename",
"=",
"_add_shard_to_filename",
"(",
"base_filename",
",",
"decode_hp",
")",
"if",
"(",
"\"beam{bea... | Generates decode filename.
Args:
base_filename: A string, base of the decode filename.
problem_name: A string, name of the problem.
decode_hp: HParams for decoding.
Returns:
A string, produced decode filename. | [
"Generates",
"decode",
"filename",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L573-L598 |
22,792 | tensorflow/tensor2tensor | tensor2tensor/utils/decoding.py | make_input_fn_from_generator | def make_input_fn_from_generator(gen):
"""Use py_func to yield elements from the given generator."""
first_ex = six.next(gen)
flattened = tf.contrib.framework.nest.flatten(first_ex)
types = [t.dtype for t in flattened]
shapes = [[None] * len(t.shape) for t in flattened]
first_ex_list = [first_ex]
def py_... | python | def make_input_fn_from_generator(gen):
"""Use py_func to yield elements from the given generator."""
first_ex = six.next(gen)
flattened = tf.contrib.framework.nest.flatten(first_ex)
types = [t.dtype for t in flattened]
shapes = [[None] * len(t.shape) for t in flattened]
first_ex_list = [first_ex]
def py_... | [
"def",
"make_input_fn_from_generator",
"(",
"gen",
")",
":",
"first_ex",
"=",
"six",
".",
"next",
"(",
"gen",
")",
"flattened",
"=",
"tf",
".",
"contrib",
".",
"framework",
".",
"nest",
".",
"flatten",
"(",
"first_ex",
")",
"types",
"=",
"[",
"t",
".",... | Use py_func to yield elements from the given generator. | [
"Use",
"py_func",
"to",
"yield",
"elements",
"from",
"the",
"given",
"generator",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L601-L622 |
22,793 | tensorflow/tensor2tensor | tensor2tensor/utils/decoding.py | decode_interactively | def decode_interactively(estimator, hparams, decode_hp, checkpoint_path=None):
"""Interactive decoding."""
is_image = "image" in hparams.problem.name
is_text2class = isinstance(hparams.problem,
text_problems.Text2ClassProblem)
skip_eos_postprocess = (
is_image or is_text2clas... | python | def decode_interactively(estimator, hparams, decode_hp, checkpoint_path=None):
"""Interactive decoding."""
is_image = "image" in hparams.problem.name
is_text2class = isinstance(hparams.problem,
text_problems.Text2ClassProblem)
skip_eos_postprocess = (
is_image or is_text2clas... | [
"def",
"decode_interactively",
"(",
"estimator",
",",
"hparams",
",",
"decode_hp",
",",
"checkpoint_path",
"=",
"None",
")",
":",
"is_image",
"=",
"\"image\"",
"in",
"hparams",
".",
"problem",
".",
"name",
"is_text2class",
"=",
"isinstance",
"(",
"hparams",
".... | Interactive decoding. | [
"Interactive",
"decoding",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L625-L666 |
22,794 | tensorflow/tensor2tensor | tensor2tensor/utils/decoding.py | _decode_batch_input_fn | def _decode_batch_input_fn(num_decode_batches, sorted_inputs, vocabulary,
batch_size, max_input_size,
task_id=-1, has_input=True):
"""Generator to produce batches of inputs."""
tf.logging.info(" batch %d" % num_decode_batches)
for b in range(num_decode_batches... | python | def _decode_batch_input_fn(num_decode_batches, sorted_inputs, vocabulary,
batch_size, max_input_size,
task_id=-1, has_input=True):
"""Generator to produce batches of inputs."""
tf.logging.info(" batch %d" % num_decode_batches)
for b in range(num_decode_batches... | [
"def",
"_decode_batch_input_fn",
"(",
"num_decode_batches",
",",
"sorted_inputs",
",",
"vocabulary",
",",
"batch_size",
",",
"max_input_size",
",",
"task_id",
"=",
"-",
"1",
",",
"has_input",
"=",
"True",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"... | Generator to produce batches of inputs. | [
"Generator",
"to",
"produce",
"batches",
"of",
"inputs",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L669-L697 |
22,795 | tensorflow/tensor2tensor | tensor2tensor/utils/decoding.py | _interactive_input_fn | def _interactive_input_fn(hparams, decode_hp):
"""Generator that reads from the terminal and yields "interactive inputs".
Due to temporary limitations in tf.learn, if we don't want to reload the
whole graph, then we are stuck encoding all of the input as one fixed-size
numpy array.
We yield int32 arrays wit... | python | def _interactive_input_fn(hparams, decode_hp):
"""Generator that reads from the terminal and yields "interactive inputs".
Due to temporary limitations in tf.learn, if we don't want to reload the
whole graph, then we are stuck encoding all of the input as one fixed-size
numpy array.
We yield int32 arrays wit... | [
"def",
"_interactive_input_fn",
"(",
"hparams",
",",
"decode_hp",
")",
":",
"num_samples",
"=",
"decode_hp",
".",
"num_samples",
"if",
"decode_hp",
".",
"num_samples",
">",
"0",
"else",
"1",
"decode_length",
"=",
"decode_hp",
".",
"extra_length",
"input_type",
"... | Generator that reads from the terminal and yields "interactive inputs".
Due to temporary limitations in tf.learn, if we don't want to reload the
whole graph, then we are stuck encoding all of the input as one fixed-size
numpy array.
We yield int32 arrays with shape [const_array_size]. The format is:
[num_s... | [
"Generator",
"that",
"reads",
"from",
"the",
"terminal",
"and",
"yields",
"interactive",
"inputs",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L700-L779 |
22,796 | tensorflow/tensor2tensor | tensor2tensor/utils/decoding.py | save_video | def save_video(video, save_path_template):
"""Save frames of the videos into files."""
try:
from PIL import Image # pylint: disable=g-import-not-at-top
except ImportError as e:
tf.logging.warning(
"Showing and saving an image requires PIL library to be "
"installed: %s", e)
raise NotI... | python | def save_video(video, save_path_template):
"""Save frames of the videos into files."""
try:
from PIL import Image # pylint: disable=g-import-not-at-top
except ImportError as e:
tf.logging.warning(
"Showing and saving an image requires PIL library to be "
"installed: %s", e)
raise NotI... | [
"def",
"save_video",
"(",
"video",
",",
"save_path_template",
")",
":",
"try",
":",
"from",
"PIL",
"import",
"Image",
"# pylint: disable=g-import-not-at-top",
"except",
"ImportError",
"as",
"e",
":",
"tf",
".",
"logging",
".",
"warning",
"(",
"\"Showing and saving... | Save frames of the videos into files. | [
"Save",
"frames",
"of",
"the",
"videos",
"into",
"files",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L782-L795 |
22,797 | tensorflow/tensor2tensor | tensor2tensor/utils/decoding.py | show_and_save_image | def show_and_save_image(img, save_path):
"""Shows an image using matplotlib and saves it."""
try:
import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top
except ImportError as e:
tf.logging.warning(
"Showing and saving an image requires matplotlib to be "
"installed: %s", e)... | python | def show_and_save_image(img, save_path):
"""Shows an image using matplotlib and saves it."""
try:
import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top
except ImportError as e:
tf.logging.warning(
"Showing and saving an image requires matplotlib to be "
"installed: %s", e)... | [
"def",
"show_and_save_image",
"(",
"img",
",",
"save_path",
")",
":",
"try",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"# pylint: disable=g-import-not-at-top",
"except",
"ImportError",
"as",
"e",
":",
"tf",
".",
"logging",
".",
"warning",
"(",
"... | Shows an image using matplotlib and saves it. | [
"Shows",
"an",
"image",
"using",
"matplotlib",
"and",
"saves",
"it",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L798-L809 |
22,798 | tensorflow/tensor2tensor | tensor2tensor/utils/decoding.py | _get_language_modeling_inputs | def _get_language_modeling_inputs(filename,
delimiter="\n",
repeat=1,
append_space_to_final_punctionation=True):
"""Read a file of partial texts to continue.
The purpose of append_space_to_final_punctionation is t... | python | def _get_language_modeling_inputs(filename,
delimiter="\n",
repeat=1,
append_space_to_final_punctionation=True):
"""Read a file of partial texts to continue.
The purpose of append_space_to_final_punctionation is t... | [
"def",
"_get_language_modeling_inputs",
"(",
"filename",
",",
"delimiter",
"=",
"\"\\n\"",
",",
"repeat",
"=",
"1",
",",
"append_space_to_final_punctionation",
"=",
"True",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"filename",
")",
"as",
"f",
"... | Read a file of partial texts to continue.
The purpose of append_space_to_final_punctionation is that SubwordTokenizer
groups punctuation and the ensuing space in the same token. Adding a space
causes the token to be completed.
Args:
filename: a string
delimiter: a string
repeat: an integer - we r... | [
"Read",
"a",
"file",
"of",
"partial",
"texts",
"to",
"continue",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L812-L840 |
22,799 | tensorflow/tensor2tensor | tensor2tensor/utils/decoding.py | _get_sorted_inputs | def _get_sorted_inputs(filename, delimiter="\n"):
"""Returning inputs sorted according to decreasing length.
This causes inputs of similar lengths to be processed in the same batch,
facilitating early stopping for short sequences.
Longer sequences are sorted first so that if you're going to get OOMs,
you'll... | python | def _get_sorted_inputs(filename, delimiter="\n"):
"""Returning inputs sorted according to decreasing length.
This causes inputs of similar lengths to be processed in the same batch,
facilitating early stopping for short sequences.
Longer sequences are sorted first so that if you're going to get OOMs,
you'll... | [
"def",
"_get_sorted_inputs",
"(",
"filename",
",",
"delimiter",
"=",
"\"\\n\"",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Getting sorted inputs\"",
")",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"filename",
")",
"as",
"f",
":",
"text",
"="... | Returning inputs sorted according to decreasing length.
This causes inputs of similar lengths to be processed in the same batch,
facilitating early stopping for short sequences.
Longer sequences are sorted first so that if you're going to get OOMs,
you'll see it in the first batch.
Args:
filename: path... | [
"Returning",
"inputs",
"sorted",
"according",
"to",
"decreasing",
"length",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L843-L876 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.