id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
22,300 | tensorflow/tensor2tensor | tensor2tensor/models/research/attention_lm_moe.py | attention_lm_moe_memory_efficient | def attention_lm_moe_memory_efficient():
"""Memory-efficient version."""
hparams = attention_lm_moe_large()
hparams.diet_experts = True
hparams.layer_preprocess_sequence = "n"
hparams.layer_postprocess_sequence = "da"
hparams.layer_prepostprocess_dropout = 0.0
hparams.memory_efficient_ffn = True
hparams... | python | def attention_lm_moe_memory_efficient():
"""Memory-efficient version."""
hparams = attention_lm_moe_large()
hparams.diet_experts = True
hparams.layer_preprocess_sequence = "n"
hparams.layer_postprocess_sequence = "da"
hparams.layer_prepostprocess_dropout = 0.0
hparams.memory_efficient_ffn = True
hparams... | [
"def",
"attention_lm_moe_memory_efficient",
"(",
")",
":",
"hparams",
"=",
"attention_lm_moe_large",
"(",
")",
"hparams",
".",
"diet_experts",
"=",
"True",
"hparams",
".",
"layer_preprocess_sequence",
"=",
"\"n\"",
"hparams",
".",
"layer_postprocess_sequence",
"=",
"\... | Memory-efficient version. | [
"Memory",
"-",
"efficient",
"version",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm_moe.py#L733-L744 |
22,301 | tensorflow/tensor2tensor | tensor2tensor/models/research/attention_lm_moe.py | attention_lm_moe_24b_diet | def attention_lm_moe_24b_diet():
"""Unnecessarily large model with 24B params - because we can."""
hparams = attention_lm_moe_large_diet()
hparams.moe_hidden_sizes = "12288"
hparams.moe_num_experts = 1024
hparams.batch_size = 4096
return hparams | python | def attention_lm_moe_24b_diet():
"""Unnecessarily large model with 24B params - because we can."""
hparams = attention_lm_moe_large_diet()
hparams.moe_hidden_sizes = "12288"
hparams.moe_num_experts = 1024
hparams.batch_size = 4096
return hparams | [
"def",
"attention_lm_moe_24b_diet",
"(",
")",
":",
"hparams",
"=",
"attention_lm_moe_large_diet",
"(",
")",
"hparams",
".",
"moe_hidden_sizes",
"=",
"\"12288\"",
"hparams",
".",
"moe_num_experts",
"=",
"1024",
"hparams",
".",
"batch_size",
"=",
"4096",
"return",
"... | Unnecessarily large model with 24B params - because we can. | [
"Unnecessarily",
"large",
"model",
"with",
"24B",
"params",
"-",
"because",
"we",
"can",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm_moe.py#L757-L763 |
22,302 | tensorflow/tensor2tensor | tensor2tensor/models/research/attention_lm_moe.py | attention_lm_moe_unscramble_base | def attention_lm_moe_unscramble_base():
"""Version to use with languagemodel_wiki_scramble1k50."""
hparams = attention_lm_no_moe_small()
hparams.use_inputs = True
hparams.min_length_bucket = 1024
hparams.max_length = 1024
hparams.batch_size = 5000
hparams.layer_prepostprocess_dropout = 0.0
hparams.layer... | python | def attention_lm_moe_unscramble_base():
"""Version to use with languagemodel_wiki_scramble1k50."""
hparams = attention_lm_no_moe_small()
hparams.use_inputs = True
hparams.min_length_bucket = 1024
hparams.max_length = 1024
hparams.batch_size = 5000
hparams.layer_prepostprocess_dropout = 0.0
hparams.layer... | [
"def",
"attention_lm_moe_unscramble_base",
"(",
")",
":",
"hparams",
"=",
"attention_lm_no_moe_small",
"(",
")",
"hparams",
".",
"use_inputs",
"=",
"True",
"hparams",
".",
"min_length_bucket",
"=",
"1024",
"hparams",
".",
"max_length",
"=",
"1024",
"hparams",
".",... | Version to use with languagemodel_wiki_scramble1k50. | [
"Version",
"to",
"use",
"with",
"languagemodel_wiki_scramble1k50",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm_moe.py#L784-L794 |
22,303 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | audio_bottom | def audio_bottom(x, model_hparams, vocab_size):
"""Transform input from data space to model space.
Args:
x: A Tensor with shape [batch, ...]
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
body_input: A Tensor with shape [batch, ?, ?,
model_hparams.... | python | def audio_bottom(x, model_hparams, vocab_size):
"""Transform input from data space to model space.
Args:
x: A Tensor with shape [batch, ...]
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
body_input: A Tensor with shape [batch, ?, ?,
model_hparams.... | [
"def",
"audio_bottom",
"(",
"x",
",",
"model_hparams",
",",
"vocab_size",
")",
":",
"del",
"vocab_size",
"# unused arg",
"inputs",
"=",
"x",
"with",
"tf",
".",
"variable_scope",
"(",
"\"audio_modality\"",
")",
":",
"# TODO(aidangomez): Will need to sort out a better a... | Transform input from data space to model space.
Args:
x: A Tensor with shape [batch, ...]
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
body_input: A Tensor with shape [batch, ?, ?,
model_hparams.hidden_size]. | [
"Transform",
"input",
"from",
"data",
"space",
"to",
"model",
"space",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L128-L173 |
22,304 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | image_targets_bottom | def image_targets_bottom(x, model_hparams, vocab_size):
"""Bottom transformation for target images."""
pixel_embedding_size = 64
inputs = x
with tf.variable_scope("image_modality"):
if not tf.executing_eagerly():
tf.summary.image(
"targets_bottom",
common_layers.tpu_safe_image_summ... | python | def image_targets_bottom(x, model_hparams, vocab_size):
"""Bottom transformation for target images."""
pixel_embedding_size = 64
inputs = x
with tf.variable_scope("image_modality"):
if not tf.executing_eagerly():
tf.summary.image(
"targets_bottom",
common_layers.tpu_safe_image_summ... | [
"def",
"image_targets_bottom",
"(",
"x",
",",
"model_hparams",
",",
"vocab_size",
")",
":",
"pixel_embedding_size",
"=",
"64",
"inputs",
"=",
"x",
"with",
"tf",
".",
"variable_scope",
"(",
"\"image_modality\"",
")",
":",
"if",
"not",
"tf",
".",
"executing_eage... | Bottom transformation for target images. | [
"Bottom",
"transformation",
"for",
"target",
"images",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L260-L288 |
22,305 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | _image_channel_compress_bottom | def _image_channel_compress_bottom(inputs, model_hparams, name="bottom"):
"""Compresses channel-wise input pixels into whole pixel representions.
Perform conversion of RGB pixel values to a real number in the range -1 to
1. This combines pixel channels to form a representation of shape
[img_len, img_len].
A... | python | def _image_channel_compress_bottom(inputs, model_hparams, name="bottom"):
"""Compresses channel-wise input pixels into whole pixel representions.
Perform conversion of RGB pixel values to a real number in the range -1 to
1. This combines pixel channels to form a representation of shape
[img_len, img_len].
A... | [
"def",
"_image_channel_compress_bottom",
"(",
"inputs",
",",
"model_hparams",
",",
"name",
"=",
"\"bottom\"",
")",
":",
"num_channels",
"=",
"3",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
")",
":",
"inputs",
"=",
"tf",
".",
"to_float",
"(",
"inputs",... | Compresses channel-wise input pixels into whole pixel representions.
Perform conversion of RGB pixel values to a real number in the range -1 to
1. This combines pixel channels to form a representation of shape
[img_len, img_len].
Args:
inputs: Tensor representing RGB pixel intensities as integers, of shap... | [
"Compresses",
"channel",
"-",
"wise",
"input",
"pixels",
"into",
"whole",
"pixel",
"representions",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L291-L333 |
22,306 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | image_channel_embeddings_bottom | def image_channel_embeddings_bottom(x, model_hparams, vocab_size):
"""Bottom transformation for image targets."""
del vocab_size # unused arg
inputs = tf.to_int32(x)
io_depth = model_hparams.num_channels
tshape = common_layers.shape_list(inputs)
hidden_size = model_hparams.hidden_size
target_embeddings =... | python | def image_channel_embeddings_bottom(x, model_hparams, vocab_size):
"""Bottom transformation for image targets."""
del vocab_size # unused arg
inputs = tf.to_int32(x)
io_depth = model_hparams.num_channels
tshape = common_layers.shape_list(inputs)
hidden_size = model_hparams.hidden_size
target_embeddings =... | [
"def",
"image_channel_embeddings_bottom",
"(",
"x",
",",
"model_hparams",
",",
"vocab_size",
")",
":",
"del",
"vocab_size",
"# unused arg",
"inputs",
"=",
"tf",
".",
"to_int32",
"(",
"x",
")",
"io_depth",
"=",
"model_hparams",
".",
"num_channels",
"tshape",
"=",... | Bottom transformation for image targets. | [
"Bottom",
"transformation",
"for",
"image",
"targets",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L346-L356 |
22,307 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | speech_recognition_bottom | def speech_recognition_bottom(x, model_hparams, vocab_size):
"""Use batchnorm instead of CMVN and shorten the stft with strided convs.
Args:
x: float32 tensor with shape [batch_size, len, 1, freqs * channels]
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
... | python | def speech_recognition_bottom(x, model_hparams, vocab_size):
"""Use batchnorm instead of CMVN and shorten the stft with strided convs.
Args:
x: float32 tensor with shape [batch_size, len, 1, freqs * channels]
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
... | [
"def",
"speech_recognition_bottom",
"(",
"x",
",",
"model_hparams",
",",
"vocab_size",
")",
":",
"del",
"vocab_size",
"# unused arg",
"inputs",
"=",
"x",
"p",
"=",
"model_hparams",
"num_mel_bins",
"=",
"p",
".",
"audio_num_mel_bins",
"num_channels",
"=",
"3",
"i... | Use batchnorm instead of CMVN and shorten the stft with strided convs.
Args:
x: float32 tensor with shape [batch_size, len, 1, freqs * channels]
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
float32 tensor with shape [batch_size, shorter_len, 1, hidden_si... | [
"Use",
"batchnorm",
"instead",
"of",
"CMVN",
"and",
"shorten",
"the",
"stft",
"with",
"strided",
"convs",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L373-L452 |
22,308 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | get_weights | def get_weights(model_hparams, vocab_size, hidden_dim=None):
"""Create or get concatenated embedding or softmax variable.
Args:
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
hidden_dim: dim of the variable. Defaults to _model_hparams' hidden_size
Returns:
a lis... | python | def get_weights(model_hparams, vocab_size, hidden_dim=None):
"""Create or get concatenated embedding or softmax variable.
Args:
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
hidden_dim: dim of the variable. Defaults to _model_hparams' hidden_size
Returns:
a lis... | [
"def",
"get_weights",
"(",
"model_hparams",
",",
"vocab_size",
",",
"hidden_dim",
"=",
"None",
")",
":",
"if",
"hidden_dim",
"is",
"None",
":",
"hidden_dim",
"=",
"model_hparams",
".",
"hidden_size",
"num_shards",
"=",
"model_hparams",
".",
"symbol_modality_num_sh... | Create or get concatenated embedding or softmax variable.
Args:
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
hidden_dim: dim of the variable. Defaults to _model_hparams' hidden_size
Returns:
a list of num_shards Tensors. | [
"Create",
"or",
"get",
"concatenated",
"embedding",
"or",
"softmax",
"variable",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L455-L485 |
22,309 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | _symbol_bottom_simple | def _symbol_bottom_simple(x, model_hparams, vocab_size, name, reuse):
"""Bottom transformation for symbols."""
with tf.variable_scope(name, reuse=reuse):
# Ensure the inputs are 3-D
if len(x.get_shape()) == 4:
x = tf.squeeze(x, axis=3)
while len(x.get_shape()) < 3:
x = tf.expand_dims(x, axis... | python | def _symbol_bottom_simple(x, model_hparams, vocab_size, name, reuse):
"""Bottom transformation for symbols."""
with tf.variable_scope(name, reuse=reuse):
# Ensure the inputs are 3-D
if len(x.get_shape()) == 4:
x = tf.squeeze(x, axis=3)
while len(x.get_shape()) < 3:
x = tf.expand_dims(x, axis... | [
"def",
"_symbol_bottom_simple",
"(",
"x",
",",
"model_hparams",
",",
"vocab_size",
",",
"name",
",",
"reuse",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"reuse",
"=",
"reuse",
")",
":",
"# Ensure the inputs are 3-D",
"if",
"len",
"(",
... | Bottom transformation for symbols. | [
"Bottom",
"transformation",
"for",
"symbols",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L488-L505 |
22,310 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | symbol_targets_bottom | def symbol_targets_bottom(x, model_hparams, vocab_size):
"""Bottom transformation for target symbols."""
if (model_hparams.shared_embedding_and_softmax_weights or
model_hparams.get("shared_embedding")):
try:
return _symbol_bottom_simple(
x, model_hparams, vocab_size, "shared", reuse=True)
... | python | def symbol_targets_bottom(x, model_hparams, vocab_size):
"""Bottom transformation for target symbols."""
if (model_hparams.shared_embedding_and_softmax_weights or
model_hparams.get("shared_embedding")):
try:
return _symbol_bottom_simple(
x, model_hparams, vocab_size, "shared", reuse=True)
... | [
"def",
"symbol_targets_bottom",
"(",
"x",
",",
"model_hparams",
",",
"vocab_size",
")",
":",
"if",
"(",
"model_hparams",
".",
"shared_embedding_and_softmax_weights",
"or",
"model_hparams",
".",
"get",
"(",
"\"shared_embedding\"",
")",
")",
":",
"try",
":",
"return... | Bottom transformation for target symbols. | [
"Bottom",
"transformation",
"for",
"target",
"symbols",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L517-L530 |
22,311 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | video_bitwise_bottom | def video_bitwise_bottom(x, model_hparams, vocab_size):
"""Bottom transformation for embedding video bitwise."""
pixel_embedding_size = 64
inputs = x
with tf.variable_scope("video_modality_bitwise", reuse=tf.AUTO_REUSE):
common_layers.summarize_video(inputs, "bottom")
# Embed bitwise.
assert vocab_s... | python | def video_bitwise_bottom(x, model_hparams, vocab_size):
"""Bottom transformation for embedding video bitwise."""
pixel_embedding_size = 64
inputs = x
with tf.variable_scope("video_modality_bitwise", reuse=tf.AUTO_REUSE):
common_layers.summarize_video(inputs, "bottom")
# Embed bitwise.
assert vocab_s... | [
"def",
"video_bitwise_bottom",
"(",
"x",
",",
"model_hparams",
",",
"vocab_size",
")",
":",
"pixel_embedding_size",
"=",
"64",
"inputs",
"=",
"x",
"with",
"tf",
".",
"variable_scope",
"(",
"\"video_modality_bitwise\"",
",",
"reuse",
"=",
"tf",
".",
"AUTO_REUSE",... | Bottom transformation for embedding video bitwise. | [
"Bottom",
"transformation",
"for",
"embedding",
"video",
"bitwise",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L552-L566 |
22,312 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | video_pixel_noise_bottom | def video_pixel_noise_bottom(x, model_hparams, vocab_size):
"""Bottom transformation for video."""
input_noise = getattr(model_hparams, "video_modality_input_noise", 0.25)
inputs = x
if model_hparams.mode == tf.estimator.ModeKeys.TRAIN:
background = tfp.stats.percentile(inputs, 50., axis=[0, 1, 2, 3])
i... | python | def video_pixel_noise_bottom(x, model_hparams, vocab_size):
"""Bottom transformation for video."""
input_noise = getattr(model_hparams, "video_modality_input_noise", 0.25)
inputs = x
if model_hparams.mode == tf.estimator.ModeKeys.TRAIN:
background = tfp.stats.percentile(inputs, 50., axis=[0, 1, 2, 3])
i... | [
"def",
"video_pixel_noise_bottom",
"(",
"x",
",",
"model_hparams",
",",
"vocab_size",
")",
":",
"input_noise",
"=",
"getattr",
"(",
"model_hparams",
",",
"\"video_modality_input_noise\"",
",",
"0.25",
")",
"inputs",
"=",
"x",
"if",
"model_hparams",
".",
"mode",
... | Bottom transformation for video. | [
"Bottom",
"transformation",
"for",
"video",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L599-L612 |
22,313 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | convert_rgb_to_real | def convert_rgb_to_real(prediction, targets):
"""Convert prediction and target from rgb to real."""
prediction = tf.squeeze(prediction, axis=-1)
prediction = common_layers.convert_rgb_to_real(prediction)
targets = common_layers.convert_rgb_to_real(targets)
return prediction, targets | python | def convert_rgb_to_real(prediction, targets):
"""Convert prediction and target from rgb to real."""
prediction = tf.squeeze(prediction, axis=-1)
prediction = common_layers.convert_rgb_to_real(prediction)
targets = common_layers.convert_rgb_to_real(targets)
return prediction, targets | [
"def",
"convert_rgb_to_real",
"(",
"prediction",
",",
"targets",
")",
":",
"prediction",
"=",
"tf",
".",
"squeeze",
"(",
"prediction",
",",
"axis",
"=",
"-",
"1",
")",
"prediction",
"=",
"common_layers",
".",
"convert_rgb_to_real",
"(",
"prediction",
")",
"t... | Convert prediction and target from rgb to real. | [
"Convert",
"prediction",
"and",
"target",
"from",
"rgb",
"to",
"real",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L615-L620 |
22,314 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | ctc_symbol_loss | def ctc_symbol_loss(top_out, targets, model_hparams, vocab_size, weight_fn):
"""Compute the CTC loss."""
del model_hparams, vocab_size # unused arg
logits = top_out
with tf.name_scope("ctc_loss", values=[logits, targets]):
# For CTC we assume targets are 1d, [batch, length, 1, 1] here.
targets_shape = ... | python | def ctc_symbol_loss(top_out, targets, model_hparams, vocab_size, weight_fn):
"""Compute the CTC loss."""
del model_hparams, vocab_size # unused arg
logits = top_out
with tf.name_scope("ctc_loss", values=[logits, targets]):
# For CTC we assume targets are 1d, [batch, length, 1, 1] here.
targets_shape = ... | [
"def",
"ctc_symbol_loss",
"(",
"top_out",
",",
"targets",
",",
"model_hparams",
",",
"vocab_size",
",",
"weight_fn",
")",
":",
"del",
"model_hparams",
",",
"vocab_size",
"# unused arg",
"logits",
"=",
"top_out",
"with",
"tf",
".",
"name_scope",
"(",
"\"ctc_loss\... | Compute the CTC loss. | [
"Compute",
"the",
"CTC",
"loss",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L638-L662 |
22,315 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | multi_label_loss | def multi_label_loss(top_out, targets, model_hparams, vocab_size, weights_fn):
"""Average loss over the labels."""
del vocab_size # unused arg
logits = top_out
num_labels = tf.shape(targets)[1]
logits = tf.tile(logits, [1, num_labels, 1, 1, 1])
xent, weights = common_layers.padded_cross_entropy(
log... | python | def multi_label_loss(top_out, targets, model_hparams, vocab_size, weights_fn):
"""Average loss over the labels."""
del vocab_size # unused arg
logits = top_out
num_labels = tf.shape(targets)[1]
logits = tf.tile(logits, [1, num_labels, 1, 1, 1])
xent, weights = common_layers.padded_cross_entropy(
log... | [
"def",
"multi_label_loss",
"(",
"top_out",
",",
"targets",
",",
"model_hparams",
",",
"vocab_size",
",",
"weights_fn",
")",
":",
"del",
"vocab_size",
"# unused arg",
"logits",
"=",
"top_out",
"num_labels",
"=",
"tf",
".",
"shape",
"(",
"targets",
")",
"[",
"... | Average loss over the labels. | [
"Average",
"loss",
"over",
"the",
"labels",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L689-L711 |
22,316 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | one_hot_class_label_loss | def one_hot_class_label_loss(top_out,
targets,
model_hparams,
vocab_size,
weights_fn):
"""Apply softmax cross-entropy between outputs and targets.
Args:
top_out: logits Tensor with shape [batch, ... | python | def one_hot_class_label_loss(top_out,
targets,
model_hparams,
vocab_size,
weights_fn):
"""Apply softmax cross-entropy between outputs and targets.
Args:
top_out: logits Tensor with shape [batch, ... | [
"def",
"one_hot_class_label_loss",
"(",
"top_out",
",",
"targets",
",",
"model_hparams",
",",
"vocab_size",
",",
"weights_fn",
")",
":",
"del",
"model_hparams",
",",
"vocab_size",
"# unused arg",
"loss_scale",
"=",
"tf",
".",
"losses",
".",
"softmax_cross_entropy",
... | Apply softmax cross-entropy between outputs and targets.
Args:
top_out: logits Tensor with shape [batch, ?, ?, num_classes]
targets: one-hot encoding Tensor with shape [batch, ?, ?, num_classes]
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
weights_fn:
Returns... | [
"Apply",
"softmax",
"cross",
"-",
"entropy",
"between",
"outputs",
"and",
"targets",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L714-L736 |
22,317 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | real_log_poisson_loss | def real_log_poisson_loss(top_out,
targets,
model_hparams,
vocab_size,
weights_fn):
"""Poisson loss for real."""
del model_hparams, vocab_size # unused arg
predictions = top_out
if (len(common_layers.shape_l... | python | def real_log_poisson_loss(top_out,
targets,
model_hparams,
vocab_size,
weights_fn):
"""Poisson loss for real."""
del model_hparams, vocab_size # unused arg
predictions = top_out
if (len(common_layers.shape_l... | [
"def",
"real_log_poisson_loss",
"(",
"top_out",
",",
"targets",
",",
"model_hparams",
",",
"vocab_size",
",",
"weights_fn",
")",
":",
"del",
"model_hparams",
",",
"vocab_size",
"# unused arg",
"predictions",
"=",
"top_out",
"if",
"(",
"len",
"(",
"common_layers",
... | Poisson loss for real. | [
"Poisson",
"loss",
"for",
"real",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L751-L765 |
22,318 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | class_label_top | def class_label_top(body_output, targets, model_hparams, vocab_size):
"""Transform inputs from model space to target space.
Average over inner dims and a linear layer to logits.
Args:
body_output: A Tensor with shape [batch, ?, ?, body_output_size].
targets:
model_hparams: HParams, model hyperparmet... | python | def class_label_top(body_output, targets, model_hparams, vocab_size):
"""Transform inputs from model space to target space.
Average over inner dims and a linear layer to logits.
Args:
body_output: A Tensor with shape [batch, ?, ?, body_output_size].
targets:
model_hparams: HParams, model hyperparmet... | [
"def",
"class_label_top",
"(",
"body_output",
",",
"targets",
",",
"model_hparams",
",",
"vocab_size",
")",
":",
"del",
"targets",
"# unused arg",
"with",
"tf",
".",
"variable_scope",
"(",
"\"class_label_modality_%d_%d\"",
"%",
"(",
"vocab_size",
",",
"model_hparams... | Transform inputs from model space to target space.
Average over inner dims and a linear layer to logits.
Args:
body_output: A Tensor with shape [batch, ?, ?, body_output_size].
targets:
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
a Tensors, each ... | [
"Transform",
"inputs",
"from",
"model",
"space",
"to",
"target",
"space",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L927-L947 |
22,319 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | image_channel_compress_top | def image_channel_compress_top(body_output, targets, model_hparams, vocab_size):
"""Transforms body output to return logits.
Args:
body_output: Tensor of shape [batch, img_len, img_len, depth].
targets:
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
... | python | def image_channel_compress_top(body_output, targets, model_hparams, vocab_size):
"""Transforms body output to return logits.
Args:
body_output: Tensor of shape [batch, img_len, img_len, depth].
targets:
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
... | [
"def",
"image_channel_compress_top",
"(",
"body_output",
",",
"targets",
",",
"model_hparams",
",",
"vocab_size",
")",
":",
"del",
"targets",
"# unused arg",
"with",
"tf",
".",
"variable_scope",
"(",
"\"image_channel_compress_modality\"",
")",
":",
"hidden_size",
"=",... | Transforms body output to return logits.
Args:
body_output: Tensor of shape [batch, img_len, img_len, depth].
targets:
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
Tensor of shape [batch, img_len, img_len, channels, vocab_size]. | [
"Transforms",
"body",
"output",
"to",
"return",
"logits",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L975-L1010 |
22,320 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | symbol_top | def symbol_top(body_output, targets, model_hparams, vocab_size):
"""Generate logits.
Args:
body_output: A Tensor with shape
[batch, p0, p1, model_hparams.hidden_size].
targets: Unused.
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
logits: A Te... | python | def symbol_top(body_output, targets, model_hparams, vocab_size):
"""Generate logits.
Args:
body_output: A Tensor with shape
[batch, p0, p1, model_hparams.hidden_size].
targets: Unused.
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
logits: A Te... | [
"def",
"symbol_top",
"(",
"body_output",
",",
"targets",
",",
"model_hparams",
",",
"vocab_size",
")",
":",
"del",
"targets",
"# unused arg",
"if",
"model_hparams",
".",
"shared_embedding_and_softmax_weights",
":",
"scope_name",
"=",
"\"shared\"",
"reuse",
"=",
"tf"... | Generate logits.
Args:
body_output: A Tensor with shape
[batch, p0, p1, model_hparams.hidden_size].
targets: Unused.
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
logits: A Tensor with shape [batch, p0, p1, ?, vocab_size]. | [
"Generate",
"logits",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L1105-L1137 |
22,321 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | get_bottom | def get_bottom(modality_type, value=None):
"""Gets default bottom transformation; if none available, return value."""
if modality_type == ModalityType.AUDIO:
return audio_bottom
elif modality_type == ModalityType.AUDIO_SPECTRAL:
return audio_spectral_bottom
elif modality_type in (ModalityType.CLASS_LABE... | python | def get_bottom(modality_type, value=None):
"""Gets default bottom transformation; if none available, return value."""
if modality_type == ModalityType.AUDIO:
return audio_bottom
elif modality_type == ModalityType.AUDIO_SPECTRAL:
return audio_spectral_bottom
elif modality_type in (ModalityType.CLASS_LABE... | [
"def",
"get_bottom",
"(",
"modality_type",
",",
"value",
"=",
"None",
")",
":",
"if",
"modality_type",
"==",
"ModalityType",
".",
"AUDIO",
":",
"return",
"audio_bottom",
"elif",
"modality_type",
"==",
"ModalityType",
".",
"AUDIO_SPECTRAL",
":",
"return",
"audio_... | Gets default bottom transformation; if none available, return value. | [
"Gets",
"default",
"bottom",
"transformation",
";",
"if",
"none",
"available",
"return",
"value",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L1192-L1242 |
22,322 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | get_loss | def get_loss(modality_type, value=None):
"""Gets default loss transformation; if none available, return value."""
if modality_type in (ModalityType.AUDIO,
ModalityType.AUDIO_SPECTRAL,
ModalityType.CLASS_LABEL,
ModalityType.IDENTITY,
... | python | def get_loss(modality_type, value=None):
"""Gets default loss transformation; if none available, return value."""
if modality_type in (ModalityType.AUDIO,
ModalityType.AUDIO_SPECTRAL,
ModalityType.CLASS_LABEL,
ModalityType.IDENTITY,
... | [
"def",
"get_loss",
"(",
"modality_type",
",",
"value",
"=",
"None",
")",
":",
"if",
"modality_type",
"in",
"(",
"ModalityType",
".",
"AUDIO",
",",
"ModalityType",
".",
"AUDIO_SPECTRAL",
",",
"ModalityType",
".",
"CLASS_LABEL",
",",
"ModalityType",
".",
"IDENTI... | Gets default loss transformation; if none available, return value. | [
"Gets",
"default",
"loss",
"transformation",
";",
"if",
"none",
"available",
"return",
"value",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L1245-L1296 |
22,323 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | get_name | def get_name(modality_type, value=None):
"""Gets default name for transformations; if none available, return value."""
# For legacy reasons, modalities vary in their naming scheme. Future plans are
# to remove any need for get_name. We do not recommend using it.
if modality_type == ModalityType.AUDIO:
retur... | python | def get_name(modality_type, value=None):
"""Gets default name for transformations; if none available, return value."""
# For legacy reasons, modalities vary in their naming scheme. Future plans are
# to remove any need for get_name. We do not recommend using it.
if modality_type == ModalityType.AUDIO:
retur... | [
"def",
"get_name",
"(",
"modality_type",
",",
"value",
"=",
"None",
")",
":",
"# For legacy reasons, modalities vary in their naming scheme. Future plans are",
"# to remove any need for get_name. We do not recommend using it.",
"if",
"modality_type",
"==",
"ModalityType",
".",
"AUD... | Gets default name for transformations; if none available, return value. | [
"Gets",
"default",
"name",
"for",
"transformations",
";",
"if",
"none",
"available",
"return",
"value",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L1299-L1384 |
22,324 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | get_targets_bottom | def get_targets_bottom(modality_type, value=None):
"""Gets default bottom transformation for targets; if none, return value."""
if modality_type == ModalityType.AUDIO:
return make_targets_bottom(audio_bottom)
elif modality_type == ModalityType.AUDIO_SPECTRAL:
return make_targets_bottom(audio_spectral_bott... | python | def get_targets_bottom(modality_type, value=None):
"""Gets default bottom transformation for targets; if none, return value."""
if modality_type == ModalityType.AUDIO:
return make_targets_bottom(audio_bottom)
elif modality_type == ModalityType.AUDIO_SPECTRAL:
return make_targets_bottom(audio_spectral_bott... | [
"def",
"get_targets_bottom",
"(",
"modality_type",
",",
"value",
"=",
"None",
")",
":",
"if",
"modality_type",
"==",
"ModalityType",
".",
"AUDIO",
":",
"return",
"make_targets_bottom",
"(",
"audio_bottom",
")",
"elif",
"modality_type",
"==",
"ModalityType",
".",
... | Gets default bottom transformation for targets; if none, return value. | [
"Gets",
"default",
"bottom",
"transformation",
"for",
"targets",
";",
"if",
"none",
"return",
"value",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L1387-L1439 |
22,325 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | get_top | def get_top(modality_type, value=None):
"""Gets default top transformation; if none available, return value."""
if modality_type in (ModalityType.AUDIO,
ModalityType.AUDIO_SPECTRAL,
ModalityType.GENERIC_L2_LOSS,
ModalityType.IDENTITY,
... | python | def get_top(modality_type, value=None):
"""Gets default top transformation; if none available, return value."""
if modality_type in (ModalityType.AUDIO,
ModalityType.AUDIO_SPECTRAL,
ModalityType.GENERIC_L2_LOSS,
ModalityType.IDENTITY,
... | [
"def",
"get_top",
"(",
"modality_type",
",",
"value",
"=",
"None",
")",
":",
"if",
"modality_type",
"in",
"(",
"ModalityType",
".",
"AUDIO",
",",
"ModalityType",
".",
"AUDIO_SPECTRAL",
",",
"ModalityType",
".",
"GENERIC_L2_LOSS",
",",
"ModalityType",
".",
"IDE... | Gets default top transformation; if none available, return value. | [
"Gets",
"default",
"top",
"transformation",
";",
"if",
"none",
"available",
"return",
"value",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L1442-L1492 |
22,326 | tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | get_weights_fn | def get_weights_fn(modality_type, value=None):
"""Gets default weights function; if none available, return value."""
if modality_type in (ModalityType.CTC_SYMBOL,
ModalityType.IDENTITY_SYMBOL,
ModalityType.MULTI_LABEL,
ModalityType.SYMBOL,
... | python | def get_weights_fn(modality_type, value=None):
"""Gets default weights function; if none available, return value."""
if modality_type in (ModalityType.CTC_SYMBOL,
ModalityType.IDENTITY_SYMBOL,
ModalityType.MULTI_LABEL,
ModalityType.SYMBOL,
... | [
"def",
"get_weights_fn",
"(",
"modality_type",
",",
"value",
"=",
"None",
")",
":",
"if",
"modality_type",
"in",
"(",
"ModalityType",
".",
"CTC_SYMBOL",
",",
"ModalityType",
".",
"IDENTITY_SYMBOL",
",",
"ModalityType",
".",
"MULTI_LABEL",
",",
"ModalityType",
".... | Gets default weights function; if none available, return value. | [
"Gets",
"default",
"weights",
"function",
";",
"if",
"none",
"available",
"return",
"value",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L1495-L1505 |
22,327 | tensorflow/tensor2tensor | tensor2tensor/data_generators/paraphrase_ms_coco.py | create_combination | def create_combination(list_of_sentences):
"""Generates all possible pair combinations for the input list of sentences.
For example:
input = ["paraphrase1", "paraphrase2", "paraphrase3"]
output = [("paraphrase1", "paraphrase2"),
("paraphrase1", "paraphrase3"),
("paraphrase2", "paraphr... | python | def create_combination(list_of_sentences):
"""Generates all possible pair combinations for the input list of sentences.
For example:
input = ["paraphrase1", "paraphrase2", "paraphrase3"]
output = [("paraphrase1", "paraphrase2"),
("paraphrase1", "paraphrase3"),
("paraphrase2", "paraphr... | [
"def",
"create_combination",
"(",
"list_of_sentences",
")",
":",
"num_sentences",
"=",
"len",
"(",
"list_of_sentences",
")",
"-",
"1",
"combinations",
"=",
"[",
"]",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
"list_of_sentences",
")",
":",
"if",
"i",
"=... | Generates all possible pair combinations for the input list of sentences.
For example:
input = ["paraphrase1", "paraphrase2", "paraphrase3"]
output = [("paraphrase1", "paraphrase2"),
("paraphrase1", "paraphrase3"),
("paraphrase2", "paraphrase3")]
Args:
list_of_sentences: the list... | [
"Generates",
"all",
"possible",
"pair",
"combinations",
"for",
"the",
"input",
"list",
"of",
"sentences",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/paraphrase_ms_coco.py#L42-L67 |
22,328 | tensorflow/tensor2tensor | tensor2tensor/models/image_transformer_2d.py | imagetransformer2d_base_8l_8_32_big | def imagetransformer2d_base_8l_8_32_big():
"""hparams fo 8 layer big 2d model for cifar 10."""
hparams = image_transformer2d_base()
hparams.num_heads = 16
hparams.hidden_size = 1024
hparams.filter_size = 2048
hparams.num_decoder_layers = 8
hparams.batch_size = 1
hparams.layer_prepostprocess_dropout = 0.... | python | def imagetransformer2d_base_8l_8_32_big():
"""hparams fo 8 layer big 2d model for cifar 10."""
hparams = image_transformer2d_base()
hparams.num_heads = 16
hparams.hidden_size = 1024
hparams.filter_size = 2048
hparams.num_decoder_layers = 8
hparams.batch_size = 1
hparams.layer_prepostprocess_dropout = 0.... | [
"def",
"imagetransformer2d_base_8l_8_32_big",
"(",
")",
":",
"hparams",
"=",
"image_transformer2d_base",
"(",
")",
"hparams",
".",
"num_heads",
"=",
"16",
"hparams",
".",
"hidden_size",
"=",
"1024",
"hparams",
".",
"filter_size",
"=",
"2048",
"hparams",
".",
"nu... | hparams fo 8 layer big 2d model for cifar 10. | [
"hparams",
"fo",
"8",
"layer",
"big",
"2d",
"model",
"for",
"cifar",
"10",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer_2d.py#L485-L497 |
22,329 | tensorflow/tensor2tensor | tensor2tensor/models/image_transformer_2d.py | img2img_transformer2d_base | def img2img_transformer2d_base():
"""Base params for img2img 2d attention."""
hparams = image_transformer2d_base()
# learning related flags
hparams.layer_preprocess_sequence = "n"
hparams.layer_postprocess_sequence = "da"
# This version seems to benefit from a higher learning rate.
hparams.learning_rate =... | python | def img2img_transformer2d_base():
"""Base params for img2img 2d attention."""
hparams = image_transformer2d_base()
# learning related flags
hparams.layer_preprocess_sequence = "n"
hparams.layer_postprocess_sequence = "da"
# This version seems to benefit from a higher learning rate.
hparams.learning_rate =... | [
"def",
"img2img_transformer2d_base",
"(",
")",
":",
"hparams",
"=",
"image_transformer2d_base",
"(",
")",
"# learning related flags",
"hparams",
".",
"layer_preprocess_sequence",
"=",
"\"n\"",
"hparams",
".",
"layer_postprocess_sequence",
"=",
"\"da\"",
"# This version seem... | Base params for img2img 2d attention. | [
"Base",
"params",
"for",
"img2img",
"2d",
"attention",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer_2d.py#L585-L601 |
22,330 | tensorflow/tensor2tensor | tensor2tensor/models/image_transformer_2d.py | img2img_transformer2d_q3 | def img2img_transformer2d_q3():
"""Current best hparams for local 2d."""
hparams = img2img_transformer2d_q1()
hparams.batch_size = 2
hparams.query_shape = (8, 16)
hparams.memory_flange = (8, 32)
return hparams | python | def img2img_transformer2d_q3():
"""Current best hparams for local 2d."""
hparams = img2img_transformer2d_q1()
hparams.batch_size = 2
hparams.query_shape = (8, 16)
hparams.memory_flange = (8, 32)
return hparams | [
"def",
"img2img_transformer2d_q3",
"(",
")",
":",
"hparams",
"=",
"img2img_transformer2d_q1",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"2",
"hparams",
".",
"query_shape",
"=",
"(",
"8",
",",
"16",
")",
"hparams",
".",
"memory_flange",
"=",
"(",
"8",
",... | Current best hparams for local 2d. | [
"Current",
"best",
"hparams",
"for",
"local",
"2d",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer_2d.py#L627-L633 |
22,331 | tensorflow/tensor2tensor | tensor2tensor/models/image_transformer_2d.py | img2img_transformer_base | def img2img_transformer_base():
"""Base params for local1d attention."""
hparams = image_transformer2d_base()
# learning related flags
hparams.layer_preprocess_sequence = "n"
hparams.layer_postprocess_sequence = "da"
# This version seems to benefit from a higher learning rate.
hparams.learning_rate = 0.2
... | python | def img2img_transformer_base():
"""Base params for local1d attention."""
hparams = image_transformer2d_base()
# learning related flags
hparams.layer_preprocess_sequence = "n"
hparams.layer_postprocess_sequence = "da"
# This version seems to benefit from a higher learning rate.
hparams.learning_rate = 0.2
... | [
"def",
"img2img_transformer_base",
"(",
")",
":",
"hparams",
"=",
"image_transformer2d_base",
"(",
")",
"# learning related flags",
"hparams",
".",
"layer_preprocess_sequence",
"=",
"\"n\"",
"hparams",
".",
"layer_postprocess_sequence",
"=",
"\"da\"",
"# This version seems ... | Base params for local1d attention. | [
"Base",
"params",
"for",
"local1d",
"attention",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer_2d.py#L637-L654 |
22,332 | tensorflow/tensor2tensor | tensor2tensor/models/image_transformer_2d.py | img2img_transformer_b3 | def img2img_transformer_b3():
"""Current best hparams for local 1d."""
hparams = img2img_transformer_base()
hparams.batch_size = 2
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.block_length = 128
hparams.sampling_temp = 0.9
return hparams | python | def img2img_transformer_b3():
"""Current best hparams for local 1d."""
hparams = img2img_transformer_base()
hparams.batch_size = 2
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.block_length = 128
hparams.sampling_temp = 0.9
return hparams | [
"def",
"img2img_transformer_b3",
"(",
")",
":",
"hparams",
"=",
"img2img_transformer_base",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"2",
"hparams",
".",
"layer_preprocess_sequence",
"=",
"\"none\"",
"hparams",
".",
"layer_postprocess_sequence",
"=",
"\"dan\"",
... | Current best hparams for local 1d. | [
"Current",
"best",
"hparams",
"for",
"local",
"1d",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer_2d.py#L678-L686 |
22,333 | tensorflow/tensor2tensor | tensor2tensor/models/image_transformer_2d.py | img2img_transformer_dilated | def img2img_transformer_dilated():
"""Try dilated."""
hparams = img2img_transformer_base()
hparams.add_hparam("num_memory_blocks", 1)
hparams.num_heads = 8
hparams.attention_key_channels = hparams.attention_value_channels = 0
hparams.hidden_size = 512
hparams.filter_size = 2048
hparams.num_decoder_layer... | python | def img2img_transformer_dilated():
"""Try dilated."""
hparams = img2img_transformer_base()
hparams.add_hparam("num_memory_blocks", 1)
hparams.num_heads = 8
hparams.attention_key_channels = hparams.attention_value_channels = 0
hparams.hidden_size = 512
hparams.filter_size = 2048
hparams.num_decoder_layer... | [
"def",
"img2img_transformer_dilated",
"(",
")",
":",
"hparams",
"=",
"img2img_transformer_base",
"(",
")",
"hparams",
".",
"add_hparam",
"(",
"\"num_memory_blocks\"",
",",
"1",
")",
"hparams",
".",
"num_heads",
"=",
"8",
"hparams",
".",
"attention_key_channels",
"... | Try dilated. | [
"Try",
"dilated",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer_2d.py#L760-L775 |
22,334 | tensorflow/tensor2tensor | tensor2tensor/models/image_transformer_2d.py | img2img_transformer_base_tpu | def img2img_transformer_base_tpu():
"""Hparams for training img2img_transformer on tpu."""
hparams = img2img_transformer_base()
update_hparams_for_tpu(hparams)
hparams.batch_size = 2
hparams.num_heads = 4 # heads are expensive on tpu
hparams.num_decoder_layers = 8
hparams.num_encoder_layers = 4
hparam... | python | def img2img_transformer_base_tpu():
"""Hparams for training img2img_transformer on tpu."""
hparams = img2img_transformer_base()
update_hparams_for_tpu(hparams)
hparams.batch_size = 2
hparams.num_heads = 4 # heads are expensive on tpu
hparams.num_decoder_layers = 8
hparams.num_encoder_layers = 4
hparam... | [
"def",
"img2img_transformer_base_tpu",
"(",
")",
":",
"hparams",
"=",
"img2img_transformer_base",
"(",
")",
"update_hparams_for_tpu",
"(",
"hparams",
")",
"hparams",
".",
"batch_size",
"=",
"2",
"hparams",
".",
"num_heads",
"=",
"4",
"# heads are expensive on tpu",
... | Hparams for training img2img_transformer on tpu. | [
"Hparams",
"for",
"training",
"img2img_transformer",
"on",
"tpu",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer_2d.py#L794-L803 |
22,335 | tensorflow/tensor2tensor | tensor2tensor/trax/models/transformer.py | ResidualFeedForward | def ResidualFeedForward(feature_depth,
feedforward_depth,
dropout,
mode):
"""Residual feed-forward layer with normalization at start."""
return layers.Residual(
layers.LayerNorm(),
layers.Dense(feedforward_depth),
layers.Relu(... | python | def ResidualFeedForward(feature_depth,
feedforward_depth,
dropout,
mode):
"""Residual feed-forward layer with normalization at start."""
return layers.Residual(
layers.LayerNorm(),
layers.Dense(feedforward_depth),
layers.Relu(... | [
"def",
"ResidualFeedForward",
"(",
"feature_depth",
",",
"feedforward_depth",
",",
"dropout",
",",
"mode",
")",
":",
"return",
"layers",
".",
"Residual",
"(",
"layers",
".",
"LayerNorm",
"(",
")",
",",
"layers",
".",
"Dense",
"(",
"feedforward_depth",
")",
"... | Residual feed-forward layer with normalization at start. | [
"Residual",
"feed",
"-",
"forward",
"layer",
"with",
"normalization",
"at",
"start",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/models/transformer.py#L24-L36 |
22,336 | tensorflow/tensor2tensor | tensor2tensor/trax/models/transformer.py | EncoderLayer | def EncoderLayer(feature_depth,
feedforward_depth,
num_heads,
dropout,
mode):
"""Transformer encoder layer.
The input to the encoder is a pair (embedded source, mask) where
the mask is created from the original source to prevent attending
to t... | python | def EncoderLayer(feature_depth,
feedforward_depth,
num_heads,
dropout,
mode):
"""Transformer encoder layer.
The input to the encoder is a pair (embedded source, mask) where
the mask is created from the original source to prevent attending
to t... | [
"def",
"EncoderLayer",
"(",
"feature_depth",
",",
"feedforward_depth",
",",
"num_heads",
",",
"dropout",
",",
"mode",
")",
":",
"# The encoder block expects (activation, mask) as input and returns",
"# the new activations only, we add the mask back to output next.",
"encoder_block",
... | Transformer encoder layer.
The input to the encoder is a pair (embedded source, mask) where
the mask is created from the original source to prevent attending
to the padding part of the input.
Args:
feature_depth: int: depth of embedding
feedforward_depth: int: depth of feed-forward layer
num_head... | [
"Transformer",
"encoder",
"layer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/models/transformer.py#L39-L76 |
22,337 | tensorflow/tensor2tensor | tensor2tensor/trax/models/transformer.py | TransformerEncoder | def TransformerEncoder(vocab_size,
num_classes=10,
feature_depth=512,
feedforward_depth=2048,
num_layers=6,
num_heads=8,
dropout=0.1,
max_len=2048,
... | python | def TransformerEncoder(vocab_size,
num_classes=10,
feature_depth=512,
feedforward_depth=2048,
num_layers=6,
num_heads=8,
dropout=0.1,
max_len=2048,
... | [
"def",
"TransformerEncoder",
"(",
"vocab_size",
",",
"num_classes",
"=",
"10",
",",
"feature_depth",
"=",
"512",
",",
"feedforward_depth",
"=",
"2048",
",",
"num_layers",
"=",
"6",
",",
"num_heads",
"=",
"8",
",",
"dropout",
"=",
"0.1",
",",
"max_len",
"="... | Transformer encoder.
Args:
vocab_size: int: vocab size
num_classes: how many classes on output
feature_depth: int: depth of embedding
feedforward_depth: int: depth of feed-forward layer
num_layers: int: number of encoder/decoder layers
num_heads: int: number of attention heads
dropout: f... | [
"Transformer",
"encoder",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/models/transformer.py#L79-L120 |
22,338 | tensorflow/tensor2tensor | tensor2tensor/trax/models/transformer.py | DecoderLayer | def DecoderLayer(feature_depth,
feedforward_depth,
num_heads,
dropout,
mode):
"""Transformer decoder layer.
Args:
feature_depth: int: depth of embedding
feedforward_depth: int: depth of feed-forward layer
num_heads: int: number of att... | python | def DecoderLayer(feature_depth,
feedforward_depth,
num_heads,
dropout,
mode):
"""Transformer decoder layer.
Args:
feature_depth: int: depth of embedding
feedforward_depth: int: depth of feed-forward layer
num_heads: int: number of att... | [
"def",
"DecoderLayer",
"(",
"feature_depth",
",",
"feedforward_depth",
",",
"num_heads",
",",
"dropout",
",",
"mode",
")",
":",
"return",
"layers",
".",
"Serial",
"(",
"layers",
".",
"Residual",
"(",
"# Self-attention block.",
"layers",
".",
"LayerNorm",
"(",
... | Transformer decoder layer.
Args:
feature_depth: int: depth of embedding
feedforward_depth: int: depth of feed-forward layer
num_heads: int: number of attention heads
dropout: float: dropout rate (how much to drop out)
mode: str: 'train' or 'eval'
Returns:
the layer. | [
"Transformer",
"decoder",
"layer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/models/transformer.py#L123-L151 |
22,339 | tensorflow/tensor2tensor | tensor2tensor/trax/models/transformer.py | ChunkedDecoderLayer | def ChunkedDecoderLayer(feature_depth,
feedforward_depth,
num_heads,
dropout,
chunk_selector,
mode):
"""Transformer decoder layer operating on chunks.
Args:
feature_depth: int: depth of embe... | python | def ChunkedDecoderLayer(feature_depth,
feedforward_depth,
num_heads,
dropout,
chunk_selector,
mode):
"""Transformer decoder layer operating on chunks.
Args:
feature_depth: int: depth of embe... | [
"def",
"ChunkedDecoderLayer",
"(",
"feature_depth",
",",
"feedforward_depth",
",",
"num_heads",
",",
"dropout",
",",
"chunk_selector",
",",
"mode",
")",
":",
"return",
"layers",
".",
"Serial",
"(",
"layers",
".",
"Residual",
"(",
"# Self-attention block.",
"layers... | Transformer decoder layer operating on chunks.
Args:
feature_depth: int: depth of embedding
feedforward_depth: int: depth of feed-forward layer
num_heads: int: number of attention heads
dropout: float: dropout rate (how much to drop out)
chunk_selector: a function from chunk number to list of ch... | [
"Transformer",
"decoder",
"layer",
"operating",
"on",
"chunks",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/models/transformer.py#L191-L220 |
22,340 | tensorflow/tensor2tensor | tensor2tensor/trax/models/transformer.py | ChunkedTransformerLM | def ChunkedTransformerLM(vocab_size,
feature_depth=512,
feedforward_depth=2048,
num_layers=6,
num_heads=8,
dropout=0.1,
chunk_selector=None,
max_... | python | def ChunkedTransformerLM(vocab_size,
feature_depth=512,
feedforward_depth=2048,
num_layers=6,
num_heads=8,
dropout=0.1,
chunk_selector=None,
max_... | [
"def",
"ChunkedTransformerLM",
"(",
"vocab_size",
",",
"feature_depth",
"=",
"512",
",",
"feedforward_depth",
"=",
"2048",
",",
"num_layers",
"=",
"6",
",",
"num_heads",
"=",
"8",
",",
"dropout",
"=",
"0.1",
",",
"chunk_selector",
"=",
"None",
",",
"max_len"... | Transformer language model operating on chunks.
The input to this model is a sequence presented as a list or tuple of chunks:
(chunk1, chunk2, chunks3, ..., chunkN).
Each chunk should have the same shape (batch, chunk-length) and together they
represent a long sequence that's a concatenation chunk1,chunk2,.... | [
"Transformer",
"language",
"model",
"operating",
"on",
"chunks",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/models/transformer.py#L223-L273 |
22,341 | tensorflow/tensor2tensor | tensor2tensor/models/mtf_transformer.py | mtf_transformer_paper_lm | def mtf_transformer_paper_lm(size):
"""Config for language-model experiments.
Train these on languagemodel_lm1b32k_packed for 136000 steps (10 epochs)
The size parameter is an integer that controls the number of heads and the
size of the size of the feedforward hidden layers. Increasing size by 1
doubles e... | python | def mtf_transformer_paper_lm(size):
"""Config for language-model experiments.
Train these on languagemodel_lm1b32k_packed for 136000 steps (10 epochs)
The size parameter is an integer that controls the number of heads and the
size of the size of the feedforward hidden layers. Increasing size by 1
doubles e... | [
"def",
"mtf_transformer_paper_lm",
"(",
"size",
")",
":",
"n",
"=",
"2",
"**",
"size",
"hparams",
"=",
"mtf_transformer_base_lm",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"256",
"hparams",
".",
"d_model",
"=",
"1024",
"hparams",
".",
"d_ff",
"=",
"int"... | Config for language-model experiments.
Train these on languagemodel_lm1b32k_packed for 136000 steps (10 epochs)
The size parameter is an integer that controls the number of heads and the
size of the size of the feedforward hidden layers. Increasing size by 1
doubles each of these.
Results:
size params... | [
"Config",
"for",
"language",
"-",
"model",
"experiments",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer.py#L953-L989 |
22,342 | tensorflow/tensor2tensor | tensor2tensor/models/mtf_transformer.py | mtf_transformer_paper_tr | def mtf_transformer_paper_tr(size):
"""Config for translation experiments.
Train these on translate_enfr_wmt32k_packed for 154000 steps (3 epochs)
The size parameter is an integer that controls the number of heads and the
size of the size of the feedforward hidden layers. Increasing size by 1
doubles each ... | python | def mtf_transformer_paper_tr(size):
"""Config for translation experiments.
Train these on translate_enfr_wmt32k_packed for 154000 steps (3 epochs)
The size parameter is an integer that controls the number of heads and the
size of the size of the feedforward hidden layers. Increasing size by 1
doubles each ... | [
"def",
"mtf_transformer_paper_tr",
"(",
"size",
")",
":",
"n",
"=",
"2",
"**",
"size",
"hparams",
"=",
"mtf_transformer_base",
"(",
")",
"hparams",
".",
"label_smoothing",
"=",
"0.1",
"hparams",
".",
"batch_size",
"=",
"128",
"hparams",
".",
"d_model",
"=",
... | Config for translation experiments.
Train these on translate_enfr_wmt32k_packed for 154000 steps (3 epochs)
The size parameter is an integer that controls the number of heads and the
size of the size of the feedforward hidden layers. Increasing size by 1
doubles each of these.
Args:
size: an integer
... | [
"Config",
"for",
"translation",
"experiments",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer.py#L1041-L1065 |
22,343 | tensorflow/tensor2tensor | tensor2tensor/models/mtf_transformer.py | mtf_transformer_lm_baseline | def mtf_transformer_lm_baseline():
"""Small language model to run on 1 TPU.
Run this on 2x2 on languagemodel_lm1b32k_packed for 272000 steps (10 epochs)
Results:
params/10^9 log-ppl(per-token)
0.14 3.202
Returns:
a hparams
"""
hparams = mtf_transformer_paper_lm(-1)
hparams... | python | def mtf_transformer_lm_baseline():
"""Small language model to run on 1 TPU.
Run this on 2x2 on languagemodel_lm1b32k_packed for 272000 steps (10 epochs)
Results:
params/10^9 log-ppl(per-token)
0.14 3.202
Returns:
a hparams
"""
hparams = mtf_transformer_paper_lm(-1)
hparams... | [
"def",
"mtf_transformer_lm_baseline",
"(",
")",
":",
"hparams",
"=",
"mtf_transformer_paper_lm",
"(",
"-",
"1",
")",
"hparams",
".",
"batch_size",
"=",
"128",
"hparams",
".",
"learning_rate_decay_steps",
"=",
"27200",
"# one epoch on lm1b",
"hparams",
".",
"mesh_sha... | Small language model to run on 1 TPU.
Run this on 2x2 on languagemodel_lm1b32k_packed for 272000 steps (10 epochs)
Results:
params/10^9 log-ppl(per-token)
0.14 3.202
Returns:
a hparams | [
"Small",
"language",
"model",
"to",
"run",
"on",
"1",
"TPU",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer.py#L1171-L1186 |
22,344 | tensorflow/tensor2tensor | tensor2tensor/layers/message_passing_attention.py | graph_attention | def graph_attention(q,
k,
v,
bias,
dropout_rate=0.0,
image_shapes=None,
name=None,
make_image_summary=True,
save_weights_to=None,
dropout_br... | python | def graph_attention(q,
k,
v,
bias,
dropout_rate=0.0,
image_shapes=None,
name=None,
make_image_summary=True,
save_weights_to=None,
dropout_br... | [
"def",
"graph_attention",
"(",
"q",
",",
"k",
",",
"v",
",",
"bias",
",",
"dropout_rate",
"=",
"0.0",
",",
"image_shapes",
"=",
"None",
",",
"name",
"=",
"None",
",",
"make_image_summary",
"=",
"True",
",",
"save_weights_to",
"=",
"None",
",",
"dropout_b... | graph attention.
Args:
q: a Tensor with shape [batch, heads, length_q, depth_k]
k: a Tensor with shape [batch, heads, length_kv, depth_k]
v: a Tensor with shape [batch, heads, length_kv, depth_v]
bias: bias Tensor (see attention_bias())
dropout_rate: a floating point number
image_shapes: opti... | [
"graph",
"attention",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/message_passing_attention.py#L185-L248 |
22,345 | tensorflow/tensor2tensor | tensor2tensor/layers/message_passing_attention.py | _compute_edge_transforms | def _compute_edge_transforms(node_states,
depth,
num_transforms,
name="transform"):
"""Helper function that computes transformation for keys and values.
Let B be the number of batches.
Let N be the number of nodes in the graph... | python | def _compute_edge_transforms(node_states,
depth,
num_transforms,
name="transform"):
"""Helper function that computes transformation for keys and values.
Let B be the number of batches.
Let N be the number of nodes in the graph... | [
"def",
"_compute_edge_transforms",
"(",
"node_states",
",",
"depth",
",",
"num_transforms",
",",
"name",
"=",
"\"transform\"",
")",
":",
"node_shapes",
"=",
"common_layers",
".",
"shape_list",
"(",
"node_states",
")",
"x",
"=",
"common_layers",
".",
"dense",
"("... | Helper function that computes transformation for keys and values.
Let B be the number of batches.
Let N be the number of nodes in the graph.
Let D be the size of the node hidden states.
Let K be the size of the attention keys/queries (total_key_depth).
Let V be the size of the attention values (total_value_d... | [
"Helper",
"function",
"that",
"computes",
"transformation",
"for",
"keys",
"and",
"values",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/message_passing_attention.py#L251-L301 |
22,346 | tensorflow/tensor2tensor | tensor2tensor/layers/message_passing_attention.py | compute_mpnn_qkv | def compute_mpnn_qkv(node_states,
total_key_depth,
total_value_depth,
num_transforms):
"""Computes query, key and value for edge matrices.
Let B be the number of batches.
Let N be the number of nodes in the graph.
Let D be the size of the node hidd... | python | def compute_mpnn_qkv(node_states,
total_key_depth,
total_value_depth,
num_transforms):
"""Computes query, key and value for edge matrices.
Let B be the number of batches.
Let N be the number of nodes in the graph.
Let D be the size of the node hidd... | [
"def",
"compute_mpnn_qkv",
"(",
"node_states",
",",
"total_key_depth",
",",
"total_value_depth",
",",
"num_transforms",
")",
":",
"# node_states is initially a tensor with shape [B, N, D]. The call to dense",
"# creates a D x K kernel that serves as a fully-connected layer.",
"#",
"# F... | Computes query, key and value for edge matrices.
Let B be the number of batches.
Let N be the number of nodes in the graph.
Let D be the size of the node hidden states.
Let K be the size of the attention keys/queries (total_key_depth).
Let V be the size of the attention values (total_value_depth).
Let T be... | [
"Computes",
"query",
"key",
"and",
"value",
"for",
"edge",
"matrices",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/message_passing_attention.py#L304-L364 |
22,347 | tensorflow/tensor2tensor | tensor2tensor/layers/message_passing_attention.py | sparse_message_pass_batched | def sparse_message_pass_batched(node_states,
adjacency_matrices,
num_edge_types,
hidden_size,
use_bias=True,
average_aggregation=False,
... | python | def sparse_message_pass_batched(node_states,
adjacency_matrices,
num_edge_types,
hidden_size,
use_bias=True,
average_aggregation=False,
... | [
"def",
"sparse_message_pass_batched",
"(",
"node_states",
",",
"adjacency_matrices",
",",
"num_edge_types",
",",
"hidden_size",
",",
"use_bias",
"=",
"True",
",",
"average_aggregation",
"=",
"False",
",",
"name",
"=",
"\"sparse_ggnn_batched\"",
")",
":",
"b",
",",
... | Identical to sparse_ggnn except that each input has a batch dimension.
B = The batch size.
N = The number of nodes in each batch.
H = The size of the hidden states.
T = The number of edge types.
Args:
node_states: Initial states of each node in the graph. Shape: [B, N, H]
adjacency_matrices: Adjacen... | [
"Identical",
"to",
"sparse_ggnn",
"except",
"that",
"each",
"input",
"has",
"a",
"batch",
"dimension",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/message_passing_attention.py#L367-L428 |
22,348 | tensorflow/tensor2tensor | tensor2tensor/layers/message_passing_attention.py | sparse_message_pass | def sparse_message_pass(node_states,
adjacency_matrices,
num_edge_types,
hidden_size,
use_bias=True,
average_aggregation=False,
name="sparse_ggnn"):
"""One message-passing st... | python | def sparse_message_pass(node_states,
adjacency_matrices,
num_edge_types,
hidden_size,
use_bias=True,
average_aggregation=False,
name="sparse_ggnn"):
"""One message-passing st... | [
"def",
"sparse_message_pass",
"(",
"node_states",
",",
"adjacency_matrices",
",",
"num_edge_types",
",",
"hidden_size",
",",
"use_bias",
"=",
"True",
",",
"average_aggregation",
"=",
"False",
",",
"name",
"=",
"\"sparse_ggnn\"",
")",
":",
"n",
"=",
"tf",
".",
... | One message-passing step for a GNN with a sparse adjacency matrix.
Implements equation 2 (the message passing step) in
[Li et al. 2015](https://arxiv.org/abs/1511.05493).
N = The number of nodes in each batch.
H = The size of the hidden states.
T = The number of edge types.
Args:
node_states: Initial... | [
"One",
"message",
"-",
"passing",
"step",
"for",
"a",
"GNN",
"with",
"a",
"sparse",
"adjacency",
"matrix",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/message_passing_attention.py#L431-L511 |
22,349 | tensorflow/tensor2tensor | tensor2tensor/layers/message_passing_attention.py | dot_product_mpnn_attention | def dot_product_mpnn_attention(q,
k,
v,
adjacency_matrix,
num_edge_types,
num_transforms=None,
use_weighted_sum=False,
... | python | def dot_product_mpnn_attention(q,
k,
v,
adjacency_matrix,
num_edge_types,
num_transforms=None,
use_weighted_sum=False,
... | [
"def",
"dot_product_mpnn_attention",
"(",
"q",
",",
"k",
",",
"v",
",",
"adjacency_matrix",
",",
"num_edge_types",
",",
"num_transforms",
"=",
"None",
",",
"use_weighted_sum",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_sco... | Dot product attention with edge vectors.
Let B be the number of batches.
Let N be the number of nodes in the graph.
Let K be the size of the attention keys/queries.
Let V be the size of the attention values.
Let T be the total number of transforms (num_transforms).
Args:
q: The query Tensor of shape [... | [
"Dot",
"product",
"attention",
"with",
"edge",
"vectors",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/message_passing_attention.py#L652-L783 |
22,350 | tensorflow/tensor2tensor | tensor2tensor/layers/message_passing_attention.py | ggnn_fast_dense | def ggnn_fast_dense(node_states,
adjacency_matrix,
num_edge_types,
total_value_depth,
name=None):
"""ggnn version of the MPNN from Gilmer et al.
Let B be the number of batches.
Let D be the size of the node hidden states.
Let K be ... | python | def ggnn_fast_dense(node_states,
adjacency_matrix,
num_edge_types,
total_value_depth,
name=None):
"""ggnn version of the MPNN from Gilmer et al.
Let B be the number of batches.
Let D be the size of the node hidden states.
Let K be ... | [
"def",
"ggnn_fast_dense",
"(",
"node_states",
",",
"adjacency_matrix",
",",
"num_edge_types",
",",
"total_value_depth",
",",
"name",
"=",
"None",
")",
":",
"# between the same nodes (with only one edge of each type. adjacency_matrix",
"# will need to be converted to shape [B, T, N,... | ggnn version of the MPNN from Gilmer et al.
Let B be the number of batches.
Let D be the size of the node hidden states.
Let K be the size of the attention keys/queries.
Let V be the size of the output of the ggnn.
Let T be the number of transforms / edge types.
Args:
node_states: The value Tensor of ... | [
"ggnn",
"version",
"of",
"the",
"MPNN",
"from",
"Gilmer",
"et",
"al",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/message_passing_attention.py#L786-L837 |
22,351 | tensorflow/tensor2tensor | tensor2tensor/layers/message_passing_attention.py | compute_values | def compute_values(edge_compatibility, v):
"""Compute values. If edge compatibilities is just adjacency, we get ggnn.
Args:
edge_compatibility: A tensor of shape [batch, num_transforms, length, depth]
v: A tensor of shape [batch, num_transforms, length, depth]
Returns:
output: A [batch, length, dept... | python | def compute_values(edge_compatibility, v):
"""Compute values. If edge compatibilities is just adjacency, we get ggnn.
Args:
edge_compatibility: A tensor of shape [batch, num_transforms, length, depth]
v: A tensor of shape [batch, num_transforms, length, depth]
Returns:
output: A [batch, length, dept... | [
"def",
"compute_values",
"(",
"edge_compatibility",
",",
"v",
")",
":",
"# Computes the incoming value vectors for each node by weighting them",
"# according to the attention weights. These values are still segregated by",
"# edge type.",
"# Shape = [B, T, N, V].",
"all_edge_values",
"=",
... | Compute values. If edge compatibilities is just adjacency, we get ggnn.
Args:
edge_compatibility: A tensor of shape [batch, num_transforms, length, depth]
v: A tensor of shape [batch, num_transforms, length, depth]
Returns:
output: A [batch, length, depth] tensor | [
"Compute",
"values",
".",
"If",
"edge",
"compatibilities",
"is",
"just",
"adjacency",
"we",
"get",
"ggnn",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/message_passing_attention.py#L840-L860 |
22,352 | tensorflow/tensor2tensor | tensor2tensor/layers/message_passing_attention.py | precompute_edge_matrices | def precompute_edge_matrices(adjacency, hparams):
"""Precompute the a_in and a_out tensors.
(we don't want to add to the graph everytime _fprop is called)
Args:
adjacency: placeholder of real valued vectors of shape [B, L, L, E]
hparams: HParams object
Returns:
edge_matrices: [batch, L * D, L * D] ... | python | def precompute_edge_matrices(adjacency, hparams):
"""Precompute the a_in and a_out tensors.
(we don't want to add to the graph everytime _fprop is called)
Args:
adjacency: placeholder of real valued vectors of shape [B, L, L, E]
hparams: HParams object
Returns:
edge_matrices: [batch, L * D, L * D] ... | [
"def",
"precompute_edge_matrices",
"(",
"adjacency",
",",
"hparams",
")",
":",
"batch_size",
",",
"num_nodes",
",",
"_",
",",
"edge_dim",
"=",
"common_layers",
".",
"shape_list",
"(",
"adjacency",
")",
"# build the edge_network for incoming edges",
"with",
"tf",
"."... | Precompute the a_in and a_out tensors.
(we don't want to add to the graph everytime _fprop is called)
Args:
adjacency: placeholder of real valued vectors of shape [B, L, L, E]
hparams: HParams object
Returns:
edge_matrices: [batch, L * D, L * D] the dense matrix for message passing
viewed as a bl... | [
"Precompute",
"the",
"a_in",
"and",
"a_out",
"tensors",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/message_passing_attention.py#L863-L907 |
22,353 | tensorflow/tensor2tensor | tensor2tensor/data_generators/generator_utils.py | generate_files_distributed | def generate_files_distributed(generator,
output_name,
output_dir,
num_shards=1,
max_cases=None,
task_id=0):
"""generate_files but with a single writer writing to ... | python | def generate_files_distributed(generator,
output_name,
output_dir,
num_shards=1,
max_cases=None,
task_id=0):
"""generate_files but with a single writer writing to ... | [
"def",
"generate_files_distributed",
"(",
"generator",
",",
"output_name",
",",
"output_dir",
",",
"num_shards",
"=",
"1",
",",
"max_cases",
"=",
"None",
",",
"task_id",
"=",
"0",
")",
":",
"assert",
"task_id",
"<",
"num_shards",
"output_filename",
"=",
"shard... | generate_files but with a single writer writing to shard task_id. | [
"generate_files",
"but",
"with",
"a",
"single",
"writer",
"writing",
"to",
"shard",
"task_id",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L65-L89 |
22,354 | tensorflow/tensor2tensor | tensor2tensor/data_generators/generator_utils.py | generate_files | def generate_files(generator, output_filenames,
max_cases=None, cycle_every_n=1):
"""Generate cases from a generator and save as TFRecord files.
Generated cases are transformed to tf.Example protos and saved as TFRecords
in sharded files named output_dir/output_name-00..N-of-00..M=num_shards.
... | python | def generate_files(generator, output_filenames,
max_cases=None, cycle_every_n=1):
"""Generate cases from a generator and save as TFRecord files.
Generated cases are transformed to tf.Example protos and saved as TFRecords
in sharded files named output_dir/output_name-00..N-of-00..M=num_shards.
... | [
"def",
"generate_files",
"(",
"generator",
",",
"output_filenames",
",",
"max_cases",
"=",
"None",
",",
"cycle_every_n",
"=",
"1",
")",
":",
"if",
"outputs_exist",
"(",
"output_filenames",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Skipping generator... | Generate cases from a generator and save as TFRecord files.
Generated cases are transformed to tf.Example protos and saved as TFRecords
in sharded files named output_dir/output_name-00..N-of-00..M=num_shards.
Args:
generator: a generator yielding (string -> int/float/str list) dictionaries.
output_filen... | [
"Generate",
"cases",
"from",
"a",
"generator",
"and",
"save",
"as",
"TFRecord",
"files",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L134-L193 |
22,355 | tensorflow/tensor2tensor | tensor2tensor/data_generators/generator_utils.py | download_report_hook | def download_report_hook(count, block_size, total_size):
"""Report hook for download progress.
Args:
count: current block number
block_size: block size
total_size: total size
"""
percent = int(count * block_size * 100 / total_size)
print("\r%d%%" % percent + " completed", end="\r") | python | def download_report_hook(count, block_size, total_size):
"""Report hook for download progress.
Args:
count: current block number
block_size: block size
total_size: total size
"""
percent = int(count * block_size * 100 / total_size)
print("\r%d%%" % percent + " completed", end="\r") | [
"def",
"download_report_hook",
"(",
"count",
",",
"block_size",
",",
"total_size",
")",
":",
"percent",
"=",
"int",
"(",
"count",
"*",
"block_size",
"*",
"100",
"/",
"total_size",
")",
"print",
"(",
"\"\\r%d%%\"",
"%",
"percent",
"+",
"\" completed\"",
",",
... | Report hook for download progress.
Args:
count: current block number
block_size: block size
total_size: total size | [
"Report",
"hook",
"for",
"download",
"progress",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L196-L205 |
22,356 | tensorflow/tensor2tensor | tensor2tensor/data_generators/generator_utils.py | maybe_download | def maybe_download(directory, filename, uri):
"""Download filename from uri unless it's already in directory.
Copies a remote file to local if that local file does not already exist. If
the local file pre-exists this function call, it does not check that the local
file is a copy of the remote.
Remote filen... | python | def maybe_download(directory, filename, uri):
"""Download filename from uri unless it's already in directory.
Copies a remote file to local if that local file does not already exist. If
the local file pre-exists this function call, it does not check that the local
file is a copy of the remote.
Remote filen... | [
"def",
"maybe_download",
"(",
"directory",
",",
"filename",
",",
"uri",
")",
":",
"tf",
".",
"gfile",
".",
"MakeDirs",
"(",
"directory",
")",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"filename",
")",
"if",
"tf",
".",
"g... | Download filename from uri unless it's already in directory.
Copies a remote file to local if that local file does not already exist. If
the local file pre-exists this function call, it does not check that the local
file is a copy of the remote.
Remote filenames can be filepaths, any URI readable by tensorfl... | [
"Download",
"filename",
"from",
"uri",
"unless",
"it",
"s",
"already",
"in",
"directory",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L208-L248 |
22,357 | tensorflow/tensor2tensor | tensor2tensor/data_generators/generator_utils.py | maybe_download_from_drive | def maybe_download_from_drive(directory, filename, url):
"""Download filename from Google drive unless it's already in directory.
Args:
directory: path to the directory that will be used.
filename: name of the file to download to (do nothing if it already exists).
url: URL to download from.
Returns:... | python | def maybe_download_from_drive(directory, filename, url):
"""Download filename from Google drive unless it's already in directory.
Args:
directory: path to the directory that will be used.
filename: name of the file to download to (do nothing if it already exists).
url: URL to download from.
Returns:... | [
"def",
"maybe_download_from_drive",
"(",
"directory",
",",
"filename",
",",
"url",
")",
":",
"if",
"not",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"directory",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Creating directory %s\"",
"%",
"directory",
... | Download filename from Google drive unless it's already in directory.
Args:
directory: path to the directory that will be used.
filename: name of the file to download to (do nothing if it already exists).
url: URL to download from.
Returns:
The path to the downloaded file. | [
"Download",
"filename",
"from",
"Google",
"drive",
"unless",
"it",
"s",
"already",
"in",
"directory",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L251-L298 |
22,358 | tensorflow/tensor2tensor | tensor2tensor/data_generators/generator_utils.py | gunzip_file | def gunzip_file(gz_path, new_path):
"""Unzips from gz_path into new_path.
Args:
gz_path: path to the zipped file.
new_path: path to where the file will be unzipped.
"""
if tf.gfile.Exists(new_path):
tf.logging.info("File %s already exists, skipping unpacking" % new_path)
return
tf.logging.inf... | python | def gunzip_file(gz_path, new_path):
"""Unzips from gz_path into new_path.
Args:
gz_path: path to the zipped file.
new_path: path to where the file will be unzipped.
"""
if tf.gfile.Exists(new_path):
tf.logging.info("File %s already exists, skipping unpacking" % new_path)
return
tf.logging.inf... | [
"def",
"gunzip_file",
"(",
"gz_path",
",",
"new_path",
")",
":",
"if",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"new_path",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"File %s already exists, skipping unpacking\"",
"%",
"new_path",
")",
"return",
"tf... | Unzips from gz_path into new_path.
Args:
gz_path: path to the zipped file.
new_path: path to where the file will be unzipped. | [
"Unzips",
"from",
"gz_path",
"into",
"new_path",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L301-L318 |
22,359 | tensorflow/tensor2tensor | tensor2tensor/data_generators/generator_utils.py | get_or_generate_vocab_inner | def get_or_generate_vocab_inner(data_dir, vocab_filename, vocab_size,
generator, max_subtoken_length=None,
reserved_tokens=None):
"""Inner implementation for vocab generators.
Args:
data_dir: The base directory where data and vocab files are store... | python | def get_or_generate_vocab_inner(data_dir, vocab_filename, vocab_size,
generator, max_subtoken_length=None,
reserved_tokens=None):
"""Inner implementation for vocab generators.
Args:
data_dir: The base directory where data and vocab files are store... | [
"def",
"get_or_generate_vocab_inner",
"(",
"data_dir",
",",
"vocab_filename",
",",
"vocab_size",
",",
"generator",
",",
"max_subtoken_length",
"=",
"None",
",",
"reserved_tokens",
"=",
"None",
")",
":",
"if",
"data_dir",
"and",
"vocab_filename",
":",
"vocab_filepath... | Inner implementation for vocab generators.
Args:
data_dir: The base directory where data and vocab files are stored. If None,
then do not save the vocab even if it doesn't exist.
vocab_filename: relative filename where vocab file is stored
vocab_size: target size of the vocabulary constructed by Su... | [
"Inner",
"implementation",
"for",
"vocab",
"generators",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L321-L358 |
22,360 | tensorflow/tensor2tensor | tensor2tensor/data_generators/generator_utils.py | get_or_generate_vocab | def get_or_generate_vocab(data_dir, tmp_dir, vocab_filename, vocab_size,
sources, file_byte_budget=1e6,
max_subtoken_length=None):
"""Generate a vocabulary from the datasets in sources."""
vocab_generator = generate_lines_for_vocab(tmp_dir, sources, file_byte_bud... | python | def get_or_generate_vocab(data_dir, tmp_dir, vocab_filename, vocab_size,
sources, file_byte_budget=1e6,
max_subtoken_length=None):
"""Generate a vocabulary from the datasets in sources."""
vocab_generator = generate_lines_for_vocab(tmp_dir, sources, file_byte_bud... | [
"def",
"get_or_generate_vocab",
"(",
"data_dir",
",",
"tmp_dir",
",",
"vocab_filename",
",",
"vocab_size",
",",
"sources",
",",
"file_byte_budget",
"=",
"1e6",
",",
"max_subtoken_length",
"=",
"None",
")",
":",
"vocab_generator",
"=",
"generate_lines_for_vocab",
"("... | Generate a vocabulary from the datasets in sources. | [
"Generate",
"a",
"vocabulary",
"from",
"the",
"datasets",
"in",
"sources",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L361-L368 |
22,361 | tensorflow/tensor2tensor | tensor2tensor/data_generators/generator_utils.py | generate_lines_for_vocab | def generate_lines_for_vocab(tmp_dir, sources, file_byte_budget=1e6):
"""Generate lines for vocabulary generation."""
tf.logging.info("Generating vocab from: %s", str(sources))
for source in sources:
url = source[0]
filename = os.path.basename(url)
compressed_file = maybe_download(tmp_dir, filename, u... | python | def generate_lines_for_vocab(tmp_dir, sources, file_byte_budget=1e6):
"""Generate lines for vocabulary generation."""
tf.logging.info("Generating vocab from: %s", str(sources))
for source in sources:
url = source[0]
filename = os.path.basename(url)
compressed_file = maybe_download(tmp_dir, filename, u... | [
"def",
"generate_lines_for_vocab",
"(",
"tmp_dir",
",",
"sources",
",",
"file_byte_budget",
"=",
"1e6",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Generating vocab from: %s\"",
",",
"str",
"(",
"sources",
")",
")",
"for",
"source",
"in",
"sources",
... | Generate lines for vocabulary generation. | [
"Generate",
"lines",
"for",
"vocabulary",
"generation",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L371-L413 |
22,362 | tensorflow/tensor2tensor | tensor2tensor/data_generators/generator_utils.py | get_or_generate_tabbed_vocab | def get_or_generate_tabbed_vocab(data_dir, tmp_dir, source_filename,
index, vocab_filename, vocab_size):
r"""Generate a vocabulary from a tabbed source file.
The source is a file of source, target pairs, where each line contains
a source string and a target string, separated by a... | python | def get_or_generate_tabbed_vocab(data_dir, tmp_dir, source_filename,
index, vocab_filename, vocab_size):
r"""Generate a vocabulary from a tabbed source file.
The source is a file of source, target pairs, where each line contains
a source string and a target string, separated by a... | [
"def",
"get_or_generate_tabbed_vocab",
"(",
"data_dir",
",",
"tmp_dir",
",",
"source_filename",
",",
"index",
",",
"vocab_filename",
",",
"vocab_size",
")",
":",
"def",
"generate",
"(",
")",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmp_dir... | r"""Generate a vocabulary from a tabbed source file.
The source is a file of source, target pairs, where each line contains
a source string and a target string, separated by a tab ('\t') character.
The index parameter specifies 0 for the source or 1 for the target.
Args:
data_dir: path to the data directo... | [
"r",
"Generate",
"a",
"vocabulary",
"from",
"a",
"tabbed",
"source",
"file",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L416-L447 |
22,363 | tensorflow/tensor2tensor | tensor2tensor/data_generators/generator_utils.py | get_or_generate_txt_vocab | def get_or_generate_txt_vocab(data_dir, vocab_filename, vocab_size,
filepatterns):
"""Generate a vocabulary from txt files with example-per-line."""
if isinstance(filepatterns, str):
filepatterns = [filepatterns]
def generate():
tf.logging.info("Generating vocab from %s", fi... | python | def get_or_generate_txt_vocab(data_dir, vocab_filename, vocab_size,
filepatterns):
"""Generate a vocabulary from txt files with example-per-line."""
if isinstance(filepatterns, str):
filepatterns = [filepatterns]
def generate():
tf.logging.info("Generating vocab from %s", fi... | [
"def",
"get_or_generate_txt_vocab",
"(",
"data_dir",
",",
"vocab_filename",
",",
"vocab_size",
",",
"filepatterns",
")",
":",
"if",
"isinstance",
"(",
"filepatterns",
",",
"str",
")",
":",
"filepatterns",
"=",
"[",
"filepatterns",
"]",
"def",
"generate",
"(",
... | Generate a vocabulary from txt files with example-per-line. | [
"Generate",
"a",
"vocabulary",
"from",
"txt",
"files",
"with",
"example",
"-",
"per",
"-",
"line",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L450-L465 |
22,364 | tensorflow/tensor2tensor | tensor2tensor/data_generators/generator_utils.py | _shuffle_single | def _shuffle_single(fname, extra_fn=None):
"""Shuffle a single file of records.
Args:
fname: a string
extra_fn: an optional function from list of TFRecords to list of TFRecords
to be called after shuffling.
"""
records = read_records(fname)
random.shuffle(records)
if extra_fn is not None:
... | python | def _shuffle_single(fname, extra_fn=None):
"""Shuffle a single file of records.
Args:
fname: a string
extra_fn: an optional function from list of TFRecords to list of TFRecords
to be called after shuffling.
"""
records = read_records(fname)
random.shuffle(records)
if extra_fn is not None:
... | [
"def",
"_shuffle_single",
"(",
"fname",
",",
"extra_fn",
"=",
"None",
")",
":",
"records",
"=",
"read_records",
"(",
"fname",
")",
"random",
".",
"shuffle",
"(",
"records",
")",
"if",
"extra_fn",
"is",
"not",
"None",
":",
"records",
"=",
"extra_fn",
"(",... | Shuffle a single file of records.
Args:
fname: a string
extra_fn: an optional function from list of TFRecords to list of TFRecords
to be called after shuffling. | [
"Shuffle",
"a",
"single",
"file",
"of",
"records",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L499-L513 |
22,365 | tensorflow/tensor2tensor | tensor2tensor/data_generators/generator_utils.py | shuffle_dataset | def shuffle_dataset(filenames, extra_fn=None):
"""Shuffles the dataset.
Args:
filenames: a list of strings
extra_fn: an optional function from list of records to list of records
to be called after shuffling a file.
"""
if outputs_exist(filenames):
tf.logging.info("Skipping shuffle because out... | python | def shuffle_dataset(filenames, extra_fn=None):
"""Shuffles the dataset.
Args:
filenames: a list of strings
extra_fn: an optional function from list of records to list of records
to be called after shuffling a file.
"""
if outputs_exist(filenames):
tf.logging.info("Skipping shuffle because out... | [
"def",
"shuffle_dataset",
"(",
"filenames",
",",
"extra_fn",
"=",
"None",
")",
":",
"if",
"outputs_exist",
"(",
"filenames",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Skipping shuffle because output files exist\"",
")",
"return",
"tf",
".",
"logging",... | Shuffles the dataset.
Args:
filenames: a list of strings
extra_fn: an optional function from list of records to list of records
to be called after shuffling a file. | [
"Shuffles",
"the",
"dataset",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L516-L530 |
22,366 | tensorflow/tensor2tensor | tensor2tensor/data_generators/generator_utils.py | pack_examples | def pack_examples(examples,
has_inputs,
packed_length=256,
spacing=2,
queue_size=10,
chop_long_sequences=False):
"""Pack examples into longer examples.
If has_inputs=False, we are packing single-sequence examples with
targe... | python | def pack_examples(examples,
has_inputs,
packed_length=256,
spacing=2,
queue_size=10,
chop_long_sequences=False):
"""Pack examples into longer examples.
If has_inputs=False, we are packing single-sequence examples with
targe... | [
"def",
"pack_examples",
"(",
"examples",
",",
"has_inputs",
",",
"packed_length",
"=",
"256",
",",
"spacing",
"=",
"2",
",",
"queue_size",
"=",
"10",
",",
"chop_long_sequences",
"=",
"False",
")",
":",
"packer",
"=",
"SequencePairPacker",
"if",
"has_inputs",
... | Pack examples into longer examples.
If has_inputs=False, we are packing single-sequence examples with
targets only and no inputs.
In this case, we concatenate the targets from several examples to form
each new example. We insert a number of zeros for spacing between the
original sequences. This is to help... | [
"Pack",
"examples",
"into",
"longer",
"examples",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L589-L660 |
22,367 | tensorflow/tensor2tensor | tensor2tensor/data_generators/generator_utils.py | make_tmp_dir | def make_tmp_dir(suffix="", prefix="tmp", dir=None): # pylint: disable=redefined-builtin
"""Make a temporary directory."""
if dir is None:
return tempfile.mkdtemp(suffix, prefix, dir)
else:
while True:
rand_term = random.randint(1, 9999)
tmp_dir = os.path.join(dir, "%s%d%s" % (prefix, rand_te... | python | def make_tmp_dir(suffix="", prefix="tmp", dir=None): # pylint: disable=redefined-builtin
"""Make a temporary directory."""
if dir is None:
return tempfile.mkdtemp(suffix, prefix, dir)
else:
while True:
rand_term = random.randint(1, 9999)
tmp_dir = os.path.join(dir, "%s%d%s" % (prefix, rand_te... | [
"def",
"make_tmp_dir",
"(",
"suffix",
"=",
"\"\"",
",",
"prefix",
"=",
"\"tmp\"",
",",
"dir",
"=",
"None",
")",
":",
"# pylint: disable=redefined-builtin",
"if",
"dir",
"is",
"None",
":",
"return",
"tempfile",
".",
"mkdtemp",
"(",
"suffix",
",",
"prefix",
... | Make a temporary directory. | [
"Make",
"a",
"temporary",
"directory",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L883-L895 |
22,368 | tensorflow/tensor2tensor | tensor2tensor/data_generators/generator_utils.py | tfrecord_iterator_for_problem | def tfrecord_iterator_for_problem(problem, data_dir,
dataset_split=tf.estimator.ModeKeys.TRAIN):
"""Iterate over the records on disk for the Problem."""
filenames = tf.gfile.Glob(problem.filepattern(data_dir, mode=dataset_split))
example_spec = problem.example_reading_spec()[0]
... | python | def tfrecord_iterator_for_problem(problem, data_dir,
dataset_split=tf.estimator.ModeKeys.TRAIN):
"""Iterate over the records on disk for the Problem."""
filenames = tf.gfile.Glob(problem.filepattern(data_dir, mode=dataset_split))
example_spec = problem.example_reading_spec()[0]
... | [
"def",
"tfrecord_iterator_for_problem",
"(",
"problem",
",",
"data_dir",
",",
"dataset_split",
"=",
"tf",
".",
"estimator",
".",
"ModeKeys",
".",
"TRAIN",
")",
":",
"filenames",
"=",
"tf",
".",
"gfile",
".",
"Glob",
"(",
"problem",
".",
"filepattern",
"(",
... | Iterate over the records on disk for the Problem. | [
"Iterate",
"over",
"the",
"records",
"on",
"disk",
"for",
"the",
"Problem",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L898-L903 |
22,369 | tensorflow/tensor2tensor | tensor2tensor/data_generators/generator_utils.py | tfrecord_iterator | def tfrecord_iterator(filenames, gzipped=False, example_spec=None):
"""Yields records from TFRecord files.
Args:
filenames: list<str>, list of TFRecord filenames to read from.
gzipped: bool, whether the TFRecord files are gzip-encoded.
example_spec: dict<str feature name, tf.VarLenFeature/tf.FixedLenFe... | python | def tfrecord_iterator(filenames, gzipped=False, example_spec=None):
"""Yields records from TFRecord files.
Args:
filenames: list<str>, list of TFRecord filenames to read from.
gzipped: bool, whether the TFRecord files are gzip-encoded.
example_spec: dict<str feature name, tf.VarLenFeature/tf.FixedLenFe... | [
"def",
"tfrecord_iterator",
"(",
"filenames",
",",
"gzipped",
"=",
"False",
",",
"example_spec",
"=",
"None",
")",
":",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
":",
"dataset",
"=",
"tf",
".",
"data",
".",
"Dataset",
".",
"f... | Yields records from TFRecord files.
Args:
filenames: list<str>, list of TFRecord filenames to read from.
gzipped: bool, whether the TFRecord files are gzip-encoded.
example_spec: dict<str feature name, tf.VarLenFeature/tf.FixedLenFeature>,
if provided, will parse each record as a tensorflow.Example... | [
"Yields",
"records",
"from",
"TFRecord",
"files",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L906-L943 |
22,370 | tensorflow/tensor2tensor | tensor2tensor/data_generators/generator_utils.py | random_deinterleave | def random_deinterleave(text, separator_symbol="X"):
"""Create a fill-in-the-blanks training example from text.
Split on spaces, then cut into segments at random points. Alternate segments
are assigned to the two output strings. separator_symbol separates segments
within each of the outputs.
example:
t... | python | def random_deinterleave(text, separator_symbol="X"):
"""Create a fill-in-the-blanks training example from text.
Split on spaces, then cut into segments at random points. Alternate segments
are assigned to the two output strings. separator_symbol separates segments
within each of the outputs.
example:
t... | [
"def",
"random_deinterleave",
"(",
"text",
",",
"separator_symbol",
"=",
"\"X\"",
")",
":",
"words",
"=",
"text",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\" \"",
")",
"n",
"=",
"len",
"(",
"words",
")",
"if",
"n",
"<=",
"1",
":",
"return",
"tex... | Create a fill-in-the-blanks training example from text.
Split on spaces, then cut into segments at random points. Alternate segments
are assigned to the two output strings. separator_symbol separates segments
within each of the outputs.
example:
text="The quick brown fox jumps over the lazy dog."
ret... | [
"Create",
"a",
"fill",
"-",
"in",
"-",
"the",
"-",
"blanks",
"training",
"example",
"from",
"text",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/generator_utils.py#L946-L981 |
22,371 | tensorflow/tensor2tensor | tensor2tensor/models/neural_gpu.py | neural_gpu_body | def neural_gpu_body(inputs, hparams, name=None):
"""The core Neural GPU."""
with tf.variable_scope(name, "neural_gpu"):
def step(state, inp): # pylint: disable=missing-docstring
x = tf.nn.dropout(state, 1.0 - hparams.dropout)
for layer in range(hparams.num_hidden_layers):
x = common_layers... | python | def neural_gpu_body(inputs, hparams, name=None):
"""The core Neural GPU."""
with tf.variable_scope(name, "neural_gpu"):
def step(state, inp): # pylint: disable=missing-docstring
x = tf.nn.dropout(state, 1.0 - hparams.dropout)
for layer in range(hparams.num_hidden_layers):
x = common_layers... | [
"def",
"neural_gpu_body",
"(",
"inputs",
",",
"hparams",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"\"neural_gpu\"",
")",
":",
"def",
"step",
"(",
"state",
",",
"inp",
")",
":",
"# pylint: disable=missing-do... | The core Neural GPU. | [
"The",
"core",
"Neural",
"GPU",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/neural_gpu.py#L31-L52 |
22,372 | tensorflow/tensor2tensor | tensor2tensor/trax/layers/combinators.py | _reorder_shape | def _reorder_shape(input_shape, output=None): # pylint: disable=invalid-name
"""Helper to determine the shape of reorder output."""
if output is None:
return input_shape
return base.nested_map(output, lambda i: input_shape[i]) | python | def _reorder_shape(input_shape, output=None): # pylint: disable=invalid-name
"""Helper to determine the shape of reorder output."""
if output is None:
return input_shape
return base.nested_map(output, lambda i: input_shape[i]) | [
"def",
"_reorder_shape",
"(",
"input_shape",
",",
"output",
"=",
"None",
")",
":",
"# pylint: disable=invalid-name",
"if",
"output",
"is",
"None",
":",
"return",
"input_shape",
"return",
"base",
".",
"nested_map",
"(",
"output",
",",
"lambda",
"i",
":",
"input... | Helper to determine the shape of reorder output. | [
"Helper",
"to",
"determine",
"the",
"shape",
"of",
"reorder",
"output",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/combinators.py#L77-L81 |
22,373 | tensorflow/tensor2tensor | tensor2tensor/trax/layers/combinators.py | Reorder | def Reorder(x, params, output=None, **kwargs):
"""Reorder a tuple into another tuple.
For example, we can re-order (x, y) into (y, x) or even (y, (x, y), y).
The output argument specifies how to re-order, using integers that refer
to indices in the input tuple. For example, if
input = (x, y, z)
then
... | python | def Reorder(x, params, output=None, **kwargs):
"""Reorder a tuple into another tuple.
For example, we can re-order (x, y) into (y, x) or even (y, (x, y), y).
The output argument specifies how to re-order, using integers that refer
to indices in the input tuple. For example, if
input = (x, y, z)
then
... | [
"def",
"Reorder",
"(",
"x",
",",
"params",
",",
"output",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"params",
",",
"kwargs",
"if",
"output",
"is",
"None",
":",
"return",
"x",
"return",
"base",
".",
"nested_map",
"(",
"output",
",",
"la... | Reorder a tuple into another tuple.
For example, we can re-order (x, y) into (y, x) or even (y, (x, y), y).
The output argument specifies how to re-order, using integers that refer
to indices in the input tuple. For example, if
input = (x, y, z)
then
Reorder(input, output=(1, 0, 2)) = (y, x, z)
... | [
"Reorder",
"a",
"tuple",
"into",
"another",
"tuple",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/combinators.py#L85-L115 |
22,374 | tensorflow/tensor2tensor | tensor2tensor/trax/layers/combinators.py | _concatenate_shape | def _concatenate_shape(input_shape, axis=-1): # pylint: disable=invalid-name
"""Helper to determine the shape of Concatenate output."""
ax = axis % len(input_shape[0])
concat_size = sum(shape[ax] for shape in input_shape)
out_shape = input_shape[0][:ax] + (concat_size,) + input_shape[0][ax+1:]
return out_sha... | python | def _concatenate_shape(input_shape, axis=-1): # pylint: disable=invalid-name
"""Helper to determine the shape of Concatenate output."""
ax = axis % len(input_shape[0])
concat_size = sum(shape[ax] for shape in input_shape)
out_shape = input_shape[0][:ax] + (concat_size,) + input_shape[0][ax+1:]
return out_sha... | [
"def",
"_concatenate_shape",
"(",
"input_shape",
",",
"axis",
"=",
"-",
"1",
")",
":",
"# pylint: disable=invalid-name",
"ax",
"=",
"axis",
"%",
"len",
"(",
"input_shape",
"[",
"0",
"]",
")",
"concat_size",
"=",
"sum",
"(",
"shape",
"[",
"ax",
"]",
"for"... | Helper to determine the shape of Concatenate output. | [
"Helper",
"to",
"determine",
"the",
"shape",
"of",
"Concatenate",
"output",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/combinators.py#L189-L194 |
22,375 | tensorflow/tensor2tensor | tensor2tensor/trax/layers/combinators.py | Residual | def Residual(*layers, **kwargs):
"""Constructs a residual version of layers, summing input to layers output."""
shortcut = kwargs.get('shortcut', Identity()) # pylint: disable=no-value-for-parameter
if len(layers) > 1:
return Serial(
Branch(), # pylint: disable=no-value-for-parameter
Paralle... | python | def Residual(*layers, **kwargs):
"""Constructs a residual version of layers, summing input to layers output."""
shortcut = kwargs.get('shortcut', Identity()) # pylint: disable=no-value-for-parameter
if len(layers) > 1:
return Serial(
Branch(), # pylint: disable=no-value-for-parameter
Paralle... | [
"def",
"Residual",
"(",
"*",
"layers",
",",
"*",
"*",
"kwargs",
")",
":",
"shortcut",
"=",
"kwargs",
".",
"get",
"(",
"'shortcut'",
",",
"Identity",
"(",
")",
")",
"# pylint: disable=no-value-for-parameter",
"if",
"len",
"(",
"layers",
")",
">",
"1",
":"... | Constructs a residual version of layers, summing input to layers output. | [
"Constructs",
"a",
"residual",
"version",
"of",
"layers",
"summing",
"input",
"to",
"layers",
"output",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/combinators.py#L240-L256 |
22,376 | tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer.py | update_hparams_for_universal_transformer | def update_hparams_for_universal_transformer(hparams):
"""Adds default hparams for all of the variants of the Universal Transformer.
Args:
hparams: default hparams (usually one of the standard hparams from
transformer model (like "transformer_base")
Returns:
hparams with default values for Univers... | python | def update_hparams_for_universal_transformer(hparams):
"""Adds default hparams for all of the variants of the Universal Transformer.
Args:
hparams: default hparams (usually one of the standard hparams from
transformer model (like "transformer_base")
Returns:
hparams with default values for Univers... | [
"def",
"update_hparams_for_universal_transformer",
"(",
"hparams",
")",
":",
"hparams",
".",
"daisy_chain_variables",
"=",
"False",
"# Breaks multi-gpu in while loops.",
"# If not None, mixes vanilla transformer with Universal Transformer.",
"# Options: None, \"before_ut\", and \"after_ut\... | Adds default hparams for all of the variants of the Universal Transformer.
Args:
hparams: default hparams (usually one of the standard hparams from
transformer model (like "transformer_base")
Returns:
hparams with default values for Universal Transformers hyper-parameters | [
"Adds",
"default",
"hparams",
"for",
"all",
"of",
"the",
"variants",
"of",
"the",
"Universal",
"Transformer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer.py#L352-L436 |
22,377 | tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer.py | universal_transformer_base | def universal_transformer_base():
"""Base parameters for Universal Transformer."""
hparams = transformer.transformer_base()
# To have a similar capacity to the transformer_base with 6 layers,
# we need to increase the size of the UT's layer
# since, in fact, UT has a single layer repeating multiple times.
h... | python | def universal_transformer_base():
"""Base parameters for Universal Transformer."""
hparams = transformer.transformer_base()
# To have a similar capacity to the transformer_base with 6 layers,
# we need to increase the size of the UT's layer
# since, in fact, UT has a single layer repeating multiple times.
h... | [
"def",
"universal_transformer_base",
"(",
")",
":",
"hparams",
"=",
"transformer",
".",
"transformer_base",
"(",
")",
"# To have a similar capacity to the transformer_base with 6 layers,",
"# we need to increase the size of the UT's layer",
"# since, in fact, UT has a single layer repeat... | Base parameters for Universal Transformer. | [
"Base",
"parameters",
"for",
"Universal",
"Transformer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer.py#L440-L451 |
22,378 | tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer.py | adaptive_universal_transformer_multilayer_tpu | def adaptive_universal_transformer_multilayer_tpu():
"""Multi-layer config for adaptive Transformer on TPU."""
hparams = adaptive_universal_transformer_base_tpu()
hparams.num_inrecurrence_layers = 2
hparams.mix_with_transformer = "before_ut,after_ut"
hparams.num_mixedin_layers = 1
hparams.transformer_ffn_ty... | python | def adaptive_universal_transformer_multilayer_tpu():
"""Multi-layer config for adaptive Transformer on TPU."""
hparams = adaptive_universal_transformer_base_tpu()
hparams.num_inrecurrence_layers = 2
hparams.mix_with_transformer = "before_ut,after_ut"
hparams.num_mixedin_layers = 1
hparams.transformer_ffn_ty... | [
"def",
"adaptive_universal_transformer_multilayer_tpu",
"(",
")",
":",
"hparams",
"=",
"adaptive_universal_transformer_base_tpu",
"(",
")",
"hparams",
".",
"num_inrecurrence_layers",
"=",
"2",
"hparams",
".",
"mix_with_transformer",
"=",
"\"before_ut,after_ut\"",
"hparams",
... | Multi-layer config for adaptive Transformer on TPU. | [
"Multi",
"-",
"layer",
"config",
"for",
"adaptive",
"Transformer",
"on",
"TPU",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer.py#L543-L555 |
22,379 | tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer.py | adaptive_universal_transformer_multilayer_hard | def adaptive_universal_transformer_multilayer_hard():
"""Multi-layer config for adaptive Transformer with hard attention."""
hparams = adaptive_universal_transformer_multilayer_tpu()
hparams.batch_size = 256
hparams.hard_attention_k = 8
hparams.add_step_timing_signal = True
# hparams.add_sru = True # This ... | python | def adaptive_universal_transformer_multilayer_hard():
"""Multi-layer config for adaptive Transformer with hard attention."""
hparams = adaptive_universal_transformer_multilayer_tpu()
hparams.batch_size = 256
hparams.hard_attention_k = 8
hparams.add_step_timing_signal = True
# hparams.add_sru = True # This ... | [
"def",
"adaptive_universal_transformer_multilayer_hard",
"(",
")",
":",
"hparams",
"=",
"adaptive_universal_transformer_multilayer_tpu",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"256",
"hparams",
".",
"hard_attention_k",
"=",
"8",
"hparams",
".",
"add_step_timing_sign... | Multi-layer config for adaptive Transformer with hard attention. | [
"Multi",
"-",
"layer",
"config",
"for",
"adaptive",
"Transformer",
"with",
"hard",
"attention",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer.py#L559-L568 |
22,380 | tensorflow/tensor2tensor | tensor2tensor/trax/models/neural_gpu.py | ConvDiagonalGRU | def ConvDiagonalGRU(units, kernel_size=(3, 3)):
"""Build convolutional GRU with diagonal gating as in ImprovedNGPU."""
def BuildConv():
return layers.Conv(filters=units, kernel_size=kernel_size, padding='SAME')
return layers.GeneralGRUCell(
candidate_transform=BuildConv,
memory_transform=Diagona... | python | def ConvDiagonalGRU(units, kernel_size=(3, 3)):
"""Build convolutional GRU with diagonal gating as in ImprovedNGPU."""
def BuildConv():
return layers.Conv(filters=units, kernel_size=kernel_size, padding='SAME')
return layers.GeneralGRUCell(
candidate_transform=BuildConv,
memory_transform=Diagona... | [
"def",
"ConvDiagonalGRU",
"(",
"units",
",",
"kernel_size",
"=",
"(",
"3",
",",
"3",
")",
")",
":",
"def",
"BuildConv",
"(",
")",
":",
"return",
"layers",
".",
"Conv",
"(",
"filters",
"=",
"units",
",",
"kernel_size",
"=",
"kernel_size",
",",
"padding"... | Build convolutional GRU with diagonal gating as in ImprovedNGPU. | [
"Build",
"convolutional",
"GRU",
"with",
"diagonal",
"gating",
"as",
"in",
"ImprovedNGPU",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/models/neural_gpu.py#L50-L60 |
22,381 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | strip_ids | def strip_ids(ids, ids_to_strip):
"""Strip ids_to_strip from the end ids."""
ids = list(ids)
while ids and ids[-1] in ids_to_strip:
ids.pop()
return ids | python | def strip_ids(ids, ids_to_strip):
"""Strip ids_to_strip from the end ids."""
ids = list(ids)
while ids and ids[-1] in ids_to_strip:
ids.pop()
return ids | [
"def",
"strip_ids",
"(",
"ids",
",",
"ids_to_strip",
")",
":",
"ids",
"=",
"list",
"(",
"ids",
")",
"while",
"ids",
"and",
"ids",
"[",
"-",
"1",
"]",
"in",
"ids_to_strip",
":",
"ids",
".",
"pop",
"(",
")",
"return",
"ids"
] | Strip ids_to_strip from the end ids. | [
"Strip",
"ids_to_strip",
"from",
"the",
"end",
"ids",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L99-L104 |
22,382 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | _escape_token | def _escape_token(token, alphabet):
"""Escape away underscores and OOV characters and append '_'.
This allows the token to be expressed as the concatenation of a list
of subtokens from the vocabulary. The underscore acts as a sentinel
which allows us to invertibly concatenate multiple such lists.
Args:
... | python | def _escape_token(token, alphabet):
"""Escape away underscores and OOV characters and append '_'.
This allows the token to be expressed as the concatenation of a list
of subtokens from the vocabulary. The underscore acts as a sentinel
which allows us to invertibly concatenate multiple such lists.
Args:
... | [
"def",
"_escape_token",
"(",
"token",
",",
"alphabet",
")",
":",
"if",
"not",
"isinstance",
"(",
"token",
",",
"six",
".",
"text_type",
")",
":",
"raise",
"ValueError",
"(",
"\"Expected string type for token, got %s\"",
"%",
"type",
"(",
"token",
")",
")",
"... | Escape away underscores and OOV characters and append '_'.
This allows the token to be expressed as the concatenation of a list
of subtokens from the vocabulary. The underscore acts as a sentinel
which allows us to invertibly concatenate multiple such lists.
Args:
token: A unicode string to be escaped.
... | [
"Escape",
"away",
"underscores",
"and",
"OOV",
"characters",
"and",
"append",
"_",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L400-L422 |
22,383 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | TextEncoder.encode | def encode(self, s):
"""Transform a human-readable string into a sequence of int ids.
The ids should be in the range [num_reserved_ids, vocab_size). Ids [0,
num_reserved_ids) are reserved.
EOS is not appended.
Args:
s: human-readable string to be converted.
Returns:
ids: list of ... | python | def encode(self, s):
"""Transform a human-readable string into a sequence of int ids.
The ids should be in the range [num_reserved_ids, vocab_size). Ids [0,
num_reserved_ids) are reserved.
EOS is not appended.
Args:
s: human-readable string to be converted.
Returns:
ids: list of ... | [
"def",
"encode",
"(",
"self",
",",
"s",
")",
":",
"return",
"[",
"int",
"(",
"w",
")",
"+",
"self",
".",
"_num_reserved_ids",
"for",
"w",
"in",
"s",
".",
"split",
"(",
")",
"]"
] | Transform a human-readable string into a sequence of int ids.
The ids should be in the range [num_reserved_ids, vocab_size). Ids [0,
num_reserved_ids) are reserved.
EOS is not appended.
Args:
s: human-readable string to be converted.
Returns:
ids: list of integers | [
"Transform",
"a",
"human",
"-",
"readable",
"string",
"into",
"a",
"sequence",
"of",
"int",
"ids",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L117-L131 |
22,384 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | TextEncoder.decode | def decode(self, ids, strip_extraneous=False):
"""Transform a sequence of int ids into a human-readable string.
EOS is not expected in ids.
Args:
ids: list of integers to be converted.
strip_extraneous: bool, whether to strip off extraneous tokens
(EOS and PAD).
Returns:
s: ... | python | def decode(self, ids, strip_extraneous=False):
"""Transform a sequence of int ids into a human-readable string.
EOS is not expected in ids.
Args:
ids: list of integers to be converted.
strip_extraneous: bool, whether to strip off extraneous tokens
(EOS and PAD).
Returns:
s: ... | [
"def",
"decode",
"(",
"self",
",",
"ids",
",",
"strip_extraneous",
"=",
"False",
")",
":",
"if",
"strip_extraneous",
":",
"ids",
"=",
"strip_ids",
"(",
"ids",
",",
"list",
"(",
"range",
"(",
"self",
".",
"_num_reserved_ids",
"or",
"0",
")",
")",
")",
... | Transform a sequence of int ids into a human-readable string.
EOS is not expected in ids.
Args:
ids: list of integers to be converted.
strip_extraneous: bool, whether to strip off extraneous tokens
(EOS and PAD).
Returns:
s: human-readable string. | [
"Transform",
"a",
"sequence",
"of",
"int",
"ids",
"into",
"a",
"human",
"-",
"readable",
"string",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L133-L148 |
22,385 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | TextEncoder.decode_list | def decode_list(self, ids):
"""Transform a sequence of int ids into a their string versions.
This method supports transforming individual input/output ids to their
string versions so that sequence to/from text conversions can be visualized
in a human readable format.
Args:
ids: list of integ... | python | def decode_list(self, ids):
"""Transform a sequence of int ids into a their string versions.
This method supports transforming individual input/output ids to their
string versions so that sequence to/from text conversions can be visualized
in a human readable format.
Args:
ids: list of integ... | [
"def",
"decode_list",
"(",
"self",
",",
"ids",
")",
":",
"decoded_ids",
"=",
"[",
"]",
"for",
"id_",
"in",
"ids",
":",
"if",
"0",
"<=",
"id_",
"<",
"self",
".",
"_num_reserved_ids",
":",
"decoded_ids",
".",
"append",
"(",
"RESERVED_TOKENS",
"[",
"int",... | Transform a sequence of int ids into a their string versions.
This method supports transforming individual input/output ids to their
string versions so that sequence to/from text conversions can be visualized
in a human readable format.
Args:
ids: list of integers to be converted.
Returns:
... | [
"Transform",
"a",
"sequence",
"of",
"int",
"ids",
"into",
"a",
"their",
"string",
"versions",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L150-L169 |
22,386 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | TokenTextEncoder.encode | def encode(self, s):
"""Converts a space-separated string of tokens to a list of ids."""
sentence = s
tokens = sentence.strip().split()
if self._replace_oov is not None:
tokens = [t if t in self._token_to_id else self._replace_oov
for t in tokens]
ret = [self._token_to_id[tok] ... | python | def encode(self, s):
"""Converts a space-separated string of tokens to a list of ids."""
sentence = s
tokens = sentence.strip().split()
if self._replace_oov is not None:
tokens = [t if t in self._token_to_id else self._replace_oov
for t in tokens]
ret = [self._token_to_id[tok] ... | [
"def",
"encode",
"(",
"self",
",",
"s",
")",
":",
"sentence",
"=",
"s",
"tokens",
"=",
"sentence",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"if",
"self",
".",
"_replace_oov",
"is",
"not",
"None",
":",
"tokens",
"=",
"[",
"t",
"if",
"t",
... | Converts a space-separated string of tokens to a list of ids. | [
"Converts",
"a",
"space",
"-",
"separated",
"string",
"of",
"tokens",
"to",
"a",
"list",
"of",
"ids",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L314-L322 |
22,387 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | TokenTextEncoder._init_vocab_from_list | def _init_vocab_from_list(self, vocab_list):
"""Initialize tokens from a list of tokens.
It is ok if reserved tokens appear in the vocab list. They will be
removed. The set of tokens in vocab_list should be unique.
Args:
vocab_list: A list of tokens.
"""
def token_gen():
for token ... | python | def _init_vocab_from_list(self, vocab_list):
"""Initialize tokens from a list of tokens.
It is ok if reserved tokens appear in the vocab list. They will be
removed. The set of tokens in vocab_list should be unique.
Args:
vocab_list: A list of tokens.
"""
def token_gen():
for token ... | [
"def",
"_init_vocab_from_list",
"(",
"self",
",",
"vocab_list",
")",
":",
"def",
"token_gen",
"(",
")",
":",
"for",
"token",
"in",
"vocab_list",
":",
"if",
"token",
"not",
"in",
"RESERVED_TOKENS",
":",
"yield",
"token",
"self",
".",
"_init_vocab",
"(",
"to... | Initialize tokens from a list of tokens.
It is ok if reserved tokens appear in the vocab list. They will be
removed. The set of tokens in vocab_list should be unique.
Args:
vocab_list: A list of tokens. | [
"Initialize",
"tokens",
"from",
"a",
"list",
"of",
"tokens",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L353-L367 |
22,388 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | TokenTextEncoder._init_vocab | def _init_vocab(self, token_generator, add_reserved_tokens=True):
"""Initialize vocabulary with tokens from token_generator."""
self._id_to_token = {}
non_reserved_start_index = 0
if add_reserved_tokens:
self._id_to_token.update(enumerate(RESERVED_TOKENS))
non_reserved_start_index = len(RE... | python | def _init_vocab(self, token_generator, add_reserved_tokens=True):
"""Initialize vocabulary with tokens from token_generator."""
self._id_to_token = {}
non_reserved_start_index = 0
if add_reserved_tokens:
self._id_to_token.update(enumerate(RESERVED_TOKENS))
non_reserved_start_index = len(RE... | [
"def",
"_init_vocab",
"(",
"self",
",",
"token_generator",
",",
"add_reserved_tokens",
"=",
"True",
")",
":",
"self",
".",
"_id_to_token",
"=",
"{",
"}",
"non_reserved_start_index",
"=",
"0",
"if",
"add_reserved_tokens",
":",
"self",
".",
"_id_to_token",
".",
... | Initialize vocabulary with tokens from token_generator. | [
"Initialize",
"vocabulary",
"with",
"tokens",
"from",
"token_generator",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L369-L384 |
22,389 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | TokenTextEncoder.store_to_file | def store_to_file(self, filename):
"""Write vocab file to disk.
Vocab files have one token per line. The file ends in a newline. Reserved
tokens are written to the vocab file as well.
Args:
filename: Full path of the file to store the vocab to.
"""
with tf.gfile.Open(filename, "w") as f:... | python | def store_to_file(self, filename):
"""Write vocab file to disk.
Vocab files have one token per line. The file ends in a newline. Reserved
tokens are written to the vocab file as well.
Args:
filename: Full path of the file to store the vocab to.
"""
with tf.gfile.Open(filename, "w") as f:... | [
"def",
"store_to_file",
"(",
"self",
",",
"filename",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"filename",
",",
"\"w\"",
")",
"as",
"f",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_id_to_token",
")",
")",
":",
"... | Write vocab file to disk.
Vocab files have one token per line. The file ends in a newline. Reserved
tokens are written to the vocab file as well.
Args:
filename: Full path of the file to store the vocab to. | [
"Write",
"vocab",
"file",
"to",
"disk",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L386-L397 |
22,390 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | SubwordTextEncoder.decode | def decode(self, ids, strip_extraneous=False):
"""Converts a sequence of subtoken ids to a native string.
Args:
ids: a list of integers in the range [0, vocab_size)
strip_extraneous: bool, whether to strip off extraneous tokens
(EOS and PAD).
Returns:
a native string
"""
... | python | def decode(self, ids, strip_extraneous=False):
"""Converts a sequence of subtoken ids to a native string.
Args:
ids: a list of integers in the range [0, vocab_size)
strip_extraneous: bool, whether to strip off extraneous tokens
(EOS and PAD).
Returns:
a native string
"""
... | [
"def",
"decode",
"(",
"self",
",",
"ids",
",",
"strip_extraneous",
"=",
"False",
")",
":",
"if",
"strip_extraneous",
":",
"ids",
"=",
"strip_ids",
"(",
"ids",
",",
"list",
"(",
"range",
"(",
"self",
".",
"_num_reserved_ids",
"or",
"0",
")",
")",
")",
... | Converts a sequence of subtoken ids to a native string.
Args:
ids: a list of integers in the range [0, vocab_size)
strip_extraneous: bool, whether to strip off extraneous tokens
(EOS and PAD).
Returns:
a native string | [
"Converts",
"a",
"sequence",
"of",
"subtoken",
"ids",
"to",
"a",
"native",
"string",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L522-L536 |
22,391 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | SubwordTextEncoder._tokens_to_subtoken_ids | def _tokens_to_subtoken_ids(self, tokens):
"""Converts a list of tokens to a list of subtoken ids.
Args:
tokens: a list of strings.
Returns:
a list of integers in the range [0, vocab_size)
"""
ret = []
for token in tokens:
ret.extend(self._token_to_subtoken_ids(token))
ret... | python | def _tokens_to_subtoken_ids(self, tokens):
"""Converts a list of tokens to a list of subtoken ids.
Args:
tokens: a list of strings.
Returns:
a list of integers in the range [0, vocab_size)
"""
ret = []
for token in tokens:
ret.extend(self._token_to_subtoken_ids(token))
ret... | [
"def",
"_tokens_to_subtoken_ids",
"(",
"self",
",",
"tokens",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"token",
"in",
"tokens",
":",
"ret",
".",
"extend",
"(",
"self",
".",
"_token_to_subtoken_ids",
"(",
"token",
")",
")",
"return",
"ret"
] | Converts a list of tokens to a list of subtoken ids.
Args:
tokens: a list of strings.
Returns:
a list of integers in the range [0, vocab_size) | [
"Converts",
"a",
"list",
"of",
"tokens",
"to",
"a",
"list",
"of",
"subtoken",
"ids",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L546-L557 |
22,392 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | SubwordTextEncoder._token_to_subtoken_ids | def _token_to_subtoken_ids(self, token):
"""Converts token to a list of subtoken ids.
Args:
token: a string.
Returns:
a list of integers in the range [0, vocab_size)
"""
cache_location = hash(token) % self._cache_size
cache_key, cache_value = self._cache[cache_location]
if cache... | python | def _token_to_subtoken_ids(self, token):
"""Converts token to a list of subtoken ids.
Args:
token: a string.
Returns:
a list of integers in the range [0, vocab_size)
"""
cache_location = hash(token) % self._cache_size
cache_key, cache_value = self._cache[cache_location]
if cache... | [
"def",
"_token_to_subtoken_ids",
"(",
"self",
",",
"token",
")",
":",
"cache_location",
"=",
"hash",
"(",
"token",
")",
"%",
"self",
".",
"_cache_size",
"cache_key",
",",
"cache_value",
"=",
"self",
".",
"_cache",
"[",
"cache_location",
"]",
"if",
"cache_key... | Converts token to a list of subtoken ids.
Args:
token: a string.
Returns:
a list of integers in the range [0, vocab_size) | [
"Converts",
"token",
"to",
"a",
"list",
"of",
"subtoken",
"ids",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L559-L574 |
22,393 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | SubwordTextEncoder._subtoken_ids_to_tokens | def _subtoken_ids_to_tokens(self, subtokens):
"""Converts a list of subtoken ids to a list of tokens.
Args:
subtokens: a list of integers in the range [0, vocab_size)
Returns:
a list of strings.
"""
concatenated = "".join(
[self._subtoken_id_to_subtoken_string(s) for s in subtok... | python | def _subtoken_ids_to_tokens(self, subtokens):
"""Converts a list of subtoken ids to a list of tokens.
Args:
subtokens: a list of integers in the range [0, vocab_size)
Returns:
a list of strings.
"""
concatenated = "".join(
[self._subtoken_id_to_subtoken_string(s) for s in subtok... | [
"def",
"_subtoken_ids_to_tokens",
"(",
"self",
",",
"subtokens",
")",
":",
"concatenated",
"=",
"\"\"",
".",
"join",
"(",
"[",
"self",
".",
"_subtoken_id_to_subtoken_string",
"(",
"s",
")",
"for",
"s",
"in",
"subtokens",
"]",
")",
"split",
"=",
"concatenated... | Converts a list of subtoken ids to a list of tokens.
Args:
subtokens: a list of integers in the range [0, vocab_size)
Returns:
a list of strings. | [
"Converts",
"a",
"list",
"of",
"subtoken",
"ids",
"to",
"a",
"list",
"of",
"tokens",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L576-L593 |
22,394 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | SubwordTextEncoder._subtoken_id_to_subtoken_string | def _subtoken_id_to_subtoken_string(self, subtoken):
"""Converts a subtoken integer ID to a subtoken string."""
if 0 <= subtoken < self.vocab_size:
return self._all_subtoken_strings[subtoken]
return u"" | python | def _subtoken_id_to_subtoken_string(self, subtoken):
"""Converts a subtoken integer ID to a subtoken string."""
if 0 <= subtoken < self.vocab_size:
return self._all_subtoken_strings[subtoken]
return u"" | [
"def",
"_subtoken_id_to_subtoken_string",
"(",
"self",
",",
"subtoken",
")",
":",
"if",
"0",
"<=",
"subtoken",
"<",
"self",
".",
"vocab_size",
":",
"return",
"self",
".",
"_all_subtoken_strings",
"[",
"subtoken",
"]",
"return",
"u\"\""
] | Converts a subtoken integer ID to a subtoken string. | [
"Converts",
"a",
"subtoken",
"integer",
"ID",
"to",
"a",
"subtoken",
"string",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L595-L599 |
22,395 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | SubwordTextEncoder._escaped_token_to_subtoken_ids | def _escaped_token_to_subtoken_ids(self, escaped_token):
"""Converts an escaped token string to a list of subtoken IDs.
Args:
escaped_token: An escaped token as a unicode string.
Returns:
A list of subtoken IDs as integers.
"""
return [
self._subtoken_string_to_id[subtoken]
... | python | def _escaped_token_to_subtoken_ids(self, escaped_token):
"""Converts an escaped token string to a list of subtoken IDs.
Args:
escaped_token: An escaped token as a unicode string.
Returns:
A list of subtoken IDs as integers.
"""
return [
self._subtoken_string_to_id[subtoken]
... | [
"def",
"_escaped_token_to_subtoken_ids",
"(",
"self",
",",
"escaped_token",
")",
":",
"return",
"[",
"self",
".",
"_subtoken_string_to_id",
"[",
"subtoken",
"]",
"for",
"subtoken",
"in",
"self",
".",
"_escaped_token_to_subtoken_strings",
"(",
"escaped_token",
")",
"... | Converts an escaped token string to a list of subtoken IDs.
Args:
escaped_token: An escaped token as a unicode string.
Returns:
A list of subtoken IDs as integers. | [
"Converts",
"an",
"escaped",
"token",
"string",
"to",
"a",
"list",
"of",
"subtoken",
"IDs",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L631-L642 |
22,396 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | SubwordTextEncoder.build_from_generator | def build_from_generator(cls,
generator,
target_size,
max_subtoken_length=None,
reserved_tokens=None):
"""Builds a SubwordTextEncoder from the generated text.
Args:
generator: yields text.
ta... | python | def build_from_generator(cls,
generator,
target_size,
max_subtoken_length=None,
reserved_tokens=None):
"""Builds a SubwordTextEncoder from the generated text.
Args:
generator: yields text.
ta... | [
"def",
"build_from_generator",
"(",
"cls",
",",
"generator",
",",
"target_size",
",",
"max_subtoken_length",
"=",
"None",
",",
"reserved_tokens",
"=",
"None",
")",
":",
"token_counts",
"=",
"collections",
".",
"defaultdict",
"(",
"int",
")",
"for",
"item",
"in... | Builds a SubwordTextEncoder from the generated text.
Args:
generator: yields text.
target_size: int, approximate vocabulary size to create.
max_subtoken_length: Maximum length of a subtoken. If this is not set,
then the runtime and memory use of creating the vocab is quadratic in
... | [
"Builds",
"a",
"SubwordTextEncoder",
"from",
"the",
"generated",
"text",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L645-L674 |
22,397 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | SubwordTextEncoder.build_to_target_size | def build_to_target_size(cls,
target_size,
token_counts,
min_val,
max_val,
max_subtoken_length=None,
reserved_tokens=None,
num_iter... | python | def build_to_target_size(cls,
target_size,
token_counts,
min_val,
max_val,
max_subtoken_length=None,
reserved_tokens=None,
num_iter... | [
"def",
"build_to_target_size",
"(",
"cls",
",",
"target_size",
",",
"token_counts",
",",
"min_val",
",",
"max_val",
",",
"max_subtoken_length",
"=",
"None",
",",
"reserved_tokens",
"=",
"None",
",",
"num_iterations",
"=",
"4",
")",
":",
"if",
"min_val",
">",
... | Builds a SubwordTextEncoder that has `vocab_size` near `target_size`.
Uses simple recursive binary search to find a minimum token count that most
closely matches the `target_size`.
Args:
target_size: Desired vocab_size to approximate.
token_counts: A dictionary of token counts, mapping string ... | [
"Builds",
"a",
"SubwordTextEncoder",
"that",
"has",
"vocab_size",
"near",
"target_size",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L677-L748 |
22,398 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | SubwordTextEncoder.build_from_token_counts | def build_from_token_counts(self,
token_counts,
min_count,
num_iterations=4,
reserved_tokens=None,
max_subtoken_length=None):
"""Train a SubwordTextEncoder based on a... | python | def build_from_token_counts(self,
token_counts,
min_count,
num_iterations=4,
reserved_tokens=None,
max_subtoken_length=None):
"""Train a SubwordTextEncoder based on a... | [
"def",
"build_from_token_counts",
"(",
"self",
",",
"token_counts",
",",
"min_count",
",",
"num_iterations",
"=",
"4",
",",
"reserved_tokens",
"=",
"None",
",",
"max_subtoken_length",
"=",
"None",
")",
":",
"if",
"reserved_tokens",
"is",
"None",
":",
"reserved_t... | Train a SubwordTextEncoder based on a dictionary of word counts.
Args:
token_counts: a dictionary of Unicode strings to int.
min_count: an integer - discard subtokens with lower counts.
num_iterations: an integer. how many iterations of refinement.
reserved_tokens: List of reserved tokens.... | [
"Train",
"a",
"SubwordTextEncoder",
"based",
"on",
"a",
"dictionary",
"of",
"word",
"counts",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L750-L866 |
22,399 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | SubwordTextEncoder.dump | def dump(self):
"""Debugging dump of the current subtoken vocabulary."""
subtoken_strings = [(i, s)
for s, i in six.iteritems(self._subtoken_string_to_id)]
print(u", ".join(u"{0} : '{1}'".format(i, s)
for i, s in sorted(subtoken_strings))) | python | def dump(self):
"""Debugging dump of the current subtoken vocabulary."""
subtoken_strings = [(i, s)
for s, i in six.iteritems(self._subtoken_string_to_id)]
print(u", ".join(u"{0} : '{1}'".format(i, s)
for i, s in sorted(subtoken_strings))) | [
"def",
"dump",
"(",
"self",
")",
":",
"subtoken_strings",
"=",
"[",
"(",
"i",
",",
"s",
")",
"for",
"s",
",",
"i",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_subtoken_string_to_id",
")",
"]",
"print",
"(",
"u\", \"",
".",
"join",
"(",
"u\"{... | Debugging dump of the current subtoken vocabulary. | [
"Debugging",
"dump",
"of",
"the",
"current",
"subtoken",
"vocabulary",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L872-L877 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.