repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
tensorflow/tensor2tensor | tensor2tensor/layers/common_video.py | WholeVideoWriter._start_reader_thread | def _start_reader_thread(self, stream, chunks):
"""Starts a thread for reading output from FFMPEG.
The thread reads consecutive chunks from the stream and saves them in
the given list.
Args:
stream: output stream of the FFMPEG process.
chunks: list to save output chunks to.
Returns:
... | python | def _start_reader_thread(self, stream, chunks):
"""Starts a thread for reading output from FFMPEG.
The thread reads consecutive chunks from the stream and saves them in
the given list.
Args:
stream: output stream of the FFMPEG process.
chunks: list to save output chunks to.
Returns:
... | [
"def",
"_start_reader_thread",
"(",
"self",
",",
"stream",
",",
"chunks",
")",
":",
"import",
"io",
"# pylint: disable=g-import-not-at-top",
"import",
"threading",
"# pylint: disable=g-import-not-at-top",
"def",
"target",
"(",
")",
":",
"while",
"True",
":",
"chunk",
... | Starts a thread for reading output from FFMPEG.
The thread reads consecutive chunks from the stream and saves them in
the given list.
Args:
stream: output stream of the FFMPEG process.
chunks: list to save output chunks to.
Returns:
Thread | [
"Starts",
"a",
"thread",
"for",
"reading",
"output",
"from",
"FFMPEG",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_video.py#L746-L769 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_video.py | WholeVideoWriter.finish | def finish(self):
"""Finishes transconding and returns the video.
Returns:
bytes
Raises:
IOError: in case of transcoding error.
"""
if self.proc is None:
return None
self.proc.stdin.close()
for thread in (self._out_thread, self._err_thread):
thread.join()
(out, ... | python | def finish(self):
"""Finishes transconding and returns the video.
Returns:
bytes
Raises:
IOError: in case of transcoding error.
"""
if self.proc is None:
return None
self.proc.stdin.close()
for thread in (self._out_thread, self._err_thread):
thread.join()
(out, ... | [
"def",
"finish",
"(",
"self",
")",
":",
"if",
"self",
".",
"proc",
"is",
"None",
":",
"return",
"None",
"self",
".",
"proc",
".",
"stdin",
".",
"close",
"(",
")",
"for",
"thread",
"in",
"(",
"self",
".",
"_out_thread",
",",
"self",
".",
"_err_threa... | Finishes transconding and returns the video.
Returns:
bytes
Raises:
IOError: in case of transcoding error. | [
"Finishes",
"transconding",
"and",
"returns",
"the",
"video",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_video.py#L776-L800 | train |
tensorflow/tensor2tensor | tensor2tensor/serving/query.py | validate_flags | def validate_flags():
"""Validates flags are set to acceptable values."""
if FLAGS.cloud_mlengine_model_name:
assert not FLAGS.server
assert not FLAGS.servable_name
else:
assert FLAGS.server
assert FLAGS.servable_name | python | def validate_flags():
"""Validates flags are set to acceptable values."""
if FLAGS.cloud_mlengine_model_name:
assert not FLAGS.server
assert not FLAGS.servable_name
else:
assert FLAGS.server
assert FLAGS.servable_name | [
"def",
"validate_flags",
"(",
")",
":",
"if",
"FLAGS",
".",
"cloud_mlengine_model_name",
":",
"assert",
"not",
"FLAGS",
".",
"server",
"assert",
"not",
"FLAGS",
".",
"servable_name",
"else",
":",
"assert",
"FLAGS",
".",
"server",
"assert",
"FLAGS",
".",
"ser... | Validates flags are set to acceptable values. | [
"Validates",
"flags",
"are",
"set",
"to",
"acceptable",
"values",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/serving/query.py#L53-L60 | train |
tensorflow/tensor2tensor | tensor2tensor/serving/query.py | make_request_fn | def make_request_fn():
"""Returns a request function."""
if FLAGS.cloud_mlengine_model_name:
request_fn = serving_utils.make_cloud_mlengine_request_fn(
credentials=GoogleCredentials.get_application_default(),
model_name=FLAGS.cloud_mlengine_model_name,
version=FLAGS.cloud_mlengine_model_... | python | def make_request_fn():
"""Returns a request function."""
if FLAGS.cloud_mlengine_model_name:
request_fn = serving_utils.make_cloud_mlengine_request_fn(
credentials=GoogleCredentials.get_application_default(),
model_name=FLAGS.cloud_mlengine_model_name,
version=FLAGS.cloud_mlengine_model_... | [
"def",
"make_request_fn",
"(",
")",
":",
"if",
"FLAGS",
".",
"cloud_mlengine_model_name",
":",
"request_fn",
"=",
"serving_utils",
".",
"make_cloud_mlengine_request_fn",
"(",
"credentials",
"=",
"GoogleCredentials",
".",
"get_application_default",
"(",
")",
",",
"mode... | Returns a request function. | [
"Returns",
"a",
"request",
"function",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/serving/query.py#L63-L76 | train |
tensorflow/tensor2tensor | tensor2tensor/models/video/savp.py | NextFrameSavpBase.encoder | def encoder(self, inputs, n_layers=3):
"""Convnet that encodes inputs into mean and std of a gaussian.
Args:
inputs: 5-D Tensor, shape (batch_size, num_frames, width, height, channels)
n_layers: Number of layers.
Returns:
z_mu: Mean of the latent gaussians.
z_log_var: log(var) of the l... | python | def encoder(self, inputs, n_layers=3):
"""Convnet that encodes inputs into mean and std of a gaussian.
Args:
inputs: 5-D Tensor, shape (batch_size, num_frames, width, height, channels)
n_layers: Number of layers.
Returns:
z_mu: Mean of the latent gaussians.
z_log_var: log(var) of the l... | [
"def",
"encoder",
"(",
"self",
",",
"inputs",
",",
"n_layers",
"=",
"3",
")",
":",
"latent_dims",
"=",
"self",
".",
"hparams",
".",
"z_dim",
"shape_as_list",
"=",
"inputs",
".",
"shape",
".",
"as_list",
"(",
")",
"if",
"len",
"(",
"shape_as_list",
")",... | Convnet that encodes inputs into mean and std of a gaussian.
Args:
inputs: 5-D Tensor, shape (batch_size, num_frames, width, height, channels)
n_layers: Number of layers.
Returns:
z_mu: Mean of the latent gaussians.
z_log_var: log(var) of the latent gaussians.
Raises:
ValueError... | [
"Convnet",
"that",
"encodes",
"inputs",
"into",
"mean",
"and",
"std",
"of",
"a",
"gaussian",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/savp.py#L42-L105 | train |
tensorflow/tensor2tensor | tensor2tensor/models/video/savp.py | NextFrameSavpBase.get_fc_dimensions | def get_fc_dimensions(self, strides, kernel_sizes):
"""Get expected fully connected shape after a series of convolutions."""
output_height, output_width, _ = self.hparams.problem.frame_shape
output_steps = self.hparams.video_num_target_frames
output_shape = np.array([output_steps, output_height, output_... | python | def get_fc_dimensions(self, strides, kernel_sizes):
"""Get expected fully connected shape after a series of convolutions."""
output_height, output_width, _ = self.hparams.problem.frame_shape
output_steps = self.hparams.video_num_target_frames
output_shape = np.array([output_steps, output_height, output_... | [
"def",
"get_fc_dimensions",
"(",
"self",
",",
"strides",
",",
"kernel_sizes",
")",
":",
"output_height",
",",
"output_width",
",",
"_",
"=",
"self",
".",
"hparams",
".",
"problem",
".",
"frame_shape",
"output_steps",
"=",
"self",
".",
"hparams",
".",
"video_... | Get expected fully connected shape after a series of convolutions. | [
"Get",
"expected",
"fully",
"connected",
"shape",
"after",
"a",
"series",
"of",
"convolutions",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/savp.py#L110-L118 | train |
tensorflow/tensor2tensor | tensor2tensor/models/video/savp.py | NextFrameSavpBase.discriminator | def discriminator(self, frames):
"""3-D SNGAN discriminator.
Args:
frames: a list of batch-major tensors indexed by time.
Returns:
logits: 1-D Tensor with shape=batch_size.
Positive logits imply that the discriminator thinks that it
belongs to the true class.
""... | python | def discriminator(self, frames):
"""3-D SNGAN discriminator.
Args:
frames: a list of batch-major tensors indexed by time.
Returns:
logits: 1-D Tensor with shape=batch_size.
Positive logits imply that the discriminator thinks that it
belongs to the true class.
""... | [
"def",
"discriminator",
"(",
"self",
",",
"frames",
")",
":",
"ndf",
"=",
"self",
".",
"hparams",
".",
"num_discriminator_filters",
"frames",
"=",
"tf",
".",
"stack",
"(",
"frames",
")",
"# Switch from time-major axis to batch-major axis.",
"frames",
"=",
"common_... | 3-D SNGAN discriminator.
Args:
frames: a list of batch-major tensors indexed by time.
Returns:
logits: 1-D Tensor with shape=batch_size.
Positive logits imply that the discriminator thinks that it
belongs to the true class. | [
"3",
"-",
"D",
"SNGAN",
"discriminator",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/savp.py#L120-L153 | train |
tensorflow/tensor2tensor | tensor2tensor/models/video/savp.py | NextFrameSavpBase.d_step | def d_step(self, true_frames, gen_frames):
"""Performs the discriminator step in computing the GAN loss.
Applies stop-gradient to the generated frames while computing the
discriminator loss to make sure that the gradients are not back-propagated
to the generator. This makes sure that only the discrimin... | python | def d_step(self, true_frames, gen_frames):
"""Performs the discriminator step in computing the GAN loss.
Applies stop-gradient to the generated frames while computing the
discriminator loss to make sure that the gradients are not back-propagated
to the generator. This makes sure that only the discrimin... | [
"def",
"d_step",
"(",
"self",
",",
"true_frames",
",",
"gen_frames",
")",
":",
"hparam_to_disc_loss",
"=",
"{",
"\"least_squares\"",
":",
"gan_losses",
".",
"least_squares_discriminator_loss",
",",
"\"cross_entropy\"",
":",
"gan_losses",
".",
"modified_discriminator_los... | Performs the discriminator step in computing the GAN loss.
Applies stop-gradient to the generated frames while computing the
discriminator loss to make sure that the gradients are not back-propagated
to the generator. This makes sure that only the discriminator is updated.
Args:
true_frames: Tru... | [
"Performs",
"the",
"discriminator",
"step",
"in",
"computing",
"the",
"GAN",
"loss",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/savp.py#L155-L192 | train |
tensorflow/tensor2tensor | tensor2tensor/models/video/savp.py | NextFrameSavpBase.g_step | def g_step(self, gen_frames, fake_logits_stop):
"""Performs the generator step in computing the GAN loss.
Args:
gen_frames: Generated frames
fake_logits_stop: Logits corresponding to the generated frames as per
the discriminator. Assumed to have a stop-gradient term.
Ret... | python | def g_step(self, gen_frames, fake_logits_stop):
"""Performs the generator step in computing the GAN loss.
Args:
gen_frames: Generated frames
fake_logits_stop: Logits corresponding to the generated frames as per
the discriminator. Assumed to have a stop-gradient term.
Ret... | [
"def",
"g_step",
"(",
"self",
",",
"gen_frames",
",",
"fake_logits_stop",
")",
":",
"hparam_to_gen_loss",
"=",
"{",
"\"least_squares\"",
":",
"gan_losses",
".",
"least_squares_generator_loss",
",",
"\"cross_entropy\"",
":",
"gan_losses",
".",
"modified_generator_loss",
... | Performs the generator step in computing the GAN loss.
Args:
gen_frames: Generated frames
fake_logits_stop: Logits corresponding to the generated frames as per
the discriminator. Assumed to have a stop-gradient term.
Returns:
gan_g_loss_pos_d: Loss.
gan_g_loss_ne... | [
"Performs",
"the",
"generator",
"step",
"in",
"computing",
"the",
"GAN",
"loss",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/savp.py#L194-L226 | train |
tensorflow/tensor2tensor | tensor2tensor/models/video/savp.py | NextFrameSavpBase.get_gan_loss | def get_gan_loss(self, true_frames, gen_frames, name):
"""Get the discriminator + generator loss at every step.
This performs an 1:1 update of the discriminator and generator at every
step.
Args:
true_frames: 5-D Tensor of shape (num_steps, batch_size, H, W, C)
Assumed to be g... | python | def get_gan_loss(self, true_frames, gen_frames, name):
"""Get the discriminator + generator loss at every step.
This performs an 1:1 update of the discriminator and generator at every
step.
Args:
true_frames: 5-D Tensor of shape (num_steps, batch_size, H, W, C)
Assumed to be g... | [
"def",
"get_gan_loss",
"(",
"self",
",",
"true_frames",
",",
"gen_frames",
",",
"name",
")",
":",
"# D - STEP",
"with",
"tf",
".",
"variable_scope",
"(",
"\"%s_discriminator\"",
"%",
"name",
",",
"reuse",
"=",
"tf",
".",
"AUTO_REUSE",
")",
":",
"gan_d_loss",... | Get the discriminator + generator loss at every step.
This performs an 1:1 update of the discriminator and generator at every
step.
Args:
true_frames: 5-D Tensor of shape (num_steps, batch_size, H, W, C)
Assumed to be ground truth.
gen_frames: 5-D Tensor of shape (num_steps,... | [
"Get",
"the",
"discriminator",
"+",
"generator",
"loss",
"at",
"every",
"step",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/savp.py#L228-L262 | train |
tensorflow/tensor2tensor | tensor2tensor/models/video/savp.py | NextFrameSavpBase.get_extra_loss | def get_extra_loss(self, latent_means=None, latent_stds=None,
true_frames=None, gen_frames=None):
"""Gets extra loss from VAE and GAN."""
if not self.is_training:
return 0.0
vae_loss, d_vae_loss, d_gan_loss = 0.0, 0.0, 0.0
# Use sv2p's KL divergence computation.
if self.h... | python | def get_extra_loss(self, latent_means=None, latent_stds=None,
true_frames=None, gen_frames=None):
"""Gets extra loss from VAE and GAN."""
if not self.is_training:
return 0.0
vae_loss, d_vae_loss, d_gan_loss = 0.0, 0.0, 0.0
# Use sv2p's KL divergence computation.
if self.h... | [
"def",
"get_extra_loss",
"(",
"self",
",",
"latent_means",
"=",
"None",
",",
"latent_stds",
"=",
"None",
",",
"true_frames",
"=",
"None",
",",
"gen_frames",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"is_training",
":",
"return",
"0.0",
"vae_loss",
... | Gets extra loss from VAE and GAN. | [
"Gets",
"extra",
"loss",
"from",
"VAE",
"and",
"GAN",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/savp.py#L264-L296 | train |
tensorflow/tensor2tensor | tensor2tensor/models/video/savp.py | NextFrameSavpBase.pad_conv3d_lrelu | def pad_conv3d_lrelu(self, activations, n_filters, kernel_size, strides,
scope):
"""Pad, apply 3-D convolution and leaky relu."""
padding = [[0, 0], [1, 1], [1, 1], [1, 1], [0, 0]]
# tf.nn.conv3d accepts a list of 5 values for strides
# with first and last value equal to 1
if... | python | def pad_conv3d_lrelu(self, activations, n_filters, kernel_size, strides,
scope):
"""Pad, apply 3-D convolution and leaky relu."""
padding = [[0, 0], [1, 1], [1, 1], [1, 1], [0, 0]]
# tf.nn.conv3d accepts a list of 5 values for strides
# with first and last value equal to 1
if... | [
"def",
"pad_conv3d_lrelu",
"(",
"self",
",",
"activations",
",",
"n_filters",
",",
"kernel_size",
",",
"strides",
",",
"scope",
")",
":",
"padding",
"=",
"[",
"[",
"0",
",",
"0",
"]",
",",
"[",
"1",
",",
"1",
"]",
",",
"[",
"1",
",",
"1",
"]",
... | Pad, apply 3-D convolution and leaky relu. | [
"Pad",
"apply",
"3",
"-",
"D",
"convolution",
"and",
"leaky",
"relu",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/savp.py#L298-L327 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/pruning_utils.py | weight | def weight(w, sparsity):
"""Weight-level magnitude pruning."""
w_shape = common_layers.shape_list(w)
k = int(np.prod(w_shape[:-1]))
count = tf.to_int32(k * sparsity)
mask = common_layers.weight_targeting(w, count)
return (1 - mask) * w | python | def weight(w, sparsity):
"""Weight-level magnitude pruning."""
w_shape = common_layers.shape_list(w)
k = int(np.prod(w_shape[:-1]))
count = tf.to_int32(k * sparsity)
mask = common_layers.weight_targeting(w, count)
return (1 - mask) * w | [
"def",
"weight",
"(",
"w",
",",
"sparsity",
")",
":",
"w_shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"w",
")",
"k",
"=",
"int",
"(",
"np",
".",
"prod",
"(",
"w_shape",
"[",
":",
"-",
"1",
"]",
")",
")",
"count",
"=",
"tf",
".",
"to_in... | Weight-level magnitude pruning. | [
"Weight",
"-",
"level",
"magnitude",
"pruning",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/pruning_utils.py#L27-L33 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/pruning_utils.py | unit | def unit(w, sparsity):
"""Unit-level magnitude pruning."""
w_shape = common_layers.shape_list(w)
count = tf.to_int32(w_shape[-1] * sparsity)
mask = common_layers.unit_targeting(w, count)
return (1 - mask) * w | python | def unit(w, sparsity):
"""Unit-level magnitude pruning."""
w_shape = common_layers.shape_list(w)
count = tf.to_int32(w_shape[-1] * sparsity)
mask = common_layers.unit_targeting(w, count)
return (1 - mask) * w | [
"def",
"unit",
"(",
"w",
",",
"sparsity",
")",
":",
"w_shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"w",
")",
"count",
"=",
"tf",
".",
"to_int32",
"(",
"w_shape",
"[",
"-",
"1",
"]",
"*",
"sparsity",
")",
"mask",
"=",
"common_layers",
".",
... | Unit-level magnitude pruning. | [
"Unit",
"-",
"level",
"magnitude",
"pruning",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/pruning_utils.py#L37-L42 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/pruning_utils.py | sparsify | def sparsify(sess, eval_model, pruning_strategy, pruning_params):
"""Prune the weights of a model and evaluate."""
weights = tf.trainable_variables()
def should_prune(name):
"""Whether to prune a weight or not."""
in_whitelist = not pruning_params.white_list or any(
e in name for e in pruning_par... | python | def sparsify(sess, eval_model, pruning_strategy, pruning_params):
"""Prune the weights of a model and evaluate."""
weights = tf.trainable_variables()
def should_prune(name):
"""Whether to prune a weight or not."""
in_whitelist = not pruning_params.white_list or any(
e in name for e in pruning_par... | [
"def",
"sparsify",
"(",
"sess",
",",
"eval_model",
",",
"pruning_strategy",
",",
"pruning_params",
")",
":",
"weights",
"=",
"tf",
".",
"trainable_variables",
"(",
")",
"def",
"should_prune",
"(",
"name",
")",
":",
"\"\"\"Whether to prune a weight or not.\"\"\"",
... | Prune the weights of a model and evaluate. | [
"Prune",
"the",
"weights",
"of",
"a",
"model",
"and",
"evaluate",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/pruning_utils.py#L45-L80 | train |
tensorflow/tensor2tensor | tensor2tensor/insights/server.py | DebugFrontendApplication.load_config | def load_config(self):
"""Loads the configuration."""
config = dict([(key, value) for key, value in iteritems(self.options)
if key in self.cfg.settings and value is not None])
for key, value in iteritems(config):
self.cfg.set(key.lower(), value) | python | def load_config(self):
"""Loads the configuration."""
config = dict([(key, value) for key, value in iteritems(self.options)
if key in self.cfg.settings and value is not None])
for key, value in iteritems(config):
self.cfg.set(key.lower(), value) | [
"def",
"load_config",
"(",
"self",
")",
":",
"config",
"=",
"dict",
"(",
"[",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"self",
".",
"options",
")",
"if",
"key",
"in",
"self",
".",
"cfg",
".",
"settings",
... | Loads the configuration. | [
"Loads",
"the",
"configuration",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/insights/server.py#L79-L84 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/rl.py | ppo_base_v1 | def ppo_base_v1():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.learning_rate_schedule = "constant"
hparams.learning_rate_constant = 1e-4
hparams.clip_grad_norm = 0.5
hparams.weight_decay = 0
# If set, extends the LR warmup to all epochs except the final one.
hparams.ad... | python | def ppo_base_v1():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.learning_rate_schedule = "constant"
hparams.learning_rate_constant = 1e-4
hparams.clip_grad_norm = 0.5
hparams.weight_decay = 0
# If set, extends the LR warmup to all epochs except the final one.
hparams.ad... | [
"def",
"ppo_base_v1",
"(",
")",
":",
"hparams",
"=",
"common_hparams",
".",
"basic_params1",
"(",
")",
"hparams",
".",
"learning_rate_schedule",
"=",
"\"constant\"",
"hparams",
".",
"learning_rate_constant",
"=",
"1e-4",
"hparams",
".",
"clip_grad_norm",
"=",
"0.5... | Set of hyperparameters. | [
"Set",
"of",
"hyperparameters",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L46-L76 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/rl.py | ppo_atari_base | def ppo_atari_base():
"""Pong base parameters."""
hparams = ppo_discrete_action_base()
hparams.learning_rate_constant = 1e-4
hparams.epoch_length = 200
hparams.gae_gamma = 0.985
hparams.gae_lambda = 0.985
hparams.entropy_loss_coef = 0.003
hparams.value_loss_coef = 1
hparams.optimization_epochs = 3
h... | python | def ppo_atari_base():
"""Pong base parameters."""
hparams = ppo_discrete_action_base()
hparams.learning_rate_constant = 1e-4
hparams.epoch_length = 200
hparams.gae_gamma = 0.985
hparams.gae_lambda = 0.985
hparams.entropy_loss_coef = 0.003
hparams.value_loss_coef = 1
hparams.optimization_epochs = 3
h... | [
"def",
"ppo_atari_base",
"(",
")",
":",
"hparams",
"=",
"ppo_discrete_action_base",
"(",
")",
"hparams",
".",
"learning_rate_constant",
"=",
"1e-4",
"hparams",
".",
"epoch_length",
"=",
"200",
"hparams",
".",
"gae_gamma",
"=",
"0.985",
"hparams",
".",
"gae_lambd... | Pong base parameters. | [
"Pong",
"base",
"parameters",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L100-L115 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/rl.py | ppo_original_params | def ppo_original_params():
"""Parameters based on the original PPO paper."""
hparams = ppo_atari_base()
hparams.learning_rate_constant = 2.5e-4
hparams.gae_gamma = 0.99
hparams.gae_lambda = 0.95
hparams.clipping_coef = 0.1
hparams.value_loss_coef = 1
hparams.entropy_loss_coef = 0.01
hparams.eval_every... | python | def ppo_original_params():
"""Parameters based on the original PPO paper."""
hparams = ppo_atari_base()
hparams.learning_rate_constant = 2.5e-4
hparams.gae_gamma = 0.99
hparams.gae_lambda = 0.95
hparams.clipping_coef = 0.1
hparams.value_loss_coef = 1
hparams.entropy_loss_coef = 0.01
hparams.eval_every... | [
"def",
"ppo_original_params",
"(",
")",
":",
"hparams",
"=",
"ppo_atari_base",
"(",
")",
"hparams",
".",
"learning_rate_constant",
"=",
"2.5e-4",
"hparams",
".",
"gae_gamma",
"=",
"0.99",
"hparams",
".",
"gae_lambda",
"=",
"0.95",
"hparams",
".",
"clipping_coef"... | Parameters based on the original PPO paper. | [
"Parameters",
"based",
"on",
"the",
"original",
"PPO",
"paper",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L119-L134 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/rl.py | ppo_original_world_model | def ppo_original_world_model():
"""Atari parameters with world model as policy."""
hparams = ppo_original_params()
hparams.policy_network = "next_frame_basic_deterministic"
hparams_keys = hparams.values().keys()
video_hparams = basic_deterministic_params.next_frame_basic_deterministic()
for (name, value) in... | python | def ppo_original_world_model():
"""Atari parameters with world model as policy."""
hparams = ppo_original_params()
hparams.policy_network = "next_frame_basic_deterministic"
hparams_keys = hparams.values().keys()
video_hparams = basic_deterministic_params.next_frame_basic_deterministic()
for (name, value) in... | [
"def",
"ppo_original_world_model",
"(",
")",
":",
"hparams",
"=",
"ppo_original_params",
"(",
")",
"hparams",
".",
"policy_network",
"=",
"\"next_frame_basic_deterministic\"",
"hparams_keys",
"=",
"hparams",
".",
"values",
"(",
")",
".",
"keys",
"(",
")",
"video_h... | Atari parameters with world model as policy. | [
"Atari",
"parameters",
"with",
"world",
"model",
"as",
"policy",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L172-L185 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/rl.py | ppo_tiny_world_model | def ppo_tiny_world_model():
"""Atari parameters with world model as policy."""
hparams = ppo_original_params()
hparams.policy_network = "next_frame_basic_deterministic"
hparams_keys = hparams.values().keys()
video_hparams = basic_deterministic_params.next_frame_tiny()
for (name, value) in six.iteritems(vide... | python | def ppo_tiny_world_model():
"""Atari parameters with world model as policy."""
hparams = ppo_original_params()
hparams.policy_network = "next_frame_basic_deterministic"
hparams_keys = hparams.values().keys()
video_hparams = basic_deterministic_params.next_frame_tiny()
for (name, value) in six.iteritems(vide... | [
"def",
"ppo_tiny_world_model",
"(",
")",
":",
"hparams",
"=",
"ppo_original_params",
"(",
")",
"hparams",
".",
"policy_network",
"=",
"\"next_frame_basic_deterministic\"",
"hparams_keys",
"=",
"hparams",
".",
"values",
"(",
")",
".",
"keys",
"(",
")",
"video_hpara... | Atari parameters with world model as policy. | [
"Atari",
"parameters",
"with",
"world",
"model",
"as",
"policy",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L189-L201 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/rl.py | ppo_original_world_model_stochastic_discrete | def ppo_original_world_model_stochastic_discrete():
"""Atari parameters with stochastic discrete world model as policy."""
hparams = ppo_original_params()
hparams.policy_network = "next_frame_basic_stochastic_discrete"
hparams_keys = hparams.values().keys()
video_hparams = basic_stochastic.next_frame_basic_st... | python | def ppo_original_world_model_stochastic_discrete():
"""Atari parameters with stochastic discrete world model as policy."""
hparams = ppo_original_params()
hparams.policy_network = "next_frame_basic_stochastic_discrete"
hparams_keys = hparams.values().keys()
video_hparams = basic_stochastic.next_frame_basic_st... | [
"def",
"ppo_original_world_model_stochastic_discrete",
"(",
")",
":",
"hparams",
"=",
"ppo_original_params",
"(",
")",
"hparams",
".",
"policy_network",
"=",
"\"next_frame_basic_stochastic_discrete\"",
"hparams_keys",
"=",
"hparams",
".",
"values",
"(",
")",
".",
"keys"... | Atari parameters with stochastic discrete world model as policy. | [
"Atari",
"parameters",
"with",
"stochastic",
"discrete",
"world",
"model",
"as",
"policy",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L205-L219 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/rl.py | make_simulated_env_fn | def make_simulated_env_fn(**env_kwargs):
"""Returns a function creating a simulated env, in or out of graph.
Args:
**env_kwargs: kwargs to pass to the simulated env constructor.
Returns:
Function in_graph -> env.
"""
def env_fn(in_graph):
class_ = SimulatedBatchEnv if in_graph else SimulatedBatc... | python | def make_simulated_env_fn(**env_kwargs):
"""Returns a function creating a simulated env, in or out of graph.
Args:
**env_kwargs: kwargs to pass to the simulated env constructor.
Returns:
Function in_graph -> env.
"""
def env_fn(in_graph):
class_ = SimulatedBatchEnv if in_graph else SimulatedBatc... | [
"def",
"make_simulated_env_fn",
"(",
"*",
"*",
"env_kwargs",
")",
":",
"def",
"env_fn",
"(",
"in_graph",
")",
":",
"class_",
"=",
"SimulatedBatchEnv",
"if",
"in_graph",
"else",
"SimulatedBatchGymEnv",
"return",
"class_",
"(",
"*",
"*",
"env_kwargs",
")",
"retu... | Returns a function creating a simulated env, in or out of graph.
Args:
**env_kwargs: kwargs to pass to the simulated env constructor.
Returns:
Function in_graph -> env. | [
"Returns",
"a",
"function",
"creating",
"a",
"simulated",
"env",
"in",
"or",
"out",
"of",
"graph",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L234-L246 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/rl.py | make_simulated_env_kwargs | def make_simulated_env_kwargs(real_env, hparams, **extra_kwargs):
"""Extracts simulated env kwargs from real_env and loop hparams."""
objs_and_attrs = [
(real_env, [
"reward_range", "observation_space", "action_space", "frame_height",
"frame_width"
]),
(hparams, ["frame_stack_s... | python | def make_simulated_env_kwargs(real_env, hparams, **extra_kwargs):
"""Extracts simulated env kwargs from real_env and loop hparams."""
objs_and_attrs = [
(real_env, [
"reward_range", "observation_space", "action_space", "frame_height",
"frame_width"
]),
(hparams, ["frame_stack_s... | [
"def",
"make_simulated_env_kwargs",
"(",
"real_env",
",",
"hparams",
",",
"*",
"*",
"extra_kwargs",
")",
":",
"objs_and_attrs",
"=",
"[",
"(",
"real_env",
",",
"[",
"\"reward_range\"",
",",
"\"observation_space\"",
",",
"\"action_space\"",
",",
"\"frame_height\"",
... | Extracts simulated env kwargs from real_env and loop hparams. | [
"Extracts",
"simulated",
"env",
"kwargs",
"from",
"real_env",
"and",
"loop",
"hparams",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L250-L270 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/rl.py | get_policy | def get_policy(observations, hparams, action_space):
"""Get a policy network.
Args:
observations: observations
hparams: parameters
action_space: action space
Returns:
Tuple (action logits, value).
"""
if not isinstance(action_space, gym.spaces.Discrete):
raise ValueError("Expecting discr... | python | def get_policy(observations, hparams, action_space):
"""Get a policy network.
Args:
observations: observations
hparams: parameters
action_space: action space
Returns:
Tuple (action logits, value).
"""
if not isinstance(action_space, gym.spaces.Discrete):
raise ValueError("Expecting discr... | [
"def",
"get_policy",
"(",
"observations",
",",
"hparams",
",",
"action_space",
")",
":",
"if",
"not",
"isinstance",
"(",
"action_space",
",",
"gym",
".",
"spaces",
".",
"Discrete",
")",
":",
"raise",
"ValueError",
"(",
"\"Expecting discrete action space.\"",
")"... | Get a policy network.
Args:
observations: observations
hparams: parameters
action_space: action space
Returns:
Tuple (action logits, value). | [
"Get",
"a",
"policy",
"network",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L280-L332 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/rl.py | rlmf_tictactoe | def rlmf_tictactoe():
"""Base set of hparams for model-free PPO."""
hparams = rlmf_original()
hparams.game = "tictactoe"
hparams.rl_env_name = "T2TEnv-TicTacToeEnv-v0"
# Since we don't have any no-op actions, otherwise we have to have an
# attribute called `get_action_meanings`.
hparams.eval_max_num_noops... | python | def rlmf_tictactoe():
"""Base set of hparams for model-free PPO."""
hparams = rlmf_original()
hparams.game = "tictactoe"
hparams.rl_env_name = "T2TEnv-TicTacToeEnv-v0"
# Since we don't have any no-op actions, otherwise we have to have an
# attribute called `get_action_meanings`.
hparams.eval_max_num_noops... | [
"def",
"rlmf_tictactoe",
"(",
")",
":",
"hparams",
"=",
"rlmf_original",
"(",
")",
"hparams",
".",
"game",
"=",
"\"tictactoe\"",
"hparams",
".",
"rl_env_name",
"=",
"\"T2TEnv-TicTacToeEnv-v0\"",
"# Since we don't have any no-op actions, otherwise we have to have an",
"# att... | Base set of hparams for model-free PPO. | [
"Base",
"set",
"of",
"hparams",
"for",
"model",
"-",
"free",
"PPO",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L427-L443 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/rl.py | rlmf_tiny | def rlmf_tiny():
"""Tiny set of hparams for model-free PPO."""
hparams = rlmf_original()
hparams = hparams.override_from_dict(rlmf_tiny_overrides())
hparams.batch_size = 2
hparams.base_algo_params = "ppo_original_tiny"
hparams.add_hparam("ppo_epochs_num", 3)
hparams.add_hparam("ppo_epoch_length", 2)
ret... | python | def rlmf_tiny():
"""Tiny set of hparams for model-free PPO."""
hparams = rlmf_original()
hparams = hparams.override_from_dict(rlmf_tiny_overrides())
hparams.batch_size = 2
hparams.base_algo_params = "ppo_original_tiny"
hparams.add_hparam("ppo_epochs_num", 3)
hparams.add_hparam("ppo_epoch_length", 2)
ret... | [
"def",
"rlmf_tiny",
"(",
")",
":",
"hparams",
"=",
"rlmf_original",
"(",
")",
"hparams",
"=",
"hparams",
".",
"override_from_dict",
"(",
"rlmf_tiny_overrides",
"(",
")",
")",
"hparams",
".",
"batch_size",
"=",
"2",
"hparams",
".",
"base_algo_params",
"=",
"\... | Tiny set of hparams for model-free PPO. | [
"Tiny",
"set",
"of",
"hparams",
"for",
"model",
"-",
"free",
"PPO",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L456-L464 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/rl.py | rlmf_dqn_tiny | def rlmf_dqn_tiny():
"""Tiny DQN params."""
hparams = rlmf_original()
hparams = hparams.override_from_dict(rlmf_tiny_overrides())
hparams.batch_size = 1
hparams.base_algo = "dqn"
hparams.base_algo_params = "dqn_original_params"
hparams.add_hparam("dqn_num_frames", 128)
hparams.add_hparam("dqn_save_every... | python | def rlmf_dqn_tiny():
"""Tiny DQN params."""
hparams = rlmf_original()
hparams = hparams.override_from_dict(rlmf_tiny_overrides())
hparams.batch_size = 1
hparams.base_algo = "dqn"
hparams.base_algo_params = "dqn_original_params"
hparams.add_hparam("dqn_num_frames", 128)
hparams.add_hparam("dqn_save_every... | [
"def",
"rlmf_dqn_tiny",
"(",
")",
":",
"hparams",
"=",
"rlmf_original",
"(",
")",
"hparams",
"=",
"hparams",
".",
"override_from_dict",
"(",
"rlmf_tiny_overrides",
"(",
")",
")",
"hparams",
".",
"batch_size",
"=",
"1",
"hparams",
".",
"base_algo",
"=",
"\"dq... | Tiny DQN params. | [
"Tiny",
"DQN",
"params",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L468-L479 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/rl.py | rlmf_eval | def rlmf_eval():
"""Eval set of hparams for model-free PPO."""
hparams = rlmf_original()
hparams.batch_size = 8
hparams.eval_sampling_temps = [0.0, 0.5, 1.0]
hparams.eval_rl_env_max_episode_steps = -1
hparams.add_hparam("ppo_epoch_length", 128)
hparams.add_hparam("ppo_optimization_batch_size", 32)
hpara... | python | def rlmf_eval():
"""Eval set of hparams for model-free PPO."""
hparams = rlmf_original()
hparams.batch_size = 8
hparams.eval_sampling_temps = [0.0, 0.5, 1.0]
hparams.eval_rl_env_max_episode_steps = -1
hparams.add_hparam("ppo_epoch_length", 128)
hparams.add_hparam("ppo_optimization_batch_size", 32)
hpara... | [
"def",
"rlmf_eval",
"(",
")",
":",
"hparams",
"=",
"rlmf_original",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"8",
"hparams",
".",
"eval_sampling_temps",
"=",
"[",
"0.0",
",",
"0.5",
",",
"1.0",
"]",
"hparams",
".",
"eval_rl_env_max_episode_steps",
"=",
... | Eval set of hparams for model-free PPO. | [
"Eval",
"set",
"of",
"hparams",
"for",
"model",
"-",
"free",
"PPO",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L483-L495 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/rl.py | feed_forward_gaussian_fun | def feed_forward_gaussian_fun(action_space, config, observations):
"""Feed-forward Gaussian."""
if not isinstance(action_space, gym.spaces.box.Box):
raise ValueError("Expecting continuous action space.")
mean_weights_initializer = tf.initializers.variance_scaling(
scale=config.init_mean_factor)
logst... | python | def feed_forward_gaussian_fun(action_space, config, observations):
"""Feed-forward Gaussian."""
if not isinstance(action_space, gym.spaces.box.Box):
raise ValueError("Expecting continuous action space.")
mean_weights_initializer = tf.initializers.variance_scaling(
scale=config.init_mean_factor)
logst... | [
"def",
"feed_forward_gaussian_fun",
"(",
"action_space",
",",
"config",
",",
"observations",
")",
":",
"if",
"not",
"isinstance",
"(",
"action_space",
",",
"gym",
".",
"spaces",
".",
"box",
".",
"Box",
")",
":",
"raise",
"ValueError",
"(",
"\"Expecting continu... | Feed-forward Gaussian. | [
"Feed",
"-",
"forward",
"Gaussian",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/rl.py#L559-L596 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/yellowfin.py | YellowFinOptimizer._curvature_range | def _curvature_range(self):
"""Curvature range.
Returns:
h_max_t, h_min_t ops
"""
self._curv_win = tf.get_variable("curv_win",
dtype=tf.float32,
trainable=False,
shape=[self.curvature_wi... | python | def _curvature_range(self):
"""Curvature range.
Returns:
h_max_t, h_min_t ops
"""
self._curv_win = tf.get_variable("curv_win",
dtype=tf.float32,
trainable=False,
shape=[self.curvature_wi... | [
"def",
"_curvature_range",
"(",
"self",
")",
":",
"self",
".",
"_curv_win",
"=",
"tf",
".",
"get_variable",
"(",
"\"curv_win\"",
",",
"dtype",
"=",
"tf",
".",
"float32",
",",
"trainable",
"=",
"False",
",",
"shape",
"=",
"[",
"self",
".",
"curvature_wind... | Curvature range.
Returns:
h_max_t, h_min_t ops | [
"Curvature",
"range",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L193-L230 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/yellowfin.py | YellowFinOptimizer._grad_variance | def _grad_variance(self):
"""Estimate of gradient Variance.
Returns:
C_t ops.
"""
grad_var_ops = []
tensor_to_avg = []
for t, g in zip(self._vars, self._grad):
if isinstance(g, tf.IndexedSlices):
tensor_to_avg.append(
tf.reshape(tf.unsorted_segment_sum(g.values,
... | python | def _grad_variance(self):
"""Estimate of gradient Variance.
Returns:
C_t ops.
"""
grad_var_ops = []
tensor_to_avg = []
for t, g in zip(self._vars, self._grad):
if isinstance(g, tf.IndexedSlices):
tensor_to_avg.append(
tf.reshape(tf.unsorted_segment_sum(g.values,
... | [
"def",
"_grad_variance",
"(",
"self",
")",
":",
"grad_var_ops",
"=",
"[",
"]",
"tensor_to_avg",
"=",
"[",
"]",
"for",
"t",
",",
"g",
"in",
"zip",
"(",
"self",
".",
"_vars",
",",
"self",
".",
"_grad",
")",
":",
"if",
"isinstance",
"(",
"g",
",",
"... | Estimate of gradient Variance.
Returns:
C_t ops. | [
"Estimate",
"of",
"gradient",
"Variance",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L232-L263 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/yellowfin.py | YellowFinOptimizer._dist_to_opt | def _dist_to_opt(self):
"""Distance to optimum.
Returns:
D_t ops
"""
dist_to_opt_ops = []
# Running average of the norm of gradient
self._grad_norm = tf.sqrt(self._grad_norm_squared)
avg_op = self._moving_averager.apply([self._grad_norm,])
dist_to_opt_ops.append(avg_op)
with t... | python | def _dist_to_opt(self):
"""Distance to optimum.
Returns:
D_t ops
"""
dist_to_opt_ops = []
# Running average of the norm of gradient
self._grad_norm = tf.sqrt(self._grad_norm_squared)
avg_op = self._moving_averager.apply([self._grad_norm,])
dist_to_opt_ops.append(avg_op)
with t... | [
"def",
"_dist_to_opt",
"(",
"self",
")",
":",
"dist_to_opt_ops",
"=",
"[",
"]",
"# Running average of the norm of gradient",
"self",
".",
"_grad_norm",
"=",
"tf",
".",
"sqrt",
"(",
"self",
".",
"_grad_norm_squared",
")",
"avg_op",
"=",
"self",
".",
"_moving_aver... | Distance to optimum.
Returns:
D_t ops | [
"Distance",
"to",
"optimum",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L265-L289 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/yellowfin.py | YellowFinOptimizer._grad_sparsity | def _grad_sparsity(self):
"""Gradient sparsity."""
# If the sparse minibatch gradient has 10 percent of its entries
# non-zero, its sparsity is 0.1.
# The norm of dense gradient averaged from full dataset
# are roughly estimated norm of minibatch
# sparse gradient norm * sqrt(sparsity)
# An ... | python | def _grad_sparsity(self):
"""Gradient sparsity."""
# If the sparse minibatch gradient has 10 percent of its entries
# non-zero, its sparsity is 0.1.
# The norm of dense gradient averaged from full dataset
# are roughly estimated norm of minibatch
# sparse gradient norm * sqrt(sparsity)
# An ... | [
"def",
"_grad_sparsity",
"(",
"self",
")",
":",
"# If the sparse minibatch gradient has 10 percent of its entries",
"# non-zero, its sparsity is 0.1.",
"# The norm of dense gradient averaged from full dataset",
"# are roughly estimated norm of minibatch",
"# sparse gradient norm * sqrt(sparsity)... | Gradient sparsity. | [
"Gradient",
"sparsity",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L291-L306 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/yellowfin.py | YellowFinOptimizer._prepare_variables | def _prepare_variables(self):
"""Prepare Variables for YellowFin.
Returns:
Grad**2, Norm, Norm**2, Mean(Norm**2) ops
"""
self._moving_averager = tf.train.ExponentialMovingAverage(
decay=self._beta, zero_debias=self._zero_debias)
# assert self._grad is not None and len(self._grad) > 0
... | python | def _prepare_variables(self):
"""Prepare Variables for YellowFin.
Returns:
Grad**2, Norm, Norm**2, Mean(Norm**2) ops
"""
self._moving_averager = tf.train.ExponentialMovingAverage(
decay=self._beta, zero_debias=self._zero_debias)
# assert self._grad is not None and len(self._grad) > 0
... | [
"def",
"_prepare_variables",
"(",
"self",
")",
":",
"self",
".",
"_moving_averager",
"=",
"tf",
".",
"train",
".",
"ExponentialMovingAverage",
"(",
"decay",
"=",
"self",
".",
"_beta",
",",
"zero_debias",
"=",
"self",
".",
"_zero_debias",
")",
"# assert self._g... | Prepare Variables for YellowFin.
Returns:
Grad**2, Norm, Norm**2, Mean(Norm**2) ops | [
"Prepare",
"Variables",
"for",
"YellowFin",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L308-L349 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/yellowfin.py | YellowFinOptimizer._get_cubic_root | def _get_cubic_root(self):
"""Get the cubic root."""
# We have the equation x^2 D^2 + (1-x)^4 * C / h_min^2
# where x = sqrt(mu).
# We substitute x, which is sqrt(mu), with x = y + 1.
# It gives y^3 + py = q
# where p = (D^2 h_min^2)/(2*C) and q = -p.
# We use the Vieta's substitution to com... | python | def _get_cubic_root(self):
"""Get the cubic root."""
# We have the equation x^2 D^2 + (1-x)^4 * C / h_min^2
# where x = sqrt(mu).
# We substitute x, which is sqrt(mu), with x = y + 1.
# It gives y^3 + py = q
# where p = (D^2 h_min^2)/(2*C) and q = -p.
# We use the Vieta's substitution to com... | [
"def",
"_get_cubic_root",
"(",
"self",
")",
":",
"# We have the equation x^2 D^2 + (1-x)^4 * C / h_min^2",
"# where x = sqrt(mu).",
"# We substitute x, which is sqrt(mu), with x = y + 1.",
"# It gives y^3 + py = q",
"# where p = (D^2 h_min^2)/(2*C) and q = -p.",
"# We use the Vieta's substitut... | Get the cubic root. | [
"Get",
"the",
"cubic",
"root",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L351-L387 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/yellowfin.py | YellowFinOptimizer._get_lr_tensor | def _get_lr_tensor(self):
"""Get lr minimizing the surrogate.
Returns:
The lr_t.
"""
lr = tf.squared_difference(1.0, tf.sqrt(self._mu)) / self._h_min
return lr | python | def _get_lr_tensor(self):
"""Get lr minimizing the surrogate.
Returns:
The lr_t.
"""
lr = tf.squared_difference(1.0, tf.sqrt(self._mu)) / self._h_min
return lr | [
"def",
"_get_lr_tensor",
"(",
"self",
")",
":",
"lr",
"=",
"tf",
".",
"squared_difference",
"(",
"1.0",
",",
"tf",
".",
"sqrt",
"(",
"self",
".",
"_mu",
")",
")",
"/",
"self",
".",
"_h_min",
"return",
"lr"
] | Get lr minimizing the surrogate.
Returns:
The lr_t. | [
"Get",
"lr",
"minimizing",
"the",
"surrogate",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L389-L396 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/yellowfin.py | YellowFinOptimizer._get_mu_tensor | def _get_mu_tensor(self):
"""Get the min mu which minimize the surrogate.
Returns:
The mu_t.
"""
root = self._get_cubic_root()
dr = self._h_max / self._h_min
mu = tf.maximum(
root**2, ((tf.sqrt(dr) - 1) / (tf.sqrt(dr) + 1))**2)
return mu | python | def _get_mu_tensor(self):
"""Get the min mu which minimize the surrogate.
Returns:
The mu_t.
"""
root = self._get_cubic_root()
dr = self._h_max / self._h_min
mu = tf.maximum(
root**2, ((tf.sqrt(dr) - 1) / (tf.sqrt(dr) + 1))**2)
return mu | [
"def",
"_get_mu_tensor",
"(",
"self",
")",
":",
"root",
"=",
"self",
".",
"_get_cubic_root",
"(",
")",
"dr",
"=",
"self",
".",
"_h_max",
"/",
"self",
".",
"_h_min",
"mu",
"=",
"tf",
".",
"maximum",
"(",
"root",
"**",
"2",
",",
"(",
"(",
"tf",
"."... | Get the min mu which minimize the surrogate.
Returns:
The mu_t. | [
"Get",
"the",
"min",
"mu",
"which",
"minimize",
"the",
"surrogate",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L398-L408 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/yellowfin.py | YellowFinOptimizer._yellowfin | def _yellowfin(self):
"""YellowFin auto-tuning optimizer based on momentum SGD.
Returns:
YF ops
(Curvature range,
Grad_variance,
Dist_to_opt,
Single-Step,
Auto-Tuning)
"""
# List for the returned Operations.
yellowfin_ops = []
# Curvature range... | python | def _yellowfin(self):
"""YellowFin auto-tuning optimizer based on momentum SGD.
Returns:
YF ops
(Curvature range,
Grad_variance,
Dist_to_opt,
Single-Step,
Auto-Tuning)
"""
# List for the returned Operations.
yellowfin_ops = []
# Curvature range... | [
"def",
"_yellowfin",
"(",
"self",
")",
":",
"# List for the returned Operations.",
"yellowfin_ops",
"=",
"[",
"]",
"# Curvature range ops.",
"curv_range_ops",
"=",
"self",
".",
"_curvature_range",
"(",
")",
"yellowfin_ops",
"+=",
"curv_range_ops",
"# Estimate of gradient ... | YellowFin auto-tuning optimizer based on momentum SGD.
Returns:
YF ops
(Curvature range,
Grad_variance,
Dist_to_opt,
Single-Step,
Auto-Tuning) | [
"YellowFin",
"auto",
"-",
"tuning",
"optimizer",
"based",
"on",
"momentum",
"SGD",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L410-L454 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/yellowfin.py | YellowFinOptimizer.apply_gradients | def apply_gradients(self, grads_and_vars, global_step=None, name=None):
"""Applying gradients and tune hyperparams with YellowFin.
Args:
grads_and_vars: List of (gradient, variable) pairs as returned by
compute_gradients().
global_step: Optional Variable to increment by one after the
... | python | def apply_gradients(self, grads_and_vars, global_step=None, name=None):
"""Applying gradients and tune hyperparams with YellowFin.
Args:
grads_and_vars: List of (gradient, variable) pairs as returned by
compute_gradients().
global_step: Optional Variable to increment by one after the
... | [
"def",
"apply_gradients",
"(",
"self",
",",
"grads_and_vars",
",",
"global_step",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"self",
".",
"_grad",
",",
"self",
".",
"_vars",
"=",
"zip",
"(",
"*",
"[",
"(",
"g",
",",
"t",
")",
"for",
"g",
",... | Applying gradients and tune hyperparams with YellowFin.
Args:
grads_and_vars: List of (gradient, variable) pairs as returned by
compute_gradients().
global_step: Optional Variable to increment by one after the
variables have been updated.
name: Optional name for the returned oper... | [
"Applying",
"gradients",
"and",
"tune",
"hyperparams",
"with",
"YellowFin",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L460-L519 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/yellowfin.py | YellowFinOptimizer.compute_gradients | def compute_gradients(self,
loss,
var_list,
global_step=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
name=N... | python | def compute_gradients(self,
loss,
var_list,
global_step=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
name=N... | [
"def",
"compute_gradients",
"(",
"self",
",",
"loss",
",",
"var_list",
",",
"global_step",
"=",
"None",
",",
"gate_gradients",
"=",
"GATE_OP",
",",
"aggregation_method",
"=",
"None",
",",
"colocate_gradients_with_ops",
"=",
"False",
",",
"name",
"=",
"None",
"... | Compute gradients through momentum optimizer.
Args:
loss: A Tensor containing the value to minimize.
var_list: Optional list or tuple of tf.Variable to update
to minimize loss. Defaults to the list of variables collected
in the graph under the key GraphKey.TRAINABLE_VARIABLES.
glo... | [
"Compute",
"gradients",
"through",
"momentum",
"optimizer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L521-L560 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/yellowfin.py | YellowFinOptimizer.minimize | def minimize(self,
loss,
global_step=None,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
name=None,
grad_loss=None):
"""Adapted from TensorFlow... | python | def minimize(self,
loss,
global_step=None,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
name=None,
grad_loss=None):
"""Adapted from TensorFlow... | [
"def",
"minimize",
"(",
"self",
",",
"loss",
",",
"global_step",
"=",
"None",
",",
"var_list",
"=",
"None",
",",
"gate_gradients",
"=",
"GATE_OP",
",",
"aggregation_method",
"=",
"None",
",",
"colocate_gradients_with_ops",
"=",
"False",
",",
"name",
"=",
"No... | Adapted from TensorFlow Optimizer base class member function.
Add operations to minimize `loss` by updating `var_list`.
This method simply combines calls `compute_gradients()` and
`apply_gradients()`. If you want to process the gradient before applying
them call `tf.gradients()` and `self.apply_gradien... | [
"Adapted",
"from",
"TensorFlow",
"Optimizer",
"base",
"class",
"member",
"function",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/yellowfin.py#L562-L622 | train |
tensorflow/tensor2tensor | tensor2tensor/models/bytenet.py | residual_dilated_conv | def residual_dilated_conv(x, repeat, padding, name, hparams):
"""A stack of convolution blocks with residual connections."""
with tf.variable_scope(name):
k = (hparams.kernel_height, hparams.kernel_width)
dilations_and_kernels = [((2**i, 1), k)
for i in range(hparams.num_hidden_... | python | def residual_dilated_conv(x, repeat, padding, name, hparams):
"""A stack of convolution blocks with residual connections."""
with tf.variable_scope(name):
k = (hparams.kernel_height, hparams.kernel_width)
dilations_and_kernels = [((2**i, 1), k)
for i in range(hparams.num_hidden_... | [
"def",
"residual_dilated_conv",
"(",
"x",
",",
"repeat",
",",
"padding",
",",
"name",
",",
"hparams",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
")",
":",
"k",
"=",
"(",
"hparams",
".",
"kernel_height",
",",
"hparams",
".",
"kernel_width... | A stack of convolution blocks with residual connections. | [
"A",
"stack",
"of",
"convolution",
"blocks",
"with",
"residual",
"connections",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/bytenet.py#L31-L47 | train |
tensorflow/tensor2tensor | tensor2tensor/models/bytenet.py | bytenet_internal | def bytenet_internal(inputs, targets, hparams):
"""ByteNet, main step used for training."""
with tf.variable_scope("bytenet"):
# Flatten inputs and extend length by 50%.
inputs = tf.expand_dims(common_layers.flatten4d3d(inputs), axis=2)
extend_length = tf.to_int32(0.5 * tf.to_float(tf.shape(inputs)[1]))... | python | def bytenet_internal(inputs, targets, hparams):
"""ByteNet, main step used for training."""
with tf.variable_scope("bytenet"):
# Flatten inputs and extend length by 50%.
inputs = tf.expand_dims(common_layers.flatten4d3d(inputs), axis=2)
extend_length = tf.to_int32(0.5 * tf.to_float(tf.shape(inputs)[1]))... | [
"def",
"bytenet_internal",
"(",
"inputs",
",",
"targets",
",",
"hparams",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"bytenet\"",
")",
":",
"# Flatten inputs and extend length by 50%.",
"inputs",
"=",
"tf",
".",
"expand_dims",
"(",
"common_layers",
".",... | ByteNet, main step used for training. | [
"ByteNet",
"main",
"step",
"used",
"for",
"training",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/bytenet.py#L50-L74 | train |
tensorflow/tensor2tensor | tensor2tensor/models/bytenet.py | bytenet_base | def bytenet_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.batch_size = 2048
hparams.hidden_size = 768
hparams.dropout = 0.2
hparams.symbol_dropout = 0.2
hparams.label_smoothing = 0.1
hparams.clip_grad_norm = 2.0
hparams.num_hidden_layers = 4
hparams.kernel_he... | python | def bytenet_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.batch_size = 2048
hparams.hidden_size = 768
hparams.dropout = 0.2
hparams.symbol_dropout = 0.2
hparams.label_smoothing = 0.1
hparams.clip_grad_norm = 2.0
hparams.num_hidden_layers = 4
hparams.kernel_he... | [
"def",
"bytenet_base",
"(",
")",
":",
"hparams",
"=",
"common_hparams",
".",
"basic_params1",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"2048",
"hparams",
".",
"hidden_size",
"=",
"768",
"hparams",
".",
"dropout",
"=",
"0.2",
"hparams",
".",
"symbol_dropo... | Set of hyperparameters. | [
"Set",
"of",
"hyperparameters",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/bytenet.py#L86-L109 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/snli.py | _download_and_parse_dataset | def _download_and_parse_dataset(tmp_dir, train):
"""Downloads and prepairs the dataset to be parsed by the data_generator."""
file_path = generator_utils.maybe_download(tmp_dir, _SNLI_ZIP, _SNLI_URL)
zip_ref = zipfile.ZipFile(file_path, 'r')
zip_ref.extractall(tmp_dir)
zip_ref.close()
file_name = 'train' i... | python | def _download_and_parse_dataset(tmp_dir, train):
"""Downloads and prepairs the dataset to be parsed by the data_generator."""
file_path = generator_utils.maybe_download(tmp_dir, _SNLI_ZIP, _SNLI_URL)
zip_ref = zipfile.ZipFile(file_path, 'r')
zip_ref.extractall(tmp_dir)
zip_ref.close()
file_name = 'train' i... | [
"def",
"_download_and_parse_dataset",
"(",
"tmp_dir",
",",
"train",
")",
":",
"file_path",
"=",
"generator_utils",
".",
"maybe_download",
"(",
"tmp_dir",
",",
"_SNLI_ZIP",
",",
"_SNLI_URL",
")",
"zip_ref",
"=",
"zipfile",
".",
"ZipFile",
"(",
"file_path",
",",
... | Downloads and prepairs the dataset to be parsed by the data_generator. | [
"Downloads",
"and",
"prepairs",
"the",
"dataset",
"to",
"be",
"parsed",
"by",
"the",
"data_generator",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/snli.py#L51-L60 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/snli.py | _get_tokens_and_tags | def _get_tokens_and_tags(parse_str):
"""Parse str to tokens and pos tags."""
tokens = []
parse_split = parse_str.split(' ')
for p in parse_split:
assert p.startswith('(') or p.endswith(')')
if p.endswith(')'):
token = p.replace(')', '')
tokens.append(token)
return tokens | python | def _get_tokens_and_tags(parse_str):
"""Parse str to tokens and pos tags."""
tokens = []
parse_split = parse_str.split(' ')
for p in parse_split:
assert p.startswith('(') or p.endswith(')')
if p.endswith(')'):
token = p.replace(')', '')
tokens.append(token)
return tokens | [
"def",
"_get_tokens_and_tags",
"(",
"parse_str",
")",
":",
"tokens",
"=",
"[",
"]",
"parse_split",
"=",
"parse_str",
".",
"split",
"(",
"' '",
")",
"for",
"p",
"in",
"parse_split",
":",
"assert",
"p",
".",
"startswith",
"(",
"'('",
")",
"or",
"p",
".",... | Parse str to tokens and pos tags. | [
"Parse",
"str",
"to",
"tokens",
"and",
"pos",
"tags",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/snli.py#L63-L73 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/snli.py | _parse_dataset | def _parse_dataset(file_path, tmp_dir, train):
"""Convert the dataset in to a simpler format.
This function creates two files. One for being processed to produce a vocab
and another to generate the data.
Args:
file_path: string, path to the file to parse.
tmp_dir: string, path to the directory to outp... | python | def _parse_dataset(file_path, tmp_dir, train):
"""Convert the dataset in to a simpler format.
This function creates two files. One for being processed to produce a vocab
and another to generate the data.
Args:
file_path: string, path to the file to parse.
tmp_dir: string, path to the directory to outp... | [
"def",
"_parse_dataset",
"(",
"file_path",
",",
"tmp_dir",
",",
"train",
")",
":",
"input_path",
"=",
"file_path",
"file_name",
"=",
"'train'",
"if",
"train",
"else",
"'dev'",
"gen_output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmp_dir",
",",
"fi... | Convert the dataset in to a simpler format.
This function creates two files. One for being processed to produce a vocab
and another to generate the data.
Args:
file_path: string, path to the file to parse.
tmp_dir: string, path to the directory to output the files.
train: bool, indicating if we are ... | [
"Convert",
"the",
"dataset",
"in",
"to",
"a",
"simpler",
"format",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/snli.py#L76-L128 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/snli.py | _get_or_generate_vocab | def _get_or_generate_vocab(tmp_dir, vocab_filename, vocab_size):
"""Read or create vocabulary."""
vocab_filepath = os.path.join(tmp_dir, vocab_filename)
print('Vocab file written to: ' + vocab_filepath)
if tf.gfile.Exists(vocab_filepath):
gs = text_encoder.SubwordTextEncoder(vocab_filepath)
return gs
... | python | def _get_or_generate_vocab(tmp_dir, vocab_filename, vocab_size):
"""Read or create vocabulary."""
vocab_filepath = os.path.join(tmp_dir, vocab_filename)
print('Vocab file written to: ' + vocab_filepath)
if tf.gfile.Exists(vocab_filepath):
gs = text_encoder.SubwordTextEncoder(vocab_filepath)
return gs
... | [
"def",
"_get_or_generate_vocab",
"(",
"tmp_dir",
",",
"vocab_filename",
",",
"vocab_size",
")",
":",
"vocab_filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmp_dir",
",",
"vocab_filename",
")",
"print",
"(",
"'Vocab file written to: '",
"+",
"vocab_filepath"... | Read or create vocabulary. | [
"Read",
"or",
"create",
"vocabulary",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/snli.py#L131-L146 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/snli.py | snli_token_generator | def snli_token_generator(tmp_dir, train, vocab_size):
"""Generate example dicts."""
_download_and_parse_dataset(tmp_dir, train)
symbolizer_vocab = _get_or_generate_vocab(
tmp_dir, 'vocab.subword_text_encoder', vocab_size)
file_name = 'train' if train else 'dev'
data_file = os.path.join(tmp_dir, file_n... | python | def snli_token_generator(tmp_dir, train, vocab_size):
"""Generate example dicts."""
_download_and_parse_dataset(tmp_dir, train)
symbolizer_vocab = _get_or_generate_vocab(
tmp_dir, 'vocab.subword_text_encoder', vocab_size)
file_name = 'train' if train else 'dev'
data_file = os.path.join(tmp_dir, file_n... | [
"def",
"snli_token_generator",
"(",
"tmp_dir",
",",
"train",
",",
"vocab_size",
")",
":",
"_download_and_parse_dataset",
"(",
"tmp_dir",
",",
"train",
")",
"symbolizer_vocab",
"=",
"_get_or_generate_vocab",
"(",
"tmp_dir",
",",
"'vocab.subword_text_encoder'",
",",
"vo... | Generate example dicts. | [
"Generate",
"example",
"dicts",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/snli.py#L149-L168 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wikisum/get_references_web_single_group.py | shard | def shard(items, num_shards):
"""Split items into num_shards groups."""
sharded = []
num_per_shard = len(items) // num_shards
start = 0
for _ in range(num_shards):
sharded.append(items[start:start + num_per_shard])
start += num_per_shard
remainder = len(items) % num_shards
start = len(items) - re... | python | def shard(items, num_shards):
"""Split items into num_shards groups."""
sharded = []
num_per_shard = len(items) // num_shards
start = 0
for _ in range(num_shards):
sharded.append(items[start:start + num_per_shard])
start += num_per_shard
remainder = len(items) % num_shards
start = len(items) - re... | [
"def",
"shard",
"(",
"items",
",",
"num_shards",
")",
":",
"sharded",
"=",
"[",
"]",
"num_per_shard",
"=",
"len",
"(",
"items",
")",
"//",
"num_shards",
"start",
"=",
"0",
"for",
"_",
"in",
"range",
"(",
"num_shards",
")",
":",
"sharded",
".",
"appen... | Split items into num_shards groups. | [
"Split",
"items",
"into",
"num_shards",
"groups",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/get_references_web_single_group.py#L87-L102 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/core.py | RandomNormalInitializer | def RandomNormalInitializer(stddev=1e-2):
"""An initializer function for random normal coefficients."""
def init(shape, rng):
return (stddev * backend.random.normal(rng, shape)).astype('float32')
return init | python | def RandomNormalInitializer(stddev=1e-2):
"""An initializer function for random normal coefficients."""
def init(shape, rng):
return (stddev * backend.random.normal(rng, shape)).astype('float32')
return init | [
"def",
"RandomNormalInitializer",
"(",
"stddev",
"=",
"1e-2",
")",
":",
"def",
"init",
"(",
"shape",
",",
"rng",
")",
":",
"return",
"(",
"stddev",
"*",
"backend",
".",
"random",
".",
"normal",
"(",
"rng",
",",
"shape",
")",
")",
".",
"astype",
"(",
... | An initializer function for random normal coefficients. | [
"An",
"initializer",
"function",
"for",
"random",
"normal",
"coefficients",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L42-L46 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/core.py | GlorotNormalInitializer | def GlorotNormalInitializer(out_dim=0, in_dim=1, scale=onp.sqrt(2)):
"""An initializer function for random Glorot-scaled coefficients."""
def init(shape, rng):
fan_in, fan_out = shape[in_dim], shape[out_dim]
size = onp.prod(onp.delete(shape, [in_dim, out_dim]))
std = scale / np.sqrt((fan_in + fan_out) /... | python | def GlorotNormalInitializer(out_dim=0, in_dim=1, scale=onp.sqrt(2)):
"""An initializer function for random Glorot-scaled coefficients."""
def init(shape, rng):
fan_in, fan_out = shape[in_dim], shape[out_dim]
size = onp.prod(onp.delete(shape, [in_dim, out_dim]))
std = scale / np.sqrt((fan_in + fan_out) /... | [
"def",
"GlorotNormalInitializer",
"(",
"out_dim",
"=",
"0",
",",
"in_dim",
"=",
"1",
",",
"scale",
"=",
"onp",
".",
"sqrt",
"(",
"2",
")",
")",
":",
"def",
"init",
"(",
"shape",
",",
"rng",
")",
":",
"fan_in",
",",
"fan_out",
"=",
"shape",
"[",
"... | An initializer function for random Glorot-scaled coefficients. | [
"An",
"initializer",
"function",
"for",
"random",
"Glorot",
"-",
"scaled",
"coefficients",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L49-L56 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/core.py | GlorotUniformInitializer | def GlorotUniformInitializer(out_dim=0, in_dim=1):
"""An initializer function for random uniform Glorot-scaled coefficients."""
def init(shape, rng):
fan_in, fan_out = shape[in_dim], shape[out_dim]
std = np.sqrt(2.0 / (fan_in + fan_out))
a = np.sqrt(3.0) * std
return backend.random.uniform(rng, shap... | python | def GlorotUniformInitializer(out_dim=0, in_dim=1):
"""An initializer function for random uniform Glorot-scaled coefficients."""
def init(shape, rng):
fan_in, fan_out = shape[in_dim], shape[out_dim]
std = np.sqrt(2.0 / (fan_in + fan_out))
a = np.sqrt(3.0) * std
return backend.random.uniform(rng, shap... | [
"def",
"GlorotUniformInitializer",
"(",
"out_dim",
"=",
"0",
",",
"in_dim",
"=",
"1",
")",
":",
"def",
"init",
"(",
"shape",
",",
"rng",
")",
":",
"fan_in",
",",
"fan_out",
"=",
"shape",
"[",
"in_dim",
"]",
",",
"shape",
"[",
"out_dim",
"]",
"std",
... | An initializer function for random uniform Glorot-scaled coefficients. | [
"An",
"initializer",
"function",
"for",
"random",
"uniform",
"Glorot",
"-",
"scaled",
"coefficients",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L59-L66 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/core.py | one_hot | def one_hot(x, size, dtype=np.float32):
"""Make a n+1 dim one-hot array from n dim int-categorical array."""
return np.array(x[..., np.newaxis] == np.arange(size), dtype) | python | def one_hot(x, size, dtype=np.float32):
"""Make a n+1 dim one-hot array from n dim int-categorical array."""
return np.array(x[..., np.newaxis] == np.arange(size), dtype) | [
"def",
"one_hot",
"(",
"x",
",",
"size",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
":",
"return",
"np",
".",
"array",
"(",
"x",
"[",
"...",
",",
"np",
".",
"newaxis",
"]",
"==",
"np",
".",
"arange",
"(",
"size",
")",
",",
"dtype",
")"
] | Make a n+1 dim one-hot array from n dim int-categorical array. | [
"Make",
"a",
"n",
"+",
"1",
"dim",
"one",
"-",
"hot",
"array",
"from",
"n",
"dim",
"int",
"-",
"categorical",
"array",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L69-L71 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/core.py | LogSoftmax | def LogSoftmax(x, params, axis=-1, **kwargs):
"""Apply log softmax to x: log-normalize along the given axis."""
del params, kwargs
return x - backend.logsumexp(x, axis, keepdims=True) | python | def LogSoftmax(x, params, axis=-1, **kwargs):
"""Apply log softmax to x: log-normalize along the given axis."""
del params, kwargs
return x - backend.logsumexp(x, axis, keepdims=True) | [
"def",
"LogSoftmax",
"(",
"x",
",",
"params",
",",
"axis",
"=",
"-",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"params",
",",
"kwargs",
"return",
"x",
"-",
"backend",
".",
"logsumexp",
"(",
"x",
",",
"axis",
",",
"keepdims",
"=",
"True",
")"... | Apply log softmax to x: log-normalize along the given axis. | [
"Apply",
"log",
"softmax",
"to",
"x",
":",
"log",
"-",
"normalize",
"along",
"the",
"given",
"axis",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L116-L119 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/core.py | Softmax | def Softmax(x, params, axis=-1, **kwargs):
"""Apply softmax to x: exponentiate and normalize along the given axis."""
del params, kwargs
return np.exp(x - backend.logsumexp(x, axis, keepdims=True)) | python | def Softmax(x, params, axis=-1, **kwargs):
"""Apply softmax to x: exponentiate and normalize along the given axis."""
del params, kwargs
return np.exp(x - backend.logsumexp(x, axis, keepdims=True)) | [
"def",
"Softmax",
"(",
"x",
",",
"params",
",",
"axis",
"=",
"-",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"params",
",",
"kwargs",
"return",
"np",
".",
"exp",
"(",
"x",
"-",
"backend",
".",
"logsumexp",
"(",
"x",
",",
"axis",
",",
"keepd... | Apply softmax to x: exponentiate and normalize along the given axis. | [
"Apply",
"softmax",
"to",
"x",
":",
"exponentiate",
"and",
"normalize",
"along",
"the",
"given",
"axis",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L123-L126 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/core.py | padtype_to_pads | def padtype_to_pads(in_shape, window_shape, window_strides, padding):
"""Convert padding string to list of pairs of pad values."""
padding = padding.upper()
if padding == 'SAME':
out_shape = onp.ceil(
onp.true_divide(in_shape, window_strides)).astype(int)
pad_sizes = [max((out_size - 1) * stride +... | python | def padtype_to_pads(in_shape, window_shape, window_strides, padding):
"""Convert padding string to list of pairs of pad values."""
padding = padding.upper()
if padding == 'SAME':
out_shape = onp.ceil(
onp.true_divide(in_shape, window_strides)).astype(int)
pad_sizes = [max((out_size - 1) * stride +... | [
"def",
"padtype_to_pads",
"(",
"in_shape",
",",
"window_shape",
",",
"window_strides",
",",
"padding",
")",
":",
"padding",
"=",
"padding",
".",
"upper",
"(",
")",
"if",
"padding",
"==",
"'SAME'",
":",
"out_shape",
"=",
"onp",
".",
"ceil",
"(",
"onp",
".... | Convert padding string to list of pairs of pad values. | [
"Convert",
"padding",
"string",
"to",
"list",
"of",
"pairs",
"of",
"pad",
"values",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L181-L196 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/core.py | _flatten_output_shape | def _flatten_output_shape(input_shape, num_axis_to_keep=1):
"""Output shape of a flatten layer."""
if num_axis_to_keep >= len(input_shape):
raise ValueError(
"num_axis_to_keep[%d] should be less than input's rank[%d]" %
(num_axis_to_keep, len(input_shape)))
return tuple(input_shape[:num_axis_t... | python | def _flatten_output_shape(input_shape, num_axis_to_keep=1):
"""Output shape of a flatten layer."""
if num_axis_to_keep >= len(input_shape):
raise ValueError(
"num_axis_to_keep[%d] should be less than input's rank[%d]" %
(num_axis_to_keep, len(input_shape)))
return tuple(input_shape[:num_axis_t... | [
"def",
"_flatten_output_shape",
"(",
"input_shape",
",",
"num_axis_to_keep",
"=",
"1",
")",
":",
"if",
"num_axis_to_keep",
">=",
"len",
"(",
"input_shape",
")",
":",
"raise",
"ValueError",
"(",
"\"num_axis_to_keep[%d] should be less than input's rank[%d]\"",
"%",
"(",
... | Output shape of a flatten layer. | [
"Output",
"shape",
"of",
"a",
"flatten",
"layer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L304-L311 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/core.py | _batch_norm_new_params | def _batch_norm_new_params(input_shape, rng, axis=(0, 1, 2),
center=True, scale=True, **kwargs):
"""Helper to initialize batch norm params."""
del rng, kwargs
axis = (axis,) if np.isscalar(axis) else axis
shape = tuple(d for i, d in enumerate(input_shape) if i not in axis)
beta = np... | python | def _batch_norm_new_params(input_shape, rng, axis=(0, 1, 2),
center=True, scale=True, **kwargs):
"""Helper to initialize batch norm params."""
del rng, kwargs
axis = (axis,) if np.isscalar(axis) else axis
shape = tuple(d for i, d in enumerate(input_shape) if i not in axis)
beta = np... | [
"def",
"_batch_norm_new_params",
"(",
"input_shape",
",",
"rng",
",",
"axis",
"=",
"(",
"0",
",",
"1",
",",
"2",
")",
",",
"center",
"=",
"True",
",",
"scale",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"rng",
",",
"kwargs",
"axis",
"... | Helper to initialize batch norm params. | [
"Helper",
"to",
"initialize",
"batch",
"norm",
"params",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L321-L329 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/core.py | BatchNorm | def BatchNorm(x, params, axis=(0, 1, 2), epsilon=1e-5,
center=True, scale=True, **unused_kwargs):
"""Layer construction function for a batch normalization layer."""
mean = np.mean(x, axis, keepdims=True)
# Fast but less numerically-stable variance calculation than np.var.
m1 = np.mean(x**2, axis, ... | python | def BatchNorm(x, params, axis=(0, 1, 2), epsilon=1e-5,
center=True, scale=True, **unused_kwargs):
"""Layer construction function for a batch normalization layer."""
mean = np.mean(x, axis, keepdims=True)
# Fast but less numerically-stable variance calculation than np.var.
m1 = np.mean(x**2, axis, ... | [
"def",
"BatchNorm",
"(",
"x",
",",
"params",
",",
"axis",
"=",
"(",
"0",
",",
"1",
",",
"2",
")",
",",
"epsilon",
"=",
"1e-5",
",",
"center",
"=",
"True",
",",
"scale",
"=",
"True",
",",
"*",
"*",
"unused_kwargs",
")",
":",
"mean",
"=",
"np",
... | Layer construction function for a batch normalization layer. | [
"Layer",
"construction",
"function",
"for",
"a",
"batch",
"normalization",
"layer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L333-L357 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/core.py | _pooling_output_shape | def _pooling_output_shape(input_shape, pool_size=(2, 2),
strides=None, padding='VALID'):
"""Helper: compute the output shape for the pooling layer."""
dims = (1,) + pool_size + (1,) # NHWC
spatial_strides = strides or (1,) * len(pool_size)
strides = (1,) + spatial_strides + (1,)
pad... | python | def _pooling_output_shape(input_shape, pool_size=(2, 2),
strides=None, padding='VALID'):
"""Helper: compute the output shape for the pooling layer."""
dims = (1,) + pool_size + (1,) # NHWC
spatial_strides = strides or (1,) * len(pool_size)
strides = (1,) + spatial_strides + (1,)
pad... | [
"def",
"_pooling_output_shape",
"(",
"input_shape",
",",
"pool_size",
"=",
"(",
"2",
",",
"2",
")",
",",
"strides",
"=",
"None",
",",
"padding",
"=",
"'VALID'",
")",
":",
"dims",
"=",
"(",
"1",
",",
")",
"+",
"pool_size",
"+",
"(",
"1",
",",
")",
... | Helper: compute the output shape for the pooling layer. | [
"Helper",
":",
"compute",
"the",
"output",
"shape",
"for",
"the",
"pooling",
"layer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L361-L370 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/core.py | _pooling_general | def _pooling_general(inputs, reducer, init_val, rescaler=None,
pool_size=(2, 2), strides=None, padding='VALID'):
"""Helper: general pooling computation used in pooling layers later."""
spatial_strides = strides or (1,) * len(pool_size)
rescale = rescaler(pool_size, spatial_strides, padding) i... | python | def _pooling_general(inputs, reducer, init_val, rescaler=None,
pool_size=(2, 2), strides=None, padding='VALID'):
"""Helper: general pooling computation used in pooling layers later."""
spatial_strides = strides or (1,) * len(pool_size)
rescale = rescaler(pool_size, spatial_strides, padding) i... | [
"def",
"_pooling_general",
"(",
"inputs",
",",
"reducer",
",",
"init_val",
",",
"rescaler",
"=",
"None",
",",
"pool_size",
"=",
"(",
"2",
",",
"2",
")",
",",
"strides",
"=",
"None",
",",
"padding",
"=",
"'VALID'",
")",
":",
"spatial_strides",
"=",
"str... | Helper: general pooling computation used in pooling layers later. | [
"Helper",
":",
"general",
"pooling",
"computation",
"used",
"in",
"pooling",
"layers",
"later",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L373-L381 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/core.py | Dropout | def Dropout(x, params, rate=0.0, mode='train', rng=None, **kwargs):
"""Layer construction function for a dropout layer with given rate."""
del params, kwargs
if rng is None:
msg = ('Dropout layer requires apply_fun to be called with a rng keyword '
'argument. That is, instead of `Dropout(params, in... | python | def Dropout(x, params, rate=0.0, mode='train', rng=None, **kwargs):
"""Layer construction function for a dropout layer with given rate."""
del params, kwargs
if rng is None:
msg = ('Dropout layer requires apply_fun to be called with a rng keyword '
'argument. That is, instead of `Dropout(params, in... | [
"def",
"Dropout",
"(",
"x",
",",
"params",
",",
"rate",
"=",
"0.0",
",",
"mode",
"=",
"'train'",
",",
"rng",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"params",
",",
"kwargs",
"if",
"rng",
"is",
"None",
":",
"msg",
"=",
"(",
"'Drop... | Layer construction function for a dropout layer with given rate. | [
"Layer",
"construction",
"function",
"for",
"a",
"dropout",
"layer",
"with",
"given",
"rate",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L415-L429 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/core.py | Conv._kernel_shape | def _kernel_shape(self, input_shape):
"""Helper to calculate the kernel shape."""
kernel_size_iter = iter(self._kernel_size)
return [self._filters if c == 'O' else
input_shape[self._lhs_spec.index('C')] if c == 'I' else
next(kernel_size_iter) for c in self._rhs_spec] | python | def _kernel_shape(self, input_shape):
"""Helper to calculate the kernel shape."""
kernel_size_iter = iter(self._kernel_size)
return [self._filters if c == 'O' else
input_shape[self._lhs_spec.index('C')] if c == 'I' else
next(kernel_size_iter) for c in self._rhs_spec] | [
"def",
"_kernel_shape",
"(",
"self",
",",
"input_shape",
")",
":",
"kernel_size_iter",
"=",
"iter",
"(",
"self",
".",
"_kernel_size",
")",
"return",
"[",
"self",
".",
"_filters",
"if",
"c",
"==",
"'O'",
"else",
"input_shape",
"[",
"self",
".",
"_lhs_spec",... | Helper to calculate the kernel shape. | [
"Helper",
"to",
"calculate",
"the",
"kernel",
"shape",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L226-L231 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/core.py | Conv._conv_shape_tuple | def _conv_shape_tuple(self, lhs_shape, rhs_shape, strides, pads):
"""Compute the shape of a conv given input shapes in canonical order."""
if isinstance(pads, str):
pads = padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads)
if len(pads) != len(lhs_shape) - 2:
msg = 'Wrong number of expl... | python | def _conv_shape_tuple(self, lhs_shape, rhs_shape, strides, pads):
"""Compute the shape of a conv given input shapes in canonical order."""
if isinstance(pads, str):
pads = padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads)
if len(pads) != len(lhs_shape) - 2:
msg = 'Wrong number of expl... | [
"def",
"_conv_shape_tuple",
"(",
"self",
",",
"lhs_shape",
",",
"rhs_shape",
",",
"strides",
",",
"pads",
")",
":",
"if",
"isinstance",
"(",
"pads",
",",
"str",
")",
":",
"pads",
"=",
"padtype_to_pads",
"(",
"lhs_shape",
"[",
"2",
":",
"]",
",",
"rhs_s... | Compute the shape of a conv given input shapes in canonical order. | [
"Compute",
"the",
"shape",
"of",
"a",
"conv",
"given",
"input",
"shapes",
"in",
"canonical",
"order",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L233-L245 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/core.py | Conv._conv_general_permutations | def _conv_general_permutations(self, dimension_numbers):
"""Utility for convolution dimension permutations relative to Conv HLO."""
lhs_spec, rhs_spec, out_spec = dimension_numbers
lhs_char, rhs_char, out_char = ('N', 'C'), ('O', 'I'), ('N', 'C')
charpairs = (lhs_char, rhs_char, out_char)
for i, (a,... | python | def _conv_general_permutations(self, dimension_numbers):
"""Utility for convolution dimension permutations relative to Conv HLO."""
lhs_spec, rhs_spec, out_spec = dimension_numbers
lhs_char, rhs_char, out_char = ('N', 'C'), ('O', 'I'), ('N', 'C')
charpairs = (lhs_char, rhs_char, out_char)
for i, (a,... | [
"def",
"_conv_general_permutations",
"(",
"self",
",",
"dimension_numbers",
")",
":",
"lhs_spec",
",",
"rhs_spec",
",",
"out_spec",
"=",
"dimension_numbers",
"lhs_char",
",",
"rhs_char",
",",
"out_char",
"=",
"(",
"'N'",
",",
"'C'",
")",
",",
"(",
"'O'",
","... | Utility for convolution dimension permutations relative to Conv HLO. | [
"Utility",
"for",
"convolution",
"dimension",
"permutations",
"relative",
"to",
"Conv",
"HLO",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L247-L275 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/core.py | Conv._conv_general_shape_tuple | def _conv_general_shape_tuple(self, lhs_shape, rhs_shape, window_strides,
padding, dimension_numbers):
"""Generalized computation of conv shape."""
lhs_perm, rhs_perm, out_perm = self._conv_general_permutations(
dimension_numbers)
lhs_trans = onp.take(lhs_shape, lhs_p... | python | def _conv_general_shape_tuple(self, lhs_shape, rhs_shape, window_strides,
padding, dimension_numbers):
"""Generalized computation of conv shape."""
lhs_perm, rhs_perm, out_perm = self._conv_general_permutations(
dimension_numbers)
lhs_trans = onp.take(lhs_shape, lhs_p... | [
"def",
"_conv_general_shape_tuple",
"(",
"self",
",",
"lhs_shape",
",",
"rhs_shape",
",",
"window_strides",
",",
"padding",
",",
"dimension_numbers",
")",
":",
"lhs_perm",
",",
"rhs_perm",
",",
"out_perm",
"=",
"self",
".",
"_conv_general_permutations",
"(",
"dime... | Generalized computation of conv shape. | [
"Generalized",
"computation",
"of",
"conv",
"shape",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L277-L286 | train |
tensorflow/tensor2tensor | tensor2tensor/rl/dopamine_connector.py | get_create_agent | def get_create_agent(agent_kwargs):
"""Factory for dopamine agent initialization.
Args:
agent_kwargs: dict of BatchDQNAgent parameters
Returns:
Function(sess, environment, summary_writer) -> BatchDQNAgent instance.
"""
def create_agent(sess, environment, summary_writer=None):
"""Creates a DQN a... | python | def get_create_agent(agent_kwargs):
"""Factory for dopamine agent initialization.
Args:
agent_kwargs: dict of BatchDQNAgent parameters
Returns:
Function(sess, environment, summary_writer) -> BatchDQNAgent instance.
"""
def create_agent(sess, environment, summary_writer=None):
"""Creates a DQN a... | [
"def",
"get_create_agent",
"(",
"agent_kwargs",
")",
":",
"def",
"create_agent",
"(",
"sess",
",",
"environment",
",",
"summary_writer",
"=",
"None",
")",
":",
"\"\"\"Creates a DQN agent.\n\n Simplified version of `dopamine.discrete_domains.train.create_agent`\n\n Args:\n ... | Factory for dopamine agent initialization.
Args:
agent_kwargs: dict of BatchDQNAgent parameters
Returns:
Function(sess, environment, summary_writer) -> BatchDQNAgent instance. | [
"Factory",
"for",
"dopamine",
"agent",
"initialization",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/dopamine_connector.py#L274-L305 | train |
tensorflow/tensor2tensor | tensor2tensor/rl/dopamine_connector.py | get_create_batch_env_fun | def get_create_batch_env_fun(batch_env_fn, time_limit):
"""Factory for dopamine environment initialization function.
Args:
batch_env_fn: function(in_graph: bool) -> batch environment.
time_limit: time steps limit for environment.
Returns:
function (with optional, unused parameters) initializing envi... | python | def get_create_batch_env_fun(batch_env_fn, time_limit):
"""Factory for dopamine environment initialization function.
Args:
batch_env_fn: function(in_graph: bool) -> batch environment.
time_limit: time steps limit for environment.
Returns:
function (with optional, unused parameters) initializing envi... | [
"def",
"get_create_batch_env_fun",
"(",
"batch_env_fn",
",",
"time_limit",
")",
":",
"def",
"create_env_fun",
"(",
"game_name",
"=",
"None",
",",
"sticky_actions",
"=",
"None",
")",
":",
"del",
"game_name",
",",
"sticky_actions",
"batch_env",
"=",
"batch_env_fn",
... | Factory for dopamine environment initialization function.
Args:
batch_env_fn: function(in_graph: bool) -> batch environment.
time_limit: time steps limit for environment.
Returns:
function (with optional, unused parameters) initializing environment. | [
"Factory",
"for",
"dopamine",
"environment",
"initialization",
"function",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/dopamine_connector.py#L450-L468 | train |
tensorflow/tensor2tensor | tensor2tensor/rl/dopamine_connector.py | _parse_hparams | def _parse_hparams(hparams):
"""Split hparams, based on key prefixes.
Args:
hparams: hyperparameters
Returns:
Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer.
"""
prefixes = ["agent_", "optimizer_", "runner_", "replay_buffer_"]
ret = []
for prefix in prefixes:
ret_... | python | def _parse_hparams(hparams):
"""Split hparams, based on key prefixes.
Args:
hparams: hyperparameters
Returns:
Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer.
"""
prefixes = ["agent_", "optimizer_", "runner_", "replay_buffer_"]
ret = []
for prefix in prefixes:
ret_... | [
"def",
"_parse_hparams",
"(",
"hparams",
")",
":",
"prefixes",
"=",
"[",
"\"agent_\"",
",",
"\"optimizer_\"",
",",
"\"runner_\"",
",",
"\"replay_buffer_\"",
"]",
"ret",
"=",
"[",
"]",
"for",
"prefix",
"in",
"prefixes",
":",
"ret_dict",
"=",
"{",
"}",
"for"... | Split hparams, based on key prefixes.
Args:
hparams: hyperparameters
Returns:
Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer. | [
"Split",
"hparams",
"based",
"on",
"key",
"prefixes",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/dopamine_connector.py#L471-L491 | train |
tensorflow/tensor2tensor | tensor2tensor/rl/dopamine_connector.py | _DQNAgent._build_replay_buffer | def _build_replay_buffer(self, use_staging):
"""Build WrappedReplayBuffer with custom OutOfGraphReplayBuffer."""
replay_buffer_kwargs = dict(
observation_shape=dqn_agent.NATURE_DQN_OBSERVATION_SHAPE,
stack_size=dqn_agent.NATURE_DQN_STACK_SIZE,
replay_capacity=self._replay_capacity,
... | python | def _build_replay_buffer(self, use_staging):
"""Build WrappedReplayBuffer with custom OutOfGraphReplayBuffer."""
replay_buffer_kwargs = dict(
observation_shape=dqn_agent.NATURE_DQN_OBSERVATION_SHAPE,
stack_size=dqn_agent.NATURE_DQN_STACK_SIZE,
replay_capacity=self._replay_capacity,
... | [
"def",
"_build_replay_buffer",
"(",
"self",
",",
"use_staging",
")",
":",
"replay_buffer_kwargs",
"=",
"dict",
"(",
"observation_shape",
"=",
"dqn_agent",
".",
"NATURE_DQN_OBSERVATION_SHAPE",
",",
"stack_size",
"=",
"dqn_agent",
".",
"NATURE_DQN_STACK_SIZE",
",",
"rep... | Build WrappedReplayBuffer with custom OutOfGraphReplayBuffer. | [
"Build",
"WrappedReplayBuffer",
"with",
"custom",
"OutOfGraphReplayBuffer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/dopamine_connector.py#L60-L79 | train |
tensorflow/tensor2tensor | tensor2tensor/rl/dopamine_connector.py | _OutOfGraphReplayBuffer.add | def add(self, observation, action, reward, terminal, *args):
"""Append artificial_done to *args and run parent method."""
# If this will be a problem for maintenance, we could probably override
# DQNAgent.add() method instead.
artificial_done = self._artificial_done and terminal
args = list(args)
... | python | def add(self, observation, action, reward, terminal, *args):
"""Append artificial_done to *args and run parent method."""
# If this will be a problem for maintenance, we could probably override
# DQNAgent.add() method instead.
artificial_done = self._artificial_done and terminal
args = list(args)
... | [
"def",
"add",
"(",
"self",
",",
"observation",
",",
"action",
",",
"reward",
",",
"terminal",
",",
"*",
"args",
")",
":",
"# If this will be a problem for maintenance, we could probably override",
"# DQNAgent.add() method instead.",
"artificial_done",
"=",
"self",
".",
... | Append artificial_done to *args and run parent method. | [
"Append",
"artificial_done",
"to",
"*",
"args",
"and",
"run",
"parent",
"method",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/dopamine_connector.py#L257-L265 | train |
tensorflow/tensor2tensor | tensor2tensor/rl/dopamine_connector.py | DopamineBatchEnv.step | def step(self, actions):
"""Step."""
self._elapsed_steps += 1
obs, rewards, dones = \
[np.array(r) for r in self.batch_env.step(actions)]
if self._elapsed_steps > self._max_episode_steps:
done = True
if self._elapsed_steps > self._max_episode_steps + 1:
rewards.fill(0)
el... | python | def step(self, actions):
"""Step."""
self._elapsed_steps += 1
obs, rewards, dones = \
[np.array(r) for r in self.batch_env.step(actions)]
if self._elapsed_steps > self._max_episode_steps:
done = True
if self._elapsed_steps > self._max_episode_steps + 1:
rewards.fill(0)
el... | [
"def",
"step",
"(",
"self",
",",
"actions",
")",
":",
"self",
".",
"_elapsed_steps",
"+=",
"1",
"obs",
",",
"rewards",
",",
"dones",
"=",
"[",
"np",
".",
"array",
"(",
"r",
")",
"for",
"r",
"in",
"self",
".",
"batch_env",
".",
"step",
"(",
"actio... | Step. | [
"Step",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/dopamine_connector.py#L371-L388 | train |
tensorflow/tensor2tensor | tensor2tensor/models/text_cnn.py | text_cnn_base | def text_cnn_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.batch_size = 4096
hparams.max_length = 256
hparams.clip_grad_norm = 0. # i.e. no gradient clipping
hparams.optimizer_adam_epsilon = 1e-9
hparams.learning_rate_schedule = "legacy"
hparams.learning_rate_de... | python | def text_cnn_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.batch_size = 4096
hparams.max_length = 256
hparams.clip_grad_norm = 0. # i.e. no gradient clipping
hparams.optimizer_adam_epsilon = 1e-9
hparams.learning_rate_schedule = "legacy"
hparams.learning_rate_de... | [
"def",
"text_cnn_base",
"(",
")",
":",
"hparams",
"=",
"common_hparams",
".",
"basic_params1",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"4096",
"hparams",
".",
"max_length",
"=",
"256",
"hparams",
".",
"clip_grad_norm",
"=",
"0.",
"# i.e. no gradient clippin... | Set of hyperparameters. | [
"Set",
"of",
"hyperparameters",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/text_cnn.py#L86-L112 | train |
tensorflow/tensor2tensor | tensor2tensor/models/video/next_frame_glow.py | next_frame_glow_hparams | def next_frame_glow_hparams():
"""Hparams for next_frame_glow."""
hparams = glow.glow_hparams()
# Possible modes are conditional and unconditional
hparams.add_hparam("gen_mode", "conditional")
hparams.add_hparam("learn_top_scale", False)
hparams.add_hparam("condition_all_levels", True)
# For each video, s... | python | def next_frame_glow_hparams():
"""Hparams for next_frame_glow."""
hparams = glow.glow_hparams()
# Possible modes are conditional and unconditional
hparams.add_hparam("gen_mode", "conditional")
hparams.add_hparam("learn_top_scale", False)
hparams.add_hparam("condition_all_levels", True)
# For each video, s... | [
"def",
"next_frame_glow_hparams",
"(",
")",
":",
"hparams",
"=",
"glow",
".",
"glow_hparams",
"(",
")",
"# Possible modes are conditional and unconditional",
"hparams",
".",
"add_hparam",
"(",
"\"gen_mode\"",
",",
"\"conditional\"",
")",
"hparams",
".",
"add_hparam",
... | Hparams for next_frame_glow. | [
"Hparams",
"for",
"next_frame_glow",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/next_frame_glow.py#L37-L87 | train |
tensorflow/tensor2tensor | tensor2tensor/models/video/next_frame_glow.py | next_frame_glow_bair_quant | def next_frame_glow_bair_quant():
"""Hparams to reproduce bits-per-pixel results on BAIR action-free dataset."""
hparams = next_frame_glow_hparams()
hparams.video_num_input_frames = 3
hparams.video_num_target_frames = 10
hparams.num_train_frames = 4
hparams.num_cond_latents = 3
hparams.depth = 24
hparam... | python | def next_frame_glow_bair_quant():
"""Hparams to reproduce bits-per-pixel results on BAIR action-free dataset."""
hparams = next_frame_glow_hparams()
hparams.video_num_input_frames = 3
hparams.video_num_target_frames = 10
hparams.num_train_frames = 4
hparams.num_cond_latents = 3
hparams.depth = 24
hparam... | [
"def",
"next_frame_glow_bair_quant",
"(",
")",
":",
"hparams",
"=",
"next_frame_glow_hparams",
"(",
")",
"hparams",
".",
"video_num_input_frames",
"=",
"3",
"hparams",
".",
"video_num_target_frames",
"=",
"10",
"hparams",
".",
"num_train_frames",
"=",
"4",
"hparams"... | Hparams to reproduce bits-per-pixel results on BAIR action-free dataset. | [
"Hparams",
"to",
"reproduce",
"bits",
"-",
"per",
"-",
"pixel",
"results",
"on",
"BAIR",
"action",
"-",
"free",
"dataset",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/next_frame_glow.py#L91-L111 | train |
tensorflow/tensor2tensor | tensor2tensor/models/video/next_frame_glow.py | next_frame_glow_bair_qual | def next_frame_glow_bair_qual():
"""Hparams for qualitative video generation results."""
hparams = next_frame_glow_bair_quant()
hparams.coupling = "additive"
hparams.temperature = 0.5
hparams.coupling_width = 392
return hparams | python | def next_frame_glow_bair_qual():
"""Hparams for qualitative video generation results."""
hparams = next_frame_glow_bair_quant()
hparams.coupling = "additive"
hparams.temperature = 0.5
hparams.coupling_width = 392
return hparams | [
"def",
"next_frame_glow_bair_qual",
"(",
")",
":",
"hparams",
"=",
"next_frame_glow_bair_quant",
"(",
")",
"hparams",
".",
"coupling",
"=",
"\"additive\"",
"hparams",
".",
"temperature",
"=",
"0.5",
"hparams",
".",
"coupling_width",
"=",
"392",
"return",
"hparams"... | Hparams for qualitative video generation results. | [
"Hparams",
"for",
"qualitative",
"video",
"generation",
"results",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/next_frame_glow.py#L115-L121 | train |
tensorflow/tensor2tensor | tensor2tensor/models/video/next_frame_glow.py | next_frame_glow_shapes | def next_frame_glow_shapes():
"""Hparams for qualitative and quantitative results on shapes dataset."""
hparams = next_frame_glow_bair_quant()
hparams.video_num_input_frames = 1
hparams.video_num_target_frames = 2
hparams.num_train_frames = 2
hparams.num_cond_latents = 1
hparams.coupling = "additive"
hp... | python | def next_frame_glow_shapes():
"""Hparams for qualitative and quantitative results on shapes dataset."""
hparams = next_frame_glow_bair_quant()
hparams.video_num_input_frames = 1
hparams.video_num_target_frames = 2
hparams.num_train_frames = 2
hparams.num_cond_latents = 1
hparams.coupling = "additive"
hp... | [
"def",
"next_frame_glow_shapes",
"(",
")",
":",
"hparams",
"=",
"next_frame_glow_bair_quant",
"(",
")",
"hparams",
".",
"video_num_input_frames",
"=",
"1",
"hparams",
".",
"video_num_target_frames",
"=",
"2",
"hparams",
".",
"num_train_frames",
"=",
"2",
"hparams",
... | Hparams for qualitative and quantitative results on shapes dataset. | [
"Hparams",
"for",
"qualitative",
"and",
"quantitative",
"results",
"on",
"shapes",
"dataset",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/next_frame_glow.py#L125-L138 | train |
tensorflow/tensor2tensor | tensor2tensor/models/video/next_frame_glow.py | get_cond_latents | def get_cond_latents(all_latents=None, hparams=None):
"""Get z^{cond}_{t} given z^{1..t-1}.
Args:
all_latents: list of list of tensors,
outer-size equals no.of time_steps-1
inner-size equals hparams.n_levels.
hparams: See next_frame_glow_hparams.
Returns:
cond_latent... | python | def get_cond_latents(all_latents=None, hparams=None):
"""Get z^{cond}_{t} given z^{1..t-1}.
Args:
all_latents: list of list of tensors,
outer-size equals no.of time_steps-1
inner-size equals hparams.n_levels.
hparams: See next_frame_glow_hparams.
Returns:
cond_latent... | [
"def",
"get_cond_latents",
"(",
"all_latents",
"=",
"None",
",",
"hparams",
"=",
"None",
")",
":",
"cond_latents",
"=",
"None",
"if",
"hparams",
".",
"gen_mode",
"==",
"\"conditional\"",
":",
"if",
"hparams",
".",
"latent_dist_encoder",
"in",
"[",
"\"conv_net\... | Get z^{cond}_{t} given z^{1..t-1}.
Args:
all_latents: list of list of tensors,
outer-size equals no.of time_steps-1
inner-size equals hparams.n_levels.
hparams: See next_frame_glow_hparams.
Returns:
cond_latents: conditional latents at time-step t. | [
"Get",
"z^",
"{",
"cond",
"}",
"_",
"{",
"t",
"}",
"given",
"z^",
"{",
"1",
"..",
"t",
"-",
"1",
"}",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/next_frame_glow.py#L150-L179 | train |
tensorflow/tensor2tensor | tensor2tensor/models/basic.py | basic_fc_small | def basic_fc_small():
"""Small fully connected model."""
hparams = common_hparams.basic_params1()
hparams.learning_rate = 0.1
hparams.batch_size = 128
hparams.hidden_size = 256
hparams.num_hidden_layers = 2
hparams.initializer = "uniform_unit_scaling"
hparams.initializer_gain = 1.0
hparams.weight_deca... | python | def basic_fc_small():
"""Small fully connected model."""
hparams = common_hparams.basic_params1()
hparams.learning_rate = 0.1
hparams.batch_size = 128
hparams.hidden_size = 256
hparams.num_hidden_layers = 2
hparams.initializer = "uniform_unit_scaling"
hparams.initializer_gain = 1.0
hparams.weight_deca... | [
"def",
"basic_fc_small",
"(",
")",
":",
"hparams",
"=",
"common_hparams",
".",
"basic_params1",
"(",
")",
"hparams",
".",
"learning_rate",
"=",
"0.1",
"hparams",
".",
"batch_size",
"=",
"128",
"hparams",
".",
"hidden_size",
"=",
"256",
"hparams",
".",
"num_h... | Small fully connected model. | [
"Small",
"fully",
"connected",
"model",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/basic.py#L47-L58 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/transformer_symshard.py | _layer_stack | def _layer_stack(mp,
inputs,
self_attention_bias,
layers,
hparams,
encoder_output=None,
encoder_decoder_attention_bias=None):
"""A stack of layers.
Args:
mp: a Parallelism object
inputs: a list of Tensors
... | python | def _layer_stack(mp,
inputs,
self_attention_bias,
layers,
hparams,
encoder_output=None,
encoder_decoder_attention_bias=None):
"""A stack of layers.
Args:
mp: a Parallelism object
inputs: a list of Tensors
... | [
"def",
"_layer_stack",
"(",
"mp",
",",
"inputs",
",",
"self_attention_bias",
",",
"layers",
",",
"hparams",
",",
"encoder_output",
"=",
"None",
",",
"encoder_decoder_attention_bias",
"=",
"None",
")",
":",
"layers",
"=",
"layers",
".",
"strip",
"(",
"\",\"",
... | A stack of layers.
Args:
mp: a Parallelism object
inputs: a list of Tensors
self_attention_bias: list of bias Tensor for self-attention
(see common_attention.attention_bias())
layers: a string
hparams: hyperparameters for model
encoder_output: optional list of tensors
encoder_decode... | [
"A",
"stack",
"of",
"layers",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_symshard.py#L227-L339 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/transformer_symshard.py | transformer_symshard_base | def transformer_symshard_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.hidden_size = 256
hparams.batch_size = 2048
hparams.max_length = 0
# All hyperparameters ending in "dropout" are automatically set to 0.0
# when not in training mode.
hparams.layer_prepostproc... | python | def transformer_symshard_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.hidden_size = 256
hparams.batch_size = 2048
hparams.max_length = 0
# All hyperparameters ending in "dropout" are automatically set to 0.0
# when not in training mode.
hparams.layer_prepostproc... | [
"def",
"transformer_symshard_base",
"(",
")",
":",
"hparams",
"=",
"common_hparams",
".",
"basic_params1",
"(",
")",
"hparams",
".",
"hidden_size",
"=",
"256",
"hparams",
".",
"batch_size",
"=",
"2048",
"hparams",
".",
"max_length",
"=",
"0",
"# All hyperparamet... | Set of hyperparameters. | [
"Set",
"of",
"hyperparameters",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_symshard.py#L343-L392 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/imagenet.py | imagenet_pixelrnn_generator | def imagenet_pixelrnn_generator(tmp_dir,
training,
size=_IMAGENET_SMALL_IMAGE_SIZE):
"""Image generator for Imagenet 64x64 downsampled images.
It assumes that the data has been downloaded from
http://image-net.org/small/*_32x32.tar or
http://image... | python | def imagenet_pixelrnn_generator(tmp_dir,
training,
size=_IMAGENET_SMALL_IMAGE_SIZE):
"""Image generator for Imagenet 64x64 downsampled images.
It assumes that the data has been downloaded from
http://image-net.org/small/*_32x32.tar or
http://image... | [
"def",
"imagenet_pixelrnn_generator",
"(",
"tmp_dir",
",",
"training",
",",
"size",
"=",
"_IMAGENET_SMALL_IMAGE_SIZE",
")",
":",
"if",
"size",
"==",
"_IMAGENET_SMALL_IMAGE_SIZE",
":",
"train_prefix",
"=",
"_IMAGENET_SMALL_TRAIN_PREFIX",
"eval_prefix",
"=",
"_IMAGENET_SMAL... | Image generator for Imagenet 64x64 downsampled images.
It assumes that the data has been downloaded from
http://image-net.org/small/*_32x32.tar or
http://image-net.org/small/*_64x64.tar into tmp_dir.
Args:
tmp_dir: path to temporary storage directory.
training: a Boolean; if true, we use the train set,... | [
"Image",
"generator",
"for",
"Imagenet",
"64x64",
"downsampled",
"images",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L56-L98 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/imagenet.py | imagenet_preprocess_example | def imagenet_preprocess_example(example, mode, resize_size=None,
normalize=True):
"""Preprocessing used for Imagenet and similar problems."""
resize_size = resize_size or [299, 299]
assert resize_size[0] == resize_size[1]
image = example["inputs"]
if mode == tf.estimator.ModeK... | python | def imagenet_preprocess_example(example, mode, resize_size=None,
normalize=True):
"""Preprocessing used for Imagenet and similar problems."""
resize_size = resize_size or [299, 299]
assert resize_size[0] == resize_size[1]
image = example["inputs"]
if mode == tf.estimator.ModeK... | [
"def",
"imagenet_preprocess_example",
"(",
"example",
",",
"mode",
",",
"resize_size",
"=",
"None",
",",
"normalize",
"=",
"True",
")",
":",
"resize_size",
"=",
"resize_size",
"or",
"[",
"299",
",",
"299",
"]",
"assert",
"resize_size",
"[",
"0",
"]",
"==",... | Preprocessing used for Imagenet and similar problems. | [
"Preprocessing",
"used",
"for",
"Imagenet",
"and",
"similar",
"problems",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L101-L116 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/imagenet.py | _crop | def _crop(image, offset_height, offset_width, crop_height, crop_width):
"""Crops the given image using the provided offsets and sizes.
Note that the method doesn't assume we know the input image size but it does
assume we know the input image rank.
Args:
image: `Tensor` image of shape [height, width, chan... | python | def _crop(image, offset_height, offset_width, crop_height, crop_width):
"""Crops the given image using the provided offsets and sizes.
Note that the method doesn't assume we know the input image size but it does
assume we know the input image rank.
Args:
image: `Tensor` image of shape [height, width, chan... | [
"def",
"_crop",
"(",
"image",
",",
"offset_height",
",",
"offset_width",
",",
"crop_height",
",",
"crop_width",
")",
":",
"original_shape",
"=",
"tf",
".",
"shape",
"(",
"image",
")",
"rank_assertion",
"=",
"tf",
".",
"Assert",
"(",
"tf",
".",
"equal",
"... | Crops the given image using the provided offsets and sizes.
Note that the method doesn't assume we know the input image size but it does
assume we know the input image rank.
Args:
image: `Tensor` image of shape [height, width, channels].
offset_height: `Tensor` indicating the height offset.
offset_w... | [
"Crops",
"the",
"given",
"image",
"using",
"the",
"provided",
"offsets",
"and",
"sizes",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L427-L466 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/imagenet.py | distorted_bounding_box_crop | def distorted_bounding_box_crop(image,
bbox,
min_object_covered=0.1,
aspect_ratio_range=(0.75, 1.33),
area_range=(0.05, 1.0),
max_attempts=100,
... | python | def distorted_bounding_box_crop(image,
bbox,
min_object_covered=0.1,
aspect_ratio_range=(0.75, 1.33),
area_range=(0.05, 1.0),
max_attempts=100,
... | [
"def",
"distorted_bounding_box_crop",
"(",
"image",
",",
"bbox",
",",
"min_object_covered",
"=",
"0.1",
",",
"aspect_ratio_range",
"=",
"(",
"0.75",
",",
"1.33",
")",
",",
"area_range",
"=",
"(",
"0.05",
",",
"1.0",
")",
",",
"max_attempts",
"=",
"100",
",... | Generates cropped_image using a one of the bboxes randomly distorted.
See `tf.image.sample_distorted_bounding_box` for more documentation.
Args:
image: `Tensor` of image (it will be converted to floats in [0, 1]).
bbox: `Tensor` of bounding boxes arranged `[1, num_boxes, coords]`
where each coordi... | [
"Generates",
"cropped_image",
"using",
"a",
"one",
"of",
"the",
"bboxes",
"randomly",
"distorted",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L469-L524 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/imagenet.py | _random_crop | def _random_crop(image, size):
"""Make a random crop of (`size` x `size`)."""
bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4])
random_image, bbox = distorted_bounding_box_crop(
image,
bbox,
min_object_covered=0.1,
aspect_ratio_range=(3. / 4, 4. / 3.),
area_... | python | def _random_crop(image, size):
"""Make a random crop of (`size` x `size`)."""
bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4])
random_image, bbox = distorted_bounding_box_crop(
image,
bbox,
min_object_covered=0.1,
aspect_ratio_range=(3. / 4, 4. / 3.),
area_... | [
"def",
"_random_crop",
"(",
"image",
",",
"size",
")",
":",
"bbox",
"=",
"tf",
".",
"constant",
"(",
"[",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"1.0",
"]",
",",
"dtype",
"=",
"tf",
".",
"float32",
",",
"shape",
"=",
"[",
"1",
",",
"1",
",",
"4"... | Make a random crop of (`size` x `size`). | [
"Make",
"a",
"random",
"crop",
"of",
"(",
"size",
"x",
"size",
")",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L527-L543 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/imagenet.py | _at_least_x_are_true | def _at_least_x_are_true(a, b, x):
"""At least `x` of `a` and `b` `Tensors` are true."""
match = tf.equal(a, b)
match = tf.cast(match, tf.int32)
return tf.greater_equal(tf.reduce_sum(match), x) | python | def _at_least_x_are_true(a, b, x):
"""At least `x` of `a` and `b` `Tensors` are true."""
match = tf.equal(a, b)
match = tf.cast(match, tf.int32)
return tf.greater_equal(tf.reduce_sum(match), x) | [
"def",
"_at_least_x_are_true",
"(",
"a",
",",
"b",
",",
"x",
")",
":",
"match",
"=",
"tf",
".",
"equal",
"(",
"a",
",",
"b",
")",
"match",
"=",
"tf",
".",
"cast",
"(",
"match",
",",
"tf",
".",
"int32",
")",
"return",
"tf",
".",
"greater_equal",
... | At least `x` of `a` and `b` `Tensors` are true. | [
"At",
"least",
"x",
"of",
"a",
"and",
"b",
"Tensors",
"are",
"true",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L552-L556 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/imagenet.py | _do_scale | def _do_scale(image, size):
"""Rescale the image by scaling the smaller spatial dimension to `size`."""
shape = tf.cast(tf.shape(image), tf.float32)
w_greater = tf.greater(shape[0], shape[1])
shape = tf.cond(w_greater,
lambda: tf.cast([shape[0] / shape[1] * size, size], tf.int32),
... | python | def _do_scale(image, size):
"""Rescale the image by scaling the smaller spatial dimension to `size`."""
shape = tf.cast(tf.shape(image), tf.float32)
w_greater = tf.greater(shape[0], shape[1])
shape = tf.cond(w_greater,
lambda: tf.cast([shape[0] / shape[1] * size, size], tf.int32),
... | [
"def",
"_do_scale",
"(",
"image",
",",
"size",
")",
":",
"shape",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"shape",
"(",
"image",
")",
",",
"tf",
".",
"float32",
")",
"w_greater",
"=",
"tf",
".",
"greater",
"(",
"shape",
"[",
"0",
"]",
",",
"sha... | Rescale the image by scaling the smaller spatial dimension to `size`. | [
"Rescale",
"the",
"image",
"by",
"scaling",
"the",
"smaller",
"spatial",
"dimension",
"to",
"size",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L559-L567 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/imagenet.py | _center_crop | def _center_crop(image, size):
"""Crops to center of image with specified `size`."""
image_height = tf.shape(image)[0]
image_width = tf.shape(image)[1]
offset_height = ((image_height - size) + 1) / 2
offset_width = ((image_width - size) + 1) / 2
image = _crop(image, offset_height, offset_width, size, size)... | python | def _center_crop(image, size):
"""Crops to center of image with specified `size`."""
image_height = tf.shape(image)[0]
image_width = tf.shape(image)[1]
offset_height = ((image_height - size) + 1) / 2
offset_width = ((image_width - size) + 1) / 2
image = _crop(image, offset_height, offset_width, size, size)... | [
"def",
"_center_crop",
"(",
"image",
",",
"size",
")",
":",
"image_height",
"=",
"tf",
".",
"shape",
"(",
"image",
")",
"[",
"0",
"]",
"image_width",
"=",
"tf",
".",
"shape",
"(",
"image",
")",
"[",
"1",
"]",
"offset_height",
"=",
"(",
"(",
"image_... | Crops to center of image with specified `size`. | [
"Crops",
"to",
"center",
"of",
"image",
"with",
"specified",
"size",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L570-L578 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/imagenet.py | _normalize | def _normalize(image):
"""Normalize the image to zero mean and unit variance."""
offset = tf.constant(MEAN_RGB, shape=[1, 1, 3])
image -= offset
scale = tf.constant(STDDEV_RGB, shape=[1, 1, 3])
image /= scale
return image | python | def _normalize(image):
"""Normalize the image to zero mean and unit variance."""
offset = tf.constant(MEAN_RGB, shape=[1, 1, 3])
image -= offset
scale = tf.constant(STDDEV_RGB, shape=[1, 1, 3])
image /= scale
return image | [
"def",
"_normalize",
"(",
"image",
")",
":",
"offset",
"=",
"tf",
".",
"constant",
"(",
"MEAN_RGB",
",",
"shape",
"=",
"[",
"1",
",",
"1",
",",
"3",
"]",
")",
"image",
"-=",
"offset",
"scale",
"=",
"tf",
".",
"constant",
"(",
"STDDEV_RGB",
",",
"... | Normalize the image to zero mean and unit variance. | [
"Normalize",
"the",
"image",
"to",
"zero",
"mean",
"and",
"unit",
"variance",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L581-L588 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/imagenet.py | preprocess_for_train | def preprocess_for_train(image, image_size=224, normalize=True):
"""Preprocesses the given image for evaluation.
Args:
image: `Tensor` representing an image of arbitrary size.
image_size: int, how large the output image should be.
normalize: bool, if True the image is normalized.
Returns:
A prep... | python | def preprocess_for_train(image, image_size=224, normalize=True):
"""Preprocesses the given image for evaluation.
Args:
image: `Tensor` representing an image of arbitrary size.
image_size: int, how large the output image should be.
normalize: bool, if True the image is normalized.
Returns:
A prep... | [
"def",
"preprocess_for_train",
"(",
"image",
",",
"image_size",
"=",
"224",
",",
"normalize",
"=",
"True",
")",
":",
"if",
"normalize",
":",
"image",
"=",
"tf",
".",
"to_float",
"(",
"image",
")",
"/",
"255.0",
"image",
"=",
"_random_crop",
"(",
"image",... | Preprocesses the given image for evaluation.
Args:
image: `Tensor` representing an image of arbitrary size.
image_size: int, how large the output image should be.
normalize: bool, if True the image is normalized.
Returns:
A preprocessed image `Tensor`. | [
"Preprocesses",
"the",
"given",
"image",
"for",
"evaluation",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L591-L607 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/imagenet.py | preprocess_for_eval | def preprocess_for_eval(image, image_size=224, normalize=True):
"""Preprocesses the given image for evaluation.
Args:
image: `Tensor` representing an image of arbitrary size.
image_size: int, how large the output image should be.
normalize: bool, if True the image is normalized.
Returns:
A prepr... | python | def preprocess_for_eval(image, image_size=224, normalize=True):
"""Preprocesses the given image for evaluation.
Args:
image: `Tensor` representing an image of arbitrary size.
image_size: int, how large the output image should be.
normalize: bool, if True the image is normalized.
Returns:
A prepr... | [
"def",
"preprocess_for_eval",
"(",
"image",
",",
"image_size",
"=",
"224",
",",
"normalize",
"=",
"True",
")",
":",
"if",
"normalize",
":",
"image",
"=",
"tf",
".",
"to_float",
"(",
"image",
")",
"/",
"255.0",
"image",
"=",
"_do_scale",
"(",
"image",
"... | Preprocesses the given image for evaluation.
Args:
image: `Tensor` representing an image of arbitrary size.
image_size: int, how large the output image should be.
normalize: bool, if True the image is normalized.
Returns:
A preprocessed image `Tensor`. | [
"Preprocesses",
"the",
"given",
"image",
"for",
"evaluation",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L610-L626 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/learning_rate.py | MultifactorSchedule | def MultifactorSchedule(history=None,
factors="constant * linear_warmup * rsqrt_decay",
constant=0.1,
warmup_steps=100,
decay_factor=0.5,
steps_per_decay=20000):
"""Factor-based learning rate schedu... | python | def MultifactorSchedule(history=None,
factors="constant * linear_warmup * rsqrt_decay",
constant=0.1,
warmup_steps=100,
decay_factor=0.5,
steps_per_decay=20000):
"""Factor-based learning rate schedu... | [
"def",
"MultifactorSchedule",
"(",
"history",
"=",
"None",
",",
"factors",
"=",
"\"constant * linear_warmup * rsqrt_decay\"",
",",
"constant",
"=",
"0.1",
",",
"warmup_steps",
"=",
"100",
",",
"decay_factor",
"=",
"0.5",
",",
"steps_per_decay",
"=",
"20000",
")",
... | Factor-based learning rate schedule.
Interprets factors in the factors string which can consist of:
* constant: interpreted as the constant value,
* linear_warmup: interpreted as linear warmup until warmup_steps,
* rsqrt_decay: divide by square root of max(step, warmup_steps)
* decay_every: Every k steps dec... | [
"Factor",
"-",
"based",
"learning",
"rate",
"schedule",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/learning_rate.py#L42-L92 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/learning_rate.py | EvalAdjustingSchedule | def EvalAdjustingSchedule(history,
constant=0.1,
steps_to_decrease=20,
improvement_margin=0.001,
decrease_rate=1.5,
history_mode="eval",
metric="metrics/accuracy"):... | python | def EvalAdjustingSchedule(history,
constant=0.1,
steps_to_decrease=20,
improvement_margin=0.001,
decrease_rate=1.5,
history_mode="eval",
metric="metrics/accuracy"):... | [
"def",
"EvalAdjustingSchedule",
"(",
"history",
",",
"constant",
"=",
"0.1",
",",
"steps_to_decrease",
"=",
"20",
",",
"improvement_margin",
"=",
"0.001",
",",
"decrease_rate",
"=",
"1.5",
",",
"history_mode",
"=",
"\"eval\"",
",",
"metric",
"=",
"\"metrics/accu... | Learning rate that decreases when eval metric stalls.
If the chosen metric does not improve by improvement_margin for as many as
steps_to_decrease steps, then the constant gets decreased by decrease rate.
Finally, the MultifactorSchedule gets called with the adjusted constant.
Args:
history: trax.history.... | [
"Learning",
"rate",
"that",
"decreases",
"when",
"eval",
"metric",
"stalls",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/learning_rate.py#L96-L143 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/discretization.py | project_hidden | def project_hidden(x, projection_tensors, hidden_size, num_blocks):
"""Project encoder hidden state under num_blocks using projection tensors.
Args:
x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size].
projection_tensors: Projection tensors used to project the hidden state.
hidden_s... | python | def project_hidden(x, projection_tensors, hidden_size, num_blocks):
"""Project encoder hidden state under num_blocks using projection tensors.
Args:
x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size].
projection_tensors: Projection tensors used to project the hidden state.
hidden_s... | [
"def",
"project_hidden",
"(",
"x",
",",
"projection_tensors",
",",
"hidden_size",
",",
"num_blocks",
")",
":",
"batch_size",
",",
"latent_dim",
",",
"_",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"x",
"=",
"tf",
".",
"reshape",
"(",
"x",
",... | Project encoder hidden state under num_blocks using projection tensors.
Args:
x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size].
projection_tensors: Projection tensors used to project the hidden state.
hidden_size: Dimension of the latent space.
num_blocks: Number of blocks in D... | [
"Project",
"encoder",
"hidden",
"state",
"under",
"num_blocks",
"using",
"projection",
"tensors",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L33-L54 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/discretization.py | slice_hidden | def slice_hidden(x, hidden_size, num_blocks):
"""Slice encoder hidden state under num_blocks.
Args:
x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size].
hidden_size: Dimension of the latent space.
num_blocks: Number of blocks in DVQ.
Returns:
Sliced states of shape [batch_size... | python | def slice_hidden(x, hidden_size, num_blocks):
"""Slice encoder hidden state under num_blocks.
Args:
x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size].
hidden_size: Dimension of the latent space.
num_blocks: Number of blocks in DVQ.
Returns:
Sliced states of shape [batch_size... | [
"def",
"slice_hidden",
"(",
"x",
",",
"hidden_size",
",",
"num_blocks",
")",
":",
"batch_size",
",",
"latent_dim",
",",
"_",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"block_dim",
"=",
"hidden_size",
"//",
"num_blocks",
"x_sliced",
"=",
"tf",
... | Slice encoder hidden state under num_blocks.
Args:
x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size].
hidden_size: Dimension of the latent space.
num_blocks: Number of blocks in DVQ.
Returns:
Sliced states of shape [batch_size, latent_dim, num_blocks, block_dim]. | [
"Slice",
"encoder",
"hidden",
"state",
"under",
"num_blocks",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L57-L72 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/discretization.py | nearest_neighbor | def nearest_neighbor(x,
means,
block_v_size,
random_top_k=1,
soft_em=False,
num_samples=1,
sum_over_latents=False,
summary=True):
"""Find the nearest element in means to e... | python | def nearest_neighbor(x,
means,
block_v_size,
random_top_k=1,
soft_em=False,
num_samples=1,
sum_over_latents=False,
summary=True):
"""Find the nearest element in means to e... | [
"def",
"nearest_neighbor",
"(",
"x",
",",
"means",
",",
"block_v_size",
",",
"random_top_k",
"=",
"1",
",",
"soft_em",
"=",
"False",
",",
"num_samples",
"=",
"1",
",",
"sum_over_latents",
"=",
"False",
",",
"summary",
"=",
"True",
")",
":",
"batch_size",
... | Find the nearest element in means to elements in x.
Args:
x: Continuous encodings of shape [batch_size, latent_dim, num_blocks,
block_dim].
means: Embedding table of shape [num_blocks, block_v_size, block_dim].
block_v_size: Number of table entries per block.
random_top_k: Noisy top-k if this i... | [
"Find",
"the",
"nearest",
"element",
"in",
"means",
"to",
"elements",
"in",
"x",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L75-L141 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/discretization.py | embedding_lookup | def embedding_lookup(x,
means,
num_blocks,
block_v_size,
bottleneck_kind="dvq",
random_top_k=1,
soft_em=False,
num_samples=1,
do_hard_gumbel_softmax=Fal... | python | def embedding_lookup(x,
means,
num_blocks,
block_v_size,
bottleneck_kind="dvq",
random_top_k=1,
soft_em=False,
num_samples=1,
do_hard_gumbel_softmax=Fal... | [
"def",
"embedding_lookup",
"(",
"x",
",",
"means",
",",
"num_blocks",
",",
"block_v_size",
",",
"bottleneck_kind",
"=",
"\"dvq\"",
",",
"random_top_k",
"=",
"1",
",",
"soft_em",
"=",
"False",
",",
"num_samples",
"=",
"1",
",",
"do_hard_gumbel_softmax",
"=",
... | Compute nearest neighbors and loss for training the embeddings via DVQ.
Args:
x: Continuous encodings of shape [batch_size, latent_dim, num_blocks,
block_dim].
means: Embedding table of shape [num_blocks, block_v_size, block_dim].
num_blocks: Number of blocks in DVQ.
block_v_size: Number of tab... | [
"Compute",
"nearest",
"neighbors",
"and",
"loss",
"for",
"training",
"the",
"embeddings",
"via",
"DVQ",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L144-L222 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.