id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
22,000
tensorflow/tensor2tensor
tensor2tensor/serving/serving_utils.py
make_grpc_request_fn
def make_grpc_request_fn(servable_name, server, timeout_secs): """Wraps function to make grpc requests with runtime args.""" stub = _create_stub(server) def _make_grpc_request(examples): """Builds and sends request to TensorFlow model server.""" request = predict_pb2.PredictRequest() request.model_sp...
python
def make_grpc_request_fn(servable_name, server, timeout_secs): """Wraps function to make grpc requests with runtime args.""" stub = _create_stub(server) def _make_grpc_request(examples): """Builds and sends request to TensorFlow model server.""" request = predict_pb2.PredictRequest() request.model_sp...
[ "def", "make_grpc_request_fn", "(", "servable_name", ",", "server", ",", "timeout_secs", ")", ":", "stub", "=", "_create_stub", "(", "server", ")", "def", "_make_grpc_request", "(", "examples", ")", ":", "\"\"\"Builds and sends request to TensorFlow model server.\"\"\"", ...
Wraps function to make grpc requests with runtime args.
[ "Wraps", "function", "to", "make", "grpc", "requests", "with", "runtime", "args", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/serving/serving_utils.py#L105-L125
22,001
tensorflow/tensor2tensor
tensor2tensor/serving/serving_utils.py
make_cloud_mlengine_request_fn
def make_cloud_mlengine_request_fn(credentials, model_name, version): """Wraps function to make CloudML Engine requests with runtime args.""" def _make_cloud_mlengine_request(examples): """Builds and sends requests to Cloud ML Engine.""" api = discovery.build("ml", "v1", credentials=credentials) parent...
python
def make_cloud_mlengine_request_fn(credentials, model_name, version): """Wraps function to make CloudML Engine requests with runtime args.""" def _make_cloud_mlengine_request(examples): """Builds and sends requests to Cloud ML Engine.""" api = discovery.build("ml", "v1", credentials=credentials) parent...
[ "def", "make_cloud_mlengine_request_fn", "(", "credentials", ",", "model_name", ",", "version", ")", ":", "def", "_make_cloud_mlengine_request", "(", "examples", ")", ":", "\"\"\"Builds and sends requests to Cloud ML Engine.\"\"\"", "api", "=", "discovery", ".", "build", ...
Wraps function to make CloudML Engine requests with runtime args.
[ "Wraps", "function", "to", "make", "CloudML", "Engine", "requests", "with", "runtime", "args", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/serving/serving_utils.py#L128-L146
22,002
tensorflow/tensor2tensor
tensor2tensor/serving/serving_utils.py
predict
def predict(inputs_list, problem, request_fn): """Encodes inputs, makes request to deployed TF model, and decodes outputs.""" assert isinstance(inputs_list, list) fname = "inputs" if problem.has_inputs else "targets" input_encoder = problem.feature_info[fname].encoder input_ids_list = [ _encode(inputs, ...
python
def predict(inputs_list, problem, request_fn): """Encodes inputs, makes request to deployed TF model, and decodes outputs.""" assert isinstance(inputs_list, list) fname = "inputs" if problem.has_inputs else "targets" input_encoder = problem.feature_info[fname].encoder input_ids_list = [ _encode(inputs, ...
[ "def", "predict", "(", "inputs_list", ",", "problem", ",", "request_fn", ")", ":", "assert", "isinstance", "(", "inputs_list", ",", "list", ")", "fname", "=", "\"inputs\"", "if", "problem", ".", "has_inputs", "else", "\"targets\"", "input_encoder", "=", "probl...
Encodes inputs, makes request to deployed TF model, and decodes outputs.
[ "Encodes", "inputs", "makes", "request", "to", "deployed", "TF", "model", "and", "decodes", "outputs", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/serving/serving_utils.py#L149-L167
22,003
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_recurrent.py
next_frame_basic_recurrent
def next_frame_basic_recurrent(): """Basic 2-frame recurrent model with stochastic tower.""" hparams = basic_stochastic.next_frame_basic_stochastic_discrete() hparams.filter_double_steps = 2 hparams.hidden_size = 64 hparams.video_num_input_frames = 4 hparams.video_num_target_frames = 4 hparams.concat_inte...
python
def next_frame_basic_recurrent(): """Basic 2-frame recurrent model with stochastic tower.""" hparams = basic_stochastic.next_frame_basic_stochastic_discrete() hparams.filter_double_steps = 2 hparams.hidden_size = 64 hparams.video_num_input_frames = 4 hparams.video_num_target_frames = 4 hparams.concat_inte...
[ "def", "next_frame_basic_recurrent", "(", ")", ":", "hparams", "=", "basic_stochastic", ".", "next_frame_basic_stochastic_discrete", "(", ")", "hparams", ".", "filter_double_steps", "=", "2", "hparams", ".", "hidden_size", "=", "64", "hparams", ".", "video_num_input_f...
Basic 2-frame recurrent model with stochastic tower.
[ "Basic", "2", "-", "frame", "recurrent", "model", "with", "stochastic", "tower", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_recurrent.py#L52-L62
22,004
tensorflow/tensor2tensor
tensor2tensor/bin/t2t_distill.py
create_teacher_experiment
def create_teacher_experiment(run_config, hparams, argv): """Creates experiment function.""" tf.logging.info("training teacher") tf.logging.set_verbosity(tf.logging.INFO) trainer_lib.set_random_seed(FLAGS.random_seed) usr_dir.import_usr_dir(FLAGS.t2t_usr_dir) t2t_trainer.maybe_log_registry_and_exit() if ...
python
def create_teacher_experiment(run_config, hparams, argv): """Creates experiment function.""" tf.logging.info("training teacher") tf.logging.set_verbosity(tf.logging.INFO) trainer_lib.set_random_seed(FLAGS.random_seed) usr_dir.import_usr_dir(FLAGS.t2t_usr_dir) t2t_trainer.maybe_log_registry_and_exit() if ...
[ "def", "create_teacher_experiment", "(", "run_config", ",", "hparams", ",", "argv", ")", ":", "tf", ".", "logging", ".", "info", "(", "\"training teacher\"", ")", "tf", ".", "logging", ".", "set_verbosity", "(", "tf", ".", "logging", ".", "INFO", ")", "tra...
Creates experiment function.
[ "Creates", "experiment", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_distill.py#L91-L114
22,005
tensorflow/tensor2tensor
tensor2tensor/trax/trax.py
masked_mean
def masked_mean(inputs, targets, mask_id=None): """Mean of the inputs but counting only those where targets != mask_id.""" inputs = [x.astype(np.float32) for x in inputs] # We assume all elements in the list contribute equally. # TODO(lukaszkaiser): remove this assumption (e.g., when masks differ). length = l...
python
def masked_mean(inputs, targets, mask_id=None): """Mean of the inputs but counting only those where targets != mask_id.""" inputs = [x.astype(np.float32) for x in inputs] # We assume all elements in the list contribute equally. # TODO(lukaszkaiser): remove this assumption (e.g., when masks differ). length = l...
[ "def", "masked_mean", "(", "inputs", ",", "targets", ",", "mask_id", "=", "None", ")", ":", "inputs", "=", "[", "x", ".", "astype", "(", "np", ".", "float32", ")", "for", "x", "in", "inputs", "]", "# We assume all elements in the list contribute equally.", "...
Mean of the inputs but counting only those where targets != mask_id.
[ "Mean", "of", "the", "inputs", "but", "counting", "only", "those", "where", "targets", "!", "=", "mask_id", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L68-L79
22,006
tensorflow/tensor2tensor
tensor2tensor/trax/trax.py
neg_log_perplexity
def neg_log_perplexity(batch, model_predictions): """Calculate negative log perplexity.""" _, targets = batch model_predictions, targets = _make_list(model_predictions, targets) xent = [] for (prediction, target) in zip(model_predictions, targets): hot_target = layers.one_hot(target, prediction.shape[-1])...
python
def neg_log_perplexity(batch, model_predictions): """Calculate negative log perplexity.""" _, targets = batch model_predictions, targets = _make_list(model_predictions, targets) xent = [] for (prediction, target) in zip(model_predictions, targets): hot_target = layers.one_hot(target, prediction.shape[-1])...
[ "def", "neg_log_perplexity", "(", "batch", ",", "model_predictions", ")", ":", "_", ",", "targets", "=", "batch", "model_predictions", ",", "targets", "=", "_make_list", "(", "model_predictions", ",", "targets", ")", "xent", "=", "[", "]", "for", "(", "predi...
Calculate negative log perplexity.
[ "Calculate", "negative", "log", "perplexity", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L93-L101
22,007
tensorflow/tensor2tensor
tensor2tensor/trax/trax.py
loss
def loss(params, batch, model_predict, rng): """Calculate loss.""" inputs, targets = batch predictions = model_predict(inputs, params, rng=rng) predictions, targets = _make_list(predictions, targets) xent = [] for (pred, target) in zip(predictions, targets): xent.append(np.sum(pred * layers.one_hot(targ...
python
def loss(params, batch, model_predict, rng): """Calculate loss.""" inputs, targets = batch predictions = model_predict(inputs, params, rng=rng) predictions, targets = _make_list(predictions, targets) xent = [] for (pred, target) in zip(predictions, targets): xent.append(np.sum(pred * layers.one_hot(targ...
[ "def", "loss", "(", "params", ",", "batch", ",", "model_predict", ",", "rng", ")", ":", "inputs", ",", "targets", "=", "batch", "predictions", "=", "model_predict", "(", "inputs", ",", "params", ",", "rng", "=", "rng", ")", "predictions", ",", "targets",...
Calculate loss.
[ "Calculate", "loss", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L104-L112
22,008
tensorflow/tensor2tensor
tensor2tensor/trax/trax.py
restore_state
def restore_state(output_dir): """Restore State.""" params_file = os.path.join(output_dir, "model.pkl") if not gfile.exists(params_file): return State(step=None, params=None, history=trax_history.History()) with gfile.GFile(params_file, "rb") as f: (params, step, history) = pickle.load(f) log("Model ...
python
def restore_state(output_dir): """Restore State.""" params_file = os.path.join(output_dir, "model.pkl") if not gfile.exists(params_file): return State(step=None, params=None, history=trax_history.History()) with gfile.GFile(params_file, "rb") as f: (params, step, history) = pickle.load(f) log("Model ...
[ "def", "restore_state", "(", "output_dir", ")", ":", "params_file", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "\"model.pkl\"", ")", "if", "not", "gfile", ".", "exists", "(", "params_file", ")", ":", "return", "State", "(", "step", "=",...
Restore State.
[ "Restore", "State", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L129-L139
22,009
tensorflow/tensor2tensor
tensor2tensor/trax/trax.py
save_state
def save_state(state, output_dir, keep=False): """Save State and optionally gin config.""" params_file = os.path.join(output_dir, "model.pkl") with gfile.GFile(params_file, "wb") as f: pickle.dump((state.params, state.step, state.history), f) if keep: params_file = os.path.join(output_dir, "model_{}.pkl...
python
def save_state(state, output_dir, keep=False): """Save State and optionally gin config.""" params_file = os.path.join(output_dir, "model.pkl") with gfile.GFile(params_file, "wb") as f: pickle.dump((state.params, state.step, state.history), f) if keep: params_file = os.path.join(output_dir, "model_{}.pkl...
[ "def", "save_state", "(", "state", ",", "output_dir", ",", "keep", "=", "False", ")", ":", "params_file", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "\"model.pkl\"", ")", "with", "gfile", ".", "GFile", "(", "params_file", ",", "\"wb\"",...
Save State and optionally gin config.
[ "Save", "State", "and", "optionally", "gin", "config", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L152-L161
22,010
tensorflow/tensor2tensor
tensor2tensor/trax/trax.py
evaluate_train_and_eval
def evaluate_train_and_eval(step, inputs, predict_fun, eval_steps, rng, train_sw=None, eval_sw=None, history=None): """Evalaute on train and eval data, and log metrics.""" step_log(step, "Evaluation") train_metrics, eval_metrics = [ evaluate( # pylint: disable=g-complex-comprehe...
python
def evaluate_train_and_eval(step, inputs, predict_fun, eval_steps, rng, train_sw=None, eval_sw=None, history=None): """Evalaute on train and eval data, and log metrics.""" step_log(step, "Evaluation") train_metrics, eval_metrics = [ evaluate( # pylint: disable=g-complex-comprehe...
[ "def", "evaluate_train_and_eval", "(", "step", ",", "inputs", ",", "predict_fun", ",", "eval_steps", ",", "rng", ",", "train_sw", "=", "None", ",", "eval_sw", "=", "None", ",", "history", "=", "None", ")", ":", "step_log", "(", "step", ",", "\"Evaluation\"...
Evalaute on train and eval data, and log metrics.
[ "Evalaute", "on", "train", "and", "eval", "data", "and", "log", "metrics", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L172-L189
22,011
tensorflow/tensor2tensor
tensor2tensor/trax/trax.py
log_metrics
def log_metrics(metrics, summ_writer, log_prefix, step, history=None): """Log metrics to summary writer and history.""" rjust_len = max([len(name) for name in metrics]) for name, value in six.iteritems(metrics): step_log(step, "%s %s | % .8f" % ( log_prefix.ljust(5), name.rjust(rjust_len), value)) ...
python
def log_metrics(metrics, summ_writer, log_prefix, step, history=None): """Log metrics to summary writer and history.""" rjust_len = max([len(name) for name in metrics]) for name, value in six.iteritems(metrics): step_log(step, "%s %s | % .8f" % ( log_prefix.ljust(5), name.rjust(rjust_len), value)) ...
[ "def", "log_metrics", "(", "metrics", ",", "summ_writer", ",", "log_prefix", ",", "step", ",", "history", "=", "None", ")", ":", "rjust_len", "=", "max", "(", "[", "len", "(", "name", ")", "for", "name", "in", "metrics", "]", ")", "for", "name", ",",...
Log metrics to summary writer and history.
[ "Log", "metrics", "to", "summary", "writer", "and", "history", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L218-L228
22,012
tensorflow/tensor2tensor
tensor2tensor/trax/trax.py
get_random_number_generator_and_set_seed
def get_random_number_generator_and_set_seed(seed=None): """Get a JAX random number generator and set random seed everywhere.""" random.seed(seed) # While python random accepts None as seed and uses time/os seed then, # some other functions expect integers so we create one here. if seed is None: seed = ra...
python
def get_random_number_generator_and_set_seed(seed=None): """Get a JAX random number generator and set random seed everywhere.""" random.seed(seed) # While python random accepts None as seed and uses time/os seed then, # some other functions expect integers so we create one here. if seed is None: seed = ra...
[ "def", "get_random_number_generator_and_set_seed", "(", "seed", "=", "None", ")", ":", "random", ".", "seed", "(", "seed", ")", "# While python random accepts None as seed and uses time/os seed then,", "# some other functions expect integers so we create one here.", "if", "seed", ...
Get a JAX random number generator and set random seed everywhere.
[ "Get", "a", "JAX", "random", "number", "generator", "and", "set", "random", "seed", "everywhere", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L231-L240
22,013
tensorflow/tensor2tensor
tensor2tensor/trax/trax.py
epochs
def epochs(steps=None, epoch_steps=1): """Iterator over epochs until steps is reached. 1-indexed. Args: steps: int, total number of steps. Infinite if None. epoch_steps: int, number of steps per epoch. Can also be an iterable<int> to enable variable length epochs. Yields: (epoch: int, epoch id...
python
def epochs(steps=None, epoch_steps=1): """Iterator over epochs until steps is reached. 1-indexed. Args: steps: int, total number of steps. Infinite if None. epoch_steps: int, number of steps per epoch. Can also be an iterable<int> to enable variable length epochs. Yields: (epoch: int, epoch id...
[ "def", "epochs", "(", "steps", "=", "None", ",", "epoch_steps", "=", "1", ")", ":", "try", ":", "iter", "(", "epoch_steps", ")", "except", "TypeError", ":", "epoch_steps", "=", "itertools", ".", "repeat", "(", "epoch_steps", ")", "step", "=", "0", "for...
Iterator over epochs until steps is reached. 1-indexed. Args: steps: int, total number of steps. Infinite if None. epoch_steps: int, number of steps per epoch. Can also be an iterable<int> to enable variable length epochs. Yields: (epoch: int, epoch id, epoch_steps: int, number of steps in this ...
[ "Iterator", "over", "epochs", "until", "steps", "is", "reached", ".", "1", "-", "indexed", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L255-L277
22,014
tensorflow/tensor2tensor
tensor2tensor/trax/trax.py
_jit_predict_fun
def _jit_predict_fun(model_predict, num_devices): """Use jit on model_predict if required.""" def predict(x, params=(), rng=None): """Predict function jited and parallelized as requested.""" # On one device, jit and run. if num_devices == 1: return backend.jit(model_predict)(x, params, rng=rng) ...
python
def _jit_predict_fun(model_predict, num_devices): """Use jit on model_predict if required.""" def predict(x, params=(), rng=None): """Predict function jited and parallelized as requested.""" # On one device, jit and run. if num_devices == 1: return backend.jit(model_predict)(x, params, rng=rng) ...
[ "def", "_jit_predict_fun", "(", "model_predict", ",", "num_devices", ")", ":", "def", "predict", "(", "x", ",", "params", "=", "(", ")", ",", "rng", "=", "None", ")", ":", "\"\"\"Predict function jited and parallelized as requested.\"\"\"", "# On one device, jit and r...
Use jit on model_predict if required.
[ "Use", "jit", "on", "model_predict", "if", "required", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L280-L304
22,015
tensorflow/tensor2tensor
tensor2tensor/trax/trax.py
_jit_update_fun
def _jit_update_fun(predict_fun, loss_fun, optimizer, lr_fun, num_devices): """Get jit-ed update function for loss, optimizer, learning rate function.""" if num_devices == 1: # TODO(lukaszkaiser): remove branch when not needed. def single_update(i, opt_state, batch, rng): rng, subrng = jax_random.split(r...
python
def _jit_update_fun(predict_fun, loss_fun, optimizer, lr_fun, num_devices): """Get jit-ed update function for loss, optimizer, learning rate function.""" if num_devices == 1: # TODO(lukaszkaiser): remove branch when not needed. def single_update(i, opt_state, batch, rng): rng, subrng = jax_random.split(r...
[ "def", "_jit_update_fun", "(", "predict_fun", ",", "loss_fun", ",", "optimizer", ",", "lr_fun", ",", "num_devices", ")", ":", "if", "num_devices", "==", "1", ":", "# TODO(lukaszkaiser): remove branch when not needed.", "def", "single_update", "(", "i", ",", "opt_sta...
Get jit-ed update function for loss, optimizer, learning rate function.
[ "Get", "jit", "-", "ed", "update", "function", "for", "loss", "optimizer", "learning", "rate", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L307-L333
22,016
tensorflow/tensor2tensor
tensor2tensor/keras/initializers.py
_compute_fans
def _compute_fans(shape): """Computes the number of input and output units for a weight shape. Args: shape: Integer shape tuple or TF tensor shape. Returns: A tuple of scalars (fan_in, fan_out). """ if len(shape) < 1: # Just to avoid errors for constants. fan_in = fan_out = 1 elif len(shape) ...
python
def _compute_fans(shape): """Computes the number of input and output units for a weight shape. Args: shape: Integer shape tuple or TF tensor shape. Returns: A tuple of scalars (fan_in, fan_out). """ if len(shape) < 1: # Just to avoid errors for constants. fan_in = fan_out = 1 elif len(shape) ...
[ "def", "_compute_fans", "(", "shape", ")", ":", "if", "len", "(", "shape", ")", "<", "1", ":", "# Just to avoid errors for constants.", "fan_in", "=", "fan_out", "=", "1", "elif", "len", "(", "shape", ")", "==", "1", ":", "fan_in", "=", "fan_out", "=", ...
Computes the number of input and output units for a weight shape. Args: shape: Integer shape tuple or TF tensor shape. Returns: A tuple of scalars (fan_in, fan_out).
[ "Computes", "the", "number", "of", "input", "and", "output", "units", "for", "a", "weight", "shape", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/keras/initializers.py#L32-L60
22,017
tensorflow/tensor2tensor
tensor2tensor/keras/initializers.py
get
def get(identifier, value=None): """Getter for loading from strings; returns value if can't load.""" if value is None: value = identifier if identifier is None: return None elif isinstance(identifier, dict): try: return deserialize(identifier) except ValueError: return value elif i...
python
def get(identifier, value=None): """Getter for loading from strings; returns value if can't load.""" if value is None: value = identifier if identifier is None: return None elif isinstance(identifier, dict): try: return deserialize(identifier) except ValueError: return value elif i...
[ "def", "get", "(", "identifier", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "value", "=", "identifier", "if", "identifier", "is", "None", ":", "return", "None", "elif", "isinstance", "(", "identifier", ",", "dict", ")", ":",...
Getter for loading from strings; returns value if can't load.
[ "Getter", "for", "loading", "from", "strings", ";", "returns", "value", "if", "can", "t", "load", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/keras/initializers.py#L279-L298
22,018
tensorflow/tensor2tensor
tensor2tensor/envs/trajectory.py
Trajectory.add_time_step
def add_time_step(self, **create_time_step_kwargs): """Creates a time-step and appends it to the list. Args: **create_time_step_kwargs: Forwarded to time_step.TimeStep.create_time_step. """ ts = time_step.TimeStep.create_time_step(**create_time_step_kwargs) assert isinstance(ts, time_...
python
def add_time_step(self, **create_time_step_kwargs): """Creates a time-step and appends it to the list. Args: **create_time_step_kwargs: Forwarded to time_step.TimeStep.create_time_step. """ ts = time_step.TimeStep.create_time_step(**create_time_step_kwargs) assert isinstance(ts, time_...
[ "def", "add_time_step", "(", "self", ",", "*", "*", "create_time_step_kwargs", ")", ":", "ts", "=", "time_step", ".", "TimeStep", ".", "create_time_step", "(", "*", "*", "create_time_step_kwargs", ")", "assert", "isinstance", "(", "ts", ",", "time_step", ".", ...
Creates a time-step and appends it to the list. Args: **create_time_step_kwargs: Forwarded to time_step.TimeStep.create_time_step.
[ "Creates", "a", "time", "-", "step", "and", "appends", "it", "to", "the", "list", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L42-L51
22,019
tensorflow/tensor2tensor
tensor2tensor/envs/trajectory.py
Trajectory.change_last_time_step
def change_last_time_step(self, **replace_time_step_kwargs): """Replace the last time-steps with the given kwargs.""" # Pre-conditions: self._time_steps shouldn't be empty. assert self._time_steps self._time_steps[-1] = self._time_steps[-1].replace( **replace_time_step_kwargs)
python
def change_last_time_step(self, **replace_time_step_kwargs): """Replace the last time-steps with the given kwargs.""" # Pre-conditions: self._time_steps shouldn't be empty. assert self._time_steps self._time_steps[-1] = self._time_steps[-1].replace( **replace_time_step_kwargs)
[ "def", "change_last_time_step", "(", "self", ",", "*", "*", "replace_time_step_kwargs", ")", ":", "# Pre-conditions: self._time_steps shouldn't be empty.", "assert", "self", ".", "_time_steps", "self", ".", "_time_steps", "[", "-", "1", "]", "=", "self", ".", "_time...
Replace the last time-steps with the given kwargs.
[ "Replace", "the", "last", "time", "-", "steps", "with", "the", "given", "kwargs", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L53-L59
22,020
tensorflow/tensor2tensor
tensor2tensor/envs/trajectory.py
Trajectory.reward
def reward(self): """Returns a tuple of sum of raw and processed rewards.""" raw_rewards, processed_rewards = 0, 0 for ts in self.time_steps: # NOTE: raw_reward and processed_reward are None for the first time-step. if ts.raw_reward is not None: raw_rewards += ts.raw_reward if ts.p...
python
def reward(self): """Returns a tuple of sum of raw and processed rewards.""" raw_rewards, processed_rewards = 0, 0 for ts in self.time_steps: # NOTE: raw_reward and processed_reward are None for the first time-step. if ts.raw_reward is not None: raw_rewards += ts.raw_reward if ts.p...
[ "def", "reward", "(", "self", ")", ":", "raw_rewards", ",", "processed_rewards", "=", "0", ",", "0", "for", "ts", "in", "self", ".", "time_steps", ":", "# NOTE: raw_reward and processed_reward are None for the first time-step.", "if", "ts", ".", "raw_reward", "is", ...
Returns a tuple of sum of raw and processed rewards.
[ "Returns", "a", "tuple", "of", "sum", "of", "raw", "and", "processed", "rewards", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L85-L94
22,021
tensorflow/tensor2tensor
tensor2tensor/envs/trajectory.py
BatchTrajectory._complete_trajectory
def _complete_trajectory(self, trajectory, index): """Completes the given trajectory at the given index.""" assert isinstance(trajectory, Trajectory) # This *should* be the case. assert trajectory.last_time_step.action is None # Add to completed trajectories. self._completed_trajectories.appe...
python
def _complete_trajectory(self, trajectory, index): """Completes the given trajectory at the given index.""" assert isinstance(trajectory, Trajectory) # This *should* be the case. assert trajectory.last_time_step.action is None # Add to completed trajectories. self._completed_trajectories.appe...
[ "def", "_complete_trajectory", "(", "self", ",", "trajectory", ",", "index", ")", ":", "assert", "isinstance", "(", "trajectory", ",", "Trajectory", ")", "# This *should* be the case.", "assert", "trajectory", ".", "last_time_step", ".", "action", "is", "None", "#...
Completes the given trajectory at the given index.
[ "Completes", "the", "given", "trajectory", "at", "the", "given", "index", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L133-L145
22,022
tensorflow/tensor2tensor
tensor2tensor/envs/trajectory.py
BatchTrajectory.reset
def reset(self, indices, observations): """Resets trajectories at given indices and populates observations. Reset can either be called right at the beginning, when there are no time-steps, or to reset a currently active trajectory. If resetting a currently active trajectory then we save it in self...
python
def reset(self, indices, observations): """Resets trajectories at given indices and populates observations. Reset can either be called right at the beginning, when there are no time-steps, or to reset a currently active trajectory. If resetting a currently active trajectory then we save it in self...
[ "def", "reset", "(", "self", ",", "indices", ",", "observations", ")", ":", "# Pre-conditions: indices, observations are np arrays.", "# : indices is one-dimensional.", "# : their first dimension (batch) is the same.", "assert", "isinstance", "(", "indices...
Resets trajectories at given indices and populates observations. Reset can either be called right at the beginning, when there are no time-steps, or to reset a currently active trajectory. If resetting a currently active trajectory then we save it in self._completed_trajectories. Args: indi...
[ "Resets", "trajectories", "at", "given", "indices", "and", "populates", "observations", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L147-L192
22,023
tensorflow/tensor2tensor
tensor2tensor/envs/trajectory.py
BatchTrajectory.complete_all_trajectories
def complete_all_trajectories(self): """Essentially same as reset, but we don't have observations.""" for index in range(self.batch_size): trajectory = self._trajectories[index] assert trajectory.is_active self._complete_trajectory(trajectory, index)
python
def complete_all_trajectories(self): """Essentially same as reset, but we don't have observations.""" for index in range(self.batch_size): trajectory = self._trajectories[index] assert trajectory.is_active self._complete_trajectory(trajectory, index)
[ "def", "complete_all_trajectories", "(", "self", ")", ":", "for", "index", "in", "range", "(", "self", ".", "batch_size", ")", ":", "trajectory", "=", "self", ".", "_trajectories", "[", "index", "]", "assert", "trajectory", ".", "is_active", "self", ".", "...
Essentially same as reset, but we don't have observations.
[ "Essentially", "same", "as", "reset", "but", "we", "don", "t", "have", "observations", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L194-L199
22,024
tensorflow/tensor2tensor
tensor2tensor/envs/trajectory.py
BatchTrajectory.step
def step(self, observations, raw_rewards, processed_rewards, dones, actions): """Record the information obtained from taking a step in all envs. Records (observation, rewards, done) in a new time-step and actions in the current time-step. If any trajectory gets done, we move that trajectory to com...
python
def step(self, observations, raw_rewards, processed_rewards, dones, actions): """Record the information obtained from taking a step in all envs. Records (observation, rewards, done) in a new time-step and actions in the current time-step. If any trajectory gets done, we move that trajectory to com...
[ "def", "step", "(", "self", ",", "observations", ",", "raw_rewards", ",", "processed_rewards", ",", "dones", ",", "actions", ")", ":", "# Pre-conditions", "assert", "isinstance", "(", "observations", ",", "np", ".", "ndarray", ")", "assert", "isinstance", "(",...
Record the information obtained from taking a step in all envs. Records (observation, rewards, done) in a new time-step and actions in the current time-step. If any trajectory gets done, we move that trajectory to completed_trajectories. Args: observations: ndarray of first dimension self.b...
[ "Record", "the", "information", "obtained", "from", "taking", "a", "step", "in", "all", "envs", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L201-L266
22,025
tensorflow/tensor2tensor
tensor2tensor/envs/trajectory.py
BatchTrajectory.num_time_steps
def num_time_steps(self): """Returns the number of time-steps in completed and incomplete trajectories.""" num_time_steps = sum(t.num_time_steps for t in self.trajectories) return num_time_steps + self.num_completed_time_steps
python
def num_time_steps(self): """Returns the number of time-steps in completed and incomplete trajectories.""" num_time_steps = sum(t.num_time_steps for t in self.trajectories) return num_time_steps + self.num_completed_time_steps
[ "def", "num_time_steps", "(", "self", ")", ":", "num_time_steps", "=", "sum", "(", "t", ".", "num_time_steps", "for", "t", "in", "self", ".", "trajectories", ")", "return", "num_time_steps", "+", "self", ".", "num_completed_time_steps" ]
Returns the number of time-steps in completed and incomplete trajectories.
[ "Returns", "the", "number", "of", "time", "-", "steps", "in", "completed", "and", "incomplete", "trajectories", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L275-L279
22,026
tensorflow/tensor2tensor
tensor2tensor/envs/trajectory.py
BatchTrajectory.observations_np
def observations_np(self, boundary=20): """Pads the observations in all the trajectories and returns them. Args: boundary: integer, Observations will be padded to (n * boundary) + 1 where n is an integer. Returns: a tuple(padded_observations, time_steps), with shapes: padded_ob...
python
def observations_np(self, boundary=20): """Pads the observations in all the trajectories and returns them. Args: boundary: integer, Observations will be padded to (n * boundary) + 1 where n is an integer. Returns: a tuple(padded_observations, time_steps), with shapes: padded_ob...
[ "def", "observations_np", "(", "self", ",", "boundary", "=", "20", ")", ":", "list_observations_np_ts", "=", "[", "t", ".", "observations_np", "for", "t", "in", "self", ".", "trajectories", "]", "# Every element in `list_observations_np_ts` is shaped (t,) + OBS", "OBS...
Pads the observations in all the trajectories and returns them. Args: boundary: integer, Observations will be padded to (n * boundary) + 1 where n is an integer. Returns: a tuple(padded_observations, time_steps), with shapes: padded_observations: (self.batch_size, n * boundary + 1)...
[ "Pads", "the", "observations", "in", "all", "the", "trajectories", "and", "returns", "them", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L286-L315
22,027
tensorflow/tensor2tensor
tensor2tensor/data_generators/squad.py
_generate_examples
def _generate_examples(tmp_dir, dataset_split): """Generate squad examples. Args: tmp_dir: a string dataset_split: problem.DatasetSplit.TRAIN or problem.DatasetSplit.EVAL Yields: dictionaries representing examples """ if dataset_split == problem.DatasetSplit.TRAIN: file_name = _TRAINING_SET ...
python
def _generate_examples(tmp_dir, dataset_split): """Generate squad examples. Args: tmp_dir: a string dataset_split: problem.DatasetSplit.TRAIN or problem.DatasetSplit.EVAL Yields: dictionaries representing examples """ if dataset_split == problem.DatasetSplit.TRAIN: file_name = _TRAINING_SET ...
[ "def", "_generate_examples", "(", "tmp_dir", ",", "dataset_split", ")", ":", "if", "dataset_split", "==", "problem", ".", "DatasetSplit", ".", "TRAIN", ":", "file_name", "=", "_TRAINING_SET", "else", ":", "file_name", "=", "_DEV_SET", "squad_file", "=", "generat...
Generate squad examples. Args: tmp_dir: a string dataset_split: problem.DatasetSplit.TRAIN or problem.DatasetSplit.EVAL Yields: dictionaries representing examples
[ "Generate", "squad", "examples", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/squad.py#L39-L85
22,028
tensorflow/tensor2tensor
tensor2tensor/models/mtf_transformer2.py
layer_stack_from_hparams
def layer_stack_from_hparams(hparams, prefix): """Create a layer stack based on the hyperparameter values.""" layers = hparams.get(prefix + "layers") return transformer.LayerStack( [layers_registry[l](hparams, prefix) for l in layers], dropout_rate=hparams.layer_prepostprocess_dropout, norm_epsi...
python
def layer_stack_from_hparams(hparams, prefix): """Create a layer stack based on the hyperparameter values.""" layers = hparams.get(prefix + "layers") return transformer.LayerStack( [layers_registry[l](hparams, prefix) for l in layers], dropout_rate=hparams.layer_prepostprocess_dropout, norm_epsi...
[ "def", "layer_stack_from_hparams", "(", "hparams", ",", "prefix", ")", ":", "layers", "=", "hparams", ".", "get", "(", "prefix", "+", "\"layers\"", ")", "return", "transformer", ".", "LayerStack", "(", "[", "layers_registry", "[", "l", "]", "(", "hparams", ...
Create a layer stack based on the hyperparameter values.
[ "Create", "a", "layer", "stack", "based", "on", "the", "hyperparameter", "values", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L366-L372
22,029
tensorflow/tensor2tensor
tensor2tensor/models/mtf_transformer2.py
mtf_unitransformer_base
def mtf_unitransformer_base(): """Hyperparameters for single-stack Transformer.""" hparams = mtf_transformer2_base() hparams.add_hparam("autoregressive", True) # HYPERPARAMETERS FOR THE SINGLE LAYER STACK hparams.add_hparam("layers", ["self_att", "drd"] * 6) # number of heads in multihead attention hparam...
python
def mtf_unitransformer_base(): """Hyperparameters for single-stack Transformer.""" hparams = mtf_transformer2_base() hparams.add_hparam("autoregressive", True) # HYPERPARAMETERS FOR THE SINGLE LAYER STACK hparams.add_hparam("layers", ["self_att", "drd"] * 6) # number of heads in multihead attention hparam...
[ "def", "mtf_unitransformer_base", "(", ")", ":", "hparams", "=", "mtf_transformer2_base", "(", ")", "hparams", ".", "add_hparam", "(", "\"autoregressive\"", ",", "True", ")", "# HYPERPARAMETERS FOR THE SINGLE LAYER STACK", "hparams", ".", "add_hparam", "(", "\"layers\""...
Hyperparameters for single-stack Transformer.
[ "Hyperparameters", "for", "single", "-", "stack", "Transformer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L454-L469
22,030
tensorflow/tensor2tensor
tensor2tensor/models/mtf_transformer2.py
mtf_bitransformer_base
def mtf_bitransformer_base(): """Machine translation base configuration.""" hparams = mtf_transformer2_base() hparams.max_length = 256 hparams.shared_embedding = True # HYPERPARAMETERS FOR THE LAYER STACKS hparams.add_hparam("encoder_layers", ["self_att", "drd"] * 6) hparams.add_hparam("decoder_layers", [...
python
def mtf_bitransformer_base(): """Machine translation base configuration.""" hparams = mtf_transformer2_base() hparams.max_length = 256 hparams.shared_embedding = True # HYPERPARAMETERS FOR THE LAYER STACKS hparams.add_hparam("encoder_layers", ["self_att", "drd"] * 6) hparams.add_hparam("decoder_layers", [...
[ "def", "mtf_bitransformer_base", "(", ")", ":", "hparams", "=", "mtf_transformer2_base", "(", ")", "hparams", ".", "max_length", "=", "256", "hparams", ".", "shared_embedding", "=", "True", "# HYPERPARAMETERS FOR THE LAYER STACKS", "hparams", ".", "add_hparam", "(", ...
Machine translation base configuration.
[ "Machine", "translation", "base", "configuration", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L473-L505
22,031
tensorflow/tensor2tensor
tensor2tensor/models/mtf_transformer2.py
mtf_bitransformer_tiny
def mtf_bitransformer_tiny(): """Small encoder-decoder model for testing.""" hparams = mtf_bitransformer_base() hparams.batch_size = 2 hparams.mesh_shape = "" hparams.d_model = 128 hparams.encoder_layers = ["self_att", "drd"] * 2 hparams.decoder_layers = ["self_att", "enc_att", "drd"] * 2 hparams.num_he...
python
def mtf_bitransformer_tiny(): """Small encoder-decoder model for testing.""" hparams = mtf_bitransformer_base() hparams.batch_size = 2 hparams.mesh_shape = "" hparams.d_model = 128 hparams.encoder_layers = ["self_att", "drd"] * 2 hparams.decoder_layers = ["self_att", "enc_att", "drd"] * 2 hparams.num_he...
[ "def", "mtf_bitransformer_tiny", "(", ")", ":", "hparams", "=", "mtf_bitransformer_base", "(", ")", "hparams", ".", "batch_size", "=", "2", "hparams", ".", "mesh_shape", "=", "\"\"", "hparams", ".", "d_model", "=", "128", "hparams", ".", "encoder_layers", "=",...
Small encoder-decoder model for testing.
[ "Small", "encoder", "-", "decoder", "model", "for", "testing", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L521-L531
22,032
tensorflow/tensor2tensor
tensor2tensor/models/mtf_transformer2.py
mtr_lm_v1
def mtr_lm_v1(): """Model incorporating mixture-of-experts, local and global attention. ~6B parameters 32 experts in 3 hierarchichal moe layers. Returns: a hparams """ hparams = mtr_lm_dense(0) hparams.layers = (["local_self_att", "local_self_att", "drd", "self_att", "drd", "lo...
python
def mtr_lm_v1(): """Model incorporating mixture-of-experts, local and global attention. ~6B parameters 32 experts in 3 hierarchichal moe layers. Returns: a hparams """ hparams = mtr_lm_dense(0) hparams.layers = (["local_self_att", "local_self_att", "drd", "self_att", "drd", "lo...
[ "def", "mtr_lm_v1", "(", ")", ":", "hparams", "=", "mtr_lm_dense", "(", "0", ")", "hparams", ".", "layers", "=", "(", "[", "\"local_self_att\"", ",", "\"local_self_att\"", ",", "\"drd\"", ",", "\"self_att\"", ",", "\"drd\"", ",", "\"local_self_att\"", ",", "...
Model incorporating mixture-of-experts, local and global attention. ~6B parameters 32 experts in 3 hierarchichal moe layers. Returns: a hparams
[ "Model", "incorporating", "mixture", "-", "of", "-", "experts", "local", "and", "global", "attention", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L626-L649
22,033
tensorflow/tensor2tensor
tensor2tensor/models/mtf_transformer2.py
mtr_tr_dense
def mtr_tr_dense(sz): """Series of machine translation models. All models are trained on sequences of 256 tokens. You can use the dataset translate_enfr_wmt32k_packed. 154000 steps = 3 epochs. Args: sz: an integer Returns: a hparams """ n = 2 ** sz hparams = mtf_bitransformer_base() hpar...
python
def mtr_tr_dense(sz): """Series of machine translation models. All models are trained on sequences of 256 tokens. You can use the dataset translate_enfr_wmt32k_packed. 154000 steps = 3 epochs. Args: sz: an integer Returns: a hparams """ n = 2 ** sz hparams = mtf_bitransformer_base() hpar...
[ "def", "mtr_tr_dense", "(", "sz", ")", ":", "n", "=", "2", "**", "sz", "hparams", "=", "mtf_bitransformer_base", "(", ")", "hparams", ".", "d_model", "=", "1024", "hparams", ".", "max_length", "=", "256", "hparams", ".", "batch_size", "=", "128", "hparam...
Series of machine translation models. All models are trained on sequences of 256 tokens. You can use the dataset translate_enfr_wmt32k_packed. 154000 steps = 3 epochs. Args: sz: an integer Returns: a hparams
[ "Series", "of", "machine", "translation", "models", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L660-L691
22,034
tensorflow/tensor2tensor
tensor2tensor/models/mtf_transformer2.py
mtr_tr_dense_local
def mtr_tr_dense_local(sz): """With local self-attention in the decoder.""" hparams = mtr_tr_dense(sz) hparams.decoder_layers = ["local_self_att", "enc_att", "drd"] * 6 hparams.local_attention_radius = 32 return hparams
python
def mtr_tr_dense_local(sz): """With local self-attention in the decoder.""" hparams = mtr_tr_dense(sz) hparams.decoder_layers = ["local_self_att", "enc_att", "drd"] * 6 hparams.local_attention_radius = 32 return hparams
[ "def", "mtr_tr_dense_local", "(", "sz", ")", ":", "hparams", "=", "mtr_tr_dense", "(", "sz", ")", "hparams", ".", "decoder_layers", "=", "[", "\"local_self_att\"", ",", "\"enc_att\"", ",", "\"drd\"", "]", "*", "6", "hparams", ".", "local_attention_radius", "="...
With local self-attention in the decoder.
[ "With", "local", "self", "-", "attention", "in", "the", "decoder", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L734-L739
22,035
tensorflow/tensor2tensor
tensor2tensor/models/research/vqa_recurrent_self_attention.py
recurrent_transformer_decoder
def recurrent_transformer_decoder( decoder_input, encoder_output, decoder_self_attention_bias, encoder_decoder_attention_bias, hparams, name="decoder", nonpadding=None, save_weights_to=None, make_image_summary=True): """Recurrent decoder function.""" x = decoder_input attention...
python
def recurrent_transformer_decoder( decoder_input, encoder_output, decoder_self_attention_bias, encoder_decoder_attention_bias, hparams, name="decoder", nonpadding=None, save_weights_to=None, make_image_summary=True): """Recurrent decoder function.""" x = decoder_input attention...
[ "def", "recurrent_transformer_decoder", "(", "decoder_input", ",", "encoder_output", ",", "decoder_self_attention_bias", ",", "encoder_decoder_attention_bias", ",", "hparams", ",", "name", "=", "\"decoder\"", ",", "nonpadding", "=", "None", ",", "save_weights_to", "=", ...
Recurrent decoder function.
[ "Recurrent", "decoder", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/vqa_recurrent_self_attention.py#L138-L173
22,036
tensorflow/tensor2tensor
tensor2tensor/models/mtf_resnet.py
batch_norm_relu
def batch_norm_relu(inputs, is_training, relu=True): """Block of batch norm and relu.""" inputs = mtf.layers.batch_norm( inputs, is_training, BATCH_NORM_DECAY, epsilon=BATCH_NORM_EPSILON, init_zero=(not relu)) if relu: inputs = mtf.relu(inputs) return inputs
python
def batch_norm_relu(inputs, is_training, relu=True): """Block of batch norm and relu.""" inputs = mtf.layers.batch_norm( inputs, is_training, BATCH_NORM_DECAY, epsilon=BATCH_NORM_EPSILON, init_zero=(not relu)) if relu: inputs = mtf.relu(inputs) return inputs
[ "def", "batch_norm_relu", "(", "inputs", ",", "is_training", ",", "relu", "=", "True", ")", ":", "inputs", "=", "mtf", ".", "layers", ".", "batch_norm", "(", "inputs", ",", "is_training", ",", "BATCH_NORM_DECAY", ",", "epsilon", "=", "BATCH_NORM_EPSILON", ",...
Block of batch norm and relu.
[ "Block", "of", "batch", "norm", "and", "relu", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L38-L48
22,037
tensorflow/tensor2tensor
tensor2tensor/models/research/universal_transformer_util.py
universal_transformer_encoder
def universal_transformer_encoder(encoder_input, encoder_self_attention_bias, hparams, name="encoder", nonpadding=None, save_weights_to=None, ...
python
def universal_transformer_encoder(encoder_input, encoder_self_attention_bias, hparams, name="encoder", nonpadding=None, save_weights_to=None, ...
[ "def", "universal_transformer_encoder", "(", "encoder_input", ",", "encoder_self_attention_bias", ",", "hparams", ",", "name", "=", "\"encoder\"", ",", "nonpadding", "=", "None", ",", "save_weights_to", "=", "None", ",", "make_image_summary", "=", "True", ")", ":", ...
Universal Transformer encoder function. Prepares all the arguments and the inputs and passes it to a universal_transformer_layer to encode the encoder_input. Args: encoder_input: a Tensor encoder_self_attention_bias: bias Tensor for self-attention (see common_attention.attention_bias()) hpara...
[ "Universal", "Transformer", "encoder", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L62-L128
22,038
tensorflow/tensor2tensor
tensor2tensor/models/research/universal_transformer_util.py
universal_transformer_layer
def universal_transformer_layer(x, hparams, ffn_unit, attention_unit, pad_remover=None): """Core function applying the universal transformer layer. Args: x: input hparams: model h...
python
def universal_transformer_layer(x, hparams, ffn_unit, attention_unit, pad_remover=None): """Core function applying the universal transformer layer. Args: x: input hparams: model h...
[ "def", "universal_transformer_layer", "(", "x", ",", "hparams", ",", "ffn_unit", ",", "attention_unit", ",", "pad_remover", "=", "None", ")", ":", "def", "add_vanilla_transformer_layer", "(", "x", ",", "num_layers", ",", "name", ")", ":", "\"\"\"Passes the input t...
Core function applying the universal transformer layer. Args: x: input hparams: model hyper-parameters ffn_unit: feed-forward unit attention_unit: multi-head attention unit pad_remover: to mask out padding in convolutional layers (efficiency). Returns: the output tensor, extra output (can...
[ "Core", "function", "applying", "the", "universal", "transformer", "layer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L194-L265
22,039
tensorflow/tensor2tensor
tensor2tensor/models/research/universal_transformer_util.py
get_ut_layer
def get_ut_layer(x, hparams, ffn_unit, attention_unit, pad_remover=None): """Provides the function that is used in universal transforemr steps. Args: x: input hparams: model hyper-parameters ffn_unit: feed-forward unit attention_un...
python
def get_ut_layer(x, hparams, ffn_unit, attention_unit, pad_remover=None): """Provides the function that is used in universal transforemr steps. Args: x: input hparams: model hyper-parameters ffn_unit: feed-forward unit attention_un...
[ "def", "get_ut_layer", "(", "x", ",", "hparams", ",", "ffn_unit", ",", "attention_unit", ",", "pad_remover", "=", "None", ")", ":", "if", "hparams", ".", "recurrence_type", "==", "\"basic\"", ":", "ut_initializer", "=", "(", "x", ",", "x", ",", "x", ")",...
Provides the function that is used in universal transforemr steps. Args: x: input hparams: model hyper-parameters ffn_unit: feed-forward unit attention_unit: multi-head attention unit pad_remover: to mask out padding in convolutional layers (efficiency). Returns: ut_function and the ut_ini...
[ "Provides", "the", "function", "that", "is", "used", "in", "universal", "transforemr", "steps", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L268-L354
22,040
tensorflow/tensor2tensor
tensor2tensor/models/research/universal_transformer_util.py
transformer_encoder_ffn_unit
def transformer_encoder_ffn_unit(x, hparams, nonpadding_mask=None, pad_remover=None): """Applies a feed-forward function which is parametrised for encoding. Args: x: input hparams: model hyper-parameters ...
python
def transformer_encoder_ffn_unit(x, hparams, nonpadding_mask=None, pad_remover=None): """Applies a feed-forward function which is parametrised for encoding. Args: x: input hparams: model hyper-parameters ...
[ "def", "transformer_encoder_ffn_unit", "(", "x", ",", "hparams", ",", "nonpadding_mask", "=", "None", ",", "pad_remover", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"ffn\"", ")", ":", "if", "hparams", ".", "transformer_ffn_type", "==", ...
Applies a feed-forward function which is parametrised for encoding. Args: x: input hparams: model hyper-parameters nonpadding_mask: optional Tensor with shape [batch_size, encoder_length] indicating what positions are not padding. This is used to mask out padding in convoltutional layers. We ge...
[ "Applies", "a", "feed", "-", "forward", "function", "which", "is", "parametrised", "for", "encoding", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L357-L402
22,041
tensorflow/tensor2tensor
tensor2tensor/models/research/universal_transformer_util.py
transformer_encoder_attention_unit
def transformer_encoder_attention_unit(x, hparams, encoder_self_attention_bias, attention_dropout_broadcast_dims, save_weights_to=None, ...
python
def transformer_encoder_attention_unit(x, hparams, encoder_self_attention_bias, attention_dropout_broadcast_dims, save_weights_to=None, ...
[ "def", "transformer_encoder_attention_unit", "(", "x", ",", "hparams", ",", "encoder_self_attention_bias", ",", "attention_dropout_broadcast_dims", ",", "save_weights_to", "=", "None", ",", "make_image_summary", "=", "True", ")", ":", "with", "tf", ".", "variable_scope"...
Applies multihead attention function which is parametrised for encoding. Args: x: input hparams: model hyper-parameters encoder_self_attention_bias: a bias tensor for use in encoder self-attention attention_dropout_broadcast_dims: Fpr noise broadcasting in the dropout layers to save memory duri...
[ "Applies", "multihead", "attention", "function", "which", "is", "parametrised", "for", "encoding", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L405-L446
22,042
tensorflow/tensor2tensor
tensor2tensor/models/research/universal_transformer_util.py
transformer_decoder_attention_unit
def transformer_decoder_attention_unit(x, hparams, encoder_output, decoder_self_attention_bias, encoder_decoder_attention_bias, ...
python
def transformer_decoder_attention_unit(x, hparams, encoder_output, decoder_self_attention_bias, encoder_decoder_attention_bias, ...
[ "def", "transformer_decoder_attention_unit", "(", "x", ",", "hparams", ",", "encoder_output", ",", "decoder_self_attention_bias", ",", "encoder_decoder_attention_bias", ",", "attention_dropout_broadcast_dims", ",", "save_weights_to", "=", "None", ",", "make_image_summary", "=...
Applies multihead attention function which is parametrised for decoding. Args: x: input (decoder input) hparams: model hyper-parameters encoder_output: Encoder representation. [batch_size, input_length, hidden_dim] decoder_self_attention_bias: Bias and mask weights for decoder self-attent...
[ "Applies", "multihead", "attention", "function", "which", "is", "parametrised", "for", "decoding", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L492-L556
22,043
tensorflow/tensor2tensor
tensor2tensor/models/research/universal_transformer_util.py
universal_transformer_basic
def universal_transformer_basic(layer_inputs, step, hparams, ffn_unit, attention_unit): """Basic Universal Transformer. This model is pretty similar to the vanilla transformer in which weights are shared between layer...
python
def universal_transformer_basic(layer_inputs, step, hparams, ffn_unit, attention_unit): """Basic Universal Transformer. This model is pretty similar to the vanilla transformer in which weights are shared between layer...
[ "def", "universal_transformer_basic", "(", "layer_inputs", ",", "step", ",", "hparams", ",", "ffn_unit", ",", "attention_unit", ")", ":", "state", ",", "inputs", ",", "memory", "=", "tf", ".", "unstack", "(", "layer_inputs", ",", "num", "=", "None", ",", "...
Basic Universal Transformer. This model is pretty similar to the vanilla transformer in which weights are shared between layers. For some tasks, this simple idea brings a generalization that is not achievable by playing with the size of the model or drop_out parameters in the vanilla transformer. Args: ...
[ "Basic", "Universal", "Transformer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L559-L590
22,044
tensorflow/tensor2tensor
tensor2tensor/models/research/universal_transformer_util.py
universal_transformer_highway
def universal_transformer_highway(layer_inputs, step, hparams, ffn_unit, attention_unit, pad_remover=None): """Universal Transformer with highway connection. It transforms the st...
python
def universal_transformer_highway(layer_inputs, step, hparams, ffn_unit, attention_unit, pad_remover=None): """Universal Transformer with highway connection. It transforms the st...
[ "def", "universal_transformer_highway", "(", "layer_inputs", ",", "step", ",", "hparams", ",", "ffn_unit", ",", "attention_unit", ",", "pad_remover", "=", "None", ")", ":", "state", ",", "inputs", ",", "memory", "=", "layer_inputs", "new_state", "=", "step_prepr...
Universal Transformer with highway connection. It transforms the state using a block contaaining sel-attention and transition function and wrap the whole block with a highway connection. (the new state is a combination of the state and the transformed-state based on cary/transform gates.) Interesting obse...
[ "Universal", "Transformer", "with", "highway", "connection", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L593-L682
22,045
tensorflow/tensor2tensor
tensor2tensor/models/research/universal_transformer_util.py
universal_transformer_depthwise_attention
def universal_transformer_depthwise_attention(layer_inputs, step, hparams, ffn_unit, attention_unit): """universal_transformer with depth-wise attention. It uses an attention me...
python
def universal_transformer_depthwise_attention(layer_inputs, step, hparams, ffn_unit, attention_unit): """universal_transformer with depth-wise attention. It uses an attention me...
[ "def", "universal_transformer_depthwise_attention", "(", "layer_inputs", ",", "step", ",", "hparams", ",", "ffn_unit", ",", "attention_unit", ")", ":", "_", ",", "inputs", ",", "memory", "=", "layer_inputs", "all_states", "=", "memory", "# add depth signal", "if", ...
universal_transformer with depth-wise attention. It uses an attention mechanism-flipped vertically- over all the states from previous steps to generate the new_state. Args: layer_inputs: - state: state - memory: contains states from all the previous steps. step: indicating number of steps ta...
[ "universal_transformer", "with", "depth", "-", "wise", "attention", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L777-L832
22,046
tensorflow/tensor2tensor
tensor2tensor/models/research/universal_transformer_util.py
universal_transformer_with_gru_as_transition_function
def universal_transformer_with_gru_as_transition_function( layer_inputs, step, hparams, ffn_unit, attention_unit, pad_remover=None): """Universal Transformer which uses a gru as transition function. It's kind of like having a gru, filliped vertically next to the Universal Transformer that controls the flow o...
python
def universal_transformer_with_gru_as_transition_function( layer_inputs, step, hparams, ffn_unit, attention_unit, pad_remover=None): """Universal Transformer which uses a gru as transition function. It's kind of like having a gru, filliped vertically next to the Universal Transformer that controls the flow o...
[ "def", "universal_transformer_with_gru_as_transition_function", "(", "layer_inputs", ",", "step", ",", "hparams", ",", "ffn_unit", ",", "attention_unit", ",", "pad_remover", "=", "None", ")", ":", "state", ",", "unused_inputs", ",", "unused_memory", "=", "tf", ".", ...
Universal Transformer which uses a gru as transition function. It's kind of like having a gru, filliped vertically next to the Universal Transformer that controls the flow of the information in depth, over different steps of the Universal Transformer. Args: layer_inputs: - state: state - input...
[ "Universal", "Transformer", "which", "uses", "a", "gru", "as", "transition", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L835-L924
22,047
tensorflow/tensor2tensor
tensor2tensor/models/research/universal_transformer_util.py
universal_transformer_with_lstm_as_transition_function
def universal_transformer_with_lstm_as_transition_function( layer_inputs, step, hparams, ffn_unit, attention_unit, pad_remover=None): """Universal Transformer which uses a lstm as transition function. It's kind of like having a lstm, filliped vertically next to the Universal Transformer that controls the flo...
python
def universal_transformer_with_lstm_as_transition_function( layer_inputs, step, hparams, ffn_unit, attention_unit, pad_remover=None): """Universal Transformer which uses a lstm as transition function. It's kind of like having a lstm, filliped vertically next to the Universal Transformer that controls the flo...
[ "def", "universal_transformer_with_lstm_as_transition_function", "(", "layer_inputs", ",", "step", ",", "hparams", ",", "ffn_unit", ",", "attention_unit", ",", "pad_remover", "=", "None", ")", ":", "state", ",", "unused_inputs", ",", "memory", "=", "tf", ".", "uns...
Universal Transformer which uses a lstm as transition function. It's kind of like having a lstm, filliped vertically next to the Universal Transformer that controls the flow of the information in depth, over different steps of the Universal Transformer. Args: layer_inputs: - state: state - in...
[ "Universal", "Transformer", "which", "uses", "a", "lstm", "as", "transition", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L927-L1037
22,048
tensorflow/tensor2tensor
tensor2tensor/models/research/universal_transformer_util.py
_ffn_layer_multi_inputs
def _ffn_layer_multi_inputs(inputs_list, hparams, ffn_layer_type="dense", name="ffn", kernel_initializer=None, bias_initializer=None, activation=None, ...
python
def _ffn_layer_multi_inputs(inputs_list, hparams, ffn_layer_type="dense", name="ffn", kernel_initializer=None, bias_initializer=None, activation=None, ...
[ "def", "_ffn_layer_multi_inputs", "(", "inputs_list", ",", "hparams", ",", "ffn_layer_type", "=", "\"dense\"", ",", "name", "=", "\"ffn\"", ",", "kernel_initializer", "=", "None", ",", "bias_initializer", "=", "None", ",", "activation", "=", "None", ",", "pad_re...
Implements a Feed-forward layer with multiple inputs, pad-removing, etc. Args: inputs_list: list of input tensors hparams: hyper-parameters ffn_layer_type: dense / dense_dropconnect/ dense_relu_dense name: name kernel_initializer: kernel initializer bias_initializer: bias initializer acti...
[ "Implements", "a", "Feed", "-", "forward", "layer", "with", "multiple", "inputs", "pad", "-", "removing", "etc", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L1215-L1326
22,049
tensorflow/tensor2tensor
tensor2tensor/models/research/universal_transformer_util.py
fill_memory_slot
def fill_memory_slot(memory, value, index): """Fills the memory slot at a particular index with the given value. Args: memory: a 4-d tensor [memory_size, batch, length, channel] containing the state of all steps value: a 3-d tensor [batch, length, channel] as the sate index: integer in [0, memory...
python
def fill_memory_slot(memory, value, index): """Fills the memory slot at a particular index with the given value. Args: memory: a 4-d tensor [memory_size, batch, length, channel] containing the state of all steps value: a 3-d tensor [batch, length, channel] as the sate index: integer in [0, memory...
[ "def", "fill_memory_slot", "(", "memory", ",", "value", ",", "index", ")", ":", "mask", "=", "tf", ".", "to_float", "(", "tf", ".", "one_hot", "(", "index", ",", "tf", ".", "shape", "(", "memory", ")", "[", "0", "]", ")", "[", ":", ",", "None", ...
Fills the memory slot at a particular index with the given value. Args: memory: a 4-d tensor [memory_size, batch, length, channel] containing the state of all steps value: a 3-d tensor [batch, length, channel] as the sate index: integer in [0, memory_size) Returns: filled memory
[ "Fills", "the", "memory", "slot", "at", "a", "particular", "index", "with", "the", "given", "value", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L1329-L1346
22,050
tensorflow/tensor2tensor
tensor2tensor/models/research/universal_transformer_util.py
step_preprocess
def step_preprocess(x, step, hparams): """Preprocess the input at the beginning of each step. Args: x: input tensor step: step hparams: model hyper-parameters Returns: preprocessed input. """ original_channel_size = common_layers.shape_list(x)[-1] if hparams.add_position_timing_signal: ...
python
def step_preprocess(x, step, hparams): """Preprocess the input at the beginning of each step. Args: x: input tensor step: step hparams: model hyper-parameters Returns: preprocessed input. """ original_channel_size = common_layers.shape_list(x)[-1] if hparams.add_position_timing_signal: ...
[ "def", "step_preprocess", "(", "x", ",", "step", ",", "hparams", ")", ":", "original_channel_size", "=", "common_layers", ".", "shape_list", "(", "x", ")", "[", "-", "1", "]", "if", "hparams", ".", "add_position_timing_signal", ":", "x", "=", "add_position_t...
Preprocess the input at the beginning of each step. Args: x: input tensor step: step hparams: model hyper-parameters Returns: preprocessed input.
[ "Preprocess", "the", "input", "at", "the", "beginning", "of", "each", "step", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/universal_transformer_util.py#L1376-L1405
22,051
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikisum/utils.py
wet_records_from_file_obj
def wet_records_from_file_obj(f, take_ownership=False): """Iterate through records in WET file object.""" while True: record = WETRecord.read(f) if record is None: break if not record.url: continue yield record if take_ownership: f.close()
python
def wet_records_from_file_obj(f, take_ownership=False): """Iterate through records in WET file object.""" while True: record = WETRecord.read(f) if record is None: break if not record.url: continue yield record if take_ownership: f.close()
[ "def", "wet_records_from_file_obj", "(", "f", ",", "take_ownership", "=", "False", ")", ":", "while", "True", ":", "record", "=", "WETRecord", ".", "read", "(", "f", ")", "if", "record", "is", "None", ":", "break", "if", "not", "record", ".", "url", ":...
Iterate through records in WET file object.
[ "Iterate", "through", "records", "in", "WET", "file", "object", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/utils.py#L101-L115
22,052
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikisum/utils.py
wet_records
def wet_records(wet_filepath): """Generate WETRecords from filepath.""" if wet_filepath.endswith('.gz'): fopen = gzip.open else: fopen = tf.gfile.GFile with fopen(wet_filepath) as f: for record in wet_records_from_file_obj(f): yield record
python
def wet_records(wet_filepath): """Generate WETRecords from filepath.""" if wet_filepath.endswith('.gz'): fopen = gzip.open else: fopen = tf.gfile.GFile with fopen(wet_filepath) as f: for record in wet_records_from_file_obj(f): yield record
[ "def", "wet_records", "(", "wet_filepath", ")", ":", "if", "wet_filepath", ".", "endswith", "(", "'.gz'", ")", ":", "fopen", "=", "gzip", ".", "open", "else", ":", "fopen", "=", "tf", ".", "gfile", ".", "GFile", "with", "fopen", "(", "wet_filepath", ")...
Generate WETRecords from filepath.
[ "Generate", "WETRecords", "from", "filepath", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/utils.py#L118-L127
22,053
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikisum/utils.py
timing
def timing(name=''): """Log start, end, and duration.""" start = datetime.datetime.now() timestamp = start.strftime('%H:%M') tf.logging.info('Starting job [%s] at %s', name, timestamp) yield end = datetime.datetime.now() timestamp = end.strftime('%H:%M') tf.logging.info('Finished job [%s] at %s', name, ...
python
def timing(name=''): """Log start, end, and duration.""" start = datetime.datetime.now() timestamp = start.strftime('%H:%M') tf.logging.info('Starting job [%s] at %s', name, timestamp) yield end = datetime.datetime.now() timestamp = end.strftime('%H:%M') tf.logging.info('Finished job [%s] at %s', name, ...
[ "def", "timing", "(", "name", "=", "''", ")", ":", "start", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "timestamp", "=", "start", ".", "strftime", "(", "'%H:%M'", ")", "tf", ".", "logging", ".", "info", "(", "'Starting job [%s] at %s'", ",...
Log start, end, and duration.
[ "Log", "start", "end", "and", "duration", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/utils.py#L258-L269
22,054
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikisum/utils.py
WETHeader.read
def read(cls, f): """Read header from file. Headers end with length and then 1 blank line.""" url = None line = f.readline() if not line: # EOF return None while not line.startswith(cls.LENGTH_HEADER): if line.startswith(cls.URI_HEADER): url = line[len(cls.URI_HEADER):].st...
python
def read(cls, f): """Read header from file. Headers end with length and then 1 blank line.""" url = None line = f.readline() if not line: # EOF return None while not line.startswith(cls.LENGTH_HEADER): if line.startswith(cls.URI_HEADER): url = line[len(cls.URI_HEADER):].st...
[ "def", "read", "(", "cls", ",", "f", ")", ":", "url", "=", "None", "line", "=", "f", ".", "readline", "(", ")", "if", "not", "line", ":", "# EOF", "return", "None", "while", "not", "line", ".", "startswith", "(", "cls", ".", "LENGTH_HEADER", ")", ...
Read header from file. Headers end with length and then 1 blank line.
[ "Read", "header", "from", "file", ".", "Headers", "end", "with", "length", "and", "then", "1", "blank", "line", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/utils.py#L61-L80
22,055
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikisum/utils.py
WETRecord.read
def read(cls, f): """Read WETRecord from file. Records end with 2 blank lines.""" header = WETHeader.read(f) if header is None: # EOF return None content = f.read(header.length) # Consume empty separators f.readline() f.readline() return cls(header.url, content)
python
def read(cls, f): """Read WETRecord from file. Records end with 2 blank lines.""" header = WETHeader.read(f) if header is None: # EOF return None content = f.read(header.length) # Consume empty separators f.readline() f.readline() return cls(header.url, content)
[ "def", "read", "(", "cls", ",", "f", ")", ":", "header", "=", "WETHeader", ".", "read", "(", "f", ")", "if", "header", "is", "None", ":", "# EOF", "return", "None", "content", "=", "f", ".", "read", "(", "header", ".", "length", ")", "# Consume emp...
Read WETRecord from file. Records end with 2 blank lines.
[ "Read", "WETRecord", "from", "file", ".", "Records", "end", "with", "2", "blank", "lines", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/utils.py#L86-L98
22,056
tensorflow/tensor2tensor
tensor2tensor/trax/models/mlp.py
MLP
def MLP(num_hidden_layers=2, hidden_size=512, activation_fn=layers.Relu, num_output_classes=10, mode="train"): """Multi-layer feed-forward neural network with non-linear activations.""" del mode cur_layers = [layers.Flatten()] for _ in range(num_hidden_layers): cur_layers += ...
python
def MLP(num_hidden_layers=2, hidden_size=512, activation_fn=layers.Relu, num_output_classes=10, mode="train"): """Multi-layer feed-forward neural network with non-linear activations.""" del mode cur_layers = [layers.Flatten()] for _ in range(num_hidden_layers): cur_layers += ...
[ "def", "MLP", "(", "num_hidden_layers", "=", "2", ",", "hidden_size", "=", "512", ",", "activation_fn", "=", "layers", ".", "Relu", ",", "num_output_classes", "=", "10", ",", "mode", "=", "\"train\"", ")", ":", "del", "mode", "cur_layers", "=", "[", "lay...
Multi-layer feed-forward neural network with non-linear activations.
[ "Multi", "-", "layer", "feed", "-", "forward", "neural", "network", "with", "non", "-", "linear", "activations", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/models/mlp.py#L25-L36
22,057
tensorflow/tensor2tensor
tensor2tensor/envs/env_problem.py
EnvProblem._verify_same_spaces
def _verify_same_spaces(self): """Verifies that all the envs have the same observation and action space.""" # Pre-conditions: self._envs is initialized. if self._envs is None: raise ValueError("Environments not initialized.") if not isinstance(self._envs, list): tf.logging.warning("Not ch...
python
def _verify_same_spaces(self): """Verifies that all the envs have the same observation and action space.""" # Pre-conditions: self._envs is initialized. if self._envs is None: raise ValueError("Environments not initialized.") if not isinstance(self._envs, list): tf.logging.warning("Not ch...
[ "def", "_verify_same_spaces", "(", "self", ")", ":", "# Pre-conditions: self._envs is initialized.", "if", "self", ".", "_envs", "is", "None", ":", "raise", "ValueError", "(", "\"Environments not initialized.\"", ")", "if", "not", "isinstance", "(", "self", ".", "_e...
Verifies that all the envs have the same observation and action space.
[ "Verifies", "that", "all", "the", "envs", "have", "the", "same", "observation", "and", "action", "space", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L199-L235
22,058
tensorflow/tensor2tensor
tensor2tensor/envs/env_problem.py
EnvProblem.initialize_environments
def initialize_environments(self, batch_size=1): """Initializes the environments and trajectories. Subclasses can override this if they don't want a default implementation which initializes `batch_size` environments, but must take care to initialize self._trajectories (this is checked in __init__ anywa...
python
def initialize_environments(self, batch_size=1): """Initializes the environments and trajectories. Subclasses can override this if they don't want a default implementation which initializes `batch_size` environments, but must take care to initialize self._trajectories (this is checked in __init__ anywa...
[ "def", "initialize_environments", "(", "self", ",", "batch_size", "=", "1", ")", ":", "assert", "batch_size", ">=", "1", "self", ".", "_batch_size", "=", "batch_size", "self", ".", "_envs", "=", "[", "gym", ".", "make", "(", "self", ".", "base_env_name", ...
Initializes the environments and trajectories. Subclasses can override this if they don't want a default implementation which initializes `batch_size` environments, but must take care to initialize self._trajectories (this is checked in __init__ anyways). Args: batch_size: (int) Number of `self....
[ "Initializes", "the", "environments", "and", "trajectories", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L248-L295
22,059
tensorflow/tensor2tensor
tensor2tensor/envs/env_problem.py
EnvProblem.process_rewards
def process_rewards(self, rewards): """Clips, rounds, and changes to integer type. Args: rewards: numpy array of raw (float) rewards. Returns: processed_rewards: numpy array of np.int64 """ min_reward, max_reward = self.reward_range # Clips at min and max reward. rewards = np...
python
def process_rewards(self, rewards): """Clips, rounds, and changes to integer type. Args: rewards: numpy array of raw (float) rewards. Returns: processed_rewards: numpy array of np.int64 """ min_reward, max_reward = self.reward_range # Clips at min and max reward. rewards = np...
[ "def", "process_rewards", "(", "self", ",", "rewards", ")", ":", "min_reward", ",", "max_reward", "=", "self", ".", "reward_range", "# Clips at min and max reward.", "rewards", "=", "np", ".", "clip", "(", "rewards", ",", "min_reward", ",", "max_reward", ")", ...
Clips, rounds, and changes to integer type. Args: rewards: numpy array of raw (float) rewards. Returns: processed_rewards: numpy array of np.int64
[ "Clips", "rounds", "and", "changes", "to", "integer", "type", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L352-L368
22,060
tensorflow/tensor2tensor
tensor2tensor/envs/env_problem.py
EnvProblem.num_rewards
def num_rewards(self): """Returns the number of distinct rewards. Returns: Returns None if the reward range is infinite or the processed rewards aren't discrete, otherwise returns the number of distinct rewards. """ # Pre-conditions: reward range is finite. # : processed ...
python
def num_rewards(self): """Returns the number of distinct rewards. Returns: Returns None if the reward range is infinite or the processed rewards aren't discrete, otherwise returns the number of distinct rewards. """ # Pre-conditions: reward range is finite. # : processed ...
[ "def", "num_rewards", "(", "self", ")", ":", "# Pre-conditions: reward range is finite.", "# : processed rewards are discrete.", "if", "not", "self", ".", "is_reward_range_finite", ":", "tf", ".", "logging", ".", "error", "(", "\"Infinite reward range, `num_rewa...
Returns the number of distinct rewards. Returns: Returns None if the reward range is infinite or the processed rewards aren't discrete, otherwise returns the number of distinct rewards.
[ "Returns", "the", "number", "of", "distinct", "rewards", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L380-L399
22,061
tensorflow/tensor2tensor
tensor2tensor/envs/env_problem.py
EnvProblem._reset
def _reset(self, indices): """Resets environments at indices shouldn't pre-process or record. Subclasses should override this to do the actual reset if something other than the default implementation is desired. Args: indices: list of indices of underlying envs to call reset on. Returns: ...
python
def _reset(self, indices): """Resets environments at indices shouldn't pre-process or record. Subclasses should override this to do the actual reset if something other than the default implementation is desired. Args: indices: list of indices of underlying envs to call reset on. Returns: ...
[ "def", "_reset", "(", "self", ",", "indices", ")", ":", "# Pre-conditions: common_preconditions, see `assert_common_preconditions`.", "self", ".", "assert_common_preconditions", "(", ")", "# This returns a numpy array with first dimension `len(indices)` and the", "# rest being the dime...
Resets environments at indices shouldn't pre-process or record. Subclasses should override this to do the actual reset if something other than the default implementation is desired. Args: indices: list of indices of underlying envs to call reset on. Returns: np.ndarray of stacked observat...
[ "Resets", "environments", "at", "indices", "shouldn", "t", "pre", "-", "process", "or", "record", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L454-L472
22,062
tensorflow/tensor2tensor
tensor2tensor/envs/env_problem.py
EnvProblem._step
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...
python
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", ")", ":", "# Pre-conditions: common_preconditions, see `assert_common_preconditions`.", "# : len(actions) == len(self._envs)", "self", ".", "assert_common_preconditions", "(", ")", "assert", "len", "(", "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. Returns: a tuple of stacked raw...
[ "Takes", "a", "step", "in", "all", "environments", "shouldn", "t", "pre", "-", "process", "or", "record", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L504-L538
22,063
tensorflow/tensor2tensor
tensor2tensor/envs/env_problem.py
EnvProblem.step
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). ...
python
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", ")", ":", "observations", ",", "raw_rewards", ",", "dones", ",", "infos", "=", "self", ".", "_step", "(", "actions", ")", "# Process rewards.", "raw_rewards", "=", "raw_rewards", ".", "astype", "(", "np", ".", ...
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", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L540-L566
22,064
tensorflow/tensor2tensor
tensor2tensor/envs/env_problem.py
EnvProblem.example_reading_spec
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...
python
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", ")", ":", "# Subclasses can override and/or extend.", "processed_reward_type", "=", "tf", ".", "float32", "if", "self", ".", "is_processed_rewards_discrete", ":", "processed_reward_type", "=", "tf", ".", "int64", "data_fields", ...
Data fields to store on disk and their decoders.
[ "Data", "fields", "to", "store", "on", "disk", "and", "their", "decoders", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L568-L594
22,065
tensorflow/tensor2tensor
tensor2tensor/envs/env_problem.py
EnvProblem._generate_time_steps
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 ...
python
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", ")", ":", "for", "single_trajectory", "in", "trajectory_list", ":", "assert", "isinstance", "(", "single_trajectory", ",", "trajectory", ".", "Trajectory", ")", "# Skip writing trajectories that have only...
A generator to yield single time-steps from a list of trajectories.
[ "A", "generator", "to", "yield", "single", "time", "-", "steps", "from", "a", "list", "of", "trajectories", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L656-L713
22,066
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_nat.py
decompress_step
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)]...
python
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", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "shape", "=", "common_layers", ".", "shape_list", "(", "source", ")", "multiplier", "=", "2", "...
Decompression function.
[ "Decompression", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L138-L149
22,067
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_nat.py
encode
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...
python
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", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "(", "encoder_input", ",", "encoder_self_attention_bias", ",", "ed", ")", "=", "transformer", ".", "transformer_pr...
Transformer preparations and encoder.
[ "Transformer", "preparations", "and", "encoder", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_nat.py#L169-L176
22,068
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
policy_net
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 = [...
python
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", ")", ":", "# 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", "...
A policy net function.
[ "A", "policy", "net", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L78-L92
22,069
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
value_net
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...
python
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", ")", ":", "del", "num_actions", "if", "bottom_layers", "is", "None", ":", "bottom_layers", "=", "[", "]", "bottom_layers", ".", "extend", ...
A value net function.
[ "A", "value", "net", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L95-L108
22,070
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
policy_and_value_net
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, ...
python
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", ")", ":", "# Layers.", "cur_layers", "=", "[", "]", "if", "bottom_layers", "is", "not", "None", ":", "cur_layers", ".", "extend...
A policy and value net function.
[ "A", "policy", "and", "value", "net", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L111-L130
22,071
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
log_params
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)) ...
python
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\"", ")", ":", "for", "i", ",", "param", "in", "enumerate", "(", "params", ")", ":", "if", "not", "param", ":", "# Empty tuple.", "continue", "if", "not", "isinstance", "(", "param", ",", "...
Dumps the params with `logging.error`.
[ "Dumps", "the", "params", "with", "logging", ".", "error", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L140-L152
22,072
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
collect_trajectories
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...
python
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", ")", ":", "trajectories", "=", "[", "]", "for", "t", "in", "r...
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...
[ "Collect", "trajectories", "with", "the", "given", "policy", "net", "and", "behaviour", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L159-L275
22,073
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
get_padding_value
def get_padding_value(dtype): """Returns the padding value given a dtype.""" padding_value = None if dtype == np.uint8: padding_value = np.uint8(0) elif dtype == np.uint16: padding_value = np.uint16(0) elif dtype == np.float32: padding_value = 0.0 else: padding_value = 0 assert padding_val...
python
def get_padding_value(dtype): """Returns the padding value given a dtype.""" padding_value = None if dtype == np.uint8: padding_value = np.uint8(0) elif dtype == np.uint16: padding_value = np.uint16(0) elif dtype == np.float32: padding_value = 0.0 else: padding_value = 0 assert padding_val...
[ "def", "get_padding_value", "(", "dtype", ")", ":", "padding_value", "=", "None", "if", "dtype", "==", "np", ".", "uint8", ":", "padding_value", "=", "np", ".", "uint8", "(", "0", ")", "elif", "dtype", "==", "np", ".", "uint16", ":", "padding_value", "...
Returns the padding value given a dtype.
[ "Returns", "the", "padding", "value", "given", "a", "dtype", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L283-L295
22,074
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
pad_trajectories
def pad_trajectories(trajectories, boundary=20): """Pad trajectories to a bucket length that is a multiple of boundary. Args: trajectories: list[(observation, actions, rewards)], where each observation is shaped (t+1,) + OBS and actions & rewards are shaped (t,), with the length of the list being B...
python
def pad_trajectories(trajectories, boundary=20): """Pad trajectories to a bucket length that is a multiple of boundary. Args: trajectories: list[(observation, actions, rewards)], where each observation is shaped (t+1,) + OBS and actions & rewards are shaped (t,), with the length of the list being B...
[ "def", "pad_trajectories", "(", "trajectories", ",", "boundary", "=", "20", ")", ":", "# Let's compute max(t) over all trajectories.", "t_max", "=", "max", "(", "r", ".", "shape", "[", "0", "]", "for", "(", "_", ",", "_", ",", "r", ")", "in", "trajectories...
Pad trajectories to a bucket length that is a multiple of boundary. Args: trajectories: list[(observation, actions, rewards)], where each observation is shaped (t+1,) + OBS and actions & rewards are shaped (t,), with the length of the list being B (batch size). boundary: int, bucket length, the a...
[ "Pad", "trajectories", "to", "a", "bucket", "length", "that", "is", "a", "multiple", "of", "boundary", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L299-L369
22,075
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
rewards_to_go
def rewards_to_go(rewards, mask, gamma=0.99): r"""Computes rewards to go. Reward to go is defined as follows, the discounted reward that we have to yet collect, going forward from this point, i.e.: r2g_t = \sum_{l=0}^{\infty} (\gamma^{l} * reward_{t+l}) Args: rewards: np.ndarray of shape (B, T) of rewa...
python
def rewards_to_go(rewards, mask, gamma=0.99): r"""Computes rewards to go. Reward to go is defined as follows, the discounted reward that we have to yet collect, going forward from this point, i.e.: r2g_t = \sum_{l=0}^{\infty} (\gamma^{l} * reward_{t+l}) Args: rewards: np.ndarray of shape (B, T) of rewa...
[ "def", "rewards_to_go", "(", "rewards", ",", "mask", ",", "gamma", "=", "0.99", ")", ":", "B", ",", "T", "=", "rewards", ".", "shape", "# pylint: disable=invalid-name,unused-variable", "masked_rewards", "=", "rewards", "*", "mask", "# (B, T)", "# We use the follow...
r"""Computes rewards to go. Reward to go is defined as follows, the discounted reward that we have to yet collect, going forward from this point, i.e.: r2g_t = \sum_{l=0}^{\infty} (\gamma^{l} * reward_{t+l}) Args: rewards: np.ndarray of shape (B, T) of rewards. mask: np.ndarray of shape (B, T) of mas...
[ "r", "Computes", "rewards", "to", "go", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L373-L421
22,076
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
value_loss
def value_loss(value_net_apply, value_net_params, observations, rewards, reward_mask, gamma=0.99): """Computes the value loss. Args: value_net_apply: value net apply function with signature (params, ndarray of shape (B, T+1) + OBS...
python
def value_loss(value_net_apply, value_net_params, observations, rewards, reward_mask, gamma=0.99): """Computes the value loss. Args: value_net_apply: value net apply function with signature (params, ndarray of shape (B, T+1) + OBS...
[ "def", "value_loss", "(", "value_net_apply", ",", "value_net_params", ",", "observations", ",", "rewards", ",", "reward_mask", ",", "gamma", "=", "0.99", ")", ":", "B", ",", "T", "=", "rewards", ".", "shape", "# pylint: disable=invalid-name", "assert", "(", "B...
Computes the value loss. Args: value_net_apply: value net apply function with signature (params, ndarray of shape (B, T+1) + OBS) -> ndarray(B, T+1, 1) value_net_params: params of value_net_apply. observations: np.ndarray of shape (B, T+1) + OBS rewards: np.ndarray of shape (B, T) of rewards. ...
[ "Computes", "the", "value", "loss", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L425-L454
22,077
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
value_loss_given_predictions
def value_loss_given_predictions(value_prediction, rewards, reward_mask, gamma=0.99): """Computes the value loss given the prediction of the value function. Args: value_prediction: np.ndarray of shape (B, T+1, 1)...
python
def value_loss_given_predictions(value_prediction, rewards, reward_mask, gamma=0.99): """Computes the value loss given the prediction of the value function. Args: value_prediction: np.ndarray of shape (B, T+1, 1)...
[ "def", "value_loss_given_predictions", "(", "value_prediction", ",", "rewards", ",", "reward_mask", ",", "gamma", "=", "0.99", ")", ":", "B", ",", "T", "=", "rewards", ".", "shape", "# pylint: disable=invalid-name", "assert", "(", "B", ",", "T", ")", "==", "...
Computes the value loss given the prediction of the value function. Args: value_prediction: np.ndarray of shape (B, T+1, 1) rewards: np.ndarray of shape (B, T) of rewards. reward_mask: np.ndarray of shape (B, T), the mask over rewards. gamma: float, discount factor. Returns: The average L2 val...
[ "Computes", "the", "value", "loss", "given", "the", "prediction", "of", "the", "value", "function", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L458-L484
22,078
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
gae_advantages
def gae_advantages(td_deltas, mask, lambda_=0.95, gamma=0.99): r"""Computes the GAE advantages given the one step TD-residuals. The formula for a GAE advantage estimator is as follows: A_{bt} = \sum_{l=0}^{\infty}(\gamma * \lambda)^{l}(\delta_{b,t+l}). Internally we just call rewards_to_go, since it is the s...
python
def gae_advantages(td_deltas, mask, lambda_=0.95, gamma=0.99): r"""Computes the GAE advantages given the one step TD-residuals. The formula for a GAE advantage estimator is as follows: A_{bt} = \sum_{l=0}^{\infty}(\gamma * \lambda)^{l}(\delta_{b,t+l}). Internally we just call rewards_to_go, since it is the s...
[ "def", "gae_advantages", "(", "td_deltas", ",", "mask", ",", "lambda_", "=", "0.95", ",", "gamma", "=", "0.99", ")", ":", "return", "rewards_to_go", "(", "td_deltas", ",", "mask", ",", "lambda_", "*", "gamma", ")" ]
r"""Computes the GAE advantages given the one step TD-residuals. The formula for a GAE advantage estimator is as follows: A_{bt} = \sum_{l=0}^{\infty}(\gamma * \lambda)^{l}(\delta_{b,t+l}). Internally we just call rewards_to_go, since it is the same computation. Args: td_deltas: np.ndarray of shape (B, ...
[ "r", "Computes", "the", "GAE", "advantages", "given", "the", "one", "step", "TD", "-", "residuals", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L516-L537
22,079
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
chosen_probabs
def chosen_probabs(probab_observations, actions): """Picks out the probabilities of the actions along batch and time-steps. Args: probab_observations: ndarray of shape `[B, T+1, A]`, where probab_observations[b, t, i] contains the log-probability of action = i at the t^th time-step in the b^th traj...
python
def chosen_probabs(probab_observations, actions): """Picks out the probabilities of the actions along batch and time-steps. Args: probab_observations: ndarray of shape `[B, T+1, A]`, where probab_observations[b, t, i] contains the log-probability of action = i at the t^th time-step in the b^th traj...
[ "def", "chosen_probabs", "(", "probab_observations", ",", "actions", ")", ":", "B", ",", "T", "=", "actions", ".", "shape", "# pylint: disable=invalid-name", "assert", "(", "B", ",", "T", "+", "1", ")", "==", "probab_observations", ".", "shape", "[", ":", ...
Picks out the probabilities of the actions along batch and time-steps. Args: probab_observations: ndarray of shape `[B, T+1, A]`, where probab_observations[b, t, i] contains the log-probability of action = i at the t^th time-step in the b^th trajectory. actions: ndarray of shape `[B, T]`, with ea...
[ "Picks", "out", "the", "probabilities", "of", "the", "actions", "along", "batch", "and", "time", "-", "steps", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L540-L555
22,080
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
compute_probab_ratios
def compute_probab_ratios(p_new, p_old, actions, reward_mask): """Computes the probability ratios for each time-step in a trajectory. Args: p_new: ndarray of shape [B, T+1, A] of the log-probabilities that the policy network assigns to all the actions at each time-step in each batch using the old p...
python
def compute_probab_ratios(p_new, p_old, actions, reward_mask): """Computes the probability ratios for each time-step in a trajectory. Args: p_new: ndarray of shape [B, T+1, A] of the log-probabilities that the policy network assigns to all the actions at each time-step in each batch using the old p...
[ "def", "compute_probab_ratios", "(", "p_new", ",", "p_old", ",", "actions", ",", "reward_mask", ")", ":", "B", ",", "T", "=", "actions", ".", "shape", "# pylint: disable=invalid-name", "assert", "(", "B", ",", "T", "+", "1", ")", "==", "p_old", ".", "sha...
Computes the probability ratios for each time-step in a trajectory. Args: p_new: ndarray of shape [B, T+1, A] of the log-probabilities that the policy network assigns to all the actions at each time-step in each batch using the old parameters. p_old: ndarray of shape [B, T+1, A], same as above, b...
[ "Computes", "the", "probability", "ratios", "for", "each", "time", "-", "step", "in", "a", "trajectory", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L558-L588
22,081
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
ppo_loss
def ppo_loss(policy_net_apply, new_policy_params, old_policy_params, value_net_apply, value_net_params, padded_observations, padded_actions, padded_rewards, reward_mask, gamma=0.99, lambda_=...
python
def ppo_loss(policy_net_apply, new_policy_params, old_policy_params, value_net_apply, value_net_params, padded_observations, padded_actions, padded_rewards, reward_mask, gamma=0.99, lambda_=...
[ "def", "ppo_loss", "(", "policy_net_apply", ",", "new_policy_params", ",", "old_policy_params", ",", "value_net_apply", ",", "value_net_params", ",", "padded_observations", ",", "padded_actions", ",", "padded_rewards", ",", "reward_mask", ",", "gamma", "=", "0.99", ",...
PPO objective, with an eventual minus sign, given observations.
[ "PPO", "objective", "with", "an", "eventual", "minus", "sign", "given", "observations", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L602-L645
22,082
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
ppo_loss_given_predictions
def ppo_loss_given_predictions(log_probab_actions_new, log_probab_actions_old, predicted_values, padded_actions, padded_rewards, reward_mask, ...
python
def ppo_loss_given_predictions(log_probab_actions_new, log_probab_actions_old, predicted_values, padded_actions, padded_rewards, reward_mask, ...
[ "def", "ppo_loss_given_predictions", "(", "log_probab_actions_new", ",", "log_probab_actions_old", ",", "predicted_values", ",", "padded_actions", ",", "padded_rewards", ",", "reward_mask", ",", "gamma", "=", "0.99", ",", "lambda_", "=", "0.95", ",", "epsilon", "=", ...
PPO objective, with an eventual minus sign, given predictions.
[ "PPO", "objective", "with", "an", "eventual", "minus", "sign", "given", "predictions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L649-L695
22,083
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
ppo_opt_step
def ppo_opt_step(i, opt_state, ppo_opt_update, policy_net_apply, old_policy_params, value_net_apply, value_net_params, padded_observations, padded_actions, padded_rewa...
python
def ppo_opt_step(i, opt_state, ppo_opt_update, policy_net_apply, old_policy_params, value_net_apply, value_net_params, padded_observations, padded_actions, padded_rewa...
[ "def", "ppo_opt_step", "(", "i", ",", "opt_state", ",", "ppo_opt_update", ",", "policy_net_apply", ",", "old_policy_params", ",", "value_net_apply", ",", "value_net_params", ",", "padded_observations", ",", "padded_actions", ",", "padded_rewards", ",", "reward_mask", ...
PPO optimizer step.
[ "PPO", "optimizer", "step", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L765-L795
22,084
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
value_opt_step
def value_opt_step(i, opt_state, opt_update, value_net_apply, padded_observations, padded_rewards, reward_mask, gamma=0.99): """Value optimizer step.""" value_params = trax_opt.get_pa...
python
def value_opt_step(i, opt_state, opt_update, value_net_apply, padded_observations, padded_rewards, reward_mask, gamma=0.99): """Value optimizer step.""" value_params = trax_opt.get_pa...
[ "def", "value_opt_step", "(", "i", ",", "opt_state", ",", "opt_update", ",", "value_net_apply", ",", "padded_observations", ",", "padded_rewards", ",", "reward_mask", ",", "gamma", "=", "0.99", ")", ":", "value_params", "=", "trax_opt", ".", "get_params", "(", ...
Value optimizer step.
[ "Value", "optimizer", "step", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L799-L816
22,085
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
policy_and_value_opt_step
def policy_and_value_opt_step(i, opt_state, opt_update, policy_and_value_net_apply, old_params, padded_observations, padded_actions, ...
python
def policy_and_value_opt_step(i, opt_state, opt_update, policy_and_value_net_apply, old_params, padded_observations, padded_actions, ...
[ "def", "policy_and_value_opt_step", "(", "i", ",", "opt_state", ",", "opt_update", ",", "policy_and_value_net_apply", ",", "old_params", ",", "padded_observations", ",", "padded_actions", ",", "padded_rewards", ",", "reward_mask", ",", "c1", "=", "1.0", ",", "c2", ...
Policy and Value optimizer step.
[ "Policy", "and", "Value", "optimizer", "step", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L820-L855
22,086
tensorflow/tensor2tensor
tensor2tensor/data_generators/multinli.py
_maybe_download_corpora
def _maybe_download_corpora(tmp_dir): """Download corpora for multinli. Args: tmp_dir: a string Returns: a string """ mnli_filename = "MNLI.zip" mnli_finalpath = os.path.join(tmp_dir, "MNLI") if not tf.gfile.Exists(mnli_finalpath): zip_filepath = generator_utils.maybe_download( tmp_di...
python
def _maybe_download_corpora(tmp_dir): """Download corpora for multinli. Args: tmp_dir: a string Returns: a string """ mnli_filename = "MNLI.zip" mnli_finalpath = os.path.join(tmp_dir, "MNLI") if not tf.gfile.Exists(mnli_finalpath): zip_filepath = generator_utils.maybe_download( tmp_di...
[ "def", "_maybe_download_corpora", "(", "tmp_dir", ")", ":", "mnli_filename", "=", "\"MNLI.zip\"", "mnli_finalpath", "=", "os", ".", "path", ".", "join", "(", "tmp_dir", ",", "\"MNLI\"", ")", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "mnli_finalpat...
Download corpora for multinli. Args: tmp_dir: a string Returns: a string
[ "Download", "corpora", "for", "multinli", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multinli.py#L42-L59
22,087
tensorflow/tensor2tensor
tensor2tensor/models/shake_shake.py
shake_shake_skip_connection
def shake_shake_skip_connection(x, output_filters, stride, is_training): """Adds a residual connection to the filter x for the shake-shake model.""" curr_filters = common_layers.shape_list(x)[-1] if curr_filters == output_filters: return x stride_spec = [1, stride, stride, 1] # Skip path 1. path1 = tf.n...
python
def shake_shake_skip_connection(x, output_filters, stride, is_training): """Adds a residual connection to the filter x for the shake-shake model.""" curr_filters = common_layers.shape_list(x)[-1] if curr_filters == output_filters: return x stride_spec = [1, stride, stride, 1] # Skip path 1. path1 = tf.n...
[ "def", "shake_shake_skip_connection", "(", "x", ",", "output_filters", ",", "stride", ",", "is_training", ")", ":", "curr_filters", "=", "common_layers", ".", "shape_list", "(", "x", ")", "[", "-", "1", "]", "if", "curr_filters", "==", "output_filters", ":", ...
Adds a residual connection to the filter x for the shake-shake model.
[ "Adds", "a", "residual", "connection", "to", "the", "filter", "x", "for", "the", "shake", "-", "shake", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/shake_shake.py#L30-L52
22,088
tensorflow/tensor2tensor
tensor2tensor/models/shake_shake.py
shake_shake_branch
def shake_shake_branch(x, output_filters, stride, rand_forward, rand_backward, hparams): """Building a 2 branching convnet.""" is_training = hparams.mode == tf.estimator.ModeKeys.TRAIN x = tf.nn.relu(x) x = tf.layers.conv2d( x, output_filters, (3, 3), strides=(stride, st...
python
def shake_shake_branch(x, output_filters, stride, rand_forward, rand_backward, hparams): """Building a 2 branching convnet.""" is_training = hparams.mode == tf.estimator.ModeKeys.TRAIN x = tf.nn.relu(x) x = tf.layers.conv2d( x, output_filters, (3, 3), strides=(stride, st...
[ "def", "shake_shake_branch", "(", "x", ",", "output_filters", ",", "stride", ",", "rand_forward", ",", "rand_backward", ",", "hparams", ")", ":", "is_training", "=", "hparams", ".", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", "x", ...
Building a 2 branching convnet.
[ "Building", "a", "2", "branching", "convnet", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/shake_shake.py#L55-L75
22,089
tensorflow/tensor2tensor
tensor2tensor/models/shake_shake.py
shake_shake_block
def shake_shake_block(x, output_filters, stride, hparams): """Builds a full shake-shake sub layer.""" is_training = hparams.mode == tf.estimator.ModeKeys.TRAIN batch_size = common_layers.shape_list(x)[0] # Generate random numbers for scaling the branches. rand_forward = [ tf.random_uniform( [...
python
def shake_shake_block(x, output_filters, stride, hparams): """Builds a full shake-shake sub layer.""" is_training = hparams.mode == tf.estimator.ModeKeys.TRAIN batch_size = common_layers.shape_list(x)[0] # Generate random numbers for scaling the branches. rand_forward = [ tf.random_uniform( [...
[ "def", "shake_shake_block", "(", "x", ",", "output_filters", ",", "stride", ",", "hparams", ")", ":", "is_training", "=", "hparams", ".", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", "batch_size", "=", "common_layers", ".", "shape_lis...
Builds a full shake-shake sub layer.
[ "Builds", "a", "full", "shake", "-", "shake", "sub", "layer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/shake_shake.py#L78-L119
22,090
tensorflow/tensor2tensor
tensor2tensor/models/shake_shake.py
shake_shake_layer
def shake_shake_layer(x, output_filters, num_blocks, stride, hparams): """Builds many sub layers into one full layer.""" for block_num in range(num_blocks): curr_stride = stride if (block_num == 0) else 1 with tf.variable_scope("layer_{}".format(block_num)): x = shake_shake_block(x, output_filters, cu...
python
def shake_shake_layer(x, output_filters, num_blocks, stride, hparams): """Builds many sub layers into one full layer.""" for block_num in range(num_blocks): curr_stride = stride if (block_num == 0) else 1 with tf.variable_scope("layer_{}".format(block_num)): x = shake_shake_block(x, output_filters, cu...
[ "def", "shake_shake_layer", "(", "x", ",", "output_filters", ",", "num_blocks", ",", "stride", ",", "hparams", ")", ":", "for", "block_num", "in", "range", "(", "num_blocks", ")", ":", "curr_stride", "=", "stride", "if", "(", "block_num", "==", "0", ")", ...
Builds many sub layers into one full layer.
[ "Builds", "many", "sub", "layers", "into", "one", "full", "layer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/shake_shake.py#L122-L128
22,091
tensorflow/tensor2tensor
tensor2tensor/models/shake_shake.py
shakeshake_small
def shakeshake_small(): """Parameters for CIFAR-10. Gets to about 96% accuracy@700K steps, 1 GPU.""" hparams = common_hparams.basic_params1() hparams.batch_size = 128 hparams.hidden_size = 32 hparams.layer_prepostprocess_dropout = 0.0 hparams.dropout = 0 hparams.label_smoothing = 0.0 hparams.clip_grad_n...
python
def shakeshake_small(): """Parameters for CIFAR-10. Gets to about 96% accuracy@700K steps, 1 GPU.""" hparams = common_hparams.basic_params1() hparams.batch_size = 128 hparams.hidden_size = 32 hparams.layer_prepostprocess_dropout = 0.0 hparams.dropout = 0 hparams.label_smoothing = 0.0 hparams.clip_grad_n...
[ "def", "shakeshake_small", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "batch_size", "=", "128", "hparams", ".", "hidden_size", "=", "32", "hparams", ".", "layer_prepostprocess_dropout", "=", "0.0", "hparams",...
Parameters for CIFAR-10. Gets to about 96% accuracy@700K steps, 1 GPU.
[ "Parameters", "for", "CIFAR", "-", "10", ".", "Gets", "to", "about", "96%", "accuracy" ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/shake_shake.py#L165-L187
22,092
tensorflow/tensor2tensor
tensor2tensor/utils/metrics_hook.py
has_metric_plateaued
def has_metric_plateaued(steps, values, num_steps=100, delta=0.1, decrease=True): """Check if metric has plateaued. A metric has plateaued if the value has not increased/decreased (depending on `decrease`) by `delta` for at least `num_steps`. Args: steps: list<int> list of global ...
python
def has_metric_plateaued(steps, values, num_steps=100, delta=0.1, decrease=True): """Check if metric has plateaued. A metric has plateaued if the value has not increased/decreased (depending on `decrease`) by `delta` for at least `num_steps`. Args: steps: list<int> list of global ...
[ "def", "has_metric_plateaued", "(", "steps", ",", "values", ",", "num_steps", "=", "100", ",", "delta", "=", "0.1", ",", "decrease", "=", "True", ")", ":", "assert", "num_steps", ">", "0", "if", "len", "(", "steps", ")", "<", "2", ":", "return", "Fal...
Check if metric has plateaued. A metric has plateaued if the value has not increased/decreased (depending on `decrease`) by `delta` for at least `num_steps`. Args: steps: list<int> list of global steps for values. values: list<float> list of metric values. num_steps: int, number of steps the metric ...
[ "Check", "if", "metric", "has", "plateaued", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/metrics_hook.py#L249-L290
22,093
tensorflow/tensor2tensor
tensor2tensor/models/video/savp_params.py
next_frame_savp
def next_frame_savp(): """SAVP model hparams.""" hparams = sv2p_params.next_frame_sv2p() hparams.add_hparam("z_dim", 8) hparams.add_hparam("num_discriminator_filters", 32) hparams.add_hparam("use_vae", True) hparams.add_hparam("use_gan", False) hparams.add_hparam("use_spectral_norm", True) hparams.add_h...
python
def next_frame_savp(): """SAVP model hparams.""" hparams = sv2p_params.next_frame_sv2p() hparams.add_hparam("z_dim", 8) hparams.add_hparam("num_discriminator_filters", 32) hparams.add_hparam("use_vae", True) hparams.add_hparam("use_gan", False) hparams.add_hparam("use_spectral_norm", True) hparams.add_h...
[ "def", "next_frame_savp", "(", ")", ":", "hparams", "=", "sv2p_params", ".", "next_frame_sv2p", "(", ")", "hparams", ".", "add_hparam", "(", "\"z_dim\"", ",", "8", ")", "hparams", ".", "add_hparam", "(", "\"num_discriminator_filters\"", ",", "32", ")", "hparam...
SAVP model hparams.
[ "SAVP", "model", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/savp_params.py#L27-L56
22,094
tensorflow/tensor2tensor
tensor2tensor/models/video/savp_params.py
next_frame_savp_vae
def next_frame_savp_vae(): """SAVP - VAE only model.""" hparams = next_frame_savp() hparams.use_vae = True hparams.use_gan = False hparams.latent_loss_multiplier = 1e-3 hparams.latent_loss_multiplier_schedule = "linear_anneal" return hparams
python
def next_frame_savp_vae(): """SAVP - VAE only model.""" hparams = next_frame_savp() hparams.use_vae = True hparams.use_gan = False hparams.latent_loss_multiplier = 1e-3 hparams.latent_loss_multiplier_schedule = "linear_anneal" return hparams
[ "def", "next_frame_savp_vae", "(", ")", ":", "hparams", "=", "next_frame_savp", "(", ")", "hparams", ".", "use_vae", "=", "True", "hparams", ".", "use_gan", "=", "False", "hparams", ".", "latent_loss_multiplier", "=", "1e-3", "hparams", ".", "latent_loss_multipl...
SAVP - VAE only model.
[ "SAVP", "-", "VAE", "only", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/savp_params.py#L70-L77
22,095
tensorflow/tensor2tensor
tensor2tensor/models/video/savp_params.py
next_frame_savp_gan
def next_frame_savp_gan(): """SAVP - GAN only model.""" hparams = next_frame_savp() hparams.use_gan = True hparams.use_vae = False hparams.gan_loss_multiplier = 0.001 hparams.optimizer_adam_beta1 = 0.5 hparams.learning_rate_constant = 2e-4 hparams.gan_loss = "cross_entropy" hparams.learning_rate_decay...
python
def next_frame_savp_gan(): """SAVP - GAN only model.""" hparams = next_frame_savp() hparams.use_gan = True hparams.use_vae = False hparams.gan_loss_multiplier = 0.001 hparams.optimizer_adam_beta1 = 0.5 hparams.learning_rate_constant = 2e-4 hparams.gan_loss = "cross_entropy" hparams.learning_rate_decay...
[ "def", "next_frame_savp_gan", "(", ")", ":", "hparams", "=", "next_frame_savp", "(", ")", "hparams", ".", "use_gan", "=", "True", "hparams", ".", "use_vae", "=", "False", "hparams", ".", "gan_loss_multiplier", "=", "0.001", "hparams", ".", "optimizer_adam_beta1"...
SAVP - GAN only model.
[ "SAVP", "-", "GAN", "only", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/savp_params.py#L81-L92
22,096
tensorflow/tensor2tensor
tensor2tensor/utils/diet.py
diet_adam_optimizer_params
def diet_adam_optimizer_params(): """Default hyperparameters for a DietAdamOptimizer. Returns: a hyperparameters object. """ return hparam.HParams( quantize=True, # use 16-bit fixed-point quantization_scale=10.0 / tf.int16.max, optimizer="DietAdam", learning_rate=1.0, learnin...
python
def diet_adam_optimizer_params(): """Default hyperparameters for a DietAdamOptimizer. Returns: a hyperparameters object. """ return hparam.HParams( quantize=True, # use 16-bit fixed-point quantization_scale=10.0 / tf.int16.max, optimizer="DietAdam", learning_rate=1.0, learnin...
[ "def", "diet_adam_optimizer_params", "(", ")", ":", "return", "hparam", ".", "HParams", "(", "quantize", "=", "True", ",", "# use 16-bit fixed-point", "quantization_scale", "=", "10.0", "/", "tf", ".", "int16", ".", "max", ",", "optimizer", "=", "\"DietAdam\"", ...
Default hyperparameters for a DietAdamOptimizer. Returns: a hyperparameters object.
[ "Default", "hyperparameters", "for", "a", "DietAdamOptimizer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L34-L51
22,097
tensorflow/tensor2tensor
tensor2tensor/utils/diet.py
diet_expert
def diet_expert(x, hidden_size, params): """A two-layer feed-forward network with relu activation on hidden layer. Uses diet variables. Recomputes hidden layer on backprop to save activation memory. Args: x: a Tensor with shape [batch, io_size] hidden_size: an integer params: a diet variable HPara...
python
def diet_expert(x, hidden_size, params): """A two-layer feed-forward network with relu activation on hidden layer. Uses diet variables. Recomputes hidden layer on backprop to save activation memory. Args: x: a Tensor with shape [batch, io_size] hidden_size: an integer params: a diet variable HPara...
[ "def", "diet_expert", "(", "x", ",", "hidden_size", ",", "params", ")", ":", "@", "fn_with_diet_vars", "(", "params", ")", "def", "diet_expert_internal", "(", "x", ")", ":", "dim", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", ...
A two-layer feed-forward network with relu activation on hidden layer. Uses diet variables. Recomputes hidden layer on backprop to save activation memory. Args: x: a Tensor with shape [batch, io_size] hidden_size: an integer params: a diet variable HParams object. Returns: a Tensor with shape...
[ "A", "two", "-", "layer", "feed", "-", "forward", "network", "with", "relu", "activation", "on", "hidden", "layer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L54-L77
22,098
tensorflow/tensor2tensor
tensor2tensor/utils/diet.py
_quantize
def _quantize(x, params, randomize=True): """Quantize x according to params, optionally randomizing the rounding.""" if not params.quantize: return x if not randomize: return tf.bitcast( tf.cast(x / params.quantization_scale, tf.int16), tf.float16) abs_x = tf.abs(x) sign_x = tf.sign(x) y =...
python
def _quantize(x, params, randomize=True): """Quantize x according to params, optionally randomizing the rounding.""" if not params.quantize: return x if not randomize: return tf.bitcast( tf.cast(x / params.quantization_scale, tf.int16), tf.float16) abs_x = tf.abs(x) sign_x = tf.sign(x) y =...
[ "def", "_quantize", "(", "x", ",", "params", ",", "randomize", "=", "True", ")", ":", "if", "not", "params", ".", "quantize", ":", "return", "x", "if", "not", "randomize", ":", "return", "tf", ".", "bitcast", "(", "tf", ".", "cast", "(", "x", "/", ...
Quantize x according to params, optionally randomizing the rounding.
[ "Quantize", "x", "according", "to", "params", "optionally", "randomizing", "the", "rounding", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L235-L250
22,099
tensorflow/tensor2tensor
tensor2tensor/utils/diet.py
_dequantize
def _dequantize(q, params): """Dequantize q according to params.""" if not params.quantize: return q return tf.to_float(tf.bitcast(q, tf.int16)) * params.quantization_scale
python
def _dequantize(q, params): """Dequantize q according to params.""" if not params.quantize: return q return tf.to_float(tf.bitcast(q, tf.int16)) * params.quantization_scale
[ "def", "_dequantize", "(", "q", ",", "params", ")", ":", "if", "not", "params", ".", "quantize", ":", "return", "q", "return", "tf", ".", "to_float", "(", "tf", ".", "bitcast", "(", "q", ",", "tf", ".", "int16", ")", ")", "*", "params", ".", "qua...
Dequantize q according to params.
[ "Dequantize", "q", "according", "to", "params", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L253-L257