id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
22,400 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | SubwordTextEncoder._load_from_file_object | def _load_from_file_object(self, f):
"""Load from a file object.
Args:
f: File object to load vocabulary from
"""
subtoken_strings = []
for line in f:
s = line.strip()
# Some vocab files wrap words in single quotes, but others don't
if ((s.startswith("'") and s.endswith("'")... | python | def _load_from_file_object(self, f):
"""Load from a file object.
Args:
f: File object to load vocabulary from
"""
subtoken_strings = []
for line in f:
s = line.strip()
# Some vocab files wrap words in single quotes, but others don't
if ((s.startswith("'") and s.endswith("'")... | [
"def",
"_load_from_file_object",
"(",
"self",
",",
"f",
")",
":",
"subtoken_strings",
"=",
"[",
"]",
"for",
"line",
"in",
"f",
":",
"s",
"=",
"line",
".",
"strip",
"(",
")",
"# Some vocab files wrap words in single quotes, but others don't",
"if",
"(",
"(",
"s... | Load from a file object.
Args:
f: File object to load vocabulary from | [
"Load",
"from",
"a",
"file",
"object",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L919-L934 |
22,401 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | SubwordTextEncoder._load_from_file | def _load_from_file(self, filename):
"""Load from a vocab file."""
if not tf.gfile.Exists(filename):
raise ValueError("File %s not found" % filename)
with tf.gfile.Open(filename) as f:
self._load_from_file_object(f) | python | def _load_from_file(self, filename):
"""Load from a vocab file."""
if not tf.gfile.Exists(filename):
raise ValueError("File %s not found" % filename)
with tf.gfile.Open(filename) as f:
self._load_from_file_object(f) | [
"def",
"_load_from_file",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"filename",
")",
":",
"raise",
"ValueError",
"(",
"\"File %s not found\"",
"%",
"filename",
")",
"with",
"tf",
".",
"gfile",
".",
"Open... | Load from a vocab file. | [
"Load",
"from",
"a",
"vocab",
"file",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L936-L941 |
22,402 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | ImageEncoder.encode | def encode(self, s):
"""Transform a string with a filename into a list of RGB integers.
Args:
s: path to the file with an image.
Returns:
ids: list of integers
"""
try:
import matplotlib.image as im # pylint: disable=g-import-not-at-top
except ImportError as e:
tf.logg... | python | def encode(self, s):
"""Transform a string with a filename into a list of RGB integers.
Args:
s: path to the file with an image.
Returns:
ids: list of integers
"""
try:
import matplotlib.image as im # pylint: disable=g-import-not-at-top
except ImportError as e:
tf.logg... | [
"def",
"encode",
"(",
"self",
",",
"s",
")",
":",
"try",
":",
"import",
"matplotlib",
".",
"image",
"as",
"im",
"# pylint: disable=g-import-not-at-top",
"except",
"ImportError",
"as",
"e",
":",
"tf",
".",
"logging",
".",
"warning",
"(",
"\"Reading an image req... | Transform a string with a filename into a list of RGB integers.
Args:
s: path to the file with an image.
Returns:
ids: list of integers | [
"Transform",
"a",
"string",
"with",
"a",
"filename",
"into",
"a",
"list",
"of",
"RGB",
"integers",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L965-L980 |
22,403 | tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | ImageEncoder.decode | def decode(self, ids, strip_extraneous=False):
"""Transform a sequence of int ids into an image file.
Args:
ids: list of integers to be converted.
strip_extraneous: unused
Returns:
Path to the temporary file where the image was saved.
Raises:
ValueError: if the ids are not of ... | python | def decode(self, ids, strip_extraneous=False):
"""Transform a sequence of int ids into an image file.
Args:
ids: list of integers to be converted.
strip_extraneous: unused
Returns:
Path to the temporary file where the image was saved.
Raises:
ValueError: if the ids are not of ... | [
"def",
"decode",
"(",
"self",
",",
"ids",
",",
"strip_extraneous",
"=",
"False",
")",
":",
"del",
"strip_extraneous",
"_",
",",
"tmp_file_path",
"=",
"tempfile",
".",
"mkstemp",
"(",
"\"_decode.png\"",
")",
"if",
"self",
".",
"_height",
"is",
"None",
"or",... | Transform a sequence of int ids into an image file.
Args:
ids: list of integers to be converted.
strip_extraneous: unused
Returns:
Path to the temporary file where the image was saved.
Raises:
ValueError: if the ids are not of the appropriate size. | [
"Transform",
"a",
"sequence",
"of",
"int",
"ids",
"into",
"an",
"image",
"file",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L982-L1018 |
22,404 | tensorflow/tensor2tensor | tensor2tensor/trax/jaxboard.py | _pack_images | def _pack_images(images, rows, cols):
"""Helper utility to make a tiled field of images from numpy arrays.
Args:
images: Image tensor in shape [N, W, H, C].
rows: Number of images per row in tiled image.
cols: Number of images per column in tiled image.
Returns:
A tiled image of shape [W * rows,... | python | def _pack_images(images, rows, cols):
"""Helper utility to make a tiled field of images from numpy arrays.
Args:
images: Image tensor in shape [N, W, H, C].
rows: Number of images per row in tiled image.
cols: Number of images per column in tiled image.
Returns:
A tiled image of shape [W * rows,... | [
"def",
"_pack_images",
"(",
"images",
",",
"rows",
",",
"cols",
")",
":",
"shape",
"=",
"onp",
".",
"shape",
"(",
"images",
")",
"width",
",",
"height",
",",
"depth",
"=",
"shape",
"[",
"-",
"3",
":",
"]",
"images",
"=",
"onp",
".",
"reshape",
"(... | Helper utility to make a tiled field of images from numpy arrays.
Args:
images: Image tensor in shape [N, W, H, C].
rows: Number of images per row in tiled image.
cols: Number of images per column in tiled image.
Returns:
A tiled image of shape [W * rows, H * cols, C].
Truncates incomplete row... | [
"Helper",
"utility",
"to",
"make",
"a",
"tiled",
"field",
"of",
"images",
"from",
"numpy",
"arrays",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/jaxboard.py#L49-L71 |
22,405 | tensorflow/tensor2tensor | tensor2tensor/trax/jaxboard.py | markdownify_operative_config_str | def markdownify_operative_config_str(string):
"""Convert an operative config string to markdown format."""
# TODO(b/37527917): Total hack below. Implement more principled formatting.
def process(line):
"""Convert a single line to markdown format."""
if not line.startswith('#'):
return ' ' + line... | python | def markdownify_operative_config_str(string):
"""Convert an operative config string to markdown format."""
# TODO(b/37527917): Total hack below. Implement more principled formatting.
def process(line):
"""Convert a single line to markdown format."""
if not line.startswith('#'):
return ' ' + line... | [
"def",
"markdownify_operative_config_str",
"(",
"string",
")",
":",
"# TODO(b/37527917): Total hack below. Implement more principled formatting.",
"def",
"process",
"(",
"line",
")",
":",
"\"\"\"Convert a single line to markdown format.\"\"\"",
"if",
"not",
"line",
".",
"startswi... | Convert an operative config string to markdown format. | [
"Convert",
"an",
"operative",
"config",
"string",
"to",
"markdown",
"format",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/jaxboard.py#L326-L350 |
22,406 | tensorflow/tensor2tensor | tensor2tensor/trax/jaxboard.py | SummaryWriter.close | def close(self):
"""Close SummaryWriter. Final!"""
if not self._closed:
self._event_writer.close()
self._closed = True
del self._event_writer | python | def close(self):
"""Close SummaryWriter. Final!"""
if not self._closed:
self._event_writer.close()
self._closed = True
del self._event_writer | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_closed",
":",
"self",
".",
"_event_writer",
".",
"close",
"(",
")",
"self",
".",
"_closed",
"=",
"True",
"del",
"self",
".",
"_event_writer"
] | Close SummaryWriter. Final! | [
"Close",
"SummaryWriter",
".",
"Final!"
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/jaxboard.py#L98-L103 |
22,407 | tensorflow/tensor2tensor | tensor2tensor/trax/jaxboard.py | SummaryWriter.scalar | def scalar(self, tag, value, step=None):
"""Saves scalar value.
Args:
tag: str: label for this data
value: int/float: number to log
step: int: training step
"""
value = float(onp.array(value))
if step is None:
step = self._step
else:
self._step = step
summary =... | python | def scalar(self, tag, value, step=None):
"""Saves scalar value.
Args:
tag: str: label for this data
value: int/float: number to log
step: int: training step
"""
value = float(onp.array(value))
if step is None:
step = self._step
else:
self._step = step
summary =... | [
"def",
"scalar",
"(",
"self",
",",
"tag",
",",
"value",
",",
"step",
"=",
"None",
")",
":",
"value",
"=",
"float",
"(",
"onp",
".",
"array",
"(",
"value",
")",
")",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"self",
".",
"_step",
"else",
":"... | Saves scalar value.
Args:
tag: str: label for this data
value: int/float: number to log
step: int: training step | [
"Saves",
"scalar",
"value",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/jaxboard.py#L111-L125 |
22,408 | tensorflow/tensor2tensor | tensor2tensor/trax/jaxboard.py | SummaryWriter.plot | def plot(self, tag, mpl_plt, step=None, close_plot=True):
"""Saves matplotlib plot output to summary image.
Args:
tag: str: label for this data
mpl_plt: matplotlib stateful pyplot object with prepared plotting state
step: int: training step
close_plot: bool: automatically closes plot
... | python | def plot(self, tag, mpl_plt, step=None, close_plot=True):
"""Saves matplotlib plot output to summary image.
Args:
tag: str: label for this data
mpl_plt: matplotlib stateful pyplot object with prepared plotting state
step: int: training step
close_plot: bool: automatically closes plot
... | [
"def",
"plot",
"(",
"self",
",",
"tag",
",",
"mpl_plt",
",",
"step",
"=",
"None",
",",
"close_plot",
"=",
"True",
")",
":",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"self",
".",
"_step",
"else",
":",
"self",
".",
"_step",
"=",
"step",
"fig",... | Saves matplotlib plot output to summary image.
Args:
tag: str: label for this data
mpl_plt: matplotlib stateful pyplot object with prepared plotting state
step: int: training step
close_plot: bool: automatically closes plot | [
"Saves",
"matplotlib",
"plot",
"output",
"to",
"summary",
"image",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/jaxboard.py#L185-L210 |
22,409 | tensorflow/tensor2tensor | tensor2tensor/trax/jaxboard.py | SummaryWriter.audio | def audio(self, tag, audiodata, step=None, sample_rate=44100):
"""Saves audio.
NB: single channel only right now.
Args:
tag: str: label for this data
audiodata: ndarray [Nsamples,]: data between (-1.0,1.0) to save as wave
step: int: training step
sample_rate: sample rate of passed ... | python | def audio(self, tag, audiodata, step=None, sample_rate=44100):
"""Saves audio.
NB: single channel only right now.
Args:
tag: str: label for this data
audiodata: ndarray [Nsamples,]: data between (-1.0,1.0) to save as wave
step: int: training step
sample_rate: sample rate of passed ... | [
"def",
"audio",
"(",
"self",
",",
"tag",
",",
"audiodata",
",",
"step",
"=",
"None",
",",
"sample_rate",
"=",
"44100",
")",
":",
"audiodata",
"=",
"onp",
".",
"array",
"(",
"audiodata",
")",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"self",
"."... | Saves audio.
NB: single channel only right now.
Args:
tag: str: label for this data
audiodata: ndarray [Nsamples,]: data between (-1.0,1.0) to save as wave
step: int: training step
sample_rate: sample rate of passed in audio buffer | [
"Saves",
"audio",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/jaxboard.py#L212-L249 |
22,410 | tensorflow/tensor2tensor | tensor2tensor/trax/jaxboard.py | SummaryWriter.histogram | def histogram(self, tag, values, bins, step=None):
"""Saves histogram of values.
Args:
tag: str: label for this data
values: ndarray: will be flattened by this routine
bins: number of bins in histogram, or array of bins for onp.histogram
step: int: training step
"""
if step is N... | python | def histogram(self, tag, values, bins, step=None):
"""Saves histogram of values.
Args:
tag: str: label for this data
values: ndarray: will be flattened by this routine
bins: number of bins in histogram, or array of bins for onp.histogram
step: int: training step
"""
if step is N... | [
"def",
"histogram",
"(",
"self",
",",
"tag",
",",
"values",
",",
"bins",
",",
"step",
"=",
"None",
")",
":",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"self",
".",
"_step",
"else",
":",
"self",
".",
"_step",
"=",
"step",
"values",
"=",
"onp",... | Saves histogram of values.
Args:
tag: str: label for this data
values: ndarray: will be flattened by this routine
bins: number of bins in histogram, or array of bins for onp.histogram
step: int: training step | [
"Saves",
"histogram",
"of",
"values",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/jaxboard.py#L251-L287 |
22,411 | tensorflow/tensor2tensor | tensor2tensor/trax/jaxboard.py | SummaryWriter.text | def text(self, tag, textdata, step=None):
"""Saves a text summary.
Args:
tag: str: label for this data
textdata: string, or 1D/2D list/numpy array of strings
step: int: training step
Note: markdown formatting is rendered by tensorboard.
"""
if step is None:
step = self._step... | python | def text(self, tag, textdata, step=None):
"""Saves a text summary.
Args:
tag: str: label for this data
textdata: string, or 1D/2D list/numpy array of strings
step: int: training step
Note: markdown formatting is rendered by tensorboard.
"""
if step is None:
step = self._step... | [
"def",
"text",
"(",
"self",
",",
"tag",
",",
"textdata",
",",
"step",
"=",
"None",
")",
":",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"self",
".",
"_step",
"else",
":",
"self",
".",
"_step",
"=",
"step",
"smd",
"=",
"SummaryMetadata",
"(",
"... | Saves a text summary.
Args:
tag: str: label for this data
textdata: string, or 1D/2D list/numpy array of strings
step: int: training step
Note: markdown formatting is rendered by tensorboard. | [
"Saves",
"a",
"text",
"summary",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/jaxboard.py#L289-L322 |
22,412 | tensorflow/tensor2tensor | tensor2tensor/utils/usr_dir.py | import_usr_dir | def import_usr_dir(usr_dir):
"""Import module at usr_dir, if provided."""
if not usr_dir:
return
if usr_dir == INTERNAL_USR_DIR_PACKAGE:
# The package has been installed with pip under this name for Cloud ML
# Engine so just import it.
importlib.import_module(INTERNAL_USR_DIR_PACKAGE)
return
... | python | def import_usr_dir(usr_dir):
"""Import module at usr_dir, if provided."""
if not usr_dir:
return
if usr_dir == INTERNAL_USR_DIR_PACKAGE:
# The package has been installed with pip under this name for Cloud ML
# Engine so just import it.
importlib.import_module(INTERNAL_USR_DIR_PACKAGE)
return
... | [
"def",
"import_usr_dir",
"(",
"usr_dir",
")",
":",
"if",
"not",
"usr_dir",
":",
"return",
"if",
"usr_dir",
"==",
"INTERNAL_USR_DIR_PACKAGE",
":",
"# The package has been installed with pip under this name for Cloud ML",
"# Engine so just import it.",
"importlib",
".",
"import... | Import module at usr_dir, if provided. | [
"Import",
"module",
"at",
"usr_dir",
"if",
"provided",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/usr_dir.py#L30-L46 |
22,413 | tensorflow/tensor2tensor | tensor2tensor/layers/common_hparams.py | basic_params1 | def basic_params1():
"""A set of basic hyperparameters."""
return hparam.HParams(
# If the problem consists of variable-length sequences
# (see problem.batch_size_means_tokens()), then this is the number
# of tokens per batch per GPU or per TPU core. Otherwise, this is
# the number of examp... | python | def basic_params1():
"""A set of basic hyperparameters."""
return hparam.HParams(
# If the problem consists of variable-length sequences
# (see problem.batch_size_means_tokens()), then this is the number
# of tokens per batch per GPU or per TPU core. Otherwise, this is
# the number of examp... | [
"def",
"basic_params1",
"(",
")",
":",
"return",
"hparam",
".",
"HParams",
"(",
"# If the problem consists of variable-length sequences",
"# (see problem.batch_size_means_tokens()), then this is the number",
"# of tokens per batch per GPU or per TPU core. Otherwise, this is",
"# the numbe... | A set of basic hyperparameters. | [
"A",
"set",
"of",
"basic",
"hyperparameters",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_hparams.py#L29-L351 |
22,414 | tensorflow/tensor2tensor | tensor2tensor/layers/common_hparams.py | basic_range1 | def basic_range1(ranged_hparams):
"""A basic range of hyperparameters."""
rhp = ranged_hparams
rhp.set_discrete("batch_size", [1024, 2048, 4096])
rhp.set_discrete("num_hidden_layers", [1, 2, 3, 4, 5, 6])
rhp.set_discrete("hidden_size", [32, 64, 128, 256, 512], scale=rhp.LOG_SCALE)
rhp.set_discrete("kernel_h... | python | def basic_range1(ranged_hparams):
"""A basic range of hyperparameters."""
rhp = ranged_hparams
rhp.set_discrete("batch_size", [1024, 2048, 4096])
rhp.set_discrete("num_hidden_layers", [1, 2, 3, 4, 5, 6])
rhp.set_discrete("hidden_size", [32, 64, 128, 256, 512], scale=rhp.LOG_SCALE)
rhp.set_discrete("kernel_h... | [
"def",
"basic_range1",
"(",
"ranged_hparams",
")",
":",
"rhp",
"=",
"ranged_hparams",
"rhp",
".",
"set_discrete",
"(",
"\"batch_size\"",
",",
"[",
"1024",
",",
"2048",
",",
"4096",
"]",
")",
"rhp",
".",
"set_discrete",
"(",
"\"num_hidden_layers\"",
",",
"[",... | A basic range of hyperparameters. | [
"A",
"basic",
"range",
"of",
"hyperparameters",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_hparams.py#L473-L497 |
22,415 | tensorflow/tensor2tensor | tensor2tensor/layers/common_hparams.py | RangedHParams._check_reset_and_type_change | def _check_reset_and_type_change(self, name, orig_ctr):
"""Check if name is in orig_ctr or in one of the other type containers."""
# Resetting a hyperparameter
if name in orig_ctr:
tf.logging.warning("Overwriting hparam %s", name)
ctr_names = [
(self._categorical_params, "categorical"),
... | python | def _check_reset_and_type_change(self, name, orig_ctr):
"""Check if name is in orig_ctr or in one of the other type containers."""
# Resetting a hyperparameter
if name in orig_ctr:
tf.logging.warning("Overwriting hparam %s", name)
ctr_names = [
(self._categorical_params, "categorical"),
... | [
"def",
"_check_reset_and_type_change",
"(",
"self",
",",
"name",
",",
"orig_ctr",
")",
":",
"# Resetting a hyperparameter",
"if",
"name",
"in",
"orig_ctr",
":",
"tf",
".",
"logging",
".",
"warning",
"(",
"\"Overwriting hparam %s\"",
",",
"name",
")",
"ctr_names",
... | Check if name is in orig_ctr or in one of the other type containers. | [
"Check",
"if",
"name",
"is",
"in",
"orig_ctr",
"or",
"in",
"one",
"of",
"the",
"other",
"type",
"containers",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_hparams.py#L374-L397 |
22,416 | tensorflow/tensor2tensor | tensor2tensor/layers/common_hparams.py | RangedHParams.to_parameter_specs | def to_parameter_specs(self, name_prefix=""):
"""To list of dicts suitable for Cloud ML Engine hyperparameter tuning."""
specs = []
for name, categories, _ in self._categorical_params.values():
spec = {
"parameterName": name_prefix + name,
"type": "CATEGORICAL",
"categori... | python | def to_parameter_specs(self, name_prefix=""):
"""To list of dicts suitable for Cloud ML Engine hyperparameter tuning."""
specs = []
for name, categories, _ in self._categorical_params.values():
spec = {
"parameterName": name_prefix + name,
"type": "CATEGORICAL",
"categori... | [
"def",
"to_parameter_specs",
"(",
"self",
",",
"name_prefix",
"=",
"\"\"",
")",
":",
"specs",
"=",
"[",
"]",
"for",
"name",
",",
"categories",
",",
"_",
"in",
"self",
".",
"_categorical_params",
".",
"values",
"(",
")",
":",
"spec",
"=",
"{",
"\"parame... | To list of dicts suitable for Cloud ML Engine hyperparameter tuning. | [
"To",
"list",
"of",
"dicts",
"suitable",
"for",
"Cloud",
"ML",
"Engine",
"hyperparameter",
"tuning",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_hparams.py#L426-L469 |
22,417 | tensorflow/tensor2tensor | tensor2tensor/data_generators/gym_env.py | register_game | def register_game(game_name, game_mode="NoFrameskip-v4"):
"""Create and register problems for the game.
Args:
game_name: str, one of the games in ATARI_GAMES, e.g. "bank_heist".
game_mode: the frame skip and sticky keys config.
Raises:
ValueError: if game_name or game_mode are wrong.
"""
if game... | python | def register_game(game_name, game_mode="NoFrameskip-v4"):
"""Create and register problems for the game.
Args:
game_name: str, one of the games in ATARI_GAMES, e.g. "bank_heist".
game_mode: the frame skip and sticky keys config.
Raises:
ValueError: if game_name or game_mode are wrong.
"""
if game... | [
"def",
"register_game",
"(",
"game_name",
",",
"game_mode",
"=",
"\"NoFrameskip-v4\"",
")",
":",
"if",
"game_name",
"not",
"in",
"ATARI_GAMES",
":",
"raise",
"ValueError",
"(",
"\"Game %s not in ATARI_GAMES\"",
"%",
"game_name",
")",
"if",
"game_mode",
"not",
"in"... | Create and register problems for the game.
Args:
game_name: str, one of the games in ATARI_GAMES, e.g. "bank_heist".
game_mode: the frame skip and sticky keys config.
Raises:
ValueError: if game_name or game_mode are wrong. | [
"Create",
"and",
"register",
"problems",
"for",
"the",
"game",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/gym_env.py#L884-L902 |
22,418 | tensorflow/tensor2tensor | tensor2tensor/data_generators/gym_env.py | T2TEnv._decode_png | def _decode_png(self, encoded_observation):
"""Decodes a single observation from PNG."""
return self._session.obj.run(
self._decoded_image_t.obj,
feed_dict={self._encoded_image_p.obj: encoded_observation}
) | python | def _decode_png(self, encoded_observation):
"""Decodes a single observation from PNG."""
return self._session.obj.run(
self._decoded_image_t.obj,
feed_dict={self._encoded_image_p.obj: encoded_observation}
) | [
"def",
"_decode_png",
"(",
"self",
",",
"encoded_observation",
")",
":",
"return",
"self",
".",
"_session",
".",
"obj",
".",
"run",
"(",
"self",
".",
"_decoded_image_t",
".",
"obj",
",",
"feed_dict",
"=",
"{",
"self",
".",
"_encoded_image_p",
".",
"obj",
... | Decodes a single observation from PNG. | [
"Decodes",
"a",
"single",
"observation",
"from",
"PNG",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/gym_env.py#L227-L232 |
22,419 | tensorflow/tensor2tensor | tensor2tensor/data_generators/gym_env.py | T2TEnv._encode_observations | def _encode_observations(self, observations):
"""Encodes observations as PNG."""
return [
Observation(
self._session.obj.run(
self._encoded_image_t.obj,
feed_dict={self._decoded_image_p.obj: observation}
),
self._decode_png
)
... | python | def _encode_observations(self, observations):
"""Encodes observations as PNG."""
return [
Observation(
self._session.obj.run(
self._encoded_image_t.obj,
feed_dict={self._decoded_image_p.obj: observation}
),
self._decode_png
)
... | [
"def",
"_encode_observations",
"(",
"self",
",",
"observations",
")",
":",
"return",
"[",
"Observation",
"(",
"self",
".",
"_session",
".",
"obj",
".",
"run",
"(",
"self",
".",
"_encoded_image_t",
".",
"obj",
",",
"feed_dict",
"=",
"{",
"self",
".",
"_de... | Encodes observations as PNG. | [
"Encodes",
"observations",
"as",
"PNG",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/gym_env.py#L234-L245 |
22,420 | tensorflow/tensor2tensor | tensor2tensor/data_generators/gym_env.py | T2TEnv.step | def step(self, actions):
"""Makes a step in all environments.
Does any preprocessing and records frames.
Args:
actions: Batch of actions.
Returns:
(obs, rewards, dones) - batches of observations, rewards and done flags
respectively.
Raises:
ValueError: when the data for c... | python | def step(self, actions):
"""Makes a step in all environments.
Does any preprocessing and records frames.
Args:
actions: Batch of actions.
Returns:
(obs, rewards, dones) - batches of observations, rewards and done flags
respectively.
Raises:
ValueError: when the data for c... | [
"def",
"step",
"(",
"self",
",",
"actions",
")",
":",
"if",
"self",
".",
"_store_rollouts",
"and",
"self",
".",
"_rollouts_by_epoch_and_split",
"[",
"self",
".",
"current_epoch",
"]",
":",
"raise",
"ValueError",
"(",
"\"Data for current epoch has already been loaded... | Makes a step in all environments.
Does any preprocessing and records frames.
Args:
actions: Batch of actions.
Returns:
(obs, rewards, dones) - batches of observations, rewards and done flags
respectively.
Raises:
ValueError: when the data for current epoch has already been lo... | [
"Makes",
"a",
"step",
"in",
"all",
"environments",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/gym_env.py#L264-L301 |
22,421 | tensorflow/tensor2tensor | tensor2tensor/data_generators/gym_env.py | T2TEnv.extra_reading_spec | def extra_reading_spec(self):
"""Additional data fields to store on disk and their decoders."""
field_names = ("frame_number", "action", "reward", "done")
data_fields = {
name: tf.FixedLenFeature([1], tf.int64) for name in field_names
}
decoders = {
name: tf.contrib.slim.tfexample_de... | python | def extra_reading_spec(self):
"""Additional data fields to store on disk and their decoders."""
field_names = ("frame_number", "action", "reward", "done")
data_fields = {
name: tf.FixedLenFeature([1], tf.int64) for name in field_names
}
decoders = {
name: tf.contrib.slim.tfexample_de... | [
"def",
"extra_reading_spec",
"(",
"self",
")",
":",
"field_names",
"=",
"(",
"\"frame_number\"",
",",
"\"action\"",
",",
"\"reward\"",
",",
"\"done\"",
")",
"data_fields",
"=",
"{",
"name",
":",
"tf",
".",
"FixedLenFeature",
"(",
"[",
"1",
"]",
",",
"tf",
... | Additional data fields to store on disk and their decoders. | [
"Additional",
"data",
"fields",
"to",
"store",
"on",
"disk",
"and",
"their",
"decoders",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/gym_env.py#L373-L383 |
22,422 | tensorflow/tensor2tensor | tensor2tensor/data_generators/gym_env.py | T2TEnv._split_current_epoch | def _split_current_epoch(self):
"""Splits frames in the current epoch according to self.dataset_splits.
Rollouts can be broken on shard boundary. This is desirable when we have
few long rollouts and we want to make sure we have data in the dev set.
"""
num_frames = self._calc_num_frames(self._curre... | python | def _split_current_epoch(self):
"""Splits frames in the current epoch according to self.dataset_splits.
Rollouts can be broken on shard boundary. This is desirable when we have
few long rollouts and we want to make sure we have data in the dev set.
"""
num_frames = self._calc_num_frames(self._curre... | [
"def",
"_split_current_epoch",
"(",
"self",
")",
":",
"num_frames",
"=",
"self",
".",
"_calc_num_frames",
"(",
"self",
".",
"_current_epoch_rollouts",
")",
"num_shards",
"=",
"sum",
"(",
"split",
"[",
"\"shards\"",
"]",
"for",
"split",
"in",
"self",
".",
"da... | Splits frames in the current epoch according to self.dataset_splits.
Rollouts can be broken on shard boundary. This is desirable when we have
few long rollouts and we want to make sure we have data in the dev set. | [
"Splits",
"frames",
"in",
"the",
"current",
"epoch",
"according",
"to",
"self",
".",
"dataset_splits",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/gym_env.py#L417-L462 |
22,423 | tensorflow/tensor2tensor | tensor2tensor/data_generators/image_utils.py | image_to_tf_summary_value | def image_to_tf_summary_value(image, tag):
"""Converts a NumPy image to a tf.Summary.Value object.
Args:
image: 3-D NumPy array.
tag: name for tf.Summary.Value for display in tensorboard.
Returns:
image_summary: A tf.Summary.Value object.
"""
curr_image = np.asarray(image, dtype=np.uint8)
heigh... | python | def image_to_tf_summary_value(image, tag):
"""Converts a NumPy image to a tf.Summary.Value object.
Args:
image: 3-D NumPy array.
tag: name for tf.Summary.Value for display in tensorboard.
Returns:
image_summary: A tf.Summary.Value object.
"""
curr_image = np.asarray(image, dtype=np.uint8)
heigh... | [
"def",
"image_to_tf_summary_value",
"(",
"image",
",",
"tag",
")",
":",
"curr_image",
"=",
"np",
".",
"asarray",
"(",
"image",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"height",
",",
"width",
",",
"n_channels",
"=",
"curr_image",
".",
"shape",
"# If m... | Converts a NumPy image to a tf.Summary.Value object.
Args:
image: 3-D NumPy array.
tag: name for tf.Summary.Value for display in tensorboard.
Returns:
image_summary: A tf.Summary.Value object. | [
"Converts",
"a",
"NumPy",
"image",
"to",
"a",
"tf",
".",
"Summary",
".",
"Value",
"object",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_utils.py#L43-L62 |
22,424 | tensorflow/tensor2tensor | tensor2tensor/data_generators/image_utils.py | convert_predictions_to_image_summaries | def convert_predictions_to_image_summaries(hook_args):
"""Optionally converts images from hooks_args to image summaries.
Args:
hook_args: DecodeHookArgs namedtuple
Returns:
summaries: list of tf.Summary values if hook_args.decode_hpara
"""
decode_hparams = hook_args.decode_hparams
if not decode_hpa... | python | def convert_predictions_to_image_summaries(hook_args):
"""Optionally converts images from hooks_args to image summaries.
Args:
hook_args: DecodeHookArgs namedtuple
Returns:
summaries: list of tf.Summary values if hook_args.decode_hpara
"""
decode_hparams = hook_args.decode_hparams
if not decode_hpa... | [
"def",
"convert_predictions_to_image_summaries",
"(",
"hook_args",
")",
":",
"decode_hparams",
"=",
"hook_args",
".",
"decode_hparams",
"if",
"not",
"decode_hparams",
".",
"display_decoded_images",
":",
"return",
"[",
"]",
"predictions",
"=",
"hook_args",
".",
"predic... | Optionally converts images from hooks_args to image summaries.
Args:
hook_args: DecodeHookArgs namedtuple
Returns:
summaries: list of tf.Summary values if hook_args.decode_hpara | [
"Optionally",
"converts",
"images",
"from",
"hooks_args",
"to",
"image",
"summaries",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_utils.py#L65-L88 |
22,425 | tensorflow/tensor2tensor | tensor2tensor/data_generators/image_utils.py | resize_by_area | def resize_by_area(img, size):
"""image resize function used by quite a few image problems."""
return tf.to_int64(
tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA)) | python | def resize_by_area(img, size):
"""image resize function used by quite a few image problems."""
return tf.to_int64(
tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA)) | [
"def",
"resize_by_area",
"(",
"img",
",",
"size",
")",
":",
"return",
"tf",
".",
"to_int64",
"(",
"tf",
".",
"image",
".",
"resize_images",
"(",
"img",
",",
"[",
"size",
",",
"size",
"]",
",",
"tf",
".",
"image",
".",
"ResizeMethod",
".",
"AREA",
"... | image resize function used by quite a few image problems. | [
"image",
"resize",
"function",
"used",
"by",
"quite",
"a",
"few",
"image",
"problems",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_utils.py#L91-L94 |
22,426 | tensorflow/tensor2tensor | tensor2tensor/data_generators/image_utils.py | encode_images_as_png | def encode_images_as_png(images):
"""Yield images encoded as pngs."""
if tf.executing_eagerly():
for image in images:
yield tf.image.encode_png(image).numpy()
else:
(height, width, channels) = images[0].shape
with tf.Graph().as_default():
image_t = tf.placeholder(dtype=tf.uint8, shape=(hei... | python | def encode_images_as_png(images):
"""Yield images encoded as pngs."""
if tf.executing_eagerly():
for image in images:
yield tf.image.encode_png(image).numpy()
else:
(height, width, channels) = images[0].shape
with tf.Graph().as_default():
image_t = tf.placeholder(dtype=tf.uint8, shape=(hei... | [
"def",
"encode_images_as_png",
"(",
"images",
")",
":",
"if",
"tf",
".",
"executing_eagerly",
"(",
")",
":",
"for",
"image",
"in",
"images",
":",
"yield",
"tf",
".",
"image",
".",
"encode_png",
"(",
"image",
")",
".",
"numpy",
"(",
")",
"else",
":",
... | Yield images encoded as pngs. | [
"Yield",
"images",
"encoded",
"as",
"pngs",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_utils.py#L266-L279 |
22,427 | tensorflow/tensor2tensor | tensor2tensor/data_generators/image_utils.py | image_generator | def image_generator(images, labels):
"""Generator for images that takes image and labels lists and creates pngs.
Args:
images: list of images given as [width x height x channels] numpy arrays.
labels: list of ints, same length as images.
Yields:
A dictionary representing the images with the followin... | python | def image_generator(images, labels):
"""Generator for images that takes image and labels lists and creates pngs.
Args:
images: list of images given as [width x height x channels] numpy arrays.
labels: list of ints, same length as images.
Yields:
A dictionary representing the images with the followin... | [
"def",
"image_generator",
"(",
"images",
",",
"labels",
")",
":",
"if",
"not",
"images",
":",
"raise",
"ValueError",
"(",
"\"Must provide some images for the generator.\"",
")",
"width",
",",
"height",
",",
"_",
"=",
"images",
"[",
"0",
"]",
".",
"shape",
"f... | Generator for images that takes image and labels lists and creates pngs.
Args:
images: list of images given as [width x height x channels] numpy arrays.
labels: list of ints, same length as images.
Yields:
A dictionary representing the images with the following fields:
* image/encoded: the string ... | [
"Generator",
"for",
"images",
"that",
"takes",
"image",
"and",
"labels",
"lists",
"and",
"creates",
"pngs",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_utils.py#L282-L311 |
22,428 | tensorflow/tensor2tensor | tensor2tensor/data_generators/image_utils.py | random_shift | def random_shift(image, wsr=0.1, hsr=0.1):
"""Apply random horizontal and vertical shift to images.
This is the default data-augmentation strategy used on CIFAR in Glow.
Args:
image: a 3-D Tensor
wsr: Width shift range, as a float fraction of the width.
hsr: Height shift range, as a float fraction o... | python | def random_shift(image, wsr=0.1, hsr=0.1):
"""Apply random horizontal and vertical shift to images.
This is the default data-augmentation strategy used on CIFAR in Glow.
Args:
image: a 3-D Tensor
wsr: Width shift range, as a float fraction of the width.
hsr: Height shift range, as a float fraction o... | [
"def",
"random_shift",
"(",
"image",
",",
"wsr",
"=",
"0.1",
",",
"hsr",
"=",
"0.1",
")",
":",
"height",
",",
"width",
",",
"_",
"=",
"common_layers",
".",
"shape_list",
"(",
"image",
")",
"width_range",
",",
"height_range",
"=",
"wsr",
"*",
"width",
... | Apply random horizontal and vertical shift to images.
This is the default data-augmentation strategy used on CIFAR in Glow.
Args:
image: a 3-D Tensor
wsr: Width shift range, as a float fraction of the width.
hsr: Height shift range, as a float fraction of the width.
Returns:
images: images trans... | [
"Apply",
"random",
"horizontal",
"and",
"vertical",
"shift",
"to",
"images",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/image_utils.py#L408-L425 |
22,429 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | add_standard_attention_hparams | def add_standard_attention_hparams(hparams):
"""Adds the hparams used by get_standardized_layers."""
# All hyperparameters ending in "dropout" are automatically set to 0.0
# when not in training mode.
# hparams used and which should have been defined outside (in
# common_hparams):
# Global flags
# hparam... | python | def add_standard_attention_hparams(hparams):
"""Adds the hparams used by get_standardized_layers."""
# All hyperparameters ending in "dropout" are automatically set to 0.0
# when not in training mode.
# hparams used and which should have been defined outside (in
# common_hparams):
# Global flags
# hparam... | [
"def",
"add_standard_attention_hparams",
"(",
"hparams",
")",
":",
"# All hyperparameters ending in \"dropout\" are automatically set to 0.0",
"# when not in training mode.",
"# hparams used and which should have been defined outside (in",
"# common_hparams):",
"# Global flags",
"# hparams.mod... | Adds the hparams used by get_standardized_layers. | [
"Adds",
"the",
"hparams",
"used",
"by",
"get_standardized_layers",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L302-L344 |
22,430 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | encoder_decoder_attention_loss | def encoder_decoder_attention_loss(expected_attention_logits,
actual_attentions,
loss_type="kl_divergence",
loss_multiplier=1.0):
"""Computes encdec attention loss between expected and actual attentions.
Args:
... | python | def encoder_decoder_attention_loss(expected_attention_logits,
actual_attentions,
loss_type="kl_divergence",
loss_multiplier=1.0):
"""Computes encdec attention loss between expected and actual attentions.
Args:
... | [
"def",
"encoder_decoder_attention_loss",
"(",
"expected_attention_logits",
",",
"actual_attentions",
",",
"loss_type",
"=",
"\"kl_divergence\"",
",",
"loss_multiplier",
"=",
"1.0",
")",
":",
"def",
"combine_attentions",
"(",
"attention_list",
")",
":",
"\"\"\"Combine diff... | Computes encdec attention loss between expected and actual attentions.
Args:
expected_attention_logits: Tensor storing the expected encoder-decoder
attention logits with shape [batch_size, target_length, input_length].
actual_attentions: Dictionary with actual attention logits for different
atten... | [
"Computes",
"encdec",
"attention",
"loss",
"between",
"expected",
"and",
"actual",
"attentions",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L347-L402 |
22,431 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | get_timing_signal_1d | def get_timing_signal_1d(length,
channels,
min_timescale=1.0,
max_timescale=1.0e4,
start_index=0):
"""Gets a bunch of sinusoids of different frequencies.
Each channel of the input Tensor is incremented by a sinusoid... | python | def get_timing_signal_1d(length,
channels,
min_timescale=1.0,
max_timescale=1.0e4,
start_index=0):
"""Gets a bunch of sinusoids of different frequencies.
Each channel of the input Tensor is incremented by a sinusoid... | [
"def",
"get_timing_signal_1d",
"(",
"length",
",",
"channels",
",",
"min_timescale",
"=",
"1.0",
",",
"max_timescale",
"=",
"1.0e4",
",",
"start_index",
"=",
"0",
")",
":",
"position",
"=",
"tf",
".",
"to_float",
"(",
"tf",
".",
"range",
"(",
"length",
"... | Gets a bunch of sinusoids of different frequencies.
Each channel of the input Tensor is incremented by a sinusoid of a different
frequency and phase.
This allows attention to learn to use absolute and relative positions.
Timing signals should be added to some precursors of both the query and the
memory inpu... | [
"Gets",
"a",
"bunch",
"of",
"sinusoids",
"of",
"different",
"frequencies",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L406-L452 |
22,432 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | add_timing_signal_1d_given_position | def add_timing_signal_1d_given_position(x,
position,
min_timescale=1.0,
max_timescale=1.0e4):
"""Adds sinusoids of diff frequencies to a Tensor, with timing position given.
Args:
x: a Tensor ... | python | def add_timing_signal_1d_given_position(x,
position,
min_timescale=1.0,
max_timescale=1.0e4):
"""Adds sinusoids of diff frequencies to a Tensor, with timing position given.
Args:
x: a Tensor ... | [
"def",
"add_timing_signal_1d_given_position",
"(",
"x",
",",
"position",
",",
"min_timescale",
"=",
"1.0",
",",
"max_timescale",
"=",
"1.0e4",
")",
":",
"channels",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"[",
"2",
"]",
"num_timescales",
"=",
... | Adds sinusoids of diff frequencies to a Tensor, with timing position given.
Args:
x: a Tensor with shape [batch, length, channels]
position: a Tensor with shape [batch, length]
min_timescale: a float
max_timescale: a float
Returns:
a Tensor the same shape as x. | [
"Adds",
"sinusoids",
"of",
"diff",
"frequencies",
"to",
"a",
"Tensor",
"with",
"timing",
"position",
"given",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L578-L606 |
22,433 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | add_positional_embedding | def add_positional_embedding(x, max_length, name=None, positions=None):
"""Adds positional embedding.
Args:
x: Tensor with shape [batch, length, depth].
max_length: int representing static maximum size of any dimension.
name: str representing name of the embedding tf.Variable.
positions: Tensor wit... | python | def add_positional_embedding(x, max_length, name=None, positions=None):
"""Adds positional embedding.
Args:
x: Tensor with shape [batch, length, depth].
max_length: int representing static maximum size of any dimension.
name: str representing name of the embedding tf.Variable.
positions: Tensor wit... | [
"def",
"add_positional_embedding",
"(",
"x",
",",
"max_length",
",",
"name",
"=",
"None",
",",
"positions",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"add_positional_embedding\"",
")",
":",
"_",
",",
"length",
",",
"depth",
"=",
"commo... | Adds positional embedding.
Args:
x: Tensor with shape [batch, length, depth].
max_length: int representing static maximum size of any dimension.
name: str representing name of the embedding tf.Variable.
positions: Tensor with shape [batch, length].
Returns:
Tensor of same shape as x. | [
"Adds",
"positional",
"embedding",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L666-L689 |
22,434 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | add_positional_embedding_nd | def add_positional_embedding_nd(x, max_length, name=None):
"""Adds n-dimensional positional embedding.
The embeddings add to all positional dimensions of the tensor.
Args:
x: Tensor with shape [batch, p1 ... pn, depth]. It has n positional
dimensions, i.e., 1 for text, 2 for images, 3 for video, etc.
... | python | def add_positional_embedding_nd(x, max_length, name=None):
"""Adds n-dimensional positional embedding.
The embeddings add to all positional dimensions of the tensor.
Args:
x: Tensor with shape [batch, p1 ... pn, depth]. It has n positional
dimensions, i.e., 1 for text, 2 for images, 3 for video, etc.
... | [
"def",
"add_positional_embedding_nd",
"(",
"x",
",",
"max_length",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"add_positional_embedding_nd\"",
")",
":",
"x_shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"num_di... | Adds n-dimensional positional embedding.
The embeddings add to all positional dimensions of the tensor.
Args:
x: Tensor with shape [batch, p1 ... pn, depth]. It has n positional
dimensions, i.e., 1 for text, 2 for images, 3 for video, etc.
max_length: int representing static maximum size of any dime... | [
"Adds",
"n",
"-",
"dimensional",
"positional",
"embedding",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L692-L725 |
22,435 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | make_edge_vectors | def make_edge_vectors(adjacency_matrix, num_edge_types, depth, name=None):
"""Gets edge vectors for the edge types in the adjacency matrix.
Args:
adjacency_matrix: A [batch, num_nodes, num_nodes] tensor of ints.
num_edge_types: Number of different edge types
depth: Number of channels
name: a string... | python | def make_edge_vectors(adjacency_matrix, num_edge_types, depth, name=None):
"""Gets edge vectors for the edge types in the adjacency matrix.
Args:
adjacency_matrix: A [batch, num_nodes, num_nodes] tensor of ints.
num_edge_types: Number of different edge types
depth: Number of channels
name: a string... | [
"def",
"make_edge_vectors",
"(",
"adjacency_matrix",
",",
"num_edge_types",
",",
"depth",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"edge_vectors\"",
")",
":",
"att_adj_vectors_shape",
"=",
... | Gets edge vectors for the edge types in the adjacency matrix.
Args:
adjacency_matrix: A [batch, num_nodes, num_nodes] tensor of ints.
num_edge_types: Number of different edge types
depth: Number of channels
name: a string
Returns:
A [batch, num_nodes, num_nodes, depth] vector of tensors | [
"Gets",
"edge",
"vectors",
"for",
"the",
"edge",
"types",
"in",
"the",
"adjacency",
"matrix",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L728-L759 |
22,436 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | padding_to_length | def padding_to_length(padding):
"""Calculate the length of mask based on padding.
Args:
padding: a Tensor with shape [..., length].
Returns:
a Tensor with shape [...].
"""
non_padding = 1.0 - padding
return tf.to_int32(tf.reduce_sum(non_padding, axis=-1)) | python | def padding_to_length(padding):
"""Calculate the length of mask based on padding.
Args:
padding: a Tensor with shape [..., length].
Returns:
a Tensor with shape [...].
"""
non_padding = 1.0 - padding
return tf.to_int32(tf.reduce_sum(non_padding, axis=-1)) | [
"def",
"padding_to_length",
"(",
"padding",
")",
":",
"non_padding",
"=",
"1.0",
"-",
"padding",
"return",
"tf",
".",
"to_int32",
"(",
"tf",
".",
"reduce_sum",
"(",
"non_padding",
",",
"axis",
"=",
"-",
"1",
")",
")"
] | Calculate the length of mask based on padding.
Args:
padding: a Tensor with shape [..., length].
Returns:
a Tensor with shape [...]. | [
"Calculate",
"the",
"length",
"of",
"mask",
"based",
"on",
"padding",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L860-L869 |
22,437 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | attention_bias_prepend_inputs_full_attention | def attention_bias_prepend_inputs_full_attention(padding):
"""Create a bias tensor for prepend_mode="prepend_inputs_full_attention".
See prepend_inputs in common_hparams.py.
Produces a bias tensor to be used in self-attention.
This bias tensor allows for full connectivity in the "inputs" part of
the sequen... | python | def attention_bias_prepend_inputs_full_attention(padding):
"""Create a bias tensor for prepend_mode="prepend_inputs_full_attention".
See prepend_inputs in common_hparams.py.
Produces a bias tensor to be used in self-attention.
This bias tensor allows for full connectivity in the "inputs" part of
the sequen... | [
"def",
"attention_bias_prepend_inputs_full_attention",
"(",
"padding",
")",
":",
"# Everything past the first padding position is part of the target.",
"# This Tensor has zeros for the source portion and separator,",
"# and ones for the target portion.",
"in_target",
"=",
"tf",
".",
"cumsu... | Create a bias tensor for prepend_mode="prepend_inputs_full_attention".
See prepend_inputs in common_hparams.py.
Produces a bias tensor to be used in self-attention.
This bias tensor allows for full connectivity in the "inputs" part of
the sequence and masked connectivity in the targets part.
Args:
pad... | [
"Create",
"a",
"bias",
"tensor",
"for",
"prepend_mode",
"=",
"prepend_inputs_full_attention",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L969-L999 |
22,438 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | attention_bias_proximal | def attention_bias_proximal(length):
"""Bias for self-attention to encourage attention to close positions.
Args:
length: an integer scalar.
Returns:
a Tensor with shape [1, 1, length, length]
"""
r = tf.to_float(tf.range(length))
diff = tf.expand_dims(r, 0) - tf.expand_dims(r, 1)
return tf.expan... | python | def attention_bias_proximal(length):
"""Bias for self-attention to encourage attention to close positions.
Args:
length: an integer scalar.
Returns:
a Tensor with shape [1, 1, length, length]
"""
r = tf.to_float(tf.range(length))
diff = tf.expand_dims(r, 0) - tf.expand_dims(r, 1)
return tf.expan... | [
"def",
"attention_bias_proximal",
"(",
"length",
")",
":",
"r",
"=",
"tf",
".",
"to_float",
"(",
"tf",
".",
"range",
"(",
"length",
")",
")",
"diff",
"=",
"tf",
".",
"expand_dims",
"(",
"r",
",",
"0",
")",
"-",
"tf",
".",
"expand_dims",
"(",
"r",
... | Bias for self-attention to encourage attention to close positions.
Args:
length: an integer scalar.
Returns:
a Tensor with shape [1, 1, length, length] | [
"Bias",
"for",
"self",
"-",
"attention",
"to",
"encourage",
"attention",
"to",
"close",
"positions",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1003-L1014 |
22,439 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | attention_bias_batch | def attention_bias_batch(batch_coordinates_q,
batch_coordinates_k=None,
condition_fn=None):
"""Generate a mask to prevent the batch to attend to each others.
Args:
batch_coordinates_q: Int-like Tensor of shape [length_q, 1] containing the
coordinates of t... | python | def attention_bias_batch(batch_coordinates_q,
batch_coordinates_k=None,
condition_fn=None):
"""Generate a mask to prevent the batch to attend to each others.
Args:
batch_coordinates_q: Int-like Tensor of shape [length_q, 1] containing the
coordinates of t... | [
"def",
"attention_bias_batch",
"(",
"batch_coordinates_q",
",",
"batch_coordinates_k",
"=",
"None",
",",
"condition_fn",
"=",
"None",
")",
":",
"if",
"batch_coordinates_k",
"is",
"None",
":",
"batch_coordinates_k",
"=",
"batch_coordinates_q",
"# Convert to float first bec... | Generate a mask to prevent the batch to attend to each others.
Args:
batch_coordinates_q: Int-like Tensor of shape [length_q, 1] containing the
coordinates of the batches
batch_coordinates_k: Int-like Tensor of shape [length_k, 1] containing the
coordinates of the batches. If None, do self-attent... | [
"Generate",
"a",
"mask",
"to",
"prevent",
"the",
"batch",
"to",
"attend",
"to",
"each",
"others",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1018-L1049 |
22,440 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | split_last_dimension | def split_last_dimension(x, n):
"""Reshape x so that the last dimension becomes two dimensions.
The first of these two dimensions is n.
Args:
x: a Tensor with shape [..., m]
n: an integer.
Returns:
a Tensor with shape [..., n, m/n]
"""
x_shape = common_layers.shape_list(x)
m = x_shape[-1]
... | python | def split_last_dimension(x, n):
"""Reshape x so that the last dimension becomes two dimensions.
The first of these two dimensions is n.
Args:
x: a Tensor with shape [..., m]
n: an integer.
Returns:
a Tensor with shape [..., n, m/n]
"""
x_shape = common_layers.shape_list(x)
m = x_shape[-1]
... | [
"def",
"split_last_dimension",
"(",
"x",
",",
"n",
")",
":",
"x_shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"m",
"=",
"x_shape",
"[",
"-",
"1",
"]",
"if",
"isinstance",
"(",
"m",
",",
"int",
")",
"and",
"isinstance",
"(",
"n",
"... | Reshape x so that the last dimension becomes two dimensions.
The first of these two dimensions is n.
Args:
x: a Tensor with shape [..., m]
n: an integer.
Returns:
a Tensor with shape [..., n, m/n] | [
"Reshape",
"x",
"so",
"that",
"the",
"last",
"dimension",
"becomes",
"two",
"dimensions",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1069-L1085 |
22,441 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | combine_last_two_dimensions | def combine_last_two_dimensions(x):
"""Reshape x so that the last two dimension become one.
Args:
x: a Tensor with shape [..., a, b]
Returns:
a Tensor with shape [..., ab]
"""
x_shape = common_layers.shape_list(x)
a, b = x_shape[-2:]
return tf.reshape(x, x_shape[:-2] + [a * b]) | python | def combine_last_two_dimensions(x):
"""Reshape x so that the last two dimension become one.
Args:
x: a Tensor with shape [..., a, b]
Returns:
a Tensor with shape [..., ab]
"""
x_shape = common_layers.shape_list(x)
a, b = x_shape[-2:]
return tf.reshape(x, x_shape[:-2] + [a * b]) | [
"def",
"combine_last_two_dimensions",
"(",
"x",
")",
":",
"x_shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"a",
",",
"b",
"=",
"x_shape",
"[",
"-",
"2",
":",
"]",
"return",
"tf",
".",
"reshape",
"(",
"x",
",",
"x_shape",
"[",
":",
... | Reshape x so that the last two dimension become one.
Args:
x: a Tensor with shape [..., a, b]
Returns:
a Tensor with shape [..., ab] | [
"Reshape",
"x",
"so",
"that",
"the",
"last",
"two",
"dimension",
"become",
"one",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1089-L1100 |
22,442 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | combine_first_two_dimensions | def combine_first_two_dimensions(x):
"""Reshape x so that the first two dimension become one.
Args:
x: a Tensor with shape [a, b, ...]
Returns:
a Tensor with shape [ab, ...]
"""
ret = tf.reshape(x, tf.concat([[-1], common_layers.shape_list(x)[2:]], 0))
old_shape = x.get_shape().dims
a, b = old_s... | python | def combine_first_two_dimensions(x):
"""Reshape x so that the first two dimension become one.
Args:
x: a Tensor with shape [a, b, ...]
Returns:
a Tensor with shape [ab, ...]
"""
ret = tf.reshape(x, tf.concat([[-1], common_layers.shape_list(x)[2:]], 0))
old_shape = x.get_shape().dims
a, b = old_s... | [
"def",
"combine_first_two_dimensions",
"(",
"x",
")",
":",
"ret",
"=",
"tf",
".",
"reshape",
"(",
"x",
",",
"tf",
".",
"concat",
"(",
"[",
"[",
"-",
"1",
"]",
",",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"[",
"2",
":",
"]",
"]",
",",
... | Reshape x so that the first two dimension become one.
Args:
x: a Tensor with shape [a, b, ...]
Returns:
a Tensor with shape [ab, ...] | [
"Reshape",
"x",
"so",
"that",
"the",
"first",
"two",
"dimension",
"become",
"one",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1104-L1118 |
22,443 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | attention_image_summary | def attention_image_summary(attn, image_shapes=None):
"""Compute color image summary.
Args:
attn: a Tensor with shape [batch, num_heads, query_length, memory_length]
image_shapes: optional tuple of integer scalars.
If the query positions and memory positions represent the
pixels of flattened im... | python | def attention_image_summary(attn, image_shapes=None):
"""Compute color image summary.
Args:
attn: a Tensor with shape [batch, num_heads, query_length, memory_length]
image_shapes: optional tuple of integer scalars.
If the query positions and memory positions represent the
pixels of flattened im... | [
"def",
"attention_image_summary",
"(",
"attn",
",",
"image_shapes",
"=",
"None",
")",
":",
"attn",
"=",
"tf",
".",
"cast",
"(",
"attn",
",",
"tf",
".",
"float32",
")",
"num_heads",
"=",
"common_layers",
".",
"shape_list",
"(",
"attn",
")",
"[",
"1",
"]... | Compute color image summary.
Args:
attn: a Tensor with shape [batch, num_heads, query_length, memory_length]
image_shapes: optional tuple of integer scalars.
If the query positions and memory positions represent the
pixels of flattened images, then pass in their dimensions:
(query_rows, q... | [
"Compute",
"color",
"image",
"summary",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1176-L1217 |
22,444 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | harden_attention_weights | def harden_attention_weights(weights, hard_attention_k):
"""Make attention weights non-0 only on the top-hard_attention_k ones."""
# Subtract the top-kth weight and zero-out all lower ones.
# Note that currently in case of numerical ties it will retain more
# than k elements. In the future, we may want to avoid... | python | def harden_attention_weights(weights, hard_attention_k):
"""Make attention weights non-0 only on the top-hard_attention_k ones."""
# Subtract the top-kth weight and zero-out all lower ones.
# Note that currently in case of numerical ties it will retain more
# than k elements. In the future, we may want to avoid... | [
"def",
"harden_attention_weights",
"(",
"weights",
",",
"hard_attention_k",
")",
":",
"# Subtract the top-kth weight and zero-out all lower ones.",
"# Note that currently in case of numerical ties it will retain more",
"# than k elements. In the future, we may want to avoid this.",
"weights",
... | Make attention weights non-0 only on the top-hard_attention_k ones. | [
"Make",
"attention",
"weights",
"non",
"-",
"0",
"only",
"on",
"the",
"top",
"-",
"hard_attention_k",
"ones",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1475-L1486 |
22,445 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | _generate_relative_positions_matrix | def _generate_relative_positions_matrix(length_q, length_k,
max_relative_position,
cache=False):
"""Generates matrix of relative positions between inputs."""
if not cache:
if length_q == length_k:
range_vec_q = range_vec_k = t... | python | def _generate_relative_positions_matrix(length_q, length_k,
max_relative_position,
cache=False):
"""Generates matrix of relative positions between inputs."""
if not cache:
if length_q == length_k:
range_vec_q = range_vec_k = t... | [
"def",
"_generate_relative_positions_matrix",
"(",
"length_q",
",",
"length_k",
",",
"max_relative_position",
",",
"cache",
"=",
"False",
")",
":",
"if",
"not",
"cache",
":",
"if",
"length_q",
"==",
"length_k",
":",
"range_vec_q",
"=",
"range_vec_k",
"=",
"tf",
... | Generates matrix of relative positions between inputs. | [
"Generates",
"matrix",
"of",
"relative",
"positions",
"between",
"inputs",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1552-L1570 |
22,446 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | _relative_attention_inner | def _relative_attention_inner(x, y, z, transpose):
"""Relative position-aware dot-product attention inner calculation.
This batches matrix multiply calculations to avoid unnecessary broadcasting.
Args:
x: Tensor with shape [batch_size, heads, length or 1, length or depth].
y: Tensor with shape [batch_si... | python | def _relative_attention_inner(x, y, z, transpose):
"""Relative position-aware dot-product attention inner calculation.
This batches matrix multiply calculations to avoid unnecessary broadcasting.
Args:
x: Tensor with shape [batch_size, heads, length or 1, length or depth].
y: Tensor with shape [batch_si... | [
"def",
"_relative_attention_inner",
"(",
"x",
",",
"y",
",",
"z",
",",
"transpose",
")",
":",
"batch_size",
"=",
"tf",
".",
"shape",
"(",
"x",
")",
"[",
"0",
"]",
"heads",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"1",
... | Relative position-aware dot-product attention inner calculation.
This batches matrix multiply calculations to avoid unnecessary broadcasting.
Args:
x: Tensor with shape [batch_size, heads, length or 1, length or depth].
y: Tensor with shape [batch_size, heads, length or 1, depth].
z: Tensor with shape... | [
"Relative",
"position",
"-",
"aware",
"dot",
"-",
"product",
"attention",
"inner",
"calculation",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1587-L1618 |
22,447 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | _relative_position_to_absolute_position_masked | def _relative_position_to_absolute_position_masked(x):
"""Helper to dot_product_self_attention_relative_v2.
Rearrange an attention logits or weights Tensor.
The dimensions of the input represent:
[batch, heads, query_position, memory_position - query_position + length - 1]
The dimensions of the output repr... | python | def _relative_position_to_absolute_position_masked(x):
"""Helper to dot_product_self_attention_relative_v2.
Rearrange an attention logits or weights Tensor.
The dimensions of the input represent:
[batch, heads, query_position, memory_position - query_position + length - 1]
The dimensions of the output repr... | [
"def",
"_relative_position_to_absolute_position_masked",
"(",
"x",
")",
":",
"batch",
",",
"heads",
",",
"length",
",",
"_",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"x",
"=",
"tf",
".",
"pad",
"(",
"x",
",",
"[",
"[",
"0",
",",
"0",
"... | Helper to dot_product_self_attention_relative_v2.
Rearrange an attention logits or weights Tensor.
The dimensions of the input represent:
[batch, heads, query_position, memory_position - query_position + length - 1]
The dimensions of the output represent:
[batch, heads, query_position, memory_position]
... | [
"Helper",
"to",
"dot_product_self_attention_relative_v2",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1705-L1729 |
22,448 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | _absolute_position_to_relative_position_unmasked | def _absolute_position_to_relative_position_unmasked(x):
"""Helper function for dot_product_unmasked_self_attention_relative_v2.
Rearrange an attention logits or weights Tensor.
The dimensions of the input represent:
[batch, heads, query_position, memory_position]
The dimensions of the output represent:
... | python | def _absolute_position_to_relative_position_unmasked(x):
"""Helper function for dot_product_unmasked_self_attention_relative_v2.
Rearrange an attention logits or weights Tensor.
The dimensions of the input represent:
[batch, heads, query_position, memory_position]
The dimensions of the output represent:
... | [
"def",
"_absolute_position_to_relative_position_unmasked",
"(",
"x",
")",
":",
"batch",
",",
"heads",
",",
"length",
",",
"_",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"# padd along column",
"x",
"=",
"tf",
".",
"pad",
"(",
"x",
",",
"[",
"[... | Helper function for dot_product_unmasked_self_attention_relative_v2.
Rearrange an attention logits or weights Tensor.
The dimensions of the input represent:
[batch, heads, query_position, memory_position]
The dimensions of the output represent:
[batch, heads, query_position, memory_position - query_positio... | [
"Helper",
"function",
"for",
"dot_product_unmasked_self_attention_relative_v2",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1902-L1930 |
22,449 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | get_relative_embeddings_left_right | def get_relative_embeddings_left_right(max_relative_position, length, depth,
num_heads,
heads_share_relative_embedding,
name):
"""Instantiate or retrieve relative embeddings, sliced according to length... | python | def get_relative_embeddings_left_right(max_relative_position, length, depth,
num_heads,
heads_share_relative_embedding,
name):
"""Instantiate or retrieve relative embeddings, sliced according to length... | [
"def",
"get_relative_embeddings_left_right",
"(",
"max_relative_position",
",",
"length",
",",
"depth",
",",
"num_heads",
",",
"heads_share_relative_embedding",
",",
"name",
")",
":",
"initializer_stddev",
"=",
"depth",
"**",
"-",
"0.5",
"max_relative_position_unmasked",
... | Instantiate or retrieve relative embeddings, sliced according to length.
Use for unmasked case where the relative attention looks both left and right.
Args:
max_relative_position: an Integer for the number of entries in the relative
embedding, which corresponds to the max relative distance that is
... | [
"Instantiate",
"or",
"retrieve",
"relative",
"embeddings",
"sliced",
"according",
"to",
"length",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1933-L1982 |
22,450 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | _matmul_with_relative_keys_2d | def _matmul_with_relative_keys_2d(x, y, heads_share_relative_embedding):
"""Helper function for dot_product_unmasked_self_attention_relative_2d."""
if heads_share_relative_embedding:
ret = tf.einsum("bhxyd,md->bhxym", x, y)
else:
ret = tf.einsum("bhxyd,hmd->bhxym", x, y)
return ret | python | def _matmul_with_relative_keys_2d(x, y, heads_share_relative_embedding):
"""Helper function for dot_product_unmasked_self_attention_relative_2d."""
if heads_share_relative_embedding:
ret = tf.einsum("bhxyd,md->bhxym", x, y)
else:
ret = tf.einsum("bhxyd,hmd->bhxym", x, y)
return ret | [
"def",
"_matmul_with_relative_keys_2d",
"(",
"x",
",",
"y",
",",
"heads_share_relative_embedding",
")",
":",
"if",
"heads_share_relative_embedding",
":",
"ret",
"=",
"tf",
".",
"einsum",
"(",
"\"bhxyd,md->bhxym\"",
",",
"x",
",",
"y",
")",
"else",
":",
"ret",
... | Helper function for dot_product_unmasked_self_attention_relative_2d. | [
"Helper",
"function",
"for",
"dot_product_unmasked_self_attention_relative_2d",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2077-L2083 |
22,451 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | _get_left_right_blocks | def _get_left_right_blocks(x):
"""Helper function. Assumes that memory_flange is half of query sizes.
This function splits the tensor of width 'n' into two halves, where the
first half gets the width indices 0, 2, 4.. and the second half gets the
width indices 3, 5, ... We also fuse two blocks along the h dime... | python | def _get_left_right_blocks(x):
"""Helper function. Assumes that memory_flange is half of query sizes.
This function splits the tensor of width 'n' into two halves, where the
first half gets the width indices 0, 2, 4.. and the second half gets the
width indices 3, 5, ... We also fuse two blocks along the h dime... | [
"def",
"_get_left_right_blocks",
"(",
"x",
")",
":",
"(",
"_",
",",
"x_num_outer_h_blocks",
",",
"x_num_outer_w_blocks",
",",
"x_memory_flange_h",
",",
"x_memory_flange_w",
",",
"depth",
")",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"x_left_right_bl... | Helper function. Assumes that memory_flange is half of query sizes.
This function splits the tensor of width 'n' into two halves, where the
first half gets the width indices 0, 2, 4.. and the second half gets the
width indices 3, 5, ... We also fuse two blocks along the h dimension.
Args:
x: a 6-d tensor.... | [
"Helper",
"function",
".",
"Assumes",
"that",
"memory_flange",
"is",
"half",
"of",
"query",
"sizes",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2268-L2303 |
22,452 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | get_2d_local_memory | def get_2d_local_memory(x, query_shape, memory_flange):
"""Stitches together the local 2d memory blocks.
Args:
x: a [batch, height, width, depth tensor]
query_shape: 2-d integer list of query shape
memory_flange: 2-d integer list of memory flanges
Returns:
x: A [batch, num_h_blocks, num_w_blocks... | python | def get_2d_local_memory(x, query_shape, memory_flange):
"""Stitches together the local 2d memory blocks.
Args:
x: a [batch, height, width, depth tensor]
query_shape: 2-d integer list of query shape
memory_flange: 2-d integer list of memory flanges
Returns:
x: A [batch, num_h_blocks, num_w_blocks... | [
"def",
"get_2d_local_memory",
"(",
"x",
",",
"query_shape",
",",
"memory_flange",
")",
":",
"(",
"_",
",",
"height",
",",
"width",
",",
"depth_x",
")",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"x_center_blocks",
"=",
"_extract_blocks",
"(",
... | Stitches together the local 2d memory blocks.
Args:
x: a [batch, height, width, depth tensor]
query_shape: 2-d integer list of query shape
memory_flange: 2-d integer list of memory flanges
Returns:
x: A [batch, num_h_blocks, num_w_blocks,
query_shape[0]+2*memory_flange[0],query_shape[1]+... | [
"Stitches",
"together",
"the",
"local",
"2d",
"memory",
"blocks",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2326-L2404 |
22,453 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | get_2d_local_memory_v2 | def get_2d_local_memory_v2(x, query_shape, memory_flange):
"""Gathering memory blocks around query blocks. flange is half of query .
Only works if memory flanges are half of query sizes.
Args:
x: a [batch, height, width, depth tensor]
query_shape: 2-d integer list of query shape
memory_flange: 2-d... | python | def get_2d_local_memory_v2(x, query_shape, memory_flange):
"""Gathering memory blocks around query blocks. flange is half of query .
Only works if memory flanges are half of query sizes.
Args:
x: a [batch, height, width, depth tensor]
query_shape: 2-d integer list of query shape
memory_flange: 2-d... | [
"def",
"get_2d_local_memory_v2",
"(",
"x",
",",
"query_shape",
",",
"memory_flange",
")",
":",
"(",
"_",
",",
"height",
",",
"width",
",",
"depth_x",
")",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"# add extra padding to x so that we can extract the ... | Gathering memory blocks around query blocks. flange is half of query .
Only works if memory flanges are half of query sizes.
Args:
x: a [batch, height, width, depth tensor]
query_shape: 2-d integer list of query shape
memory_flange: 2-d integer list of memory flanges
Returns:
x: A [batch, num... | [
"Gathering",
"memory",
"blocks",
"around",
"query",
"blocks",
".",
"flange",
"is",
"half",
"of",
"query",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2407-L2445 |
22,454 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | dot_product_unmasked_attention_local_2d_tpu_simple | def dot_product_unmasked_attention_local_2d_tpu_simple(
x, bias, total_key_depth, total_value_depth, num_heads,
query_shape=(8, 8),
dropout_rate=0.0, image_shapes=None, make_image_summary=False,
dropout_broadcast_dims=None):
"""Calculate simple unmasked dot-product local self-attention 2d on tpu.
... | python | def dot_product_unmasked_attention_local_2d_tpu_simple(
x, bias, total_key_depth, total_value_depth, num_heads,
query_shape=(8, 8),
dropout_rate=0.0, image_shapes=None, make_image_summary=False,
dropout_broadcast_dims=None):
"""Calculate simple unmasked dot-product local self-attention 2d on tpu.
... | [
"def",
"dot_product_unmasked_attention_local_2d_tpu_simple",
"(",
"x",
",",
"bias",
",",
"total_key_depth",
",",
"total_value_depth",
",",
"num_heads",
",",
"query_shape",
"=",
"(",
"8",
",",
"8",
")",
",",
"dropout_rate",
"=",
"0.0",
",",
"image_shapes",
"=",
"... | Calculate simple unmasked dot-product local self-attention 2d on tpu.
The query, key, and value blocks are the same. We do not do a second linear
transformation after computing the values
Args:
x: a Tensor with shape [batch, height, width, depth].
bias: bias Tensor.
total_key_depth: the dimensions o... | [
"Calculate",
"simple",
"unmasked",
"dot",
"-",
"product",
"local",
"self",
"-",
"attention",
"2d",
"on",
"tpu",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2540-L2615 |
22,455 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | masked_within_block_local_attention_1d | def masked_within_block_local_attention_1d(q, k, v, block_length=64, name=None):
"""Attention to the source and a neighborhood to the left within a block.
The sequence is divided into blocks of length block_length. Attention for a
given query position can only see memory positions less than or equal to the
que... | python | def masked_within_block_local_attention_1d(q, k, v, block_length=64, name=None):
"""Attention to the source and a neighborhood to the left within a block.
The sequence is divided into blocks of length block_length. Attention for a
given query position can only see memory positions less than or equal to the
que... | [
"def",
"masked_within_block_local_attention_1d",
"(",
"q",
",",
"k",
",",
"v",
",",
"block_length",
"=",
"64",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"within_local_attention_1d\"",
",",... | Attention to the source and a neighborhood to the left within a block.
The sequence is divided into blocks of length block_length. Attention for a
given query position can only see memory positions less than or equal to the
query position in the corresponding block.
Args:
q: a Tensor with shape [batch, he... | [
"Attention",
"to",
"the",
"source",
"and",
"a",
"neighborhood",
"to",
"the",
"left",
"within",
"a",
"block",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2618-L2671 |
22,456 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | _relative_position_to_absolute_position_unmasked | def _relative_position_to_absolute_position_unmasked(x):
"""Converts tensor from relative to aboslute indexing for local attention.
Args:
x: a Tensor of shape [batch (or batch*num_blocks), heads,
length, 2 * length - 1]
Returns:
A Tensor of shape [batch (or batch*num_blocks), h... | python | def _relative_position_to_absolute_position_unmasked(x):
"""Converts tensor from relative to aboslute indexing for local attention.
Args:
x: a Tensor of shape [batch (or batch*num_blocks), heads,
length, 2 * length - 1]
Returns:
A Tensor of shape [batch (or batch*num_blocks), h... | [
"def",
"_relative_position_to_absolute_position_unmasked",
"(",
"x",
")",
":",
"x_shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"batch",
"=",
"x_shape",
"[",
"0",
"]",
"heads",
"=",
"x_shape",
"[",
"1",
"]",
"length",
"=",
"x_shape",
"[",
... | Converts tensor from relative to aboslute indexing for local attention.
Args:
x: a Tensor of shape [batch (or batch*num_blocks), heads,
length, 2 * length - 1]
Returns:
A Tensor of shape [batch (or batch*num_blocks), heads, length, length-1] | [
"Converts",
"tensor",
"from",
"relative",
"to",
"aboslute",
"indexing",
"for",
"local",
"attention",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2674-L2701 |
22,457 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | _make_local_block | def _make_local_block(x, depth, batch, heads, num_blocks, block_length):
"""Helper function to create a local version of the keys or values for 1d."""
prev_block = tf.slice(x, [0, 0, 0, 0, 0],
[-1, -1, num_blocks - 1, -1, -1])
cur_block = tf.slice(x, [0, 0, 1, 0, 0], [-1, -1, -1, -1, -1])
... | python | def _make_local_block(x, depth, batch, heads, num_blocks, block_length):
"""Helper function to create a local version of the keys or values for 1d."""
prev_block = tf.slice(x, [0, 0, 0, 0, 0],
[-1, -1, num_blocks - 1, -1, -1])
cur_block = tf.slice(x, [0, 0, 1, 0, 0], [-1, -1, -1, -1, -1])
... | [
"def",
"_make_local_block",
"(",
"x",
",",
"depth",
",",
"batch",
",",
"heads",
",",
"num_blocks",
",",
"block_length",
")",
":",
"prev_block",
"=",
"tf",
".",
"slice",
"(",
"x",
",",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
",",
... | Helper function to create a local version of the keys or values for 1d. | [
"Helper",
"function",
"to",
"create",
"a",
"local",
"version",
"of",
"the",
"keys",
"or",
"values",
"for",
"1d",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2815-L2822 |
22,458 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | reshape_by_blocks | def reshape_by_blocks(x, x_shape, memory_block_size):
"""Reshapes input by splitting its length over blocks of memory_block_size.
Args:
x: a Tensor with shape [batch, heads, length, depth]
x_shape: tf.TensorShape of x.
memory_block_size: Integer which divides length.
Returns:
Tensor with shape
... | python | def reshape_by_blocks(x, x_shape, memory_block_size):
"""Reshapes input by splitting its length over blocks of memory_block_size.
Args:
x: a Tensor with shape [batch, heads, length, depth]
x_shape: tf.TensorShape of x.
memory_block_size: Integer which divides length.
Returns:
Tensor with shape
... | [
"def",
"reshape_by_blocks",
"(",
"x",
",",
"x_shape",
",",
"memory_block_size",
")",
":",
"x",
"=",
"tf",
".",
"reshape",
"(",
"x",
",",
"[",
"x_shape",
"[",
"0",
"]",
",",
"x_shape",
"[",
"1",
"]",
",",
"x_shape",
"[",
"2",
"]",
"//",
"memory_bloc... | Reshapes input by splitting its length over blocks of memory_block_size.
Args:
x: a Tensor with shape [batch, heads, length, depth]
x_shape: tf.TensorShape of x.
memory_block_size: Integer which divides length.
Returns:
Tensor with shape
[batch, heads, length // memory_block_size, memory_block... | [
"Reshapes",
"input",
"by",
"splitting",
"its",
"length",
"over",
"blocks",
"of",
"memory_block_size",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3157-L3173 |
22,459 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | gather_dilated_memory_blocks | def gather_dilated_memory_blocks(x,
num_memory_blocks,
gap_size,
query_block_size,
memory_block_size,
gather_indices,
dire... | python | def gather_dilated_memory_blocks(x,
num_memory_blocks,
gap_size,
query_block_size,
memory_block_size,
gather_indices,
dire... | [
"def",
"gather_dilated_memory_blocks",
"(",
"x",
",",
"num_memory_blocks",
",",
"gap_size",
",",
"query_block_size",
",",
"memory_block_size",
",",
"gather_indices",
",",
"direction",
"=",
"\"left\"",
")",
":",
"gathered_blocks",
"=",
"[",
"]",
"# gathering memory blo... | Gathers blocks with gaps in between.
Args:
x: Tensor of shape [length, batch, heads, depth]
num_memory_blocks: how many memory blocks to look in "direction". Each will
be separated by gap_size.
gap_size: an integer indicating the gap size
query_block_size: an integer indicating size of query bl... | [
"Gathers",
"blocks",
"with",
"gaps",
"in",
"between",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3296-L3339 |
22,460 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | pad_to_multiple_2d | def pad_to_multiple_2d(x, block_shape):
"""Making sure x is a multiple of shape.
Args:
x: a [batch, heads, h, w, depth] or [batch, h, w, depth] tensor
block_shape: a 2-d list of integer shapes
Returns:
padded_x: a [batch, heads, h, w, depth] or [batch, h, w, depth] tensor
"""
old_shape = x.get_s... | python | def pad_to_multiple_2d(x, block_shape):
"""Making sure x is a multiple of shape.
Args:
x: a [batch, heads, h, w, depth] or [batch, h, w, depth] tensor
block_shape: a 2-d list of integer shapes
Returns:
padded_x: a [batch, heads, h, w, depth] or [batch, h, w, depth] tensor
"""
old_shape = x.get_s... | [
"def",
"pad_to_multiple_2d",
"(",
"x",
",",
"block_shape",
")",
":",
"old_shape",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"dims",
"last",
"=",
"old_shape",
"[",
"-",
"1",
"]",
"if",
"len",
"(",
"old_shape",
")",
"==",
"4",
":",
"height_padding",
"... | Making sure x is a multiple of shape.
Args:
x: a [batch, heads, h, w, depth] or [batch, h, w, depth] tensor
block_shape: a 2-d list of integer shapes
Returns:
padded_x: a [batch, heads, h, w, depth] or [batch, h, w, depth] tensor | [
"Making",
"sure",
"x",
"is",
"a",
"multiple",
"of",
"shape",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3526-L3551 |
22,461 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | reshape_range | def reshape_range(tensor, i, j, shape):
"""Reshapes a tensor between dimensions i and j."""
t_shape = common_layers.shape_list(tensor)
target_shape = t_shape[:i] + shape + t_shape[j:]
return tf.reshape(tensor, target_shape) | python | def reshape_range(tensor, i, j, shape):
"""Reshapes a tensor between dimensions i and j."""
t_shape = common_layers.shape_list(tensor)
target_shape = t_shape[:i] + shape + t_shape[j:]
return tf.reshape(tensor, target_shape) | [
"def",
"reshape_range",
"(",
"tensor",
",",
"i",
",",
"j",
",",
"shape",
")",
":",
"t_shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"tensor",
")",
"target_shape",
"=",
"t_shape",
"[",
":",
"i",
"]",
"+",
"shape",
"+",
"t_shape",
"[",
"j",
":"... | Reshapes a tensor between dimensions i and j. | [
"Reshapes",
"a",
"tensor",
"between",
"dimensions",
"i",
"and",
"j",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3554-L3558 |
22,462 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | gather_blocks_2d | def gather_blocks_2d(x, indices):
"""Gathers flattened blocks from x."""
x_shape = common_layers.shape_list(x)
x = reshape_range(x, 2, 4, [tf.reduce_prod(x_shape[2:4])])
# [length, batch, heads, dim]
x_t = tf.transpose(x, [2, 0, 1, 3])
x_new = tf.gather(x_t, indices)
# returns [batch, heads, num_blocks, b... | python | def gather_blocks_2d(x, indices):
"""Gathers flattened blocks from x."""
x_shape = common_layers.shape_list(x)
x = reshape_range(x, 2, 4, [tf.reduce_prod(x_shape[2:4])])
# [length, batch, heads, dim]
x_t = tf.transpose(x, [2, 0, 1, 3])
x_new = tf.gather(x_t, indices)
# returns [batch, heads, num_blocks, b... | [
"def",
"gather_blocks_2d",
"(",
"x",
",",
"indices",
")",
":",
"x_shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"x",
"=",
"reshape_range",
"(",
"x",
",",
"2",
",",
"4",
",",
"[",
"tf",
".",
"reduce_prod",
"(",
"x_shape",
"[",
"2",
... | Gathers flattened blocks from x. | [
"Gathers",
"flattened",
"blocks",
"from",
"x",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3561-L3569 |
22,463 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | scatter_blocks_2d | def scatter_blocks_2d(x, indices, shape):
"""scatters blocks from x into shape with indices."""
x_shape = common_layers.shape_list(x)
# [length, batch, heads, dim]
x_t = tf.transpose(
tf.reshape(x, [x_shape[0], x_shape[1], -1, x_shape[-1]]), [2, 0, 1, 3])
x_t_shape = common_layers.shape_list(x_t)
indi... | python | def scatter_blocks_2d(x, indices, shape):
"""scatters blocks from x into shape with indices."""
x_shape = common_layers.shape_list(x)
# [length, batch, heads, dim]
x_t = tf.transpose(
tf.reshape(x, [x_shape[0], x_shape[1], -1, x_shape[-1]]), [2, 0, 1, 3])
x_t_shape = common_layers.shape_list(x_t)
indi... | [
"def",
"scatter_blocks_2d",
"(",
"x",
",",
"indices",
",",
"shape",
")",
":",
"x_shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"# [length, batch, heads, dim]",
"x_t",
"=",
"tf",
".",
"transpose",
"(",
"tf",
".",
"reshape",
"(",
"x",
",",
... | scatters blocks from x into shape with indices. | [
"scatters",
"blocks",
"from",
"x",
"into",
"shape",
"with",
"indices",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3572-L3582 |
22,464 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | gather_indices_2d | def gather_indices_2d(x, block_shape, block_stride):
"""Getting gather indices."""
# making an identity matrix kernel
kernel = tf.eye(block_shape[0] * block_shape[1])
kernel = reshape_range(kernel, 0, 1, [block_shape[0], block_shape[1], 1])
# making indices [1, h, w, 1] to appy convs
x_shape = common_layers... | python | def gather_indices_2d(x, block_shape, block_stride):
"""Getting gather indices."""
# making an identity matrix kernel
kernel = tf.eye(block_shape[0] * block_shape[1])
kernel = reshape_range(kernel, 0, 1, [block_shape[0], block_shape[1], 1])
# making indices [1, h, w, 1] to appy convs
x_shape = common_layers... | [
"def",
"gather_indices_2d",
"(",
"x",
",",
"block_shape",
",",
"block_stride",
")",
":",
"# making an identity matrix kernel",
"kernel",
"=",
"tf",
".",
"eye",
"(",
"block_shape",
"[",
"0",
"]",
"*",
"block_shape",
"[",
"1",
"]",
")",
"kernel",
"=",
"reshape... | Getting gather indices. | [
"Getting",
"gather",
"indices",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3585-L3606 |
22,465 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | make_2d_block_raster_mask | def make_2d_block_raster_mask(query_shape, memory_flange):
"""Creates a mask for 2d block raster scan.
The query mask can look to the left, top left, top, and top right, but
not to the right. Inside the query, we have the standard raster scan
masking.
Args:
query_shape: A tuple of ints (query_height, que... | python | def make_2d_block_raster_mask(query_shape, memory_flange):
"""Creates a mask for 2d block raster scan.
The query mask can look to the left, top left, top, and top right, but
not to the right. Inside the query, we have the standard raster scan
masking.
Args:
query_shape: A tuple of ints (query_height, que... | [
"def",
"make_2d_block_raster_mask",
"(",
"query_shape",
",",
"memory_flange",
")",
":",
"# mask inside the query block",
"query_triangle",
"=",
"common_layers",
".",
"ones_matrix_band_part",
"(",
"np",
".",
"prod",
"(",
"query_shape",
")",
",",
"np",
".",
"prod",
"(... | Creates a mask for 2d block raster scan.
The query mask can look to the left, top left, top, and top right, but
not to the right. Inside the query, we have the standard raster scan
masking.
Args:
query_shape: A tuple of ints (query_height, query_width)
memory_flange: A tuple of ints
(memory_flang... | [
"Creates",
"a",
"mask",
"for",
"2d",
"block",
"raster",
"scan",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3609-L3646 |
22,466 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | get_memory_region | def get_memory_region(x, query_block_shape, memory_flange, q_indices):
"""Get the memory regions that surround a 2d query.
The memory regions will be the left and top right.
Args:
x: A tensor with shape [batch, heads, height, width, depth]
query_block_shape: a 2-d tuple of integers
memory_flange: ... | python | def get_memory_region(x, query_block_shape, memory_flange, q_indices):
"""Get the memory regions that surround a 2d query.
The memory regions will be the left and top right.
Args:
x: A tensor with shape [batch, heads, height, width, depth]
query_block_shape: a 2-d tuple of integers
memory_flange: ... | [
"def",
"get_memory_region",
"(",
"x",
",",
"query_block_shape",
",",
"memory_flange",
",",
"q_indices",
")",
":",
"# Padding x to be multiple of query_shape and then",
"# extracting the memory blocks from the same regions as the query blocks",
"x_query_padded",
"=",
"pad_to_multiple_... | Get the memory regions that surround a 2d query.
The memory regions will be the left and top right.
Args:
x: A tensor with shape [batch, heads, height, width, depth]
query_block_shape: a 2-d tuple of integers
memory_flange: a 2-d tuple of integers
q_indices: a tensor of indices for each of the c... | [
"Get",
"the",
"memory",
"regions",
"that",
"surround",
"a",
"2d",
"query",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3649-L3700 |
22,467 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | get_shifted_center_blocks | def get_shifted_center_blocks(x, indices):
"""Get right shifted blocks for masked local attention 2d.
Args:
x: A tensor with shape [batch, heads, height, width, depth]
indices: The indices to gather blocks
Returns:
x_shifted: a tensor of extracted blocks, each block right shifted along
length.... | python | def get_shifted_center_blocks(x, indices):
"""Get right shifted blocks for masked local attention 2d.
Args:
x: A tensor with shape [batch, heads, height, width, depth]
indices: The indices to gather blocks
Returns:
x_shifted: a tensor of extracted blocks, each block right shifted along
length.... | [
"def",
"get_shifted_center_blocks",
"(",
"x",
",",
"indices",
")",
":",
"center_x",
"=",
"gather_blocks_2d",
"(",
"x",
",",
"indices",
")",
"# Shift right along the length dimension",
"def",
"shift_right_2d_blocks",
"(",
"x",
")",
":",
"\"\"\"Shift the second to last di... | Get right shifted blocks for masked local attention 2d.
Args:
x: A tensor with shape [batch, heads, height, width, depth]
indices: The indices to gather blocks
Returns:
x_shifted: a tensor of extracted blocks, each block right shifted along
length. | [
"Get",
"right",
"shifted",
"blocks",
"for",
"masked",
"local",
"attention",
"2d",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3703-L3724 |
22,468 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | right_shift_blockwise | def right_shift_blockwise(x, query_shape, name=None):
"""Right shifts once in every block.
Args:
x: a tensor of shape [batch, height, width, depth]
query_shape: A 2d tuple of ints
name: a string
Returns:
output: a tensor of the same shape as x
"""
with tf.variable_scope(
name, default_... | python | def right_shift_blockwise(x, query_shape, name=None):
"""Right shifts once in every block.
Args:
x: a tensor of shape [batch, height, width, depth]
query_shape: A 2d tuple of ints
name: a string
Returns:
output: a tensor of the same shape as x
"""
with tf.variable_scope(
name, default_... | [
"def",
"right_shift_blockwise",
"(",
"x",
",",
"query_shape",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"right_shift_blockwise\"",
",",
"values",
"=",
"[",
"x",
"]",
")",
":",
"x_list_... | Right shifts once in every block.
Args:
x: a tensor of shape [batch, height, width, depth]
query_shape: A 2d tuple of ints
name: a string
Returns:
output: a tensor of the same shape as x | [
"Right",
"shifts",
"once",
"in",
"every",
"block",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3727-L3757 |
22,469 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | compute_qkv | def compute_qkv(query_antecedent,
memory_antecedent,
total_key_depth,
total_value_depth,
q_filter_width=1,
kv_filter_width=1,
q_padding="VALID",
kv_padding="VALID",
vars_3d_num_heads=0,
... | python | def compute_qkv(query_antecedent,
memory_antecedent,
total_key_depth,
total_value_depth,
q_filter_width=1,
kv_filter_width=1,
q_padding="VALID",
kv_padding="VALID",
vars_3d_num_heads=0,
... | [
"def",
"compute_qkv",
"(",
"query_antecedent",
",",
"memory_antecedent",
",",
"total_key_depth",
",",
"total_value_depth",
",",
"q_filter_width",
"=",
"1",
",",
"kv_filter_width",
"=",
"1",
",",
"q_padding",
"=",
"\"VALID\"",
",",
"kv_padding",
"=",
"\"VALID\"",
"... | Computes query, key and value.
Args:
query_antecedent: a Tensor with shape [batch, length_q, channels]
memory_antecedent: a Tensor with shape [batch, length_m, channels]
total_key_depth: an integer
total_value_depth: an integer
q_filter_width: An integer specifying how wide you want the query to ... | [
"Computes",
"query",
"key",
"and",
"value",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3906-L3961 |
22,470 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | ffn_self_attention_layer | def ffn_self_attention_layer(x,
filter_depth,
output_depth,
num_parts,
dropout_rate,
share_kv=False,
name=None):
"""Self-attention feedforward l... | python | def ffn_self_attention_layer(x,
filter_depth,
output_depth,
num_parts,
dropout_rate,
share_kv=False,
name=None):
"""Self-attention feedforward l... | [
"def",
"ffn_self_attention_layer",
"(",
"x",
",",
"filter_depth",
",",
"output_depth",
",",
"num_parts",
",",
"dropout_rate",
",",
"share_kv",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_n... | Self-attention feedforward layer.
We use self-attention to do feedforward computations. We apply this function
positionwise where for each position, we linearly transform the output to have
depth filter_depth, and break up the result depth-wise into num_parts
contiguous parts. The parts self-attend, we concate... | [
"Self",
"-",
"attention",
"feedforward",
"layer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L4368-L4430 |
22,471 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | parameter_attention | def parameter_attention(x,
total_key_depth,
total_value_depth,
output_depth,
memory_rows,
num_heads,
dropout_rate,
name=None):
"""Attention over param... | python | def parameter_attention(x,
total_key_depth,
total_value_depth,
output_depth,
memory_rows,
num_heads,
dropout_rate,
name=None):
"""Attention over param... | [
"def",
"parameter_attention",
"(",
"x",
",",
"total_key_depth",
",",
"total_value_depth",
",",
"output_depth",
",",
"memory_rows",
",",
"num_heads",
",",
"dropout_rate",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",... | Attention over parameters.
We use the same multi-headed attention as in the other layers, but the memory
keys and values are model parameters. There are no linear transformation on
the keys or values.
We are also a bit more careful about memory usage, since the number of
memory positions may be very large.
... | [
"Attention",
"over",
"parameters",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L4433-L4502 |
22,472 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | coordinate_tensor | def coordinate_tensor(shape, axis):
"""Return a tensor with given shape containing coordinate along given axis.
Args:
shape: a Tensor representing the shape of the output Tensor
axis: an integer
Returns:
A tensor with shape shape and type tf.int32, where each elements its
coordinate along the gi... | python | def coordinate_tensor(shape, axis):
"""Return a tensor with given shape containing coordinate along given axis.
Args:
shape: a Tensor representing the shape of the output Tensor
axis: an integer
Returns:
A tensor with shape shape and type tf.int32, where each elements its
coordinate along the gi... | [
"def",
"coordinate_tensor",
"(",
"shape",
",",
"axis",
")",
":",
"if",
"axis",
"<",
"0",
":",
"axis",
"=",
"tf",
".",
"size",
"(",
"shape",
")",
"+",
"axis",
"# Convert to positive for the one_hot indice",
"r",
"=",
"tf",
".",
"range",
"(",
"shape",
"[",... | Return a tensor with given shape containing coordinate along given axis.
Args:
shape: a Tensor representing the shape of the output Tensor
axis: an integer
Returns:
A tensor with shape shape and type tf.int32, where each elements its
coordinate along the given axis. | [
"Return",
"a",
"tensor",
"with",
"given",
"shape",
"containing",
"coordinate",
"along",
"given",
"axis",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L4506-L4523 |
22,473 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | self_attention_expert | def self_attention_expert(x,
batch_coordinate,
mask_right=True,
split_batch=False,
attention_num_head=1,
attention_kq_size=None,
attention_v_size=None):
"""Implem... | python | def self_attention_expert(x,
batch_coordinate,
mask_right=True,
split_batch=False,
attention_num_head=1,
attention_kq_size=None,
attention_v_size=None):
"""Implem... | [
"def",
"self_attention_expert",
"(",
"x",
",",
"batch_coordinate",
",",
"mask_right",
"=",
"True",
",",
"split_batch",
"=",
"False",
",",
"attention_num_head",
"=",
"1",
",",
"attention_kq_size",
"=",
"None",
",",
"attention_v_size",
"=",
"None",
")",
":",
"de... | Implementing attention that runs inside each expert.
Args:
x: A tensor of shape[batch, depth]. Contains representations from
different positions, which are lexicographically ordered.
batch_coordinate: A tensor of shape [batch, 1] containing the batch
coordinate of each element in x. This is neede... | [
"Implementing",
"attention",
"that",
"runs",
"inside",
"each",
"expert",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L4526-L4632 |
22,474 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | local_expert_attention | def local_expert_attention(x,
k,
loss_coef,
attention_num_experts,
train=True,
batch_coordinate=None,
**kwargs):
"""Attention using a mixture of experts.
... | python | def local_expert_attention(x,
k,
loss_coef,
attention_num_experts,
train=True,
batch_coordinate=None,
**kwargs):
"""Attention using a mixture of experts.
... | [
"def",
"local_expert_attention",
"(",
"x",
",",
"k",
",",
"loss_coef",
",",
"attention_num_experts",
",",
"train",
"=",
"True",
",",
"batch_coordinate",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"batch_coordinate",
"is",
"None",
":",
"batch_coord... | Attention using a mixture of experts.
Positions sent to the same expert can attend to each other.
The mixture of experts is "local" in that it is replicated on each
datashard.
local_moe flatten all batches so to avoid problems with padding (ex: all
padding going to the same expert, self attention ... | [
"Attention",
"using",
"a",
"mixture",
"of",
"experts",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L4635-L4681 |
22,475 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | expert_dot_product | def expert_dot_product(q, k, v, info_q, info_k):
"""Perform dot product on a subset of the sequence.
Can add a mask to the attention to prevent sequences to attend to each other
and to prevent attention to the future.
Args:
q (tf.Tensor): Queries of shape [length_expert_q, depth_k]
k (tf.Tensor): Keys... | python | def expert_dot_product(q, k, v, info_q, info_k):
"""Perform dot product on a subset of the sequence.
Can add a mask to the attention to prevent sequences to attend to each other
and to prevent attention to the future.
Args:
q (tf.Tensor): Queries of shape [length_expert_q, depth_k]
k (tf.Tensor): Keys... | [
"def",
"expert_dot_product",
"(",
"q",
",",
"k",
",",
"v",
",",
"info_q",
",",
"info_k",
")",
":",
"length_q",
"=",
"common_layers",
".",
"shape_list",
"(",
"q",
")",
"[",
"0",
"]",
"length_k",
"=",
"common_layers",
".",
"shape_list",
"(",
"k",
")",
... | Perform dot product on a subset of the sequence.
Can add a mask to the attention to prevent sequences to attend to each other
and to prevent attention to the future.
Args:
q (tf.Tensor): Queries of shape [length_expert_q, depth_k]
k (tf.Tensor): Keys of shape [length_expert_k, depth_k]
v (tf.Tensor)... | [
"Perform",
"dot",
"product",
"on",
"a",
"subset",
"of",
"the",
"sequence",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L4685-L4746 |
22,476 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | map_fn_switch | def map_fn_switch(fn, elems, use_map_fn=True, **kwargs):
"""Construct the graph with either tf.map_fn or a python for loop.
This function is mainly for for benchmarking purpose.
tf.map_fn is dynamic but is much slower than creating a static graph with
for loop. However, having a for loop make the graph much l... | python | def map_fn_switch(fn, elems, use_map_fn=True, **kwargs):
"""Construct the graph with either tf.map_fn or a python for loop.
This function is mainly for for benchmarking purpose.
tf.map_fn is dynamic but is much slower than creating a static graph with
for loop. However, having a for loop make the graph much l... | [
"def",
"map_fn_switch",
"(",
"fn",
",",
"elems",
",",
"use_map_fn",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"use_map_fn",
":",
"return",
"tf",
".",
"map_fn",
"(",
"fn",
",",
"elems",
",",
"*",
"*",
"kwargs",
")",
"elems_unpacked",
"=",
... | Construct the graph with either tf.map_fn or a python for loop.
This function is mainly for for benchmarking purpose.
tf.map_fn is dynamic but is much slower than creating a static graph with
for loop. However, having a for loop make the graph much longer to build
and can consume too much RAM on distributed s... | [
"Construct",
"the",
"graph",
"with",
"either",
"tf",
".",
"map_fn",
"or",
"a",
"python",
"for",
"loop",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L4811-L4836 |
22,477 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | deconv_elems_1d | def deconv_elems_1d(x, factor, out_depth=None):
"""Increase the length and change the dimensionality.
Expand/project each positions of dim depth of the input into
factor*tokens of dim out_depth
Args:
x (tf.Tensor): shape [batch_size, length, depth]
factor (int): Multiplicative factor of each tokens.
... | python | def deconv_elems_1d(x, factor, out_depth=None):
"""Increase the length and change the dimensionality.
Expand/project each positions of dim depth of the input into
factor*tokens of dim out_depth
Args:
x (tf.Tensor): shape [batch_size, length, depth]
factor (int): Multiplicative factor of each tokens.
... | [
"def",
"deconv_elems_1d",
"(",
"x",
",",
"factor",
",",
"out_depth",
"=",
"None",
")",
":",
"out_depth",
"=",
"out_depth",
"or",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"-",
"1",
"]",
"x",
"=",
"tf",
".",
"expand_dims",
"(",... | Increase the length and change the dimensionality.
Expand/project each positions of dim depth of the input into
factor*tokens of dim out_depth
Args:
x (tf.Tensor): shape [batch_size, length, depth]
factor (int): Multiplicative factor of each tokens.
out_depth (int): Output depth (if None, keep depth... | [
"Increase",
"the",
"length",
"and",
"change",
"the",
"dimensionality",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L5116-L5140 |
22,478 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | conv_elems_1d | def conv_elems_1d(x, factor, out_depth=None):
"""Decrease the length and change the dimensionality.
Merge/restore/compress factors positions of dim depth of the input into
a single position of dim out_depth.
This is basically just a strided convolution without overlap
between each strides. The original lengt... | python | def conv_elems_1d(x, factor, out_depth=None):
"""Decrease the length and change the dimensionality.
Merge/restore/compress factors positions of dim depth of the input into
a single position of dim out_depth.
This is basically just a strided convolution without overlap
between each strides. The original lengt... | [
"def",
"conv_elems_1d",
"(",
"x",
",",
"factor",
",",
"out_depth",
"=",
"None",
")",
":",
"out_depth",
"=",
"out_depth",
"or",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"-",
"1",
"]",
"# with tf.control_dependencies( # Dynamic assertio... | Decrease the length and change the dimensionality.
Merge/restore/compress factors positions of dim depth of the input into
a single position of dim out_depth.
This is basically just a strided convolution without overlap
between each strides. The original length has to be divided by factor.
Args:
x (tf.T... | [
"Decrease",
"the",
"length",
"and",
"change",
"the",
"dimensionality",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L5144-L5172 |
22,479 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | local_reduction_attention | def local_reduction_attention(x, block_length, multihead_params):
"""Reduce the length dimension using self attention.
Args:
x (tf.Tensor): float32 of shape [batch, length, depth]
block_length (int): Block length for local attention (Compression factor)
multihead_params (dict): parameters for multihead... | python | def local_reduction_attention(x, block_length, multihead_params):
"""Reduce the length dimension using self attention.
Args:
x (tf.Tensor): float32 of shape [batch, length, depth]
block_length (int): Block length for local attention (Compression factor)
multihead_params (dict): parameters for multihead... | [
"def",
"local_reduction_attention",
"(",
"x",
",",
"block_length",
",",
"multihead_params",
")",
":",
"@",
"expert_utils",
".",
"add_name_scope",
"(",
")",
"def",
"dot_product_self_local_attention_flattened",
"(",
"q",
",",
"k",
",",
"v",
")",
":",
"\"\"\"Strided ... | Reduce the length dimension using self attention.
Args:
x (tf.Tensor): float32 of shape [batch, length, depth]
block_length (int): Block length for local attention (Compression factor)
multihead_params (dict): parameters for multihead attention
Returns:
tf.Tensor: Compressed tensor of shape [batch... | [
"Reduce",
"the",
"length",
"dimension",
"using",
"self",
"attention",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L5176-L5255 |
22,480 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | multihead_self_attention_reduced | def multihead_self_attention_reduced(
x,
memory_antecedent=None,
bias=None,
factor=None,
multihead_params=None,
nonlinearity="none",
reduction_type="conv",
add_mask=True,
):
"""Reduce the length dimension by compressing with conv.
Args:
x (tf.Tensor): float32 of shape [batch, le... | python | def multihead_self_attention_reduced(
x,
memory_antecedent=None,
bias=None,
factor=None,
multihead_params=None,
nonlinearity="none",
reduction_type="conv",
add_mask=True,
):
"""Reduce the length dimension by compressing with conv.
Args:
x (tf.Tensor): float32 of shape [batch, le... | [
"def",
"multihead_self_attention_reduced",
"(",
"x",
",",
"memory_antecedent",
"=",
"None",
",",
"bias",
"=",
"None",
",",
"factor",
"=",
"None",
",",
"multihead_params",
"=",
"None",
",",
"nonlinearity",
"=",
"\"none\"",
",",
"reduction_type",
"=",
"\"conv\"",
... | Reduce the length dimension by compressing with conv.
Args:
x (tf.Tensor): float32 of shape [batch, length, depth]
memory_antecedent (tf.Tensor): Unsupported for now
bias (tf.Tensor): Ignored
factor (int): compression factor for the memory sequence
multihead_params (dict): parameters for multihea... | [
"Reduce",
"the",
"length",
"dimension",
"by",
"compressing",
"with",
"conv",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L5259-L5350 |
22,481 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | scaled_dot_product_attention_simple | def scaled_dot_product_attention_simple(q, k, v, bias, name=None):
"""Scaled dot-product attention. One head. One spatial dimension.
Args:
q: a Tensor with shape [batch, length_q, depth_k]
k: a Tensor with shape [batch, length_kv, depth_k]
v: a Tensor with shape [batch, length_kv, depth_v]
bias: op... | python | def scaled_dot_product_attention_simple(q, k, v, bias, name=None):
"""Scaled dot-product attention. One head. One spatial dimension.
Args:
q: a Tensor with shape [batch, length_q, depth_k]
k: a Tensor with shape [batch, length_kv, depth_k]
v: a Tensor with shape [batch, length_kv, depth_v]
bias: op... | [
"def",
"scaled_dot_product_attention_simple",
"(",
"q",
",",
"k",
",",
"v",
",",
"bias",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"scaled_dot_product_attention_simple\"",
")",
":",
"scala... | Scaled dot-product attention. One head. One spatial dimension.
Args:
q: a Tensor with shape [batch, length_q, depth_k]
k: a Tensor with shape [batch, length_kv, depth_k]
v: a Tensor with shape [batch, length_kv, depth_v]
bias: optional Tensor broadcastable to [batch, length_q, length_kv]
name: an... | [
"Scaled",
"dot",
"-",
"product",
"attention",
".",
"One",
"head",
".",
"One",
"spatial",
"dimension",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L5353-L5376 |
22,482 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | LshGating._idx_to_bits | def _idx_to_bits(self, i):
"""Convert an group index to its bit representation."""
bits = bin(i)[2:].zfill(self.nb_hyperplanes) # Pad the bits str with 0
return [-1.0 if b == "0" else 1.0 for b in bits] | python | def _idx_to_bits(self, i):
"""Convert an group index to its bit representation."""
bits = bin(i)[2:].zfill(self.nb_hyperplanes) # Pad the bits str with 0
return [-1.0 if b == "0" else 1.0 for b in bits] | [
"def",
"_idx_to_bits",
"(",
"self",
",",
"i",
")",
":",
"bits",
"=",
"bin",
"(",
"i",
")",
"[",
"2",
":",
"]",
".",
"zfill",
"(",
"self",
".",
"nb_hyperplanes",
")",
"# Pad the bits str with 0",
"return",
"[",
"-",
"1.0",
"if",
"b",
"==",
"\"0\"",
... | Convert an group index to its bit representation. | [
"Convert",
"an",
"group",
"index",
"to",
"its",
"bit",
"representation",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L803-L806 |
22,483 | tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | LshGating.get_gates | def get_gates(self, x):
"""Return the bucket id of the given tensor.
Args:
x (tf.Tensor): float32 of shape [length, depth]
Returns:
tf.Tensor: One-hot vector int64 of shape [heads, length, nb_buckets]
containing the id of the bucket
"""
# The balance loss don't propagate to th... | python | def get_gates(self, x):
"""Return the bucket id of the given tensor.
Args:
x (tf.Tensor): float32 of shape [length, depth]
Returns:
tf.Tensor: One-hot vector int64 of shape [heads, length, nb_buckets]
containing the id of the bucket
"""
# The balance loss don't propagate to th... | [
"def",
"get_gates",
"(",
"self",
",",
"x",
")",
":",
"# The balance loss don't propagate to the rest of the network",
"x",
"=",
"tf",
".",
"stop_gradient",
"(",
"x",
")",
"# [length, depth] * [depth, nb_vectors * replicat]",
"x",
"=",
"tf",
".",
"matmul",
"(",
"x",
... | Return the bucket id of the given tensor.
Args:
x (tf.Tensor): float32 of shape [length, depth]
Returns:
tf.Tensor: One-hot vector int64 of shape [heads, length, nb_buckets]
containing the id of the bucket | [
"Return",
"the",
"bucket",
"id",
"of",
"the",
"given",
"tensor",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L809-L839 |
22,484 | tensorflow/tensor2tensor | tensor2tensor/models/video/epva.py | van_image_enc_2d | def van_image_enc_2d(x, first_depth, reuse=False, hparams=None):
"""The image encoder for the VAN.
Similar architecture as Ruben's paper
(http://proceedings.mlr.press/v70/villegas17a/villegas17a.pdf).
Args:
x: The image to encode.
first_depth: The depth of the first layer. Depth is increased in subseq... | python | def van_image_enc_2d(x, first_depth, reuse=False, hparams=None):
"""The image encoder for the VAN.
Similar architecture as Ruben's paper
(http://proceedings.mlr.press/v70/villegas17a/villegas17a.pdf).
Args:
x: The image to encode.
first_depth: The depth of the first layer. Depth is increased in subseq... | [
"def",
"van_image_enc_2d",
"(",
"x",
",",
"first_depth",
",",
"reuse",
"=",
"False",
",",
"hparams",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"'van_image_enc'",
",",
"reuse",
"=",
"reuse",
")",
":",
"enc_history",
"=",
"[",
"x",
... | The image encoder for the VAN.
Similar architecture as Ruben's paper
(http://proceedings.mlr.press/v70/villegas17a/villegas17a.pdf).
Args:
x: The image to encode.
first_depth: The depth of the first layer. Depth is increased in subsequent
layers.
reuse: To reuse in variable scope or not.
h... | [
"The",
"image",
"encoder",
"for",
"the",
"VAN",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L53-L124 |
22,485 | tensorflow/tensor2tensor | tensor2tensor/models/video/epva.py | van_enc_2d | def van_enc_2d(x, first_depth, reuse=False):
"""The higher level structure encoder for the VAN.
The high level structure is a vector instead of an image.
Args:
x: The higher level structure to encode.
first_depth: The depth of the first layer. Depth is increased in subsequent
layers.
reuse: To... | python | def van_enc_2d(x, first_depth, reuse=False):
"""The higher level structure encoder for the VAN.
The high level structure is a vector instead of an image.
Args:
x: The higher level structure to encode.
first_depth: The depth of the first layer. Depth is increased in subsequent
layers.
reuse: To... | [
"def",
"van_enc_2d",
"(",
"x",
",",
"first_depth",
",",
"reuse",
"=",
"False",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"'van_enc'",
",",
"reuse",
"=",
"reuse",
")",
":",
"a",
"=",
"4",
"# depends on the inputs size",
"b",
"=",
"4",
"# a, b = ... | The higher level structure encoder for the VAN.
The high level structure is a vector instead of an image.
Args:
x: The higher level structure to encode.
first_depth: The depth of the first layer. Depth is increased in subsequent
layers.
reuse: To reuse in variable scope or not.
Returns:
T... | [
"The",
"higher",
"level",
"structure",
"encoder",
"for",
"the",
"VAN",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L127-L182 |
22,486 | tensorflow/tensor2tensor | tensor2tensor/models/video/epva.py | van_dec_2d | def van_dec_2d(x, skip_connections, output_shape, first_depth, hparams=None):
"""The VAN decoder.
Args:
x: The analogy information to decode.
skip_connections: The encoder layers which can be used as skip connections.
output_shape: The shape of the desired output image.
first_depth: The depth of th... | python | def van_dec_2d(x, skip_connections, output_shape, first_depth, hparams=None):
"""The VAN decoder.
Args:
x: The analogy information to decode.
skip_connections: The encoder layers which can be used as skip connections.
output_shape: The shape of the desired output image.
first_depth: The depth of th... | [
"def",
"van_dec_2d",
"(",
"x",
",",
"skip_connections",
",",
"output_shape",
",",
"first_depth",
",",
"hparams",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"'van_dec'",
")",
":",
"dec",
"=",
"tf",
".",
"layers",
".",
"conv2d_transpose... | The VAN decoder.
Args:
x: The analogy information to decode.
skip_connections: The encoder layers which can be used as skip connections.
output_shape: The shape of the desired output image.
first_depth: The depth of the first layer of the van image encoder.
hparams: The python hparams.
Returns... | [
"The",
"VAN",
"decoder",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L185-L249 |
22,487 | tensorflow/tensor2tensor | tensor2tensor/models/video/epva.py | analogy_computation_2d | def analogy_computation_2d(f_first_enc,
f_first_frame,
f_current_enc,
first_depth):
"""Implements the deep analogy computation."""
with tf.variable_scope('analogy_computation'):
frame_enc_diff = f_first_frame - f_first_enc
fr... | python | def analogy_computation_2d(f_first_enc,
f_first_frame,
f_current_enc,
first_depth):
"""Implements the deep analogy computation."""
with tf.variable_scope('analogy_computation'):
frame_enc_diff = f_first_frame - f_first_enc
fr... | [
"def",
"analogy_computation_2d",
"(",
"f_first_enc",
",",
"f_first_frame",
",",
"f_current_enc",
",",
"first_depth",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"'analogy_computation'",
")",
":",
"frame_enc_diff",
"=",
"f_first_frame",
"-",
"f_first_enc",
"f... | Implements the deep analogy computation. | [
"Implements",
"the",
"deep",
"analogy",
"computation",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L252-L298 |
22,488 | tensorflow/tensor2tensor | tensor2tensor/models/video/epva.py | van | def van(first_enc,
first_frame,
current_enc,
gt_image,
reuse=False,
scope_prefix='',
hparams=None):
"""Implements a VAN.
Args:
first_enc: The first encoding.
first_frame: The first ground truth frame.
current_enc: The encoding of the frame to generate.
... | python | def van(first_enc,
first_frame,
current_enc,
gt_image,
reuse=False,
scope_prefix='',
hparams=None):
"""Implements a VAN.
Args:
first_enc: The first encoding.
first_frame: The first ground truth frame.
current_enc: The encoding of the frame to generate.
... | [
"def",
"van",
"(",
"first_enc",
",",
"first_frame",
",",
"current_enc",
",",
"gt_image",
",",
"reuse",
"=",
"False",
",",
"scope_prefix",
"=",
"''",
",",
"hparams",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"scope_prefix",
"+",
"'v... | Implements a VAN.
Args:
first_enc: The first encoding.
first_frame: The first ground truth frame.
current_enc: The encoding of the frame to generate.
gt_image: The ground truth image, only used for regularization.
reuse: To reuse in variable scope or not.
scope_prefix: The prefix before the s... | [
"Implements",
"a",
"VAN",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L301-L346 |
22,489 | tensorflow/tensor2tensor | tensor2tensor/models/video/epva.py | encoder_vgg | def encoder_vgg(x, enc_final_size, reuse=False, scope_prefix='', hparams=None,
is_training=True):
"""VGG network to use as encoder without the top few layers.
Can be pretrained.
Args:
x: The image to encode. In the range 0 to 1.
enc_final_size: The desired size of the encoding.
reuse... | python | def encoder_vgg(x, enc_final_size, reuse=False, scope_prefix='', hparams=None,
is_training=True):
"""VGG network to use as encoder without the top few layers.
Can be pretrained.
Args:
x: The image to encode. In the range 0 to 1.
enc_final_size: The desired size of the encoding.
reuse... | [
"def",
"encoder_vgg",
"(",
"x",
",",
"enc_final_size",
",",
"reuse",
"=",
"False",
",",
"scope_prefix",
"=",
"''",
",",
"hparams",
"=",
"None",
",",
"is_training",
"=",
"True",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"scope_prefix",
"+",
"'en... | VGG network to use as encoder without the top few layers.
Can be pretrained.
Args:
x: The image to encode. In the range 0 to 1.
enc_final_size: The desired size of the encoding.
reuse: To reuse in variable scope or not.
scope_prefix: The prefix before the scope name.
hparams: The python hparam... | [
"VGG",
"network",
"to",
"use",
"as",
"encoder",
"without",
"the",
"top",
"few",
"layers",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L349-L401 |
22,490 | tensorflow/tensor2tensor | tensor2tensor/models/video/epva.py | predictor | def predictor(enc_flat,
action,
lstm_states,
pred_depth,
reuse=False,
scope_prefix='',
hparams=None):
"""LSTM predictor network."""
with tf.variable_scope(scope_prefix + 'predict', reuse=reuse):
enc_final_size = enc_flat.get_sh... | python | def predictor(enc_flat,
action,
lstm_states,
pred_depth,
reuse=False,
scope_prefix='',
hparams=None):
"""LSTM predictor network."""
with tf.variable_scope(scope_prefix + 'predict', reuse=reuse):
enc_final_size = enc_flat.get_sh... | [
"def",
"predictor",
"(",
"enc_flat",
",",
"action",
",",
"lstm_states",
",",
"pred_depth",
",",
"reuse",
"=",
"False",
",",
"scope_prefix",
"=",
"''",
",",
"hparams",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"scope_prefix",
"+",
"... | LSTM predictor network. | [
"LSTM",
"predictor",
"network",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L404-L492 |
22,491 | tensorflow/tensor2tensor | tensor2tensor/models/video/epva.py | construct_model | def construct_model(images,
actions=None,
context_frames=2,
hparams=None,
is_training=True):
"""Constructs the tensorflow graph of the hierarchical model."""
pred_depth = 20
enc_out_all, pred_out_all, van_out_all, van_on_enc_all = [... | python | def construct_model(images,
actions=None,
context_frames=2,
hparams=None,
is_training=True):
"""Constructs the tensorflow graph of the hierarchical model."""
pred_depth = 20
enc_out_all, pred_out_all, van_out_all, van_on_enc_all = [... | [
"def",
"construct_model",
"(",
"images",
",",
"actions",
"=",
"None",
",",
"context_frames",
"=",
"2",
",",
"hparams",
"=",
"None",
",",
"is_training",
"=",
"True",
")",
":",
"pred_depth",
"=",
"20",
"enc_out_all",
",",
"pred_out_all",
",",
"van_out_all",
... | Constructs the tensorflow graph of the hierarchical model. | [
"Constructs",
"the",
"tensorflow",
"graph",
"of",
"the",
"hierarchical",
"model",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L495-L569 |
22,492 | tensorflow/tensor2tensor | tensor2tensor/models/video/epva.py | peak_signal_to_noise_ratio | def peak_signal_to_noise_ratio(true, pred):
"""Image quality metric based on maximal signal power vs. power of the noise.
Args:
true: the ground truth image.
pred: the predicted image.
Returns:
peak signal to noise ratio (PSNR)
"""
return 10.0 * tf.log(1.0 / mean_squared_error(true, pred)) / tf.l... | python | def peak_signal_to_noise_ratio(true, pred):
"""Image quality metric based on maximal signal power vs. power of the noise.
Args:
true: the ground truth image.
pred: the predicted image.
Returns:
peak signal to noise ratio (PSNR)
"""
return 10.0 * tf.log(1.0 / mean_squared_error(true, pred)) / tf.l... | [
"def",
"peak_signal_to_noise_ratio",
"(",
"true",
",",
"pred",
")",
":",
"return",
"10.0",
"*",
"tf",
".",
"log",
"(",
"1.0",
"/",
"mean_squared_error",
"(",
"true",
",",
"pred",
")",
")",
"/",
"tf",
".",
"log",
"(",
"10.0",
")"
] | Image quality metric based on maximal signal power vs. power of the noise.
Args:
true: the ground truth image.
pred: the predicted image.
Returns:
peak signal to noise ratio (PSNR) | [
"Image",
"quality",
"metric",
"based",
"on",
"maximal",
"signal",
"power",
"vs",
".",
"power",
"of",
"the",
"noise",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L572-L581 |
22,493 | tensorflow/tensor2tensor | tensor2tensor/models/video/epva.py | mean_squared_error | def mean_squared_error(true, pred):
"""L2 distance between tensors true and pred.
Args:
true: the ground truth image.
pred: the predicted image.
Returns:
mean squared error between ground truth and predicted image.
"""
result = tf.reduce_sum(
tf.squared_difference(true, pred)) / tf.to_float... | python | def mean_squared_error(true, pred):
"""L2 distance between tensors true and pred.
Args:
true: the ground truth image.
pred: the predicted image.
Returns:
mean squared error between ground truth and predicted image.
"""
result = tf.reduce_sum(
tf.squared_difference(true, pred)) / tf.to_float... | [
"def",
"mean_squared_error",
"(",
"true",
",",
"pred",
")",
":",
"result",
"=",
"tf",
".",
"reduce_sum",
"(",
"tf",
".",
"squared_difference",
"(",
"true",
",",
"pred",
")",
")",
"/",
"tf",
".",
"to_float",
"(",
"tf",
".",
"size",
"(",
"pred",
")",
... | L2 distance between tensors true and pred.
Args:
true: the ground truth image.
pred: the predicted image.
Returns:
mean squared error between ground truth and predicted image. | [
"L2",
"distance",
"between",
"tensors",
"true",
"and",
"pred",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L584-L595 |
22,494 | tensorflow/tensor2tensor | tensor2tensor/models/video/epva.py | l1_error | def l1_error(true, pred):
"""L1 distance between tensors true and pred."""
return tf.reduce_sum(tf.abs(true - pred)) / tf.to_float(tf.size(pred)) | python | def l1_error(true, pred):
"""L1 distance between tensors true and pred."""
return tf.reduce_sum(tf.abs(true - pred)) / tf.to_float(tf.size(pred)) | [
"def",
"l1_error",
"(",
"true",
",",
"pred",
")",
":",
"return",
"tf",
".",
"reduce_sum",
"(",
"tf",
".",
"abs",
"(",
"true",
"-",
"pred",
")",
")",
"/",
"tf",
".",
"to_float",
"(",
"tf",
".",
"size",
"(",
"pred",
")",
")"
] | L1 distance between tensors true and pred. | [
"L1",
"distance",
"between",
"tensors",
"true",
"and",
"pred",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L598-L600 |
22,495 | tensorflow/tensor2tensor | tensor2tensor/models/video/epva.py | calc_loss_psnr | def calc_loss_psnr(gen_images, images, name, hparams=None, use_l1_loss=False):
"""Calculates loss and psnr for predictions over multiple timesteps."""
del hparams
with tf.name_scope(name):
loss, error, psnr_all = 0.0, 0.0, 0.0
for _, x, gx in zip(range(len(gen_images)), images, gen_images):
recon_co... | python | def calc_loss_psnr(gen_images, images, name, hparams=None, use_l1_loss=False):
"""Calculates loss and psnr for predictions over multiple timesteps."""
del hparams
with tf.name_scope(name):
loss, error, psnr_all = 0.0, 0.0, 0.0
for _, x, gx in zip(range(len(gen_images)), images, gen_images):
recon_co... | [
"def",
"calc_loss_psnr",
"(",
"gen_images",
",",
"images",
",",
"name",
",",
"hparams",
"=",
"None",
",",
"use_l1_loss",
"=",
"False",
")",
":",
"del",
"hparams",
"with",
"tf",
".",
"name_scope",
"(",
"name",
")",
":",
"loss",
",",
"error",
",",
"psnr_... | Calculates loss and psnr for predictions over multiple timesteps. | [
"Calculates",
"loss",
"and",
"psnr",
"for",
"predictions",
"over",
"multiple",
"timesteps",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/epva.py#L603-L627 |
22,496 | tensorflow/tensor2tensor | tensor2tensor/models/video/sv2p_params.py | next_frame_sv2p | def next_frame_sv2p():
"""SV2P model hparams."""
hparams = basic_stochastic.next_frame_basic_stochastic()
hparams.optimizer = "true_adam"
hparams.learning_rate_schedule = "constant"
hparams.learning_rate_constant = 1e-3
hparams.video_num_input_frames = 1
hparams.video_num_target_frames = 3
hparams.batch... | python | def next_frame_sv2p():
"""SV2P model hparams."""
hparams = basic_stochastic.next_frame_basic_stochastic()
hparams.optimizer = "true_adam"
hparams.learning_rate_schedule = "constant"
hparams.learning_rate_constant = 1e-3
hparams.video_num_input_frames = 1
hparams.video_num_target_frames = 3
hparams.batch... | [
"def",
"next_frame_sv2p",
"(",
")",
":",
"hparams",
"=",
"basic_stochastic",
".",
"next_frame_basic_stochastic",
"(",
")",
"hparams",
".",
"optimizer",
"=",
"\"true_adam\"",
"hparams",
".",
"learning_rate_schedule",
"=",
"\"constant\"",
"hparams",
".",
"learning_rate_... | SV2P model hparams. | [
"SV2P",
"model",
"hparams",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/sv2p_params.py#L27-L60 |
22,497 | tensorflow/tensor2tensor | tensor2tensor/models/video/sv2p_params.py | next_frame_sv2p_discrete | def next_frame_sv2p_discrete():
"""SV2P discrete model hparams."""
hparams = next_frame_sv2p()
hparams.action_injection = "multiplicative"
hparams.small_mode = True
hparams.add_hparam("bottleneck_bits", 128)
hparams.add_hparam("bottleneck_noise", 0.02)
hparams.add_hparam("discrete_warmup_steps", 40000)
... | python | def next_frame_sv2p_discrete():
"""SV2P discrete model hparams."""
hparams = next_frame_sv2p()
hparams.action_injection = "multiplicative"
hparams.small_mode = True
hparams.add_hparam("bottleneck_bits", 128)
hparams.add_hparam("bottleneck_noise", 0.02)
hparams.add_hparam("discrete_warmup_steps", 40000)
... | [
"def",
"next_frame_sv2p_discrete",
"(",
")",
":",
"hparams",
"=",
"next_frame_sv2p",
"(",
")",
"hparams",
".",
"action_injection",
"=",
"\"multiplicative\"",
"hparams",
".",
"small_mode",
"=",
"True",
"hparams",
".",
"add_hparam",
"(",
"\"bottleneck_bits\"",
",",
... | SV2P discrete model hparams. | [
"SV2P",
"discrete",
"model",
"hparams",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/sv2p_params.py#L64-L76 |
22,498 | tensorflow/tensor2tensor | tensor2tensor/models/video/sv2p_params.py | next_frame_sv2p_atari | def next_frame_sv2p_atari():
"""SV2P model for atari."""
hparams = next_frame_sv2p()
hparams.video_num_input_frames = 4
hparams.video_num_target_frames = 4
hparams.action_injection = "multiplicative"
hparams.num_iterations_1st_stage = 12000
hparams.num_iterations_2nd_stage = 12000
hparams.anneal_end = 4... | python | def next_frame_sv2p_atari():
"""SV2P model for atari."""
hparams = next_frame_sv2p()
hparams.video_num_input_frames = 4
hparams.video_num_target_frames = 4
hparams.action_injection = "multiplicative"
hparams.num_iterations_1st_stage = 12000
hparams.num_iterations_2nd_stage = 12000
hparams.anneal_end = 4... | [
"def",
"next_frame_sv2p_atari",
"(",
")",
":",
"hparams",
"=",
"next_frame_sv2p",
"(",
")",
"hparams",
".",
"video_num_input_frames",
"=",
"4",
"hparams",
".",
"video_num_target_frames",
"=",
"4",
"hparams",
".",
"action_injection",
"=",
"\"multiplicative\"",
"hpara... | SV2P model for atari. | [
"SV2P",
"model",
"for",
"atari",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/sv2p_params.py#L80-L93 |
22,499 | tensorflow/tensor2tensor | tensor2tensor/models/video/sv2p_params.py | next_frame_sv2p_atari_softmax | def next_frame_sv2p_atari_softmax():
"""SV2P model for atari with softmax."""
hparams = next_frame_sv2p_atari()
hparams.bottom = {}
hparams.loss = {}
hparams.top = {}
hparams.internal_loss = True
return hparams | python | def next_frame_sv2p_atari_softmax():
"""SV2P model for atari with softmax."""
hparams = next_frame_sv2p_atari()
hparams.bottom = {}
hparams.loss = {}
hparams.top = {}
hparams.internal_loss = True
return hparams | [
"def",
"next_frame_sv2p_atari_softmax",
"(",
")",
":",
"hparams",
"=",
"next_frame_sv2p_atari",
"(",
")",
"hparams",
".",
"bottom",
"=",
"{",
"}",
"hparams",
".",
"loss",
"=",
"{",
"}",
"hparams",
".",
"top",
"=",
"{",
"}",
"hparams",
".",
"internal_loss",... | SV2P model for atari with softmax. | [
"SV2P",
"model",
"for",
"atari",
"with",
"softmax",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/sv2p_params.py#L97-L104 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.