repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | brelu | def brelu(x):
"""Bipolar ReLU as in https://arxiv.org/abs/1709.04054."""
x_shape = shape_list(x)
x1, x2 = tf.split(tf.reshape(x, x_shape[:-1] + [-1, 2]), 2, axis=-1)
y1 = tf.nn.relu(x1)
y2 = -tf.nn.relu(-x2)
return tf.reshape(tf.concat([y1, y2], axis=-1), x_shape) | python | def brelu(x):
"""Bipolar ReLU as in https://arxiv.org/abs/1709.04054."""
x_shape = shape_list(x)
x1, x2 = tf.split(tf.reshape(x, x_shape[:-1] + [-1, 2]), 2, axis=-1)
y1 = tf.nn.relu(x1)
y2 = -tf.nn.relu(-x2)
return tf.reshape(tf.concat([y1, y2], axis=-1), x_shape) | [
"def",
"brelu",
"(",
"x",
")",
":",
"x_shape",
"=",
"shape_list",
"(",
"x",
")",
"x1",
",",
"x2",
"=",
"tf",
".",
"split",
"(",
"tf",
".",
"reshape",
"(",
"x",
",",
"x_shape",
"[",
":",
"-",
"1",
"]",
"+",
"[",
"-",
"1",
",",
"2",
"]",
")... | Bipolar ReLU as in https://arxiv.org/abs/1709.04054. | [
"Bipolar",
"ReLU",
"as",
"in",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1709",
".",
"04054",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3254-L3260 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | belu | def belu(x):
"""Bipolar ELU as in https://arxiv.org/abs/1709.04054."""
x_shape = shape_list(x)
x1, x2 = tf.split(tf.reshape(x, x_shape[:-1] + [-1, 2]), 2, axis=-1)
y1 = tf.nn.elu(x1)
y2 = -tf.nn.elu(-x2)
return tf.reshape(tf.concat([y1, y2], axis=-1), x_shape) | python | def belu(x):
"""Bipolar ELU as in https://arxiv.org/abs/1709.04054."""
x_shape = shape_list(x)
x1, x2 = tf.split(tf.reshape(x, x_shape[:-1] + [-1, 2]), 2, axis=-1)
y1 = tf.nn.elu(x1)
y2 = -tf.nn.elu(-x2)
return tf.reshape(tf.concat([y1, y2], axis=-1), x_shape) | [
"def",
"belu",
"(",
"x",
")",
":",
"x_shape",
"=",
"shape_list",
"(",
"x",
")",
"x1",
",",
"x2",
"=",
"tf",
".",
"split",
"(",
"tf",
".",
"reshape",
"(",
"x",
",",
"x_shape",
"[",
":",
"-",
"1",
"]",
"+",
"[",
"-",
"1",
",",
"2",
"]",
")"... | Bipolar ELU as in https://arxiv.org/abs/1709.04054. | [
"Bipolar",
"ELU",
"as",
"in",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1709",
".",
"04054",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3263-L3269 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | gelu | def gelu(x):
"""Gaussian Error Linear Unit.
This is a smoother version of the RELU.
Original paper: https://arxiv.org/abs/1606.08415
Args:
x: float Tensor to perform activation.
Returns:
x with the GELU activation applied.
"""
cdf = 0.5 * (1.0 + tf.tanh(
(np.sqrt(2 / np.pi) * (x + 0.04471... | python | def gelu(x):
"""Gaussian Error Linear Unit.
This is a smoother version of the RELU.
Original paper: https://arxiv.org/abs/1606.08415
Args:
x: float Tensor to perform activation.
Returns:
x with the GELU activation applied.
"""
cdf = 0.5 * (1.0 + tf.tanh(
(np.sqrt(2 / np.pi) * (x + 0.04471... | [
"def",
"gelu",
"(",
"x",
")",
":",
"cdf",
"=",
"0.5",
"*",
"(",
"1.0",
"+",
"tf",
".",
"tanh",
"(",
"(",
"np",
".",
"sqrt",
"(",
"2",
"/",
"np",
".",
"pi",
")",
"*",
"(",
"x",
"+",
"0.044715",
"*",
"tf",
".",
"pow",
"(",
"x",
",",
"3",
... | Gaussian Error Linear Unit.
This is a smoother version of the RELU.
Original paper: https://arxiv.org/abs/1606.08415
Args:
x: float Tensor to perform activation.
Returns:
x with the GELU activation applied. | [
"Gaussian",
"Error",
"Linear",
"Unit",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3272-L3286 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | nac | def nac(x, depth, name=None, reuse=None):
"""NAC as in https://arxiv.org/abs/1808.00508."""
with tf.variable_scope(name, default_name="nac", values=[x], reuse=reuse):
x_shape = shape_list(x)
w = tf.get_variable("w", [x_shape[-1], depth])
m = tf.get_variable("m", [x_shape[-1], depth])
w = tf.tanh(w) ... | python | def nac(x, depth, name=None, reuse=None):
"""NAC as in https://arxiv.org/abs/1808.00508."""
with tf.variable_scope(name, default_name="nac", values=[x], reuse=reuse):
x_shape = shape_list(x)
w = tf.get_variable("w", [x_shape[-1], depth])
m = tf.get_variable("m", [x_shape[-1], depth])
w = tf.tanh(w) ... | [
"def",
"nac",
"(",
"x",
",",
"depth",
",",
"name",
"=",
"None",
",",
"reuse",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"nac\"",
",",
"values",
"=",
"[",
"x",
"]",
",",
"reuse",
"=",
"reu... | NAC as in https://arxiv.org/abs/1808.00508. | [
"NAC",
"as",
"in",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1808",
".",
"00508",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3289-L3298 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | nalu | def nalu(x, depth, epsilon=1e-30, name=None, reuse=None):
"""NALU as in https://arxiv.org/abs/1808.00508."""
with tf.variable_scope(name, default_name="nalu", values=[x], reuse=reuse):
x_shape = shape_list(x)
x_flat = tf.reshape(x, [-1, x_shape[-1]])
gw = tf.get_variable("w", [x_shape[-1], depth])
g... | python | def nalu(x, depth, epsilon=1e-30, name=None, reuse=None):
"""NALU as in https://arxiv.org/abs/1808.00508."""
with tf.variable_scope(name, default_name="nalu", values=[x], reuse=reuse):
x_shape = shape_list(x)
x_flat = tf.reshape(x, [-1, x_shape[-1]])
gw = tf.get_variable("w", [x_shape[-1], depth])
g... | [
"def",
"nalu",
"(",
"x",
",",
"depth",
",",
"epsilon",
"=",
"1e-30",
",",
"name",
"=",
"None",
",",
"reuse",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"nalu\"",
",",
"values",
"=",
"[",
"x"... | NALU as in https://arxiv.org/abs/1808.00508. | [
"NALU",
"as",
"in",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1808",
".",
"00508",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3301-L3312 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | argmax_with_score | def argmax_with_score(logits, axis=None):
"""Argmax along with the value."""
axis = axis or len(logits.get_shape()) - 1
predictions = tf.argmax(logits, axis=axis)
logits_shape = shape_list(logits)
prefix_shape, vocab_size = logits_shape[:-1], logits_shape[-1]
prefix_size = 1
for d in prefix_shape:
pr... | python | def argmax_with_score(logits, axis=None):
"""Argmax along with the value."""
axis = axis or len(logits.get_shape()) - 1
predictions = tf.argmax(logits, axis=axis)
logits_shape = shape_list(logits)
prefix_shape, vocab_size = logits_shape[:-1], logits_shape[-1]
prefix_size = 1
for d in prefix_shape:
pr... | [
"def",
"argmax_with_score",
"(",
"logits",
",",
"axis",
"=",
"None",
")",
":",
"axis",
"=",
"axis",
"or",
"len",
"(",
"logits",
".",
"get_shape",
"(",
")",
")",
"-",
"1",
"predictions",
"=",
"tf",
".",
"argmax",
"(",
"logits",
",",
"axis",
"=",
"ax... | Argmax along with the value. | [
"Argmax",
"along",
"with",
"the",
"value",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3315-L3338 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | top_kth_iterative | def top_kth_iterative(x, k):
"""Compute the k-th top element of x on the last axis iteratively.
This assumes values in x are non-negative, rescale if needed.
It is often faster than tf.nn.top_k for small k, especially if k < 30.
Note: this does not support back-propagation, it stops gradients!
Args:
x: ... | python | def top_kth_iterative(x, k):
"""Compute the k-th top element of x on the last axis iteratively.
This assumes values in x are non-negative, rescale if needed.
It is often faster than tf.nn.top_k for small k, especially if k < 30.
Note: this does not support back-propagation, it stops gradients!
Args:
x: ... | [
"def",
"top_kth_iterative",
"(",
"x",
",",
"k",
")",
":",
"# The iterative computation is as follows:",
"#",
"# cur_x = x",
"# for _ in range(k):",
"# top_x = maximum of elements of cur_x on the last axis",
"# cur_x = cur_x where cur_x < top_x and 0 everywhere else (top elements)",
"... | Compute the k-th top element of x on the last axis iteratively.
This assumes values in x are non-negative, rescale if needed.
It is often faster than tf.nn.top_k for small k, especially if k < 30.
Note: this does not support back-propagation, it stops gradients!
Args:
x: a Tensor of non-negative numbers o... | [
"Compute",
"the",
"k",
"-",
"th",
"top",
"element",
"of",
"x",
"on",
"the",
"last",
"axis",
"iteratively",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3345-L3375 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | top_1_tpu | def top_1_tpu(inputs):
"""find max and argmax over the last dimension.
Works well on TPU
Args:
inputs: A tensor with shape [..., depth]
Returns:
values: a Tensor with shape [...]
indices: a Tensor with shape [...]
"""
inputs_max = tf.reduce_max(inputs, axis=-1, keepdims=True)
mask = tf.to_i... | python | def top_1_tpu(inputs):
"""find max and argmax over the last dimension.
Works well on TPU
Args:
inputs: A tensor with shape [..., depth]
Returns:
values: a Tensor with shape [...]
indices: a Tensor with shape [...]
"""
inputs_max = tf.reduce_max(inputs, axis=-1, keepdims=True)
mask = tf.to_i... | [
"def",
"top_1_tpu",
"(",
"inputs",
")",
":",
"inputs_max",
"=",
"tf",
".",
"reduce_max",
"(",
"inputs",
",",
"axis",
"=",
"-",
"1",
",",
"keepdims",
"=",
"True",
")",
"mask",
"=",
"tf",
".",
"to_int32",
"(",
"tf",
".",
"equal",
"(",
"inputs_max",
"... | find max and argmax over the last dimension.
Works well on TPU
Args:
inputs: A tensor with shape [..., depth]
Returns:
values: a Tensor with shape [...]
indices: a Tensor with shape [...] | [
"find",
"max",
"and",
"argmax",
"over",
"the",
"last",
"dimension",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3378-L3393 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | sliced_gan_loss | def sliced_gan_loss(input1,
input2,
discriminator,
num_vecs,
do_random_vecs=True,
do_tanh=True,
return_logits=False):
"""Loss inspired by the sliced WGAN paper: https://arxiv.org/abs/1804.01947.
... | python | def sliced_gan_loss(input1,
input2,
discriminator,
num_vecs,
do_random_vecs=True,
do_tanh=True,
return_logits=False):
"""Loss inspired by the sliced WGAN paper: https://arxiv.org/abs/1804.01947.
... | [
"def",
"sliced_gan_loss",
"(",
"input1",
",",
"input2",
",",
"discriminator",
",",
"num_vecs",
",",
"do_random_vecs",
"=",
"True",
",",
"do_tanh",
"=",
"True",
",",
"return_logits",
"=",
"False",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"sliced_... | Loss inspired by the sliced WGAN paper: https://arxiv.org/abs/1804.01947.
Puts input1 and input2 through the provided discriminator to get logits.
Then, computes num_vecs random projections of the logits, sorts them on
the batch dimension and returns the L2 loss between the sorted vectors.
See the above-mentio... | [
"Loss",
"inspired",
"by",
"the",
"sliced",
"WGAN",
"paper",
":",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1804",
".",
"01947",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3524-L3594 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | deep_discriminator | def deep_discriminator(x,
batch_norm,
is_training,
filters=64,
filter_size=4,
stride=2,
output_size=1024):
"""Discriminator architecture based on InfoGAN."""
with tf.variable_sco... | python | def deep_discriminator(x,
batch_norm,
is_training,
filters=64,
filter_size=4,
stride=2,
output_size=1024):
"""Discriminator architecture based on InfoGAN."""
with tf.variable_sco... | [
"def",
"deep_discriminator",
"(",
"x",
",",
"batch_norm",
",",
"is_training",
",",
"filters",
"=",
"64",
",",
"filter_size",
"=",
"4",
",",
"stride",
"=",
"2",
",",
"output_size",
"=",
"1024",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"discri... | Discriminator architecture based on InfoGAN. | [
"Discriminator",
"architecture",
"based",
"on",
"InfoGAN",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3601-L3637 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | weight_targeting | def weight_targeting(w, k):
"""Weight-level magnitude pruning."""
k = tf.to_int32(k)
w_shape = shape_list(w)
size = tf.to_int32(tf.reduce_prod(w_shape[:-1]))
w = tf.reshape(w, [size, w_shape[-1]])
transpose_w = tf.transpose(w)
thres = tf.contrib.framework.sort(tf.abs(transpose_w), axis=1)[:, k]
mask = ... | python | def weight_targeting(w, k):
"""Weight-level magnitude pruning."""
k = tf.to_int32(k)
w_shape = shape_list(w)
size = tf.to_int32(tf.reduce_prod(w_shape[:-1]))
w = tf.reshape(w, [size, w_shape[-1]])
transpose_w = tf.transpose(w)
thres = tf.contrib.framework.sort(tf.abs(transpose_w), axis=1)[:, k]
mask = ... | [
"def",
"weight_targeting",
"(",
"w",
",",
"k",
")",
":",
"k",
"=",
"tf",
".",
"to_int32",
"(",
"k",
")",
"w_shape",
"=",
"shape_list",
"(",
"w",
")",
"size",
"=",
"tf",
".",
"to_int32",
"(",
"tf",
".",
"reduce_prod",
"(",
"w_shape",
"[",
":",
"-"... | Weight-level magnitude pruning. | [
"Weight",
"-",
"level",
"magnitude",
"pruning",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3844-L3855 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | unit_targeting | def unit_targeting(w, k):
"""Unit-level magnitude pruning."""
k = tf.to_int32(k)
w_shape = shape_list(w)
size = tf.to_int32(tf.reduce_prod(w_shape[:-1]))
w = tf.reshape(w, [size, w_shape[-1]])
norm = tf.norm(w, axis=0)
thres = tf.contrib.framework.sort(norm, axis=0)[k]
mask = to_float(thres >= norm)[No... | python | def unit_targeting(w, k):
"""Unit-level magnitude pruning."""
k = tf.to_int32(k)
w_shape = shape_list(w)
size = tf.to_int32(tf.reduce_prod(w_shape[:-1]))
w = tf.reshape(w, [size, w_shape[-1]])
norm = tf.norm(w, axis=0)
thres = tf.contrib.framework.sort(norm, axis=0)[k]
mask = to_float(thres >= norm)[No... | [
"def",
"unit_targeting",
"(",
"w",
",",
"k",
")",
":",
"k",
"=",
"tf",
".",
"to_int32",
"(",
"k",
")",
"w_shape",
"=",
"shape_list",
"(",
"w",
")",
"size",
"=",
"tf",
".",
"to_int32",
"(",
"tf",
".",
"reduce_prod",
"(",
"w_shape",
"[",
":",
"-",
... | Unit-level magnitude pruning. | [
"Unit",
"-",
"level",
"magnitude",
"pruning",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3858-L3870 | train |
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 | train |
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 | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | kl_divergence | def kl_divergence(mu, log_var, mu_p=0.0, log_var_p=0.0):
"""KL divergence of diagonal gaussian N(mu,exp(log_var)) and N(0,1).
Args:
mu: mu parameter of the distribution.
log_var: log(var) parameter of the distribution.
mu_p: optional mu from a learned prior distribution
log_var_p: optional log(var)... | python | def kl_divergence(mu, log_var, mu_p=0.0, log_var_p=0.0):
"""KL divergence of diagonal gaussian N(mu,exp(log_var)) and N(0,1).
Args:
mu: mu parameter of the distribution.
log_var: log(var) parameter of the distribution.
mu_p: optional mu from a learned prior distribution
log_var_p: optional log(var)... | [
"def",
"kl_divergence",
"(",
"mu",
",",
"log_var",
",",
"mu_p",
"=",
"0.0",
",",
"log_var_p",
"=",
"0.0",
")",
":",
"batch_size",
"=",
"shape_list",
"(",
"mu",
")",
"[",
"0",
"]",
"prior_distribution",
"=",
"tfp",
".",
"distributions",
".",
"Normal",
"... | KL divergence of diagonal gaussian N(mu,exp(log_var)) and N(0,1).
Args:
mu: mu parameter of the distribution.
log_var: log(var) parameter of the distribution.
mu_p: optional mu from a learned prior distribution
log_var_p: optional log(var) from a learned prior distribution
Returns:
the KL loss. | [
"KL",
"divergence",
"of",
"diagonal",
"gaussian",
"N",
"(",
"mu",
"exp",
"(",
"log_var",
"))",
"and",
"N",
"(",
"0",
"1",
")",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3985-L4004 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
tensorflow/tensor2tensor | tensor2tensor/rl/rl_utils.py | evaluate_world_model | def evaluate_world_model(
real_env, hparams, world_model_dir, debug_video_path,
split=tf.estimator.ModeKeys.EVAL,
):
"""Evaluate the world model (reward accuracy)."""
frame_stack_size = hparams.frame_stack_size
rollout_subsequences = []
def initial_frame_chooser(batch_size):
assert batch_size == len... | python | def evaluate_world_model(
real_env, hparams, world_model_dir, debug_video_path,
split=tf.estimator.ModeKeys.EVAL,
):
"""Evaluate the world model (reward accuracy)."""
frame_stack_size = hparams.frame_stack_size
rollout_subsequences = []
def initial_frame_chooser(batch_size):
assert batch_size == len... | [
"def",
"evaluate_world_model",
"(",
"real_env",
",",
"hparams",
",",
"world_model_dir",
",",
"debug_video_path",
",",
"split",
"=",
"tf",
".",
"estimator",
".",
"ModeKeys",
".",
"EVAL",
",",
")",
":",
"frame_stack_size",
"=",
"hparams",
".",
"frame_stack_size",
... | Evaluate the world model (reward accuracy). | [
"Evaluate",
"the",
"world",
"model",
"(",
"reward",
"accuracy",
")",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L120-L249 | train |
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 | train |
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 | train |
tensorflow/tensor2tensor | tensor2tensor/rl/rl_utils.py | setup_env | def setup_env(hparams,
batch_size,
max_num_noops,
rl_env_max_episode_steps=-1,
env_name=None):
"""Setup."""
if not env_name:
env_name = full_game_name(hparams.game)
maxskip_envs = should_apply_max_and_skip_env(hparams)
env = T2TGymEnv(
base_env... | python | def setup_env(hparams,
batch_size,
max_num_noops,
rl_env_max_episode_steps=-1,
env_name=None):
"""Setup."""
if not env_name:
env_name = full_game_name(hparams.game)
maxskip_envs = should_apply_max_and_skip_env(hparams)
env = T2TGymEnv(
base_env... | [
"def",
"setup_env",
"(",
"hparams",
",",
"batch_size",
",",
"max_num_noops",
",",
"rl_env_max_episode_steps",
"=",
"-",
"1",
",",
"env_name",
"=",
"None",
")",
":",
"if",
"not",
"env_name",
":",
"env_name",
"=",
"full_game_name",
"(",
"hparams",
".",
"game",... | Setup. | [
"Setup",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L289-L313 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
tensorflow/tensor2tensor | tensor2tensor/rl/rl_utils.py | BatchStackWrapper.set_initial_state | def set_initial_state(self, initial_state, initial_frames):
"""Sets the state that will be used on next reset."""
self.env.set_initial_state(initial_state, initial_frames)
self._initial_frames = initial_frames | python | def set_initial_state(self, initial_state, initial_frames):
"""Sets the state that will be used on next reset."""
self.env.set_initial_state(initial_state, initial_frames)
self._initial_frames = initial_frames | [
"def",
"set_initial_state",
"(",
"self",
",",
"initial_state",
",",
"initial_frames",
")",
":",
"self",
".",
"env",
".",
"set_initial_state",
"(",
"initial_state",
",",
"initial_frames",
")",
"self",
".",
"_initial_frames",
"=",
"initial_frames"
] | Sets the state that will be used on next reset. | [
"Sets",
"the",
"state",
"that",
"will",
"be",
"used",
"on",
"next",
"reset",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L806-L809 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
tensorflow/tensor2tensor | tensor2tensor/rl/player_utils.py | SimulatedGymEnv.add_to_initial_stack | def add_to_initial_stack(self, frame):
"""Adds new frame to (initial) frame stack, removes last one."""
if not self._setable_initial_frames:
raise ValueError(
"This instance does not allow to manually set initial frame stack.")
assert_msg = "{}, {}".format(frame.shape, self._initial_frames.s... | python | def add_to_initial_stack(self, frame):
"""Adds new frame to (initial) frame stack, removes last one."""
if not self._setable_initial_frames:
raise ValueError(
"This instance does not allow to manually set initial frame stack.")
assert_msg = "{}, {}".format(frame.shape, self._initial_frames.s... | [
"def",
"add_to_initial_stack",
"(",
"self",
",",
"frame",
")",
":",
"if",
"not",
"self",
".",
"_setable_initial_frames",
":",
"raise",
"ValueError",
"(",
"\"This instance does not allow to manually set initial frame stack.\"",
")",
"assert_msg",
"=",
"\"{}, {}\"",
".",
... | Adds new frame to (initial) frame stack, removes last one. | [
"Adds",
"new",
"frame",
"to",
"(",
"initial",
")",
"frame",
"stack",
"removes",
"last",
"one",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L111-L120 | train |
tensorflow/tensor2tensor | tensor2tensor/rl/player_utils.py | ExtendToEvenDimentions.observation | def observation(self, frame):
"""Add single zero row/column to observation if needed."""
if frame.shape == self.observation_space.shape:
return frame
else:
extended_frame = np.zeros(self.observation_space.shape,
self.observation_space.dtype)
assert self.HW_A... | python | def observation(self, frame):
"""Add single zero row/column to observation if needed."""
if frame.shape == self.observation_space.shape:
return frame
else:
extended_frame = np.zeros(self.observation_space.shape,
self.observation_space.dtype)
assert self.HW_A... | [
"def",
"observation",
"(",
"self",
",",
"frame",
")",
":",
"if",
"frame",
".",
"shape",
"==",
"self",
".",
"observation_space",
".",
"shape",
":",
"return",
"frame",
"else",
":",
"extended_frame",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"observation_s... | Add single zero row/column to observation if needed. | [
"Add",
"single",
"zero",
"row",
"/",
"column",
"to",
"observation",
"if",
"needed",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/player_utils.py#L208-L217 | train |
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 | train |
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 | train |
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 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/babi_qa.py | _prepare_babi_data | def _prepare_babi_data(tmp_dir, data_dir):
"""Downloads and extracts the dataset.
Args:
tmp_dir: temp directory to download and extract the dataset
data_dir: The base directory where data and vocab files are stored.
Returns:
tmp_dir: temp directory containing the raw data.
"""
if not tf.gfile.Ex... | python | def _prepare_babi_data(tmp_dir, data_dir):
"""Downloads and extracts the dataset.
Args:
tmp_dir: temp directory to download and extract the dataset
data_dir: The base directory where data and vocab files are stored.
Returns:
tmp_dir: temp directory containing the raw data.
"""
if not tf.gfile.Ex... | [
"def",
"_prepare_babi_data",
"(",
"tmp_dir",
",",
"data_dir",
")",
":",
"if",
"not",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"data_dir",
")",
":",
"tf",
".",
"gfile",
".",
"MakeDirs",
"(",
"data_dir",
")",
"file_path",
"=",
"os",
".",
"path",
".",
"j... | Downloads and extracts the dataset.
Args:
tmp_dir: temp directory to download and extract the dataset
data_dir: The base directory where data and vocab files are stored.
Returns:
tmp_dir: temp directory containing the raw data. | [
"Downloads",
"and",
"extracts",
"the",
"dataset",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/babi_qa.py#L98-L123 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/babi_qa.py | _babi_parser | def _babi_parser(tmp_dir,
babi_task_id,
subset,
dataset_split,
joint_training=True):
"""Parsing the bAbi dataset (train and test).
Args:
tmp_dir: temp directory to download and extract the dataset
babi_task_id: babi task id
subset: bab... | python | def _babi_parser(tmp_dir,
babi_task_id,
subset,
dataset_split,
joint_training=True):
"""Parsing the bAbi dataset (train and test).
Args:
tmp_dir: temp directory to download and extract the dataset
babi_task_id: babi task id
subset: bab... | [
"def",
"_babi_parser",
"(",
"tmp_dir",
",",
"babi_task_id",
",",
"subset",
",",
"dataset_split",
",",
"joint_training",
"=",
"True",
")",
":",
"def",
"_data_file",
"(",
"mode",
",",
"task_id",
")",
":",
"\"\"\"Generates the path to the data file for the given mode(tra... | Parsing the bAbi dataset (train and test).
Args:
tmp_dir: temp directory to download and extract the dataset
babi_task_id: babi task id
subset: babi subset
dataset_split: dataset split (train or eval)
joint_training: if training the model on all tasks.
Returns:
babi_instances: set of trai... | [
"Parsing",
"the",
"bAbi",
"dataset",
"(",
"train",
"and",
"test",
")",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/babi_qa.py#L152-L253 | train |
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 | train |
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 | train |
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 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/babi_qa.py | BabiQa.feature_encoders | def feature_encoders(self, data_dir):
"""Return a dict for encoding and decoding inference input/output.
Args:
data_dir: data directory
Returns:
A dict of <feature name, TextEncoder>.
"""
encoders = (super(BabiQa, self).feature_encoders(data_dir))
label_encoder = self.get_labels_e... | python | def feature_encoders(self, data_dir):
"""Return a dict for encoding and decoding inference input/output.
Args:
data_dir: data directory
Returns:
A dict of <feature name, TextEncoder>.
"""
encoders = (super(BabiQa, self).feature_encoders(data_dir))
label_encoder = self.get_labels_e... | [
"def",
"feature_encoders",
"(",
"self",
",",
"data_dir",
")",
":",
"encoders",
"=",
"(",
"super",
"(",
"BabiQa",
",",
"self",
")",
".",
"feature_encoders",
"(",
"data_dir",
")",
")",
"label_encoder",
"=",
"self",
".",
"get_labels_encoder",
"(",
"data_dir",
... | Return a dict for encoding and decoding inference input/output.
Args:
data_dir: data directory
Returns:
A dict of <feature name, TextEncoder>. | [
"Return",
"a",
"dict",
"for",
"encoding",
"and",
"decoding",
"inference",
"input",
"/",
"output",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/babi_qa.py#L388-L401 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/babi_qa.py | BabiQa.hparams | def hparams(self, defaults, unused_model_hparams):
"""Returns problem_hparams.
Args:
defaults: default hyperparameters
unused_model_hparams: model hyperparameters
"""
(super(BabiQa, self).hparams(defaults, unused_model_hparams))
p = defaults
num_classes = self._encoders["targets"].... | python | def hparams(self, defaults, unused_model_hparams):
"""Returns problem_hparams.
Args:
defaults: default hyperparameters
unused_model_hparams: model hyperparameters
"""
(super(BabiQa, self).hparams(defaults, unused_model_hparams))
p = defaults
num_classes = self._encoders["targets"].... | [
"def",
"hparams",
"(",
"self",
",",
"defaults",
",",
"unused_model_hparams",
")",
":",
"(",
"super",
"(",
"BabiQa",
",",
"self",
")",
".",
"hparams",
"(",
"defaults",
",",
"unused_model_hparams",
")",
")",
"p",
"=",
"defaults",
"num_classes",
"=",
"self",
... | Returns problem_hparams.
Args:
defaults: default hyperparameters
unused_model_hparams: model hyperparameters | [
"Returns",
"problem_hparams",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/babi_qa.py#L417-L429 | train |
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 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/librispeech.py | _collect_data | def _collect_data(directory, input_ext, transcription_ext):
"""Traverses directory collecting input and target files."""
# Directory from string to tuple pair of strings
# key: the filepath to a datafile including the datafile's basename. Example,
# if the datafile was "/path/to/datafile.wav" then the key wou... | python | def _collect_data(directory, input_ext, transcription_ext):
"""Traverses directory collecting input and target files."""
# Directory from string to tuple pair of strings
# key: the filepath to a datafile including the datafile's basename. Example,
# if the datafile was "/path/to/datafile.wav" then the key wou... | [
"def",
"_collect_data",
"(",
"directory",
",",
"input_ext",
",",
"transcription_ext",
")",
":",
"# Directory from string to tuple pair of strings",
"# key: the filepath to a datafile including the datafile's basename. Example,",
"# if the datafile was \"/path/to/datafile.wav\" then the key... | Traverses directory collecting input and target files. | [
"Traverses",
"directory",
"collecting",
"input",
"and",
"target",
"files",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/librispeech.py#L63-L85 | train |
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 | train |
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 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wsj_parsing.py | token_generator | def token_generator(tree_path, source_token_vocab, target_token_vocab,
eos=None):
"""Generator for parsing as a sequence-to-sequence task that uses tokens.
This generator assumes the files at source_path and target_path have
the same number of lines and yields dictionaries of "inputs" and "ta... | python | def token_generator(tree_path, source_token_vocab, target_token_vocab,
eos=None):
"""Generator for parsing as a sequence-to-sequence task that uses tokens.
This generator assumes the files at source_path and target_path have
the same number of lines and yields dictionaries of "inputs" and "ta... | [
"def",
"token_generator",
"(",
"tree_path",
",",
"source_token_vocab",
",",
"target_token_vocab",
",",
"eos",
"=",
"None",
")",
":",
"eos_list",
"=",
"[",
"]",
"if",
"eos",
"is",
"None",
"else",
"[",
"eos",
"]",
"with",
"tf",
".",
"gfile",
".",
"GFile",
... | Generator for parsing as a sequence-to-sequence task that uses tokens.
This generator assumes the files at source_path and target_path have
the same number of lines and yields dictionaries of "inputs" and "targets"
where inputs and targets are token ids from source and target lines
converted to integers using ... | [
"Generator",
"for",
"parsing",
"as",
"a",
"sequence",
"-",
"to",
"-",
"sequence",
"task",
"that",
"uses",
"tokens",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wsj_parsing.py#L106-L133 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wsj_parsing.py | parsing_token_generator | def parsing_token_generator(data_dir, tmp_dir, train, source_vocab_size,
target_vocab_size):
"""Generator for parsing as a sequence-to-sequence task that uses tokens.
This generator assumes the files parsing_{train,dev}.trees, which contain
trees in WSJ format.
Args:
data_dir: ... | python | def parsing_token_generator(data_dir, tmp_dir, train, source_vocab_size,
target_vocab_size):
"""Generator for parsing as a sequence-to-sequence task that uses tokens.
This generator assumes the files parsing_{train,dev}.trees, which contain
trees in WSJ format.
Args:
data_dir: ... | [
"def",
"parsing_token_generator",
"(",
"data_dir",
",",
"tmp_dir",
",",
"train",
",",
"source_vocab_size",
",",
"target_vocab_size",
")",
":",
"# TODO(lukaszkaiser): Correct these calls to generate vocabularies. No data",
"# sources are being passed.",
"del",
"(",
"data_dir",
"... | Generator for parsing as a sequence-to-sequence task that uses tokens.
This generator assumes the files parsing_{train,dev}.trees, which contain
trees in WSJ format.
Args:
data_dir: path to the data directory.
tmp_dir: path to temporary storage directory.
train: whether we're training or not.
so... | [
"Generator",
"for",
"parsing",
"as",
"a",
"sequence",
"-",
"to",
"-",
"sequence",
"task",
"that",
"uses",
"tokens",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wsj_parsing.py#L136-L156 | train |
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 | train |
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 | train |
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 | train |
tensorflow/tensor2tensor | tensor2tensor/models/distillation.py | distill_resnet_32_to_15_cifar20x5 | def distill_resnet_32_to_15_cifar20x5():
"""Set of hyperparameters."""
hparams = distill_base()
hparams.teacher_model = "resnet"
hparams.teacher_hparams = "resnet_cifar_32"
hparams.student_model = "resnet"
hparams.student_hparams = "resnet_cifar_15"
hparams.optimizer_momentum_nesterov = True
# (base_lr... | python | def distill_resnet_32_to_15_cifar20x5():
"""Set of hyperparameters."""
hparams = distill_base()
hparams.teacher_model = "resnet"
hparams.teacher_hparams = "resnet_cifar_32"
hparams.student_model = "resnet"
hparams.student_hparams = "resnet_cifar_15"
hparams.optimizer_momentum_nesterov = True
# (base_lr... | [
"def",
"distill_resnet_32_to_15_cifar20x5",
"(",
")",
":",
"hparams",
"=",
"distill_base",
"(",
")",
"hparams",
".",
"teacher_model",
"=",
"\"resnet\"",
"hparams",
".",
"teacher_hparams",
"=",
"\"resnet_cifar_32\"",
"hparams",
".",
"student_model",
"=",
"\"resnet\"",
... | Set of hyperparameters. | [
"Set",
"of",
"hyperparameters",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/distillation.py#L175-L196 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/trainer_lib.py | next_checkpoint | def next_checkpoint(model_dir, timeout_mins=240):
"""Yields successive checkpoints from model_dir.
Args:
model_dir: The directory in which checkpoints are saved.
timeout_mins: The maximum amount of time in minutes to wait
between checkpoints. Set this to -1 to wait indefinitely.
Yields:... | python | def next_checkpoint(model_dir, timeout_mins=240):
"""Yields successive checkpoints from model_dir.
Args:
model_dir: The directory in which checkpoints are saved.
timeout_mins: The maximum amount of time in minutes to wait
between checkpoints. Set this to -1 to wait indefinitely.
Yields:... | [
"def",
"next_checkpoint",
"(",
"model_dir",
",",
"timeout_mins",
"=",
"240",
")",
":",
"last_ckpt",
"=",
"None",
"timeout_secs",
"=",
"None",
"if",
"timeout_mins",
"!=",
"-",
"1",
":",
"timeout_secs",
"=",
"timeout_mins",
"*",
"60",
"while",
"True",
":",
"... | Yields successive checkpoints from model_dir.
Args:
model_dir: The directory in which checkpoints are saved.
timeout_mins: The maximum amount of time in minutes to wait
between checkpoints. Set this to -1 to wait indefinitely.
Yields:
last_ckpt: a new checkpoint path, or None if the t... | [
"Yields",
"successive",
"checkpoints",
"from",
"model_dir",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L46-L69 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/trainer_lib.py | next_undecoded_checkpoint | def next_undecoded_checkpoint(model_dir, timeout_mins=240):
"""Yields successive checkpoints from model_dir."""
last_ckpt = None
last_step = 0
while True:
# Get the latest checkpoint.
last_ckpt = tf.contrib.training.wait_for_new_checkpoint(
model_dir, last_ckpt, seconds_to_sleep=60, timeout=60 *... | python | def next_undecoded_checkpoint(model_dir, timeout_mins=240):
"""Yields successive checkpoints from model_dir."""
last_ckpt = None
last_step = 0
while True:
# Get the latest checkpoint.
last_ckpt = tf.contrib.training.wait_for_new_checkpoint(
model_dir, last_ckpt, seconds_to_sleep=60, timeout=60 *... | [
"def",
"next_undecoded_checkpoint",
"(",
"model_dir",
",",
"timeout_mins",
"=",
"240",
")",
":",
"last_ckpt",
"=",
"None",
"last_step",
"=",
"0",
"while",
"True",
":",
"# Get the latest checkpoint.",
"last_ckpt",
"=",
"tf",
".",
"contrib",
".",
"training",
".",
... | Yields successive checkpoints from model_dir. | [
"Yields",
"successive",
"checkpoints",
"from",
"model_dir",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L72-L102 | train |
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 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/trainer_lib.py | create_run_config | def create_run_config(model_name,
master="",
model_dir=None,
iterations_per_loop=1000,
num_shards=8,
log_device_placement=False,
save_checkpoints_steps=1000,
save_che... | python | def create_run_config(model_name,
master="",
model_dir=None,
iterations_per_loop=1000,
num_shards=8,
log_device_placement=False,
save_checkpoints_steps=1000,
save_che... | [
"def",
"create_run_config",
"(",
"model_name",
",",
"master",
"=",
"\"\"",
",",
"model_dir",
"=",
"None",
",",
"iterations_per_loop",
"=",
"1000",
",",
"num_shards",
"=",
"8",
",",
"log_device_placement",
"=",
"False",
",",
"save_checkpoints_steps",
"=",
"1000",... | Create RunConfig, TPUConfig, and Parallelism object. | [
"Create",
"RunConfig",
"TPUConfig",
"and",
"Parallelism",
"object",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L145-L278 | train |
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 | train |
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 | train |
tensorflow/tensor2tensor | tensor2tensor/utils/trainer_lib.py | create_experiment | def create_experiment(
run_config,
hparams,
model_name,
problem_name,
data_dir,
train_steps,
eval_steps,
min_eval_frequency=2000,
eval_throttle_seconds=600,
schedule="train_and_evaluate",
export=False,
decode_hparams=None,
use_tfdbg=False,
use_dbgprofile=False,
... | python | def create_experiment(
run_config,
hparams,
model_name,
problem_name,
data_dir,
train_steps,
eval_steps,
min_eval_frequency=2000,
eval_throttle_seconds=600,
schedule="train_and_evaluate",
export=False,
decode_hparams=None,
use_tfdbg=False,
use_dbgprofile=False,
... | [
"def",
"create_experiment",
"(",
"run_config",
",",
"hparams",
",",
"model_name",
",",
"problem_name",
",",
"data_dir",
",",
"train_steps",
",",
"eval_steps",
",",
"min_eval_frequency",
"=",
"2000",
",",
"eval_throttle_seconds",
"=",
"600",
",",
"schedule",
"=",
... | Create Experiment. | [
"Create",
"Experiment",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/trainer_lib.py#L613-L767 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.