repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
tensorflow/tensor2tensor | tensor2tensor/rl/restarter.py | Restarter.training_loop | def training_loop(self):
"""Context manager wrapping the training loop, updates step counters."""
if not self.restarting:
self._write_counters(self._local_step_at_start, self._global_step)
tf.logging.info(
"Training %s up to %d, %d to go", self.model_mode,
self.target_local_step, self... | python | def training_loop(self):
"""Context manager wrapping the training loop, updates step counters."""
if not self.restarting:
self._write_counters(self._local_step_at_start, self._global_step)
tf.logging.info(
"Training %s up to %d, %d to go", self.model_mode,
self.target_local_step, self... | [
"def",
"training_loop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"restarting",
":",
"self",
".",
"_write_counters",
"(",
"self",
".",
"_local_step_at_start",
",",
"self",
".",
"_global_step",
")",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Training... | Context manager wrapping the training loop, updates step counters. | [
"Context",
"manager",
"wrapping",
"the",
"training",
"loop",
"updates",
"step",
"counters",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/restarter.py#L90-L102 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/ptb.py | _read_words | def _read_words(filename):
"""Reads words from a file."""
with tf.gfile.GFile(filename, "r") as f:
if sys.version_info[0] >= 3:
return f.read().replace("\n", " %s " % EOS).split()
else:
return f.read().decode("utf-8").replace("\n", " %s " % EOS).split() | python | def _read_words(filename):
"""Reads words from a file."""
with tf.gfile.GFile(filename, "r") as f:
if sys.version_info[0] >= 3:
return f.read().replace("\n", " %s " % EOS).split()
else:
return f.read().decode("utf-8").replace("\n", " %s " % EOS).split() | [
"def",
"_read_words",
"(",
"filename",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"GFile",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"f",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
">=",
"3",
":",
"return",
"f",
".",
"read",
"(",
")",
... | Reads words from a file. | [
"Reads",
"words",
"from",
"a",
"file",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/ptb.py#L39-L45 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/ptb.py | _build_vocab | def _build_vocab(filename, vocab_path, vocab_size):
"""Reads a file to build a vocabulary of `vocab_size` most common words.
The vocabulary is sorted by occurrence count and has one word per line.
Originally from:
https://github.com/tensorflow/models/blob/master/tutorials/rnn/ptb/reader.py
Args:
file... | python | def _build_vocab(filename, vocab_path, vocab_size):
"""Reads a file to build a vocabulary of `vocab_size` most common words.
The vocabulary is sorted by occurrence count and has one word per line.
Originally from:
https://github.com/tensorflow/models/blob/master/tutorials/rnn/ptb/reader.py
Args:
file... | [
"def",
"_build_vocab",
"(",
"filename",
",",
"vocab_path",
",",
"vocab_size",
")",
":",
"data",
"=",
"_read_words",
"(",
"filename",
")",
"counter",
"=",
"collections",
".",
"Counter",
"(",
"data",
")",
"count_pairs",
"=",
"sorted",
"(",
"counter",
".",
"i... | Reads a file to build a vocabulary of `vocab_size` most common words.
The vocabulary is sorted by occurrence count and has one word per line.
Originally from:
https://github.com/tensorflow/models/blob/master/tutorials/rnn/ptb/reader.py
Args:
filename: file to read list of words from.
vocab_path: pa... | [
"Reads",
"a",
"file",
"to",
"build",
"a",
"vocabulary",
"of",
"vocab_size",
"most",
"common",
"words",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/ptb.py#L48-L66 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/ptb.py | _get_token_encoder | def _get_token_encoder(vocab_dir, vocab_name, filename):
"""Reads from file and returns a `TokenTextEncoder` for the vocabulary."""
vocab_path = os.path.join(vocab_dir, vocab_name)
if not tf.gfile.Exists(vocab_path):
_build_vocab(filename, vocab_path, 10000)
return text_encoder.TokenTextEncoder(vocab_path) | python | def _get_token_encoder(vocab_dir, vocab_name, filename):
"""Reads from file and returns a `TokenTextEncoder` for the vocabulary."""
vocab_path = os.path.join(vocab_dir, vocab_name)
if not tf.gfile.Exists(vocab_path):
_build_vocab(filename, vocab_path, 10000)
return text_encoder.TokenTextEncoder(vocab_path) | [
"def",
"_get_token_encoder",
"(",
"vocab_dir",
",",
"vocab_name",
",",
"filename",
")",
":",
"vocab_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"vocab_dir",
",",
"vocab_name",
")",
"if",
"not",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"vocab_path",
"... | Reads from file and returns a `TokenTextEncoder` for the vocabulary. | [
"Reads",
"from",
"file",
"and",
"returns",
"a",
"TokenTextEncoder",
"for",
"the",
"vocabulary",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/ptb.py#L69-L74 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/ptb.py | _maybe_download_corpus | def _maybe_download_corpus(tmp_dir, vocab_type):
"""Download and unpack the corpus.
Args:
tmp_dir: directory containing dataset.
vocab_type: which vocabulary are we using.
Returns:
The list of names of files.
"""
filename = os.path.basename(PTB_URL)
compressed_filepath = generator_utils.maybe_... | python | def _maybe_download_corpus(tmp_dir, vocab_type):
"""Download and unpack the corpus.
Args:
tmp_dir: directory containing dataset.
vocab_type: which vocabulary are we using.
Returns:
The list of names of files.
"""
filename = os.path.basename(PTB_URL)
compressed_filepath = generator_utils.maybe_... | [
"def",
"_maybe_download_corpus",
"(",
"tmp_dir",
",",
"vocab_type",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"PTB_URL",
")",
"compressed_filepath",
"=",
"generator_utils",
".",
"maybe_download",
"(",
"tmp_dir",
",",
"filename",
",",
... | Download and unpack the corpus.
Args:
tmp_dir: directory containing dataset.
vocab_type: which vocabulary are we using.
Returns:
The list of names of files. | [
"Download",
"and",
"unpack",
"the",
"corpus",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/ptb.py#L77-L109 | train |
tensorflow/tensor2tensor | tensor2tensor/visualization/attention.py | resize | def resize(att_mat, max_length=None):
"""Normalize attention matrices and reshape as necessary."""
for i, att in enumerate(att_mat):
# Add extra batch dim for viz code to work.
if att.ndim == 3:
att = np.expand_dims(att, axis=0)
if max_length is not None:
# Sum across different attention val... | python | def resize(att_mat, max_length=None):
"""Normalize attention matrices and reshape as necessary."""
for i, att in enumerate(att_mat):
# Add extra batch dim for viz code to work.
if att.ndim == 3:
att = np.expand_dims(att, axis=0)
if max_length is not None:
# Sum across different attention val... | [
"def",
"resize",
"(",
"att_mat",
",",
"max_length",
"=",
"None",
")",
":",
"for",
"i",
",",
"att",
"in",
"enumerate",
"(",
"att_mat",
")",
":",
"# Add extra batch dim for viz code to work.",
"if",
"att",
".",
"ndim",
"==",
"3",
":",
"att",
"=",
"np",
"."... | Normalize attention matrices and reshape as necessary. | [
"Normalize",
"attention",
"matrices",
"and",
"reshape",
"as",
"necessary",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/visualization/attention.py#L62-L75 | train |
tensorflow/tensor2tensor | tensor2tensor/visualization/attention.py | _get_attention | def _get_attention(inp_text, out_text, enc_atts, dec_atts, encdec_atts):
"""Compute representation of the attention ready for the d3 visualization.
Args:
inp_text: list of strings, words to be displayed on the left of the vis
out_text: list of strings, words to be displayed on the right of the vis
enc_... | python | def _get_attention(inp_text, out_text, enc_atts, dec_atts, encdec_atts):
"""Compute representation of the attention ready for the d3 visualization.
Args:
inp_text: list of strings, words to be displayed on the left of the vis
out_text: list of strings, words to be displayed on the right of the vis
enc_... | [
"def",
"_get_attention",
"(",
"inp_text",
",",
"out_text",
",",
"enc_atts",
",",
"dec_atts",
",",
"encdec_atts",
")",
":",
"def",
"get_full_attention",
"(",
"layer",
")",
":",
"\"\"\"Get the full input+output - input+output attentions.\"\"\"",
"enc_att",
"=",
"enc_atts"... | Compute representation of the attention ready for the d3 visualization.
Args:
inp_text: list of strings, words to be displayed on the left of the vis
out_text: list of strings, words to be displayed on the right of the vis
enc_atts: numpy array, encoder self-attentions
[num_layers, batch_size, nu... | [
"Compute",
"representation",
"of",
"the",
"attention",
"ready",
"for",
"the",
"d3",
"visualization",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/visualization/attention.py#L78-L163 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/tokenizer.py | decode | def decode(tokens):
"""Decode a list of tokens to a unicode string.
Args:
tokens: a list of Unicode strings
Returns:
a unicode string
"""
token_is_alnum = [t[0] in _ALPHANUMERIC_CHAR_SET for t in tokens]
ret = []
for i, token in enumerate(tokens):
if i > 0 and token_is_alnum[i - 1] and token_... | python | def decode(tokens):
"""Decode a list of tokens to a unicode string.
Args:
tokens: a list of Unicode strings
Returns:
a unicode string
"""
token_is_alnum = [t[0] in _ALPHANUMERIC_CHAR_SET for t in tokens]
ret = []
for i, token in enumerate(tokens):
if i > 0 and token_is_alnum[i - 1] and token_... | [
"def",
"decode",
"(",
"tokens",
")",
":",
"token_is_alnum",
"=",
"[",
"t",
"[",
"0",
"]",
"in",
"_ALPHANUMERIC_CHAR_SET",
"for",
"t",
"in",
"tokens",
"]",
"ret",
"=",
"[",
"]",
"for",
"i",
",",
"token",
"in",
"enumerate",
"(",
"tokens",
")",
":",
"... | Decode a list of tokens to a unicode string.
Args:
tokens: a list of Unicode strings
Returns:
a unicode string | [
"Decode",
"a",
"list",
"of",
"tokens",
"to",
"a",
"unicode",
"string",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/tokenizer.py#L91-L105 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/tokenizer.py | _read_filepattern | def _read_filepattern(filepattern, max_lines=None, split_on_newlines=True):
"""Reads files matching a wildcard pattern, yielding the contents.
Args:
filepattern: A wildcard pattern matching one or more files.
max_lines: If set, stop reading after reading this many lines.
split_on_newlines: A boolean. I... | python | def _read_filepattern(filepattern, max_lines=None, split_on_newlines=True):
"""Reads files matching a wildcard pattern, yielding the contents.
Args:
filepattern: A wildcard pattern matching one or more files.
max_lines: If set, stop reading after reading this many lines.
split_on_newlines: A boolean. I... | [
"def",
"_read_filepattern",
"(",
"filepattern",
",",
"max_lines",
"=",
"None",
",",
"split_on_newlines",
"=",
"True",
")",
":",
"filenames",
"=",
"sorted",
"(",
"tf",
".",
"gfile",
".",
"Glob",
"(",
"filepattern",
")",
")",
"lines_read",
"=",
"0",
"for",
... | Reads files matching a wildcard pattern, yielding the contents.
Args:
filepattern: A wildcard pattern matching one or more files.
max_lines: If set, stop reading after reading this many lines.
split_on_newlines: A boolean. If true, then split files by lines and strip
leading and trailing whitespa... | [
"Reads",
"files",
"matching",
"a",
"wildcard",
"pattern",
"yielding",
"the",
"contents",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/tokenizer.py#L108-L145 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/tokenizer.py | corpus_token_counts | def corpus_token_counts(
text_filepattern, corpus_max_lines, split_on_newlines=True):
"""Read the corpus and compute a dictionary of token counts.
Args:
text_filepattern: A pattern matching one or more files.
corpus_max_lines: An integer; maximum total lines to read.
split_on_newlines: A boolean. I... | python | def corpus_token_counts(
text_filepattern, corpus_max_lines, split_on_newlines=True):
"""Read the corpus and compute a dictionary of token counts.
Args:
text_filepattern: A pattern matching one or more files.
corpus_max_lines: An integer; maximum total lines to read.
split_on_newlines: A boolean. I... | [
"def",
"corpus_token_counts",
"(",
"text_filepattern",
",",
"corpus_max_lines",
",",
"split_on_newlines",
"=",
"True",
")",
":",
"counts",
"=",
"collections",
".",
"Counter",
"(",
")",
"for",
"doc",
"in",
"_read_filepattern",
"(",
"text_filepattern",
",",
"max_lin... | Read the corpus and compute a dictionary of token counts.
Args:
text_filepattern: A pattern matching one or more files.
corpus_max_lines: An integer; maximum total lines to read.
split_on_newlines: A boolean. If true, then split files by lines and strip
leading and trailing whitespace from each l... | [
"Read",
"the",
"corpus",
"and",
"compute",
"a",
"dictionary",
"of",
"token",
"counts",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/tokenizer.py#L148-L171 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/tokenizer.py | vocab_token_counts | def vocab_token_counts(text_filepattern, max_lines):
"""Read a vocab file and return a dictionary of token counts.
Reads a two-column CSV file of tokens and their frequency in a dataset. The
tokens are presumed to be generated by encode() or the equivalent.
Args:
text_filepattern: A pattern matching one o... | python | def vocab_token_counts(text_filepattern, max_lines):
"""Read a vocab file and return a dictionary of token counts.
Reads a two-column CSV file of tokens and their frequency in a dataset. The
tokens are presumed to be generated by encode() or the equivalent.
Args:
text_filepattern: A pattern matching one o... | [
"def",
"vocab_token_counts",
"(",
"text_filepattern",
",",
"max_lines",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"_read_filepattern",
"(",
"text_filepattern",
",",
"max_lines",
"=",
"max_lines",
")",
")",
":",
"if",
... | Read a vocab file and return a dictionary of token counts.
Reads a two-column CSV file of tokens and their frequency in a dataset. The
tokens are presumed to be generated by encode() or the equivalent.
Args:
text_filepattern: A pattern matching one or more files.
max_lines: An integer; maximum total lin... | [
"Read",
"a",
"vocab",
"file",
"and",
"return",
"a",
"dictionary",
"of",
"token",
"counts",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/tokenizer.py#L174-L197 | train |
tensorflow/tensor2tensor | tensor2tensor/serving/serving_utils.py | _make_example | def _make_example(input_ids, problem, input_feature_name="inputs"):
"""Make a tf.train.Example for the problem.
features[input_feature_name] = input_ids
Also fills in any other required features with dummy values.
Args:
input_ids: list<int>.
problem: Problem.
input_feature_name: name of feature f... | python | def _make_example(input_ids, problem, input_feature_name="inputs"):
"""Make a tf.train.Example for the problem.
features[input_feature_name] = input_ids
Also fills in any other required features with dummy values.
Args:
input_ids: list<int>.
problem: Problem.
input_feature_name: name of feature f... | [
"def",
"_make_example",
"(",
"input_ids",
",",
"problem",
",",
"input_feature_name",
"=",
"\"inputs\"",
")",
":",
"features",
"=",
"{",
"input_feature_name",
":",
"tf",
".",
"train",
".",
"Feature",
"(",
"int64_list",
"=",
"tf",
".",
"train",
".",
"Int64List... | Make a tf.train.Example for the problem.
features[input_feature_name] = input_ids
Also fills in any other required features with dummy values.
Args:
input_ids: list<int>.
problem: Problem.
input_feature_name: name of feature for input_ids.
Returns:
tf.train.Example | [
"Make",
"a",
"tf",
".",
"train",
".",
"Example",
"for",
"the",
"problem",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/serving/serving_utils.py#L36-L81 | train |
tensorflow/tensor2tensor | tensor2tensor/serving/serving_utils.py | make_grpc_request_fn | def make_grpc_request_fn(servable_name, server, timeout_secs):
"""Wraps function to make grpc requests with runtime args."""
stub = _create_stub(server)
def _make_grpc_request(examples):
"""Builds and sends request to TensorFlow model server."""
request = predict_pb2.PredictRequest()
request.model_sp... | python | def make_grpc_request_fn(servable_name, server, timeout_secs):
"""Wraps function to make grpc requests with runtime args."""
stub = _create_stub(server)
def _make_grpc_request(examples):
"""Builds and sends request to TensorFlow model server."""
request = predict_pb2.PredictRequest()
request.model_sp... | [
"def",
"make_grpc_request_fn",
"(",
"servable_name",
",",
"server",
",",
"timeout_secs",
")",
":",
"stub",
"=",
"_create_stub",
"(",
"server",
")",
"def",
"_make_grpc_request",
"(",
"examples",
")",
":",
"\"\"\"Builds and sends request to TensorFlow model server.\"\"\"",
... | Wraps function to make grpc requests with runtime args. | [
"Wraps",
"function",
"to",
"make",
"grpc",
"requests",
"with",
"runtime",
"args",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/serving/serving_utils.py#L105-L125 | train |
tensorflow/tensor2tensor | tensor2tensor/serving/serving_utils.py | make_cloud_mlengine_request_fn | def make_cloud_mlengine_request_fn(credentials, model_name, version):
"""Wraps function to make CloudML Engine requests with runtime args."""
def _make_cloud_mlengine_request(examples):
"""Builds and sends requests to Cloud ML Engine."""
api = discovery.build("ml", "v1", credentials=credentials)
parent... | python | def make_cloud_mlengine_request_fn(credentials, model_name, version):
"""Wraps function to make CloudML Engine requests with runtime args."""
def _make_cloud_mlengine_request(examples):
"""Builds and sends requests to Cloud ML Engine."""
api = discovery.build("ml", "v1", credentials=credentials)
parent... | [
"def",
"make_cloud_mlengine_request_fn",
"(",
"credentials",
",",
"model_name",
",",
"version",
")",
":",
"def",
"_make_cloud_mlengine_request",
"(",
"examples",
")",
":",
"\"\"\"Builds and sends requests to Cloud ML Engine.\"\"\"",
"api",
"=",
"discovery",
".",
"build",
... | Wraps function to make CloudML Engine requests with runtime args. | [
"Wraps",
"function",
"to",
"make",
"CloudML",
"Engine",
"requests",
"with",
"runtime",
"args",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/serving/serving_utils.py#L128-L146 | train |
tensorflow/tensor2tensor | tensor2tensor/serving/serving_utils.py | predict | def predict(inputs_list, problem, request_fn):
"""Encodes inputs, makes request to deployed TF model, and decodes outputs."""
assert isinstance(inputs_list, list)
fname = "inputs" if problem.has_inputs else "targets"
input_encoder = problem.feature_info[fname].encoder
input_ids_list = [
_encode(inputs, ... | python | def predict(inputs_list, problem, request_fn):
"""Encodes inputs, makes request to deployed TF model, and decodes outputs."""
assert isinstance(inputs_list, list)
fname = "inputs" if problem.has_inputs else "targets"
input_encoder = problem.feature_info[fname].encoder
input_ids_list = [
_encode(inputs, ... | [
"def",
"predict",
"(",
"inputs_list",
",",
"problem",
",",
"request_fn",
")",
":",
"assert",
"isinstance",
"(",
"inputs_list",
",",
"list",
")",
"fname",
"=",
"\"inputs\"",
"if",
"problem",
".",
"has_inputs",
"else",
"\"targets\"",
"input_encoder",
"=",
"probl... | Encodes inputs, makes request to deployed TF model, and decodes outputs. | [
"Encodes",
"inputs",
"makes",
"request",
"to",
"deployed",
"TF",
"model",
"and",
"decodes",
"outputs",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/serving/serving_utils.py#L149-L167 | train |
tensorflow/tensor2tensor | tensor2tensor/models/video/basic_recurrent.py | next_frame_basic_recurrent | def next_frame_basic_recurrent():
"""Basic 2-frame recurrent model with stochastic tower."""
hparams = basic_stochastic.next_frame_basic_stochastic_discrete()
hparams.filter_double_steps = 2
hparams.hidden_size = 64
hparams.video_num_input_frames = 4
hparams.video_num_target_frames = 4
hparams.concat_inte... | python | def next_frame_basic_recurrent():
"""Basic 2-frame recurrent model with stochastic tower."""
hparams = basic_stochastic.next_frame_basic_stochastic_discrete()
hparams.filter_double_steps = 2
hparams.hidden_size = 64
hparams.video_num_input_frames = 4
hparams.video_num_target_frames = 4
hparams.concat_inte... | [
"def",
"next_frame_basic_recurrent",
"(",
")",
":",
"hparams",
"=",
"basic_stochastic",
".",
"next_frame_basic_stochastic_discrete",
"(",
")",
"hparams",
".",
"filter_double_steps",
"=",
"2",
"hparams",
".",
"hidden_size",
"=",
"64",
"hparams",
".",
"video_num_input_f... | Basic 2-frame recurrent model with stochastic tower. | [
"Basic",
"2",
"-",
"frame",
"recurrent",
"model",
"with",
"stochastic",
"tower",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_recurrent.py#L52-L62 | train |
tensorflow/tensor2tensor | tensor2tensor/bin/t2t_distill.py | create_teacher_experiment | def create_teacher_experiment(run_config, hparams, argv):
"""Creates experiment function."""
tf.logging.info("training teacher")
tf.logging.set_verbosity(tf.logging.INFO)
trainer_lib.set_random_seed(FLAGS.random_seed)
usr_dir.import_usr_dir(FLAGS.t2t_usr_dir)
t2t_trainer.maybe_log_registry_and_exit()
if ... | python | def create_teacher_experiment(run_config, hparams, argv):
"""Creates experiment function."""
tf.logging.info("training teacher")
tf.logging.set_verbosity(tf.logging.INFO)
trainer_lib.set_random_seed(FLAGS.random_seed)
usr_dir.import_usr_dir(FLAGS.t2t_usr_dir)
t2t_trainer.maybe_log_registry_and_exit()
if ... | [
"def",
"create_teacher_experiment",
"(",
"run_config",
",",
"hparams",
",",
"argv",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"training teacher\"",
")",
"tf",
".",
"logging",
".",
"set_verbosity",
"(",
"tf",
".",
"logging",
".",
"INFO",
")",
"tra... | Creates experiment function. | [
"Creates",
"experiment",
"function",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_distill.py#L91-L114 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/ice_parsing.py | tabbed_parsing_token_generator | def tabbed_parsing_token_generator(data_dir, tmp_dir, train, prefix,
source_vocab_size, target_vocab_size):
"""Generate source and target data from a single file."""
filename = "parsing_{0}.pairs".format("train" if train else "dev")
source_vocab = generator_utils.get_or_generate... | python | def tabbed_parsing_token_generator(data_dir, tmp_dir, train, prefix,
source_vocab_size, target_vocab_size):
"""Generate source and target data from a single file."""
filename = "parsing_{0}.pairs".format("train" if train else "dev")
source_vocab = generator_utils.get_or_generate... | [
"def",
"tabbed_parsing_token_generator",
"(",
"data_dir",
",",
"tmp_dir",
",",
"train",
",",
"prefix",
",",
"source_vocab_size",
",",
"target_vocab_size",
")",
":",
"filename",
"=",
"\"parsing_{0}.pairs\"",
".",
"format",
"(",
"\"train\"",
"if",
"train",
"else",
"... | Generate source and target data from a single file. | [
"Generate",
"source",
"and",
"target",
"data",
"from",
"a",
"single",
"file",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/ice_parsing.py#L37-L50 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/ice_parsing.py | tabbed_parsing_character_generator | def tabbed_parsing_character_generator(tmp_dir, train):
"""Generate source and target data from a single file."""
character_vocab = text_encoder.ByteTextEncoder()
filename = "parsing_{0}.pairs".format("train" if train else "dev")
pair_filepath = os.path.join(tmp_dir, filename)
return text_problems.text2text_g... | python | def tabbed_parsing_character_generator(tmp_dir, train):
"""Generate source and target data from a single file."""
character_vocab = text_encoder.ByteTextEncoder()
filename = "parsing_{0}.pairs".format("train" if train else "dev")
pair_filepath = os.path.join(tmp_dir, filename)
return text_problems.text2text_g... | [
"def",
"tabbed_parsing_character_generator",
"(",
"tmp_dir",
",",
"train",
")",
":",
"character_vocab",
"=",
"text_encoder",
".",
"ByteTextEncoder",
"(",
")",
"filename",
"=",
"\"parsing_{0}.pairs\"",
".",
"format",
"(",
"\"train\"",
"if",
"train",
"else",
"\"dev\""... | Generate source and target data from a single file. | [
"Generate",
"source",
"and",
"target",
"data",
"from",
"a",
"single",
"file",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/ice_parsing.py#L53-L59 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/trax.py | _make_list | def _make_list(predictions, targets):
"""Helper: make predictions and targets lists, check they match on length."""
# Our models sometimes return predictions in lists, make it a list always.
# TODO(lukaszkaiser): make abstractions for nested structures and refactor.
if not isinstance(predictions, (list, tuple)... | python | def _make_list(predictions, targets):
"""Helper: make predictions and targets lists, check they match on length."""
# Our models sometimes return predictions in lists, make it a list always.
# TODO(lukaszkaiser): make abstractions for nested structures and refactor.
if not isinstance(predictions, (list, tuple)... | [
"def",
"_make_list",
"(",
"predictions",
",",
"targets",
")",
":",
"# Our models sometimes return predictions in lists, make it a list always.",
"# TODO(lukaszkaiser): make abstractions for nested structures and refactor.",
"if",
"not",
"isinstance",
"(",
"predictions",
",",
"(",
... | Helper: make predictions and targets lists, check they match on length. | [
"Helper",
":",
"make",
"predictions",
"and",
"targets",
"lists",
"check",
"they",
"match",
"on",
"length",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L54-L64 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/trax.py | masked_mean | def masked_mean(inputs, targets, mask_id=None):
"""Mean of the inputs but counting only those where targets != mask_id."""
inputs = [x.astype(np.float32) for x in inputs]
# We assume all elements in the list contribute equally.
# TODO(lukaszkaiser): remove this assumption (e.g., when masks differ).
length = l... | python | def masked_mean(inputs, targets, mask_id=None):
"""Mean of the inputs but counting only those where targets != mask_id."""
inputs = [x.astype(np.float32) for x in inputs]
# We assume all elements in the list contribute equally.
# TODO(lukaszkaiser): remove this assumption (e.g., when masks differ).
length = l... | [
"def",
"masked_mean",
"(",
"inputs",
",",
"targets",
",",
"mask_id",
"=",
"None",
")",
":",
"inputs",
"=",
"[",
"x",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"for",
"x",
"in",
"inputs",
"]",
"# We assume all elements in the list contribute equally.",
"... | Mean of the inputs but counting only those where targets != mask_id. | [
"Mean",
"of",
"the",
"inputs",
"but",
"counting",
"only",
"those",
"where",
"targets",
"!",
"=",
"mask_id",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L68-L79 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/trax.py | accuracy | def accuracy(batch, model_predictions):
"""Calculate accuracy."""
_, targets = batch
model_predictions, targets = _make_list(model_predictions, targets)
correct = []
for (prediction, target) in zip(model_predictions, targets):
predicted_class = np.argmax(prediction, axis=-1)
correct.append(np.equal(pr... | python | def accuracy(batch, model_predictions):
"""Calculate accuracy."""
_, targets = batch
model_predictions, targets = _make_list(model_predictions, targets)
correct = []
for (prediction, target) in zip(model_predictions, targets):
predicted_class = np.argmax(prediction, axis=-1)
correct.append(np.equal(pr... | [
"def",
"accuracy",
"(",
"batch",
",",
"model_predictions",
")",
":",
"_",
",",
"targets",
"=",
"batch",
"model_predictions",
",",
"targets",
"=",
"_make_list",
"(",
"model_predictions",
",",
"targets",
")",
"correct",
"=",
"[",
"]",
"for",
"(",
"prediction",... | Calculate accuracy. | [
"Calculate",
"accuracy",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L82-L90 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/trax.py | neg_log_perplexity | def neg_log_perplexity(batch, model_predictions):
"""Calculate negative log perplexity."""
_, targets = batch
model_predictions, targets = _make_list(model_predictions, targets)
xent = []
for (prediction, target) in zip(model_predictions, targets):
hot_target = layers.one_hot(target, prediction.shape[-1])... | python | def neg_log_perplexity(batch, model_predictions):
"""Calculate negative log perplexity."""
_, targets = batch
model_predictions, targets = _make_list(model_predictions, targets)
xent = []
for (prediction, target) in zip(model_predictions, targets):
hot_target = layers.one_hot(target, prediction.shape[-1])... | [
"def",
"neg_log_perplexity",
"(",
"batch",
",",
"model_predictions",
")",
":",
"_",
",",
"targets",
"=",
"batch",
"model_predictions",
",",
"targets",
"=",
"_make_list",
"(",
"model_predictions",
",",
"targets",
")",
"xent",
"=",
"[",
"]",
"for",
"(",
"predi... | Calculate negative log perplexity. | [
"Calculate",
"negative",
"log",
"perplexity",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L93-L101 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/trax.py | loss | def loss(params, batch, model_predict, rng):
"""Calculate loss."""
inputs, targets = batch
predictions = model_predict(inputs, params, rng=rng)
predictions, targets = _make_list(predictions, targets)
xent = []
for (pred, target) in zip(predictions, targets):
xent.append(np.sum(pred * layers.one_hot(targ... | python | def loss(params, batch, model_predict, rng):
"""Calculate loss."""
inputs, targets = batch
predictions = model_predict(inputs, params, rng=rng)
predictions, targets = _make_list(predictions, targets)
xent = []
for (pred, target) in zip(predictions, targets):
xent.append(np.sum(pred * layers.one_hot(targ... | [
"def",
"loss",
"(",
"params",
",",
"batch",
",",
"model_predict",
",",
"rng",
")",
":",
"inputs",
",",
"targets",
"=",
"batch",
"predictions",
"=",
"model_predict",
"(",
"inputs",
",",
"params",
",",
"rng",
"=",
"rng",
")",
"predictions",
",",
"targets",... | Calculate loss. | [
"Calculate",
"loss",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L104-L112 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/trax.py | restore_state | def restore_state(output_dir):
"""Restore State."""
params_file = os.path.join(output_dir, "model.pkl")
if not gfile.exists(params_file):
return State(step=None, params=None, history=trax_history.History())
with gfile.GFile(params_file, "rb") as f:
(params, step, history) = pickle.load(f)
log("Model ... | python | def restore_state(output_dir):
"""Restore State."""
params_file = os.path.join(output_dir, "model.pkl")
if not gfile.exists(params_file):
return State(step=None, params=None, history=trax_history.History())
with gfile.GFile(params_file, "rb") as f:
(params, step, history) = pickle.load(f)
log("Model ... | [
"def",
"restore_state",
"(",
"output_dir",
")",
":",
"params_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"\"model.pkl\"",
")",
"if",
"not",
"gfile",
".",
"exists",
"(",
"params_file",
")",
":",
"return",
"State",
"(",
"step",
"=",... | Restore State. | [
"Restore",
"State",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L129-L139 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/trax.py | save_state | def save_state(state, output_dir, keep=False):
"""Save State and optionally gin config."""
params_file = os.path.join(output_dir, "model.pkl")
with gfile.GFile(params_file, "wb") as f:
pickle.dump((state.params, state.step, state.history), f)
if keep:
params_file = os.path.join(output_dir, "model_{}.pkl... | python | def save_state(state, output_dir, keep=False):
"""Save State and optionally gin config."""
params_file = os.path.join(output_dir, "model.pkl")
with gfile.GFile(params_file, "wb") as f:
pickle.dump((state.params, state.step, state.history), f)
if keep:
params_file = os.path.join(output_dir, "model_{}.pkl... | [
"def",
"save_state",
"(",
"state",
",",
"output_dir",
",",
"keep",
"=",
"False",
")",
":",
"params_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"\"model.pkl\"",
")",
"with",
"gfile",
".",
"GFile",
"(",
"params_file",
",",
"\"wb\"",... | Save State and optionally gin config. | [
"Save",
"State",
"and",
"optionally",
"gin",
"config",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L152-L161 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/trax.py | evaluate_train_and_eval | def evaluate_train_and_eval(step, inputs, predict_fun, eval_steps, rng,
train_sw=None, eval_sw=None, history=None):
"""Evalaute on train and eval data, and log metrics."""
step_log(step, "Evaluation")
train_metrics, eval_metrics = [
evaluate( # pylint: disable=g-complex-comprehe... | python | def evaluate_train_and_eval(step, inputs, predict_fun, eval_steps, rng,
train_sw=None, eval_sw=None, history=None):
"""Evalaute on train and eval data, and log metrics."""
step_log(step, "Evaluation")
train_metrics, eval_metrics = [
evaluate( # pylint: disable=g-complex-comprehe... | [
"def",
"evaluate_train_and_eval",
"(",
"step",
",",
"inputs",
",",
"predict_fun",
",",
"eval_steps",
",",
"rng",
",",
"train_sw",
"=",
"None",
",",
"eval_sw",
"=",
"None",
",",
"history",
"=",
"None",
")",
":",
"step_log",
"(",
"step",
",",
"\"Evaluation\"... | Evalaute on train and eval data, and log metrics. | [
"Evalaute",
"on",
"train",
"and",
"eval",
"data",
"and",
"log",
"metrics",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L172-L189 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/trax.py | evaluate | def evaluate(inputs_stream, predict_fun, metric_funs, rng):
"""Evaluate.
Args:
inputs_stream: iterable of inputs to evaluate on.
predict_fun: function from inputs to predictions. params should already be
partially applied.
metric_funs: dict from metric name to metric function, which takes inputs
... | python | def evaluate(inputs_stream, predict_fun, metric_funs, rng):
"""Evaluate.
Args:
inputs_stream: iterable of inputs to evaluate on.
predict_fun: function from inputs to predictions. params should already be
partially applied.
metric_funs: dict from metric name to metric function, which takes inputs
... | [
"def",
"evaluate",
"(",
"inputs_stream",
",",
"predict_fun",
",",
"metric_funs",
",",
"rng",
")",
":",
"metrics",
"=",
"collections",
".",
"defaultdict",
"(",
"float",
")",
"count",
"=",
"0",
"for",
"inp",
"in",
"inputs_stream",
":",
"count",
"+=",
"1",
... | Evaluate.
Args:
inputs_stream: iterable of inputs to evaluate on.
predict_fun: function from inputs to predictions. params should already be
partially applied.
metric_funs: dict from metric name to metric function, which takes inputs
and predictions and returns a scalar metric value.
rng:... | [
"Evaluate",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L192-L215 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/trax.py | log_metrics | def log_metrics(metrics, summ_writer, log_prefix, step, history=None):
"""Log metrics to summary writer and history."""
rjust_len = max([len(name) for name in metrics])
for name, value in six.iteritems(metrics):
step_log(step, "%s %s | % .8f" % (
log_prefix.ljust(5), name.rjust(rjust_len), value))
... | python | def log_metrics(metrics, summ_writer, log_prefix, step, history=None):
"""Log metrics to summary writer and history."""
rjust_len = max([len(name) for name in metrics])
for name, value in six.iteritems(metrics):
step_log(step, "%s %s | % .8f" % (
log_prefix.ljust(5), name.rjust(rjust_len), value))
... | [
"def",
"log_metrics",
"(",
"metrics",
",",
"summ_writer",
",",
"log_prefix",
",",
"step",
",",
"history",
"=",
"None",
")",
":",
"rjust_len",
"=",
"max",
"(",
"[",
"len",
"(",
"name",
")",
"for",
"name",
"in",
"metrics",
"]",
")",
"for",
"name",
",",... | Log metrics to summary writer and history. | [
"Log",
"metrics",
"to",
"summary",
"writer",
"and",
"history",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L218-L228 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/trax.py | get_random_number_generator_and_set_seed | def get_random_number_generator_and_set_seed(seed=None):
"""Get a JAX random number generator and set random seed everywhere."""
random.seed(seed)
# While python random accepts None as seed and uses time/os seed then,
# some other functions expect integers so we create one here.
if seed is None:
seed = ra... | python | def get_random_number_generator_and_set_seed(seed=None):
"""Get a JAX random number generator and set random seed everywhere."""
random.seed(seed)
# While python random accepts None as seed and uses time/os seed then,
# some other functions expect integers so we create one here.
if seed is None:
seed = ra... | [
"def",
"get_random_number_generator_and_set_seed",
"(",
"seed",
"=",
"None",
")",
":",
"random",
".",
"seed",
"(",
"seed",
")",
"# While python random accepts None as seed and uses time/os seed then,",
"# some other functions expect integers so we create one here.",
"if",
"seed",
... | Get a JAX random number generator and set random seed everywhere. | [
"Get",
"a",
"JAX",
"random",
"number",
"generator",
"and",
"set",
"random",
"seed",
"everywhere",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L231-L240 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/trax.py | epochs | def epochs(steps=None, epoch_steps=1):
"""Iterator over epochs until steps is reached. 1-indexed.
Args:
steps: int, total number of steps. Infinite if None.
epoch_steps: int, number of steps per epoch. Can also be an iterable<int> to
enable variable length epochs.
Yields:
(epoch: int, epoch id... | python | def epochs(steps=None, epoch_steps=1):
"""Iterator over epochs until steps is reached. 1-indexed.
Args:
steps: int, total number of steps. Infinite if None.
epoch_steps: int, number of steps per epoch. Can also be an iterable<int> to
enable variable length epochs.
Yields:
(epoch: int, epoch id... | [
"def",
"epochs",
"(",
"steps",
"=",
"None",
",",
"epoch_steps",
"=",
"1",
")",
":",
"try",
":",
"iter",
"(",
"epoch_steps",
")",
"except",
"TypeError",
":",
"epoch_steps",
"=",
"itertools",
".",
"repeat",
"(",
"epoch_steps",
")",
"step",
"=",
"0",
"for... | Iterator over epochs until steps is reached. 1-indexed.
Args:
steps: int, total number of steps. Infinite if None.
epoch_steps: int, number of steps per epoch. Can also be an iterable<int> to
enable variable length epochs.
Yields:
(epoch: int, epoch id, epoch_steps: int, number of steps in this ... | [
"Iterator",
"over",
"epochs",
"until",
"steps",
"is",
"reached",
".",
"1",
"-",
"indexed",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L255-L277 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/trax.py | _jit_predict_fun | def _jit_predict_fun(model_predict, num_devices):
"""Use jit on model_predict if required."""
def predict(x, params=(), rng=None):
"""Predict function jited and parallelized as requested."""
# On one device, jit and run.
if num_devices == 1:
return backend.jit(model_predict)(x, params, rng=rng)
... | python | def _jit_predict_fun(model_predict, num_devices):
"""Use jit on model_predict if required."""
def predict(x, params=(), rng=None):
"""Predict function jited and parallelized as requested."""
# On one device, jit and run.
if num_devices == 1:
return backend.jit(model_predict)(x, params, rng=rng)
... | [
"def",
"_jit_predict_fun",
"(",
"model_predict",
",",
"num_devices",
")",
":",
"def",
"predict",
"(",
"x",
",",
"params",
"=",
"(",
")",
",",
"rng",
"=",
"None",
")",
":",
"\"\"\"Predict function jited and parallelized as requested.\"\"\"",
"# On one device, jit and r... | Use jit on model_predict if required. | [
"Use",
"jit",
"on",
"model_predict",
"if",
"required",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L280-L304 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/trax.py | _jit_update_fun | def _jit_update_fun(predict_fun, loss_fun, optimizer, lr_fun, num_devices):
"""Get jit-ed update function for loss, optimizer, learning rate function."""
if num_devices == 1: # TODO(lukaszkaiser): remove branch when not needed.
def single_update(i, opt_state, batch, rng):
rng, subrng = jax_random.split(r... | python | def _jit_update_fun(predict_fun, loss_fun, optimizer, lr_fun, num_devices):
"""Get jit-ed update function for loss, optimizer, learning rate function."""
if num_devices == 1: # TODO(lukaszkaiser): remove branch when not needed.
def single_update(i, opt_state, batch, rng):
rng, subrng = jax_random.split(r... | [
"def",
"_jit_update_fun",
"(",
"predict_fun",
",",
"loss_fun",
",",
"optimizer",
",",
"lr_fun",
",",
"num_devices",
")",
":",
"if",
"num_devices",
"==",
"1",
":",
"# TODO(lukaszkaiser): remove branch when not needed.",
"def",
"single_update",
"(",
"i",
",",
"opt_sta... | Get jit-ed update function for loss, optimizer, learning rate function. | [
"Get",
"jit",
"-",
"ed",
"update",
"function",
"for",
"loss",
"optimizer",
"learning",
"rate",
"function",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L307-L333 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/trax.py | _reshape_by_device_single | def _reshape_by_device_single(x, num_devices):
"""Reshape x into a shape [num_devices, ...]."""
x_shape = list(x.shape)
batch_size = x_shape[0]
batch_size_per_device = batch_size // num_devices
# We require that num_devices divides batch_size evenly.
if batch_size_per_device * num_devices != batch_size:
... | python | def _reshape_by_device_single(x, num_devices):
"""Reshape x into a shape [num_devices, ...]."""
x_shape = list(x.shape)
batch_size = x_shape[0]
batch_size_per_device = batch_size // num_devices
# We require that num_devices divides batch_size evenly.
if batch_size_per_device * num_devices != batch_size:
... | [
"def",
"_reshape_by_device_single",
"(",
"x",
",",
"num_devices",
")",
":",
"x_shape",
"=",
"list",
"(",
"x",
".",
"shape",
")",
"batch_size",
"=",
"x_shape",
"[",
"0",
"]",
"batch_size_per_device",
"=",
"batch_size",
"//",
"num_devices",
"# We require that num_... | Reshape x into a shape [num_devices, ...]. | [
"Reshape",
"x",
"into",
"a",
"shape",
"[",
"num_devices",
"...",
"]",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L336-L348 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/trax.py | reshape_by_device | def reshape_by_device(x, num_devices):
"""Reshape possibly nested x into a shape [num_devices, ...]."""
return layers.nested_map(
x, lambda x: _reshape_by_device_single(x, num_devices)) | python | def reshape_by_device(x, num_devices):
"""Reshape possibly nested x into a shape [num_devices, ...]."""
return layers.nested_map(
x, lambda x: _reshape_by_device_single(x, num_devices)) | [
"def",
"reshape_by_device",
"(",
"x",
",",
"num_devices",
")",
":",
"return",
"layers",
".",
"nested_map",
"(",
"x",
",",
"lambda",
"x",
":",
"_reshape_by_device_single",
"(",
"x",
",",
"num_devices",
")",
")"
] | Reshape possibly nested x into a shape [num_devices, ...]. | [
"Reshape",
"possibly",
"nested",
"x",
"into",
"a",
"shape",
"[",
"num_devices",
"...",
"]",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L351-L354 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/trax.py | train | def train(output_dir,
model=gin.REQUIRED,
loss_fun=loss,
inputs=trax_inputs.inputs,
optimizer=trax_opt.adam,
lr_schedule=lr.MultifactorSchedule,
train_steps=1000,
save_steps=None,
eval_steps=10,
eval_frequency=100,
num_d... | python | def train(output_dir,
model=gin.REQUIRED,
loss_fun=loss,
inputs=trax_inputs.inputs,
optimizer=trax_opt.adam,
lr_schedule=lr.MultifactorSchedule,
train_steps=1000,
save_steps=None,
eval_steps=10,
eval_frequency=100,
num_d... | [
"def",
"train",
"(",
"output_dir",
",",
"model",
"=",
"gin",
".",
"REQUIRED",
",",
"loss_fun",
"=",
"loss",
",",
"inputs",
"=",
"trax_inputs",
".",
"inputs",
",",
"optimizer",
"=",
"trax_opt",
".",
"adam",
",",
"lr_schedule",
"=",
"lr",
".",
"Multifactor... | Train the model on the inputs.
Args:
output_dir: Directory where to put the logs and checkpoints.
model: The model to train as a callable returning 2 callables, an init_fun
and apply_fun.
loss_fun: callable with signature: params, trax.inputs.Inputs, model, rng
-> loss.
inputs: callable r... | [
"Train",
"the",
"model",
"on",
"the",
"inputs",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L358-L532 | train |
tensorflow/tensor2tensor | tensor2tensor/keras/initializers.py | _compute_fans | def _compute_fans(shape):
"""Computes the number of input and output units for a weight shape.
Args:
shape: Integer shape tuple or TF tensor shape.
Returns:
A tuple of scalars (fan_in, fan_out).
"""
if len(shape) < 1: # Just to avoid errors for constants.
fan_in = fan_out = 1
elif len(shape) ... | python | def _compute_fans(shape):
"""Computes the number of input and output units for a weight shape.
Args:
shape: Integer shape tuple or TF tensor shape.
Returns:
A tuple of scalars (fan_in, fan_out).
"""
if len(shape) < 1: # Just to avoid errors for constants.
fan_in = fan_out = 1
elif len(shape) ... | [
"def",
"_compute_fans",
"(",
"shape",
")",
":",
"if",
"len",
"(",
"shape",
")",
"<",
"1",
":",
"# Just to avoid errors for constants.",
"fan_in",
"=",
"fan_out",
"=",
"1",
"elif",
"len",
"(",
"shape",
")",
"==",
"1",
":",
"fan_in",
"=",
"fan_out",
"=",
... | Computes the number of input and output units for a weight shape.
Args:
shape: Integer shape tuple or TF tensor shape.
Returns:
A tuple of scalars (fan_in, fan_out). | [
"Computes",
"the",
"number",
"of",
"input",
"and",
"output",
"units",
"for",
"a",
"weight",
"shape",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/keras/initializers.py#L32-L60 | train |
tensorflow/tensor2tensor | tensor2tensor/keras/initializers.py | get | def get(identifier, value=None):
"""Getter for loading from strings; returns value if can't load."""
if value is None:
value = identifier
if identifier is None:
return None
elif isinstance(identifier, dict):
try:
return deserialize(identifier)
except ValueError:
return value
elif i... | python | def get(identifier, value=None):
"""Getter for loading from strings; returns value if can't load."""
if value is None:
value = identifier
if identifier is None:
return None
elif isinstance(identifier, dict):
try:
return deserialize(identifier)
except ValueError:
return value
elif i... | [
"def",
"get",
"(",
"identifier",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"identifier",
"if",
"identifier",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"identifier",
",",
"dict",
")",
":",... | Getter for loading from strings; returns value if can't load. | [
"Getter",
"for",
"loading",
"from",
"strings",
";",
"returns",
"value",
"if",
"can",
"t",
"load",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/keras/initializers.py#L279-L298 | train |
tensorflow/tensor2tensor | tensor2tensor/envs/trajectory.py | Trajectory.add_time_step | def add_time_step(self, **create_time_step_kwargs):
"""Creates a time-step and appends it to the list.
Args:
**create_time_step_kwargs: Forwarded to
time_step.TimeStep.create_time_step.
"""
ts = time_step.TimeStep.create_time_step(**create_time_step_kwargs)
assert isinstance(ts, time_... | python | def add_time_step(self, **create_time_step_kwargs):
"""Creates a time-step and appends it to the list.
Args:
**create_time_step_kwargs: Forwarded to
time_step.TimeStep.create_time_step.
"""
ts = time_step.TimeStep.create_time_step(**create_time_step_kwargs)
assert isinstance(ts, time_... | [
"def",
"add_time_step",
"(",
"self",
",",
"*",
"*",
"create_time_step_kwargs",
")",
":",
"ts",
"=",
"time_step",
".",
"TimeStep",
".",
"create_time_step",
"(",
"*",
"*",
"create_time_step_kwargs",
")",
"assert",
"isinstance",
"(",
"ts",
",",
"time_step",
".",
... | Creates a time-step and appends it to the list.
Args:
**create_time_step_kwargs: Forwarded to
time_step.TimeStep.create_time_step. | [
"Creates",
"a",
"time",
"-",
"step",
"and",
"appends",
"it",
"to",
"the",
"list",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L42-L51 | train |
tensorflow/tensor2tensor | tensor2tensor/envs/trajectory.py | Trajectory.change_last_time_step | def change_last_time_step(self, **replace_time_step_kwargs):
"""Replace the last time-steps with the given kwargs."""
# Pre-conditions: self._time_steps shouldn't be empty.
assert self._time_steps
self._time_steps[-1] = self._time_steps[-1].replace(
**replace_time_step_kwargs) | python | def change_last_time_step(self, **replace_time_step_kwargs):
"""Replace the last time-steps with the given kwargs."""
# Pre-conditions: self._time_steps shouldn't be empty.
assert self._time_steps
self._time_steps[-1] = self._time_steps[-1].replace(
**replace_time_step_kwargs) | [
"def",
"change_last_time_step",
"(",
"self",
",",
"*",
"*",
"replace_time_step_kwargs",
")",
":",
"# Pre-conditions: self._time_steps shouldn't be empty.",
"assert",
"self",
".",
"_time_steps",
"self",
".",
"_time_steps",
"[",
"-",
"1",
"]",
"=",
"self",
".",
"_time... | Replace the last time-steps with the given kwargs. | [
"Replace",
"the",
"last",
"time",
"-",
"steps",
"with",
"the",
"given",
"kwargs",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L53-L59 | train |
tensorflow/tensor2tensor | tensor2tensor/envs/trajectory.py | Trajectory.reward | def reward(self):
"""Returns a tuple of sum of raw and processed rewards."""
raw_rewards, processed_rewards = 0, 0
for ts in self.time_steps:
# NOTE: raw_reward and processed_reward are None for the first time-step.
if ts.raw_reward is not None:
raw_rewards += ts.raw_reward
if ts.p... | python | def reward(self):
"""Returns a tuple of sum of raw and processed rewards."""
raw_rewards, processed_rewards = 0, 0
for ts in self.time_steps:
# NOTE: raw_reward and processed_reward are None for the first time-step.
if ts.raw_reward is not None:
raw_rewards += ts.raw_reward
if ts.p... | [
"def",
"reward",
"(",
"self",
")",
":",
"raw_rewards",
",",
"processed_rewards",
"=",
"0",
",",
"0",
"for",
"ts",
"in",
"self",
".",
"time_steps",
":",
"# NOTE: raw_reward and processed_reward are None for the first time-step.",
"if",
"ts",
".",
"raw_reward",
"is",
... | Returns a tuple of sum of raw and processed rewards. | [
"Returns",
"a",
"tuple",
"of",
"sum",
"of",
"raw",
"and",
"processed",
"rewards",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L85-L94 | train |
tensorflow/tensor2tensor | tensor2tensor/envs/trajectory.py | BatchTrajectory._complete_trajectory | def _complete_trajectory(self, trajectory, index):
"""Completes the given trajectory at the given index."""
assert isinstance(trajectory, Trajectory)
# This *should* be the case.
assert trajectory.last_time_step.action is None
# Add to completed trajectories.
self._completed_trajectories.appe... | python | def _complete_trajectory(self, trajectory, index):
"""Completes the given trajectory at the given index."""
assert isinstance(trajectory, Trajectory)
# This *should* be the case.
assert trajectory.last_time_step.action is None
# Add to completed trajectories.
self._completed_trajectories.appe... | [
"def",
"_complete_trajectory",
"(",
"self",
",",
"trajectory",
",",
"index",
")",
":",
"assert",
"isinstance",
"(",
"trajectory",
",",
"Trajectory",
")",
"# This *should* be the case.",
"assert",
"trajectory",
".",
"last_time_step",
".",
"action",
"is",
"None",
"#... | Completes the given trajectory at the given index. | [
"Completes",
"the",
"given",
"trajectory",
"at",
"the",
"given",
"index",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L133-L145 | train |
tensorflow/tensor2tensor | tensor2tensor/envs/trajectory.py | BatchTrajectory.reset | def reset(self, indices, observations):
"""Resets trajectories at given indices and populates observations.
Reset can either be called right at the beginning, when there are no
time-steps, or to reset a currently active trajectory.
If resetting a currently active trajectory then we save it in
self... | python | def reset(self, indices, observations):
"""Resets trajectories at given indices and populates observations.
Reset can either be called right at the beginning, when there are no
time-steps, or to reset a currently active trajectory.
If resetting a currently active trajectory then we save it in
self... | [
"def",
"reset",
"(",
"self",
",",
"indices",
",",
"observations",
")",
":",
"# Pre-conditions: indices, observations are np arrays.",
"# : indices is one-dimensional.",
"# : their first dimension (batch) is the same.",
"assert",
"isinstance",
"(",
"indices... | Resets trajectories at given indices and populates observations.
Reset can either be called right at the beginning, when there are no
time-steps, or to reset a currently active trajectory.
If resetting a currently active trajectory then we save it in
self._completed_trajectories.
Args:
indi... | [
"Resets",
"trajectories",
"at",
"given",
"indices",
"and",
"populates",
"observations",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L147-L192 | train |
tensorflow/tensor2tensor | tensor2tensor/envs/trajectory.py | BatchTrajectory.complete_all_trajectories | def complete_all_trajectories(self):
"""Essentially same as reset, but we don't have observations."""
for index in range(self.batch_size):
trajectory = self._trajectories[index]
assert trajectory.is_active
self._complete_trajectory(trajectory, index) | python | def complete_all_trajectories(self):
"""Essentially same as reset, but we don't have observations."""
for index in range(self.batch_size):
trajectory = self._trajectories[index]
assert trajectory.is_active
self._complete_trajectory(trajectory, index) | [
"def",
"complete_all_trajectories",
"(",
"self",
")",
":",
"for",
"index",
"in",
"range",
"(",
"self",
".",
"batch_size",
")",
":",
"trajectory",
"=",
"self",
".",
"_trajectories",
"[",
"index",
"]",
"assert",
"trajectory",
".",
"is_active",
"self",
".",
"... | Essentially same as reset, but we don't have observations. | [
"Essentially",
"same",
"as",
"reset",
"but",
"we",
"don",
"t",
"have",
"observations",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L194-L199 | train |
tensorflow/tensor2tensor | tensor2tensor/envs/trajectory.py | BatchTrajectory.step | def step(self, observations, raw_rewards, processed_rewards, dones, actions):
"""Record the information obtained from taking a step in all envs.
Records (observation, rewards, done) in a new time-step and actions in the
current time-step.
If any trajectory gets done, we move that trajectory to
com... | python | def step(self, observations, raw_rewards, processed_rewards, dones, actions):
"""Record the information obtained from taking a step in all envs.
Records (observation, rewards, done) in a new time-step and actions in the
current time-step.
If any trajectory gets done, we move that trajectory to
com... | [
"def",
"step",
"(",
"self",
",",
"observations",
",",
"raw_rewards",
",",
"processed_rewards",
",",
"dones",
",",
"actions",
")",
":",
"# Pre-conditions",
"assert",
"isinstance",
"(",
"observations",
",",
"np",
".",
"ndarray",
")",
"assert",
"isinstance",
"(",... | Record the information obtained from taking a step in all envs.
Records (observation, rewards, done) in a new time-step and actions in the
current time-step.
If any trajectory gets done, we move that trajectory to
completed_trajectories.
Args:
observations: ndarray of first dimension self.b... | [
"Record",
"the",
"information",
"obtained",
"from",
"taking",
"a",
"step",
"in",
"all",
"envs",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L201-L266 | train |
tensorflow/tensor2tensor | tensor2tensor/envs/trajectory.py | BatchTrajectory.num_time_steps | def num_time_steps(self):
"""Returns the number of time-steps in completed and incomplete trajectories."""
num_time_steps = sum(t.num_time_steps for t in self.trajectories)
return num_time_steps + self.num_completed_time_steps | python | def num_time_steps(self):
"""Returns the number of time-steps in completed and incomplete trajectories."""
num_time_steps = sum(t.num_time_steps for t in self.trajectories)
return num_time_steps + self.num_completed_time_steps | [
"def",
"num_time_steps",
"(",
"self",
")",
":",
"num_time_steps",
"=",
"sum",
"(",
"t",
".",
"num_time_steps",
"for",
"t",
"in",
"self",
".",
"trajectories",
")",
"return",
"num_time_steps",
"+",
"self",
".",
"num_completed_time_steps"
] | Returns the number of time-steps in completed and incomplete trajectories. | [
"Returns",
"the",
"number",
"of",
"time",
"-",
"steps",
"in",
"completed",
"and",
"incomplete",
"trajectories",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L275-L279 | train |
tensorflow/tensor2tensor | tensor2tensor/envs/trajectory.py | BatchTrajectory.observations_np | def observations_np(self, boundary=20):
"""Pads the observations in all the trajectories and returns them.
Args:
boundary: integer, Observations will be padded to (n * boundary) + 1 where
n is an integer.
Returns:
a tuple(padded_observations, time_steps), with shapes:
padded_ob... | python | def observations_np(self, boundary=20):
"""Pads the observations in all the trajectories and returns them.
Args:
boundary: integer, Observations will be padded to (n * boundary) + 1 where
n is an integer.
Returns:
a tuple(padded_observations, time_steps), with shapes:
padded_ob... | [
"def",
"observations_np",
"(",
"self",
",",
"boundary",
"=",
"20",
")",
":",
"list_observations_np_ts",
"=",
"[",
"t",
".",
"observations_np",
"for",
"t",
"in",
"self",
".",
"trajectories",
"]",
"# Every element in `list_observations_np_ts` is shaped (t,) + OBS",
"OBS... | Pads the observations in all the trajectories and returns them.
Args:
boundary: integer, Observations will be padded to (n * boundary) + 1 where
n is an integer.
Returns:
a tuple(padded_observations, time_steps), with shapes:
padded_observations: (self.batch_size, n * boundary + 1)... | [
"Pads",
"the",
"observations",
"in",
"all",
"the",
"trajectories",
"and",
"returns",
"them",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L286-L315 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/squad.py | _generate_examples | def _generate_examples(tmp_dir, dataset_split):
"""Generate squad examples.
Args:
tmp_dir: a string
dataset_split: problem.DatasetSplit.TRAIN or problem.DatasetSplit.EVAL
Yields:
dictionaries representing examples
"""
if dataset_split == problem.DatasetSplit.TRAIN:
file_name = _TRAINING_SET
... | python | def _generate_examples(tmp_dir, dataset_split):
"""Generate squad examples.
Args:
tmp_dir: a string
dataset_split: problem.DatasetSplit.TRAIN or problem.DatasetSplit.EVAL
Yields:
dictionaries representing examples
"""
if dataset_split == problem.DatasetSplit.TRAIN:
file_name = _TRAINING_SET
... | [
"def",
"_generate_examples",
"(",
"tmp_dir",
",",
"dataset_split",
")",
":",
"if",
"dataset_split",
"==",
"problem",
".",
"DatasetSplit",
".",
"TRAIN",
":",
"file_name",
"=",
"_TRAINING_SET",
"else",
":",
"file_name",
"=",
"_DEV_SET",
"squad_file",
"=",
"generat... | Generate squad examples.
Args:
tmp_dir: a string
dataset_split: problem.DatasetSplit.TRAIN or problem.DatasetSplit.EVAL
Yields:
dictionaries representing examples | [
"Generate",
"squad",
"examples",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/squad.py#L39-L85 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_transformer2.py | self_attention_layer | def self_attention_layer(hparams, prefix):
"""Create self-attention layer based on hyperparameters."""
return transformer_layers.SelfAttention(
num_heads=hparams.get(prefix + "num_heads"),
num_memory_heads=hparams.get(prefix + "num_memory_heads"),
key_value_size=hparams.d_kv,
shared_kv=hpara... | python | def self_attention_layer(hparams, prefix):
"""Create self-attention layer based on hyperparameters."""
return transformer_layers.SelfAttention(
num_heads=hparams.get(prefix + "num_heads"),
num_memory_heads=hparams.get(prefix + "num_memory_heads"),
key_value_size=hparams.d_kv,
shared_kv=hpara... | [
"def",
"self_attention_layer",
"(",
"hparams",
",",
"prefix",
")",
":",
"return",
"transformer_layers",
".",
"SelfAttention",
"(",
"num_heads",
"=",
"hparams",
".",
"get",
"(",
"prefix",
"+",
"\"num_heads\"",
")",
",",
"num_memory_heads",
"=",
"hparams",
".",
... | Create self-attention layer based on hyperparameters. | [
"Create",
"self",
"-",
"attention",
"layer",
"based",
"on",
"hyperparameters",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L311-L318 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_transformer2.py | local_self_attention_layer | def local_self_attention_layer(hparams, prefix):
"""Create self-attention layer based on hyperparameters."""
return transformer_layers.LocalSelfAttention(
num_heads=hparams.get(prefix + "num_heads"),
num_memory_heads=hparams.get(prefix + "num_memory_heads"),
radius=hparams.local_attention_radius,
... | python | def local_self_attention_layer(hparams, prefix):
"""Create self-attention layer based on hyperparameters."""
return transformer_layers.LocalSelfAttention(
num_heads=hparams.get(prefix + "num_heads"),
num_memory_heads=hparams.get(prefix + "num_memory_heads"),
radius=hparams.local_attention_radius,
... | [
"def",
"local_self_attention_layer",
"(",
"hparams",
",",
"prefix",
")",
":",
"return",
"transformer_layers",
".",
"LocalSelfAttention",
"(",
"num_heads",
"=",
"hparams",
".",
"get",
"(",
"prefix",
"+",
"\"num_heads\"",
")",
",",
"num_memory_heads",
"=",
"hparams"... | Create self-attention layer based on hyperparameters. | [
"Create",
"self",
"-",
"attention",
"layer",
"based",
"on",
"hyperparameters",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L322-L330 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_transformer2.py | layer_stack_from_hparams | def layer_stack_from_hparams(hparams, prefix):
"""Create a layer stack based on the hyperparameter values."""
layers = hparams.get(prefix + "layers")
return transformer.LayerStack(
[layers_registry[l](hparams, prefix) for l in layers],
dropout_rate=hparams.layer_prepostprocess_dropout,
norm_epsi... | python | def layer_stack_from_hparams(hparams, prefix):
"""Create a layer stack based on the hyperparameter values."""
layers = hparams.get(prefix + "layers")
return transformer.LayerStack(
[layers_registry[l](hparams, prefix) for l in layers],
dropout_rate=hparams.layer_prepostprocess_dropout,
norm_epsi... | [
"def",
"layer_stack_from_hparams",
"(",
"hparams",
",",
"prefix",
")",
":",
"layers",
"=",
"hparams",
".",
"get",
"(",
"prefix",
"+",
"\"layers\"",
")",
"return",
"transformer",
".",
"LayerStack",
"(",
"[",
"layers_registry",
"[",
"l",
"]",
"(",
"hparams",
... | Create a layer stack based on the hyperparameter values. | [
"Create",
"a",
"layer",
"stack",
"based",
"on",
"the",
"hyperparameter",
"values",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L366-L372 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_transformer2.py | mtf_unitransformer_base | def mtf_unitransformer_base():
"""Hyperparameters for single-stack Transformer."""
hparams = mtf_transformer2_base()
hparams.add_hparam("autoregressive", True)
# HYPERPARAMETERS FOR THE SINGLE LAYER STACK
hparams.add_hparam("layers", ["self_att", "drd"] * 6)
# number of heads in multihead attention
hparam... | python | def mtf_unitransformer_base():
"""Hyperparameters for single-stack Transformer."""
hparams = mtf_transformer2_base()
hparams.add_hparam("autoregressive", True)
# HYPERPARAMETERS FOR THE SINGLE LAYER STACK
hparams.add_hparam("layers", ["self_att", "drd"] * 6)
# number of heads in multihead attention
hparam... | [
"def",
"mtf_unitransformer_base",
"(",
")",
":",
"hparams",
"=",
"mtf_transformer2_base",
"(",
")",
"hparams",
".",
"add_hparam",
"(",
"\"autoregressive\"",
",",
"True",
")",
"# HYPERPARAMETERS FOR THE SINGLE LAYER STACK",
"hparams",
".",
"add_hparam",
"(",
"\"layers\""... | Hyperparameters for single-stack Transformer. | [
"Hyperparameters",
"for",
"single",
"-",
"stack",
"Transformer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L454-L469 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_transformer2.py | mtf_bitransformer_base | def mtf_bitransformer_base():
"""Machine translation base configuration."""
hparams = mtf_transformer2_base()
hparams.max_length = 256
hparams.shared_embedding = True
# HYPERPARAMETERS FOR THE LAYER STACKS
hparams.add_hparam("encoder_layers", ["self_att", "drd"] * 6)
hparams.add_hparam("decoder_layers", [... | python | def mtf_bitransformer_base():
"""Machine translation base configuration."""
hparams = mtf_transformer2_base()
hparams.max_length = 256
hparams.shared_embedding = True
# HYPERPARAMETERS FOR THE LAYER STACKS
hparams.add_hparam("encoder_layers", ["self_att", "drd"] * 6)
hparams.add_hparam("decoder_layers", [... | [
"def",
"mtf_bitransformer_base",
"(",
")",
":",
"hparams",
"=",
"mtf_transformer2_base",
"(",
")",
"hparams",
".",
"max_length",
"=",
"256",
"hparams",
".",
"shared_embedding",
"=",
"True",
"# HYPERPARAMETERS FOR THE LAYER STACKS",
"hparams",
".",
"add_hparam",
"(",
... | Machine translation base configuration. | [
"Machine",
"translation",
"base",
"configuration",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L473-L505 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_transformer2.py | mtf_bitransformer_tiny | def mtf_bitransformer_tiny():
"""Small encoder-decoder model for testing."""
hparams = mtf_bitransformer_base()
hparams.batch_size = 2
hparams.mesh_shape = ""
hparams.d_model = 128
hparams.encoder_layers = ["self_att", "drd"] * 2
hparams.decoder_layers = ["self_att", "enc_att", "drd"] * 2
hparams.num_he... | python | def mtf_bitransformer_tiny():
"""Small encoder-decoder model for testing."""
hparams = mtf_bitransformer_base()
hparams.batch_size = 2
hparams.mesh_shape = ""
hparams.d_model = 128
hparams.encoder_layers = ["self_att", "drd"] * 2
hparams.decoder_layers = ["self_att", "enc_att", "drd"] * 2
hparams.num_he... | [
"def",
"mtf_bitransformer_tiny",
"(",
")",
":",
"hparams",
"=",
"mtf_bitransformer_base",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"2",
"hparams",
".",
"mesh_shape",
"=",
"\"\"",
"hparams",
".",
"d_model",
"=",
"128",
"hparams",
".",
"encoder_layers",
"=",... | Small encoder-decoder model for testing. | [
"Small",
"encoder",
"-",
"decoder",
"model",
"for",
"testing",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L521-L531 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_transformer2.py | mtf_unitransformer_all_layers_tiny | def mtf_unitransformer_all_layers_tiny():
"""Test out all the layers on local CPU."""
hparams = mtf_unitransformer_tiny()
hparams.moe_num_experts = 4
hparams.moe_expert_x = 4
hparams.moe_expert_y = 4
hparams.moe_hidden_size = 512
hparams.layers = ["self_att", "local_self_att", "moe_1d", "moe_2d", "drd"]
... | python | def mtf_unitransformer_all_layers_tiny():
"""Test out all the layers on local CPU."""
hparams = mtf_unitransformer_tiny()
hparams.moe_num_experts = 4
hparams.moe_expert_x = 4
hparams.moe_expert_y = 4
hparams.moe_hidden_size = 512
hparams.layers = ["self_att", "local_self_att", "moe_1d", "moe_2d", "drd"]
... | [
"def",
"mtf_unitransformer_all_layers_tiny",
"(",
")",
":",
"hparams",
"=",
"mtf_unitransformer_tiny",
"(",
")",
"hparams",
".",
"moe_num_experts",
"=",
"4",
"hparams",
".",
"moe_expert_x",
"=",
"4",
"hparams",
".",
"moe_expert_y",
"=",
"4",
"hparams",
".",
"moe... | Test out all the layers on local CPU. | [
"Test",
"out",
"all",
"the",
"layers",
"on",
"local",
"CPU",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L535-L543 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_transformer2.py | mtf_bitransformer_all_layers_tiny | def mtf_bitransformer_all_layers_tiny():
"""Test out all the layers on local CPU."""
hparams = mtf_bitransformer_tiny()
hparams.moe_num_experts = 4
hparams.moe_expert_x = 4
hparams.moe_expert_y = 4
hparams.moe_hidden_size = 512
hparams.encoder_layers = [
"self_att", "local_self_att", "moe_1d", "moe_... | python | def mtf_bitransformer_all_layers_tiny():
"""Test out all the layers on local CPU."""
hparams = mtf_bitransformer_tiny()
hparams.moe_num_experts = 4
hparams.moe_expert_x = 4
hparams.moe_expert_y = 4
hparams.moe_hidden_size = 512
hparams.encoder_layers = [
"self_att", "local_self_att", "moe_1d", "moe_... | [
"def",
"mtf_bitransformer_all_layers_tiny",
"(",
")",
":",
"hparams",
"=",
"mtf_bitransformer_tiny",
"(",
")",
"hparams",
".",
"moe_num_experts",
"=",
"4",
"hparams",
".",
"moe_expert_x",
"=",
"4",
"hparams",
".",
"moe_expert_y",
"=",
"4",
"hparams",
".",
"moe_h... | Test out all the layers on local CPU. | [
"Test",
"out",
"all",
"the",
"layers",
"on",
"local",
"CPU",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L547-L558 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_transformer2.py | mtr_lm_dense | def mtr_lm_dense(sz):
"""Series of architectures for language modeling.
We assume infinite training data, so no dropout necessary.
You can use languagemodel_wiki_noref_v32k_l1k.
(1 epoch = ~46000 steps).
TODO(noam): find a large enough dataset for these experiments.
Args:
sz: an integer
Returns:
... | python | def mtr_lm_dense(sz):
"""Series of architectures for language modeling.
We assume infinite training data, so no dropout necessary.
You can use languagemodel_wiki_noref_v32k_l1k.
(1 epoch = ~46000 steps).
TODO(noam): find a large enough dataset for these experiments.
Args:
sz: an integer
Returns:
... | [
"def",
"mtr_lm_dense",
"(",
"sz",
")",
":",
"n",
"=",
"2",
"**",
"sz",
"hparams",
"=",
"mtf_unitransformer_base",
"(",
")",
"hparams",
".",
"d_model",
"=",
"1024",
"hparams",
".",
"max_length",
"=",
"1024",
"hparams",
".",
"batch_size",
"=",
"128",
"# Pa... | Series of architectures for language modeling.
We assume infinite training data, so no dropout necessary.
You can use languagemodel_wiki_noref_v32k_l1k.
(1 epoch = ~46000 steps).
TODO(noam): find a large enough dataset for these experiments.
Args:
sz: an integer
Returns:
a hparams | [
"Series",
"of",
"architectures",
"for",
"language",
"modeling",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L562-L590 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_transformer2.py | mtr_lm_v1 | def mtr_lm_v1():
"""Model incorporating mixture-of-experts, local and global attention.
~6B parameters
32 experts in 3 hierarchichal moe layers.
Returns:
a hparams
"""
hparams = mtr_lm_dense(0)
hparams.layers = (["local_self_att", "local_self_att", "drd",
"self_att", "drd", "lo... | python | def mtr_lm_v1():
"""Model incorporating mixture-of-experts, local and global attention.
~6B parameters
32 experts in 3 hierarchichal moe layers.
Returns:
a hparams
"""
hparams = mtr_lm_dense(0)
hparams.layers = (["local_self_att", "local_self_att", "drd",
"self_att", "drd", "lo... | [
"def",
"mtr_lm_v1",
"(",
")",
":",
"hparams",
"=",
"mtr_lm_dense",
"(",
"0",
")",
"hparams",
".",
"layers",
"=",
"(",
"[",
"\"local_self_att\"",
",",
"\"local_self_att\"",
",",
"\"drd\"",
",",
"\"self_att\"",
",",
"\"drd\"",
",",
"\"local_self_att\"",
",",
"... | Model incorporating mixture-of-experts, local and global attention.
~6B parameters
32 experts in 3 hierarchichal moe layers.
Returns:
a hparams | [
"Model",
"incorporating",
"mixture",
"-",
"of",
"-",
"experts",
"local",
"and",
"global",
"attention",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L626-L649 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_transformer2.py | mtr_tr_dense | def mtr_tr_dense(sz):
"""Series of machine translation models.
All models are trained on sequences of 256 tokens.
You can use the dataset translate_enfr_wmt32k_packed.
154000 steps = 3 epochs.
Args:
sz: an integer
Returns:
a hparams
"""
n = 2 ** sz
hparams = mtf_bitransformer_base()
hpar... | python | def mtr_tr_dense(sz):
"""Series of machine translation models.
All models are trained on sequences of 256 tokens.
You can use the dataset translate_enfr_wmt32k_packed.
154000 steps = 3 epochs.
Args:
sz: an integer
Returns:
a hparams
"""
n = 2 ** sz
hparams = mtf_bitransformer_base()
hpar... | [
"def",
"mtr_tr_dense",
"(",
"sz",
")",
":",
"n",
"=",
"2",
"**",
"sz",
"hparams",
"=",
"mtf_bitransformer_base",
"(",
")",
"hparams",
".",
"d_model",
"=",
"1024",
"hparams",
".",
"max_length",
"=",
"256",
"hparams",
".",
"batch_size",
"=",
"128",
"hparam... | Series of machine translation models.
All models are trained on sequences of 256 tokens.
You can use the dataset translate_enfr_wmt32k_packed.
154000 steps = 3 epochs.
Args:
sz: an integer
Returns:
a hparams | [
"Series",
"of",
"machine",
"translation",
"models",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L660-L691 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_transformer2.py | mtr_tr_dense_local | def mtr_tr_dense_local(sz):
"""With local self-attention in the decoder."""
hparams = mtr_tr_dense(sz)
hparams.decoder_layers = ["local_self_att", "enc_att", "drd"] * 6
hparams.local_attention_radius = 32
return hparams | python | def mtr_tr_dense_local(sz):
"""With local self-attention in the decoder."""
hparams = mtr_tr_dense(sz)
hparams.decoder_layers = ["local_self_att", "enc_att", "drd"] * 6
hparams.local_attention_radius = 32
return hparams | [
"def",
"mtr_tr_dense_local",
"(",
"sz",
")",
":",
"hparams",
"=",
"mtr_tr_dense",
"(",
"sz",
")",
"hparams",
".",
"decoder_layers",
"=",
"[",
"\"local_self_att\"",
",",
"\"enc_att\"",
",",
"\"drd\"",
"]",
"*",
"6",
"hparams",
".",
"local_attention_radius",
"="... | With local self-attention in the decoder. | [
"With",
"local",
"self",
"-",
"attention",
"in",
"the",
"decoder",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L734-L739 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/vqa_recurrent_self_attention.py | recurrent_transformer_decoder | def recurrent_transformer_decoder(
decoder_input,
encoder_output,
decoder_self_attention_bias,
encoder_decoder_attention_bias,
hparams,
name="decoder",
nonpadding=None,
save_weights_to=None,
make_image_summary=True):
"""Recurrent decoder function."""
x = decoder_input
attention... | python | def recurrent_transformer_decoder(
decoder_input,
encoder_output,
decoder_self_attention_bias,
encoder_decoder_attention_bias,
hparams,
name="decoder",
nonpadding=None,
save_weights_to=None,
make_image_summary=True):
"""Recurrent decoder function."""
x = decoder_input
attention... | [
"def",
"recurrent_transformer_decoder",
"(",
"decoder_input",
",",
"encoder_output",
",",
"decoder_self_attention_bias",
",",
"encoder_decoder_attention_bias",
",",
"hparams",
",",
"name",
"=",
"\"decoder\"",
",",
"nonpadding",
"=",
"None",
",",
"save_weights_to",
"=",
... | Recurrent decoder function. | [
"Recurrent",
"decoder",
"function",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/vqa_recurrent_self_attention.py#L138-L173 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/vqa_recurrent_self_attention.py | vqa_recurrent_self_attention_base | def vqa_recurrent_self_attention_base():
"""VQA attention baseline hparams."""
hparams = universal_transformer.universal_transformer_base()
hparams.batch_size = 1024
hparams.use_fixed_batch_size = True
hparams.weight_decay = 0.
hparams.clip_grad_norm = 0.
# use default initializer
# hparams.initializer ... | python | def vqa_recurrent_self_attention_base():
"""VQA attention baseline hparams."""
hparams = universal_transformer.universal_transformer_base()
hparams.batch_size = 1024
hparams.use_fixed_batch_size = True
hparams.weight_decay = 0.
hparams.clip_grad_norm = 0.
# use default initializer
# hparams.initializer ... | [
"def",
"vqa_recurrent_self_attention_base",
"(",
")",
":",
"hparams",
"=",
"universal_transformer",
".",
"universal_transformer_base",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"1024",
"hparams",
".",
"use_fixed_batch_size",
"=",
"True",
"hparams",
".",
"weight_dec... | VQA attention baseline hparams. | [
"VQA",
"attention",
"baseline",
"hparams",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/vqa_recurrent_self_attention.py#L177-L233 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_resnet.py | batch_norm_relu | def batch_norm_relu(inputs, is_training, relu=True):
"""Block of batch norm and relu."""
inputs = mtf.layers.batch_norm(
inputs,
is_training,
BATCH_NORM_DECAY,
epsilon=BATCH_NORM_EPSILON,
init_zero=(not relu))
if relu:
inputs = mtf.relu(inputs)
return inputs | python | def batch_norm_relu(inputs, is_training, relu=True):
"""Block of batch norm and relu."""
inputs = mtf.layers.batch_norm(
inputs,
is_training,
BATCH_NORM_DECAY,
epsilon=BATCH_NORM_EPSILON,
init_zero=(not relu))
if relu:
inputs = mtf.relu(inputs)
return inputs | [
"def",
"batch_norm_relu",
"(",
"inputs",
",",
"is_training",
",",
"relu",
"=",
"True",
")",
":",
"inputs",
"=",
"mtf",
".",
"layers",
".",
"batch_norm",
"(",
"inputs",
",",
"is_training",
",",
"BATCH_NORM_DECAY",
",",
"epsilon",
"=",
"BATCH_NORM_EPSILON",
",... | Block of batch norm and relu. | [
"Block",
"of",
"batch",
"norm",
"and",
"relu",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L38-L48 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_resnet.py | bottleneck_block | def bottleneck_block(inputs,
filters,
is_training,
strides,
projection_shortcut=None,
row_blocks_dim=None,
col_blocks_dim=None):
"""Bottleneck block variant for residual networks with BN after... | python | def bottleneck_block(inputs,
filters,
is_training,
strides,
projection_shortcut=None,
row_blocks_dim=None,
col_blocks_dim=None):
"""Bottleneck block variant for residual networks with BN after... | [
"def",
"bottleneck_block",
"(",
"inputs",
",",
"filters",
",",
"is_training",
",",
"strides",
",",
"projection_shortcut",
"=",
"None",
",",
"row_blocks_dim",
"=",
"None",
",",
"col_blocks_dim",
"=",
"None",
")",
":",
"shortcut",
"=",
"inputs",
"filter_h_dim",
... | Bottleneck block variant for residual networks with BN after convolutions.
Args:
inputs: a `mtf.Tensor` of shape
`[batch_dim, row_blocks, col_blocks, rows, cols, in_channels]`.
filters: `int` number of filters for the first two convolutions. Note
that the third and final convolution will use ... | [
"Bottleneck",
"block",
"variant",
"for",
"residual",
"networks",
"with",
"BN",
"after",
"convolutions",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L51-L142 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_resnet.py | block_layer | def block_layer(inputs,
filters,
blocks,
strides,
is_training,
name,
row_blocks_dim=None,
col_blocks_dim=None):
"""Creates one layer of blocks for the ResNet model.
Args:
inputs: `Tensor` of size `[b... | python | def block_layer(inputs,
filters,
blocks,
strides,
is_training,
name,
row_blocks_dim=None,
col_blocks_dim=None):
"""Creates one layer of blocks for the ResNet model.
Args:
inputs: `Tensor` of size `[b... | [
"def",
"block_layer",
"(",
"inputs",
",",
"filters",
",",
"blocks",
",",
"strides",
",",
"is_training",
",",
"name",
",",
"row_blocks_dim",
"=",
"None",
",",
"col_blocks_dim",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
... | Creates one layer of blocks for the ResNet model.
Args:
inputs: `Tensor` of size `[batch, channels, height, width]`.
filters: `int` number of filters for the first convolution of the layer.
blocks: `int` number of blocks contained in the layer.
strides: `int` stride to use for the first convolution o... | [
"Creates",
"one",
"layer",
"of",
"blocks",
"for",
"the",
"ResNet",
"model",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L145-L204 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_resnet.py | mtf_resnet_base | def mtf_resnet_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.no_data_parallelism = True
hparams.use_fixed_batch_size = True
hparams.batch_size = 32
hparams.max_length = 3072
hparams.hidden_size = 256
hparams.label_smoothing = 0.0
# 8-way model-parallelism
hpa... | python | def mtf_resnet_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.no_data_parallelism = True
hparams.use_fixed_batch_size = True
hparams.batch_size = 32
hparams.max_length = 3072
hparams.hidden_size = 256
hparams.label_smoothing = 0.0
# 8-way model-parallelism
hpa... | [
"def",
"mtf_resnet_base",
"(",
")",
":",
"hparams",
"=",
"common_hparams",
".",
"basic_params1",
"(",
")",
"hparams",
".",
"no_data_parallelism",
"=",
"True",
"hparams",
".",
"use_fixed_batch_size",
"=",
"True",
"hparams",
".",
"batch_size",
"=",
"32",
"hparams"... | Set of hyperparameters. | [
"Set",
"of",
"hyperparameters",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L333-L376 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_resnet.py | mtf_resnet_tiny | def mtf_resnet_tiny():
"""Catch bugs locally..."""
hparams = mtf_resnet_base()
hparams.num_layers = 2
hparams.hidden_size = 64
hparams.filter_size = 64
hparams.batch_size = 16
# data parallelism and model-parallelism
hparams.col_blocks = 1
hparams.mesh_shape = "batch:2"
hparams.layout = "batch:batch... | python | def mtf_resnet_tiny():
"""Catch bugs locally..."""
hparams = mtf_resnet_base()
hparams.num_layers = 2
hparams.hidden_size = 64
hparams.filter_size = 64
hparams.batch_size = 16
# data parallelism and model-parallelism
hparams.col_blocks = 1
hparams.mesh_shape = "batch:2"
hparams.layout = "batch:batch... | [
"def",
"mtf_resnet_tiny",
"(",
")",
":",
"hparams",
"=",
"mtf_resnet_base",
"(",
")",
"hparams",
".",
"num_layers",
"=",
"2",
"hparams",
".",
"hidden_size",
"=",
"64",
"hparams",
".",
"filter_size",
"=",
"64",
"hparams",
".",
"batch_size",
"=",
"16",
"# da... | Catch bugs locally... | [
"Catch",
"bugs",
"locally",
"..."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L380-L393 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_resnet.py | mtf_resnet_single | def mtf_resnet_single():
"""Small single parameters."""
hparams = mtf_resnet_tiny()
hparams.mesh_shape = ""
hparams.layout = ""
hparams.hidden_size = 32
hparams.filter_size = 32
hparams.batch_size = 1
hparams.num_encoder_layers = 1
hparams.num_layers = 1
hparams.block_length = 16
return hparams | python | def mtf_resnet_single():
"""Small single parameters."""
hparams = mtf_resnet_tiny()
hparams.mesh_shape = ""
hparams.layout = ""
hparams.hidden_size = 32
hparams.filter_size = 32
hparams.batch_size = 1
hparams.num_encoder_layers = 1
hparams.num_layers = 1
hparams.block_length = 16
return hparams | [
"def",
"mtf_resnet_single",
"(",
")",
":",
"hparams",
"=",
"mtf_resnet_tiny",
"(",
")",
"hparams",
".",
"mesh_shape",
"=",
"\"\"",
"hparams",
".",
"layout",
"=",
"\"\"",
"hparams",
".",
"hidden_size",
"=",
"32",
"hparams",
".",
"filter_size",
"=",
"32",
"h... | Small single parameters. | [
"Small",
"single",
"parameters",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L397-L408 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_resnet.py | mtf_resnet_base_single | def mtf_resnet_base_single():
"""Small single parameters."""
hparams = mtf_resnet_base()
hparams.num_layers = 6
hparams.filter_size = 256
hparams.block_length = 128
hparams.mesh_shape = ""
hparams.layout = ""
return hparams | python | def mtf_resnet_base_single():
"""Small single parameters."""
hparams = mtf_resnet_base()
hparams.num_layers = 6
hparams.filter_size = 256
hparams.block_length = 128
hparams.mesh_shape = ""
hparams.layout = ""
return hparams | [
"def",
"mtf_resnet_base_single",
"(",
")",
":",
"hparams",
"=",
"mtf_resnet_base",
"(",
")",
"hparams",
".",
"num_layers",
"=",
"6",
"hparams",
".",
"filter_size",
"=",
"256",
"hparams",
".",
"block_length",
"=",
"128",
"hparams",
".",
"mesh_shape",
"=",
"\"... | Small single parameters. | [
"Small",
"single",
"parameters",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L412-L420 | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_resnet.py | mtf_resnet_base_cifar | def mtf_resnet_base_cifar():
"""Data parallel CIFAR parameters."""
hparams = mtf_resnet_base()
hparams.mesh_shape = "batch:32"
hparams.layoyt = "batch:batch"
hparams.batch_size = 8
hparams.num_layers = 12
hparams.block_length = 256
hparams.hidden_size = 512
hparams.filter_size = 2048
hparams.learnin... | python | def mtf_resnet_base_cifar():
"""Data parallel CIFAR parameters."""
hparams = mtf_resnet_base()
hparams.mesh_shape = "batch:32"
hparams.layoyt = "batch:batch"
hparams.batch_size = 8
hparams.num_layers = 12
hparams.block_length = 256
hparams.hidden_size = 512
hparams.filter_size = 2048
hparams.learnin... | [
"def",
"mtf_resnet_base_cifar",
"(",
")",
":",
"hparams",
"=",
"mtf_resnet_base",
"(",
")",
"hparams",
".",
"mesh_shape",
"=",
"\"batch:32\"",
"hparams",
".",
"layoyt",
"=",
"\"batch:batch\"",
"hparams",
".",
"batch_size",
"=",
"8",
"hparams",
".",
"num_layers",... | Data parallel CIFAR parameters. | [
"Data",
"parallel",
"CIFAR",
"parameters",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L424-L440 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer_util.py | universal_transformer_encoder | def universal_transformer_encoder(encoder_input,
encoder_self_attention_bias,
hparams,
name="encoder",
nonpadding=None,
save_weights_to=None,
... | python | def universal_transformer_encoder(encoder_input,
encoder_self_attention_bias,
hparams,
name="encoder",
nonpadding=None,
save_weights_to=None,
... | [
"def",
"universal_transformer_encoder",
"(",
"encoder_input",
",",
"encoder_self_attention_bias",
",",
"hparams",
",",
"name",
"=",
"\"encoder\"",
",",
"nonpadding",
"=",
"None",
",",
"save_weights_to",
"=",
"None",
",",
"make_image_summary",
"=",
"True",
")",
":",
... | Universal Transformer encoder function.
Prepares all the arguments and the inputs and passes it to a
universal_transformer_layer to encode the encoder_input.
Args:
encoder_input: a Tensor
encoder_self_attention_bias: bias Tensor for self-attention
(see common_attention.attention_bias())
hpara... | [
"Universal",
"Transformer",
"encoder",
"function",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L62-L128 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer_util.py | universal_transformer_layer | def universal_transformer_layer(x,
hparams,
ffn_unit,
attention_unit,
pad_remover=None):
"""Core function applying the universal transformer layer.
Args:
x: input
hparams: model h... | python | def universal_transformer_layer(x,
hparams,
ffn_unit,
attention_unit,
pad_remover=None):
"""Core function applying the universal transformer layer.
Args:
x: input
hparams: model h... | [
"def",
"universal_transformer_layer",
"(",
"x",
",",
"hparams",
",",
"ffn_unit",
",",
"attention_unit",
",",
"pad_remover",
"=",
"None",
")",
":",
"def",
"add_vanilla_transformer_layer",
"(",
"x",
",",
"num_layers",
",",
"name",
")",
":",
"\"\"\"Passes the input t... | Core function applying the universal transformer layer.
Args:
x: input
hparams: model hyper-parameters
ffn_unit: feed-forward unit
attention_unit: multi-head attention unit
pad_remover: to mask out padding in convolutional layers (efficiency).
Returns:
the output tensor, extra output (can... | [
"Core",
"function",
"applying",
"the",
"universal",
"transformer",
"layer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L194-L265 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer_util.py | get_ut_layer | def get_ut_layer(x,
hparams,
ffn_unit,
attention_unit,
pad_remover=None):
"""Provides the function that is used in universal transforemr steps.
Args:
x: input
hparams: model hyper-parameters
ffn_unit: feed-forward unit
attention_un... | python | def get_ut_layer(x,
hparams,
ffn_unit,
attention_unit,
pad_remover=None):
"""Provides the function that is used in universal transforemr steps.
Args:
x: input
hparams: model hyper-parameters
ffn_unit: feed-forward unit
attention_un... | [
"def",
"get_ut_layer",
"(",
"x",
",",
"hparams",
",",
"ffn_unit",
",",
"attention_unit",
",",
"pad_remover",
"=",
"None",
")",
":",
"if",
"hparams",
".",
"recurrence_type",
"==",
"\"basic\"",
":",
"ut_initializer",
"=",
"(",
"x",
",",
"x",
",",
"x",
")",... | Provides the function that is used in universal transforemr steps.
Args:
x: input
hparams: model hyper-parameters
ffn_unit: feed-forward unit
attention_unit: multi-head attention unit
pad_remover: to mask out padding in convolutional layers (efficiency).
Returns:
ut_function and the ut_ini... | [
"Provides",
"the",
"function",
"that",
"is",
"used",
"in",
"universal",
"transforemr",
"steps",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L268-L354 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer_util.py | transformer_encoder_ffn_unit | def transformer_encoder_ffn_unit(x,
hparams,
nonpadding_mask=None,
pad_remover=None):
"""Applies a feed-forward function which is parametrised for encoding.
Args:
x: input
hparams: model hyper-parameters
... | python | def transformer_encoder_ffn_unit(x,
hparams,
nonpadding_mask=None,
pad_remover=None):
"""Applies a feed-forward function which is parametrised for encoding.
Args:
x: input
hparams: model hyper-parameters
... | [
"def",
"transformer_encoder_ffn_unit",
"(",
"x",
",",
"hparams",
",",
"nonpadding_mask",
"=",
"None",
",",
"pad_remover",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"ffn\"",
")",
":",
"if",
"hparams",
".",
"transformer_ffn_type",
"==",
... | Applies a feed-forward function which is parametrised for encoding.
Args:
x: input
hparams: model hyper-parameters
nonpadding_mask: optional Tensor with shape [batch_size, encoder_length]
indicating what positions are not padding. This is used
to mask out padding in convoltutional layers. We ge... | [
"Applies",
"a",
"feed",
"-",
"forward",
"function",
"which",
"is",
"parametrised",
"for",
"encoding",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L357-L402 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer_util.py | transformer_encoder_attention_unit | def transformer_encoder_attention_unit(x,
hparams,
encoder_self_attention_bias,
attention_dropout_broadcast_dims,
save_weights_to=None,
... | python | def transformer_encoder_attention_unit(x,
hparams,
encoder_self_attention_bias,
attention_dropout_broadcast_dims,
save_weights_to=None,
... | [
"def",
"transformer_encoder_attention_unit",
"(",
"x",
",",
"hparams",
",",
"encoder_self_attention_bias",
",",
"attention_dropout_broadcast_dims",
",",
"save_weights_to",
"=",
"None",
",",
"make_image_summary",
"=",
"True",
")",
":",
"with",
"tf",
".",
"variable_scope"... | Applies multihead attention function which is parametrised for encoding.
Args:
x: input
hparams: model hyper-parameters
encoder_self_attention_bias: a bias tensor for use in encoder self-attention
attention_dropout_broadcast_dims: Fpr noise broadcasting in the dropout
layers to save memory duri... | [
"Applies",
"multihead",
"attention",
"function",
"which",
"is",
"parametrised",
"for",
"encoding",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L405-L446 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer_util.py | transformer_decoder_attention_unit | def transformer_decoder_attention_unit(x,
hparams,
encoder_output,
decoder_self_attention_bias,
encoder_decoder_attention_bias,
... | python | def transformer_decoder_attention_unit(x,
hparams,
encoder_output,
decoder_self_attention_bias,
encoder_decoder_attention_bias,
... | [
"def",
"transformer_decoder_attention_unit",
"(",
"x",
",",
"hparams",
",",
"encoder_output",
",",
"decoder_self_attention_bias",
",",
"encoder_decoder_attention_bias",
",",
"attention_dropout_broadcast_dims",
",",
"save_weights_to",
"=",
"None",
",",
"make_image_summary",
"=... | Applies multihead attention function which is parametrised for decoding.
Args:
x: input (decoder input)
hparams: model hyper-parameters
encoder_output: Encoder representation. [batch_size, input_length,
hidden_dim]
decoder_self_attention_bias: Bias and mask weights for decoder
self-attent... | [
"Applies",
"multihead",
"attention",
"function",
"which",
"is",
"parametrised",
"for",
"decoding",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L492-L556 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer_util.py | universal_transformer_basic | def universal_transformer_basic(layer_inputs,
step, hparams,
ffn_unit,
attention_unit):
"""Basic Universal Transformer.
This model is pretty similar to the vanilla transformer in which weights are
shared between layer... | python | def universal_transformer_basic(layer_inputs,
step, hparams,
ffn_unit,
attention_unit):
"""Basic Universal Transformer.
This model is pretty similar to the vanilla transformer in which weights are
shared between layer... | [
"def",
"universal_transformer_basic",
"(",
"layer_inputs",
",",
"step",
",",
"hparams",
",",
"ffn_unit",
",",
"attention_unit",
")",
":",
"state",
",",
"inputs",
",",
"memory",
"=",
"tf",
".",
"unstack",
"(",
"layer_inputs",
",",
"num",
"=",
"None",
",",
"... | Basic Universal Transformer.
This model is pretty similar to the vanilla transformer in which weights are
shared between layers. For some tasks, this simple idea brings a
generalization that is not achievable by playing with the size of the model
or drop_out parameters in the vanilla transformer.
Args:
... | [
"Basic",
"Universal",
"Transformer",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L559-L590 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer_util.py | universal_transformer_highway | def universal_transformer_highway(layer_inputs,
step, hparams,
ffn_unit,
attention_unit,
pad_remover=None):
"""Universal Transformer with highway connection.
It transforms the st... | python | def universal_transformer_highway(layer_inputs,
step, hparams,
ffn_unit,
attention_unit,
pad_remover=None):
"""Universal Transformer with highway connection.
It transforms the st... | [
"def",
"universal_transformer_highway",
"(",
"layer_inputs",
",",
"step",
",",
"hparams",
",",
"ffn_unit",
",",
"attention_unit",
",",
"pad_remover",
"=",
"None",
")",
":",
"state",
",",
"inputs",
",",
"memory",
"=",
"layer_inputs",
"new_state",
"=",
"step_prepr... | Universal Transformer with highway connection.
It transforms the state using a block contaaining sel-attention and transition
function and wrap the whole block with a highway connection.
(the new state is a combination of the state and the transformed-state
based on cary/transform gates.)
Interesting obse... | [
"Universal",
"Transformer",
"with",
"highway",
"connection",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L593-L682 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer_util.py | universal_transformer_depthwise_attention | def universal_transformer_depthwise_attention(layer_inputs,
step, hparams,
ffn_unit,
attention_unit):
"""universal_transformer with depth-wise attention.
It uses an attention me... | python | def universal_transformer_depthwise_attention(layer_inputs,
step, hparams,
ffn_unit,
attention_unit):
"""universal_transformer with depth-wise attention.
It uses an attention me... | [
"def",
"universal_transformer_depthwise_attention",
"(",
"layer_inputs",
",",
"step",
",",
"hparams",
",",
"ffn_unit",
",",
"attention_unit",
")",
":",
"_",
",",
"inputs",
",",
"memory",
"=",
"layer_inputs",
"all_states",
"=",
"memory",
"# add depth signal",
"if",
... | universal_transformer with depth-wise attention.
It uses an attention mechanism-flipped vertically-
over all the states from previous steps to generate the new_state.
Args:
layer_inputs:
- state: state
- memory: contains states from all the previous steps.
step: indicating number of steps ta... | [
"universal_transformer",
"with",
"depth",
"-",
"wise",
"attention",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L777-L832 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer_util.py | universal_transformer_with_gru_as_transition_function | def universal_transformer_with_gru_as_transition_function(
layer_inputs, step, hparams, ffn_unit, attention_unit, pad_remover=None):
"""Universal Transformer which uses a gru as transition function.
It's kind of like having a gru, filliped vertically next to the Universal
Transformer that controls the flow o... | python | def universal_transformer_with_gru_as_transition_function(
layer_inputs, step, hparams, ffn_unit, attention_unit, pad_remover=None):
"""Universal Transformer which uses a gru as transition function.
It's kind of like having a gru, filliped vertically next to the Universal
Transformer that controls the flow o... | [
"def",
"universal_transformer_with_gru_as_transition_function",
"(",
"layer_inputs",
",",
"step",
",",
"hparams",
",",
"ffn_unit",
",",
"attention_unit",
",",
"pad_remover",
"=",
"None",
")",
":",
"state",
",",
"unused_inputs",
",",
"unused_memory",
"=",
"tf",
".",
... | Universal Transformer which uses a gru as transition function.
It's kind of like having a gru, filliped vertically next to the Universal
Transformer that controls the flow of the information in depth,
over different steps of the Universal Transformer.
Args:
layer_inputs:
- state: state
- input... | [
"Universal",
"Transformer",
"which",
"uses",
"a",
"gru",
"as",
"transition",
"function",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L835-L924 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer_util.py | universal_transformer_with_lstm_as_transition_function | def universal_transformer_with_lstm_as_transition_function(
layer_inputs, step, hparams, ffn_unit, attention_unit, pad_remover=None):
"""Universal Transformer which uses a lstm as transition function.
It's kind of like having a lstm, filliped vertically next to the Universal
Transformer that controls the flo... | python | def universal_transformer_with_lstm_as_transition_function(
layer_inputs, step, hparams, ffn_unit, attention_unit, pad_remover=None):
"""Universal Transformer which uses a lstm as transition function.
It's kind of like having a lstm, filliped vertically next to the Universal
Transformer that controls the flo... | [
"def",
"universal_transformer_with_lstm_as_transition_function",
"(",
"layer_inputs",
",",
"step",
",",
"hparams",
",",
"ffn_unit",
",",
"attention_unit",
",",
"pad_remover",
"=",
"None",
")",
":",
"state",
",",
"unused_inputs",
",",
"memory",
"=",
"tf",
".",
"uns... | Universal Transformer which uses a lstm as transition function.
It's kind of like having a lstm, filliped vertically next to the Universal
Transformer that controls the flow of the information in depth,
over different steps of the Universal Transformer.
Args:
layer_inputs:
- state: state
- in... | [
"Universal",
"Transformer",
"which",
"uses",
"a",
"lstm",
"as",
"transition",
"function",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L927-L1037 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer_util.py | universal_transformer_act | def universal_transformer_act(x, hparams, ffn_unit, attention_unit):
"""ACT based models.
Implementations of all act models are based on craffel@'s cl/160711592.
(1) Basic AUT based on remainder-distribution ACT (position-wise).
(2) AUT with global halting probability (not position-wise).
(3) AUT with rando... | python | def universal_transformer_act(x, hparams, ffn_unit, attention_unit):
"""ACT based models.
Implementations of all act models are based on craffel@'s cl/160711592.
(1) Basic AUT based on remainder-distribution ACT (position-wise).
(2) AUT with global halting probability (not position-wise).
(3) AUT with rando... | [
"def",
"universal_transformer_act",
"(",
"x",
",",
"hparams",
",",
"ffn_unit",
",",
"attention_unit",
")",
":",
"if",
"hparams",
".",
"act_type",
"not",
"in",
"[",
"\"basic\"",
",",
"\"global\"",
",",
"\"random\"",
",",
"\"accumulated\"",
"]",
":",
"raise",
... | ACT based models.
Implementations of all act models are based on craffel@'s cl/160711592.
(1) Basic AUT based on remainder-distribution ACT (position-wise).
(2) AUT with global halting probability (not position-wise).
(3) AUT with random halting probability (not position-wise).
(4) AUT with final state as a... | [
"ACT",
"based",
"models",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L1040-L1212 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer_util.py | _ffn_layer_multi_inputs | def _ffn_layer_multi_inputs(inputs_list,
hparams,
ffn_layer_type="dense",
name="ffn",
kernel_initializer=None,
bias_initializer=None,
activation=None,
... | python | def _ffn_layer_multi_inputs(inputs_list,
hparams,
ffn_layer_type="dense",
name="ffn",
kernel_initializer=None,
bias_initializer=None,
activation=None,
... | [
"def",
"_ffn_layer_multi_inputs",
"(",
"inputs_list",
",",
"hparams",
",",
"ffn_layer_type",
"=",
"\"dense\"",
",",
"name",
"=",
"\"ffn\"",
",",
"kernel_initializer",
"=",
"None",
",",
"bias_initializer",
"=",
"None",
",",
"activation",
"=",
"None",
",",
"pad_re... | Implements a Feed-forward layer with multiple inputs, pad-removing, etc.
Args:
inputs_list: list of input tensors
hparams: hyper-parameters
ffn_layer_type: dense / dense_dropconnect/ dense_relu_dense
name: name
kernel_initializer: kernel initializer
bias_initializer: bias initializer
acti... | [
"Implements",
"a",
"Feed",
"-",
"forward",
"layer",
"with",
"multiple",
"inputs",
"pad",
"-",
"removing",
"etc",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L1215-L1326 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer_util.py | fill_memory_slot | def fill_memory_slot(memory, value, index):
"""Fills the memory slot at a particular index with the given value.
Args:
memory: a 4-d tensor [memory_size, batch, length, channel] containing
the state of all steps
value: a 3-d tensor [batch, length, channel] as the sate
index: integer in [0, memory... | python | def fill_memory_slot(memory, value, index):
"""Fills the memory slot at a particular index with the given value.
Args:
memory: a 4-d tensor [memory_size, batch, length, channel] containing
the state of all steps
value: a 3-d tensor [batch, length, channel] as the sate
index: integer in [0, memory... | [
"def",
"fill_memory_slot",
"(",
"memory",
",",
"value",
",",
"index",
")",
":",
"mask",
"=",
"tf",
".",
"to_float",
"(",
"tf",
".",
"one_hot",
"(",
"index",
",",
"tf",
".",
"shape",
"(",
"memory",
")",
"[",
"0",
"]",
")",
"[",
":",
",",
"None",
... | Fills the memory slot at a particular index with the given value.
Args:
memory: a 4-d tensor [memory_size, batch, length, channel] containing
the state of all steps
value: a 3-d tensor [batch, length, channel] as the sate
index: integer in [0, memory_size)
Returns:
filled memory | [
"Fills",
"the",
"memory",
"slot",
"at",
"a",
"particular",
"index",
"with",
"the",
"given",
"value",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L1329-L1346 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer_util.py | add_depth_embedding | def add_depth_embedding(x):
"""Add n-dimensional embedding as the depth embedding (timing signal).
Adds embeddings to represent the position of the step in the recurrent
tower.
Args:
x: a tensor with shape [max_step, batch, length, depth]
Returns:
a Tensor the same shape as x.
"""
x_shape = com... | python | def add_depth_embedding(x):
"""Add n-dimensional embedding as the depth embedding (timing signal).
Adds embeddings to represent the position of the step in the recurrent
tower.
Args:
x: a tensor with shape [max_step, batch, length, depth]
Returns:
a Tensor the same shape as x.
"""
x_shape = com... | [
"def",
"add_depth_embedding",
"(",
"x",
")",
":",
"x_shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"depth",
"=",
"x_shape",
"[",
"-",
"1",
"]",
"num_steps",
"=",
"x_shape",
"[",
"0",
"]",
"shape",
"=",
"[",
"num_steps",
",",
"1",
",... | Add n-dimensional embedding as the depth embedding (timing signal).
Adds embeddings to represent the position of the step in the recurrent
tower.
Args:
x: a tensor with shape [max_step, batch, length, depth]
Returns:
a Tensor the same shape as x. | [
"Add",
"n",
"-",
"dimensional",
"embedding",
"as",
"the",
"depth",
"embedding",
"(",
"timing",
"signal",
")",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L1349-L1373 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer_util.py | step_preprocess | def step_preprocess(x, step, hparams):
"""Preprocess the input at the beginning of each step.
Args:
x: input tensor
step: step
hparams: model hyper-parameters
Returns:
preprocessed input.
"""
original_channel_size = common_layers.shape_list(x)[-1]
if hparams.add_position_timing_signal:
... | python | def step_preprocess(x, step, hparams):
"""Preprocess the input at the beginning of each step.
Args:
x: input tensor
step: step
hparams: model hyper-parameters
Returns:
preprocessed input.
"""
original_channel_size = common_layers.shape_list(x)[-1]
if hparams.add_position_timing_signal:
... | [
"def",
"step_preprocess",
"(",
"x",
",",
"step",
",",
"hparams",
")",
":",
"original_channel_size",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"[",
"-",
"1",
"]",
"if",
"hparams",
".",
"add_position_timing_signal",
":",
"x",
"=",
"add_position_t... | Preprocess the input at the beginning of each step.
Args:
x: input tensor
step: step
hparams: model hyper-parameters
Returns:
preprocessed input. | [
"Preprocess",
"the",
"input",
"at",
"the",
"beginning",
"of",
"each",
"step",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L1376-L1405 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer_util.py | add_position_timing_signal | def add_position_timing_signal(x, step, hparams):
"""Add n-dimensional embedding as the position (horizontal) timing signal.
Args:
x: a tensor with shape [batch, length, depth]
step: step
hparams: model hyper parameters
Returns:
a Tensor with the same shape as x.
"""
if not hparams.positio... | python | def add_position_timing_signal(x, step, hparams):
"""Add n-dimensional embedding as the position (horizontal) timing signal.
Args:
x: a tensor with shape [batch, length, depth]
step: step
hparams: model hyper parameters
Returns:
a Tensor with the same shape as x.
"""
if not hparams.positio... | [
"def",
"add_position_timing_signal",
"(",
"x",
",",
"step",
",",
"hparams",
")",
":",
"if",
"not",
"hparams",
".",
"position_start_index",
":",
"index",
"=",
"0",
"elif",
"hparams",
".",
"position_start_index",
"==",
"\"random\"",
":",
"# Shift all positions rando... | Add n-dimensional embedding as the position (horizontal) timing signal.
Args:
x: a tensor with shape [batch, length, depth]
step: step
hparams: model hyper parameters
Returns:
a Tensor with the same shape as x. | [
"Add",
"n",
"-",
"dimensional",
"embedding",
"as",
"the",
"position",
"(",
"horizontal",
")",
"timing",
"signal",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L1408-L1455 | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/universal_transformer_util.py | add_step_timing_signal | def add_step_timing_signal(x, step, hparams):
"""Add n-dimensional embedding as the step (vertical) timing signal.
Args:
x: a tensor with shape [batch, length, depth]
step: step
hparams: model hyper parameters
Returns:
a Tensor with the same shape as x.
"""
if hparams.recurrence_type == "ac... | python | def add_step_timing_signal(x, step, hparams):
"""Add n-dimensional embedding as the step (vertical) timing signal.
Args:
x: a tensor with shape [batch, length, depth]
step: step
hparams: model hyper parameters
Returns:
a Tensor with the same shape as x.
"""
if hparams.recurrence_type == "ac... | [
"def",
"add_step_timing_signal",
"(",
"x",
",",
"step",
",",
"hparams",
")",
":",
"if",
"hparams",
".",
"recurrence_type",
"==",
"\"act\"",
":",
"num_steps",
"=",
"hparams",
".",
"act_max_steps",
"else",
":",
"num_steps",
"=",
"hparams",
".",
"num_rec_steps",
... | Add n-dimensional embedding as the step (vertical) timing signal.
Args:
x: a tensor with shape [batch, length, depth]
step: step
hparams: model hyper parameters
Returns:
a Tensor with the same shape as x. | [
"Add",
"n",
"-",
"dimensional",
"embedding",
"as",
"the",
"step",
"(",
"vertical",
")",
"timing",
"signal",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L1458-L1493 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wikisum/utils.py | wet_records_from_file_obj | def wet_records_from_file_obj(f, take_ownership=False):
"""Iterate through records in WET file object."""
while True:
record = WETRecord.read(f)
if record is None:
break
if not record.url:
continue
yield record
if take_ownership:
f.close() | python | def wet_records_from_file_obj(f, take_ownership=False):
"""Iterate through records in WET file object."""
while True:
record = WETRecord.read(f)
if record is None:
break
if not record.url:
continue
yield record
if take_ownership:
f.close() | [
"def",
"wet_records_from_file_obj",
"(",
"f",
",",
"take_ownership",
"=",
"False",
")",
":",
"while",
"True",
":",
"record",
"=",
"WETRecord",
".",
"read",
"(",
"f",
")",
"if",
"record",
"is",
"None",
":",
"break",
"if",
"not",
"record",
".",
"url",
":... | Iterate through records in WET file object. | [
"Iterate",
"through",
"records",
"in",
"WET",
"file",
"object",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/utils.py#L101-L115 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wikisum/utils.py | wet_records | def wet_records(wet_filepath):
"""Generate WETRecords from filepath."""
if wet_filepath.endswith('.gz'):
fopen = gzip.open
else:
fopen = tf.gfile.GFile
with fopen(wet_filepath) as f:
for record in wet_records_from_file_obj(f):
yield record | python | def wet_records(wet_filepath):
"""Generate WETRecords from filepath."""
if wet_filepath.endswith('.gz'):
fopen = gzip.open
else:
fopen = tf.gfile.GFile
with fopen(wet_filepath) as f:
for record in wet_records_from_file_obj(f):
yield record | [
"def",
"wet_records",
"(",
"wet_filepath",
")",
":",
"if",
"wet_filepath",
".",
"endswith",
"(",
"'.gz'",
")",
":",
"fopen",
"=",
"gzip",
".",
"open",
"else",
":",
"fopen",
"=",
"tf",
".",
"gfile",
".",
"GFile",
"with",
"fopen",
"(",
"wet_filepath",
")... | Generate WETRecords from filepath. | [
"Generate",
"WETRecords",
"from",
"filepath",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/utils.py#L118-L127 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wikisum/utils.py | filter_paragraph | def filter_paragraph(p):
"""Simple filter to remove obviously bad paragraphs (bad text extraction).
Note this needs to run very quickly as it is applied to every paragraph
in the corpus, so nothing fancy! This whole method should be linear
expected time in len(p).
Args:
p: string, paragraph
Returns:
... | python | def filter_paragraph(p):
"""Simple filter to remove obviously bad paragraphs (bad text extraction).
Note this needs to run very quickly as it is applied to every paragraph
in the corpus, so nothing fancy! This whole method should be linear
expected time in len(p).
Args:
p: string, paragraph
Returns:
... | [
"def",
"filter_paragraph",
"(",
"p",
")",
":",
"# Expect a minimum number of words.",
"tokens",
"=",
"p",
".",
"split",
"(",
")",
"if",
"len",
"(",
"tokens",
")",
"<",
"6",
":",
"return",
"True",
"# Require some letters.",
"if",
"not",
"re",
".",
"search",
... | Simple filter to remove obviously bad paragraphs (bad text extraction).
Note this needs to run very quickly as it is applied to every paragraph
in the corpus, so nothing fancy! This whole method should be linear
expected time in len(p).
Args:
p: string, paragraph
Returns:
True if we should remove t... | [
"Simple",
"filter",
"to",
"remove",
"obviously",
"bad",
"paragraphs",
"(",
"bad",
"text",
"extraction",
")",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/utils.py#L214-L254 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wikisum/utils.py | timing | def timing(name=''):
"""Log start, end, and duration."""
start = datetime.datetime.now()
timestamp = start.strftime('%H:%M')
tf.logging.info('Starting job [%s] at %s', name, timestamp)
yield
end = datetime.datetime.now()
timestamp = end.strftime('%H:%M')
tf.logging.info('Finished job [%s] at %s', name, ... | python | def timing(name=''):
"""Log start, end, and duration."""
start = datetime.datetime.now()
timestamp = start.strftime('%H:%M')
tf.logging.info('Starting job [%s] at %s', name, timestamp)
yield
end = datetime.datetime.now()
timestamp = end.strftime('%H:%M')
tf.logging.info('Finished job [%s] at %s', name, ... | [
"def",
"timing",
"(",
"name",
"=",
"''",
")",
":",
"start",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"timestamp",
"=",
"start",
".",
"strftime",
"(",
"'%H:%M'",
")",
"tf",
".",
"logging",
".",
"info",
"(",
"'Starting job [%s] at %s'",
",... | Log start, end, and duration. | [
"Log",
"start",
"end",
"and",
"duration",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/utils.py#L258-L269 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wikisum/utils.py | WETHeader.read | def read(cls, f):
"""Read header from file. Headers end with length and then 1 blank line."""
url = None
line = f.readline()
if not line:
# EOF
return None
while not line.startswith(cls.LENGTH_HEADER):
if line.startswith(cls.URI_HEADER):
url = line[len(cls.URI_HEADER):].st... | python | def read(cls, f):
"""Read header from file. Headers end with length and then 1 blank line."""
url = None
line = f.readline()
if not line:
# EOF
return None
while not line.startswith(cls.LENGTH_HEADER):
if line.startswith(cls.URI_HEADER):
url = line[len(cls.URI_HEADER):].st... | [
"def",
"read",
"(",
"cls",
",",
"f",
")",
":",
"url",
"=",
"None",
"line",
"=",
"f",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"# EOF",
"return",
"None",
"while",
"not",
"line",
".",
"startswith",
"(",
"cls",
".",
"LENGTH_HEADER",
")",
... | Read header from file. Headers end with length and then 1 blank line. | [
"Read",
"header",
"from",
"file",
".",
"Headers",
"end",
"with",
"length",
"and",
"then",
"1",
"blank",
"line",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/utils.py#L61-L80 | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wikisum/utils.py | WETRecord.read | def read(cls, f):
"""Read WETRecord from file. Records end with 2 blank lines."""
header = WETHeader.read(f)
if header is None:
# EOF
return None
content = f.read(header.length)
# Consume empty separators
f.readline()
f.readline()
return cls(header.url, content) | python | def read(cls, f):
"""Read WETRecord from file. Records end with 2 blank lines."""
header = WETHeader.read(f)
if header is None:
# EOF
return None
content = f.read(header.length)
# Consume empty separators
f.readline()
f.readline()
return cls(header.url, content) | [
"def",
"read",
"(",
"cls",
",",
"f",
")",
":",
"header",
"=",
"WETHeader",
".",
"read",
"(",
"f",
")",
"if",
"header",
"is",
"None",
":",
"# EOF",
"return",
"None",
"content",
"=",
"f",
".",
"read",
"(",
"header",
".",
"length",
")",
"# Consume emp... | Read WETRecord from file. Records end with 2 blank lines. | [
"Read",
"WETRecord",
"from",
"file",
".",
"Records",
"end",
"with",
"2",
"blank",
"lines",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/utils.py#L86-L98 | train |
tensorflow/tensor2tensor | tensor2tensor/trax/models/mlp.py | MLP | def MLP(num_hidden_layers=2,
hidden_size=512,
activation_fn=layers.Relu,
num_output_classes=10,
mode="train"):
"""Multi-layer feed-forward neural network with non-linear activations."""
del mode
cur_layers = [layers.Flatten()]
for _ in range(num_hidden_layers):
cur_layers += ... | python | def MLP(num_hidden_layers=2,
hidden_size=512,
activation_fn=layers.Relu,
num_output_classes=10,
mode="train"):
"""Multi-layer feed-forward neural network with non-linear activations."""
del mode
cur_layers = [layers.Flatten()]
for _ in range(num_hidden_layers):
cur_layers += ... | [
"def",
"MLP",
"(",
"num_hidden_layers",
"=",
"2",
",",
"hidden_size",
"=",
"512",
",",
"activation_fn",
"=",
"layers",
".",
"Relu",
",",
"num_output_classes",
"=",
"10",
",",
"mode",
"=",
"\"train\"",
")",
":",
"del",
"mode",
"cur_layers",
"=",
"[",
"lay... | Multi-layer feed-forward neural network with non-linear activations. | [
"Multi",
"-",
"layer",
"feed",
"-",
"forward",
"neural",
"network",
"with",
"non",
"-",
"linear",
"activations",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/models/mlp.py#L25-L36 | train |
tensorflow/tensor2tensor | tensor2tensor/envs/env_problem.py | EnvProblem._verify_same_spaces | def _verify_same_spaces(self):
"""Verifies that all the envs have the same observation and action space."""
# Pre-conditions: self._envs is initialized.
if self._envs is None:
raise ValueError("Environments not initialized.")
if not isinstance(self._envs, list):
tf.logging.warning("Not ch... | python | def _verify_same_spaces(self):
"""Verifies that all the envs have the same observation and action space."""
# Pre-conditions: self._envs is initialized.
if self._envs is None:
raise ValueError("Environments not initialized.")
if not isinstance(self._envs, list):
tf.logging.warning("Not ch... | [
"def",
"_verify_same_spaces",
"(",
"self",
")",
":",
"# Pre-conditions: self._envs is initialized.",
"if",
"self",
".",
"_envs",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Environments not initialized.\"",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_e... | Verifies that all the envs have the same observation and action space. | [
"Verifies",
"that",
"all",
"the",
"envs",
"have",
"the",
"same",
"observation",
"and",
"action",
"space",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L199-L235 | train |
tensorflow/tensor2tensor | tensor2tensor/envs/env_problem.py | EnvProblem.initialize_environments | def initialize_environments(self, batch_size=1):
"""Initializes the environments and trajectories.
Subclasses can override this if they don't want a default implementation
which initializes `batch_size` environments, but must take care to
initialize self._trajectories (this is checked in __init__ anywa... | python | def initialize_environments(self, batch_size=1):
"""Initializes the environments and trajectories.
Subclasses can override this if they don't want a default implementation
which initializes `batch_size` environments, but must take care to
initialize self._trajectories (this is checked in __init__ anywa... | [
"def",
"initialize_environments",
"(",
"self",
",",
"batch_size",
"=",
"1",
")",
":",
"assert",
"batch_size",
">=",
"1",
"self",
".",
"_batch_size",
"=",
"batch_size",
"self",
".",
"_envs",
"=",
"[",
"gym",
".",
"make",
"(",
"self",
".",
"base_env_name",
... | Initializes the environments and trajectories.
Subclasses can override this if they don't want a default implementation
which initializes `batch_size` environments, but must take care to
initialize self._trajectories (this is checked in __init__ anyways).
Args:
batch_size: (int) Number of `self.... | [
"Initializes",
"the",
"environments",
"and",
"trajectories",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L248-L295 | train |
tensorflow/tensor2tensor | tensor2tensor/envs/env_problem.py | EnvProblem.process_rewards | def process_rewards(self, rewards):
"""Clips, rounds, and changes to integer type.
Args:
rewards: numpy array of raw (float) rewards.
Returns:
processed_rewards: numpy array of np.int64
"""
min_reward, max_reward = self.reward_range
# Clips at min and max reward.
rewards = np... | python | def process_rewards(self, rewards):
"""Clips, rounds, and changes to integer type.
Args:
rewards: numpy array of raw (float) rewards.
Returns:
processed_rewards: numpy array of np.int64
"""
min_reward, max_reward = self.reward_range
# Clips at min and max reward.
rewards = np... | [
"def",
"process_rewards",
"(",
"self",
",",
"rewards",
")",
":",
"min_reward",
",",
"max_reward",
"=",
"self",
".",
"reward_range",
"# Clips at min and max reward.",
"rewards",
"=",
"np",
".",
"clip",
"(",
"rewards",
",",
"min_reward",
",",
"max_reward",
")",
... | Clips, rounds, and changes to integer type.
Args:
rewards: numpy array of raw (float) rewards.
Returns:
processed_rewards: numpy array of np.int64 | [
"Clips",
"rounds",
"and",
"changes",
"to",
"integer",
"type",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L352-L368 | train |
tensorflow/tensor2tensor | tensor2tensor/envs/env_problem.py | EnvProblem.num_rewards | def num_rewards(self):
"""Returns the number of distinct rewards.
Returns:
Returns None if the reward range is infinite or the processed rewards
aren't discrete, otherwise returns the number of distinct rewards.
"""
# Pre-conditions: reward range is finite.
# : processed ... | python | def num_rewards(self):
"""Returns the number of distinct rewards.
Returns:
Returns None if the reward range is infinite or the processed rewards
aren't discrete, otherwise returns the number of distinct rewards.
"""
# Pre-conditions: reward range is finite.
# : processed ... | [
"def",
"num_rewards",
"(",
"self",
")",
":",
"# Pre-conditions: reward range is finite.",
"# : processed rewards are discrete.",
"if",
"not",
"self",
".",
"is_reward_range_finite",
":",
"tf",
".",
"logging",
".",
"error",
"(",
"\"Infinite reward range, `num_rewa... | Returns the number of distinct rewards.
Returns:
Returns None if the reward range is infinite or the processed rewards
aren't discrete, otherwise returns the number of distinct rewards. | [
"Returns",
"the",
"number",
"of",
"distinct",
"rewards",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L380-L399 | train |
tensorflow/tensor2tensor | tensor2tensor/envs/env_problem.py | EnvProblem._reset | def _reset(self, indices):
"""Resets environments at indices shouldn't pre-process or record.
Subclasses should override this to do the actual reset if something other
than the default implementation is desired.
Args:
indices: list of indices of underlying envs to call reset on.
Returns:
... | python | def _reset(self, indices):
"""Resets environments at indices shouldn't pre-process or record.
Subclasses should override this to do the actual reset if something other
than the default implementation is desired.
Args:
indices: list of indices of underlying envs to call reset on.
Returns:
... | [
"def",
"_reset",
"(",
"self",
",",
"indices",
")",
":",
"# Pre-conditions: common_preconditions, see `assert_common_preconditions`.",
"self",
".",
"assert_common_preconditions",
"(",
")",
"# This returns a numpy array with first dimension `len(indices)` and the",
"# rest being the dime... | Resets environments at indices shouldn't pre-process or record.
Subclasses should override this to do the actual reset if something other
than the default implementation is desired.
Args:
indices: list of indices of underlying envs to call reset on.
Returns:
np.ndarray of stacked observat... | [
"Resets",
"environments",
"at",
"indices",
"shouldn",
"t",
"pre",
"-",
"process",
"or",
"record",
"."
] | 272500b6efe353aeb638d2745ed56e519462ca31 | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L454-L472 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.