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,200 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | index_last_dim_with_indices | def index_last_dim_with_indices(x, indices):
"""Use indices to index into the last axis of x.
This can be useful for recovering the actual probabilities of a sample from a
probability distribution.
Args:
x: Tensor, n-d.
indices: Tensor, (n-1)-d, where the dimension sizes match the first (n-1)
di... | python | def index_last_dim_with_indices(x, indices):
"""Use indices to index into the last axis of x.
This can be useful for recovering the actual probabilities of a sample from a
probability distribution.
Args:
x: Tensor, n-d.
indices: Tensor, (n-1)-d, where the dimension sizes match the first (n-1)
di... | [
"def",
"index_last_dim_with_indices",
"(",
"x",
",",
"indices",
")",
":",
"assert",
"len",
"(",
"x",
".",
"shape",
")",
"==",
"len",
"(",
"indices",
".",
"shape",
")",
"+",
"1",
"x_shape",
"=",
"shape_list",
"(",
"x",
")",
"vocab_size",
"=",
"x_shape",... | Use indices to index into the last axis of x.
This can be useful for recovering the actual probabilities of a sample from a
probability distribution.
Args:
x: Tensor, n-d.
indices: Tensor, (n-1)-d, where the dimension sizes match the first (n-1)
dimensions of x. The values of indices will be used ... | [
"Use",
"indices",
"to",
"index",
"into",
"the",
"last",
"axis",
"of",
"x",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3396-L3429 |
22,201 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | should_generate_summaries | def should_generate_summaries():
"""Is this an appropriate context to generate summaries.
Returns:
a boolean
"""
name_scope = tf.contrib.framework.get_name_scope()
if name_scope and "while/" in name_scope:
# Summaries don't work well within tf.while_loop()
return False
if tf.get_variable_scope(... | python | def should_generate_summaries():
"""Is this an appropriate context to generate summaries.
Returns:
a boolean
"""
name_scope = tf.contrib.framework.get_name_scope()
if name_scope and "while/" in name_scope:
# Summaries don't work well within tf.while_loop()
return False
if tf.get_variable_scope(... | [
"def",
"should_generate_summaries",
"(",
")",
":",
"name_scope",
"=",
"tf",
".",
"contrib",
".",
"framework",
".",
"get_name_scope",
"(",
")",
"if",
"name_scope",
"and",
"\"while/\"",
"in",
"name_scope",
":",
"# Summaries don't work well within tf.while_loop()",
"retu... | Is this an appropriate context to generate summaries.
Returns:
a boolean | [
"Is",
"this",
"an",
"appropriate",
"context",
"to",
"generate",
"summaries",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3432-L3445 |
22,202 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | reshape_like | def reshape_like(a, b):
"""Reshapes a to match the shape of b in all but the last dimension."""
ret = tf.reshape(a, tf.concat([tf.shape(b)[:-1], tf.shape(a)[-1:]], 0))
if not tf.executing_eagerly():
ret.set_shape(b.get_shape().as_list()[:-1] + a.get_shape().as_list()[-1:])
return ret | python | def reshape_like(a, b):
"""Reshapes a to match the shape of b in all but the last dimension."""
ret = tf.reshape(a, tf.concat([tf.shape(b)[:-1], tf.shape(a)[-1:]], 0))
if not tf.executing_eagerly():
ret.set_shape(b.get_shape().as_list()[:-1] + a.get_shape().as_list()[-1:])
return ret | [
"def",
"reshape_like",
"(",
"a",
",",
"b",
")",
":",
"ret",
"=",
"tf",
".",
"reshape",
"(",
"a",
",",
"tf",
".",
"concat",
"(",
"[",
"tf",
".",
"shape",
"(",
"b",
")",
"[",
":",
"-",
"1",
"]",
",",
"tf",
".",
"shape",
"(",
"a",
")",
"[",
... | Reshapes a to match the shape of b in all but the last dimension. | [
"Reshapes",
"a",
"to",
"match",
"the",
"shape",
"of",
"b",
"in",
"all",
"but",
"the",
"last",
"dimension",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3448-L3453 |
22,203 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | summarize_video | def summarize_video(video, prefix, max_outputs=1):
"""Summarize the video using image summaries starting with prefix."""
video_shape = shape_list(video)
if len(video_shape) != 5:
raise ValueError("Assuming videos given as tensors in the format "
"[batch, time, height, width, channels] but... | python | def summarize_video(video, prefix, max_outputs=1):
"""Summarize the video using image summaries starting with prefix."""
video_shape = shape_list(video)
if len(video_shape) != 5:
raise ValueError("Assuming videos given as tensors in the format "
"[batch, time, height, width, channels] but... | [
"def",
"summarize_video",
"(",
"video",
",",
"prefix",
",",
"max_outputs",
"=",
"1",
")",
":",
"video_shape",
"=",
"shape_list",
"(",
"video",
")",
"if",
"len",
"(",
"video_shape",
")",
"!=",
"5",
":",
"raise",
"ValueError",
"(",
"\"Assuming videos given as ... | Summarize the video using image summaries starting with prefix. | [
"Summarize",
"the",
"video",
"using",
"image",
"summaries",
"starting",
"with",
"prefix",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3456-L3475 |
22,204 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | cast_like | def cast_like(x, y):
"""Cast x to y's dtype, if necessary."""
x = tf.convert_to_tensor(x)
y = tf.convert_to_tensor(y)
if x.dtype.base_dtype == y.dtype.base_dtype:
return x
cast_x = tf.cast(x, y.dtype)
if cast_x.device != x.device:
x_name = "(eager Tensor)"
try:
x_name = x.name
except... | python | def cast_like(x, y):
"""Cast x to y's dtype, if necessary."""
x = tf.convert_to_tensor(x)
y = tf.convert_to_tensor(y)
if x.dtype.base_dtype == y.dtype.base_dtype:
return x
cast_x = tf.cast(x, y.dtype)
if cast_x.device != x.device:
x_name = "(eager Tensor)"
try:
x_name = x.name
except... | [
"def",
"cast_like",
"(",
"x",
",",
"y",
")",
":",
"x",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"x",
")",
"y",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"y",
")",
"if",
"x",
".",
"dtype",
".",
"base_dtype",
"==",
"y",
".",
"dtype",
".",
"base_dt... | Cast x to y's dtype, if necessary. | [
"Cast",
"x",
"to",
"y",
"s",
"dtype",
"if",
"necessary",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3478-L3495 |
22,205 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | make_even_size | def make_even_size(x):
"""Pad x to be even-sized on axis 1 and 2, but only if necessary."""
x_shape = x.get_shape().as_list()
assert len(x_shape) > 2, "Only 3+-dimensional tensors supported."
shape = [dim if dim is not None else -1 for dim in x_shape]
new_shape = x_shape # To make sure constant shapes remain... | python | def make_even_size(x):
"""Pad x to be even-sized on axis 1 and 2, but only if necessary."""
x_shape = x.get_shape().as_list()
assert len(x_shape) > 2, "Only 3+-dimensional tensors supported."
shape = [dim if dim is not None else -1 for dim in x_shape]
new_shape = x_shape # To make sure constant shapes remain... | [
"def",
"make_even_size",
"(",
"x",
")",
":",
"x_shape",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"assert",
"len",
"(",
"x_shape",
")",
">",
"2",
",",
"\"Only 3+-dimensional tensors supported.\"",
"shape",
"=",
"[",
"dim",
"if",
"di... | Pad x to be even-sized on axis 1 and 2, but only if necessary. | [
"Pad",
"x",
"to",
"be",
"even",
"-",
"sized",
"on",
"axis",
"1",
"and",
"2",
"but",
"only",
"if",
"necessary",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3498-L3521 |
22,206 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | instance_norm | def instance_norm(x):
"""Instance normalization layer."""
with tf.variable_scope("instance_norm"):
epsilon = 1e-5
mean, var = tf.nn.moments(x, [1, 2], keep_dims=True)
scale = tf.get_variable(
"scale", [x.get_shape()[-1]],
initializer=tf.truncated_normal_initializer(mean=1.0, stddev=0.02)... | python | def instance_norm(x):
"""Instance normalization layer."""
with tf.variable_scope("instance_norm"):
epsilon = 1e-5
mean, var = tf.nn.moments(x, [1, 2], keep_dims=True)
scale = tf.get_variable(
"scale", [x.get_shape()[-1]],
initializer=tf.truncated_normal_initializer(mean=1.0, stddev=0.02)... | [
"def",
"instance_norm",
"(",
"x",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"instance_norm\"",
")",
":",
"epsilon",
"=",
"1e-5",
"mean",
",",
"var",
"=",
"tf",
".",
"nn",
".",
"moments",
"(",
"x",
",",
"[",
"1",
",",
"2",
"]",
",",
"k... | Instance normalization layer. | [
"Instance",
"normalization",
"layer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3640-L3652 |
22,207 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | general_conv | def general_conv(x,
num_filters=64,
filter_size=7,
stride=1,
stddev=0.02,
padding="VALID",
name="conv",
do_norm="instance",
do_relu=True,
relufactor=0):
"""Generaliz... | python | def general_conv(x,
num_filters=64,
filter_size=7,
stride=1,
stddev=0.02,
padding="VALID",
name="conv",
do_norm="instance",
do_relu=True,
relufactor=0):
"""Generaliz... | [
"def",
"general_conv",
"(",
"x",
",",
"num_filters",
"=",
"64",
",",
"filter_size",
"=",
"7",
",",
"stride",
"=",
"1",
",",
"stddev",
"=",
"0.02",
",",
"padding",
"=",
"\"VALID\"",
",",
"name",
"=",
"\"conv\"",
",",
"do_norm",
"=",
"\"instance\"",
",",... | Generalized convolution layer. | [
"Generalized",
"convolution",
"layer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3655-L3686 |
22,208 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | patch_discriminator | def patch_discriminator(x, filters=64, filter_size=5, n=4,
name="patch_discrim"):
"""Patch descriminator."""
with tf.variable_scope(name):
x_shape = shape_list(x)
spatial_dims = [x_shape[1] // 4, x_shape[2] // 4]
x = tf.random_crop(x, [x_shape[0]] + spatial_dims + [x_shape[3]])
... | python | def patch_discriminator(x, filters=64, filter_size=5, n=4,
name="patch_discrim"):
"""Patch descriminator."""
with tf.variable_scope(name):
x_shape = shape_list(x)
spatial_dims = [x_shape[1] // 4, x_shape[2] // 4]
x = tf.random_crop(x, [x_shape[0]] + spatial_dims + [x_shape[3]])
... | [
"def",
"patch_discriminator",
"(",
"x",
",",
"filters",
"=",
"64",
",",
"filter_size",
"=",
"5",
",",
"n",
"=",
"4",
",",
"name",
"=",
"\"patch_discrim\"",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
")",
":",
"x_shape",
"=",
"shape_lis... | Patch descriminator. | [
"Patch",
"descriminator",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3689-L3709 |
22,209 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | mean_with_attention | def mean_with_attention(x, name, num_heads=4):
"""Mean and attention to reduce spatial dimensions."""
with tf.variable_scope(name):
shape = shape_list(x)
m = tf.reduce_mean(x, [1, 2])
a = layers().Dense(num_heads, name="mean_attn")(x)
s = tf.reshape(a, [shape[0], -1, num_heads])
s = tf.nn.softma... | python | def mean_with_attention(x, name, num_heads=4):
"""Mean and attention to reduce spatial dimensions."""
with tf.variable_scope(name):
shape = shape_list(x)
m = tf.reduce_mean(x, [1, 2])
a = layers().Dense(num_heads, name="mean_attn")(x)
s = tf.reshape(a, [shape[0], -1, num_heads])
s = tf.nn.softma... | [
"def",
"mean_with_attention",
"(",
"x",
",",
"name",
",",
"num_heads",
"=",
"4",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
")",
":",
"shape",
"=",
"shape_list",
"(",
"x",
")",
"m",
"=",
"tf",
".",
"reduce_mean",
"(",
"x",
",",
"["... | Mean and attention to reduce spatial dimensions. | [
"Mean",
"and",
"attention",
"to",
"reduce",
"spatial",
"dimensions",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3712-L3724 |
22,210 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | single_discriminator | def single_discriminator(x, filters=128, kernel_size=8,
strides=4, pure_mean=False):
"""A simple single-layer convolutional discriminator."""
with tf.variable_scope("discriminator"):
net = layers().Conv2D(
filters, kernel_size, strides=strides, padding="SAME", name="conv1")(x)
... | python | def single_discriminator(x, filters=128, kernel_size=8,
strides=4, pure_mean=False):
"""A simple single-layer convolutional discriminator."""
with tf.variable_scope("discriminator"):
net = layers().Conv2D(
filters, kernel_size, strides=strides, padding="SAME", name="conv1")(x)
... | [
"def",
"single_discriminator",
"(",
"x",
",",
"filters",
"=",
"128",
",",
"kernel_size",
"=",
"8",
",",
"strides",
"=",
"4",
",",
"pure_mean",
"=",
"False",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"discriminator\"",
")",
":",
"net",
"=",
... | A simple single-layer convolutional discriminator. | [
"A",
"simple",
"single",
"-",
"layer",
"convolutional",
"discriminator",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3727-L3737 |
22,211 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | double_discriminator | def double_discriminator(x, filters1=128, filters2=None,
kernel_size=8, strides=4, pure_mean=False):
"""A convolutional discriminator with 2 layers and concatenated output."""
if filters2 is None:
filters2 = 4 * filters1
with tf.variable_scope("discriminator"):
batch_size = shape_... | python | def double_discriminator(x, filters1=128, filters2=None,
kernel_size=8, strides=4, pure_mean=False):
"""A convolutional discriminator with 2 layers and concatenated output."""
if filters2 is None:
filters2 = 4 * filters1
with tf.variable_scope("discriminator"):
batch_size = shape_... | [
"def",
"double_discriminator",
"(",
"x",
",",
"filters1",
"=",
"128",
",",
"filters2",
"=",
"None",
",",
"kernel_size",
"=",
"8",
",",
"strides",
"=",
"4",
",",
"pure_mean",
"=",
"False",
")",
":",
"if",
"filters2",
"is",
"None",
":",
"filters2",
"=",
... | A convolutional discriminator with 2 layers and concatenated output. | [
"A",
"convolutional",
"discriminator",
"with",
"2",
"layers",
"and",
"concatenated",
"output",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3740-L3761 |
22,212 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | upscale | def upscale(inputs, f, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR):
"""Upscaling the image by a factor of f."""
height, width = shape_list(inputs)[1:3] # pylint: disable=unbalanced-tuple-unpacking
return tf.image.resize_images(inputs, (height * f, width * f), method) | python | def upscale(inputs, f, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR):
"""Upscaling the image by a factor of f."""
height, width = shape_list(inputs)[1:3] # pylint: disable=unbalanced-tuple-unpacking
return tf.image.resize_images(inputs, (height * f, width * f), method) | [
"def",
"upscale",
"(",
"inputs",
",",
"f",
",",
"method",
"=",
"tf",
".",
"image",
".",
"ResizeMethod",
".",
"NEAREST_NEIGHBOR",
")",
":",
"height",
",",
"width",
"=",
"shape_list",
"(",
"inputs",
")",
"[",
"1",
":",
"3",
"]",
"# pylint: disable=unbalanc... | Upscaling the image by a factor of f. | [
"Upscaling",
"the",
"image",
"by",
"a",
"factor",
"of",
"f",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3764-L3767 |
22,213 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | cyclegan_upsample | def cyclegan_upsample(net, num_outputs, stride, method="conv2d_transpose"):
"""Upsamples the given inputs.
Args:
net: A Tensor of size [batch_size, height, width, filters].
num_outputs: The number of output filters.
stride: A list of 2 scalars or a 1x2 Tensor indicating the scale,
relative to the... | python | def cyclegan_upsample(net, num_outputs, stride, method="conv2d_transpose"):
"""Upsamples the given inputs.
Args:
net: A Tensor of size [batch_size, height, width, filters].
num_outputs: The number of output filters.
stride: A list of 2 scalars or a 1x2 Tensor indicating the scale,
relative to the... | [
"def",
"cyclegan_upsample",
"(",
"net",
",",
"num_outputs",
",",
"stride",
",",
"method",
"=",
"\"conv2d_transpose\"",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"upconv\"",
")",
":",
"net_shape",
"=",
"tf",
".",
"shape",
"(",
"net",
")",
"heigh... | Upsamples the given inputs.
Args:
net: A Tensor of size [batch_size, height, width, filters].
num_outputs: The number of output filters.
stride: A list of 2 scalars or a 1x2 Tensor indicating the scale,
relative to the inputs, of the output dimensions. For example, if kernel
size is [2, 3], t... | [
"Upsamples",
"the",
"given",
"inputs",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3788-L3841 |
22,214 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | td_conv | def td_conv(inputs,
filters,
kernel_size,
targeting_count,
targeting_fn,
keep_prob,
is_training,
do_prune=True,
strides=(1, 1),
padding="valid",
data_format="channels_last",
dilation_rate=... | python | def td_conv(inputs,
filters,
kernel_size,
targeting_count,
targeting_fn,
keep_prob,
is_training,
do_prune=True,
strides=(1, 1),
padding="valid",
data_format="channels_last",
dilation_rate=... | [
"def",
"td_conv",
"(",
"inputs",
",",
"filters",
",",
"kernel_size",
",",
"targeting_count",
",",
"targeting_fn",
",",
"keep_prob",
",",
"is_training",
",",
"do_prune",
"=",
"True",
",",
"strides",
"=",
"(",
"1",
",",
"1",
")",
",",
"padding",
"=",
"\"va... | Apply targeted dropout to the weights of a convolution. | [
"Apply",
"targeted",
"dropout",
"to",
"the",
"weights",
"of",
"a",
"convolution",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3873-L3938 |
22,215 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | targeted_dropout | def targeted_dropout(inputs,
k,
keep_prob,
targeting_fn,
is_training,
do_prune=False):
"""Applies targeted dropout.
Applies dropout at a rate of `1 - keep_prob` to only those elements of
`inputs` marked by `t... | python | def targeted_dropout(inputs,
k,
keep_prob,
targeting_fn,
is_training,
do_prune=False):
"""Applies targeted dropout.
Applies dropout at a rate of `1 - keep_prob` to only those elements of
`inputs` marked by `t... | [
"def",
"targeted_dropout",
"(",
"inputs",
",",
"k",
",",
"keep_prob",
",",
"targeting_fn",
",",
"is_training",
",",
"do_prune",
"=",
"False",
")",
":",
"if",
"not",
"is_training",
"and",
"do_prune",
":",
"k",
"=",
"tf",
".",
"round",
"(",
"to_float",
"("... | Applies targeted dropout.
Applies dropout at a rate of `1 - keep_prob` to only those elements of
`inputs` marked by `targeting_fn`. See below and paper for more detail:
"Targeted Dropout for Posthoc Pruning" Aidan N. Gomez, Ivan Zhang,
Kevin Swersky, Yarin Gal, and Geoffrey E. Hinton.
Args:
inputs: T... | [
"Applies",
"targeted",
"dropout",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3941-L3982 |
22,216 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | FactoredTensor.to_tensor | def to_tensor(self):
"""Convert to Tensor."""
a_shape = shape_list(self.a)
b_shape = shape_list(self.b)
inner_dim = b_shape[1]
result_dim = b_shape[0]
flat_a = tf.reshape(self.a, [-1, inner_dim])
product = tf.matmul(flat_a, self.b, transpose_b=True)
product_shape = a_shape[:-1] + [result... | python | def to_tensor(self):
"""Convert to Tensor."""
a_shape = shape_list(self.a)
b_shape = shape_list(self.b)
inner_dim = b_shape[1]
result_dim = b_shape[0]
flat_a = tf.reshape(self.a, [-1, inner_dim])
product = tf.matmul(flat_a, self.b, transpose_b=True)
product_shape = a_shape[:-1] + [result... | [
"def",
"to_tensor",
"(",
"self",
")",
":",
"a_shape",
"=",
"shape_list",
"(",
"self",
".",
"a",
")",
"b_shape",
"=",
"shape_list",
"(",
"self",
".",
"b",
")",
"inner_dim",
"=",
"b_shape",
"[",
"1",
"]",
"result_dim",
"=",
"b_shape",
"[",
"0",
"]",
... | Convert to Tensor. | [
"Convert",
"to",
"Tensor",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2601-L2613 |
22,217 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | WeightNorm._compute_weights | def _compute_weights(self):
"""Generate weights with normalization."""
with tf.variable_scope("compute_weights"):
self.layer.kernel = tf.nn.l2_normalize(
self.layer.v, axis=self.norm_axes) * self.layer.g | python | def _compute_weights(self):
"""Generate weights with normalization."""
with tf.variable_scope("compute_weights"):
self.layer.kernel = tf.nn.l2_normalize(
self.layer.v, axis=self.norm_axes) * self.layer.g | [
"def",
"_compute_weights",
"(",
"self",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"compute_weights\"",
")",
":",
"self",
".",
"layer",
".",
"kernel",
"=",
"tf",
".",
"nn",
".",
"l2_normalize",
"(",
"self",
".",
"layer",
".",
"v",
",",
"axis... | Generate weights with normalization. | [
"Generate",
"weights",
"with",
"normalization",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L4089-L4093 |
22,218 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | WeightNorm._init_norm | def _init_norm(self, weights):
"""Set the norm of the weight vector."""
with tf.variable_scope("init_norm"):
flat = tf.reshape(weights, [-1, self.layer_depth])
return tf.reshape(tf.norm(flat, axis=0), (self.layer_depth,)) | python | def _init_norm(self, weights):
"""Set the norm of the weight vector."""
with tf.variable_scope("init_norm"):
flat = tf.reshape(weights, [-1, self.layer_depth])
return tf.reshape(tf.norm(flat, axis=0), (self.layer_depth,)) | [
"def",
"_init_norm",
"(",
"self",
",",
"weights",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"init_norm\"",
")",
":",
"flat",
"=",
"tf",
".",
"reshape",
"(",
"weights",
",",
"[",
"-",
"1",
",",
"self",
".",
"layer_depth",
"]",
")",
"return... | Set the norm of the weight vector. | [
"Set",
"the",
"norm",
"of",
"the",
"weight",
"vector",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L4095-L4099 |
22,219 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | WeightNorm._data_dep_init | def _data_dep_init(self, inputs):
"""Data dependent initialization for eager execution."""
with tf.variable_scope("data_dep_init"):
# Generate data dependent init values
activation = self.layer.activation
self.layer.activation = None
x_init = self.layer.call(inputs)
m_init, v_init... | python | def _data_dep_init(self, inputs):
"""Data dependent initialization for eager execution."""
with tf.variable_scope("data_dep_init"):
# Generate data dependent init values
activation = self.layer.activation
self.layer.activation = None
x_init = self.layer.call(inputs)
m_init, v_init... | [
"def",
"_data_dep_init",
"(",
"self",
",",
"inputs",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"data_dep_init\"",
")",
":",
"# Generate data dependent init values",
"activation",
"=",
"self",
".",
"layer",
".",
"activation",
"self",
".",
"layer",
"."... | Data dependent initialization for eager execution. | [
"Data",
"dependent",
"initialization",
"for",
"eager",
"execution",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L4101-L4116 |
22,220 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | WeightNorm.build | def build(self, input_shape=None):
"""Build `Layer`."""
input_shape = tf.TensorShape(input_shape).as_list()
self.input_spec = layers().InputSpec(shape=input_shape)
if not self.layer.built:
self.layer.build(input_shape)
self.layer.built = False
if not hasattr(self.layer, "kernel"):
... | python | def build(self, input_shape=None):
"""Build `Layer`."""
input_shape = tf.TensorShape(input_shape).as_list()
self.input_spec = layers().InputSpec(shape=input_shape)
if not self.layer.built:
self.layer.build(input_shape)
self.layer.built = False
if not hasattr(self.layer, "kernel"):
... | [
"def",
"build",
"(",
"self",
",",
"input_shape",
"=",
"None",
")",
":",
"input_shape",
"=",
"tf",
".",
"TensorShape",
"(",
"input_shape",
")",
".",
"as_list",
"(",
")",
"self",
".",
"input_spec",
"=",
"layers",
"(",
")",
".",
"InputSpec",
"(",
"shape",... | Build `Layer`. | [
"Build",
"Layer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L4118-L4151 |
22,221 | tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | WeightNorm.call | def call(self, inputs):
"""Call `Layer`."""
# if context.executing_eagerly():
# if not self.initialized:
# self._data_dep_init(inputs)
self._compute_weights() # Recompute weights for each forward pass
output = self.layer.call(inputs)
return output | python | def call(self, inputs):
"""Call `Layer`."""
# if context.executing_eagerly():
# if not self.initialized:
# self._data_dep_init(inputs)
self._compute_weights() # Recompute weights for each forward pass
output = self.layer.call(inputs)
return output | [
"def",
"call",
"(",
"self",
",",
"inputs",
")",
":",
"# if context.executing_eagerly():",
"# if not self.initialized:",
"# self._data_dep_init(inputs)",
"self",
".",
"_compute_weights",
"(",
")",
"# Recompute weights for each forward pass",
"output",
"=",
"self",
".",
... | Call `Layer`. | [
"Call",
"Layer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L4153-L4161 |
22,222 | tensorflow/tensor2tensor | tensor2tensor/rl/rl_utils.py | compute_mean_reward | def compute_mean_reward(rollouts, clipped):
"""Calculate mean rewards from given epoch."""
reward_name = "reward" if clipped else "unclipped_reward"
rewards = []
for rollout in rollouts:
if rollout[-1].done:
rollout_reward = sum(getattr(frame, reward_name) for frame in rollout)
rewards.append(ro... | python | def compute_mean_reward(rollouts, clipped):
"""Calculate mean rewards from given epoch."""
reward_name = "reward" if clipped else "unclipped_reward"
rewards = []
for rollout in rollouts:
if rollout[-1].done:
rollout_reward = sum(getattr(frame, reward_name) for frame in rollout)
rewards.append(ro... | [
"def",
"compute_mean_reward",
"(",
"rollouts",
",",
"clipped",
")",
":",
"reward_name",
"=",
"\"reward\"",
"if",
"clipped",
"else",
"\"unclipped_reward\"",
"rewards",
"=",
"[",
"]",
"for",
"rollout",
"in",
"rollouts",
":",
"if",
"rollout",
"[",
"-",
"1",
"]"... | Calculate mean rewards from given epoch. | [
"Calculate",
"mean",
"rewards",
"from",
"given",
"epoch",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L45-L57 |
22,223 | tensorflow/tensor2tensor | tensor2tensor/rl/rl_utils.py | evaluate_single_config | def evaluate_single_config(
hparams, sampling_temp, max_num_noops, agent_model_dir,
eval_fn=_eval_fn_with_learner
):
"""Evaluate the PPO agent in the real environment."""
tf.logging.info("Evaluating metric %s", get_metric_name(
sampling_temp, max_num_noops, clipped=False
))
eval_hparams = trainer_... | python | def evaluate_single_config(
hparams, sampling_temp, max_num_noops, agent_model_dir,
eval_fn=_eval_fn_with_learner
):
"""Evaluate the PPO agent in the real environment."""
tf.logging.info("Evaluating metric %s", get_metric_name(
sampling_temp, max_num_noops, clipped=False
))
eval_hparams = trainer_... | [
"def",
"evaluate_single_config",
"(",
"hparams",
",",
"sampling_temp",
",",
"max_num_noops",
",",
"agent_model_dir",
",",
"eval_fn",
"=",
"_eval_fn_with_learner",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Evaluating metric %s\"",
",",
"get_metric_name",
"... | Evaluate the PPO agent in the real environment. | [
"Evaluate",
"the",
"PPO",
"agent",
"in",
"the",
"real",
"environment",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L77-L97 |
22,224 | tensorflow/tensor2tensor | tensor2tensor/rl/rl_utils.py | evaluate_all_configs | def evaluate_all_configs(
hparams, agent_model_dir, eval_fn=_eval_fn_with_learner
):
"""Evaluate the agent with multiple eval configurations."""
metrics = {}
# Iterate over all combinations of sampling temperatures and whether to do
# initial no-ops.
for sampling_temp in hparams.eval_sampling_temps:
#... | python | def evaluate_all_configs(
hparams, agent_model_dir, eval_fn=_eval_fn_with_learner
):
"""Evaluate the agent with multiple eval configurations."""
metrics = {}
# Iterate over all combinations of sampling temperatures and whether to do
# initial no-ops.
for sampling_temp in hparams.eval_sampling_temps:
#... | [
"def",
"evaluate_all_configs",
"(",
"hparams",
",",
"agent_model_dir",
",",
"eval_fn",
"=",
"_eval_fn_with_learner",
")",
":",
"metrics",
"=",
"{",
"}",
"# Iterate over all combinations of sampling temperatures and whether to do",
"# initial no-ops.",
"for",
"sampling_temp",
... | Evaluate the agent with multiple eval configurations. | [
"Evaluate",
"the",
"agent",
"with",
"multiple",
"eval",
"configurations",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L100-L117 |
22,225 | tensorflow/tensor2tensor | tensor2tensor/rl/rl_utils.py | summarize_metrics | def summarize_metrics(eval_metrics_writer, metrics, epoch):
"""Write metrics to summary."""
for (name, value) in six.iteritems(metrics):
summary = tf.Summary()
summary.value.add(tag=name, simple_value=value)
eval_metrics_writer.add_summary(summary, epoch)
eval_metrics_writer.flush() | python | def summarize_metrics(eval_metrics_writer, metrics, epoch):
"""Write metrics to summary."""
for (name, value) in six.iteritems(metrics):
summary = tf.Summary()
summary.value.add(tag=name, simple_value=value)
eval_metrics_writer.add_summary(summary, epoch)
eval_metrics_writer.flush() | [
"def",
"summarize_metrics",
"(",
"eval_metrics_writer",
",",
"metrics",
",",
"epoch",
")",
":",
"for",
"(",
"name",
",",
"value",
")",
"in",
"six",
".",
"iteritems",
"(",
"metrics",
")",
":",
"summary",
"=",
"tf",
".",
"Summary",
"(",
")",
"summary",
"... | Write metrics to summary. | [
"Write",
"metrics",
"to",
"summary",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L252-L258 |
22,226 | tensorflow/tensor2tensor | tensor2tensor/rl/rl_utils.py | full_game_name | def full_game_name(short_name):
"""CamelCase game name with mode suffix.
Args:
short_name: snake_case name without mode e.g "crazy_climber"
Returns:
full game name e.g. "CrazyClimberNoFrameskip-v4"
"""
camel_game_name = misc_utils.snakecase_to_camelcase(short_name)
full_name = camel_game_name + AT... | python | def full_game_name(short_name):
"""CamelCase game name with mode suffix.
Args:
short_name: snake_case name without mode e.g "crazy_climber"
Returns:
full game name e.g. "CrazyClimberNoFrameskip-v4"
"""
camel_game_name = misc_utils.snakecase_to_camelcase(short_name)
full_name = camel_game_name + AT... | [
"def",
"full_game_name",
"(",
"short_name",
")",
":",
"camel_game_name",
"=",
"misc_utils",
".",
"snakecase_to_camelcase",
"(",
"short_name",
")",
"full_name",
"=",
"camel_game_name",
"+",
"ATARI_GAME_MODE",
"return",
"full_name"
] | CamelCase game name with mode suffix.
Args:
short_name: snake_case name without mode e.g "crazy_climber"
Returns:
full game name e.g. "CrazyClimberNoFrameskip-v4" | [
"CamelCase",
"game",
"name",
"with",
"mode",
"suffix",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L270-L281 |
22,227 | tensorflow/tensor2tensor | tensor2tensor/rl/rl_utils.py | update_hparams_from_hparams | def update_hparams_from_hparams(target_hparams, source_hparams, prefix):
"""Copy a subset of hparams to target_hparams."""
for (param_name, param_value) in six.iteritems(source_hparams.values()):
if param_name.startswith(prefix):
target_hparams.set_hparam(param_name[len(prefix):], param_value) | python | def update_hparams_from_hparams(target_hparams, source_hparams, prefix):
"""Copy a subset of hparams to target_hparams."""
for (param_name, param_value) in six.iteritems(source_hparams.values()):
if param_name.startswith(prefix):
target_hparams.set_hparam(param_name[len(prefix):], param_value) | [
"def",
"update_hparams_from_hparams",
"(",
"target_hparams",
",",
"source_hparams",
",",
"prefix",
")",
":",
"for",
"(",
"param_name",
",",
"param_value",
")",
"in",
"six",
".",
"iteritems",
"(",
"source_hparams",
".",
"values",
"(",
")",
")",
":",
"if",
"pa... | Copy a subset of hparams to target_hparams. | [
"Copy",
"a",
"subset",
"of",
"hparams",
"to",
"target_hparams",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L316-L320 |
22,228 | tensorflow/tensor2tensor | tensor2tensor/rl/rl_utils.py | random_rollout_subsequences | def random_rollout_subsequences(rollouts, num_subsequences, subsequence_length):
"""Chooses a random frame sequence of given length from a set of rollouts."""
def choose_subsequence():
# TODO(koz4k): Weigh rollouts by their lengths so sampling is uniform over
# frames and not rollouts.
rollout = random.... | python | def random_rollout_subsequences(rollouts, num_subsequences, subsequence_length):
"""Chooses a random frame sequence of given length from a set of rollouts."""
def choose_subsequence():
# TODO(koz4k): Weigh rollouts by their lengths so sampling is uniform over
# frames and not rollouts.
rollout = random.... | [
"def",
"random_rollout_subsequences",
"(",
"rollouts",
",",
"num_subsequences",
",",
"subsequence_length",
")",
":",
"def",
"choose_subsequence",
"(",
")",
":",
"# TODO(koz4k): Weigh rollouts by their lengths so sampling is uniform over",
"# frames and not rollouts.",
"rollout",
... | Chooses a random frame sequence of given length from a set of rollouts. | [
"Chooses",
"a",
"random",
"frame",
"sequence",
"of",
"given",
"length",
"from",
"a",
"set",
"of",
"rollouts",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L323-L336 |
22,229 | tensorflow/tensor2tensor | tensor2tensor/rl/rl_utils.py | make_initial_frame_chooser | def make_initial_frame_chooser(
real_env, frame_stack_size, simulation_random_starts,
simulation_flip_first_random_for_beginning,
split=tf.estimator.ModeKeys.TRAIN,
):
"""Make frame chooser.
Args:
real_env: T2TEnv to take initial frames from.
frame_stack_size (int): Number of consecutive frames... | python | def make_initial_frame_chooser(
real_env, frame_stack_size, simulation_random_starts,
simulation_flip_first_random_for_beginning,
split=tf.estimator.ModeKeys.TRAIN,
):
"""Make frame chooser.
Args:
real_env: T2TEnv to take initial frames from.
frame_stack_size (int): Number of consecutive frames... | [
"def",
"make_initial_frame_chooser",
"(",
"real_env",
",",
"frame_stack_size",
",",
"simulation_random_starts",
",",
"simulation_flip_first_random_for_beginning",
",",
"split",
"=",
"tf",
".",
"estimator",
".",
"ModeKeys",
".",
"TRAIN",
",",
")",
":",
"initial_frame_rol... | Make frame chooser.
Args:
real_env: T2TEnv to take initial frames from.
frame_stack_size (int): Number of consecutive frames to extract.
simulation_random_starts (bool): Whether to choose frames at random.
simulation_flip_first_random_for_beginning (bool): Whether to flip the first
frame stack ... | [
"Make",
"frame",
"chooser",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L339-L382 |
22,230 | tensorflow/tensor2tensor | tensor2tensor/rl/rl_utils.py | absolute_hinge_difference | def absolute_hinge_difference(arr1, arr2, min_diff=10, dtype=np.uint8):
"""Point-wise, hinge loss-like, difference between arrays.
Args:
arr1: integer array to compare.
arr2: integer array to compare.
min_diff: minimal difference taken into consideration.
dtype: dtype of returned array.
Returns:... | python | def absolute_hinge_difference(arr1, arr2, min_diff=10, dtype=np.uint8):
"""Point-wise, hinge loss-like, difference between arrays.
Args:
arr1: integer array to compare.
arr2: integer array to compare.
min_diff: minimal difference taken into consideration.
dtype: dtype of returned array.
Returns:... | [
"def",
"absolute_hinge_difference",
"(",
"arr1",
",",
"arr2",
",",
"min_diff",
"=",
"10",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
":",
"diff",
"=",
"np",
".",
"abs",
"(",
"arr1",
".",
"astype",
"(",
"np",
".",
"int",
")",
"-",
"arr2",
",",
"d... | Point-wise, hinge loss-like, difference between arrays.
Args:
arr1: integer array to compare.
arr2: integer array to compare.
min_diff: minimal difference taken into consideration.
dtype: dtype of returned array.
Returns:
array | [
"Point",
"-",
"wise",
"hinge",
"loss",
"-",
"like",
"difference",
"between",
"arrays",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L385-L398 |
22,231 | tensorflow/tensor2tensor | tensor2tensor/rl/rl_utils.py | augment_observation | def augment_observation(
observation, reward, cum_reward, frame_index, bar_color=None,
header_height=27
):
"""Augments an observation with debug info."""
img = PIL_Image().new(
"RGB", (observation.shape[1], header_height,)
)
draw = PIL_ImageDraw().Draw(img)
draw.text(
(1, 0), "c:{:3}, r:{:... | python | def augment_observation(
observation, reward, cum_reward, frame_index, bar_color=None,
header_height=27
):
"""Augments an observation with debug info."""
img = PIL_Image().new(
"RGB", (observation.shape[1], header_height,)
)
draw = PIL_ImageDraw().Draw(img)
draw.text(
(1, 0), "c:{:3}, r:{:... | [
"def",
"augment_observation",
"(",
"observation",
",",
"reward",
",",
"cum_reward",
",",
"frame_index",
",",
"bar_color",
"=",
"None",
",",
"header_height",
"=",
"27",
")",
":",
"img",
"=",
"PIL_Image",
"(",
")",
".",
"new",
"(",
"\"RGB\"",
",",
"(",
"ob... | Augments an observation with debug info. | [
"Augments",
"an",
"observation",
"with",
"debug",
"info",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L402-L423 |
22,232 | tensorflow/tensor2tensor | tensor2tensor/rl/rl_utils.py | run_rollouts | def run_rollouts(
env, agent, initial_observations, step_limit=None, discount_factor=1.0,
log_every_steps=None, video_writers=(), color_bar=False,
many_rollouts_from_each_env=False
):
"""Runs a batch of rollouts from given initial observations."""
assert step_limit is not None or not many_rollouts_from_... | python | def run_rollouts(
env, agent, initial_observations, step_limit=None, discount_factor=1.0,
log_every_steps=None, video_writers=(), color_bar=False,
many_rollouts_from_each_env=False
):
"""Runs a batch of rollouts from given initial observations."""
assert step_limit is not None or not many_rollouts_from_... | [
"def",
"run_rollouts",
"(",
"env",
",",
"agent",
",",
"initial_observations",
",",
"step_limit",
"=",
"None",
",",
"discount_factor",
"=",
"1.0",
",",
"log_every_steps",
"=",
"None",
",",
"video_writers",
"=",
"(",
")",
",",
"color_bar",
"=",
"False",
",",
... | Runs a batch of rollouts from given initial observations. | [
"Runs",
"a",
"batch",
"of",
"rollouts",
"from",
"given",
"initial",
"observations",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L426-L499 |
22,233 | tensorflow/tensor2tensor | tensor2tensor/data_generators/cnn_dailymail.py | _maybe_download_corpora | def _maybe_download_corpora(tmp_dir, dataset_split):
"""Download corpora if necessary and unzip them.
Args:
tmp_dir: directory containing dataset.
dataset_split: whether we're in train/dev/test mode.
Returns:
List of all files generated and path to file containing
train/dev/test split info.
... | python | def _maybe_download_corpora(tmp_dir, dataset_split):
"""Download corpora if necessary and unzip them.
Args:
tmp_dir: directory containing dataset.
dataset_split: whether we're in train/dev/test mode.
Returns:
List of all files generated and path to file containing
train/dev/test split info.
... | [
"def",
"_maybe_download_corpora",
"(",
"tmp_dir",
",",
"dataset_split",
")",
":",
"cnn_filename",
"=",
"\"cnn_stories.tgz\"",
"cnn_finalpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmp_dir",
",",
"\"cnn/stories/\"",
")",
"dailymail_filename",
"=",
"\"dailymail_... | Download corpora if necessary and unzip them.
Args:
tmp_dir: directory containing dataset.
dataset_split: whether we're in train/dev/test mode.
Returns:
List of all files generated and path to file containing
train/dev/test split info. | [
"Download",
"corpora",
"if",
"necessary",
"and",
"unzip",
"them",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/cnn_dailymail.py#L67-L107 |
22,234 | tensorflow/tensor2tensor | tensor2tensor/data_generators/cnn_dailymail.py | example_splits | def example_splits(url_file, all_files):
"""Generate splits of the data."""
def generate_hash(inp):
"""Generate a sha1 hash to match the raw url to the filename extracted."""
h = hashlib.sha1()
h.update(inp)
return h.hexdigest()
all_files_map = {f.split("/")[-1]: f for f in all_files}
urls = ... | python | def example_splits(url_file, all_files):
"""Generate splits of the data."""
def generate_hash(inp):
"""Generate a sha1 hash to match the raw url to the filename extracted."""
h = hashlib.sha1()
h.update(inp)
return h.hexdigest()
all_files_map = {f.split("/")[-1]: f for f in all_files}
urls = ... | [
"def",
"example_splits",
"(",
"url_file",
",",
"all_files",
")",
":",
"def",
"generate_hash",
"(",
"inp",
")",
":",
"\"\"\"Generate a sha1 hash to match the raw url to the filename extracted.\"\"\"",
"h",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"h",
".",
"update",
"(... | Generate splits of the data. | [
"Generate",
"splits",
"of",
"the",
"data",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/cnn_dailymail.py#L110-L134 |
22,235 | tensorflow/tensor2tensor | tensor2tensor/data_generators/cnn_dailymail.py | example_generator | def example_generator(all_files, urls_path, sum_token):
"""Generate examples."""
def fix_run_on_sents(line):
if u"@highlight" in line:
return line
if not line:
return line
if line[-1] in END_TOKENS:
return line
return line + u"."
filelist = example_splits(urls_path, all_files)
... | python | def example_generator(all_files, urls_path, sum_token):
"""Generate examples."""
def fix_run_on_sents(line):
if u"@highlight" in line:
return line
if not line:
return line
if line[-1] in END_TOKENS:
return line
return line + u"."
filelist = example_splits(urls_path, all_files)
... | [
"def",
"example_generator",
"(",
"all_files",
",",
"urls_path",
",",
"sum_token",
")",
":",
"def",
"fix_run_on_sents",
"(",
"line",
")",
":",
"if",
"u\"@highlight\"",
"in",
"line",
":",
"return",
"line",
"if",
"not",
"line",
":",
"return",
"line",
"if",
"l... | Generate examples. | [
"Generate",
"examples",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/cnn_dailymail.py#L137-L173 |
22,236 | tensorflow/tensor2tensor | tensor2tensor/data_generators/cnn_dailymail.py | write_raw_text_to_files | def write_raw_text_to_files(all_files, urls_path, dataset_split, tmp_dir):
"""Write text to files."""
def write_to_file(all_files, urls_path, tmp_dir, filename):
"""Write text to files."""
with io.open(
os.path.join(tmp_dir, filename + ".source"), "w",
encoding="utf-8") as fstory:
wit... | python | def write_raw_text_to_files(all_files, urls_path, dataset_split, tmp_dir):
"""Write text to files."""
def write_to_file(all_files, urls_path, tmp_dir, filename):
"""Write text to files."""
with io.open(
os.path.join(tmp_dir, filename + ".source"), "w",
encoding="utf-8") as fstory:
wit... | [
"def",
"write_raw_text_to_files",
"(",
"all_files",
",",
"urls_path",
",",
"dataset_split",
",",
"tmp_dir",
")",
":",
"def",
"write_to_file",
"(",
"all_files",
",",
"urls_path",
",",
"tmp_dir",
",",
"filename",
")",
":",
"\"\"\"Write text to files.\"\"\"",
"with",
... | Write text to files. | [
"Write",
"text",
"to",
"files",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/cnn_dailymail.py#L183-L207 |
22,237 | tensorflow/tensor2tensor | tensor2tensor/rl/player_utils.py | infer_last_epoch_num | def infer_last_epoch_num(data_dir):
"""Infer highest epoch number from file names in data_dir."""
names = os.listdir(data_dir)
epochs_str = [re.findall(pattern=r".*\.(-?\d+)$", string=name)
for name in names]
epochs_str = sum(epochs_str, [])
return max([int(epoch_str) for epoch_str in epochs_s... | python | def infer_last_epoch_num(data_dir):
"""Infer highest epoch number from file names in data_dir."""
names = os.listdir(data_dir)
epochs_str = [re.findall(pattern=r".*\.(-?\d+)$", string=name)
for name in names]
epochs_str = sum(epochs_str, [])
return max([int(epoch_str) for epoch_str in epochs_s... | [
"def",
"infer_last_epoch_num",
"(",
"data_dir",
")",
":",
"names",
"=",
"os",
".",
"listdir",
"(",
"data_dir",
")",
"epochs_str",
"=",
"[",
"re",
".",
"findall",
"(",
"pattern",
"=",
"r\".*\\.(-?\\d+)$\"",
",",
"string",
"=",
"name",
")",
"for",
"name",
... | Infer highest epoch number from file names in data_dir. | [
"Infer",
"highest",
"epoch",
"number",
"from",
"file",
"names",
"in",
"data_dir",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L123-L129 |
22,238 | tensorflow/tensor2tensor | tensor2tensor/rl/player_utils.py | setup_and_load_epoch | def setup_and_load_epoch(hparams, data_dir, which_epoch_data=None):
"""Load T2TGymEnv with data from one epoch.
Args:
hparams: hparams.
data_dir: data directory.
which_epoch_data: data from which epoch to load.
Returns:
env.
"""
t2t_env = rl_utils.setup_env(
hparams, batch_size=hparams... | python | def setup_and_load_epoch(hparams, data_dir, which_epoch_data=None):
"""Load T2TGymEnv with data from one epoch.
Args:
hparams: hparams.
data_dir: data directory.
which_epoch_data: data from which epoch to load.
Returns:
env.
"""
t2t_env = rl_utils.setup_env(
hparams, batch_size=hparams... | [
"def",
"setup_and_load_epoch",
"(",
"hparams",
",",
"data_dir",
",",
"which_epoch_data",
"=",
"None",
")",
":",
"t2t_env",
"=",
"rl_utils",
".",
"setup_env",
"(",
"hparams",
",",
"batch_size",
"=",
"hparams",
".",
"real_batch_size",
",",
"max_num_noops",
"=",
... | Load T2TGymEnv with data from one epoch.
Args:
hparams: hparams.
data_dir: data directory.
which_epoch_data: data from which epoch to load.
Returns:
env. | [
"Load",
"T2TGymEnv",
"with",
"data",
"from",
"one",
"epoch",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L132-L156 |
22,239 | tensorflow/tensor2tensor | tensor2tensor/rl/player_utils.py | infer_game_name_from_filenames | def infer_game_name_from_filenames(data_dir, snake_case=True):
"""Infer name from filenames."""
names = os.listdir(data_dir)
game_names = [re.findall(pattern=r"^Gym(.*)NoFrameskip", string=name)
for name in names]
assert game_names, "No data files found in {}".format(data_dir)
game_names = sum... | python | def infer_game_name_from_filenames(data_dir, snake_case=True):
"""Infer name from filenames."""
names = os.listdir(data_dir)
game_names = [re.findall(pattern=r"^Gym(.*)NoFrameskip", string=name)
for name in names]
assert game_names, "No data files found in {}".format(data_dir)
game_names = sum... | [
"def",
"infer_game_name_from_filenames",
"(",
"data_dir",
",",
"snake_case",
"=",
"True",
")",
":",
"names",
"=",
"os",
".",
"listdir",
"(",
"data_dir",
")",
"game_names",
"=",
"[",
"re",
".",
"findall",
"(",
"pattern",
"=",
"r\"^Gym(.*)NoFrameskip\"",
",",
... | Infer name from filenames. | [
"Infer",
"name",
"from",
"filenames",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L159-L171 |
22,240 | tensorflow/tensor2tensor | tensor2tensor/rl/player_utils.py | wrap_with_monitor | def wrap_with_monitor(env, video_dir):
"""Wrap environment with gym.Monitor.
Video recording provided by Monitor requires
1) both height and width of observation to be even numbers.
2) rendering of environment
Args:
env: environment.
video_dir: video directory.
Returns:
wrapped environmen... | python | def wrap_with_monitor(env, video_dir):
"""Wrap environment with gym.Monitor.
Video recording provided by Monitor requires
1) both height and width of observation to be even numbers.
2) rendering of environment
Args:
env: environment.
video_dir: video directory.
Returns:
wrapped environmen... | [
"def",
"wrap_with_monitor",
"(",
"env",
",",
"video_dir",
")",
":",
"env",
"=",
"ExtendToEvenDimentions",
"(",
"env",
")",
"env",
"=",
"RenderObservations",
"(",
"env",
")",
"# pylint: disable=redefined-variable-type",
"env",
"=",
"gym",
".",
"wrappers",
".",
"M... | Wrap environment with gym.Monitor.
Video recording provided by Monitor requires
1) both height and width of observation to be even numbers.
2) rendering of environment
Args:
env: environment.
video_dir: video directory.
Returns:
wrapped environment. | [
"Wrap",
"environment",
"with",
"gym",
".",
"Monitor",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L245-L264 |
22,241 | tensorflow/tensor2tensor | tensor2tensor/rl/player_utils.py | create_simulated_env | def create_simulated_env(
output_dir, grayscale, resize_width_factor, resize_height_factor,
frame_stack_size, generative_model, generative_model_params,
random_starts=True, which_epoch_data="last", **other_hparams
):
""""Create SimulatedEnv with minimal subset of hparams."""
# We need these, to initiali... | python | def create_simulated_env(
output_dir, grayscale, resize_width_factor, resize_height_factor,
frame_stack_size, generative_model, generative_model_params,
random_starts=True, which_epoch_data="last", **other_hparams
):
""""Create SimulatedEnv with minimal subset of hparams."""
# We need these, to initiali... | [
"def",
"create_simulated_env",
"(",
"output_dir",
",",
"grayscale",
",",
"resize_width_factor",
",",
"resize_height_factor",
",",
"frame_stack_size",
",",
"generative_model",
",",
"generative_model_params",
",",
"random_starts",
"=",
"True",
",",
"which_epoch_data",
"=",
... | Create SimulatedEnv with minimal subset of hparams. | [
"Create",
"SimulatedEnv",
"with",
"minimal",
"subset",
"of",
"hparams",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L267-L298 |
22,242 | tensorflow/tensor2tensor | tensor2tensor/rl/player_utils.py | infer_paths | def infer_paths(output_dir, **subdirs):
"""Infers standard paths to policy and model directories.
Example:
>>> infer_paths("/some/output/dir/", policy="", model="custom/path")
{"policy": "/some/output/dir/policy", "model": "custom/path",
"output_dir":"/some/output/dir/"}
Args:
output_dir: output... | python | def infer_paths(output_dir, **subdirs):
"""Infers standard paths to policy and model directories.
Example:
>>> infer_paths("/some/output/dir/", policy="", model="custom/path")
{"policy": "/some/output/dir/policy", "model": "custom/path",
"output_dir":"/some/output/dir/"}
Args:
output_dir: output... | [
"def",
"infer_paths",
"(",
"output_dir",
",",
"*",
"*",
"subdirs",
")",
":",
"directories",
"=",
"{",
"}",
"for",
"name",
",",
"path",
"in",
"six",
".",
"iteritems",
"(",
"subdirs",
")",
":",
"directories",
"[",
"name",
"]",
"=",
"path",
"if",
"path"... | Infers standard paths to policy and model directories.
Example:
>>> infer_paths("/some/output/dir/", policy="", model="custom/path")
{"policy": "/some/output/dir/policy", "model": "custom/path",
"output_dir":"/some/output/dir/"}
Args:
output_dir: output directory.
**subdirs: sub-directories.
... | [
"Infers",
"standard",
"paths",
"to",
"policy",
"and",
"model",
"directories",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L377-L396 |
22,243 | tensorflow/tensor2tensor | tensor2tensor/rl/player_utils.py | PPOPolicyInferencer.infer | def infer(self, ob):
"""Add new observation to frame stack and infer policy.
Args:
ob: array of shape (height, width, channels)
Returns:
logits and vf.
"""
self._add_to_stack(ob)
logits, vf = self.infer_from_frame_stack(self._frame_stack)
return logits, vf | python | def infer(self, ob):
"""Add new observation to frame stack and infer policy.
Args:
ob: array of shape (height, width, channels)
Returns:
logits and vf.
"""
self._add_to_stack(ob)
logits, vf = self.infer_from_frame_stack(self._frame_stack)
return logits, vf | [
"def",
"infer",
"(",
"self",
",",
"ob",
")",
":",
"self",
".",
"_add_to_stack",
"(",
"ob",
")",
"logits",
",",
"vf",
"=",
"self",
".",
"infer_from_frame_stack",
"(",
"self",
".",
"_frame_stack",
")",
"return",
"logits",
",",
"vf"
] | Add new observation to frame stack and infer policy.
Args:
ob: array of shape (height, width, channels)
Returns:
logits and vf. | [
"Add",
"new",
"observation",
"to",
"frame",
"stack",
"and",
"infer",
"policy",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L350-L361 |
22,244 | tensorflow/tensor2tensor | tensor2tensor/rl/player_utils.py | PPOPolicyInferencer.infer_from_frame_stack | def infer_from_frame_stack(self, ob_stack):
"""Infer policy from stack of observations.
Args:
ob_stack: array of shape (1, frame_stack_size, height, width, channels)
Returns:
logits and vf.
"""
logits, vf = self.sess.run([self.logits_t, self.value_function_t],
... | python | def infer_from_frame_stack(self, ob_stack):
"""Infer policy from stack of observations.
Args:
ob_stack: array of shape (1, frame_stack_size, height, width, channels)
Returns:
logits and vf.
"""
logits, vf = self.sess.run([self.logits_t, self.value_function_t],
... | [
"def",
"infer_from_frame_stack",
"(",
"self",
",",
"ob_stack",
")",
":",
"logits",
",",
"vf",
"=",
"self",
".",
"sess",
".",
"run",
"(",
"[",
"self",
".",
"logits_t",
",",
"self",
".",
"value_function_t",
"]",
",",
"feed_dict",
"=",
"{",
"self",
".",
... | Infer policy from stack of observations.
Args:
ob_stack: array of shape (1, frame_stack_size, height, width, channels)
Returns:
logits and vf. | [
"Infer",
"policy",
"from",
"stack",
"of",
"observations",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L363-L374 |
22,245 | tensorflow/tensor2tensor | tensor2tensor/data_generators/babi_qa.py | _normalize_string | def _normalize_string(raw_str):
"""Normalizes the string using tokenizer.encode.
Args:
raw_str: the input string
Returns:
A string which is ready to be tokenized using split()
"""
return " ".join(
token.strip()
for token in tokenizer.encode(text_encoder.native_to_unicode(raw_str))) | python | def _normalize_string(raw_str):
"""Normalizes the string using tokenizer.encode.
Args:
raw_str: the input string
Returns:
A string which is ready to be tokenized using split()
"""
return " ".join(
token.strip()
for token in tokenizer.encode(text_encoder.native_to_unicode(raw_str))) | [
"def",
"_normalize_string",
"(",
"raw_str",
")",
":",
"return",
"\" \"",
".",
"join",
"(",
"token",
".",
"strip",
"(",
")",
"for",
"token",
"in",
"tokenizer",
".",
"encode",
"(",
"text_encoder",
".",
"native_to_unicode",
"(",
"raw_str",
")",
")",
")"
] | Normalizes the string using tokenizer.encode.
Args:
raw_str: the input string
Returns:
A string which is ready to be tokenized using split() | [
"Normalizes",
"the",
"string",
"using",
"tokenizer",
".",
"encode",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/babi_qa.py#L84-L95 |
22,246 | tensorflow/tensor2tensor | tensor2tensor/data_generators/babi_qa.py | _register_babi_problems | def _register_babi_problems():
"""It dynamically instantiates a class for each babi subsets-tasks.
@registry.register_problem
class BabiQaConcatAllTasks_10k(EditSequenceRegexProblem):
@property
def babi_task_id(self):
return "qa0"
@property
def babi_subset(self):
return "en-10k... | python | def _register_babi_problems():
"""It dynamically instantiates a class for each babi subsets-tasks.
@registry.register_problem
class BabiQaConcatAllTasks_10k(EditSequenceRegexProblem):
@property
def babi_task_id(self):
return "qa0"
@property
def babi_subset(self):
return "en-10k... | [
"def",
"_register_babi_problems",
"(",
")",
":",
"for",
"(",
"subset",
",",
"subset_suffix",
")",
"in",
"[",
"(",
"\"en\"",
",",
"\"_1k\"",
")",
",",
"(",
"\"en-10k\"",
",",
"\"_10k\"",
")",
"]",
":",
"for",
"problem_name",
",",
"babi_task_id",
"in",
"si... | It dynamically instantiates a class for each babi subsets-tasks.
@registry.register_problem
class BabiQaConcatAllTasks_10k(EditSequenceRegexProblem):
@property
def babi_task_id(self):
return "qa0"
@property
def babi_subset(self):
return "en-10k"
It does not put the classes int... | [
"It",
"dynamically",
"instantiates",
"a",
"class",
"for",
"each",
"babi",
"subsets",
"-",
"tasks",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/babi_qa.py#L510-L539 |
22,247 | tensorflow/tensor2tensor | tensor2tensor/data_generators/babi_qa.py | BabiQa.get_labels_encoder | def get_labels_encoder(self, data_dir):
"""Builds encoder for the given class labels.
Args:
data_dir: data directory
Returns:
An encoder for class labels.
"""
label_filepath = os.path.join(data_dir, self.vocab_filename)
return text_encoder.TokenTextEncoder(label_filepath) | python | def get_labels_encoder(self, data_dir):
"""Builds encoder for the given class labels.
Args:
data_dir: data directory
Returns:
An encoder for class labels.
"""
label_filepath = os.path.join(data_dir, self.vocab_filename)
return text_encoder.TokenTextEncoder(label_filepath) | [
"def",
"get_labels_encoder",
"(",
"self",
",",
"data_dir",
")",
":",
"label_filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
"self",
".",
"vocab_filename",
")",
"return",
"text_encoder",
".",
"TokenTextEncoder",
"(",
"label_filepath",
")"
... | Builds encoder for the given class labels.
Args:
data_dir: data directory
Returns:
An encoder for class labels. | [
"Builds",
"encoder",
"for",
"the",
"given",
"class",
"labels",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/babi_qa.py#L326-L336 |
22,248 | tensorflow/tensor2tensor | tensor2tensor/data_generators/babi_qa.py | BabiQa.generate_encoded_samples | def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split):
"""A generator that generates samples that are encoded.
Args:
data_dir: data directory
tmp_dir: temp directory
dataset_split: dataset split
Yields:
A dict.
"""
generator = self.generate_samples(data_dir,... | python | def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split):
"""A generator that generates samples that are encoded.
Args:
data_dir: data directory
tmp_dir: temp directory
dataset_split: dataset split
Yields:
A dict.
"""
generator = self.generate_samples(data_dir,... | [
"def",
"generate_encoded_samples",
"(",
"self",
",",
"data_dir",
",",
"tmp_dir",
",",
"dataset_split",
")",
":",
"generator",
"=",
"self",
".",
"generate_samples",
"(",
"data_dir",
",",
"tmp_dir",
",",
"dataset_split",
")",
"encoder",
"=",
"self",
".",
"get_or... | A generator that generates samples that are encoded.
Args:
data_dir: data directory
tmp_dir: temp directory
dataset_split: dataset split
Yields:
A dict. | [
"A",
"generator",
"that",
"generates",
"samples",
"that",
"are",
"encoded",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/babi_qa.py#L364-L386 |
22,249 | tensorflow/tensor2tensor | tensor2tensor/data_generators/timeseries.py | TimeseriesProblem.dataset_splits | def dataset_splits(self):
"""Splits of data to produce and number the output shards for each."""
return [{
"split": problem.DatasetSplit.TRAIN,
"shards": self.num_train_shards,
}, {
"split": problem.DatasetSplit.EVAL,
"shards": self.num_eval_shards,
}, {
"split": ... | python | def dataset_splits(self):
"""Splits of data to produce and number the output shards for each."""
return [{
"split": problem.DatasetSplit.TRAIN,
"shards": self.num_train_shards,
}, {
"split": problem.DatasetSplit.EVAL,
"shards": self.num_eval_shards,
}, {
"split": ... | [
"def",
"dataset_splits",
"(",
"self",
")",
":",
"return",
"[",
"{",
"\"split\"",
":",
"problem",
".",
"DatasetSplit",
".",
"TRAIN",
",",
"\"shards\"",
":",
"self",
".",
"num_train_shards",
",",
"}",
",",
"{",
"\"split\"",
":",
"problem",
".",
"DatasetSplit... | Splits of data to produce and number the output shards for each. | [
"Splits",
"of",
"data",
"to",
"produce",
"and",
"number",
"the",
"output",
"shards",
"for",
"each",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/timeseries.py#L49-L60 |
22,250 | tensorflow/tensor2tensor | tensor2tensor/data_generators/librispeech.py | add_librispeech_hparams | def add_librispeech_hparams(hparams):
"""Adding to base hparams the attributes for for librispeech."""
hparams.batch_size = 36
hparams.audio_compression = 8
hparams.hidden_size = 2048
hparams.max_input_seq_length = 600000
hparams.max_target_seq_length = 350
hparams.max_length = hparams.max_input_seq_lengt... | python | def add_librispeech_hparams(hparams):
"""Adding to base hparams the attributes for for librispeech."""
hparams.batch_size = 36
hparams.audio_compression = 8
hparams.hidden_size = 2048
hparams.max_input_seq_length = 600000
hparams.max_target_seq_length = 350
hparams.max_length = hparams.max_input_seq_lengt... | [
"def",
"add_librispeech_hparams",
"(",
"hparams",
")",
":",
"hparams",
".",
"batch_size",
"=",
"36",
"hparams",
".",
"audio_compression",
"=",
"8",
"hparams",
".",
"hidden_size",
"=",
"2048",
"hparams",
".",
"max_input_seq_length",
"=",
"600000",
"hparams",
".",... | Adding to base hparams the attributes for for librispeech. | [
"Adding",
"to",
"base",
"hparams",
"the",
"attributes",
"for",
"for",
"librispeech",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/librispeech.py#L261-L273 |
22,251 | tensorflow/tensor2tensor | tensor2tensor/data_generators/wsj_parsing.py | words_and_tags_from_wsj_tree | def words_and_tags_from_wsj_tree(tree_string):
"""Generates linearized trees and tokens from the wsj tree format.
It uses the linearized algorithm described in https://arxiv.org/abs/1412.7449.
Args:
tree_string: tree in wsj format
Returns:
tuple: (words, linearized tree)
"""
stack, tags, words = ... | python | def words_and_tags_from_wsj_tree(tree_string):
"""Generates linearized trees and tokens from the wsj tree format.
It uses the linearized algorithm described in https://arxiv.org/abs/1412.7449.
Args:
tree_string: tree in wsj format
Returns:
tuple: (words, linearized tree)
"""
stack, tags, words = ... | [
"def",
"words_and_tags_from_wsj_tree",
"(",
"tree_string",
")",
":",
"stack",
",",
"tags",
",",
"words",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"for",
"tok",
"in",
"tree_string",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
":",
"if",
"tok... | Generates linearized trees and tokens from the wsj tree format.
It uses the linearized algorithm described in https://arxiv.org/abs/1412.7449.
Args:
tree_string: tree in wsj format
Returns:
tuple: (words, linearized tree) | [
"Generates",
"linearized",
"trees",
"and",
"tokens",
"from",
"the",
"wsj",
"tree",
"format",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wsj_parsing.py#L79-L103 |
22,252 | tensorflow/tensor2tensor | tensor2tensor/data_generators/wikisum/validate_data.py | aggregate_stats | def aggregate_stats(stats_files):
"""Aggregate stats in per-shard stats files."""
all_stats = {}
for fname in stats_files:
with tf.gfile.Open(fname) as f:
stats = json.loads(f.read())
for k, v in stats.iteritems():
if k not in all_stats:
if isinstance(v, list):
all_st... | python | def aggregate_stats(stats_files):
"""Aggregate stats in per-shard stats files."""
all_stats = {}
for fname in stats_files:
with tf.gfile.Open(fname) as f:
stats = json.loads(f.read())
for k, v in stats.iteritems():
if k not in all_stats:
if isinstance(v, list):
all_st... | [
"def",
"aggregate_stats",
"(",
"stats_files",
")",
":",
"all_stats",
"=",
"{",
"}",
"for",
"fname",
"in",
"stats_files",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"fname",
")",
"as",
"f",
":",
"stats",
"=",
"json",
".",
"loads",
"(",
"f",
... | Aggregate stats in per-shard stats files. | [
"Aggregate",
"stats",
"in",
"per",
"-",
"shard",
"stats",
"files",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/validate_data.py#L41-L91 |
22,253 | tensorflow/tensor2tensor | tensor2tensor/data_generators/wikisum/validate_data.py | filename_to_task_id | def filename_to_task_id(fname):
"""Map filename to the task id that created it assuming 1k tasks."""
# This matches the order and size in WikisumBase.out_filepaths
fname = os.path.basename(fname)
shard_id_increment = {
"train": 0,
"dev": 800,
"test": 900,
}
parts = fname.split("-")
split... | python | def filename_to_task_id(fname):
"""Map filename to the task id that created it assuming 1k tasks."""
# This matches the order and size in WikisumBase.out_filepaths
fname = os.path.basename(fname)
shard_id_increment = {
"train": 0,
"dev": 800,
"test": 900,
}
parts = fname.split("-")
split... | [
"def",
"filename_to_task_id",
"(",
"fname",
")",
":",
"# This matches the order and size in WikisumBase.out_filepaths",
"fname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"fname",
")",
"shard_id_increment",
"=",
"{",
"\"train\"",
":",
"0",
",",
"\"dev\"",
":",
... | Map filename to the task id that created it assuming 1k tasks. | [
"Map",
"filename",
"to",
"the",
"task",
"id",
"that",
"created",
"it",
"assuming",
"1k",
"tasks",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/validate_data.py#L94-L107 |
22,254 | tensorflow/tensor2tensor | tensor2tensor/data_generators/wikisum/validate_data.py | validate_data_files | def validate_data_files(problem, data_files, min_size):
"""Validate presence and minimum size of files."""
# Check that all files are present
data_dir = os.path.split(data_files[0])[0]
out_filepaths = problem.out_filepaths(data_dir)
missing_filepaths = set(out_filepaths) - set(data_files)
if missing_filepat... | python | def validate_data_files(problem, data_files, min_size):
"""Validate presence and minimum size of files."""
# Check that all files are present
data_dir = os.path.split(data_files[0])[0]
out_filepaths = problem.out_filepaths(data_dir)
missing_filepaths = set(out_filepaths) - set(data_files)
if missing_filepat... | [
"def",
"validate_data_files",
"(",
"problem",
",",
"data_files",
",",
"min_size",
")",
":",
"# Check that all files are present",
"data_dir",
"=",
"os",
".",
"path",
".",
"split",
"(",
"data_files",
"[",
"0",
"]",
")",
"[",
"0",
"]",
"out_filepaths",
"=",
"p... | Validate presence and minimum size of files. | [
"Validate",
"presence",
"and",
"minimum",
"size",
"of",
"files",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/validate_data.py#L114-L133 |
22,255 | tensorflow/tensor2tensor | tensor2tensor/data_generators/lambada.py | _prepare_lambada_data | def _prepare_lambada_data(tmp_dir, data_dir, vocab_size, vocab_filename):
"""Downloading and preparing the dataset.
Args:
tmp_dir: tem directory
data_dir: data directory
vocab_size: size of vocabulary
vocab_filename: name of vocab file
"""
if not tf.gfile.Exists(data_dir):
tf.gfile.MakeDi... | python | def _prepare_lambada_data(tmp_dir, data_dir, vocab_size, vocab_filename):
"""Downloading and preparing the dataset.
Args:
tmp_dir: tem directory
data_dir: data directory
vocab_size: size of vocabulary
vocab_filename: name of vocab file
"""
if not tf.gfile.Exists(data_dir):
tf.gfile.MakeDi... | [
"def",
"_prepare_lambada_data",
"(",
"tmp_dir",
",",
"data_dir",
",",
"vocab_size",
",",
"vocab_filename",
")",
":",
"if",
"not",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"data_dir",
")",
":",
"tf",
".",
"gfile",
".",
"MakeDirs",
"(",
"data_dir",
")",
"fi... | Downloading and preparing the dataset.
Args:
tmp_dir: tem directory
data_dir: data directory
vocab_size: size of vocabulary
vocab_filename: name of vocab file | [
"Downloading",
"and",
"preparing",
"the",
"dataset",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/lambada.py#L57-L86 |
22,256 | tensorflow/tensor2tensor | tensor2tensor/data_generators/lambada.py | get_dataset_split | def get_dataset_split(tmp_dir, split, use_control_set):
"""Gives the file paths with regards to the given split.
Args:
tmp_dir: temp directory
split: dataset split
use_control_set: uses control dataset if true.
Returns:
list of file paths.
"""
if not use_control_set:
dataset_split = {
... | python | def get_dataset_split(tmp_dir, split, use_control_set):
"""Gives the file paths with regards to the given split.
Args:
tmp_dir: temp directory
split: dataset split
use_control_set: uses control dataset if true.
Returns:
list of file paths.
"""
if not use_control_set:
dataset_split = {
... | [
"def",
"get_dataset_split",
"(",
"tmp_dir",
",",
"split",
",",
"use_control_set",
")",
":",
"if",
"not",
"use_control_set",
":",
"dataset_split",
"=",
"{",
"problem",
".",
"DatasetSplit",
".",
"TRAIN",
":",
"[",
"f",
"for",
"f",
"in",
"tf",
".",
"gfile",
... | Gives the file paths with regards to the given split.
Args:
tmp_dir: temp directory
split: dataset split
use_control_set: uses control dataset if true.
Returns:
list of file paths. | [
"Gives",
"the",
"file",
"paths",
"with",
"regards",
"to",
"the",
"given",
"split",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/lambada.py#L89-L126 |
22,257 | tensorflow/tensor2tensor | tensor2tensor/data_generators/transduction_problems.py | TransductionProblem.min_sequence_length | def min_sequence_length(self, dataset_split):
"""Determine the minimum sequence length given a dataset_split.
Args:
dataset_split: A problem.DatasetSplit.
Returns:
The minimum length that a sequence can be for this dataset_split.
"""
return {
problem.DatasetSplit.TRAIN: 8,
... | python | def min_sequence_length(self, dataset_split):
"""Determine the minimum sequence length given a dataset_split.
Args:
dataset_split: A problem.DatasetSplit.
Returns:
The minimum length that a sequence can be for this dataset_split.
"""
return {
problem.DatasetSplit.TRAIN: 8,
... | [
"def",
"min_sequence_length",
"(",
"self",
",",
"dataset_split",
")",
":",
"return",
"{",
"problem",
".",
"DatasetSplit",
".",
"TRAIN",
":",
"8",
",",
"problem",
".",
"DatasetSplit",
".",
"EVAL",
":",
"65",
",",
"problem",
".",
"DatasetSplit",
".",
"TEST",... | Determine the minimum sequence length given a dataset_split.
Args:
dataset_split: A problem.DatasetSplit.
Returns:
The minimum length that a sequence can be for this dataset_split. | [
"Determine",
"the",
"minimum",
"sequence",
"length",
"given",
"a",
"dataset_split",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/transduction_problems.py#L63-L76 |
22,258 | tensorflow/tensor2tensor | tensor2tensor/data_generators/transduction_problems.py | TransductionProblem.max_sequence_length | def max_sequence_length(self, dataset_split):
"""Determine the maximum sequence length given a dataset_split.
Args:
dataset_split: A problem.DatasetSplit.
Returns:
The maximum length that a sequence can be for this dataset_split.
"""
return {
problem.DatasetSplit.TRAIN: 64,
... | python | def max_sequence_length(self, dataset_split):
"""Determine the maximum sequence length given a dataset_split.
Args:
dataset_split: A problem.DatasetSplit.
Returns:
The maximum length that a sequence can be for this dataset_split.
"""
return {
problem.DatasetSplit.TRAIN: 64,
... | [
"def",
"max_sequence_length",
"(",
"self",
",",
"dataset_split",
")",
":",
"return",
"{",
"problem",
".",
"DatasetSplit",
".",
"TRAIN",
":",
"64",
",",
"problem",
".",
"DatasetSplit",
".",
"EVAL",
":",
"128",
",",
"problem",
".",
"DatasetSplit",
".",
"TEST... | Determine the maximum sequence length given a dataset_split.
Args:
dataset_split: A problem.DatasetSplit.
Returns:
The maximum length that a sequence can be for this dataset_split. | [
"Determine",
"the",
"maximum",
"sequence",
"length",
"given",
"a",
"dataset_split",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/transduction_problems.py#L78-L91 |
22,259 | tensorflow/tensor2tensor | tensor2tensor/data_generators/transduction_problems.py | TransductionProblem.num_samples | def num_samples(self, dataset_split):
"""Determine the dataset sized given a dataset_split.
Args:
dataset_split: A problem.DatasetSplit.
Returns:
The desired number of samples for this dataset_split.
"""
return {
problem.DatasetSplit.TRAIN: 1000000,
problem.DatasetSplit... | python | def num_samples(self, dataset_split):
"""Determine the dataset sized given a dataset_split.
Args:
dataset_split: A problem.DatasetSplit.
Returns:
The desired number of samples for this dataset_split.
"""
return {
problem.DatasetSplit.TRAIN: 1000000,
problem.DatasetSplit... | [
"def",
"num_samples",
"(",
"self",
",",
"dataset_split",
")",
":",
"return",
"{",
"problem",
".",
"DatasetSplit",
".",
"TRAIN",
":",
"1000000",
",",
"problem",
".",
"DatasetSplit",
".",
"EVAL",
":",
"10000",
",",
"problem",
".",
"DatasetSplit",
".",
"TEST"... | Determine the dataset sized given a dataset_split.
Args:
dataset_split: A problem.DatasetSplit.
Returns:
The desired number of samples for this dataset_split. | [
"Determine",
"the",
"dataset",
"sized",
"given",
"a",
"dataset_split",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/transduction_problems.py#L93-L106 |
22,260 | tensorflow/tensor2tensor | tensor2tensor/utils/trainer_lib.py | create_session_config | def create_session_config(log_device_placement=False,
enable_graph_rewriter=False,
gpu_mem_fraction=0.95,
use_tpu=False,
xla_jit_level=tf.OptimizerOptions.OFF,
inter_op_parallelism_threads=0... | python | def create_session_config(log_device_placement=False,
enable_graph_rewriter=False,
gpu_mem_fraction=0.95,
use_tpu=False,
xla_jit_level=tf.OptimizerOptions.OFF,
inter_op_parallelism_threads=0... | [
"def",
"create_session_config",
"(",
"log_device_placement",
"=",
"False",
",",
"enable_graph_rewriter",
"=",
"False",
",",
"gpu_mem_fraction",
"=",
"0.95",
",",
"use_tpu",
"=",
"False",
",",
"xla_jit_level",
"=",
"tf",
".",
"OptimizerOptions",
".",
"OFF",
",",
... | The TensorFlow Session config to use. | [
"The",
"TensorFlow",
"Session",
"config",
"to",
"use",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L105-L137 |
22,261 | tensorflow/tensor2tensor | tensor2tensor/utils/trainer_lib.py | create_estimator | def create_estimator(model_name,
hparams,
run_config,
schedule="train_and_evaluate",
decode_hparams=None,
use_tpu=False,
use_tpu_estimator=False,
use_xla=False):
"""Create... | python | def create_estimator(model_name,
hparams,
run_config,
schedule="train_and_evaluate",
decode_hparams=None,
use_tpu=False,
use_tpu_estimator=False,
use_xla=False):
"""Create... | [
"def",
"create_estimator",
"(",
"model_name",
",",
"hparams",
",",
"run_config",
",",
"schedule",
"=",
"\"train_and_evaluate\"",
",",
"decode_hparams",
"=",
"None",
",",
"use_tpu",
"=",
"False",
",",
"use_tpu_estimator",
"=",
"False",
",",
"use_xla",
"=",
"False... | Create a T2T Estimator. | [
"Create",
"a",
"T2T",
"Estimator",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L281-L325 |
22,262 | tensorflow/tensor2tensor | tensor2tensor/utils/trainer_lib.py | create_hooks | def create_hooks(use_tfdbg=False,
use_dbgprofile=False,
dbgprofile_kwargs=None,
use_validation_monitor=False,
validation_monitor_kwargs=None,
use_early_stopping=False,
early_stopping_kwargs=None):
"""Create train and... | python | def create_hooks(use_tfdbg=False,
use_dbgprofile=False,
dbgprofile_kwargs=None,
use_validation_monitor=False,
validation_monitor_kwargs=None,
use_early_stopping=False,
early_stopping_kwargs=None):
"""Create train and... | [
"def",
"create_hooks",
"(",
"use_tfdbg",
"=",
"False",
",",
"use_dbgprofile",
"=",
"False",
",",
"dbgprofile_kwargs",
"=",
"None",
",",
"use_validation_monitor",
"=",
"False",
",",
"validation_monitor_kwargs",
"=",
"None",
",",
"use_early_stopping",
"=",
"False",
... | Create train and eval hooks for Experiment. | [
"Create",
"train",
"and",
"eval",
"hooks",
"for",
"Experiment",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L328-L365 |
22,263 | tensorflow/tensor2tensor | tensor2tensor/utils/trainer_lib.py | create_experiment_fn | def create_experiment_fn(*args, **kwargs):
"""Wrapper for canonical experiment_fn. See create_experiment."""
def experiment_fn(run_config, hparams):
return create_experiment(run_config, hparams, *args, **kwargs)
return experiment_fn | python | def create_experiment_fn(*args, **kwargs):
"""Wrapper for canonical experiment_fn. See create_experiment."""
def experiment_fn(run_config, hparams):
return create_experiment(run_config, hparams, *args, **kwargs)
return experiment_fn | [
"def",
"create_experiment_fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"experiment_fn",
"(",
"run_config",
",",
"hparams",
")",
":",
"return",
"create_experiment",
"(",
"run_config",
",",
"hparams",
",",
"*",
"args",
",",
"*",
"*",
"k... | Wrapper for canonical experiment_fn. See create_experiment. | [
"Wrapper",
"for",
"canonical",
"experiment_fn",
".",
"See",
"create_experiment",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L770-L776 |
22,264 | tensorflow/tensor2tensor | tensor2tensor/utils/trainer_lib.py | restore_checkpoint | def restore_checkpoint(ckpt_dir, saver, sess, must_restore=False):
"""Restore from a checkpoint."""
ckpt = tf.train.get_checkpoint_state(ckpt_dir)
if must_restore and not ckpt:
raise ValueError("No checkpoint found in %s" % ckpt_dir)
if not ckpt:
return 0
path = ckpt.model_checkpoint_path
tf.loggin... | python | def restore_checkpoint(ckpt_dir, saver, sess, must_restore=False):
"""Restore from a checkpoint."""
ckpt = tf.train.get_checkpoint_state(ckpt_dir)
if must_restore and not ckpt:
raise ValueError("No checkpoint found in %s" % ckpt_dir)
if not ckpt:
return 0
path = ckpt.model_checkpoint_path
tf.loggin... | [
"def",
"restore_checkpoint",
"(",
"ckpt_dir",
",",
"saver",
",",
"sess",
",",
"must_restore",
"=",
"False",
")",
":",
"ckpt",
"=",
"tf",
".",
"train",
".",
"get_checkpoint_state",
"(",
"ckpt_dir",
")",
"if",
"must_restore",
"and",
"not",
"ckpt",
":",
"rais... | Restore from a checkpoint. | [
"Restore",
"from",
"a",
"checkpoint",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L785-L797 |
22,265 | tensorflow/tensor2tensor | tensor2tensor/utils/trainer_lib.py | T2TExperiment.train_eval_and_decode | def train_eval_and_decode(self):
"""Does eval and decode after training every eval_freq_in_steps."""
eval_steps = self._hparams.eval_freq_in_steps
packed_dataset = "_packed" in self._hparams.problem.name
mlperf_log.transformer_print(key=mlperf_log.TRAIN_LOOP)
for i in range(0, self._train_spec.max_s... | python | def train_eval_and_decode(self):
"""Does eval and decode after training every eval_freq_in_steps."""
eval_steps = self._hparams.eval_freq_in_steps
packed_dataset = "_packed" in self._hparams.problem.name
mlperf_log.transformer_print(key=mlperf_log.TRAIN_LOOP)
for i in range(0, self._train_spec.max_s... | [
"def",
"train_eval_and_decode",
"(",
"self",
")",
":",
"eval_steps",
"=",
"self",
".",
"_hparams",
".",
"eval_freq_in_steps",
"packed_dataset",
"=",
"\"_packed\"",
"in",
"self",
".",
"_hparams",
".",
"problem",
".",
"name",
"mlperf_log",
".",
"transformer_print",
... | Does eval and decode after training every eval_freq_in_steps. | [
"Does",
"eval",
"and",
"decode",
"after",
"training",
"every",
"eval_freq_in_steps",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L419-L461 |
22,266 | tensorflow/tensor2tensor | tensor2tensor/utils/trainer_lib.py | T2TExperiment.continuous_eval | def continuous_eval(self):
"""Evaluate until checkpoints stop being produced."""
for ckpt_path in next_checkpoint(self._hparams.model_dir,
self._hparams.eval_timeout_mins):
# Skip zero'th step.
train_step = decoding.get_step_from_ckpt_path(ckpt_path)
if tra... | python | def continuous_eval(self):
"""Evaluate until checkpoints stop being produced."""
for ckpt_path in next_checkpoint(self._hparams.model_dir,
self._hparams.eval_timeout_mins):
# Skip zero'th step.
train_step = decoding.get_step_from_ckpt_path(ckpt_path)
if tra... | [
"def",
"continuous_eval",
"(",
"self",
")",
":",
"for",
"ckpt_path",
"in",
"next_checkpoint",
"(",
"self",
".",
"_hparams",
".",
"model_dir",
",",
"self",
".",
"_hparams",
".",
"eval_timeout_mins",
")",
":",
"# Skip zero'th step.",
"train_step",
"=",
"decoding",... | Evaluate until checkpoints stop being produced. | [
"Evaluate",
"until",
"checkpoints",
"stop",
"being",
"produced",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L488-L497 |
22,267 | tensorflow/tensor2tensor | tensor2tensor/utils/trainer_lib.py | T2TExperiment.continuous_eval_on_train_data | def continuous_eval_on_train_data(self):
"""Evaluate on train data until checkpoints stop being produced."""
for ckpt_path in next_checkpoint(self._hparams.model_dir,
self._hparams.eval_timeout_mins):
# Skip zero'th step.
train_step = decoding.get_step_from_ckpt_... | python | def continuous_eval_on_train_data(self):
"""Evaluate on train data until checkpoints stop being produced."""
for ckpt_path in next_checkpoint(self._hparams.model_dir,
self._hparams.eval_timeout_mins):
# Skip zero'th step.
train_step = decoding.get_step_from_ckpt_... | [
"def",
"continuous_eval_on_train_data",
"(",
"self",
")",
":",
"for",
"ckpt_path",
"in",
"next_checkpoint",
"(",
"self",
".",
"_hparams",
".",
"model_dir",
",",
"self",
".",
"_hparams",
".",
"eval_timeout_mins",
")",
":",
"# Skip zero'th step.",
"train_step",
"=",... | Evaluate on train data until checkpoints stop being produced. | [
"Evaluate",
"on",
"train",
"data",
"until",
"checkpoints",
"stop",
"being",
"produced",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L499-L508 |
22,268 | tensorflow/tensor2tensor | tensor2tensor/utils/trainer_lib.py | T2TExperiment.run_std_server | def run_std_server(self):
"""Starts a TensorFlow server and joins the serving thread.
Typically used for parameter servers.
Raises:
ValueError: if not enough information is available in the estimator's
config to create a server.
"""
config = tf.estimator.RunConfig()
server = tf.t... | python | def run_std_server(self):
"""Starts a TensorFlow server and joins the serving thread.
Typically used for parameter servers.
Raises:
ValueError: if not enough information is available in the estimator's
config to create a server.
"""
config = tf.estimator.RunConfig()
server = tf.t... | [
"def",
"run_std_server",
"(",
"self",
")",
":",
"config",
"=",
"tf",
".",
"estimator",
".",
"RunConfig",
"(",
")",
"server",
"=",
"tf",
".",
"train",
".",
"Server",
"(",
"config",
".",
"cluster_spec",
",",
"job_name",
"=",
"config",
".",
"task_type",
"... | Starts a TensorFlow server and joins the serving thread.
Typically used for parameter servers.
Raises:
ValueError: if not enough information is available in the estimator's
config to create a server. | [
"Starts",
"a",
"TensorFlow",
"server",
"and",
"joins",
"the",
"serving",
"thread",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L521-L536 |
22,269 | tensorflow/tensor2tensor | tensor2tensor/utils/trainer_lib.py | T2TExperiment.decode | def decode(self,
dataset_split=None,
decode_from_file=False,
checkpoint_path=None):
"""Decodes from dataset or file."""
if decode_from_file:
decoding.decode_from_file(self._estimator,
self._decode_hparams.decode_from_file,
... | python | def decode(self,
dataset_split=None,
decode_from_file=False,
checkpoint_path=None):
"""Decodes from dataset or file."""
if decode_from_file:
decoding.decode_from_file(self._estimator,
self._decode_hparams.decode_from_file,
... | [
"def",
"decode",
"(",
"self",
",",
"dataset_split",
"=",
"None",
",",
"decode_from_file",
"=",
"False",
",",
"checkpoint_path",
"=",
"None",
")",
":",
"if",
"decode_from_file",
":",
"decoding",
".",
"decode_from_file",
"(",
"self",
".",
"_estimator",
",",
"s... | Decodes from dataset or file. | [
"Decodes",
"from",
"dataset",
"or",
"file",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L538-L556 |
22,270 | tensorflow/tensor2tensor | tensor2tensor/utils/trainer_lib.py | T2TExperiment.continuous_decode_from_file | def continuous_decode_from_file(self):
"""Decode from file on new checkpoint."""
for _ in next_checkpoint(self._hparams.model_dir,
self._decode_hparams.decode_timeout_mins):
self.decode(decode_from_file=True) | python | def continuous_decode_from_file(self):
"""Decode from file on new checkpoint."""
for _ in next_checkpoint(self._hparams.model_dir,
self._decode_hparams.decode_timeout_mins):
self.decode(decode_from_file=True) | [
"def",
"continuous_decode_from_file",
"(",
"self",
")",
":",
"for",
"_",
"in",
"next_checkpoint",
"(",
"self",
".",
"_hparams",
".",
"model_dir",
",",
"self",
".",
"_decode_hparams",
".",
"decode_timeout_mins",
")",
":",
"self",
".",
"decode",
"(",
"decode_fro... | Decode from file on new checkpoint. | [
"Decode",
"from",
"file",
"on",
"new",
"checkpoint",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L606-L610 |
22,271 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | _flatten_dict | def _flatten_dict(original_dict):
"""Flatten dict of dicts into a single dict with appropriate prefixes.
Handles only 2 levels of nesting in the original dict.
Args:
original_dict: Dict which may contain one or more dicts.
Returns:
flat_dict: Dict without any nesting. Any dicts in the original dict ha... | python | def _flatten_dict(original_dict):
"""Flatten dict of dicts into a single dict with appropriate prefixes.
Handles only 2 levels of nesting in the original dict.
Args:
original_dict: Dict which may contain one or more dicts.
Returns:
flat_dict: Dict without any nesting. Any dicts in the original dict ha... | [
"def",
"_flatten_dict",
"(",
"original_dict",
")",
":",
"flat_dict",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"original_dict",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"for",
"name",
",",
"tensor",
... | Flatten dict of dicts into a single dict with appropriate prefixes.
Handles only 2 levels of nesting in the original dict.
Args:
original_dict: Dict which may contain one or more dicts.
Returns:
flat_dict: Dict without any nesting. Any dicts in the original dict have
their keys as prefixes in the ... | [
"Flatten",
"dict",
"of",
"dicts",
"into",
"a",
"single",
"dict",
"with",
"appropriate",
"prefixes",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L63-L87 |
22,272 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | _unflatten_dict | def _unflatten_dict(flat_dict, prefixes):
"""Returns a dict of dicts if any prefixes match keys in the flat dict.
The function handles the case where the prefix may not be a dict.
Args:
flat_dict: A dict without any nesting.
prefixes: A list of strings which may have been dicts in the
original s... | python | def _unflatten_dict(flat_dict, prefixes):
"""Returns a dict of dicts if any prefixes match keys in the flat dict.
The function handles the case where the prefix may not be a dict.
Args:
flat_dict: A dict without any nesting.
prefixes: A list of strings which may have been dicts in the
original s... | [
"def",
"_unflatten_dict",
"(",
"flat_dict",
",",
"prefixes",
")",
":",
"original_dict",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"flat_dict",
".",
"items",
"(",
")",
":",
"prefix_found",
"=",
"False",
"for",
"prefix",
"in",
"prefixes",
":",
"full... | Returns a dict of dicts if any prefixes match keys in the flat dict.
The function handles the case where the prefix may not be a dict.
Args:
flat_dict: A dict without any nesting.
prefixes: A list of strings which may have been dicts in the
original structure. | [
"Returns",
"a",
"dict",
"of",
"dicts",
"if",
"any",
"prefixes",
"match",
"keys",
"in",
"the",
"flat",
"dict",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L90-L117 |
22,273 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | create_dummy_vars | def create_dummy_vars():
"""Dummy vars for restore to work when not using TPU codepath."""
var_names = set([v.name for v in tf.global_variables()])
if "losses_avg/problem_0/total_loss:0" in var_names:
return
with tf.variable_scope("losses_avg"):
with tf.variable_scope("problem_0"):
for var_name in... | python | def create_dummy_vars():
"""Dummy vars for restore to work when not using TPU codepath."""
var_names = set([v.name for v in tf.global_variables()])
if "losses_avg/problem_0/total_loss:0" in var_names:
return
with tf.variable_scope("losses_avg"):
with tf.variable_scope("problem_0"):
for var_name in... | [
"def",
"create_dummy_vars",
"(",
")",
":",
"var_names",
"=",
"set",
"(",
"[",
"v",
".",
"name",
"for",
"v",
"in",
"tf",
".",
"global_variables",
"(",
")",
"]",
")",
"if",
"\"losses_avg/problem_0/total_loss:0\"",
"in",
"var_names",
":",
"return",
"with",
"t... | Dummy vars for restore to work when not using TPU codepath. | [
"Dummy",
"vars",
"for",
"restore",
"to",
"work",
"when",
"not",
"using",
"TPU",
"codepath",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L1916-L1927 |
22,274 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | remove_summaries | def remove_summaries():
"""Remove summaries from the default graph."""
g = tf.get_default_graph()
key = tf.GraphKeys.SUMMARIES
log_debug("Remove summaries %s" % str(g.get_collection(key)))
del g.get_collection_ref(key)[:]
assert not g.get_collection(key) | python | def remove_summaries():
"""Remove summaries from the default graph."""
g = tf.get_default_graph()
key = tf.GraphKeys.SUMMARIES
log_debug("Remove summaries %s" % str(g.get_collection(key)))
del g.get_collection_ref(key)[:]
assert not g.get_collection(key) | [
"def",
"remove_summaries",
"(",
")",
":",
"g",
"=",
"tf",
".",
"get_default_graph",
"(",
")",
"key",
"=",
"tf",
".",
"GraphKeys",
".",
"SUMMARIES",
"log_debug",
"(",
"\"Remove summaries %s\"",
"%",
"str",
"(",
"g",
".",
"get_collection",
"(",
"key",
")",
... | Remove summaries from the default graph. | [
"Remove",
"summaries",
"from",
"the",
"default",
"graph",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L2018-L2024 |
22,275 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | create_host_call | def create_host_call(model_dir):
"""Construct a host_call writing scalar summaries.
Args:
model_dir: String containing path to train
Returns:
(fn, args) Pair to be called by TPUEstimator as the host_call.
"""
graph = tf.get_default_graph()
summaries = graph.get_collection(tf.GraphKeys.SUMMARIES)
... | python | def create_host_call(model_dir):
"""Construct a host_call writing scalar summaries.
Args:
model_dir: String containing path to train
Returns:
(fn, args) Pair to be called by TPUEstimator as the host_call.
"""
graph = tf.get_default_graph()
summaries = graph.get_collection(tf.GraphKeys.SUMMARIES)
... | [
"def",
"create_host_call",
"(",
"model_dir",
")",
":",
"graph",
"=",
"tf",
".",
"get_default_graph",
"(",
")",
"summaries",
"=",
"graph",
".",
"get_collection",
"(",
"tf",
".",
"GraphKeys",
".",
"SUMMARIES",
")",
"gs_t",
"=",
"tf",
".",
"reshape",
"(",
"... | Construct a host_call writing scalar summaries.
Args:
model_dir: String containing path to train
Returns:
(fn, args) Pair to be called by TPUEstimator as the host_call. | [
"Construct",
"a",
"host_call",
"writing",
"scalar",
"summaries",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L2027-L2098 |
22,276 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | average_sharded_losses | def average_sharded_losses(sharded_losses):
"""Average losses across datashards.
Args:
sharded_losses: list<dict<str loss_name, Tensor loss>>. The loss
can be a single Tensor or a 2-tuple (numerator and denominator).
Returns:
losses: dict<str loss_name, Tensor avg_loss>
"""
losses = {}
for l... | python | def average_sharded_losses(sharded_losses):
"""Average losses across datashards.
Args:
sharded_losses: list<dict<str loss_name, Tensor loss>>. The loss
can be a single Tensor or a 2-tuple (numerator and denominator).
Returns:
losses: dict<str loss_name, Tensor avg_loss>
"""
losses = {}
for l... | [
"def",
"average_sharded_losses",
"(",
"sharded_losses",
")",
":",
"losses",
"=",
"{",
"}",
"for",
"loss_name",
"in",
"sorted",
"(",
"sharded_losses",
"[",
"0",
"]",
")",
":",
"all_shards",
"=",
"[",
"shard_losses",
"[",
"loss_name",
"]",
"for",
"shard_losses... | Average losses across datashards.
Args:
sharded_losses: list<dict<str loss_name, Tensor loss>>. The loss
can be a single Tensor or a 2-tuple (numerator and denominator).
Returns:
losses: dict<str loss_name, Tensor avg_loss> | [
"Average",
"losses",
"across",
"datashards",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L2121-L2143 |
22,277 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | summarize_features | def summarize_features(features, num_shards=1):
"""Generate summaries for features."""
if not common_layers.should_generate_summaries():
return
with tf.name_scope("input_stats"):
for (k, v) in sorted(six.iteritems(features)):
if (isinstance(v, tf.Tensor) and (v.get_shape().ndims > 1) and
... | python | def summarize_features(features, num_shards=1):
"""Generate summaries for features."""
if not common_layers.should_generate_summaries():
return
with tf.name_scope("input_stats"):
for (k, v) in sorted(six.iteritems(features)):
if (isinstance(v, tf.Tensor) and (v.get_shape().ndims > 1) and
... | [
"def",
"summarize_features",
"(",
"features",
",",
"num_shards",
"=",
"1",
")",
":",
"if",
"not",
"common_layers",
".",
"should_generate_summaries",
"(",
")",
":",
"return",
"with",
"tf",
".",
"name_scope",
"(",
"\"input_stats\"",
")",
":",
"for",
"(",
"k",
... | Generate summaries for features. | [
"Generate",
"summaries",
"for",
"features",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L2146-L2161 |
22,278 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | _compose_custom_getters | def _compose_custom_getters(getter_a, getter_b):
"""Compose two custom getters.
Example use:
tf.get_variable_scope().set_custom_getter(
compose_custom_getters(tf.get_variable_scope().custom_getter, new_getter))
This composes getters in the same way as creating a new variable scope with
the new_getter, b... | python | def _compose_custom_getters(getter_a, getter_b):
"""Compose two custom getters.
Example use:
tf.get_variable_scope().set_custom_getter(
compose_custom_getters(tf.get_variable_scope().custom_getter, new_getter))
This composes getters in the same way as creating a new variable scope with
the new_getter, b... | [
"def",
"_compose_custom_getters",
"(",
"getter_a",
",",
"getter_b",
")",
":",
"if",
"not",
"getter_a",
":",
"return",
"getter_b",
"if",
"not",
"getter_b",
":",
"return",
"getter_a",
"def",
"getter_fn",
"(",
"getter",
",",
"*",
"args",
",",
"*",
"*",
"kwarg... | Compose two custom getters.
Example use:
tf.get_variable_scope().set_custom_getter(
compose_custom_getters(tf.get_variable_scope().custom_getter, new_getter))
This composes getters in the same way as creating a new variable scope with
the new_getter, but it does not actually create a new variable scope.
... | [
"Compose",
"two",
"custom",
"getters",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L2186-L2211 |
22,279 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | set_custom_getter_compose | def set_custom_getter_compose(custom_getter):
"""Set a custom getter in the current variable scope.
Do not overwrite the existing custom getter - rather compose with it.
Args:
custom_getter: a custom getter.
"""
tf.get_variable_scope().set_custom_getter(
_compose_custom_getters(tf.get_variable_sco... | python | def set_custom_getter_compose(custom_getter):
"""Set a custom getter in the current variable scope.
Do not overwrite the existing custom getter - rather compose with it.
Args:
custom_getter: a custom getter.
"""
tf.get_variable_scope().set_custom_getter(
_compose_custom_getters(tf.get_variable_sco... | [
"def",
"set_custom_getter_compose",
"(",
"custom_getter",
")",
":",
"tf",
".",
"get_variable_scope",
"(",
")",
".",
"set_custom_getter",
"(",
"_compose_custom_getters",
"(",
"tf",
".",
"get_variable_scope",
"(",
")",
".",
"custom_getter",
",",
"custom_getter",
")",
... | Set a custom getter in the current variable scope.
Do not overwrite the existing custom getter - rather compose with it.
Args:
custom_getter: a custom getter. | [
"Set",
"a",
"custom",
"getter",
"in",
"the",
"current",
"variable",
"scope",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L2214-L2224 |
22,280 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | initialize_from_ckpt | def initialize_from_ckpt(ckpt_dir, hparams):
"""Initialize variables from given directory."""
model_dir = hparams.get("model_dir", None)
already_has_ckpt = (
model_dir and tf.train.latest_checkpoint(model_dir) is not None)
if already_has_ckpt:
return
tf.logging.info("Checkpoint dir: %s", ckpt_dir)
... | python | def initialize_from_ckpt(ckpt_dir, hparams):
"""Initialize variables from given directory."""
model_dir = hparams.get("model_dir", None)
already_has_ckpt = (
model_dir and tf.train.latest_checkpoint(model_dir) is not None)
if already_has_ckpt:
return
tf.logging.info("Checkpoint dir: %s", ckpt_dir)
... | [
"def",
"initialize_from_ckpt",
"(",
"ckpt_dir",
",",
"hparams",
")",
":",
"model_dir",
"=",
"hparams",
".",
"get",
"(",
"\"model_dir\"",
",",
"None",
")",
"already_has_ckpt",
"=",
"(",
"model_dir",
"and",
"tf",
".",
"train",
".",
"latest_checkpoint",
"(",
"m... | Initialize variables from given directory. | [
"Initialize",
"variables",
"from",
"given",
"directory",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L2236-L2255 |
22,281 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | T2TModel._target_modality_is_real | def _target_modality_is_real(self):
"""Whether the target modality is real-valued."""
vocab_size = self._problem_hparams.vocab_size["targets"]
if vocab_size is not None and hasattr(self._hparams, "vocab_divisor"):
vocab_size += (-vocab_size) % self._hparams.vocab_divisor
modality = self._problem_h... | python | def _target_modality_is_real(self):
"""Whether the target modality is real-valued."""
vocab_size = self._problem_hparams.vocab_size["targets"]
if vocab_size is not None and hasattr(self._hparams, "vocab_divisor"):
vocab_size += (-vocab_size) % self._hparams.vocab_divisor
modality = self._problem_h... | [
"def",
"_target_modality_is_real",
"(",
"self",
")",
":",
"vocab_size",
"=",
"self",
".",
"_problem_hparams",
".",
"vocab_size",
"[",
"\"targets\"",
"]",
"if",
"vocab_size",
"is",
"not",
"None",
"and",
"hasattr",
"(",
"self",
".",
"_hparams",
",",
"\"vocab_div... | Whether the target modality is real-valued. | [
"Whether",
"the",
"target",
"modality",
"is",
"real",
"-",
"valued",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L302-L311 |
22,282 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | T2TModel.model_fn_sharded | def model_fn_sharded(self, sharded_features):
"""Estimator model_fn sharded along batch dimension.
Args:
sharded_features: {str: [Tensor]}. Features sharded along batch dimension.
Each list is the same length (== number of shards).
Returns:
sharded_logits: [Tensor]. Logits for each sha... | python | def model_fn_sharded(self, sharded_features):
"""Estimator model_fn sharded along batch dimension.
Args:
sharded_features: {str: [Tensor]}. Features sharded along batch dimension.
Each list is the same length (== number of shards).
Returns:
sharded_logits: [Tensor]. Logits for each sha... | [
"def",
"model_fn_sharded",
"(",
"self",
",",
"sharded_features",
")",
":",
"dp",
"=",
"self",
".",
"_data_parallelism",
"# [{str: Tensor}]. Transpose of 'sharded_features'.",
"datashard_to_features",
"=",
"self",
".",
"_to_features_per_datashard",
"(",
"sharded_features",
"... | Estimator model_fn sharded along batch dimension.
Args:
sharded_features: {str: [Tensor]}. Features sharded along batch dimension.
Each list is the same length (== number of shards).
Returns:
sharded_logits: [Tensor]. Logits for each shard of examples.
losses: {str: 0-D Tensor}. Loss... | [
"Estimator",
"model_fn",
"sharded",
"along",
"batch",
"dimension",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L348-L412 |
22,283 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | T2TModel.bottom | def bottom(self, features):
"""Transforms features to feed into body.
Args:
features: dict of str to Tensor. Typically it is the preprocessed data
batch after Problem's preprocess_example().
Returns:
transformed_features: dict of same key-value pairs as features. The value
Tens... | python | def bottom(self, features):
"""Transforms features to feed into body.
Args:
features: dict of str to Tensor. Typically it is the preprocessed data
batch after Problem's preprocess_example().
Returns:
transformed_features: dict of same key-value pairs as features. The value
Tens... | [
"def",
"bottom",
"(",
"self",
",",
"features",
")",
":",
"if",
"not",
"self",
".",
"_problem_hparams",
":",
"log_warn",
"(",
"\"Without a Problem, T2TModel.bottom is a passthrough.\"",
")",
"return",
"features",
"transformed_features",
"=",
"collections",
".",
"Ordere... | Transforms features to feed into body.
Args:
features: dict of str to Tensor. Typically it is the preprocessed data
batch after Problem's preprocess_example().
Returns:
transformed_features: dict of same key-value pairs as features. The value
Tensors are newly transformed. | [
"Transforms",
"features",
"to",
"feed",
"into",
"body",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L443-L516 |
22,284 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | T2TModel.top | def top(self, body_output, features):
"""Computes logits given body output and features.
Args:
body_output: dict of str to Tensor, comprising one key-value pair for each
target. Each value denotes the target's pre-logit activations.
Alternatively, it may be a single Tensor denoting the pr... | python | def top(self, body_output, features):
"""Computes logits given body output and features.
Args:
body_output: dict of str to Tensor, comprising one key-value pair for each
target. Each value denotes the target's pre-logit activations.
Alternatively, it may be a single Tensor denoting the pr... | [
"def",
"top",
"(",
"self",
",",
"body_output",
",",
"features",
")",
":",
"if",
"isinstance",
"(",
"body_output",
",",
"dict",
")",
":",
"logits",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"body_output",
")",
":",
"# ... | Computes logits given body output and features.
Args:
body_output: dict of str to Tensor, comprising one key-value pair for each
target. Each value denotes the target's pre-logit activations.
Alternatively, it may be a single Tensor denoting the pre-logits for
that target.
featu... | [
"Computes",
"logits",
"given",
"body",
"output",
"and",
"features",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L583-L612 |
22,285 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | T2TModel.optimize | def optimize(self, loss, num_async_replicas=1, use_tpu=False):
"""Return a training op minimizing loss."""
lr = learning_rate.learning_rate_schedule(self.hparams)
if num_async_replicas > 1:
log_info("Dividing learning rate by num_async_replicas: %d",
num_async_replicas)
lr /= math.s... | python | def optimize(self, loss, num_async_replicas=1, use_tpu=False):
"""Return a training op minimizing loss."""
lr = learning_rate.learning_rate_schedule(self.hparams)
if num_async_replicas > 1:
log_info("Dividing learning rate by num_async_replicas: %d",
num_async_replicas)
lr /= math.s... | [
"def",
"optimize",
"(",
"self",
",",
"loss",
",",
"num_async_replicas",
"=",
"1",
",",
"use_tpu",
"=",
"False",
")",
":",
"lr",
"=",
"learning_rate",
".",
"learning_rate_schedule",
"(",
"self",
".",
"hparams",
")",
"if",
"num_async_replicas",
">",
"1",
":"... | Return a training op minimizing loss. | [
"Return",
"a",
"training",
"op",
"minimizing",
"loss",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L710-L718 |
22,286 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | T2TModel.set_mode | def set_mode(self, mode):
"""Set hparams with the given mode."""
log_info("Setting T2TModel mode to '%s'", mode)
hparams = hparams_lib.copy_hparams(self._original_hparams)
hparams.add_hparam("mode", mode)
# When not in training mode, set all forms of dropout to zero.
if mode != tf.estimator.Mode... | python | def set_mode(self, mode):
"""Set hparams with the given mode."""
log_info("Setting T2TModel mode to '%s'", mode)
hparams = hparams_lib.copy_hparams(self._original_hparams)
hparams.add_hparam("mode", mode)
# When not in training mode, set all forms of dropout to zero.
if mode != tf.estimator.Mode... | [
"def",
"set_mode",
"(",
"self",
",",
"mode",
")",
":",
"log_info",
"(",
"\"Setting T2TModel mode to '%s'\"",
",",
"mode",
")",
"hparams",
"=",
"hparams_lib",
".",
"copy_hparams",
"(",
"self",
".",
"_original_hparams",
")",
"hparams",
".",
"add_hparam",
"(",
"\... | Set hparams with the given mode. | [
"Set",
"hparams",
"with",
"the",
"given",
"mode",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L720-L731 |
22,287 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | T2TModel.eval_autoregressive | def eval_autoregressive(self, features=None, decode_length=50):
"""Autoregressive eval.
Quadratic time in decode_length.
Args:
features: an map of string to `Tensor`
decode_length: an integer. How many additional timesteps to decode.
Returns:
logits: `Tensor`
losses: a dictio... | python | def eval_autoregressive(self, features=None, decode_length=50):
"""Autoregressive eval.
Quadratic time in decode_length.
Args:
features: an map of string to `Tensor`
decode_length: an integer. How many additional timesteps to decode.
Returns:
logits: `Tensor`
losses: a dictio... | [
"def",
"eval_autoregressive",
"(",
"self",
",",
"features",
"=",
"None",
",",
"decode_length",
"=",
"50",
")",
":",
"results",
"=",
"self",
".",
"_slow_greedy_infer",
"(",
"features",
",",
"decode_length",
"=",
"decode_length",
")",
"return",
"results",
"[",
... | Autoregressive eval.
Quadratic time in decode_length.
Args:
features: an map of string to `Tensor`
decode_length: an integer. How many additional timesteps to decode.
Returns:
logits: `Tensor`
losses: a dictionary: {loss-name (string): floating point `Scalar`}.
Contains... | [
"Autoregressive",
"eval",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L737-L752 |
22,288 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | T2TModel.infer | def infer(self,
features=None,
decode_length=50,
beam_size=1,
top_beams=1,
alpha=0.0,
use_tpu=False):
"""A inference method.
Quadratic time in decode_length.
Args:
features: an map of string to `Tensor`
decode_length: an i... | python | def infer(self,
features=None,
decode_length=50,
beam_size=1,
top_beams=1,
alpha=0.0,
use_tpu=False):
"""A inference method.
Quadratic time in decode_length.
Args:
features: an map of string to `Tensor`
decode_length: an i... | [
"def",
"infer",
"(",
"self",
",",
"features",
"=",
"None",
",",
"decode_length",
"=",
"50",
",",
"beam_size",
"=",
"1",
",",
"top_beams",
"=",
"1",
",",
"alpha",
"=",
"0.0",
",",
"use_tpu",
"=",
"False",
")",
":",
"set_custom_getter_compose",
"(",
"sel... | A inference method.
Quadratic time in decode_length.
Args:
features: an map of string to `Tensor`
decode_length: an integer. How many additional timesteps to decode.
beam_size: number of beams.
top_beams: an integer. How many of the beams to return.
alpha: Float that controls th... | [
"A",
"inference",
"method",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L761-L817 |
22,289 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | T2TModel._beam_decode | def _beam_decode(self,
features,
decode_length,
beam_size,
top_beams,
alpha,
use_tpu=False):
"""Beam search decoding.
Models should ideally implement a more efficient version of this function.
... | python | def _beam_decode(self,
features,
decode_length,
beam_size,
top_beams,
alpha,
use_tpu=False):
"""Beam search decoding.
Models should ideally implement a more efficient version of this function.
... | [
"def",
"_beam_decode",
"(",
"self",
",",
"features",
",",
"decode_length",
",",
"beam_size",
",",
"top_beams",
",",
"alpha",
",",
"use_tpu",
"=",
"False",
")",
":",
"return",
"self",
".",
"_beam_decode_slow",
"(",
"features",
",",
"decode_length",
",",
"beam... | Beam search decoding.
Models should ideally implement a more efficient version of this function.
Args:
features: an map of string to `Tensor`
decode_length: an integer. How many additional timesteps to decode.
beam_size: number of beams.
top_beams: an integer. How many of the beams to... | [
"Beam",
"search",
"decoding",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L819-L843 |
22,290 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | T2TModel._greedy_infer | def _greedy_infer(self, features, decode_length, use_tpu=False):
"""A greedy inference method.
Models should ideally implement a more efficient version of this function.
Args:
features: an map of string to `Tensor`
decode_length: an integer. How many additional timesteps to decode.
use_... | python | def _greedy_infer(self, features, decode_length, use_tpu=False):
"""A greedy inference method.
Models should ideally implement a more efficient version of this function.
Args:
features: an map of string to `Tensor`
decode_length: an integer. How many additional timesteps to decode.
use_... | [
"def",
"_greedy_infer",
"(",
"self",
",",
"features",
",",
"decode_length",
",",
"use_tpu",
"=",
"False",
")",
":",
"if",
"use_tpu",
":",
"return",
"self",
".",
"_slow_greedy_infer_tpu",
"(",
"features",
",",
"decode_length",
")",
"return",
"self",
".",
"_sl... | A greedy inference method.
Models should ideally implement a more efficient version of this function.
Args:
features: an map of string to `Tensor`
decode_length: an integer. How many additional timesteps to decode.
use_tpu: A bool, whether to build the inference graph for TPU.
Returns:... | [
"A",
"greedy",
"inference",
"method",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L953-L975 |
22,291 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | T2TModel.sample | def sample(self, features):
"""Run the model and extract samples.
Args:
features: an map of string to `Tensor`.
Returns:
samples: an integer `Tensor`.
logits: a list of `Tensor`s, one per datashard.
losses: a dictionary: {loss-name (string): floating point `Scalar`}.
"""
... | python | def sample(self, features):
"""Run the model and extract samples.
Args:
features: an map of string to `Tensor`.
Returns:
samples: an integer `Tensor`.
logits: a list of `Tensor`s, one per datashard.
losses: a dictionary: {loss-name (string): floating point `Scalar`}.
"""
... | [
"def",
"sample",
"(",
"self",
",",
"features",
")",
":",
"logits",
",",
"losses",
"=",
"self",
"(",
"features",
")",
"# pylint: disable=not-callable",
"if",
"self",
".",
"_target_modality_is_real",
":",
"return",
"logits",
",",
"logits",
",",
"losses",
"# Raw ... | Run the model and extract samples.
Args:
features: an map of string to `Tensor`.
Returns:
samples: an integer `Tensor`.
logits: a list of `Tensor`s, one per datashard.
losses: a dictionary: {loss-name (string): floating point `Scalar`}. | [
"Run",
"the",
"model",
"and",
"extract",
"samples",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L1326-L1355 |
22,292 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | T2TModel._summarize_losses | def _summarize_losses(self, losses_dict):
"""Adds `tf.summary`s to all terms in the losses dictionary."""
if common_layers.should_generate_summaries():
with tf.name_scope("losses"):
for loss_name, loss_val in sorted(losses_dict.items()):
tf.summary.scalar(loss_name, loss_val) | python | def _summarize_losses(self, losses_dict):
"""Adds `tf.summary`s to all terms in the losses dictionary."""
if common_layers.should_generate_summaries():
with tf.name_scope("losses"):
for loss_name, loss_val in sorted(losses_dict.items()):
tf.summary.scalar(loss_name, loss_val) | [
"def",
"_summarize_losses",
"(",
"self",
",",
"losses_dict",
")",
":",
"if",
"common_layers",
".",
"should_generate_summaries",
"(",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"losses\"",
")",
":",
"for",
"loss_name",
",",
"loss_val",
"in",
"sorted",
... | Adds `tf.summary`s to all terms in the losses dictionary. | [
"Adds",
"tf",
".",
"summary",
"s",
"to",
"all",
"terms",
"in",
"the",
"losses",
"dictionary",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L1771-L1776 |
22,293 | tensorflow/tensor2tensor | tensor2tensor/utils/t2t_model.py | T2TModel.maybe_scheduled_sampling | def maybe_scheduled_sampling(self, features, logits, losses):
"""Scheduled sampling.
Performs forward inference again with "targets" feature replaced with values
sampled from the model.
This is the identity unless self.hparams.scheduled_sampling_prob > 0
(default).
**WARNING**: This is not a ... | python | def maybe_scheduled_sampling(self, features, logits, losses):
"""Scheduled sampling.
Performs forward inference again with "targets" feature replaced with values
sampled from the model.
This is the identity unless self.hparams.scheduled_sampling_prob > 0
(default).
**WARNING**: This is not a ... | [
"def",
"maybe_scheduled_sampling",
"(",
"self",
",",
"features",
",",
"logits",
",",
"losses",
")",
":",
"hparams",
"=",
"self",
".",
"hparams",
"problem_hparams",
"=",
"self",
".",
"_problem_hparams",
"# Only do scheduled sampling if requested.",
"if",
"hparams",
"... | Scheduled sampling.
Performs forward inference again with "targets" feature replaced with values
sampled from the model.
This is the identity unless self.hparams.scheduled_sampling_prob > 0
(default).
**WARNING**: This is not a faithful implementation of scheduled sampling.
This implementatio... | [
"Scheduled",
"sampling",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L1778-L1901 |
22,294 | tensorflow/tensor2tensor | tensor2tensor/models/research/attention_lm_moe.py | expand_batch_coordinates | def expand_batch_coordinates(bc, length_factor):
"""Duplicate elements of bc by length_factor.
Args:
bc (tf.Tensor): int32 tensor of shape [1, length, 1]
length_factor (int):
Returns:
tf.Tensor: of shape [1, length*length_factor, 1] where every elements has
been duplicated length_factor times.... | python | def expand_batch_coordinates(bc, length_factor):
"""Duplicate elements of bc by length_factor.
Args:
bc (tf.Tensor): int32 tensor of shape [1, length, 1]
length_factor (int):
Returns:
tf.Tensor: of shape [1, length*length_factor, 1] where every elements has
been duplicated length_factor times.... | [
"def",
"expand_batch_coordinates",
"(",
"bc",
",",
"length_factor",
")",
":",
"assert",
"bc",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"==",
"[",
"1",
",",
"None",
",",
"1",
"]",
"# bc has shape [1, length, 1]",
"bc",
"*=",
"tf",
".",
"const... | Duplicate elements of bc by length_factor.
Args:
bc (tf.Tensor): int32 tensor of shape [1, length, 1]
length_factor (int):
Returns:
tf.Tensor: of shape [1, length*length_factor, 1] where every elements has
been duplicated length_factor times. | [
"Duplicate",
"elements",
"of",
"bc",
"by",
"length_factor",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm_moe.py#L377-L394 |
22,295 | tensorflow/tensor2tensor | tensor2tensor/models/research/attention_lm_moe.py | remove_pad | def remove_pad(x, pad_remover, mode):
"""Remove padding by concatenating all dimension into one.
Args:
x (tf.Tensor): input of shape [batch_size, length, depth]
pad_remover (obj): a PadRemover object
mode (ModeKeys): infer, train or eval. If inference, the padding remover is
not applied
Return... | python | def remove_pad(x, pad_remover, mode):
"""Remove padding by concatenating all dimension into one.
Args:
x (tf.Tensor): input of shape [batch_size, length, depth]
pad_remover (obj): a PadRemover object
mode (ModeKeys): infer, train or eval. If inference, the padding remover is
not applied
Return... | [
"def",
"remove_pad",
"(",
"x",
",",
"pad_remover",
",",
"mode",
")",
":",
"# Concatenate all tokens (without padding)",
"x",
"=",
"expert_utils",
".",
"flatten_all_but_last",
"(",
"x",
")",
"# Remove padding for training and eval",
"if",
"mode",
"!=",
"ModeKeys",
".",... | Remove padding by concatenating all dimension into one.
Args:
x (tf.Tensor): input of shape [batch_size, length, depth]
pad_remover (obj): a PadRemover object
mode (ModeKeys): infer, train or eval. If inference, the padding remover is
not applied
Returns:
tf.Tensor of shape [1,length_nonpad,... | [
"Remove",
"padding",
"by",
"concatenating",
"all",
"dimension",
"into",
"one",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm_moe.py#L398-L422 |
22,296 | tensorflow/tensor2tensor | tensor2tensor/models/research/attention_lm_moe.py | attention_lm_ae_extended | def attention_lm_ae_extended():
"""Experiment with the exp_factor params."""
hparams = attention_lm_moe_base_long_seq()
hparams.attention_layers = "eeee"
hparams.attention_local = True
# hparams.factored_logits=1 # Necessary when the number of expert grow bigger
hparams.attention_moe_k = 2
hparams.attent... | python | def attention_lm_ae_extended():
"""Experiment with the exp_factor params."""
hparams = attention_lm_moe_base_long_seq()
hparams.attention_layers = "eeee"
hparams.attention_local = True
# hparams.factored_logits=1 # Necessary when the number of expert grow bigger
hparams.attention_moe_k = 2
hparams.attent... | [
"def",
"attention_lm_ae_extended",
"(",
")",
":",
"hparams",
"=",
"attention_lm_moe_base_long_seq",
"(",
")",
"hparams",
".",
"attention_layers",
"=",
"\"eeee\"",
"hparams",
".",
"attention_local",
"=",
"True",
"# hparams.factored_logits=1 # Necessary when the number of expe... | Experiment with the exp_factor params. | [
"Experiment",
"with",
"the",
"exp_factor",
"params",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm_moe.py#L599-L611 |
22,297 | tensorflow/tensor2tensor | tensor2tensor/models/research/attention_lm_moe.py | attention_lm_moe_small | def attention_lm_moe_small():
"""Cheap model for single-gpu training.
on lm1b_32k:
~312M params
1.6 steps/sec on [GeForce GTX TITAN X]
After 50K steps on 8 GPUs (synchronous):
eval_log_ppl_per_token = 3.31
Returns:
an hparams object.
"""
hparams = attention_lm_moe_base()
hparam... | python | def attention_lm_moe_small():
"""Cheap model for single-gpu training.
on lm1b_32k:
~312M params
1.6 steps/sec on [GeForce GTX TITAN X]
After 50K steps on 8 GPUs (synchronous):
eval_log_ppl_per_token = 3.31
Returns:
an hparams object.
"""
hparams = attention_lm_moe_base()
hparam... | [
"def",
"attention_lm_moe_small",
"(",
")",
":",
"hparams",
"=",
"attention_lm_moe_base",
"(",
")",
"hparams",
".",
"num_hidden_layers",
"=",
"4",
"hparams",
".",
"hidden_size",
"=",
"512",
"hparams",
".",
"filter_size",
"=",
"2048",
"hparams",
".",
"moe_num_expe... | Cheap model for single-gpu training.
on lm1b_32k:
~312M params
1.6 steps/sec on [GeForce GTX TITAN X]
After 50K steps on 8 GPUs (synchronous):
eval_log_ppl_per_token = 3.31
Returns:
an hparams object. | [
"Cheap",
"model",
"for",
"single",
"-",
"gpu",
"training",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm_moe.py#L632-L650 |
22,298 | tensorflow/tensor2tensor | tensor2tensor/models/research/attention_lm_moe.py | attention_lm_attention_moe_tiny | def attention_lm_attention_moe_tiny():
"""Cheap model for debugging.
Returns:
an hparams object.
"""
hparams = attention_lm_moe_small()
hparams.moe_layers = ""
hparams.attention_num_experts = 128
hparams.filter_size = 8192
hparams.attention_type = AttentionType.LOCAL_EXPERTS
return hparams | python | def attention_lm_attention_moe_tiny():
"""Cheap model for debugging.
Returns:
an hparams object.
"""
hparams = attention_lm_moe_small()
hparams.moe_layers = ""
hparams.attention_num_experts = 128
hparams.filter_size = 8192
hparams.attention_type = AttentionType.LOCAL_EXPERTS
return hparams | [
"def",
"attention_lm_attention_moe_tiny",
"(",
")",
":",
"hparams",
"=",
"attention_lm_moe_small",
"(",
")",
"hparams",
".",
"moe_layers",
"=",
"\"\"",
"hparams",
".",
"attention_num_experts",
"=",
"128",
"hparams",
".",
"filter_size",
"=",
"8192",
"hparams",
".",... | Cheap model for debugging.
Returns:
an hparams object. | [
"Cheap",
"model",
"for",
"debugging",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm_moe.py#L666-L677 |
22,299 | tensorflow/tensor2tensor | tensor2tensor/models/research/attention_lm_moe.py | attention_lm_moe_large | def attention_lm_moe_large():
"""Large model for distributed training.
Over 1B parameters, so requires multi-gpu training due to memory
requirements.
on lm1b_32k:
After 45K steps on 8 GPUs (synchronous):
eval_log_ppl_per_token = 3.18
eval_ppl_per_word = exp(1.107893 * eval_log_ppl_per_to... | python | def attention_lm_moe_large():
"""Large model for distributed training.
Over 1B parameters, so requires multi-gpu training due to memory
requirements.
on lm1b_32k:
After 45K steps on 8 GPUs (synchronous):
eval_log_ppl_per_token = 3.18
eval_ppl_per_word = exp(1.107893 * eval_log_ppl_per_to... | [
"def",
"attention_lm_moe_large",
"(",
")",
":",
"hparams",
"=",
"attention_lm_moe_base",
"(",
")",
"hparams",
".",
"num_hidden_layers",
"=",
"5",
"hparams",
".",
"moe_layers",
"=",
"\"3\"",
"hparams",
".",
"hidden_size",
"=",
"1024",
"hparams",
".",
"num_heads",... | Large model for distributed training.
Over 1B parameters, so requires multi-gpu training due to memory
requirements.
on lm1b_32k:
After 45K steps on 8 GPUs (synchronous):
eval_log_ppl_per_token = 3.18
eval_ppl_per_word = exp(1.107893 * eval_log_ppl_per_token) = 33.9
Returns:
an hpar... | [
"Large",
"model",
"for",
"distributed",
"training",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm_moe.py#L699-L722 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.