partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | restore_state | Restore State. | tensor2tensor/trax/trax.py | 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):
"""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 ... | [
"Restore",
"State",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L129-L139 | [
"def",
"restore_state",
"(",
"output_dir",
")",
":",
"params_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"\"model.pkl\"",
")",
"if",
"not",
"gfile",
".",
"exists",
"(",
"params_file",
")",
":",
"return",
"State",
"(",
"step",
"=",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | save_state | Save State and optionally gin config. | tensor2tensor/trax/trax.py | 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):
"""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... | [
"Save",
"State",
"and",
"optionally",
"gin",
"config",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L152-L161 | [
"def",
"save_state",
"(",
"state",
",",
"output_dir",
",",
"keep",
"=",
"False",
")",
":",
"params_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"\"model.pkl\"",
")",
"with",
"gfile",
".",
"GFile",
"(",
"params_file",
",",
"\"wb\"",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | evaluate_train_and_eval | Evalaute on train and eval data, and log metrics. | tensor2tensor/trax/trax.py | 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):
"""Evalaute on train and eval data, and log metrics."""
step_log(step, "Evaluation")
train_metrics, eval_metrics = [
evaluate( # pylint: disable=g-complex-comprehe... | [
"Evalaute",
"on",
"train",
"and",
"eval",
"data",
"and",
"log",
"metrics",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L172-L189 | [
"def",
"evaluate_train_and_eval",
"(",
"step",
",",
"inputs",
",",
"predict_fun",
",",
"eval_steps",
",",
"rng",
",",
"train_sw",
"=",
"None",
",",
"eval_sw",
"=",
"None",
",",
"history",
"=",
"None",
")",
":",
"step_log",
"(",
"step",
",",
"\"Evaluation\"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | evaluate | 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:... | tensor2tensor/trax/trax.py | 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):
"""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
... | [
"Evaluate",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L192-L215 | [
"def",
"evaluate",
"(",
"inputs_stream",
",",
"predict_fun",
",",
"metric_funs",
",",
"rng",
")",
":",
"metrics",
"=",
"collections",
".",
"defaultdict",
"(",
"float",
")",
"count",
"=",
"0",
"for",
"inp",
"in",
"inputs_stream",
":",
"count",
"+=",
"1",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | log_metrics | Log metrics to summary writer and history. | tensor2tensor/trax/trax.py | 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):
"""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))
... | [
"Log",
"metrics",
"to",
"summary",
"writer",
"and",
"history",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L218-L228 | [
"def",
"log_metrics",
"(",
"metrics",
",",
"summ_writer",
",",
"log_prefix",
",",
"step",
",",
"history",
"=",
"None",
")",
":",
"rjust_len",
"=",
"max",
"(",
"[",
"len",
"(",
"name",
")",
"for",
"name",
"in",
"metrics",
"]",
")",
"for",
"name",
",",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | get_random_number_generator_and_set_seed | Get a JAX random number generator and set random seed everywhere. | tensor2tensor/trax/trax.py | 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):
"""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... | [
"Get",
"a",
"JAX",
"random",
"number",
"generator",
"and",
"set",
"random",
"seed",
"everywhere",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L231-L240 | [
"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",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | epochs | 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 ... | tensor2tensor/trax/trax.py | 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):
"""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... | [
"Iterator",
"over",
"epochs",
"until",
"steps",
"is",
"reached",
".",
"1",
"-",
"indexed",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L255-L277 | [
"def",
"epochs",
"(",
"steps",
"=",
"None",
",",
"epoch_steps",
"=",
"1",
")",
":",
"try",
":",
"iter",
"(",
"epoch_steps",
")",
"except",
"TypeError",
":",
"epoch_steps",
"=",
"itertools",
".",
"repeat",
"(",
"epoch_steps",
")",
"step",
"=",
"0",
"for... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | _jit_predict_fun | Use jit on model_predict if required. | tensor2tensor/trax/trax.py | 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):
"""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)
... | [
"Use",
"jit",
"on",
"model_predict",
"if",
"required",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L280-L304 | [
"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... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | _jit_update_fun | Get jit-ed update function for loss, optimizer, learning rate function. | tensor2tensor/trax/trax.py | 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):
"""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... | [
"Get",
"jit",
"-",
"ed",
"update",
"function",
"for",
"loss",
"optimizer",
"learning",
"rate",
"function",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L307-L333 | [
"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... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | _reshape_by_device_single | Reshape x into a shape [num_devices, ...]. | tensor2tensor/trax/trax.py | 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):
"""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:
... | [
"Reshape",
"x",
"into",
"a",
"shape",
"[",
"num_devices",
"...",
"]",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L336-L348 | [
"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_... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | reshape_by_device | Reshape possibly nested x into a shape [num_devices, ...]. | tensor2tensor/trax/trax.py | 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):
"""Reshape possibly nested x into a shape [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",
"...",
"]",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L351-L354 | [
"def",
"reshape_by_device",
"(",
"x",
",",
"num_devices",
")",
":",
"return",
"layers",
".",
"nested_map",
"(",
"x",
",",
"lambda",
"x",
":",
"_reshape_by_device_single",
"(",
"x",
",",
"num_devices",
")",
")"
] | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | train | 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... | tensor2tensor/trax/trax.py | 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.MultifactorSchedule,
train_steps=1000,
save_steps=None,
eval_steps=10,
eval_frequency=100,
num_d... | [
"Train",
"the",
"model",
"on",
"the",
"inputs",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L358-L532 | [
"def",
"train",
"(",
"output_dir",
",",
"model",
"=",
"gin",
".",
"REQUIRED",
",",
"loss_fun",
"=",
"loss",
",",
"inputs",
"=",
"trax_inputs",
".",
"inputs",
",",
"optimizer",
"=",
"trax_opt",
".",
"adam",
",",
"lr_schedule",
"=",
"lr",
".",
"Multifactor... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | _compute_fans | 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). | tensor2tensor/keras/initializers.py | 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):
"""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) ... | [
"Computes",
"the",
"number",
"of",
"input",
"and",
"output",
"units",
"for",
"a",
"weight",
"shape",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/keras/initializers.py#L32-L60 | [
"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",
"=",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | get | Getter for loading from strings; returns value if can't load. | tensor2tensor/keras/initializers.py | 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):
"""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... | [
"Getter",
"for",
"loading",
"from",
"strings",
";",
"returns",
"value",
"if",
"can",
"t",
"load",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/keras/initializers.py#L279-L298 | [
"def",
"get",
"(",
"identifier",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"identifier",
"if",
"identifier",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"identifier",
",",
"dict",
")",
":",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | Trajectory.add_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. | tensor2tensor/envs/trajectory.py | 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):
"""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_... | [
"Creates",
"a",
"time",
"-",
"step",
"and",
"appends",
"it",
"to",
"the",
"list",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L42-L51 | [
"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",
".",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | Trajectory.change_last_time_step | Replace the last time-steps with the given kwargs. | tensor2tensor/envs/trajectory.py | 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):
"""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) | [
"Replace",
"the",
"last",
"time",
"-",
"steps",
"with",
"the",
"given",
"kwargs",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L53-L59 | [
"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... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | Trajectory.reward | Returns a tuple of sum of raw and processed rewards. | tensor2tensor/envs/trajectory.py | 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):
"""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... | [
"Returns",
"a",
"tuple",
"of",
"sum",
"of",
"raw",
"and",
"processed",
"rewards",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L85-L94 | [
"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",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | BatchTrajectory._complete_trajectory | Completes the given trajectory at the given index. | tensor2tensor/envs/trajectory.py | 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):
"""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... | [
"Completes",
"the",
"given",
"trajectory",
"at",
"the",
"given",
"index",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L133-L145 | [
"def",
"_complete_trajectory",
"(",
"self",
",",
"trajectory",
",",
"index",
")",
":",
"assert",
"isinstance",
"(",
"trajectory",
",",
"Trajectory",
")",
"# This *should* be the case.",
"assert",
"trajectory",
".",
"last_time_step",
".",
"action",
"is",
"None",
"#... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | BatchTrajectory.reset | 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... | tensor2tensor/envs/trajectory.py | 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):
"""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... | [
"Resets",
"trajectories",
"at",
"given",
"indices",
"and",
"populates",
"observations",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L147-L192 | [
"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... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | BatchTrajectory.complete_all_trajectories | Essentially same as reset, but we don't have observations. | tensor2tensor/envs/trajectory.py | 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):
"""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) | [
"Essentially",
"same",
"as",
"reset",
"but",
"we",
"don",
"t",
"have",
"observations",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L194-L199 | [
"def",
"complete_all_trajectories",
"(",
"self",
")",
":",
"for",
"index",
"in",
"range",
"(",
"self",
".",
"batch_size",
")",
":",
"trajectory",
"=",
"self",
".",
"_trajectories",
"[",
"index",
"]",
"assert",
"trajectory",
".",
"is_active",
"self",
".",
"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | BatchTrajectory.step | 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... | tensor2tensor/envs/trajectory.py | 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):
"""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... | [
"Record",
"the",
"information",
"obtained",
"from",
"taking",
"a",
"step",
"in",
"all",
"envs",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L201-L266 | [
"def",
"step",
"(",
"self",
",",
"observations",
",",
"raw_rewards",
",",
"processed_rewards",
",",
"dones",
",",
"actions",
")",
":",
"# Pre-conditions",
"assert",
"isinstance",
"(",
"observations",
",",
"np",
".",
"ndarray",
")",
"assert",
"isinstance",
"(",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | BatchTrajectory.num_time_steps | Returns the number of time-steps in completed and incomplete trajectories. | tensor2tensor/envs/trajectory.py | 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):
"""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 | [
"Returns",
"the",
"number",
"of",
"time",
"-",
"steps",
"in",
"completed",
"and",
"incomplete",
"trajectories",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L275-L279 | [
"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"
] | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | BatchTrajectory.observations_np | 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)... | tensor2tensor/envs/trajectory.py | 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):
"""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... | [
"Pads",
"the",
"observations",
"in",
"all",
"the",
"trajectories",
"and",
"returns",
"them",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L286-L315 | [
"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... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | _generate_examples | Generate squad examples.
Args:
tmp_dir: a string
dataset_split: problem.DatasetSplit.TRAIN or problem.DatasetSplit.EVAL
Yields:
dictionaries representing examples | tensor2tensor/data_generators/squad.py | 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):
"""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
... | [
"Generate",
"squad",
"examples",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/squad.py#L39-L85 | [
"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... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | self_attention_layer | Create self-attention layer based on hyperparameters. | tensor2tensor/models/mtf_transformer2.py | 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):
"""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... | [
"Create",
"self",
"-",
"attention",
"layer",
"based",
"on",
"hyperparameters",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L311-L318 | [
"def",
"self_attention_layer",
"(",
"hparams",
",",
"prefix",
")",
":",
"return",
"transformer_layers",
".",
"SelfAttention",
"(",
"num_heads",
"=",
"hparams",
".",
"get",
"(",
"prefix",
"+",
"\"num_heads\"",
")",
",",
"num_memory_heads",
"=",
"hparams",
".",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | local_self_attention_layer | Create self-attention layer based on hyperparameters. | tensor2tensor/models/mtf_transformer2.py | 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):
"""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,
... | [
"Create",
"self",
"-",
"attention",
"layer",
"based",
"on",
"hyperparameters",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L322-L330 | [
"def",
"local_self_attention_layer",
"(",
"hparams",
",",
"prefix",
")",
":",
"return",
"transformer_layers",
".",
"LocalSelfAttention",
"(",
"num_heads",
"=",
"hparams",
".",
"get",
"(",
"prefix",
"+",
"\"num_heads\"",
")",
",",
"num_memory_heads",
"=",
"hparams"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | layer_stack_from_hparams | Create a layer stack based on the hyperparameter values. | tensor2tensor/models/mtf_transformer2.py | 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):
"""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... | [
"Create",
"a",
"layer",
"stack",
"based",
"on",
"the",
"hyperparameter",
"values",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L366-L372 | [
"def",
"layer_stack_from_hparams",
"(",
"hparams",
",",
"prefix",
")",
":",
"layers",
"=",
"hparams",
".",
"get",
"(",
"prefix",
"+",
"\"layers\"",
")",
"return",
"transformer",
".",
"LayerStack",
"(",
"[",
"layers_registry",
"[",
"l",
"]",
"(",
"hparams",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | mtf_unitransformer_base | Hyperparameters for single-stack Transformer. | tensor2tensor/models/mtf_transformer2.py | 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():
"""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... | [
"Hyperparameters",
"for",
"single",
"-",
"stack",
"Transformer",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L454-L469 | [
"def",
"mtf_unitransformer_base",
"(",
")",
":",
"hparams",
"=",
"mtf_transformer2_base",
"(",
")",
"hparams",
".",
"add_hparam",
"(",
"\"autoregressive\"",
",",
"True",
")",
"# HYPERPARAMETERS FOR THE SINGLE LAYER STACK",
"hparams",
".",
"add_hparam",
"(",
"\"layers\""... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | mtf_bitransformer_base | Machine translation base configuration. | tensor2tensor/models/mtf_transformer2.py | 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():
"""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", [... | [
"Machine",
"translation",
"base",
"configuration",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L473-L505 | [
"def",
"mtf_bitransformer_base",
"(",
")",
":",
"hparams",
"=",
"mtf_transformer2_base",
"(",
")",
"hparams",
".",
"max_length",
"=",
"256",
"hparams",
".",
"shared_embedding",
"=",
"True",
"# HYPERPARAMETERS FOR THE LAYER STACKS",
"hparams",
".",
"add_hparam",
"(",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | mtf_bitransformer_tiny | Small encoder-decoder model for testing. | tensor2tensor/models/mtf_transformer2.py | 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():
"""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... | [
"Small",
"encoder",
"-",
"decoder",
"model",
"for",
"testing",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L521-L531 | [
"def",
"mtf_bitransformer_tiny",
"(",
")",
":",
"hparams",
"=",
"mtf_bitransformer_base",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"2",
"hparams",
".",
"mesh_shape",
"=",
"\"\"",
"hparams",
".",
"d_model",
"=",
"128",
"hparams",
".",
"encoder_layers",
"=",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | mtf_unitransformer_all_layers_tiny | Test out all the layers on local CPU. | tensor2tensor/models/mtf_transformer2.py | 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():
"""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"]
... | [
"Test",
"out",
"all",
"the",
"layers",
"on",
"local",
"CPU",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L535-L543 | [
"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... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | mtf_bitransformer_all_layers_tiny | Test out all the layers on local CPU. | tensor2tensor/models/mtf_transformer2.py | 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():
"""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_... | [
"Test",
"out",
"all",
"the",
"layers",
"on",
"local",
"CPU",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L547-L558 | [
"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... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | mtr_lm_dense | 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 | tensor2tensor/models/mtf_transformer2.py | 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):
"""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:
... | [
"Series",
"of",
"architectures",
"for",
"language",
"modeling",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L562-L590 | [
"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... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | mtr_lm_v1 | Model incorporating mixture-of-experts, local and global attention.
~6B parameters
32 experts in 3 hierarchichal moe layers.
Returns:
a hparams | tensor2tensor/models/mtf_transformer2.py | 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():
"""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... | [
"Model",
"incorporating",
"mixture",
"-",
"of",
"-",
"experts",
"local",
"and",
"global",
"attention",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L626-L649 | [
"def",
"mtr_lm_v1",
"(",
")",
":",
"hparams",
"=",
"mtr_lm_dense",
"(",
"0",
")",
"hparams",
".",
"layers",
"=",
"(",
"[",
"\"local_self_att\"",
",",
"\"local_self_att\"",
",",
"\"drd\"",
",",
"\"self_att\"",
",",
"\"drd\"",
",",
"\"local_self_att\"",
",",
"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | mtr_tr_dense | 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 | tensor2tensor/models/mtf_transformer2.py | 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):
"""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... | [
"Series",
"of",
"machine",
"translation",
"models",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L660-L691 | [
"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... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | mtr_tr_dense_local | With local self-attention in the decoder. | tensor2tensor/models/mtf_transformer2.py | 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):
"""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 | [
"With",
"local",
"self",
"-",
"attention",
"in",
"the",
"decoder",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L734-L739 | [
"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",
"="... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | recurrent_transformer_decoder | Recurrent decoder function. | tensor2tensor/models/research/vqa_recurrent_self_attention.py | 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=None,
make_image_summary=True):
"""Recurrent decoder function."""
x = decoder_input
attention... | [
"Recurrent",
"decoder",
"function",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/vqa_recurrent_self_attention.py#L138-L173 | [
"def",
"recurrent_transformer_decoder",
"(",
"decoder_input",
",",
"encoder_output",
",",
"decoder_self_attention_bias",
",",
"encoder_decoder_attention_bias",
",",
"hparams",
",",
"name",
"=",
"\"decoder\"",
",",
"nonpadding",
"=",
"None",
",",
"save_weights_to",
"=",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | vqa_recurrent_self_attention_base | VQA attention baseline hparams. | tensor2tensor/models/research/vqa_recurrent_self_attention.py | 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():
"""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 ... | [
"VQA",
"attention",
"baseline",
"hparams",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/vqa_recurrent_self_attention.py#L177-L233 | [
"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... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | batch_norm_relu | Block of batch norm and relu. | tensor2tensor/models/mtf_resnet.py | 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):
"""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 | [
"Block",
"of",
"batch",
"norm",
"and",
"relu",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L38-L48 | [
"def",
"batch_norm_relu",
"(",
"inputs",
",",
"is_training",
",",
"relu",
"=",
"True",
")",
":",
"inputs",
"=",
"mtf",
".",
"layers",
".",
"batch_norm",
"(",
"inputs",
",",
"is_training",
",",
"BATCH_NORM_DECAY",
",",
"epsilon",
"=",
"BATCH_NORM_EPSILON",
",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | bottleneck_block | 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 ... | tensor2tensor/models/mtf_resnet.py | 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):
"""Bottleneck block variant for residual networks with BN after... | [
"Bottleneck",
"block",
"variant",
"for",
"residual",
"networks",
"with",
"BN",
"after",
"convolutions",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L51-L142 | [
"def",
"bottleneck_block",
"(",
"inputs",
",",
"filters",
",",
"is_training",
",",
"strides",
",",
"projection_shortcut",
"=",
"None",
",",
"row_blocks_dim",
"=",
"None",
",",
"col_blocks_dim",
"=",
"None",
")",
":",
"shortcut",
"=",
"inputs",
"filter_h_dim",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | block_layer | 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... | tensor2tensor/models/mtf_resnet.py | 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):
"""Creates one layer of blocks for the ResNet model.
Args:
inputs: `Tensor` of size `[b... | [
"Creates",
"one",
"layer",
"of",
"blocks",
"for",
"the",
"ResNet",
"model",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L145-L204 | [
"def",
"block_layer",
"(",
"inputs",
",",
"filters",
",",
"blocks",
",",
"strides",
",",
"is_training",
",",
"name",
",",
"row_blocks_dim",
"=",
"None",
",",
"col_blocks_dim",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | mtf_resnet_base | Set of hyperparameters. | tensor2tensor/models/mtf_resnet.py | 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():
"""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... | [
"Set",
"of",
"hyperparameters",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L333-L376 | [
"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"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | mtf_resnet_tiny | Catch bugs locally... | tensor2tensor/models/mtf_resnet.py | 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():
"""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... | [
"Catch",
"bugs",
"locally",
"..."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L380-L393 | [
"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... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | mtf_resnet_single | Small single parameters. | tensor2tensor/models/mtf_resnet.py | 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():
"""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 | [
"Small",
"single",
"parameters",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L397-L408 | [
"def",
"mtf_resnet_single",
"(",
")",
":",
"hparams",
"=",
"mtf_resnet_tiny",
"(",
")",
"hparams",
".",
"mesh_shape",
"=",
"\"\"",
"hparams",
".",
"layout",
"=",
"\"\"",
"hparams",
".",
"hidden_size",
"=",
"32",
"hparams",
".",
"filter_size",
"=",
"32",
"h... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | mtf_resnet_base_single | Small single parameters. | tensor2tensor/models/mtf_resnet.py | 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():
"""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 | [
"Small",
"single",
"parameters",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L412-L420 | [
"def",
"mtf_resnet_base_single",
"(",
")",
":",
"hparams",
"=",
"mtf_resnet_base",
"(",
")",
"hparams",
".",
"num_layers",
"=",
"6",
"hparams",
".",
"filter_size",
"=",
"256",
"hparams",
".",
"block_length",
"=",
"128",
"hparams",
".",
"mesh_shape",
"=",
"\"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | mtf_resnet_base_cifar | Data parallel CIFAR parameters. | tensor2tensor/models/mtf_resnet.py | 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():
"""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... | [
"Data",
"parallel",
"CIFAR",
"parameters",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L424-L440 | [
"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",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | universal_transformer_encoder | 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... | tensor2tensor/models/research/universal_transformer_util.py | 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,
... | [
"Universal",
"Transformer",
"encoder",
"function",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L62-L128 | [
"def",
"universal_transformer_encoder",
"(",
"encoder_input",
",",
"encoder_self_attention_bias",
",",
"hparams",
",",
"name",
"=",
"\"encoder\"",
",",
"nonpadding",
"=",
"None",
",",
"save_weights_to",
"=",
"None",
",",
"make_image_summary",
"=",
"True",
")",
":",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | universal_transformer_layer | 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... | tensor2tensor/models/research/universal_transformer_util.py | 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):
"""Core function applying the universal transformer layer.
Args:
x: input
hparams: model h... | [
"Core",
"function",
"applying",
"the",
"universal",
"transformer",
"layer",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L194-L265 | [
"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... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | get_ut_layer | 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... | tensor2tensor/models/research/universal_transformer_util.py | 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):
"""Provides the function that is used in universal transforemr steps.
Args:
x: input
hparams: model hyper-parameters
ffn_unit: feed-forward unit
attention_un... | [
"Provides",
"the",
"function",
"that",
"is",
"used",
"in",
"universal",
"transforemr",
"steps",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L268-L354 | [
"def",
"get_ut_layer",
"(",
"x",
",",
"hparams",
",",
"ffn_unit",
",",
"attention_unit",
",",
"pad_remover",
"=",
"None",
")",
":",
"if",
"hparams",
".",
"recurrence_type",
"==",
"\"basic\"",
":",
"ut_initializer",
"=",
"(",
"x",
",",
"x",
",",
"x",
")",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | transformer_encoder_ffn_unit | 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... | tensor2tensor/models/research/universal_transformer_util.py | 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):
"""Applies a feed-forward function which is parametrised for encoding.
Args:
x: input
hparams: model hyper-parameters
... | [
"Applies",
"a",
"feed",
"-",
"forward",
"function",
"which",
"is",
"parametrised",
"for",
"encoding",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L357-L402 | [
"def",
"transformer_encoder_ffn_unit",
"(",
"x",
",",
"hparams",
",",
"nonpadding_mask",
"=",
"None",
",",
"pad_remover",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"ffn\"",
")",
":",
"if",
"hparams",
".",
"transformer_ffn_type",
"==",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | transformer_encoder_attention_unit | 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... | tensor2tensor/models/research/universal_transformer_util.py | 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,
... | [
"Applies",
"multihead",
"attention",
"function",
"which",
"is",
"parametrised",
"for",
"encoding",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L405-L446 | [
"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"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | transformer_decoder_attention_unit | 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... | tensor2tensor/models/research/universal_transformer_util.py | 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,
... | [
"Applies",
"multihead",
"attention",
"function",
"which",
"is",
"parametrised",
"for",
"decoding",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L492-L556 | [
"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",
"=... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | universal_transformer_basic | 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:
... | tensor2tensor/models/research/universal_transformer_util.py | 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):
"""Basic Universal Transformer.
This model is pretty similar to the vanilla transformer in which weights are
shared between layer... | [
"Basic",
"Universal",
"Transformer",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L559-L590 | [
"def",
"universal_transformer_basic",
"(",
"layer_inputs",
",",
"step",
",",
"hparams",
",",
"ffn_unit",
",",
"attention_unit",
")",
":",
"state",
",",
"inputs",
",",
"memory",
"=",
"tf",
".",
"unstack",
"(",
"layer_inputs",
",",
"num",
"=",
"None",
",",
"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | universal_transformer_highway | 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... | tensor2tensor/models/research/universal_transformer_util.py | 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):
"""Universal Transformer with highway connection.
It transforms the st... | [
"Universal",
"Transformer",
"with",
"highway",
"connection",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L593-L682 | [
"def",
"universal_transformer_highway",
"(",
"layer_inputs",
",",
"step",
",",
"hparams",
",",
"ffn_unit",
",",
"attention_unit",
",",
"pad_remover",
"=",
"None",
")",
":",
"state",
",",
"inputs",
",",
"memory",
"=",
"layer_inputs",
"new_state",
"=",
"step_prepr... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | universal_transformer_depthwise_attention | 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... | tensor2tensor/models/research/universal_transformer_util.py | 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):
"""universal_transformer with depth-wise attention.
It uses an attention me... | [
"universal_transformer",
"with",
"depth",
"-",
"wise",
"attention",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L777-L832 | [
"def",
"universal_transformer_depthwise_attention",
"(",
"layer_inputs",
",",
"step",
",",
"hparams",
",",
"ffn_unit",
",",
"attention_unit",
")",
":",
"_",
",",
"inputs",
",",
"memory",
"=",
"layer_inputs",
"all_states",
"=",
"memory",
"# add depth signal",
"if",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | universal_transformer_with_gru_as_transition_function | 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... | tensor2tensor/models/research/universal_transformer_util.py | 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):
"""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... | [
"Universal",
"Transformer",
"which",
"uses",
"a",
"gru",
"as",
"transition",
"function",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L835-L924 | [
"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",
".",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | universal_transformer_with_lstm_as_transition_function | 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... | tensor2tensor/models/research/universal_transformer_util.py | 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):
"""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... | [
"Universal",
"Transformer",
"which",
"uses",
"a",
"lstm",
"as",
"transition",
"function",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L927-L1037 | [
"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... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | universal_transformer_act | 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... | tensor2tensor/models/research/universal_transformer_util.py | 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):
"""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... | [
"ACT",
"based",
"models",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L1040-L1212 | [
"def",
"universal_transformer_act",
"(",
"x",
",",
"hparams",
",",
"ffn_unit",
",",
"attention_unit",
")",
":",
"if",
"hparams",
".",
"act_type",
"not",
"in",
"[",
"\"basic\"",
",",
"\"global\"",
",",
"\"random\"",
",",
"\"accumulated\"",
"]",
":",
"raise",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | _ffn_layer_multi_inputs | 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... | tensor2tensor/models/research/universal_transformer_util.py | 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,
... | [
"Implements",
"a",
"Feed",
"-",
"forward",
"layer",
"with",
"multiple",
"inputs",
"pad",
"-",
"removing",
"etc",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L1215-L1326 | [
"def",
"_ffn_layer_multi_inputs",
"(",
"inputs_list",
",",
"hparams",
",",
"ffn_layer_type",
"=",
"\"dense\"",
",",
"name",
"=",
"\"ffn\"",
",",
"kernel_initializer",
"=",
"None",
",",
"bias_initializer",
"=",
"None",
",",
"activation",
"=",
"None",
",",
"pad_re... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | fill_memory_slot | 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 | tensor2tensor/models/research/universal_transformer_util.py | 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):
"""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... | [
"Fills",
"the",
"memory",
"slot",
"at",
"a",
"particular",
"index",
"with",
"the",
"given",
"value",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L1329-L1346 | [
"def",
"fill_memory_slot",
"(",
"memory",
",",
"value",
",",
"index",
")",
":",
"mask",
"=",
"tf",
".",
"to_float",
"(",
"tf",
".",
"one_hot",
"(",
"index",
",",
"tf",
".",
"shape",
"(",
"memory",
")",
"[",
"0",
"]",
")",
"[",
":",
",",
"None",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | add_depth_embedding | 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. | tensor2tensor/models/research/universal_transformer_util.py | 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):
"""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... | [
"Add",
"n",
"-",
"dimensional",
"embedding",
"as",
"the",
"depth",
"embedding",
"(",
"timing",
"signal",
")",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L1349-L1373 | [
"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",
",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | step_preprocess | Preprocess the input at the beginning of each step.
Args:
x: input tensor
step: step
hparams: model hyper-parameters
Returns:
preprocessed input. | tensor2tensor/models/research/universal_transformer_util.py | 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):
"""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:
... | [
"Preprocess",
"the",
"input",
"at",
"the",
"beginning",
"of",
"each",
"step",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L1376-L1405 | [
"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... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | add_position_timing_signal | 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. | tensor2tensor/models/research/universal_transformer_util.py | 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):
"""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... | [
"Add",
"n",
"-",
"dimensional",
"embedding",
"as",
"the",
"position",
"(",
"horizontal",
")",
"timing",
"signal",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L1408-L1455 | [
"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... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | add_step_timing_signal | 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. | tensor2tensor/models/research/universal_transformer_util.py | 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):
"""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... | [
"Add",
"n",
"-",
"dimensional",
"embedding",
"as",
"the",
"step",
"(",
"vertical",
")",
"timing",
"signal",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L1458-L1493 | [
"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",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | wet_records_from_file_obj | Iterate through records in WET file object. | tensor2tensor/data_generators/wikisum/utils.py | 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):
"""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() | [
"Iterate",
"through",
"records",
"in",
"WET",
"file",
"object",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/utils.py#L101-L115 | [
"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",
":... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | wet_records | Generate WETRecords from filepath. | tensor2tensor/data_generators/wikisum/utils.py | 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):
"""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 | [
"Generate",
"WETRecords",
"from",
"filepath",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/utils.py#L118-L127 | [
"def",
"wet_records",
"(",
"wet_filepath",
")",
":",
"if",
"wet_filepath",
".",
"endswith",
"(",
"'.gz'",
")",
":",
"fopen",
"=",
"gzip",
".",
"open",
"else",
":",
"fopen",
"=",
"tf",
".",
"gfile",
".",
"GFile",
"with",
"fopen",
"(",
"wet_filepath",
")... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | filter_paragraph | 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... | tensor2tensor/data_generators/wikisum/utils.py | 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):
"""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:
... | [
"Simple",
"filter",
"to",
"remove",
"obviously",
"bad",
"paragraphs",
"(",
"bad",
"text",
"extraction",
")",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/utils.py#L214-L254 | [
"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",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | timing | Log start, end, and duration. | tensor2tensor/data_generators/wikisum/utils.py | 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=''):
"""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, ... | [
"Log",
"start",
"end",
"and",
"duration",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/utils.py#L258-L269 | [
"def",
"timing",
"(",
"name",
"=",
"''",
")",
":",
"start",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"timestamp",
"=",
"start",
".",
"strftime",
"(",
"'%H:%M'",
")",
"tf",
".",
"logging",
".",
"info",
"(",
"'Starting job [%s] at %s'",
",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | WETHeader.read | Read header from file. Headers end with length and then 1 blank line. | tensor2tensor/data_generators/wikisum/utils.py | 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):
"""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... | [
"Read",
"header",
"from",
"file",
".",
"Headers",
"end",
"with",
"length",
"and",
"then",
"1",
"blank",
"line",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/utils.py#L61-L80 | [
"def",
"read",
"(",
"cls",
",",
"f",
")",
":",
"url",
"=",
"None",
"line",
"=",
"f",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"# EOF",
"return",
"None",
"while",
"not",
"line",
".",
"startswith",
"(",
"cls",
".",
"LENGTH_HEADER",
")",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | WETRecord.read | Read WETRecord from file. Records end with 2 blank lines. | tensor2tensor/data_generators/wikisum/utils.py | 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):
"""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) | [
"Read",
"WETRecord",
"from",
"file",
".",
"Records",
"end",
"with",
"2",
"blank",
"lines",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/utils.py#L86-L98 | [
"def",
"read",
"(",
"cls",
",",
"f",
")",
":",
"header",
"=",
"WETHeader",
".",
"read",
"(",
"f",
")",
"if",
"header",
"is",
"None",
":",
"# EOF",
"return",
"None",
"content",
"=",
"f",
".",
"read",
"(",
"header",
".",
"length",
")",
"# Consume emp... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | MLP | Multi-layer feed-forward neural network with non-linear activations. | tensor2tensor/trax/models/mlp.py | 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"):
"""Multi-layer feed-forward neural network with non-linear activations."""
del mode
cur_layers = [layers.Flatten()]
for _ in range(num_hidden_layers):
cur_layers += ... | [
"Multi",
"-",
"layer",
"feed",
"-",
"forward",
"neural",
"network",
"with",
"non",
"-",
"linear",
"activations",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/models/mlp.py#L25-L36 | [
"def",
"MLP",
"(",
"num_hidden_layers",
"=",
"2",
",",
"hidden_size",
"=",
"512",
",",
"activation_fn",
"=",
"layers",
".",
"Relu",
",",
"num_output_classes",
"=",
"10",
",",
"mode",
"=",
"\"train\"",
")",
":",
"del",
"mode",
"cur_layers",
"=",
"[",
"lay... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | EnvProblem._verify_same_spaces | Verifies that all the envs have the same observation and action space. | tensor2tensor/envs/env_problem.py | 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):
"""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... | [
"Verifies",
"that",
"all",
"the",
"envs",
"have",
"the",
"same",
"observation",
"and",
"action",
"space",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L199-L235 | [
"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... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | EnvProblem.initialize_environments | 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.... | tensor2tensor/envs/env_problem.py | 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):
"""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... | [
"Initializes",
"the",
"environments",
"and",
"trajectories",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L248-L295 | [
"def",
"initialize_environments",
"(",
"self",
",",
"batch_size",
"=",
"1",
")",
":",
"assert",
"batch_size",
">=",
"1",
"self",
".",
"_batch_size",
"=",
"batch_size",
"self",
".",
"_envs",
"=",
"[",
"gym",
".",
"make",
"(",
"self",
".",
"base_env_name",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | EnvProblem.process_rewards | Clips, rounds, and changes to integer type.
Args:
rewards: numpy array of raw (float) rewards.
Returns:
processed_rewards: numpy array of np.int64 | tensor2tensor/envs/env_problem.py | 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):
"""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... | [
"Clips",
"rounds",
"and",
"changes",
"to",
"integer",
"type",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L352-L368 | [
"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",
")",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | EnvProblem.num_rewards | 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. | tensor2tensor/envs/env_problem.py | 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):
"""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 ... | [
"Returns",
"the",
"number",
"of",
"distinct",
"rewards",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L380-L399 | [
"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... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | EnvProblem._reset | 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... | tensor2tensor/envs/env_problem.py | 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):
"""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:
... | [
"Resets",
"environments",
"at",
"indices",
"shouldn",
"t",
"pre",
"-",
"process",
"or",
"record",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L454-L472 | [
"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... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | EnvProblem.reset | Resets environments at given indices.
Subclasses should override _reset to do the actual reset if something other
than the default implementation is desired.
Args:
indices: Indices of environments to reset. If None all envs are reset.
Returns:
Batch of initial observations of reset enviro... | tensor2tensor/envs/env_problem.py | def reset(self, indices=None):
"""Resets environments at given indices.
Subclasses should override _reset to do the actual reset if something other
than the default implementation is desired.
Args:
indices: Indices of environments to reset. If None all envs are reset.
Returns:
Batch o... | def reset(self, indices=None):
"""Resets environments at given indices.
Subclasses should override _reset to do the actual reset if something other
than the default implementation is desired.
Args:
indices: Indices of environments to reset. If None all envs are reset.
Returns:
Batch o... | [
"Resets",
"environments",
"at",
"given",
"indices",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L474-L502 | [
"def",
"reset",
"(",
"self",
",",
"indices",
"=",
"None",
")",
":",
"if",
"indices",
"is",
"None",
":",
"indices",
"=",
"np",
".",
"arange",
"(",
"self",
".",
"trajectories",
".",
"batch_size",
")",
"# If this is empty (not None) then don't do anything, no env w... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | EnvProblem._step | Takes a step in all environments, shouldn't pre-process or record.
Subclasses should override this to do the actual step if something other
than the default implementation is desired.
Args:
actions: (np.ndarray) with first dimension equal to the batch size.
Returns:
a tuple of stacked raw... | tensor2tensor/envs/env_problem.py | def _step(self, actions):
"""Takes a step in all environments, shouldn't pre-process or record.
Subclasses should override this to do the actual step if something other
than the default implementation is desired.
Args:
actions: (np.ndarray) with first dimension equal to the batch size.
Retu... | def _step(self, actions):
"""Takes a step in all environments, shouldn't pre-process or record.
Subclasses should override this to do the actual step if something other
than the default implementation is desired.
Args:
actions: (np.ndarray) with first dimension equal to the batch size.
Retu... | [
"Takes",
"a",
"step",
"in",
"all",
"environments",
"shouldn",
"t",
"pre",
"-",
"process",
"or",
"record",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L504-L538 | [
"def",
"_step",
"(",
"self",
",",
"actions",
")",
":",
"# Pre-conditions: common_preconditions, see `assert_common_preconditions`.",
"# : len(actions) == len(self._envs)",
"self",
".",
"assert_common_preconditions",
"(",
")",
"assert",
"len",
"(",
"actions",
")",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | EnvProblem.step | Takes a step in all environments.
Subclasses should override _step to do the actual reset if something other
than the default implementation is desired.
Args:
actions: Batch of actions.
Returns:
(preprocessed_observations, processed_rewards, dones, infos). | tensor2tensor/envs/env_problem.py | def step(self, actions):
"""Takes a step in all environments.
Subclasses should override _step to do the actual reset if something other
than the default implementation is desired.
Args:
actions: Batch of actions.
Returns:
(preprocessed_observations, processed_rewards, dones, infos).
... | def step(self, actions):
"""Takes a step in all environments.
Subclasses should override _step to do the actual reset if something other
than the default implementation is desired.
Args:
actions: Batch of actions.
Returns:
(preprocessed_observations, processed_rewards, dones, infos).
... | [
"Takes",
"a",
"step",
"in",
"all",
"environments",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L540-L566 | [
"def",
"step",
"(",
"self",
",",
"actions",
")",
":",
"observations",
",",
"raw_rewards",
",",
"dones",
",",
"infos",
"=",
"self",
".",
"_step",
"(",
"actions",
")",
"# Process rewards.",
"raw_rewards",
"=",
"raw_rewards",
".",
"astype",
"(",
"np",
".",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | EnvProblem.example_reading_spec | Data fields to store on disk and their decoders. | tensor2tensor/envs/env_problem.py | def example_reading_spec(self):
"""Data fields to store on disk and their decoders."""
# Subclasses can override and/or extend.
processed_reward_type = tf.float32
if self.is_processed_rewards_discrete:
processed_reward_type = tf.int64
data_fields = {
TIMESTEP_FIELD: tf.FixedLenFeatu... | def example_reading_spec(self):
"""Data fields to store on disk and their decoders."""
# Subclasses can override and/or extend.
processed_reward_type = tf.float32
if self.is_processed_rewards_discrete:
processed_reward_type = tf.int64
data_fields = {
TIMESTEP_FIELD: tf.FixedLenFeatu... | [
"Data",
"fields",
"to",
"store",
"on",
"disk",
"and",
"their",
"decoders",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L568-L594 | [
"def",
"example_reading_spec",
"(",
"self",
")",
":",
"# Subclasses can override and/or extend.",
"processed_reward_type",
"=",
"tf",
".",
"float32",
"if",
"self",
".",
"is_processed_rewards_discrete",
":",
"processed_reward_type",
"=",
"tf",
".",
"int64",
"data_fields",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | EnvProblem._generate_time_steps | A generator to yield single time-steps from a list of trajectories. | tensor2tensor/envs/env_problem.py | def _generate_time_steps(self, trajectory_list):
"""A generator to yield single time-steps from a list of trajectories."""
for single_trajectory in trajectory_list:
assert isinstance(single_trajectory, trajectory.Trajectory)
# Skip writing trajectories that have only a single time-step -- this
... | def _generate_time_steps(self, trajectory_list):
"""A generator to yield single time-steps from a list of trajectories."""
for single_trajectory in trajectory_list:
assert isinstance(single_trajectory, trajectory.Trajectory)
# Skip writing trajectories that have only a single time-step -- this
... | [
"A",
"generator",
"to",
"yield",
"single",
"time",
"-",
"steps",
"from",
"a",
"list",
"of",
"trajectories",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L656-L713 | [
"def",
"_generate_time_steps",
"(",
"self",
",",
"trajectory_list",
")",
":",
"for",
"single_trajectory",
"in",
"trajectory_list",
":",
"assert",
"isinstance",
"(",
"single_trajectory",
",",
"trajectory",
".",
"Trajectory",
")",
"# Skip writing trajectories that have only... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | init_vq_bottleneck | Get lookup table for VQ bottleneck. | tensor2tensor/models/research/transformer_nat.py | def init_vq_bottleneck(bottleneck_size, hidden_size):
"""Get lookup table for VQ bottleneck."""
means = tf.get_variable(
name="means",
shape=[bottleneck_size, hidden_size],
initializer=tf.uniform_unit_scaling_initializer())
ema_count = tf.get_variable(
name="ema_count",
shape=[bottle... | def init_vq_bottleneck(bottleneck_size, hidden_size):
"""Get lookup table for VQ bottleneck."""
means = tf.get_variable(
name="means",
shape=[bottleneck_size, hidden_size],
initializer=tf.uniform_unit_scaling_initializer())
ema_count = tf.get_variable(
name="ema_count",
shape=[bottle... | [
"Get",
"lookup",
"table",
"for",
"VQ",
"bottleneck",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L31-L48 | [
"def",
"init_vq_bottleneck",
"(",
"bottleneck_size",
",",
"hidden_size",
")",
":",
"means",
"=",
"tf",
".",
"get_variable",
"(",
"name",
"=",
"\"means\"",
",",
"shape",
"=",
"[",
"bottleneck_size",
",",
"hidden_size",
"]",
",",
"initializer",
"=",
"tf",
".",... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | vq_nearest_neighbor | Find the nearest element in means to elements in x. | tensor2tensor/models/research/transformer_nat.py | def vq_nearest_neighbor(x, hparams):
"""Find the nearest element in means to elements in x."""
bottleneck_size = 2**hparams.bottleneck_bits
means = hparams.means
x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keepdims=True)
means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keepdims=True)
scalar_pro... | def vq_nearest_neighbor(x, hparams):
"""Find the nearest element in means to elements in x."""
bottleneck_size = 2**hparams.bottleneck_bits
means = hparams.means
x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keepdims=True)
means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keepdims=True)
scalar_pro... | [
"Find",
"the",
"nearest",
"element",
"in",
"means",
"to",
"elements",
"in",
"x",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L51-L69 | [
"def",
"vq_nearest_neighbor",
"(",
"x",
",",
"hparams",
")",
":",
"bottleneck_size",
"=",
"2",
"**",
"hparams",
".",
"bottleneck_bits",
"means",
"=",
"hparams",
".",
"means",
"x_norm_sq",
"=",
"tf",
".",
"reduce_sum",
"(",
"tf",
".",
"square",
"(",
"x",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | vq_discrete_bottleneck | Simple vector quantized discrete bottleneck. | tensor2tensor/models/research/transformer_nat.py | def vq_discrete_bottleneck(x, hparams):
"""Simple vector quantized discrete bottleneck."""
tf.logging.info("Using EMA with beta = {}".format(hparams.beta))
bottleneck_size = 2**hparams.bottleneck_bits
x_shape = common_layers.shape_list(x)
x = tf.reshape(x, [-1, hparams.hidden_size])
x_means_hot, e_loss = vq... | def vq_discrete_bottleneck(x, hparams):
"""Simple vector quantized discrete bottleneck."""
tf.logging.info("Using EMA with beta = {}".format(hparams.beta))
bottleneck_size = 2**hparams.bottleneck_bits
x_shape = common_layers.shape_list(x)
x = tf.reshape(x, [-1, hparams.hidden_size])
x_means_hot, e_loss = vq... | [
"Simple",
"vector",
"quantized",
"discrete",
"bottleneck",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L72-L107 | [
"def",
"vq_discrete_bottleneck",
"(",
"x",
",",
"hparams",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Using EMA with beta = {}\"",
".",
"format",
"(",
"hparams",
".",
"beta",
")",
")",
"bottleneck_size",
"=",
"2",
"**",
"hparams",
".",
"bottleneck_... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | vq_discrete_unbottleneck | Simple undiscretization from vector quantized representation. | tensor2tensor/models/research/transformer_nat.py | def vq_discrete_unbottleneck(x, hparams):
"""Simple undiscretization from vector quantized representation."""
x_shape = common_layers.shape_list(x)
bottleneck_size = 2**hparams.bottleneck_bits
means = hparams.means
x_flat = tf.reshape(x, [-1, bottleneck_size])
result = tf.matmul(x_flat, means)
result = tf... | def vq_discrete_unbottleneck(x, hparams):
"""Simple undiscretization from vector quantized representation."""
x_shape = common_layers.shape_list(x)
bottleneck_size = 2**hparams.bottleneck_bits
means = hparams.means
x_flat = tf.reshape(x, [-1, bottleneck_size])
result = tf.matmul(x_flat, means)
result = tf... | [
"Simple",
"undiscretization",
"from",
"vector",
"quantized",
"representation",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L110-L118 | [
"def",
"vq_discrete_unbottleneck",
"(",
"x",
",",
"hparams",
")",
":",
"x_shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"bottleneck_size",
"=",
"2",
"**",
"hparams",
".",
"bottleneck_bits",
"means",
"=",
"hparams",
".",
"means",
"x_flat",
"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | residual_conv | A stack of convolution blocks with residual connections. | tensor2tensor/models/research/transformer_nat.py | def residual_conv(x, repeat, k, hparams, name, reuse=None):
"""A stack of convolution blocks with residual connections."""
with tf.variable_scope(name, reuse=reuse):
dilations_and_kernels = [((1, 1), k) for _ in range(3)]
for i in range(repeat):
with tf.variable_scope("repeat_%d" % i):
y = com... | def residual_conv(x, repeat, k, hparams, name, reuse=None):
"""A stack of convolution blocks with residual connections."""
with tf.variable_scope(name, reuse=reuse):
dilations_and_kernels = [((1, 1), k) for _ in range(3)]
for i in range(repeat):
with tf.variable_scope("repeat_%d" % i):
y = com... | [
"A",
"stack",
"of",
"convolution",
"blocks",
"with",
"residual",
"connections",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L121-L135 | [
"def",
"residual_conv",
"(",
"x",
",",
"repeat",
",",
"k",
",",
"hparams",
",",
"name",
",",
"reuse",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"reuse",
"=",
"reuse",
")",
":",
"dilations_and_kernels",
"=",
"[",
"(... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | decompress_step | Decompression function. | tensor2tensor/models/research/transformer_nat.py | def decompress_step(source, hparams, first_relu, name):
"""Decompression function."""
with tf.variable_scope(name):
shape = common_layers.shape_list(source)
multiplier = 2
kernel = (1, 1)
thicker = common_layers.conv_block(
source,
hparams.hidden_size * multiplier, [((1, 1), kernel)]... | def decompress_step(source, hparams, first_relu, name):
"""Decompression function."""
with tf.variable_scope(name):
shape = common_layers.shape_list(source)
multiplier = 2
kernel = (1, 1)
thicker = common_layers.conv_block(
source,
hparams.hidden_size * multiplier, [((1, 1), kernel)]... | [
"Decompression",
"function",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L138-L149 | [
"def",
"decompress_step",
"(",
"source",
",",
"hparams",
",",
"first_relu",
",",
"name",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
")",
":",
"shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"source",
")",
"multiplier",
"=",
"2",
"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | compress | Compress. | tensor2tensor/models/research/transformer_nat.py | def compress(x, hparams, name):
"""Compress."""
with tf.variable_scope(name):
# Run compression by strided convs.
cur = x
k1 = (3, 1)
k2 = (2, 1)
cur = residual_conv(cur, hparams.num_compress_steps, k1, hparams, "rc")
for i in range(hparams.num_compress_steps):
cur = common_layers.conv... | def compress(x, hparams, name):
"""Compress."""
with tf.variable_scope(name):
# Run compression by strided convs.
cur = x
k1 = (3, 1)
k2 = (2, 1)
cur = residual_conv(cur, hparams.num_compress_steps, k1, hparams, "rc")
for i in range(hparams.num_compress_steps):
cur = common_layers.conv... | [
"Compress",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L152-L166 | [
"def",
"compress",
"(",
"x",
",",
"hparams",
",",
"name",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
")",
":",
"# Run compression by strided convs.",
"cur",
"=",
"x",
"k1",
"=",
"(",
"3",
",",
"1",
")",
"k2",
"=",
"(",
"2",
",",
"1... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | encode | Transformer preparations and encoder. | tensor2tensor/models/research/transformer_nat.py | def encode(x, x_space, hparams, name):
"""Transformer preparations and encoder."""
with tf.variable_scope(name):
(encoder_input, encoder_self_attention_bias,
ed) = transformer.transformer_prepare_encoder(x, x_space, hparams)
encoder_input = tf.nn.dropout(encoder_input, 1.0 - hparams.dropout)
return... | def encode(x, x_space, hparams, name):
"""Transformer preparations and encoder."""
with tf.variable_scope(name):
(encoder_input, encoder_self_attention_bias,
ed) = transformer.transformer_prepare_encoder(x, x_space, hparams)
encoder_input = tf.nn.dropout(encoder_input, 1.0 - hparams.dropout)
return... | [
"Transformer",
"preparations",
"and",
"encoder",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L169-L176 | [
"def",
"encode",
"(",
"x",
",",
"x_space",
",",
"hparams",
",",
"name",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
")",
":",
"(",
"encoder_input",
",",
"encoder_self_attention_bias",
",",
"ed",
")",
"=",
"transformer",
".",
"transformer_pr... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | decode_transformer | Original Transformer decoder. | tensor2tensor/models/research/transformer_nat.py | def decode_transformer(encoder_output, encoder_decoder_attention_bias, targets,
hparams, name):
"""Original Transformer decoder."""
with tf.variable_scope(name):
targets = common_layers.flatten4d3d(targets)
decoder_input, decoder_self_bias = (
transformer.transformer_prepare_... | def decode_transformer(encoder_output, encoder_decoder_attention_bias, targets,
hparams, name):
"""Original Transformer decoder."""
with tf.variable_scope(name):
targets = common_layers.flatten4d3d(targets)
decoder_input, decoder_self_bias = (
transformer.transformer_prepare_... | [
"Original",
"Transformer",
"decoder",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L179-L199 | [
"def",
"decode_transformer",
"(",
"encoder_output",
",",
"encoder_decoder_attention_bias",
",",
"targets",
",",
"hparams",
",",
"name",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
")",
":",
"targets",
"=",
"common_layers",
".",
"flatten4d3d",
"("... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | get_latent_pred_loss | Latent prediction and loss. | tensor2tensor/models/research/transformer_nat.py | def get_latent_pred_loss(latents_pred, latents_discrete_hot, hparams):
"""Latent prediction and loss."""
latents_logits = tf.layers.dense(
latents_pred, 2**hparams.bottleneck_bits, name="extra_logits")
loss = tf.nn.softmax_cross_entropy_with_logits_v2(
labels=tf.stop_gradient(latents_discrete_hot), lo... | def get_latent_pred_loss(latents_pred, latents_discrete_hot, hparams):
"""Latent prediction and loss."""
latents_logits = tf.layers.dense(
latents_pred, 2**hparams.bottleneck_bits, name="extra_logits")
loss = tf.nn.softmax_cross_entropy_with_logits_v2(
labels=tf.stop_gradient(latents_discrete_hot), lo... | [
"Latent",
"prediction",
"and",
"loss",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L202-L208 | [
"def",
"get_latent_pred_loss",
"(",
"latents_pred",
",",
"latents_discrete_hot",
",",
"hparams",
")",
":",
"latents_logits",
"=",
"tf",
".",
"layers",
".",
"dense",
"(",
"latents_pred",
",",
"2",
"**",
"hparams",
".",
"bottleneck_bits",
",",
"name",
"=",
"\"ex... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | ae_transformer_internal | Main step used for training. | tensor2tensor/models/research/transformer_nat.py | def ae_transformer_internal(inputs, targets, target_space, hparams, cache=None):
"""Main step used for training."""
# Encoder.
inputs = common_layers.flatten4d3d(inputs)
inputs, ed = encode(inputs, target_space, hparams, "input_enc")
# Autoencoding.
losses = {"extra": tf.constant(0.0), "latent_pred": tf.co... | def ae_transformer_internal(inputs, targets, target_space, hparams, cache=None):
"""Main step used for training."""
# Encoder.
inputs = common_layers.flatten4d3d(inputs)
inputs, ed = encode(inputs, target_space, hparams, "input_enc")
# Autoencoding.
losses = {"extra": tf.constant(0.0), "latent_pred": tf.co... | [
"Main",
"step",
"used",
"for",
"training",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L245-L316 | [
"def",
"ae_transformer_internal",
"(",
"inputs",
",",
"targets",
",",
"target_space",
",",
"hparams",
",",
"cache",
"=",
"None",
")",
":",
"# Encoder.",
"inputs",
"=",
"common_layers",
".",
"flatten4d3d",
"(",
"inputs",
")",
"inputs",
",",
"ed",
"=",
"encode... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | transformer_nat_small | Set of hyperparameters. | tensor2tensor/models/research/transformer_nat.py | def transformer_nat_small():
"""Set of hyperparameters."""
hparams = transformer.transformer_small()
hparams.batch_size = 2048
hparams.learning_rate = 0.2
hparams.learning_rate_warmup_steps = 4000
hparams.num_hidden_layers = 3
hparams.hidden_size = 384
hparams.filter_size = 2048
hparams.label_smoothin... | def transformer_nat_small():
"""Set of hyperparameters."""
hparams = transformer.transformer_small()
hparams.batch_size = 2048
hparams.learning_rate = 0.2
hparams.learning_rate_warmup_steps = 4000
hparams.num_hidden_layers = 3
hparams.hidden_size = 384
hparams.filter_size = 2048
hparams.label_smoothin... | [
"Set",
"of",
"hyperparameters",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L384-L407 | [
"def",
"transformer_nat_small",
"(",
")",
":",
"hparams",
"=",
"transformer",
".",
"transformer_small",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"2048",
"hparams",
".",
"learning_rate",
"=",
"0.2",
"hparams",
".",
"learning_rate_warmup_steps",
"=",
"4000",
"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | transformer_nat_base | Set of hyperparameters. | tensor2tensor/models/research/transformer_nat.py | def transformer_nat_base():
"""Set of hyperparameters."""
hparams = transformer_nat_small()
hparams.batch_size = 2048
hparams.hidden_size = 512
hparams.filter_size = 4096
hparams.num_hidden_layers = 6
return hparams | def transformer_nat_base():
"""Set of hyperparameters."""
hparams = transformer_nat_small()
hparams.batch_size = 2048
hparams.hidden_size = 512
hparams.filter_size = 4096
hparams.num_hidden_layers = 6
return hparams | [
"Set",
"of",
"hyperparameters",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L411-L418 | [
"def",
"transformer_nat_base",
"(",
")",
":",
"hparams",
"=",
"transformer_nat_small",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"2048",
"hparams",
".",
"hidden_size",
"=",
"512",
"hparams",
".",
"filter_size",
"=",
"4096",
"hparams",
".",
"num_hidden_layers"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | transformer_nat_big | Set of hyperparameters. | tensor2tensor/models/research/transformer_nat.py | def transformer_nat_big():
"""Set of hyperparameters."""
hparams = transformer_nat_small()
hparams.batch_size = 2048
hparams.hidden_size = 1024
hparams.filter_size = 4096
hparams.num_hidden_layers = 6
hparams.num_heads = 16
hparams.layer_prepostprocess_dropout = 0.3
return hparams | def transformer_nat_big():
"""Set of hyperparameters."""
hparams = transformer_nat_small()
hparams.batch_size = 2048
hparams.hidden_size = 1024
hparams.filter_size = 4096
hparams.num_hidden_layers = 6
hparams.num_heads = 16
hparams.layer_prepostprocess_dropout = 0.3
return hparams | [
"Set",
"of",
"hyperparameters",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L422-L431 | [
"def",
"transformer_nat_big",
"(",
")",
":",
"hparams",
"=",
"transformer_nat_small",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"2048",
"hparams",
".",
"hidden_size",
"=",
"1024",
"hparams",
".",
"filter_size",
"=",
"4096",
"hparams",
".",
"num_hidden_layers"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | policy_net | A policy net function. | tensor2tensor/trax/rlax/ppo.py | def policy_net(rng_key,
batch_observations_shape,
num_actions,
bottom_layers=None):
"""A policy net function."""
# Use the bottom_layers as the bottom part of the network and just add the
# required layers on top of it.
if bottom_layers is None:
bottom_layers = [... | def policy_net(rng_key,
batch_observations_shape,
num_actions,
bottom_layers=None):
"""A policy net function."""
# Use the bottom_layers as the bottom part of the network and just add the
# required layers on top of it.
if bottom_layers is None:
bottom_layers = [... | [
"A",
"policy",
"net",
"function",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L78-L92 | [
"def",
"policy_net",
"(",
"rng_key",
",",
"batch_observations_shape",
",",
"num_actions",
",",
"bottom_layers",
"=",
"None",
")",
":",
"# Use the bottom_layers as the bottom part of the network and just add the",
"# required layers on top of it.",
"if",
"bottom_layers",
"is",
"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | value_net | A value net function. | tensor2tensor/trax/rlax/ppo.py | def value_net(rng_key,
batch_observations_shape,
num_actions,
bottom_layers=None):
"""A value net function."""
del num_actions
if bottom_layers is None:
bottom_layers = []
bottom_layers.extend([
layers.Dense(1),
])
net = layers.Serial(*bottom_layers)
re... | def value_net(rng_key,
batch_observations_shape,
num_actions,
bottom_layers=None):
"""A value net function."""
del num_actions
if bottom_layers is None:
bottom_layers = []
bottom_layers.extend([
layers.Dense(1),
])
net = layers.Serial(*bottom_layers)
re... | [
"A",
"value",
"net",
"function",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L95-L108 | [
"def",
"value_net",
"(",
"rng_key",
",",
"batch_observations_shape",
",",
"num_actions",
",",
"bottom_layers",
"=",
"None",
")",
":",
"del",
"num_actions",
"if",
"bottom_layers",
"is",
"None",
":",
"bottom_layers",
"=",
"[",
"]",
"bottom_layers",
".",
"extend",
... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | policy_and_value_net | A policy and value net function. | tensor2tensor/trax/rlax/ppo.py | def policy_and_value_net(rng_key,
batch_observations_shape,
num_actions,
bottom_layers=None):
"""A policy and value net function."""
# Layers.
cur_layers = []
if bottom_layers is not None:
cur_layers.extend(bottom_layers)
# Now, ... | def policy_and_value_net(rng_key,
batch_observations_shape,
num_actions,
bottom_layers=None):
"""A policy and value net function."""
# Layers.
cur_layers = []
if bottom_layers is not None:
cur_layers.extend(bottom_layers)
# Now, ... | [
"A",
"policy",
"and",
"value",
"net",
"function",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L111-L130 | [
"def",
"policy_and_value_net",
"(",
"rng_key",
",",
"batch_observations_shape",
",",
"num_actions",
",",
"bottom_layers",
"=",
"None",
")",
":",
"# Layers.",
"cur_layers",
"=",
"[",
"]",
"if",
"bottom_layers",
"is",
"not",
"None",
":",
"cur_layers",
".",
"extend... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | log_params | Dumps the params with `logging.error`. | tensor2tensor/trax/rlax/ppo.py | def log_params(params, name="params"):
"""Dumps the params with `logging.error`."""
for i, param in enumerate(params):
if not param:
# Empty tuple.
continue
if not isinstance(param, (list, tuple)):
logging.error(
"%s[%d] : (%s) = [%s]", name, i, param.shape, onp.array(param))
... | def log_params(params, name="params"):
"""Dumps the params with `logging.error`."""
for i, param in enumerate(params):
if not param:
# Empty tuple.
continue
if not isinstance(param, (list, tuple)):
logging.error(
"%s[%d] : (%s) = [%s]", name, i, param.shape, onp.array(param))
... | [
"Dumps",
"the",
"params",
"with",
"logging",
".",
"error",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L140-L152 | [
"def",
"log_params",
"(",
"params",
",",
"name",
"=",
"\"params\"",
")",
":",
"for",
"i",
",",
"param",
"in",
"enumerate",
"(",
"params",
")",
":",
"if",
"not",
"param",
":",
"# Empty tuple.",
"continue",
"if",
"not",
"isinstance",
"(",
"param",
",",
"... | 272500b6efe353aeb638d2745ed56e519462ca31 |
train | collect_trajectories | Collect trajectories with the given policy net and behaviour.
Args:
env: A gym env interface, for now this is not-batched.
policy_fun: observations(B,T+1) -> log-probabs(B,T+1, A) callable.
num_trajectories: int, number of trajectories.
policy: string, "greedy", "epsilon-greedy", or "categorical-samp... | tensor2tensor/trax/rlax/ppo.py | def collect_trajectories(env,
policy_fun,
num_trajectories=1,
policy="greedy",
max_timestep=None,
epsilon=0.1):
"""Collect trajectories with the given policy net and behaviour.
Args:
env... | def collect_trajectories(env,
policy_fun,
num_trajectories=1,
policy="greedy",
max_timestep=None,
epsilon=0.1):
"""Collect trajectories with the given policy net and behaviour.
Args:
env... | [
"Collect",
"trajectories",
"with",
"the",
"given",
"policy",
"net",
"and",
"behaviour",
"."
] | tensorflow/tensor2tensor | python | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L159-L275 | [
"def",
"collect_trajectories",
"(",
"env",
",",
"policy_fun",
",",
"num_trajectories",
"=",
"1",
",",
"policy",
"=",
"\"greedy\"",
",",
"max_timestep",
"=",
"None",
",",
"epsilon",
"=",
"0.1",
")",
":",
"trajectories",
"=",
"[",
"]",
"for",
"t",
"in",
"r... | 272500b6efe353aeb638d2745ed56e519462ca31 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.